From 15c059ef12a2592f2ba291feeae0a30618b5a7f1 Mon Sep 17 00:00:00 2001 From: "(no author)" <(no author)@6015fed2-1504-0410-9fe1-9d1591cc4771> Date: Fri, 31 May 1996 13:02:52 +0000 Subject: [PATCH] This commit was manufactured by cvs2svn to create tag 'cwisync1'. git-svn-id: http://svn.python.org/projects/python/tags/cwisync1@6128 6015fed2-1504-0410-9fe1-9d1591cc4771 --- BUGS | 373 -- ChangeLog | 4532 ---------------- Demo/Makefile | 12 - Demo/README | 53 - Demo/classes/Complex.py | 288 - Demo/classes/Dates.py | 218 - Demo/classes/Dbm.py | 66 - Demo/classes/README | 14 - Demo/classes/Range.py | 71 - Demo/classes/Rat.py | 103 - Demo/classes/Rev.py | 89 - Demo/classes/Vec.py | 64 - Demo/classes/bitvec.py | 332 -- Demo/classes/class.doc | 110 - Demo/comparisons/README | 60 - Demo/comparisons/patterns | 4 - Demo/comparisons/regextest.py | 50 - Demo/comparisons/sortingtest.py | 50 - Demo/comparisons/systemtest.py | 74 - Demo/cwilib/cwilib.py | 213 - Demo/cwilib/form.py | 170 - Demo/cwilib/telnetlib.py | 321 -- Demo/cwilib/vt100.py | 328 -- Demo/cwilib/vt100win.py | 78 - Demo/dns/README | 12 - Demo/dns/dnsclass.py | 23 - Demo/dns/dnslib.py | 588 -- Demo/dns/dnsopcode.py | 16 - Demo/dns/dnstype.py | 41 - Demo/embed/Makefile | 43 - Demo/embed/README | 12 - Demo/embed/demo.c | 47 - Demo/ibrowse/README | 34 - Demo/ibrowse/ib | 2 - Demo/ibrowse/ib.py | 21 - Demo/ibrowse/ibrowse | 719 --- Demo/ibrowse/ibrowse.py | 617 --- Demo/ibrowse/icache.py | 74 - Demo/ibrowse/ifile.py | 328 -- Demo/ibrowse/itags.py | 127 - Demo/md5test/README | 10 - Demo/md5test/foo | 1 - Demo/md5test/md5driver.py | 125 - Demo/pdist/FSProxy.py | 322 -- Demo/pdist/RCSProxy.py | 198 - Demo/pdist/README | 121 - Demo/pdist/client.py | 158 - Demo/pdist/cmdfw.py | 144 - Demo/pdist/cmptree.py | 208 - Demo/pdist/cvslib.py | 364 -- Demo/pdist/cvslock.py | 280 - Demo/pdist/new | 1 - Demo/pdist/rcsbump | 33 - Demo/pdist/rcsclient.py | 71 - Demo/pdist/rcslib.py | 337 -- Demo/pdist/rcvs | 8 - Demo/pdist/rcvs.py | 481 -- Demo/pdist/rrcs | 8 - Demo/pdist/rrcs.py | 164 - Demo/pdist/security.py | 33 - Demo/pdist/server.py | 145 - Demo/pdist/sumtree.py | 24 - Demo/rpc/MANIFEST | 10 - Demo/rpc/README | 23 - Demo/rpc/T.py | 22 - Demo/rpc/mountclient.py | 201 - Demo/rpc/nfsclient.py | 201 - Demo/rpc/rnusersclient.py | 98 - Demo/rpc/rpc.py | 863 --- Demo/rpc/test | 24 - Demo/rpc/xdr.py | 201 - Demo/scripts/README | 18 - Demo/scripts/eqfix.py | 199 - Demo/scripts/fact.py | 48 - Demo/scripts/freeze.py | 480 -- Demo/scripts/from.py | 35 - Demo/scripts/ftpstats.py | 143 - Demo/scripts/lpwatch.py | 109 - Demo/scripts/makedir.py | 20 - Demo/scripts/markov.py | 116 - Demo/scripts/mboxconvert.py | 123 - Demo/scripts/mkrcs.py | 60 - Demo/scripts/morse.py | 149 - Demo/scripts/mpzpi.py | 34 - Demo/scripts/newslist.doc | 59 - Demo/scripts/newslist.py | 365 -- Demo/scripts/pi.py | 33 - Demo/scripts/pp.py | 138 - Demo/scripts/primes.py | 26 - Demo/scripts/script.py | 33 - Demo/scripts/unbirthday.py | 106 - Demo/scripts/update.py | 91 - Demo/scripts/wh.py | 2 - Demo/sgi/README | 22 - Demo/sgi/al/README | 15 - Demo/sgi/al/alwatch.py | 33 - Demo/sgi/al/broadcast.py | 27 - Demo/sgi/al/cmpaf.py | 64 - Demo/sgi/al/cmpaf_form.fd | 90 - Demo/sgi/al/intercom.py | 212 - Demo/sgi/al/listen.py | 34 - Demo/sgi/al/names.py | 14 - Demo/sgi/al/playaiff.py | 54 - Demo/sgi/al/playback.py | 23 - Demo/sgi/al/playold.py | 51 - Demo/sgi/al/radio.py | 21 - Demo/sgi/al/rec_play.py | 28 - Demo/sgi/al/record.py | 23 - Demo/sgi/al/unicast.py | 26 - Demo/sgi/al/x.py | 12 - Demo/sgi/audio/README | 8 - Demo/sgi/audio/play.py | 75 - Demo/sgi/audio_stdwin/README | 19 - Demo/sgi/audio_stdwin/jukebox.py | 321 -- Demo/sgi/audio_stdwin/rec.py | 268 - Demo/sgi/audio_stdwin/vumeter.py | 35 - Demo/sgi/cd/CD.doc | 46 - Demo/sgi/cd/README | 28 - Demo/sgi/cd/cdaiff.py | 33 - Demo/sgi/cd/cdwin.py | 103 - Demo/sgi/cd/listcd.py | 24 - Demo/sgi/cd/playcd.py | 102 - Demo/sgi/cd/recvcd.py | 36 - Demo/sgi/cd/sendcd.py | 154 - Demo/sgi/flp/tcache.fd | 51 - Demo/sgi/flp/tcache.py | 32 - Demo/sgi/flp/test_cb.fd | 75 - Demo/sgi/flp/test_cb.py | 61 - Demo/sgi/flp/test_nocb.fd | 75 - Demo/sgi/flp/test_nocb.py | 45 - Demo/sgi/gl/README | 35 - Demo/sgi/gl/backface.py | 140 - Demo/sgi/gl/glinfo.py | 20 - Demo/sgi/gl/glstdwin/fontchart.py | 34 - Demo/sgi/gl/glstdwin/glstdwdraw.py | 135 - Demo/sgi/gl/glstdwin/glstdwin.py | 400 -- Demo/sgi/gl/glstdwin/glstdwmenu.py | 62 - Demo/sgi/gl/glstdwin/glstdwwin.py | 139 - Demo/sgi/gl/glstdwin/stdwingl.py | 10 - Demo/sgi/gl/glstdwin/tcolor.py | 43 - Demo/sgi/gl/glstdwin/tglsw.py | 70 - Demo/sgi/gl/glstdwin/tmenu.py | 44 - Demo/sgi/gl/kites.py | 194 - Demo/sgi/gl/kunst.py | 426 -- Demo/sgi/gl/mclock.doc | 60 - Demo/sgi/gl/mclock.py | 736 --- Demo/sgi/gl/mixing.py | 116 - Demo/sgi/gl/nurbs.py | 171 - Demo/sgi/gl/zrgb.py | 168 - Demo/sgi/sv/README | 23 - Demo/sgi/sv/burstcapt.py | 52 - Demo/sgi/sv/contcapt.py | 107 - Demo/sgi/sv/rgbgrab.py | 81 - Demo/sgi/sv/simpleinput.py | 22 - Demo/sgi/video/.cvsignore | 2 - Demo/sgi/video/DisplayVideoIn.py | 99 - Demo/sgi/video/Dsend.py | 188 - Demo/sgi/video/IN.py | 54 - Demo/sgi/video/LiveVideoIn.py | 139 - Demo/sgi/video/LiveVideoOut.py | 130 - Demo/sgi/video/Makefile | 7 - Demo/sgi/video/OldVcopy.py | 148 - Demo/sgi/video/README | 113 - Demo/sgi/video/VCR.py | 534 -- Demo/sgi/video/VFile.py | 1193 ---- Demo/sgi/video/VGrabber.py | 80 - Demo/sgi/video/Vaddcache.py | 80 - Demo/sgi/video/Vb.py | 963 ---- Demo/sgi/video/VbForm.fd | 615 --- Demo/sgi/video/Vcopy.py | 291 - Demo/sgi/video/VcrIndex.py | 327 -- Demo/sgi/video/Vedit.py | 301 - Demo/sgi/video/VeditForm.fd | 435 -- Demo/sgi/video/Vfix.py | 90 - Demo/sgi/video/Vgeneric.py | 2 - Demo/sgi/video/Viewer.py | 255 - Demo/sgi/video/Vinfo.py | 174 - Demo/sgi/video/Vmkjpeg.py | 92 - Demo/sgi/video/Vplay.py | 355 -- Demo/sgi/video/Vrec.py | 413 -- Demo/sgi/video/Vrecb.py | 429 -- Demo/sgi/video/Vrecc.py | 281 - Demo/sgi/video/Vreceive.py | 135 - Demo/sgi/video/Vsend.py | 152 - Demo/sgi/video/Vstat.py | 23 - Demo/sgi/video/Vtime.py | 117 - Demo/sgi/video/Vunjpeg.py | 97 - Demo/sgi/video/aplay.py | 167 - Demo/sgi/video/cam.py | 129 - Demo/sgi/video/camcorder.py | 266 - Demo/sgi/video/cmif-film.ms | 200 - Demo/sgi/video/colorsys.py | 106 - Demo/sgi/video/i2v.c | 80 - Demo/sgi/video/imgconv.py | 140 - Demo/sgi/video/makemovie.py | 218 - Demo/sgi/video/rgb2video.py | 79 - Demo/sgi/video/senddefs.py | 11 - Demo/sgi/video/squash.c | 130 - Demo/sgi/video/squash2.c | 72 - Demo/sgi/video/statit.py | 115 - Demo/sgi/video/svgrab24.c | 97 - Demo/sgi/video/syncaudio.py | 94 - Demo/sgi/video/tomono.c | 165 - Demo/sgi/video/tv.py | 79 - Demo/sgi/video/v2i.c | 79 - Demo/sgi/video/vcopy.py | 134 - Demo/sgi/video/video.doc | 109 - Demo/sgi/video/video.py | 218 - Demo/sgi/video/video2rgb.py | 159 - Demo/sgi/video/vinfo.py | 90 - Demo/sgi/video/vpregs.py | 28 - Demo/sgi/video/vtime.py | 106 - Demo/sgi/video/watchcursor.py | 45 - Demo/sockets/ChangeLog | 35 - Demo/sockets/README | 20 - Demo/sockets/broadcast.py | 17 - Demo/sockets/echosvr.py | 31 - Demo/sockets/finger.py | 58 - Demo/sockets/ftp.py | 146 - Demo/sockets/gopher.py | 347 -- Demo/sockets/mcast.py | 94 - Demo/sockets/radio.py | 14 - Demo/sockets/rpython.py | 35 - Demo/sockets/rpythond.py | 52 - Demo/sockets/telnet.py | 109 - Demo/sockets/throughput.py | 93 - Demo/sockets/udpecho.py | 63 - Demo/stdwin/FormTest.py | 30 - Demo/stdwin/README | 18 - Demo/stdwin/RadioGroups.py | 98 - Demo/stdwin/TestCSplit.py | 25 - Demo/stdwin/TestDirList.py | 18 - Demo/stdwin/TestFormSplit.py | 27 - Demo/stdwin/TestSched.py | 38 - Demo/stdwin/TestTextEdit.py | 13 - Demo/stdwin/clock.py | 193 - Demo/stdwin/ibrowse/README | 34 - Demo/stdwin/ibrowse/dir | 62 - Demo/stdwin/ibrowse/ib | 2 - Demo/stdwin/ibrowse/ib.py | 21 - Demo/stdwin/ibrowse/ibrowse | 719 --- Demo/stdwin/ibrowse/ibrowse.py | 617 --- Demo/stdwin/ibrowse/icache.py | 74 - Demo/stdwin/ibrowse/ifile.py | 328 -- Demo/stdwin/ibrowse/itags.py | 127 - Demo/stdwin/jukebox.py | 413 -- Demo/stdwin/lpwin.py | 198 - Demo/stdwin/microedit.py | 183 - Demo/stdwin/miniedit.py | 356 -- Demo/stdwin/python.py | 449 -- Demo/stdwin/wdiff.py | 484 -- Demo/threads/Generator.py | 84 - Demo/threads/README | 14 - Demo/threads/bug.py | 69 - Demo/threads/condition.py | 475 -- Demo/threads/find.py | 152 - Demo/threads/sync.py | 603 -- Demo/threads/telnet.py | 114 - Demo/threads/wpi.py | 80 - Demo/tkinter/README | 11 - Demo/tkinter/Tree.py | 23 - Demo/tkinter/guido/AttrDialog.py | 463 -- Demo/tkinter/guido/ManPage.py | 220 - Demo/tkinter/guido/MimeViewer.py | 143 - Demo/tkinter/guido/ShellWindow.py | 164 - Demo/tkinter/guido/dialog.py | 118 - Demo/tkinter/guido/electrons.py | 90 - Demo/tkinter/guido/hanoi.py | 155 - Demo/tkinter/guido/hello.py | 17 - Demo/tkinter/guido/imagedraw.py | 23 - Demo/tkinter/guido/imageview.py | 12 - Demo/tkinter/guido/kill.py | 120 - Demo/tkinter/guido/listtree.py | 36 - Demo/tkinter/guido/mbox.py | 285 - Demo/tkinter/guido/rmt.py | 159 - Demo/tkinter/guido/svkill.py | 149 - Demo/tkinter/guido/tkman.py | 255 - Demo/tkinter/guido/wish.py | 27 - Demo/tkinter/matt/00-HELLO-WORLD.py | 30 - Demo/tkinter/matt/README | 30 - Demo/tkinter/matt/animation-simple.py | 36 - Demo/tkinter/matt/animation-w-velocity-ctrl.py | 51 - Demo/tkinter/matt/bind-w-mult-calls-p-type.py | 43 - Demo/tkinter/matt/canvas-demo-simple.py | 30 - Demo/tkinter/matt/canvas-gridding.py | 60 - Demo/tkinter/matt/canvas-moving-or-creating.py | 70 - Demo/tkinter/matt/canvas-moving-w-mouse.py | 59 - Demo/tkinter/matt/canvas-mult-item-sel.py | 85 - Demo/tkinter/matt/canvas-reading-tag-info.py | 51 - Demo/tkinter/matt/canvas-w-widget-draw-el.py | 39 - Demo/tkinter/matt/canvas-with-scrollbars.py | 67 - Demo/tkinter/matt/dialog-box.py | 65 - Demo/tkinter/matt/entry-simple.py | 25 - Demo/tkinter/matt/entry-with-shared-variable.py | 47 - Demo/tkinter/matt/killing-window-w-wm.py | 43 - Demo/tkinter/matt/menu-all-types-of-entries.py | 268 - Demo/tkinter/matt/menu-simple.py | 132 - Demo/tkinter/matt/not-what-you-might-think-1.py | 32 - Demo/tkinter/matt/not-what-you-might-think-2.py | 37 - Demo/tkinter/matt/packer-and-placer-together.py | 50 - Demo/tkinter/matt/packer-simple.py | 35 - Demo/tkinter/matt/placer-simple.py | 48 - Demo/tkinter/matt/pong-demo-1.py | 59 - Demo/tkinter/matt/printing-coords-of-items.py | 69 - Demo/tkinter/matt/radiobutton-simple.py | 66 - Demo/tkinter/matt/rubber-band-box-demo-1.py | 57 - Demo/tkinter/matt/rubber-line-demo-1.py | 50 - Demo/tkinter/matt/slider-demo-1.py | 40 - Demo/tkinter/matt/subclass-existing-widgets.py | 33 - Demo/tkinter/matt/two-radio-groups.py | 118 - Demo/tkinter/matt/window-creation-more.py | 37 - Demo/tkinter/matt/window-creation-simple.py | 34 - Demo/tkinter/matt/window-creation-w-location.py | 40 - Demo/tkinter/www/Para.py | 408 -- Demo/tkinter/www/fmt.py | 627 --- Demo/tkinter/www/htmllib.py | 639 --- Demo/tkinter/www/sgmllib.py | 321 -- Demo/tkinter/www/tkfmt.py | 63 - Demo/tkinter/www/www1.py | 19 - Demo/tkinter/www/www10.py | 101 - Demo/tkinter/www/www11.py | 137 - Demo/tkinter/www/www12.py | 210 - Demo/tkinter/www/www13.py | 218 - Demo/tkinter/www/www2.py | 35 - Demo/tkinter/www/www3.py | 46 - Demo/tkinter/www/www4.py | 26 - Demo/tkinter/www/www5.py | 29 - Demo/tkinter/www/www6.py | 31 - Demo/tkinter/www/www7.py | 33 - Demo/tkinter/www/www8.py | 43 - Demo/tkinter/www/www9.py | 60 - Doc/.cvsignore | 2 - Doc/Makefile | 234 - Doc/README | 100 - Doc/boilerplate.tex | 8 - Doc/copyright.tex | 22 - Doc/ext.tex | 1369 ----- Doc/ext/ext.tex | 1369 ----- Doc/fix.el | 5 - Doc/fix_hack | 2 - Doc/info/texipost.dat | 23 - Doc/info/texipre.dat | 86 - Doc/keywords.py | 20 - Doc/lib.tex | 186 - Doc/lib/lib.tex | 186 - Doc/lib/libaifc.tex | 189 - Doc/lib/libal.tex | 172 - Doc/lib/liballos.tex | 23 - Doc/lib/libamoeba.tex | 128 - Doc/lib/libarray.tex | 114 - Doc/lib/libaudioop.tex | 235 - Doc/lib/libbinascii.tex | 150 - Doc/lib/libbltin.tex | 7 - Doc/lib/libcd.tex | 300 - Doc/lib/libcgi.tex | 219 - Doc/lib/libcopy.tex | 81 - Doc/lib/libcrypt.tex | 21 - Doc/lib/libcrypto.tex | 30 - Doc/lib/libdbm.tex | 36 - Doc/lib/libexcs.tex | 172 - Doc/lib/libfcntl.tex | 60 - Doc/lib/libfl.tex | 485 -- Doc/lib/libfm.tex | 87 - Doc/lib/libftplib.tex | 204 - Doc/lib/libfuncs.tex | 491 -- Doc/lib/libgdbm.tex | 8 - Doc/lib/libgetopt.tex | 56 - Doc/lib/libgl.tex | 198 - Doc/lib/libgopherlib.tex | 30 - Doc/lib/libgrp.tex | 32 - Doc/lib/libhtmllib.tex | 274 - Doc/lib/libhttplib.tex | 127 - Doc/lib/libimageop.tex | 86 - Doc/lib/libimgfile.tex | 63 - Doc/lib/libimp.tex | 174 - Doc/lib/libintro.tex | 47 - Doc/lib/libjpeg.tex | 51 - Doc/lib/libmain.tex | 6 - Doc/lib/libmarshal.tex | 83 - Doc/lib/libmath.tex | 72 - Doc/lib/libmd5.tex | 64 - Doc/lib/libmimetools.tex | 96 - Doc/lib/libmisc.tex | 20 - Doc/lib/libmm.tex | 25 - Doc/lib/libmpz.tex | 78 - Doc/lib/libnntplib.tex | 212 - Doc/lib/libobjs.tex | 25 - Doc/lib/libos.tex | 104 - Doc/lib/libpanel.tex | 66 - Doc/lib/libparser.tex | 250 - Doc/lib/libpdb.tex | 303 -- Doc/lib/libpickle.tex | 229 - Doc/lib/libposix.tex | 371 -- Doc/lib/libposixfile.tex | 154 - Doc/lib/libppath.tex | 144 - Doc/lib/libprofile.tex | 760 --- Doc/lib/libpwd.tex | 32 - Doc/lib/libpython.tex | 40 - Doc/lib/librand.tex | 21 - Doc/lib/libregex.tex | 200 - Doc/lib/libregsub.tex | 30 - Doc/lib/librfc822.tex | 112 - Doc/lib/librgbimg.tex | 45 - Doc/lib/librotor.tex | 105 - Doc/lib/libselect.tex | 42 - Doc/lib/libsgi.tex | 4 - Doc/lib/libsgmllib.tex | 148 - Doc/lib/libshelve.tex | 59 - Doc/lib/libsignal.tex | 139 - Doc/lib/libsocket.tex | 317 -- Doc/lib/libsomeos.tex | 23 - Doc/lib/libstdwin.tex | 910 ---- Doc/lib/libstring.tex | 197 - Doc/lib/libstrings.tex | 20 - Doc/lib/libstruct.tex | 78 - Doc/lib/libsun.tex | 112 - Doc/lib/libsys.tex | 152 - Doc/lib/libsyslog.tex | 67 - Doc/lib/libtempfile.tex | 50 - Doc/lib/libtemplate.tex | 122 - Doc/lib/libtermios.tex | 108 - Doc/lib/libthread.tex | 101 - Doc/lib/libtime.tex | 122 - Doc/lib/libtraceback.tex | 54 - Doc/lib/libtypes.tex | 761 --- Doc/lib/libtypes2.tex | 122 - Doc/lib/libunix.tex | 39 - Doc/lib/liburllib.tex | 121 - Doc/lib/liburlparse.tex | 84 - Doc/lib/libwhrandom.tex | 20 - Doc/lib/libwww.tex | 51 - Doc/libaifc.tex | 189 - Doc/libal.tex | 172 - Doc/liballos.tex | 23 - Doc/libamoeba.tex | 128 - Doc/libarray.tex | 114 - Doc/libaudio.tex | 120 - Doc/libaudioop.tex | 235 - Doc/libbinascii.tex | 150 - Doc/libbltin.tex | 7 - Doc/libcd.tex | 300 - Doc/libcgi.tex | 219 - Doc/libcopy.tex | 81 - Doc/libcrypt.tex | 21 - Doc/libcrypto.tex | 30 - Doc/libctb.tex | 149 - Doc/libdbm.tex | 36 - Doc/libexcs.tex | 172 - Doc/libfcntl.tex | 60 - Doc/libfl.tex | 485 -- Doc/libfm.tex | 87 - Doc/libftplib.tex | 204 - Doc/libfuncs.tex | 491 -- Doc/libgdbm.tex | 8 - Doc/libgetopt.tex | 56 - Doc/libgl.tex | 198 - Doc/libgopherlib.tex | 30 - Doc/libgrp.tex | 32 - Doc/libhtmllib.tex | 274 - Doc/libhttplib.tex | 127 - Doc/libimageop.tex | 86 - Doc/libimgfile.tex | 63 - Doc/libimp.tex | 174 - Doc/libintro.tex | 47 - Doc/libjpeg.tex | 51 - Doc/libmac.tex | 40 - Doc/libmacconsole.tex | 111 - Doc/libmacdnr.tex | 119 - Doc/libmacfs.tex | 182 - Doc/libmacos.tex | 74 - Doc/libmacostools.tex | 39 - Doc/libmacspeech.tex | 86 - Doc/libmactcp.tex | 173 - Doc/libmacui.tex | 221 - Doc/libmain.tex | 6 - Doc/libmarshal.tex | 83 - Doc/libmath.tex | 72 - Doc/libmd5.tex | 64 - Doc/libmimetools.tex | 96 - Doc/libmisc.tex | 20 - Doc/libmm.tex | 25 - Doc/libmods.tex | 7 - Doc/libmpz.tex | 78 - Doc/libnntplib.tex | 212 - Doc/libobjs.tex | 25 - Doc/libos.tex | 104 - Doc/libpanel.tex | 66 - Doc/libparser.tex | 250 - Doc/libpdb.tex | 303 -- Doc/libpickle.tex | 229 - Doc/libposix.tex | 371 -- Doc/libposixfile.tex | 154 - Doc/libppath.tex | 144 - Doc/libprofile.tex | 760 --- Doc/libpwd.tex | 32 - Doc/libpython.tex | 40 - Doc/librand.tex | 21 - Doc/libregex.tex | 200 - Doc/libregsub.tex | 30 - Doc/librfc822.tex | 112 - Doc/librgbimg.tex | 45 - Doc/librotor.tex | 105 - Doc/libselect.tex | 42 - Doc/libsgi.tex | 4 - Doc/libsgmllib.tex | 148 - Doc/libshelve.tex | 59 - Doc/libsignal.tex | 139 - Doc/libsocket.tex | 317 -- Doc/libsomeos.tex | 23 - Doc/libstd.tex | 7 - Doc/libstdwin.tex | 910 ---- Doc/libstring.tex | 197 - Doc/libstrings.tex | 20 - Doc/libstruct.tex | 78 - Doc/libsun.tex | 112 - Doc/libsys.tex | 152 - Doc/libsyslog.tex | 67 - Doc/libtempfile.tex | 50 - Doc/libtemplate.tex | 122 - Doc/libtermios.tex | 108 - Doc/libthread.tex | 101 - Doc/libtime.tex | 122 - Doc/libtraceback.tex | 54 - Doc/libtypes.tex | 761 --- Doc/libtypes2.tex | 122 - Doc/libunix.tex | 39 - Doc/liburllib.tex | 121 - Doc/liburlparse.tex | 84 - Doc/libwhrandom.tex | 20 - Doc/libwww.tex | 51 - Doc/mac/libctb.tex | 149 - Doc/mac/libmac.tex | 40 - Doc/mac/libmacconsole.tex | 111 - Doc/mac/libmacdnr.tex | 119 - Doc/mac/libmacfs.tex | 182 - Doc/mac/libmacos.tex | 74 - Doc/mac/libmacostools.tex | 39 - Doc/mac/libmacspeech.tex | 86 - Doc/mac/libmactcp.tex | 173 - Doc/mac/libmacui.tex | 221 - Doc/myformat.perl | 153 - Doc/myformat.sty | 196 - Doc/partparse.py | 2165 -------- Doc/qua.tex | 1236 ----- Doc/quabib.bib | 139 - Doc/ref.tex | 68 - Doc/ref/ref.tex | 68 - Doc/ref/ref1.tex | 81 - Doc/ref/ref2.tex | 372 -- Doc/ref/ref3.tex | 876 --- Doc/ref/ref4.tex | 176 - Doc/ref/ref5.tex | 759 --- Doc/ref/ref6.tex | 536 -- Doc/ref/ref7.tex | 389 -- Doc/ref/ref8.tex | 105 - Doc/ref1.tex | 81 - Doc/ref2.tex | 372 -- Doc/ref3.tex | 876 --- Doc/ref4.tex | 176 - Doc/ref5.tex | 759 --- Doc/ref6.tex | 536 -- Doc/ref7.tex | 389 -- Doc/ref8.tex | 105 - Doc/templates/module.tex | 122 - Doc/texi2html.py | 1500 ----- Doc/texinputs/boilerplate.tex | 8 - Doc/texinputs/copyright.tex | 22 - Doc/texipost.dat | 23 - Doc/texipre.dat | 86 - Doc/text2latex.py | 55 - Doc/tools/fix.el | 5 - Doc/tools/fix_hack | 2 - Doc/tools/keywords.py | 20 - Doc/tools/partparse.py | 2165 -------- Doc/tools/texi2html.py | 1500 ----- Doc/tools/text2latex.py | 55 - Doc/tools/whichlibs | 2 - Doc/tut.tex | 3863 ------------- Doc/tut/tut.tex | 3863 ------------- Doc/whichlibs | 2 - Grammar/Grammar | 86 - Grammar/Makefile | 30 - Include/Makefile | 12 - Include/Python.h | 3 - Include/abstract.h | 817 --- Include/accessobject.h | 66 - Include/allobjects.h | 110 - Include/assert.h | 42 - Include/bitset.h | 55 - Include/bltinmodule.h | 40 - Include/ceval.h | 121 - Include/cgensupport.h | 49 - Include/classobject.h | 82 - Include/cobject.h | 61 - Include/compile.h | 69 - Include/complexobject.h | 57 - Include/config.h | 82 - Include/dictobject.h | 38 - Include/errcode.h | 51 - Include/errors.h | 76 - Include/eval.h | 38 - Include/fileobject.h | 51 - Include/floatobject.h | 55 - Include/frameobject.h | 111 - Include/funcobject.h | 55 - Include/graminit.h | 56 - Include/grammar.h | 116 - Include/import.h | 53 - Include/intobject.h | 83 - Include/intrcheck.h | 37 - Include/listobject.h | 74 - Include/longintrepr.h | 74 - Include/longobject.h | 49 - Include/mappingobject.h | 57 - Include/marshal.h | 45 - Include/metagrammar.h | 41 - Include/methodobject.h | 74 - Include/modsupport.h | 79 - Include/moduleobject.h | 44 - Include/mymalloc.h | 92 - Include/mymath.h | 16 - Include/myproto.h | 49 - Include/myselect.h | 86 - Include/mytime.h | 47 - Include/node.h | 68 - Include/object.h | 452 -- Include/objimpl.h | 59 - Include/opcode.h | 151 - Include/osdefs.h | 64 - Include/parsetok.h | 48 - Include/patchlevel.h | 1 - Include/pgenheaders.h | 84 - Include/pydebug.h | 40 - Include/pyerrors.h | 76 - Include/pythonrun.h | 64 - Include/pythread.h | 49 - Include/rangeobject.h | 39 - Include/rename1.h | 360 -- Include/rename2.h | 438 -- Include/stringobject.h | 77 - Include/structmember.h | 94 - Include/sysmodule.h | 46 - Include/thread.h | 49 - Include/token.h | 91 - Include/traceback.h | 47 - Include/tupleobject.h | 72 - Lib/ArrayIO.py | 142 - Lib/BaseHTTPServer.py | 482 -- Lib/CGIHTTPServer.py | 203 - Lib/Complex.py | 275 - Lib/Makefile | 12 - Lib/Para.py | 409 -- Lib/Queue.py | 121 - Lib/SimpleHTTPServer.py | 168 - Lib/SocketServer.py | 413 -- Lib/StringIO.py | 133 - Lib/UserDict.py | 18 - Lib/UserList.py | 50 - Lib/addpack.py | 67 - Lib/aifc.py | 1015 ---- Lib/anydbm.py | 54 - Lib/audiodev.py | 244 - Lib/base64.py | 78 - Lib/bdb.py | 362 -- Lib/binhex.py | 505 -- Lib/bisect.py | 23 - Lib/builtin.py | 3 - Lib/calendar.py | 153 - Lib/cgi.py | 1159 ---- Lib/cmd.py | 91 - Lib/cmp.py | 61 - Lib/cmpcache.py | 68 - Lib/codehack.py | 67 - Lib/colorsys.py | 119 - Lib/commands.py | 58 - Lib/compileall.py | 70 - Lib/copy.py | 273 - Lib/dbhash.py | 8 - Lib/dircache.py | 35 - Lib/dircmp.py | 203 - Lib/dis.py | 190 - Lib/dospath.py | 345 -- Lib/dumbdbm.py | 145 - Lib/dump.py | 63 - Lib/emacs.py | 18 - Lib/find.py | 26 - Lib/fmt.py | 622 --- Lib/fnmatch.py | 92 - Lib/formatter.py | 399 -- Lib/fpformat.py | 138 - Lib/ftplib.py | 546 -- Lib/getopt.py | 47 - Lib/glob.py | 51 - Lib/gopherlib.py | 191 - Lib/grep.py | 62 - Lib/htmlentitydefs.py | 105 - Lib/htmllib.py | 428 -- Lib/httplib.py | 134 - Lib/ihooks.py | 366 -- Lib/imghdr.py | 129 - Lib/importall.py | 36 - Lib/irix5/AL.py | 60 - Lib/irix5/AWARE.py | 54 - Lib/irix5/CD.py | 34 - Lib/irix5/CL.py | 24 - Lib/irix5/CL_old.py | 236 - Lib/irix5/DEVICE.py | 400 -- Lib/irix5/ERRNO.py | 147 - Lib/irix5/FCNTL.py | 53 - Lib/irix5/FL.py | 289 - Lib/irix5/GET.py | 59 - Lib/irix5/GL.py | 393 -- Lib/irix5/GLWS.py | 12 - Lib/irix5/IN.py | 83 - Lib/irix5/IOCTL.py | 233 - Lib/irix5/SOCKET.py | 108 - Lib/irix5/SV.py | 120 - Lib/irix5/TERMIOS.py | 339 -- Lib/irix5/WAIT.py | 14 - Lib/irix5/auds.py | 106 - Lib/irix5/cddb.py | 208 - Lib/irix5/cdplayer.py | 89 - Lib/irix5/flp.doc | 117 - Lib/irix5/flp.py | 455 -- Lib/irix5/jpeg.py | 110 - Lib/irix5/panel.py | 281 - Lib/irix5/panelparser.py | 128 - Lib/irix5/readcd.doc | 104 - Lib/irix5/readcd.py | 242 - Lib/irix5/regen | 12 - Lib/irix5/torgb.py | 97 - Lib/lib-old/Para.py | 409 -- Lib/lib-old/addpack.py | 67 - Lib/lib-old/codehack.py | 67 - Lib/lib-old/dump.py | 63 - Lib/lib-old/find.py | 26 - Lib/lib-old/fmt.py | 622 --- Lib/lib-old/grep.py | 62 - Lib/lib-old/lockfile.py | 15 - Lib/lib-old/newdir.py | 73 - Lib/lib-old/packmail.py | 112 - Lib/lib-old/rand.py | 13 - Lib/lib-old/tb.py | 177 - Lib/lib-old/util.py | 25 - Lib/lib-old/whatsound.py | 270 - Lib/lib-stdwin/Abstract.py | 63 - Lib/lib-stdwin/BoxParent.py | 40 - Lib/lib-stdwin/Buttons.py | 411 -- Lib/lib-stdwin/CSplit.py | 69 - Lib/lib-stdwin/DirList.py | 58 - Lib/lib-stdwin/FormSplit.py | 58 - Lib/lib-stdwin/HVSplit.py | 62 - Lib/lib-stdwin/Histogram.py | 36 - Lib/lib-stdwin/Sliders.py | 174 - Lib/lib-stdwin/Soundogram.py | 36 - Lib/lib-stdwin/Split.py | 211 - Lib/lib-stdwin/StripChart.py | 70 - Lib/lib-stdwin/TextEdit.py | 126 - Lib/lib-stdwin/TransParent.py | 123 - Lib/lib-stdwin/VUMeter.py | 47 - Lib/lib-stdwin/WindowParent.py | 189 - Lib/lib-stdwin/WindowSched.py | 61 - Lib/lib-stdwin/anywin.py | 14 - Lib/lib-stdwin/basewin.py | 64 - Lib/lib-stdwin/dirwin.py | 29 - Lib/lib-stdwin/filewin.py | 20 - Lib/lib-stdwin/formatter.py | 207 - Lib/lib-stdwin/gwin.py | 110 - Lib/lib-stdwin/listwin.py | 47 - Lib/lib-stdwin/mainloop.py | 256 - Lib/lib-stdwin/rect.py | 89 - Lib/lib-stdwin/srcwin.py | 129 - Lib/lib-stdwin/stdwinevents.py | 61 - Lib/lib-stdwin/stdwinq.py | 53 - Lib/lib-stdwin/tablewin.py | 236 - Lib/lib-stdwin/textwin.py | 117 - Lib/lib-stdwin/wdb.py | 316 -- Lib/lib-stdwin/wdbframewin.py | 146 - Lib/lib-stdwin/wdbsrcwin.py | 100 - Lib/lib-tk/Canvas.py | 190 - Lib/lib-tk/Dialog.py | 49 - Lib/lib-tk/FileDialog.py | 267 - Lib/lib-tk/ScrolledText.py | 37 - Lib/lib-tk/Tkconstants.py | 76 - Lib/lib-tk/Tkinter.py | 1569 ------ Lib/linecache.py | 90 - Lib/linux1/FCNTL.py | 101 - Lib/linux1/IN.py | 239 - Lib/linux1/SOCKET.py | 183 - Lib/linux1/TERMIOS.py | 270 - Lib/linux1/regen | 11 - Lib/lockfile.py | 15 - Lib/macpath.py | 169 - Lib/macstat.py | 83 - Lib/macurl2path.py | 76 - Lib/mailbox.py | 168 - Lib/mailcap.py | 223 - Lib/mhlib.py | 867 --- Lib/mimetools.py | 187 - Lib/mimify.py | 415 -- Lib/multifile.py | 128 - Lib/mutex.py | 58 - Lib/newdir.py | 73 - Lib/newimp.py | 1570 ------ Lib/ni.py | 435 -- Lib/ni1.py | 435 -- Lib/nntplib.py | 448 -- Lib/ntpath.py | 347 -- Lib/os.py | 123 - Lib/ospath.py | 3 - Lib/packmail.py | 112 - Lib/pdb.doc | 166 - Lib/pdb.py | 492 -- Lib/persist.py | 297 - Lib/pickle.py | 569 -- Lib/pipes.py | 301 - Lib/plat-irix5/AL.py | 60 - Lib/plat-irix5/AWARE.py | 54 - Lib/plat-irix5/CD.py | 34 - Lib/plat-irix5/CL.py | 24 - Lib/plat-irix5/CL_old.py | 236 - Lib/plat-irix5/DEVICE.py | 400 -- Lib/plat-irix5/ERRNO.py | 147 - Lib/plat-irix5/FCNTL.py | 53 - Lib/plat-irix5/FL.py | 289 - Lib/plat-irix5/GET.py | 59 - Lib/plat-irix5/GL.py | 393 -- Lib/plat-irix5/GLWS.py | 12 - Lib/plat-irix5/IN.py | 83 - Lib/plat-irix5/IOCTL.py | 233 - Lib/plat-irix5/SOCKET.py | 108 - Lib/plat-irix5/SV.py | 120 - Lib/plat-irix5/TERMIOS.py | 339 -- Lib/plat-irix5/WAIT.py | 14 - Lib/plat-irix5/cddb.py | 208 - Lib/plat-irix5/cdplayer.py | 89 - Lib/plat-irix5/flp.doc | 117 - Lib/plat-irix5/flp.py | 455 -- Lib/plat-irix5/jpeg.py | 110 - Lib/plat-irix5/panel.py | 281 - Lib/plat-irix5/panelparser.py | 128 - Lib/plat-irix5/readcd.doc | 104 - Lib/plat-irix5/readcd.py | 242 - Lib/plat-irix5/regen | 12 - Lib/plat-irix5/torgb.py | 97 - Lib/plat-linux1/FCNTL.py | 101 - Lib/plat-linux1/IN.py | 239 - Lib/plat-linux1/SOCKET.py | 183 - Lib/plat-linux1/TERMIOS.py | 270 - Lib/plat-linux1/regen | 11 - Lib/plat-sunos4/FCNTL.py | 67 - Lib/plat-sunos4/IN.py | 59 - Lib/plat-sunos4/SOCKET.py | 78 - Lib/plat-sunos4/SUNAUDIODEV.py | 38 - Lib/plat-sunos4/WAIT.py | 13 - Lib/plat-sunos4/regen | 12 - Lib/plat-sunos5/FCNTL.py | 47 - Lib/plat-sunos5/IN.py | 81 - Lib/plat-sunos5/SOCKET.py | 103 - Lib/plat-sunos5/SUNAUDIODEV.py | 38 - Lib/plat-sunos5/TERMIOS.py | 385 -- Lib/plat-sunos5/regen | 11 - Lib/poly.py | 52 - Lib/popen2.py | 35 - Lib/posixfile.py | 207 - Lib/posixpath.py | 307 -- Lib/profile.doc | 702 --- Lib/profile.py | 614 --- Lib/pstats.py | 532 -- Lib/pty.py | 106 - Lib/py_compile.py | 31 - Lib/pyclbr.py | 205 - Lib/quopri.py | 133 - Lib/rand.py | 13 - Lib/random.py | 260 - Lib/regex_syntax.py | 41 - Lib/regexp.py | 32 - Lib/regsub.py | 148 - Lib/repr.py | 95 - Lib/rexec.py | 357 -- Lib/rfc822.py | 405 -- Lib/sched.py | 99 - Lib/sgmllib.py | 446 -- Lib/shelve.py | 136 - Lib/shutil.py | 69 - Lib/sndhdr.py | 270 - Lib/stat.py | 88 - Lib/statcache.py | 82 - Lib/stdwin/Abstract.py | 63 - Lib/stdwin/BoxParent.py | 40 - Lib/stdwin/Buttons.py | 411 -- Lib/stdwin/CSplit.py | 69 - Lib/stdwin/DirList.py | 58 - Lib/stdwin/FormSplit.py | 58 - Lib/stdwin/HVSplit.py | 62 - Lib/stdwin/Histogram.py | 36 - Lib/stdwin/Sliders.py | 174 - Lib/stdwin/Soundogram.py | 36 - Lib/stdwin/Split.py | 211 - Lib/stdwin/StripChart.py | 70 - Lib/stdwin/TextEdit.py | 126 - Lib/stdwin/TransParent.py | 123 - Lib/stdwin/VUMeter.py | 47 - Lib/stdwin/WindowParent.py | 189 - Lib/stdwin/WindowSched.py | 61 - Lib/stdwin/anywin.py | 14 - Lib/stdwin/basewin.py | 64 - Lib/stdwin/dirwin.py | 29 - Lib/stdwin/filewin.py | 20 - Lib/stdwin/formatter.py | 207 - Lib/stdwin/gwin.py | 110 - Lib/stdwin/listwin.py | 47 - Lib/stdwin/mainloop.py | 256 - Lib/stdwin/rect.py | 89 - Lib/stdwin/srcwin.py | 129 - Lib/stdwin/stdwinevents.py | 61 - Lib/stdwin/stdwinq.py | 53 - Lib/stdwin/tablewin.py | 236 - Lib/stdwin/textwin.py | 117 - Lib/stdwin/wdb.py | 316 -- Lib/stdwin/wdbframewin.py | 146 - Lib/stdwin/wdbsrcwin.py | 100 - Lib/string.py | 274 - Lib/stringold.py | 274 - Lib/sunau.py | 474 -- Lib/sunaudio.py | 46 - Lib/sunos4/FCNTL.py | 67 - Lib/sunos4/IN.py | 59 - Lib/sunos4/SOCKET.py | 78 - Lib/sunos4/SUNAUDIODEV.py | 38 - Lib/sunos4/WAIT.py | 13 - Lib/sunos4/regen | 12 - Lib/sunos5/FCNTL.py | 47 - Lib/sunos5/IN.py | 81 - Lib/sunos5/SOCKET.py | 103 - Lib/sunos5/SUNAUDIODEV.py | 38 - Lib/sunos5/TERMIOS.py | 385 -- Lib/sunos5/regen | 11 - Lib/symbol.py | 60 - Lib/tb.py | 177 - Lib/tempfile.py | 69 - Lib/test/autotest.py | 67 - Lib/test/pystone.py | 229 - Lib/test/test.rawimg | 82 - Lib/test/test.rawimg.rev | 82 - Lib/test/test.rgb | Bin 43554 -> 0 bytes Lib/test/test_audioop.py | 202 - Lib/test/test_b1.py | 273 - Lib/test/test_b2.py | 260 - Lib/test/test_builtin.py | 13 - Lib/test/test_exceptions.py | 92 - Lib/test/test_grammar.py | 513 -- Lib/test/test_md5.py | 24 - Lib/test/test_opcodes.py | 59 - Lib/test/test_operations.py | 5 - Lib/test/test_pow.py | 92 - Lib/test/test_rgbimg.py | 49 - Lib/test/test_select.py | 23 - Lib/test/test_signal.py | 50 - Lib/test/test_support.py | 41 - Lib/test/test_thread.py | 106 - Lib/test/test_types.py | 182 - Lib/test/testall.out | 141 - Lib/test/testall.py | 32 - Lib/tkinter/Canvas.py | 190 - Lib/tkinter/Dialog.py | 49 - Lib/tkinter/FileDialog.py | 267 - Lib/tkinter/README | 27 - Lib/tkinter/ScrolledText.py | 37 - Lib/tkinter/Tkconstants.py | 76 - Lib/tkinter/Tkinter.py | 1569 ------ Lib/toaiff.py | 101 - Lib/token.py | 50 - Lib/tokenize.py | 63 - Lib/traceback.py | 125 - Lib/tty.py | 35 - Lib/types.py | 50 - Lib/tzparse.py | 80 - Lib/urllib.py | 715 --- Lib/urlopen.py | 410 -- Lib/urlparse.py | 218 - Lib/util.py | 25 - Lib/uu.py | 169 - Lib/wave.py | 559 -- Lib/whatsound.py | 270 - Lib/whrandom.py | 98 - Lib/zmod.py | 94 - Mac/MPW/buildall | 29 - Mac/Unsupported/mactcp/dnrglue.c | 301 - Mac/errno_unix.h | 18 - Mac/fopenRF.c | 336 -- Mac/mkapplet.py | 257 - Mac/mwerks/mwerks_applet_config.h | 4 - Mac/mwerks/mwerks_config.h | 2 - Mac/mwerks/mwerks_shlib_config.h | 3 - Mac/mwerksglue.c | 43 - Makefile.in | 379 -- Misc/ACKS | 132 - Misc/AIX-NOTES | 61 - Misc/BLURB | 45 - Misc/BLURB.LUTZ | 122 - Misc/COPYRIGHT | 20 - Misc/FAQ | 2158 -------- Misc/Fixcprt.py | 75 - Misc/HISTORY | 2360 -------- Misc/HPUX-NOTES | 21 - Misc/HYPE | 70 - Misc/Makefile | 10 - Misc/NEWS | 153 - Misc/QuickRef-1.1.1.ps | 6639 ----------------------- Misc/README | 33 - Misc/RFD | 114 - Misc/cheatsheet | 541 -- Misc/dlMakefile | 58 - Misc/faq2html.py | 193 - Misc/fixfuncptrs.sh | 47 - Misc/indent.pro | 15 - Misc/pyimenu.el | 305 -- Misc/python-mode-old.el | 2056 ------- Misc/python-mode.el | 2075 ------- Misc/python.gif | Bin 7380 -> 0 bytes Misc/python.man | 243 - Misc/renumber.py | 110 - Misc/setuid-prog.c | 172 - Modules/Makefile.pre.in | 181 - Modules/Setup.in | 319 -- Modules/_cursesmodule.c | 1584 ------ Modules/_tkinter.c | 1407 ----- Modules/almodule.c | 777 --- Modules/arraymodule.c | 1157 ---- Modules/audioop.c | 1238 ----- Modules/binascii.c | 743 --- Modules/bsddbmodule.c | 676 --- Modules/cdmodule.c | 877 --- Modules/cgen.py | 532 -- Modules/cgensupport.c | 377 -- Modules/cgensupport.h | 49 - Modules/clmodule.c | 1282 ----- Modules/cmathmodule.c | 314 -- Modules/config.c.in | 57 - Modules/cryptmodule.c | 35 - Modules/cstubs | 1369 ----- Modules/dbhashmodule.c | 380 -- Modules/dbmmodule.c | 300 - Modules/dlmodule.c | 244 - Modules/environment.c | 104 - Modules/fcntlmodule.c | 185 - Modules/flmodule.c | 2535 --------- Modules/fmmodule.c | 326 -- Modules/gdbmmodule.c | 382 -- Modules/getpath.c | 67 - Modules/grpmodule.c | 124 - Modules/imageop.c | 742 --- Modules/imgfile.c | 527 -- Modules/main.c | 241 - Modules/makesetup | 248 - Modules/mathmodule.c | 263 - Modules/md5.h | 94 - Modules/md5c.c | 337 -- Modules/md5module.c | 200 - Modules/mpzmodule.c | 1809 ------ Modules/newmodule.c | 186 - Modules/nismodule.c | 344 -- Modules/objc.c | 651 --- Modules/parsermodule.c | 2176 -------- Modules/posixmodule.c | 1746 ------ Modules/pwdmodule.c | 113 - Modules/regexmodule.c | 592 -- Modules/regexpr.c | 1702 ------ Modules/regexpr.h | 165 - Modules/rgbimgmodule.c | 752 --- Modules/rotormodule.c | 813 --- Modules/selectmodule.c | 207 - Modules/sgimodule.c | 88 - Modules/signalmodule.c | 493 -- Modules/socketmodule.c | 1537 ------ Modules/soundex.c | 175 - Modules/stdwinmodule.c | 2651 --------- Modules/stropmodule.c | 602 -- Modules/structmodule.c | 487 -- Modules/sunaudiodev.c | 488 -- Modules/svmodule.c | 994 ---- Modules/sybasemodule.c | 309 -- Modules/syslogmodule.c | 209 - Modules/termios.c | 243 - Modules/threadmodule.c | 326 -- Modules/timemodule.c | 482 -- Modules/timing.h | 67 - Modules/timingmodule.c | 91 - Modules/tkappinit.c | 36 - Modules/xxmodule.c | 210 - Modules/yuv.h | 122 - Modules/yuvconvert.c | 141 - Objects/Makefile.in | 96 - Objects/abstract.c | 1026 ---- Objects/accessobject.c | 360 -- Objects/classobject.c | 1316 ----- Objects/cobject.c | 100 - Objects/complexobject.c | 573 -- Objects/dictobject.c | 845 --- Objects/fileobject.c | 846 --- Objects/floatobject.c | 526 -- Objects/frameobject.c | 356 -- Objects/funcobject.c | 211 - Objects/intobject.c | 779 --- Objects/listobject.c | 795 --- Objects/longobject.c | 1423 ----- Objects/mappingobject.c | 845 --- Objects/methodobject.c | 260 - Objects/moduleobject.c | 175 - Objects/object.c | 582 -- Objects/rangeobject.c | 257 - Objects/stringobject.c | 923 ---- Objects/tupleobject.c | 458 -- Objects/typeobject.c | 83 - Objects/xxobject.c | 140 - PC/config.c | 99 - PC/config.h | 406 -- Parser/Makefile.in | 91 - Parser/acceler.c | 153 - Parser/assert.h | 42 - Parser/bitset.c | 99 - Parser/firstsets.c | 133 - Parser/grammar.c | 249 - Parser/grammar1.c | 83 - Parser/intrcheck.c | 184 - Parser/listnode.c | 94 - Parser/metagrammar.c | 176 - Parser/myreadline.c | 191 - Parser/node.c | 100 - Parser/parser.c | 421 -- Parser/parser.h | 61 - Parser/parsetok.c | 181 - Parser/pgen.c | 766 --- Parser/pgen.h | 41 - Parser/pgenmain.c | 204 - Parser/printgrammar.c | 149 - Parser/tokenizer.c | 745 --- Parser/tokenizer.h | 68 - Python/Makefile.in | 122 - Python/atof.c | 76 - Python/bltinmodule.c | 1714 ------ Python/ceval.c | 2975 ---------- Python/cgensupport.c | 377 -- Python/compile.c | 2864 ---------- Python/dup2.c | 31 - Python/errors.c | 198 - Python/fmod.c | 52 - Python/frozen.c | 49 - Python/frozenmain.c | 93 - Python/getargs.c | 615 --- Python/getcompiler.c | 51 - Python/getcopyright.c | 33 - Python/getcwd.c | 106 - Python/getmtime.c | 46 - Python/getopt.c | 88 - Python/getplatform.c | 35 - Python/getversion.c | 47 - Python/graminit.c | 1436 ----- Python/import.c | 1047 ---- Python/importdl.c | 539 -- Python/importdl.h | 42 - Python/marshal.c | 633 --- Python/memmove.c | 51 - Python/modsupport.c | 472 -- Python/mystrtoul.c | 174 - Python/pythonmain.c | 211 - Python/pythonrun.c | 744 --- Python/sigcheck.c | 43 - Python/strerror.c | 47 - Python/strtod.c | 158 - Python/structmember.c | 262 - Python/sysmodule.c | 361 -- Python/thread.c | 137 - Python/thread_cthread.h | 160 - Python/thread_foobar.h | 154 - Python/thread_lwp.h | 202 - Python/thread_nt.h | 245 - Python/thread_os2.h | 214 - Python/thread_pthread.h | 283 - Python/thread_sgi.h | 439 -- Python/thread_solaris.h | 226 - Python/traceback.c | 271 - README | 569 -- TODO | 475 -- Tools/README | 14 - Tools/bgen/README | 7 - Tools/bgen/bgen/bgen.py | 12 - Tools/bgen/bgen/bgenBuffer.py | 243 - Tools/bgen/bgen/bgenGenerator.py | 259 - Tools/bgen/bgen/bgenGeneratorGroup.py | 35 - Tools/bgen/bgen/bgenHeapBuffer.py | 110 - Tools/bgen/bgen/bgenModule.py | 85 - Tools/bgen/bgen/bgenObjectDefinition.py | 183 - Tools/bgen/bgen/bgenOutput.py | 221 - Tools/bgen/bgen/bgenStackBuffer.py | 59 - Tools/bgen/bgen/bgenStringBuffer.py | 64 - Tools/bgen/bgen/bgenType.py | 241 - Tools/bgen/bgen/bgenVariable.py | 88 - Tools/bgen/bgen/bgenlocations.py | 12 - Tools/bgen/bgen/macsupport.py | 168 - Tools/bgen/bgen/scantools.py | 508 -- Tools/freeze/README | 170 - Tools/freeze/checkextensions.py | 87 - Tools/freeze/findmodules.py | 127 - Tools/freeze/freeze.py | 300 - Tools/freeze/hello.py | 1 - Tools/freeze/makeconfig.py | 57 - Tools/freeze/makefreeze.py | 91 - Tools/freeze/makemakefile.py | 27 - Tools/freeze/nfreeze.py | 312 -- Tools/freeze/parsesetup.py | 98 - Tools/modulator/EXAMPLE.py | 53 - Tools/modulator/README | 24 - Tools/modulator/ScrolledListbox.py | 37 - Tools/modulator/Templates/copyright | 23 - Tools/modulator/Templates/module_head | 6 - Tools/modulator/Templates/module_method | 16 - Tools/modulator/Templates/module_tail | 37 - Tools/modulator/Templates/object_head | 13 - Tools/modulator/Templates/object_method | 16 - Tools/modulator/Templates/object_mlist | 8 - Tools/modulator/Templates/object_new | 13 - Tools/modulator/Templates/object_structure | 42 - Tools/modulator/Templates/object_tail | 33 - Tools/modulator/Templates/object_tp_as_mapping | 34 - Tools/modulator/Templates/object_tp_as_number | 206 - Tools/modulator/Templates/object_tp_as_sequence | 73 - Tools/modulator/Templates/object_tp_call | 10 - Tools/modulator/Templates/object_tp_compare | 7 - Tools/modulator/Templates/object_tp_dealloc | 8 - Tools/modulator/Templates/object_tp_getattr | 9 - Tools/modulator/Templates/object_tp_hash | 7 - Tools/modulator/Templates/object_tp_print | 10 - Tools/modulator/Templates/object_tp_repr | 10 - Tools/modulator/Templates/object_tp_setattr | 12 - Tools/modulator/Templates/object_tp_str | 11 - Tools/modulator/Tkextra.py | 235 - Tools/modulator/genmodule.py | 161 - Tools/modulator/modulator.py | 379 -- Tools/modulator/varsubst.py | 61 - Tools/scripts/README | 33 - Tools/scripts/byteyears.py | 57 - Tools/scripts/checkpyc.py | 69 - Tools/scripts/classfix.py | 188 - Tools/scripts/copytime.py | 25 - Tools/scripts/dutree.doc | 54 - Tools/scripts/dutree.py | 55 - Tools/scripts/eptags.py | 50 - Tools/scripts/findlinksto.py | 42 - Tools/scripts/fixcid.py | 318 -- Tools/scripts/fixheader.py | 49 - Tools/scripts/fixps.py | 32 - Tools/scripts/ftpmirror.py | 318 -- Tools/scripts/h2py.py | 141 - Tools/scripts/ifdef.py | 113 - Tools/scripts/linktree.py | 76 - Tools/scripts/lll.py | 25 - Tools/scripts/mailerdaemon.py | 257 - Tools/scripts/methfix.py | 173 - Tools/scripts/mkreal.py | 65 - Tools/scripts/objgraph.py | 215 - Tools/scripts/pathfix.py | 150 - Tools/scripts/pdeps.py | 167 - Tools/scripts/pindent.py | 440 -- Tools/scripts/ptags.py | 50 - Tools/scripts/pystone.py | 229 - Tools/scripts/suff.py | 29 - Tools/scripts/sum5.py | 97 - Tools/scripts/texi2html.py | 1500 ----- Tools/scripts/which.py | 53 - Tools/scripts/xxci.py | 117 - Tools/world/world | 143 - acconfig.h | 79 - config.h.in | 320 -- configure | 3329 ------------ configure.in | 395 -- install-sh | 119 - 1278 files changed, 279809 deletions(-) delete mode 100644 BUGS delete mode 100644 ChangeLog delete mode 100644 Demo/Makefile delete mode 100644 Demo/README delete mode 100755 Demo/classes/Complex.py delete mode 100755 Demo/classes/Dates.py delete mode 100755 Demo/classes/Dbm.py delete mode 100644 Demo/classes/README delete mode 100755 Demo/classes/Range.py delete mode 100755 Demo/classes/Rat.py delete mode 100755 Demo/classes/Rev.py delete mode 100755 Demo/classes/Vec.py delete mode 100755 Demo/classes/bitvec.py delete mode 100755 Demo/classes/class.doc delete mode 100644 Demo/comparisons/README delete mode 100755 Demo/comparisons/patterns delete mode 100755 Demo/comparisons/regextest.py delete mode 100755 Demo/comparisons/sortingtest.py delete mode 100755 Demo/comparisons/systemtest.py delete mode 100755 Demo/cwilib/cwilib.py delete mode 100755 Demo/cwilib/form.py delete mode 100755 Demo/cwilib/telnetlib.py delete mode 100755 Demo/cwilib/vt100.py delete mode 100755 Demo/cwilib/vt100win.py delete mode 100644 Demo/dns/README delete mode 100755 Demo/dns/dnsclass.py delete mode 100755 Demo/dns/dnslib.py delete mode 100755 Demo/dns/dnsopcode.py delete mode 100755 Demo/dns/dnstype.py delete mode 100644 Demo/embed/Makefile delete mode 100644 Demo/embed/README delete mode 100644 Demo/embed/demo.c delete mode 100644 Demo/ibrowse/README delete mode 100755 Demo/ibrowse/ib delete mode 100755 Demo/ibrowse/ib.py delete mode 100755 Demo/ibrowse/ibrowse delete mode 100755 Demo/ibrowse/ibrowse.py delete mode 100755 Demo/ibrowse/icache.py delete mode 100755 Demo/ibrowse/ifile.py delete mode 100755 Demo/ibrowse/itags.py delete mode 100644 Demo/md5test/README delete mode 100755 Demo/md5test/foo delete mode 100755 Demo/md5test/md5driver.py delete mode 100755 Demo/pdist/FSProxy.py delete mode 100755 Demo/pdist/RCSProxy.py delete mode 100644 Demo/pdist/README delete mode 100755 Demo/pdist/client.py delete mode 100755 Demo/pdist/cmdfw.py delete mode 100755 Demo/pdist/cmptree.py delete mode 100755 Demo/pdist/cvslib.py delete mode 100755 Demo/pdist/cvslock.py delete mode 100755 Demo/pdist/new delete mode 100755 Demo/pdist/rcsbump delete mode 100755 Demo/pdist/rcsclient.py delete mode 100755 Demo/pdist/rcslib.py delete mode 100755 Demo/pdist/rcvs delete mode 100755 Demo/pdist/rcvs.py delete mode 100755 Demo/pdist/rrcs delete mode 100755 Demo/pdist/rrcs.py delete mode 100755 Demo/pdist/security.py delete mode 100755 Demo/pdist/server.py delete mode 100755 Demo/pdist/sumtree.py delete mode 100644 Demo/rpc/MANIFEST delete mode 100644 Demo/rpc/README delete mode 100644 Demo/rpc/T.py delete mode 100644 Demo/rpc/mountclient.py delete mode 100644 Demo/rpc/nfsclient.py delete mode 100644 Demo/rpc/rnusersclient.py delete mode 100644 Demo/rpc/rpc.py delete mode 100755 Demo/rpc/test delete mode 100644 Demo/rpc/xdr.py delete mode 100644 Demo/scripts/README delete mode 100755 Demo/scripts/eqfix.py delete mode 100755 Demo/scripts/fact.py delete mode 100755 Demo/scripts/freeze.py delete mode 100755 Demo/scripts/from.py delete mode 100755 Demo/scripts/ftpstats.py delete mode 100755 Demo/scripts/lpwatch.py delete mode 100755 Demo/scripts/makedir.py delete mode 100755 Demo/scripts/markov.py delete mode 100755 Demo/scripts/mboxconvert.py delete mode 100755 Demo/scripts/mkrcs.py delete mode 100755 Demo/scripts/morse.py delete mode 100755 Demo/scripts/mpzpi.py delete mode 100755 Demo/scripts/newslist.doc delete mode 100755 Demo/scripts/newslist.py delete mode 100755 Demo/scripts/pi.py delete mode 100755 Demo/scripts/pp.py delete mode 100755 Demo/scripts/primes.py delete mode 100755 Demo/scripts/script.py delete mode 100755 Demo/scripts/unbirthday.py delete mode 100755 Demo/scripts/update.py delete mode 100755 Demo/scripts/wh.py delete mode 100644 Demo/sgi/README delete mode 100644 Demo/sgi/al/README delete mode 100755 Demo/sgi/al/alwatch.py delete mode 100755 Demo/sgi/al/broadcast.py delete mode 100755 Demo/sgi/al/cmpaf.py delete mode 100755 Demo/sgi/al/cmpaf_form.fd delete mode 100755 Demo/sgi/al/intercom.py delete mode 100755 Demo/sgi/al/listen.py delete mode 100755 Demo/sgi/al/names.py delete mode 100755 Demo/sgi/al/playaiff.py delete mode 100755 Demo/sgi/al/playback.py delete mode 100755 Demo/sgi/al/playold.py delete mode 100755 Demo/sgi/al/radio.py delete mode 100755 Demo/sgi/al/rec_play.py delete mode 100755 Demo/sgi/al/record.py delete mode 100755 Demo/sgi/al/unicast.py delete mode 100755 Demo/sgi/al/x.py delete mode 100644 Demo/sgi/audio/README delete mode 100755 Demo/sgi/audio/play.py delete mode 100644 Demo/sgi/audio_stdwin/README delete mode 100755 Demo/sgi/audio_stdwin/jukebox.py delete mode 100755 Demo/sgi/audio_stdwin/rec.py delete mode 100755 Demo/sgi/audio_stdwin/vumeter.py delete mode 100755 Demo/sgi/cd/CD.doc delete mode 100644 Demo/sgi/cd/README delete mode 100755 Demo/sgi/cd/cdaiff.py delete mode 100755 Demo/sgi/cd/cdwin.py delete mode 100755 Demo/sgi/cd/listcd.py delete mode 100755 Demo/sgi/cd/playcd.py delete mode 100755 Demo/sgi/cd/recvcd.py delete mode 100755 Demo/sgi/cd/sendcd.py delete mode 100755 Demo/sgi/flp/tcache.fd delete mode 100755 Demo/sgi/flp/tcache.py delete mode 100755 Demo/sgi/flp/test_cb.fd delete mode 100755 Demo/sgi/flp/test_cb.py delete mode 100755 Demo/sgi/flp/test_nocb.fd delete mode 100755 Demo/sgi/flp/test_nocb.py delete mode 100644 Demo/sgi/gl/README delete mode 100755 Demo/sgi/gl/backface.py delete mode 100755 Demo/sgi/gl/glinfo.py delete mode 100644 Demo/sgi/gl/glstdwin/fontchart.py delete mode 100644 Demo/sgi/gl/glstdwin/glstdwdraw.py delete mode 100644 Demo/sgi/gl/glstdwin/glstdwin.py delete mode 100644 Demo/sgi/gl/glstdwin/glstdwmenu.py delete mode 100644 Demo/sgi/gl/glstdwin/glstdwwin.py delete mode 100644 Demo/sgi/gl/glstdwin/stdwingl.py delete mode 100644 Demo/sgi/gl/glstdwin/tcolor.py delete mode 100644 Demo/sgi/gl/glstdwin/tglsw.py delete mode 100644 Demo/sgi/gl/glstdwin/tmenu.py delete mode 100755 Demo/sgi/gl/kites.py delete mode 100755 Demo/sgi/gl/kunst.py delete mode 100755 Demo/sgi/gl/mclock.doc delete mode 100755 Demo/sgi/gl/mclock.py delete mode 100755 Demo/sgi/gl/mixing.py delete mode 100755 Demo/sgi/gl/nurbs.py delete mode 100755 Demo/sgi/gl/zrgb.py delete mode 100644 Demo/sgi/sv/README delete mode 100755 Demo/sgi/sv/burstcapt.py delete mode 100755 Demo/sgi/sv/contcapt.py delete mode 100755 Demo/sgi/sv/rgbgrab.py delete mode 100755 Demo/sgi/sv/simpleinput.py delete mode 100755 Demo/sgi/video/.cvsignore delete mode 100755 Demo/sgi/video/DisplayVideoIn.py delete mode 100755 Demo/sgi/video/Dsend.py delete mode 100755 Demo/sgi/video/IN.py delete mode 100755 Demo/sgi/video/LiveVideoIn.py delete mode 100755 Demo/sgi/video/LiveVideoOut.py delete mode 100755 Demo/sgi/video/Makefile delete mode 100755 Demo/sgi/video/OldVcopy.py delete mode 100644 Demo/sgi/video/README delete mode 100755 Demo/sgi/video/VCR.py delete mode 100755 Demo/sgi/video/VFile.py delete mode 100755 Demo/sgi/video/VGrabber.py delete mode 100755 Demo/sgi/video/Vaddcache.py delete mode 100755 Demo/sgi/video/Vb.py delete mode 100644 Demo/sgi/video/VbForm.fd delete mode 100755 Demo/sgi/video/Vcopy.py delete mode 100755 Demo/sgi/video/VcrIndex.py delete mode 100755 Demo/sgi/video/Vedit.py delete mode 100644 Demo/sgi/video/VeditForm.fd delete mode 100755 Demo/sgi/video/Vfix.py delete mode 100755 Demo/sgi/video/Vgeneric.py delete mode 100755 Demo/sgi/video/Viewer.py delete mode 100755 Demo/sgi/video/Vinfo.py delete mode 100755 Demo/sgi/video/Vmkjpeg.py delete mode 100755 Demo/sgi/video/Vplay.py delete mode 100755 Demo/sgi/video/Vrec.py delete mode 100755 Demo/sgi/video/Vrecb.py delete mode 100755 Demo/sgi/video/Vrecc.py delete mode 100755 Demo/sgi/video/Vreceive.py delete mode 100755 Demo/sgi/video/Vsend.py delete mode 100755 Demo/sgi/video/Vstat.py delete mode 100755 Demo/sgi/video/Vtime.py delete mode 100755 Demo/sgi/video/Vunjpeg.py delete mode 100755 Demo/sgi/video/aplay.py delete mode 100755 Demo/sgi/video/cam.py delete mode 100755 Demo/sgi/video/camcorder.py delete mode 100755 Demo/sgi/video/cmif-film.ms delete mode 100755 Demo/sgi/video/colorsys.py delete mode 100755 Demo/sgi/video/i2v.c delete mode 100755 Demo/sgi/video/imgconv.py delete mode 100755 Demo/sgi/video/makemovie.py delete mode 100755 Demo/sgi/video/rgb2video.py delete mode 100755 Demo/sgi/video/senddefs.py delete mode 100755 Demo/sgi/video/squash.c delete mode 100755 Demo/sgi/video/squash2.c delete mode 100755 Demo/sgi/video/statit.py delete mode 100755 Demo/sgi/video/svgrab24.c delete mode 100755 Demo/sgi/video/syncaudio.py delete mode 100755 Demo/sgi/video/tomono.c delete mode 100755 Demo/sgi/video/tv.py delete mode 100755 Demo/sgi/video/v2i.c delete mode 100755 Demo/sgi/video/vcopy.py delete mode 100755 Demo/sgi/video/video.doc delete mode 100755 Demo/sgi/video/video.py delete mode 100755 Demo/sgi/video/video2rgb.py delete mode 100755 Demo/sgi/video/vinfo.py delete mode 100755 Demo/sgi/video/vpregs.py delete mode 100755 Demo/sgi/video/vtime.py delete mode 100755 Demo/sgi/video/watchcursor.py delete mode 100755 Demo/sockets/ChangeLog delete mode 100644 Demo/sockets/README delete mode 100755 Demo/sockets/broadcast.py delete mode 100755 Demo/sockets/echosvr.py delete mode 100755 Demo/sockets/finger.py delete mode 100755 Demo/sockets/ftp.py delete mode 100755 Demo/sockets/gopher.py delete mode 100755 Demo/sockets/mcast.py delete mode 100755 Demo/sockets/radio.py delete mode 100755 Demo/sockets/rpython.py delete mode 100755 Demo/sockets/rpythond.py delete mode 100755 Demo/sockets/telnet.py delete mode 100755 Demo/sockets/throughput.py delete mode 100755 Demo/sockets/udpecho.py delete mode 100755 Demo/stdwin/FormTest.py delete mode 100644 Demo/stdwin/README delete mode 100755 Demo/stdwin/RadioGroups.py delete mode 100755 Demo/stdwin/TestCSplit.py delete mode 100755 Demo/stdwin/TestDirList.py delete mode 100755 Demo/stdwin/TestFormSplit.py delete mode 100755 Demo/stdwin/TestSched.py delete mode 100755 Demo/stdwin/TestTextEdit.py delete mode 100755 Demo/stdwin/clock.py delete mode 100644 Demo/stdwin/ibrowse/README delete mode 100755 Demo/stdwin/ibrowse/dir delete mode 100755 Demo/stdwin/ibrowse/ib delete mode 100755 Demo/stdwin/ibrowse/ib.py delete mode 100755 Demo/stdwin/ibrowse/ibrowse delete mode 100755 Demo/stdwin/ibrowse/ibrowse.py delete mode 100755 Demo/stdwin/ibrowse/icache.py delete mode 100755 Demo/stdwin/ibrowse/ifile.py delete mode 100755 Demo/stdwin/ibrowse/itags.py delete mode 100755 Demo/stdwin/jukebox.py delete mode 100755 Demo/stdwin/lpwin.py delete mode 100755 Demo/stdwin/microedit.py delete mode 100755 Demo/stdwin/miniedit.py delete mode 100755 Demo/stdwin/python.py delete mode 100755 Demo/stdwin/wdiff.py delete mode 100644 Demo/threads/Generator.py delete mode 100644 Demo/threads/README delete mode 100644 Demo/threads/bug.py delete mode 100755 Demo/threads/condition.py delete mode 100644 Demo/threads/find.py delete mode 100644 Demo/threads/sync.py delete mode 100644 Demo/threads/telnet.py delete mode 100644 Demo/threads/wpi.py delete mode 100644 Demo/tkinter/README delete mode 100644 Demo/tkinter/Tree.py delete mode 100755 Demo/tkinter/guido/AttrDialog.py delete mode 100755 Demo/tkinter/guido/ManPage.py delete mode 100755 Demo/tkinter/guido/MimeViewer.py delete mode 100755 Demo/tkinter/guido/ShellWindow.py delete mode 100755 Demo/tkinter/guido/dialog.py delete mode 100755 Demo/tkinter/guido/electrons.py delete mode 100755 Demo/tkinter/guido/hanoi.py delete mode 100755 Demo/tkinter/guido/hello.py delete mode 100755 Demo/tkinter/guido/imagedraw.py delete mode 100755 Demo/tkinter/guido/imageview.py delete mode 100755 Demo/tkinter/guido/kill.py delete mode 100755 Demo/tkinter/guido/listtree.py delete mode 100755 Demo/tkinter/guido/mbox.py delete mode 100755 Demo/tkinter/guido/rmt.py delete mode 100755 Demo/tkinter/guido/svkill.py delete mode 100755 Demo/tkinter/guido/tkman.py delete mode 100755 Demo/tkinter/guido/wish.py delete mode 100644 Demo/tkinter/matt/00-HELLO-WORLD.py delete mode 100644 Demo/tkinter/matt/README delete mode 100644 Demo/tkinter/matt/animation-simple.py delete mode 100644 Demo/tkinter/matt/animation-w-velocity-ctrl.py delete mode 100644 Demo/tkinter/matt/bind-w-mult-calls-p-type.py delete mode 100644 Demo/tkinter/matt/canvas-demo-simple.py delete mode 100644 Demo/tkinter/matt/canvas-gridding.py delete mode 100644 Demo/tkinter/matt/canvas-moving-or-creating.py delete mode 100644 Demo/tkinter/matt/canvas-moving-w-mouse.py delete mode 100644 Demo/tkinter/matt/canvas-mult-item-sel.py delete mode 100644 Demo/tkinter/matt/canvas-reading-tag-info.py delete mode 100644 Demo/tkinter/matt/canvas-w-widget-draw-el.py delete mode 100644 Demo/tkinter/matt/canvas-with-scrollbars.py delete mode 100644 Demo/tkinter/matt/dialog-box.py delete mode 100644 Demo/tkinter/matt/entry-simple.py delete mode 100644 Demo/tkinter/matt/entry-with-shared-variable.py delete mode 100644 Demo/tkinter/matt/killing-window-w-wm.py delete mode 100644 Demo/tkinter/matt/menu-all-types-of-entries.py delete mode 100644 Demo/tkinter/matt/menu-simple.py delete mode 100644 Demo/tkinter/matt/not-what-you-might-think-1.py delete mode 100644 Demo/tkinter/matt/not-what-you-might-think-2.py delete mode 100644 Demo/tkinter/matt/packer-and-placer-together.py delete mode 100644 Demo/tkinter/matt/packer-simple.py delete mode 100644 Demo/tkinter/matt/placer-simple.py delete mode 100644 Demo/tkinter/matt/pong-demo-1.py delete mode 100644 Demo/tkinter/matt/printing-coords-of-items.py delete mode 100644 Demo/tkinter/matt/radiobutton-simple.py delete mode 100644 Demo/tkinter/matt/rubber-band-box-demo-1.py delete mode 100644 Demo/tkinter/matt/rubber-line-demo-1.py delete mode 100644 Demo/tkinter/matt/slider-demo-1.py delete mode 100644 Demo/tkinter/matt/subclass-existing-widgets.py delete mode 100644 Demo/tkinter/matt/two-radio-groups.py delete mode 100644 Demo/tkinter/matt/window-creation-more.py delete mode 100644 Demo/tkinter/matt/window-creation-simple.py delete mode 100644 Demo/tkinter/matt/window-creation-w-location.py delete mode 100755 Demo/tkinter/www/Para.py delete mode 100755 Demo/tkinter/www/fmt.py delete mode 100755 Demo/tkinter/www/htmllib.py delete mode 100755 Demo/tkinter/www/sgmllib.py delete mode 100755 Demo/tkinter/www/tkfmt.py delete mode 100755 Demo/tkinter/www/www1.py delete mode 100755 Demo/tkinter/www/www10.py delete mode 100755 Demo/tkinter/www/www11.py delete mode 100755 Demo/tkinter/www/www12.py delete mode 100755 Demo/tkinter/www/www13.py delete mode 100755 Demo/tkinter/www/www2.py delete mode 100755 Demo/tkinter/www/www3.py delete mode 100755 Demo/tkinter/www/www4.py delete mode 100755 Demo/tkinter/www/www5.py delete mode 100755 Demo/tkinter/www/www6.py delete mode 100755 Demo/tkinter/www/www7.py delete mode 100755 Demo/tkinter/www/www8.py delete mode 100755 Demo/tkinter/www/www9.py delete mode 100755 Doc/.cvsignore delete mode 100644 Doc/Makefile delete mode 100644 Doc/README delete mode 100644 Doc/boilerplate.tex delete mode 100644 Doc/copyright.tex delete mode 100644 Doc/ext.tex delete mode 100644 Doc/ext/ext.tex delete mode 100644 Doc/fix.el delete mode 100755 Doc/fix_hack delete mode 100644 Doc/info/texipost.dat delete mode 100644 Doc/info/texipre.dat delete mode 100644 Doc/keywords.py delete mode 100644 Doc/lib.tex delete mode 100644 Doc/lib/lib.tex delete mode 100644 Doc/lib/libaifc.tex delete mode 100644 Doc/lib/libal.tex delete mode 100644 Doc/lib/liballos.tex delete mode 100644 Doc/lib/libamoeba.tex delete mode 100644 Doc/lib/libarray.tex delete mode 100644 Doc/lib/libaudioop.tex delete mode 100644 Doc/lib/libbinascii.tex delete mode 100644 Doc/lib/libbltin.tex delete mode 100644 Doc/lib/libcd.tex delete mode 100644 Doc/lib/libcgi.tex delete mode 100644 Doc/lib/libcopy.tex delete mode 100644 Doc/lib/libcrypt.tex delete mode 100644 Doc/lib/libcrypto.tex delete mode 100644 Doc/lib/libdbm.tex delete mode 100644 Doc/lib/libexcs.tex delete mode 100644 Doc/lib/libfcntl.tex delete mode 100644 Doc/lib/libfl.tex delete mode 100644 Doc/lib/libfm.tex delete mode 100644 Doc/lib/libftplib.tex delete mode 100644 Doc/lib/libfuncs.tex delete mode 100644 Doc/lib/libgdbm.tex delete mode 100644 Doc/lib/libgetopt.tex delete mode 100644 Doc/lib/libgl.tex delete mode 100644 Doc/lib/libgopherlib.tex delete mode 100644 Doc/lib/libgrp.tex delete mode 100644 Doc/lib/libhtmllib.tex delete mode 100644 Doc/lib/libhttplib.tex delete mode 100644 Doc/lib/libimageop.tex delete mode 100644 Doc/lib/libimgfile.tex delete mode 100644 Doc/lib/libimp.tex delete mode 100644 Doc/lib/libintro.tex delete mode 100644 Doc/lib/libjpeg.tex delete mode 100644 Doc/lib/libmain.tex delete mode 100644 Doc/lib/libmarshal.tex delete mode 100644 Doc/lib/libmath.tex delete mode 100644 Doc/lib/libmd5.tex delete mode 100644 Doc/lib/libmimetools.tex delete mode 100644 Doc/lib/libmisc.tex delete mode 100644 Doc/lib/libmm.tex delete mode 100644 Doc/lib/libmpz.tex delete mode 100644 Doc/lib/libnntplib.tex delete mode 100644 Doc/lib/libobjs.tex delete mode 100644 Doc/lib/libos.tex delete mode 100644 Doc/lib/libpanel.tex delete mode 100644 Doc/lib/libparser.tex delete mode 100644 Doc/lib/libpdb.tex delete mode 100644 Doc/lib/libpickle.tex delete mode 100644 Doc/lib/libposix.tex delete mode 100644 Doc/lib/libposixfile.tex delete mode 100644 Doc/lib/libppath.tex delete mode 100644 Doc/lib/libprofile.tex delete mode 100644 Doc/lib/libpwd.tex delete mode 100644 Doc/lib/libpython.tex delete mode 100644 Doc/lib/librand.tex delete mode 100644 Doc/lib/libregex.tex delete mode 100644 Doc/lib/libregsub.tex delete mode 100644 Doc/lib/librfc822.tex delete mode 100644 Doc/lib/librgbimg.tex delete mode 100644 Doc/lib/librotor.tex delete mode 100644 Doc/lib/libselect.tex delete mode 100644 Doc/lib/libsgi.tex delete mode 100644 Doc/lib/libsgmllib.tex delete mode 100644 Doc/lib/libshelve.tex delete mode 100644 Doc/lib/libsignal.tex delete mode 100644 Doc/lib/libsocket.tex delete mode 100644 Doc/lib/libsomeos.tex delete mode 100644 Doc/lib/libstdwin.tex delete mode 100644 Doc/lib/libstring.tex delete mode 100644 Doc/lib/libstrings.tex delete mode 100644 Doc/lib/libstruct.tex delete mode 100644 Doc/lib/libsun.tex delete mode 100644 Doc/lib/libsys.tex delete mode 100644 Doc/lib/libsyslog.tex delete mode 100644 Doc/lib/libtempfile.tex delete mode 100644 Doc/lib/libtemplate.tex delete mode 100644 Doc/lib/libtermios.tex delete mode 100644 Doc/lib/libthread.tex delete mode 100644 Doc/lib/libtime.tex delete mode 100644 Doc/lib/libtraceback.tex delete mode 100644 Doc/lib/libtypes.tex delete mode 100644 Doc/lib/libtypes2.tex delete mode 100644 Doc/lib/libunix.tex delete mode 100644 Doc/lib/liburllib.tex delete mode 100644 Doc/lib/liburlparse.tex delete mode 100644 Doc/lib/libwhrandom.tex delete mode 100644 Doc/lib/libwww.tex delete mode 100644 Doc/libaifc.tex delete mode 100644 Doc/libal.tex delete mode 100644 Doc/liballos.tex delete mode 100644 Doc/libamoeba.tex delete mode 100644 Doc/libarray.tex delete mode 100644 Doc/libaudio.tex delete mode 100644 Doc/libaudioop.tex delete mode 100644 Doc/libbinascii.tex delete mode 100644 Doc/libbltin.tex delete mode 100644 Doc/libcd.tex delete mode 100644 Doc/libcgi.tex delete mode 100644 Doc/libcopy.tex delete mode 100644 Doc/libcrypt.tex delete mode 100644 Doc/libcrypto.tex delete mode 100644 Doc/libctb.tex delete mode 100644 Doc/libdbm.tex delete mode 100644 Doc/libexcs.tex delete mode 100644 Doc/libfcntl.tex delete mode 100644 Doc/libfl.tex delete mode 100644 Doc/libfm.tex delete mode 100644 Doc/libftplib.tex delete mode 100644 Doc/libfuncs.tex delete mode 100644 Doc/libgdbm.tex delete mode 100644 Doc/libgetopt.tex delete mode 100644 Doc/libgl.tex delete mode 100644 Doc/libgopherlib.tex delete mode 100644 Doc/libgrp.tex delete mode 100644 Doc/libhtmllib.tex delete mode 100644 Doc/libhttplib.tex delete mode 100644 Doc/libimageop.tex delete mode 100644 Doc/libimgfile.tex delete mode 100644 Doc/libimp.tex delete mode 100644 Doc/libintro.tex delete mode 100644 Doc/libjpeg.tex delete mode 100644 Doc/libmac.tex delete mode 100644 Doc/libmacconsole.tex delete mode 100644 Doc/libmacdnr.tex delete mode 100644 Doc/libmacfs.tex delete mode 100644 Doc/libmacos.tex delete mode 100644 Doc/libmacostools.tex delete mode 100644 Doc/libmacspeech.tex delete mode 100644 Doc/libmactcp.tex delete mode 100644 Doc/libmacui.tex delete mode 100644 Doc/libmain.tex delete mode 100644 Doc/libmarshal.tex delete mode 100644 Doc/libmath.tex delete mode 100644 Doc/libmd5.tex delete mode 100644 Doc/libmimetools.tex delete mode 100644 Doc/libmisc.tex delete mode 100644 Doc/libmm.tex delete mode 100755 Doc/libmods.tex delete mode 100644 Doc/libmpz.tex delete mode 100644 Doc/libnntplib.tex delete mode 100644 Doc/libobjs.tex delete mode 100644 Doc/libos.tex delete mode 100644 Doc/libpanel.tex delete mode 100644 Doc/libparser.tex delete mode 100644 Doc/libpdb.tex delete mode 100644 Doc/libpickle.tex delete mode 100644 Doc/libposix.tex delete mode 100644 Doc/libposixfile.tex delete mode 100644 Doc/libppath.tex delete mode 100644 Doc/libprofile.tex delete mode 100644 Doc/libpwd.tex delete mode 100644 Doc/libpython.tex delete mode 100644 Doc/librand.tex delete mode 100644 Doc/libregex.tex delete mode 100644 Doc/libregsub.tex delete mode 100644 Doc/librfc822.tex delete mode 100644 Doc/librgbimg.tex delete mode 100644 Doc/librotor.tex delete mode 100644 Doc/libselect.tex delete mode 100644 Doc/libsgi.tex delete mode 100644 Doc/libsgmllib.tex delete mode 100644 Doc/libshelve.tex delete mode 100644 Doc/libsignal.tex delete mode 100644 Doc/libsocket.tex delete mode 100644 Doc/libsomeos.tex delete mode 100755 Doc/libstd.tex delete mode 100644 Doc/libstdwin.tex delete mode 100644 Doc/libstring.tex delete mode 100644 Doc/libstrings.tex delete mode 100644 Doc/libstruct.tex delete mode 100644 Doc/libsun.tex delete mode 100644 Doc/libsys.tex delete mode 100644 Doc/libsyslog.tex delete mode 100644 Doc/libtempfile.tex delete mode 100644 Doc/libtemplate.tex delete mode 100644 Doc/libtermios.tex delete mode 100644 Doc/libthread.tex delete mode 100644 Doc/libtime.tex delete mode 100644 Doc/libtraceback.tex delete mode 100644 Doc/libtypes.tex delete mode 100644 Doc/libtypes2.tex delete mode 100644 Doc/libunix.tex delete mode 100644 Doc/liburllib.tex delete mode 100644 Doc/liburlparse.tex delete mode 100644 Doc/libwhrandom.tex delete mode 100644 Doc/libwww.tex delete mode 100644 Doc/mac/libctb.tex delete mode 100644 Doc/mac/libmac.tex delete mode 100644 Doc/mac/libmacconsole.tex delete mode 100644 Doc/mac/libmacdnr.tex delete mode 100644 Doc/mac/libmacfs.tex delete mode 100644 Doc/mac/libmacos.tex delete mode 100644 Doc/mac/libmacostools.tex delete mode 100644 Doc/mac/libmacspeech.tex delete mode 100644 Doc/mac/libmactcp.tex delete mode 100644 Doc/mac/libmacui.tex delete mode 100644 Doc/myformat.perl delete mode 100644 Doc/myformat.sty delete mode 100644 Doc/partparse.py delete mode 100644 Doc/qua.tex delete mode 100644 Doc/quabib.bib delete mode 100644 Doc/ref.tex delete mode 100644 Doc/ref/ref.tex delete mode 100644 Doc/ref/ref1.tex delete mode 100644 Doc/ref/ref2.tex delete mode 100644 Doc/ref/ref3.tex delete mode 100644 Doc/ref/ref4.tex delete mode 100644 Doc/ref/ref5.tex delete mode 100644 Doc/ref/ref6.tex delete mode 100644 Doc/ref/ref7.tex delete mode 100644 Doc/ref/ref8.tex delete mode 100644 Doc/ref1.tex delete mode 100644 Doc/ref2.tex delete mode 100644 Doc/ref3.tex delete mode 100644 Doc/ref4.tex delete mode 100644 Doc/ref5.tex delete mode 100644 Doc/ref6.tex delete mode 100644 Doc/ref7.tex delete mode 100644 Doc/ref8.tex delete mode 100644 Doc/templates/module.tex delete mode 100644 Doc/texi2html.py delete mode 100644 Doc/texinputs/boilerplate.tex delete mode 100644 Doc/texinputs/copyright.tex delete mode 100644 Doc/texipost.dat delete mode 100644 Doc/texipre.dat delete mode 100644 Doc/text2latex.py delete mode 100644 Doc/tools/fix.el delete mode 100755 Doc/tools/fix_hack delete mode 100644 Doc/tools/keywords.py delete mode 100644 Doc/tools/partparse.py delete mode 100644 Doc/tools/texi2html.py delete mode 100644 Doc/tools/text2latex.py delete mode 100755 Doc/tools/whichlibs delete mode 100644 Doc/tut.tex delete mode 100644 Doc/tut/tut.tex delete mode 100755 Doc/whichlibs delete mode 100644 Grammar/Grammar delete mode 100644 Grammar/Makefile delete mode 100644 Include/Makefile delete mode 100644 Include/Python.h delete mode 100644 Include/abstract.h delete mode 100644 Include/accessobject.h delete mode 100644 Include/allobjects.h delete mode 100644 Include/assert.h delete mode 100644 Include/bitset.h delete mode 100644 Include/bltinmodule.h delete mode 100644 Include/ceval.h delete mode 100644 Include/cgensupport.h delete mode 100644 Include/classobject.h delete mode 100644 Include/cobject.h delete mode 100644 Include/compile.h delete mode 100644 Include/complexobject.h delete mode 100755 Include/config.h delete mode 100644 Include/dictobject.h delete mode 100644 Include/errcode.h delete mode 100755 Include/errors.h delete mode 100644 Include/eval.h delete mode 100644 Include/fileobject.h delete mode 100644 Include/floatobject.h delete mode 100644 Include/frameobject.h delete mode 100644 Include/funcobject.h delete mode 100644 Include/graminit.h delete mode 100644 Include/grammar.h delete mode 100644 Include/import.h delete mode 100644 Include/intobject.h delete mode 100644 Include/intrcheck.h delete mode 100644 Include/listobject.h delete mode 100644 Include/longintrepr.h delete mode 100644 Include/longobject.h delete mode 100644 Include/mappingobject.h delete mode 100644 Include/marshal.h delete mode 100644 Include/metagrammar.h delete mode 100644 Include/methodobject.h delete mode 100644 Include/modsupport.h delete mode 100644 Include/moduleobject.h delete mode 100644 Include/mymalloc.h delete mode 100644 Include/mymath.h delete mode 100644 Include/myproto.h delete mode 100644 Include/myselect.h delete mode 100644 Include/mytime.h delete mode 100644 Include/node.h delete mode 100644 Include/object.h delete mode 100644 Include/objimpl.h delete mode 100644 Include/opcode.h delete mode 100644 Include/osdefs.h delete mode 100644 Include/parsetok.h delete mode 100644 Include/patchlevel.h delete mode 100644 Include/pgenheaders.h delete mode 100644 Include/pydebug.h delete mode 100644 Include/pyerrors.h delete mode 100644 Include/pythonrun.h delete mode 100644 Include/pythread.h delete mode 100644 Include/rangeobject.h delete mode 100755 Include/rename1.h delete mode 100644 Include/rename2.h delete mode 100644 Include/stringobject.h delete mode 100644 Include/structmember.h delete mode 100644 Include/sysmodule.h delete mode 100644 Include/thread.h delete mode 100644 Include/token.h delete mode 100644 Include/traceback.h delete mode 100644 Include/tupleobject.h delete mode 100755 Lib/ArrayIO.py delete mode 100644 Lib/BaseHTTPServer.py delete mode 100644 Lib/CGIHTTPServer.py delete mode 100644 Lib/Complex.py delete mode 100644 Lib/Makefile delete mode 100644 Lib/Para.py delete mode 100644 Lib/Queue.py delete mode 100644 Lib/SimpleHTTPServer.py delete mode 100644 Lib/SocketServer.py delete mode 100644 Lib/StringIO.py delete mode 100644 Lib/UserDict.py delete mode 100644 Lib/UserList.py delete mode 100644 Lib/addpack.py delete mode 100644 Lib/aifc.py delete mode 100644 Lib/anydbm.py delete mode 100644 Lib/audiodev.py delete mode 100755 Lib/base64.py delete mode 100644 Lib/bdb.py delete mode 100644 Lib/binhex.py delete mode 100644 Lib/bisect.py delete mode 100755 Lib/builtin.py delete mode 100644 Lib/calendar.py delete mode 100755 Lib/cgi.py delete mode 100644 Lib/cmd.py delete mode 100644 Lib/cmp.py delete mode 100644 Lib/cmpcache.py delete mode 100644 Lib/codehack.py delete mode 100644 Lib/colorsys.py delete mode 100644 Lib/commands.py delete mode 100644 Lib/compileall.py delete mode 100644 Lib/copy.py delete mode 100644 Lib/dbhash.py delete mode 100644 Lib/dircache.py delete mode 100644 Lib/dircmp.py delete mode 100644 Lib/dis.py delete mode 100644 Lib/dospath.py delete mode 100644 Lib/dumbdbm.py delete mode 100644 Lib/dump.py delete mode 100644 Lib/emacs.py delete mode 100644 Lib/find.py delete mode 100644 Lib/fmt.py delete mode 100644 Lib/fnmatch.py delete mode 100644 Lib/formatter.py delete mode 100644 Lib/fpformat.py delete mode 100644 Lib/ftplib.py delete mode 100644 Lib/getopt.py delete mode 100644 Lib/glob.py delete mode 100644 Lib/gopherlib.py delete mode 100644 Lib/grep.py delete mode 100644 Lib/htmlentitydefs.py delete mode 100644 Lib/htmllib.py delete mode 100644 Lib/httplib.py delete mode 100644 Lib/ihooks.py delete mode 100644 Lib/imghdr.py delete mode 100755 Lib/importall.py delete mode 100755 Lib/irix5/AL.py delete mode 100755 Lib/irix5/AWARE.py delete mode 100755 Lib/irix5/CD.py delete mode 100755 Lib/irix5/CL.py delete mode 100755 Lib/irix5/CL_old.py delete mode 100755 Lib/irix5/DEVICE.py delete mode 100755 Lib/irix5/ERRNO.py delete mode 100755 Lib/irix5/FCNTL.py delete mode 100755 Lib/irix5/FL.py delete mode 100755 Lib/irix5/GET.py delete mode 100755 Lib/irix5/GL.py delete mode 100755 Lib/irix5/GLWS.py delete mode 100755 Lib/irix5/IN.py delete mode 100755 Lib/irix5/IOCTL.py delete mode 100755 Lib/irix5/SOCKET.py delete mode 100755 Lib/irix5/SV.py delete mode 100755 Lib/irix5/TERMIOS.py delete mode 100755 Lib/irix5/WAIT.py delete mode 100755 Lib/irix5/auds.py delete mode 100755 Lib/irix5/cddb.py delete mode 100755 Lib/irix5/cdplayer.py delete mode 100755 Lib/irix5/flp.doc delete mode 100755 Lib/irix5/flp.py delete mode 100755 Lib/irix5/jpeg.py delete mode 100755 Lib/irix5/panel.py delete mode 100755 Lib/irix5/panelparser.py delete mode 100755 Lib/irix5/readcd.doc delete mode 100755 Lib/irix5/readcd.py delete mode 100755 Lib/irix5/regen delete mode 100755 Lib/irix5/torgb.py delete mode 100644 Lib/lib-old/Para.py delete mode 100644 Lib/lib-old/addpack.py delete mode 100644 Lib/lib-old/codehack.py delete mode 100644 Lib/lib-old/dump.py delete mode 100644 Lib/lib-old/find.py delete mode 100644 Lib/lib-old/fmt.py delete mode 100644 Lib/lib-old/grep.py delete mode 100644 Lib/lib-old/lockfile.py delete mode 100644 Lib/lib-old/newdir.py delete mode 100644 Lib/lib-old/packmail.py delete mode 100644 Lib/lib-old/rand.py delete mode 100644 Lib/lib-old/tb.py delete mode 100644 Lib/lib-old/util.py delete mode 100644 Lib/lib-old/whatsound.py delete mode 100644 Lib/lib-stdwin/Abstract.py delete mode 100644 Lib/lib-stdwin/BoxParent.py delete mode 100644 Lib/lib-stdwin/Buttons.py delete mode 100644 Lib/lib-stdwin/CSplit.py delete mode 100644 Lib/lib-stdwin/DirList.py delete mode 100644 Lib/lib-stdwin/FormSplit.py delete mode 100644 Lib/lib-stdwin/HVSplit.py delete mode 100644 Lib/lib-stdwin/Histogram.py delete mode 100644 Lib/lib-stdwin/Sliders.py delete mode 100644 Lib/lib-stdwin/Soundogram.py delete mode 100644 Lib/lib-stdwin/Split.py delete mode 100644 Lib/lib-stdwin/StripChart.py delete mode 100644 Lib/lib-stdwin/TextEdit.py delete mode 100644 Lib/lib-stdwin/TransParent.py delete mode 100644 Lib/lib-stdwin/VUMeter.py delete mode 100644 Lib/lib-stdwin/WindowParent.py delete mode 100644 Lib/lib-stdwin/WindowSched.py delete mode 100644 Lib/lib-stdwin/anywin.py delete mode 100644 Lib/lib-stdwin/basewin.py delete mode 100644 Lib/lib-stdwin/dirwin.py delete mode 100644 Lib/lib-stdwin/filewin.py delete mode 100644 Lib/lib-stdwin/formatter.py delete mode 100644 Lib/lib-stdwin/gwin.py delete mode 100644 Lib/lib-stdwin/listwin.py delete mode 100644 Lib/lib-stdwin/mainloop.py delete mode 100644 Lib/lib-stdwin/rect.py delete mode 100644 Lib/lib-stdwin/srcwin.py delete mode 100644 Lib/lib-stdwin/stdwinevents.py delete mode 100644 Lib/lib-stdwin/stdwinq.py delete mode 100644 Lib/lib-stdwin/tablewin.py delete mode 100644 Lib/lib-stdwin/textwin.py delete mode 100644 Lib/lib-stdwin/wdb.py delete mode 100644 Lib/lib-stdwin/wdbframewin.py delete mode 100644 Lib/lib-stdwin/wdbsrcwin.py delete mode 100644 Lib/lib-tk/Canvas.py delete mode 100644 Lib/lib-tk/Dialog.py delete mode 100644 Lib/lib-tk/FileDialog.py delete mode 100644 Lib/lib-tk/ScrolledText.py delete mode 100644 Lib/lib-tk/Tkconstants.py delete mode 100644 Lib/lib-tk/Tkinter.py delete mode 100644 Lib/linecache.py delete mode 100755 Lib/linux1/FCNTL.py delete mode 100755 Lib/linux1/IN.py delete mode 100755 Lib/linux1/SOCKET.py delete mode 100755 Lib/linux1/TERMIOS.py delete mode 100755 Lib/linux1/regen delete mode 100644 Lib/lockfile.py delete mode 100644 Lib/macpath.py delete mode 100755 Lib/macstat.py delete mode 100644 Lib/macurl2path.py delete mode 100755 Lib/mailbox.py delete mode 100644 Lib/mailcap.py delete mode 100644 Lib/mhlib.py delete mode 100644 Lib/mimetools.py delete mode 100755 Lib/mimify.py delete mode 100644 Lib/multifile.py delete mode 100644 Lib/mutex.py delete mode 100644 Lib/newdir.py delete mode 100755 Lib/newimp.py delete mode 100644 Lib/ni.py delete mode 100644 Lib/ni1.py delete mode 100644 Lib/nntplib.py delete mode 100644 Lib/ntpath.py delete mode 100644 Lib/os.py delete mode 100644 Lib/ospath.py delete mode 100644 Lib/packmail.py delete mode 100644 Lib/pdb.doc delete mode 100755 Lib/pdb.py delete mode 100755 Lib/persist.py delete mode 100644 Lib/pickle.py delete mode 100644 Lib/pipes.py delete mode 100755 Lib/plat-irix5/AL.py delete mode 100755 Lib/plat-irix5/AWARE.py delete mode 100755 Lib/plat-irix5/CD.py delete mode 100755 Lib/plat-irix5/CL.py delete mode 100755 Lib/plat-irix5/CL_old.py delete mode 100755 Lib/plat-irix5/DEVICE.py delete mode 100755 Lib/plat-irix5/ERRNO.py delete mode 100755 Lib/plat-irix5/FCNTL.py delete mode 100755 Lib/plat-irix5/FL.py delete mode 100755 Lib/plat-irix5/GET.py delete mode 100755 Lib/plat-irix5/GL.py delete mode 100755 Lib/plat-irix5/GLWS.py delete mode 100755 Lib/plat-irix5/IN.py delete mode 100755 Lib/plat-irix5/IOCTL.py delete mode 100755 Lib/plat-irix5/SOCKET.py delete mode 100755 Lib/plat-irix5/SV.py delete mode 100755 Lib/plat-irix5/TERMIOS.py delete mode 100755 Lib/plat-irix5/WAIT.py delete mode 100755 Lib/plat-irix5/cddb.py delete mode 100755 Lib/plat-irix5/cdplayer.py delete mode 100755 Lib/plat-irix5/flp.doc delete mode 100755 Lib/plat-irix5/flp.py delete mode 100755 Lib/plat-irix5/jpeg.py delete mode 100755 Lib/plat-irix5/panel.py delete mode 100755 Lib/plat-irix5/panelparser.py delete mode 100755 Lib/plat-irix5/readcd.doc delete mode 100755 Lib/plat-irix5/readcd.py delete mode 100755 Lib/plat-irix5/regen delete mode 100755 Lib/plat-irix5/torgb.py delete mode 100755 Lib/plat-linux1/FCNTL.py delete mode 100755 Lib/plat-linux1/IN.py delete mode 100755 Lib/plat-linux1/SOCKET.py delete mode 100755 Lib/plat-linux1/TERMIOS.py delete mode 100755 Lib/plat-linux1/regen delete mode 100755 Lib/plat-sunos4/FCNTL.py delete mode 100755 Lib/plat-sunos4/IN.py delete mode 100755 Lib/plat-sunos4/SOCKET.py delete mode 100755 Lib/plat-sunos4/SUNAUDIODEV.py delete mode 100755 Lib/plat-sunos4/WAIT.py delete mode 100755 Lib/plat-sunos4/regen delete mode 100755 Lib/plat-sunos5/FCNTL.py delete mode 100755 Lib/plat-sunos5/IN.py delete mode 100755 Lib/plat-sunos5/SOCKET.py delete mode 100755 Lib/plat-sunos5/SUNAUDIODEV.py delete mode 100755 Lib/plat-sunos5/TERMIOS.py delete mode 100755 Lib/plat-sunos5/regen delete mode 100644 Lib/poly.py delete mode 100644 Lib/popen2.py delete mode 100644 Lib/posixfile.py delete mode 100644 Lib/posixpath.py delete mode 100644 Lib/profile.doc delete mode 100755 Lib/profile.py delete mode 100644 Lib/pstats.py delete mode 100644 Lib/pty.py delete mode 100644 Lib/py_compile.py delete mode 100644 Lib/pyclbr.py delete mode 100755 Lib/quopri.py delete mode 100644 Lib/rand.py delete mode 100644 Lib/random.py delete mode 100644 Lib/regex_syntax.py delete mode 100644 Lib/regexp.py delete mode 100644 Lib/regsub.py delete mode 100644 Lib/repr.py delete mode 100644 Lib/rexec.py delete mode 100644 Lib/rfc822.py delete mode 100644 Lib/sched.py delete mode 100644 Lib/sgmllib.py delete mode 100644 Lib/shelve.py delete mode 100644 Lib/shutil.py delete mode 100644 Lib/sndhdr.py delete mode 100644 Lib/stat.py delete mode 100644 Lib/statcache.py delete mode 100755 Lib/stdwin/Abstract.py delete mode 100755 Lib/stdwin/BoxParent.py delete mode 100755 Lib/stdwin/Buttons.py delete mode 100755 Lib/stdwin/CSplit.py delete mode 100755 Lib/stdwin/DirList.py delete mode 100755 Lib/stdwin/FormSplit.py delete mode 100755 Lib/stdwin/HVSplit.py delete mode 100755 Lib/stdwin/Histogram.py delete mode 100755 Lib/stdwin/Sliders.py delete mode 100755 Lib/stdwin/Soundogram.py delete mode 100755 Lib/stdwin/Split.py delete mode 100755 Lib/stdwin/StripChart.py delete mode 100755 Lib/stdwin/TextEdit.py delete mode 100755 Lib/stdwin/TransParent.py delete mode 100755 Lib/stdwin/VUMeter.py delete mode 100755 Lib/stdwin/WindowParent.py delete mode 100755 Lib/stdwin/WindowSched.py delete mode 100755 Lib/stdwin/anywin.py delete mode 100755 Lib/stdwin/basewin.py delete mode 100755 Lib/stdwin/dirwin.py delete mode 100755 Lib/stdwin/filewin.py delete mode 100755 Lib/stdwin/formatter.py delete mode 100755 Lib/stdwin/gwin.py delete mode 100755 Lib/stdwin/listwin.py delete mode 100755 Lib/stdwin/mainloop.py delete mode 100755 Lib/stdwin/rect.py delete mode 100755 Lib/stdwin/srcwin.py delete mode 100755 Lib/stdwin/stdwinevents.py delete mode 100755 Lib/stdwin/stdwinq.py delete mode 100755 Lib/stdwin/tablewin.py delete mode 100755 Lib/stdwin/textwin.py delete mode 100755 Lib/stdwin/wdb.py delete mode 100755 Lib/stdwin/wdbframewin.py delete mode 100755 Lib/stdwin/wdbsrcwin.py delete mode 100644 Lib/string.py delete mode 100644 Lib/stringold.py delete mode 100644 Lib/sunau.py delete mode 100644 Lib/sunaudio.py delete mode 100755 Lib/sunos4/FCNTL.py delete mode 100755 Lib/sunos4/IN.py delete mode 100755 Lib/sunos4/SOCKET.py delete mode 100755 Lib/sunos4/SUNAUDIODEV.py delete mode 100755 Lib/sunos4/WAIT.py delete mode 100755 Lib/sunos4/regen delete mode 100755 Lib/sunos5/FCNTL.py delete mode 100755 Lib/sunos5/IN.py delete mode 100755 Lib/sunos5/SOCKET.py delete mode 100755 Lib/sunos5/SUNAUDIODEV.py delete mode 100755 Lib/sunos5/TERMIOS.py delete mode 100755 Lib/sunos5/regen delete mode 100755 Lib/symbol.py delete mode 100644 Lib/tb.py delete mode 100644 Lib/tempfile.py delete mode 100644 Lib/test/autotest.py delete mode 100755 Lib/test/pystone.py delete mode 100644 Lib/test/test.rawimg delete mode 100644 Lib/test/test.rawimg.rev delete mode 100644 Lib/test/test.rgb delete mode 100644 Lib/test/test_audioop.py delete mode 100644 Lib/test/test_b1.py delete mode 100644 Lib/test/test_b2.py delete mode 100644 Lib/test/test_builtin.py delete mode 100644 Lib/test/test_exceptions.py delete mode 100644 Lib/test/test_grammar.py delete mode 100644 Lib/test/test_md5.py delete mode 100644 Lib/test/test_opcodes.py delete mode 100644 Lib/test/test_operations.py delete mode 100644 Lib/test/test_pow.py delete mode 100644 Lib/test/test_rgbimg.py delete mode 100644 Lib/test/test_select.py delete mode 100644 Lib/test/test_signal.py delete mode 100644 Lib/test/test_support.py delete mode 100644 Lib/test/test_thread.py delete mode 100644 Lib/test/test_types.py delete mode 100644 Lib/test/testall.out delete mode 100644 Lib/test/testall.py delete mode 100755 Lib/tkinter/Canvas.py delete mode 100755 Lib/tkinter/Dialog.py delete mode 100755 Lib/tkinter/FileDialog.py delete mode 100755 Lib/tkinter/README delete mode 100755 Lib/tkinter/ScrolledText.py delete mode 100755 Lib/tkinter/Tkconstants.py delete mode 100755 Lib/tkinter/Tkinter.py delete mode 100644 Lib/toaiff.py delete mode 100755 Lib/token.py delete mode 100644 Lib/tokenize.py delete mode 100644 Lib/traceback.py delete mode 100644 Lib/tty.py delete mode 100644 Lib/types.py delete mode 100644 Lib/tzparse.py delete mode 100644 Lib/urllib.py delete mode 100755 Lib/urlopen.py delete mode 100644 Lib/urlparse.py delete mode 100644 Lib/util.py delete mode 100755 Lib/uu.py delete mode 100644 Lib/wave.py delete mode 100644 Lib/whatsound.py delete mode 100644 Lib/whrandom.py delete mode 100644 Lib/zmod.py delete mode 100644 Mac/MPW/buildall delete mode 100644 Mac/Unsupported/mactcp/dnrglue.c delete mode 100644 Mac/errno_unix.h delete mode 100644 Mac/fopenRF.c delete mode 100644 Mac/mkapplet.py delete mode 100644 Mac/mwerks/mwerks_applet_config.h delete mode 100644 Mac/mwerks/mwerks_config.h delete mode 100644 Mac/mwerks/mwerks_shlib_config.h delete mode 100644 Mac/mwerksglue.c delete mode 100644 Makefile.in delete mode 100644 Misc/ACKS delete mode 100644 Misc/AIX-NOTES delete mode 100644 Misc/BLURB delete mode 100644 Misc/BLURB.LUTZ delete mode 100644 Misc/COPYRIGHT delete mode 100644 Misc/FAQ delete mode 100755 Misc/Fixcprt.py delete mode 100644 Misc/HISTORY delete mode 100644 Misc/HPUX-NOTES delete mode 100644 Misc/HYPE delete mode 100644 Misc/Makefile delete mode 100644 Misc/NEWS delete mode 100644 Misc/QuickRef-1.1.1.ps delete mode 100644 Misc/README delete mode 100644 Misc/RFD delete mode 100644 Misc/cheatsheet delete mode 100755 Misc/dlMakefile delete mode 100755 Misc/faq2html.py delete mode 100755 Misc/fixfuncptrs.sh delete mode 100644 Misc/indent.pro delete mode 100755 Misc/pyimenu.el delete mode 100644 Misc/python-mode-old.el delete mode 100644 Misc/python-mode.el delete mode 100644 Misc/python.gif delete mode 100644 Misc/python.man delete mode 100755 Misc/renumber.py delete mode 100644 Misc/setuid-prog.c delete mode 100644 Modules/Makefile.pre.in delete mode 100644 Modules/Setup.in delete mode 100644 Modules/_cursesmodule.c delete mode 100644 Modules/_tkinter.c delete mode 100644 Modules/almodule.c delete mode 100644 Modules/arraymodule.c delete mode 100644 Modules/audioop.c delete mode 100644 Modules/binascii.c delete mode 100644 Modules/bsddbmodule.c delete mode 100644 Modules/cdmodule.c delete mode 100644 Modules/cgen.py delete mode 100644 Modules/cgensupport.c delete mode 100644 Modules/cgensupport.h delete mode 100644 Modules/clmodule.c delete mode 100644 Modules/cmathmodule.c delete mode 100644 Modules/config.c.in delete mode 100644 Modules/cryptmodule.c delete mode 100644 Modules/cstubs delete mode 100644 Modules/dbhashmodule.c delete mode 100644 Modules/dbmmodule.c delete mode 100644 Modules/dlmodule.c delete mode 100644 Modules/environment.c delete mode 100644 Modules/fcntlmodule.c delete mode 100644 Modules/flmodule.c delete mode 100644 Modules/fmmodule.c delete mode 100644 Modules/gdbmmodule.c delete mode 100644 Modules/getpath.c delete mode 100644 Modules/grpmodule.c delete mode 100644 Modules/imageop.c delete mode 100644 Modules/imgfile.c delete mode 100644 Modules/main.c delete mode 100755 Modules/makesetup delete mode 100644 Modules/mathmodule.c delete mode 100644 Modules/md5.h delete mode 100644 Modules/md5c.c delete mode 100644 Modules/md5module.c delete mode 100644 Modules/mpzmodule.c delete mode 100644 Modules/newmodule.c delete mode 100644 Modules/nismodule.c delete mode 100644 Modules/objc.c delete mode 100644 Modules/parsermodule.c delete mode 100644 Modules/posixmodule.c delete mode 100644 Modules/pwdmodule.c delete mode 100644 Modules/regexmodule.c delete mode 100644 Modules/regexpr.c delete mode 100644 Modules/regexpr.h delete mode 100644 Modules/rgbimgmodule.c delete mode 100644 Modules/rotormodule.c delete mode 100644 Modules/selectmodule.c delete mode 100644 Modules/sgimodule.c delete mode 100644 Modules/signalmodule.c delete mode 100644 Modules/socketmodule.c delete mode 100644 Modules/soundex.c delete mode 100644 Modules/stdwinmodule.c delete mode 100644 Modules/stropmodule.c delete mode 100644 Modules/structmodule.c delete mode 100644 Modules/sunaudiodev.c delete mode 100644 Modules/svmodule.c delete mode 100644 Modules/sybasemodule.c delete mode 100644 Modules/syslogmodule.c delete mode 100644 Modules/termios.c delete mode 100644 Modules/threadmodule.c delete mode 100644 Modules/timemodule.c delete mode 100644 Modules/timing.h delete mode 100644 Modules/timingmodule.c delete mode 100644 Modules/tkappinit.c delete mode 100644 Modules/xxmodule.c delete mode 100644 Modules/yuv.h delete mode 100644 Modules/yuvconvert.c delete mode 100644 Objects/Makefile.in delete mode 100644 Objects/abstract.c delete mode 100644 Objects/accessobject.c delete mode 100644 Objects/classobject.c delete mode 100644 Objects/cobject.c delete mode 100644 Objects/complexobject.c delete mode 100644 Objects/dictobject.c delete mode 100644 Objects/fileobject.c delete mode 100644 Objects/floatobject.c delete mode 100644 Objects/frameobject.c delete mode 100644 Objects/funcobject.c delete mode 100644 Objects/intobject.c delete mode 100644 Objects/listobject.c delete mode 100644 Objects/longobject.c delete mode 100644 Objects/mappingobject.c delete mode 100644 Objects/methodobject.c delete mode 100644 Objects/moduleobject.c delete mode 100644 Objects/object.c delete mode 100644 Objects/rangeobject.c delete mode 100644 Objects/stringobject.c delete mode 100644 Objects/tupleobject.c delete mode 100644 Objects/typeobject.c delete mode 100644 Objects/xxobject.c delete mode 100644 PC/config.c delete mode 100644 PC/config.h delete mode 100644 Parser/Makefile.in delete mode 100644 Parser/acceler.c delete mode 100644 Parser/assert.h delete mode 100644 Parser/bitset.c delete mode 100644 Parser/firstsets.c delete mode 100644 Parser/grammar.c delete mode 100644 Parser/grammar1.c delete mode 100644 Parser/intrcheck.c delete mode 100644 Parser/listnode.c delete mode 100644 Parser/metagrammar.c delete mode 100644 Parser/myreadline.c delete mode 100644 Parser/node.c delete mode 100644 Parser/parser.c delete mode 100644 Parser/parser.h delete mode 100644 Parser/parsetok.c delete mode 100644 Parser/pgen.c delete mode 100644 Parser/pgen.h delete mode 100644 Parser/pgenmain.c delete mode 100644 Parser/printgrammar.c delete mode 100644 Parser/tokenizer.c delete mode 100644 Parser/tokenizer.h delete mode 100644 Python/Makefile.in delete mode 100644 Python/atof.c delete mode 100644 Python/bltinmodule.c delete mode 100644 Python/ceval.c delete mode 100644 Python/cgensupport.c delete mode 100644 Python/compile.c delete mode 100644 Python/dup2.c delete mode 100644 Python/errors.c delete mode 100644 Python/fmod.c delete mode 100644 Python/frozen.c delete mode 100644 Python/frozenmain.c delete mode 100644 Python/getargs.c delete mode 100644 Python/getcompiler.c delete mode 100644 Python/getcopyright.c delete mode 100644 Python/getcwd.c delete mode 100644 Python/getmtime.c delete mode 100644 Python/getopt.c delete mode 100644 Python/getplatform.c delete mode 100644 Python/getversion.c delete mode 100644 Python/graminit.c delete mode 100644 Python/import.c delete mode 100644 Python/importdl.c delete mode 100644 Python/importdl.h delete mode 100644 Python/marshal.c delete mode 100644 Python/memmove.c delete mode 100644 Python/modsupport.c delete mode 100644 Python/mystrtoul.c delete mode 100644 Python/pythonmain.c delete mode 100644 Python/pythonrun.c delete mode 100644 Python/sigcheck.c delete mode 100644 Python/strerror.c delete mode 100644 Python/strtod.c delete mode 100644 Python/structmember.c delete mode 100644 Python/sysmodule.c delete mode 100644 Python/thread.c delete mode 100644 Python/thread_cthread.h delete mode 100644 Python/thread_foobar.h delete mode 100644 Python/thread_lwp.h delete mode 100644 Python/thread_nt.h delete mode 100644 Python/thread_os2.h delete mode 100644 Python/thread_pthread.h delete mode 100644 Python/thread_sgi.h delete mode 100644 Python/thread_solaris.h delete mode 100644 Python/traceback.c delete mode 100644 README delete mode 100644 TODO delete mode 100644 Tools/README delete mode 100644 Tools/bgen/README delete mode 100644 Tools/bgen/bgen/bgen.py delete mode 100644 Tools/bgen/bgen/bgenBuffer.py delete mode 100644 Tools/bgen/bgen/bgenGenerator.py delete mode 100644 Tools/bgen/bgen/bgenGeneratorGroup.py delete mode 100644 Tools/bgen/bgen/bgenHeapBuffer.py delete mode 100644 Tools/bgen/bgen/bgenModule.py delete mode 100644 Tools/bgen/bgen/bgenObjectDefinition.py delete mode 100644 Tools/bgen/bgen/bgenOutput.py delete mode 100644 Tools/bgen/bgen/bgenStackBuffer.py delete mode 100644 Tools/bgen/bgen/bgenStringBuffer.py delete mode 100644 Tools/bgen/bgen/bgenType.py delete mode 100644 Tools/bgen/bgen/bgenVariable.py delete mode 100644 Tools/bgen/bgen/bgenlocations.py delete mode 100644 Tools/bgen/bgen/macsupport.py delete mode 100644 Tools/bgen/bgen/scantools.py delete mode 100644 Tools/freeze/README delete mode 100644 Tools/freeze/checkextensions.py delete mode 100644 Tools/freeze/findmodules.py delete mode 100755 Tools/freeze/freeze.py delete mode 100644 Tools/freeze/hello.py delete mode 100644 Tools/freeze/makeconfig.py delete mode 100644 Tools/freeze/makefreeze.py delete mode 100644 Tools/freeze/makemakefile.py delete mode 100755 Tools/freeze/nfreeze.py delete mode 100644 Tools/freeze/parsesetup.py delete mode 100644 Tools/modulator/EXAMPLE.py delete mode 100644 Tools/modulator/README delete mode 100644 Tools/modulator/ScrolledListbox.py delete mode 100644 Tools/modulator/Templates/copyright delete mode 100644 Tools/modulator/Templates/module_head delete mode 100644 Tools/modulator/Templates/module_method delete mode 100644 Tools/modulator/Templates/module_tail delete mode 100644 Tools/modulator/Templates/object_head delete mode 100644 Tools/modulator/Templates/object_method delete mode 100644 Tools/modulator/Templates/object_mlist delete mode 100644 Tools/modulator/Templates/object_new delete mode 100644 Tools/modulator/Templates/object_structure delete mode 100644 Tools/modulator/Templates/object_tail delete mode 100644 Tools/modulator/Templates/object_tp_as_mapping delete mode 100644 Tools/modulator/Templates/object_tp_as_number delete mode 100644 Tools/modulator/Templates/object_tp_as_sequence delete mode 100644 Tools/modulator/Templates/object_tp_call delete mode 100644 Tools/modulator/Templates/object_tp_compare delete mode 100644 Tools/modulator/Templates/object_tp_dealloc delete mode 100644 Tools/modulator/Templates/object_tp_getattr delete mode 100644 Tools/modulator/Templates/object_tp_hash delete mode 100644 Tools/modulator/Templates/object_tp_print delete mode 100644 Tools/modulator/Templates/object_tp_repr delete mode 100644 Tools/modulator/Templates/object_tp_setattr delete mode 100644 Tools/modulator/Templates/object_tp_str delete mode 100755 Tools/modulator/Tkextra.py delete mode 100755 Tools/modulator/genmodule.py delete mode 100755 Tools/modulator/modulator.py delete mode 100644 Tools/modulator/varsubst.py delete mode 100644 Tools/scripts/README delete mode 100755 Tools/scripts/byteyears.py delete mode 100755 Tools/scripts/checkpyc.py delete mode 100755 Tools/scripts/classfix.py delete mode 100755 Tools/scripts/copytime.py delete mode 100644 Tools/scripts/dutree.doc delete mode 100755 Tools/scripts/dutree.py delete mode 100755 Tools/scripts/eptags.py delete mode 100755 Tools/scripts/findlinksto.py delete mode 100755 Tools/scripts/fixcid.py delete mode 100755 Tools/scripts/fixheader.py delete mode 100755 Tools/scripts/fixps.py delete mode 100755 Tools/scripts/ftpmirror.py delete mode 100755 Tools/scripts/h2py.py delete mode 100755 Tools/scripts/ifdef.py delete mode 100755 Tools/scripts/linktree.py delete mode 100755 Tools/scripts/lll.py delete mode 100755 Tools/scripts/mailerdaemon.py delete mode 100755 Tools/scripts/methfix.py delete mode 100755 Tools/scripts/mkreal.py delete mode 100755 Tools/scripts/objgraph.py delete mode 100755 Tools/scripts/pathfix.py delete mode 100755 Tools/scripts/pdeps.py delete mode 100755 Tools/scripts/pindent.py delete mode 100755 Tools/scripts/ptags.py delete mode 100755 Tools/scripts/pystone.py delete mode 100755 Tools/scripts/suff.py delete mode 100755 Tools/scripts/sum5.py delete mode 100755 Tools/scripts/texi2html.py delete mode 100755 Tools/scripts/which.py delete mode 100755 Tools/scripts/xxci.py delete mode 100755 Tools/world/world delete mode 100644 acconfig.h delete mode 100644 config.h.in delete mode 100755 configure delete mode 100644 configure.in delete mode 100755 install-sh diff --git a/BUGS b/BUGS deleted file mode 100644 index 3bb18c0b82..0000000000 --- a/BUGS +++ /dev/null @@ -1,373 +0,0 @@ -THIS LIST DOES NOT CLAIM COMPLETENESS. - -==> Status indicators: (-) not fixed; (*) fixed; (?) not sure. - -====================================================================== - -Problems that are difficult to solve ------------------------------------- - -(-) "f()=0" generates syntax error msg without line number - -(-) tkinter seems to leave an exception around sometime which breaks -unmarshalling code objects [hard to reproduce, have added a trap to -marshal.c to catch it] - -(-) destroying all modules may destroy __builtin__ (or other modules) -while destructors of other modules may still need it [hard to fix -- -could maintain a list of all modules in order of importation so we can -destroy them in reverse order??? really hopeless -- would have to -destroy objects in a module in reverse order too...] - -(-) doneimport() should be called *before* the Py_AtExit code is -called [problem: what if other threads are still active?] - -Known portability problems --------------------------- - -(-) arraymodule doesn't compile under Ultrix (FPROTO macro) - -(-) makesetup assumes CCC is the C++ compiler -- not portable - -(-) "make depend" assumes mkdep exists -- not portable - -(-) regen calls h2py which isn't defined by default - -(-) HP doesn't compile out of the box (needs LIBS=-ldld or -LIBS=/usr/lib/libdld.sl) [hard to test without a HP machine handy] - -====================================================================== -BUGS present in 1.1.1 and fixed in 1.2 --------------------------------------- - -(*) extraneous fclose() in run_script() in pythonrun.c for .pyc file - -(*) __str__ is called if it exists (and then fails) when applying -str() to a class - -(*) mem leaks in inittime() in timemodule.c - -(*) mem leak in optimize() in compile.c - -(*) mem leak in func_dealloc() in funcobject.c - -(*) missing DECREF for result of run_string in exec_statement() in -ceval.c - -(*) missing INCREF in RAISE_EXCEPTION case after gettupleitem() in -ceval.c - -(*) posix.utime gives problems on problems on platforms where struct -utime members are bitfields - -(*) leak in regex module.c:reg_dealloc() -- should free compiled pattern - -(*) many uses of macros from fail with signed characters - -(*) compilation on NeXT requires manual editing of the Makefile - -(*) tkinter should cast malloc() result - -(*) marshal.c (w_object()) triggers GCC bug on DEC Alpha - -(*) int/long size bug in range() and xrange() on DEC Alpha - -(*) memory leaks in dbm and gdbm modules - -(*) refcnt bug in select.select([f], [f], [f]) - -(*) Should fflush(stdout) before printing traceback to stderr - -(*) Linux uses GNU getopt by default which is broken - -(*) make sharedinstall references to machdep directory but doesn't -create it - -(*) a file with unmatched triple quotes causes a loop in the scanner - -(*) [X]DECREF can cause the interpreter to be called recursively (for -__del__ disciplines) -- so list and dict implementation calls doing -DECREF can cause recursive calls to methods of the object being -modified. Other files too. - -(*) if __getattr__ or __repr__ prints something, calling repr(x) from -cmd line forgets a newline - -(*) C-level coerce() doesn't call __coerce__ when it should (and -similar for __cmp__) - -(*) struct module assigns unaligned doubles when compiled with -DDEBUG -on sparc - -(*) memory leak (namebuf) in initmodule2 - -(*) hash() of float values returns bogus values - -(*) pow(int, int, long) does wrong series of DECREF() calls. - -(*) flushline() may clear the exception condition so shouldn't be -called before print_error() - -(*) Everything else that uses err_get() should use err_fetch() - -(*) sockets aren't thread safe (address of static struct returned, -some calls aren't thread safe) - -(*) threadmodule.c leaks LOTS of memory at thread exit - -(*) shared install in Modules still doesn't work for empty list - -(*) threadmodule.c leaks 'res' in t_bootstrap - -(*) errors.c shouldn't declare strerror() on NT - -(*) DECREF can cause the interpreter to be called recursively (for -__del__ disciplines) -- so list and dict implementation calls doing -DECREF can cause recursive calls to methods of the object being -modified. Other files too. (Only partially fixed.) - -(*) tkinter dereferences NULL if timer callback raises an exception - -(*) must link with -lieee for linux - -(*) if a timer handler routine raises an exception, the interpreter -dereferences NULL - -(*) __getattr__ doesn't clear error - -(*) '%s' % a, where a is a class instance, fails - -(*) "make test" won't find freshly built dynamically loaded modules -- -should add ./Modules to TESTPATH - -(*) lshift calls __rshift__ instead of __rlshift__ - -(*) memory leak in creation of sys.builtin_module_names - -(*) Bugs in instance_dealloc(): (a) memory leak for exception -type+value; (2) should save+restore traceback as well - -(*) modsupport.c(vmkvalue): on systems where va_list is an array, the -calls to do_mkvalue and do_mktuple don't want an "&" before va. - -====================================================================== -BUGS found in 1.1 and fixed in 1.1.1 ------------------------------------- - -(*) printing name of lambda in traceback dereferences NULL - -(*) A built-in function using getargs() and expecting >= 1 argument -may dump core when called without arguments - -(*) newgetargs() dumps core in compat mode when NULL is passed in but -max is >0 - -(*) pow() should be declared varargs since it uses newgetargs - -(*) newmodule.c doesn't compile on SunOS 4.1.3 due to non-K&R backslashes - -(*) some typos in tut.tex - -(*) test for broken static forward is not strong enough - -(*) Doc/Makefile assumes . is in $PATH in call to whichlibs - -(*) math module misses hypot() function - -(*) structmember.h should include stddef.h (for offsetof macro) - -(*) gdbmmodule.c frees the wrong structures - -(*) makesetup script misses some dollars and backslashes - -(*) getargs.obj missing from NT makefile - -(*) sorting class instances broken if no __cmp__ defined - -====================================================================== -BUGS found in 1.0.3 and fixed in 1.1 ------------------------------------- - -(*) 2 specific leaks: 1 PYTHONPATH; 2 reading code from .pyc - -(*) If class C doesn't define __cmp__, cmp(a,b) will return -2 and -[a,b].sort() will fail - -(*) Syntax errors are reported in a silly way if multi-line tokens are -involved. - -(*) SyntaxError exception for compile('...') are reported wrongly -(lineno is always zero and offset is offset into the whole string). - -(*) freeze script needs major rewrite to cope with multiple extensions -(Jack seems to have fixed it now -- where is it?) - -(*) unwanted entries in stack trace if err_clear() clears an error -that also set a stack trace - -(*) i, x[i] = a, b assigns b to x[a] rather than to x[i] as expected -(documented with a warning in ref6.tex!) - -(*) etags no longer supports -t flag - -(*) compile.c:com_argdefs() references unalloc'ed memory for def -f(a=1,): ... - -(*) If you have a python binary in your path like -/ufs/guido/bin/sgi/python then the default prefix option computed by -the configure script is bogus! - -(*) Make rule for making lib*.a should remove the lib*.a file first. - -(*) vars() error message is wrong (copied from dir() obviously). - -(*) socket.gethostname() is undocumented. - -(*) rfc822.py: getfirst* dies when multiple headers occur - -(*) urllib caching is wrong (should use date from Expires header) - -(*) On a related matter: regexpr.c still has two malloc()s the results -of which are not tested for being NULL (lines 1253 and 1530). There -are also some in rgbimagemodule.c. Am I overlooking something or is -this a crasher? - -(*) strop.rindex('abc', '') returns 0 instead of 3 - -(*) sunaudiodevmodule.o is too long! - -(*) toplevel README needs new text on PC and Mac builds - -(*) long(0x80000000) has wrong value! - -====================================================================== -Bugs found in 1.0.2 and not yet fixed -------------------------------------- - -(?) compiler warnings about argument type of uname() on ULTRIX -machines (don't know what to do about it) [could be fixed by fix for -bitfields in struct uname] - -(?) syntax error for interactive input prints garbage instead of last -source line on some systems (e.g. AIX) (impossible to test/reproduce) -[I think I've found this one -- a missing INCREF in print_error] - -(?) (maybe) a bad .pyc file (with old magic number) causes the .py -file to be ignored [should be fixed by rewrite of import.c] - -(?) Sunos4.0.2 / 386 configure bugs: - - timelocal instead of mktime - - unistd.h doesn't declare some functions -(don't know what to do about this) - -Bugs found in 1.0.2 and fixed in 1.0.3 --------------------------------------- - -(*) nasty bug in string formatting (see test_types.py, search for %) - -(*) if a triple-quoted string ends in a quote followed by a newline -(followed immediately by the terminating 3 quotes) then a syntax error -or system error ensues - -(*) bug in socket.listen: clipping backlog to >= 1 doesn't work - -(*) two bogus XDEL's in Modules/regexmodule.reg_dealloc() - -(*) Parser/myreadline.my_fgets: #endif EINTR misplaced - -(*) new IP address for ftp.cwi.nl !!! - -(*) typing vars() to interactive prompt runs into infinite loop -because of '_' - -(*) tokenizer/tok_nextc() runs into infinite loop when file does not -end in linefeed - -(*) Sunos4.0.2 / 386 configure bugs: -(*) - use size_t at some places without including sys/types.h -(*) - missing clock_t -(*) - uses SEEK_SET in some places that don't include unistd.h - -====================================================================== -Bugs found in 1.0.1 and not yet fixed -------------------------------------- - -(?) threads are slow on Solaris 2 -(so what?) - -(*) threads cause myreadline.c's readline() to think it sees an EOF. -(I *think* I've fixed this, by testing for EINTR) - -(?) min() on PC version generates wrong result (i.e. same as max()) - [this happens on SoftPC -- don't know about other systems] -(can't find the reason -- may be SoftPC bug) - -(*) flp.py cache bug: if the cache only contains one form, asking for -all forms returns only the cached form - -Bugs found in 1.0.1 and fixed in 1.0.2 --------------------------------------- - -(*) core dump when parser.parsefile() called - -(*) man page contains a mess before -d option - -(*) threads don't work on IRIX 4 - -(*) wrong cast of svideo_getattr in svmodule.c - -(*) bad return value in runpython.c's run_tty_1() - -(*) creating dict of 100,000 objects gets MemoryError or dumps core - -(*) freeze script doesn't work - -====================================================================== -BUGS found in 1.0.0 and not yet fixed -------------------------------------- - -(*) On NeXT, need to define _POSIX_SOURCE. - -(?) there appears to be something wrong with gcc and -ldl on some -SunOS 4.1.3 systems - -(?) jredfords reports core dump with float literals - -BUGS found in 1.0.0 and fixed in 1.0.1 --------------------------------------- - -(*) On SGI IRIX 4 using cc, compilation errors in md5module.c. - -(*) In cdmodule.c, getattr initialized with (destructor)! - -(*) Lib/tzparse.py runs test() on import - -(*) Lib/filewin.py belongs in Lib/stdwin - -(*) lib and man install targets don't use $(srcdir) - -(*) Modules/rgbimgmodule.c: exception name contains comma instead of dot - -(*) The FAQ still references misc/EXTENDING and misc/DYNLOAD etc - -(*) The FAQ still describes how to work around a problem in 0.9.9 exec() - -(*) Lib/aifc.py, returns float rate, should be int - -(*) Lib/sunau.py, incorrectly cumputes byte count from frame rate - -(*) README should mention possibility of passing OPT=-g to make - -(*) dynamic loading on sunos 4.1.3 must call dlopen(..., 1) - -(*) use of vs. should depend on - HAVE_STDARG_PROTOTYPES, not on HAVE_STDARG_H - -(*) Doc/README refers to Misc/FTP which in fact does not exist any more - -(*) filter(None, 'abcdefg') dumps core - -(*) once you interrupt time.sleep(), there is no interrupt handler! - -====================================================================== -end of file diff --git a/ChangeLog b/ChangeLog deleted file mode 100644 index d3dd048df6..0000000000 --- a/ChangeLog +++ /dev/null @@ -1,4532 +0,0 @@ -Sat Oct 7 15:18:22 1995 Guido van Rossum - - * Modules/fcntlmodule.c: add BGN/END_SAVE macros around - fcntl/ioctl calls - -Sat Oct 7 15:14:01 1995 Guido van Rossum - - * Python/pythonrun.c: keep exitfunc alive while calling it - -Sat Oct 7 15:08:37 1995 Guido van Rossum - - * Lib/tkinter/Tkinter.py: better version sanity checks; get rid - of Widget.unbind_class() - -Fri Oct 6 11:31:30 1995 Guido van Rossum - - * Lib/formatter.py: added NullFormatter - -Fri Oct 6 11:30:57 1995 Guido van Rossum - - * Lib/htmllib.py: strip attribute values - -Fri Oct 6 11:30:28 1995 Guido van Rossum - - * Lib/sgmllib.py: typos in attrfind regex - -Fri Oct 6 11:26:52 1995 Guido van Rossum - - * Lib/htmlentitydefs.py: added lt, gt, amp back to entity - definitions - -Wed Oct 4 12:39:20 1995 Jack Jansen - - * Lib/base64.py: Use binascii module (resulting in a 60-fold - speedup:-) - -Wed Oct 4 12:38:44 1995 Jack Jansen - - * Modules/binasciimodule.c: Added base64 support - -Wed Oct 4 12:36:53 1995 Jack Jansen - - * Lib/uu.py: Fixed two minor errors. - -Tue Oct 3 10:41:15 1995 Jack Jansen - - * Lib/binhex.py: Fixed hexbin handling - -Tue Oct 3 10:40:35 1995 Jack Jansen - - * Mac/{Relnotes-1.3,ReadMeOrSuffer}: Clarified some things, - started adding mods since 1.3beta3 - -Tue Oct 3 10:39:44 1995 Jack Jansen - - * {Mac/macfs/macfsmodule.c, Modules/timemodule.c, - Python/{import.c,compile.c}}: Removed unused variables - -Sat Sep 30 13:05:26 1995 Guido van Rossum - - * Lib/tkinter/Tkinter.py: new after options; text.search; new - image methods - -Sat Sep 30 13:01:49 1995 Guido van Rossum - - * Modules/Makefile.pre.in: Move some stuff around so - customizations in Setup take precedence - -Sat Sep 30 13:01:02 1995 Guido van Rossum - - * Modules/newmodule.c: re-enable new.code(...) with new args - -Sat Sep 30 13:00:24 1995 Guido van Rossum - - * Modules/tkintermodule.c: clear quitMainLoop when we fall - through the main loop - -Sat Sep 30 12:51:50 1995 Guido van Rossum - - * Lib/ftplib.py: actualized example, catch EOFError, print - retrieved lines if debugging>2 - -Sat Sep 30 12:50:46 1995 Guido van Rossum - - * Lib/httplib.py: actualized example/reference, fix bug w/ - nonnumeric port - -Sat Sep 30 12:49:58 1995 Guido van Rossum - - * Lib/formatter.py: add flush_softspace() interface - -Sat Sep 30 12:49:36 1995 Guido van Rossum - - * Lib/sgmllib.py: allow _ in attr names (Netscape!) - -Sat Sep 30 12:48:54 1995 Guido van Rossum - - * Lib/{pstats.py,profile.py}: more robust coding, adapted for mac - -Sat Sep 30 12:10:43 1995 Guido van Rossum - - * Include/rename2.h: delete PyNothing_Check, which does not - actually exist - -Wed Sep 27 12:22:17 1995 Guido van Rossum - - * Lib/htmllib.py: entity definitions from HTML 2.0 std - -Sun Sep 24 17:08:22 1995 Jack Jansen - - * Mac/ReadMeOrSuffer: Added some clarifications and fixed host - names. - -Sun Sep 24 17:06:50 1995 Jack Jansen - - * Mac/scripts/MkPluginAliases.py: Load toolbox modules "by hand" - using imp, so this script should now work in a virgin - distribution. - -Sun Sep 24 17:05:24 1995 Jack Jansen - - * Mac/scripts/mkapplet.py: Changed the way .rsrc and template - are copied: hopefully this will finally get the bundle stuff - right. - -Fri Sep 22 19:49:28 1995 Guido van Rossum - - * Modules/tkintermodule.c: Mac changes - -Thu Sep 21 20:55:50 1995 Guido van Rossum - - * Lib/htmllib.py: added verbose option; added - ismap/align/width/height to handle_image args - -Thu Sep 21 20:54:32 1995 Guido van Rossum - - * Lib/sgmllib.py: fix parsing; added verbose option; - don't lowercase entityrefs - -Thu Sep 21 20:52:38 1995 Guido van Rossum - - * Lib/nntplib.py: actualized example; added xover, xgtitle, - xpath, date methods by Kevan Heydon - -Thu Sep 21 16:36:34 1995 Guido van Rossum - - * Parser/tokenizer.c: fix bogus resize length in nextc - -Wed Sep 20 16:31:51 1995 Guido van Rossum - - * Lib/traceback.py: add file parameter to all printing fns, - default stderr - -Mon Sep 18 18:00:37 1995 Guido van Rossum - - * Lib/irix5/panel.py: new exec syntax - -Mon Sep 18 17:54:35 1995 Guido van Rossum - - * Lib/tkinter/Tkinter.py: added getitem/setitem to Image class; - changed call wrapping (again) - -Mon Sep 18 17:52:37 1995 Guido van Rossum - - * Lib/cgi.py: handle missing QUERY_STRING - -Mon Sep 18 17:50:43 1995 Guido van Rossum - - * Lib/SimpleHTTPServer.py: recognize a few more file types - -Mon Sep 18 17:49:24 1995 Guido van Rossum - - * Lib/{quopri.py,base64.py}: improved test/main program - -Mon Sep 18 17:44:04 1995 Guido van Rossum - - * Python/compile.c: fix bug with missing default for last arg - (discovered by Tommy Burnette) - -Mon Sep 18 17:42:42 1995 Guido van Rossum - - * Python/pythonrun.c: #undef argument, for the Mac - -Mon Sep 18 17:40:19 1995 Guido van Rossum - - * Python/{getversion.c,getcopyright.c}: include Python.h - -Mon Sep 18 17:31:16 1995 Guido van Rossum - - * Python/errors.c: remove unwanted fatal() from err_badcall() - -Mon Sep 18 17:29:36 1995 Guido van Rossum - - * Python/{traceback.{c,h},ceval.c}: spell TraceBack with capital B - -Mon Sep 18 17:20:02 1995 Guido van Rossum - - * Include/abstract.h: use Py_PROTO macro - -Mon Sep 18 17:17:59 1995 Guido van Rossum - - * Objects/abstract.c: adapted to K&R C - -Mon Sep 18 06:49:04 1995 Sjoerd Mullender - - * Objects/classobject.c: Get ordering right for - TRACE_REFS/COUNT_ALLOCS combination (otherwise may get inc_count - sanity check abort). - -Wed Sep 13 14:39:47 1995 Guido van Rossum - - * Modules/socketmodule.c: plug some leaks - -Wed Sep 13 14:39:04 1995 Guido van Rossum - - * Modules/Setup.in: added SITEPATH and DESTPATH variables - -Wed Sep 13 13:39:51 1995 Guido van Rossum - - * Modules/posixmodule.c: added 5th return item, clock time, to - posix.times() - -Wed Sep 13 13:39:06 1995 Guido van Rossum - - * Modules/stropmodule.c: added strop.translate(s, table) - -Wed Sep 13 13:38:35 1995 Guido van Rossum - - * Modules/timemodule.c: added time.strftime() - -Thu Sep 7 15:37:11 1995 Guido van Rossum - - * Include/allobjects.h: removed redundant C++ hack - -Thu Sep 7 15:28:19 1995 Guido van Rossum - - * Lib/httplib.py: fixed the test program - -Thu Sep 7 15:22:00 1995 Guido van Rossum - - * Lib/tkinter/Tkinter.py: move constants to Tkconstants; added - some; overridable error reporting; fix typo in propagate - -Fri Sep 1 18:55:11 1995 Guido van Rossum - - * Lib/mac/dbmac.py: add (dummy) mode arg to open() - -Fri Sep 1 18:53:37 1995 Guido van Rossum - - * Lib/mac/socket.py: added read/writelines, bufsize to makefile, - gethostbyaddr - -Fri Sep 1 16:36:47 1995 Guido van Rossum - - * Lib/tkinter/FileDialog.py: Filter button should set - selection's directory, too - -Fri Sep 1 16:35:37 1995 Guido van Rossum - - * Lib/tkinter/Tkinter.py: added OptionMenu class (tk_optionMenu - interface) - -Fri Sep 1 16:34:29 1995 Guido van Rossum - - * Lib/sgmllib.py: support value-less attributes, using - regex.group() - -Fri Sep 1 16:33:32 1995 Guido van Rossum - - * Lib/htmllib.py: took out forms support (in favor a Grail - extension) - -Fri Sep 1 16:32:21 1995 Guido van Rossum - - * Lib/posixpath.py: rationalized os.path.split() so split "/a/" - yields "/a", "" - -Fri Sep 1 07:54:11 1995 Jack Jansen - - * Mac/scripts/mkapplet.py: Slightly reorganized so it is useable - from another program, and put all print statements in 'if - DEBUG'. - -Fri Sep 1 07:53:17 1995 Jack Jansen - - * Mac/scripts/binhextree.py: Fixed typo - -Fri Sep 1 07:50:53 1995 Jack Jansen - - * Mac/Resources/bundle.rsrc.hqx: Minor fix - -Fri Sep 1 07:49:10 1995 Jack Jansen - - * Mac/Relnotes-1.3: Updated 1.3 relnotes and added top-level - instructions - -Fri Sep 1 07:48:10 1995 Jack Jansen - - * Mac/macgetpath.c: Fixed to work on 68K (could be yet another - optimizer bug or something) - -Fri Sep 1 07:46:27 1995 Jack Jansen - - * Include/patchlevel.h: patchlevel set to 1.3b3 - -Thu Aug 31 09:59:36 1995 Jack Jansen - - * Mac/{pythonresources.h,macgetpath.c,macgetargv.c}: Python will - now attempt (again) to create at least a minimal preferences file - if it is missing. - -Thu Aug 31 09:58:28 1995 Jack Jansen - - * Mac/config.c: Added List module - -Thu Aug 31 09:57:40 1995 Jack Jansen - - * Mac/{macglue.c,macmain.c,mwerks/{mwfopenrf.c,malloc/malloc.c}}: - Removed unused variables - -Thu Aug 31 09:53:10 1995 Jack Jansen - - * Mac/Resources/dialogs.rsrc.hqx: Added version resource Added - dialogs for initial preference file creation - -Thu Aug 31 09:53:09 1995 Jack Jansen - - * Mac/Resources/bundle.rsrc.hqx: Added version resource Added - dialogs for initial preference file creation - -Thu Aug 31 09:51:58 1995 Jack Jansen - - * Mac/mwerks/mwfopenrf.c: removed unused var - -Thu Aug 31 09:51:13 1995 Jack Jansen - - * Mac/mwerks/malloc/malloc.c: Removed unused var - -Thu Aug 31 09:48:43 1995 Jack Jansen - - * Mac/scripts/mkapplet.py: - Allow PythonApplet to be an alias - - Correctly set bundle and init bits - -Thu Aug 31 09:47:14 1995 Jack Jansen - - * Mac/scripts/binhextree.py: Added functionality: locate CW - projects, copy them, empty them and binhex them. - -Thu Aug 31 09:46:13 1995 Jack Jansen - - * Mac/scripts/RunLibScript.py: - imp seems to always want a file - object arg - continue if resource file not found (may be an - applet) - -Thu Aug 31 09:44:23 1995 Jack Jansen - - * Modules/binasciimodule.c: Obscure bugfix - -Thu Aug 31 09:40:03 1995 Jack Jansen - - * Lib/mac/macostools.py: copy() can now create destination path - -Thu Aug 31 09:38:01 1995 Jack Jansen - - * Lib/mac/FrameWork.py: Fixed dialog-window event handling - -Wed Aug 30 19:44:41 1995 Guido van Rossum - - * Modules/Setup.in: fix typo in bsddb entry - -Wed Aug 30 08:19:30 1995 Jack Jansen - - * Lib/uu.py: Changed arguments and added a lot of functionality - besides - -Tue Aug 29 15:25:11 1995 Guido van Rossum - - * Lib/mimetools.py: forget previous change (content-encoding) - -Tue Aug 29 15:19:51 1995 Guido van Rossum - - * Lib/mimetools.py: encoding can be content-transfer-encoding or - content-encoding - -Tue Aug 29 15:19:12 1995 Guido van Rossum - - * Lib/urllib.py: support overriding how to open unknown url - types - -Tue Aug 29 15:18:24 1995 Guido van Rossum - - * Lib/CGIHTTPServer.py: changed some commas into percent signs - -Tue Aug 29 05:18:14 1995 Sjoerd Mullender - - * {Python/sysmodule.c,Objects/object.c}: Implemented two new - functions in sys: getcounts() returns a list of counts of - allocations and deallocations for all different object - types. getobjects(n [, type ]) returns a list of recently - allocated and not-yet-freed objects of the given type (all objects - if no type given). Only the n most recent (all if n==0) objects - are returned. getcounts is only available if compiled with - -DCOUNT_ALLOCS, getobjects is only available if compiled with - -DTRACE_REFS. Note that everything must be compiled with these - options! - -Mon Aug 28 05:00:43 1995 Sjoerd Mullender - - * Objects/classobject.c: Fixed calling of __del__ method with - TRACE_REFS defined. - -Sun Aug 27 22:59:06 1995 Guido van Rossum - - * Modules/Setup.in: dbhash -> bsddb - -Sun Aug 27 22:58:31 1995 Guido van Rossum - - * Modules/dbmmodule.c: fix bug in close() - -Sun Aug 27 22:58:00 1995 Guido van Rossum - - * Modules/gdbmmodule.c: fix leaks in keys(); fix bug in close() - -Sun Aug 27 22:56:20 1995 Guido van Rossum - - * Python/marshal.c: rd_object() with exception is fatal error - -Sun Aug 27 22:55:48 1995 Guido van Rossum - - * Python/errors.c: err_badcall() is fatal error - -Sun Aug 27 22:54:01 1995 Guido van Rossum - - * Lib/irix5/flp.py: exec() -> exec - -Sun Aug 27 22:53:41 1995 Guido van Rossum - - * Lib/irix5/regen: add errno.h - -Thu Aug 17 10:18:20 1995 Jack Jansen - - * Lib/mac/FrameWork.py: Made separate window class (and - subclasses for special windows like dialogs). This is an - incompatible change. - -Thu Aug 17 10:17:39 1995 Jack Jansen - - * Lib/binhex.py: Indent bug - -Tue Aug 15 07:33:39 1995 Sjoerd Mullender - - * Lib/urllib.py: Removed addbase.__del__ because it can't work. - If code keeps a reference to self.fp or any of its methods, you - don't want to close self.fp just because no explicit reference - is kept to self. - -Mon Aug 14 08:41:20 1995 Jack Jansen - - * Lib/binhex.py: Put debug output inside 'if DEBUG'. - -Mon Aug 14 08:39:54 1995 Jack Jansen - - * Lib/mac/FrameWork.py: Various fixes: missing imports, missing - calls to MacOS.HandleEvent. Also, prints are now inside 'if - DEBUG'. - -Mon Aug 14 08:36:37 1995 Jack Jansen - - * Mac/macglue.h: Added PyMac_PromptGetFile, removed stuff gone - to other sources. - -Mon Aug 14 08:35:10 1995 Jack Jansen - - * Mac/macglue.c: Lots of stuff moved to other files. Include - pythonresources.h. - -Mon Aug 14 08:33:48 1995 Jack Jansen - - * Mac/config.c: Lots of stuff removed: gone to various other - files. - -Mon Aug 14 08:33:20 1995 Jack Jansen - - * Mac/macmain.c: This is completely different from the old - mainmain (which wasn't used anymore) and is the new main program - for MacPython. Built from bits and pieces of config.c, macglue.c - and pythonmain.c. - -Mon Aug 14 08:30:15 1995 Jack Jansen - - * Mac/macgetcompiler.c: Merged Jack's macgetcompiler.c and - Guido's maccompiler.c and named the result macgetcompiler.c - (after all, *I* did the merging:-) - -Mon Aug 14 08:24:05 1995 Jack Jansen - - * Mac/Resources/dialogs.rsrc.hqx: Renumbered dialogs: 128-255 - are for interpreter use 256-511 are for extension modules, - libraries, etc 512 and above are for applications - -Mon Aug 14 08:22:56 1995 Jack Jansen - - * Mac/macfs/macfsmodule.c: Added new call PromptGetFile (like - StandardGetFile, but accepts a prompt) and added optional prompt - to GetDirectory. - -Mon Aug 14 08:21:50 1995 Jack Jansen - - * Mac/mwerks/mwfopenrf.c: Added missing initializer and extra - error check. - -Mon Aug 14 08:21:12 1995 Jack Jansen - - * Mac/scripts/*: Added prompts to various - file-select dialogs Renumbered resources to above 512 - -Mon Aug 14 08:20:22 1995 Jack Jansen - - * Mac/scripts/MkPluginAliases.{py,as}: Added List.slb alias - -Mon Aug 14 08:17:57 1995 Jack Jansen - - * Modules/binasciimodule.c: Added missing 'leftchar' - initializer. - -Mon Aug 14 08:17:18 1995 Jack Jansen - - * Modules/stdwinmodule.c: Shuffled include's around (name - conflict on Mac wrt teclick()) - -Mon Aug 14 03:49:51 1995 Sjoerd Mullender - - * Lib/sunau.py: Temporary fix for access statement. Definition - of Error was missing. - -Fri Aug 11 10:24:47 1995 Guido van Rossum - - * Lib/test/test_exceptions.py: exec() -> exec - -Fri Aug 11 10:24:35 1995 Guido van Rossum - - * Lib/test/test_b2.py: test for specific bug in vars() - -Fri Aug 11 10:21:06 1995 Guido van Rossum - - * Lib/tkinter/Tkinter.py: added select_present and select_range - to Entry widget - -Fri Aug 11 10:19:16 1995 Guido van Rossum - - * Lib/shelve.py: renamed DbShelf->DbfilenameShelf;added - BsdDbShelf (David Ely) - -Fri Aug 11 10:18:27 1995 Guido van Rossum - - * Lib/anydbm.py: change default flag to match dbm/gdbm - -Fri Aug 11 09:56:04 1995 Guido van Rossum - - * Lib/rexec.py: make sure the path ends in a slash in reload() - -Thu Aug 10 15:46:50 1995 Guido van Rossum - - * Lib/profile.py: exec() -> exec - -Thu Aug 10 15:45:41 1995 Guido van Rossum - - * Lib/urlparse.py: remove file: from list of protocols taking - host - -Thu Aug 10 15:44:54 1995 Guido van Rossum - - * Lib/urllib.py: changed version :-) - -Thu Aug 10 15:43:53 1995 Guido van Rossum - - * Lib/sgmllib.py: added note about missing features - -Thu Aug 10 15:43:04 1995 Guido van Rossum - - * Lib/tb.py: noted obsolescence; exec() -> exec - -Thu Aug 10 15:42:05 1995 Guido van Rossum - - * Lib/string.py: default tabsize to 8 - -Thu Aug 10 15:40:39 1995 Guido van Rossum - - * Lib/rexec.py: fix reload use of __filename__ - -Thu Aug 10 15:38:36 1995 Guido van Rossum - - * Lib/posixfile.py: fix stupid typo: r->RDLK - -Thu Aug 10 15:34:50 1995 Guido van Rossum - - * Lib/ntpath.py: same thing as for dospath, plus - HOMEDRIVE/HOMEPATH support - -Thu Aug 10 15:32:22 1995 Guido van Rossum - - * Lib/linecache.py: don't print Cannot open/stat messages - -Thu Aug 10 15:31:20 1995 Guido van Rossum - - * Lib/importall.py: exec() -> exec - -Thu Aug 10 15:27:42 1995 Guido van Rossum - - * Lib/dospath.py: redefined normcase() - -Thu Aug 10 15:26:37 1995 Guido van Rossum - - * Lib/base64.py: upgdaded the test program - -Thu Aug 10 15:24:30 1995 Guido van Rossum - - * Lib/anydbm.py: revamped somewhat - -Thu Aug 10 15:23:37 1995 Guido van Rossum - - * Lib/aifc.py: temporarily disabled the access statements - -Thu Aug 10 14:09:16 1995 Guido van Rossum - - * Lib/macpath.py: added normpath() and splitdrive() - -Thu Aug 10 14:00:03 1995 Guido van Rossum - - * Lib/fmt.py: added note about obsolescence - -Thu Aug 10 14:00:00 1995 Guido van Rossum - - * Lib/Para.py: added note about obsolescence - -Wed Aug 9 11:17:23 1995 Jack Jansen - - * Mac/config.c: re-enabled newmodule - -Tue Aug 8 22:33:38 1995 Guido van Rossum - - * Lib/audiodev.py: rather ugly temporary hacks to make it work - in grail & restricted mode - -Tue Aug 8 22:32:49 1995 Guido van Rossum - - * Lib/ihooks.py: fix bug in reload - -Tue Aug 8 22:32:08 1995 Guido van Rossum - - * Lib/rexec.py: add module binascii; add r_unload/s_unload; - don't change 'rb' to 'r' in open - -Tue Aug 8 22:31:00 1995 Guido van Rossum - - * Lib/htmllib.py: change blank line insertion at a few places - and fix recursion bug for - -Tue Aug 8 10:18:12 1995 Guido van Rossum - - * Modules/Makefile.pre.in: added MACHDEP back in - -Tue Aug 8 10:10:22 1995 Guido van Rossum - - * Mac/macmodule.c: add xstat (extended stat, returns resource - fork size and creator/type) - -Tue Aug 8 10:09:33 1995 Guido van Rossum - - * Mac/macstat.c: set some fields to zero for directories - -Mon Aug 7 16:19:27 1995 Guido van Rossum - - * Lib/rexec.py: added sys.std files, read-only open, reload - -Mon Aug 7 16:17:55 1995 Guido van Rossum - - * Lib/posixpath.py: add splitdrive() - -Mon Aug 7 16:17:23 1995 Guido van Rossum - - * Lib/popen2.py: pass the command to sh -c - -Mon Aug 7 16:16:58 1995 Guido van Rossum - - * Lib/pickle.py: correct typo (persis*ent) - -Mon Aug 7 16:16:05 1995 Guido van Rossum - - * Lib/pdb.py: use new "single" compile option - -Mon Aug 7 16:15:23 1995 Guido van Rossum - - * Lib/os.py: make sure os.environ exists (maybe empty) - -Mon Aug 7 16:13:56 1995 Guido van Rossum - - * Lib/mimetools.py: add seekable option to __init__ - -Mon Aug 7 16:13:02 1995 Guido van Rossum - - * Lib/httplib.py: use mimetools; add close() - -Mon Aug 7 16:12:09 1995 Guido van Rossum - - * Lib/cgi.py: added parse_qs(query_string) - -Mon Aug 7 16:07:44 1995 Guido van Rossum - - * Lib/htmllib.py: new formatter module; redid htmllib module to - use it - -Mon Aug 7 10:37:38 1995 Jack Jansen - - * Lib/uu.py: Use binascii module for inner loop - -Mon Aug 7 10:36:06 1995 Jack Jansen - - * Mac/macglue.c: Better error messages wrt missing resources and - preferences - -Mon Aug 7 10:35:24 1995 Jack Jansen - - * Mac/config.c: Added binascii - -Mon Aug 7 10:34:15 1995 Jack Jansen - - * Modules/Setup.in: Helper module for uuencode and binhex coders - -Mon Aug 7 10:09:27 1995 Jack Jansen - - * Lib/macpath.py: Added missing walk() function - -Mon Aug 7 10:04:10 1995 Jack Jansen - - * Mac/macfs/macfsmodule.c: Added interfaces to {Get,Set}FInfo - and accompanying objects - -Mon Aug 7 10:03:14 1995 Jack Jansen - - * Mac/config.h: Mwerks now also has fopenrf - -Mon Aug 7 10:01:46 1995 Jack Jansen - - * Mac/mwerks/mwerks_nonshared_config.h: Fix for cfm68k - -Fri Aug 4 00:39:30 1995 Guido van Rossum - - * Lib/ftplib.py: new sendport() interface; add test() program - call - -Fri Aug 4 00:30:30 1995 Guido van Rossum - - * Lib/traceback.py: added format_* functions (suggestion by Ken - M) - -Fri Aug 4 00:29:32 1995 Guido van Rossum - - * Lib/urlparse.py: subtle changes to relative url joins - -Fri Aug 4 00:29:05 1995 Guido van Rossum - - * Lib/urllib.py: use mimetools; add error handling and - authentication - -Fri Aug 4 00:23:30 1995 Guido van Rossum - - * Lib/htmllib.py: major rewrite using different formatting - paradigm - -Fri Aug 4 00:22:39 1995 Guido van Rossum - - * Lib/sgmllib.py: changed comment parsing - -Fri Aug 4 00:20:45 1995 Guido van Rossum - - * Modules/{config.c.in,Setup.in,Makefile.pre.in}: split config.c - in 1000 parts; new main; new unfinished objective-C module - -Fri Aug 4 00:14:47 1995 Guido van Rossum - - * Python/ceval.c: empty kw dict is ok for builtins - -Fri Aug 4 00:13:00 1995 Guido van Rossum - - * Python/Makefile.in: split config.c in 1000 little files :-) - -Fri Aug 4 00:10:43 1995 Guido van Rossum - - * Python/frozenmain.c: moved stuff around to resemble main.c - -Fri Aug 4 00:08:57 1995 Guido van Rossum - - * Python/import.c: add imp.get_frozen_object() - -Fri Aug 4 00:07:45 1995 Guido van Rossum - - * Python/bltinmodule.c: avoid resize of 0-length tuple - -Fri Aug 4 00:05:31 1995 Guido van Rossum - - * Objects/classobject.c: class objects are read-only in - restricted mode - -Fri Aug 4 00:05:10 1995 Guido van Rossum - - * Objects/tupleobject.c: better err checks in resizetuple - -Thu Aug 3 23:59:03 1995 Guido van Rossum - - * Lib/rexec.py: new package support, import hooks, restricted - execution support - -Thu Aug 3 23:51:48 1995 Guido van Rossum - - * Lib/tkinter/Tkinter.py: added some missing constants - -Thu Aug 3 23:50:29 1995 Guido van Rossum - - * Lib/tkinter/Tkinter.py: keyword arguments; redid Photo image - class; other goodies - -Thu Aug 3 23:49:39 1995 Guido van Rossum - - * Lib/tkinter/Dialog.py: keyword parameter changes - -Sat Jul 29 09:55:06 1995 Jack Jansen - - * Python/pythonrun.c: mac CW-only fix for messy windows upon - exit - -Sat Jul 29 09:52:37 1995 Jack Jansen - - * Mac/macglue.c: Added code so you canset "command line options" - if you option-click/drag python. Needs a new dialog resource. - -Sat Jul 29 09:50:59 1995 Jack Jansen - - * Mac/macgetargv.c: Un-installing of AE handlers fixed (AE is - very picky that you specify the same UPP) - -Fri Jul 28 19:06:00 1995 Guido van Rossum - - * Python/ceval.c: fix bogus DECREF in finally clause - -Fri Jul 28 12:44:53 1995 Guido van Rossum - - * Modules/newmodule.c: \temporary 'fix' for brokenness - -Fri Jul 28 07:44:29 1995 Jack Jansen - - * Mac/chdir.c: Made more ppc-savvy - -Fri Jul 28 07:29:54 1995 Jack Jansen - - * Mac/config.c: - Added getplatform() - (temporarily?) removed - newmodule reference - -Fri Jul 28 07:28:14 1995 Jack Jansen - - * Python/import.c: Undef 'argument' before including mac headers - -Wed Jul 26 14:16:42 1995 Guido van Rossum - - * Python/ceval.c: changes for keyword args to built-in functions - and classes - -Wed Jul 26 14:13:27 1995 Guido van Rossum - - * Python/import.c: never close the file in imp.load_... - -Wed Jul 26 14:07:32 1995 Guido van Rossum - - * Objects/methodobject.c: changes for keyword args to built-in - functions and classes - -Wed Jul 26 14:07:26 1995 Guido van Rossum - - * Objects/classobject.c: changes for keyword args to built-in - functions and classes - -Wed Jul 26 13:58:29 1995 Guido van Rossum - - * Include/rename2.h: changes for keyword args to built-in - functions and classes - -Wed Jul 26 13:58:27 1995 Guido van Rossum - - * Include/methodobject.h: changes for keyword args to built-in - functions and classes - -Wed Jul 26 13:58:23 1995 Guido van Rossum - - * Include/classobject.h: changes for keyword args to built-in - functions and classes - -Wed Jul 26 13:53:29 1995 Guido van Rossum - - * Include/object.h: add forgotten PyObject_SetAttrString - -Wed Jul 26 13:33:44 1995 Guido van Rossum - - * Modules/dbhashmodule.c: add locking where it exists - -Wed Jul 26 13:33:10 1995 Guido van Rossum - - * Modules/md5module.c: use newgetargs - -Wed Jul 26 13:31:41 1995 Guido van Rossum - - * Modules/Setup.in: improved comments for curses, dbhash - -Wed Jul 26 13:29:45 1995 Guido van Rossum - - * Modules/tkintermodule.c: use getnewargs where it makes sense - -Wed Jul 26 12:26:31 1995 Guido van Rossum - - * Python/bltinmodule.c: be more suspicious of getlocals() - -Wed Jul 26 12:14:30 1995 Guido van Rossum - - * Objects/frameobject.c: better policy regarding NULL locals - -Wed Jul 19 07:21:47 1995 Sjoerd Mullender - - * Lib/py_compile.py: Get magic number from interpreter (using - module imp). - -Wed Jul 19 07:21:21 1995 Sjoerd Mullender - - * Lib/StringIO.py: Added flush() method. - -Tue Jul 18 14:33:09 1995 Guido van Rossum - - * Modules/dbhashmodule.c: fixed arg checking for keys() and - close() - -Tue Jul 18 14:18:11 1995 Guido van Rossum - - * Modules/Setup.in: added dbhash; Tk is now officially at 4.0 - -Tue Jul 18 14:16:52 1995 Guido van Rossum - - * Modules/posixmodule.c: suppress . and .. in listdir return - value - -Tue Jul 18 10:51:37 1995 Guido van Rossum - - * Python/*.c: keyword arguments and faster calls - -Tue Jul 18 10:40:09 1995 Guido van Rossum - - * Python/importdl.c: NT specific change for nicer error message - (Mark H) - -Tue Jul 18 10:30:34 1995 Guido van Rossum - - * Objects/{Makefile.in,funcobject.c,frameobject.c,abstract.c}: - changes for keyword arguments and fast function call; added - abstract.c - -Tue Jul 18 10:21:06 1995 Guido van Rossum - - * Include/*.h: keyword arguments and faster function - calls - -Tue Jul 18 10:07:52 1995 Guido van Rossum - - * Include/allobjects.h: include abstract.h - -Mon Jul 17 09:25:15 1995 Jack Jansen - - * Lib/mac/FrameWork.py: Various toolbox routines have gotten new - names. - -Mon Jul 17 09:25:14 1995 Jack Jansen - - * Lib/mac/EasyDialogs.py: Various toolbox routines have gotten - new names. - -Mon Jul 17 07:36:01 1995 Jack Jansen - - * Mac/macosmodule.c: Added GetErrorString method (convert OSErr - number to string) - -Fri Jul 14 11:29:10 1995 Guido van Rossum - - * Lib/tkinter/{Tkinter.py,Dialog.py}: Tk 4.0 and Tcl 7.4 are now - standard - -Tue Jul 11 22:22:06 1995 Guido van Rossum - - * Objects/classobject.c: args to call_object must be tuple or - NULL - -Tue Jul 11 22:22:01 1995 Guido van Rossum - - * Objects/listobject.c: args to call_object must be tuple or - NULL - -Tue Jul 11 22:21:58 1995 Guido van Rossum - - * Objects/object.c: args to call_object must be tuple or NULL - -Mon Jul 10 19:32:26 1995 Guido van Rossum - - * Objects/fileobject.c: fix read(0), readline(0); make tuple for - call_object args - -Mon Jul 10 09:52:21 1995 Guido van Rossum - - * Python/bltinmodule.c: rename arglist to alist (conflict with - new grammar symbol) - -Fri Jul 7 18:53:21 1995 Guido van Rossum - - * Python/compile.c: 3rd arg for raise; INCOMPLETE keyword - parameter passing (currently f(kw=value) is seen as f('kw', - value)) - -Fri Jul 7 18:53:14 1995 Guido van Rossum - - * Python/ceval.c: 3rd arg for raise; INCOMPLETE keyword - parameter passing (currently f(kw=value) is seen as f('kw', - value)) - -Fri Jul 7 18:50:36 1995 Guido van Rossum - - * Python/import.c: new MAGIC; some changes to default files for - imp.load_... functions - -Fri Jul 7 18:45:41 1995 Guido van Rossum - - * Python/traceback.c: ignore control-l (parallelling change to - tokenizer.c) - -Fri Jul 7 18:45:02 1995 Guido van Rossum - - * Python/sysmodule.c: added sys.platform - -Fri Jul 7 18:44:10 1995 Guido van Rossum - - * Python/graminit.c: new grammar - -Fri Jul 7 18:43:42 1995 Guido van Rossum - - * Python/bltinmodule.c: added locals() and globals(); - [raw_]input() uses readline() - -Fri Jul 7 18:39:14 1995 Guido van Rossum - - * Modules/cgen.py: err() should be varargs -- and fix one call - -Fri Jul 7 18:38:14 1995 Guido van Rossum - - * Modules/config.c.in: added getpalatform() - -Fri Jul 7 18:37:11 1995 Guido van Rossum - - * Modules/gdbmmodule.c: normalized flag arg and made flag, mode - default args; minor cosmetics - -Fri Jul 7 18:37:09 1995 Guido van Rossum - - * Modules/dbmmodule.c: normalized flag arg and made flag, mode - default args; minor cosmetics - -Fri Jul 7 18:35:21 1995 Guido van Rossum - - * Modules/Makefile.pre.in: pass $PLATFORM into config.c - -Fri Jul 7 18:32:10 1995 Guido van Rossum - - * Include/opcode.h: new opcodes RAISE_VARARGS, CALL_FUNCTION - -Fri Jul 7 18:31:40 1995 Guido van Rossum - - * Include/graminit.h: new grammar symbols arglist and argument - -Fri Jul 7 18:27:27 1995 Guido van Rossum - - * Parser/tokenizer.c: ignore control-l in whitespace - -Fri Jul 7 18:26:23 1995 Guido van Rossum - - * Grammar/Grammar: new grammar for 3rd raise arg and keyword - parameters - -Tue Jun 27 09:17:54 1995 Jack Jansen - - * Mac/*: Initial port to CodeWarrior CFM68K support - (mainly by disabling unsupported features). - -Tue Jun 27 09:15:14 1995 Jack Jansen - - * Python/{importdl.c,errors.c}: Porting to CW CFM68K - -Tue Jun 27 09:12:09 1995 Jack Jansen - - * Include/{mymath.h,mymalloc.h,allobjects.h}: Changed ifdef - __CFM68K__ to ifdef SYMANTEC__CFM68K__: CW has its own unique set - of ideosyncracies:-( - -Thu Jun 22 15:06:57 1995 Guido van Rossum - - * Lib/rfc822.py: added seekable option; save unix from lines; - speed up islast() - -Thu Jun 22 15:00:13 1995 Guido van Rossum - - * Lib/urllib.py: add User-agent hdr; read and close the file - upon http error - -Thu Jun 22 14:58:00 1995 Guido van Rossum - - * Lib/string.py: make split and splitfields, join and joinfields - synonyms - -Thu Jun 22 14:56:36 1995 Guido van Rossum - - * Lib/sgmllib.py: make reporting unbalanced tags an overridable - method - -Thu Jun 22 14:55:10 1995 Guido van Rossum - - * Lib/rexec.py: use imp.new_module(), not new.module(); and - /usr/local - -Thu Jun 22 14:52:35 1995 Guido van Rossum - - * Lib/profile.py: functions don't have a __name__ attribute - -Thu Jun 22 14:51:23 1995 Guido van Rossum - - * Lib/pickle.py: test other name variable - -Thu Jun 22 14:48:48 1995 Guido van Rossum - - * Lib/httplib.py: discard endrequest(); minor stuff; rfc822 no - seek flag - -Thu Jun 22 14:46:12 1995 Guido van Rossum - - * Lib/htmllib.py: support , remove
- -Thu Jun 22 14:45:04 1995 Guido van Rossum - - * Lib/StringIO.py: set softspace to 0 in __init__ - -Tue Jun 20 13:21:42 1995 Guido van Rossum - - * Lib/ftplib.py: add bind(0,''); better way of guessing our - fully qualified hostname - -Sun Jun 18 16:06:44 1995 Jack Jansen - - * Python/import.c: Added PY_RESOURCE (mac only) to imp module - -Sun Jun 18 16:05:14 1995 Jack Jansen - - * Mac/macfs/macfsmodule.c: Added FindFolder interface - -Sun Jun 18 16:03:40 1995 Jack Jansen - - * Mac/macglue.c: Added code to obtain sys.path from a resource - Removed code to update the preferences file, use - EditPythonPrefs.py in stead (actually, code is still there if - you define USE_MAC_MODPREFS) - -Sun Jun 18 15:57:01 1995 Jack Jansen - - * Mac/config.c: Obtain path from a resource (unless - USE_BUILTIN_PATH is #defined) - -Fri Jun 16 06:57:14 1995 Jack Jansen - - * Lib/rfc822.py: Removed >From stuff - -Wed Jun 14 18:54:23 1995 Guido van Rossum - - * Modules/posixmodule.c: sys/wait.h; NeXT changes (no unistd, - utime; getcwd?) - -Wed Jun 14 18:52:06 1995 Guido van Rossum - - * Modules/makesetup: fix NL for Linux bash bug; special - processing for -u options - -Wed Jun 14 18:49:20 1995 Guido van Rossum - - * Modules/soundex.c: edited RCS cruft - -Wed Jun 14 18:31:38 1995 Guido van Rossum - - * Modules/Setup.in: new modules soundex.c and environment.c - -Wed Jun 14 18:28:08 1995 Guido van Rossum - - * Modules/socketmodule.c: add setblocking(); NT changes; - null-terminate Unix path - -Wed Jun 14 18:23:17 1995 Guido van Rossum - - * Modules/timingmodule.c: removed rcs cruft - -Wed Jun 14 18:17:37 1995 Guido van Rossum - - * Modules/mathmodule.c: NeXT doesn't like me to declare - hypot(double, double) - -Wed Jun 14 18:07:26 1995 Guido van Rossum - - * Python/importdl.c: re-enabled NeXT dynamic linking (#ifdef - NeXT) - -Wed Jun 14 14:26:02 1995 Guido van Rossum - - * Parser/tokenizer.c: replace "\r\n" with "\n" at line end (Jim - Ahlstrom) - -Wed Jun 14 10:54:25 1995 Jack Jansen - - * Python/importdl.c: Mac dynloading is now enabled by - USE_MAC_DYNAMIC_LOADING. Mac dynloading changed to allow - multiple modules to live in with each other in the same file. - -Wed Jun 14 10:47:21 1995 Jack Jansen - - * Mac/config.c: Added USE_* ifdefs for a couple of optional - modules. - -Wed Jun 14 10:44:17 1995 Jack Jansen - - * Mac/macshlglue.c: Ported to CW6 - -Wed Jun 14 10:43:41 1995 Jack Jansen - - * Mac/mwerks/mwerks_{,no}shared_config.h: Split shared-library - support and dynamic-loading support (they were both enabled with - USE_SHARED_LIBRARY, now there's also USE_MAC_DYNAMIC_LOADING). - Added a few other USE_ defines for optional modules to nonshared - config (they're not included in the base shared library) - -Tue Jun 13 07:19:48 1995 Jack Jansen - - * Lib/rfc822.py: Skip old-style 'From name time' lines at - beginning of message. - -Mon Jun 12 11:51:34 1995 Sjoerd Mullender - - * Python/importdl.{h,c}: Check if we've already loaded a dynamic - module under a different name. - -Mon Jun 12 11:51:29 1995 Sjoerd Mullender - - * Python/import.c: Check if we've already loaded a dynamic - module under a different name. - -Fri Jun 9 16:39:24 1995 Jack Jansen - - * Mac/{mactcp/macdnrmodule.c,macstat.h,macmodule.c}: Ported to - CodeWarrior 6 - -Sat Jun 3 17:16:40 1995 Jack Jansen - - * Mac/config.c: Added img stuff (within #ifdef, so they're easy - to remove) - -Sat Jun 3 17:15:50 1995 Jack Jansen - - * Mac/macfs/macfsmodule.c: StandardGetFile without args now - shows all files (in stead of none) - -Wed May 17 07:18:20 1995 Sjoerd Mullender - - * Lib/irix5/CL.py: Backward compatibity module for constants - from cl.h include file. The values are gotten from the cl - module. CL_old is there in case cl doesn't exist. - -Wed May 17 07:16:52 1995 Sjoerd Mullender - - * Modules/clmodule.c: Make constants from cl.h include file - available as module variables. Also added Irix 5.3 constants. - -Fri May 5 11:54:14 1995 Guido van Rossum - - * Lib/ftplib.py: don't show print passwords in debug output - -Thu May 4 11:02:18 1995 Jack Jansen - - * Lib/ftplib.py: For anonymous ftp, make sure local hostname is - fully qualified. - -Wed May 3 13:40:23 1995 Guido van Rossum - - * Modules/stropmodule.c: unified join(fields), split(fields) - -Fri Apr 28 17:28:02 1995 Guido van Rossum - - * Include/rename2.h: removed duplicate defs for None, False, - True - -Tue Apr 25 07:53:24 1995 Sjoerd Mullender - - * Include/{object.h,tupleobject.h}: DL_IMPORT needs an argument. - -Mon Apr 24 08:41:41 1995 Jack Jansen - - * Mac/macglue.c: - The prefs file wasn't updated correctly if it - already existed. - Guido's r1.23 fix wrt PyMac_DoYieldEnabled - had somehow gotten lost. - -Sun Apr 23 18:12:47 1995 Jack Jansen - - * Objects/fileobject.c: MW does not always set errno on failing - fopen() - -Sun Apr 23 18:10:18 1995 Jack Jansen - - * Lib/mac/dbmac.py: Removed seeks beyond eof (MW doesn't support - them) - -Sun Apr 23 18:06:57 1995 Jack Jansen - - * Lib/py_compile.py: Mac-specific code for setting filetype was - outdated. - -Sun Apr 23 18:06:05 1995 Jack Jansen - - * Include/{object.h,tupleobject.h}: DL_IMPORT macro was called in - a funny way (and MW barfed on it) - -================================= -==> Release 1.2 (10 Apr 1995) <== -================================= - -Thu Apr 6 16:34:28 1995 Guido van Rossum - - * Objects/classobject.c (instancemethod_compare): change the way - instance methods are compared -- don't apply cmpobject() to - im_self but do a simple pointer compare - - * Objects/object.c: move counting of free'd objects (#ifdef - COUNT_ALLOCS) from DELREF() to UNREF() - - * Include/object.h (_Py_ForgetReference()): add counting of free'd - objects (#ifdef COUNT_ALLOCS) - -Tue Apr 4 13:53:47 1995 Guido van Rossum - - * Objects/frameobject.c (newframeobject): changed dictlookup() - with constant C string arg to mappinglookup() with static Python - string (Sjoerd) - -Fri Mar 31 12:26:03 1995 Guido van Rossum - - * irix5/tmp/lib/python/lib/frozenmain.c: carried through renaming - phase 3 - -Thu Mar 30 11:44:23 1995 Guido van Rossum - - * README: added warning about bash bug in certain Slackware Linux - version - - * Doc/lib*.tex: reorganized into more subject-related chapters; - rewritten abstract and introduction - - * Doc/myformat.sty: define \dfn{} as \em instead of \sl - - * Modules/config.c.in: moved decl of realmain() out of #ifdef - - * Python/pythonrun.c (print_error): added fflush(stdout) to - print_error() so output doesn't get mangled when stdout and stderr - are redirected to the same file - - * Modules/selectmodule.c: fix subtle refcnt bugs with fd2obj - arrays (R Lindsay Todd) - - * Include/object.h, Object/{tupleobject.c,stringobject.c}, - Python/ceval.c: fix ref-count debugging (R Lindsay Todd) - - * Python/sysmodule.c (sys_checkinterval): initialize to 10 as - before (major speed up!) - - * Modules/cdmodule.c: use newgetargs; removed sbtoa() and - timetoa(); added msftoframe(); added constants that used to be in - standard module CD (Sjoerd) - - * Modules/posixmodule.c: added WNOHANG constant - -Fri Mar 24 14:55:48 1995 Guido van Rossum - - * Lib/nntplib.py: rename debug() to set_debuglevel() as for - ftplib.py - -Thu Mar 23 11:10:24 1995 Guido van Rossum - - * Lib/posixfile.py (open): make mode default to 'r' and add - optional bufsize - -======================================== -==> Release 1.2 BETA 4 (21 Mar 1995) <== -======================================== - -Tue Mar 21 13:28:32 1995 Guido van Rossum - - * Python/ceval.c (call_object): removed #ifdef'ed out code - -Mon Mar 20 17:14:14 1995 Guido van Rossum - - * Lib/copy.py (_copy_dispatch): fix typo in hasattr() exprs - -Sat Mar 18 00:04:14 1995 Guido van Rossum - - * Makefile.in: change -f Makefile.in to -f $(srcdir)/Makefile.in - -Fri Mar 17 10:52:07 1995 Guido van Rossum - - * Lib/tkinter/Tkinter.py: add TkVersion and TclVersion variables; - handle crash in callback different (don't drop into debugger); add - _getdoubles() and streamline _getints() - - * Doc/lib*.tex: mass update - - * Doc/partparse.py: fix several small things so it doesn't crash - so easily - - * Modules/threadmodule.c: change exit_thread so it raises - SystemExit -- this allow proper cleanup in t_bootstrap - - * Makefile.in (distclean): add -f Makefile.in (John Interrante) - -Thu Mar 16 13:35:25 1995 Guido van Rossum - - * Doc/ref*.tex: made palatable to latex2html -- basically rewrote - all math using \code{} and \var{} (and pow() and some integer - literals), and added braces to some \item[]s containing \tt - - * Modules/socketmodule.c: fixed up comments describing interface - - * Lib/test/test_signal.py: new module to test signal module - -Wed Mar 15 11:07:43 1995 Guido van Rossum - - * Modules/signalmodule.c (PySignal_Signal): use PyCallable_Check - where suitable; split some lines - - * Lib/posixfile.py (open) defaults mode='r', bufsize=-1 - -Tue Mar 14 10:42:39 1995 Guido van Rossum - - * Lib/copy.py: rename copy.Error to copy.error - - * Lib/cgi.py: correct some typos that broke escape() and print_form() - - * Lib/string.py: add (unsupported) optional base argument to - atoi() and atol(); be more careful about very negative start - indices in [r]find() and count() - - * Modules/timemodule.c: tiny additions for Windows 3.1 - - * Modules/gdbmmodule.c: plugged some memory leaks (Steve Clift) - - * Modules/socketmodule.c (makefile): made mode optional and added - optional buffer size, like built-in open() - -Mon Mar 13 11:26:20 1995 Guido van Rossum - - * Lib/pickle.py: added ability to pickle classes (could be used - for exceptions in RPC); made format_version non-hidden variable, - added compatible_formats variable, added shorthand functions - dump(), load(), dumps() and loads() -- similar to marshal - - * Python/pythonrun.c (fatal): In NT, write msg to debugging device - - * Doc/lib*.tex: small changes by Soren Larsen - -Thu Mar 9 15:06:02 1995 Guido van Rossum - - * Lib/pickle.py: added explicit exception for unpicklable object - type: PicklingError; raise EOFError when end of file read - - * Lib/profile.py: runcall(): return the function's return value - - * Lib/rexec.py: support calling __import__ with 4 args - - * Lib/shelve.py: fix typo in close() (self.db should be self.dict) - - * Python/{ceval.c,marshal.c}: optimized many calls to get/set - tuple items - - * Include/{tupleobject.h,rename2.h}: added SETTUPLEITEM macro and - added cast to GETTUPLEITEM - - * Objects/{stringobject.c,mappingobject.c}: a few peephole - optimizations - - * configure(.in): added test for CC value not matching cache - - * Modules/tkintermodule.c: add casts to malloc() calls in - tkintermodule.c - - * Moved Demo/bgen, Demo/freeze, Demo/modulator and most of - Demo/script to new Tools/ directory - - * Doc/ext.tex: revised for new naming; added new section on - reference counting - - * Doc/lib*.tex: revised much of the library documentation - - * Doc/ref*.tex: corrected typos and other small errors in the - reference manual - - * Doc/tut.tex: corrected typos and small errors, and added a - chapter on new features in release 1.2 - - * Extensions/X11: MANY (incompatible) changes by Sjoerd - - * Most header files, Include/allobjects.h: changed the way - DL_IMPORT is used -- it now has the object's type as a parameter - (this is done for Borland C) - - * Many places: small changes for MPW and CFM-68K on the Mac - - * Include/mymath.h: new header to be used instead of - - * Include/pythonrun.h: added decl for Py_FatalError() - - * Include/rename2.h: added PyImport_ExecCodeModule - - * Lib/cgi.py: general cleanup; translate & to "&" - - * Lib/{compileall.py,tb.py,traceback.py}: don't break on class - exceptions - - * Lib/types.py: added DictType as alias for DictionaryType - - * Lib/cddb.py: write track artist info if given - - * Lib/{pdb.py,wdb.py,stdwin/wdbframewin.py}: don't break on class - exceptions; added runeval(), generalized run to allow optional - context; deprecate runctx() - - * Lib/test/{test_b1.py,test_grammar.py}: cope with 'math' not - existing; don't fail if overflow check doesn't work - - * Mac/*: too many changes to log; we now support about 5 compilers - (Think C, MPW, MPW with Symantec C, CodeWarrior 68K, CodeWarrior - PPC) - - * Misc/python-mode.el: cope with triple-quoted strings (sez Barry) - - * Modules/Makefile.pre.in: don't exit Make if 'sharedmods' for - loop fails - - * Modules/Setup.in: move posix, signal, thread and gl permanently - ahead of #*noconfig*, to avoid confusion - -Mon Feb 20 13:48:50 1995 Guido van Rossum - - * Objects/stringobject.c (formatstring): allow string without - formats and dictionary argument - -Fri Feb 17 12:00:29 1995 Guido van Rossum - - * Python/bltinmodule.c (do_pow): fixed bogus test for negative - number to the float power - - * Python/ceval.c (eval_code): fix SystemError in try-finally when - a class exception was raised - - * Demo/stdwin/python.py, Lib/stdwin/wdbframewin.py, Lib/pdb.py, - Lib/tb.py, Lib/traceback.py: cope with class exceptions when - printing or formatting them (R Lindsay Todd) - -Thu Feb 16 11:21:45 1995 Guido van Rossum - - * Doc/libshelve.tex: added/reorganized list of restrictions - - * Doc/libsocket.tex: added quick list of new exported symbols - - * Demo/sockets/{mcast.py,broadcast.py}: don't use modules SOCKET - or IN -- all symbols are now exported by the socket module itself - - * Modules/socketmodule.c (initsocket): added INADDR_* symbols - - * Include/object.h: added missing decls for PyObject_IsTrue() and - PyCallable_Check() - -Wed Feb 15 14:43:24 1995 Guido van Rossum - - * Python/compile.c (com_addopname): use = instead of == for - assignment - - * Modules/config.c.in (COMPILER): removed bogus ## in front of - __VERSION__ - - * Doc/{lib.tex,libpickle.tex,libcopy.tex,libshelve.tex}: - documented some new modules (cheaply -- by slightly reformatting - their __doc__ strings) - - * Lib/builtin.py: got rid of it - - * Doc/tut.tex: added sections on new stuff in release 1.2 - - * Doc/libsignal.tex: added a lot more details about how this - works. - -Tue Feb 14 13:57:28 1995 Guido van Rossum - - * Python/marshal.c (w_object): change long i, n to int -- should - solve GCC problems on DEC Alpha (Paul Sijben) - - * Python/{ceval.c,bltinmodule.c}: call __import__ with 4 - arguments: modulename, globals, locals, list_of_from_names_or_None - (for Ken Manheimer) - - * Python/ceval.c (eval_code): call locals_2_fast before doing - import from (Jim Roskind) - -======================================== -==> Release 1.2 BETA 3 (13 Feb 1995) <== -======================================== - -Mon Feb 13 12:39:16 1995 Guido van Rossum - - * README: removed remark on NeXT and -posix since this is now done - by configure - - * Mac/config.c, Modules/config.c.in (getversion): tack compiler - name and version (where known) onto version string - - * Objects/floatobject.c: work-around for NeXT Sparc 3.3 prerelease - (Barry Warsaw) - -Fri Feb 10 17:08:35 1995 Guido van Rossum - - * Objects/object.c (newvarobject), Include/objimpl.h: make size - argument signed - - * Include/allobjects.h, several other files: introduce - Py_CHARMASK(c) which expands to c&0xff, or just c if characters - are unsigned. This should fix problems with passing negative - values to isspace() and friends for characters > 0x7f on systems - where 'char' is signed - -Thu Feb 9 10:26:21 1995 Guido van Rossum - - * Lib/copy.py: added __doc__ strings - - * Lib/shelve.py: added __doc__ strings - - * Lib/anydbm.py: added __doc__ strings and test for gdbm - - * Include/longintrepr.h: remove untrue comment about - signed/unsigned ob_size - - * Modules/mpzmodule.c (mpz_div_and_mod): add proper casts (Jim - Fulton) - -Wed Feb 8 15:48:24 1995 Guido van Rossum - - * Python/bltinmodule.c (do_pow), Objects/floatobject.c - (float_pow): move check for negative float to the float power to - the pow() function, so negative float to the integer power can be - implemented correctly (after coercion to float) - -Tue Feb 7 10:14:34 1995 Guido van Rossum - - * Python/import.c (init_frozen): make it non-static, so - frozenmain.c can use it. Also remove the reference to - frozenmain.o from Python/Makefile.in - - * Doc/{ref6.tex,ref7.tex} (raise, except): describe classes and - instances used as exceptions (R Lindsay Todd) - - * Lib/test/test_exceptions.py: added tests for raising classes (R - Lindsay Todd) - - * Python/ceval.c (exec_statement): DECREF result of run_string - (Mark Lutz) - - * Modules/cursesmodule.c: patches to clear errors between failing - calls to Arg_Parse (Steve Clift) - -Fri Feb 3 13:48:12 1995 Guido van Rossum - - * Lib/bdb.py (format_stack_entry): append () to function name if - no __args__ - - * Lib/pdb.py (print_stack_entry): default prompt_prefix is - line_prefix, and use the default everywhere - -Thu Feb 2 15:27:15 1995 Guido van Rossum - - * Python/pythonrun.c (print_error): print class name for - exceptions that are classes (R Lindsay Todd) - - * Modules/tkintermodule.c: use PyCallable_Check instead of - manually checking for some callable types for callbacks; export - TK_VERSION and TCL_VERSION strings; a few Tk 4.0 specific changes - - * Modules/socketmodule.c (initsocket): added a long list of socket - related constants -- better here than in a separate python module, - because the values change per system (R Lindsay Todd) - - * Doc/{lib.tex,libsignal.tex}: added documentation for signal - module (Andrew Kuchling) - -Tue Jan 31 13:06:59 1995 Guido van Rossum - - * Include/pythonrun.h: remove declaration of (now static) - run_pyc_file - - * Modules/posixmodule.c (posix_utime): correct typo in utime() - stub - -Tue Jan 31 11:02:00 1995 Guido van Rossum - - * Modules/{pwdmodule.c,grpmodule.c} (mkpwent, mkgrent): NeXT - specific patch for little endian machines where the uid and gid - are in the wrong place in the structure (Mike Carlton) - -Mon Jan 30 16:17:33 1995 Guido van Rossum - - * configure.in: add -posix to definition of CC when detecting Next - -Mon Jan 30 13:32:07 1995 Guido van Rossum - - * Mac/*: not clearly logged are lots of changes to the Mac - specific modules, e.g. reworking of the interrupt detection code - and general reorganization of macglue.[ch], as well as support for - modules generated by "bgen" (see Demo/bgen), and subsequent - removal of the resource and sound interfaces from MacOS (since - they now have their own, complete, generated interface), and also - lots of development on the mactcp and macfs front - - * Modules/stdwinmodule.c (initstdwin): disable python's own event - processing on the mac as soon as stdwin is imported; removed some - unused variables - - * Parser/intrcheck.c: moved all mac specific stuff to - Mac/macglue.c - - * Python/pythonrun.c (goaway): Think C mod to suppress pausing at - normal exit - - * Python/import.c (imp_get_magic): fix glaring indexing bug - - * Modules/dbmmodule.c (dbm_keys): fix memory leak and tighten - error checking (and redo lay-out) - -Fri Jan 27 00:00:17 1995 Guido van Rossum - - * Objects/listobject.c: round up item count on resize to improve - realloc performance (dramatic effect in the Mac with Think C!) - - * Include/{rename2.h,methodobject.h}, Objects/methodobject.c: - added support for chaining method lists: Py_FindMethodInChain - -Thu Jan 26 12:59:51 1995 Guido van Rossum - - * Python/Makefile.in: removed frozenmain.o from OBJS -- it has no - business being in libPython.a. (Still build it though.) - -Thu Jan 26 00:42:29 1995 Guido van Rossum - - * Lib/mhlib.py: fix bogus test for matching regex - - * stdwinmodule.c: (re)move some unused variables - - * Python/pythonrun.c (run_pyc_file): made static - (fatal): loop forever on Mac, so error message remains visible - - * Python/import.c (doneimport): no need to dictclear() the - module's dictionary (that's done automatically when the module is - actually deleted) - - * Objects/classobject.c (instancebinop): removed unused variables - - * Objects/moduleobject.c (module_dealloc): explicitly erase a - module's dictionary when the module object disappears -- this was - formerly done in import's doneimport() - - * Objects/object.c, Python/bltinmodule.c: moved callable() to - object.c (from static in bltinmodule.c) since it is generally - useful (and I needed it :-); removed some unused vars - -Wed Jan 25 13:20:52 1995 Guido van Rossum - - * Modules/posixmodule.c (posix_utime): Be more robust in the light - of unusual types for uname struct members and 64-bit longs - - * Python/ceval.c (eval_code): mods to allow using classes as - exceptions (R Lindsay Todd) - -Mon Jan 23 20:48:16 1995 Guido van Rossum - - * configure.in (LDSHARED): add case for OSF/1 (Bob Kras); - (socket libraries): add conditional for IRIX 5, where -lsocket - exists but doesn't seem to work properly - - * Python/compile.c (get_docstring): add missing case for - file_input, so __doc__ strings in modules work - -Sun Jan 22 20:45:40 1995 Guido van Rossum - - * Modules/regexmodule.c (reg_dealloc): free the compiled pattern - buffer -- plugs a memory leak - -Sun Jan 22 01:44:01 1995 Guido van Rossum - - * Modules/signalmodule.c (sigcheck): renamed to PyErr_CheckSignals - -- signal checking was broken because of this! - -Sat Jan 21 15:10:08 1995 Guido van Rossum - - * Python/getargs.c (seterror): don't overwrite error if one is - already set (e.g. by O& handler) - (convertsimple1): return "(unspecified)" instead of empty string - for type description of "O&" object - -Fri Jan 20 15:27:51 1995 Guido van Rossum - - * Modules/Makefile.pre.in (sharedinstall): add command to make the - $(DESTSHARED) directory - - * README: change NeXT hint to add -posix to C compiler flags - - * Python/import.c: document the fact that almost all functions - returning a module object (except add_module()) increment its - reference count, and add missing INCREF calls here and there - - * Python/bltinmodule.c (builtin___import__): don't INCREF the - module -- import_module() has already done that - - * Python/ceval.c (eval_code, RAISE_EXCEPTION): add missing INCREF - after gettupleitem() call (R Lindsay Todd) - - * configure.in: added check for working getopt (R Lindsay Todd); - modernize all tests to use cache and report outcome (John - Interrante) - - * Include/{classobject.h,listobject.h}: corrected two unconverted - names (found by John Interrante) - -Thu Jan 19 01:31:46 1995 Guido van Rossum - - * configure.in (LDSHARED): added case for Sequent DYNIX (Jaap - Vermeulen) - - * Mac/macglue.c (Pstring): truncate string to 255 bytes - - * Objects/listobject.c (list_dealloc): Fix NULL dereference in - case of out-of-memory condition (Jack) - - * Parser/intrcheck.c (intrpeek): new Mac specific routine to test - for interrupt without clearing the interrupt flag (Jack) - - * Python/errors.c (strerror): #undef it first on the Mac (Jack) - - * Lib/ftplib.py: don't break if os.environ doesn't exist (Jack) - - * Modules/timemodule.c (inittime): fix memory leaks (should decref - new objects passed to dictinsert) - - * Python/compile.c (optimize): fix memory leak (forgot to decref - localmap) - - * Objects/funcobject.c (func_dealloc): fix memory leak (forgot to - decref func_name) - - * Python/importdl.c: added changes for NetBSD dynamic linking - (David Hobley); removed shared linking for NeXT (incompatible with - the -posix flag) - - * Modules/mathmodule.c: removed empty #ifdef macintosh...#endif - - * Parser/parsetok.c (parsetok): avoid uninitialized memory read - - * Mac: various stuff to port Jack's mods back to THINK C, as well - as my own changes for apple events - - * Python/modsupport.c: support "O&" taking an object constructor - and a void* (sort of inverse of O& in getargs) - - * configure.in, Makefile.in: mods to define and use - INSTALL_PROGRAM and INSTALL_DATA as well as INSTALL (John - Interrante) - -Wed Jan 18 12:01:20 1995 Guido van Rossum - - * Mac: lots of new stuff checked in by jack - - * configure.in: added test for genuine getopt (R Lindsay Todd) - - * Python/Makefile.in: removed getopt.o from OBJS (but left in - getopt.o: getopt.c rule) - - * Python/getopt.c: don't use function prototypes (Anthony Baxter) - - * Modules/arraymodule.c: make the routines static now that their - forward declarations are! (Anthony Baxter) - -======================================== -==> Release 1.2 BETA 2 (17 Jan 1995) <== -======================================== - -Tue Jan 17 11:24:23 1995 Guido van Rossum - - * Include/patchlevel.h: set version to 1.2-beta-2 - - * Python/Makefile.in: added getopt to list of objects - - * Makefile.pre.in: be more careful about building - Modules/Makefile.pre - - * Objects/floatobject.c: test for __STDC__ instead of macintosh de - decide whether to declare fmod() and pow() -- this works in - mathomodule.c so why not here... - - * Objects/rangeobject.c: made a few things static - - * Objects/longobject.c, Include/{longobject.h,rename2.h}: - long_scan is now a macro that calls long_escan; long_scan no - longer exists - - * Objects/object.c (strobject): use tp_str and only try __str__ if - it's an instance - - * configure.in: hopefully final changes for Sequent's -linet - - * README: add hint for NeXT users to use --without-gcc - - * Python/{bltinmodule.c,ceval.c}, Objects/frameobject.c: - initialize __builtins__ from built-in *module* instead of *dict*, - to prevent interactive vars() call to loop recursively - - * Python/bltinmodule.c: fix Alpha bug in range and xrange -- - sizeof(int) != sizeof(long) - - * Python/mystrtoul.c: include rename2.h - - * Modules/*: made things static and general clean-up for new - naming scheme - - * Include/*.h: new names for lots of new functions - - * Lib/rexec.py: no need for distrusting dir() or vars(), changed - open() to allow everything (for reading) except /etc/* - - * Mac/macmain.c: include rename2.h - - * */Makefile*in: added harmless $& to $(LIB) target for Sequent - parallel make - - * Parser/tokenizer.c: fix loop on unterminated triple quotes - - * Parser/intrcheck.c: made 'interrupted' flag static again - - * Objects/listobject.c (list_ass_slice): free recycling bin when - making early exit due to memory error - - * Objects/listobject.c, Include/{listobject.h,rename2.h}: added - reverselist, C interface to list.reverse(). - - * Object/listobject.c (list_ass_slice): fixed re-entrancy bug - (noticed by Jim Roskind) - -Sat Jan 14 11:21:29 1995 Guido van Rossum - - * Python/modsupport.c (PyEval_CallMethod): changed method argument - name to methodname -- since method is also a typedef and some - compiler choke on this (e.g. HP) (Andrew Kuchling) - - * Python/thread.c: added #include thread_nt.h (Mark Hammond) - - * Demo/scripts/h2py.py: support $include or $INCLUDE path instead - of only using /usr/include (Mark Hammond) - - * Python/ceval.c (eval_code/PRINT_EXPR): fix messed output when - x.__repr__() prints something and repr(x) is called at the prompt - -======================================== -==> Release 1.2 BETA 1 (12 Jan 1995) <== -======================================== - -Thu Jan 12 12:27:23 1995 Guido van Rossum - - * Python/pythonrun.c (initmain), Python/import.c - (exec_code_module): use getbuiltins(), not getbuiltindict() to - initialize new modules - - * Python/ceval.c (getbuiltins): return getbuiltindict() instead of - NULL if no current frame - - * Modules/cryptmodule.c: removed redundant include of modsupport.h - - * Modules/signalmodule.c: remove unwanted trigraph from comment - - * Modules/Setup.in: clarify status of dlmodule.c - - * Objects/object.c (cmpobject): properly implement cmp() for class - instances - -Wed Jan 11 10:56:12 1995 Guido van Rossum - - * README: removed references to --with-svr4; added docs for - --without-gcc - - * Modules/mathmodule.c: rearrange declarations somewhat - -Tue Jan 10 11:34:23 1995 Guido van Rossum - - * Include/*.h, Python/getmtime.c, Modules/.c: THE GREAT - RENAMING (inspired by Jun Hamano). One now either includes - "Python.h" and then uses new names only, or one includes - "allobjects.h" and uses old names. "rename1.h" no longer exists; - instead, "rename2.h" performs the reverse mapping. - - * Python/bltinmodule.c (builtin_filter): fix subtle refcount big - in filter() (Tim MacKenzie) - - * Include/mymalloc.h, Modules/{Makefile.pre.in,config.c.in}: - change to make things palatable for C++ (Tim MacKenzie) - - * Modules/socketmodule.c: only call hstrerror() if it exists - - * Modules/tkintermodule.c: added interface to Tk_DoOneEvent() (R - Lindsay Todd) - - * Objects/longobject.c (long_pow): some defensive programming - (Eric Siegerman) - - * Objects/intobject.c (int_pow): fix memory leak in ternary pow() - (Eric Siegerman) - - * Modules/posixmodule.c (posix_fdopen, posix_popen): add optional - argument to specify buffer size as for __builtin__.open(); also - make mode argument optional (default "r") - - * Objects/classobject.c (instance_coerce): implement coercions - involving instances properly - - * Objects/object.c, Python/bltinmodule.c: moved coerce() to - objects.c, where it belongs - - * Doc/libfuncs.tex: added execfile(); reformulated eval() somewhat - - * Python/bltinmodule.c (builtin_{execfile,eval}): fix - globals/locals defaults to match the manual again; also allow None - to mean the same as the default - - * Lib/nntplib.py: fix comments for list command (should be last, - first instead of first, last) - - * Lib/test/test_grammar.py: fix exec test so presence of - __builtins__ doesn't break it - -Mon Jan 9 14:20:16 1995 Guido van Rossum - - * Objects/{funcobject.c,methodobject.c,classobject.c}: don't - expose certain internals (e.g. __dict__) in restricted mode. - - * Python/thread_pthread.h: Alpha OSF/1 fix - - * Python/importdl.c (load_dynamic_module): removed bogus check for - reloading of dynamically loaded modules (tested uninitialized - local variable) - - * Include/{frameobject.h,ceval.h,bltinmodule.h,rename1}, - Python/{ceval.c,import.c,pythonrun.c,bltinmodule.c}, - Object/frameobject.c: changed handling of builtins. Each frame - now has a pointer to the dictionary of builtins to be used in that - frame, initialized from __builtins__ in the globals passed to the - frame. Only run_node() and exec_code_module() initialize - __builtins__ to the dictionary of the real __builtin__ module. - Furthermore, a frame is in "restricted" mode if its builtins are - not the real __builtin__ module. In restricted mode, some other - modules and object types restrict their interfaces. Subtle - change: eval_code() no longer automatically fills in the default - globals; this must be done by the caller (who can then also - explicitly stick in the builtins if needed). bltinmodule.c no - longer exports {get,set}builtin() but instead exports - getbuiltindict(). ceval.c export getbuiltins() and - getrestricted() in analogy of getglobals(). - - * Include/sysmodule.h, Python/{sysmodule.c,ceval.c}, - Doc/libsys.tex: change sys.check_interval Python variable into - Python function sys.setcheckinterval(interval) and C variable - sys_checkinterval - - * Mac/macosmodule.c: use new getargs interface; add - {Get,Set}FileInfo - -Sat Jan 7 09:40:24 1995 Guido van Rossum - - * Python/compile.c: support import A.B...Z; added doc strings to - modules, classes and function - - * Python/ceval.c: use new instancebinop interface - - * Python/bltinmodule.c: restructured coerce(), divmod(), pow() to - use new instancebinop interface - - * Objects/classobject.c: added 5th (function) parameter to - instancebinop, to support things like Rational * float; added - documentation strings to classes and methods - - * Objects/methodobject.c: changed drastically, the object now - contains a pointer to the struct methodlist (which must be - static); added attributes __name__, __doc__ and __self__ - - * Objects/funcobject.c: added __doc__ attribute (alias func_doc), - initialized from first constand in code object if it is a string, - else to None - - * Objects/moduleobject.c: initialize __doc__ to None - - * Objects/typeobject.c: added getattr(), supporting __doc__ and - __name__ - - * Objects/object.c: raise AttributeError, not TypeError for object - without attributes - - * Python/modsupport.c, Include/modsupport.h: add doc string - parameter to initmodule3 (renamed from initmodule2); new - newmethodobject() interface - - * Modules/signalmodule.c (initsignal): don't call - newmethodobject() directly -- rely on initmodule() - - * Modules/newmodule.c: rationalize argument checking, redo - lay-out, add __doc__ strings - - * Include/object.h: added tp_str (to implement str()), tp_doc, and - some dummy fields - - * Include/methodobject.h: added ml_doc member to struct methodlist - and renamed ml_varargs to ml_flags; changed newmethodobject() to - take a struct methodlist * argument instead of individual parts; - got rid of ML_FREENAME again - - * Include/funcobject.h: added func_doc struct member - - * Include/classobject.h: added 5th (function) parameter to - instancebinop, to support things like Rational * float - - * Grammar/Grammar: changed import to support NAME.NAME...NAME - - * Python/importdl.c (load_dynamic_module): NT dlls have extension - .pyd, not .dll - -Thu Jan 5 11:00:13 1995 Guido van Rossum - - * Demo/scripts/mboxconvert.py: invent Message-ID if none present - -Wed Jan 4 18:23:09 1995 Guido van Rossum - - * Python/modsupport.c (initmodule2), Include/methodobject.h, - Objects/methodobject.c: introduced METH_FREENAME bit passed to - newmethodobject to indicate that if the object is freed the name - pointer must also be freed (this saves a long standing memory leak - in initmodule2) - - * Modules/structmodule.c (struct_pack, struct_unpack): use memcpy - instead of double precision assignment (since a string isn't - always double-aligned, e.g. when debug fields are present in the - object header) - - * Objects/floatobject.c (float_hash): changed a constant to avoid - float->long conversion overflow - - * Python/bltinmodule.c (builtin_pow): fix coerce() ref count - nightmare (core dumps on Linux) - - * Python/pythonrun.c: call flushline() in print_error(), after - fetching the exception info, since flushline() can mask an - exception; move flushline() calls around so they are not between - the detection and printing of the exception - -Tue Jan 3 12:55:28 1995 Guido van Rossum - - * Modules/config.c.in (getcopyright): Change copyright to include - 1995 - -Mon Jan 2 20:15:39 1995 Guido van Rossum - - * Objects/mappingobject.c (mappingremove): don't call - lookmapping() for empty dictionary - - * Doc/libsocket.tex (section{Built-in Module \sectcode{socket}}): - documented gethostbyaddr() - - * Modules/mpzmodule.c (mpz_power): made it ternary - - * Modules/mathmodule.c: only use hypot() if it exists - - * Modules/Makefile.pre.in (sharedinstall): fix bug (sh can't loop - over empty list) when $(SHAREDMODS) is empty - - * Python/errors.c: added hook for better mac error messages - - * Python/pythonrun.c (run_script): removed extraneous fclose() in - case of .pyc file argument - - * Include/{object.h,stringobject.h}: changed refcnt and sizes from - unsigned to int (i.e. signed) - - * Objects/fileobject.c (newfileobject): use HAVE_FOPENRF instead - of USE_FOPENRF - - * Lib/test/test_b1.py: test eval() and execfile() with globals, - locals arguments - - * Lib/mhlib.py: added movemessage(), copymessage(), added copy - fallback for refilemessages(), and updated the docs - -Fri Dec 30 16:19:17 1994 Guido van Rossum - - * Parser/tokenizer.c (tok_nextc): zap tok->buf after freeing - - * Include/traceback.h: added struct _frame declaration for ANSI C - - * Include/bitset.h: move definition of testbit() around - -Thu Dec 29 10:09:25 1994 Guido van Rossum - - * Objects/mappingobject.c (mapping_has_key): don't call - lookmapping() for empty dictionary - - * Modules/Makefile.pre.in: use new style @prefix@ substitution - (sharedinstall): fix case of loop over empty $(SHAREDMODS) - - * Several files: removed redundant variables etc. (Sam Leffler) - -Wed Dec 28 12:09:10 1994 Guido van Rossum - - * Modules/threadmodule.c (t_bootstrap): XDECREF the return value; - (thread_exit_thread): DECREF the frame returned by save_thread() - - * Modules/md5module.c, Doc/libmd5.tex: renamed md5.md5() to md5.new() - -Wed Dec 21 13:30:47 1994 Guido van Rossum - - * Python/ceval.c (build_class): add hook for Donald Beaudry - -Mon Dec 19 17:35:13 1994 Guido van Rossum - - * Doc/libposixfile.tex: the fileopen function was erroneously - documented as openfile - -Tue Dec 13 11:46:03 1994 Guido Van Rossum - - * config.h.in, configure: rewritten *by* autoconf 2.0 - - * configure.in: parts rewritten for autoconf 2.0; strip spaces - from uname output for QNX; test for some new things like - ftruncate, truncate and va_list as array - - * acconfig.h: some reordering to get things in alphabetical order; - added GETTIMEOFDAY_NO_TZ and VA_LIST_IS_ARRAY - - * README: Added SCO notes - - * Python/thread_solaris.h (start_new_thread): create new threads - with THR_DETACHED option instead of THR_NEW_LWP -- else there's a - limit to the number of threads you can create in total, ever, per - process - - * Python/traceback.c (tb_print): don't store in sys.last_traceback - (that's done in pythonrun.c:print_error() now) - - * Python/pythonrun.c (print_error): use fatal() instead of - abort(); use err_fetch() instead of err_get(); call tb_print() - instead of going through ceval.c:printtraceback() - - * Python/modsupport.c: fix vmkvalue() for systems where va_list is - an array; add support for creating lists and dictionaries; added - convenience functions for calling functions/methods with format - and argument list - - * Python/marshal.c (rd[s]_object): add trap for calls while an - exception condition is still set - - * Python/{import.c,importdl.c}: completely restructured: moved - all dynamic loading stuff to importdl.c; added public interface - to the functionality through module 'imp' (for __import__ hack) - - * Modules/threadmodule.c (t_bootstrap): fix leak of result value - (still a massive leak left I think) - - * Python/errors.c: don't declare strerror on NT - - * Python/getargs.c (vgetargs[1]): fix for systems where va_list - is an array - - * Python/compile.c: use fatal() instead of abort(); use - err_{fetch,restore} - - * Python/ceval.c: move some (X)DECREF's around for improved - re-entrancy; call built-in __import__ to implement IMPORT_NAME; - use err_{fetch,restore}; fix call to __rshift__ in __lshift__; - check for string left arg before anything else in rem() - - * Python/ceval.c, Include/ceval.h: get rid of printtraceback - - * Python/bltinmodule.c: added __import__ built-in function; - restructured argument parsing of most built-ins to use - newgetargs() - - * Python/Makefile.in: add importdl.o to OBJS; special-case - compilation of importdl.c instead of import.c - - * Parser/{pgen.c,parser.c,grammar.c}: use fatal() instead of abort() - - * Objects/object.c: use fatal() instead of abort() - - * Objects/mappingobject.c: fix re-entrancy bugs (allow ma_table - and ma_size to be 0) - - * Objects/listobject.c: fix some re-entrancy bugs (not complete) - - * Objects/frameobject.c: use err_{fetch,restore} everywhere; use - fatal() instead of abort() - - * Objects/fileobject.c (file_truncate): new method (only of - ftruncate() is in libc) - - * Objects/classobject.c (instance_getattr): add err_clear() when - retrying after failing instance_getattr1() call; use - err_{fetch,restore} everywhere - - * Modules/tkintermodule.c: use PyErr_{Fetch,Restore} instead of - {GetAndClear,SetObject}; fix NULL dereference in TimerHandler - - * configure.in, Modules/timemodule.c: on some systems, - gettimeofday() has no second argument - - * Modules/socketmodule.c: if O_NDELAY undefined, use O_NONBLOCK - (for QNX); use gethostbyname_r if it exists (since it is - re-entrant); use h_error and hstrerror when they exist; other - changes for re-entrancy; make printable representation more - useful; cosmetic changes in argument lists; add gethostbyaddr() - - * Modules/signalmodule.c: if NSIG undefined, use _SIGMAX + 1 - - * Modules/posixmodule.c: changes for direct/dirent dictated by - autoconf 2.0 - - * Modules/config.c.in: added standard built-in module "imp" - - * Modules/{Makefile.pre.in,makesetup}: change @...@ to _..._ - - * Makefile.in: adapted to autoconf 2.0; treat prefix in a standard - way, remove config caches in distclean target - - * Lib/tkinter/Tkinter.py (Pack.propagate): fix calling convention - - * Lib/test/test_b2.py: test reload() of built-in module (marshal) - - * Lib/test/{test_b1.py,testall.out}: added test for __import__ - - * Include/rename1.h: change HEAD_INIT to macro with argument - - * Include/import.h: added decl for get_pyc_magic() - - * Include/{rename1.h,errors.h}, Python/errors.c: added err_fetch() - and err_restore(), get rid of err_get() - - * Include/bltinmodule.h, Python/bltinmodule.c (getbuiltins): new - like getbuiltin() buit takes char * instead of stringobject * - argument (for __import__ hack) - - * Doc/tut.tex: use spam, bacon and eggs instead of foo, bar, bletch - - * Doc/libtypes.tex (File Objects): add footnote - explaining why readline() leaves the trailing newline in - -Sat Nov 19 15:14:02 1994 Guido Van Rossum - - * Objects/mappingobject.c: ma_table may now be NULL (when ma_size - == ); changes to avoid re-entering the interpreter via DECREF - while the mapping object is being modified - - * Several other places: similar - - * errors.[ch]: new functions err_fetch and err_restore - fetch and restore all three exception related values (plus places - using these) - - * Makefile.in (TESTPATH): Added ./Modules to test path so - dynamically loaded modules are found even if not yet installed - -Wed Nov 16 14:19:01 1994 Guido Van Rossum - - * Python/sysmodule.c (list_builtin_module_names): stop a leak - -Mon Nov 14 13:21:45 1994 Guido van Rossum - - * Doc/ref[467].tex: don't use \verb{...} in footnotes; rewritten - using {\tt ...} - - * Lib/urlparse.py (urljoin): safe version of Andy Bensky's fix to - urllib.py - - * Lib/urllib.py (basejoin): (Andy Bensky) fix case where url has a - type and a path but no host -- the host from the base should be - inserted - - * Parser/grammar.c: (Don Beaudry) initialize accelerators print - "Translating labels" header only if debugging - - * Doc/ref[36].tex: some typos - - * Doc/ref[35].tex: clarify reverse/backward quotes, add them to - the index - -=================================== -==> Release 1.1.1 (10 Nov 1994) <== -=================================== - -Thu Nov 10 13:09:26 1994 Guido van Rossum - - * Objects/classobject.c (instance_compare): don't ever raise an - exception or return -2 - - * Python/compile.c: stick "" in function name instead of - NULL or None - - * Doc/tut.tex: corrected a few typos - - * Modules/tkintermodule.c: added timer and file handler interfaces - and made mainloop/quit global functions (as well still being tk - methods) - - * Modules/newmodule.c: made it compile on SunOS4.1.3 (there were - continuation backslashes on non-cpp lines :-) - - * Modules/gdbmmodule.c: fix some bugs (freed the wrong objects) - - * Modules/Setup.in: clarified some things a little in the comments - - * Modules/Makefile.pre.in (sharedinstall): don't fail if there - aren't any shared modules - - * Include/structmember.h: include stddef.h (for offsetof) - - * Include/rename1.h: added PyArg_ParseTuple for newgetargs - - * Python/bltinmodule.c: fix core dump in pow() (should be declared - varargs in methodlist array) - - * Python/ceval.c: replace abort() calls with fatal() calls - - * Python/errors.c (err_setval): call err_clear() to clear existing - error instead of calling XDECREF - - * Python/getargs.c: fix core dump when old style call expecting - some arguments receives none - - * Lib/test/{test_b[12].py,testall.out}: added more tests (now all - built-ins are covered again) - -Thu Oct 20 08:31:02 1994 Guido van Rossum - - * Modules/makesetup: should use $cc not cc - - * configure.in, configure, config.h.in: test for presence of - stddef.h - - * Include/structmember.h: include if it exists - -Wed Oct 19 11:45:35 1994 Guido Van Rossum - - * Makefile.in: patch by Wolf-D. Ihlenfeld to use BINDIR etc - - * Lib/tkinter/Tkinter.py: added option_{add,clear,get,readfile} to - Misc class - - * Lib/poly.py: fix bug in minus() - - * Modules/Setup.in: clarified optional SGI modules and improved - template for using *noconfig* - - * Doc/Makefile: don't assum '.' is in $PATH - - * Modules/mathmodule.c, Doc/libmath.tex: add hypot() - - * Makefile.in: on libinstall, automatically run sharedinstall in - Modules - - * Modules/Makefile.pre.in: always make sharedmods - - * Modules/makesetup: quote $ in two places - - * configure.in, acconfig.h.in, config.h.in, configure, - Modules/posixmodule.c: separate arg requirements for getpgrp() and - setpgrp() - - * Nt/Python/makefile.nt.mak: added getargs() - -Thu Oct 13 07:51:03 1994 Guido van Rossum - - * README: removed misleading comment about example Setup.* files - -================================= -==> Release 1.1 (11 Oct 1994) <== -================================= - -Tue Oct 11 16:24:42 1994 Guido van Rossum - - * last-minute changes for SunOS 4.1.3: test for volatile in - configure; add getargs.o dependency to Modules/Makefile.in; some - things in README and Misc/NEWS; change pathnames in - Demo/tkinter/guido/*.py; new date in Doc - -Mon Oct 10 19:00:34 1994 Guido van Rossum - - * Makefile.in: apply ranlib to installed libraries - - * Modules/socketmodule.c: new style - - * Doc/ref3.tex: some stuff about __getattr__ etc. - -Thu Oct 6 16:40:05 1994 Guido van Rossum - - * Got rid of Modules/imgformat.c (will be distributed with Jack's - img package) - - * Doc/*.tex: moved title boilerplate to separate file, added - copyright notice (separate file) - -Wed Oct 5 11:13:13 1994 Guido van Rossum - - * Modules/config.c.in: don't include frozen.c when frozen (the new - freeze script compiles it separately) - - * Lib/os.py: add dummy import posixpath, for freeze script - - * Python/marshal.c (r_object): plugged memory leak in reading of - code objects - - * Modules/config.c.in (getpythonpath): always return malloc'ed - memory -- save a static pointer to free next time (prevents leaks) - -Thu Sep 29 10:35:28 1994 Guido van Rossum - - * Grammar/Grammar: got rid of history; changed some diagram - commands - - * Lib/types.py: cosmetic changes - - * Mac/{config.c,macosmodule.c}: new interface to (a few bits of) - the Mac OS - - * Modules/xxmodule.c: integrated with xxobject.c by Jack - - * Modules/(posix,socket}module.c: more NT changes - - * Python/traceback.c: security fix -- check for buffer oveflow - before concatenating sys.path item and module name - - * Python/ceval.c, Include/ceval.h: promote MakePendingCalls to - global: Py_MakePendingCalls. Also guard against recursive calls - - * Python/pythonmain.c: fatal error if can't alloc mem for -c - string - - * Python/pythonrun.c: add string "Python" to fatal error message - -Wed Sep 28 16:39:09 1994 Guido van Rossum - - * Objects/longobject.c: change ValueError to OverflowError when - converting to int - - * Objects/xxobject.c: changed to use new style (not finished?) - - * Objects/stringobject.c: use HAVE_LIMITS instead of __STDC__ - - * Objects/rangeobject.c: modernized - - * Objects/floatobject.c: add overflow check when converting float - to int and implement truncation towards zero using ceil/float - - * Parser/intrcheck.c: make 'interrupted' global (forgot for - whom...) - - * Include/rename1.h: don't even define Py_FPROTO - - * Python/{modsupport.c,getargs.c,Makefile.in}, - Include/modsupport.h: moved getargs() to its own file and - re-implemented it entirely to support optional arguments, multiple - arguments without surrounding parentheses - (when called as newgetargs()), and better error messages - - * Include/classobject.h, Objects/classobject.c, - Python/{ceval.c,bltinmodule.c}: entirely redone operator - overloading. The rules for class instances are now much more - relaxed than for other built-in types - (whose coerce must still return two objects of the same type) - -Sun Sep 18 07:26:39 1994 Guido van Rossum - - * Python/pythonrun.c (print_error): print only last line of - multi-line source line - - * Parser/tokenizer.c (tok_nextc): count line numbers when parsing - strings - -Fri Sep 16 15:54:56 1994 Guido van Rossum - - * Python/modsupport.c (do_arg): added error message if "O!" fails; - change type of converter for "O&" to function returning int taking - an object* and a void* parameter; it should return 1 for success - or return 0 and set an exception for failure to convert - -Wed Sep 14 14:08:44 1994 Guido van Rossum - - * Include/Python.h: new header file for new naming scheme - - * various modules: #include "Python.h" and remove most remporary - renaming hacks - - * Lib/whrandom.py: if seed is (0,0,0), initialize from current - time; default seed's arguments to (0,0,0) - - * Python/ceval.c (eval_code), Include/ceval.h: added registry of - pending functions (to be used by functions that are called - asynchronously, like UNIX signal handlers or Mac I/O completion - routines) - -Wed Sep 14 11:05:36 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/libsys.tex (section{Built-in Module \sectcode{sys}}): - documented sys.check_interval - -Tue Sep 13 21:35:19 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Import/pythonrun.h, Python/{import,pythonrun}.c, - mac/macsetfiletype.c: changes by Jack to execute .pyc file passed - as command line argument. On the Mac .pyc files are given a - special type so they can be double-clicked - - * Modules/stropmodule.c (strop_[r]find): change index range check - -- don't raise ValueError buit silently clip when it's out of - range (this is compatible with slicing) - -Mon Sep 12 12:53:07 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Extensions/X11/Xmmodule.c: (Sjoerd): Implemented - Xm.OptionButtonGadget and Xm.OptionLabelGadget - - * Modules/Setup.in: define PYTHONPATH using COREPYTHONPATH for - extensions; add -lm to math module definition - - * Modules/Makefile.pre.in: remove *.so and so_locations on clobber - - * Modules/makesetup: (Sjoerd): treat words beginning with a dollar - and not ending in a well-known extension as linker arguments - - * Lib/urlparse.py: URL parser according to the latest Internet - draft - - * README: added note about HP-UX - -Sun Sep 11 12:12:28 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Misc/indent.pro: Steen's approximation of my C style as a GNU - indent profile - - * Modules/{Setup.in,termios.c}: add Steen's termios; also - Lib/[pt]ty.py, Demo/scripts/script.py, Lib/irix5/TERMIOS.py - - * Demo/scripts/h2py.py: merged in Steen Lumholt's changes to - handle #include. Now also handles one-argument macros. - - * configure.in: use uname to decide how to create / link shared - libraries and to set $(MACHDEP) (machine dependent subdirectory of - Lib) - - * Makefile.in: shared library support; added target sharedinstall - which move shared libraries into Lib/$(MACHDEP) - - * Modules/{Makefile.pre.in,Setup.in,makesetup}: support shared - libraries. Had to re-engineer rule production in makesetup - because sed was dumping core on the script fed to it -- now the - rules are always appended to the end of the Makefile. - -Fri Sep 9 11:35:28 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/uu.py: new module, does uuencode/uudecode (thanks to Lance) - - * Grammar/Grammar: fewer #diagram:break hacks needed; removed - history from file - -Thu Sep 8 10:24:41 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Parser/grammar1.c (finddfa): massive speed up by using direct - addressing instead of searching - -Wed Sep 7 08:49:37 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Include/rename1.h: added PyArg_GetInt - - * pythonrun.h: added Py_AtExit - - * Doc/libsocket.tex, Modules/socketmodule.c: added Tommy - Burnette's setblocking() method - - * Modules/signalmodule.c: adapted to new module style (Lance); - added {BGN,END}_SAVE around pause() call - - * Objects/object.c (DELREF): must zap type pointer *before* - calling free() (or other destructor) - -Sat Sep 3 14:12:38 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/{Setup.in,tkintermodule.c,tkappinit.c}: moved tkinter - into the main Modules directory, and its Lib and Demo - subdirectories into the main Lib and Demo directories. Moved - definition of STDWIN component and TK component of PYTHONPATH to - their respective sections so it's easier to remember to enable - them. - - * Python/pythonrun.c (cleanup), Include/pythonrun.h: added - Py_AtExit() -- register cleanup functions for C modules - -Tue Aug 30 10:53:50 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/getmtime.c: Remove mac specifics (Mac subdirectory has - its own version now) - - * Modules/Setup.in: uses .c instead of .o now; added curses - - * Modules/{rotormodule,syslogmodule}.c: new naming conventions - - * Modules/cursesmodule.c: new, interface to curses - - * Modules/makesetup: bugfix: add objects from sources to OBJS - - * Modules/cursesmodule.c: new contribution from Lance - - * Python/bltinmodule.c (builtin_tuple): use pre-existing - listtuple(v) for lists - -Mon Aug 29 15:41:02 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Various places: merged THINK C 6.0 and MPW 3.2 mods: Python 1.1 - should build flawlessly on the Mac using either compiler - -Fri Aug 26 10:18:05 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/tut.tex (subsection{Lambda Forms}): fix typo in lambda - example - -Thu Aug 25 12:30:11 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/importall.py: obsolete. - - * Lib/{compileall,py_compile}.py: new modules for compiling .py - files. - - * Modules/timemodule.c (floattime), Objects/longobject.c - (dgetlongvalue): add (double) casts for the benefit of the SCO C - compiler - -Tue Aug 23 00:52:32 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/Setup.*: removed all except Setup.in (huh? I thought - I'd done that already?!); disable gdbm by default - - * Modules/makesetup: support C++ files now; these should be given - as file.C or file.cc or file.c++; C files can be given as file.c - (instead of file.o, which is still supported) - - * configure.in, */Makefile*.in: OPT can now be specified in the - env at configure time and will then be put in all Makefiles as - default - - * Modules/config.c.in: change mac specific things - - * Python/import.c: add lost NT-specific code back in - - * Parser/tokenizer.c: backup over illegal newline in string - literal (for "completeness" test) - - * Include/node.h: make some fields short to save space during - parsing - - * Modules/posixmodule.c: some more NT changes - - * Doc/libtime.tex: get rid of references to millitime() and - millisleep(); document clock() - -Mon Aug 22 10:53:59 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/linecache.py: don't crash on empty filename - - * Lib/macpath.py: don't return trailing colon for dirname() - (XXX won't do for volume names -- but otherwise glob(':*:*.py') - loops forever) - - * Lib/traceback.py: print SyntaxError correctly - - * Modules/signalmodule.c: added pause(). - - * Python/pythonrun.c (print_error): added INCREF/DECREF pair -- - the exception returned by a syntax error (when reported) would - contain an object with refcnt zero! - -Fri Aug 19 15:35:44 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * */Makefile*.in: remove lib*.a before adding to it - - * Lib/urllib.py: fix caching bug (by disabling the cache) - - * Lib/sgi/flp.py: fix caching bug (always write the whole file to - the cache!) - - * Doc/ref6.tex (section{Assignment statements}): added warning - about overlaps in lhs of assignment (e.g. "i, x[i] = 1, 2") - - * Python/errors.c (err_clear): clear interpreter stack trace - -Wed Aug 17 16:10:07 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Moved patchlevel.h from Python/ to Include/, moved all code from - version.c to config.c and removed version.c, and changed - Modules/Makefile(.pre.in) to add dependencies on $(MYLIBS) for - config.c (so the date in the version is always current). Also - changed the format of PATCHLEVEL: it is now a string containing - the complete version number, e.g. "1.1". - - * Grammar/Grammar: Added #diagram:... comments for Kees Blom's - railroad diagram generator - - * Doc/libstring.tex (section{Standard Module \sectcode{string}}): - removed references to {ato{f,i,l},index}_error - - * Lib/string.py: find/rfind is now the main implementation and - index/rindex is a wrapper that raises index_error (which is now - always ValueError) - - * Modules/stropmodule.c: implement find/rfind instead of - index/rindex (raising and catching an exception is much more - expensive than returning and testing -1) - - * Lib/os.py: do fake "import posix" for freeze.py script - -Tue Aug 16 23:58:30 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Parser/parsetok.c (parsetok): don't call strncpy(str, NULL, 0) - - * Doc/libfuncs.tex (section{Built-in Functions}): added docs for - delattr() - - * Python/bltinmodule.c: added delattr(x, 'attr'), equivalent to - del x.attr - -Fri Aug 12 15:00:20 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/libfuncs.tex: don't use $math$ in description of pow(x,y,z); - describe tuple() - - * Doc/libposixfile.tex: use tableiii instead of tableii, so - partparse will work again (I know, chicken!) - - * Doc/libthread.tex: Added get_ident(); updated text on module - availability - - * Doc/myformat.perl: Added sub do_cmd_Cpp - - * Python/compile.c (com_argdefs, com_arglist): avoid referencing - CHILD(n,i) for i >= NCH(n) - - * Python/bltinmodule.c: added tuple() builtin - -Thu Aug 11 16:41:14 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Objects/classobject.c, Include/classobject.h: added __getattr__ - and __setattr__ support to override getattr(x, name) and - setattr(x, name, value) for class instances. This uses a special - hack whereby the class is supposed to be static: the __getattr__ - and __setattr__ methods are looked up only once and saved in the - instance structure for speed. - (Later rewritten to also support __delattr__ and to store the - routines in the class instead of in the instance) - -Wed Aug 10 13:42:29 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * configure.in, Makefile.in: remove the AC_PREFIX() call -- it's - more trouble than it's worth at CWI and most other people seem to - install Python in the default (/usr/local) anway. Changed comment - describing --prefix in Makefile.in - - * Lib/urllib.py (ftpcache): remove debug print statement - -Tue Aug 9 14:32:45 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Objects/{int,long,float}object.c, Include/object.h, - Python/bltinmodule.c: mods by Andrew Kuchling to implement - pow(x,y,z) == pow(x,y)%z, but without incurring overflow - - * Python/import.c: if initializing a module did not enter the - module into sys.modules, it may have raised an exception -- don't - override this exception. - - * Include/rename1.h: added PyMethodDef and PyObject - -Mon Aug 8 09:51:08 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/{Makefile,*.tex}: Changes by Andrew Kuchling: - * Added dependencies to the Makefile - * Added \optional{} commands all over the place (possibly not - finished yet) - * Defined \optional and \Cpp in myformat.sty - * Changed all occurrences of C++ to \Cpp{}, for nicely - formatting the + signs. - * Fixed typos, sentence structure in lots of places - * Added documentation for the rotor module - * Added a commented-out paragraph to libcrypto.tex that can be - added once the Python Cryptography Kit is released. - * Altered the table in libposixfile.tex a bit. - * Documented socket.gethostname() - * Started completely rewriting the Extending manual. - - * Modules/{Setup.in, gdbmmodule.c}, Doc/{lib,libgdbm}.tex: added - Anthony Baxter's gdbm module (derived from Jack's dbm module) - -Fri Aug 5 11:43:16 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * BUGS: new file (merger of unofficial BUGS1.0.x files) - - * Modules/{Setup.in,Makefile.pre.in}: renamed some modules to - shorter names (dropped the "module" from the name): sunaudiodev, - imgformat, audioop, imageop, imgfile - - * Python/import.c: support *.o/*.so as alternative for - *module.o/*module.so - - * Modules/stropmodule.c (strop_rindex): make rindex('abc', '') do - the right thing (i.e. return 3 instead of 0) - - * Python/bltinmodule.c (builtin_vars): correct typo in error msg - - * Doc/libsocket.tex (subsection{Socket Object Methods}): - documented gethostname() and a few misc things - - * Modules/socketmodule.c: disabled allowbroadcast() socket method - -Mon Aug 1 01:28:29 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Makefile.in (TAGS): Call etags w/o -t option - - * Lib/rfc822.py: fix two bugs: error in readheaders interpreting - regex.match() result, and wrong logic in getfirstmatchingheader() - when the same header occurs twice consecutively - - * Lib/test/test_types.py (6.4.1): test for particular bug in - integer multiply - -Sat Jul 30 13:31:40 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/libsocket.tex, Modules/socketmodule.c: send() and sendto() - now return actual byte count (useful for sockets in non-blocking - mode) - -Tue Jul 26 14:21:17 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * configure.in: check for - - * Objects/longobject.c (newlongobject): fix long(0x80000000) and - add warning that it isn't actually correct on 64-bit machines; - include if HAVE_LIMITS_H is defined - - * Objects/intobject.c (int_mul): check int*int overflow without - resorting to double precision (many thanks to John Tromp) - - * Modules/signalmodule.c (signal_alarm): interface to Posix alarm() - - * Python/ceval.c (call_object): print message before abort() - -Mon Jul 25 11:30:56 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/libstring.tex (section{Standard Module \sectcode{string}}): - documented string.count() - - * Lib/string.py: added count(s, sub, i=0), returns number of - occurrences of sub in s[i:] - - * Doc/keywords.py: program to sort table of keywords in ref2.tex - - * Doc/ref2.tex (subsection{Keywords}): add 'access' and 'lambda' - to list of reserved words - -Thu Jul 14 15:26:14 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * README, Misc/NEWS, Python/patchlevel.h, - Doc/{lib,ext,tut,ref}.tex: bump version to 1.0.3; in README, fewer - references to it elsewhere, nor to IP numbers. - -Wed Jul 13 18:51:36 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/mhlib.py (removefromallsequences): call putsequences with - proper argument - -Mon Jul 11 13:00:36 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/selectmodule.c: don't accept negative file descriptors; - changed error messages slightly - -Thu Jul 7 12:20:10 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/syslogmodule.c: new module by Lance - - * configure.in: don't check for strtod! - - * Python/import.c: undo Mac DL mods (temporarily) and install NeXT - dl mods by William Lewis instead. - - * Modules/posixmodule.c (posix_popen): substitute pclose for - fclose (how did fclose ever creep into this?) - -Wed Jul 6 21:45:54 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/{bdb,cmd,pdb}.py: Mods by Rickard Westman: No longer barfs - on lambda:s (outputs "" as the function name); "a(rgs)" in - pdb now works; help messages added to pdb (lifted from pdb.doc). - Also, "h pdb" calls pdb.help(). cmd.do_help() displays topics on - a nicer way (I think). Also, topics for which there is a help_ - method, but no do_method (like "pdb" above) are displayed in a - special way. My own mod: fix break on function to also support - methods. - -Tue Jul 5 23:18:16 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/stropmodule.c (strop_rindex): change semantics of third - argument -- as in the original string.rindex, search to its right, - not to its left. (Maybe both index and rindex need a 4th - parameter to restrict the search on the other end? - -Mon Jul 4 23:01:36 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/timemodule.c (sleep, floatsleep): don't use setjmp or - signal, rely on err_errno() or sigcheck() instead. - - * Dos/{pcmodule,dosmodule}.c, Modules/posixmodule.c: don't include - - -Sat Jul 2 00:42:47 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/urllib.py: implemented new quoting rules; added splituser, - splitpasswd, splitattr, splitvalue; new ftp syntax (user:passwd, - cwd to each subdir, type={a,i,d}) - -Fri Jul 1 17:32:51 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/traceback.c: add function name to traceback info - - * Object/listobject.c, Modules/{array,mpz}module.c: include - for size_t - -Fri Jul 1 12:47:05 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Makefile.in (Makefile): add dependency on config.status - - * configure.in: support --with-gcc[=value], --without-gcc - - * configure.in, acconfig.h, config.h.in: check for clock_t - - * Modules/{arraymodule,mpzmodule}.c: Include sys/types.h, for size_t - - * Lib/test/test_types.py (6.5.1 Strings): test for nasty string - formatting bug - - * Objects/stringobject.c (formatstring): fix nasty bug in resizing - -Wed Jun 29 10:01:17 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/ref3.tex (section{The standard type hierarchy} - \label{types}): fix typo - - * Lib/packmail.py: applied patch from Lance to remove '.' and '..' - -Tue Jun 28 00:57:35 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/ref1.tex: grammar notation can use single or double quotes now - - * configure.in (termcap): hack around conflict about clear() on - IRIX 5 in shared libraries gl and termcap - - * Python/bltinmodule.c: added callable() predicate - -Wed May 18 15:01:13 1994 Donald Beaudry (don@zippy.vicorp.com) - - * modsupport.c (do_arg): Changed all of the int getting things to - just try to get and int, instead of explicitly checking for an int - first. - - (do_arg): Added the "O&" option to allow using a user supplied - conversion function. - -Wed May 18 14:10:49 1994 Donald Beaudry (don@zippy.vicorp.com) - - * intobject.c (getintvalue): Changed to allow automatic conversion - from any type that supports the nb_int method. - - * floatobject.c (getfloatvalue): Changed to allow automatic - conversion from any numeric type that supports the nb_float - method. - -Wed May 4 22:56:15 1994 Donald Beaudry (don@scooter.vicorp.com) - - * object.h -- Added tp_call member to the typeobject struct - This along with a minor change to the ceval.c allows overloading - of the function call operator for any class. - -Wed May 4 22:23:48 1994 Donald Beaudry (don@scooter.vicorp.com) - - * modsupport.c -- replace the part of getargs that processes "O!", - it had a minor problem with comparing the types. - - * ceval.c -- changed call_object to make use of the tp_call - field. - -Fri Jun 27 17:22:00 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/pythonmain.c: On MPW (3.2) unbuffered seems to hang, so - use setvbuf ... _IOLBF for -u option. - - * Python/mystrtoul.c: MPW hack (overflow check doesn't seem to work) - -Thu Jun 23 14:46:34 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/Makefile.pre.in (clobber): delete config.c and glmodule.c - -Thu Jun 23 00:17:16 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Parser/tokenizer.c: if a triple-quoted string ends in a quote - followed by a newline (followed immediately by the terminating 3 - quotes) then a syntax error or system error ensues (one-line fix) - - * Doc/ref4.tex: clarify that global name space is almost always - containing module's name space - - * Lib/profile.{py,doc}: totally new versions by James Roskind; - also edited source & doc to replace 'jprofile' by 'profile' - - * Modules/posixmodule.c: don't mess with SIGPIPE any more -- this - is now done in Python/pythonrun.c (saves NT dependency here) - - * Modules/Setup.*: removed all except Setup.in (keeping them up to - date was too much of a pain) - - * Python/import.c: don't rely on three-line "dl.h", just copy the - contents. - - * Doc/libtypes.tex (subsubsection{More String Operations.}): - clarified tuple vs non-tuple argument to format strings. - -Wed Jun 22 10:38:22 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/libsocket.tex: clarify the meaning of address for those - methods that or return addresses. - - * Doc/libtypes.tex (subsubsection{File Objects.}): documented - writelines. - -Tue Jun 21 15:54:36 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/aifc.py: avoid calling read(0) - - * Lib/sgi/cddp.py: added some functionality (Sjoerd) - - * Include/modsupport.h: added decl for initmodule2(). - - * Parser/myreadline.c (my_readline): fixed typo in MPW-specific - hack; removed debug fprintfs; added two needed #includes. - -Mon Jun 20 23:46:04 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Objects/fileobject.c (file_read): test for negative read count - was misplaced. - -Mon Jun 18 11:20:00 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * acconfig.h: changed GETPGRP_HAVE_ARGS into GETPGRP_HAVE_ARG - - * Lib/posixpath.py(walk): don't descend down symbolic links - -Thu Jun 16 16:20:12 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/imgformatmodule.c: new module for Jack by Jack - -Tue Jun 14 21:07:00 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Fix bug in 3quoted strings where string ends in quote followed - by newline - -Mon Jun 13 00:24:06 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/multifile.py: added readlines() and read() methods - - * Lib/mimetools.py: added functions to encode/decode standard MIME - Content-transfer-encoding types (as well as uuencode) - - * Lib/mhlib.py: new interface to MH folders and messages - -Sun Jun 12 17:38:31 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/socketmodule.c (sock_listen): fix typo (== instead of =) - -Thu Jun 9 23:33:33 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/compile.c (parsenumber), Python/marshal.c (r_object): - replace strtod() by atof() - -Tue Jun 7 11:41:05 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/lib.tex: added warning about lineii, libposixfile and partparse - - * Lib/bdb.py (clear_all_breaks): this was defined with two - arguments that weren't used and shouldn't have been there - -Mon Jun 6 14:53:05 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/ceval.c (call_trace): Added call to fast_2_locals so - locals_2_fast won't zap locals if the trace function never looks - in f.f_locals; don't XDECREF(f->f_trace) - -Sun Jun 5 13:18:00 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/rfc822.py: Accept lines ending in CR LF as well - -Fri Jun 3 16:37:58 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/profile.py: unspecified improvements by Sjoerd - - * Lib/{bdb,pwd,stdwin/wdb}.py: remove debugger overhead when - continuing with no breakpoints; add set_trace() method and - functions to forcibly enter the debugger - - * Python/ceval.c(eval_code): give the name of the local variable - when LOAD_FAST or DELETE_FAST fails - - * frameobject.[ch], ceval.c: made fast_2_locals and locals_2_fast - global and moved them to frameobject.c. getattr(f, "f_locals") - now calls fast_2_locals and there are fewer other calls to it - -Thu Jun 2 13:50:11 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/ceval.c (call_trace): *p_trace can now be cleared by the - trace function! - - * Modules/{{pwd,grp}module.c,Setup.in}: split pwdmodule.c into pwd - and grp modules (e.g. OS2 seems to have pwd but not grp) - - * Modules/posixmodule.c: OS/2 mods: add #include - - * configure.in: test for existence of link, chown, setuid, setgid; - use std macros for output; require autoconf 1.8 - - * Python/sigcheck.c: sigcheck() for use without signalmodule.c - - * Modules/signalmodule.c: added thread compatibility (only main - thread uses signals); much improved efficiency; intrcheck() - doesn't call sigcheck() but only tests and clears the SIGINT - tripped flag. - - * Lots of places: replace intrcheck() by sigcheck() and remove - following err_set(KeyboardInterrupt). - -Wed Jun 1 11:33:34 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/regexmodule.c (reg_dealloc): remove bogus XDEL's. - -Tue May 31 11:22:47 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/intrcheck.c: removed sigcheck() - - * Python/structmember.c (setmember): test for NULL value - - * frameobject, Python/ceval.c (eval_code): moved trace variable to - frame object so debugging can be switched on later - -Mon May 23 14:44:46 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/newmodule.c: new module, create empty new objects (by - Tommy) - -Fri May 20 09:46:50 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/Makefile: add DVIPS variable with default "dvips -f" - - * Parser/myreadline.c (my_fgets): Fix position of #endif EINTR - -Wed May 18 00:21:05 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/lib.tex: added libfcntl and libposixfile (by Jaap V) - - * Objects/funcobject.c (func_compare): take argcount and argdefs - into account - -Wed May 17 00:00:00 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/import.c: bump MAGIC because of changes below - - * Python/{ceval,compile}.c, Include/frameobject.h: changes to code - objects -- consts/names are tuples, RESERVE_LOCALS instruction - gets tuple of names instead of dictionary -- so code objects are - immutable and thus code and function objects are hashable - - * Objects/listobject.c, Include/listobject.h: added listtuple() -- - convert list to tuple - -Tue May 17 15:40:12 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/ceval.c (getframe): cast current_frame to (object *) - - * Lib/ftplib.py (login): default user='' is translated explicitly - to 'anonymous' - -Wed May 11 10:29:22 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Parser/tokenizer.c (tok_nextc): fix inf loop when file does not - end in newline - - * Modules/sybasemodule.c: new, interface to sybase (John Redford) - - * Modules/signalmodule.c: new, catch unix signals (Lance) - - * Parser/intrcheck.c, Python/ceval.c, Include/ceval.h, - Python/pythonrun.c: prepare for signalmodule.c; add sigcheck() - interface to intrcheck.c, add getframe() interface to ceval.c; - don't override signal handlers in pythonrun.c - -Tue May 10 09:01:06 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/import.c (get_module): print dlopen debug message only of - verbose - -Mon May 9 10:37:48 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * acconfig.h: added _POSIX_THREADS define - - * configure.in: test for -lpthreads; add directory argument to - --with-thread to LIBS as -L option - - * Python/thread.c: split in per-system files (thread.c includes - thread_foobar.h for foobar threads) - - * Objects/stringobject.c (formatstring): don't DECREF result of - strobject() before using it - - * Doc/libtypes.tex: fix typo in table of list methods; clarify - truncation behavior of floating point formatting - - * Doc/ref3.tex: clarify defaults for __repr__, __cmp__ and - __str__; correct (some) descriptions of class constructors - -Fri May 6 11:25:26 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * various files: micro changes needed to compile on Mac; - Grouped more Mac-specific files in Mac subdirectory - - * Lib/*.py: rewrote many functions to use default arguments - instead of arbitrary argument lists - -Thu May 5 12:33:31 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/{cryptmodule.c,Setup.in}: new crypt(3) interface (Steve M) - - * Python/bltinmodule.c, Include/bltinmodule.h: new fn setbuiltin() - to set a built-in variable - - * Python/ceval.c (eval_code): place '_' variable in __builtin__ - instead of in local dictionary, to avoid endless recursion when - printing vars() - -======================================================================== -Release 1.0.3 (14 July 1994) -======================================================================== - -Thu Jul 14 14:38:11 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * copied FAQ 1.10 (which still references 1.0.2 by the way) - -Thu Jul 7 12:20:10 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * configure.in: don't check for strtod! - -Tue Jul 5 23:18:16 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/stropmodule.c (strop_rindex): change semantics of third - argument -- as in the original string.rindex, search to its right, - not to its left. (Maybe both index and rindex need a 4th - parameter to restrict the search on the other end? - -Fri Jul 1 12:47:05 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * configure.in: support --with-gcc[=value], --without-gcc - - * configure.in, acconfig.h, config.h.in: check for clock_t - - * Objects/stringobject.c (formatstring): fix nasty bug in resizing - -Tue Jun 28 00:57:35 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * configure.in (termcap): hack around conflict about clear() on - IRIX 5 in shared libraries gl and termcap - -Thu Jun 23 00:17:16 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Parser/tokenizer.c: if a triple-quoted string ends in a quote - followed by a newline (followed immediately by the terminating 3 - quotes) then a syntax error or system error ensues (one-line fix) - -Sun Jun 12 17:38:31 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/socketmodule.c (sock_listen): fix typo (== instead of =) - -Thu Jun 9 23:33:33 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/compile.c (parsenumber), Python/marshal.c (r_object): - replace strtod() by atof() - -Thu Jun 2 13:50:11 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * configure.in: test for existence of link, chown, setuid, setgid; - use std macros for output; require autoconf 1.8 - -Wed Jun 1 11:33:34 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/regexmodule.c (reg_dealloc): remove bogus XDEL's. - -Tue May 31 11:22:47 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/structmember.c (setmember): test for NULL value - -Fri May 20 09:46:50 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Parser/myreadline.c (my_fgets): Fix position of #endif EINTR - -Wed May 11 10:29:22 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Parser/tokenizer.c (tok_nextc): fix inf loop when file does not - end in newline - -Tue May 10 09:01:06 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/import.c (get_module): print dlopen debug message only of - verbose - -Mon May 9 10:37:48 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * acconfig.h: added _POSIX_THREADS define - - * configure.in: test for -lpthreads; add directory argument to - --with-thread to LIBS as -L option - - * Objects/stringobject.c (formatstring): don't DECREF result of - strobject() before using it - -Fri May 6 11:25:26 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * various files: micro changes needed to compile on Mac; - Grouped more Mac-specific files in Mac subdirectory - -Thu May 5 12:33:31 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/bltinmodule.c, Include/bltinmodule.h: new fn setbuiltin() - to set a built-in variable - - * Python/ceval.c (eval_code): place '_' variable in __builtin__ - instead of in local dictionary, to avoid endless recursion when - printing vars() - -======================================================================== -Release 1.0.2 (4 May 1994) -======================================================================== - -Wed May 4 13:12:00 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * README: version 1.0.2 - - * Objects/fileobject.c (setfilebufsize): less error checking - - * configure.in: test for withval != yes (autoconf 1.8 change) - - * Makefile.in: don't remove config.status on "make clobber" - - * Python/ceval.c (eval_code): removed last traces of killprint (-k - option) - - * Doc/tut.tex: documented some more new stuff - - * Added else clause to try-except. Affected files: - Grammar/Grammar, Include/graminit.h, Python/graminit.c, - Python/compile.c, Doc/ref7.tex, Doc/tut.tex - -Tue May 3 15:21:47 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Misc/python.man: documented -u; undocumented -k - - * Python/{python,frozen}main.c: got rid of -k option; added -u - option (unbuffered stdout/stderr); plus environment - - * Python/import.c: Steven Majewski's mods for AIX - - * Lib/lockfile.py: new module to lock files (using fcntl) - - * Objects/fileobject.c, Include/fileobject.h: added setfilebufsize - function to set buffer size (call only from C when it's safe!) - - * Python/bltinmodule.c (builtin_open): Added 3rd parameter to give - buffer size; default 2nd parameter to "r" - -Mon May 2 17:51:23 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/{al,cd,sv}module.c: added (method) casts to methodlist - initializers - -Thu Apr 28 15:01:50 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/ref2.tex: (section{Line structure}): documented line joining - without backslashes inside parens - -Wed Apr 27 13:15:42 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Misc/python-mode.el: version 1.09 from Tim (grand new - indentation scheme) - - * configure.in: test for setvbuf - - * Python/ceval.c (PRINT_EXPR): assign a non-None value to '_' - before printing it - - * Python/compile.c: only call PRINT_EXPR for interactive code - (start symbol single_input), else call POP_TOP after evaluating an - expression - -Tue Apr 26 16:23:06 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/bltinmodule.c (builtin_reduce): added essential INCREF() - if a third argument is present - - * Doc/tut.tex: added chapter "Recent Additions" - -Mon Apr 25 11:27:09 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/ref7.tex (section{Function definitions}): add missing '}'. - - * Doc/ref2.tex (subsection{String literals}): documented triple - quotes and double quotes. - - * Lib/test/test_grammar.py: added tests for triple-quoted strings - and strings continued with backslash-newline - - * Objects/fileobject.c (writestring): don't do anything when - writing to a Python object while an error is already set - - * Parser/tokenizer.c: added support for triple-quoted strings and - strings continued with backslash - - * Parser/tokenizer.h: moved here from Include - - * Python/compile.c (parsenumber): support triple-quoted strings. - Raise SyntaxError, not SystemError for bad number syntax - -Fri Apr 22 17:39:20 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Objects/{tuple,list,string,mapping}object.c, - Modules/arraymodule.c, Python/compile.c: use new - joinstring(_decref) interface for more compact code - - * Objects/stringobject.c (joinstring): if error, DECREF and zero - result; added joinstring_decref() which XDECREFs its second - argument - -Thu Apr 21 10:59:04 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/libtypes.tex (subsubsection{More String Operations}): - documented new '%(key)s' % {...} formatting and more liberal %s - interpretation (applies str() first) - - * Doc/libfuncs.tex (section{Built-in Functions}): documented new - vars() built-in function - - * Objects/stringobject.c (formatstring): add Donald Beaudry's - patch (slightly changed) to allow '%()' % {...} to - format dictionary entries by key. Also changed %s format to - accept any type and convert it to a string using str() - - * Python/bltinmodule.c: add new built-in function vars() which - returns variables (of which dir() returns the sorted keys()) - -Mon Apr 18 11:00:54 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/libppath.tex (section{Standard Module - \sectcode{posixpath}}): describe for expandvars() - - * Lib/posixpath.py (expandvars): do it using regular expressions - instead of forking of a shell - - * Lib/urllib.py (open_http, open_gopher): diagnose missing - hostname - -Sun Apr 17 21:52:52 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/compile.c (com_atom), Grammar/Grammar (atom): string - literal concatenation -- "abc" 'def' is equivalent to 'abcdef' - -Thu Apr 14 12:36:25 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/test/test_thread.py: new module to test threads (very basic) - - * Python/thread.c: remove #define DEBUG 1 - - * Demo/scripts/freeze.py: changes by Jaap V and my own to make it - work again - - * Makefile.in (libainstall): install frozenmain.c - - * Python/frozenmain.c: added getprogramname() - - * Doc/ref7.tex (section{Function definitions}): describe default - parameter values - - * Lib/test/test_grammar.py: added grammar variants for default - argument expressions - - * Python/compile.c: compile default argument values (com_argdefs - plus related stuff) - - * Python/bltinmodule.c (builtin_apply): require that the argument - list is a tuple - - * Misc/python-mode.el: change by Donald Beaudry to - py-compute-indentation; and fix to that by Sjoerd - -Wed Apr 13 10:08:33 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/ceval.c (eval_code): implement SET_FUNC_ARGS opcode - - * Include/opcode.h: added SET_FUNC_ARGS opcode - - * Objects/funcobject.c (newfuncobject, func_memberlist): added - func_argcount and func_argdefs fields and {get,set}funcargstuff() - functions. - - * Include/funcobject.h: Added func_argcount and func_argdefs - fields and {get,set}funcargstuff() functions. - - * Python/import.c (init_builtin): Give error message if module's - initialization function is NULL (e.g. for 'sys'). - (get_module): Give error message if reloading a dynamically - loadable module. - (reload_module): Give error message if reloading a built-in - module; correctly (I hope) reload a frozen module. - - * Doc/ref6.tex (break and continue): rephrase definition of - restrictions on where these may occur; change rules for continue - to match implementation. - - * Doc/ref4.tex (section{Code blocks, execution frames, and name - spaces}): fix definition of what's local to include deleted - targets; added footnote describing exec and from - import * - restriction. - - * Lib/dis.py: added LOAD_GLOBALS and EXEC_STMT to list of opcodes. - -Tue Apr 12 10:27:19 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/ceval.c (eval_code): fix core dump on "raise ()" -- found - by Tim Peters - -Mon Apr 11 20:48:26 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/compile.c (optimize): added optimization for LOAD_NAME - suggested by Steve Majewski - - * Python/ceval.c (eval_code: case DELETE_FAST): fix cut-paste - error (w should be x) found by Steve Majewski - -Tue Mar 22 15:37:06 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/profile.py: fix handle_return for exceptional case (fix - suggested by Jim Roskind) - - * Lib/tzparse.py (tzprog): Fix typo in test for regex.match - - * Lib/urlopen.py: renamed to Lib/urllib.py - -Thu Mar 17 01:24:29 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/urlopen.py: added quote() and unquote() functions - -Wed Mar 16 11:26:29 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Objects/mappingobject.c: allow dictionaries with more than - 20,000 entries. - -Thu Mar 10 11:13:24 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/{pdb,profile,bdb,codehack,stdwin/wdb}.py: - codehack.getcodename() is obsolete now we have co.co_name; same - for getfuncname(): f.func_name. Module codehack is still needed - for getlineno(), used in profile and pdb - -Tue Mar 8 10:37:21 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/modsupport.c (do_arg): Format "O!" means typechecked - object; pointer argument must be preceded by typeobject - - * Modules/threadmodule.c: don't define exit_prog if NO_EXIT_PROG - is defined - - * Python/thread.c: don't define [_]exit_prog if NO_EXIT_PROG is - defined; in the SGI version, don't use signals if exit_prog is - node defined defined; in the SGI version, waitpid() for exited - threads. - - * Python/pythonrun.c: don't call [_]exit_prog if NO_EXIT_PROG is - defined - - * Include/thread.h: define NO_EXIT_PROG and then don't define - [_]exit_prog - - * Modules/dbmmodule.c: Add calls to dbm_clearerr() after error on - assignment (fix by Jack) - -Mon Mar 7 12:41:32 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/test/test_rgbimg.py: search test file along sys.path - - * Lib/test/test_{b1,b2,grammar}.py: tests for indefinite sequences - - * Python/{bltinmodule,ceval}.c: Changed implied and explicit loops - over sequences to allow for "indefinite" sequences a la Steve - Majewski. Instead of iterating over 0, 1, 2, ..., len(a)-1, we - now iterate over 0, 1, 2, ..., until we get an IndexError - exception (other exceptions are still errors). This affects the - semantics of the following language constructs: "for x in a: ...", - "x in a", "x not in a", and the following built-in functions: - filter(), map(), max(), min(), reduce(). - - * Doc/ref6.tex (section{Assignment statements}): clarify slice - assignment; (section{The {\tt break} statement}): fix typo - - * Doc/ref5.tex (subsection{Identifiers (Names)}): clarify - difference between local and global - - * Doc/ref2.tex (subsection{String literals}): fix typo in def of - escapeseq - - * Lib/addpack.py: new module to add packages to sys.path - - * Lib/urlopen.py: added basejoin() function - -Fri Mar 4 13:07:43 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/urlopen.py(open_ftp): avoid crash when no host given - -Wed Mar 2 10:33:39 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/ceval.c (eval_code): use sys.check_interval to reset the - ticker - - * Lib/repr.py: added special case for class instances (which may - cause exceptions in their __repr__) - - * Lib/pdb.{py,doc}: mod by Steve Kirsch to allow setting a break - on a function name - -Tue Mar 1 10:32:54 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/pythonrun.c (run_tty_1): Fix wrong (uninitialized) return - value - - * Doc/ref4.tex (table 4.1): differentiated between exec stmt and - eval() - -Mon Feb 28 10:49:20 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/svmodule.c: correct wrong cast of svideo_getattr - - * README: added Linux to list of supported systems. - - * Doc/libsocket.tex: adapt to min value of 1 for listen() backlog - argument. - - * Modules/socketmodule.c (sock_listen): ensure backlog argument is - at least 1. - -Fri Feb 25 14:25:30 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Include/osdefs.h, Modules/config.c.in: Added NT case (same as - MSDOS) - -Thu Feb 24 09:58:53 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/posixmodule.c: merged in NT changes by Jaap Vermeulen - - * README: added Mac and PC platforms to blurb. - - * Doc/libfuncs.tex (section{Built-in Functions}): documented - xrange() - - * Doc/ref7.tex (section{Function definitions} added index entry - for second ref to lambda. - - * Lib/{bdb.py,pdb.py,stdwin/wdb.py}: call linecache.checkcache() - in bdb.Bdb's reset method; remove it from the test() functions. - -Wed Feb 23 10:15:28 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/parsermodule.c (parser_parsefile): fix fatal typo in - NULL comparison - - * Misc/python.man: fixed mess describing -d and -i options - -Tue Feb 22 09:08:22 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Demo2: added new subdirectory holmes, with Mark Lutz' expert - system shell - - * Demo: added new subdirectory lutz, with Mark Lutz' examples - (e.g. psh.py, a nice enhanced Python shell!!!) - - * Lib/os.py: added listdir for Windows NT - - * Modules/timemodule.c, Parser/intrcheck.c: changes for Windows NT - by Jaap Vermeulen (#ifdef _M_IX86) - - * Makefile.in (inclinstall): added variable INCLUDEPY to specify - where the include files are installed - - * Modules/nismodule.c (nisproc_maplist_2): cast some args to - (caddr_t) as required on some systems - - * Objects/mappingobject.c (getmappingitems): correct typo (called - _values instead of _items) - -Mon Feb 21 17:07:07 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/rfc822.py: added access as a dictionary - - * Lib/urlopen.py: new module to access arbitrary files designated - by a URL (Universal Resource Locator) - - * Lib/{httplib,gopherlib}.py: new modules to interface to HTTP - and gopher servers - - * Lib/rfc822.py: moved _monthnames to where it is used; add some - blank lines - -Fri Feb 18 09:54:34 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/sgi/flp.py: avoid using time.milli{sleep,timer} - - * Lib/stdwin/WindowSched.py: avoid using time.milli{sleep,timer} - -- still maintain time in milliseconds though - - * Lib/sched.py: remove references to milli{timer,sleep} from comments - - * Lib/os.py: made execvp more portable; added os.pathsep and - os.defpath - -Thu Feb 17 12:53:33 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/ftplib.py(FTP.makeport): call listen(1) instead of listen(0) - so it works on Solaris 2 - - * Modules/makesetup: reverse order of DEFS so first Setup file can - override; any non-cpp uppercase option is sent to the linker - -Wed Feb 16 10:26:59 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Objects/fileobject.c: add name, mode, softspace and closed - attributes (softspace is also writable). - - * configure.in: in --verbose mode, don't hide compiler output - -======================================================================== -Release of 1.0.1 (Feb 15 1994) -======================================================================== - -Tue Feb 15 11:32:42 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/string.py (atof): force the result to be float - - * Python/modsupport.c (do_arg): don't use a local object va -- - this doesn't work on some compilers (e.g. WATCOM) - -Mon Feb 14 10:52:01 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/dospath.py: proper version by Jaap Vermeulen - - * Makefile.in (Makefiles): add semicolon after ) which some Make - versions need - - * Doc/libposix.tex: added doc for posix.fdopen - - * README: add Sequent and NeXT to list of platforms; add - troubleshooting section; add hist about -Dindex for readline - - * Lib/os.py: generalize to many os specific modules using a - dictionary - - * Lib/ospath.py: now obsolete; use os.name to import the right one - - * configure.in: change order of -lsocket and -lnsl and insert - -linet in between, so it works on Sequent (it still works on - Solaris 2 -- hope it still works elsewhere as well); add test for - _NEXT_SOURCE (then define _POSIX_SOURCE); remove test for dlopen; - - * configure.in, acconfig.h, */modsupport.[ch]: rename - HAVE_VARARGS_PROTOTYPES to HAVE_STDARG_PROTOTYPES, to avoid - confusion - - * Include/modsupport.h: no prototypes for getargs() and mkvalue() - in case no varargs prototypes - - * Lib/test/test_grammar.py: don't import sleep from time, but time - (since sleep has portability problems) - -Fri Feb 11 23:47:46 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Parser/intrcheck.c: added QUICKWIN version (doesn't really - work); fixed MSDOS version to also set a SIGINT handler. - - * Modules/timemodule.c (time_sleep): declare sigsave 'auto' hoping - this will avoid restoring its pre-setjmp value. On non-threaded - systems declare it 'static' since at least Microsoft C still puts - the auto variable in a register causing a bug... Also implement - the MSDOS version of floatsleep() using a busy-wait loop calling - intrcheck() - -Wed Feb 9 11:43:11 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Lib/rfc822.py: added parsedate() and parseaddr() utility - functions and getdate(), getaddr(), getaddrlist() methods; added - test code when run as script - - * Include/pythonrun.h, Python/pythonrun.c: cleanup() is now - externally visible, for the benefits of embedded use. - - * Lib/dospath.py: new module for dos stuff - -Mon Feb 7 09:50:16 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/makesetup: add -n option between Setup files (suppresses - making of .o files but keeps processing of libraries and module - names) - - * Makefile.in (libainstall): install Setup, makesetup, config.c.in - - * Modules/Setup*: added -lX11_s to line for gl module - - * Demo/scripts/unbirthday.py: new script, print unbirthday count - - * Modules/audioopmodule.c: removed hack for signed on sun - (there's now a test in the configure script); check that if - 'signed' is defined away characters aren't unsigned - - * Modules/posixmodule.c: include mytime.h (for clock_t on NeXT) - - * acconfig.h: add entry for 'signed' keyword - - * configure.in: remove const from check for exec prototypes; add - check for signed keyword and check for whether chars are unsigned - -Fri Feb 4 13:07:03 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/makesetup: added usage message, -c and -m options to - specify config.c.in and Makefile.pre input files, -s option to - specify source directory, added comments - - * Modules/Setup.in: remove -lm from imgfile entry - - * Modules/nismodule.c: only define YPPROC_MAPLIST, YPPROG and - YPVERS if not already defined - - * configure.in, acconfig.h, Include/modsupport.h, - Python/modsupport.c: added separate check for varargs prototypes - (HAVE_VARARGS_PROTOTYPES) - -Thu Feb 3 11:00:26 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/bltinmodule.c (filterstring): fix core dump of func == - None - - * Lib/string.py: replace atoi_error, atof_error, atol_error by - ValueError when the strop versions are used - - * Modules/stropmodule.c: added atol(), added optional base - argument to atoi() and atol() - - * Objects/longobject.c, Include/longobject.h: added long_escan - (like long_scan but raises exception for bad base and stores end - of string into return argument) - - * Objects/rangeobject.c (range_repr): repr must use "xrange..." - -Wed Feb 2 12:28:04 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/stropmodule.c: added atoi() and atof() - - * Python/modsupport.c: use stdarg.h / varargs.h depending on - presence of prototypes - - * Modules/timemodule.c (floattime): try ftime() or time() if - gettime() fails - -Tue Feb 1 14:41:04 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/Makefile (python-lib.info): change makeinfo option style - from +foo to --foo - - * Doc/README: remove invalid reference to ../misc/FTP; update - description of making the info version - - * Doc/{fix.el,fix_hack,whichlibs}: minor updates/corrections - -Mon Jan 31 11:16:38 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/import.c: only use shared libraries if HAVE_DLOPEN *and* - HAVE_DLFCN_H are defined; define symbol USE_SHLIB then - - * Doc/tut.tex: lots of small changes by Tim Peters: typos, - out-of-date examples, restrictions lifted, new and better ways to - do some things... - -Fri Jan 28 10:59:48 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * README: added Minix note - - * Lib/sunau.py: correct byte count calculation from frame rate - - * Lib/aifc.py: rate should be an integer - -Thu Jan 27 12:55:17 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/ext.tex: removed obsolete reminder in line 1; correct typo - - * Misc/FAQ: fixed some out of date info, added question on module - run as script - - * Modules/rgbimgmodule.c (initrgbimg): exception string should - contain dot not comma - - * Modules/md5module.c: fix compiler warnings about (unsigned) char - - * Makefile.in: libinstall and maninstall should use $(srcdir) - - * Lib/tzparse.py: don't run test() on import - - * Lib/filewin.py: moved into Lib/stdwin - - * Modules/cdmodule.c: fix wrong cast of cdparser_getattr - -======================================================================== -Release of 1.0.0 (Jan 26 1994) -======================================================================== - -Wed Jan 26 14:13:39 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/tut.tex: updated version number in invocation example - - * Doc/Makefile: update destination of texi2html - - * Misc/FAQ: updated for release 1.0.0 - - * Misc/NEWS: created -- all bits of news - - * Misc/HISTORY: added (from old releases) - - * Misc/README: documented some new files - - * README: non-beta version and preface, don't ref TODO - - * Makefile.in: got rid of references to TODO - - * Python/version.c, Doc/???.tex: updated version and date - -Tue Jan 25 20:11:49 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/ext.tex: revamped, finally ready for release - - * Doc/{Makefile,myformat.perl}: support latex2html (0.5.1) - - * README: correct typo on DL_DIRECTORY - -======================================================================== -Release of 1.0.0 BETA 6 (Jan 24 1994) -======================================================================== - -Mon Jan 24 16:37:46 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Doc/ref?.tex: Change \verb\\ into \verb@@ so - latex2html doesn't crash - -Thu Jan 20 18:05:18 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Ext-dummy/, README, Makefile.in: Created new directory - Ext-dummy/. Ext-dummy/ contains its own README and copies of - Extensions/mk{ext,mf}.py. - -Tue Jan 18 11:04:16 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/getmtime.c: Include config.h if we have it - - * Modules/Setup.in: fixed comments about GMP version - - * Modules/nismodule.c: define YPPROC_MAPLIST, YPPROG, YPVERS as - plain integer literals, to make it work on 64 bit machines - - * Parser/grammar.c (translabel): remove redundant decl of strchr() - (which caused trouble on AIX) - -Sun Jan 16 14:13:13 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * configure.in: test for fcntl.h - - * Modules/posixmodule.c: include fcntl.h if it exists - -Fri Jan 14 17:35:33 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * configure.in: check for sys/time.h; substitute and check for AR; - check for nice() - - * Makefile.in: make python .PRECIOUS; define OPT=-O and pass it to - submakes - - * */Makefile*in: set OPT=-O; set AR=@ar@ - - * Modules/Setup.minix: new - - * Lib/audiodev.py: only import system specific modules if needed - -Thu Jan 13 16:40:28 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/flmodule.c: make type objects static - - * Modules/almodule.c: make type objects static - - * Makefile.in: add rule to build Makefile; add VPATH for that; - remove dependency on configure script (you can run 'make autoconf' - instead); add Lib/test to path for test target; - - * Lib/test: new subdirectory, holds all test modules - -Wed Jan 12 10:17:41 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * acconfig.h: added HAVE_ALTZONE - - * configure.in: test for altzone; check for working - termcap/termlib when --with-readline used; don't test for readline - function; send errors to stderr - - * Lib/test_grammar.py: fix 64-bit int test for max negative int - - * Python/import.c (get_module): call dlerror() when dlopen() fails - (also some layout changes) - -Tue Jan 11 10:56:00 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Python/import.c: use RTLD_NOW (define as 2 if undefined) - - * Makefile.in: "make (local)clean" shouldn't bother about Include; - added .PRECIOUS: config.status - - * Modules/md5.h: define PROTOTYES as 1 if HAVE_PROTOTYPES is - defined - - * Modules/md5module.c: grand cleanup - - * Modules/Setup.sgi: renamed to Setup.irix4 - - * Modules/Setup.sunos5: renamed to Setup.solaris2 - - * Modules/Setup.in: some makes (e.g. Ultrix) don't strip trailing - whitespace from variable definitions -- make sure there isn't any - in the defs used to generate PYTHONPATH - - * Many modules and objects: use 'staticforward' where needed - - * Include/object.h: added #define 'staticforward' as either static - or extern depending on BAD_STATIC_FORWARD - - * acconfig.h: added BAD_STATIC_FORWARD - - * configure.in: added test for bad static forward - -Mon Jan 10 10:35:21 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/md5module.c: SCO ODT 3.0 dependent fix - - * Objects/xxobject.c: quote size fields as tp_basicsize instead of - (incorrectly) tp_size - - * Objects/listobject.c (cmp): arguments must be const!!! - - * Modules/imageopmodule.c: another attempt at casting away - warnings about changed semantics in ANSI C - - * Modules/regexpr.c: cast away warning about changed semantics in - ANSI C - - * Modules/Makefile.pre.in: add LIBC_S (shared version of -lc, to - be figured out by configure) - - * README, Python/version.c: version 1.0.0 BETA 6 - - * README: fixed description of Setup (which was buried under the - SVR4 exception!); added description of --prefix, --exec-prefix, - --with-libm and --with-libc - - * configure.in: added --with-libc=... and --with-libm=... - - * Modules/Makefile.pre.in: Remove dependency of Setup on Setup.in, - so it is only copied when Setup does not exist at all; add - prefix=/usr/local so Setup can base default path on --prefix - option to toplevel configure script - - * Modules/Setup.in: clarified build procedure in comments; don't - include GNN's timing module by default; use $(prefix) instead - requiring manual edit of DESTDIR - - * Makefile.in: replace DESTDIR by prefix and exec_prefix and - updated affected targets; added inclinstall and libainstall - targets - - * Objects/accessobject.c: removed (???) from comment to avoid - trigraph warning - - * Makefile.in (libinstall): correct typo: (D)DESTDIR - -Fri Jan 7 10:34:43 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * README: describe --with-sgi-dl and --with-dl-dld - - * Python/Makefile.in: compile import.c with -I$(DLINCLDIR) - - * Python/import.c: check for WITH_SGI_DL and WITH_DL_DLD - - * acconfig.h: added WITH_SGI_DL and WITH_DL_DLD - - * configure.in: added --with-sgi-dl=DIR and - --with-dl-dld=DIR,DIR; now require --with-readline=DIR and test - for existing directory - - * Lib/test_audioop.py: new module to test (you guessed it) audioop - - * Modules/audioopmodule.c: got rid of adpcm32lin and lin2adpcm3 -- - Jack says they're not useful - -======================================================================== -Release of 1.0.0 BETA 5 (Jan 6 1994) -======================================================================== - -Thu Jan 6 13:36:32 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * readline/Makefile: remove some cruft so it works with VPATH - - * Lib/aifc.py: remove dependencies on AL (Sjoerd) - - * README: describe new Setup procedure - - * Modules/Makefile.pre.in: copy Setup from $9srcdir)/Setup.in so - it *really* works with VPATH - - * Modules/Setup: renamed to Modules/Setup.in - - * Python/pythonmain.c (realmain): fclose script file - - * Python/import.c (get_module): fix important leak: close the .py - file after parsing! - - * README, Python/version.c: version 1.0.0 BETA 5 - -Wed Jan 5 16:42:35 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Modules/rgbimgmodule.c: Only include if it exists - - * Modules/timemodule.c: don't include sys/time.h on the Mac - - * Modules/stdwinmodule.c (initstdwin): don't fuss with sys.argv on - the mac -- so {check,putback}stringlist aren't needed there - - * Parser/intrcheck.c: Make sure is included before - any other include file - - * Modules/audioopmodule.c: include math.h after allobjects.h (so - the latter can be a precompiled header file on the Mac) - -Wed Jan 5 15:34:26 1994 Guido van Rossum (guido@poseidon.cwi.nl) - - * Python/pythonrun.c (sighandler): only call kill(getpid()) if - getpid() exists; otherwise call exit(1) - - * configure.in: added test for getpid() - - * Modules/config.c.in: Changes for Macintosh: new default path, - call wargc() in main(); 1994 copyright - - * Python/frozenmain.c: added declarations for getversion() and - getcopyright() (foei!); insert "Python " before version on banner - - * Python/pythonmain.c: added declarations for getversion() and - getcopyright() (foei!); default startupfile to "PythonStartup" on - Macintosh; add fclose(fp) for startupfile; insert "Python " before - version on banner - -======================================================================== -Release of 1.0.0 BETA 4 (Jan 5 1994) -======================================================================== - -Wed Jan 5 01:21:59 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * README, version.c: bumped version to 1.0.0 BETA 4 - - * README: removed all references to --with-solaris; updated list - of files and directories - - * Modules/sunaudiodevmodule.c: define SOLARIS if - HAVE_SYS_AUDIOIO_H is defined - - * Python/thread.c: define SOLARIS if HAVE_THREAD_H is defined - - * configure.in: added test for (SOLARIS thread - interface); remvoe test for --with-solaris - -======================================================================== -Release of 1.0.0 BETA 3 (Jan 5 1994) -======================================================================== - -Wed Jan 5 00:18:45 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * {Parser,Objects,Python,Makefile}/Makefile*in: made depend target - work with VPATH - - * README: describe new build procedure; added section on building - for multiple architectures - - * acconfig.h: fix (reversed!) comment for SYS_SELECT_WITH_SYS_TIME - - * Modules/Makefile.pre.in: copy Setup from $(srcdir) if not - present, and use local Setup as input for makesetup script - -Tue Jan 4 12:32:16 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Note that there are no functional changes below -- just changes - to the build process and changes to avoid compiler warnings - - * Modules/Setup: disable nis as well by default, change the - pertaining comments, and change the comments about the multimedia - modules to be default on - - * fixed all warnings about function pointer initializations, and - miscellanous other warnings (e.g. about extern forward references - to static variables); touched random bits of code as a consequence - - * changed configuration process and Makefiles to support VPATH; - for this, config.h(.in) now lives to the toplevel directory, the - toplevel Makefile is now created by configure as well, and various - improvements to it have been made (e.g. working tags and TAGS - targets), the makesetup script follows configure instead of - preceding it, it understands srcdir and has an exception for - glmodule.c, the intermediate file is called Makefile.pre, the - Makefiles don't use TOP any more and are much more careful about - the difference between .. and the toplevel directory, and I've - improved my understanding of how configure handles srcdir - - * Modules/threadmodule.c: refuse to compile when WITH_THREAD is not - defined - - * configure.in, acconfig.h, config.h.in, Include/ceval.h, - Modules/{stdwin,thread}module.c, Python/{ceval,pythonrun}.c: - renamed USE_THREAD to WITH_THREAD - - * configure.in: add AC_PROG_INSTALL - - * README, Python/version.c: version set to 1.0.0 BETA 3 - - * Demo, Include, Lib: added Makefile with clean/clobber targets - - * README: added remarks on --with-svr4; unnumber special cases - - * configure.in: only look for -lnsl and -lsocket if --with-svr4 is - specified, to avoid linking with them on IRIX 5 - -======================================================================== -Release of 1.0.0 BETA 2 (Jan 3 1994) -======================================================================== - -Mon Jan 3 22:21:24 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * Include/myselect.h: fix typo in name of SYS_SELECT_WITH_SYS_TIME - - * Parser/pgen.h: moved here from Include; removed extern - definition of 'gram' - - * Parser/acceler.c: include node.h, now needed by parser.h - - * README: added paragraph on testing - - * Misc/python.man: changed date and add 1994 copyright - - * Makefile: added test target - - * Python/thread.c: include config.h if needed - - * Parser/parser.h: remove references to struct _grammar and - similar things - - * Modules/rotormodule.c (RTR_e_char, RTR_d_char): avoid warnings - by picky compilers about unsigned % signed - - * README: added a section on building it for non-UNIX systems - - * Makefile (configure): call autoheader when calling autoconf - - * Include/config.h.in: now generated by autoheader - - * acconfig.h: new file (input for autoheader) - - * configure.in: added AC_REVISION call to top - - * Modules/flmodule.c (form_setattr): one NULL should be 0 - - * Include/myselect.h: this now implies mytime.h and attempts to - work around systems where sys/select.h and sys/time.h can't be - included together - - * Modules/socketmodule.c, Doc/libsocket.tex: remove socket avail() - method -- you can use select instead - - * Modules/Setup: disable dbm, it is not truly portable - - * Lib/sunau.py: incorporate one-line fix by Sjoerd - - * Include/pgenheaders.h: include if its symbol - defined, not just on the mac - - * Include/grammar.h: remove redundant structure tags - - * Include/cgensupport.h: avoid possible macro argument - substitution inside string literal - - * configure.in, Include/config.h.in: add test whether sys/select.h - and sys/times.h can be included by the same program - - * Include/config.h.in: add lines for HAVE_SYS_UN_H and - HAVE_GETPEERNAME - - * Extensions/mkext.py: copy change in library order from - Modules/Makefile.in.in - - * Modules/Makefile.in.in: change library order subtly so -ltermcap - follows instead of precedes -lgl_s on SGI systems; this solves - (hides?) problems with clashing entry points - - * configure.in: added sys/un.h to list of tested header files; - added getpeername to list of tested functions (both for - Modules/socketmodule.c) - - * Modules/socketmodule.c: conditionally include sys/un.h and - change tests for AF_UNIX to tests for HAVE_SYS_UN_H; test for - HAVE_GETPEERNAME instead of NO_PEERNAME - - * Modules/config.c.in: add marshal and __main__ built-in modules - - * Python/sysmodule.c (list_builtin_module_names): sort the list - - * Doc/Makefile: remove 'qua' from default targets - - * Doc/README: add reference to ext.tex, change reference to - lib*.tex, explain that qua isn't built by default - - * README: explain DESTDIR, clarify install procedure, add more - explanation to some options, add description of ChangeLog, add - wuarchive.wustl.edu to list of mirror sites - - * Modules/socketmodule.c: make AF_UNIX code dependent on existence - of AF_UNIX (SCO ODT 3.0 doesn't support it -- let's hope it - doesn't define the symbol either) - - * Makefile: attempt to fix install targets (added separate - libinstall and maninstall) - - * Doc/libregex.tex: documented Tracy Tims' changes - - * Modules/regexpr.c: redid Tracy Tims' changes to minimize diffs - (only two added lines now) - - * Modules/regexmodule.c: fix core dump when asking a plain regex - object for a named group - -Sun Jan 2 23:10:44 1994 Guido van Rossum (guido@voorn.cwi.nl) - - * README, Python/version.c: changed version string to 1.0.0 BETA 2 - - * Modules/{regexpr.{c,h},regexmodule.c}: merged in Tracy Tims' - mods for named subexpressions - - * Include/regexpr.h: moved to Modules/regexpr.h - - * Modules/timingmodule.c: change tests for no arguments - - * configure.in: remove strtoul from AC_REPLACE_FUNCS; remove - initial blank line (which got copied into configure so it wouldn't - start with #!/bin/sh as required) - - * Python/compile.c: call mystrto(u)l instrad of strto(u)l - - * Python/Makefile.in: add mystrtoul.c to OBJS - - * Python/mystrtoul.c: renamed from strtol.c; renamed functions to - mystrto(u)l; this is now a standard source file (since some - systems have a strto(u)l that doesn't report errors properly) - - * Modules/Setup: added entry for timing module - - * Modules/{timing.h,timingmodule.c}: new files implementing GNN's - timing module - -======================================================================== -Release of 1.0.0 BETA (Jan 1 1994) -======================================================================== diff --git a/Demo/Makefile b/Demo/Makefile deleted file mode 100644 index b70dc12f9b..0000000000 --- a/Demo/Makefile +++ /dev/null @@ -1,12 +0,0 @@ -all: - @echo Nothing to make in this directory. - -clean: - find . '(' -name '*.pyc' -o -name '*.fdc' \ - -o -name core -o -name '*~' \ - -o -name '[@,#]*' -o -name '*.old' \ - -o -name '*.orig' -o -name '*.rej' \ - -o -name '*.bak' ')' \ - -print -exec rm -f {} ';' - -clobber: clean diff --git a/Demo/README b/Demo/README deleted file mode 100644 index 4fd095ada1..0000000000 --- a/Demo/README +++ /dev/null @@ -1,53 +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. - - -classes Some examples of how to use classes. - -embed An example of embedding Python in another application. - -ibrowse An Emacs info file browser (uses stdwin). - See also ../doc (the Python library documentation can - be converted to info format). - -md5test Test program for the optional md5 module. - -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'. - -sgi Demos that only run on Silicon Graphics machines. - These require at least one of the optional built-in - modules that only make sense for the SGI, such as - 'gl', 'al', and 'sv'. Split in subdirectories - per subject. - -stdwin Demos that use the STDWIN library. Require the 'stdwin' - built-in module. - -threads Demos that use the 'thread' module. (Currently these - only run on SGIs, but this may change in the future.) - -tkinter Demos using the Tk interface (including Matt Conway's - excellent set of demos). - -www An old, abandoned collection of WWW utilities. - - ---Guido van Rossum, CWI, Amsterdam - diff --git a/Demo/classes/Complex.py b/Demo/classes/Complex.py deleted file mode 100755 index 5ac6b186c6..0000000000 --- a/Demo/classes/Complex.py +++ /dev/null @@ -1,288 +0,0 @@ -# Complex numbers -# --------------- - -# 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) -# -# 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. -# (I suppose it would be easy to implement a cmath module.) -# -# 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 types, math - -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 type(obj) == types.TupleType: - return apply(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 - else: - return obj - -def Im(obj): - if IsComplex(obj): - return obj.im - else: - return obj - -class Complex: - - def __init__(self, re=0, im=0): - if IsComplex(re): - im = i + Complex(0, re.im) - re = re.re - if IsComplex(im): - re = re - im.im - im = im.re - 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) - mod = sys.maxint + 1L - return int((hash(self.re) + 2L*hash(self.im) + mod) % (2L*mod) - mod) - - def __repr__(self): - if not self.im: - return 'Complex(%s)' % `self.re` - else: - return 'Complex(%s, %s)' % (`self.re`, `self.im`) - - def __str__(self): - if not self.im: - return `self.re` - else: - return 'Complex(%s, %s)' % (`self.re`, `self.im`) - - def __neg__(self): - return Complex(-self.re, -self.im) - - def __pos__(self): - return self - - def __abs__(self): - # XXX could be done differently to avoid overflow! - return math.sqrt(self.re*self.re + self.im*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: raise TypeError, 'Complex to the Complex power' - 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 checkop(expr, a, b, value, fuzz = 1e-6): - import sys - print ' ', a, 'and', b, - try: - result = eval(expr) - except: - result = sys.exc_type - print '->', result - if (type(result) == type('') or type(value) == type('')): - ok = result == value - else: - ok = abs(result - value) <= fuzz - if not ok: - print '!!\t!!\t!! should be', value, 'diff', abs(result - value) - - -def test(): - 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), 'TypeError'), - (Complex(0,10), 1, Complex(0,10)), - (Complex(0,10), Complex(1), Complex(0,10)), - (Complex(1), Complex(0,10), 'TypeError'), - (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), - ], - } - exprs = testsuite.keys() - exprs.sort() - for expr in exprs: - print expr + ':' - t = (expr,) - for item in testsuite[expr]: - apply(checkop, t+item) - - -if __name__ == '__main__': - test() diff --git a/Demo/classes/Dates.py b/Demo/classes/Dates.py deleted file mode 100755 index 7f55d24df5..0000000000 --- a/Demo/classes/Dates.py +++ /dev/null @@ -1,218 +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 . - -# 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 - -# 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: ' + `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: ' + `month` - dim = _days_in_month( month, year ) - if not 1 <= day <= dim: - raise ValueError, 'day must be in 1..' + `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 ' % ( - 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 ' + `type(n)` + ' to date' - 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] ) - -DateTestError = 'DateTestError' -def test( firstyear, lastyear ): - a = Date(9,30,1913) - b = Date(9,30,1914) - if `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 diff --git a/Demo/classes/Dbm.py b/Demo/classes/Dbm.py deleted file mode 100755 index 8d7fe0f8f4..0000000000 --- a/Demo/classes/Dbm.py +++ /dev/null @@ -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 = `key` + ': ' + `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[`key`]) - - def __setitem__(self, key, value): - self.db[`key`] = `value` - - def __delitem__(self, key): - del self.db[`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(`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 == None: - del d[key] - else: - d[key] = value - except KeyboardInterrupt: - print '' - print d - except EOFError: - print '[eof]' - break - print d - - -test() diff --git a/Demo/classes/README b/Demo/classes/README deleted file mode 100644 index cca7524891..0000000000 --- a/Demo/classes/README +++ /dev/null @@ -1,14 +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() -Rat.py Rational numbers -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 -- especially the window -modules are full of them.) diff --git a/Demo/classes/Range.py b/Demo/classes/Range.py deleted file mode 100755 index 18f626f458..0000000000 --- a/Demo/classes/Range.py +++ /dev/null @@ -1,71 +0,0 @@ -# Example of a generator: re-implement the built-in range function -# without actually constructing the list of values. (It turns out -# that the built-in function is about 20 times faster -- that's why -# it's built-in. :-) - - -# Wrapper function to emulate the complicated range() arguments - -def range(*a): - if len(a) == 1: - start, stop, step = 0, a[0], 1 - elif len(a) == 2: - start, stop = a - step = 1 - elif len(a) == 3: - start, stop, step = a - else: - raise TypeError, 'range() needs 1-3 arguments' - return Range(start, stop, step) - - -# Class implementing a range object. -# To the user the instances feel like immutable sequences -# (and you can't concatenate or slice them) - -class Range: - - # initialization -- should be called only by range() above - def __init__(self, start, stop, step): - if step == 0: - raise ValueError, 'range() called with zero step' - self.start = start - self.stop = stop - self.step = step - self.len = max(0, int((self.stop - self.start) / self.step)) - - # implement `x` and is also used by print x - def __repr__(self): - return 'range' + `self.start, self.stop, self.step` - - # implement len(x) - def __len__(self): - return self.len - - # implement x[i] - def __getitem__(self, i): - if 0 <= i < self.len: - return self.start + self.step * i - else: - raise IndexError, 'range[i] index out of range' - - -# Small test program - -def test(): - import time, __builtin__ - print range(10), range(-10, 10), range(0, 10, 2) - for i in range(100, -100, -10): print i, - print - t1 = time.time() - for i in range(1000): - pass - t2 = time.time() - for i in __builtin__.range(1000): - pass - t3 = time.time() - print t2-t1, 'sec (class)' - print t3-t2, 'sec (built-in)' - - -test() diff --git a/Demo/classes/Rat.py b/Demo/classes/Rat.py deleted file mode 100755 index 7553745706..0000000000 --- a/Demo/classes/Rat.py +++ /dev/null @@ -1,103 +0,0 @@ -# Rational numbers - -from types import * - -def rat(num, den): - if type(num) == FloatType or type(den) == FloatType: - return num/den - return Rat(num, den) - - -def gcd(a, b): - while b: - a, b = b, a%b - return a - - -class Rat: - - def __init__(self, num, den): - if den == 0: - raise ZeroDivisionError, 'rat(x, 0)' - if type(den) == FloatType or type(num) == FloatType: - g = float(den) - else: - g = gcd(num, den) - self.num = num/g - self.den = den/g - - def __repr__(self): - return 'Rat(%s, %s)' % (self.num, self.den) - - def __str__(self): - if self.den == 1: - return str(self.num) - else: - return '%s/%s' % (self.num, self.den) - - def __cmp__(a, b): - c = a-b - if c.num < 0: - return -1 - if c.num > 0: - return 1 - return 0 - - def __float__(self): - return float(self.num) / float(self.den) - - def __long__(self): - return long(self.num) / long(self.den) - - def __int__(self): - return int(self.num / self.den) - - def __coerce__(a, b): - t = type(b) - if t == IntType: - return a, Rat(b, 1) - if t == LongType: - return a, Rat(b, 1L) - if t == FloatType: - return a, Rat(b, 1.0) - if t == InstanceType and a.__class__ == b.__class__: - return a, b - raise TypeError, 'Rat.__coerce__: bad other arg' - - def __add__(a, b): - return rat(a.num*b.den + b.num*a.den, a.den*b.den) - - def __sub__(a, b): - return rat(a.num*b.den - b.num*a.den, a.den*b.den) - - def __mul__(a, b): - return rat(a.num*b.num, a.den*b.den) - - def __div__(a, b): - return rat(a.num*b.den, a.den*b.num) - - def __neg__(self): - return rat(-self.num, self.den) - - -def test(): - print Rat(-1L, 1) - print Rat(1, -1) - a = Rat(1, 10) - print int(a), long(a), float(a) - b = Rat(2, 5) - l = [a+b, a-b, a*b, a/b] - print l - l.sort() - print l - print Rat(0, 1) - print a+1 - print a+1L - print a+1.0 - try: - print Rat(1, 0) - raise SystemError, 'should have been ZeroDivisionError' - except ZeroDivisionError: - print 'OK' - -test() diff --git a/Demo/classes/Rev.py b/Demo/classes/Rev.py deleted file mode 100755 index c1874c65c5..0000000000 --- a/Demo/classes/Rev.py +++ /dev/null @@ -1,89 +0,0 @@ -# A class which presents the reverse of a sequence without duplicating it. -# From: "Steven D. Majewski" - -# It works on mutable or inmutable sequences. -# -# >>> for c in Rev( 'Hello World!' ) : sys.stdout.write( c ) -# ... else: sys.stdout.write( '\n' ) -# ... -# !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( 0, 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 -# nnn = Rev( range( 1, 10 ) ) -# print nnn.forw -# print nnn -# -# produces output: -# -# Hello World! !dlroW olleH -# [1, 2, 3, 4, 5, 6, 7, 8, 9] -# [9, 8, 7, 6, 5, 4, 3, 2, 1] -# -# >>>rrr = Rev( nnn ) -# >>>rrr -# <1, 2, 3, 4, 5, 6, 7, 8, 9> - -from string import joinfields -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 type(seq) == type( [] ) : - wrap = '[]' - sep = ', ' - elif type(seq) == type( () ) : - wrap = '()' - sep = ', ' - elif type(seq) == type( '' ) : - wrap = '' - sep = '' - else: - wrap = '<>' - sep = ', ' - outstrs = [] - for item in self.back : - outstrs.append( str( item ) ) - return wrap[:1] + joinfields( outstrs, sep ) + wrap[-1:] diff --git a/Demo/classes/Vec.py b/Demo/classes/Vec.py deleted file mode 100755 index 8289bc847e..0000000000 --- a/Demo/classes/Vec.py +++ /dev/null @@ -1,64 +0,0 @@ -# A simple vector class - - -def vec(*v): - return apply(Vec, v) - - -class Vec: - - def __init__(self, *v): - self.v = [] - for x in v: - self.v.append(x) - - - def fromlist(self, v): - self.v = [] - if type(v) <> type([]): - raise TypeError - self.v = v[:] - return self - - - def __repr__(self): - return 'vec(' + `self.v`[1:-1] + ')' - - def __len__(self): - return len(self.v) - - def __getitem__(self, i): - return self.v[i] - - def __add__(a, b): - # Element-wise addition - v = [] - for i in range(len(a)): - v.append(a[i] + b[i]) - return Vec().fromlist(v) - - def __sub__(a, b): - # Element-wise subtraction - v = [] - for i in range(len(a)): - v.append(a[i] - b[i]) - return Vec().fromlist(v) - - def __mul__(self, scalar): - # Multiply by scalar - v = [] - for i in range(len(self.v)): - v.append(self.v[i]*scalar) - return Vec().fromlist(v) - - - -def test(): - a = vec(1, 2, 3) - b = vec(3, 2, 1) - print a - print b - print a+b - print a*3.0 - -test() diff --git a/Demo/classes/bitvec.py b/Demo/classes/bitvec.py deleted file mode 100755 index 69718d7a3e..0000000000 --- a/Demo/classes/bitvec.py +++ /dev/null @@ -1,332 +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 - -error = 'bitvec.error' - - -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 'FATAL', '(param, l) = ' + `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 lenght 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('.' + '__repr__()\n') - return 'bitvec' + `self._data, self._len` - - def __cmp__(self, other, *rest): - #rprt(`self`+'.__cmp__'+`(other, ) + rest`+'\n') - 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_lenght = 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(`self`+'.__len__()\n') - return self._len - - def __getitem__(self, key): - #rprt(`self`+'.__getitem__('+`key`+')\n') - key = _check_key(self._len, key) - return self._data & (1L << key) != 0 - - def __setitem__(self, key, value): - #rprt(`self`+'.__setitem__'+`key, value`+'\n') - 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(`self`+'.__delitem__('+`key`+')\n') - 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(`self`+'.__getslice__'+`i, j`+'\n') - 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(`self`+'.__setslice__'+`(i, j, sequence) + rest`+'\n') - 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(`self`+'.__delslice__'+`i, j`+'\n') - 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(`self`+'.__add__('+`other`+')\n') - retval = self.copy() - retval[self._len:self._len] = other - return retval - - def __mul__(self, multiplier): - #rprt(`self`+'.__mul__('+`multiplier`+')\n') - 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(`self`+'.__and__'+`(otherseq, ) + rest`+'\n') - 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(`self`+'.__xor__'+`(otherseq, ) + rest`+'\n') - 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(`self`+'.__or__'+`(otherseq, ) + rest`+'\n') - 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(`self`+'.__invert__()\n') - return BitVec(~self._data & ((1L << self._len) - 1), \ - self._len) - - def __coerce__(self, otherseq, *rest): - #needed for *some* of the arithmetic operations - #rprt(`self`+'.__coerce__'+`(otherseq, ) + rest`+'\n') - 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 diff --git a/Demo/classes/class.doc b/Demo/classes/class.doc deleted file mode 100755 index fddc60bf7b..0000000000 --- a/Demo/classes/class.doc +++ /dev/null @@ -1,110 +0,0 @@ -New features of classes -======================= - -A class can implement certain operations that are invoked by special -syntax (such as subscription or arithmetic operations) by defining -methods with special names. - - -Special methods for any type ----------------------------- - -__repr__(self) --> string - -Used by the print statement and conversions (reverse quotes) to -compute the string representation of an object. - -__cmp__(self, other) --> int - -Used by all comparison operations. Should return -1 if selfother. Due to limitations in the -interpreter, exceptions raised by comparisons are ignored, and the -objects will be considered equal in this case. - - -Special methods for sequence and mapping types ----------------------------------------------- - -__len__(self) --> int - -Used by the built-in function len(). Should return the length of the -object, which should be >= 0. Also, an object whose __len__() method -returns 0 - -__getitem__(self, key) --> value - -Used to implement value = self[key]. Note that the special -interpretation of negative keys (if the class wishes to emulate a -sequence type) is up to the __getitem__ method. - -__setitem__(self, key, value) - -Used to implement self[key] = value. Same note as for __getitem__. - -__delitem__(self, key) - -Used to implement del self[key]. Same note as for __getitem__. - - -Special methods for sequence types ----------------------------------- - -__getslice__(self, i, j) --> sequence - -Used to implement self[i:j]. Note that missing i or j are replaced by -0 or len(self), respectively, and len(self) has been added to negative -i or j. - -__setslice__(self, i, j, sequence) - -Used to implement self[i:j] = value. Same note as for __getslice__. - -__delslice__(self, i, j) - -Used to implement del self[i:j]. Same note as for __getslice__. - - -Special methods for numeric types ---------------------------------- - -__add__, __sub__, __mul__, __div__, __mod__, __divmod__, __pow__, -__lshift__, __rshift__, __and__, __xor__, __or__ - -Used to implement the binary arithmetic operations (divmod and pow are -called by built-in functions). All have the call pattern -func(self, other) --> number. - -__neg__, __pos__, __abs__, __invert__ - -Used to implement the unary arithmetic operations (-, +, abs and ~). -All have the call pattern func(self) --> number. - -__nonzero__(self) --> int - -Used to implement boolean testing. An alternative name for this -method is __len__. - -__coerce__(self, other) --> (self1, other1) or None - -Used to implement "mixed-mode" numeric arithmetic. Either return a -tuple containing self and other converted to some common type, or None -if no way of conversion is known. When the common type would be the -type of other, it is sufficient to return None, since the interpreter -will also ask the other object to attempt a coercion (but sometimes, -if the implementation of the other type cannot be changed, it is -useful to do the conversion to the other type here). - -__int__(self) --> int -__long__(self) --> long -__float__(self) --> float - -Used to implement the built-in functions int(), long() and float(). - - -Notes ------ - -Except for __repr__ and __cmp__, when no appropriate method is -defined, attempts to execute the operation raise an exception. For -__repr__ and __cmp__, the traditional interpretations are used -in this case. diff --git a/Demo/comparisons/README b/Demo/comparisons/README deleted file mode 100644 index 111667c264..0000000000 --- a/Demo/comparisons/README +++ /dev/null @@ -1,60 +0,0 @@ -Subject: Re: What language would you use? -From: Tom Christiansen -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 diff --git a/Demo/comparisons/patterns b/Demo/comparisons/patterns deleted file mode 100755 index f4da846af6..0000000000 --- a/Demo/comparisons/patterns +++ /dev/null @@ -1,4 +0,0 @@ -^def -^class -^import -^from diff --git a/Demo/comparisons/regextest.py b/Demo/comparisons/regextest.py deleted file mode 100755 index 35ee9eed77..0000000000 --- a/Demo/comparisons/regextest.py +++ /dev/null @@ -1,50 +0,0 @@ -#! /usr/local/bin/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 :: -# - 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 regex -from regex_syntax import * - -regex.set_syntax(RE_SYNTAX_EGREP) - -def main(): - pats = map(chomp, sys.stdin.readlines()) - bigpat = '(' + string.joinfields(pats, '|') + ')' - prog = regex.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) >= 0: - print "%s:%s:%s" % (file, lineno, line), - -def chomp(s): - if s[-1:] == '\n': return s[:-1] - else: return s - -main() diff --git a/Demo/comparisons/sortingtest.py b/Demo/comparisons/sortingtest.py deleted file mode 100755 index 1de683bafd..0000000000 --- a/Demo/comparisons/sortingtest.py +++ /dev/null @@ -1,50 +0,0 @@ -#! /usr/local/bin/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 regex -import string -import sys - -def main(): - prog = regex.compile('^\(.*\)=\([-+]?[0-9]+\)') - def makekey(item, prog=prog): - if prog.match(item) >= 0: - var, num = prog.group(1, 2) - return string.atoi(num), var - else: - # Bad input -- pretend it's a var with value 0 - return 0, item - while 1: - line = sys.stdin.readline() - if not line: - break - items = string.split(line) - items = map(makekey, items) - items.sort() - for num, var in items: - print "%s=%s" % (var, num), - print - -main() diff --git a/Demo/comparisons/systemtest.py b/Demo/comparisons/systemtest.py deleted file mode 100755 index 26d9f548db..0000000000 --- a/Demo/comparisons/systemtest.py +++ /dev/null @@ -1,74 +0,0 @@ -#! /usr/local/bin/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() diff --git a/Demo/cwilib/cwilib.py b/Demo/cwilib/cwilib.py deleted file mode 100755 index ebe468a853..0000000000 --- a/Demo/cwilib/cwilib.py +++ /dev/null @@ -1,213 +0,0 @@ -# Interface to the interactive CWI library catalog. - -import sys -import stdwin -from stdwinevents import * -import select -import telnetlib -import vt100win -from form import Form - - -# Main program - -def main(): - vt = vt100win.VT100win() - # - host = 'biefstuk.cwi.nl' - tn = telnetlib.Telnet(host, 0) - # - try: - vt.send(tn.read_until('login: ', 10)) - tn.write('cwilib\r') - # - vt.send(tn.read_until('Hit to continue...', 10)) - tn.write('\r') - # - vt.send(tn.read_until('QUIT', 20)) - except EOFError: - sys.stderr.write('Connection closed prematurely\n') - sys.exit(1) - # - define_screens(vt) - matches = vt.which_screens() - if 'menu' not in matches: - sys.stderr.write('Main menu does not appear\n') - sys.exit(1) - # - tn.write('\r\r') - vt.open('Progress -- CWI Library') - vt.set_debuglevel(0) - ui = UserInterface() - # - while 1: - try: - data = tn.read_very_eager() - except EOFError: - stdwin.message('Connection closed--goodbye') - break - if data: - print 'send...' - vt.send(data) - print 'send...done' - continue - event = stdwin.pollevent() - if event: - type, window, detail = event - if window == None and type == WE_LOST_SEL: - window = ui.queryform.window - event = type, window, detail - if type == WE_CLOSE: - break - if window in ui.windows: - ui.dispatch(type, window, detail) - elif window == vt.window: - if type == WE_NULL: - pass - elif type == WE_COMMAND: - if detail == WC_RETURN: - tn.write('\r') - elif detail == WC_BACKSPACE: - tn.write('\b') - elif detail == WC_TAB: - tn.write('\t') - elif detail == WC_UP: - tn.write('\033[A') - elif detail == WC_DOWN: - tn.write('\033[B') - elif detail == WC_RIGHT: - tn.write('\033[C') - elif detail == WC_LEFT: - tn.write('\033[D') - else: - print '*** Command:', detail - elif type == WE_CHAR: - tn.write(detail) - elif type == WE_DRAW: - vt.draw(detail) - elif type in (WE_ACTIVATE, WE_DEACTIVATE): - pass - else: - print '*** VT100 event:', type, detail - else: - print '*** Alien event:', type, window, detail - continue - rfd, wfd, xfd = select.select([tn, stdwin], [], []) - - -# Subroutine to define our screen recognition patterns - -def define_screens(vt): - vt.define_screen('menu', { - 'title': ('search', 0, 0, 80, - ' SEARCH FUNCTIONS +OTHER FUNCTIONS '), - }) - vt.define_screen('search', { - 'title': ('search', 0, 0, 80, ' Search '), - }) - vt.define_screen('shortlist', {'title': ('search', 0, 0, 80, - ' Short-list')}) - vt.define_screen('showrecord', { - 'title': ('search', 0, 0, 80, ' Show record '), - }) - vt.define_screen('timelimit', { - 'limit': ('search', 12, 0, 80, ' TIME LIMIT '), - }) - vt.define_screen('attention', { - 'BASE': ('copy', 0, 0, 0, 'search'), - 'title': ('search', 10, 0, 80, ' ATTENTION ')}) - vt.define_screen('syntaxerror', { - 'BASE': ('copy', 0, 0, 0, 'attention'), - 'message': ('search', 12, 0, 80, ' Syntax error'), - }) - vt.define_screen('emptyerror', { - 'BASE': ('copy', 0, 0, 0, 'attention'), - 'message': ('search', 12, 0, 80, - ' Check your input. Search at least one term'), - }) - vt.define_screen('unsortedwarning', { - 'BASE': ('copy', 0, 0, 0, 'attention'), - 'message': ('search', 12, 0, 80, - ' Number of records exceeds sort limit'), - }) - vt.define_screen('thereismore', { - 'BASE': ('copy', 0, 0, 0, 'showrecord'), - 'message': ('search', 15, 0, 80, - 'There is more within this record. Use the arrow keys'), - }) - vt.define_screen('nofurther', { - 'BASE': ('copy', 0, 0, 0, 'showrecord'), - 'message': ('search', 17, 0, 80, 'You cannot go further\.'), - }) - vt.define_screen('nofurtherback', { - 'BASE': ('copy', 0, 0, 0, 'showrecord'), - 'message': ('search', 17, 0, 80, - 'You cannot go further back'), - }) - - -# Class to implement our user interface. - -class UserInterface: - - def __init__(self): - stdwin.setfont('7x14') - self.queryform = QueryForm() - self.listform = ListForm() - self.recordform = RecordForm() - self.forms = [self.queryform, self.listform, self.recordform] - define_query_fields(self.queryform) - self.windows = [] - for form in self.forms: - if form.formheight > 0: - form.open() - self.windows.append(form.window) - - def __del__(self): - self.close() - - def close(self): - for form in self.forms: - form.close() - - def dispatch(self, type, window, detail): - for form in self.forms: - if window == form.window: - form.dispatch(type, detail) - - -def define_query_fields(f): - f.define_field('name', 'Name auth./ed.', 1, 60) - f.define_field('title', 'Title', 4, 60) - f.define_field('shelfmark', 'Shelf mark', 1, 60) - f.define_field('class', 'Prim. classif.', 1, 60) - f.define_field('series', 'Series', 1, 60) - f.define_field('congress', 'Congr. pl./year', 1, 60) - f.define_field('type', 'Type', 1, 60) - - -class QueryForm(Form): - - def __init__(self): - Form.__init__(self, 'Query form -- CWI Library') - - def dispatch(self, type, detail): - if type == WE_COMMAND and detail == WC_RETURN: - print '*** SUBMIT ***' - else: - Form.dispatch(self, type, detail) - - -class ListForm(Form): - - def __init__(self): - Form.__init__(self, 'Short list -- CWI Library') - - -class RecordForm(Form): - - def __init__(self): - Form.__init__(self, 'Record detail -- CWI Library') - - -main() diff --git a/Demo/cwilib/form.py b/Demo/cwilib/form.py deleted file mode 100755 index 8dd6ef96eb..0000000000 --- a/Demo/cwilib/form.py +++ /dev/null @@ -1,170 +0,0 @@ -# Fill-out form window - -import stdwin -from stdwinevents import * - - -class Form: - - def __init__(self, title): - self.title = title - self.window = None - self.fields = {} - self.fieldnames = [] - self.formwidth = self.formheight = 0 - self.focusname = None - self.tefocus = None - - def define_field(self, name, label, lines, chars): - self.fieldnames.append(name) - lh = stdwin.lineheight() - cw = stdwin.textwidth('m') - left = 20*cw - top = self.formheight + 4 - right = left + chars*cw - bottom = top + lines*lh - te = None - self.fields[name] = (label, left, top, right, bottom, te) - self.formheight = bottom + 2 - self.formwidth = max(self.formwidth, right + 4) - - def open(self): - if self.window: return - self.formwidth = max(100, self.formwidth) - self.formheight = max(50, self.formheight) - stdwin.setdefwinsize(self.formwidth, self.formheight) - stdwin.setdefscrollbars(0, 0) - self.window = stdwin.open(self.title) - self.window.setdocsize(self.formwidth, self.formheight) - for name in self.fieldnames: - label, left, top, right, bottom, te = \ - self.fields[name] - rect = (left, top), (right, bottom) - te = self.window.textcreate(rect) - te.setactive(0) - te.setview(rect) - self.fields[name] = \ - label, left, top, right, bottom, te - if self.fieldnames: - self.setfocus(self.fieldnames[0]) - - def setfocus(self, name): - if name <> self.focusname and self.tefocus: - self.tefocus.setactive(0) - self.focusname = name - if self.focusname: - self.tefocus = self.fields[self.focusname][-1] - self.tefocus.setactive(1) - else: - self.tefocus = None - - def dispatch(self, type, detail): - event = type, self.window, detail - if type == WE_NULL: - pass - elif type == WE_DRAW: - self.draw(detail) - elif type == WE_MOUSE_DOWN: - x, y = detail[0] - for name in self.fieldnames: - label, left, top, right, bottom, te = \ - self.fields[name] - if left <= x < right and \ - top <= y < bottom: - self.setfocus(name) - break - else: - stdwin.fleep() - return - if self.tefocus: - (left, top), (right, bottom) = \ - self.tefocus.getrect() - if x < left: x = left - if x >= right: x = right-1 - if y < top: y = top - if y >= bottom: - y = bottom-1 - x = right-1 - event = type, self.window, ((x,y),)+detail[1:] - if not self.tefocus.event(event): - stdwin.fleep() - elif type in (WE_MOUSE_MOVE, WE_MOUSE_UP, WE_CHAR): - if not self.tefocus or not self.tefocus.event(event): - stdwin.fleep() - elif type == WE_MOUSE_UP: - button = detail[2] - if button == 2: - self.paste_selection() - else: - self.make_selection() - elif type == WE_COMMAND: - if detail in (WC_BACKSPACE, WC_UP, WC_DOWN, - WC_LEFT, WC_RIGHT): - if not self.tefocus or \ - not self.tefocus.event(event): - stdwin.fleep() - elif detail == WC_RETURN: - print '*** Submit query' - elif detail == WC_TAB: - if not self.fields: - stdwin.fleep() - return - if not self.focusname: - i = 0 - else: - i = self.fieldnames.index( - self.focusname) - i = (i+1) % len(self.fieldnames) - self.setfocus(self.fieldnames[i]) - self.tefocus.setfocus(0, 0x7fff) - self.make_selection() - elif type in (WE_ACTIVATE, WE_DEACTIVATE): - pass - elif type == WE_LOST_SEL: - if self.tefocus: - a, b = self.tefocus.getfocus() - self.tefocus.setfocus(a, a) - else: - print 'Form.dispatch(%d, %s)' % (type, `detail`) - - def draw(self, detail): - d = self.window.begindrawing() - d.cliprect(detail) - d.erase(detail) - self.drawform(d, detail) - d.noclip() - d.close() - # Stupid textedit objects can't draw with open draw object... - self.drawtextedit(detail) - - def drawform(self, d, detail): - for name in self.fieldnames: - label, left, top, right, bottom, te = self.fields[name] - d.text((0, top), label) - d.box((left-3, top-2), (right+4, bottom+2)) - - def drawtextedit(self, detail): - for name in self.fieldnames: - label, left, top, right, bottom, te = self.fields[name] - te.draw(detail) - - def make_selection(self): - s = self.tefocus.getfocustext() - if not s: - return - stdwin.rotatecutbuffers(1) - stdwin.setcutbuffer(0, s) - if not self.window.setselection(WS_PRIMARY, s): - stdwin.fleep() - - def paste_selection(self): - if not self.tefocus: - stdwin.fleep() - return - s = stdwin.getselection(WS_PRIMARY) - if not s: - s = stdwin.getcutbuffer(0) - if not s: - stdwin.fleep() - return - self.tefocus.replace(s) diff --git a/Demo/cwilib/telnetlib.py b/Demo/cwilib/telnetlib.py deleted file mode 100755 index 3a48a79b75..0000000000 --- a/Demo/cwilib/telnetlib.py +++ /dev/null @@ -1,321 +0,0 @@ -# A TELNET client class. Based on RFC 854: TELNET Protocol -# Specification, by J. Postel and J. Reynolds - - -# Example: -# -# >>> from telnetlib import Telnet -# >>> tn = Telnet('voorn.cwi.nl', 79) # connect to finger port -# >>> tn.write('guido\r\n') -# >>> print tn.read_all() -# Login name: guido In real life: Guido van Rossum -# Office: M353, x4127 Home phone: 020-6225521 -# Directory: /ufs/guido Shell: /usr/local/bin/esh -# On since Oct 28 11:02:16 on ttyq1 -# Project: Multimedia Kernel Systems -# No Plan. -# >>> -# -# Note that read() won't read until eof -- it just reads some data -# (but it guarantees to read at least one byte unless EOF is hit). -# -# It is possible to pass a Telnet object to select.select() in order -# to wait until more data is available. Note that in this case, -# read_eager() may return '' even if there was data on the socket, -# because the protocol negotiation may have eaten the data. -# This is why EOFError is needed to distinguish between "no data" -# and "connection closed" (since the socket also appears ready for -# reading when it is closed). -# -# Bugs: -# - may hang when connection is slow in the middle of an IAC sequence -# -# To do: -# - option negotiation - - -# Imported modules -import socket -import select -import string -import regsub - -# Tunable parameters -DEBUGLEVEL = 0 - -# Telnet protocol defaults -TELNET_PORT = 23 - -# Telnet protocol characters (don't change) -IAC = chr(255) # "Interpret As Command" -DONT = chr(254) -DO = chr(253) -WONT = chr(252) -WILL = chr(251) - - -# Telnet interface class - -class Telnet: - - # Constructor - def __init__(self, host, *args): - if not args: - port = TELNET_PORT - else: - if len(args) > 1: raise TypeError, 'too many args' - port = args[0] - if not port: port = TELNET_PORT - self.debuglevel = DEBUGLEVEL - self.host = host - self.port = port - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.sock.connect((self.host, self.port)) - self.rawq = '' - self.irawq = 0 - self.cookedq = '' - self.eof = 0 - - # Destructor - def __del__(self): - self.close() - - # Debug message - def msg(self, msg, *args): - if self.debuglevel > 0: - print 'Telnet(%s,%d):' % (self.host, self.port), msg % args - - # Set debug level - def set_debuglevel(self, debuglevel): - self.debuglevel = debuglevel - - # Explicit close - def close(self): - if self.sock: - self.sock.close() - self.sock = None - self.eof = 1 - - # Return socket (e.g. for select) - def get_socket(self): - return self.sock - - # Return socket's fileno (e.g. for select) - def fileno(self): - return self.sock.fileno() - - # Write a string to the socket, doubling any IAC characters - # Might block if the connection is blocked - # May raise socket.error if the connection is closed - def write(self, buffer): - if IAC in buffer: - buffer = regsub.gsub(IAC, IAC+IAC, buffer) - self.sock.send(buffer) - - # The following read_* methods exist: - # Special case: - # - read_until() reads until a string is encountered or a timeout is hit - # These may block: - # - read_all() reads all data until EOF - # - read_some() reads at least one byte until EOF - # These may do I/O but won't block doing it: - # - read_very_eager() reads all data available on the socket - # - read_eager() reads either data already queued or some data - # available on the socket - # These don't do I/O: - # - read_lazy() reads all data in the raw queue (processing it first) - # - read_very_lazy() reads all data in the cooked queue - - # Read until a given string is encountered or until timeout - # Raise EOFError if connection closed and no cooked data available - # Return '' if no cooked data available otherwise - def read_until(self, match, *args): - if not args: - timeout = None - else: - if len(args) > 1: raise TypeError, 'too many args' - timeout = args[0] - n = len(match) - self.process_rawq() - i = string.find(self.cookedq, match) - if i >= 0: - i = i+n - buf = self.cookedq[:i] - self.cookedq = self.cookedq[i:] - return buf - s_reply = ([self], [], []) - s_args = s_reply - if timeout is not None: - s_args = s_args + (timeout,) - while not self.eof and apply(select.select, s_args) == s_reply: - i = max(0, len(self.cookedq)-n) - self.fill_rawq() - self.process_rawq() - i = string.find(self.cookedq, match, i) - if i >= 0: - i = i+n - buf = self.cookedq[:i] - self.cookedq = self.cookedq[i:] - return buf - return self.read_very_lazy() - - # Read all data until EOF - # Block until connection closed - def read_all(self): - self.process_rawq() - while not self.eof: - self.fill_rawq() - self.process_rawq() - buf = self.cookedq - self.cookedq = '' - return buf - - # Read at least one byte of cooked data unless EOF is hit - # Return '' if EOF is hit - # Block if no data is immediately available - def read_some(self): - self.process_rawq() - while not self.cookedq and not self.eof: - self.fill_rawq() - self.process_rawq() - buf = self.cookedq - self.cookedq = '' - return buf - - # Read everything that's possible without blocking in I/O (eager) - # Raise EOFError if connection closed and no cooked data available - # Return '' if no cooked data available otherwise - # Don't block unless in the midst of an IAC sequence - def read_very_eager(self): - self.process_rawq() - while not self.eof and self.sock_avail(): - self.fill_rawq() - self.process_rawq() - return self.read_very_lazy() - - # Read readily available data - # Raise EOFError if connection closed and no cooked data available - # Return '' if no cooked data available otherwise - # Don't block unless in the midst of an IAC sequence - def read_eager(self): - self.process_rawq() - while not self.cookedq and not self.eof and self.sock_avail(): - self.fill_rawq() - self.process_rawq() - return self.read_very_lazy() - - # Process and return data that's already in the queues (lazy) - # Raise EOFError if connection closed and no data available - # Return '' if no cooked data available otherwise - # Don't block unless in the midst of an IAC sequence - def read_lazy(self): - self.process_rawq() - return self.read_very_lazy() - - # Return any data available in the cooked queue (very lazy) - # Raise EOFError if connection closed and no data available - # Return '' if no cooked data available otherwise - # Don't block - def read_very_lazy(self): - buf = self.cookedq - self.cookedq = '' - if not buf and self.eof and not self.rawq: - raise EOFError, 'telnet connection closed' - return buf - - # Transfer from raw queue to cooked queue - # Set self.eof when connection is closed - # Don't block unless in the midst of an IAC sequence - def process_rawq(self): - buf = '' - try: - while self.rawq: - c = self.rawq_getchar() - if c != IAC: - buf = buf + c - continue - c = self.rawq_getchar() - if c == IAC: - buf = buf + c - elif c in (DO, DONT): - opt = self.rawq_getchar() - self.msg('IAC %s %d', c == DO and 'DO' or 'DONT', ord(c)) - self.sock.send(IAC + WONT + opt) - elif c in (WILL, WONT): - opt = self.rawq_getchar() - self.msg('IAC %s %d', - c == WILL and 'WILL' or 'WONT', ord(c)) - else: - self.msg('IAC %s not recognized' % `c`) - except EOFError: # raised by self.rawq_getchar() - pass - self.cookedq = self.cookedq + buf - - # Get next char from raw queue - # Block if no data is immediately available - # Raise EOFError when connection is closed - def rawq_getchar(self): - if not self.rawq: - self.fill_rawq() - if self.eof: - raise EOFError - c = self.rawq[self.irawq] - self.irawq = self.irawq + 1 - if self.irawq >= len(self.rawq): - self.rawq = '' - self.irawq = 0 - return c - - # Fill raw queue from exactly one recv() system call - # Block if no data is immediately available - # Set self.eof when connection is closed - def fill_rawq(self): - if self.irawq >= len(self.rawq): - self.rawq = '' - self.irawq = 0 - # The buffer size should be fairly small so as to avoid quadratic - # behavior in process_rawq() above - buf = self.sock.recv(50) - self.eof = (not buf) - self.rawq = self.rawq + buf - - # Test whether data is available on the socket - def sock_avail(self): - return select.select([self], [], [], 0) == ([self], [], []) - - -# Test program -# Usage: test [-d] ... [host [port]] -def test(): - import sys, string, socket, select - debuglevel = 0 - while sys.argv[1:] and sys.argv[1] == '-d': - debuglevel = debuglevel+1 - del sys.argv[1] - host = 'localhost' - if sys.argv[1:]: - host = sys.argv[1] - port = 0 - if sys.argv[2:]: - portstr = sys.argv[2] - try: - port = string.atoi(portstr) - except string.atoi_error: - port = socket.getservbyname(portstr, 'tcp') - tn = Telnet(host, port) - tn.set_debuglevel(debuglevel) - while 1: - rfd, wfd, xfd = select.select([tn, sys.stdin], [], []) - if sys.stdin in rfd: - line = sys.stdin.readline() - tn.write(line) - if tn in rfd: - try: - text = tn.read_eager() - except EOFError: - print '*** Connection closed by remote host ***' - break - if text: - sys.stdout.write(text) - sys.stdout.flush() - tn.close() diff --git a/Demo/cwilib/vt100.py b/Demo/cwilib/vt100.py deleted file mode 100755 index 9edd4810b9..0000000000 --- a/Demo/cwilib/vt100.py +++ /dev/null @@ -1,328 +0,0 @@ -# VT100 terminal emulator. -# This is incomplete and slow, but will do for now... -# It shouldn't be difficult to extend it to be a more-or-less complete -# VT100 emulator. And little bit of profiling could go a long way... - -from array import array -import regex -import string - -# Tunable parameters -DEBUGLEVEL = 1 - -# Symbolic constants -ESC = '\033' - - -# VT100 emulation class - -class VT100: - - def __init__(self): - self.debuglevel = DEBUGLEVEL - # Unchangeable parameters (for now) - self.width = 80 - self.height = 24 - self.blankline = array('c', ' '*self.width) - self.blankattr = array('b', '\0'*self.width) - # Set mutable display state - self.reset() - # Set parser state - self.unfinished = '' - # Set screen recognition state - self.reset_recognizer() - - def msg(self, msg, *args): - if self.debuglevel > 0: - print 'VT100:', msg%args - - def set_debuglevel(self, debuglevel): - self.debuglevel = debuglevel - - def reset(self): - self.lines = [] - self.attrs = [] - self.fill_bottom() - self.x = 0 - self.y = 0 - self.curattrs = [] - - def show(self): - lineno = 0 - for line in self.lines: - lineno = lineno + 1 - i = len(line) - while i > 0 and line[i-1] == ' ': i = i-1 - print line[:i] - print 'CURSOR:', self.x, self.y - - def fill_bottom(self): - while len(self.lines) < self.height: - self.lines.append(self.blankline[:]) - self.attrs.append(self.blankattr[:]) - - def fill_top(self): - while len(self.lines) < self.height: - self.lines.insert(0, self.blankline[:]) - self.attrs.insert(0, self.blankattr[:]) - - def clear_all(self): - self.lines = [] - self.attrs = [] - self.fill_bottom() - - def clear_below(self): - del self.lines[self.y:] - del self.attrs[self.y:] - self.fill_bottom() - - def clear_above(self): - del self.lines[:self.y] - del self.attrs[:self.y] - self.fill_top() - - def send(self, buffer): - self.msg('send: unfinished=%s, buffer=%s', - `self.unfinished`, `buffer`) - self.unfinished = self.unfinished + buffer - i = 0 - n = len(self.unfinished) - while i < n: - c = self.unfinished[i] - i = i+1 - if c != ESC: - self.add_char(c) - continue - if i >= n: - i = i-1 - break - c = self.unfinished[i] - i = i+1 - if c == 'c': - self.reset() - continue - if c <> '[': - self.msg('unrecognized: ESC %s', `c`) - continue - argstr = '' - while i < n: - c = self.unfinished[i] - i = i+1 - if c not in '0123456789;': - break - argstr = argstr + c - else: - i = i - len(argstr) - 2 - break -## self.msg('found ESC [ %s %s' % (`argstr`, `c`)) - args = string.splitfields(argstr, ';') - for j in range(len(args)): - s = args[j] - while s[:1] == '0': s = s[1:] - if s: args[j] = eval(s) - else: args[j] = 0 - p1 = p2 = 0 - if args: p1 = args[0] - if args[1:]: p2 = args[1] - if c in '@ABCDH': - if not p1: p1 = 1 - if c in 'H': - if not p2: p2 = 1 - if c == '@': - for j in range(p1): - self.add_char(' ') - elif c == 'A': - self.move_by(0, -p1) - elif c == 'B': - self.move_by(0, p1) - elif c == 'C': - self.move_by(p1, 0) - elif c == 'D': - self.move_by(-p1, 0) - elif c == 'H': - self.move_to(p2-1, p1-1) - elif c == 'J': - if p1 == 0: self.clear_above() - elif p1 == 1: self.clear_below() - elif p1 == 2: self.clear_all() - else: self.msg('weird ESC [ %d J', p1) - elif c == 'K': - if p1 == 0: self.erase_right() - elif p1 == 1: self.erase_left() - elif p1 == 2: self.erase_line() - else: self.msg('weird ESC [ %d K', p1) - elif c == 'm': - if p1 == 0: - self.curattrs = [] - else: - if p1 not in self.curattrs: - self.curattrs.append(p1) - self.curattrs.sort() - else: - self.msg('unrecognized: ESC [ %s', `argstr+c`) - self.unfinished = self.unfinished[i:] - - def add_char(self, c): - if c == '\r': - self.move_to(0, self.y) - return - if c in '\n\f\v': - self.move_to(self.x, self.y + 1) - if self.y >= self.height: - self.scroll_up(1) - self.move_to(self.x, self.height - 1) - return - if c == '\b': - self.move_by(-1, 0) - return - if c == '\a': - self.msg('BELL') - return - if c == '\t': - self.move_to((self.x+8)/8*8, self.y) - return - if c == '\0': - return - if c < ' ' or c > '~': - self.msg('ignored control char: %s', `c`) - return - if self.x >= self.width: - self.move_to(0, self.y + 1) - if self.y >= self.height: - self.scroll_up(1) - self.move_to(self.x, self.height - 1) - self.lines[self.y][self.x] = c - if self.curattrs: - self.attrs[self.y][self.x] = max(self.curattrs) - else: - self.attrs[self.y][self.x] = 0 - self.move_by(1, 0) - - def move_to(self, x, y): - self.x = min(max(0, x), self.width) - self.y = min(max(0, y), self.height) - - def move_by(self, dx, dy): - self.move_to(self.x + dx, self.y + dy) - - def scroll_up(self, nlines): - del self.lines[:max(0, nlines)] - del self.attrs[:max(0, nlines)] - self.fill_bottom() - - def scroll_down(self, nlines): - del self.lines[-max(0, nlines):] - del self.attrs[-max(0, nlines):] - self.fill_top() - - def erase_left(self): - x = min(self.width-1, x) - y = min(self.height-1, y) - self.lines[y][:x] = self.blankline[:x] - self.attrs[y][:x] = self.blankattr[:x] - - def erase_right(self): - x = min(self.width-1, x) - y = min(self.height-1, y) - self.lines[y][x:] = self.blankline[x:] - self.attrs[y][x:] = self.blankattr[x:] - - def erase_line(self): - self.lines[y][:] = self.blankline - self.attrs[y][:] = self.blankattr - - # The following routines help automating the recognition of - # standard screens. A standard screen is characterized by - # a number of fields. A field is part of a line, - # characterized by a (lineno, begin, end) tuple; - # e.g. the first 10 characters of the second line are - # specified by the tuple (1, 0, 10). Fields can be: - # - regex: desired contents given by a regular expression, - # - extract: can be extracted, - # - cursor: screen is only valid if cursor in field, - # - copy: identical to another screen (position is ignored). - # A screen is defined as a dictionary full of fields. Screens - # also have names and are placed in a dictionary. - - def reset_recognizer(self): - self.screens = {} - - def define_screen(self, screenname, fields): - fieldscopy = {} - # Check if the fields make sense - for fieldname in fields.keys(): - field = fields[fieldname] - ftype, lineno, begin, end, extra = field - if ftype in ('match', 'search'): - extra = regex.compile(extra) - elif ftype == 'extract': - extra = None - elif ftype == 'cursor': - extra = None - elif ftype == 'copy': - if not self.screens.has_key(extra): - raise ValueError, 'bad copy ref' - else: - raise ValueError, 'bad ftype: %s' % `ftype` - fieldscopy[fieldname] = ( - ftype, lineno, begin, end, extra) - self.screens[screenname] = fieldscopy - - def which_screens(self): - self.busy = [] - self.okay = [] - self.fail = [] - for name in self.screens.keys(): - ok = self.match_screen(name) - return self.okay[:] - - def match_screen(self, name): - if name in self.busy: raise RuntimeError, 'recursive match' - if name in self.okay: return 1 - if name in self.fail: return 0 - self.busy.append(name) - fields = self.screens[name] - ok = 0 - for key in fields.keys(): - field = fields[key] - ftype, lineno, begin, end, extra = field - if ftype == 'copy': - if not self.match_screen(extra): break - elif ftype == 'search': - text = self.lines[lineno][begin:end].tostring() - if extra.search(text) < 0: - break - elif ftype == 'match': - text = self.lines[lineno][begin:end].tostring() - if extra.match(text) < 0: - break - elif ftype == 'cursor': - if self.x != lineno or not \ - begin <= self.y < end: - break - else: - ok = 1 - if ok: - self.okay.append(name) - else: - self.fail.append(name) - self.busy.remove(name) - return ok - - def extract_field(self, screenname, fieldname): - ftype, lineno, begin, end, extra = \ - self.screens[screenname][fieldname] - return stripright(self.lines[lineno][begin:end].tostring()) - - def extract_rect(self, left, top, right, bottom): - lines = [] - for i in range(top, bottom): - lines.append(stripright(self.lines[i][left:right]) - .tostring()) - return lines - - -def stripright(line): - i = len(line) - while i > 0 and line[i-1] in string.whitespace: i = i-1 - return line[:i] diff --git a/Demo/cwilib/vt100win.py b/Demo/cwilib/vt100win.py deleted file mode 100755 index 122e5f9dfa..0000000000 --- a/Demo/cwilib/vt100win.py +++ /dev/null @@ -1,78 +0,0 @@ -# VT100 terminal emulator in a STDWIN window. - -import stdwin -from stdwinevents import * -from vt100 import VT100 - -class VT100win(VT100): - - def __init__(self): - VT100.__init__(self) - self.window = None - self.last_x = -1 - self.last_y = -1 - - def __del__(self): - self.close() - - def open(self, title): - stdwin.setfont('7x14') - self.charwidth = stdwin.textwidth('m') - self.lineheight = stdwin.lineheight() - self.docwidth = self.width * self.charwidth - self.docheight = self.height * self.lineheight - stdwin.setdefwinsize(self.docwidth + 2, self.docheight + 2) - stdwin.setdefscrollbars(0, 0) - self.window = stdwin.open(title) - self.window.setdocsize(self.docwidth + 2, self.docheight + 2) - - def close(self): - if self.window: - self.window.close() - self.window = None - - def show(self): - if not self.window: return - self.window.change(((-10, -10), - (self.docwidth+10, self.docheight+10))) - - def draw(self, detail): - d = self.window.begindrawing() - fg = stdwin.getfgcolor() - red = stdwin.fetchcolor('red') - d.cliprect(detail) - d.erase(detail) - lh = self.lineheight - cw = self.charwidth - for y in range(self.height): - d.text((0, y*lh), self.lines[y].tostring()) - if self.attrs[y] <> self.blankattr: - for x in range(len(self.attrs[y])): - if self.attrs[y][x] == 7: - p1 = x*cw, y*lh - p2 = (x+1)*cw, (y+1)*lh - d.invert((p1, p2)) - x = self.x * cw - y = self.y * lh - d.setfgcolor(red) - d.invert((x, y), (x+cw, y+lh)) - d.setfgcolor(fg) - d.close() - - def move_to(self, x, y): - VT100.move_to(self, x, y) - if not self.window: return - if self.y != self.last_y: - self.window.change((0, self.last_y * self.lineheight), - (self.width*self.charwidth, - (self.last_y+1) * self.lineheight)) - self.last_x = self.x - self.last_y = y - self.window.change((0, self.y * self.lineheight), - (self.width*self.charwidth, - (self.y+1) * self.lineheight)) - - def send(self, str): - VT100.send(self, str) -## self.show() - diff --git a/Demo/dns/README b/Demo/dns/README deleted file mode 100644 index 09ebe8ff62..0000000000 --- a/Demo/dns/README +++ /dev/null @@ -1,12 +0,0 @@ -This directory contains a module (dnslib) that implements a DNS -(Domain Name Server) client, plus additional modules that define some -symbolic constants used by DNS (dnstype, dnsclass, dnsopcode). - -Type "python dnslib.py -/" for a usage message. - -You can also import dnslib and write your own, more sophisticated -client code; use the test program as an example (there is currently no -documentation :-). - ---Guido van Rossum, CWI, Amsterdam -URL: diff --git a/Demo/dns/dnsclass.py b/Demo/dns/dnsclass.py deleted file mode 100755 index f90b9e8460..0000000000 --- a/Demo/dns/dnsclass.py +++ /dev/null @@ -1,23 +0,0 @@ -# CLASS values (section 3.2.4) - -IN = 1 # the Internet -CS = 2 # the CSNET class (Obsolete - used only for examples in - # some obsolete RFCs) -CH = 3 # the CHAOS class -HS = 4 # Hesiod [Dyer 87] - -# QCLASS values (section 3.2.5) - -ANY = 255 # any class - - -# Construct reverse mapping dictionary - -_names = dir() -classmap = {} -for _name in _names: - if _name[0] != '_': classmap[eval(_name)] = _name - -def classstr(klass): - if classmap.has_key(klass): return classmap[klass] - else: return `klass` diff --git a/Demo/dns/dnslib.py b/Demo/dns/dnslib.py deleted file mode 100755 index 9f0a3f4da5..0000000000 --- a/Demo/dns/dnslib.py +++ /dev/null @@ -1,588 +0,0 @@ -# Domain Name Server (DNS) interface -# -# See RFC 1035: -# ------------------------------------------------------------------------ -# Network Working Group P. Mockapetris -# Request for Comments: 1035 ISI -# November 1987 -# Obsoletes: RFCs 882, 883, 973 -# -# DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION -# ------------------------------------------------------------------------ - - -import string - -import dnstype -import dnsclass -import dnsopcode - - -# Low-level 16 and 32 bit integer packing and unpacking - -def pack16bit(n): - return chr((n>>8)&0xFF) + chr(n&0xFF) - -def pack32bit(n): - return chr((n>>24)&0xFF) + chr((n>>16)&0xFF) \ - + chr((n>>8)&0xFF) + chr(n&0xFF) - -def unpack16bit(s): - return (ord(s[0])<<8) | ord(s[1]) - -def unpack32bit(s): - return (ord(s[0])<<24) | (ord(s[1])<<16) \ - | (ord(s[2])<<8) | ord(s[3]) - -def addr2bin(addr): - if type(addr) == type(0): - return addr - bytes = string.splitfields(addr, '.') - if len(bytes) != 4: raise ValueError, 'bad IP address' - n = 0 - for byte in bytes: n = n<<8 | string.atoi(byte) - return n - -def bin2addr(n): - return '%d.%d.%d.%d' % ((n>>24)&0xFF, (n>>16)&0xFF, - (n>>8)&0xFF, n&0xFF) - - -# Packing class - -class Packer: - def __init__(self): - self.buf = '' - self.index = {} - def getbuf(self): - return self.buf - def addbyte(self, c): - if len(c) != 1: raise TypeError, 'one character expected' - self.buf = self.buf + c - def addbytes(self, bytes): - self.buf = self.buf + bytes - def add16bit(self, n): - self.buf = self.buf + pack16bit(n) - def add32bit(self, n): - self.buf = self.buf + pack32bit(n) - def addaddr(self, addr): - n = addr2bin(addr) - self.buf = self.buf + pack32bit(n) - def addstring(self, s): - self.addbyte(chr(len(s))) - self.addbytes(s) - def addname(self, name): - # Domain name packing (section 4.1.4) - # Add a domain name to the buffer, possibly using pointers. - # The case of the first occurrence of a name is preserved. - # Redundant dots are ignored. - list = [] - for label in string.splitfields(name, '.'): - if label: - if len(label) > 63: - raise PackError, 'label too long' - list.append(label) - keys = [] - for i in range(len(list)): - key = string.upper(string.joinfields(list[i:], '.')) - keys.append(key) - if self.index.has_key(key): - pointer = self.index[key] - break - else: - i = len(list) - pointer = None - # Do it into temporaries first so exceptions don't - # mess up self.index and self.buf - buf = '' - offset = len(self.buf) - index = [] - for j in range(i): - label = list[j] - n = len(label) - if offset + len(buf) < 0x3FFF: - index.append(keys[j], offset + len(buf)) - else: - print 'dnslib.Packer.addname:', - print 'warning: pointer too big' - buf = buf + (chr(n) + label) - if pointer: - buf = buf + pack16bit(pointer | 0xC000) - else: - buf = buf + '\0' - self.buf = self.buf + buf - for key, value in index: - self.index[key] = value - def dump(self): - keys = self.index.keys() - keys.sort() - print '-'*40 - for key in keys: - print '%20s %3d' % (key, self.index[key]) - print '-'*40 - space = 1 - for i in range(0, len(self.buf)+1, 2): - if self.buf[i:i+2] == '**': - if not space: print - space = 1 - continue - space = 0 - print '%4d' % i, - for c in self.buf[i:i+2]: - if ' ' < c < '\177': - print ' %c' % c, - else: - print '%2d' % ord(c), - print - print '-'*40 - - -# Unpacking class - -UnpackError = 'dnslib.UnpackError' # Exception - -class Unpacker: - def __init__(self, buf): - self.buf = buf - self.offset = 0 - def getbyte(self): - c = self.buf[self.offset] - self.offset = self.offset + 1 - return c - def getbytes(self, n): - s = self.buf[self.offset : self.offset + n] - if len(s) != n: raise UnpackError, 'not enough data left' - self.offset = self.offset + n - return s - def get16bit(self): - return unpack16bit(self.getbytes(2)) - def get32bit(self): - return unpack32bit(self.getbytes(4)) - def getaddr(self): - return bin2addr(self.get32bit()) - def getstring(self): - return self.getbytes(ord(self.getbyte())) - def getname(self): - # Domain name unpacking (section 4.1.4) - c = self.getbyte() - i = ord(c) - if i & 0xC0 == 0xC0: - d = self.getbyte() - j = ord(d) - pointer = ((i<<8) | j) & ~0xC000 - save_offset = self.offset - try: - self.offset = pointer - domain = self.getname() - finally: - self.offset = save_offset - return domain - if i == 0: - return '' - domain = self.getbytes(i) - remains = self.getname() - if not remains: - return domain - else: - return domain + '.' + remains - - -# Test program for packin/unpacking (section 4.1.4) - -def testpacker(): - N = 25 - R = range(N) - import timing - # See section 4.1.4 of RFC 1035 - timing.start() - for i in R: - p = Packer() - p.addbytes('*' * 20) - p.addname('f.ISI.ARPA') - p.addbytes('*' * 8) - p.addname('Foo.F.isi.arpa') - p.addbytes('*' * 18) - p.addname('arpa') - p.addbytes('*' * 26) - p.addname('') - timing.finish() - print round(timing.milli() * 0.001 / N, 3), 'seconds per packing' - p.dump() - u = Unpacker(p.buf) - u.getbytes(20) - u.getname() - u.getbytes(8) - u.getname() - u.getbytes(18) - u.getname() - u.getbytes(26) - u.getname() - timing.start() - for i in R: - u = Unpacker(p.buf) - res = (u.getbytes(20), - u.getname(), - u.getbytes(8), - u.getname(), - u.getbytes(18), - u.getname(), - u.getbytes(26), - u.getname()) - timing.finish() - print round(timing.milli() * 0.001 / N, 3), 'seconds per unpacking' - for item in res: print item - - -# Pack/unpack RR toplevel format (section 3.2.1) - -class RRpacker(Packer): - def __init__(self): - Packer.__init__(self) - self.rdstart = None - def addRRheader(self, name, type, klass, ttl, *rest): - self.addname(name) - self.add16bit(type) - self.add16bit(klass) - self.add32bit(ttl) - if rest: - if res[1:]: raise TypeError, 'too many args' - rdlength = rest[0] - else: - rdlength = 0 - self.add16bit(rdlength) - self.rdstart = len(self.buf) - def patchrdlength(self): - rdlength = unpack16bit(self.buf[self.rdstart-2:self.rdstart]) - if rdlength == len(self.buf) - self.rdstart: - return - rdata = self.buf[self.rdstart:] - save_buf = self.buf - ok = 0 - try: - self.buf = self.buf[:self.rdstart-2] - self.add16bit(len(rdata)) - self.buf = self.buf + rdata - ok = 1 - finally: - if not ok: self.buf = save_buf - def endRR(self): - if self.rdstart is not None: - self.patchrdlength() - self.rdstart = None - def getbuf(self): - if self.rdstart is not None: self.patchrdlenth() - return Packer.getbuf(self) - # Standard RRs (section 3.3) - def addCNAME(self, name, klass, ttl, cname): - self.addRRheader(name, dnstype.CNAME, klass, ttl) - self.addname(cname) - self.endRR() - def addHINFO(self, name, klass, ttl, cpu, os): - self.addRRheader(name, dnstype.HINFO, klass, ttl) - self.addstring(cpu) - self.addstring(os) - self.endRR() - def addMX(self, name, klass, ttl, preference, exchange): - self.addRRheader(name, dnstype.MX, klass, ttl) - self.add16bit(preference) - self.addname(exchange) - self.endRR() - def addNS(self, name, klass, ttl, nsdname): - self.addRRheader(name, dnstype.NS, klass, ttl) - self.addname(nsdname) - self.endRR() - def addPTR(self, name, klass, ttl, ptrdname): - self.addRRheader(name, dnstype.PTR, klass, ttl) - self.addname(ptrdname) - self.endRR() - def addSOA(self, name, klass, ttl, - mname, rname, serial, refresh, retry, expire, minimum): - self.addRRheader(name, dnstype.SOA, klass, ttl) - self.addname(mname) - self.addname(rname) - self.add32bit(serial) - self.add32bit(refresh) - self.add32bit(retry) - self.add32bit(expire) - self.add32bit(minimum) - self.endRR() - def addTXT(self, name, klass, ttl, list): - self.addRRheader(name, dnstype.TXT, klass, ttl) - for txtdata in list: - self.addstring(txtdata) - self.endRR() - # Internet specific RRs (section 3.4) -- class = IN - def addA(self, name, ttl, address): - self.addRRheader(name, dnstype.A, dnsclass.IN, ttl) - self.addaddr(address) - self.endRR() - def addWKS(self, name, ttl, address, protocol, bitmap): - self.addRRheader(name, dnstype.WKS, dnsclass.IN, ttl) - self.addaddr(address) - self.addbyte(chr(protocol)) - self.addbytes(bitmap) - self.endRR() - - -class RRunpacker(Unpacker): - def __init__(self, buf): - Unpacker.__init__(self, buf) - self.rdend = None - def getRRheader(self): - name = self.getname() - type = self.get16bit() - klass = self.get16bit() - ttl = self.get32bit() - rdlength = self.get16bit() - self.rdend = self.offset + rdlength - return (name, type, klass, ttl, rdlength) - def endRR(self): - if self.offset != self.rdend: - raise UnpackError, 'end of RR not reached' - def getCNAMEdata(self): - return self.getname() - def getHINFOdata(self): - return self.getstring(), self.getstring() - def getMXdata(self): - return self.get16bit(), self.getname() - def getNSdata(self): - return self.getname() - def getPTRdata(self): - return self.getname() - def getSOAdata(self): - return self.getname(), \ - self.getname(), \ - self.get32bit(), \ - self.get32bit(), \ - self.get32bit(), \ - self.get32bit(), \ - self.get32bit() - def getTXTdata(self): - list = [] - while self.offset != self.rdend: - list.append(self.getstring()) - return list - def getAdata(self): - return self.getaddr() - def getWKSdata(self): - address = self.getaddr() - protocol = ord(self.getbyte()) - bitmap = self.getbytes(self.rdend - self.offset) - return address, protocol, bitmap - - -# Pack/unpack Message Header (section 4.1) - -class Hpacker(Packer): - def addHeader(self, id, qr, opcode, aa, tc, rd, ra, z, rcode, - qdcount, ancount, nscount, arcount): - self.add16bit(id) - self.add16bit((qr&1)<<15 | (opcode*0xF)<<11 | (aa&1)<<10 - | (tc&1)<<9 | (rd&1)<<8 | (ra&1)<<7 - | (z&7)<<4 | (rcode&0xF)) - self.add16bit(qdcount) - self.add16bit(ancount) - self.add16bit(nscount) - self.add16bit(arcount) - -class Hunpacker(Unpacker): - def getHeader(self): - id = self.get16bit() - flags = self.get16bit() - qr, opcode, aa, tc, rd, ra, z, rcode = ( - (flags>>15)&1, - (flags>>11)&0xF, - (flags>>10)&1, - (flags>>9)&1, - (flags>>8)&1, - (flags>>7)&1, - (flags>>4)&7, - (flags>>0)&0xF) - qdcount = self.get16bit() - ancount = self.get16bit() - nscount = self.get16bit() - arcount = self.get16bit() - return (id, qr, opcode, aa, tc, rd, ra, z, rcode, - qdcount, ancount, nscount, arcount) - - -# Pack/unpack Question (section 4.1.2) - -class Qpacker(Packer): - def addQuestion(self, qname, qtype, qclass): - self.addname(qname) - self.add16bit(qtype) - self.add16bit(qclass) - -class Qunpacker(Unpacker): - def getQuestion(self): - return self.getname(), self.get16bit(), self.get16bit() - - -# Pack/unpack Message(section 4) -# NB the order of the base classes is important for __init__()! - -class Mpacker(RRpacker, Qpacker, Hpacker): - pass - -class Munpacker(RRunpacker, Qunpacker, Hunpacker): - pass - - -# Routines to print an unpacker to stdout, for debugging. -# These affect the unpacker's current position! - -def dumpM(u): - print 'HEADER:', - (id, qr, opcode, aa, tc, rd, ra, z, rcode, - qdcount, ancount, nscount, arcount) = u.getHeader() - print 'id=%d,' % id, - print 'qr=%d, opcode=%d, aa=%d, tc=%d, rd=%d, ra=%d, z=%d, rcode=%d,' \ - % (qr, opcode, aa, tc, rd, ra, z, rcode) - if tc: print '*** response truncated! ***' - if rcode: print '*** nonzero error code! (%d) ***' % rcode - print ' qdcount=%d, ancount=%d, nscount=%d, arcount=%d' \ - % (qdcount, ancount, nscount, arcount) - for i in range(qdcount): - print 'QUESTION %d:' % i, - dumpQ(u) - for i in range(ancount): - print 'ANSWER %d:' % i, - dumpRR(u) - for i in range(nscount): - print 'AUTHORITY RECORD %d:' % i, - dumpRR(u) - for i in range(arcount): - print 'ADDITIONAL RECORD %d:' % i, - dumpRR(u) - -def dumpQ(u): - qname, qtype, qclass = u.getQuestion() - print 'qname=%s, qtype=%d(%s), qclass=%d(%s)' \ - % (qname, - qtype, dnstype.typestr(qtype), - qclass, dnsclass.classstr(qclass)) - -def dumpRR(u): - name, type, klass, ttl, rdlength = u.getRRheader() - typename = dnstype.typestr(type) - print 'name=%s, type=%d(%s), class=%d(%s), ttl=%d' \ - % (name, - type, typename, - klass, dnsclass.classstr(klass), - ttl) - mname = 'get%sdata' % typename - if hasattr(u, mname): - print ' formatted rdata:', getattr(u, mname)() - else: - print ' binary rdata:', u.getbytes(rdlength) - - -# Test program - -def test(): - import sys - import getopt - import socket - protocol = 'udp' - server = 'meermin.cwi.nl' # XXX adapt this to your local - port = 53 - opcode = dnsopcode.QUERY - rd = 0 - qtype = dnstype.MX - qname = 'cwi.nl' - try: - opts, args = getopt.getopt(sys.argv[1:], 'Trs:tu') - if len(args) > 2: raise getopt.error, 'too many arguments' - except getopt.error, msg: - print msg - print 'Usage: python dnslib.py', - print '[-T] [-r] [-s server] [-t] [-u]', - print '[qtype [qname]]' - print '-T: run testpacker() and exit' - print '-r: recursion desired (default not)' - print '-s server: use server (default %s)' % server - print '-t: use TCP protocol' - print '-u: use UDP protocol (default)' - print 'qtype: query type (default %s)' % \ - dnstype.typestr(qtype) - print 'qname: query name (default %s)' % qname - print 'Recognized qtype values:' - qtypes = dnstype.typemap.keys() - qtypes.sort() - n = 0 - for qtype in qtypes: - n = n+1 - if n >= 8: n = 1; print - print '%s = %d' % (dnstype.typemap[qtype], qtype), - print - sys.exit(2) - for o, a in opts: - if o == '-T': testpacker(); return - if o == '-t': protocol = 'tcp' - if o == '-u': protocol = 'udp' - if o == '-s': server = a - if o == '-r': rd = 1 - if args[0:]: - try: - qtype = eval(string.upper(args[0]), dnstype.__dict__) - except (NameError, SyntaxError): - print 'bad query type:', `args[0]` - sys.exit(2) - if args[1:]: - qname = args[1] - if qtype == dnstype.AXFR: - print 'Query type AXFR, protocol forced to TCP' - protocol = 'tcp' - print 'QTYPE %d(%s)' % (qtype, dnstype.typestr(qtype)) - m = Mpacker() - m.addHeader(0, - 0, opcode, 0, 0, rd, 0, 0, 0, - 1, 0, 0, 0) - m.addQuestion(qname, qtype, dnsclass.IN) - request = m.getbuf() - if protocol == 'udp': - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.connect((server, port)) - s.send(request) - reply = s.recv(1024) - else: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.connect((server, port)) - s.send(pack16bit(len(request)) + request) - s.shutdown(1) - f = s.makefile('r') - header = f.read(2) - if len(header) < 2: - print '*** EOF ***' - return - count = unpack16bit(header) - reply = f.read(count) - if len(reply) != count: - print '*** Incomplete reply ***' - return - u = Munpacker(reply) - dumpM(u) - if protocol == 'tcp' and qtype == dnstype.AXFR: - while 1: - header = f.read(2) - if len(header) < 2: - print '========== EOF ==========' - break - count = unpack16bit(header) - if not count: - print '========== ZERO COUNT ==========' - break - print '========== NEXT ==========' - reply = f.read(count) - if len(reply) != count: - print '*** Incomplete reply ***' - break - u = Munpacker(reply) - dumpM(u) - - -# Run test program when called as a script - -if __name__ == '__main__': - test() diff --git a/Demo/dns/dnsopcode.py b/Demo/dns/dnsopcode.py deleted file mode 100755 index f2e7cd5b0a..0000000000 --- a/Demo/dns/dnsopcode.py +++ /dev/null @@ -1,16 +0,0 @@ -# Opcode values in message header (section 4.1.1) - -QUERY = 0 -IQUERY = 1 -STATUS = 2 - -# Construct reverse mapping dictionary - -_names = dir() -opcodemap = {} -for _name in _names: - if _name[0] != '_': opcodemap[eval(_name)] = _name - -def opcodestr(opcode): - if opcodemap.has_key(opcode): return opcodemap[opcode] - else: return `opcode` diff --git a/Demo/dns/dnstype.py b/Demo/dns/dnstype.py deleted file mode 100755 index 80c2b76c45..0000000000 --- a/Demo/dns/dnstype.py +++ /dev/null @@ -1,41 +0,0 @@ -# TYPE values (section 3.2.2) - -A = 1 # a host address -NS = 2 # an authoritative name server -MD = 3 # a mail destination (Obsolete - use MX) -MF = 4 # a mail forwarder (Obsolete - use MX) -CNAME = 5 # the canonical name for an alias -SOA = 6 # marks the start of a zone of authority -MB = 7 # a mailbox domain name (EXPERIMENTAL) -MG = 8 # a mail group member (EXPERIMENTAL) -MR = 9 # a mail rename domain name (EXPERIMENTAL) -NULL = 10 # a null RR (EXPERIMENTAL) -WKS = 11 # a well known service description -PTR = 12 # a domain name pointer -HINFO = 13 # host information -MINFO = 14 # mailbox or mail list information -MX = 15 # mail exchange -TXT = 16 # text strings - -# Additional TYPE values from host.c source - -UNAME = 110 -MP = 240 - -# QTYPE values (section 3.2.3) - -AXFR = 252 # A request for a transfer of an entire zone -MAILB = 253 # A request for mailbox-related records (MB, MG or MR) -MAILA = 254 # A request for mail agent RRs (Obsolete - see MX) -ANY = 255 # A request for all records - -# Construct reverse mapping dictionary - -_names = dir() -typemap = {} -for _name in _names: - if _name[0] != '_': typemap[eval(_name)] = _name - -def typestr(type): - if typemap.has_key(type): return typemap[type] - else: return `type` diff --git a/Demo/embed/Makefile b/Demo/embed/Makefile deleted file mode 100644 index 9835c30ae2..0000000000 --- a/Demo/embed/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Makefile for embedded Python use demo - -# Top of the build tree and source tree -blddir= ../.. -srcdir= ../.. - -# Compiler flags -OPT= -g -INCLUDES= -I$(srcdir)/Include -I$(blddir) -DEFINES= -DHAVE_CONFIG_H -CFLAGS= $(OPT) $(DEFINES) $(INCLUDES) - -# Libraries (must be in this order!) -MYLIBS= $(blddir)/Modules/libModules.a \ - $(blddir)/Python/libPython.a \ - $(blddir)/Objects/libObjects.a \ - $(blddir)/Parser/libParser.a - -# XXX edit MODLIBS, LIBS and SYSLIBS to match $(blddir)/Modules/Makefile -MODLIBS= -LIBS= -SYSLIBS= -lm -ALLLIBS= $(MYLIBS) $(MODLIBS) $(LIBS) $(SYSLIBS) - -# Build the demo application -all: demo -demo: demo.o config.o - $(CC) demo.o config.o $(ALLLIBS) -o demo - -# Build config.o, suppressing the main() function -config.o: $(blddir)/Modules/config.c - $(CC) $(CFLAGS) -DNO_MAIN -c $(blddir)/Modules/config.c - -# Administrative targets - -test: demo - ./demo - -clean: - -rm -f *.o core - -clobber: clean - -rm -f *~ @* '#'* demo diff --git a/Demo/embed/README b/Demo/embed/README deleted file mode 100644 index 8858c713e4..0000000000 --- a/Demo/embed/README +++ /dev/null @@ -1,12 +0,0 @@ -This directory show how to embed the Python interpreter in your own -application. The file demo.c shows you all that is needed in your C -code. - -To build it, you may have to edit the Makefile: - -1) set blddir to the directory where you built Python, if it isn't in -the source directory (../..) - -2) change the variables that together define the list of libraries -(MODLIBS, LIBS, SYSLIBS) to link with, to match their definitions in -$(blddir)/Modules/Makefile diff --git a/Demo/embed/demo.c b/Demo/embed/demo.c deleted file mode 100644 index 418b225cf6..0000000000 --- a/Demo/embed/demo.c +++ /dev/null @@ -1,47 +0,0 @@ -/* Example of embedding Python in another program */ - -#include "Python.h" - -static char *argv0; - -main(argc, argv) - int argc; - char **argv; -{ - /* Save a copy of argv0 */ - argv0 = argv[0]; - - /* Initialize the Python interpreter. Required. */ - Py_Initialize(); - - /* Define sys.argv. It is up to the application if you - want this; you can also let it undefined (since the Python - code is generally not a main program it has no business - touching sys.argv...) */ - PySys_SetArgv(argc, argv); - - /* Do some application specific code */ - printf("Hello, brave new world\n\n"); - - /* Execute some Python statements (in module __main__) */ - PyRun_SimpleString("import sys\n"); - PyRun_SimpleString("print sys.builtin_module_names\n"); - PyRun_SimpleString("print sys.argv\n"); - - /* Note that you can call any public function of the Python - interpreter here, e.g. call_object(). */ - - /* Some more application specific code */ - printf("\nGoodbye, cruel world\n"); - - /* Exit, cleaning up the interpreter */ - Py_Exit(0); - /*NOTREACHED*/ -} - -/* This function is called by the interpreter to get its own name */ -char * -getprogramname() -{ - return argv0; -} diff --git a/Demo/ibrowse/README b/Demo/ibrowse/README deleted file mode 100644 index 22e403928d..0000000000 --- a/Demo/ibrowse/README +++ /dev/null @@ -1,34 +0,0 @@ -This directory contains a browser written in Python for "Info files" -as used by the Emacs documentation system. The browser requires that -Python is built with the "stdwin" option and runs under X11 or the -Mac window system. - -Now you can read Info files even if you can't spare the memory, time or -disk space to run Emacs. (I have used this extensively on a Macintosh -with 1 Megabyte main memory and a 20 Meg harddisk.) - -You can give this to someone with great fear of complex computer -systems, as long as they can use a mouse. - -Another reason to use this is to encourage the use of Info for on-line -documentation of software that is not related to Emacs or GNU. -(In particular, I plan to redo the Python and STDWIN documentation -in texinfo.) - -The main program is in file "ib.py"; this accepts a file name and a -node name as optional command line arguments, i.e., its usage is - - python ib.py [file [node]] - - -Configuration: - -- The pathname of the directory (or directories) containing -the standard Info files should be set by editing the -value assigned to INFOPATH in module ifile.py. - -- The default font should be set by editing the value of FONT -in this module (ibrowse.py). - -- For fastest I/O, you may look at BLOCKSIZE and a few other -constants in ifile.py. diff --git a/Demo/ibrowse/ib b/Demo/ibrowse/ib deleted file mode 100755 index 04cb790732..0000000000 --- a/Demo/ibrowse/ib +++ /dev/null @@ -1,2 +0,0 @@ -: ${ARCH}=`arch` -exec /ufs/guido/bin/$ARCH/python ib.py ${1+"$@"} diff --git a/Demo/ibrowse/ib.py b/Demo/ibrowse/ib.py deleted file mode 100755 index 588270ed49..0000000000 --- a/Demo/ibrowse/ib.py +++ /dev/null @@ -1,21 +0,0 @@ -#! /usr/local/bin/python - -# Call ibrowse (the info file browser) under UNIX. - -import sys -import ibrowse - -if len(sys.argv) > 1: - file = sys.argv[1] - if len(sys.argv) > 2: - if len(sys.argv) > 3: - sys.stdout = sys.stderr - print 'usage:', sys.argv[0], '[file [node]]' - sys.exit(2) - else: - node = sys.argv[2] - else: - node = '' - ibrowse.start('(' + file + ')' + node) -else: - ibrowse.main() diff --git a/Demo/ibrowse/ibrowse b/Demo/ibrowse/ibrowse deleted file mode 100755 index 8b0dcde30e..0000000000 --- a/Demo/ibrowse/ibrowse +++ /dev/null @@ -1,719 +0,0 @@ -This file documents the ibrowse program. -*-Text-*- -The H command of ibrowse goes to the node Help in this file. - -File: ibrowse Node: Top Up: (DIR) Next: Expert - -Ibrowse is a program for reading documentation, which you are using now. -** Ibrowse uses the file format of the Emacs Info program, and its -** commands are similar, but not identical. - -To learn how to use Ibrowse, type the command "h". It will bring you -to a programmed instruction sequence. - -* Menu: - -* Expert:: Advanced Ibrowse commands: c, k, g, s, 1 - 9, arrows. -* Add:: Describes how to add new nodes to the hierarchy. - Also tells what nodes look like. -* Menus:: How to add to or create menus in Info nodes. -* Cross-refs:: How to add cross-references to Info nodes. -* Tags:: How to make tag tables for Info files. -* Checking:: How to check the consistency of an Info file. -* Texinfo: (texinfo). - How to generate an Info file and a printed manual - from the same source file. - -File: ibrowse Node: Summary Next: Help - -Ibrowse is a Python program for browsing through the Emacs Info -documentation tree. Documentation in Info is divided into "nodes", -each of which discusses one topic and contains references to other -nodes which discuss related topics. Ibrowse has commands to follow the -references and show you other nodes. - -h Invoke the Ibrowse tutorial. -? Display this Summary node. -q Quit Ibrowse. -w Close current window. - -Selecting other nodes: -n Move to the "next" node of this node. -p Move to the "previous" node of this node. -m Pick menu item specified by name (or abbreviation). -1-9 Pick first..ninth in node's menu. - Menu items select nodes that are "subsections" of this node. -u Move "up" from this node (i.e., from a subsection to a section). -f Follow a cross reference by name (or abbrev). Type `l' to get back. -l Move back to the last node you were in. - -Moving within a node: -Space Scroll forward a full screen. DEL, BS Scroll backward. -b Go to beginning of node. - -Advanced commands: -k Clone current window (create an independent duplicate). -c Copy text selection to clipboard (for paste in another application). -g Move to node specified by name. - You may include a filename as well, as (FILENAME)NODENAME. -d Go to the main directory of Info files. -t Go to Top node of this file. -s Search through this Info file for node with specified regexp. - -File: ibrowse Node: Help-Small-Screen Next: Help - -Since your terminal has an unusually small number of lines on its -screen, it is necessary to give you special advice at the beginning. - -If you see the text "--All----" at near the bottom right corner of -the screen, it means the entire text you are looking at fits on the -screen. If you see "--Top----" instead, it means that there is more -text below that does not fit. To move forward through the text and -see another screen full, press the Space bar. To move back up, press -the key labeled Rubout or Delete or DEL. - -Here are 40 lines of junk, so you can try Spaces and Rubout and -see what they do. At the end are instructions of what you should do -next. - -This is line 17 -This is line 18 -This is line 19 -This is line 20 -This is line 21 -This is line 22 -This is line 23 -This is line 24 -This is line 25 -This is line 26 -This is line 27 -This is line 28 -This is line 29 -This is line 30 -This is line 31 -This is line 32 -This is line 33 -This is line 34 -This is line 35 -This is line 36 -This is line 37 -This is line 38 -This is line 39 -This is line 40 -This is line 41 -This is line 42 -This is line 43 -This is line 44 -This is line 45 -This is line 46 -This is line 47 -This is line 48 -This is line 49 -This is line 50 -This is line 51 -This is line 52 -This is line 53 -This is line 54 -This is line 55 -This is line 56 - -If you have managed to get here, go back to the beginning with -Rubout, and come back here again, then you understand Space and -Rubout. So now type an "n"--just one character; don't type the -quotes and don't type a Return afterward-- to get to the normal start -of the course. - -File: ibrowse Node: Help Next: Help-P Previous: Help-Small-Screen - -You are talking to the program Ibrowse, for reading documentation. - - Right now you are looking at one "Node" of Information. -A node contains text describing a specific topic at a specific -level of detail. This node's topic is "how to use Ibrowse". - - The top line of a node is its "header". This node's header (look at -it now) says that it is the node named "Help" in the file "ibrowse". -It says that the Next node after this one is the node called "Help-P". -An advanced Ibrowse command lets you go to any node whose name you know. - - Besides a "Next", a node can have a "Previous" or an "Up". -This node has a "Previous" but no "Up", as you can see. - - Now it's time to move on to the Next node, named "Help-P". - ->> Type "n" to move there. Type just one character; - don't type the quotes and don't type a Return afterward. - -">>" in the margin means it is really time to try a command. - -File: ibrowse Node: Help-P Next: Help-Page Previous: Help - -This node is called "Help-P". The "Previous" node, as you see, is -"Help", which is the one you just came from using the "N" command. -Another "N" command now would take you to the Next node, "Help-Page". - ->> But don't do that yet. First, try the "p" command, which takes -you to the Previous node. When you get there, you can do an "n" -again to return here. - - This all probably seems insultingly simple so far, but DON'T be -led into skimming. Things will get more complicated soon. Also, -don't try a new command until you are told it's time to. Otherwise, -you may make Ibrowse skip past an important warning that was coming up. - ->> Now do an "n" to get to the node "Help-Page" and learn more. - -File: ibrowse Node: Help-Page Next: Help-M Previous: Help-P - -Space, Backspace, and B commands. - - This node's header tells you that you are now at node "Help-Page", and -that "P" would get you back to "Help-P". The line starting "Space," -is a "Title", saying what the node is about (most nodes have titles). - - This is a big node and it doesn't all fit on your display screen. -You can tell that there is more that isn't visible because you -the scroll bar on the side of the window has become active (gray). - - The Space, Backspace and B commands exist to allow you to "move -around" in a node that doesn't all fit on the screen at once. -Space moves forward, to show what was below the bottom of the screen. -Backspace moves backward, to show what was above the top of the screen -(there isn't anything above the top until you have typed some spaces). - ->> Now try typing a Space (afterward, type a Backspace to return here). - - When you type the space, the two lines that were at the bottom of the -screen appear at the top, followed by more lines. Backspace takes the -two lines from the top and moves them to the bottom, USUALLY, but if -there are not a full screen's worth of lines above them they may not -make it all the way to the bottom. - - If you type a Space when there is no more to see, it will ring the -bell and otherwise do nothing. The same goes for a Backspace when -the header of the node is visible. - - Of course you can use the mouse and directly move the scroll bar -as well, but Ibrowse has keyboard commands for almost everything, -including scrolling. These keyboard commands are called "shortcuts", -because it generally takes less effort to press a key on the -keyboard than to move the mouse. On the other hand, if you are -an infrequent user of Ibrowse, you can do everything with the -mouse that you can do with the keyboard. Just look in the menus -(I'm sure you must know how to use the menus on this system, or -else you couldn't have gotten this far...). In fact you'll see that -the commands and shortcuts listed in the menus are the same as those -described in this course. You can use the shortcuts either with or -without the "Command" or "Meta" key. - - Two menus are always available: the "Ibrowse" menu contains commands -pertaining to the Ibrowse program at large, while the "Navigation" menu -contains commands that move around between nodes. There may be other -menus; these will be explained later. - - To move back to the beginning of the node you are on, you can type -a lot of Backspaces. You can also type simply "b" for beginning. ->> Try that now. (I have put in enough verbiage to make sure you are - not on the first screenful now). Then come back, with Spaces. - - You have just learned a considerable number of commands. If you -want to use one but have trouble remembering which, just pull down -the menus to get a summary of commands and shortcuts. Some additional -shortcuts (not listed in the menus) are listed by the "Short help" -command. This brings up a dialog box which you can acknowledge -by clicking the OK button or pressing the Return key. - - From now on, you will encounter large nodes without warning, and -will be expected to know how to use Space and Backspace to move -around in them without being told. Since you could change the -size of the window used, it would be impossible to warn you anyway. - ->> Now type "n" to see the description of the "m" command. - -File: ibrowse Node: Help-M Next: Help-Adv Previous: Help-Page - -Menus and the "m" command - - With only the "n" and "p" commands for moving between nodes, nodes -are restricted to a linear sequence. Menus allow a branching -structure. A menu is a list of other nodes you can move to. It is -actually just part of the text of the node formatted specially so that -Ibrowse can interpret it. The beginning of a menu is always identified -by a line which starts with "* Menu:". A node contains a menu if and -only if it has a line in it which starts that way. The only menu you -can use at any moment is the one in the node you are in. To use a -menu in any other node, you must move to that node first. - - (There is an unfortunate confusion of terms here. "Menu" may refer -to one of the Ibrowse menus at the top, such as as the "Ibrowse" and -"Navigation" menus explained in the previous node, or to the menu in -a node. Where confusion is possible, these will be disambiguated by -calling them "Ibrowse menus" or "node menu".) - - After the start of the menu, each line that starts with a "*" -identifies one subtopic. The line will usually contain a brief name -for the subtopic (followed by a ":"), the name of the node that talks -about that subtopic, and optionally some further description of the -subtopic. Lines in the menu that don't start with a "*" have no -special meaning - they are only for the human reader's benefit and do -not define additional subtopics. Here is an example: -* Foo: FOO's Node This tells about FOO -The subtopic name is Foo, and the node describing it is "FOO's Node". -The rest of the line is just for the reader's Information. -[[ But this line is not a real menu item, simply because there is -no line above it which starts with "* Menu:".]] - - When you use a menu to go to another node (in a way that will be -described soon), what you specify is the subtopic name, the first -thing in the menu line. Ibrowse uses it to find the menu line, extracts -the node name from it, and goes to that node. The reason that there -is both a subtopic name and a node name is that the node name must be -meaningful to the computer and may therefore have to be ugly looking. -The subtopic name can be chosen just to be convenient for the user to -specify. Often the node name is convenient for the user to specify -and so both it and the subtopic name are the same. There is an -abbreviation for this: -* Foo:: This tells about FOO -This means that the subtopic name and node name are the same; they are -both "Foo". - ->> Now use Spaces to find the menu in this node, then come back to -the front with a "b". As you see, a menu is actually visible -in its node. If you can't find a menu in a node by looking at it, -then the node doesn't have a menu and the "m" command is not available. - - (Actually, a quicker way to see if there is a node menu, is to look -for an Ibrowse menu at the top named "Menu".) - - The command to go to one of the subnodes is "m" - but DON'T DO IT -YET! Before you use "m", you must understand the difference between -commands and arguments. So far, you have learned several commands -that do not need arguments. When you type one, Ibrowse processes it and -is instantly ready for another command. The "m" command is different: -it is incomplete without the NAME OF THE SUBTOPIC. Once you have -typed "m", Ibrowse wants to read the subtopic name. - - Thanks to modern user interface technology, this will be obvious: -you are prompted for the subtopic name in a dialog box. When you are -finished typing the name, press Return or click the OK button. You can -cancel the dialog box by clicking the Cancel button. The first subtopic -is provided as a default choice, so if you want to go there, you can -just press Return. - - You can abbreviate the subtopic name. If the abbreviation is not -unique, the first matching subtopic is chosen. Some menus will put -the shortest possible abbreviation for each subtopic name in capital -letters, so you can see how much you need to type. It does not -matter whether you use upper case or lower case when you type the -subtopic. You should not put any spaces at the end, or inside of the -item name, except for one space where a space appears in the item in -the menu. - - Here is a menu to give you a chance to practice. - -* Menu: The menu starts here. - -This menu gives you three ways of going to one place, Help-FOO. - -* Foo: Help-FOO A node you can visit for fun -* Bar: Help-FOO Strange! two ways to get to the same place. -* Help-FOO:: And yet another! - ->> Now type just an "m" and see what happens. (Read ahead before ->> trying this out, as the dialog box will probably cover these ->> instructions!) - - Now you are "inside" an "m" command. Commands can't be used now; -the next thing you will type must be the name of a subtopic. - - You can change your mind about doing the "m" by clicking the Cancel -button. ->> Try that now; notice the dialog box disappear. ->> Then type another "m". - ->> Now type "BAR", the item name. Don't type Return yet. - - While you are typing the item name, you can use the Backspace -key to cancel one character at a time if you make a mistake. ->> Type one to cancel the "R". You could type another "R" to -replace it. You don't have to, since "BA" is a valid abbreviation. ->> Now you are ready to go. Type a Return. - - After visiting Help-FOO, you should return here (it will tell how). - ->> Type "n" to see more commands. - -File: ibrowse Node: Help-FOO Up: Help-M - -The "u" command - - Congratulations! This is the node Help-FOO. Unlike the other -nodes you have seen, this one has an "Up": "Help-M", the node you -just came from via the "m" command. This is the usual convention-- -the nodes you reach from a menu have Ups that lead back to the menu. -Menus move Down in the tree, and Up moves Up. Previous, on the other -hand, is usually used to "stay on the same level but go backwards". - - You can go back to the node Help-M by typing the command -"u" for "Up". That will put you at the FRONT of the node - to get -back to where you were reading you will have to type some Spaces. - ->> Now type "u" to move back up to Help-M. - -File: ibrowse Node: Help-Adv Next: Help-Q Previous: Help-M - -Some advanced Ibrowse commands - - The course is almost over, so please stick with it to the end. - - If you have been moving around to different nodes and wish to -retrace your steps, the "l" command ("l" for "last") will do that, one -node at a time. If you have been following directions, an "l" command -now will get you back to Help-M. Another "l" command would undo the "u" -and get you back to Help-FOO. Another "l" would undo the M and get you -back to Help-M. - ->> Try typing three "l"'s, pausing in between to see what each "l" does. -Then follow directions again and you will end up back here. - - Note the difference between "l" and "p": "l" moves to where YOU -last were, whereas "p" always moves to the node which the header says -is the "Previous" node (from this node, to Help-M). - - The "d" command gets you instantly to the Directory node. -This node, which is the first one you saw when you entered Ibrowse, -has a menu which leads (directly, or indirectly through other menus), -to all the nodes that exist. - ->> Try doing a "d", then do an "l" to return here (yes, DO return). - - Sometimes, in Ibrowse documentation, you will see a cross reference. -Cross references look like this: *Note Cross: Help-Cross. That is a -real, live cross reference which is named "Cross" and points at the -node named "Help-Cross". - - If you wish to follow a cross reference, you must use the "f" -command. The "f" prompts for the cross reference name (in this case, -"Cross") with a dialog box. - ->> Type "f", followed by "Cross", and a Return. - - The "f" command allows abbreviations just like "m". - - To get a list of all the cross references in the current node, -look in the Ibrowse menu at the top labeled "Footnotes". This menu is -only present if there are cross references in the current node, and -can be used to directly follow a cross reference, just like the "Menu" -menu is another way to choose an item of the node's menu. - ->> Now type "n" to see the last node of the course. - -File: ibrowse Node: Help-Cross - - This is the node reached by the cross reference named "Cross". - - While this node is specifically intended to be reached by a cross -reference, most cross references lead to nodes that "belong" someplace -else far away in the structure of Ibrowse. So you can't expect the -footnote to have a Next, Previous or Up pointing back to where you -came from. In general, the "l" (el) command is the only way to get -back there. - ->> Type "l" to return to the node where the cross reference was. - -File: ibrowse Node: Help-Q Previous: Help-Adv Up: Top - - To get out of Ibrowse, type "q" for "Quit". All Ibrowse windows -will be closed (on UNIX, only those managed by the same process). -To close just one window, use the standard method of closing windows -on your system; you can also use "w". - - This is the end of the course on using Ibrowse. There are some other -commands that are not essential or meant for experienced users; they -are useful, and you can find them by looking in the directory for -documentation on Ibrowse. Finding them will be a good exercise in using -Ibrowse in the usual manner. - ->> Close this window and find back the window where you typed "h" - to enter this tutorial. - Then type "d" to go to the Ibrowse directory node if necessary, - and choose the "Ibrowse" menu item, to get to the node about - Ibrowse and see what other help is available. - -File: ibrowse, Node: Expert, Up: Top, Previous: Top, Next: Add - -Some Advanced Ibrowse Commands ("c", "k", "g", "s", "1" - "9", arrows). - -The "c" command lets you copy text from the window to the clipboard. -You must first select the text to be copied with the mouse. - -The "k" command means "klone" (we are running out of letters now...). -It creates a new Ibrowse window, showing the same node as the current. -You can then make an excursion in the new window to different nodes or -files, while the old window keeps showing the original node. Each -window has its own history for use by the "l" command. - -If you know a node's name, you can go there with the "g" command. -This prompts for a node name with a dialog box. Entering, "Top" -would go to the node called Top in this file (its directory node). -Pressing "g" again and entering "Expert" would come back here. - -Unlike "m", "g" does not allow the use of abbreviations. - -To go to a node in another file, you can include the filename in the -node name by putting it at the front, in parentheses. Thus, -"(dir)Top" would go to the Ibrowse Directory node, which is -node Top in the file dir. - -The node name "*" specifies the whole file. So you can look at all -of the current file by typing "*" or all of any other file -with "(FILENAME)*". - -File names are converted to lower case before they are tried; this -is necessary to be compatible with Emacs Info. (File names are -generally relative to the Info directory, but needn't be.) - -The "s" command allows you to search a whole file for a regular -expression. Unlike the corresponding Emacs Info command, it will -not search beyond the end of the current node. - -Regular expressions are like in UNIX egrep; if you don't know what -regular expressions are, limit your search strings to letters, digits -and spaces. Searches in Ibrowse are case-sensitive; searching for -"foo" will not find "Foo" or "FOO"! - -A description of regular expressions as they occur in Emacs is -available. (*Note Emacs Regular Expressions: (regex)syntax.) -Ibrowse regular expressions are slightly different: the meaning -of \( \| \) is swapped with that of ( | ), and there are no -escapes to handle "words" specially. - -Searching starts after the current focus position. The "B" command -resets the focus to the beginning of the file, but space and backspace -leave it unchanged (so they may render the focus invisible). - -If you grudge the system each character of type-in it requires, -you might like to use the commands "1", "2", "3", through "9". -They are short for the first nine entries of the node menu. - -The left, right and up arrow keys are duplicates of "p", "n" and "u". - -The down arrow key, as well as the Return key, goes to the first item -of the node's menu if there is one, else it executes "n". This is a -quick way to visit all nodes in a tree in pre-order: use Return to go -down and right as far as possible, then use "u" and "n" to go right -at the next higher level. - -File: ibrowse, Node: Add, Up: Top, Previous: Expert, Next: Menus - -To add a new topic to the list in the directory, you must - 1) enter the Emacs text editor. *Note Emacs: (emacs). - 2) create a node, in some file, to document that topic. - 3) put that topic in the menu in the directory. *Note Menu: Menus. - - The new node can live in an existing documentation file, or in a new -one. It must have a ^_ character before it (invisible to the user; -this node has one but you can't see it), and it ends with either a ^_, -or the end of file. A nice way to make a node boundary be a -page boundary as well is to put a ^L RIGHT AFTER the ^_. - - The ^_ starting a node must be followed by a newline or a ^L newline, -after which comes the node's header line. The header line must give -the node's name (by which Ibrowse will find it), and state the names of -the Next, Previous, and Up nodes (if there are any). As you can see, -this node's Up node is the node Top, which points at all the -documentation for Ibrowse. The Next node is "Menus". - - The keywords "Node", "Previous", "Up" and "Next", may appear in -any order, anywhere in the header line, but the recommended order is -the one in this sentence. Each keyword must be followed by a colon, -spaces and tabs, and then the appropriate name. The name may be -terminated with a tab, a comma, or a newline. A space does not end -it; node names may contain spaces. The case of letters in the names -is insignificant. "Previous" can be abbreviated to "Prev". - - A node name has two forms. A node in the current file is named by -what appears after the "Node: " in that node's first line. For -example, this node's name is "Add". A node in another file is named -by "(FILENAME)NODE-WITHIN-FILE", as in "(ibrowse)Add" for this node. -If the file name is relative, it is taken starting from the standard -Info file directory of your site. The name "(FILENAME)Top" can be -abbreviated to just "(FILENAME)". By convention, the name "Top" is -used for the "highest" node in any single file - the node whose "Up" -points out of the file. The Directory node is "(dir)". The Top node -of a document file listed in the Directory should have an "Up: (dir)" -in it. - - The node name "*" is special: it refers to the entire file. Thus, -g* will show you the whole current file. The use of the node * is to -make it possible to make old-fashioned, unstructured files into nodes -of the tree. Footnotes and node menus appearing in a file are disabled -when it is viewed in this way. - - The "Node:" name, in which a node states its own name, must not -contain a filename, since Ibrowse when searching for a node does not -expect one to be there. The Next, Previous and Up names may contain -them. In this node, since the Up node is in the same file, it was not -necessary to use one. - - Note that the nodes in this file have a File name in the header -line. The File names are ignored by Ibrowse, but they serve as -comments to help identify the node for the user. - -File: ibrowse, Node: Menus, Previous: Add, Up: Top, Next: Cross-refs - -How to Create Menus: - - Any node in the Ibrowse hierarchy may have a MENU--a list of subnodes. -The "m" command searches the current node's menu for the topic which it -reads from the terminal. - - A menu begins with a line starting with "* Menu:". The rest of the -line is a comment. After the starting line, every line that begins -with a "* " lists a single topic. The name of the topic--the arg -that the user must give to the "m" command to select this topic-- -comes right after the star and space, and is followed by -a colon, spaces and tabs, and the name of the node which discusses -that topic. The node name, like node names following Next, -Previous and Up, may be terminated with a tab, comma, or newline; -it may also be terminated with a period. - - If the node name and topic name are the same, than rather than -giving the name twice, the abbreviation "* NAME::" may be used -(and should be used, whenever possible, as it reduces the visual -clutter in the menu). - - It is considerate to choose the topic names so that they differ -from each other very near the beginning--this allows the user to type -short abbreviations. In a long menu, it is a good idea to capitalize -the beginning of each item name which is the minimum acceptable -abbreviation for it (a long menu is more than 5 or so entries). - - The node's listed in a node's menu are called its "subnodes", and -it is their "superior". They should each have an "Up:" pointing at -the superior. It is often useful to arrange all or most of the -subnodes in a sequence of Next's/Previous's so that someone who -wants to see them all need not keep revisiting the Menu. - - The Info Directory is simply the menu of the node "(dir)Top"--that -is, node Top in file .../info/dir. You can put new entries in that -menu just like any other menu. The Info Directory is NOT the same as -the file directory called "info". It happens that many of Ibrowse's -files live on that file directory, but they don't have to; and files -on that directory are not automatically listed in the Info Directory -node. - - The Ibrowse program uses a second directory called .../ibrowse, -which contains versions of the "dir" and "info" files adapted to -Ibrowse (the latter renamed to "ibrowse", obviously). It searches -any file first in the "ibrowse", then in the "info" directory. -(Actually, the search path is configurable.) - - Also, although the Info node graph is claimed to be a "hierarchy", -in fact it can be ANY directed graph. Shared structures and pointer -cycles are perfectly possible, and can be used if they are -appropriate to the meaning to be expressed. There is no need for all -the nodes in a file to form a connected structure. In fact, this -file has two connected components. You are in one of them, which is -under the node Top; the other contains the node Help which the "h" -command goes to. In fact, since there is no garbage collector, -nothing terrible happens if a substructure is not pointed to, but -such a substructure will be rather useless since nobody will ever -find out that it exists. - -File: ibrowse, Node: Cross-refs, Previous: Menus, Up: Top, Next: Tags - -Creating Cross References: - - A cross reference can be placed anywhere in the text, unlike a menu -item which must go at the front of a line. A cross reference looks -like a menu item except that it has "*note" instead of "*". It CANNOT -be terminated by a ")", because ")"'s are so often part of node names. -If you wish to enclose a cross reference in parentheses, terminate it -with a period first. Here are two examples of cross references pointers: - - *Note details: commands. (See *note 3: Full Proof.) - -They are just examples. The places they "lead to" don't really exist! - -File: ibrowse, Node: Tags, Previous: Cross-refs, Up: Top, Next: Checking - -Tag Tables for Info Files: - - You can speed up the access to nodes of a large Info file by giving -it a tag table. Unlike the tag table for a program, the tag table for -an Info file lives inside the file itself and will automatically be -used whenever Ibrowse reads in the file. - - To make a tag table, go to a node in the file using Emacs Info and type -M-x Info-tagify. Then you must use C-x C-s to save the file. - - Once the Info file has a tag table, you must make certain it is up -to date. If, as a result of deletion of text, any node moves back -more than a thousand characters in the file from the position -recorded in the tag table, Ibrowse will no longer be able to find that -node. To update the tag table, use the Info-tagify command again. - - An Info file tag table appears at the end of the file and looks like -this: - -^_^L -Tag Table: -File: ibrowse, Node: Cross-refs21419 -File: ibrowse, Node: Tags22145 -^_ -End Tag Table - -Note that it contains one line per node, and this line contains -the beginning of the node's header (ending just after the node name), -a rubout (DEL) character, and the character position in the file of the -beginning of the node. The words "Tag Table" may occur in lower case -as well. - -It is also possible for an extra level of indirection to be present. -In this case, the first line of the Tag table contains the string -"(Indirect)", and preceding the tag table is another "pseudo node" -whose header reads "Indirect:". Each following line has the form -"filename: offset", meaning that nodes at that offset or larger (but -less than the offset in the next line) really occur in the file named -here, and that the file's offset should be subtracted from the node's -offset. (Indirect tables are created by texinfo for large files. -*Note Texinfo: (texinfo). *Note Splitting files: (texinfo)Splitting.) - -File: ibrowse, Node: Checking, Previous: Tags, Up: Top - -Checking an Info File: - - When creating an Info file, it is easy to forget the name of a node -when you are making a pointer to it from another node. If you put in -the wrong name for a node, this will not be detected until someone -tries to go through the pointer using Ibrowse. Verification of the Info -file is an automatic process which checks all pointers to nodes and -reports any pointers which are invalid. Every Next, Previous, and Up -is checked, as is every menu item and every cross reference. In addition, -any Next which doesn't have a Previous pointing back is reported. -Only pointers within the file are checked, because checking pointers -to other files would be terribly slow. But those are usually few. - - To check an Info file, do M-x Info-validate while looking at any -node of the file with Emacs Info. - -Tag table: -Node: Top117 -Node: Summary952 -Node: Help-Small-Screen997 -Node: Help2628 -Node: Help-P3588 -Node: Help-Page4348 -Node: Help-M7763 -Node: Help-FOO13183 -Node: Help-Adv13887 -Node: Help-Cross15923 -Node: Help-Q16443 -Node: Expert17326 -Node: Add20280 -Node: Menus23273 -Node: Cross-refs26394 -Node: Tags27050 -Node: Checking28966 - -End tag table diff --git a/Demo/ibrowse/ibrowse.py b/Demo/ibrowse/ibrowse.py deleted file mode 100755 index 41574adba7..0000000000 --- a/Demo/ibrowse/ibrowse.py +++ /dev/null @@ -1,617 +0,0 @@ -# Browser for "Info files" as used by the Emacs documentation system. -# -# Now you can read Info files even if you can't spare the memory, time or -# disk space to run Emacs. (I have used this extensively on a Macintosh -# with 1 Megabyte main memory and a 20 Meg harddisk.) -# -# You can give this to someone with great fear of complex computer -# systems, as long as they can use a mouse. -# -# Another reason to use this is to encourage the use of Info for on-line -# documentation of software that is not related to Emacs or GNU. -# (In particular, I plan to redo the Python and STDWIN documentation -# in texinfo.) - - -# NB: this is not a self-executing script. You must startup Python, -# import ibrowse, and call ibrowse.main(). On UNIX, the script 'ib' -# runs the browser. - - -# Configuration: -# -# - The pathname of the directory (or directories) containing -# the standard Info files should be set by editing the -# value assigned to INFOPATH in module ifile.py. -# -# - The default font should be set by editing the value of FONT -# in this module (ibrowse.py). -# -# - For fastest I/O, you may look at BLOCKSIZE and a few other -# constants in ifile.py. - - -# This is a fairly large Python program, split in the following modules: -# -# ibrowse.py Main program and user interface. -# This is the only module that imports stdwin. -# -# ifile.py This module knows about the format of Info files. -# It is imported by all of the others. -# -# itags.py This module knows how to read prebuilt tag tables, -# including indirect ones used by large texinfo files. -# -# icache.py Caches tag tables and visited nodes. - - -# XXX There should really be a different tutorial, as the user interface -# XXX differs considerably from Emacs... - - -import sys -import regexp -import stdwin -from stdwinevents import * -import string -from ifile import NoSuchFile, NoSuchNode -import icache - - -# Default font. -# This should be an acceptable argument for stdwin.setfont(); -# on the Mac, this can be a pair (fontname, pointsize), while -# under X11 it should be a standard X11 font name. -# For best results, use a constant width font like Courier; -# many Info files contain tabs that don't align with other text -# unless all characters have the same width. -# -#FONT = ('Monaco', 9) # Mac -FONT = '-schumacher-clean-medium-r-normal--14-140-75-75-c-70-iso8859-1' # X11 - - -# Try not to destroy the list of windows when reload() is used. -# This is useful during debugging, and harmless in production... -# -try: - dummy = windows - del dummy -except NameError: - windows = [] - - -# Default main function -- start at the '(dir)' node. -# -def main(): - start('(dir)') - - -# Start at an arbitrary node. -# The default file is 'ibrowse'. -# -def start(ref): - stdwin.setdefscrollbars(0, 1) - stdwin.setfont(FONT) - stdwin.setdefwinsize(76*stdwin.textwidth('x'), 22*stdwin.lineheight()) - makewindow('ibrowse', ref) - mainloop() - - -# Open a new browser window. -# Arguments specify the default file and a node reference -# (if the node reference specifies a file, the default file is ignored). -# -def makewindow(file, ref): - win = stdwin.open('Info file Browser, by Guido van Rossum') - win.mainmenu = makemainmenu(win) - win.navimenu = makenavimenu(win) - win.textobj = win.textcreate((0, 0), win.getwinsize()) - win.file = file - win.node = '' - win.last = [] - win.pat = '' - win.dispatch = idispatch - win.nodemenu = None - win.footmenu = None - windows.append(win) - imove(win, ref) - -# Create the 'Ibrowse' menu for a new browser window. -# -def makemainmenu(win): - mp = win.menucreate('Ibrowse') - mp.callback = [] - additem(mp, 'New window (clone)', 'K', iclone) - additem(mp, 'Help (tutorial)', 'H', itutor) - additem(mp, 'Command summary', '?', isummary) - additem(mp, 'Close this window', 'W', iclose) - additem(mp, '', '', None) - additem(mp, 'Copy to clipboard', 'C', icopy) - additem(mp, '', '', None) - additem(mp, 'Search regexp...', 'S', isearch) - additem(mp, '', '', None) - additem(mp, 'Reset node cache', '', iresetnodecache) - additem(mp, 'Reset entire cache', '', iresetcache) - additem(mp, '', '', None) - additem(mp, 'Quit', 'Q', iquit) - return mp - -# Create the 'Navigation' menu for a new browser window. -# -def makenavimenu(win): - mp = win.menucreate('Navigation') - mp.callback = [] - additem(mp, 'Menu item...', 'M', imenu) - additem(mp, 'Follow reference...', 'F', ifollow) - additem(mp, 'Go to node...', 'G', igoto) - additem(mp, '', '', None) - additem(mp, 'Next node in tree', 'N', inext) - additem(mp, 'Previous node in tree', 'P', iprev) - additem(mp, 'Up in tree', 'U', iup) - additem(mp, 'Last visited node', 'L', ilast) - additem(mp, 'Top of tree', 'T', itop) - additem(mp, 'Directory node', 'D', idir) - return mp - -# Add an item to a menu, and a function to its list of callbacks. -# (Specifying all in one call is the only way to keep the menu -# and the list of callbacks in synchrony.) -# -def additem(mp, text, shortcut, function): - if shortcut: - mp.additem(text, shortcut) - else: - mp.additem(text) - mp.callback.append(function) - - -# Stdwin event processing main loop. -# Return when there are no windows left. -# Note that windows not in the windows list don't get their events. -# -def mainloop(): - while windows: - event = stdwin.getevent() - if event[1] in windows: - try: - event[1].dispatch(event) - except KeyboardInterrupt: - # The user can type Control-C (or whatever) - # to leave the browser without closing - # the window. Mainly useful for - # debugging. - break - except: - # During debugging, it was annoying if - # every mistake in a callback caused the - # whole browser to crash, hence this - # handler. In a production version - # it may be better to disable this. - # - msg = sys.exc_type - if sys.exc_value: - val = sys.exc_value - if type(val) <> type(''): - val = `val` - msg = msg + ': ' + val - msg = 'Oops, an exception occurred: ' + msg - event = None - stdwin.message(msg) - event = None - - -# Handle one event. The window is taken from the event's window item. -# This function is placed as a method (named 'dispatch') on the window, -# so the main loop will be able to handle windows of a different kind -# as well, as long as they are all placed in the list of windows. -# -def idispatch(event): - type, win, detail = event - if type == WE_CHAR: - if not keybindings.has_key(detail): - detail = string.lower(detail) - if keybindings.has_key(detail): - keybindings[detail](win) - return - if detail in '0123456789': - i = eval(detail) - 1 - if i < 0: i = len(win.menu) + i - if 0 <= i < len(win.menu): - topic, ref = win.menu[i] - imove(win, ref) - return - stdwin.fleep() - return - if type == WE_COMMAND: - if detail == WC_LEFT: - iprev(win) - elif detail == WC_RIGHT: - inext(win) - elif detail == WC_UP: - iup(win) - elif detail == WC_DOWN: - idown(win) - elif detail == WC_BACKSPACE: - ibackward(win) - elif detail == WC_RETURN: - idown(win) - else: - stdwin.fleep() - return - if type == WE_MENU: - mp, item = detail - if mp == None: - pass # A THINK C console menu was selected - elif mp in (win.mainmenu, win.navimenu): - mp.callback[item](win) - elif mp == win.nodemenu: - topic, ref = win.menu[item] - imove(win, ref) - elif mp == win.footmenu: - topic, ref = win.footnotes[item] - imove(win, ref) - return - if type == WE_SIZE: - win.textobj.move((0, 0), win.getwinsize()) - (left, top), (right, bottom) = win.textobj.getrect() - win.setdocsize(0, bottom) - return - if type == WE_CLOSE: - iclose(win) - return - if not win.textobj.event(event): - pass - - -# Paging callbacks - -def ibeginning(win): - win.setorigin(0, 0) - win.textobj.setfocus(0, 0) # To restart searches - -def iforward(win): - lh = stdwin.lineheight() # XXX Should really use the window's... - h, v = win.getorigin() - docwidth, docheight = win.getdocsize() - width, height = win.getwinsize() - if v + height >= docheight: - stdwin.fleep() - return - increment = max(lh, ((height - 2*lh) / lh) * lh) - v = v + increment - win.setorigin(h, v) - -def ibackward(win): - lh = stdwin.lineheight() # XXX Should really use the window's... - h, v = win.getorigin() - if v <= 0: - stdwin.fleep() - return - width, height = win.getwinsize() - increment = max(lh, ((height - 2*lh) / lh) * lh) - v = max(0, v - increment) - win.setorigin(h, v) - - -# Ibrowse menu callbacks - -def iclone(win): - stdwin.setdefwinsize(win.getwinsize()) - makewindow(win.file, win.node) - -def itutor(win): - # The course looks best at 76x22... - stdwin.setdefwinsize(76*stdwin.textwidth('x'), 22*stdwin.lineheight()) - makewindow('ibrowse', 'Help') - -def isummary(win): - stdwin.setdefwinsize(76*stdwin.textwidth('x'), 22*stdwin.lineheight()) - makewindow('ibrowse', 'Summary') - -def iclose(win): - # - # Remove the window from the windows list so the mainloop - # will notice if all windows are gone. - # Delete the textobj since it constitutes a circular reference - # to the window which would prevent it from being closed. - # (Deletion is done by assigning None to avoid crashes - # when closing a half-initialized window.) - # - if win in windows: - windows.remove(win) - win.textobj = None - -def icopy(win): - focustext = win.textobj.getfocustext() - if not focustext: - stdwin.fleep() - else: - stdwin.rotatecutbuffers(1) - stdwin.setcutbuffer(0, focustext) - # XXX Should also set the primary selection... - -def isearch(win): - try: - pat = stdwin.askstr('Search pattern:', win.pat) - except KeyboardInterrupt: - return - if not pat: - pat = win.pat - if not pat: - stdwin.message('No previous pattern') - return - try: - cpat = regexp.compile(pat) - except regexp.error, msg: - stdwin.message('Bad pattern: ' + msg) - return - win.pat = pat - f1, f2 = win.textobj.getfocus() - text = win.text - match = cpat.match(text, f2) - if not match: - stdwin.fleep() - return - a, b = match[0] - win.textobj.setfocus(a, b) - - -def iresetnodecache(win): - icache.resetnodecache() - -def iresetcache(win): - icache.resetcache() - -def iquit(win): - for win in windows[:]: - iclose(win) - - -# Navigation menu callbacks - -def imenu(win): - ichoice(win, 'Menu item (abbreviated):', win.menu, whichmenuitem(win)) - -def ifollow(win): - ichoice(win, 'Follow reference named (abbreviated):', \ - win.footnotes, whichfootnote(win)) - -def igoto(win): - try: - choice = stdwin.askstr('Go to node (full name):', '') - except KeyboardInterrupt: - return - if not choice: - stdwin.message('Sorry, Go to has no default') - return - imove(win, choice) - -def inext(win): - prev, next, up = win.header - if next: - imove(win, next) - else: - stdwin.fleep() - -def iprev(win): - prev, next, up = win.header - if prev: - imove(win, prev) - else: - stdwin.fleep() - -def iup(win): - prev, next, up = win.header - if up: - imove(win, up) - else: - stdwin.fleep() - -def ilast(win): - if not win.last: - stdwin.fleep() - else: - i = len(win.last)-1 - lastnode, lastfocus = win.last[i] - imove(win, lastnode) - if len(win.last) > i+1: - # The move succeeded -- restore the focus - win.textobj.setfocus(lastfocus) - # Delete the stack top even if the move failed, - # else the whole stack would remain unreachable - del win.last[i:] # Delete the entry pushed by imove as well! - -def itop(win): - imove(win, '') - -def idir(win): - imove(win, '(dir)') - - -# Special and generic callbacks - -def idown(win): - if win.menu: - default = whichmenuitem(win) - for topic, ref in win.menu: - if default == topic: - break - else: - topic, ref = win.menu[0] - imove(win, ref) - else: - inext(win) - -def ichoice(win, prompt, list, default): - if not list: - stdwin.fleep() - return - if not default: - topic, ref = list[0] - default = topic - try: - choice = stdwin.askstr(prompt, default) - except KeyboardInterrupt: - return - if not choice: - return - choice = string.lower(choice) - n = len(choice) - for topic, ref in list: - topic = string.lower(topic) - if topic[:n] == choice: - imove(win, ref) - return - stdwin.message('Sorry, no topic matches ' + `choice`) - - -# Follow a reference, in the same window. -# -def imove(win, ref): - savetitle = win.gettitle() - win.settitle('Looking for ' + ref + '...') - # - try: - file, node, header, menu, footnotes, text = \ - icache.get_node(win.file, ref) - except NoSuchFile, file: - win.settitle(savetitle) - stdwin.message(\ - 'Sorry, I can\'t find a file named ' + `file` + '.') - return - except NoSuchNode, node: - win.settitle(savetitle) - stdwin.message(\ - 'Sorry, I can\'t find a node named ' + `node` + '.') - return - # - win.settitle('Found (' + file + ')' + node + '...') - # - if win.file and win.node: - lastnode = '(' + win.file + ')' + win.node - win.last.append(lastnode, win.textobj.getfocus()) - win.file = file - win.node = node - win.header = header - win.menu = menu - win.footnotes = footnotes - win.text = text - # - win.setorigin(0, 0) # Scroll to the beginnning - win.textobj.settext(text) - win.textobj.setfocus(0, 0) - (left, top), (right, bottom) = win.textobj.getrect() - win.setdocsize(0, bottom) - # - if win.footmenu: win.footmenu.close() - if win.nodemenu: win.nodemenu.close() - win.footmenu = None - win.nodemenu = None - # - win.menu = menu - if menu: - win.nodemenu = win.menucreate('Menu') - digit = 1 - for topic, ref in menu: - if digit < 10: - win.nodemenu.additem(topic, `digit`) - else: - win.nodemenu.additem(topic) - digit = digit + 1 - # - win.footnotes = footnotes - if footnotes: - win.footmenu = win.menucreate('Footnotes') - for topic, ref in footnotes: - win.footmenu.additem(topic) - # - win.settitle('(' + win.file + ')' + win.node) - - -# Find menu item at focus -# -findmenu = regexp.compile('^\* [mM]enu:').match -findmenuitem = regexp.compile( \ - '^\* ([^:]+):[ \t]*(:|\([^\t]*\)[^\t,\n.]*|[^:(][^\t,\n.]*)').match -# -def whichmenuitem(win): - if not win.menu: - return '' - match = findmenu(win.text) - if not match: - return '' - a, b = match[0] - i = b - f1, f2 = win.textobj.getfocus() - lastmatch = '' - while i < len(win.text): - match = findmenuitem(win.text, i) - if not match: - break - (a, b), (a1, b1), (a2, b2) = match - if a > f1: - break - lastmatch = win.text[a1:b1] - i = b - return lastmatch - - -# Find footnote at focus -# -findfootnote = \ - regexp.compile('\*[nN]ote ([^:]+):[ \t]*(:|[^:][^\t,\n.]*)').match -# -def whichfootnote(win): - if not win.footnotes: - return '' - i = 0 - f1, f2 = win.textobj.getfocus() - lastmatch = '' - while i < len(win.text): - match = findfootnote(win.text, i) - if not match: - break - (a, b), (a1, b1), (a2, b2) = match - if a > f1: - break - lastmatch = win.text[a1:b1] - i = b - return lastmatch - - -# Now all the "methods" are defined, we can initialize the table -# of key bindings. -# -keybindings = {} - -# Window commands - -keybindings['k'] = iclone -keybindings['h'] = itutor -keybindings['?'] = isummary -keybindings['w'] = iclose - -keybindings['c'] = icopy - -keybindings['s'] = isearch - -keybindings['q'] = iquit - -# Navigation commands - -keybindings['m'] = imenu -keybindings['f'] = ifollow -keybindings['g'] = igoto - -keybindings['n'] = inext -keybindings['p'] = iprev -keybindings['u'] = iup -keybindings['l'] = ilast -keybindings['d'] = idir -keybindings['t'] = itop - -# Paging commands - -keybindings['b'] = ibeginning -keybindings['.'] = ibeginning -keybindings[' '] = iforward diff --git a/Demo/ibrowse/icache.py b/Demo/ibrowse/icache.py deleted file mode 100755 index 0629bf9f61..0000000000 --- a/Demo/ibrowse/icache.py +++ /dev/null @@ -1,74 +0,0 @@ -# Cache management for info file processing. -# The function get_node() is the standard interface; -# its signature is the same as ifile.get_node() but it uses -# the cache and supports indirect tag tables. - - -import string -import ifile -from ifile import NoSuchNode, NoSuchFile -import itags - - -# Special hack to save the cache when using reload(). -# This can just be "cache = {}" in a production version. -# -try: - dummy = cache - del dummy -except NameError: - cache = {} - - -# Clear the entire cache. -# -def resetcache(): - for key in cache.keys(): - del cache[key] - - -# Clear the node info from the cache (the most voluminous data). -# -def resetnodecache(): - for key in cache.keys(): - tags, nodes = cache[key] - cache[key] = tags, {} - - -# Get a node. -# -def get_node(curfile, ref): - file, node = ifile.parse_ref(curfile, ref) - file = string.lower(file) - node = string.lower(node) - if node == '*': - # Don't cache whole file references; - # reading the data is faster than displaying it anyway. - return ifile.get_whole_file(file) # May raise NoSuchFile - if not cache.has_key(file): - cache[file] = get_tags(file), {} # May raise NoSuchFile - tags, nodes = cache[file] - if not nodes.has_key(node): - if not tags.has_key(node): - raise NoSuchNode, ref - file1, offset, line = tags[node] - if not file1: - file1 = file - file1, node1, header, menu, footnotes, text = \ - ifile.get_file_node(file1, offset, node) - nodes[node] = file, node1, header, menu, footnotes, text - return nodes[node] - - -# Get the tag table for a file. -# Either construct one or get the one found in the file. -# Raise NoSuchFile if the file isn't found. -# -def get_tags(file): - f = ifile.try_open(file) # May raise NoSuchFile - tags = itags.get_tags(f) - if not tags: - ###print 'Scanning file...' - f.seek(0) - tags = ifile.make_tags(f) - return tags diff --git a/Demo/ibrowse/ifile.py b/Demo/ibrowse/ifile.py deleted file mode 100755 index b8d59eed8a..0000000000 --- a/Demo/ibrowse/ifile.py +++ /dev/null @@ -1,328 +0,0 @@ -# Tools for info file processing. - -# XXX Need to be more careful with reading ahead searching for nodes. - - -import regexp -import string - - -# Exported exceptions. -# -NoSuchFile = 'no such file' -NoSuchNode = 'no such node' - - -# The search path for info files; this is site-specific. -# Directory names should end in a partname delimiter, -# so they can simply be concatenated to a relative pathname. -# -#INFOPATH = ['', ':Info.Ibrowse:', ':Info:'] # Mac -INFOPATH = ['', '/usr/local/emacs/info/'] # X11 on UNIX - - -# Tunable constants. -# -BLOCKSIZE = 512 # Qty to align reads to, if possible -FUZZ = 2*BLOCKSIZE # Qty to back-up before searching for a node -CHUNKSIZE = 4*BLOCKSIZE # Qty to read at once when reading lots of data - - -# Regular expressions used. -# Note that it is essential that Python leaves unrecognized backslash -# escapes in a string so they can be seen by regexp.compile! -# -findheader = regexp.compile('\037\014?\n(.*\n)').match -findescape = regexp.compile('\037').match -parseheader = regexp.compile('[nN]ode:[ \t]*([^\t,\n]*)').match -findfirstline = regexp.compile('^.*\n').match -findnode = regexp.compile('[nN]ode:[ \t]*([^\t,\n]*)').match -findprev = regexp.compile('[pP]rev[ious]*:[ \t]*([^\t,\n]*)').match -findnext = regexp.compile('[nN]ext:[ \t]*([^\t,\n]*)').match -findup = regexp.compile('[uU]p:[ \t]*([^\t,\n]*)').match -findmenu = regexp.compile('^\* [mM]enu:').match -findmenuitem = regexp.compile( \ - '^\* ([^:]+):[ \t]*(:|\([^\t]*\)[^\t,\n.]*|[^:(][^\t,\n.]*)').match -findfootnote = regexp.compile( \ - '\*[nN]ote ([^:]+):[ \t]*(:|[^:][^\t,\n.]*)').match -parsenoderef = regexp.compile('^\((.*)\)(.*)$').match - - -# Get a node and all information pertaining to it. -# This doesn't work if there is an indirect tag table, -# and in general you are better off using icache.get_node() instead. -# Functions get_whole_file() and get_file_node() provide part -# functionality used by icache. -# Raise NoSuchFile or NoSuchNode as appropriate. -# -def get_node(curfile, ref): - file, node = parse_ref(curfile, ref) - if node == '*': - return get_whole_file(file) - else: - return get_file_node(file, 0, node) -# -def get_whole_file(file): - f = try_open(file) # May raise NoSuchFile - text = f.read() - header, menu, footnotes = ('', '', ''), [], [] - return file, '*', header, menu, footnotes, text -# -def get_file_node(file, offset, node): - f = try_open(file) # May raise NoSuchFile - text = find_node(f, offset, node) # May raise NoSuchNode - node, header, menu, footnotes = analyze_node(text) - return file, node, header, menu, footnotes, text - - -# Parse a node reference into a file (possibly default) and node name. -# Possible reference formats are: "NODE", "(FILE)", "(FILE)NODE". -# Default file is the curfile argument; default node is Top. -# A node value of '*' is a special case: the whole file should -# be interpreted (by the caller!) as a single node. -# -def parse_ref(curfile, ref): - match = parsenoderef(ref) - if not match: - file, node = curfile, ref - else: - (a, b), (a1, b1), (a2, b2) = match - file, node = ref[a1:b1], ref[a2:b2] - if not file: - file = curfile # (Is this necessary?) - if not node: - node = 'Top' - return file, node - - -# Extract node name, links, menu and footnotes from the node text. -# -def analyze_node(text): - # - # Get node name and links from the header line - # - match = findfirstline(text) - if match: - (a, b) = match[0] - line = text[a:b] - else: - line = '' - node = get_it(text, findnode) - prev = get_it(text, findprev) - next = get_it(text, findnext) - up = get_it(text, findup) - # - # Get the menu items, if there is a menu - # - menu = [] - match = findmenu(text) - if match: - (a, b) = match[0] - while 1: - match = findmenuitem(text, b) - if not match: - break - (a, b), (a1, b1), (a2, b2) = match - topic, ref = text[a1:b1], text[a2:b2] - if ref == ':': - ref = topic - menu.append(topic, ref) - # - # Get the footnotes - # - footnotes = [] - b = 0 - while 1: - match = findfootnote(text, b) - if not match: - break - (a, b), (a1, b1), (a2, b2) = match - topic, ref = text[a1:b1], text[a2:b2] - if ref == ':': - ref = topic - footnotes.append(topic, ref) - # - return node, (prev, next, up), menu, footnotes -# -def get_it(line, matcher): - match = matcher(line) - if not match: - return '' - else: - (a, b), (a1, b1) = match - return line[a1:b1] - - -# Find a node in an open file. -# The offset (from the tags table) is a hint about the node's position. -# Pass zero if there is no tags table. -# Raise NoSuchNode if the node isn't found. -# NB: This seeks around in the file. -# -def find_node(f, offset, node): - node = string.lower(node) # Just to be sure - # - # Position a little before the given offset, - # so we may find the node even if it has moved around - # in the file a little. - # - offset = max(0, ((offset-FUZZ) / BLOCKSIZE) * BLOCKSIZE) - f.seek(offset) - # - # Loop, hunting for a matching node header. - # - while 1: - buf = f.read(CHUNKSIZE) - if not buf: - break - i = 0 - while 1: - match = findheader(buf, i) - if match: - (a,b), (a1,b1) = match - start = a1 - line = buf[a1:b1] - i = b - match = parseheader(line) - if match: - (a,b), (a1,b1) = match - key = string.lower(line[a1:b1]) - if key == node: - # Got it! Now read the rest. - return read_node(f, buf[start:]) - elif findescape(buf, i): - next = f.read(CHUNKSIZE) - if not next: - break - buf = buf + next - else: - break - # - # If we get here, we didn't find it. Too bad. - # - raise NoSuchNode, node - - -# Finish off getting a node (subroutine for find_node()). -# The node begins at the start of buf and may end in buf; -# if it doesn't end there, read additional data from f. -# -def read_node(f, buf): - i = 0 - match = findescape(buf, i) - while not match: - next = f.read(CHUNKSIZE) - if not next: - end = len(buf) - break - i = len(buf) - buf = buf + next - match = findescape(buf, i) - else: - # Got a match - (a, b) = match[0] - end = a - # Strip trailing newlines - while end > 0 and buf[end-1] == '\n': - end = end-1 - buf = buf[:end] - return buf - - -# Read reverse starting at offset until the beginning of a node is found. -# Then return a buffer containing the beginning of the node, -# with f positioned just after the buffer. -# The buffer will contain at least the full header line of the node; -# the caller should finish off with read_node() if it is the right node. -# (It is also possible that the buffer extends beyond the node!) -# Return an empty string if there is no node before the given offset. -# -def backup_node(f, offset): - start = max(0, ((offset-CHUNKSIZE) / BLOCKSIZE) * BLOCKSIZE) - end = offset - while start < end: - f.seek(start) - buf = f.read(end-start) - i = 0 - hit = -1 - while 1: - match = findheader(buf, i) - if match: - (a,b), (a1,b1) = match - hit = a1 - i = b - elif end < offset and findescape(buf, i): - next = f.read(min(offset-end, BLOCKSIZE)) - if not next: - break - buf = buf + next - end = end + len(next) - else: - break - if hit >= 0: - return buf[hit:] - end = start - start = max(0, end - CHUNKSIZE) - return '' - - -# Make a tag table for the given file by scanning the file. -# The file must be open for reading, and positioned at the beginning -# (or wherever the hunt for tags must begin; it is read till the end). -# -def make_tags(f): - tags = {} - while 1: - offset = f.tell() - buf = f.read(CHUNKSIZE) - if not buf: - break - i = 0 - while 1: - match = findheader(buf, i) - if match: - (a,b), (a1,b1) = match - start = offset+a1 - line = buf[a1:b1] - i = b - match = parseheader(line) - if match: - (a,b), (a1,b1) = match - key = string.lower(line[a1:b1]) - if tags.has_key(key): - print 'Duplicate node:', - print key - tags[key] = '', start, line - elif findescape(buf, i): - next = f.read(CHUNKSIZE) - if not next: - break - buf = buf + next - else: - break - return tags - - -# Try to open a file, return a file object if succeeds. -# Raise NoSuchFile if the file can't be opened. -# Should treat absolute pathnames special. -# -def try_open(file): - for dir in INFOPATH: - try: - return open(dir + file, 'r') - except IOError: - pass - raise NoSuchFile, file - - -# A little test for the speed of make_tags(). -# -TESTFILE = 'texinfo-1' -def test_make_tags(): - import time - f = try_open(TESTFILE) - t1 = time.time() - tags = make_tags(f) - t2 = time.time() - print 'Making tag table for', `TESTFILE`, 'took', t2-t1, 'sec.' diff --git a/Demo/ibrowse/itags.py b/Demo/ibrowse/itags.py deleted file mode 100755 index f30f3fd5a1..0000000000 --- a/Demo/ibrowse/itags.py +++ /dev/null @@ -1,127 +0,0 @@ -# Utility module for 'icache.py': interpret tag tables and indirect nodes. - -# (This module is a bit chatty when confronted with the unexpected.) - - -import regexp -import string -import ifile - - -# Get the tag table of an open file, as a dictionary. -# Seeks around in the file; after reading, the position is undefined. -# Return an empty tag table if none is found. -# -def get_tags(f): - # - # First see if the last "node" is the end of tag table marker. - # - f.seek(0, 2) # Seek to EOF - end = f.tell() - buf = ifile.backup_node(f, end) - if not labelmatch(buf, 0, 'end tag table\n'): - return {} # No succes - # - # Next backup to the previous "node" -- the tag table itself. - # - ###print 'Getting prebuilt tag table...' - end = f.tell() - len(buf) - buf = ifile.backup_node(f, end) - label = 'tag table:\n' - if not labelmatch(buf, 0, label): - print 'Weird: end tag table marker but no tag table?' - print 'Node begins:', `buf[:50]` - return {} - # - # Now read the whole tag table. - # - end = f.tell() - len(buf) # Do this first! - buf = ifile.read_node(f, buf) - # - # First check for an indirection table. - # - indirlist = [] - if labelmatch(buf, len(label), '(indirect)\n'): - indirbuf = ifile.backup_node(f, end) - if not labelmatch(indirbuf, 0, 'indirect:\n'): - print 'Weird: promised indirection table not found' - print 'Node begins:', `indirbuf[:50]` - # Carry on. Things probably won't work though. - else: - indirbuf = ifile.read_node(f, indirbuf) - indirlist = parse_indirlist(indirbuf) - # - # Now parse the tag table. - # - findtag = regexp.compile('^(.*[nN]ode:[ \t]*(.*))\177([0-9]+)$').match - i = 0 - tags = {} - while 1: - match = findtag(buf, i) - if not match: - break - (a,b), (a1,b1), (a2,b2), (a3,b3) = match - i = b - line = buf[a1:b1] - node = string.lower(buf[a2:b2]) - offset = eval(buf[a3:b3]) # XXX What if it overflows? - if tags.has_key(node): - print 'Duplicate key in tag table:', `node` - file, offset = map_offset(offset, indirlist) - tags[node] = file, offset, line - # - return tags - - -# Return true if buf[i:] begins with a label, after lower case conversion. -# The label argument must be in lower case. -# -def labelmatch(buf, i, label): - return string.lower(buf[i:i+len(label)]) == label - - -# Parse the indirection list. -# Return a list of (filename, offset) pairs ready for use. -# -def parse_indirlist(buf): - list = [] - findindir = regexp.compile('^(.+):[ \t]*([0-9]+)$').match - i = 0 - while 1: - match = findindir(buf, i) - if not match: - break - (a,b), (a1,b1), (a2,b2) = match - file = buf[a1:b1] - offset = eval(buf[a2:b2]) # XXX What if this gets overflow? - list.append(file, offset) - i = b - return list - - -# Map an offset through the indirection list. -# Return (filename, new_offset). -# If the list is empty, return the given offset and an empty file name. -# -def map_offset(offset, indirlist): - if not indirlist: - return '', offset - # - # XXX This could be done more elegant. - # - filex, offx = indirlist[0] - for i in range(len(indirlist)): - file1, off1 = indirlist[i] - if i+1 >= len(indirlist): - file2, off2 = '', 0x7fffffff - else: - file2, off2 = indirlist[i+1] - if off1 <= offset < off2: - # Add offx+2 to compensate for extra header. - # No idea whether this is always correct. - return file1, offset-off1 + offx+2 - # - # XXX Shouldn't get here. - # - print 'Oops, map_offset fell through' - return '', offset # Not likely to get good results diff --git a/Demo/md5test/README b/Demo/md5test/README deleted file mode 100644 index be7621e464..0000000000 --- a/Demo/md5test/README +++ /dev/null @@ -1,10 +0,0 @@ -This is the Python version of the MD5 test program from the MD5 -Internet Draft (Rivest and Dusse, The MD5 Message-Digest Algorithm, 10 -July 1991). The file "foo" contains the string "abc" with no trailing -newline. - -When called without arguments, it acts as a filter. When called with -"-x", it executes a self-test, and the output should literally match -the output given in the RFC. - -Code by Jan-Hein B\"uhrman after the original in C. diff --git a/Demo/md5test/foo b/Demo/md5test/foo deleted file mode 100755 index f2ba8f84ab..0000000000 --- a/Demo/md5test/foo +++ /dev/null @@ -1 +0,0 @@ -abc \ No newline at end of file diff --git a/Demo/md5test/md5driver.py b/Demo/md5test/md5driver.py deleted file mode 100755 index 326c0cf2a2..0000000000 --- a/Demo/md5test/md5driver.py +++ /dev/null @@ -1,125 +0,0 @@ -import string - -def MDPrint(str): - outstr = '' - for i in str: - o = ord(i) - outstr = outstr \ - + string.hexdigits[(o >> 4) & 0xF] \ - + string.hexdigits[o & 0xF] - print outstr, - - -from time import time - -def makestr(start, end): - result = '' - for i in range(start, end + 1): - result = result + chr(i) - - return result - - -from md5 import md5 - -def MDTimeTrial(): - TEST_BLOCK_SIZE = 1000 - TEST_BLOCKS = 10000 - - TEST_BYTES = TEST_BLOCK_SIZE * TEST_BLOCKS - - # initialize test data, need temporary string filler - - filsiz = 1 << 8 - filler = makestr(0, filsiz-1) - data = filler * (TEST_BLOCK_SIZE / filsiz); - data = data + filler[:(TEST_BLOCK_SIZE % filsiz)] - - del filsiz, filler - - - # start timer - print 'MD5 time trial. Processing', TEST_BYTES, 'characters...' - t1 = time() - - mdContext = md5() - - for i in range(TEST_BLOCKS): - mdContext.update(data) - - str = mdContext.digest() - t2 = time() - - MDPrint(str) - print 'is digest of test input.' - print 'Seconds to process test input:', t2 - t1 - print 'Characters processed per second:', TEST_BYTES / (t2 - t1) - - -def MDString(str): - MDPrint(md5(str).digest()) - print '"' + str + '"' - - -def MDFile(filename): - f = open(filename, 'rb'); - mdContext = md5() - - while 1: - data = f.read(1024) - if not data: - break - mdContext.update(data) - - MDPrint(mdContext.digest()) - print filename - - -import sys - -def MDFilter(): - mdContext = md5() - - while 1: - data = sys.stdin.read(16) - if not data: - break - mdContext.update(data) - - MDPrint(mdContext.digest()) - print - - -def MDTestSuite(): - print 'MD5 test suite results:' - MDString('') - MDString('a') - MDString('abc') - MDString('message digest') - MDString(makestr(ord('a'), ord('z'))) - MDString(makestr(ord('A'), ord('Z')) \ - + makestr(ord('a'), ord('z')) \ - + makestr(ord('0'), ord('9'))) - MDString((makestr(ord('1'), ord('9')) + '0') * 8) - - # Contents of file foo are "abc" - MDFile('foo') - - -from sys import argv - -# I don't wanna use getopt(), since I want to use the same i/f... -def main(): - if len(argv) == 1: - MDFilter() - for arg in argv[1:]: - if arg[:2] == '-s': - MDString(arg[2:]) - elif arg == '-t': - MDTimeTrial() - elif arg == '-x': - MDTestSuite() - else: - MDFile(arg) - -main() diff --git a/Demo/pdist/FSProxy.py b/Demo/pdist/FSProxy.py deleted file mode 100755 index 7510d1e6fd..0000000000 --- a/Demo/pdist/FSProxy.py +++ /dev/null @@ -1,322 +0,0 @@ -"""File System Proxy. - -Provide an OS-neutral view on a file system, locally or remotely. -The functionality is geared towards implementing some sort of -rdist-like utility between a Mac and a UNIX system. - -The module defines three classes: - -FSProxyLocal -- used for local access -FSProxyServer -- used on the server side of remote access -FSProxyClient -- used on the client side of remote access - -The remote classes are instantiated with an IP address and an optional -verbosity flag. -""" - -import server -import client -import md5 -import os -import fnmatch -from stat import * -import time -import fnmatch - -if os.name == 'mac': - import macfs - maxnamelen = 31 -else: - macfs = None - maxnamelen = 255 - -skipnames = (os.curdir, os.pardir) - - -class FSProxyLocal: - - def __init__(self): - self._dirstack = [] - self._ignore = ['*.pyc'] + self._readignore() - - def _close(self): - while self._dirstack: - self.back() - - def _readignore(self): - file = self._hide('ignore') - try: - f = open(file) - except IOError: - file = self._hide('synctree.ignorefiles') - try: - f = open(file) - except IOError: - return [] - ignore = [] - while 1: - line = f.readline() - if not line: break - if line[-1] == '\n': line = line[:-1] - ignore.append(line) - f.close() - return ignore - - def _hidden(self, name): - if os.name == 'mac': - return name[0] == '(' and name[-1] == ')' - else: - return name[0] == '.' - - def _hide(self, name): - if os.name == 'mac': - return '(%s)' % name - else: - return '.%s' % name - - def visible(self, name): - if len(name) > maxnamelen: return 0 - if name[-1] == '~': return 0 - if name in skipnames: return 0 - if self._hidden(name): return 0 - head, tail = os.path.split(name) - if head or not tail: return 0 - if macfs: - if os.path.exists(name) and not os.path.isdir(name): - try: - fs = macfs.FSSpec(name) - c, t = fs.GetCreatorType() - if t != 'TEXT': return 0 - except macfs.error, msg: - print "***", name, msg - return 0 - else: - if os.path.islink(name): return 0 - if '\0' in open(name, 'rb').read(512): return 0 - for ign in self._ignore: - if fnmatch.fnmatch(name, ign): return 0 - return 1 - - def check(self, name): - if not self.visible(name): - raise os.error, "protected name %s" % repr(name) - - def checkfile(self, name): - self.check(name) - if not os.path.isfile(name): - raise os.error, "not a plain file %s" % repr(name) - - def pwd(self): - return os.getcwd() - - def cd(self, name): - self.check(name) - save = os.getcwd(), self._ignore - os.chdir(name) - self._dirstack.append(save) - self._ignore = self._ignore + self._readignore() - - def back(self): - if not self._dirstack: - raise os.error, "empty directory stack" - dir, ignore = self._dirstack[-1] - os.chdir(dir) - del self._dirstack[-1] - self._ignore = ignore - - def _filter(self, files, pat = None): - if pat: - def keep(name, pat = pat): - return fnmatch.fnmatch(name, pat) - files = filter(keep, files) - files = filter(self.visible, files) - files.sort() - return files - - def list(self, pat = None): - files = os.listdir(os.curdir) - return self._filter(files, pat) - - def listfiles(self, pat = None): - files = os.listdir(os.curdir) - files = filter(os.path.isfile, files) - return self._filter(files, pat) - - def listsubdirs(self, pat = None): - files = os.listdir(os.curdir) - files = filter(os.path.isdir, files) - return self._filter(files, pat) - - def exists(self, name): - return self.visible(name) and os.path.exists(name) - - def isdir(self, name): - return self.visible(name) and os.path.isdir(name) - - def islink(self, name): - return self.visible(name) and os.path.islink(name) - - def isfile(self, name): - return self.visible(name) and os.path.isfile(name) - - def sum(self, name): - self.checkfile(name) - BUFFERSIZE = 1024*8 - f = open(name) - sum = md5.new() - while 1: - buffer = f.read(BUFFERSIZE) - if not buffer: - break - sum.update(buffer) - return sum.digest() - - def size(self, name): - self.checkfile(name) - return os.stat(name)[ST_SIZE] - - def mtime(self, name): - self.checkfile(name) - return time.localtime(os.stat(name)[ST_MTIME]) - - def stat(self, name): - self.checkfile(name) - size = os.stat(name)[ST_SIZE] - mtime = time.localtime(os.stat(name)[ST_MTIME]) - return size, mtime - - def info(self, name): - sum = self.sum(name) - size = os.stat(name)[ST_SIZE] - mtime = time.localtime(os.stat(name)[ST_MTIME]) - return sum, size, mtime - - def _list(self, function, list): - if list is None: - list = self.listfiles() - res = [] - for name in list: - try: - res.append((name, function(name))) - except (os.error, IOError): - res.append((name, None)) - return res - - def sumlist(self, list = None): - return self._list(self.sum, list) - - def statlist(self, list = None): - return self._list(self.stat, list) - - def mtimelist(self, list = None): - return self._list(self.mtime, list) - - def sizelist(self, list = None): - return self._list(self.size, list) - - def infolist(self, list = None): - return self._list(self.info, list) - - def _dict(self, function, list): - if list is None: - list = self.listfiles() - dict = {} - for name in list: - try: - dict[name] = function(name) - except (os.error, IOError): - pass - return dict - - def sumdict(self, list = None): - return self.dict(self.sum, list) - - def sizedict(self, list = None): - return self.dict(self.size, list) - - def mtimedict(self, list = None): - return self.dict(self.mtime, list) - - def statdict(self, list = None): - return self.dict(self.stat, list) - - def infodict(self, list = None): - return self._dict(self.info, list) - - def read(self, name, offset = 0, length = -1): - self.checkfile(name) - f = open(name) - f.seek(offset) - if length == 0: - data = '' - elif length < 0: - data = f.read() - else: - data = f.read(length) - f.close() - return data - - def create(self, name): - self.check(name) - if os.path.exists(name): - self.checkfile(name) - bname = name + '~' - try: - os.unlink(bname) - except os.error: - pass - os.rename(name, bname) - f = open(name, 'w') - f.close() - - def write(self, name, data, offset = 0): - self.checkfile(name) - f = open(name, 'r+') - f.seek(offset) - f.write(data) - f.close() - - def mkdir(self, name): - self.check(name) - os.mkdir(name, 0777) - - def rmdir(self, name): - self.check(name) - os.rmdir(name) - - -class FSProxyServer(FSProxyLocal, server.Server): - - def __init__(self, address, verbose = server.VERBOSE): - FSProxyLocal.__init__(self) - server.Server.__init__(self, address, verbose) - - def _close(self): - server.Server._close(self) - FSProxyLocal._close(self) - - def _serve(self): - server.Server._serve(self) - # Retreat into start directory - while self._dirstack: self.back() - - -class FSProxyClient(client.Client): - - def __init__(self, address, verbose = client.VERBOSE): - client.Client.__init__(self, address, verbose) - - -def test(): - import string - import sys - if sys.argv[1:]: - port = string.atoi(sys.argv[1]) - else: - port = 4127 - proxy = FSProxyServer(('', port)) - proxy._serverloop() - - -if __name__ == '__main__': - test() diff --git a/Demo/pdist/RCSProxy.py b/Demo/pdist/RCSProxy.py deleted file mode 100755 index ed55e9ff1c..0000000000 --- a/Demo/pdist/RCSProxy.py +++ /dev/null @@ -1,198 +0,0 @@ -#! /usr/local/bin/python - -"""RCS Proxy. - -Provide a simplified interface on RCS files, locally or remotely. -The functionality is geared towards implementing some sort of -remote CVS like utility. It is modeled after the similar module -FSProxy. - -The module defines two classes: - -RCSProxyLocal -- used for local access -RCSProxyServer -- used on the server side of remote access - -The corresponding client class, RCSProxyClient, is defined in module -rcsclient. - -The remote classes are instantiated with an IP address and an optional -verbosity flag. -""" - -import server -import md5 -import os -import fnmatch -import string -import tempfile -import rcslib - - -class DirSupport: - - def __init__(self): - self._dirstack = [] - - def __del__(self): - self._close() - - def _close(self): - while self._dirstack: - self.back() - - def pwd(self): - return os.getcwd() - - def cd(self, name): - save = os.getcwd() - os.chdir(name) - self._dirstack.append(save) - - def back(self): - if not self._dirstack: - raise os.error, "empty directory stack" - dir = self._dirstack[-1] - os.chdir(dir) - del self._dirstack[-1] - - def listsubdirs(self, pat = None): - files = os.listdir(os.curdir) - files = filter(os.path.isdir, files) - return self._filter(files, pat) - - def isdir(self, name): - return os.path.isdir(name) - - def mkdir(self, name): - os.mkdir(name, 0777) - - def rmdir(self, name): - os.rmdir(name) - - -class RCSProxyLocal(rcslib.RCS, DirSupport): - - def __init__(self): - rcslib.RCS.__init__(self) - DirSupport.__init__(self) - - def __del__(self): - DirSupport.__del__(self) - rcslib.RCS.__del__(self) - - def sumlist(self, list = None): - return self._list(self.sum, list) - - def sumdict(self, list = None): - return self._dict(self.sum, list) - - def sum(self, name_rev): - f = self._open(name_rev) - BUFFERSIZE = 1024*8 - sum = md5.new() - while 1: - buffer = f.read(BUFFERSIZE) - if not buffer: - break - sum.update(buffer) - self._closepipe(f) - return sum.digest() - - def get(self, name_rev): - f = self._open(name_rev) - data = f.read() - self._closepipe(f) - return data - - def put(self, name_rev, data, message=None): - name, rev = self._unmangle(name_rev) - f = open(name, 'w') - f.write(data) - f.close() - self.checkin(name_rev, message) - self._remove(name) - - def _list(self, function, list = None): - """INTERNAL: apply FUNCTION to all files in LIST. - - Return a list of the results. - - The list defaults to all files in the directory if None. - - """ - if list is None: - list = self.listfiles() - res = [] - for name in list: - try: - res.append((name, function(name))) - except (os.error, IOError): - res.append((name, None)) - return res - - def _dict(self, function, list = None): - """INTERNAL: apply FUNCTION to all files in LIST. - - Return a dictionary mapping files to results. - - The list defaults to all files in the directory if None. - - """ - if list is None: - list = self.listfiles() - dict = {} - for name in list: - try: - dict[name] = function(name) - except (os.error, IOError): - pass - return dict - - -class RCSProxyServer(RCSProxyLocal, server.SecureServer): - - def __init__(self, address, verbose = server.VERBOSE): - RCSProxyLocal.__init__(self) - server.SecureServer.__init__(self, address, verbose) - - def _close(self): - server.SecureServer._close(self) - RCSProxyLocal._close(self) - - def _serve(self): - server.SecureServer._serve(self) - # Retreat into start directory - while self._dirstack: self.back() - - -def test_server(): - import string - import sys - if sys.argv[1:]: - port = string.atoi(sys.argv[1]) - else: - port = 4127 - proxy = RCSProxyServer(('', port)) - proxy._serverloop() - - -def test(): - import sys - if not sys.argv[1:] or sys.argv[1] and sys.argv[1][0] in '0123456789': - test_server() - sys.exit(0) - proxy = RCSProxyLocal() - what = sys.argv[1] - if hasattr(proxy, what): - attr = getattr(proxy, what) - if callable(attr): - print apply(attr, tuple(sys.argv[2:])) - else: - print `attr` - else: - print "%s: no such attribute" % what - sys.exit(2) - - -if __name__ == '__main__': - test() diff --git a/Demo/pdist/README b/Demo/pdist/README deleted file mode 100644 index b3fac24127..0000000000 --- a/Demo/pdist/README +++ /dev/null @@ -1,121 +0,0 @@ -Filesystem, RCS and CVS client and server classes -================================================= - -*** See the security warning at the end of this file! *** - -This directory contains various modules and classes that support -remote file system operations. - -CVS stuff ---------- - -rcvs Script to put in your bin directory -rcvs.py Remote CVS client command line interface - -cvslib.py CVS admin files classes (used by rrcs) -cvslock.py CVS locking algorithms - -RCS stuff ---------- - -rrcs Script to put in your bin directory -rrcs.py Remote RCS client command line interface - -rcsclient.py Return an RCSProxyClient instance - (has reasonable default server/port/directory) - -RCSProxy.py RCS proxy and server classes (on top of rcslib.py) - -rcslib.py Local-only RCS base class (affects stdout & - local work files) - -FSProxy stuff -------------- - -sumtree.py Old demo for FSProxy -cmptree.py First FSProxy client (used to sync from the Mac) -FSProxy.py Filesystem interface classes - -Generic client/server stuff ---------------------------- - -client.py Client class -server.py Server class - -security.py Security mix-in class (not very secure I think) - -Other generic stuff -------------------- - -cmdfw.py CommandFrameWork class - (used by rcvs, should be used by rrcs as well) - - -Client/Server operation ------------------------ - -The Client and Server classes implement a simple-minded RPC protocol, -using Python's pickle module to transfer arguments, return values and -exceptions with the most generality. The Server class is instantiated -with a port number on which it should listen for requests; the Client -class is instantiated with a host name and a port number where it -should connect to. Once a client is connected, a TCP connection is -maintained between client and server. - -The Server class currently handles only one connection at a time; -however it could be rewritten to allow various modes of operations, -using multiple threads or processes or the select() system call as -desired to serve multiple clients simultaneously (when using select(), -still handling one request at a time). This would not require -rewriting of the Client class. It may also be possible to adapt the -code to use UDP instead of TCP, but then both classes will have to be -rewritten (and unless extensive acknowlegements and request serial -numbers are used, the server should handle duplicate requests, so its -semantics should be idempotent -- shrudder). - -Even though the FSProxy and RCSProxy modules define client classes, -the client class is fully generic -- what methods it supports is -determined entirely by the server. The server class, however, must be -derived from. This is generally done as follows: - - from server import Server - from client import Client - - # Define a class that performs the operations locally - class MyClassLocal: - def __init__(self): ... - def _close(self): ... - - # Derive a server class using multiple inheritance - class MyClassServer(MyClassLocal, Server): - def __init__(self, address): - # Must initialize MyClassLocal as well as Server - MyClassLocal.__init__(self) - Server.__init__(self, address) - def _close(self): - Server._close() - MyClassLocal._close() - - # A dummy client class - class MyClassClient(Client): pass - -Note that because MyClassLocal isn't used in the definition of -MyClassClient, it would actually be better to place it in a separate -module so the definition of MyClassLocal isn't executed when we only -instantiate a client. - -The modules client and server should probably be renamed to Client and -Server in order to match the class names. - - -*** Security warning: this version requires that you have a file -$HOME/.python_keyfile at the server and client side containing two -comma- separated numbers. The security system at the moment makes no -guarantees of actuallng being secure -- however it requires that the -key file exists and contains the same numbers at both ends for this to -work. (You can specify an alternative keyfile in $PYTHON_KEYFILE). -Have a look at the Security class in security.py for details; -basically, if the key file contains (x, y), then the security server -class chooses a random number z (the challenge) in the range -10..100000 and the client must be able to produce pow(z, x, y) -(i.e. z**x mod y). diff --git a/Demo/pdist/client.py b/Demo/pdist/client.py deleted file mode 100755 index 3e93f1ce8e..0000000000 --- a/Demo/pdist/client.py +++ /dev/null @@ -1,158 +0,0 @@ -"""RPC Client module.""" - -import sys -import socket -import pickle -import __builtin__ -import os - - -# Default verbosity (0 = silent, 1 = print connections, 2 = print requests too) -VERBOSE = 1 - - -class Client: - - """RPC Client class. No need to derive a class -- it's fully generic.""" - - def __init__(self, address, verbose = VERBOSE): - self._pre_init(address, verbose) - self._post_init() - - def _pre_init(self, address, verbose = VERBOSE): - if type(address) == type(0): - address = ('', address) - self._address = address - self._verbose = verbose - if self._verbose: print "Connecting to %s ..." % repr(address) - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.connect(address) - if self._verbose: print "Connected." - self._lastid = 0 # Last id for which a reply has been received - self._nextid = 1 # Id of next request - self._replies = {} # Unprocessed replies - self._rf = self._socket.makefile('r') - self._wf = self._socket.makefile('w') - - def _post_init(self): - self._methods = self._call('.methods') - - def __del__(self): - self._close() - - def _close(self): - if self._rf: self._rf.close() - self._rf = None - if self._wf: self._wf.close() - self._wf = None - if self._socket: self._socket.close() - self._socket = None - - def __getattr__(self, name): - if name in self._methods: - method = _stub(self, name) - setattr(self, name, method) # XXX circular reference - return method - raise AttributeError, name - - def _setverbose(self, verbose): - self._verbose = verbose - - def _call(self, name, *args): - return self._vcall(name, args) - - def _vcall(self, name, args): - return self._recv(self._vsend(name, args)) - - def _send(self, name, *args): - return self._vsend(name, args) - - def _send_noreply(self, name, *args): - return self._vsend(name, args, 0) - - def _vsend_noreply(self, name, args): - return self._vsend(name, args, 0) - - def _vsend(self, name, args, wantreply = 1): - id = self._nextid - self._nextid = id+1 - if not wantreply: id = -id - request = (name, args, id) - if self._verbose > 1: print "sending request: %s" % repr(request) - wp = pickle.Pickler(self._wf) - wp.dump(request) - return id - - def _recv(self, id): - exception, value, rid = self._vrecv(id) - if rid != id: - raise RuntimeError, "request/reply id mismatch: %d/%d" % (id, rid) - if exception is None: - return value - x = exception - if hasattr(__builtin__, exception): - x = getattr(__builtin__, exception) - elif exception in ('posix.error', 'mac.error'): - x = os.error - if x == exception: - exception = x - raise exception, value - - def _vrecv(self, id): - self._flush() - if self._replies.has_key(id): - if self._verbose > 1: print "retrieving previous reply, id = %d" % id - reply = self._replies[id] - del self._replies[id] - return reply - aid = abs(id) - while 1: - if self._verbose > 1: print "waiting for reply, id = %d" % id - rp = pickle.Unpickler(self._rf) - reply = rp.load() - del rp - if self._verbose > 1: print "got reply: %s" % repr(reply) - rid = reply[2] - arid = abs(rid) - if arid == aid: - if self._verbose > 1: print "got it" - return reply - self._replies[rid] = reply - if arid > aid: - if self._verbose > 1: print "got higher id, assume all ok" - return (None, None, id) - - def _flush(self): - self._wf.flush() - - -from security import Security - - -class SecureClient(Client, Security): - - def __init__(self, *args): - import string - apply(self._pre_init, args) - Security.__init__(self) - self._wf.flush() - line = self._rf.readline() - challenge = string.atoi(string.strip(line)) - response = self._encode_challenge(challenge) - line = `long(response)` - if line[-1] in 'Ll': line = line[:-1] - self._wf.write(line + '\n') - self._wf.flush() - self._post_init() - -class _stub: - - """Helper class for Client -- each instance serves as a method of the client.""" - - def __init__(self, client, name): - self._client = client - self._name = name - - def __call__(self, *args): - return self._client._vcall(self._name, args) - diff --git a/Demo/pdist/cmdfw.py b/Demo/pdist/cmdfw.py deleted file mode 100755 index a0c6f5d8ec..0000000000 --- a/Demo/pdist/cmdfw.py +++ /dev/null @@ -1,144 +0,0 @@ -"Framework for command line interfaces like CVS. See class CmdFrameWork." - - -class CommandFrameWork: - - """Framework class for command line interfaces like CVS. - - The general command line structure is - - command [flags] subcommand [subflags] [argument] ... - - There's a class variable GlobalFlags which specifies the - global flags options. Subcommands are defined by defining - methods named do_. Flags for the subcommand are - defined by defining class or instance variables named - flags_. If there's no command, method default() - is called. The __doc__ strings for the do_ methods are used - for the usage message, printed after the general usage message - which is the class variable UsageMessage. The class variable - PostUsageMessage is printed after all the do_ methods' __doc__ - strings. The method's return value can be a suggested exit - status. [XXX Need to rewrite this to clarify it.] - - Common usage is to derive a class, instantiate it, and then call its - run() method; by default this takes its arguments from sys.argv[1:]. - """ - - UsageMessage = \ - "usage: (name)s [flags] subcommand [subflags] [argument] ..." - - PostUsageMessage = None - - GlobalFlags = '' - - def __init__(self): - """Constructor, present for completeness.""" - pass - - def run(self, args = None): - """Process flags, subcommand and options, then run it.""" - import getopt, sys - if args is None: args = sys.argv[1:] - try: - opts, args = getopt.getopt(args, self.GlobalFlags) - except getopt.error, msg: - return self.usage(msg) - self.options(opts) - if not args: - self.ready() - return self.default() - else: - cmd = args[0] - mname = 'do_' + cmd - fname = 'flags_' + cmd - try: - method = getattr(self, mname) - except AttributeError: - return self.usage("command %s unknown" % `cmd`) - try: - flags = getattr(self, fname) - except AttributeError: - flags = '' - try: - opts, args = getopt.getopt(args[1:], flags) - except getopt.error, msg: - return self.usage( - "subcommand %s: " % cmd + str(msg)) - self.ready() - return method(opts, args) - - def options(self, opts): - """Process the options retrieved by getopt. - Override this if you have any options.""" - if opts: - print "-"*40 - print "Options:" - for o, a in opts: - print 'option', o, 'value', `a` - print "-"*40 - - def ready(self): - """Called just before calling the subcommand.""" - pass - - def usage(self, msg = None): - """Print usage message. Return suitable exit code (2).""" - if msg: print msg - print self.UsageMessage % {'name': self.__class__.__name__} - docstrings = {} - c = self.__class__ - while 1: - for name in dir(c): - if name[:3] == 'do_': - if docstrings.has_key(name): - continue - try: - doc = getattr(c, name).__doc__ - except: - doc = None - if doc: - docstrings[name] = doc - if not c.__bases__: - break - c = c.__bases__[0] - if docstrings: - print "where subcommand can be:" - names = docstrings.keys() - names.sort() - for name in names: - print docstrings[name] - if self.PostUsageMessage: - print self.PostUsageMessage - return 2 - - def default(self): - """Default method, called when no subcommand is given. - You should always override this.""" - print "Nobody expects the Spanish Inquisition!" - - -def test(): - """Test script -- called when this module is run as a script.""" - import sys - class Hello(CommandFrameWork): - def do_hello(self, opts, args): - "hello -- print 'hello world', needs no arguments" - print "Hello, world" - x = Hello() - tests = [ - [], - ['hello'], - ['spam'], - ['-x'], - ['hello', '-x'], - None, - ] - for t in tests: - print '-'*10, t, '-'*10 - sts = x.run(t) - print "Exit status:", `sts` - - -if __name__ == '__main__': - test() diff --git a/Demo/pdist/cmptree.py b/Demo/pdist/cmptree.py deleted file mode 100755 index 7eaa6c3697..0000000000 --- a/Demo/pdist/cmptree.py +++ /dev/null @@ -1,208 +0,0 @@ -"""Compare local and remote dictionaries and transfer differing files -- like rdist.""" - -import sys -from repr import repr -import FSProxy -import time -import os - -def main(): - pwd = os.getcwd() - s = raw_input("chdir [%s] " % pwd) - if s: - os.chdir(s) - pwd = os.getcwd() - host = ask("host", 'voorn.cwi.nl') - port = 4127 - verbose = 1 - mode = '' - print """\ -Mode should be a string of characters, indicating what to do with differences. -r - read different files to local file system -w - write different files to remote file system -c - create new files, either remote or local -d - delete disappearing files, either remote or local -""" - s = raw_input("mode [%s] " % mode) - if s: mode = s - address = (host, port) - t1 = time.time() - local = FSProxy.FSProxyLocal() - remote = FSProxy.FSProxyClient(address, verbose) - compare(local, remote, mode) - remote._close() - local._close() - t2 = time.time() - dt = t2-t1 - mins, secs = divmod(dt, 60) - print mins, "minutes and", round(secs), "seconds" - raw_input("[Return to exit] ") - -def ask(prompt, default): - s = raw_input("%s [%s] " % (prompt, default)) - return s or default - -def askint(prompt, default): - s = raw_input("%s [%s] " % (prompt, str(default))) - if s: return string.atoi(s) - return default - -def compare(local, remote, mode): - print - print "PWD =", `os.getcwd()` - sums_id = remote._send('sumlist') - subdirs_id = remote._send('listsubdirs') - remote._flush() - print "calculating local sums ..." - lsumdict = {} - for name, info in local.sumlist(): - lsumdict[name] = info - print "getting remote sums ..." - sums = remote._recv(sums_id) - print "got", len(sums) - rsumdict = {} - for name, rsum in sums: - rsumdict[name] = rsum - if not lsumdict.has_key(name): - print `name`, "only remote" - if 'r' in mode and 'c' in mode: - recvfile(local, remote, name) - else: - lsum = lsumdict[name] - if lsum != rsum: - print `name`, - rmtime = remote.mtime(name) - lmtime = local.mtime(name) - if rmtime > lmtime: - print "remote newer", - if 'r' in mode: - recvfile(local, remote, name) - elif lmtime > rmtime: - print "local newer", - if 'w' in mode: - sendfile(local, remote, name) - else: - print "same mtime but different sum?!?!", - print - for name in lsumdict.keys(): - if not rsumdict.keys(): - print `name`, "only locally", - fl() - if 'w' in mode and 'c' in mode: - sendfile(local, remote, name) - elif 'r' in mode and 'd' in mode: - os.unlink(name) - print "removed." - print - print "gettin subdirs ..." - subdirs = remote._recv(subdirs_id) - common = [] - for name in subdirs: - if local.isdir(name): - print "Common subdirectory", repr(name) - common.append(name) - else: - print "Remote subdirectory", repr(name), "not found locally" - if 'r' in mode and 'c' in mode: - pr = "Create local subdirectory %s? [y] " % \ - repr(name) - if 'y' in mode: - ok = 'y' - else: - ok = ask(pr, "y") - if ok[:1] in ('y', 'Y'): - local.mkdir(name) - print "Subdirectory %s made" % \ - repr(name) - common.append(name) - lsubdirs = local.listsubdirs() - for name in lsubdirs: - if name not in subdirs: - print "Local subdirectory", repr(name), "not found remotely" - for name in common: - print "Entering subdirectory", repr(name) - local.cd(name) - remote.cd(name) - compare(local, remote, mode) - remote.back() - local.back() - -def sendfile(local, remote, name): - try: - remote.create(name) - except (IOError, os.error), msg: - print "cannot create:", msg - return - - print "sending ...", - fl() - - data = open(name).read() - - t1 = time.time() - - remote._send_noreply('write', name, data) - remote._flush() - - t2 = time.time() - - dt = t2-t1 - print len(data), "bytes in", round(dt), "seconds", - if dt: - print "i.e.", round(len(data)/dt), "bytes/sec", - print - -def recvfile(local, remote, name): - ok = 0 - try: - rv = recvfile_real(local, remote, name) - ok = 1 - return rv - finally: - if not ok: - print "*** recvfile of %s failed, deleting" % `name` - local.delete(name) - -def recvfile_real(local, remote, name): - try: - local.create(name) - except (IOError, os.error), msg: - print "cannot create:", msg - return - - print "receiving ...", - fl() - - f = open(name, 'w') - t1 = time.time() - - length = 4*1024 - offset = 0 - id = remote._send('read', name, offset, length) - remote._flush() - while 1: - newoffset = offset + length - newid = remote._send('read', name, newoffset, length) - data = remote._recv(id) - id = newid - if not data: break - f.seek(offset) - f.write(data) - offset = newoffset - size = f.tell() - - t2 = time.time() - f.close() - - dt = t2-t1 - print size, "bytes in", round(dt), "seconds", - if dt: - print "i.e.", int(size/dt), "bytes/sec", - print - remote._recv(id) # ignored - -def fl(): - sys.stdout.flush() - -if __name__ == '__main__': - main() diff --git a/Demo/pdist/cvslib.py b/Demo/pdist/cvslib.py deleted file mode 100755 index cf305c9798..0000000000 --- a/Demo/pdist/cvslib.py +++ /dev/null @@ -1,364 +0,0 @@ -"""Utilities for CVS administration.""" - -import string -import os -import time -import md5 -import fnmatch - -if not hasattr(time, 'timezone'): - time.timezone = 0 - -class File: - - """Represent a file's status. - - Instance variables: - - file -- the filename (no slashes), None if uninitialized - lseen -- true if the data for the local file is up to date - eseen -- true if the data from the CVS/Entries entry is up to date - (this implies that the entry must be written back) - rseen -- true if the data for the remote file is up to date - proxy -- RCSProxy instance used to contact the server, or None - - Note that lseen and rseen don't necessary mean that a local - or remote file *exists* -- they indicate that we've checked it. - However, eseen means that this instance corresponds to an - entry in the CVS/Entries file. - - If lseen is true: - - lsum -- checksum of the local file, None if no local file - lctime -- ctime of the local file, None if no local file - lmtime -- mtime of the local file, None if no local file - - If eseen is true: - - erev -- revision, None if this is a no revision (not '0') - enew -- true if this is an uncommitted added file - edeleted -- true if this is an uncommitted removed file - ectime -- ctime of last local file corresponding to erev - emtime -- mtime of last local file corresponding to erev - extra -- 5th string from CVS/Entries file - - If rseen is true: - - rrev -- revision of head, None if non-existent - rsum -- checksum of that revision, Non if non-existent - - If eseen and rseen are both true: - - esum -- checksum of revision erev, None if no revision - - Note - """ - - def __init__(self, file = None): - if file and '/' in file: - raise ValueError, "no slash allowed in file" - self.file = file - self.lseen = self.eseen = self.rseen = 0 - self.proxy = None - - def __cmp__(self, other): - return cmp(self.file, other.file) - - def getlocal(self): - try: - self.lmtime, self.lctime = os.stat(self.file)[-2:] - except os.error: - self.lmtime = self.lctime = self.lsum = None - else: - self.lsum = md5.md5(open(self.file).read()).digest() - self.lseen = 1 - - def getentry(self, line): - words = string.splitfields(line, '/') - if self.file and words[1] != self.file: - raise ValueError, "file name mismatch" - self.file = words[1] - self.erev = words[2] - self.edeleted = 0 - self.enew = 0 - self.ectime = self.emtime = None - if self.erev[:1] == '-': - self.edeleted = 1 - self.erev = self.erev[1:] - if self.erev == '0': - self.erev = None - self.enew = 1 - else: - dates = words[3] - self.ectime = unctime(dates[:24]) - self.emtime = unctime(dates[25:]) - self.extra = words[4] - if self.rseen: - self.getesum() - self.eseen = 1 - - def getremote(self, proxy = None): - if proxy: - self.proxy = proxy - try: - self.rrev = self.proxy.head(self.file) - except (os.error, IOError): - self.rrev = None - if self.rrev: - self.rsum = self.proxy.sum(self.file) - else: - self.rsum = None - if self.eseen: - self.getesum() - self.rseen = 1 - - def getesum(self): - if self.erev == self.rrev: - self.esum = self.rsum - elif self.erev: - name = (self.file, self.erev) - self.esum = self.proxy.sum(name) - else: - self.esum = None - - def putentry(self): - """Return a line suitable for inclusion in CVS/Entries. - - The returned line is terminated by a newline. - If no entry should be written for this file, - return "". - """ - if not self.eseen: - return "" - - rev = self.erev or '0' - if self.edeleted: - rev = '-' + rev - if self.enew: - dates = 'Initial ' + self.file - else: - dates = gmctime(self.ectime) + ' ' + \ - gmctime(self.emtime) - return "/%s/%s/%s/%s/\n" % ( - self.file, - rev, - dates, - self.extra) - - def report(self): - print '-'*50 - def r(key, repr=repr, self=self): - try: - value = repr(getattr(self, key)) - except AttributeError: - value = "?" - print "%-15s:" % key, value - r("file") - if self.lseen: - r("lsum", hexify) - r("lctime", gmctime) - r("lmtime", gmctime) - if self.eseen: - r("erev") - r("enew") - r("edeleted") - r("ectime", gmctime) - r("emtime", gmctime) - if self.rseen: - r("rrev") - r("rsum", hexify) - if self.eseen: - r("esum", hexify) - - -class CVS: - - """Represent the contents of a CVS admin file (and more). - - Class variables: - - FileClass -- the class to be instantiated for entries - (this should be derived from class File above) - IgnoreList -- shell patterns for local files to be ignored - - Instance variables: - - entries -- a dictionary containing File instances keyed by - their file name - proxy -- an RCSProxy instance, or None - """ - - FileClass = File - - IgnoreList = ['.*', '@*', ',*', '*~', '*.o', '*.a', '*.so', '*.pyc'] - - def __init__(self): - self.entries = {} - self.proxy = None - - def setproxy(self, proxy): - if proxy is self.proxy: - return - self.proxy = proxy - for e in self.entries.values(): - e.rseen = 0 - - def getentries(self): - """Read the contents of CVS/Entries""" - self.entries = {} - f = self.cvsopen("Entries") - while 1: - line = f.readline() - if not line: break - e = self.FileClass() - e.getentry(line) - self.entries[e.file] = e - f.close() - - def putentries(self): - """Write CVS/Entries back""" - f = self.cvsopen("Entries", 'w') - for e in self.values(): - f.write(e.putentry()) - f.close() - - def getlocalfiles(self): - list = self.entries.keys() - addlist = os.listdir(os.curdir) - for name in addlist: - if name in list: - continue - if not self.ignored(name): - list.append(name) - list.sort() - for file in list: - try: - e = self.entries[file] - except KeyError: - e = self.entries[file] = self.FileClass(file) - e.getlocal() - - def getremotefiles(self, proxy = None): - if proxy: - self.proxy = proxy - if not self.proxy: - raise RuntimeError, "no RCS proxy" - addlist = self.proxy.listfiles() - for file in addlist: - try: - e = self.entries[file] - except KeyError: - e = self.entries[file] = self.FileClass(file) - e.getremote(self.proxy) - - def report(self): - for e in self.values(): - e.report() - print '-'*50 - - def keys(self): - keys = self.entries.keys() - keys.sort() - return keys - - def values(self): - def value(key, self=self): - return self.entries[key] - return map(value, self.keys()) - - def items(self): - def item(key, self=self): - return (key, self.entries[key]) - return map(item, self.keys()) - - def cvsexists(self, file): - file = os.path.join("CVS", file) - return os.path.exists(file) - - def cvsopen(self, file, mode = 'r'): - file = os.path.join("CVS", file) - if 'r' not in mode: - self.backup(file) - return open(file, mode) - - def backup(self, file): - if os.path.isfile(file): - bfile = file + '~' - try: os.unlink(bfile) - except os.error: pass - os.rename(file, bfile) - - def ignored(self, file): - if os.path.isdir(file): return 1 - for pat in self.IgnoreList: - if fnmatch.fnmatch(file, pat): return 1 - return 0 - - -# hexify and unhexify are useful to print MD5 checksums in hex format - -hexify_format = '%02x' * 16 -def hexify(sum): - "Return a hex representation of a 16-byte string (e.g. an MD5 digest)" - if sum is None: - return "None" - return hexify_format % tuple(map(ord, sum)) - -def unhexify(hexsum): - "Return the original from a hexified string" - if hexsum == "None": - return None - sum = '' - for i in range(0, len(hexsum), 2): - sum = sum + chr(string.atoi(hexsum[i:i+2], 16)) - return sum - - -unctime_monthmap = {} -def unctime(date): - if date == "None": return None - if not unctime_monthmap: - months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] - i = 0 - for m in months: - i = i+1 - unctime_monthmap[m] = i - words = string.split(date) # Day Mon DD HH:MM:SS YEAR - year = string.atoi(words[4]) - month = unctime_monthmap[words[1]] - day = string.atoi(words[2]) - [hh, mm, ss] = map(string.atoi, string.splitfields(words[3], ':')) - ss = ss - time.timezone - return time.mktime((year, month, day, hh, mm, ss, 0, 0, 0)) - -def gmctime(t): - if t is None: return "None" - return time.asctime(time.gmtime(t)) - -def test_unctime(): - now = int(time.time()) - t = time.gmtime(now) - at = time.asctime(t) - print 'GMT', now, at - print 'timezone', time.timezone - print 'local', time.ctime(now) - u = unctime(at) - print 'unctime()', u - gu = time.gmtime(u) - print '->', gu - print time.asctime(gu) - -def test(): - x = CVS() - x.getentries() - x.getlocalfiles() -## x.report() - import rcsclient - proxy = rcsclient.openrcsclient() - x.getremotefiles(proxy) - x.report() - - -if __name__ == "__main__": - test() diff --git a/Demo/pdist/cvslock.py b/Demo/pdist/cvslock.py deleted file mode 100755 index a421e1a943..0000000000 --- a/Demo/pdist/cvslock.py +++ /dev/null @@ -1,280 +0,0 @@ -"""CVS locking algorithm. - -CVS locking strategy -==================== - -As reverse engineered from the CVS 1.3 sources (file lock.c): - -- Locking is done on a per repository basis (but a process can hold -write locks for multiple directories); all lock files are placed in -the repository and have names beginning with "#cvs.". - -- Before even attempting to lock, a file "#cvs.tfl." is created -(and removed again), to test that we can write the repository. [The -algorithm can still be fooled (1) if the repository's mode is changed -while attempting to lock; (2) if this file exists and is writable but -the directory is not.] - -- While creating the actual read/write lock files (which may exist for -a long time), a "meta-lock" is held. The meta-lock is a directory -named "#cvs.lock" in the repository. The meta-lock is also held while -a write lock is held. - -- To set a read lock: - - - acquire the meta-lock - - create the file "#cvs.rfl." - - release the meta-lock - -- To set a write lock: - - - acquire the meta-lock - - check that there are no files called "#cvs.rfl.*" - - if there are, release the meta-lock, sleep, try again - - create the file "#cvs.wfl." - -- To release a write lock: - - - remove the file "#cvs.wfl." - - rmdir the meta-lock - -- To release a read lock: - - - remove the file "#cvs.rfl." - - -Additional notes ----------------- - -- A process should read-lock at most one repository at a time. - -- A process may write-lock as many repositories as it wishes (to avoid -deadlocks, I presume it should always lock them top-down in the -directory hierarchy). - -- A process should make sure it removes all its lock files and -directories when it crashes. - -- Limitation: one user id should not be committing files into the same -repository at the same time. - - -Turn this into Python code --------------------------- - -rl = ReadLock(repository, waittime) - -wl = WriteLock(repository, waittime) - -list = MultipleWriteLock([repository1, repository2, ...], waittime) - -""" - - -import os -import time -import stat -import pwd - - -# Default wait time -DELAY = 10 - - -# XXX This should be the same on all Unix versions -EEXIST = 17 - - -# Files used for locking (must match cvs.h in the CVS sources) -CVSLCK = "#cvs.lck" -CVSRFL = "#cvs.rfl." -CVSWFL = "#cvs.wfl." - - -class Error: - - def __init__(self, msg): - self.msg = msg - - def __repr__(self): - return repr(self.msg) - - def __str__(self): - return str(self.msg) - - -class Locked(Error): - pass - - -class Lock: - - def __init__(self, repository = ".", delay = DELAY): - self.repository = repository - self.delay = delay - self.lockdir = None - self.lockfile = None - pid = `os.getpid()` - self.cvslck = self.join(CVSLCK) - self.cvsrfl = self.join(CVSRFL + pid) - self.cvswfl = self.join(CVSWFL + pid) - - def __del__(self): - print "__del__" - self.unlock() - - def setlockdir(self): - while 1: - try: - self.lockdir = self.cvslck - os.mkdir(self.cvslck, 0777) - return - except os.error, msg: - self.lockdir = None - if msg[0] == EEXIST: - try: - st = os.stat(self.cvslck) - except os.error: - continue - self.sleep(st) - continue - raise Error("failed to lock %s: %s" % ( - self.repository, msg)) - - def unlock(self): - self.unlockfile() - self.unlockdir() - - def unlockfile(self): - if self.lockfile: - print "unlink", self.lockfile - try: - os.unlink(self.lockfile) - except os.error: - pass - self.lockfile = None - - def unlockdir(self): - if self.lockdir: - print "rmdir", self.lockdir - try: - os.rmdir(self.lockdir) - except os.error: - pass - self.lockdir = None - - def sleep(self, st): - sleep(st, self.repository, self.delay) - - def join(self, name): - return os.path.join(self.repository, name) - - -def sleep(st, repository, delay): - if delay <= 0: - raise Locked(st) - uid = st[stat.ST_UID] - try: - pwent = pwd.getpwuid(uid) - user = pwent[0] - except KeyError: - user = "uid %d" % uid - print "[%s]" % time.ctime(time.time())[11:19], - print "Waiting for %s's lock in" % user, repository - time.sleep(delay) - - -class ReadLock(Lock): - - def __init__(self, repository, delay = DELAY): - Lock.__init__(self, repository, delay) - ok = 0 - try: - self.setlockdir() - self.lockfile = self.cvsrfl - fp = open(self.lockfile, 'w') - fp.close() - ok = 1 - finally: - if not ok: - self.unlockfile() - self.unlockdir() - - -class WriteLock(Lock): - - def __init__(self, repository, delay = DELAY): - Lock.__init__(self, repository, delay) - self.setlockdir() - while 1: - uid = self.readers_exist() - if not uid: - break - self.unlockdir() - self.sleep(uid) - self.lockfile = self.cvswfl - fp = open(self.lockfile, 'w') - fp.close() - - def readers_exist(self): - n = len(CVSRFL) - for name in os.listdir(self.repository): - if name[:n] == CVSRFL: - try: - st = os.stat(self.join(name)) - except os.error: - continue - return st - return None - - -def MultipleWriteLock(repositories, delay = DELAY): - while 1: - locks = [] - for r in repositories: - try: - locks.append(WriteLock(r, 0)) - except Locked, instance: - del locks - break - else: - break - sleep(instance.msg, r, delay) - return list - - -def test(): - import sys - if sys.argv[1:]: - repository = sys.argv[1] - else: - repository = "." - rl = None - wl = None - try: - print "attempting write lock ..." - wl = WriteLock(repository) - print "got it." - wl.unlock() - print "attempting read lock ..." - rl = ReadLock(repository) - print "got it." - rl.unlock() - finally: - print [1] - sys.exc_traceback = None - print [2] - if rl: - rl.unlock() - print [3] - if wl: - wl.unlock() - print [4] - rl = None - print [5] - wl = None - print [6] - - -if __name__ == '__main__': - test() diff --git a/Demo/pdist/new b/Demo/pdist/new deleted file mode 100755 index 9daeafb986..0000000000 --- a/Demo/pdist/new +++ /dev/null @@ -1 +0,0 @@ -test diff --git a/Demo/pdist/rcsbump b/Demo/pdist/rcsbump deleted file mode 100755 index 421501e7d3..0000000000 --- a/Demo/pdist/rcsbump +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/local/bin/python -# -*- python -*- -# -# guido's version, from rcsbump,v 1.2 1995/06/22 21:27:27 bwarsaw Exp -# -# Python script for bumping up an RCS major revision number. - -import sys -import regex -import rcslib -import string - -WITHLOCK = 1 -majorrev_re = regex.compile('^[0-9]+') - -dir = rcslib.RCS() - -if sys.argv[1:]: - files = sys.argv[1:] -else: - files = dir.listfiles() - -for file in files: - # get the major revnumber of the file - headbranch = dir.info(file)['head'] - majorrev_re.match(headbranch) - majorrev = string.atoi(majorrev_re.group(0)) + 1 - - if not dir.islocked(file): - dir.checkout(file, WITHLOCK) - - msg = "Bumping major revision number (to %d)" % majorrev - dir.checkin((file, "%s.0" % majorrev), msg, "-f") diff --git a/Demo/pdist/rcsclient.py b/Demo/pdist/rcsclient.py deleted file mode 100755 index 20dffeca23..0000000000 --- a/Demo/pdist/rcsclient.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Customize this file to change the default client etc. - -(In general, it is probably be better to make local operation the -default and to require something like an RCSSERVER environment -variable to enable remote operation.) - -""" - -import string -import os - -# These defaults don't belong here -- they should be taken from the -# environment or from a hidden file in the current directory - -HOST = 'voorn.cwi.nl' -PORT = 4127 -VERBOSE = 1 -LOCAL = 0 - -import client - - -class RCSProxyClient(client.SecureClient): - - def __init__(self, address, verbose = client.VERBOSE): - client.SecureClient.__init__(self, address, verbose) - - -def openrcsclient(opts = []): - "open an RCSProxy client based on a list of options returned by getopt" - import RCSProxy - host = HOST - port = PORT - verbose = VERBOSE - local = LOCAL - directory = None - for o, a in opts: - if o == '-h': - host = a - if ':' in host: - i = string.find(host, ':') - host, p = host[:i], host[i+1:] - if p: - port = string.atoi(p) - if o == '-p': - port = string.atoi(a) - if o == '-d': - directory = a - if o == '-v': - verbose = verbose + 1 - if o == '-q': - verbose = 0 - if o == '-L': - local = 1 - if local: - import RCSProxy - x = RCSProxy.RCSProxyLocal() - else: - address = (host, port) - x = RCSProxyClient(address, verbose) - if not directory: - try: - directory = open(os.path.join("CVS", "Repository")).readline() - except IOError: - pass - else: - if directory[-1] == '\n': - directory = directory[:-1] - if directory: - x.cd(directory) - return x diff --git a/Demo/pdist/rcslib.py b/Demo/pdist/rcslib.py deleted file mode 100755 index 43dcf0a07e..0000000000 --- a/Demo/pdist/rcslib.py +++ /dev/null @@ -1,337 +0,0 @@ -"""RCS interface module. - -Defines the class RCS, which represents a directory with rcs version -files and (possibly) corresponding work files. - -""" - - -import fnmatch -import os -import regsub -import string -import tempfile - - -class RCS: - - """RCS interface class (local filesystem version). - - An instance of this class represents a directory with rcs version - files and (possible) corresponding work files. - - Methods provide access to most rcs operations such as - checkin/checkout, access to the rcs metadata (revisions, logs, - branches etc.) as well as some filesystem operations such as - listing all rcs version files. - - XXX BUGS / PROBLEMS - - - The instance always represents the current directory so it's not - very useful to have more than one instance around simultaneously - - """ - - # Characters allowed in work file names - okchars = string.letters + string.digits + '-_=+.' - - def __init__(self): - """Constructor.""" - pass - - def __del__(self): - """Destructor.""" - pass - - # --- Informational methods about a single file/revision --- - - def log(self, name_rev, otherflags = ''): - """Return the full log text for NAME_REV as a string. - - Optional OTHERFLAGS are passed to rlog. - - """ - f = self._open(name_rev, 'rlog ' + otherflags) - data = f.read() - status = self._closepipe(f) - if status: - data = data + "%s: %s" % status - elif data[-1] == '\n': - data = data[:-1] - return data - - def head(self, name_rev): - """Return the head revision for NAME_REV""" - dict = self.info(name_rev) - return dict['head'] - - def info(self, name_rev): - """Return a dictionary of info (from rlog -h) for NAME_REV - - The dictionary's keys are the keywords that rlog prints - (e.g. 'head' and its values are the corresponding data - (e.g. '1.3'). - - XXX symbolic names and locks are not returned - - """ - f = self._open(name_rev, 'rlog -h') - dict = {} - while 1: - line = f.readline() - if not line: break - if line[0] == '\t': - # XXX could be a lock or symbolic name - # Anything else? - continue - i = string.find(line, ':') - if i > 0: - key, value = line[:i], string.strip(line[i+1:]) - dict[key] = value - status = self._closepipe(f) - if status: - raise IOError, status - return dict - - # --- Methods that change files --- - - def lock(self, name_rev): - """Set an rcs lock on NAME_REV.""" - name, rev = self.checkfile(name_rev) - cmd = "rcs -l%s %s" % (rev, name) - return self._system(cmd) - - def unlock(self, name_rev): - """Clear an rcs lock on NAME_REV.""" - name, rev = self.checkfile(name_rev) - cmd = "rcs -u%s %s" % (rev, name) - return self._system(cmd) - - def checkout(self, name_rev, withlock=0, otherflags=""): - """Check out NAME_REV to its work file. - - If optional WITHLOCK is set, check out locked, else unlocked. - - The optional OTHERFLAGS is passed to co without - interpretation. - - Any output from co goes to directly to stdout. - - """ - name, rev = self.checkfile(name_rev) - if withlock: lockflag = "-l" - else: lockflag = "-u" - cmd = 'co %s%s %s %s' % (lockflag, rev, otherflags, name) - return self._system(cmd) - - def checkin(self, name_rev, message=None, otherflags=""): - """Check in NAME_REV from its work file. - - The optional MESSAGE argument becomes the checkin message - (default "" if None); or the file description if this is - a new file. - - The optional OTHERFLAGS argument is passed to ci without - interpretation. - - Any output from ci goes to directly to stdout. - - """ - name, rev = self._unmangle(name_rev) - new = not self.isvalid(name) - if not message: message = "" - if message and message[-1] != '\n': - message = message + '\n' - lockflag = "-u" - textfile = None - try: - if new: - textfile = tempfile.mktemp() - f = open(textfile, 'w') - f.write(message) - f.close() - cmd = 'ci %s%s -t%s %s %s' % \ - (lockflag, rev, textfile, otherflags, name) - else: - message = regsub.gsub('\([\\"$`]\)', '\\\\\\1', message) - cmd = 'ci %s%s -m"%s" %s %s' % \ - (lockflag, rev, message, otherflags, name) - return self._system(cmd) - finally: - if textfile: self._remove(textfile) - - # --- Exported support methods --- - - def listfiles(self, pat = None): - """Return a list of all version files matching optional PATTERN.""" - files = os.listdir(os.curdir) - files = filter(self._isrcs, files) - if os.path.isdir('RCS'): - files2 = os.listdir('RCS') - files2 = filter(self._isrcs, files2) - files = files + files2 - files = map(self.realname, files) - return self._filter(files, pat) - - def isvalid(self, name): - """Test whether NAME has a version file associated.""" - namev = self.rcsname(name) - return (os.path.isfile(namev) or - os.path.isfile(os.path.join('RCS', namev))) - - def rcsname(self, name): - """Return the pathname of the version file for NAME. - - The argument can be a work file name or a version file name. - If the version file does not exist, the name of the version - file that would be created by "ci" is returned. - - """ - if self._isrcs(name): namev = name - else: namev = name + ',v' - if os.path.isfile(namev): return namev - namev = os.path.join('RCS', os.path.basename(namev)) - if os.path.isfile(namev): return namev - if os.path.isdir('RCS'): - return os.path.join('RCS', namev) - else: - return namev - - def realname(self, namev): - """Return the pathname of the work file for NAME. - - The argument can be a work file name or a version file name. - If the work file does not exist, the name of the work file - that would be created by "co" is returned. - - """ - if self._isrcs(namev): name = namev[:-2] - else: name = namev - if os.path.isfile(name): return name - name = os.path.basename(name) - return name - - def islocked(self, name_rev): - """Test whether FILE (which must have a version file) is locked. - - XXX This does not tell you which revision number is locked and - ignores any revision you may pass in (by virtue of using rlog - -L -R). - - """ - f = self._open(name_rev, 'rlog -L -R') - line = f.readline() - status = self._closepipe(f) - if status: - raise IOError, status - if not line: return None - return self.realname(name_rev) == self.realname(line) - - def checkfile(self, name_rev): - """Normalize NAME_REV into a (NAME, REV) tuple. - - Raise an exception if there is no corresponding version file. - - """ - name, rev = self._unmangle(name_rev) - if not self.isvalid(name): - raise os.error, 'not an rcs file %s' % `name` - return name, rev - - # --- Internal methods --- - - def _open(self, name_rev, cmd = 'co -p', rflag = '-r'): - """INTERNAL: open a read pipe to NAME_REV using optional COMMAND. - - Optional FLAG is used to indicate the revision (default -r). - - Default COMMAND is "co -p". - - Return a file object connected by a pipe to the command's - output. - - """ - name, rev = self.checkfile(name_rev) - namev = self.rcsname(name) - if rev: - cmd = cmd + ' ' + rflag + rev - return os.popen("%s %s" % (cmd, `namev`)) - - def _unmangle(self, name_rev): - """INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple. - - Raise an exception if NAME contains invalid characters. - - A NAME_REV argument is either NAME string (implying REV='') or - a tuple of the form (NAME, REV). - - """ - if type(name_rev) == type(''): - name_rev = name, rev = name_rev, '' - else: - name, rev = name_rev - for c in rev: - if c not in self.okchars: - raise ValueError, "bad char in rev" - return name_rev - - def _closepipe(self, f): - """INTERNAL: Close PIPE and print its exit status if nonzero.""" - sts = f.close() - if not sts: return None - detail, reason = divmod(sts, 256) - if reason == 0: return 'exit', detail # Exit status - signal = reason&0x7F - if signal == 0x7F: - code = 'stopped' - signal = detail - else: - code = 'killed' - if reason&0x80: - code = code + '(coredump)' - return code, signal - - def _system(self, cmd): - """INTERNAL: run COMMAND in a subshell. - - Standard input for the command is taken fron /dev/null. - - Raise IOError when the exit status is not zero. - - Return whatever the calling method should return; normally - None. - - A derived class may override this method and redefine it to - capture stdout/stderr of the command and return it. - - """ - cmd = cmd + " > ") - sys.stderr.flush() - line = sys.stdin.readline() - if not line or line == '.\n': break - message = message + line - return message - -def remove(fn): - try: - os.unlink(fn) - except os.error: - pass - -commands = { - 'ci': ('', checkin), - 'put': ('', checkin), - 'co': ('', checkout), - 'get': ('', checkout), - 'info': ('', info), - 'head': ('', head), - 'list': ('', list), - 'lock': ('', lock), - 'unlock': ('', unlock), - 'log': ('bhLRtd:l:r:s:w:V:', log), - 'diff': ('c', diff), - } - -if __name__ == '__main__': - main() diff --git a/Demo/pdist/security.py b/Demo/pdist/security.py deleted file mode 100755 index f9936828a4..0000000000 --- a/Demo/pdist/security.py +++ /dev/null @@ -1,33 +0,0 @@ -class Security: - - def __init__(self): - import os - env = os.environ - if env.has_key('PYTHON_KEYFILE'): - keyfile = env['PYTHON_KEYFILE'] - else: - keyfile = '.python_keyfile' - if env.has_key('HOME'): - keyfile = os.path.join(env['HOME'], keyfile) - if not os.path.exists(keyfile): - import sys - for dir in sys.path: - kf = os.path.join(dir, keyfile) - if os.path.exists(kf): - keyfile = kf - break - try: - self._key = eval(open(keyfile).readline()) - except IOError: - raise IOError, "python keyfile %s: cannot open" % keyfile - - def _generate_challenge(self): - import whrandom - return whrandom.randint(100, 100000) - - def _compare_challenge_response(self, challenge, response): - return self._encode_challenge(challenge) == response - - def _encode_challenge(self, challenge): - p, m = self._key - return pow(long(challenge), p, m) diff --git a/Demo/pdist/server.py b/Demo/pdist/server.py deleted file mode 100755 index 423d583007..0000000000 --- a/Demo/pdist/server.py +++ /dev/null @@ -1,145 +0,0 @@ -"""RPC Server module.""" - -import sys -import socket -import pickle -from fnmatch import fnmatch -from repr import repr - - -# Default verbosity (0 = silent, 1 = print connections, 2 = print requests too) -VERBOSE = 1 - - -class Server: - - """RPC Server class. Derive a class to implement a particular service.""" - - def __init__(self, address, verbose = VERBOSE): - if type(address) == type(0): - address = ('', address) - self._address = address - self._verbose = verbose - self._socket = None - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.bind(address) - self._socket.listen(1) - self._listening = 1 - - def _setverbose(self, verbose): - self._verbose = verbose - - def __del__(self): - self._close() - - def _close(self): - self._listening = 0 - if self._socket: - self._socket.close() - self._socket = None - - def _serverloop(self): - while self._listening: - self._serve() - - def _serve(self): - if self._verbose: print "Wait for connection ..." - conn, address = self._socket.accept() - if self._verbose: print "Accepted connection from %s" % repr(address) - if not self._verify(conn, address): - print "*** Connection from %s refused" % repr(address) - conn.close() - return - rf = conn.makefile('r') - wf = conn.makefile('w') - ok = 1 - while ok: - wf.flush() - if self._verbose > 1: print "Wait for next request ..." - ok = self._dorequest(rf, wf) - - _valid = ['192.16.201.*', '192.16.197.*', '132.151.1.*', '129.6.64.*'] - - def _verify(self, conn, address): - host, port = address - for pat in self._valid: - if fnmatch(host, pat): return 1 - return 0 - - def _dorequest(self, rf, wf): - rp = pickle.Unpickler(rf) - try: - request = rp.load() - except EOFError: - return 0 - if self._verbose > 1: print "Got request: %s" % repr(request) - try: - methodname, args, id = request - if '.' in methodname: - reply = (None, self._special(methodname, args), id) - elif methodname[0] == '_': - raise NameError, "illegal method name %s" % repr(methodname) - else: - method = getattr(self, methodname) - reply = (None, apply(method, args), id) - except: - reply = (sys.exc_type, sys.exc_value, id) - if id < 0 and reply[:2] == (None, None): - if self._verbose > 1: print "Suppress reply" - return 1 - if self._verbose > 1: print "Send reply: %s" % repr(reply) - wp = pickle.Pickler(wf) - wp.dump(reply) - return 1 - - def _special(self, methodname, args): - if methodname == '.methods': - if not hasattr(self, '_methods'): - self._methods = tuple(self._listmethods()) - return self._methods - raise NameError, "unrecognized special method name %s" % repr(methodname) - - def _listmethods(self, cl=None): - if not cl: cl = self.__class__ - names = cl.__dict__.keys() - names = filter(lambda x: x[0] != '_', names) - names.sort() - for base in cl.__bases__: - basenames = self._listmethods(base) - basenames = filter(lambda x, names=names: x not in names, basenames) - names[len(names):] = basenames - return names - - -from security import Security - - -class SecureServer(Server, Security): - - def __init__(self, *args): - apply(Server.__init__, (self,) + args) - Security.__init__(self) - - def _verify(self, conn, address): - import string - challenge = self._generate_challenge() - conn.send("%d\n" % challenge) - response = "" - while "\n" not in response and len(response) < 100: - data = conn.recv(100) - if not data: - break - response = response + data - try: - response = string.atol(string.strip(response)) - except string.atol_error: - if self._verbose > 0: - print "Invalid response syntax", `response` - return 0 - if not self._compare_challenge_response(challenge, response): - if self._verbose > 0: - print "Invalid response value", `response` - return 0 - if self._verbose > 1: - print "Response matches challenge. Go ahead!" - return 1 diff --git a/Demo/pdist/sumtree.py b/Demo/pdist/sumtree.py deleted file mode 100755 index 92c1fd0552..0000000000 --- a/Demo/pdist/sumtree.py +++ /dev/null @@ -1,24 +0,0 @@ -import time -import FSProxy - -def main(): - t1 = time.time() - #proxy = FSProxy.FSProxyClient(('voorn.cwi.nl', 4127)) - proxy = FSProxy.FSProxyLocal() - sumtree(proxy) - proxy._close() - t2 = time.time() - print t2-t1, "seconds" - raw_input("[Return to exit] ") - -def sumtree(proxy): - print "PWD =", proxy.pwd() - files = proxy.listfiles() - proxy.infolist(files) - subdirs = proxy.listsubdirs() - for name in subdirs: - proxy.cd(name) - sumtree(proxy) - proxy.back() - -main() diff --git a/Demo/rpc/MANIFEST b/Demo/rpc/MANIFEST deleted file mode 100644 index e65f3ebee8..0000000000 --- a/Demo/rpc/MANIFEST +++ /dev/null @@ -1,10 +0,0 @@ - File Name Archive # Description ------------------------------------------------------------ - MANIFEST 1 This shipping list - README 1 - T.py 1 - mountclient.py 1 - nfsclient.py 1 - rpc.py 1 - test 1 - xdr.py 1 diff --git a/Demo/rpc/README b/Demo/rpc/README deleted file mode 100644 index be75c10400..0000000000 --- a/Demo/rpc/README +++ /dev/null @@ -1,23 +0,0 @@ -This is a Python interface to Sun RPC, designed and implemented mostly -by reading the Internet RFCs about the subject. - -There are two library modules, xdr.py and rpc.py, and several example -clients: mountclient.py, nfsclient.py, and rnusersclient.py, -implementing the NFS Mount protocol, (part of) the NFS protocol, and -the "rnusers" protocol (used by rusers(1)), respectively. The latter -demonstrates the use of broadcast via the Port mapper's CALLIT -procedure. - -There is also a way to create servers in Python. - -To test the nfs client, run it from the shell with something like this: - - python -c 'import nfsclient; nfsclient.test()' [hostname [filesystemname]] - -When called without a filesystemname, it lists the filesystems at the -host; default host is the local machine. - -Other clients are tested similarly. - -For hostname, use e.g. wuarchive.wustl.edu or gatekeeper.dec.com (two -hosts that are known to export NFS filesystems with little restrictions). diff --git a/Demo/rpc/T.py b/Demo/rpc/T.py deleted file mode 100644 index abf3a06d05..0000000000 --- a/Demo/rpc/T.py +++ /dev/null @@ -1,22 +0,0 @@ -# Simple interface to report execution times of program fragments. -# Call TSTART() to reset the timer, TSTOP(...) to report times. - -import sys, os, time - -def TSTART(): - global t0, t1 - u, s, cu, cs = os.times() - t0 = u+cu, s+cs, time.time() - -def TSTOP(*label): - global t0, t1 - u, s, cu, cs = os.times() - t1 = u+cu, s+cs, time.time() - tt = [] - for i in range(3): - tt.append(t1[i] - t0[i]) - [u, s, r] = tt - msg = '' - for x in label: msg = msg + (x + ' ') - msg = msg + `u` + ' user, ' + `s` + ' sys, ' + `r` + ' real\n' - sys.stderr.write(msg) diff --git a/Demo/rpc/mountclient.py b/Demo/rpc/mountclient.py deleted file mode 100644 index ff66b3d6cc..0000000000 --- a/Demo/rpc/mountclient.py +++ /dev/null @@ -1,201 +0,0 @@ -# Mount RPC client -- RFC 1094 (NFS), Appendix A - -# This module demonstrates how to write your own RPC client in Python. -# Since there is no RPC compiler for Python (yet), you must first -# create classes derived from Packer and Unpacker to handle the data -# types for the server you want to interface to. You then write the -# client class. If you want to support both the TCP and the UDP -# version of a protocol, use multiple inheritance as shown below. - - -import rpc -from rpc import Packer, Unpacker, TCPClient, UDPClient - - -# Program number and version for the mount protocol -MOUNTPROG = 100005 -MOUNTVERS = 1 - -# Size of the 'fhandle' opaque structure -FHSIZE = 32 - - -# Packer derived class for Mount protocol clients. -# The only thing we need to pack beyond basic types is an 'fhandle' - -class MountPacker(Packer): - - def pack_fhandle(self, fhandle): - self.pack_fopaque(FHSIZE, fhandle) - - -# Unpacker derived class for Mount protocol clients. -# The important types we need to unpack are fhandle, fhstatus, -# mountlist and exportlist; mountstruct, exportstruct and groups are -# used to unpack components of mountlist and exportlist and the -# corresponding functions are passed as function argument to the -# generic unpack_list function. - -class MountUnpacker(Unpacker): - - def unpack_fhandle(self): - return self.unpack_fopaque(FHSIZE) - - def unpack_fhstatus(self): - status = self.unpack_uint() - if status == 0: - fh = self.unpack_fhandle() - else: - fh = None - return status, fh - - def unpack_mountlist(self): - return self.unpack_list(self.unpack_mountstruct) - - def unpack_mountstruct(self): - hostname = self.unpack_string() - directory = self.unpack_string() - return (hostname, directory) - - def unpack_exportlist(self): - return self.unpack_list(self.unpack_exportstruct) - - def unpack_exportstruct(self): - filesys = self.unpack_string() - groups = self.unpack_groups() - return (filesys, groups) - - def unpack_groups(self): - return self.unpack_list(self.unpack_string) - - -# These are the procedures specific to the Mount client class. -# Think of this as a derived class of either TCPClient or UDPClient. - -class PartialMountClient: - - # This method is called by Client.__init__ to initialize - # self.packer and self.unpacker - def addpackers(self): - self.packer = MountPacker() - self.unpacker = MountUnpacker('') - - # This method is called by Client.__init__ to bind the socket - # to a particular network interface and port. We use the - # default network interface, but if we're running as root, - # we want to bind to a reserved port - def bindsocket(self): - import os - try: - uid = os.getuid() - except AttributeError: - uid = 1 - if uid == 0: - port = rpc.bindresvport(self.sock, '') - # 'port' is not used - else: - self.sock.bind(('', 0)) - - # This function is called to cough up a suitable - # authentication object for a call to procedure 'proc'. - def mkcred(self): - if self.cred == None: - self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default() - return self.cred - - # The methods Mnt, Dump etc. each implement one Remote - # Procedure Call. This is done by calling self.make_call() - # with as arguments: - # - # - the procedure number - # - the arguments (or None) - # - the "packer" function for the arguments (or None) - # - the "unpacker" function for the return value (or None) - # - # The packer and unpacker function, if not None, *must* be - # methods of self.packer and self.unpacker, respectively. - # A value of None means that there are no arguments or is no - # return value, respectively. - # - # The return value from make_call() is the return value from - # the remote procedure call, as unpacked by the "unpacker" - # function, or None if the unpacker function is None. - # - # (Even if you expect a result of None, you should still - # return the return value from make_call(), since this may be - # needed by a broadcasting version of the class.) - # - # If the call fails, make_call() raises an exception - # (this includes time-outs and invalid results). - # - # Note that (at least with the UDP protocol) there is no - # guarantee that a call is executed at most once. When you do - # get a reply, you know it has been executed at least once; - # when you don't get a reply, you know nothing. - - def Mnt(self, directory): - return self.make_call(1, directory, \ - self.packer.pack_string, \ - self.unpacker.unpack_fhstatus) - - def Dump(self): - return self.make_call(2, None, \ - None, self.unpacker.unpack_mountlist) - - def Umnt(self, directory): - return self.make_call(3, directory, \ - self.packer.pack_string, None) - - def Umntall(self): - return self.make_call(4, None, None, None) - - def Export(self): - return self.make_call(5, None, \ - None, self.unpacker.unpack_exportlist) - - -# We turn the partial Mount client into a full one for either protocol -# by use of multiple inheritance. (In general, when class C has base -# classes B1...Bn, if x is an instance of class C, methods of x are -# searched first in C, then in B1, then in B2, ..., finally in Bn.) - -class TCPMountClient(PartialMountClient, TCPClient): - - def __init__(self, host): - TCPClient.__init__(self, host, MOUNTPROG, MOUNTVERS) - - -class UDPMountClient(PartialMountClient, UDPClient): - - def __init__(self, host): - UDPClient.__init__(self, host, MOUNTPROG, MOUNTVERS) - - -# A little test program for the Mount client. This takes a host as -# command line argument (default the local machine), prints its export -# list, and attempts to mount and unmount each exported files system. -# An optional first argument of -t or -u specifies the protocol to use -# (TCP or UDP), default is UDP. - -def test(): - import sys - if sys.argv[1:] and sys.argv[1] == '-t': - C = TCPMountClient - del sys.argv[1] - elif sys.argv[1:] and sys.argv[1] == '-u': - C = UDPMountClient - del sys.argv[1] - else: - C = UDPMountClient - if sys.argv[1:]: host = sys.argv[1] - else: host = '' - mcl = C(host) - list = mcl.Export() - for item in list: - print item - try: - mcl.Mnt(item[0]) - except: - print 'Sorry' - continue - mcl.Umnt(item[0]) diff --git a/Demo/rpc/nfsclient.py b/Demo/rpc/nfsclient.py deleted file mode 100644 index 498e2d0b98..0000000000 --- a/Demo/rpc/nfsclient.py +++ /dev/null @@ -1,201 +0,0 @@ -# NFS RPC client -- RFC 1094 - -# XXX This is not yet complete. -# XXX Only GETATTR, SETTTR, LOOKUP and READDIR are supported. - -# (See mountclient.py for some hints on how to write RPC clients in -# Python in general) - -import rpc -from rpc import UDPClient, TCPClient -from mountclient import FHSIZE, MountPacker, MountUnpacker - -NFS_PROGRAM = 100003 -NFS_VERSION = 2 - -# enum stat -NFS_OK = 0 -# (...many error values...) - -# enum ftype -NFNON = 0 -NFREG = 1 -NFDIR = 2 -NFBLK = 3 -NFCHR = 4 -NFLNK = 5 - - -class NFSPacker(MountPacker): - - def pack_sattrargs(self, sa): - file, attributes = sa - self.pack_fhandle(file) - self.pack_sattr(attributes) - - def pack_sattr(self, sa): - mode, uid, gid, size, atime, mtime = sa - self.pack_uint(mode) - self.pack_uint(uid) - self.pack_uint(gid) - self.pack_uint(size) - self.pack_timeval(atime) - self.pack_timeval(mtime) - - def pack_diropargs(self, da): - dir, name = da - self.pack_fhandle(dir) - self.pack_string(name) - - def pack_readdirargs(self, ra): - dir, cookie, count = ra - self.pack_fhandle(dir) - self.pack_uint(cookie) - self.pack_uint(count) - - def pack_timeval(self, tv): - secs, usecs = tv - self.pack_uint(secs) - self.pack_uint(usecs) - - -class NFSUnpacker(MountUnpacker): - - def unpack_readdirres(self): - status = self.unpack_enum() - if status == NFS_OK: - entries = self.unpack_list(self.unpack_entry) - eof = self.unpack_bool() - rest = (entries, eof) - else: - rest = None - return (status, rest) - - def unpack_entry(self): - fileid = self.unpack_uint() - name = self.unpack_string() - cookie = self.unpack_uint() - return (fileid, name, cookie) - - def unpack_diropres(self): - status = self.unpack_enum() - if status == NFS_OK: - fh = self.unpack_fhandle() - fa = self.unpack_fattr() - rest = (fh, fa) - else: - rest = None - return (status, rest) - - def unpack_attrstat(self): - status = self.unpack_enum() - if status == NFS_OK: - attributes = self.unpack_fattr() - else: - attributes = None - return status, attributes - - def unpack_fattr(self): - type = self.unpack_enum() - mode = self.unpack_uint() - nlink = self.unpack_uint() - uid = self.unpack_uint() - gid = self.unpack_uint() - size = self.unpack_uint() - blocksize = self.unpack_uint() - rdev = self.unpack_uint() - blocks = self.unpack_uint() - fsid = self.unpack_uint() - fileid = self.unpack_uint() - atime = self.unpack_timeval() - mtime = self.unpack_timeval() - ctime = self.unpack_timeval() - return (type, mode, nlink, uid, gid, size, blocksize, \ - rdev, blocks, fsid, fileid, atime, mtime, ctime) - - def unpack_timeval(self): - secs = self.unpack_uint() - usecs = self.unpack_uint() - return (secs, usecs) - - -class NFSClient(UDPClient): - - def __init__(self, host): - UDPClient.__init__(self, host, NFS_PROGRAM, NFS_VERSION) - - def addpackers(self): - self.packer = NFSPacker() - self.unpacker = NFSUnpacker('') - - def mkcred(self): - if self.cred == None: - self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default() - return self.cred - - def Getattr(self, fh): - return self.make_call(1, fh, \ - self.packer.pack_fhandle, \ - self.unpacker.unpack_attrstat) - - def Setattr(self, sa): - return self.make_call(2, sa, \ - self.packer.pack_sattrargs, \ - self.unpacker.unpack_attrstat) - - # Root() is obsolete - - def Lookup(self, da): - return self.make_call(4, da, \ - self.packer.pack_diropargs, \ - self.unpacker.unpack_diropres) - - # ... - - def Readdir(self, ra): - return self.make_call(16, ra, \ - self.packer.pack_readdirargs, \ - self.unpacker.unpack_readdirres) - - # Shorthand to get the entire contents of a directory - def Listdir(self, dir): - list = [] - ra = (dir, 0, 2000) - while 1: - (status, rest) = self.Readdir(ra) - if status <> NFS_OK: - break - entries, eof = rest - last_cookie = None - for fileid, name, cookie in entries: - list.append(fileid, name) - last_cookie = cookie - if eof or last_cookie == None: - break - ra = (ra[0], last_cookie, ra[2]) - return list - - -def test(): - import sys - if sys.argv[1:]: host = sys.argv[1] - else: host = '' - if sys.argv[2:]: filesys = sys.argv[2] - else: filesys = None - from mountclient import UDPMountClient, TCPMountClient - mcl = TCPMountClient(host) - if filesys == None: - list = mcl.Export() - for item in list: - print item - return - sf = mcl.Mnt(filesys) - print sf - fh = sf[1] - if fh: - ncl = NFSClient(host) - as = ncl.Getattr(fh) - print as - list = ncl.Listdir(fh) - for item in list: print item - mcl.Umnt(filesys) diff --git a/Demo/rpc/rnusersclient.py b/Demo/rpc/rnusersclient.py deleted file mode 100644 index e9cad620fd..0000000000 --- a/Demo/rpc/rnusersclient.py +++ /dev/null @@ -1,98 +0,0 @@ -# Remote nusers client interface - -import rpc -from rpc import Packer, Unpacker, UDPClient, BroadcastUDPClient - - -class RnusersPacker(Packer): - def pack_utmp(self, ui): - ut_line, ut_name, ut_host, ut_time = utmp - self.pack_string(ut_line) - self.pack_string(ut_name) - self.pack_string(ut_host) - self.pack_int(ut_time) - def pack_utmpidle(self, ui): - ui_itmp, ui_idle = ui - self.pack_utmp(ui_utmp) - self.pack_uint(ui_idle) - def pack_utmpidlearr(self, list): - self.pack_array(list, self.pack_itmpidle) - - -class RnusersUnpacker(Unpacker): - def unpack_utmp(self): - ut_line = self.unpack_string() - ut_name = self.unpack_string() - ut_host = self.unpack_string() - ut_time = self.unpack_int() - return ut_line, ut_name, ut_host, ut_time - def unpack_utmpidle(self): - ui_utmp = self.unpack_utmp() - ui_idle = self.unpack_uint() - return ui_utmp, ui_idle - def unpack_utmpidlearr(self): - return self.unpack_array(self.unpack_utmpidle) - - -class PartialRnusersClient: - - def addpackers(self): - self.packer = RnusersPacker() - self.unpacker = RnusersUnpacker('') - - def Num(self): - return self.make_call(1, None, None, self.unpacker.unpack_int) - - def Names(self): - return self.make_call(2, None, \ - None, self.unpacker.unpack_utmpidlearr) - - def Allnames(self): - return self.make_call(3, None, \ - None, self.unpacker.unpack_utmpidlearr) - - -class RnusersClient(PartialRnusersClient, UDPClient): - - def __init__(self, host): - UDPClient.__init__(self, host, 100002, 2) - - -class BroadcastRnusersClient(PartialRnusersClient, BroadcastUDPClient): - - def __init__(self, bcastaddr): - BroadcastUDPClient.__init__(self, bcastaddr, 100002, 2) - - -def test(): - import sys - if not sys.argv[1:]: - testbcast() - return - else: - host = sys.argv[1] - c = RnusersClient(host) - list = c.Names() - for (line, name, host, time), idle in list: - line = strip0(line) - name = strip0(name) - host = strip0(host) - print `name`, `host`, `line`, time, idle - -def testbcast(): - c = BroadcastRnusersClient('') - def listit(list, fromaddr): - host, port = fromaddr - print host + '\t:', - for (line, name, host, time), idle in list: - print strip0(name), - print - c.set_reply_handler(listit) - all = c.Names() - print 'Total Count:', len(all) - -def strip0(s): - while s and s[-1] == '\0': s = s[:-1] - return s - -test() diff --git a/Demo/rpc/rpc.py b/Demo/rpc/rpc.py deleted file mode 100644 index 83cc954b3d..0000000000 --- a/Demo/rpc/rpc.py +++ /dev/null @@ -1,863 +0,0 @@ -# Sun RPC version 2 -- RFC1057. - -# XXX There should be separate exceptions for the various reasons why -# XXX an RPC can fail, rather than using RuntimeError for everything - -# XXX The UDP version of the protocol resends requests when it does -# XXX not receive a timely reply -- use only for idempotent calls! - -# XXX There is no provision for call timeout on TCP connections - -import xdr -import socket -import os - -RPCVERSION = 2 - -CALL = 0 -REPLY = 1 - -AUTH_NULL = 0 -AUTH_UNIX = 1 -AUTH_SHORT = 2 -AUTH_DES = 3 - -MSG_ACCEPTED = 0 -MSG_DENIED = 1 - -SUCCESS = 0 # RPC executed successfully -PROG_UNAVAIL = 1 # remote hasn't exported program -PROG_MISMATCH = 2 # remote can't support version # -PROC_UNAVAIL = 3 # program can't support procedure -GARBAGE_ARGS = 4 # procedure can't decode params - -RPC_MISMATCH = 0 # RPC version number != 2 -AUTH_ERROR = 1 # remote can't authenticate caller - -AUTH_BADCRED = 1 # bad credentials (seal broken) -AUTH_REJECTEDCRED = 2 # client must begin new session -AUTH_BADVERF = 3 # bad verifier (seal broken) -AUTH_REJECTEDVERF = 4 # verifier expired or replayed -AUTH_TOOWEAK = 5 # rejected for security reasons - - -class Packer(xdr.Packer): - - def pack_auth(self, auth): - flavor, stuff = auth - self.pack_enum(flavor) - self.pack_opaque(stuff) - - def pack_auth_unix(self, stamp, machinename, uid, gid, gids): - self.pack_uint(stamp) - self.pack_string(machinename) - self.pack_uint(uid) - self.pack_uint(gid) - self.pack_uint(len(gids)) - for i in gids: - self.pack_uint(i) - - def pack_callheader(self, xid, prog, vers, proc, cred, verf): - self.pack_uint(xid) - self.pack_enum(CALL) - self.pack_uint(RPCVERSION) - self.pack_uint(prog) - self.pack_uint(vers) - self.pack_uint(proc) - self.pack_auth(cred) - self.pack_auth(verf) - # Caller must add procedure-specific part of call - - def pack_replyheader(self, xid, verf): - self.pack_uint(xid) - self.pack_enum(REPLY) - self.pack_uint(MSG_ACCEPTED) - self.pack_auth(verf) - self.pack_enum(SUCCESS) - # Caller must add procedure-specific part of reply - - -# Exceptions -BadRPCFormat = 'rpc.BadRPCFormat' -BadRPCVersion = 'rpc.BadRPCVersion' -GarbageArgs = 'rpc.GarbageArgs' - -class Unpacker(xdr.Unpacker): - - def unpack_auth(self): - flavor = self.unpack_enum() - stuff = self.unpack_opaque() - return (flavor, stuff) - - def unpack_callheader(self): - xid = self.unpack_uint(xid) - temp = self.unpack_enum() - if temp <> CALL: - raise BadRPCFormat, 'no CALL but ' + `temp` - temp = self.unpack_uint() - if temp <> RPCVERSION: - raise BadRPCVerspion, 'bad RPC version ' + `temp` - prog = self.unpack_uint() - vers = self.unpack_uint() - proc = self.unpack_uint() - cred = self.unpack_auth() - verf = self.unpack_auth() - return xid, prog, vers, proc, cred, verf - # Caller must add procedure-specific part of call - - def unpack_replyheader(self): - xid = self.unpack_uint() - mtype = self.unpack_enum() - if mtype <> REPLY: - raise RuntimeError, 'no REPLY but ' + `mtype` - stat = self.unpack_enum() - if stat == MSG_DENIED: - stat = self.unpack_enum() - if stat == RPC_MISMATCH: - low = self.unpack_uint() - high = self.unpack_uint() - raise RuntimeError, \ - 'MSG_DENIED: RPC_MISMATCH: ' + `low, high` - if stat == AUTH_ERROR: - stat = self.unpack_uint() - raise RuntimeError, \ - 'MSG_DENIED: AUTH_ERROR: ' + `stat` - raise RuntimeError, 'MSG_DENIED: ' + `stat` - if stat <> MSG_ACCEPTED: - raise RuntimeError, \ - 'Neither MSG_DENIED nor MSG_ACCEPTED: ' + `stat` - verf = self.unpack_auth() - stat = self.unpack_enum() - if stat == PROG_UNAVAIL: - raise RuntimeError, 'call failed: PROG_UNAVAIL' - if stat == PROG_MISMATCH: - low = self.unpack_uint() - high = self.unpack_uint() - raise RuntimeError, \ - 'call failed: PROG_MISMATCH: ' + `low, high` - if stat == PROC_UNAVAIL: - raise RuntimeError, 'call failed: PROC_UNAVAIL' - if stat == GARBAGE_ARGS: - raise RuntimeError, 'call failed: GARBAGE_ARGS' - if stat <> SUCCESS: - raise RuntimeError, 'call failed: ' + `stat` - return xid, verf - # Caller must get procedure-specific part of reply - - -# Subroutines to create opaque authentication objects - -def make_auth_null(): - return '' - -def make_auth_unix(seed, host, uid, gid, groups): - p = Packer() - p.pack_auth_unix(seed, host, uid, gid, groups) - return p.get_buf() - -def make_auth_unix_default(): - try: - from os import getuid, getgid - uid = getuid() - gid = getgid() - except ImportError: - uid = gid = 0 - import time - return make_auth_unix(int(time.time()), \ - socket.gethostname(), uid, gid, []) - - -# Common base class for clients - -class Client: - - def __init__(self, host, prog, vers, port): - self.host = host - self.prog = prog - self.vers = vers - self.port = port - self.makesocket() # Assigns to self.sock - self.bindsocket() - self.connsocket() - self.lastxid = 0 # XXX should be more random? - self.addpackers() - self.cred = None - self.verf = None - - def close(self): - self.sock.close() - - def makesocket(self): - # This MUST be overridden - raise RuntimeError, 'makesocket not defined' - - def connsocket(self): - # Override this if you don't want/need a connection - self.sock.connect((self.host, self.port)) - - def bindsocket(self): - # Override this to bind to a different port (e.g. reserved) - self.sock.bind(('', 0)) - - def addpackers(self): - # Override this to use derived classes from Packer/Unpacker - self.packer = Packer() - self.unpacker = Unpacker('') - - def make_call(self, proc, args, pack_func, unpack_func): - # Don't normally override this (but see Broadcast) - if pack_func is None and args is not None: - raise TypeError, 'non-null args with null pack_func' - self.start_call(proc) - if pack_func: - pack_func(args) - self.do_call() - if unpack_func: - result = unpack_func() - else: - result = None - self.unpacker.done() - return result - - def start_call(self, proc): - # Don't override this - self.lastxid = xid = self.lastxid + 1 - cred = self.mkcred() - verf = self.mkverf() - p = self.packer - p.reset() - p.pack_callheader(xid, self.prog, self.vers, proc, cred, verf) - - def do_call(self): - # This MUST be overridden - raise RuntimeError, 'do_call not defined' - - def mkcred(self): - # Override this to use more powerful credentials - if self.cred == None: - self.cred = (AUTH_NULL, make_auth_null()) - return self.cred - - def mkverf(self): - # Override this to use a more powerful verifier - if self.verf == None: - self.verf = (AUTH_NULL, make_auth_null()) - return self.verf - - def call_0(self): # Procedure 0 is always like this - return self.make_call(0, None, None, None) - - -# Record-Marking standard support - -def sendfrag(sock, last, frag): - x = len(frag) - if last: x = x | 0x80000000L - header = (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \ - chr(int(x>>8 & 0xff)) + chr(int(x & 0xff))) - sock.send(header + frag) - -def sendrecord(sock, record): - sendfrag(sock, 1, record) - -def recvfrag(sock): - header = sock.recv(4) - if len(header) < 4: - raise EOFError - x = long(ord(header[0]))<<24 | ord(header[1])<<16 | \ - ord(header[2])<<8 | ord(header[3]) - last = ((x & 0x80000000) != 0) - n = int(x & 0x7fffffff) - frag = '' - while n > 0: - buf = sock.recv(n) - if not buf: raise EOFError - n = n - len(buf) - frag = frag + buf - return last, frag - -def recvrecord(sock): - record = '' - last = 0 - while not last: - last, frag = recvfrag(sock) - record = record + frag - return record - - -# Try to bind to a reserved port (must be root) - -last_resv_port_tried = None -def bindresvport(sock, host): - global last_resv_port_tried - FIRST, LAST = 600, 1024 # Range of ports to try - if last_resv_port_tried == None: - import os - last_resv_port_tried = FIRST + os.getpid() % (LAST-FIRST) - for i in range(last_resv_port_tried, LAST) + \ - range(FIRST, last_resv_port_tried): - last_resv_port_tried = i - try: - sock.bind((host, i)) - return last_resv_port_tried - except socket.error, (errno, msg): - if errno <> 114: - raise socket.error, (errno, msg) - raise RuntimeError, 'can\'t assign reserved port' - - -# Client using TCP to a specific port - -class RawTCPClient(Client): - - def makesocket(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - - def do_call(self): - call = self.packer.get_buf() - sendrecord(self.sock, call) - reply = recvrecord(self.sock) - u = self.unpacker - u.reset(reply) - xid, verf = u.unpack_replyheader() - if xid <> self.lastxid: - # Can't really happen since this is TCP... - raise RuntimeError, 'wrong xid in reply ' + `xid` + \ - ' instead of ' + `self.lastxid` - - -# Client using UDP to a specific port - -class RawUDPClient(Client): - - def makesocket(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - - def do_call(self): - call = self.packer.get_buf() - self.sock.send(call) - try: - from select import select - except ImportError: - print 'WARNING: select not found, RPC may hang' - select = None - BUFSIZE = 8192 # Max UDP buffer size - timeout = 1 - count = 5 - while 1: - r, w, x = [self.sock], [], [] - if select: - r, w, x = select(r, w, x, timeout) - if self.sock not in r: - count = count - 1 - if count < 0: raise RuntimeError, 'timeout' - if timeout < 25: timeout = timeout *2 -## print 'RESEND', timeout, count - self.sock.send(call) - continue - reply = self.sock.recv(BUFSIZE) - u = self.unpacker - u.reset(reply) - xid, verf = u.unpack_replyheader() - if xid <> self.lastxid: -## print 'BAD xid' - continue - break - - -# Client using UDP broadcast to a specific port - -class RawBroadcastUDPClient(RawUDPClient): - - def __init__(self, bcastaddr, prog, vers, port): - RawUDPClient.__init__(self, bcastaddr, prog, vers, port) - self.reply_handler = None - self.timeout = 30 - - def connsocket(self): - # Don't connect -- use sendto - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) - - def set_reply_handler(self, reply_handler): - self.reply_handler = reply_handler - - def set_timeout(self, timeout): - self.timeout = timeout # Use None for infinite timeout - - def make_call(self, proc, args, pack_func, unpack_func): - if pack_func is None and args is not None: - raise TypeError, 'non-null args with null pack_func' - self.start_call(proc) - if pack_func: - pack_func(args) - call = self.packer.get_buf() - self.sock.sendto(call, (self.host, self.port)) - try: - from select import select - except ImportError: - print 'WARNING: select not found, broadcast will hang' - select = None - BUFSIZE = 8192 # Max UDP buffer size (for reply) - replies = [] - if unpack_func is None: - def dummy(): pass - unpack_func = dummy - while 1: - r, w, x = [self.sock], [], [] - if select: - if self.timeout is None: - r, w, x = select(r, w, x) - else: - r, w, x = select(r, w, x, self.timeout) - if self.sock not in r: - break - reply, fromaddr = self.sock.recvfrom(BUFSIZE) - u = self.unpacker - u.reset(reply) - xid, verf = u.unpack_replyheader() - if xid <> self.lastxid: -## print 'BAD xid' - continue - reply = unpack_func() - self.unpacker.done() - replies.append((reply, fromaddr)) - if self.reply_handler: - self.reply_handler(reply, fromaddr) - return replies - - -# Port mapper interface - -# Program number, version and (fixed!) port number -PMAP_PROG = 100000 -PMAP_VERS = 2 -PMAP_PORT = 111 - -# Procedure numbers -PMAPPROC_NULL = 0 # (void) -> void -PMAPPROC_SET = 1 # (mapping) -> bool -PMAPPROC_UNSET = 2 # (mapping) -> bool -PMAPPROC_GETPORT = 3 # (mapping) -> unsigned int -PMAPPROC_DUMP = 4 # (void) -> pmaplist -PMAPPROC_CALLIT = 5 # (call_args) -> call_result - -# A mapping is (prog, vers, prot, port) and prot is one of: - -IPPROTO_TCP = 6 -IPPROTO_UDP = 17 - -# A pmaplist is a variable-length list of mappings, as follows: -# either (1, mapping, pmaplist) or (0). - -# A call_args is (prog, vers, proc, args) where args is opaque; -# a call_result is (port, res) where res is opaque. - - -class PortMapperPacker(Packer): - - def pack_mapping(self, mapping): - prog, vers, prot, port = mapping - self.pack_uint(prog) - self.pack_uint(vers) - self.pack_uint(prot) - self.pack_uint(port) - - def pack_pmaplist(self, list): - self.pack_list(list, self.pack_mapping) - - def pack_call_args(self, ca): - prog, vers, proc, args = ca - self.pack_uint(prog) - self.pack_uint(vers) - self.pack_uint(proc) - self.pack_opaque(args) - - -class PortMapperUnpacker(Unpacker): - - def unpack_mapping(self): - prog = self.unpack_uint() - vers = self.unpack_uint() - prot = self.unpack_uint() - port = self.unpack_uint() - return prog, vers, prot, port - - def unpack_pmaplist(self): - return self.unpack_list(self.unpack_mapping) - - def unpack_call_result(self): - port = self.unpack_uint() - res = self.unpack_opaque() - return port, res - - -class PartialPortMapperClient: - - def addpackers(self): - self.packer = PortMapperPacker() - self.unpacker = PortMapperUnpacker('') - - def Set(self, mapping): - return self.make_call(PMAPPROC_SET, mapping, \ - self.packer.pack_mapping, \ - self.unpacker.unpack_uint) - - def Unset(self, mapping): - return self.make_call(PMAPPROC_UNSET, mapping, \ - self.packer.pack_mapping, \ - self.unpacker.unpack_uint) - - def Getport(self, mapping): - return self.make_call(PMAPPROC_GETPORT, mapping, \ - self.packer.pack_mapping, \ - self.unpacker.unpack_uint) - - def Dump(self): - return self.make_call(PMAPPROC_DUMP, None, \ - None, \ - self.unpacker.unpack_pmaplist) - - def Callit(self, ca): - return self.make_call(PMAPPROC_CALLIT, ca, \ - self.packer.pack_call_args, \ - self.unpacker.unpack_call_result) - - -class TCPPortMapperClient(PartialPortMapperClient, RawTCPClient): - - def __init__(self, host): - RawTCPClient.__init__(self, \ - host, PMAP_PROG, PMAP_VERS, PMAP_PORT) - - -class UDPPortMapperClient(PartialPortMapperClient, RawUDPClient): - - def __init__(self, host): - RawUDPClient.__init__(self, \ - host, PMAP_PROG, PMAP_VERS, PMAP_PORT) - - -class BroadcastUDPPortMapperClient(PartialPortMapperClient, \ - RawBroadcastUDPClient): - - def __init__(self, bcastaddr): - RawBroadcastUDPClient.__init__(self, \ - bcastaddr, PMAP_PROG, PMAP_VERS, PMAP_PORT) - - -# Generic clients that find their server through the Port mapper - -class TCPClient(RawTCPClient): - - def __init__(self, host, prog, vers): - pmap = TCPPortMapperClient(host) - port = pmap.Getport((prog, vers, IPPROTO_TCP, 0)) - pmap.close() - if port == 0: - raise RuntimeError, 'program not registered' - RawTCPClient.__init__(self, host, prog, vers, port) - - -class UDPClient(RawUDPClient): - - def __init__(self, host, prog, vers): - pmap = UDPPortMapperClient(host) - port = pmap.Getport((prog, vers, IPPROTO_UDP, 0)) - pmap.close() - if port == 0: - raise RuntimeError, 'program not registered' - RawUDPClient.__init__(self, host, prog, vers, port) - - -class BroadcastUDPClient(Client): - - def __init__(self, bcastaddr, prog, vers): - self.pmap = BroadcastUDPPortMapperClient(bcastaddr) - self.pmap.set_reply_handler(self.my_reply_handler) - self.prog = prog - self.vers = vers - self.user_reply_handler = None - self.addpackers() - - def close(self): - self.pmap.close() - - def set_reply_handler(self, reply_handler): - self.user_reply_handler = reply_handler - - def set_timeout(self, timeout): - self.pmap.set_timeout(timeout) - - def my_reply_handler(self, reply, fromaddr): - port, res = reply - self.unpacker.reset(res) - result = self.unpack_func() - self.unpacker.done() - self.replies.append((result, fromaddr)) - if self.user_reply_handler is not None: - self.user_reply_handler(result, fromaddr) - - def make_call(self, proc, args, pack_func, unpack_func): - self.packer.reset() - if pack_func: - pack_func(args) - if unpack_func is None: - def dummy(): pass - self.unpack_func = dummy - else: - self.unpack_func = unpack_func - self.replies = [] - packed_args = self.packer.get_buf() - dummy_replies = self.pmap.Callit( \ - (self.prog, self.vers, proc, packed_args)) - return self.replies - - -# Server classes - -# These are not symmetric to the Client classes -# XXX No attempt is made to provide authorization hooks yet - -class Server: - - def __init__(self, host, prog, vers, port): - self.host = host # Should normally be '' for default interface - self.prog = prog - self.vers = vers - self.port = port # Should normally be 0 for random port - self.makesocket() # Assigns to self.sock and self.prot - self.bindsocket() - self.host, self.port = self.sock.getsockname() - self.addpackers() - - def register(self): - mapping = self.prog, self.vers, self.prot, self.port - p = TCPPortMapperClient(self.host) - if not p.Set(mapping): - raise RuntimeError, 'register failed' - - def unregister(self): - mapping = self.prog, self.vers, self.prot, self.port - p = TCPPortMapperClient(self.host) - if not p.Unset(mapping): - raise RuntimeError, 'unregister failed' - - def handle(self, call): - # Don't use unpack_header but parse the header piecewise - # XXX I have no idea if I am using the right error responses! - self.unpacker.reset(call) - self.packer.reset() - xid = self.unpacker.unpack_uint() - self.packer.pack_uint(xid) - temp = self.unpacker.unpack_enum() - if temp <> CALL: - return None # Not worthy of a reply - self.packer.pack_uint(REPLY) - temp = self.unpacker.unpack_uint() - if temp <> RPCVERSION: - self.packer.pack_uint(MSG_DENIED) - self.packer.pack_uint(RPC_MISMATCH) - self.packer.pack_uint(RPCVERSION) - self.packer.pack_uint(RPCVERSION) - return self.packer.get_buf() - self.packer.pack_uint(MSG_ACCEPTED) - self.packer.pack_auth((AUTH_NULL, make_auth_null())) - prog = self.unpacker.unpack_uint() - if prog <> self.prog: - self.packer.pack_uint(PROG_UNAVAIL) - return self.packer.get_buf() - vers = self.unpacker.unpack_uint() - if vers <> self.vers: - self.packer.pack_uint(PROG_MISMATCH) - self.packer.pack_uint(self.vers) - self.packer.pack_uint(self.vers) - return self.packer.get_buf() - proc = self.unpacker.unpack_uint() - methname = 'handle_' + `proc` - try: - meth = getattr(self, methname) - except AttributeError: - self.packer.pack_uint(PROC_UNAVAIL) - return self.packer.get_buf() - cred = self.unpacker.unpack_auth() - verf = self.unpacker.unpack_auth() - try: - meth() # Unpack args, call turn_around(), pack reply - except (EOFError, GarbageArgs): - # Too few or too many arguments - self.packer.reset() - self.packer.pack_uint(xid) - self.packer.pack_uint(REPLY) - self.packer.pack_uint(MSG_ACCEPTED) - self.packer.pack_auth((AUTH_NULL, make_auth_null())) - self.packer.pack_uint(GARBAGE_ARGS) - return self.packer.get_buf() - - def turn_around(self): - try: - self.unpacker.done() - except RuntimeError: - raise GarbageArgs - self.packer.pack_uint(SUCCESS) - - def handle_0(self): # Handle NULL message - self.turn_around() - - def makesocket(self): - # This MUST be overridden - raise RuntimeError, 'makesocket not defined' - - def bindsocket(self): - # Override this to bind to a different port (e.g. reserved) - self.sock.bind((self.host, self.port)) - - def addpackers(self): - # Override this to use derived classes from Packer/Unpacker - self.packer = Packer() - self.unpacker = Unpacker('') - - -class TCPServer(Server): - - def makesocket(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.prot = IPPROTO_TCP - - def loop(self): - self.sock.listen(0) - while 1: - self.session(self.sock.accept()) - - def session(self, connection): - sock, (host, port) = connection - while 1: - try: - call = recvrecord(sock) - except EOFError: - break - except socket.error, msg: - print 'socket error:', msg - break - reply = self.handle(call) - if reply is not None: - sendrecord(sock, reply) - - def forkingloop(self): - # Like loop but uses forksession() - self.sock.listen(0) - while 1: - self.forksession(self.sock.accept()) - - def forksession(self, connection): - # Like session but forks off a subprocess - import os - # Wait for deceased children - try: - while 1: - pid, sts = os.waitpid(0, 1) - except os.error: - pass - pid = None - try: - pid = os.fork() - if pid: # Parent - connection[0].close() - return - # Child - self.session(connection) - finally: - # Make sure we don't fall through in the parent - if pid == 0: - os._exit(0) - - -class UDPServer(Server): - - def makesocket(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - self.prot = IPPROTO_UDP - - def loop(self): - while 1: - self.session() - - def session(self): - call, host_port = self.sock.recvfrom(8192) - reply = self.handle(call) - if reply <> None: - self.sock.sendto(reply, host_port) - - -# Simple test program -- dump local portmapper status - -def test(): - pmap = UDPPortMapperClient('') - list = pmap.Dump() - list.sort() - for prog, vers, prot, port in list: - print prog, vers, - if prot == IPPROTO_TCP: print 'tcp', - elif prot == IPPROTO_UDP: print 'udp', - else: print prot, - print port - - -# Test program for broadcast operation -- dump everybody's portmapper status - -def testbcast(): - import sys - if sys.argv[1:]: - bcastaddr = sys.argv[1] - else: - bcastaddr = '' - def rh(reply, fromaddr): - host, port = fromaddr - print host + '\t' + `reply` - pmap = BroadcastUDPPortMapperClient(bcastaddr) - pmap.set_reply_handler(rh) - pmap.set_timeout(5) - replies = pmap.Getport((100002, 1, IPPROTO_UDP, 0)) - - -# Test program for server, with corresponding client -# On machine A: python -c 'import rpc; rpc.testsvr()' -# On machine B: python -c 'import rpc; rpc.testclt()' A -# (A may be == B) - -def testsvr(): - # Simple test class -- proc 1 doubles its string argument as reply - class S(UDPServer): - def handle_1(self): - arg = self.unpacker.unpack_string() - self.turn_around() - print 'RPC function 1 called, arg', `arg` - self.packer.pack_string(arg + arg) - # - s = S('', 0x20000000, 1, 0) - try: - s.unregister() - except RuntimeError, msg: - print 'RuntimeError:', msg, '(ignored)' - s.register() - print 'Service started...' - try: - s.loop() - finally: - s.unregister() - print 'Service interrupted.' - - -def testclt(): - import sys - if sys.argv[1:]: host = sys.argv[1] - else: host = '' - # Client for above server - class C(UDPClient): - def call_1(self, arg): - return self.make_call(1, arg, \ - self.packer.pack_string, \ - self.unpacker.unpack_string) - c = C(host, 0x20000000, 1) - print 'making call...' - reply = c.call_1('hello, world, ') - print 'call returned', `reply` diff --git a/Demo/rpc/test b/Demo/rpc/test deleted file mode 100755 index ba220f24a2..0000000000 --- a/Demo/rpc/test +++ /dev/null @@ -1,24 +0,0 @@ -: ${PYTHON=python} -: ${SERVER=charon.cwi.nl} - -set -xe - -$PYTHON -c 'from rpc import test; test()' -$PYTHON -c 'from rpc import test; test()' ${SERVER} - -$PYTHON -c 'from rpc import testsvr; testsvr()' & -PID=$! -sleep 2 -$PYTHON -c 'from rpc import testclt; testclt()' -kill -2 $PID - -$PYTHON -c 'from mountclient import test; test()' -$PYTHON -c 'from mountclient import test; test()' gatekeeper.dec.com - -$PYTHON -c 'from nfsclient import test; test()' -$PYTHON -c 'from nfsclient import test; test()' gatekeeper.dec.com -$PYTHON -c 'from nfsclient import test; test()' gatekeeper.dec.com /archive - -$PYTHON -c 'from rnusersclient import test; test()' '' - -$PYTHON -c 'from rpc import testbcast; testbcast()' diff --git a/Demo/rpc/xdr.py b/Demo/rpc/xdr.py deleted file mode 100644 index 43abcee5a4..0000000000 --- a/Demo/rpc/xdr.py +++ /dev/null @@ -1,201 +0,0 @@ -# Implement (a subset of) Sun XDR -- RFC1014. - - -try: - import struct -except ImportError: - struct = None - - -Long = type(0L) - - -class Packer: - - def __init__(self): - self.reset() - - def reset(self): - self.buf = '' - - def get_buf(self): - return self.buf - - def pack_uint(self, x): - self.buf = self.buf + \ - (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \ - chr(int(x>>8 & 0xff)) + chr(int(x & 0xff))) - if struct and struct.pack('l', 1) == '\0\0\0\1': - def pack_uint(self, x): - if type(x) == Long: - x = int((x + 0x80000000L) % 0x100000000L \ - - 0x80000000L) - self.buf = self.buf + struct.pack('l', x) - - pack_int = pack_uint - - pack_enum = pack_int - - def pack_bool(self, x): - if x: self.buf = self.buf + '\0\0\0\1' - else: self.buf = self.buf + '\0\0\0\0' - - def pack_uhyper(self, x): - self.pack_uint(int(x>>32 & 0xffffffff)) - self.pack_uint(int(x & 0xffffffff)) - - pack_hyper = pack_uhyper - - def pack_float(self, x): - # XXX - self.buf = self.buf + struct.pack('f', x) - - def pack_double(self, x): - # XXX - self.buf = self.buf + struct.pack('d', x) - - def pack_fstring(self, n, s): - if n < 0: - raise ValueError, 'fstring size must be nonnegative' - n = ((n+3)/4)*4 - data = s[:n] - data = data + (n - len(data)) * '\0' - self.buf = self.buf + data - - pack_fopaque = pack_fstring - - def pack_string(self, s): - n = len(s) - self.pack_uint(n) - self.pack_fstring(n, s) - - pack_opaque = pack_string - - def pack_list(self, list, pack_item): - for item in list: - self.pack_uint(1) - pack_item(item) - self.pack_uint(0) - - def pack_farray(self, n, list, pack_item): - if len(list) <> n: - raise ValueError, 'wrong array size' - for item in list: - pack_item(item) - - def pack_array(self, list, pack_item): - n = len(list) - self.pack_uint(n) - self.pack_farray(n, list, pack_item) - - -class Unpacker: - - def __init__(self, data): - self.reset(data) - - def reset(self, data): - self.buf = data - self.pos = 0 - - def done(self): - if self.pos < len(self.buf): - raise RuntimeError, 'unextracted data remains' - - def unpack_uint(self): - i = self.pos - self.pos = j = i+4 - data = self.buf[i:j] - if len(data) < 4: - raise EOFError - x = long(ord(data[0]))<<24 | ord(data[1])<<16 | \ - ord(data[2])<<8 | ord(data[3]) - # Return a Python long only if the value is not representable - # as a nonnegative Python int - if x < 0x80000000L: x = int(x) - return x - if struct and struct.unpack('l', '\0\0\0\1') == 1: - def unpack_uint(self): - i = self.pos - self.pos = j = i+4 - data = self.buf[i:j] - if len(data) < 4: - raise EOFError - return struct.unpack('l', data) - - def unpack_int(self): - x = self.unpack_uint() - if x >= 0x80000000L: x = x - 0x100000000L - return int(x) - - unpack_enum = unpack_int - - unpack_bool = unpack_int - - def unpack_uhyper(self): - hi = self.unpack_uint() - lo = self.unpack_uint() - return long(hi)<<32 | lo - - def unpack_hyper(self): - x = self.unpack_uhyper() - if x >= 0x8000000000000000L: x = x - 0x10000000000000000L - return x - - def unpack_float(self): - # XXX - i = self.pos - self.pos = j = i+4 - data = self.buf[i:j] - if len(data) < 4: - raise EOFError - return struct.unpack('f', data)[0] - - def unpack_double(self): - # XXX - i = self.pos - self.pos = j = i+8 - data = self.buf[i:j] - if len(data) < 8: - raise EOFError - return struct.unpack('8', data)[0] - - def unpack_fstring(self, n): - if n < 0: - raise ValueError, 'fstring size must be nonnegative' - i = self.pos - j = i + (n+3)/4*4 - if j > len(self.buf): - raise EOFError - self.pos = j - return self.buf[i:i+n] - - unpack_fopaque = unpack_fstring - - def unpack_string(self): - n = self.unpack_uint() - return self.unpack_fstring(n) - - unpack_opaque = unpack_string - - def unpack_list(self, unpack_item): - list = [] - while 1: - x = self.unpack_uint() - if x == 0: break - if x <> 1: - raise RuntimeError, \ - '0 or 1 expected, got ' + `x` - item = unpack_item() - list.append(item) - return list - - def unpack_farray(self, n, unpack_item): - list = [] - for i in range(n): - list.append(unpack_item()) - return list - - def unpack_array(self, unpack_item): - n = self.unpack_uint() - return self.unpack_farray(n, unpack_item) diff --git a/Demo/scripts/README b/Demo/scripts/README deleted file mode 100644 index 6bc66b6eda..0000000000 --- a/Demo/scripts/README +++ /dev/null @@ -1,18 +0,0 @@ -This directory contains a collection of executable Python scripts. - -See also the Tools/scripts directory! - -fact.py Factorize numbers -from.py Summarize mailbox -ftpstats.py Summarize ftp daemon log file -lpwatch.py Watch BSD line printer queues -markov.py Markov chain simulation of words or characters -mboxconvvert.py Convert MH or MMDF mailboxes to unix mailbox format -morse.py Produce morse code (audible or on AIFF file) -mpzpi.py test mpz -- print digits of pi (compare pi.py) -pi.py Print all digits of pi -- given enough time and memory -pp.py Emulate some Perl command line options -primes.py Print prime numbers -script.py Equivalent to BSD script(1) -- by Steen Lumholt -unbirthday.py Print unbirthday count -update.py Update a bunch of files according to a script. diff --git a/Demo/scripts/eqfix.py b/Demo/scripts/eqfix.py deleted file mode 100755 index 794221af10..0000000000 --- a/Demo/scripts/eqfix.py +++ /dev/null @@ -1,199 +0,0 @@ -#! /usr/local/bin/python - -# Fix Python source files to use the new equality test operator, i.e., -# if x = y: ... -# is changed to -# if x == y: ... -# The script correctly tokenizes the Python program to reliably -# distinguish between assignments and equality tests. -# -# 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 regex -import os -from stat import * -import string - -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 = regex.compile('^[a-zA-Z0-9_]+\.py$') -def ispython(name): - return ispythonprog.match(name) >= 0 - -def recursedown(dirname): - dbg('recursedown(' + `dirname` + ')\n') - bad = 0 - try: - names = os.listdir(dirname) - except os.error, msg: - err(dirname + ': cannot list directory: ' + `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 ispython(name): - if fix(fullname): bad = 1 - for fullname in subdirs: - if recursedown(fullname): bad = 1 - return bad - -def fix(filename): -## dbg('fix(' + `filename` + ')\n') - try: - f = open(filename, 'r') - except IOError, msg: - err(filename + ': cannot open: ' + `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 - 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 = string.split(line[2:]) - if words and regex.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(tempname+': cannot create: '+\ - `msg`+'\n') - return 1 - f.seek(0) - lineno = 0 - rep(filename + ':\n') - continue # restart from the beginning - rep(`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(tempname + ': warning: chmod failed (' + `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 (' + `msg` + ')\n') - # Now move the temp file to the original file - try: - os.rename(tempname, filename) - except os.error, msg: - err(filename + ': rename failed (' + `msg` + ')\n') - return 1 - # Return succes - return 0 - - -from tokenize import tokenprog - -match = {'if':':', 'elif':':', 'while':':', 'return':'\n', \ - '(':')', '[':']', '{':'}', '`':'`'} - -def fixline(line): - # Quick check for easy case - if '=' not in line: return line - - i, n = 0, len(line) - stack = [] - while i < n: - j = tokenprog.match(line, i) - if j < 0: - # A bad token; forget about the rest of this line - print '(Syntax error:)' - print line, - return line - a, b = tokenprog.regs[3] # Location of the token proper - token = line[a:b] - i = i+j - if stack and token == stack[-1]: - del stack[-1] - elif match.has_key(token): - stack.append(match[token]) - elif token == '=' and stack: - line = line[:a] + '==' + line[b:] - i, n = a + len('=='), len(line) - elif token == '==' and not stack: - print '(Warning: \'==\' at top level:)' - print line, - return line - - -main() diff --git a/Demo/scripts/fact.py b/Demo/scripts/fact.py deleted file mode 100755 index bf49afcc44..0000000000 --- a/Demo/scripts/fact.py +++ /dev/null @@ -1,48 +0,0 @@ -#! /usr/local/bin/python - -# Factorize numbers. -# The algorithm is not efficient, but easy to understand. -# If there are large factors, it will take forever to find them, -# because we try all odd numbers between 3 and sqrt(n)... - -import sys -from math import sqrt - -error = 'fact.error' # exception - -def fact(n): - if n < 1: raise error # fact() argument should be >= 1 - if n == 1: return [] # special case - res = [] - # Treat even factors special, so we can use i = i+2 later - while n%2 == 0: - res.append(2) - n = n/2 - # Try odd numbers up to sqrt(n) - limit = sqrt(float(n+1)) - i = 3 - while i <= limit: - if n%i == 0: - res.append(i) - n = n/i - limit = sqrt(n+1) - else: - i = i+2 - if n != 1: - res.append(n) - return res - -def main(): - if len(sys.argv) > 1: - for arg in sys.argv[1:]: - n = eval(arg) - print n, fact(n) - else: - try: - while 1: - n = input() - print n, fact(n) - except EOFError: - pass - -main() diff --git a/Demo/scripts/freeze.py b/Demo/scripts/freeze.py deleted file mode 100755 index be6d263584..0000000000 --- a/Demo/scripts/freeze.py +++ /dev/null @@ -1,480 +0,0 @@ -#! /usr/local/bin/python - -# Given a Python script, create a binary that runs the script. -# The binary is 100% independent of Python libraries and binaries. -# It will not contain any Python source code -- only "compiled" Python -# (as initialized static variables containing marshalled code objects). -# It even does the right thing for dynamically loaded modules! -# The module search path of the binary is set to the current directory. -# -# Some problems remain: -# - It's highly non-portable, since it knows about paths and libraries -# (there's a customization section though, and it knows how to -# distinguish an SGI from a Sun SPARC system -- adding knowledge -# about more systems is left as an exercise for the reader). -# - You need to have the Python source tree lying around as well as -# the "libpython.a" used to generate the Python binary. -# - For scripts that use many modules it generates absurdly large -# files (frozen.c and config.o as well as the final binary), -# and is consequently rather slow. -# -# Caveats: -# - The search for modules sometimes finds modules that are never -# actually imported since the code importing them is never executed. -# - If an imported module isn't found, you get a warning but the -# process of freezing continues. The binary will fail if it -# actually tries to import one of these modules. -# - This often happens with the module 'mac', which module 'os' tries -# to import (to determine whether it is running on a Macintosh). -# You can ignore the warning about this. -# - If the program dynamically reads or generates Python code and -# executes it, this code may reference built-in or library modules -# that aren't present in the frozen binary, and this will fail. -# - Your program may be using external data files, e.g. compiled -# forms definitions (*.fd). These aren't incorporated. Since -# sys.path in the resulting binary only contains '.', if your -# program searches its data files along sys.path (as the 'flp' -# modules does to find its forms definitions), you may need to -# change the program to extend the search path or instruct its users -# to set the environment variable PYTHONPATH to point to your data -# files. -# -# Usage hints: -# - If you have a bunch of scripts that you want to freeze, instead -# of freezing each of them separately, you might consider writing -# a tiny main script that looks at sys.argv[0] and then imports -# the corresponding module. You can then make links to the -# frozen binary named after the various scripts you support. -# Pass the additional scripts as arguments after the main script. -# A minimal script to do this is the following. -# import sys, posixpath -# exec('import ' + posixpath.basename(sys.argv[0]) + '\n') - - -import os -import sys -import regex -import getopt -import regsub -import string -import marshal - -# Function to join two pathnames with a slash in between -j = os.path.join - -################################## -# START OF CONFIGURATION SECTION # -################################## - -# Attempt to guess machine architecture -if os.path.exists('/usr/lib/libgl_s'): ARCH = 'sgi' -elif os.path.exists('/etc/issue'): ARCH = 'sequent' -else: ARCH = 'sun4' - -# Site parametrizations (change to match your site) -CC = 'cc' # C compiler -TOP = '/ufs/guido/src' # Parent of all source trees -PYTHON = j(TOP, 'python') # Top of the Python source tree -SRC = j(PYTHON, 'src') # Python source directory -BLD = j(PYTHON, 'build.' + ARCH) # Python build directory -#BLD = SRC # Use this if you build in SRC - -LIBINST = '/ufs/guido/src/python/irix4/tmp/lib/python/lib' # installed libraries -INCLINST = '/ufs/guido/src/python/irix4/tmp/include/Py' # installed include files - -# Other packages (change to match your site) -DL = j(TOP, 'dl') # Top of the dl source tree -DL_DLD = j(TOP, 'dl-dld') # The dl-dld source directory -DLD = j(TOP, 'dld-3.2.3') # The dld source directory -FORMS = j(TOP, 'forms') # Top of the FORMS source tree -STDWIN = j(TOP, 'stdwin') # Top of the STDWIN source tree -READLINE = j(TOP, 'readline.' + ARCH) # Top of the GNU Readline source tree -SUN_X11 = '/usr/local/X11R5/lib/libX11.a' - -# File names (usually no need to change) -LIBP = [ # Main Python libraries - j(LIBINST, 'libPython.a'), - j(LIBINST, 'libParser.a'), - j(LIBINST, 'libObjects.a'), - j(LIBINST, 'libModules.a') - ] -CONFIG_IN = j(LIBINST, 'config.c.in') # Configuration source file -FMAIN = j(LIBINST, 'frozenmain.c') # Special main source file - -# Libraries needed when linking. First tuple item is built-in module -# for which it is needed (or '*' for always), rest are ld arguments. -# There is a separate list per architecture. -libdeps_sgi = [ \ - ('stdwin', j(STDWIN, 'Build/' + ARCH + '/x11/lib/lib.a')), \ - ('fl', j(FORMS, 'FORMS/libforms.a'), '-lfm_s'), \ - ('*', j(READLINE, 'libreadline.a'), '-ltermcap'), \ - ('al', '-laudio'), \ - ('sv', '-lsvideo', '-lXext'), \ - ('cd', '-lcdaudio', '-lds'), \ - ('cl', '-lcl'), \ - ('imgfile', '-limage', '-lgutil', '-lm'), \ - ('mpz', '/ufs/guido/src/gmp/libgmp.a'), \ - ('*', '-lsun'), \ - ('*', j(DL, 'libdl.a'), '-lmld'), \ - ('*', '-lmpc'), \ - ('fm', '-lfm_s'), \ - ('gl', '-lgl_s', '-lX11_s'), \ - ('stdwin', '-lX11_s'), \ - ('*', '-lm'), \ - ('*', '-lc_s'), \ - ] -libdeps_sun4 = [ \ - ('*', '-Bstatic'), \ - ('stdwin', j(STDWIN, 'Build/' + ARCH + '/x11/lib/lib.a')), \ - ('*', j(READLINE, 'libreadline.a')), \ - ('*', '-lm'), \ - ('*', j(DL_DLD,'libdl.a'), j(DLD,'libdld.a')), \ - ('*', SUN_X11), \ - ('*', '-ltermcap'), \ - ('*', '-lc'), \ - ] -libdeps_sequent = [ \ - ('*', j(LIBINST, 'libreadline.a'), '-ltermcap'), \ - ('*', '-lsocket'), \ - ('*', '-linet'), \ - ('*', '-lnsl'), \ - ('*', '-lm'), \ - ('*', '-lc'), \ - ] -libdeps = eval('libdeps_' + ARCH) - -################################ -# END OF CONFIGURATION SECTION # -################################ - -# Exception used when scanfile fails -NoSuchFile = 'NoSuchFile' - -# Global options -quiet = 0 # -q -verbose = 0 # -v -noexec = 0 # -n -nowrite = 0 # -N -ofile = 'a.out' # -o file - -# Main program -- argument parsing etc. -def main(): - global quiet, verbose, noexec, nowrite, ofile - try: - opts, args = getopt.getopt(sys.argv[1:], 'nNo:qv') - except getopt.error, msg: - usage(str(msg)) - sys.exit(2) - for o, a in opts: - if o == '-n': noexec = 1 - if o == '-N': nowrite = 1 - if o == '-o': ofile = a - if o == '-q': verbose = 0; quiet = 1 - if o == '-v': verbose = verbose + 1; quiet = 0 - if len(args) < 1: - usage('please pass at least one file argument') - sys.exit(2) - process(args[0], args[1:]) - -# Print usage message to stderr -def usage(*msgs): - sys.stdout = sys.stderr - for msg in msgs: print msg - print 'Usage: freeze [options] scriptfile [modulefile ...]' - print '-n : generate the files but don\'t compile and link' - print '-N : don\'t write frozen.c (do compile unless -n given)' - print '-o file : binary output file (default a.out)' - print '-q : quiet (no messages at all except errors)' - print '-v : verbose (lots of extra messages)' - -# Process the script file -def process(filename, addmodules): - global noexec - # - if not quiet: print 'Computing needed modules ...' - todo = {} - todo['__main__'] = filename - for name in addmodules: - mod = os.path.basename(name) - if mod[-3:] == '.py': mod = mod[:-3] - todo[mod] = name - try: - dict = closure(todo) - except NoSuchFile, filename: - sys.stderr.write('Can\'t open file %s\n' % filename) - sys.exit(1) - # - mods = dict.keys() - mods.sort() - # - if verbose: - print '%-15s %s' % ('Module', 'Filename') - for mod in mods: - print '%-15s %s' % (`mod`, dict[mod]) - # - if not quiet: print 'Looking for dynamically linked modules ...' - dlmodules = [] - objs = [] - libs = [] - for mod in mods: - if dict[mod][-2:] == '.o': - if verbose: print 'Found', mod, dict[mod] - dlmodules.append(mod) - objs.append(dict[mod]) - libsname = dict[mod][:-2] + '.libs' - try: - f = open(libsname, 'r') - except IOError: - f = None - if f: - libtext = f.read() - f.close() - for lib in string.split(libtext): - if lib in libs: libs.remove(lib) - libs.append(lib) - # - if not nowrite: - if not quiet: print 'Writing frozen.c ...' - writefrozen('frozen.c', dict) - else: - if not quiet: print 'NOT writing frozen.c ...' - # -## if not dlmodules: - if 0: - config = CONFIG - if not quiet: print 'Using existing', config, '...' - else: - config = 'tmpconfig.c' - if nowrite: - if not quiet: print 'NOT writing config.c ...' - else: - if not quiet: - print 'Writing config.c with dl modules ...' - f = open(CONFIG_IN, 'r') - g = open(config, 'w') - m1 = regex.compile('-- ADDMODULE MARKER 1 --') - m2 = regex.compile('-- ADDMODULE MARKER 2 --') - builtinmodules = [] - stdmodules = ('sys', '__main__', '__builtin__', - 'marshal') - todomodules = builtinmodules + dlmodules - for mod in dict.keys(): - if dict[mod] == '' and \ - mod not in stdmodules: - builtinmodules.append(mod) - while 1: - line = f.readline() - if not line: break - g.write(line) - if m1.search(line) >= 0: - if verbose: print 'Marker 1 ...' - for mod in todomodules: - g.write('extern void init' + \ - mod + '();\n') - if m2.search(line) >= 0: - if verbose: print 'Marker 2 ...' - for mod in todomodules: - g.write('{"' + mod + \ - '", init' + mod + '},\n') - g.close() - # - if not quiet: - if noexec: print 'Generating compilation commands ...' - else: print 'Starting compilation ...' - defs = ['-DNO_MAIN', '-DUSE_FROZEN', '-DPYTHONPATH=\'"."\''] - # - incs = ['-I.', '-I' + INCLINST] - if dict.has_key('stdwin'): - incs.append('-I' + j(STDWIN, 'H')) - # - srcs = [config, FMAIN] - # - if type(LIBP) == type(''): - libs.append(LIBP) - else: - for lib in LIBP: - libs.append(lib) - for item in libdeps: - m = item[0] - if m == '*' or dict.has_key(m): - for l in item[1:]: - if l in libs: libs.remove(l) - libs.append(l) - # - sts = 0 - # - cmd = CC + ' -c' - cmd = cmd + ' ' + string.join(defs) - cmd = cmd + ' ' + string.join(incs) - cmd = cmd + ' ' + string.join(srcs) - print cmd - # - if not noexec: - sts = os.system(cmd) - if sts: - print 'Exit status', sts, '-- turning on -n' - noexec = 1 - # - for s in srcs: - s = os.path.basename(s) - if s[-2:] == '.c': s = s[:-2] - o = s + '.o' - objs.insert(0, o) - # - cmd = CC - cmd = cmd + ' ' + string.join(objs) - cmd = cmd + ' ' + string.join(libs) - cmd = cmd + ' -o ' + ofile - print cmd - # - if not noexec: - sts = os.system(cmd) - if sts: - print 'Exit status', sts - else: - print 'Done.' - # - if not quiet and not noexec and sts == 0: - print 'Note: consider this:'; print '\tstrip', ofile - # - sys.exit(sts) - - -# Generate code for a given module -def makecode(filename): - if filename[-2:] == '.o': - return None - try: - f = open(filename, 'r') - except IOError: - return None - if verbose: print 'Making code from', filename, '...' - text = f.read() - code = compile(text, filename, 'exec') - f.close() - return marshal.dumps(code) - - -# Write the C source file containing the frozen Python code -def writefrozen(filename, dict): - f = open(filename, 'w') - codelist = [] - for mod in dict.keys(): - codestring = makecode(dict[mod]) - if codestring is not None: - codelist.append((mod, codestring)) - write = sys.stdout.write - save_stdout = sys.stdout - try: - sys.stdout = f - for mod, codestring in codelist: - if verbose: - write('Writing initializer for %s\n'%mod) - print 'static unsigned char M_' + mod + '[' + \ - str(len(codestring)) + '+1] = {' - for i in range(0, len(codestring), 16): - for c in codestring[i:i+16]: - print str(ord(c)) + ',', - print - print '};' - print 'struct frozen {' - print ' char *name;' - print ' unsigned char *code;' - print ' int size;' - print '} frozen_modules[] = {' - for mod, codestring in codelist: - print ' {"' + mod + '",', - print 'M_' + mod + ',', - print str(len(codestring)) + '},' - print ' {0, 0, 0} /* sentinel */' - print '};' - finally: - sys.stdout = save_stdout - f.close() - - -# Determine the names and filenames of the modules imported by the -# script, recursively. This is done by scanning for lines containing -# import statements. (The scanning has only superficial knowledge of -# Python syntax and no knowledge of semantics, so in theory the result -# may be incorrect -- however this is quite unlikely if you don't -# intentionally obscure your Python code.) - -# Compute the closure of scanfile() -- special first file because of script -def closure(todo): - done = {} - while todo: - newtodo = {} - for modname in todo.keys(): - if not done.has_key(modname): - filename = todo[modname] - if filename is None: - filename = findmodule(modname) - done[modname] = filename - if filename in ('', ''): - continue - modules = scanfile(filename) - for m in modules: - if not done.has_key(m): - newtodo[m] = None - todo = newtodo - return done - -# Scan a file looking for import statements -importstr = '\(^\|:\)[ \t]*import[ \t]+\([a-zA-Z0-9_, \t]+\)' -fromstr = '\(^\|:\)[ \t]*from[ \t]+\([a-zA-Z0-9_]+\)[ \t]+import[ \t]+' -isimport = regex.compile(importstr) -isfrom = regex.compile(fromstr) -def scanfile(filename): - allmodules = {} - try: - f = open(filename, 'r') - except IOError, msg: - raise NoSuchFile, filename - while 1: - line = f.readline() - if not line: break # EOF - while line[-2:] == '\\\n': # Continuation line - line = line[:-2] + ' ' - line = line + f.readline() - if isimport.search(line) >= 0: - rawmodules = isimport.group(2) - modules = string.splitfields(rawmodules, ',') - for i in range(len(modules)): - modules[i] = string.strip(modules[i]) - elif isfrom.search(line) >= 0: - modules = [isfrom.group(2)] - else: - continue - for mod in modules: - allmodules[mod] = None - f.close() - return allmodules.keys() - -# Find the file containing a module, given its name; None if not found -builtins = sys.builtin_module_names + ['sys'] -def findmodule(modname): - if modname in builtins: return '' - for dirname in sys.path: - dlfullname = os.path.join(dirname, modname + 'module.o') - try: - f = open(dlfullname, 'r') - except IOError: - f = None - if f: - f.close() - return dlfullname - fullname = os.path.join(dirname, modname + '.py') - try: - f = open(fullname, 'r') - except IOError: - continue - f.close() - return fullname - if not quiet: - sys.stderr.write('Warning: module %s not found\n' % modname) - return '' - - -# Call the main program -main() diff --git a/Demo/scripts/from.py b/Demo/scripts/from.py deleted file mode 100755 index 4c01b4c3a8..0000000000 --- a/Demo/scripts/from.py +++ /dev/null @@ -1,35 +0,0 @@ -#! /usr/local/bin/python - -# Print From and Subject of messages in $MAIL. -# Extension to multiple mailboxes and other bells & whistles are left -# as exercises for the reader. - -import sys, os - -# Open mailbox file. Exits with exception when this fails. - -try: - mailbox = os.environ['MAIL'] -except (AttributeError, KeyError): - sys.stderr.write('No environment variable $MAIL\n') - sys.exit(2) - -try: - mail = open(mailbox, 'r') -except IOError: - sys.stderr.write('Cannot open mailbox file: ' + mailbox + '\n') - sys.exit(2) - -while 1: - line = mail.readline() - if not line: break # EOF - if line[:5] == 'From ': - # Start of message found - print line[:-1], - while 1: - line = mail.readline() - if not line: break # EOF - if line == '\n': break # Blank line ends headers - if line[:8] == 'Subject:': - print `line[9:-1]`, - print diff --git a/Demo/scripts/ftpstats.py b/Demo/scripts/ftpstats.py deleted file mode 100755 index 9c643fe51e..0000000000 --- a/Demo/scripts/ftpstats.py +++ /dev/null @@ -1,143 +0,0 @@ -#! /usr/local/bin/python - -# Extract statistics from ftp daemon log. - -# Usage: -# ftpstats [-m maxitems] [-s search] [file] -# -m maxitems: restrict number of items in "top-N" lists, default 25. -# -s string: restrict statistics to lines containing this string. -# Default file is /usr/adm/ftpd; a "-" means read stdandard input. - -# The script must be run on the host where the ftp daemon runs. -# (At CWI this is currently buizerd.) - -import os -import sys -import regex -import string -import getopt - -pat = '^\([a-zA-Z0-9 :]*\)!\(.*\)!\(.*\)!\([<>].*\)!\([0-9]+\)!\([0-9]+\)$' -prog = regex.compile(pat) - -def main(): - maxitems = 25 - search = None - try: - opts, args = getopt.getopt(sys.argv[1:], 'm:s:') - except getopt.error, msg: - print msg - print 'usage: ftpstats [-m maxitems] [file]' - sys.exit(2) - for o, a in opts: - if o == '-m': - maxitems = string.atoi(a) - if o == '-s': - search = a - file = '/usr/adm/ftpd' - if args: file = args[0] - if file == '-': - f = sys.stdin - else: - try: - f = open(file, 'r') - except IOError, msg: - print file, ':', msg - sys.exit(1) - bydate = {} - bytime = {} - byfile = {} - bydir = {} - byhost = {} - byuser = {} - bytype = {} - lineno = 0 - try: - while 1: - line = f.readline() - if not line: break - lineno = lineno + 1 - if search and string.find(line, search) < 0: - continue - if prog.match(line) < 0: - print 'Bad line', lineno, ':', `line` - continue - items = prog.group(1, 2, 3, 4, 5, 6) - logtime, loguser, loghost, logfile, logbytes, logxxx2 = items -## print logtime -## print '-->', loguser -## print '--> -->', loghost -## print '--> --> -->', logfile -## print '--> --> --> -->', logbytes -## print '--> --> --> --> -->', logxxx2 -## for i in logtime, loghost, logbytes, logxxx2: -## if '!' in i: print '???', i - add(bydate, logtime[-4:] + ' ' + logtime[:6], items) - add(bytime, logtime[7:9] + ':00-59', items) - direction, logfile = logfile[0], logfile[1:] - # The real path probably starts at the last //... - while 1: - i = string.find(logfile, '//') - if i < 0: break - logfile = logfile[i+1:] - add(byfile, logfile + ' ' + direction, items) - logdir = os.path.dirname(logfile) -## logdir = os.path.normpath(logdir) + '/.' - while 1: - add(bydir, logdir + ' ' + direction, items) - dirhead = os.path.dirname(logdir) - if dirhead == logdir: break - logdir = dirhead - add(byhost, loghost, items) - add(byuser, loguser, items) - add(bytype, direction, items) - except KeyboardInterrupt: - print 'Interrupted at line', lineno - show(bytype, 'by transfer direction', maxitems) - show(bydir, 'by directory', maxitems) - show(byfile, 'by file', maxitems) - show(byhost, 'by host', maxitems) - show(byuser, 'by user', maxitems) - showbar(bydate, 'by date') - showbar(bytime, 'by time of day') - -def showbar(dict, title): - n = len(title) - print '='*((70-n)/2), title, '='*((71-n)/2) - list = [] - keys = dict.keys() - keys.sort() - for key in keys: - n = len(str(key)) - list.append((len(dict[key]), key)) - maxkeylength = 0 - maxcount = 0 - for count, key in list: - maxkeylength = max(maxkeylength, len(key)) - maxcount = max(maxcount, count) - maxbarlength = 72 - maxkeylength - 7 - for count, key in list: - barlength = int(round(maxbarlength*float(count)/maxcount)) - bar = '*'*barlength - print '%5d %-*s %s' % (count, maxkeylength, key, bar) - -def show(dict, title, maxitems): - if len(dict) > maxitems: - title = title + ' (first %d)'%maxitems - n = len(title) - print '='*((70-n)/2), title, '='*((71-n)/2) - list = [] - keys = dict.keys() - for key in keys: - list.append((-len(dict[key]), key)) - list.sort() - for count, key in list[:maxitems]: - print '%5d %s' % (-count, key) - -def add(dict, key, item): - if dict.has_key(key): - dict[key].append(item) - else: - dict[key] = [item] - -main() diff --git a/Demo/scripts/lpwatch.py b/Demo/scripts/lpwatch.py deleted file mode 100755 index af7d9144b0..0000000000 --- a/Demo/scripts/lpwatch.py +++ /dev/null @@ -1,109 +0,0 @@ -#! /usr/local/bin/python - -# Watch line printer queue(s). -# Intended for BSD 4.3 lpq. - -import posix -import sys -import time -import string - -DEF_PRINTER = 'psc' -DEF_DELAY = 10 - -def main(): - delay = DEF_DELAY # XXX Use getopt() later - try: - thisuser = posix.environ['LOGNAME'] - except: - thisuser = posix.environ['USER'] - printers = sys.argv[1:] - if printers: - # Strip '-P' from printer names just in case - # the user specified it... - for i in range(len(printers)): - if printers[i][:2] == '-P': - printers[i] = printers[i][2:] - else: - if posix.environ.has_key('PRINTER'): - printers = [posix.environ['PRINTER']] - else: - printers = [DEF_PRINTER] - # - clearhome = posix.popen('clear', 'r').read() - # - while 1: - text = clearhome - for name in printers: - text = text + makestatus(name, thisuser) + '\n' - print text - time.sleep(delay) - -def makestatus(name, thisuser): - pipe = posix.popen('lpq -P' + name + ' 2>&1', 'r') - lines = [] - users = {} - aheadbytes = 0 - aheadjobs = 0 - userseen = 0 - totalbytes = 0 - totaljobs = 0 - while 1: - line = pipe.readline() - if not line: break - fields = string.split(line) - n = len(fields) - if len(fields) >= 6 and fields[n-1] == 'bytes': - rank = fields[0] - user = fields[1] - job = fields[2] - files = fields[3:-2] - bytes = eval(fields[n-2]) - if user == thisuser: - userseen = 1 - elif not userseen: - aheadbytes = aheadbytes + bytes - aheadjobs = aheadjobs + 1 - totalbytes = totalbytes + bytes - totaljobs = totaljobs + 1 - if users.has_key(user): - ujobs, ubytes = users[user] - else: - ujobs, ubytes = 0, 0 - ujobs = ujobs + 1 - ubytes = ubytes + bytes - users[user] = ujobs, ubytes - else: - if fields and fields[0] <> 'Rank': - line = string.strip(line) - if line == 'no entries': - line = name + ': idle' - elif line[-22:] == ' is ready and printing': - line = name - lines.append(line) - # - if totaljobs: - line = `(totalbytes+1023)/1024` + ' K' - if totaljobs <> len(users): - line = line + ' (' + `totaljobs` + ' jobs)' - if len(users) == 1: - line = line + ' for ' + users.keys()[0] - else: - line = line + ' for ' + `len(users)` + ' users' - if userseen: - if aheadjobs == 0: - line = line + ' (' + thisuser + ' first)' - else: - line = line + ' (' + `(aheadbytes+1023)/1024` - line = line + ' K before ' + thisuser + ')' - lines.append(line) - # - sts = pipe.close() - if sts: - lines.append('lpq exit status ' + `sts`) - return string.joinfields(lines, ': ') - -try: - main() -except KeyboardInterrupt: - pass diff --git a/Demo/scripts/makedir.py b/Demo/scripts/makedir.py deleted file mode 100755 index 563c83fe4c..0000000000 --- a/Demo/scripts/makedir.py +++ /dev/null @@ -1,20 +0,0 @@ -#! /usr/local/bin/python - -# Like mkdir, but also make intermediate directories if necessary. -# It is not an error if the given directory already exists (as long -# as it is a directory). -# Errors are not treated specially -- you just get a Python exception. - -import sys, os - -def main(): - for p in sys.argv[1:]: - makedirs(p) - -def makedirs(p): - if not os.path.isdir(p): - head, tail = os.path.split(p) - makedirs(head) - os.mkdir(p, 0777) - -main() diff --git a/Demo/scripts/markov.py b/Demo/scripts/markov.py deleted file mode 100755 index 6a6d2b2c48..0000000000 --- a/Demo/scripts/markov.py +++ /dev/null @@ -1,116 +0,0 @@ -#! /usr/local/bin/python - -class Markov: - def __init__(self, histsize, choice): - self.histsize = histsize - self.choice = choice - self.trans = {} - def add(self, state, next): - if not self.trans.has_key(state): - self.trans[state] = [next] - else: - self.trans[state].append(next) - def put(self, seq): - n = self.histsize - add = self.add - add(None, seq[:0]) - for i in range(len(seq)): - add(seq[max(0, i-n):i], seq[i:i+1]) - add(seq[len(seq)-n:], None) - def get(self): - choice = self.choice - trans = self.trans - n = self.histsize - seq = choice(trans[None]) - while 1: - subseq = seq[max(0, len(seq)-n):] - options = trans[subseq] - next = choice(options) - if not next: break - seq = seq + next - return seq - -def test(): - import sys, string, whrandom, getopt - args = sys.argv[1:] - try: - opts, args = getopt.getopt(args, '0123456789cdw') - except getopt.error: - print 'Usage: markov [-#] [-cddqw] [file] ...' - print 'Options:' - print '-#: 1-digit history size (default 2)' - print '-c: characters (default)' - print '-w: words' - print '-d: more debugging output' - print '-q: no debugging output' - print 'Input files (default stdin) are split in paragraphs' - print 'separated blank lines and each paragraph is split' - print 'in words by whitespace, then reconcatenated with' - print 'exactly one space separating words.' - print 'Output consists of paragraphs separated by blank' - print 'lines, where lines are no longer than 72 characters.' - histsize = 2 - do_words = 0 - debug = 1 - for o, a in opts: - if '-0' <= o <= '-9': histsize = eval(o[1:]) - if o == '-c': do_words = 0 - if o == '-d': debug = debug + 1 - if o == '-q': debug = 0 - if o == '-w': do_words = 1 - if not args: args = ['-'] - m = Markov(histsize, whrandom.choice) - try: - for filename in args: - if filename == '-': - f = sys.stdin - if f.isatty(): - print 'Sorry, need stdin from file' - continue - else: - f = open(filename, 'r') - if debug: print 'processing', filename, '...' - text = f.read() - f.close() - paralist = string.splitfields(text, '\n\n') - for para in paralist: - if debug > 1: print 'feeding ...' - words = string.split(para) - if words: - if do_words: data = tuple(words) - else: data = string.joinfields(words, ' ') - m.put(data) - except KeyboardInterrupt: - print 'Interrupted -- continue with data read so far' - if not m.trans: - print 'No valid input files' - return - if debug: print 'done.' - if debug > 1: - for key in m.trans.keys(): - if key is None or len(key) < histsize: - print `key`, m.trans[key] - if histsize == 0: print `''`, m.trans[''] - print - while 1: - data = m.get() - if do_words: words = data - else: words = string.split(data) - n = 0 - limit = 72 - for w in words: - if n + len(w) > limit: - print - n = 0 - print w, - n = n + len(w) + 1 - print - print - -def tuple(list): - if len(list) == 0: return () - if len(list) == 1: return (list[0],) - i = len(list)/2 - return tuple(list[:i]) + tuple(list[i:]) - -test() diff --git a/Demo/scripts/mboxconvert.py b/Demo/scripts/mboxconvert.py deleted file mode 100755 index ecd6965de9..0000000000 --- a/Demo/scripts/mboxconvert.py +++ /dev/null @@ -1,123 +0,0 @@ -#! /usr/local/bin/python - -# Convert MH directories (1 message per file) or MMDF mailboxes (4x^A -# delimited) to unix mailbox (From ... delimited) on stdout. -# If -f is given, files contain one message per file (e.g. MH messages) - -import rfc822 -import sys -import time -import os -import stat -import getopt -import regex - -def main(): - dofile = mmdf - try: - opts, args = getopt.getopt(sys.argv[1:], 'f') - except getopt.error, msg: - sys.stderr.write('%s\n' % msg) - sys.exit(2) - for o, a in opts: - if o == '-f': - dofile = message - if not args: - args = ['-'] - sts = 0 - for arg in args: - if arg == '-' or arg == '': - sts = dofile(sys.stdin) or sts - elif os.path.isdir(arg): - sts = mh(arg) or sts - elif os.path.isfile(arg): - try: - f = open(arg) - except IOError, msg: - sys.stderr.write('%s: %s\n' % (arg, msg)) - sts = 1 - continue - sts = dofile(f) or sts - f.close() - else: - sys.stderr.write('%s: not found\n' % arg) - sts = 1 - if sts: - sys.exit(sts) - -numeric = regex.compile('[1-9][0-9]*') - -def mh(dir): - sts = 0 - msgs = os.listdir(dir) - for msg in msgs: - if numeric.match(msg) != len(msg): - continue - fn = os.path.join(dir, msg) - try: - f = open(fn) - except IOError, msg: - sys.stderr.write('%s: %s\n' % (fn, msg)) - sts = 1 - continue - sts = message(f) or sts - return sts - -def mmdf(f): - sts = 0 - while 1: - line = f.readline() - if not line: - break - if line == '\1\1\1\1\n': - sts = message(f, line) or sts - else: - sys.stderr.write( - 'Bad line in MMFD mailbox: %s\n' % `line`) - return sts - -counter = 0 # for generating unique Message-ID headers - -def message(f, delimiter = ''): - sts = 0 - # Parse RFC822 header - m = rfc822.Message(f) - # Write unix header line - fullname, email = m.getaddr('From') - tt = m.getdate('Date') - if tt: - t = time.mktime(tt) - else: - sys.stderr.write( - 'Unparseable date: %s\n' % `m.getheader('Date')`) - t = os.fstat(f.fileno())[stat.ST_MTIME] - print 'From', email, time.ctime(t) - # Copy RFC822 header - for line in m.headers: - print line, - # Invent Message-ID header if none is present - if not m.has_key('message-id'): - global counter - counter = counter + 1 - msgid = "<%s.%d>" % (hex(t), counter) - sys.stderr.write("Adding Message-ID %s (From %s)\n" % - (msgid, email)) - print "Message-ID:", msgid - print - # Copy body - while 1: - line = f.readline() - if line == delimiter: - break - if not line: - sys.stderr.write('Unexpected EOF in message\n') - sts = 1 - break - if line[:5] == 'From ': - line = '>' + line - print line, - # Print trailing newline - print - return sts - -main() diff --git a/Demo/scripts/mkrcs.py b/Demo/scripts/mkrcs.py deleted file mode 100755 index 2009f8c121..0000000000 --- a/Demo/scripts/mkrcs.py +++ /dev/null @@ -1,60 +0,0 @@ -#! /usr/local/bin/python - -# A rather specialized script to make sure that a symbolic link named -# RCS exists pointing to a real RCS directory in a parallel tree -# referenced as RCStree in an ancestor directory. -# (I use this because I like my RCS files to reside on a physically -# different machine). - -import os - -def main(): - rcstree = 'RCStree' - rcs = 'RCS' - if os.path.islink(rcs): - print `rcs`, 'is a symlink to', `os.readlink(rcs)` - return - if os.path.isdir(rcs): - print `rcs`, 'is an ordinary directory' - return - if os.path.exists(rcs): - print `rcs`, 'is a file?!?!' - return - # - p = os.getcwd() - up = '' - down = '' - # Invariants: - # (1) join(p, down) is the current directory - # (2) up is the same directory as p - # Ergo: - # (3) join(up, down) is the current directory - #print 'p =', `p` - while not os.path.isdir(os.path.join(p, rcstree)): - head, tail = os.path.split(p) - #print 'head =', `head`, '; tail =', `tail` - if not tail: - print 'Sorry, no ancestor dir contains', `rcstree` - return - p = head - up = os.path.join(os.pardir, up) - down = os.path.join(tail, down) - #print 'p =', `p`, '; up =', `up`, '; down =', `down` - there = os.path.join(up, rcstree) - there = os.path.join(there, down) - there = os.path.join(there, rcs) - if os.path.isdir(there): - print `there`, 'already exists' - else: - print 'making', `there` - makedirs(there) - print 'making symlink', `rcs`, '->', `there` - os.symlink(there, rcs) - -def makedirs(p): - if not os.path.isdir(p): - head, tail = os.path.split(p) - makedirs(head) - os.mkdir(p, 0777) - -main() diff --git a/Demo/scripts/morse.py b/Demo/scripts/morse.py deleted file mode 100755 index 2cea83e402..0000000000 --- a/Demo/scripts/morse.py +++ /dev/null @@ -1,149 +0,0 @@ -# DAH should be three DOTs. -# Space between DOTs and DAHs should be one DOT. -# Space between two letters should be one DAH. -# Space between two words should be DOT DAH DAH. - -import sys, math, audiodev - -DOT = 30 -DAH = 3 * DOT -OCTAVE = 2 # 1 == 441 Hz, 2 == 882 Hz, ... - -morsetab = { - 'A': '.-', 'a': '.-', - 'B': '-...', 'b': '-...', - 'C': '-.-.', 'c': '-.-.', - 'D': '-..', 'd': '-..', - 'E': '.', 'e': '.', - 'F': '..-.', 'f': '..-.', - 'G': '--.', 'g': '--.', - 'H': '....', 'h': '....', - 'I': '..', 'i': '..', - 'J': '.---', 'j': '.---', - 'K': '-.-', 'k': '-.-', - 'L': '.-..', 'l': '.-..', - 'M': '--', 'm': '--', - 'N': '-.', 'n': '-.', - 'O': '---', 'o': '---', - 'P': '.--.', 'p': '.--.', - 'Q': '--.-', 'q': '--.-', - 'R': '.-.', 'r': '.-.', - 'S': '...', 's': '...', - 'T': '-', 't': '-', - 'U': '..-', 'u': '..-', - 'V': '...-', 'v': '...-', - 'W': '.--', 'w': '.--', - 'X': '-..-', 'x': '-..-', - 'Y': '-.--', 'y': '-.--', - 'Z': '--..', 'z': '--..', - '0': '-----', - '1': '.----', - '2': '..---', - '3': '...--', - '4': '....-', - '5': '.....', - '6': '-....', - '7': '--...', - '8': '---..', - '9': '----.', - ',': '--..--', - '.': '.-.-.-', - '?': '..--..', - ';': '-.-.-.', - ':': '---...', - "'": '.----.', - '-': '-....-', - '/': '-..-.', - '(': '-.--.-', - ')': '-.--.-', - '_': '..--.-', - ' ': ' ' -} - -# If we play at 44.1 kHz (which we do), then if we produce one sine -# wave in 100 samples, we get a tone of 441 Hz. If we produce two -# sine waves in these 100 samples, we get a tone of 882 Hz. 882 Hz -# appears to be a nice one for playing morse code. -def mkwave(octave): - global sinewave, nowave - sinewave = '' - for i in range(100): - val = int(math.sin(math.pi * float(i) * octave / 50.0) * 30000) - sinewave = sinewave + chr((val >> 8) & 255) + chr(val & 255) - nowave = '\0' * 200 - -mkwave(OCTAVE) - -def main(): - import getopt, string - try: - opts, args = getopt.getopt(sys.argv[1:], 'o:p:') - except getopt.error: - sys.stderr.write('Usage ' + sys.argv[0] + - ' [ -o outfile ] [ args ] ...\n') - sys.exit(1) - dev = None - for o, a in opts: - if o == '-o': - import aifc - dev = aifc.open(a, 'w') - dev.setframerate(44100) - dev.setsampwidth(2) - dev.setnchannels(1) - if o == '-p': - mkwave(string.atoi(a)) - if not dev: - import audiodev - dev = audiodev.AudioDev() - dev.setoutrate(44100) - dev.setsampwidth(2) - dev.setnchannels(1) - dev.close = dev.stop - dev.writeframesraw = dev.writeframes - if args: - line = string.join(args) - else: - line = sys.stdin.readline() - while line: - mline = morse(line) - play(mline, dev) - if hasattr(dev, 'wait'): - dev.wait() - if not args: - line = sys.stdin.readline() - else: - line = '' - dev.close() - -# Convert a string to morse code with \001 between the characters in -# the string. -def morse(line): - res = '' - for c in line: - try: - res = res + morsetab[c] + '\001' - except KeyError: - pass - return res - -# Play a line of morse code. -def play(line, dev): - for c in line: - if c == '.': - sine(dev, DOT) - elif c == '-': - sine(dev, DAH) - else: # space - pause(dev, DAH + DOT) - pause(dev, DOT) - -def sine(dev, length): - for i in range(length): - dev.writeframesraw(sinewave) - -def pause(dev, length): - for i in range(length): - dev.writeframesraw(nowave) - -if __name__ == '__main__' or sys.argv[0] == __name__: - main() diff --git a/Demo/scripts/mpzpi.py b/Demo/scripts/mpzpi.py deleted file mode 100755 index 776c095e07..0000000000 --- a/Demo/scripts/mpzpi.py +++ /dev/null @@ -1,34 +0,0 @@ -#! /usr/local/bin/python -# Print digits of pi forever. -# -# The algorithm, using Python's 'long' integers ("bignums"), works -# with continued fractions, and was conceived by Lambert Meertens. -# -# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton, -# published by Prentice-Hall (UK) Ltd., 1990. - -import sys -from mpz import mpz - -def main(): - mpzone, mpztwo, mpzten = mpz(1), mpz(2), mpz(10) - k, a, b, a1, b1 = mpz(2), mpz(4), mpz(1), mpz(12), mpz(4) - while 1: - # Next approximation - p, q, k = k*k, mpztwo*k+mpzone, k+mpzone - a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 - # Print common digits - d, d1 = a/b, a1/b1 - while d == d1: - output(d) - a, a1 = mpzten*(a%b), mpzten*(a1%b1) - d, d1 = a/b, a1/b1 - -def output(d): - # Use write() to avoid spaces between the digits - # Use int(d) to avoid a trailing L after each digit - sys.stdout.write(`int(d)`) - # Flush so the output is seen immediately - sys.stdout.flush() - -main() diff --git a/Demo/scripts/newslist.doc b/Demo/scripts/newslist.doc deleted file mode 100755 index 87fd9ba27a..0000000000 --- a/Demo/scripts/newslist.doc +++ /dev/null @@ -1,59 +0,0 @@ - NEWSLIST - ======== - A program to assist HTTP browsing of newsgroups - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -WWW browsers such as NCSA Mosaic allow the user to read newsgroup -articles by specifying the group name in a URL eg 'news:comp.answers'. - -To browse through many groups, though, (and there are several thousand -of them) you really need a page or pages containing links to all the -groups. There are some good ones out there, for example, - - http://info.cern.ch/hypertext/DataSources/News/Groups/Overview.html - -is the standard one at CERN, but it only shows the groups available there, -which may be rather different from those available on your machine. - -Newslist is a program which creates a hierarchy of pages for you based -on the groups available from YOUR server. It is written in python - a -splendid interpreted object-oriented language which I suggest you get -right now from the directory /pub/python at ftp.cwi.nl, if you haven't -already got it. - -You should be able to see some sample output by looking at: - http://pelican.cl.cam.ac.uk/newspage/root.html - -Descriptions of newsgroups can be added from a file with one group -per line. eg: - - alt.foo Articles about foo - comp.bar Programming in 'bar' and related languages - -A suitable list detailing most groups can be found at ftp.uu.net in -/uunet-info/newsgroups.gz. - -Make sure you read the information at the beginning of the program source and -configure the variables before running. - -In addition to python, you need: - - An NNTP-based news feed. - A directory in which to put the pages. - -The programming is not very beautiful, but it works! It comes with no -warranty, express or implied, but with the hope that some others may -find it useful. - -Comments, improvements & suggestions welcomed. -Quentin Stafford-Fraser - - ---------------------------------------------------------------------- - Quentin Stafford-Fraser - http://pelican.cl.cam.ac.uk/people/qs101/me.html - - Cambridge University Computer Lab Rank Xerox Cambridge EuroPARC - qs101@cl.cam.ac.uk fraser@europarc.xerox.com - Tel: +44 223 334411 Tel: +44 223 341521 - Fax: +44 223 334679 Fax: +44 223 341510 - ---------------------------------------------------------------------- diff --git a/Demo/scripts/newslist.py b/Demo/scripts/newslist.py deleted file mode 100755 index 4c5376d48b..0000000000 --- a/Demo/scripts/newslist.py +++ /dev/null @@ -1,365 +0,0 @@ -#! /usr/local/bin/python -####################################################################### -# Newslist $Revision$ -# -# Syntax: -# newslist [ -a ] -# -# This is a program to create a directory full of HTML pages -# which between them contain links to all the newsgroups available -# on your server. -# -# The -a option causes a complete list of all groups to be read from -# the server rather than just the ones which have appeared since last -# execution. This recreates the local list from scratch. Use this on -# the first invocation of the program, and from time to time thereafter. -# When new groups are first created they may appear on your server as -# empty groups. By default, empty groups are ignored by the -a option. -# However, these new groups will not be created again, and so will not -# appear in the server's list of 'new groups' at a later date. Hence it -# won't appear until you do a '-a' after some articles have appeared. -# -# I should really keep a list of ignored empty groups and re-check them -# for articles on every run, but I haven't got around to it yet. -# -# This assumes an NNTP news feed. -# -# Feel free to copy, distribute and modify this code for -# non-commercial use. If you make any useful modifications, let me -# know! -# -# (c) Quentin Stafford-Fraser 1994 -# fraser@europarc.xerox.com qs101@cl.cam.ac.uk -# # -####################################################################### -import sys,nntplib, string, marshal, time, os, posix, string - -####################################################################### -# Check these variables before running! # - -# Top directory. -# Filenames which don't start with / are taken as being relative to this. -topdir='/anfs/qsbigdisc/web/html/newspage' - -# The name of your NNTP host -# eg. -# newshost = 'nntp-serv.cl.cam.ac.uk' -# or use following to get the name from the NNTPSERVER environment -# variable: -# newshost = posix.environ['NNTPSERVER'] -newshost = 'nntp-serv.cl.cam.ac.uk' - -# The filename for a local cache of the newsgroup list -treefile = 'grouptree' - -# The filename for descriptions of newsgroups -# I found a suitable one at ftp.uu.net in /uunet-info/newgroups.gz -# You can set this to '' if you don't wish to use one. -descfile = 'newsgroups' - -# The directory in which HTML pages should be created -# eg. -# pagedir = '/usr/local/lib/html/newspage' -# pagedir = 'pages' -pagedir = topdir - -# The html prefix which will refer to this directory -# eg. -# httppref = '/newspage/', -# or leave blank for relative links between pages: (Recommended) -# httppref = '' -httppref = '' - -# The name of the 'root' news page in this directory. -# A .html suffix will be added. -rootpage = 'root' - -# Set skipempty to 0 if you wish to see links to empty groups as well. -# Only affects the -a option. -skipempty = 1 - -# pagelinkicon can contain html to put an icon after links to -# further pages. This helps to make important links stand out. -# Set to '' if not wanted, or '...' is quite a good one. -pagelinkicon='... ' - -# --------------------------------------------------------------------- -# Less important personal preferences: - -# Sublistsize controls the maximum number of items the will appear as -# an indented sub-list before the whole thing is moved onto a different -# page. The smaller this is, the more pages you will have, but the -# shorter each will be. -sublistsize = 4 - -# That should be all. # -####################################################################### - -for dir in os.curdir, os.environ['HOME']: - rcfile = os.path.join(dir, '.newslistrc.py') - if os.path.exists(rcfile): - print rcfile - execfile(rcfile) - break - -from nntplib import NNTP -from stat import * - -rcsrev = '$Revision$'[11:15] -desc = {} - -# Make (possibly) relative filenames into absolute ones -treefile = os.path.join(topdir,treefile) -descfile = os.path.join(topdir,descfile) -page = os.path.join(topdir,pagedir) - -# First the bits for creating trees --------------------------- - -# Addtotree creates/augments a tree from a list of group names -def addtotree(tree, groups): - print 'Updating tree...' - for i in groups: - parts = string.splitfields(i,'.') - makeleaf(tree, parts) - -# Makeleaf makes a leaf and the branch leading to it if necessary -def makeleaf(tree,path): - j = path[0] - l = len(path) - - if not tree.has_key(j): - tree[j] = {} - if l == 1: - tree[j]['.'] = '.' - if l > 1: - makeleaf(tree[j],path[1:]) - -# Then the bits for outputting trees as pages ---------------- - -# Createpage creates an HTML file named .html containing links -# to those groups beginning with . - -def createpage(root, tree, p): - filename = os.path.join(pagedir,root+'.html') - if root == rootpage: - detail = '' - else: - detail = ' under ' + root - f = open(filename,'w') - # f.write('Content-Type: text/html\n') - f.write('Newsgroups available' + detail + '\n') - f.write('

Newsgroups available' + detail +'

\n') - f.write('
Back to top level

\n') - printtree(f,tree,0,p) - f.write('This page automatically created by \'newslist\' v. '+rcsrev+'.') - f.write(time.ctime(time.time()) + '

') - f.close() - -# Printtree prints the groups as a bulleted list. Groups with -# more than subgroups will be put on a separate page. -# Other sets of subgroups are just indented. - -def printtree(f, tree, indent, p): - global desc - l = len(tree) - - if l > sublistsize and indent>0: - # Create a new page and a link to it - f.write('

  • ') - f.write(p[1:]+'.*') - f.write(''+pagelinkicon+'\n') - createpage(p[1:], tree, p) - return - - kl = tree.keys() - - if l > 1: - kl.sort() - if indent > 0: - # Create a sub-list - f.write('
  • '+p[1:]+'\n
      ') - else: - # Create a main list - f.write('
        ') - indent = indent + 1 - - for i in kl: - if i == '.': - # Output a newsgroup - f.write('
      • '+ p[1:] + ' ') - if desc.has_key(p[1:]): - f.write(' '+desc[p[1:]]+'\n') - else: - f.write('\n') - else: - # Output a hierarchy - printtree(f,tree[i], indent, p+'.'+i) - - if l > 1: - f.write('\n
      ') - -# Reading descriptions file --------------------------------------- - -# This returns an array mapping group name to its description - -def readdesc(descfile): - global desc - - desc = {} - - if descfile == '': - return - - try: - d = open(descfile, 'r') - print 'Reading descriptions...' - except (IOError): - print 'Failed to open description file ' + descfile - return - l = d.readline() - while l != '': - bits = string.split(l) - try: - grp = bits[0] - dsc = string.join(bits[1:]) - if len(dsc)>1: - desc[grp] = dsc - except (IndexError): - pass - l = d.readline() - -# Check that ouput directory exists, ------------------------------ -# and offer to create it if not - -def checkopdir(pagedir): - if not os.path.isdir(pagedir): - print 'Directory '+pagedir+' does not exist.' - print 'Shall I create it for you? (y/n)' - if sys.stdin.readline()[0] == 'y': - try: - os.mkdir(pagedir,0777) - except: - print 'Sorry - failed!' - sys.exit(1) - else: - print 'OK. Exiting.' - sys.exit(1) - -# Read and write current local tree ---------------------------------- - -def readlocallist(treefile): - print 'Reading current local group list...' - tree = {} - try: - treetime = time.localtime(os.stat(treefile)[ST_MTIME]) - except: - print '\n*** Failed to open local group cache '+treefile - print 'If this is the first time you have run newslist, then' - print 'use the -a option to create it.' - sys.exit(1) - treedate = '%02d%02d%02d' % (treetime[0] % 100 ,treetime[1], treetime[2]) - try: - dump = open(treefile,'r') - tree = marshal.load(dump) - dump.close() - except (IOError): - print 'Cannot open local group list ' + treefile - return (tree, treedate) - -def writelocallist(treefile, tree): - try: - dump = open(treefile,'w') - groups = marshal.dump(tree,dump) - dump.close() - print 'Saved list to '+treefile+'\n' - except: - print 'Sorry - failed to write to local group cache '+treefile - print 'Does it (or its directory) have the correct permissions?' - sys.exit(1) - -# Return list of all groups on server ----------------------------- - -def getallgroups(server): - print 'Getting list of all groups...' - treedate='010101' - info = server.list()[1] - groups = [] - print 'Processing...' - if skipempty: - print '\nIgnoring following empty groups:' - for i in info: - grpname = string.split(i[0])[0] - if skipempty and string.atoi(i[1]) < string.atoi(i[2]): - print grpname+' ', - else: - groups.append(grpname) - print '\n' - if skipempty: - print '(End of empty groups)' - return groups - -# Return list of new groups on server ----------------------------- - -def getnewgroups(server, treedate): - print 'Getting list of new groups since start of '+treedate+'...', - info = server.newgroups(treedate,'000001')[1] - print 'got '+`len(info)`+'.' - print 'Processing...', - groups = [] - for i in info: - grpname = string.split(i)[0] - groups.append(grpname) - print 'Done' - return groups - -# Now the main program -------------------------------------------- - -def main(): - global desc - - tree={} - - # Check that the output directory exists - checkopdir(pagedir); - - try: - print 'Connecting to '+newshost+'...' - if sys.version[0] == '0': - s = NNTP.init(newshost) - else: - s = NNTP(newshost) - connected = 1 - except (nntplib.error_temp, nntplib.error_perm), x: - print 'Error connecting to host:', x - print 'I\'ll try to use just the local list.' - connected = 0 - - # If -a is specified, read the full list of groups from server - if connected and len(sys.argv) > 1 and sys.argv[1] == '-a': - - groups = getallgroups(s) - - # Otherwise just read the local file and then add - # groups created since local file last modified. - else: - - (tree, treedate) = readlocallist(treefile) - if connected: - groups = getnewgroups(s, treedate) - - if connected: - addtotree(tree, groups) - writelocallist(treefile,tree) - - # Read group descriptions - readdesc(descfile) - - print 'Creating pages...' - createpage(rootpage, tree, '') - print 'Done' - - -main() - -# That's all folks -###################################################################### diff --git a/Demo/scripts/pi.py b/Demo/scripts/pi.py deleted file mode 100755 index 200cb4ae8d..0000000000 --- a/Demo/scripts/pi.py +++ /dev/null @@ -1,33 +0,0 @@ -#! /usr/local/bin/python - -# Print digits of pi forever. -# -# The algorithm, using Python's 'long' integers ("bignums"), works -# with continued fractions, and was conceived by Lambert Meertens. -# -# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton, -# published by Prentice-Hall (UK) Ltd., 1990. - -import sys - -def main(): - k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L - while 1: - # Next approximation - p, q, k = k*k, 2L*k+1L, k+1L - a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 - # Print common digits - d, d1 = a/b, a1/b1 - while d == d1: - output(d) - a, a1 = 10L*(a%b), 10L*(a1%b1) - d, d1 = a/b, a1/b1 - -def output(d): - # Use write() to avoid spaces between the digits - # Use int(d) to avoid a trailing L after each digit - sys.stdout.write(`int(d)`) - # Flush so the output is seen immediately - sys.stdout.flush() - -main() diff --git a/Demo/scripts/pp.py b/Demo/scripts/pp.py deleted file mode 100755 index eaf7e41537..0000000000 --- a/Demo/scripts/pp.py +++ /dev/null @@ -1,138 +0,0 @@ -#! /usr/local/bin/python - -# Emulate some Perl command line options. -# Usage: pp [-a] [-c] [-d] [-e scriptline] [-F fieldsep] [-n] [-p] [file] ... -# Where the options mean the following: -# -a : together with -n or -p, splits each line into list F -# -c : check syntax only, do not execute any code -# -d : run the script under the debugger, pdb -# -e scriptline : gives one line of the Python script; may be repeated -# -F fieldsep : sets the field separator for the -a option [not in Perl] -# -n : runs the script for each line of input -# -p : prints the line after the script has run -# When no script lines have been passed, the first file argument -# contains the script. With -n or -p, the remaining arguments are -# read as input to the script, line by line. If a file is '-' -# or missing, standard input is read. - -# XXX To do: -# - add -i extension option (change files in place) -# - make a single loop over the files and lines (changes effect of 'break')? -# - add an option to specify the record separator -# - except for -n/-p, run directly from the file if at all possible - -import sys -import string -import getopt - -FS = '' -SCRIPT = [] -AFLAG = 0 -CFLAG = 0 -DFLAG = 0 -NFLAG = 0 -PFLAG = 0 - -try: - optlist, ARGS = getopt.getopt(sys.argv[1:], 'acde:F:np') -except getopt.error, msg: - sys.stderr.write(sys.argv[0] + ': ' + msg + '\n') - sys.exit(2) - -for option, optarg in optlist: - if option == '-a': - AFLAG = 1 - elif option == '-c': - CFLAG = 1 - elif option == '-d': - DFLAG = 1 - elif option == '-e': - for line in string.splitfields(optarg, '\n'): - SCRIPT.append(line) - elif option == '-F': - FS = optarg - elif option == '-n': - NFLAG = 1 - PFLAG = 0 - elif option == '-p': - NFLAG = 1 - PFLAG = 1 - else: - print option, 'not recognized???' - -if not ARGS: ARGS.append('-') - -if not SCRIPT: - if ARGS[0] == '-': - fp = sys.stdin - else: - fp = open(ARGS[0], 'r') - while 1: - line = fp.readline() - if not line: break - SCRIPT.append(line[:-1]) - del fp - del ARGS[0] - if not ARGS: ARGS.append('-') - -if CFLAG: - prologue = ['if 0:'] - epilogue = [] -elif NFLAG: - # Note that it is on purpose that AFLAG and PFLAG are - # tested dynamically each time through the loop - prologue = [ \ - 'LINECOUNT = 0', \ - 'for FILE in ARGS:', \ - ' \tif FILE == \'-\':', \ - ' \t \tFP = sys.stdin', \ - ' \telse:', \ - ' \t \tFP = open(FILE, \'r\')', \ - ' \tLINENO = 0', \ - ' \twhile 1:', \ - ' \t \tLINE = FP.readline()', \ - ' \t \tif not LINE: break', \ - ' \t \tLINENO = LINENO + 1', \ - ' \t \tLINECOUNT = LINECOUNT + 1', \ - ' \t \tL = LINE[:-1]', \ - ' \t \taflag = AFLAG', \ - ' \t \tif aflag:', \ - ' \t \t \tif FS: F = string.splitfields(L, FS)', \ - ' \t \t \telse: F = string.split(L)' \ - ] - epilogue = [ \ - ' \t \tif not PFLAG: continue', \ - ' \t \tif aflag:', \ - ' \t \t \tif FS: print string.joinfields(F, FS)', \ - ' \t \t \telse: print string.join(F)', \ - ' \t \telse: print L', \ - ] -else: - prologue = ['if 1:'] - epilogue = [] - -# Note that we indent using tabs only, so that any indentation style -# used in 'command' will come out right after re-indentation. - -program = string.joinfields(prologue, '\n') + '\n' -for line in SCRIPT: - program = program + (' \t \t' + line + '\n') -program = program + (string.joinfields(epilogue, '\n') + '\n') - -import tempfile -tfn = tempfile.mktemp() -try: - fp = open(tfn, 'w') - fp.write(program) - fp.close() - if DFLAG: - import pdb - pdb.run('execfile(' + `tfn` + ')') - else: - execfile(tfn) -finally: - import os - try: - os.unlink(tfn) - except: - pass diff --git a/Demo/scripts/primes.py b/Demo/scripts/primes.py deleted file mode 100755 index 3e6a64623f..0000000000 --- a/Demo/scripts/primes.py +++ /dev/null @@ -1,26 +0,0 @@ -#! /usr/local/bin/python - -# Print prime numbers in a given range - -def main(): - import sys - min, max = 2, 0x7fffffff - if sys.argv[1:]: - min = int(eval(sys.argv[1])) - if sys.argv[2:]: - max = int(eval(sys.argv[2])) - primes(min, max) - -def primes(min, max): - if 2 >= min: print 2 - primes = [2] - i = 3 - while i <= max: - for p in primes: - if i%p == 0 or p*p > i: break - if i%p <> 0: - primes.append(i) - if i >= min: print i - i = i+2 - -main() diff --git a/Demo/scripts/script.py b/Demo/scripts/script.py deleted file mode 100755 index 04e7ecb2bf..0000000000 --- a/Demo/scripts/script.py +++ /dev/null @@ -1,33 +0,0 @@ -#! /usr/local/bin/python -# script.py -- Make typescript of terminal session. -# Usage: -# -a Append to typescript. -# -p Use Python as shell. -# Author: Steen Lumholt. - - -import os, time, sys -import pty - -def read(fd): - data = os.read(fd, 1024) - file.write(data) - return data - -shell = 'sh' -filename = 'typescript' -mode = 'w' -if os.environ.has_key('SHELL'): - shell = os.environ['SHELL'] -if '-a' in sys.argv: - mode = 'a' -if '-p' in sys.argv: - shell = 'python' - -file = open(filename, mode) - -sys.stdout.write('Script started, file is %s\n' % filename) -file.write('Script started on %s\n' % time.ctime(time.time())) -pty.spawn(shell, read) -file.write('Script done on %s\n' % time.ctime(time.time())) -sys.stdout.write('Script done, file is %s\n' % filename) diff --git a/Demo/scripts/unbirthday.py b/Demo/scripts/unbirthday.py deleted file mode 100755 index cb018b654c..0000000000 --- a/Demo/scripts/unbirthday.py +++ /dev/null @@ -1,106 +0,0 @@ -#! /usr/local/bin/python - -# Calculate your unbirthday count (see Alice in Wonderland). -# This is defined as the number of days from your birth until today -# that weren't your birthday. (The day you were born is not counted). -# Leap years make it interesting. - -import sys -import time -import calendar - -def main(): - # Note that the range checks below also check for bad types, - # e.g. 3.14 or (). However syntactically invalid replies - # will raise an exception. - if sys.argv[1:]: - year = eval(sys.argv[1]) - else: - year = input('In which year were you born? ') - if year in range(100): - print 'I\'ll assume that by', year, - year = year + 1900 - print 'you mean', year, 'and not the early Christian era' - elif year not in range(1850, 2000): - print 'It\'s hard to believe you were born in', year - return - # - if sys.argv[2:]: - month = eval(sys.argv[2]) - else: - month = input('And in which month? (1-12) ') - if month not in range(1, 13): - print 'There is no month numbered', month - return - # - if sys.argv[3:]: - day = eval(sys.argv[3]) - else: - day = input('And on what day of that month? (1-31) ') - if month == 2 and calendar.isleap(year): - maxday = 29 - else: - maxday = calendar.mdays[month] - if day not in range(1, maxday+1): - print 'There are no', day, 'days in that month!' - return - # - bdaytuple = (year, month, day) - bdaydate = mkdate(bdaytuple) - print 'You were born on', format(bdaytuple) - # - todaytuple = time.localtime(time.time())[:3] - todaydate = mkdate(todaytuple) - print 'Today is', format(todaytuple) - # - if bdaytuple > todaytuple: - print 'You are a time traveler. Go back to the future!' - return - # - if bdaytuple == todaytuple: - print 'You were born today. Have a nice life!' - return - # - days = todaydate - bdaydate - print 'You have lived', days, 'days' - # - age = 0 - for y in range(year, todaytuple[0] + 1): - if bdaytuple < (y, month, day) <= todaytuple: - age = age + 1 - # - print 'You are', age, 'years old' - # - if todaytuple[1:] == bdaytuple[1:]: - print 'Congratulations! Today is your', nth(age), 'birthday' - print 'Yesterday was your', - else: - print 'Today is your', - print nth(days - age), 'unbirthday' - -def format((year, month, day)): - return '%d %s %d' % (day, calendar.month_name[month], year) - -def nth(n): - if n == 1: return '1st' - if n == 2: return '2nd' - if n == 3: return '3rd' - return '%dth' % n - -def mkdate((year, month, day)): - # Januari 1st, in 0 A.D. is arbitrarily defined to be day 1, - # even though that day never actually existed and the calendar - # was different then... - days = year*365 # years, roughly - days = days + (year+3)/4 # plus leap years, roughly - days = days - (year+99)/100 # minus non-leap years every century - days = days + (year+399)/400 # plus leap years every 4 centirues - for i in range(1, month): - if i == 2 and calendar.isleap(year): - days = days + 29 - else: - days = days + calendar.mdays[i] - days = days + day - return days - -main() diff --git a/Demo/scripts/update.py b/Demo/scripts/update.py deleted file mode 100755 index e8f6283676..0000000000 --- a/Demo/scripts/update.py +++ /dev/null @@ -1,91 +0,0 @@ -#! /usr/local/bin/python - -# Update a bunch of files according to a script. -# The input file contains lines of the form ::, -# meaning that the given line of the given file is to be replaced -# by the given text. This is useful for performing global substitutions -# on grep output: - -import os -import sys -import regex - -pat = '^\([^: \t\n]+\):\([1-9][0-9]*\):' -prog = regex.compile(pat) - -class FileObj: - def __init__(self, filename): - self.filename = filename - self.changed = 0 - try: - self.lines = open(filename, 'r').readlines() - except IOError, msg: - print '*** Can\'t open "%s":' % filename, msg - self.lines = None - return - print 'diffing', self.filename - - def finish(self): - if not self.changed: - print 'no changes to', self.filename - return - try: - os.rename(self.filename, self.filename + '~') - fp = open(self.filename, 'w') - except (os.error, IOError), msg: - print '*** Can\'t rewrite "%s":' % self.filename, msg - return - print 'writing', self.filename - for line in self.lines: - fp.write(line) - fp.close() - self.changed = 0 - - def process(self, lineno, rest): - if self.lines is None: - print '(not processed): %s:%s:%s' % ( - self.filename, lineno, rest), - return - i = eval(lineno) - 1 - if not 0 <= i < len(self.lines): - print '*** Line number out of range: %s:%s:%s' % ( - self.filename, lineno, rest), - return - if self.lines[i] == rest: - print '(no change): %s:%s:%s' % ( - self.filename, lineno, rest), - return - if not self.changed: - self.changed = 1 - print '%sc%s' % (lineno, lineno) - print '<', self.lines[i], - print '---' - self.lines[i] = rest - print '>', self.lines[i], - -def main(): - if sys.argv[1:]: - try: - fp = open(sys.argv[1], 'r') - except IOError, msg: - print 'Can\'t open "%s":' % sys.argv[1], msg - sys.exit(1) - else: - fp = sys.stdin - curfile = None - while 1: - line = fp.readline() - if not line: - if curfile: curfile.finish() - break - n = prog.match(line) - if n < 0: - print 'Funny line:', line, - continue - filename, lineno = prog.group(1, 2) - if not curfile or filename <> curfile.filename: - if curfile: curfile.finish() - curfile = FileObj(filename) - curfile.process(lineno, line[n:]) - -main() diff --git a/Demo/scripts/wh.py b/Demo/scripts/wh.py deleted file mode 100755 index b9b09efa6a..0000000000 --- a/Demo/scripts/wh.py +++ /dev/null @@ -1,2 +0,0 @@ -# This is here so I can use 'wh' instead of 'which' in '~/bin/generic_python' -import which diff --git a/Demo/sgi/README b/Demo/sgi/README deleted file mode 100644 index 3ef80d2dbd..0000000000 --- a/Demo/sgi/README +++ /dev/null @@ -1,22 +0,0 @@ -Demonstrations of Python that use various features of the Silicon -Graphics IRIS machines. - -al Demonstrations of the audio capabilities of the - Indigo. Require the built-in module 'al'. One program - also needs the build-in module 'fl' (the FORMS - library by Mark Overmars.) - -cd Demonstrations of the CD-ROM player's audio interface, - built-in module 'cd'. - -flp Demonstrations of using the 'flp' standard module, - which enables you to quickly create forms using the - 'fl' built-in module (available if you use the FORMS - library by Mark Overmars). - -gl Demonstrations of the Graphics Library (GL). - Require the built-in module 'gl'. - -sv Demonstrations of the Indigo Video module. - Requires the built-in module 'sv'. See also the - following directory. diff --git a/Demo/sgi/al/README b/Demo/sgi/al/README deleted file mode 100644 index fba67b7ddf..0000000000 --- a/Demo/sgi/al/README +++ /dev/null @@ -1,15 +0,0 @@ -This directory contains programs using the "al" interface, which gives -access to the most important parts of the SGI Audio Library for the -Indigo and 4D/35. - -alwatch.py Watch changes in device settings -broadcast.py Broadcast audio using UDP packets -cmpaf.py Compare different audio compression schemes (uses fl) -intercom.py 2-way communication with another host (uses fl) -playaiff.py Play an AIFF file (as output by recordaiff) -playback.py Play raw audio data read from stdin -playold.py Play an audio file recorded by the old 4D/25 audio -radio.py Listen to UDP packets sent by broadcast.py -rec_play.py Repeatedly record and play back a sample -record.py Record raw audio data to stdout -unicast.py Like broadcast but sends to one host diff --git a/Demo/sgi/al/alwatch.py b/Demo/sgi/al/alwatch.py deleted file mode 100755 index da747d4d81..0000000000 --- a/Demo/sgi/al/alwatch.py +++ /dev/null @@ -1,33 +0,0 @@ -import time -import al, AL -import string - -dev = AL.DEFAULT_DEVICE - -source_name = ['line', 'microphone', 'digital'] - -params = al.queryparams(dev) -for i in range(1, len(params), 2): - params[i] = -1 -while 1: - time.sleep(0.1) - old = params[:] - al.getparams(dev, params) - if params <> old: - for i in range(0, len(params), 2): - if params[i+1] <> old[i+1]: - name = al.getname(dev, params[i]) - if params[i] == AL.INPUT_SOURCE: - if 0 <= old[i+1] < len(source_name): - oldval = source_name[old[i+1]] - else: - oldval = '' - newval = source_name[params[i+1]] - else: - oldval = `old[i+1]` - newval = `params[i+1]` - print string.ljust(name, 25), - print '(' + string.rjust(oldval, 10) + ')', - print '-->', - print string.rjust(newval, 10) - print diff --git a/Demo/sgi/al/broadcast.py b/Demo/sgi/al/broadcast.py deleted file mode 100755 index ce4875e1fc..0000000000 --- a/Demo/sgi/al/broadcast.py +++ /dev/null @@ -1,27 +0,0 @@ -#! /usr/local/bin/python - -# broadcast [port] -# -# Broadcast audio input on the network as UDP packets; -# they can be received on any SGI machine with "radio.py". -# This uses the input sampling rate, input source etc. set by apanel. -# It uses the default sample width and #channels (16 bit/sample stereo). -# (This is 192,000 Bytes at a sampling speed of 48 kHz, or ~137 -# packets/second -- use with caution!!!) - -import sys, al -from socket import * - -port = 5555 -if sys.argv[1:]: port = eval(sys.argv[1]) - -s = socket(AF_INET, SOCK_DGRAM) -s.allowbroadcast(1) - -p = al.openport('broadcast', 'r') - -address = '', port -while 1: - # 700 samples equals 1400 bytes, or about the max packet size! - data = p.readsamps(700) - s.sendto(data, address) diff --git a/Demo/sgi/al/cmpaf.py b/Demo/sgi/al/cmpaf.py deleted file mode 100755 index 6b91e30fd6..0000000000 --- a/Demo/sgi/al/cmpaf.py +++ /dev/null @@ -1,64 +0,0 @@ -# Compare different audio compression schemes. -# -# This copies mono audio data from the input port to the output port, -# and puts up a window with 4 toggle buttons: -# -# uLAW : convert the data to uLAW and back -# ADPCM : convert the data to ADPCM and back -# Difference : make only the difference between the converted and the -# original data audible -# Exit : quit from the program - -import fl -import FL -import flp -import al -import AL -import audioop -import sys - -class Cmpaf: - def __init__(self): - parsetree = flp.parse_form('cmpaf_form','form') - flp.create_full_form(self, parsetree) - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(1800) - self.iport = al.openport('cmpaf','r', c) - self.oport = al.openport('cmpaf','w', c) - self.do_adpcm = self.do_ulaw = self.do_diff = 0 - self.acstate = None - self.form.show_form(FL.PLACE_SIZE, 1, 'compare audio formats') - - def run(self): - while 1: - olddata = data = self.iport.readsamps(600) - if self.do_ulaw: - data = audioop.lin2ulaw(data, 2) - data = audioop.ulaw2lin(data, 2) - if self.do_adpcm: - data, nacstate = audioop.lin2adpcm(data, 2, \ - self.acstate) - data, dummy = audioop.adpcm2lin(data, 2, \ - self.acstate) - self.acstate = nacstate - if self.do_diff: - olddata = audioop.mul(olddata, 2, -1) - data = audioop.add(olddata, data, 2) - self.oport.writesamps(data) - fl.check_forms() - - def cb_exit(self, *args): - sys.exit(0) - - def cb_adpcm(self, obj, val): - self.do_adpcm = obj.get_button() - - def cb_ulaw(self, obj, val): - self.do_ulaw = obj.get_button() - - def cb_diff(self, obj, val): - self.do_diff = obj.get_button() - -cmpaf = Cmpaf() -cmpaf.run() diff --git a/Demo/sgi/al/cmpaf_form.fd b/Demo/sgi/al/cmpaf_form.fd deleted file mode 100755 index 6667405133..0000000000 --- a/Demo/sgi/al/cmpaf_form.fd +++ /dev/null @@ -1,90 +0,0 @@ -Magic: 12321 - -Internal Form Definition File - (do not change) - -Number of forms: 1 - -=============== FORM =============== -Name: form -Width: 230.000000 -Height: 80.000000 -Number of Objects: 5 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 230.000000 80.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 12 -type: 1 -box: 10.000000 40.000000 100.000000 30.000000 -boxtype: 1 -colors: 39 3 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: uLAW -name: ulawbutton -callback: cb_ulaw -argument: 0 - --------------------- -class: 12 -type: 1 -box: 10.000000 10.000000 100.000000 30.000000 -boxtype: 1 -colors: 39 3 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: ADPCM -name: adpcm_button -callback: cb_adpcm -argument: 0 - --------------------- -class: 11 -type: 0 -box: 170.000000 10.000000 50.000000 20.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: EXIT -name: exit_button -callback: cb_exit -argument: 0 - --------------------- -class: 12 -type: 1 -box: 120.000000 40.000000 100.000000 30.000000 -boxtype: 1 -colors: 39 3 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Difference -name: diffbutton -callback: cb_diff -argument: 0 - -============================== -create_the_forms diff --git a/Demo/sgi/al/intercom.py b/Demo/sgi/al/intercom.py deleted file mode 100755 index fd983d39ad..0000000000 --- a/Demo/sgi/al/intercom.py +++ /dev/null @@ -1,212 +0,0 @@ -# intercom -- use mike and headset to *talk* to a person on another host. -# For SGI 4D/35 or Indigo running IRIX 4.0. -# Uses 16 bit sampling at 16000 samples/sec, or 32000 bytes/sec, -# tranmitted in 32 1000-byte UDP packets. (In each direction!) -# -# usage: -# intercom hostname - start talking to person on other host -# intercom -r hostname - called remotely to do the setup - -from names import * -import sys, time, posix, gl, fl, FL, al, AL, getopt, rand -from socket import * - -# UDP port numbers used (one for each direction!) -PORT1 = 51042 -PORT2 = PORT1+1 - -# Figure out the user name -try: - user = posix.environ['LOGNAME'] -except: - user = posix.environ['USER'] - -# Debug flags (Implemented as a list; non-empty means debugging is on) -debug = [] - -def main(): - remote = 0 - opts, args = getopt.getopt(sys.argv[1:], 'rd') - for opt, arg in opts: - if opt == '-r': remote = 1 - elif opt == '-d': debug.append(opt) - if len(args) <> 1: - msg = 'usage: intercom [-d] [-r] hostname' - msg = msg + ' (-r is for internal use only!)\n' - sys.stderr.write(msg) - sys.exit(2) - if remote: - server(args[0]) - else: - client(args[0]) - -def client(hostname): - print 'client starting' - cmd = 'rsh ' + hostname + ' "cd ' + AUDIODIR - cmd = cmd + '; DISPLAY=:0; export DISPLAY' - cmd = cmd + '; ' + PYTHON + ' intercom.py -r ' - for flag in debug: cmd = cmd + flag + ' ' - cmd = cmd + gethostname() - cmd = cmd + '"' - if debug: print cmd - pipe = posix.popen(cmd, 'r') - ack = 0 - nak = 0 - while 1: - line = pipe.readline() - if not line: break - sys.stdout.write('remote: ' + line) - if line == 'NAK\n': - nak = 1 - break - elif line == 'ACK\n': - ack = 1 - break - if nak: - print 'Remote user doesn\'t want to talk to you.' - return - if not ack: - print 'No acknowledgement (remote side crashed?).' - return - # - print 'Ready...' - # - s = socket(AF_INET, SOCK_DGRAM) - s.bind('', PORT2) - # - otheraddr = gethostbyname(hostname), PORT1 - try: - try: - ioloop(s, otheraddr) - except KeyboardInterrupt: - log('client got intr') - except error: - log('client got error') - finally: - s.sendto('', otheraddr) - log('client finished sending empty packet to server') - # - log('client exit') - print 'Done.' - -def server(hostname): - print 'server starting' - sys.stdout.flush() - # - if not remotedialog(): - print 'NAK' - return - # - print 'ACK' - # - s = socket(AF_INET, SOCK_DGRAM) - s.bind('', PORT1) - # - # Close std{in,out,err} so rsh will exit; reopen them as dummies - # - sys.stdin.close() - sys.stdin = open('/dev/null', 'r') - sys.stdout.close() - sys.stdout = open('/dev/null', 'w') - sys.stderr.close() - if debug: - sys.stderr = open('/tmp/intercom.err', 'a') - else: - sys.stderr = open('/dev/null', 'w') - # - ioloop(s, (gethostbyname(hostname), PORT2)) - log('server exit') - sys.exit(0) - -def remotedialog(): - gl.foreground() - gl.ringbell() - m1 = user + ' wants to talk to you over the audio channel.' - m2 = 'If it\'s OK, put on your headset and click Yes.' - m3 = 'If you\'re too busy, click No.' - return fl.show_question(m1, m2, m3) - -def ioloop(s, otheraddr): - # - dev = AL.DEFAULT_DEVICE - params = al.queryparams(dev) - al.getparams(dev, params) - time.sleep(1) - saveparams = params[:] - for i in range(0, len(params), 2): - if params[i] in (AL.INPUT_RATE, AL.OUTPUT_RATE): - params[i+1] = AL.RATE_16000 - elif params[i] == AL.INPUT_SOURCE: - params[i+1] = AL.INPUT_MIC - try: - al.setparams(dev, params) - ioloop1(s, otheraddr) - finally: - al.setparams(dev, saveparams) - -def ioloop1(s, otheraddr): - # - # Watch out! data is in bytes, but the port counts in samples, - # which are two bytes each (for 16-bit samples). - # Luckily, we use mono, else it would be worse (2 samples/frame...) - # - SAMPSPERBUF = 500 - BYTESPERSAMP = 2 # AL.SAMPLE_16 - BUFSIZE = BYTESPERSAMP*SAMPSPERBUF - QSIZE = 4*SAMPSPERBUF - # - config = al.newconfig() - config.setqueuesize(QSIZE) - config.setwidth(AL.SAMPLE_16) - config.setchannels(AL.MONO) - # - pid = posix.fork() - if pid: - # Parent -- speaker/headphones handler - log('parent started') - spkr = al.openport('spkr', 'w', config) - while 1: - data = s.recv(BUFSIZE) - if len(data) == 0: - # EOF packet - log('parent got empty packet; killing child') - posix.kill(pid, 15) - return - # Discard whole packet if we are too much behind - if spkr.getfillable() > len(data) / BYTESPERSAMP: - if len(debug) >= 2: - log('parent Q full; dropping packet') - spkr.writesamps(data) - else: - # Child -- microphone handler - log('child started') - try: - try: - mike = al.openport('mike', 'r', config) - # Sleep a while to let the other side get started - time.sleep(1) - # Drain the queue before starting to read - data = mike.readsamps(mike.getfilled()) - # Loop, sending packets from the mike to the net - while 1: - data = mike.readsamps(SAMPSPERBUF) - s.sendto(data, otheraddr) - except KeyboardInterrupt: - log('child got interrupt; exiting') - posix._exit(0) - except error: - log('child got error; exiting') - posix._exit(1) - finally: - log('child got unexpected error; leaving w/ traceback') - -def log(msg): - if not debug: return - if type(msg) <> type(''): - msg = `msg` - - f = open('/tmp/intercom.log', 'a') - f.write(`sys.argv` + ' ' + `posix.getpid()` + ': ' + msg + '\n') - f.close() - -main() diff --git a/Demo/sgi/al/listen.py b/Demo/sgi/al/listen.py deleted file mode 100755 index 83f850a657..0000000000 --- a/Demo/sgi/al/listen.py +++ /dev/null @@ -1,34 +0,0 @@ -# Listen to the input on host argv[1]. - -import sys, al, AL, posix - -BUFSIZE = 2000 -QSIZE = 4000 - -def main(): - if len(sys.argv) <> 2: - sys.stderr.write('usage: ' + sys.argv[0] + ' hostname\n') - sys.exit(2) - hostname = sys.argv[1] - cmd = 'exec rsh 'FORM': - raise aiff.Error, 'FORM chunk expected at start of file' - aiff.read_form_chunk(f) - while 1: - try: - type, size = aiff.read_chunk_header(f) - except EOFError: - break - if v: print 'header:', `type`, size - if type == 'COMM': - nchannels, nsampframes, sampwidth, samprate = \ - aiff.read_comm_chunk(f) - if v: print nchannels, nsampframes, sampwidth, samprate - elif type == 'SSND': - offset, blocksize = aiff.read_ssnd_chunk(f) - if v: print offset, blocksize - data = f.read(size-8) - if size%2: void = f.read(1) - p = makeport(nchannels, sampwidth, samprate) - play(p, data, offset, blocksize) - elif type in aiff.skiplist: - aiff.skip_chunk(f, size) - else: - raise aiff.Error, 'bad chunk type ' + type - -def makeport(nchannels, sampwidth, samprate): - c = al.newconfig() - c.setchannels(nchannels) - c.setwidth(sampwidth/8) - # can't set the rate... - p = al.openport('', 'w', c) - return p - -def play(p, data, offset, blocksize): - data = data[offset:] - p.writesamps(data) - while p.getfilled() > 0: time.sleep(0.01) - -main() diff --git a/Demo/sgi/al/playback.py b/Demo/sgi/al/playback.py deleted file mode 100755 index 967f746cf8..0000000000 --- a/Demo/sgi/al/playback.py +++ /dev/null @@ -1,23 +0,0 @@ -# Read mono 16bit samples from stdin and write them to the audio device. -# Assume the sampling rate is compatible. -# Use a small queue size to minimize delays. - -import al, sys -import AL - -BUFSIZE = 2000 -QSIZE = 4000 - -def main(): - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(QSIZE) - p = al.openport('', 'w', c) - while 1: - data = sys.stdin.read(BUFSIZE) - p.writesamps(data) - -try: - main() -except KeyboardInterrupt: - sys.exit(1) diff --git a/Demo/sgi/al/playold.py b/Demo/sgi/al/playold.py deleted file mode 100755 index 9792c168c5..0000000000 --- a/Demo/sgi/al/playold.py +++ /dev/null @@ -1,51 +0,0 @@ -# Play old style sound files (Guido's private format) - -import al, sys, time -import AL - -BUFSIZE = 8000 - -def main(): - if len(sys.argv) < 2: - f = sys.stdin - filename = sys.argv[0] - else: - if len(sys.argv) <> 2: - sys.stderr.write('usage: ' + \ - sys.argv[0] + ' filename\n') - sys.exit(2) - filename = sys.argv[1] - f = open(filename, 'r') - # - magic = f.read(4) - extra = '' - if magic == '0008': - rate = 8000 - elif magic == '0016': - rate = 16000 - elif magic == '0032': - rate = 32000 - else: - sys.stderr.write('no magic header; assuming 8k samples/sec.\n') - rate = 8000 - extra = magic - # - pv = [AL.OUTPUT_RATE, rate] - al.setparams(AL.DEFAULT_DEVICE, pv) - c = al.newconfig() - c.setchannels(AL.MONO) - c.setwidth(AL.SAMPLE_8) - port = al.openport(filename, 'w', c) - if extra: - port.writesamps(extra) - while 1: - buf = f.read(BUFSIZE) - if not buf: break - port.writesamps(buf) - while port.getfilled() > 0: - time.sleep(0.1) - -try: - main() -except KeyboardInterrupt: - sys.exit(1) diff --git a/Demo/sgi/al/radio.py b/Demo/sgi/al/radio.py deleted file mode 100755 index a6f6809187..0000000000 --- a/Demo/sgi/al/radio.py +++ /dev/null @@ -1,21 +0,0 @@ -#! /usr/local/bin/python - -# radio [port] -# -# Receive audio packets broadcast by "broadcast.py" on another SGI machine. -# Use apanel to set the output sampling rate to match that of the broadcast. - -import sys, al -from socket import * - -port = 5555 -if sys.argv[1:]: port = eval(sys.argv[1]) - -s = socket(AF_INET, SOCK_DGRAM) -s.bind('', port) - -p = al.openport('radio', 'w') - -while 1: - data = s.recv(1400) - p.writesamps(data) diff --git a/Demo/sgi/al/rec_play.py b/Demo/sgi/al/rec_play.py deleted file mode 100755 index 693c96e453..0000000000 --- a/Demo/sgi/al/rec_play.py +++ /dev/null @@ -1,28 +0,0 @@ -# -# records an AIFF sample and plays it -# infinity number of times. -# - -import time -import al - -def recordit () : - p = al.openport('hello', 'r') - print 'recording...' - buf = p.readsamps(500000) - print 'done.' - p.closeport() - - return buf - -def playit (buf) : - p = al.openport('hello', 'w') - print 'playing...' - p.writesamps(buf) - while p.getfilled() > 0: - time.sleep(0.01) - print 'done.' - p.closeport() - -while 1 : - playit (recordit ()) diff --git a/Demo/sgi/al/record.py b/Demo/sgi/al/record.py deleted file mode 100755 index e5c0f5b2d8..0000000000 --- a/Demo/sgi/al/record.py +++ /dev/null @@ -1,23 +0,0 @@ -# Record mono 16bits samples from the audio device and send them to stdout. -# Assume the sampling rate is compatible. -# Use a small queue size to minimize delays. - -import al, sys -import AL - -BUFSIZE = 2000 -QSIZE = 4000 - -def main(): - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(QSIZE) - p = al.openport('', 'r', c) - while 1: - data = p.readsamps(BUFSIZE) - sys.stdout.write(data) - -try: - main() -except KeyboardInterrupt: - sys.exit(1) diff --git a/Demo/sgi/al/unicast.py b/Demo/sgi/al/unicast.py deleted file mode 100755 index c9f3111fee..0000000000 --- a/Demo/sgi/al/unicast.py +++ /dev/null @@ -1,26 +0,0 @@ -#! /usr/local/bin/python - -# unicast host [port] -# -# Similar to "broadcast.py" but sends to a specific host only; -# use "radio.py" on the designated host to receive. -# This is less stressful on other hosts on the same ethernet segment -# if you need to send to one host only. - -import sys, al -from socket import * - -host = sys.argv[1] - -port = 5555 -if sys.argv[2:]: port = eval(sys.argv[1]) - -s = socket(AF_INET, SOCK_DGRAM) - -p = al.openport('unicast', 'r') - -address = host, port -while 1: - # 700 samples equals 1400 bytes, or about the max packet size! - data = p.readsamps(700) - s.sendto(data, address) diff --git a/Demo/sgi/al/x.py b/Demo/sgi/al/x.py deleted file mode 100755 index ecc12d8198..0000000000 --- a/Demo/sgi/al/x.py +++ /dev/null @@ -1,12 +0,0 @@ -# Demonstrate that rsh exits when the remote end closes std{in,out,err}. -# rsh voorn exec /ufs/guido/bin/sgi/python /ufs/guido/mm/demo/audio/x.py - -print 'hoi!' -import sys -sys.stdin.close() -sys.stdout.close() -sys.stderr.close() -import time -time.sleep(5) -sys.stdout = open('@', 'w') -sys.stdout.write('Hello\n') diff --git a/Demo/sgi/audio/README b/Demo/sgi/audio/README deleted file mode 100644 index 02a3701f92..0000000000 --- a/Demo/sgi/audio/README +++ /dev/null @@ -1,8 +0,0 @@ -Programs that demonstrate the use of the audio device on the SGI 4D/25. -These require the built-in module 'audio'. - -XXX This hardware is already obsolete; see ../al for examples of audio -XXX on the Indigo and 4D/35. - -play Read a sound sample from a file and play it through the - speaker. Options to set volume, sampling rate etc. diff --git a/Demo/sgi/audio/play.py b/Demo/sgi/audio/play.py deleted file mode 100755 index adc76252d8..0000000000 --- a/Demo/sgi/audio/play.py +++ /dev/null @@ -1,75 +0,0 @@ -#! /usr/local/python - -import sys -import audio - -import string -import getopt -import auds - -debug = [] - -DEF_RATE = 3 - -def main(): - # - gain = 100 - rate = 0 - starter = audio.write - stopper = 0 - # - optlist, args = getopt.getopt(sys.argv[1:], 'adg:r:') - # - for optname, optarg in optlist: - if 0: - pass - elif optname == '-d': - debug.append(1) - elif optname == '-g': - gain = string.atoi(optarg) - if not (0 < gain < 256): - raise optarg.error, '-g gain out of range' - elif optname == '-r': - rate = string.atoi(optarg) - if not (1 <= rate <= 3): - raise optarg.error, '-r rate out of range' - elif optname == '-a': - starter = audio.start_playing - stopper = audio.wait_playing - # - audio.setoutgain(gain) - audio.setrate(rate) - # - if not args: - play(starter, rate, auds.loadfp(sys.stdin)) - else: - real_stopper = 0 - for file in args: - if real_stopper: - real_stopper() - play(starter, rate, auds.load(file)) - real_stopper = stopper - -def play(starter, rate, data): - magic = data[:4] - if magic == '0008': - mrate = 3 - elif magic == '0016': - mrate = 2 - elif magic == '0032': - mrate = 1 - else: - mrate = 0 - if mrate: - data = data[4:] - else: - mrate = DEF_RATE - if not rate: rate = mrate - audio.setrate(rate) - starter(data) - -try: - main() -finally: - audio.setoutgain(0) - audio.done() diff --git a/Demo/sgi/audio_stdwin/README b/Demo/sgi/audio_stdwin/README deleted file mode 100644 index 6d96fe1e40..0000000000 --- a/Demo/sgi/audio_stdwin/README +++ /dev/null @@ -1,19 +0,0 @@ -Three programs that provide a user interface based upon STDWIN to the -audio device of the SGI 4D/25. These scripts also demonstrate the power -of a set of window interface classes implemented in Python that simplify -the construction of all sorts of buttons, etc. - -XXX This hardware is already obsolete; see ../al for examples of audio -XXX on the Indigo and 4D/35. - -jukebox Browses a directory full of sound samples and lets you - play selected ones. (Probably not fully functional, it - requires a conversion program.) - -rec A tape recorder that lets you record a sound sample, - play it back, and save it to a file. Various options to - set sampling rate, volume etc. When idle it doubles - as a VU meter. - -vumeter A VU meter that displays a history of the volume of - sound recently sampled from the microphone. diff --git a/Demo/sgi/audio_stdwin/jukebox.py b/Demo/sgi/audio_stdwin/jukebox.py deleted file mode 100755 index b2239929a9..0000000000 --- a/Demo/sgi/audio_stdwin/jukebox.py +++ /dev/null @@ -1,321 +0,0 @@ -#! /usr/local/python - -# JUKEBOX: browse directories full of sampled sound files. -# -# One or more "list windows" display the files and subdirectories of -# the arguments. Double-clicking on a subdirectory opens a new window -# displaying its contents (and so on recursively). Double clicking -# on a file plays it as a sound file (assuming it is one). -# -# Playing is asynchronous: the application keeps listening to events -# while the sample is playing, so you can change the volume (gain) -# during playing, cancel playing or start a new sample right away. -# -# The control window displays the current output gain and a primitive -# "stop button" to cancel the current play request. -# -# Sound files must currently be in Dik Winter's compressed Mac format. -# Since decompression is costly, decompressed samples are saved in -# /usr/tmp/@j* until the application is left. The files are read -# afresh each time, though. - -import audio -import sunaudio -import commands -import getopt -import path -import posix -import rand -import stdwin -from stdwinevents import * -import string -import sys - -from WindowParent import WindowParent -from HVSplit import VSplit -from Buttons import PushButton -from Sliders import ComplexSlider - -# Pathnames - -HOME_BIN_SGI = '/ufs/guido/bin/sgi/' # Directory where macsound2sgi lives -DEF_DB = '/ufs/dik/sounds/Mac/HCOM' # Default directory of sounds - - -# Global variables - -class struct: pass # Class to define featureless structures - -G = struct() # Holds writable global variables - - -# Main program - -def main(): - G.synchronous = 0 # If set, use synchronous audio.write() - G.debug = 0 # If set, print debug messages - G.gain = 75 # Output gain - G.rate = 3 # Sampling rate - G.busy = 0 # Set while asynchronous playing is active - G.windows = [] # List of open windows (except control) - G.mode = 'mac' # Macintosh mode - G.tempprefix = '/usr/tmp/@j' + `rand.rand()` + '-' - # - optlist, args = getopt.getopt(sys.argv[1:], 'dg:r:sSa') - for optname, optarg in optlist: - if optname == '-d': - G.debug = 1 - elif optname == '-g': - G.gain = string.atoi(optarg) - if not (0 < G.gain < 256): - raise optarg.error, '-g gain out of range' - elif optname == '-r': - G.rate = string.atoi(optarg) - if not (1 <= G.rate <= 3): - raise optarg.error, '-r rate out of range' - elif optname == '-s': - G.synchronous = 1 - elif optname == '-S': - G.mode = 'sgi' - elif optname == '-a': - G.mode = 'sun' - # - if not args: - args = [DEF_DB] - # - G.cw = opencontrolwindow() - for dirname in args: - G.windows.append(openlistwindow(dirname)) - # - # - savegain = audio.getoutgain() - try: - # Initialize stdaudio - audio.setoutgain(0) - audio.start_playing('') - dummy = audio.wait_playing() - audio.setoutgain(0) - maineventloop() - finally: - audio.setoutgain(savegain) - audio.done() - clearcache() - -def maineventloop(): - mouse_events = WE_MOUSE_DOWN, WE_MOUSE_MOVE, WE_MOUSE_UP - while G.windows: - type, w, detail = event = stdwin.getevent() - if w == G.cw.win: - if type == WE_CLOSE: - return - G.cw.dispatch(event) - else: - if type == WE_DRAW: - w.drawproc(w, detail) - elif type in mouse_events: - w.mouse(w, type, detail) - elif type == WE_CLOSE: - w.close(w) - del w, event - else: - if G.debug: print type, w, detail - -# Control window -- to set gain and cancel play operations in progress - -def opencontrolwindow(): - cw = WindowParent().create('Jukebox', (0, 0)) - v = VSplit().create(cw) - # - gain = ComplexSlider().define(v) - gain.setminvalmax(0, G.gain, 255) - gain.settexts(' ', ' ') - gain.sethook(gain_setval_hook) - # - stop = PushButton().definetext(v, 'Stop') - stop.hook = stop_hook - # - cw.realize() - return cw - -def gain_setval_hook(self): - G.gain = self.val - if G.busy: audio.setoutgain(G.gain) - -def stop_hook(self): - if G.busy: - audio.setoutgain(0) - dummy = audio.stop_playing() - G.busy = 0 - - -# List windows -- to display list of files and subdirectories - -def openlistwindow(dirname): - list = posix.listdir(dirname) - list.sort() - i = 0 - while i < len(list): - if list[i] == '.' or list[i] == '..': - del list[i] - else: - i = i+1 - for i in range(len(list)): - name = list[i] - if path.isdir(path.join(dirname, name)): - list[i] = list[i] + '/' - width = maxwidth(list) - width = width + stdwin.textwidth(' ') # XXX X11 stdwin bug workaround - height = len(list) * stdwin.lineheight() - stdwin.setdefwinsize(width, min(height, 500)) - w = stdwin.open(dirname) - stdwin.setdefwinsize(0, 0) - w.setdocsize(width, height) - w.drawproc = drawlistwindow - w.mouse = mouselistwindow - w.close = closelistwindow - w.dirname = dirname - w.list = list - w.selected = -1 - return w - -def maxwidth(list): - width = 1 - for name in list: - w = stdwin.textwidth(name) - if w > width: width = w - return width - -def drawlistwindow(w, area): - d = w.begindrawing() - d.erase((0, 0), (1000, 10000)) - lh = d.lineheight() - h, v = 0, 0 - for name in w.list: - d.text((h, v), name) - v = v + lh - showselection(w, d) - -def hideselection(w, d): - if w.selected >= 0: - invertselection(w, d) - -def showselection(w, d): - if w.selected >= 0: - invertselection(w, d) - -def invertselection(w, d): - lh = d.lineheight() - h1, v1 = p1 = 0, w.selected*lh - h2, v2 = p2 = 1000, v1 + lh - d.invert(p1, p2) - -def mouselistwindow(w, type, detail): - (h, v), clicks, button = detail[:3] - d = w.begindrawing() - lh = d.lineheight() - if 0 <= v < lh*len(w.list): - i = v / lh - else: - i = -1 - if w.selected <> i: - hideselection(w, d) - w.selected = i - showselection(w, d) - if type == WE_MOUSE_DOWN and clicks >= 2 and i >= 0: - name = path.join(w.dirname, w.list[i]) - if name[-1:] == '/': - if clicks == 2: - G.windows.append(openlistwindow(name[:-1])) - else: - playfile(name) - -def closelistwindow(w): - remove(G.windows, w) - -def remove(list, item): - for i in range(len(list)): - if list[i] == item: - del list[i] - break - - -# Playing tools - -cache = {} - -def clearcache(): - for x in cache.keys(): - try: - sts = posix.system('rm -f ' + cache[x]) - if sts: - print cmd - print 'Exit status', sts - except: - print cmd - print 'Exception?!' - del cache[x] - -def playfile(name): - if G.mode <> 'mac': - tempname = name - elif cache.has_key(name): - tempname = cache[name] - else: - tempname = G.tempprefix + `rand.rand()` - cmd = HOME_BIN_SGI + 'macsound2sgi' - cmd = cmd + ' ' + commands.mkarg(name) - cmd = cmd + ' >' + tempname - if G.debug: print cmd - sts = posix.system(cmd) - if sts: - print cmd - print 'Exit status', sts - stdwin.fleep() - return - cache[name] = tempname - fp = open(tempname, 'r') - try: - hdr = sunaudio.gethdr(fp) - except sunaudio.error, msg: - hdr = () - if hdr: - data_size = hdr[0] - data = fp.read(data_size) - # XXX this doesn't work yet, need to convert from uLAW!!! - del fp - else: - del fp - data = readfile(tempname) - if G.debug: print len(data), 'bytes read from', tempname - if G.busy: - G.busy = 0 - dummy = audio.stop_playing() - # - # Completely reset the audio device - audio.setrate(G.rate) - audio.setduration(0) - audio.setoutgain(G.gain) - # - if G.synchronous: - audio.write(data) - audio.setoutgain(0) - else: - try: - audio.start_playing(data) - G.busy = 1 - except: - stdwin.fleep() - del data - -def readfile(filename): - return readfp(open(filename, 'r')) - -def readfp(fp): - data = '' - while 1: - buf = fp.read(102400) # Reads most samples in one fell swoop - if not buf: - return data - data = data + buf - -main() diff --git a/Demo/sgi/audio_stdwin/rec.py b/Demo/sgi/audio_stdwin/rec.py deleted file mode 100755 index 0caba89826..0000000000 --- a/Demo/sgi/audio_stdwin/rec.py +++ /dev/null @@ -1,268 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -import sys -import audio -import stdwin - -import string -import getopt - -from stdwinevents import * -from Buttons import * -from Sliders import * -#from Soundogram import Soundogram -from VUMeter import VUMeter -from WindowParent import WindowParent, MainLoop -from HVSplit import HSplit, VSplit - -class TimeOutToggleButton(ToggleButton): - def define(self, parent): - self = ToggleButton.define(self, parent) - self.parent.need_timer(self) - self.timer_hook = 0 - return self - def timer(self): - if self.timer_hook: - self.timer_hook(self) - -K = 1024 -BUFSIZE = 30*8*K -Rates = [0, 32*K, 16*K, 8*K] -Magics = ['', '0032', '0016', '0008'] - -class Struct: pass -G = Struct() - -def main(): - # - # Turn off scroll bars - # - stdwin.setdefscrollbars(0, 0) - # - # Set default state - # - G.gain = 60 - G.rate = 3 - G.nomuting = 0 - G.savefile = '@rec' - # - # Set default values - # - G.data = '' - G.playing = 0 - G.recording = 0 - G.sogram = 0 - # - # Parse options - # - optlist, args = getopt.getopt(sys.argv[1:], 'mdg:r:') - # - for optname, optarg in optlist: - if 0: # (So all cases start with elif) - pass - elif optname == '-d': - G.debug = 1 - elif optname == '-g': - G.gain = string.atoi(optarg) - if not (0 < G.gain < 256): - raise optarg.error, '-g gain out of range' - elif optname == '-m': - G.nomuting = (not G.nomuting) - elif optname == '-r': - G.rate = string.atoi(optarg) - if not (1 <= G.rate <= 3): - raise optarg.error, '-r rate out of range' - # - if args: - G.savefile = args[0] - # - # Initialize the sound package - # - audio.setoutgain(G.nomuting * G.gain) # Silence the speaker - audio.setrate(G.rate) - # - # Create the WindowParent and VSplit - # - G.window = WindowParent().create('Recorder', (0, 0)) - w = G.vsplit = VSplit().create(G.window) - # - # VU-meter - # - G.vubtn = VUMeter().define(w) - # - # Radiobuttons for rates - # - r1btn = RadioButton().definetext(w, '32 K/sec') - r1btn.on_hook = rate_hook - r1btn.rate = 1 - # - r2btn = RadioButton().definetext(w, '16 K/sec') - r2btn.on_hook = rate_hook - r2btn.rate = 2 - # - r3btn = RadioButton().definetext(w, '8 K/sec') - r3btn.on_hook = rate_hook - r3btn.rate = 3 - # - radios = [r1btn, r2btn, r3btn] - r1btn.group = r2btn.group = r3btn.group = radios - for r in radios: - if r.rate == G.rate: r.select(1) - # - # Other controls - # - G.recbtn = TimeOutToggleButton().definetext(w, 'Record') - G.recbtn.on_hook = record_on_hook - G.recbtn.timer_hook = record_timer_hook - G.recbtn.off_hook = record_off_hook - # - G.mutebtn = CheckButton().definetext(w, 'Mute') - G.mutebtn.select(not G.nomuting) - G.mutebtn.hook = mute_hook - # - G.playbtn = TimeOutToggleButton().definetext(w, 'Playback') - G.playbtn.on_hook = play_on_hook - G.playbtn.timer_hook = play_timer_hook - G.playbtn.off_hook = play_off_hook - # - G.gainbtn = ComplexSlider().define(w) - G.gainbtn.settexts(' Volume: ', ' ') - G.gainbtn.setminvalmax(0, G.gain, 255) - G.gainbtn.sethook(gain_hook) - # - G.sizebtn = Label().definetext(w, `len(G.data)` + ' bytes') - # - #G.showbtn = PushButton().definetext(w, 'Sound-o-gram...') - #G.showbtn.hook = show_hook - # - G.savebtn = PushButton().definetext(w, 'Save...') - G.savebtn.hook = save_hook - # - G.quitbtn = PushButton().definetext(w, 'Quit') - G.quitbtn.hook = quit_hook - G.playbtn.enable(0) - G.savebtn.enable(0) - #G.showbtn.enable(0) - start_vu() - G.window.realize() - # - # Event loop - # - MainLoop() - -# XXX Disabled... -def show_hook(self): - savetext = self.text - self.settext('Be patient...') - close_sogram() - stdwin.setdefwinsize(400, 300) - win = stdwin.open('Sound-o-gram') - G.sogram = Soundogram().define(win, G.data) - win.buttons = [G.sogram] - self.settext(savetext) - -def close_sogram(): - if G.sogram: - # Break circular references - G.sogram.win.buttons[:] = [] - del G.sogram.win - G.sogram = 0 - -def mute_hook(self): - G.nomuting = (not self.selected) - audio.setoutgain(G.nomuting * G.gain) - -def rate_hook(self): - G.rate = self.rate - audio.setrate(G.rate) - -def record_on_hook(self): - stop_vu() - close_sogram() - audio.setrate(G.rate) - audio.setoutgain(G.nomuting * G.gain) - audio.start_recording(BUFSIZE) - G.recording = 1 - G.playbtn.enable(0) - G.window.settimer(10 * BUFSIZE / Rates[G.rate]) - -def record_timer_hook(self): - if G.recording: - if audio.poll_recording(): - self.hilite(0) - record_off_hook(self) - else: - self.parent.settimer(5) - -def record_off_hook(self): - if not G.recording: - return - G.data = audio.stop_recording() - G.recording = 0 - G.sizebtn.settext(`len(G.data)` + ' bytes') - audio.setoutgain(G.nomuting * G.gain) - G.playbtn.enable((len(G.data) > 0)) - G.savebtn.enable((len(G.data) > 0)) - #G.showbtn.enable((len(G.data) > 0)) - G.window.settimer(0) - start_vu() - -def play_on_hook(self): - stop_vu() - audio.setrate(G.rate) - audio.setoutgain(G.gain) - audio.start_playing(G.data) - G.playing = 1 - G.recbtn.enable(0) - G.window.settimer(max(10 * len(G.data) / Rates[G.rate], 1)) - -def play_timer_hook(self): - if G.playing: - if audio.poll_playing(): - self.hilite(0) - play_off_hook(self) - else: - self.parent.settimer(5) - -def play_off_hook(self): - if not G.playing: - return - x = audio.stop_playing() - G.playing = 0 - audio.setoutgain(G.nomuting * G.gain) - G.recbtn.enable(1) - G.window.settimer(0) - start_vu() - -def gain_hook(self): - G.gain = self.val - if G.playing or G.nomuting: audio.setoutgain(G.gain) - -def save_hook(self): - if not G.data: - stdwin.fleep() - else: - prompt = 'Store sampled data on file: ' - try: - G.savefile = stdwin.askfile(prompt, G.savefile, 1) - except KeyboardInterrupt: - return - try: - fp = open(G.savefile, 'w') - fp.write(Magics[G.rate] + G.data) - except: - stdwin.message('Cannot create ' + file) - -def stop_vu(): - G.vubtn.stop() - -def start_vu(): - G.vubtn.start() - -def quit_hook(self): - G.window.delayed_destroy() - -try: - main() -finally: - audio.setoutgain(0) diff --git a/Demo/sgi/audio_stdwin/vumeter.py b/Demo/sgi/audio_stdwin/vumeter.py deleted file mode 100755 index bfee66e86d..0000000000 --- a/Demo/sgi/audio_stdwin/vumeter.py +++ /dev/null @@ -1,35 +0,0 @@ -#! /usr/local/python - -import audio -import stdwin - -from VUMeter import VUMeter -from WindowParent import WindowParent -import MainLoop - -NBUFS=20 -BUFSIZE = NBUFS*48 -SCALE=128 - -class MyVUMeter(VUMeter): - def init_reactivity(self): - self.parent.need_mouse(self) - def mouse_down(self, detail): - if self.enabled: - self.stop() - else: - self.start() - def mouse_move(self, detail): pass - def mouse_up(self, detail): pass - -def main(): - audio.setrate(3) - audio.setoutgain(0) - w = WindowParent().create('VU Meter', (200, 100)) - v = MyVUMeter().define(w) - v.start() - w.realize() - while 1: - w.dispatch(stdwin.getevent()) - -main() diff --git a/Demo/sgi/cd/CD.doc b/Demo/sgi/cd/CD.doc deleted file mode 100755 index 67f6a028f0..0000000000 --- a/Demo/sgi/cd/CD.doc +++ /dev/null @@ -1,46 +0,0 @@ -Introduction. - -A number of programs have been written which access the Silicon -Graphics CD-ROM player. These programs all use the interface defined -in readcd.py (see readcd.doc for documentation). - -Specifying music stretches. - -The programs that are capable of reading music CD's all use the same -syntax to describe which part of the CD is to be read. The syntax -closely corresponds to the available methods in readcd.py. - -The music to be read is divided into stretches of music. Each stretch -must be specified as a separate argument on the command line. A -stretch can be a whole CD track, specified as a single number; or it -can be a start time and a end time. The start and end times must be -specified as a tuple, thus: ``(starttime, endtime)''. Don't forget to -quote the parenthesis to the shell. Both starttime and endtime can be -``None'', a simple number which refers to a CD track, or a tuple -consisting of either 3 or 4 elements. A starttime of ``None'' refers -to the start of the CD, an endtime of ``None'' refers to the end of -the CD. A tuple of 3 elements is an absolute time on the CD. The -three elements are (minutes, seconds, frames). A tuple of 4 elements -is a track-relative time. The four elements are (track, minutes, -seconds, frames). - -When one stretch ends at the end of a track and the following stretch -starts at the next track, there is the option of either playing or not -playing the pause between the two tracks. When either the end time of -the first stretch or the start time of the second stretch is specified -using absolute or track-relative times, the pause will not be played. -When both times are specified as simple track numbers, the pause will -be played. - -If no stretches are specified, the whole CD will be played. - -The programs. - -Currently, the following programs exist. -playcd [ stretch specification ] - Play (part of) a CD through the system loadspeaker or - headphone set. -cdaiff [ file [ stretch specification ] ] - Copy (part of) a CD to a file. The file will be written in - AIFF format. If no file is specified, cdaiff will write to - the file ``@'' in the current directory. diff --git a/Demo/sgi/cd/README b/Demo/sgi/cd/README deleted file mode 100644 index 016e4d1bb7..0000000000 --- a/Demo/sgi/cd/README +++ /dev/null @@ -1,28 +0,0 @@ -These are some programs to work with the SCSI CD-ROM player's audio -interface (see cdaudio(3) in IRIX 4.0 or higher; tested only on 4.0.2). - -See also the SGI-specific standard module 'readcd', documented as -"readcd.lib" in the library. - -cdwin.py A trivial window interface to play a CD over the CD - player's audio jack. More functionality is left as an - excersice to the reader. Needs module stdwin. - -listcd.py List the table-of-contents of a CD (data CDs will - appear as a single track). - -playcd.py Read audio data from the CD and play it over the - Indigo's built-in speker or audio jack. Needs module al. - -sendcd.py Read audio data from the CD and send it as UDP packets - over the network (to recvcd.py). - -recvcd.py Receive UDP packets containing CD audio data (from - sendcd.py) and play them over the Indigo's built-in - speaker or audio jack. Needs module al. (Doesn't - actually use module cd.) - -cdaiff.py Dump CD audio to disk in AIFF format. - -Note that to read *data* CD-ROMs you must open /dev/rdsk/dks0d4s7 or -some such special file... diff --git a/Demo/sgi/cd/cdaiff.py b/Demo/sgi/cd/cdaiff.py deleted file mode 100755 index a1b490f4ab..0000000000 --- a/Demo/sgi/cd/cdaiff.py +++ /dev/null @@ -1,33 +0,0 @@ -import sys -import readcd -import aifc -import AL -import cd - -Error = 'cdaiff.Error' - -def writeaudio(a, type, data): - a.writeframesraw(data) - -def main(): - if len(sys.argv) > 1: - a = aifc.open(sys.argv[1], 'w') - else: - a = aifc.open('@', 'w') - a.setsampwidth(AL.SAMPLE_16) - a.setnchannels(AL.STEREO) - a.setframerate(AL.RATE_44100) - r = readcd.Readcd() - for arg in sys.argv[2:]: - x = eval(arg) - try: - if len(x) <> 2: - raise Error, 'bad argument' - r.appendstretch(x[0], x[1]) - except TypeError: - r.appendtrack(x) - r.setcallback(cd.audio, writeaudio, a) - r.play() - a.close() - -main() diff --git a/Demo/sgi/cd/cdwin.py b/Demo/sgi/cd/cdwin.py deleted file mode 100755 index 284ad825ea..0000000000 --- a/Demo/sgi/cd/cdwin.py +++ /dev/null @@ -1,103 +0,0 @@ -# Window interface to (some of) the CD player's vital audio functions - -import cd -import stdwin -from stdwinevents import * -import mainloop - -def main(): - player = cd.open() - stdwin.setdefscrollbars(0, 0) - win = stdwin.open('CD') - win.player = player - win.dispatch = cddispatch - mainloop.register(win) - win.settimer(10) - mainloop.mainloop() - -def cddispatch(type, win, detail): - if type == WE_NULL: - pass - elif type == WE_CLOSE: - mainloop.unregister(win) - win.close() - elif type == WE_DRAW: - draw(win) - elif type == WE_TIMER: - update(win) - elif type == WE_MOUSE_UP: - left, top, right, bottom, v1, v2 = getgeo(win) - h, v = detail[0] - if left < h < right: - if top < v < v1: - but1(win) - elif v1 < v < v2: - but2(win) - elif v2 < v < bottom: - but3(win) - else: - stdwin.fleep() - -def but1(win): - update(win) - -def but2(win): - state = win.player.getstatus()[0] - if state == cd.ready: - win.player.play(1, 1) - elif state in (cd.playing, cd.paused): - win.player.togglepause() - else: - stdwin.fleep() - update(win) - -def but3(win): - win.player.stop() - update(win) - -def update(win): - d = win.begindrawing() - drawstatus(win, d) - d.enddrawing() - win.settimer(10) - -statedict = ['ERROR', 'NODISK', 'READY', 'PLAYING', 'PAUSED', 'STILL'] - -def draw(win): - left, top, right, bottom, v1, v2 = getgeo(win) - d = win.begindrawing() - drawstatus(win, d) - box(d, left, v1, right, v2, 'Play/Pause') - box(d, left, v2, right, bottom, 'Stop') - d.enddrawing() - -def drawstatus(win, d): - left, top, right, bottom, v1, v2 = getgeo(win) - state, track, curtime, abstime, totaltime, first, last, \ - scsi_audio, cur_block, dummy = win.player.getstatus() - if 0 <= state < len(statedict): - message = statedict[state] - else: - message = `status` - message = message + ' track ' + `track` + ' of ' + `last` - d.erase((left, top), (right, v1)) - box(d, left, top, right, v1, message) - -def box(d, left, top, right, bottom, label): - R = (left+1, top+1), (right-1, bottom-1) - width = d.textwidth(label) - height = d.lineheight() - h = (left + right - width) / 2 - v = (top + bottom - height) / 2 - d.box(R) - d.cliprect(R) - d.text((h, v), label) - d.noclip() - -def getgeo(win): - (left, top), (right, bottom) = (0, 0), win.getwinsize() - v1 = top + (bottom - top) / 3 - v2 = top + (bottom - top) * 2 / 3 - return left, top, right, bottom, v1, v2 - -main() diff --git a/Demo/sgi/cd/listcd.py b/Demo/sgi/cd/listcd.py deleted file mode 100755 index 2cfadb6b5e..0000000000 --- a/Demo/sgi/cd/listcd.py +++ /dev/null @@ -1,24 +0,0 @@ -# List track info from CD player. - -import cd - -def main(): - c = cd.open() - info = [] - while 1: - try: - info.append(c.gettrackinfo(len(info) + 1)) - except RuntimeError: - break - for i in range(len(info)): - start, total = info[i] - print 'Track', zfill(i+1), triple(start), triple(total) - -def triple((a, b, c)): - return zfill(a) + ':' + zfill(b) + ':' + zfill(c) - -def zfill(n): - s = `n` - return '0' * (2 - len(s)) + s - -main() diff --git a/Demo/sgi/cd/playcd.py b/Demo/sgi/cd/playcd.py deleted file mode 100755 index 44fa5a0697..0000000000 --- a/Demo/sgi/cd/playcd.py +++ /dev/null @@ -1,102 +0,0 @@ -# Play CD audio on speaker or headphones. - -callbacktypes = ['audio','pnum','index','ptime','atime','catalog','ident','control'] - -def playaudio(port, type, audio): - port.writesamps(audio) - -def prtrack(cdinfo, type, pnum): - if cdinfo.track[pnum] <> '': - print 'playing "' + cdinfo.track[pnum] + '"' - else: - print callbacktypes[type]+': '+`pnum` - -def callback(arg, type, data): - print callbacktypes[type]+': '+`data` - -def tcallback(arg, type, data): - print callbacktypes[type]+': '+triple(data) - -def triple((a, b, c)): - return zfill(a) + ':' + zfill(b) + ':' + zfill(c) - -def zfill(n): - s = `n` - return '0' * (2 - len(s)) + s - -def prtrackinfo(info): - for i in range(len(info)): - start, total = info[i] - print 'Track', zfill(i+1), triple(start), triple(total) - -statedict = ['ERROR', 'NODISK', 'READY', 'PLAYING', 'PAUSED', 'STILL'] - -def prstatus(status): - state, track, curtime, abstime, totaltime, first, last, \ - scsi_audio, cur_block, dummy = status - print 'Status:', - if 0 <= state < len(statedict): - print statedict[state] - else: - print state - print 'Track: ', track - print 'Time: ', triple(curtime) - print 'Abs: ', triple(abstime) - print 'Total: ', triple(totaltime) - print 'First: ', first - print 'Last: ', last - print 'SCSI: ', scsi_audio - print 'Block: ', cur_block - print 'Future:', dummy - -def main(): - import sys, readcd, al, AL, cd, cdplayer - verbose = 0 - r = readcd.Readcd() - prstatus(r.getstatus()) - prtrackinfo(r.gettrackinfo()) - cdinfo = cdplayer.Cdplayer(r.gettrackinfo()) - if cdinfo.title <> '': - print 'Title: "' + cdinfo.title + '"' - if cdinfo.artist <> '': - print 'Artist: ' + cdinfo.artist - for arg in sys.argv[1:]: - if arg == '-v': - verbose = 1 - continue - x = eval(arg) - try: - l = len(x) - r.appendstretch(x[0], x[1]) - except TypeError: - r.appendtrack(x) - try: - oldparams = [AL.OUTPUT_RATE, 0] - params = oldparams[:] - al.getparams(AL.DEFAULT_DEVICE, oldparams) - params[1] = AL.RATE_44100 - al.setparams(AL.DEFAULT_DEVICE, params) - config = al.newconfig() - config.setwidth(AL.SAMPLE_16) - config.setchannels(AL.STEREO) - port = al.openport('CD Player', 'w', config) - - for i in range(8): - r.setcallback(i, callback, None) - if verbose: - r.setcallback(cd.ptime, tcallback, None) - r.setcallback(cd.atime, tcallback, None) - else: - r.removecallback(cd.ptime) - r.removecallback(cd.atime) - r.setcallback(cd.pnum, prtrack, cdinfo) - r.setcallback(cd.audio, playaudio, port) - - data = r.play() - except KeyboardInterrupt: - status = r.getstatus() - print 'Interrupted at '+triple(status[2])+' into track '+ \ - `status[1]`+' (absolute time '+triple(status[3])+')' - al.setparams(AL.DEFAULT_DEVICE, oldparams) - -main() diff --git a/Demo/sgi/cd/recvcd.py b/Demo/sgi/cd/recvcd.py deleted file mode 100755 index e7496d1925..0000000000 --- a/Demo/sgi/cd/recvcd.py +++ /dev/null @@ -1,36 +0,0 @@ -# Receive UDP packets from sendcd.py and play them on the speaker or -# audio jack. - -import al, AL -from socket import * -from cd import DATASIZE - -PORT = 50505 # Must match the port in sendcd.py - -def main(): - s = socket(AF_INET, SOCK_DGRAM) - s.bind('', PORT) - - oldparams = [AL.OUTPUT_RATE, 0] - params = oldparams[:] - al.getparams(AL.DEFAULT_DEVICE, oldparams) - params[1] = AL.RATE_44100 - try: - al.setparams(AL.DEFAULT_DEVICE, params) - config = al.newconfig() - config.setwidth(AL.SAMPLE_16) - config.setchannels(AL.STEREO) - port = al.openport('CD Player', 'w', config) - - while 1: - data = s.recv(DATASIZE) - if not data: - print 'EOF' - break - port.writesamps(data) - except KeyboardInterrupt: - pass - - al.setparams(AL.DEFAULT_DEVICE, oldparams) - -main() diff --git a/Demo/sgi/cd/sendcd.py b/Demo/sgi/cd/sendcd.py deleted file mode 100755 index a6cf8e76a6..0000000000 --- a/Demo/sgi/cd/sendcd.py +++ /dev/null @@ -1,154 +0,0 @@ -# Read CD audio data from the SCSI CD player and send it as UDP -# packets to "recvcd.py" on another host. -# -# Usage: python sendcd.py [options] host [track | minutes seconds [frames]] -# -# Options: -# "-l" list track info and quit. -# "-s" display status and quit. -# -# Arguments: -# host host to send the audio data to (required unless -l or -s). -# track track number where to start; alternatively, -# min sec [frames] absolute address where to start; -# default is continue at current point according to status. - -import cd -import sys -from socket import * -import getopt - -PORT = 50505 # Must match the port in readcd.py - -def main(): - try: - optlist, args = getopt.getopt(sys.argv[1:], 'ls') - except getopt.error, msg: - sys.stderr.write(msg + '\n') - sys.exit(2) - - player = cd.open() - prstatus(player) - size = player.bestreadsize() - - if optlist: - for opt, arg in optlist: - if opt == '-l': - prtrackinfo(player) - elif opt == '-s': - prstatus(player) - return - - if not args: - sys.stderr.write('usage: ' + sys.argv[0] + ' host [track]\n') - sys.exit(2) - host, args = args[0], args[1:] - - sys.stdout.write('waiting for socket... ') - sys.stdout.flush() - port = socket(AF_INET, SOCK_DGRAM) - port.connect(host, PORT) - print 'socket connected' - - parser = cd.createparser() - parser.setcallback(cd.audio, audiocallback, port) - parser.setcallback(cd.pnum, pnumcallback, player) - parser.setcallback(cd.index, indexcallback, None) - ## cd.ptime: too many calls - ## cd.atime: too many calls - parser.setcallback(cd.catalog, catalogcallback, None) - parser.setcallback(cd.ident, identcallback, None) - parser.setcallback(cd.control, controlcallback, None) - - if len(args) >= 2: - if len(args) >= 3: - [min, sec, frame] = args[:3] - else: - [min, sec] = args - frame = '0' - min, sec, frame = eval(min), eval(sec), eval(frame) - print 'Seek to', triple(min, sec, frame) - dummy = player.seek(min, sec, frame) - elif len(args) == 1: - track = eval(args[0]) - print 'Seek to track', track - dummy = player.seektrack(track) - else: - min, sec, frame = player.getstatus()[3] - print 'Try to seek back to', triple(min, sec, frame) - try: - player.seek(min, sec, frame) - except RuntimeError: - print 'Seek failed' - - try: - while 1: - frames = player.readda(size) - if frames == '': - print 'END OF CD' - break - parser.parseframe(frames) - except KeyboardInterrupt: - print '[Interrupted]' - pass - -def prtrackinfo(player): - info = [] - while 1: - try: - info.append(player.gettrackinfo(len(info) + 1)) - except RuntimeError: - break - for i in range(len(info)): - start, total = info[i] - print 'Track', zfill(i+1), triple(start), triple(total) - -def audiocallback(port, type, data): -## sys.stdout.write('#') -## sys.stdout.flush() - port.send(data) - -def pnumcallback(player, type, data): - print 'pnum =', `data` - prstatus(player) - -def indexcallback(arg, type, data): - print 'index =', `data` - -def catalogcallback(arg, type, data): - print 'catalog =', `data` - -def identcallback(arg, type, data): - print 'ident =', `data` - -def controlcallback(arg, type, data): - print 'control =', `data` - -statedict = ['ERROR', 'NODISK', 'READY', 'PLAYING', 'PAUSED', 'STILL'] - -def prstatus(player): - state, track, curtime, abstime, totaltime, first, last, \ - scsi_audio, cur_block, dummy = player.getstatus() - print 'Status:', - if 0 <= state < len(statedict): - print statedict[state] - else: - print state - print 'Track: ', track - print 'Time: ', triple(curtime) - print 'Abs: ', triple(abstime) - print 'Total: ', triple(totaltime) - print 'First: ', first - print 'Last: ', last - print 'SCSI: ', scsi_audio - print 'Block: ', cur_block - print 'Future:', dummy - -def triple((a, b, c)): - return zfill(a) + ':' + zfill(b) + ':' + zfill(c) - -def zfill(n): - s = `n` - return '0' * (2 - len(s)) + s - -main() diff --git a/Demo/sgi/flp/tcache.fd b/Demo/sgi/flp/tcache.fd deleted file mode 100755 index 2ae91facd0..0000000000 --- a/Demo/sgi/flp/tcache.fd +++ /dev/null @@ -1,51 +0,0 @@ -Magic: 12321 - -Internal Form Definition File - (do not change) - -Number of forms: 2 - -=============== FORM =============== -Name: first -Width: 340.000000 -Height: 160.000000 -Number of Objects: 1 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 340.000000 160.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 10.000000 -lcol: 0 -label: -name: -callback: -argument: - -=============== FORM =============== -Name: second -Width: 150.000000 -Height: 400.000000 -Number of Objects: 1 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 150.000000 400.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 10.000000 -lcol: 0 -label: -name: -callback: -argument: - -============================== -create_the_forms diff --git a/Demo/sgi/flp/tcache.py b/Demo/sgi/flp/tcache.py deleted file mode 100755 index cf713fc325..0000000000 --- a/Demo/sgi/flp/tcache.py +++ /dev/null @@ -1,32 +0,0 @@ -# Test bug in caching of forms - -import sys -import os -import flp - -filename = 'tcache.fd' -cachename = filename + 's' - -def first(): - try: - os.unlink(cachename) - except os.error: - pass - first = flp.parse_form(filename, 'first') - -def second(): - forms = flp.parse_forms(filename) - k = forms.keys() - if 'first' in k and 'second' in k: - print 'OK' - else: - print 'BAD!', k - -def main(): - if sys.argv[1:]: - second() - else: - first() - print 'Now run the script again with an argument' - -main() diff --git a/Demo/sgi/flp/test_cb.fd b/Demo/sgi/flp/test_cb.fd deleted file mode 100755 index e83fd1f46b..0000000000 --- a/Demo/sgi/flp/test_cb.fd +++ /dev/null @@ -1,75 +0,0 @@ -Magic: 12321 - -Internal Form Definition File - (do not change) - -Number of forms: 1 - -=============== FORM =============== -Name: main_form -Width: 170.000000 -Height: 190.000000 -Number of Objects: 4 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 170.000000 190.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 11 -type: 0 -box: 10.000000 140.000000 150.000000 40.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Button 1 -name: button1 -callback: button1CB -argument: 0 - --------------------- -class: 11 -type: 0 -box: 10.000000 100.000000 150.000000 40.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Button 2 -name: button2 -callback: button2CB -argument: 0 - --------------------- -class: 11 -type: 6 -box: 10.000000 10.000000 150.000000 40.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: EXIT -name: exitbutton -callback: exitbuttonCB -argument: 0 - -============================== -create_the_forms diff --git a/Demo/sgi/flp/test_cb.py b/Demo/sgi/flp/test_cb.py deleted file mode 100755 index 41635036d3..0000000000 --- a/Demo/sgi/flp/test_cb.py +++ /dev/null @@ -1,61 +0,0 @@ -# -# Example 2 - Using fl in python with callbacks. -# -# The form is named 'main_form' and resides on file 'test_cb.fd'. -# It has three objects named button1, button2 and exitbutton. -# All buttons have callbacks with the same names as their corresponding -# buttons but with CB appended. -# -import fl # The forms library -import FL # Symbolic constants for the above -import flp # The module to parse .fd files -import sys - -# The following struct is created to hold the instance variables -# main_form, button1, button2 and exitbutton. - -class myform: - # - # The constructor parses and creates the form, but doesn't - # display it (yet). - def __init__(self, number): - # - # First we parse the form - parsetree = flp.parse_form('test_cb', 'main_form') - # - # Next we create it - - flp.create_full_form(self, parsetree) - - # And keep our number - self.number = number - - # - # The show function displays the form. It doesn't do any interaction, - # though. - def show(self): - self.main_form.show_form(FL.PLACE_SIZE, 1, '') - - # The callback functions - def button1CB(self, obj, arg): - print 'Button 1 pressed on form', self.number - - def button2CB(self, obj, arg): - print 'Button 2 pressed on form', self.number - - def exitbuttonCB(self, obj, arg): - print 'Ok, bye bye' - sys.exit(0) - -# -# The main program. Instantiate two variables of the forms class -# and interact with them. - -form1 = myform(1) -form2 = myform(2) - -form1.show() -form2.show() - -obj = fl.do_forms() -print 'do_forms() returned. This should not happen. obj=', obj diff --git a/Demo/sgi/flp/test_nocb.fd b/Demo/sgi/flp/test_nocb.fd deleted file mode 100755 index 4d3f7ef925..0000000000 --- a/Demo/sgi/flp/test_nocb.fd +++ /dev/null @@ -1,75 +0,0 @@ -Magic: 12321 - -Internal Form Definition File - (do not change) - -Number of forms: 1 - -=============== FORM =============== -Name: main_form -Width: 170.000000 -Height: 190.000000 -Number of Objects: 4 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 170.000000 190.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 11 -type: 0 -box: 10.000000 140.000000 150.000000 40.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Button 1 -name: button1 -callback: -argument: - --------------------- -class: 11 -type: 0 -box: 10.000000 100.000000 150.000000 40.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Button 2 -name: button2 -callback: -argument: - --------------------- -class: 11 -type: 6 -box: 10.000000 10.000000 150.000000 40.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: EXIT -name: exitbutton -callback: -argument: - -============================== -create_the_forms diff --git a/Demo/sgi/flp/test_nocb.py b/Demo/sgi/flp/test_nocb.py deleted file mode 100755 index 6346da3ed9..0000000000 --- a/Demo/sgi/flp/test_nocb.py +++ /dev/null @@ -1,45 +0,0 @@ -# -# Example 1 - Using fl in python without callbacks. -# -# The form is named 'main_form' and resides on file 'test_nocb.fd'. -# It has three objects named button1, button2 and exitbutton. -# -import fl # The forms library -import FL # Symbolic constants for the above -import flp # The module to parse .fd files -import sys - -# The following struct is created to hold the instance variables -# main_form, button1, button2 and exitbutton. - -class struct: pass -container = struct() - -# -# We now first parse the forms file - -parsetree = flp.parse_form('test_nocb', 'main_form') - -# -# Next we create it - -flp.create_full_form(container, parsetree) - -# -# And display it - -container.main_form.show_form(FL.PLACE_MOUSE, 1, '') - -# -# And interact until the exit button is pressed -while 1: - selected_obj = fl.do_forms() - if selected_obj == container.button1: - print 'Button 1 selected' - elif selected_obj == container.button2: - print 'Button 2 selected' - elif selected_obj == container.exitbutton: - print 'Ok, bye bye' - sys.exit(0) - else: - print 'do_forms() returned unknown object ', selected_obj diff --git a/Demo/sgi/gl/README b/Demo/sgi/gl/README deleted file mode 100644 index a89a502138..0000000000 --- a/Demo/sgi/gl/README +++ /dev/null @@ -1,35 +0,0 @@ -These demos run only on SGI machines and require the 'gl' built-in module. -The demonstrate the abilities of SGI's GL library as well as the ease of -GL programming in Python. Most demos require the Z-buffer (aka -24-bitplane) option. Press ESC to get out of any of them. - -backface.py Demonstrates the 'backface' GL function. - -kites.py Show 3 flying kites. Demonstrates the rendering speed - obtainable by Python programs. - -kunst.py Cute demo showing a ball suspended on four cables in - the central room of the CWI building. You can specify - three functions Fx(t), Fy(t), Fz(t) which define the - movement of the ball. Try something like sin(t), - cos(t), sin(2*t). - -mclock.py A colorful clock with more options than you can - remember. Works on 8-bit machines, but allows more - colors on 24-bit machines. See mclock.doc for more - info. - -mixing.py Demonstrates the effect of color mixing: through - frequent color switching it gives the effect of white - light. - -nurbs.py A simple demonstration of the 'nurbs' GL functions. - Press left mouse button to toggle surface trimming. - -zrgb.py Displays a 3-D Gouraud-shaded figure which can be moved - around with the mouse. - -glstdwin/ This is quite different: a partial STDWIN emulation - using GL! Requires only small changes to Python - programs that use STDWIN. Some features not yet - implemented, e.g., scroll bars. diff --git a/Demo/sgi/gl/backface.py b/Demo/sgi/gl/backface.py deleted file mode 100755 index 39929bef0d..0000000000 --- a/Demo/sgi/gl/backface.py +++ /dev/null @@ -1,140 +0,0 @@ -#! /usr/local/bin/python - -# backface -# -# draw a cube that can run with backface() turned on or off. -# cube is moved when LEFTMOUSE is pressed and mouse itself is moved. - -from gl import * -from DEVICE import * -from GL import * - -CUBE_SIZE = 200.0 -CUBE_OBJ = 1 - -def main () : - # - x = 0 - y = 0 - moveit = 0 - # - initialize() - # - while (1) : - # - while (qtest()) : - dev, val = qread() - # - if dev == ESCKEY : - backface(0) - return - # - elif dev == REDRAW : - reshapeviewport() - drawcube(x,y) - # - elif dev == LEFTMOUSE : - # - # LEFTMOUSE down - moveit = val - # - elif dev == BKEY : - backface(1) - drawcube(x,y) - # - elif dev == FKEY : - backface(0) - drawcube(x,y) - # - if moveit : - x = getvaluator(MOUSEX) - y = getvaluator(MOUSEY) - drawcube(x,y) - - -def initialize () : - foreground () - keepaspect (1, 1) - gid = winopen('backface') - winset(gid) - winconstraints() - # - doublebuffer() - gconfig() - shademodel(FLAT) - # - ortho(-1024.0, 1024.0, -1024.0, 1024.0, -1024.0, 1024.0) - # - qdevice(ESCKEY) - qdevice(REDRAW) - qdevice(LEFTMOUSE) - qdevice(BKEY) - qdevice(FKEY) - qenter(REDRAW,gid) - # - backface(1) - -# -# define a cube -def cube () : - # - # front face - pushmatrix() - translate(0.0,0.0,CUBE_SIZE) - color(RED) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # right face - pushmatrix() - translate(CUBE_SIZE, 0.0, 0.0) - rotate(900, 'y') - color(GREEN) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # back face - pushmatrix() - translate(0.0, 0.0, -CUBE_SIZE) - rotate(1800, 'y') - color(BLUE) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # left face - pushmatrix() - translate(-CUBE_SIZE, 0.0, 0.0) - rotate(-900, 'y') - color(CYAN) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # top face - pushmatrix() - translate(0.0, CUBE_SIZE, 0.0) - rotate(-900, 'x') - color(MAGENTA) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # bottom face - pushmatrix() - translate(0.0, -CUBE_SIZE, 0.0) - rotate(900, 'x') - color(YELLOW) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - -def drawcube(x,y) : - # - pushmatrix() - rotate(2*x, 'x') - rotate(2*y, 'y') - color(BLACK) - clear() - cube() - popmatrix() - swapbuffers() - - -main () diff --git a/Demo/sgi/gl/glinfo.py b/Demo/sgi/gl/glinfo.py deleted file mode 100755 index 2b6c356e1b..0000000000 --- a/Demo/sgi/gl/glinfo.py +++ /dev/null @@ -1,20 +0,0 @@ -#! /usr/local/bin/python - -# Print the values of all values that can be inquired with getgdesc(). -# See man getgdesc() for a description. - -import gl -import GL - -def main(): - names = [] - maxlen = 0 - for name in dir(GL): - if name[:3] == 'GD_': - names.append(name) - maxlen = max(maxlen, len(name)) - for name in names: - print name + (maxlen - len(name))*' ' + '=', - print gl.getgdesc(getattr(GL, name)) - -main() diff --git a/Demo/sgi/gl/glstdwin/fontchart.py b/Demo/sgi/gl/glstdwin/fontchart.py deleted file mode 100644 index 6b58f12a9c..0000000000 --- a/Demo/sgi/gl/glstdwin/fontchart.py +++ /dev/null @@ -1,34 +0,0 @@ -import stdwingl - -import stdwin -from stdwinevents import * - -def main(): - size = 12 - w = stdwin.open('Font chart ' + `size`) - while 1: - type, window, detail = stdwin.getevent() - if type == WE_CLOSE: - break - if type == WE_DRAW: - width, height = w.getwinsize() - d = w.begindrawing() - d.setsize(size) - h, v = 0, 0 - for c in range(32, 256): - ch = chr(c) - chw = d.textwidth(ch) - if h + chw > width: - v = v + d.lineheight() - h = 0 - if v >= height: - break - d.text((h, v), ch) - h = h + chw - del d - if type == WE_MOUSE_UP: - size = size + 1 - w.settitle('Font chart ' + `size`) - w.change((0, 0), (2000, 2000)) - -main() diff --git a/Demo/sgi/gl/glstdwin/glstdwdraw.py b/Demo/sgi/gl/glstdwin/glstdwdraw.py deleted file mode 100644 index 4ddc7a67cb..0000000000 --- a/Demo/sgi/gl/glstdwin/glstdwdraw.py +++ /dev/null @@ -1,135 +0,0 @@ -# Define drawing operations for GL stdwin - -import gl -import fm -from GL import LO_XOR, LO_SRC -from glstdwin import MASK - -class DrawingObject: - # - def _init(self, win): - self.fg = win._fg - self.bg = win._bg - self.font = win._font - self.size = win._size - self.width, self.height = win._area[1] - gl.winset(win._gid) - gl.color(self.fg) - return self - # - def setfont(self, fontname): - self.font = fm.findfont(fontname).scalefont(self.size) - # - def setsize(self, size): - ratio = float(size) / float(self.size) - self.size = size - self.font = self.font.scalefont(ratio) - # - def setfgcolor(self, color): - self.fg = color - gl.color(self.fg) - # - def setbgcolor(self, color): - self.bg = color - # - def cliprect(self, area): - #print 'cliprect', area - (left, top), (right, bottom) = area - gl.scrmask(left, right, self.height-bottom, self.height-top) - # - def noclip(self): - #print 'noclip()' - gl.scrmask(0, self.width, 0, self.height) - # - def paint(self, ((left, top), (right, bottom))): - gl.rectf(left, top, right, bottom) - # - def box(self, ((left, top), (right, bottom))): - #print 'box', ((left, top), (right, bottom)) - gl.rect(left, top, right, bottom) - # - def circle(self, (h, v), radius): - gl.circ(h, v, radius) - # - def elarc(self, center, (rh, rv), (a1, a2)): - pass # XXX - # - def erase(self, ((left, top), (right, bottom))): - #print 'erase', ((left, top), (right, bottom)) - gl.color(self.bg) - gl.rectf(left, top, right, bottom) - gl.color(self.fg) - # - def invert(self, ((left, top), (right, bottom))): - #print 'invert', ((h0, v0), (h1, v1)) - gl.logicop(LO_XOR) - gl.color(self.bg) - gl.rectf(left, top, right, bottom) - gl.color(self.fg) - gl.logicop(LO_SRC) - # - def line(self, (h0, v0), (h1, v1)): - #print 'line', ((h0, v0), (h1, v1)) - gl.bgnline() - gl.v2i(h0, v0) - gl.v2i(h1, v1) - gl.endline() - # - def xorline(self, (h0, v0), (h1, v1)): - #print 'xorline', ((h0, v0), (h1, v1)) - gl.logicop(LO_XOR) - gl.color(self.bg) - gl.bgnline() - gl.v2i(h0, v0) - gl.v2i(h1, v1) - gl.endline() - gl.color(self.fg) - gl.logicop(LO_SRC) - # - def point(self, (h, v)): - #print 'point', (h, v) - gl.bgnpoint() - gl.v2i(h, v) - gl.endpoint() - # - def text(self, (h, v), string): - #print 'text', ((h, v), string) - if h < 0: - # If the point is outside the window - # the whole string isn't drawn. - # Skip the beginning of the string. - # XXX What if the font is bigger than 20 pixels? - i, n = 0, len(string) - while h < -MASK and i < n: - h = h + self.font.getstrwidth(string[i]) - i = i + 1 - string = string[i:] - gl.cmov2(h, v + self.baseline()) - self.font.setfont() - fm.prstr(string) - # - def shade(self, (h, v), percent): - pass # XXX - # - def baseline(self): - (printermatched, fixed_width, xorig, yorig, xsize, ysize, \ - height, nglyphs) = self.font.getfontinfo() - return height - yorig - # - def lineheight(self): - (printermatched, fixed_width, xorig, yorig, xsize, ysize, \ - height, nglyphs) = self.font.getfontinfo() - return height - # - def textbreak(self, string, width): - # XXX Slooooow! - n = len(string) - nwidth = self.textwidth(string[:n]) - while nwidth > width: - n = n-1 - nwidth = self.textwidth(string[:n]) - return n - # - def textwidth(self, string): - return self.font.getstrwidth(string) - # diff --git a/Demo/sgi/gl/glstdwin/glstdwin.py b/Demo/sgi/gl/glstdwin/glstdwin.py deleted file mode 100644 index 22285548cf..0000000000 --- a/Demo/sgi/gl/glstdwin/glstdwin.py +++ /dev/null @@ -1,400 +0,0 @@ -# GL STDWIN -# -# See stdwingl for a convenient hack to use this instead of built-in stdwin -# without modifying your application, except for one line in the main file. -# -# Intrinsic differences with built-in stdwin (hard or impossible to fix): -# - Need to call w.close() to close a window !!! -# - Need to call m.close() to remove a menu !!! -# - Doesn't enforce the existence of at most one drawing object -# - No textedit package -# - No X11 selections -# -# Not yet implemented: -# - shade drawing -# - elliptical arc drawing (need to play with transformation) -# - more than one mouse button -# - scroll bars (need to redo viewport handling to get this) -# - partial redraws -# - dialog boxes -# - timer events -# - cursors -# -# Extra features: -# - color (for now, you need to know the colormap index) - - -import gl -import fm -from GL import * -from DEVICE import * -from stdwinevents import * - - -# Customizable constants -# -DEF_FONT = 'Times-Roman' # Default font -DEF_SIZE = 12 # Default font size (points) -MASK = 20 # Viewport minus scrmask - - -# A structure to hold global variables -# -class Struct: pass -G = Struct() -# -G.queue = [] # Pending STDWIN events -G.drawqueue = [] # Windows that need WE_REDRAW -G.windowmap = {} # Map window id to window object -G.windowmap['0'] = None # For convenience -G.focus = None # Input focus -G.fg = BLACK # Foreground color -G.bg = WHITE # Background color -G.def_size = 0, 0 # Default window size -G.def_pos = 0, 0 # Default window position -# -G.size = DEF_SIZE -G.font = fm.findfont(DEF_FONT).scalefont(G.size) - - -# Initialize GL -# -gl.foreground() -gl.noport() -dummygid = gl.winopen('') - -# Ask for all sorts of events -# -# Both REDRAW (= resize and/or redraw!) and INPUTCHANGE are implicitly queued -#qdevice(REDRAW) -#qdevice(INPUTCHANGE) -# -# Keyboard -gl.qdevice(KEYBD) -gl.qdevice(LEFTARROWKEY) -gl.qdevice(RIGHTARROWKEY) -gl.qdevice(UPARROWKEY) -gl.qdevice(DOWNARROWKEY) -gl.qdevice(LEFTALTKEY) -gl.qdevice(RIGHTALTKEY) -# -# Mouse -gl.qdevice(LEFTMOUSE) -#gl.qdevice(MIDDLEMOUSE) -gl.qdevice(RIGHTMOUSE) # Menu button -# NB MOUSEX, MOUSEY events are queued on button down -# -# Window close requests -gl.qdevice(WINQUIT) -gl.qdevice(WINSHUT) -# -# These aren't needed -#gl.qdevice(TIMER0) -#gl.qdevice(WINFREEZE) -#gl.qdevice(WINTHAW) -#gl.qdevice(REDRAWICONIC) - - -# STDWIN: create a new window -# -def open(title): - h, v = G.def_pos - width, height = G.def_size - if h > 0 or v > 0: - # Choose arbitrary defaults - if h < 0: h = 10 - if v < 0: v = 30 - if width <= 0: width = 400 - if height <= 0: height = 300 - gl.prefposition(h, h+width, 1024-v, 1024-v-height) - elif width > 0 or height > 0: - if width <= 0: width = 400 - if height <= 0: height = 300 - gl.prefsize(width, height) - from glstdwwin import WindowObject - win = WindowObject()._init(title) - G.windowmap[`win._gid`] = win - return win - - -# STDWIN: set default initial window position (0 means use default) -# -def setdefwinpos(h, v): - G.def_pos = h, v - - -# STDWIN: set default window size (0 means use default) -# -def setdefwinsize(width, height): - G.def_size = width, height - - -# STDWIN: beep or ring the bell -# -def fleep(): - gl.ringbell() - - -# STDWIN: set default foreground color -# -def setfgcolor(color): - G.fg = color - - -# STDWIN: set default background color -# -def setbgcolor(color): - G.bg = color - - -# STDWIN: get default foreground color -# -def getfgcolor(): - return G.fgcolor - - -# STDWIN: get default background color -# -def getbgcolor(): - return G.bgcolor - - -# Table mapping characters to key codes -# -key2code = key = {} -key['A'] = AKEY -key['B'] = BKEY -key['C'] = CKEY -key['D'] = DKEY -key['E'] = EKEY -key['F'] = FKEY -key['G'] = GKEY -key['H'] = HKEY -key['I'] = IKEY -key['J'] = JKEY -key['K'] = KKEY -key['L'] = LKEY -key['M'] = MKEY -key['N'] = NKEY -key['O'] = OKEY -key['P'] = PKEY -key['Q'] = QKEY -key['R'] = RKEY -key['S'] = SKEY -key['T'] = TKEY -key['U'] = UKEY -key['V'] = VKEY -key['W'] = WKEY -key['X'] = XKEY -key['Y'] = YKEY -key['Z'] = ZKEY -key['0'] = ZEROKEY -key['1'] = ONEKEY -key['2'] = TWOKEY -key['3'] = THREEKEY -key['4'] = FOURKEY -key['5'] = FIVEKEY -key['6'] = SIXKEY -key['7'] = SEVENKEY -key['8'] = EIGHTKEY -key['9'] = NINEKEY -del key -# -code2key = {} -codelist = [] -for key in key2code.keys(): - code = key2code[key] - code2key[`code`] = key - codelist.append(code) -del key - - -# STDWIN: wait for the next event -# -commands = {} -commands['\r'] = WC_RETURN -commands['\b'] = WC_BACKSPACE -commands['\t'] = WC_TAB -# -def getevent(): - while 1: - # - # Get next event from the processed queue, if any - # - if G.queue: - event = G.queue[0] - del G.queue[0] - #print 'getevent from queue -->', event - return event - # - # Get next event from the draw queue, if any, - # but only if there is nothing in the system queue. - # - if G.drawqueue and not gl.qtest(): - win = G.drawqueue[0] - del G.drawqueue[0] - gl.winset(win._gid) - gl.color(win._bg) - gl.clear() - event = WE_DRAW, win, win._area - #print 'getevent from drawqueue -->', event - return event - # - # Get next event from system queue, blocking if necessary - # until one is available. - # Some cases immediately return the event, others do nothing - # or append one or more events to the processed queue. - # - dev, val = gl.qread() - # - if dev == REDRAW: - win = G.windowmap[`val`] - old_area = win._area - win._fixviewport() - win._needredraw() - if old_area <> win._area: - #print 'getevent --> WE_SIZE' - return WE_SIZE, win, None - elif dev == KEYBD: - if val == 3: - raise KeyboardInterrupt # Control-C in window - character = chr(val) - if commands.has_key(character): - return WE_COMMAND, G.focus, commands[character] - return WE_CHAR, G.focus, character - elif dev == LEFTARROWKEY: - if val: - return WE_COMMAND, G.focus, WC_LEFT - elif dev == RIGHTARROWKEY: - if val: - return WE_COMMAND, G.focus, WC_RIGHT - elif dev == UPARROWKEY: - if val: - return WE_COMMAND, G.focus, WC_UP - elif dev == DOWNARROWKEY: - if val: - return WE_COMMAND, G.focus, WC_DOWN - elif dev in (LEFTALTKEY, RIGHTALTKEY): - if val: - for code in codelist: - gl.qdevice(code) - else: - for code in codelist: - gl.unqdevice(code) - elif dev in codelist: - if val: - event = G.focus._doshortcut(code2key[`dev`]) - if event: - return event - elif dev == LEFTMOUSE: - G.mousex = gl.getvaluator(MOUSEX) - G.mousey = gl.getvaluator(MOUSEY) - if val: - type = WE_MOUSE_DOWN - gl.qdevice(MOUSEX) - gl.qdevice(MOUSEY) - else: - type = WE_MOUSE_UP - gl.unqdevice(MOUSEX) - gl.unqdevice(MOUSEY) - return _mouseevent(type) - elif dev == MOUSEX: - G.mousex = val - return _mouseevent(WE_MOUSE_MOVE) - elif dev == MOUSEY: - G.mousey = val - return _mouseevent(WE_MOUSE_MOVE) - elif dev == RIGHTMOUSE: # Menu button press/release - if val: # Press - event = G.focus._domenu() - if event: - return event - elif dev == INPUTCHANGE: - if G.focus: - G.queue.append(WE_DEACTIVATE, G.focus, None) - G.focus = G.windowmap[`val`] - if G.focus: - G.queue.append(WE_ACTIVATE, G.focus, None) - elif dev in (WINSHUT, WINQUIT): - return WE_CLOSE, G.windowmap[`val`], None - else: - print '*** qread() --> dev:', dev, 'val:', val - -# Helper routine to construct a mouse (up, move or down) event -# -def _mouseevent(type): - gl.winset(G.focus._gid) - orgx, orgy = gl.getorigin() - sizex, sizey = gl.getsize() - x = G.mousex - orgx - y = G.mousey - orgy - return type, G.focus, ((x, sizey-y), 1, 0, 0) - - - - -# STDWIN: text measuring functions - -def baseline(): - (printermatched, fixed_width, xorig, yorig, xsize, ysize, \ - height, nglyphs) = G.font.getfontinfo() - return height - yorig - -def lineheight(): - (printermatched, fixed_width, xorig, yorig, xsize, ysize, \ - height, nglyphs) = G.font.getfontinfo() - return height - -def textbreak(string, width): - # XXX Slooooow! - n = len(string) - nwidth = textwidth(string[:n]) - while nwidth > width: - n = n-1 - nwidth = textwidth(string[:n]) - return n - -def textwidth(string): - return G.font.getstrwidth(string) - - -# STDWIN: set default font and size - -def setfont(fontname): - G.font = fm.findfont(fontname).scalefont(G.size) - -def setsize(size): - ratio = float(size) / float(G.size) - G.size = size - G.font = G.font.scalefont(ratio) - - -# Utility functions - -# Exclusive-or of two BYTES -# -def xor(x, y): - a = bits(x) - b = bits(y) - c = [0, 0, 0, 0, 0, 0, 0, 0] - for i in range(8): - c[i] = (a[i] + b[i]) % 2 - return stib(c) - -# Return the bits of a byte as a list of 8 integers -# -def bits(x): - b = [0, 0, 0, 0, 0, 0, 0, 0] - for i in range(8): - x, b[i] = divmod(x, 2) - return b - -# Convert a list of 8 integers (0|1) to a byte -# -def stib(b): - x = 0 - shift = 1 - for i in range(8): - x = x + b[i]*shift - shift = shift*2 - return x diff --git a/Demo/sgi/gl/glstdwin/glstdwmenu.py b/Demo/sgi/gl/glstdwin/glstdwmenu.py deleted file mode 100644 index dd6d90b6ea..0000000000 --- a/Demo/sgi/gl/glstdwin/glstdwmenu.py +++ /dev/null @@ -1,62 +0,0 @@ -# Define menu operations for GL stdwin - -import gl -from glstdwin import key2code - -class MenuObject: - # - def _init(self, win, title): - self._win = win - self._title = title - self._items = [] - return self - # - def close(self): - self._win.remove(self) - del self._win - # - def additem(self, *args): - if len(args) == 2: - text, shortcut = args - elif len(args) == 1: - text, shortcut = args[0], None - else: - raise TypeError, 'arg count' - self._items.append([text, shortcut, 1, 0]) - # - def setitem(self, i, text): - self._items[i][0] = text - # - def enable(self, i, flag): - self._items[i][2] = flag - # - def check(self, i, flag): - self._items[i][3] = flag - # - def _makepup(self, firstitem): - pup = gl.newpup() - if self._title: - gl.addtopup(pup, self._title + '%t', 0) - for item in self._items: - text = item[0] - if not item[2]: # Disabled - text = ' ( ' + text + ' )%x-1' - else: - if item[3]: # Check mark - text = '-> ' + text - else: - text = ' ' + text - if key2code.has_key(item[1]): - text = text + ' [Alt-' + item[1] + ']' - text = text + '%x' + `firstitem` - gl.addtopup(pup, text, 0) - firstitem = firstitem + 1 - return pup - # - def _checkshortcut(self, char): - for i in range(len(self._items)): - item = self._items[i] - if item[2] and item[1] == char: - return i - return -1 - # diff --git a/Demo/sgi/gl/glstdwin/glstdwwin.py b/Demo/sgi/gl/glstdwin/glstdwwin.py deleted file mode 100644 index b880b9a1f9..0000000000 --- a/Demo/sgi/gl/glstdwin/glstdwwin.py +++ /dev/null @@ -1,139 +0,0 @@ -# Define window operations for STDWIN - -import gl -from stdwinevents import * -from glstdwin import G # Global variables -from glstdwin import MASK # Tunable constant - -class WindowObject: - # - def _init(self, title): - self._docsize = (0, 0) - self._fg = G.fg - self._bg = G.bg - self._title = title - self._font = G.font - self._size = G.size - self._menus = [] - self._gid = gl.winopen(title) - gl.winconstraints() # To remove prefsize() effect - self._fixviewport() - self._needredraw() - return self - # - def close(self): - del G.windowmap[`self._gid`] - gl.winclose(self._gid) - self._gid = 0 - # - def _needredraw(self): - if self in G.drawqueue: - G.drawqueue.remove(self) - G.drawqueue.append(self) - # - def begindrawing(self): - from glstdwdraw import DrawingObject - return DrawingObject()._init(self) - # - def change(self, area): - self._needredraw() - # XXX Should record the area to be drawn? - # - def gettitle(self): - return self._title - # - def getdocsize(self): - return self._docsize - # - def getorigin(self): - return self._area[0] - # - def getwinsize(self): - return self._area[1] - # - def scroll(self, area, by): - # XXX ought to use gl.rectcopy() - if by <> (0, 0): - self.change(area) - # - def setdocsize(self, docsize): - self._docsize = docsize - # - def setorigin(self, origin): - pass # XXX - # - def settimer(self, decisecs): - pass # XXX - # - def settitle(self, title): - self._title = title - gl.wintitle(title) - # - def show(self, area): - pass # XXX - # - def _fixviewport(self): - # - # Called after redraw or resize, and initially. - # - # Fix the coordinate system so that (0, 0) is top left, - # units are pixels, and positive axes point right and down. - # - # Make the viewport slightly larger than the window, - # and set the screenmask exactly to the window; this - # help fixing character clipping. - # - # Set self._area to the window rectangle in STDWIN coords. - # - gl.winset(self._gid) - gl.reshapeviewport() - x0, x1, y0, y1 = gl.getviewport() - width, height = x1-x0, y1-y0 - gl.viewport(x0-MASK, x1+MASK, y0-MASK, y1+MASK) - gl.scrmask(x0, x1, y0, y1) - gl.ortho2(-MASK, width+MASK, height+MASK, -MASK) - self._area = (0, 0), (width, height) - # - def menucreate(self, title): - from glstdwmenu import MenuObject - menu = MenuObject()._init(self, title) - self._menus.append(menu) - return menu - # - def _domenu(self): - if not self._menus: - return None - if len(self._menus) == 1: - pup = self._menus[0]._makepup(0) - val = gl.dopup(pup) - gl.freepup(pup) - if val < 0: - return None - return WE_MENU, self, (self._menus[0], val) - # - # More than one menu: use nested menus. - # - pups = [] - firstitem = 0 - for menu in self._menus: - pups.append(menu._makepup(firstitem)) - firstitem = firstitem + 100 - pup = gl.newpup() - for i in range(len(self._menus)): - gl.addtopup(pup, self._menus[i]._title + '%m', pups[i]) - val = gl.dopup(pup) - gl.freepup(pup) - for pup in pups: - gl.freepup(pup) - if val < 0: - return None - i_menu, i_item = divmod(val, 100) - return WE_MENU, self, (self._menus[i_menu], i_item) - # - def _doshortcut(self, char): - for menu in self._menus: - i = menu._checkshortcut(char) - if i >= 0: - return WE_MENU, self, (menu, i) - return None - # diff --git a/Demo/sgi/gl/glstdwin/stdwingl.py b/Demo/sgi/gl/glstdwin/stdwingl.py deleted file mode 100644 index 442759319b..0000000000 --- a/Demo/sgi/gl/glstdwin/stdwingl.py +++ /dev/null @@ -1,10 +0,0 @@ -# If you put 'import stdwin_gl' in front of the main program of a program -# using stdwin (before it has a chance to import the real stdwin!), -# it will use glstdwin and think it is stdwin. - -import sys -if sys.modules.has_key('stdwin'): - raise RuntimeError, 'too late -- stdwin has already been imported' - -import glstdwin -sys.modules['stdwin'] = glstdwin diff --git a/Demo/sgi/gl/glstdwin/tcolor.py b/Demo/sgi/gl/glstdwin/tcolor.py deleted file mode 100644 index d1c49e115d..0000000000 --- a/Demo/sgi/gl/glstdwin/tcolor.py +++ /dev/null @@ -1,43 +0,0 @@ -# Try colors -- display all 256 possible colors, with their color index - -import stdwingl - -import stdwin -from stdwinevents import * - -NROWS = 16 -NCOLS = 16 - -def main(): - stdwin.setdefwinsize(NCOLS * stdwin.textwidth('12345'), \ - NROWS * stdwin.lineheight() * 3) - w = stdwin.open('TestColors') - # - while 1: - type, window, detail = stdwin.getevent() - if type == WE_CLOSE: - print 'Bye.' - break - elif type == WE_SIZE: - w.change((0,0), (10000, 10000)) - elif type == WE_DRAW: - width, height = w.getwinsize() - d = w.begindrawing() - for row in range(NROWS): - for col in range(NCOLS): - color = row*NCOLS + col - d.setfgcolor(color) - p = col*width/NCOLS, row*height/NROWS - q = (col+1)*width/NCOLS, \ - (row+1)*height/NROWS - d.paint((p, q)) - d.setfgcolor(0) - d.box((p, q)) - d.text(p, `color`) - p = p[0] , p[1]+ d.lineheight() - d.setfgcolor(7) - d.text(p, `color`) - del d - # - -main() diff --git a/Demo/sgi/gl/glstdwin/tglsw.py b/Demo/sgi/gl/glstdwin/tglsw.py deleted file mode 100644 index 8854e98812..0000000000 --- a/Demo/sgi/gl/glstdwin/tglsw.py +++ /dev/null @@ -1,70 +0,0 @@ -import sys - -if len(sys.argv) < 2: - import stdwingl - color = 1 - needclose = 1 -else: - color = 0 - needclose = 0 - -import stdwin -import time -from stdwinevents import * -from GL import BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE - -def main(): - # - stdwin.setdefwinsize(300, 300) - stdwin.setdefwinpos(0, 0) - if color: stdwin.setbgcolor(YELLOW) - w1 = stdwin.open('Hello, world') - w1.box = (10, 10), (90, 90) - # - stdwin.setdefwinsize(0, 0) - stdwin.setdefwinpos(50, 50) - if color: stdwin.setbgcolor(GREEN) - w2 = stdwin.open('Second window') - w2.box = (10, 10), (90, 90) - # - while w1 or w2: - type, window, detail = stdwin.getevent() - if type == WE_DRAW: - d = window.begindrawing() - if window == w1: - if color: d.setfgcolor(BLACK) - d.box(((50, 50), (250, 250))) - if color: d.setfgcolor(RED) - d.cliprect(((50, 50), (250, 250))) - d.paint(w1.box) - d.noclip() - if color: d.setfgcolor(BLUE) - d.line((0, 0), w1.box[0]) - elif window == w2: - if color: d.setfgcolor(WHITE) - d.box(w2.box) - if color: d.setfgcolor(BLACK) - d.text(w2.box[0], 'Hello world') - else: - print 'Strange draw???', window, detail - del d - elif type == WE_CLOSE: - if needclose: window.close() - if window == w1: - w1 = None - elif window == w2: - w2 = None - else: - print 'weird close event???', window, detail - elif type in (WE_MOUSE_DOWN, WE_MOUSE_MOVE, WE_MOUSE_UP): - h, v = detail[0] - window.box = (h, v), (h+80, v+80) - window.change(((0,0), (2000, 2000))) - elif type == WE_CHAR: - print 'character', `detail` - else: - print type, window, detail - # - -main() -print 'Done.' diff --git a/Demo/sgi/gl/glstdwin/tmenu.py b/Demo/sgi/gl/glstdwin/tmenu.py deleted file mode 100644 index 233edae3c1..0000000000 --- a/Demo/sgi/gl/glstdwin/tmenu.py +++ /dev/null @@ -1,44 +0,0 @@ -# Test menus - -import stdwingl - -import stdwin -from stdwinevents import * - -def main(): - w = stdwin.open('TestMenus') - # - items1 = 'Aap', 'Noot', 'Mies' - m1 = w.menucreate('Menu-1') - for item in items1: - m1.additem(item, item[0]) - # - items2 = 'Wim', 'Zus', 'Jet', 'Teun', 'Vuur' - m2 = w.menucreate('Menu-2') - for item in items2: - m2.additem(item, `len(item)`) - # - m1.enable(1, 0) - m2.check(1, 1) - # - while 1: - type, window, detail = stdwin.getevent() - if type == WE_CLOSE: - break - elif type == WE_DRAW: - d = w.begindrawing() - d.box(((50,50), (100,100))) - del d - elif type == WE_MENU: - mp, i = detail - if mp == m1: - print 'Choice:', items1[i] - elif mp == m2: - print 'Choice:', items2[i] - else: - print 'Not one of my menus!' - elif type == WE_CHAR: - print 'Character', `detail` - # - -main() diff --git a/Demo/sgi/gl/kites.py b/Demo/sgi/gl/kites.py deleted file mode 100755 index 6e3dea6f49..0000000000 --- a/Demo/sgi/gl/kites.py +++ /dev/null @@ -1,194 +0,0 @@ -#! /usr/local/bin/python - -# *** This only works correctly on a 24 bit-plane machine. *** -# -# A simple Python program that tests the some parts of the -# GL library. It shows the speed that can be obtained when -# doing simple graphics. -# -# The bottleneck in this program is NOT Python but the graphics -# engine; i.e Python can feed the graphics pipeline fast enough -# on the 4D/25G. -# -# This program show 3 kites flying around the screen. It uses -# -# * bgnpolygon, endpolygon -# * v3, n3 -# * lmdef, lmbind -# -# Usage : -# -# ESC -> exit program -# MOUSE3 -> freeze toggle -# MOUSE2 -> one step (use this in freeze state) - -from GL import * -from gl import * -import DEVICE -from math import * - -# -# viewobj : sets the rotation, translation and scaling -# set appropiate material, call drawobject() -# -def viewobj (r, s, t, mat) : - pushmatrix() - rot (r * 10.0, 'X') - rot (r * 10.0, 'Y') - rot (r * 10.0, 'Z') - scale (s[0], s[1], s[2]) - translate (t[0], t[1], t[2]) - lmbind(MATERIAL, mat) - drawobject() - popmatrix() - -# -# makeobj : the contructor of the object -# -def mkobj () : - v0 = (-5.0 ,0.0, 0.0) - v1 = (0.0 ,5.0, 0.0) - v2 = (5.0 ,0.0, 0.0) - v3 = (0.0 ,2.0, 0.0) - n0 = (sqrt(2.0)/2.0, sqrt(2.0)/2.0, 0.0) - vn = ((v0, n0), (v1, n0), (v2, n0), (v3, n0)) - # - return vn - -# -# the object itself as an array of vertices and normals -# -kite = mkobj () - -# -# drawobject : draw a triangle. with bgnpolygon -# -def drawobject () : - # - bgnpolygon() - vnarray (kite) - endpolygon() - -# -# identity matrix -# -idmat=[1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0] - -# -# the rgb-value of light-blue -# -LightBlue = (43,169,255) - -# -# the different materials. -# -m1=[SPECULAR,0.0,0.0,0.6,DIFFUSE,0.0,0.0,0.8,SHININESS,20.0,LMNULL] -m2=[SPECULAR,0.8,0.0,0.1,DIFFUSE,0.8,0.0,0.3,SHININESS,120.0,LMNULL] -m3=[SPECULAR,0.0,1.0,0.0,DIFFUSE,0.0,0.6,0.0,SHININESS,120.0,LMNULL] - -# -# lightsources -# -light1 = [LCOLOR,1.0,1.0,1.0,POSITION,15.0,15.0,0.0,1.0,LMNULL] -light2 = [LCOLOR,1.0,1.0,1.0,POSITION,-15.0,15.0,0.0,1.0,LMNULL] - -# -# the lightmodel -# -model = [AMBIENT,0.2,0.2,0.2,LMNULL] - -# -# initgl : opens the window, configures the pipeline to 2buf and zbuf, -# sets the viewing, defines and binds the materials -# -def initgl () : - # - # open window - # - foreground () - keepaspect (1, 1) - prefposition (100, 500, 100, 500) - w = winopen ('PYTHON lights') - keepaspect (1, 1) - winconstraints() - # - # configure pipeline (zbuf, 2buf, GOURAUD and RGBmode) - # - zbuffer (1) - doublebuffer () - shademodel (GOURAUD) - RGBmode () - gconfig () - # - # define and bind materials (set perspective BEFORE loadmat !) - # - mmode(MVIEWING) - perspective (900, 1.0, 1.0, 20.0) - loadmatrix(idmat) - lmdef(DEFMATERIAL, 1, m1) - lmdef(DEFMATERIAL, 2, m2) - lmdef(DEFMATERIAL, 3, m3) - lmdef(DEFLIGHT, 1, light1) - lmdef(DEFLIGHT, 2, light2) - lmdef(DEFLMODEL, 1, model) - lmbind(LIGHT0,1) - lmbind(LIGHT1,2) - lmbind(LMODEL,1) - # - # set viewing - # - lookat (0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0) - # - # ask for the REDRAW and ESCKEY events - # - qdevice(DEVICE.MOUSE3) - qdevice(DEVICE.MOUSE2) - qdevice(DEVICE.REDRAW) - qdevice(DEVICE.ESCKEY) - -# -# GoForIT : use 2buf to redraw the object 2n times. index i is used as -# the (smoothly changing) rotation angle -# -def GoForIt(i) : - freeze = 1 - while 1 : - if freeze <> 0 : - i = i + 1 - # - # clear z-buffer and clear background to light-blue - # - zclear() - c3i (LightBlue) - clear() - # - # draw the 3 traiangles scaled above each other. - # - viewobj(float(i),[1.0,1.0,1.0],[1.0,1.0,1.0],1) - viewobj(float(i),[0.75,0.75,0.75],[0.0,2.0,2.0],2) - viewobj(float(i),[0.5,0.5,0.5],[0.0,4.0,4.0],3) - # - swapbuffers() - # - if qtest() <> 0 : - dev, val = qread() - if dev == DEVICE.ESCKEY : - break - elif dev == DEVICE.REDRAW : - reshapeviewport () - elif dev == DEVICE.MOUSE3 and val <> 0 : - freeze = 1 - freeze - elif dev == DEVICE.MOUSE2 and val <> 0 : - i = i + 1 - - -# the main program -# -def main () : - initgl () - GoForIt (0) - -# -# exec main -# -main () diff --git a/Demo/sgi/gl/kunst.py b/Demo/sgi/gl/kunst.py deleted file mode 100755 index 2055e52e83..0000000000 --- a/Demo/sgi/gl/kunst.py +++ /dev/null @@ -1,426 +0,0 @@ -#! /usr/local/bin/python -# Simulate the artwork in the hall. -# Jack Jansen, Feb 91. - -from gl import * -from GL import * -from math import * -from DEVICE import * -import sys -import __main__ -main_dict = __main__.__dict__ - -SPOTDIRECTION = 103 -SPOTLIGHT = 104 - -# -# Make a cylinder paralel with the Z axis with center (X,Y,0) -# and radius 1 -def mkcyl(nslice, nparts, docircle): - cyl = [] - step = 2.0 / float(nslice) - z = -1.0 - for i in range(nslice): - cyl.append(mkslice(z, z+step, nparts, docircle)) - z = z + step - return drawcylinder(cyl) -# -# Make one part of a cylinder -# -def mkslice(z1, z2, nparts, docircle): - if docircle: - w1 = z1 - w2 = z2 - w1 = sqrt(1.0-w1*w1) - w2 = sqrt(1.0-w2*w2) - normalz = 1.0 - else: - w1 = 1.0 - w2 = 1.0 - normalz = 0.0 - slice = [] - step = (2.0*pi)/float(nparts) - angle = 0.0 - for i in range(nparts+1): - vx = cos(angle) - vy = sin(angle) - slice.append( ((vx*w1,vy*w1,z1), (vx*w1, vy*w1, z1*normalz)) ) - slice.append( ((vx*w2,vy*w2,z2), (vx*w2, vy*w2, z2*normalz)) ) - angle = angle + step - return slice -# -# Drawcylinder : draw the cylinder -# -class struct: pass -curobj = struct() -curobj.curobj = 1 -def drawcylinder(cyl): - obj = curobj.curobj - curobj.curobj = curobj.curobj+1 - makeobj(obj) - for slice in cyl: - bgntmesh() - vnarray(slice) - endtmesh() - closeobj() - return obj -# -def drawnormals(cyl): - for slice in cyl: - for triang in slice: - bgnline() - v3f(triang[0]) - v3f(triang[0][0] + triang[1][0], triang[0][1] + triang[1][1], triang[0][2] + triang[1][2]) - endline() -def drawfloors(): - obj = curobj.curobj - curobj.curobj = curobj.curobj+1 - makeobj(obj) - bgnpolygon() - v3i(4,6,-6) - v3i(-6,6,-6) - v3i(-6,-6,-6) - v3i(4,-6,-6) - endpolygon() - for floor in range(3): - pos = -1 + 5*floor - bgnpolygon() - v3i(4,4,pos) - v3i(-6,4,pos) - v3i(-6,6,pos) - v3i(4,6,pos) - endpolygon() - bgnpolygon() - v3i(-4,4,pos) - v3i(-4,-4,pos) - v3i(-6,-4,pos) - v3i(-6,4,pos) - endpolygon() - bgnpolygon() - v3i(-6,-4,pos) - v3i(-6,-6,pos) - v3i(4,-6,pos) - v3i(4,-4,pos) - endpolygon() - closeobj() - return obj -def drawdoors(): - obj = curobj.curobj - curobj.curobj = curobj.curobj+1 - makeobj(obj) - for floor in range(3): - pos = -1+5*floor - bgnpolygon() - v3i(-2,6,pos) - v3i(-2,6,pos+3) - v3i(0,6,pos+3) - v3i(0,6,pos) - endpolygon() - closeobj() - return obj -def drawrailing(): - obj = curobj.curobj - curobj.curobj = curobj.curobj+1 - makeobj(obj) - for floor in range(3): - pos = -1 + 5*floor - bgnpolygon() - v3i(4,4,pos) - v3i(4,4,pos-1) - v3i(-4,4,pos-1) - v3i(-4,4,pos) - endpolygon() - bgnpolygon() - v3i(-4,4,pos) - v3i(-4,4,pos-1) - v3i(-4,-4,pos-1) - v3i(-4,-4,pos) - endpolygon() - bgnpolygon() - v3i(-4,-4,pos) - v3i(-4,-4,pos-1) - v3i(4,-4,pos-1) - v3i(4,-4,pos) - endpolygon() - closeobj() - return obj -def drawwalls(): - obj = curobj.curobj - curobj.curobj = curobj.curobj+1 - makeobj(obj) - bgnpolygon() - v3i(4,6,-6) - v3i(4,6,18) - v3i(-6,6,18) - v3i(-6,6,-6) - endpolygon() - bgnpolygon() - v3i(-6,6,-6) - v3i(-6,6,18) - v3i(-6,-6,18) - v3i(-6,-6,-6) - endpolygon() - bgnpolygon() - v3i(-6,-6,-6) - v3i(-6,-6,18) - v3i(4,-6,18) - v3i(4,-6,-6) - endpolygon() - bgnpolygon() - v3i(4,-6,-6) - v3i(4,-6,18) - v3i(4,4,18) - v3i(4,4,-6) - endpolygon() - closeobj() - return obj -def axis(): - bgnline() - cpack(0xff0000) - v3i(-1,0,0) - v3i(1,0,0) - v3f(1.0, 0.1, 0.1) - endline() - bgnline() - cpack(0xff00) - v3i(0,-1,0) - v3i(0,1,0) - v3f(0.1, 1.0, 0.1) - endline() - bgnline() - cpack(0xff) - v3i(0,0,-1) - v3i(0,0,1) - v3f(0.1,0.1,1.0) - endline() -# -green_velvet = [ DIFFUSE, 0.05, 0.4, 0.05, LMNULL] -silver = [ DIFFUSE, 0.3, 0.3, 0.3, SPECULAR, 0.9, 0.9, 0.95, \ - SHININESS, 40.0, LMNULL] -floormat = [ AMBIENT, 0.5, 0.25, 0.15, DIFFUSE, 0.5, 0.25, 0.15, SPECULAR, 0.6, 0.3, 0.2, SHININESS, 20.0, LMNULL] -wallmat = [ DIFFUSE, 0.4, 0.2, 0.1, AMBIENT, 0.4, 0.20, 0.10, SPECULAR, 0.0, 0.0, 0.0, SHININESS, 20.0, LMNULL] -offwhite = [ DIFFUSE, 0.8, 0.8, 0.6, AMBIENT, 0.8, 0.8, 0.6, SPECULAR, 0.9, 0.9, 0.9, SHININESS, 30.0, LMNULL] -doormat = [ DIFFUSE, 0.1, 0.2, 0.5, AMBIENT, 0.2, 0.4, 1.0, SPECULAR, 0.2, 0.4, 1.0, SHININESS, 60.0, LMNULL] - -toplight = [ LCOLOR, 1.0, 1.0, 0.5, \ - POSITION, 0.0, 0.0, 11.0, 1.0, LMNULL] -floor1light = [ LCOLOR, 1.0, 1.0, 1.0, POSITION, 3.9, -3.9, 0.0, 1.0, \ - SPOTDIRECTION, 1.0, 1.0, 0.0, SPOTLIGHT, 10.0, 90.0, LMNULL] - -lmodel = [ AMBIENT, 0.92, 0.8, 0.5, LOCALVIEWER, 1.0, LMNULL] -# -def lighting(): - lmdef(DEFMATERIAL, 1, green_velvet) - lmdef(DEFMATERIAL, 2, silver) - lmdef(DEFMATERIAL, 3, floormat) - lmdef(DEFMATERIAL, 4, wallmat) - lmdef(DEFMATERIAL, 5, offwhite) - lmdef(DEFMATERIAL, 6, doormat) - lmdef(DEFLIGHT, 1, toplight) - lmdef(DEFLIGHT, 2, floor1light) - lmdef(DEFLMODEL, 1, lmodel) - lmbind(MATERIAL, 1) - lmbind(LIGHT0, 1) - lmbind(LIGHT1, 2) - lmbind(LMODEL, 1) -IdMat=[1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,0.0,0.0,1.0] -# -def defun(axis): - done = 0 - while not done: - print 'F'+axis+'(t) = ', - s = sys.stdin.readline(100) - print - try: - s = 'def f'+axis+'(t): return '+s - exec(s, main_dict) - done = 1 - except RuntimeError: - print 'Sorry, there is a syntax error in your expression' -def getfunctions(): - print 'Welcome to the CWI art simulator. You can now enter X, Y and Z' - print 'coordinates as a function of t.' - print 'Normal trig functions are available. Please use floating point' - print 'values only (so 0.0 for 0). Comments to jack@cwi.nl' - defun('x') - defun('y') - defun('z') - print 'Ok, here you go. Use mouse+right button to move up/down,' - print 'mouse+middle to speed up/slow down time. type ESC to quit simulation' -def main(): - getfunctions() - foreground() - prefposition(100,600,100,600) - void = winopen('cyl') - qdevice(ESCKEY) - qdevice(MOUSE1) - qdevice(MOUSE2) - qdevice(PKEY) - RGBmode() - doublebuffer() - gconfig() - zbuffer(1) - mmode(MVIEWING) - perspective(400, 1.0, 1.0, 20.0) - loadmatrix(IdMat) - vx = 0.0 - vy = -6.0 - vz = 0.0 - lookat(0.0, -6.0, 0.0, 0.0, 0.0, 0.0, 0) - lighting() - t = -1.0 - step = 1.0 - bol = mkcyl(12,24, 1) - cable = mkcyl(1, 6, 0) - floors = drawfloors() - walls = drawwalls() - pillar = mkcyl(1,4,0) - railing = drawrailing() - doors = drawdoors() - shademodel(GOURAUD) - mousing = -1 - pausing = 0 - while 1: - # - # Check for some user input - # - if qtest(): - dev, value = qread() - if dev == PKEY and value == 1: - pausing = 1 - if dev == ESCKEY: - break - elif (dev==MOUSE1 or dev==MOUSE2) and value == 1: - if mousing > 0: - vx = 0.0 - vy = -6.0 - vz = 0.0 - mousing = dev - oldx = getvaluator(MOUSEX) - oldy = getvaluator(MOUSEY) - elif (dev==MOUSE1 or dev==MOUSE2): - mousing = -1 - if mousing >= 0: - newx = getvaluator(MOUSEX) - newy = getvaluator(MOUSEY) - if newy <> oldy and mousing==MOUSE1: - vz = vz + float(newy - oldy)/100.0 - dist = sqrt(vx*vx + vy*vy + vz*vz) - perspective(400, 1.0, 1.0, dist+16.0) - loadmatrix(IdMat) - if vz < 0.0: - lookat(vx, vy, vz, 0.0, 0.0, 0.0, 1800) - else: - lookat(vx, vy, vz, 0.0, 0.0, 0.0, 0) - if newy <> oldy and mousing==MOUSE2: - step = step * exp(float(newy-oldy)/400.0) - if getbutton(CTRLKEY) == 0: - t = t + step - else: - t = t - step - if getbutton(LEFTSHIFTKEY) == 0: - shademodel(GOURAUD) - else: - shademodel(FLAT) - # - # Draw background and axis - cpack(0x105090) - clear() - zclear() - cpack(0x905010) - axis() - # - # Draw object - # - bolx = fx(t) - boly = fy(t) - bolz = fz(t) - err = '' - if bolx < -4.0 or bolx > 4.0: - err = 'X('+`bolx`+') out of range [-4,4]' - if boly < -4.0 or boly > 4.0: - err = 'Y('+`boly`+') out of range [-4,4]' - if bolz < -4.0 or bolz > 8.0: - err = 'Z('+`bolz`+') out of range [-4,8]' - if not err: - pushmatrix() - translate(bolx, boly, bolz) - scale(0.3, 0.3, 0.3) - lmbind(MATERIAL, 2) - callobj(bol) - popmatrix() - # - # Draw the cables - # - bolz = bolz + 0.3 - pushmatrix() - linesmooth(SML_ON) - bgnline() - v3i(-4,-4,9) - v3f(bolx, boly, bolz) - endline() - bgnline() - v3i(-4,4,9) - v3f(bolx, boly, bolz) - endline() - bgnline() - v3i(4,-4,9) - v3f(bolx, boly, bolz) - endline() - bgnline() - v3i(4,4,9) - v3f(bolx, boly, bolz) - endline() - popmatrix() - # - # draw the floors - # - lmbind(MATERIAL, 3) - callobj(floors) - lmbind(MATERIAL, 4) - callobj(walls) - lmbind(MATERIAL, 5) - pushmatrix() - translate(-4.5,4.5,3.0) - scale(0.2,0.2,9.0) - rotate(450,'z') - callobj(pillar) - popmatrix() - callobj(railing) - lmbind(MATERIAL, 6) - pushmatrix() - translate(0.0, -0.01, 0.0) - callobj(doors) - popmatrix() - if mousing == MOUSE2 or err: - cpack(0xff0000) - cmov(0.0, 0.0, 0.4) - charstr('t='+`t`) - if mousing == MOUSE2: - cpack(0xff0000) - cmov(0.0, 0.0, 0.2) - charstr('delta-t='+`step`) - if err: - cpack(0xff00) - cmov(0.0, 0.0, 0.2) - print err - charstr(err) - pausing = 1 - if pausing: - cpack(0xff00) - cmov(0.0, 0.0, 0.0) - charstr('Pausing, type P to continue') - swapbuffers() - if pausing: - while 1: - dv=qread() - if dv==(PKEY,1): - break - if dv==(ESCKEY,1): - sys.exit(0) - pausing = 0 -# -try: - main() -except KeyboardInterrupt: - sys.exit(1) diff --git a/Demo/sgi/gl/mclock.doc b/Demo/sgi/gl/mclock.doc deleted file mode 100755 index 2208f33fb3..0000000000 --- a/Demo/sgi/gl/mclock.doc +++ /dev/null @@ -1,60 +0,0 @@ -Newsgroups: cwi.sgi -Subject: Re: new clock -Distribution: cwi.sgi -References: <2246@charon.cwi.nl> - -Last week I wrote: - ->For your enjoyment I have implemented a colorful clock. - -The clock has now been extended with some new facilities: a menu, an -alarm and a gong. These may require some explanation beyond what's in -the usage message. - -Menu ----- -The right mouse button now pops up a menu that allows you to turn the -seconds hand on or off and to switch the alarm off. - -Alarm ------ - -The left and middle buttons set the alarm. When it is on, the alarm -time is displayed as a time on a 24 hour clock in the bottom left -corner. It is also indicated by two red triangles, corresponding to the -little (hours) and big (minutes) hand. These hands can be moved around: -the left mouse button moves the minutes hand, the middle button moves -the hourds hand. Watch out for differences of twelve hours (always -check the digital display); these can be corrected by dragging the hours -hand once around the dial. - -When the alarm goes off, two things happen: a shell command specified on -the command line with the -a option is executed (in the background), and -the clock's colors change every two seconds, for five minutes. You can -also turn the alarm off by using the menu accessible through the right -mouse button. - -There is no default command for the -a option; if it is not specified, -only the changing of the colors happens. If you have an 8 ohm speaker -connected to the audio output of your Personal Iris, a suitable command -would be: - - mclock -a '/ufs/guido/bin/sgi/play /ufs/guido/lib/sounds/alarm' - -Gong ----- - -Some people like a clock that makes noises every hour, or even more -often. This is supported by the -g and -G options. With -g you specify -a shell command to be executed to sound the gong; with -G you can -specify the interval between gong calls, in seconds (default is one hour). -The shell command is executed in the background. It is given two -arguments: the hours (on a 24 hour clock!) and the minutes. The -executable Python script /ufs/guido/bin/sgi/chime is a suitable example. -Again, this only works if you have installed a speaker (I bet 8 ohm -speakers are going to be in demand!) - --- -Guido van Rossum, Centre for Mathematics and Computer Science (CWI), Amsterdam -guido@cwi.nl or ..!hp4nl!cwi.nl!guido or guido%cwi.nl@uunet.uu.net -"A thing of beauty is a joy till sunrise" diff --git a/Demo/sgi/gl/mclock.py b/Demo/sgi/gl/mclock.py deleted file mode 100755 index ec39de9c8b..0000000000 --- a/Demo/sgi/gl/mclock.py +++ /dev/null @@ -1,736 +0,0 @@ -#! /usr/local/bin/python - -# "M Clock" -# -# An implementation in software of an original design by Rob Juda. -# Clock implementation: Guido van Rossum. -# Alarm and Gong features: Sape Mullender. -# -# XXX TO DO: -# add arguments to specify initial window position and size -# find out local time zone difference automatically -# add a date indicator -# allow multiple alarms -# allow the menu to change more parameters - -import sys - -from gl import * -from GL import * -from DEVICE import * -import time -import getopt -import string -import os -from math import pi -import math - -FULLC = 3600 # Full circle in 1/10-ths of a degree -MIDN = 900 # Angle of the 12 o'clock position -R, G, B = 0, 1, 2 # Indices of colors in RGB list - -HOUR = 3600 # Number of seconds per hour -MINUTE = 60 # Number of seconds per minute - -class struct: pass # Class to define featureless structures -Gl = struct() # Object to hold writable global variables - -# Default constants (used in multiple places) - -SCREENBG = 127, 156, 191 -NPARTS = 9 -TITLE = 'M Clock' - -# Set timezone, check for daylight saving time -TZDIFF = time.timezone -if time.localtime(time.time())[-1]: - TZDIFF = time.altzone - -# Default parameters - -Gl.foreground = 0 # If set, run in the foreground -Gl.fullscreen = 0 # If set, run on full screen -Gl.tzdiff = TZDIFF # Seconds west of Greenwich (winter time) -Gl.nparts = NPARTS # Number of parts each circle is divided in (>= 2) -Gl.debug = 0 # If set, print debug output -Gl.doublebuffer = 1 # If set, use double buffering -Gl.update = 0 # Update interval; seconds hand is suppressed if > 1 -Gl.colorsubset = 0 # If set, display only a subset of the colors -Gl.cyan = 0 # If set, display cyan overlay (big hand) -Gl.magenta = 0 # If set, display magenta overlay (little hand) -Gl.yellow = 0 # If set, display yellow overlay (fixed background) -Gl.black = 0 # If set, display black overlay (hands) -Gl.colormap = 0 # If set, use colormap mode instead of RGB mode -Gl.warnings = 0 # If set, print warnings -Gl.title = '' # Window title (default set later) -Gl.name = 'mclock' # Window title for resources -Gl.border = 1 # If set, use a window border (and title) -Gl.bg = 0, 0, 0 # Background color R, G, B value -Gl.iconic = 0 # Set in iconic state -Gl.fg = 255, 0, 0 # Alarm background RGB (either normal or alarm) -Gl.ox,Gl.oy = 0,0 # Window origin -Gl.cx,Gl.cy = 0,0 # Window size -Gl.alarm_set = 0 # Alarm on or off -Gl.alarm_on = 0 # Alarm is ringing -Gl.alarm_time = 0 # Alarm time in seconds after midnight -Gl.alarm_hours = 0 # Alarm hour setting, 24 hour clock -Gl.alarm_minutes = 0 # Alarm minutes setting -Gl.alarm_rgb = 0,0,0 # Alarm display RGB colors -Gl.alarm_cmd = '' # Command to execute when alarm goes off -Gl.mouse2down = 0 # Mouse button state -Gl.mouse3down = 0 # Mouse button state -Gl.gong_cmd = '' # Command to execute when chimes go off -Gl.gong_int = 3600 # Gong interval -Gl.indices = R, G, B # Colors (permuted when alarm is on) - -def main(): - # - sys.stdout = sys.stderr # All output is errors/warnings etc. - # - try: - args = getoptions() - except string.atoi_error, value: - usage(string.atoi_error, value) - except getopt.error, msg: - usage(getopt.error, msg) - # - if args: - realtime = 0 - hours = string.atoi(args[0]) - minutes = seconds = 0 - if args[1:]: minutes = string.atoi(args[1]) - if args[2:]: seconds = string.atoi(args[2]) - localtime = ((hours*60)+minutes)*60+seconds - else: - realtime = 1 - # - if Gl.title == '': - if realtime: - Gl.title = TITLE - else: - title = '' - for arg in args: title = title + ' ' + arg - Gl.title = title[1:] - del title - # - wid = makewindow() - Gl.ox,Gl.oy = getorigin() - Gl.cx,Gl.cy = getsize() - initmenu() - clearall() - # - if not Gl.update: - Gl.update = 60 - # - if Gl.update <= 1: - Gl.timernoise = 6 - else: - Gl.timernoise = 60 - noise(TIMER0, Gl.timernoise) - # - qdevice(WINSHUT) - qdevice(WINQUIT) - qdevice(ESCKEY) - if realtime: - qdevice(TIMER0) - qdevice(REDRAW) - qdevice(WINFREEZE) - qdevice(WINTHAW) - qdevice(MENUBUTTON) # MOUSE1 - qdevice(MOUSE3) # Left button - qdevice(MOUSE2) # Middle button - unqdevice(INPUTCHANGE) - # - lasttime = 0 - Gl.change = 1 - while 1: - if realtime: - localtime = int(time.time() - Gl.tzdiff) - if Gl.alarm_set: - if localtime%(24*HOUR) == Gl.alarm_time: - # Ring the alarm! - if Gl.debug: - print 'Rrrringg!' - Gl.alarm_on = 1 - if Gl.alarm_cmd <> '': - d = os.system(Gl.alarm_cmd+' '+`Gl.alarm_time/3600`+' '+`(Gl.alarm_time/60)%60` + ' &') - Gl.change = 1 - clearall() - if Gl.alarm_on: - if (localtime - Gl.alarm_time) % (24*HOUR) > 300: - # More than 5 minutes away from alarm - Gl.alarm_on = 0 - if Gl.debug: - print 'Alarm turned off' - Gl.change = 1 - clearall() - Gl.indices = R, G, B - else: - if localtime % 2 == 0: - # Permute color indices - Gl.indices = Gl.indices[2:] + Gl.indices[:2] - Gl.change = 1 - if Gl.gong_cmd <> '' and localtime%Gl.gong_int == 0: - d = os.system(Gl.gong_cmd+' '+`(localtime/3600)%24`+' '+`(localtime/60)%60` + ' &') - if localtime/Gl.update <> lasttime/Gl.update: - if Gl.debug: print 'new time' - Gl.change = 1 - if Gl.change: - if Gl.debug: print 'drawing' - doit(localtime) - lasttime = localtime - Gl.change = 0 - dev, data = qread() - if Gl.debug and dev <> TIMER0: - print dev, data - if dev == TIMER0: - if Gl.debug > 1: - print dev, data - elif dev == MOUSE3: - mousex = getvaluator(MOUSEX) - mousey = getvaluator(MOUSEY) - if mouseclick(3, data, mousex, mousey): - Gl.change = 1 - elif dev == MOUSE2: - mousex = getvaluator(MOUSEX) - mousey = getvaluator(MOUSEY) - if mouseclick(2, data, mousex, mousey): - Gl.change = 1 - elif dev == MOUSEX: - mousex = data - if Gl.mouse2down: - mouse2track(mousex, mousey) - if Gl.mouse3down: - mouse3track(mousex, mousey) - elif dev == MOUSEY: - mousey = data - if Gl.mouse2down: - mouse2track(mousex, mousey) - if Gl.mouse3down: - mouse3track(mousex, mousey) - elif dev == REDRAW or dev == REDRAWICONIC: - if Gl.debug: - if dev == REDRAW: print 'REDRAW' - else: print 'REDRAWICONIC' - reshapeviewport() - Gl.ox,Gl.oy = getorigin() - Gl.cx,Gl.cy = getsize() - Gl.change = 1 - clearall() - elif dev == MENUBUTTON: - if Gl.debug: print 'MENUBUTTON' - handlemenu() - elif dev == WINFREEZE: - if Gl.debug: print 'WINFREEZE' - Gl.iconic = 1 - noise(TIMER0, 60*60) # Redraw every 60 seconds only - elif dev == WINTHAW: - if Gl.debug: print 'WINTHAW' - Gl.iconic = 0 - noise(TIMER0, Gl.timernoise) - Gl.change = 1 - elif dev == ESCKEY or dev == WINSHUT or dev == WINQUIT: - if Gl.debug: print 'Exit' - sys.exit(0) - -def getoptions(): - optlist, args = getopt.getopt(sys.argv[1:], 'A:a:B:bc:dFfG:g:n:sT:t:u:wCMYK') - for optname, optarg in optlist: - if optname == '-A': - Gl.fg = eval(optarg) # Should be (r,g,b) - elif optname == '-a': - Gl.alarm_cmd = optarg - elif optname == '-B': - Gl.bg = eval(optarg) # Should be (r,g,b) - elif optname == '-b': - Gl.border = 0 - elif optname == '-c': - Gl.colormap = string.atoi(optarg) - elif optname == '-d': - Gl.debug = Gl.debug + 1 - Gl.warnings = 1 - elif optname == '-F': - Gl.foreground = 1 - elif optname == '-f': - Gl.fullscreen = 1 - elif optname == '-G': - Gl.gong_int = 60*string.atoi(optarg) - elif optname == '-g': - Gl.gong_cmd = optarg - elif optname == '-n': - Gl.nparts = string.atoi(optarg) - elif optname == '-s': - Gl.doublebuffer = 0 - elif optname == '-T': - Gl.title = Gl.name = optarg - elif optname == '-t': - Gl.tzdiff = string.atoi(optarg) - elif optname == '-u': - Gl.update = string.atoi(optarg) - elif optname == '-w': - Gl.warnings = 1 - elif optname == '-C': - Gl.cyan = Gl.colorsubset = 1 - elif optname == '-M': - Gl.magenta = Gl.colorsubset = 1 - elif optname == '-Y': - Gl.yellow = Gl.colorsubset = 1 - elif optname == '-K': - Gl.black = Gl.colorsubset = 1 - else: - print 'Unsupported option', optname - return args - -def usage(exc, msg): - if sys.argv: - progname = os.path.basename(sys.argv[0]) - else: - progname = 'mclock' - # - print progname + ':', - if exc == string.atoi_error: - print 'non-numeric argument:', - print msg - # - print 'usage:', progname, '[options] [hh [mm [ss]]]' - # - print '-A r,g,b : alarm background red,green,blue [255,0,0]' - print '-a cmd : shell command executed when alarm goes off' - print '-B r,g,b : background red,green,blue [0,0,0]' - print ' (-B SCREENBG uses the default screen background)' - print '-b : suppress window border and title' - print '-c cmapid : select explicit colormap' - print '-d : more debug output (implies -F, -w)' - print '-F : run in foreground' - print '-f : use full screen' - print '-G intrvl : interval between chimes in minutes [60]' - print '-g cmd : shell command executed when chimes go off' - print '-s : single buffer mode' - print '-w : print various warnings' - print '-n nparts : number of parts [' + `NPARTS` + ']' - print '-T title : alternate window title [\'' + TITLE + '\']' - print '-t tzdiff : time zone difference [' + `TZDIFF` + ']' - print '-u update : update interval [60]' - print '-CMYK : Cyan, Magenta, Yellow or blacK overlay only' - print 'if hh [mm [ss]] is specified, display that time statically' - print 'on machines with < 12 bitplanes, -s is forced on' - # - sys.exit(2) - -def doit(localtime): - hands = makehands(localtime) - list = makelist(hands) - render(list, hands) - -def makehands(localtime): - localtime = localtime % (12*HOUR) - seconds_hand = MIDN + FULLC - (localtime*60) % FULLC - big_hand = (MIDN + FULLC - (localtime%HOUR)) % FULLC - little_hand = (MIDN + FULLC - ((localtime/12) % HOUR)) % FULLC - return little_hand, big_hand, seconds_hand - -def makelist(hands): - little_hand, big_hand, seconds_hand = hands - total = [] - if Gl.cyan or not Gl.colorsubset: - total = total + makesublist(big_hand, Gl.indices[0]) - if Gl.magenta or not Gl.colorsubset: - total = total + makesublist(little_hand, Gl.indices[1]) - if Gl.yellow or not Gl.colorsubset: - total = total + makesublist(MIDN, Gl.indices[2]) - total.sort() - return total - -def makesublist(first, icolor): - list = [] - alpha = FULLC/Gl.nparts - a = first - alpha/2 - for i in range(Gl.nparts): - angle = (a + i*alpha + FULLC) % FULLC - value = 255*(Gl.nparts-1-i)/(Gl.nparts-1) - list.append(angle, icolor, value) - list.sort() - a, icolor, value = list[0] - if a <> 0: - a, icolor, value = list[len(list)-1] - t = 0, icolor, value - list.insert(0, t) - return list - -def rgb_fg(): - return Gl.fg - # Obsolete code: - if Gl.alarm_on: - return Gl.bg - else: - return Gl.fg - -def rgb_bg(): - return Gl.bg - # Obsolete code: - if Gl.alarm_on: - return Gl.fg - else: - return Gl.bg - -def clearall(): - Gl.c3i(rgb_bg()) - clear() - if Gl.doublebuffer: - swapbuffers() - clear() - -def draw_alarm(color): - frontbuffer(TRUE) - Gl.c3i(color) - pushmatrix() - rotate(-((Gl.alarm_time/12)%3600), 'z') - bgnpolygon() - v2f( 0.00,1.00) - v2f( 0.04,1.05) - v2f(-0.04,1.05) - endpolygon() - popmatrix() - # - pushmatrix() - rotate(-((Gl.alarm_time)%3600), 'z') - bgnpolygon() - v2f( 0.00,1.05) - v2f( 0.07,1.10) - v2f(-0.07,1.10) - endpolygon() - popmatrix() - # - cmov2(-1.06, -1.06) - charstr(string.rjust(`Gl.alarm_time/3600`,2)) - charstr(':') - charstr(string.zfill((Gl.alarm_time/60)%60,2)) - frontbuffer(FALSE) - -def render(list, (little_hand, big_hand, seconds_hand)): - # - if Gl.colormap: - resetindex() - # - if not list: - Gl.c3i((255, 255, 255)) # White - circf(0.0, 0.0, 1.0) - else: - list.append(3600, 0, 255) # Sentinel - # - rgb = [255, 255, 255] - a_prev = 0 - for a, icolor, value in list: - if a <> a_prev: - [r, g, b] = rgb - if Gl.debug > 1: - print rgb, a_prev, a - Gl.c3i((r, g, b)) - arcf(0.0, 0.0, 1.0, a_prev, a) - rgb[icolor] = value - a_prev = a - # - if Gl.black or not Gl.colorsubset: - # - # Draw the hands -- in black - # - Gl.c3i((0, 0, 0)) - # - if Gl.update == 1 and not Gl.iconic: - # Seconds hand is only drawn if we update every second - pushmatrix() - rotate(seconds_hand, 'z') - bgnline() - v2f(0.0, 0.0) - v2f(1.0, 0.0) - endline() - popmatrix() - # - pushmatrix() - rotate(big_hand, 'z') - rectf(0.0, -0.01, 0.97, 0.01) - circf(0.0, 0.0, 0.01) - circf(0.97, 0.0, 0.01) - popmatrix() - # - pushmatrix() - rotate(little_hand, 'z') - rectf(0.04, -0.02, 0.63, 0.02) - circf(0.04, 0.0, 0.02) - circf(0.63, 0.0, 0.02) - popmatrix() - # - # Draw the alarm time, if set or being set - # - if Gl.alarm_set: - draw_alarm(rgb_fg()) - # - if Gl.doublebuffer: swapbuffers() - -def makewindow(): - # - if Gl.debug or Gl.foreground: - foreground() - # - if Gl.fullscreen: - scrwidth, scrheight = getgdesc(GD_XPMAX), getgdesc(GD_YPMAX) - prefposition(0, scrwidth-1, 0, scrheight-1) - else: - keepaspect(1, 1) - prefsize(80, 80) - # - if not Gl.border: - noborder() - wid = winopen(Gl.name) - wintitle(Gl.title) - # - if not Gl.fullscreen: - keepaspect(1, 1) - minsize(10, 10) - maxsize(2000, 2000) - iconsize(66, 66) - winconstraints() - # - nplanes = getplanes() - nmaps = getgdesc(GD_NMMAPS) - if Gl.warnings: - print nplanes, 'color planes,', nmaps, 'color maps' - # - if Gl.doublebuffer and not Gl.colormap and nplanes < 12: - if Gl.warnings: print 'forcing single buffer mode' - Gl.doublebuffer = 0 - # - if Gl.colormap: - if not Gl.colormap: - Gl.colormap = nmaps - 1 - if Gl.warnings: - print 'not enough color planes available', - print 'for RGB mode; forcing colormap mode' - print 'using color map number', Gl.colormap - if not Gl.colorsubset: - needed = 3 - else: - needed = Gl.cyan + Gl.magenta + Gl.yellow - needed = needed*Gl.nparts - if Gl.bg <> (0, 0, 0): - needed = needed+1 - if Gl.fg <> (0, 0, 0): - needed = needed+1 - if Gl.doublebuffer: - if needed > available(nplanes/2): - Gl.doublebuffer = 0 - if Gl.warnings: - print 'not enough colors available', - print 'for double buffer mode;', - print 'forcing single buffer mode' - else: - nplanes = nplanes/2 - if needed > available(nplanes): - # Do this warning always - print 'still not enough colors available;', - print 'parts will be left white' - print '(needed', needed, 'but have only', - print available(nplanes), 'colors available)' - # - if Gl.doublebuffer: - doublebuffer() - gconfig() - # - if Gl.colormap: - Gl.c3i = pseudo_c3i - fixcolormap() - else: - Gl.c3i = c3i - RGBmode() - gconfig() - # - if Gl.fullscreen: - # XXX Should find out true screen size using getgdesc() - ortho2(-1.1*1.280, 1.1*1.280, -1.1*1.024, 1.1*1.024) - else: - ortho2(-1.1, 1.1, -1.1, 1.1) - # - return wid - -def available(nplanes): - return pow(2, nplanes) - 1 # Reserve one pixel for black - -def fixcolormap(): - multimap() - gconfig() - nplanes = getplanes() - if Gl.warnings: - print 'multimap mode has', nplanes, 'color planes' - imap = Gl.colormap - Gl.startindex = pow(2, nplanes) - 1 - Gl.stopindex = 1 - setmap(imap) - mapcolor(0, 0, 0, 0) # Fixed entry for black - if Gl.bg <> (0, 0, 0): - r, g, b = Gl.bg - mapcolor(1, r, g, b) # Fixed entry for Gl.bg - Gl.stopindex = 2 - if Gl.fg <> (0, 0, 0): - r, g, b = Gl.fg - mapcolor(2, r, g, b) # Fixed entry for Gl.fg - Gl.stopindex = 3 - Gl.overflow_seen = 0 - resetindex() - -def resetindex(): - Gl.index = Gl.startindex - -r0g0b0 = (0, 0, 0) - -def pseudo_c3i(rgb): - if rgb == r0g0b0: - index = 0 - elif rgb == Gl.bg: - index = 1 - elif rgb == Gl.fg: - index = 2 - else: - index = definecolor(rgb) - color(index) - -def definecolor(rgb): - index = Gl.index - if index < Gl.stopindex: - if Gl.debug: print 'definecolor hard case', rgb - # First see if we already have this one... - for index in range(Gl.stopindex, Gl.startindex+1): - if rgb == getmcolor(index): - if Gl.debug: print 'return', index - return index - # Don't clobber reserverd colormap entries - if not Gl.overflow_seen: - # Shouldn't happen any more, hence no Gl.warnings test - print 'mclock: out of colormap entries' - Gl.overflow_seen = 1 - return Gl.stopindex - r, g, b = rgb - if Gl.debug > 1: print 'mapcolor', (index, r, g, b) - mapcolor(index, r, g, b) - Gl.index = index - 1 - return index - -# Compute n**i -def pow(n, i): - x = 1 - for j in range(i): x = x*n - return x - -def mouseclick(mouse, updown, x, y): - if updown == 1: - # mouse button came down, start tracking - if Gl.debug: - print 'mouse', mouse, 'down at', x, y - if mouse == 2: - Gl.mouse2down = 1 - mouse2track(x, y) - elif mouse == 3: - Gl.mouse3down = 1 - mouse3track(x, y) - else: - print 'fatal error' - qdevice(MOUSEX) - qdevice(MOUSEY) - return 0 - else: - # mouse button came up, stop tracking - if Gl.debug: - print 'mouse', mouse, 'up at', x, y - unqdevice(MOUSEX) - unqdevice(MOUSEY) - if mouse == 2: - mouse2track(x, y) - Gl.mouse2down = 0 - elif mouse == 3: - mouse3track(x, y) - Gl.mouse3down = 0 - else: - print 'fatal error' - Gl.alarm_set = 1 - return 1 - -def mouse3track(x, y): - # first compute polar coordinates from x and y - cx, cy = Gl.ox + Gl.cx/2, Gl.oy + Gl.cy/2 - x, y = x - cx, y - cy - if (x, y) == (0, 0): return # would cause an exception - minutes = int(30.5 + 30.0*math.atan2(float(-x), float(-y))/pi) - if minutes == 60: minutes = 0 - a,b = Gl.alarm_minutes/15, minutes/15 - if (a,b) == (0,3): - # Moved backward through 12 o'clock: - Gl.alarm_hours = Gl.alarm_hours - 1 - if Gl.alarm_hours < 0: Gl.alarm_hours = Gl.alarm_hours + 24 - if (a,b) == (3,0): - # Moved forward through 12 o'clock: - Gl.alarm_hours = Gl.alarm_hours + 1 - if Gl.alarm_hours >= 24: Gl.alarm_hours = Gl.alarm_hours - 24 - Gl.alarm_minutes = minutes - seconds = Gl.alarm_hours * HOUR + Gl.alarm_minutes * MINUTE - if seconds <> Gl.alarm_time: - draw_alarm(rgb_bg()) - Gl.alarm_time = seconds - draw_alarm(rgb_fg()) - -def mouse2track(x, y): - # first compute polar coordinates from x and y - cx, cy = Gl.ox + Gl.cx/2, Gl.oy + Gl.cy/2 - x, y = x - cx, y - cy - if (x, y) == (0, 0): return # would cause an exception - hours = int(6.5 - float(Gl.alarm_minutes)/60.0 + 6.0*math.atan2(float(-x), float(-y))/pi) - if hours == 12: hours = 0 - if (Gl.alarm_hours,hours) == (0,11): - # Moved backward through midnight: - Gl.alarm_hours = 23 - elif (Gl.alarm_hours,hours) == (12,11): - # Moved backward through noon: - Gl.alarm_hours = 11 - elif (Gl.alarm_hours,hours) == (11,0): - # Moved forward through noon: - Gl.alarm_hours = 12 - elif (Gl.alarm_hours,hours) == (23,0): - # Moved forward through midnight: - Gl.alarm_hours = 0 - elif Gl.alarm_hours < 12: - Gl.alarm_hours = hours - else: - Gl.alarm_hours = hours + 12 - seconds = Gl.alarm_hours * HOUR + Gl.alarm_minutes * MINUTE - if seconds <> Gl.alarm_time: - draw_alarm(rgb_bg()) - Gl.alarm_time = seconds - draw_alarm(rgb_fg()) - -def initmenu(): - Gl.pup = pup = newpup() - addtopup(pup, 'M Clock%t|Alarm On/Off|Seconds Hand On/Off|Quit', 0) - -def handlemenu(): - item = dopup(Gl.pup) - if item == 1: - # Toggle alarm - if Gl.alarm_set: - Gl.alarm_set = 0 - Gl.alarm_on = 0 - else: - Gl.alarm_set = 1 - Gl.change = 1 - clearall() - elif item == 2: - # Toggle Seconds Hand - if Gl.update == 1: - Gl.update = 60 - Gl.timernoise = 60 - else: - Gl.update = 1 - Gl.timernoise = 6 - Gl.change = 1 - elif item == 3: - if Gl.debug: print 'Exit' - sys.exit(0) - -main() diff --git a/Demo/sgi/gl/mixing.py b/Demo/sgi/gl/mixing.py deleted file mode 100755 index 57dea9c865..0000000000 --- a/Demo/sgi/gl/mixing.py +++ /dev/null @@ -1,116 +0,0 @@ -#! /usr/local/bin/python - -# Use Gouraud shading to mix colors. Requires Z-buffer. -# It changes the color assignments so fast that you see white. -# Left button pauses, middle rotates the square. ESC to quit. -# Experiment with a larger window (too slow) or smaller window (really white). - -from GL import * -from gl import * -import DEVICE -from math import * - -# -# tekenvlak : draw a square. with bgnpolygon -# -def tekenvlak (vc) : - bgnpolygon() - #vcarray (vc) - for i in vc : - c3f (i[1]) - v3f (i[0]) - endpolygon() - -# -# tekendoos : draw a box -# -def tekendoos (col) : - v = [(-5.0,0.0,0.0),(0.0,5.0,0.0),(5.0,0.0,0.0),(0.0,-5.0,0.0)] - vc = [(v[0],col[0]),(v[1],col[1]),(v[2],col[2]),(v[3],col[1])] - tekenvlak (vc) - -# -# initialize gl -# -def initgl () : - # - # open window - # - foreground () - keepaspect (1, 1) - prefposition (100, 500, 100, 500) - w = winopen ('PYTHON RGB') - keepaspect (1, 1) - winconstraints() - # - # configure pipeline (2buf, GOURAUD and RGBmode) - # - doublebuffer () - zbuffer (1) - shademodel (GOURAUD) - RGBmode () - gconfig () - # - # set viewing - # - perspective (900, 1, 1.0, 10.0) - polarview (10.0, 0, 0, 0) - # - # ask for the REDRAW and ESCKEY events - # - qdevice(DEVICE.MOUSE2) - qdevice(DEVICE.MOUSE3) - qdevice(DEVICE.REDRAW) - qdevice(DEVICE.ESCKEY) - - -# -# the color black -# -black = 0 -# -# GoForIT : use 2buf to redraw the object 2n times. index i is used as -# the (smoothly changing) rotation angle -# -def GoForIt(i) : - col = [(255.0,0.0,0.0), (0.0,255.0,0.0), (0.0,0.0,255.0)] - twist = 0 - freeze = 1 - while 1 : - if freeze <> 0 : - col[0],col[1],col[2] = col[1],col[2],col[0] - # - # clear z-buffer and clear background to light-blue - # - zclear() - cpack (black) - clear() - # - tekendoos (col) - # - swapbuffers() - # - if qtest() <> 0 : - dev, val = qread() - if dev == DEVICE.ESCKEY : - break - elif dev == DEVICE.REDRAW : - reshapeviewport () - elif dev == DEVICE.MOUSE2 and val <> 0 : - twist = twist + 30 - perspective (900, 1, 1.0, 10.0) - polarview (10.0, 0, 0, twist) - elif dev == DEVICE.MOUSE3 and val <> 0 : - freeze = 1 - freeze - - -# the main program -# -def main () : - initgl () - GoForIt (0) - -# -# exec main -# -main () diff --git a/Demo/sgi/gl/nurbs.py b/Demo/sgi/gl/nurbs.py deleted file mode 100755 index af2039bc22..0000000000 --- a/Demo/sgi/gl/nurbs.py +++ /dev/null @@ -1,171 +0,0 @@ -#! /usr/local/bin/python - -# Rotate a 3D surface created using NURBS. -# -# Press left mouse button to toggle surface trimming. -# Press ESC to quit. -# -# See the GL manual for an explanation of NURBS. - -from gl import * -from GL import * -from DEVICE import * - -TRUE = 1 -FALSE = 0 -ORDER = 4 - -idmat = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1] - -surfknots = [-1, -1, -1, -1, 1, 1, 1, 1] - -def make_ctlpoints(): - c = [] - # - ci = [] - ci.append(-2.5, -3.7, 1.0) - ci.append(-1.5, -3.7, 3.0) - ci.append(1.5, -3.7, -2.5) - ci.append(2.5, -3.7, -0.75) - c.append(ci) - # - ci = [] - ci.append(-2.5, -2.0, 3.0) - ci.append(-1.5, -2.0, 4.0) - ci.append(1.5, -2.0, -3.0) - ci.append(2.5, -2.0, 0.0) - c.append(ci) - # - ci = [] - ci.append(-2.5, 2.0, 1.0) - ci.append(-1.5, 2.0, 0.0) - ci.append(1.5, 2.0, -1.0) - ci.append(2.5, 2.0, 2.0) - c.append(ci) - # - ci = [] - ci.append(-2.5, 2.7, 1.25) - ci.append(-1.5, 2.7, 0.1) - ci.append(1.5, 2.7, -0.6) - ci.append(2.5, 2.7, 0.2) - c.append(ci) - # - return c - -ctlpoints = make_ctlpoints() - -trimknots = [0., 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 4.] - -def make_trimpoints(): - c = [] - c.append(1.0, 0.0, 1.0) - c.append(1.0, 1.0, 1.0) - c.append(0.0, 2.0, 2.0) - c.append(-1.0, 1.0, 1.0) - c.append(-1.0, 0.0, 1.0) - c.append(-1.0, -1.0, 1.0) - c.append(0.0, -2.0, 2.0) - c.append(1.0, -1.0, 1.0) - c.append(1.0, 0.0, 1.0) - return c - -trimpoints = make_trimpoints() - -def main(): - init_windows() - setup_queue() - make_lights() - init_view() - # - set_scene() - setnurbsproperty( N_ERRORCHECKING, 1.0 ) - setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 ) - trim_flag = 0 - draw_trim_surface(trim_flag) - # - while 1: - while qtest(): - dev, val = qread() - if dev == ESCKEY: - return - elif dev == WINQUIT: - dglclose(-1) # this for DGL only - return - elif dev == REDRAW: - reshapeviewport() - set_scene() - draw_trim_surface(trim_flag) - elif dev == LEFTMOUSE: - if val: - trim_flag = (not trim_flag) - set_scene() - draw_trim_surface(trim_flag) - -def init_windows(): - foreground() - #prefposition(0, 500, 0, 500) - wid = winopen('nurbs') - wintitle('NURBS Surface') - doublebuffer() - RGBmode() - gconfig() - lsetdepth(0x000, 0x7fffff) - zbuffer( TRUE ) - -def setup_queue(): - qdevice(ESCKEY) - qdevice(REDRAW) - qdevice(RIGHTMOUSE) - qdevice(WINQUIT) - qdevice(LEFTMOUSE) #trimming - -def init_view(): - mmode(MPROJECTION) - ortho( -4., 4., -4., 4., -4., 4. ) - # - mmode(MVIEWING) - loadmatrix(idmat) - # - lmbind(MATERIAL, 1) - -def set_scene(): - lmbind(MATERIAL, 0) - RGBcolor(150,150,150) - lmbind(MATERIAL, 1) - clear() - zclear() - # - rotate( 100, 'y' ) - rotate( 100, 'z' ) - -def draw_trim_surface(trim_flag): - bgnsurface() - nurbssurface(surfknots, surfknots, ctlpoints, ORDER, ORDER, N_XYZ) - if trim_flag: - bgntrim() - nurbscurve(trimknots, trimpoints, ORDER-1, N_STW) - endtrim() - endsurface() - swapbuffers() - -def make_lights(): - lmdef(DEFLMODEL,1,[]) - lmdef(DEFLIGHT,1,[]) - # - # define material #1 - # - a = [] - a = a + [EMISSION, 0.0, 0.0, 0.0] - a = a + [AMBIENT, 0.1, 0.1, 0.1] - a = a + [DIFFUSE, 0.6, 0.3, 0.3] - a = a + [SPECULAR, 0.0, 0.6, 0.0] - a = a + [SHININESS, 2.0] - a = a + [LMNULL] - lmdef(DEFMATERIAL, 1, a) - # - # turn on lighting - # - lmbind(LIGHT0, 1) - lmbind(LMODEL, 1) - -main() diff --git a/Demo/sgi/gl/zrgb.py b/Demo/sgi/gl/zrgb.py deleted file mode 100755 index 6561e11b78..0000000000 --- a/Demo/sgi/gl/zrgb.py +++ /dev/null @@ -1,168 +0,0 @@ -#! /usr/local/bin/python - -# zrgb (Requires Z buffer.) -# -# This program demostrates zbuffering 3 intersecting RGB polygons while -# in doublebuffer mode where, movement of the mouse with the LEFTMOUSE -# button depressed will, rotate the 3 polygons. This is done by compound -# rotations allowing continuous screen-oriented rotations. -# -# Press the "Esc" key to exit. - -from gl import * -from GL import * -from DEVICE import * - - -idmat=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1] - -def main() : - # - # old and new mouse position - # - # - mode = 0 - omx = 0 - mx = 0 - omy = 0 - my = 0 - # - objmat=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1] - # - initialize () - # - draw_scene (objmat) - # - while (1) : - # - dev, val = qread() - # - if dev == ESCKEY : - if val : - break - # exit when key is going up, not down - # this avoids the scenario where a window - # underneath this program's window - # would otherwise "eat up" the up- - # event of the Esc key being released - return - # - elif dev == REDRAW : - reshapeviewport() - draw_scene(objmat) - # - elif dev == LEFTMOUSE: - omx = mx - omy = my - if val : - mode = 1 - else : - mode = 0 - elif dev == MOUSEX : - omx = mx - mx = val - #print omx, mx - objmat = update_scene(objmat,mx,my,omx,omy,mode) - # - elif dev == MOUSEY : - omy = my - my = val - #print omy, my - objmat = update_scene(objmat,mx,my,omx,omy,mode) - # - - -def initialize () : - # - foreground () - keepaspect(5, 4) - w = winopen('Zbuffered RGB') - # - doublebuffer() - RGBmode() - gconfig() - zbuffer(1) - lsetdepth(0x0, 0x7FFFFF) - # - qdevice(ESCKEY) - qdevice(LEFTMOUSE) - qdevice(MOUSEX) - qdevice(MOUSEY) - -def update_scene (mat, mx, my, omx, omy, mode) : - # - if mode == 1 : - mat = orient(mat, mx, my, omx, omy) - draw_scene(mat) - return mat - -def orient (mat, mx, my, omx, omy) : - # - # - pushmatrix() - loadmatrix(idmat) - # - if mx - omx : rot (float (mx - omx), 'y') - if omy - my : rot (float (omy - my), 'x') - # - multmatrix(mat) - mat = getmatrix() - # - popmatrix() - # - return mat - -def draw_scene (mat) : - RGBcolor(40, 100, 200) - clear() - zclear() - # - perspective(400, 1.25, 30.0, 60.0) - translate(0.0, 0.0, -40.0) - multmatrix(mat) - # - # skews original view to show all polygons - # - rotate(-580, 'y') - draw_polys() - # - swapbuffers() - -polygon1 = [(-10.0,-10.0,0.0),(10.0,-10.0,0.0),(-10.0,10.0,0.0)] - -polygon2 = [(0.0,-10.0,-10.0),(0.0,-10.0,10.0),(0.0,5.0,-10.0)] - -polygon3 = [(-10.0,6.0,4.0),(-10.0,3.0,4.0),(4.0,-9.0,-10.0),(4.0,-6.0,-10.0)] - -def draw_polys(): - bgnpolygon() - cpack(0x0) - v3f(polygon1[0]) - cpack(0x007F7F7F) - v3f(polygon1[1]) - cpack(0x00FFFFFF) - v3f(polygon1[2]) - endpolygon() - # - bgnpolygon() - cpack(0x0000FFFF) - v3f(polygon2[0]) - cpack(0x007FFF00) - v3f(polygon2[1]) - cpack(0x00FF0000) - v3f(polygon2[2]) - endpolygon() - # - bgnpolygon() - cpack(0x0000FFFF) - v3f(polygon3[0]) - cpack(0x00FF00FF) - v3f(polygon3[1]) - cpack(0x00FF0000) - v3f(polygon3[2]) - cpack(0x00FF00FF) - v3f(polygon3[3]) - endpolygon() - - -main () diff --git a/Demo/sgi/sv/README b/Demo/sgi/sv/README deleted file mode 100644 index 38e51407fe..0000000000 --- a/Demo/sgi/sv/README +++ /dev/null @@ -1,23 +0,0 @@ -Demo programs for the SGI Video library for the Indigo (IRIX 4.0.5). - -These are more-or-less literal translations of the C programs from the -Indigo Video Programming Guide, by Sjoerd Mullender, with some changes -by Guido. - -Note that none of the example programs save any data to a file, -although this would be easy to do (e.g. individual grabbed frames -could be written as SGI image files using the imgfile module). - -We have written a Python program to record live video to file (within -the limits of the Indigo video board), and a suite of programs to -manipulate and display such files. At the moment we don't distribute -these programs, since the file format is, eh..., weird, to say the -least. However, if you are really interested we can mail you the -source. - -Also note that we haven't tried using video *output* yet. - -simpleinput.py Live video in a resizable window -rgbgrab.py Grab still frames -contcapt.py Continuous capturing -burstcapt.py Burst capturing diff --git a/Demo/sgi/sv/burstcapt.py b/Demo/sgi/sv/burstcapt.py deleted file mode 100755 index ce1e579f36..0000000000 --- a/Demo/sgi/sv/burstcapt.py +++ /dev/null @@ -1,52 +0,0 @@ -import sys -import sv, SV -import gl, GL, DEVICE - -def main(): - format = SV.RGB8_FRAMES - requestedwidth = SV.PAL_XMAX - queuesize = 30 - if sys.argv[1:]: - queuesize = eval(sys.argv[1]) - - v = sv.OpenVideo() - svci = (format, requestedwidth, 0, queuesize, 0) - - go = raw_input('Press return to capture ' + `queuesize` + ' frames: ') - result = v.CaptureBurst(svci) - svci, buffer, bitvec = result -## svci, buffer = result # XXX If bit vector not yet implemented - - print 'Captured', svci[3], 'frames, i.e.', len(buffer)/1024, 'K bytes' - - w, h = svci[1:3] - framesize = w * h - - gl.prefposition(300, 300+w-1, 100, 100+h-1) - gl.foreground() - win = gl.winopen('Burst Capture') - gl.RGBmode() - gl.gconfig() - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.ESCKEY) - - print 'Click left mouse for next frame' - - for i in range(svci[3]): - inverted_frame = sv.RGB8toRGB32(1, \ - buffer[i*framesize:(i+1)*framesize], w, h) - gl.lrectwrite(0, 0, w-1, h-1, inverted_frame) - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE and val == 1: - break - if dev == DEVICE.REDRAW: - gl.lrectwrite(0, 0, w-1, h-1, inverted_frame) - if dev == DEVICE.ESCKEY: - v.CloseVideo() - gl.winclose(win) - return - v.CloseVideo() - gl.winclose(win) - -main() diff --git a/Demo/sgi/sv/contcapt.py b/Demo/sgi/sv/contcapt.py deleted file mode 100755 index 6c0a0003bb..0000000000 --- a/Demo/sgi/sv/contcapt.py +++ /dev/null @@ -1,107 +0,0 @@ -import sys -import sv, SV -import gl, GL, DEVICE - -def main(): - format = SV.RGB8_FRAMES - framerate = 25 - queuesize = 16 - samplingrate = 2 - - v = sv.OpenVideo() - # Determine maximum window size based on signal standard - param = [SV.BROADCAST, 0] - v.GetParam(param) - if param[1] == SV.PAL: - width = SV.PAL_XMAX - height = SV.PAL_YMAX - framefreq = 25 - else: - width = SV.NTSC_XMAX - height = SV.NTSC_YMAX - framefreq = 30 - - # Allow resizing window if capturing RGB frames, which can be scaled - if format == SV.RGB8_FRAMES: - gl.keepaspect(width, height) - gl.maxsize(width, height) - gl.stepunit(8, 6) - gl.minsize(120, 90) - else: - if format == SV.YUV411_FRAMES_AND_BLANKING_BUFFER: - height = height + SV.BLANKING_BUFFER_SIZE - gl.prefposition(300, 300+width-1, 100, 100+height-1) - - # Open the window - gl.foreground() - win = gl.winopen('Continuous Capture') - gl.RGBmode() - gl.gconfig() - if format == SV.RGB8_FRAMES: - width, height = gl.getsize() - gl.pixmode(GL.PM_SIZE, 8) - else: - gl.pixmode(GL.PM_SIZE, 32) - - svci = (format, width, height, queuesize, samplingrate) - [svci] - - svci = v.InitContinuousCapture(svci) - width, height = svci[1:3] - [svci] - - hz = gl.getgdesc(GL.GD_TIMERHZ) - gl.noise(DEVICE.TIMER0, hz / framerate) - gl.qdevice(DEVICE.TIMER0) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - - ndisplayed = 0 - lastfieldID = 0 - - while 1: - dev, val = gl.qread() - if dev == DEVICE.REDRAW: - oldw = width - oldh = height - width, height = gl.getsize() - if oldw != width or oldh != height: - v.EndContinuousCapture() - gl.viewport(0, width-1, 0, height-1) - svci = (svci[0], width, height) + svci[3:] - svci = v.InitContinuousCapture(svci) - width, height = svci[1:3] - [svci] - if ndisplayed: - print 'lost', - print fieldID/(svci[4]*2) - ndisplayed, - print 'frames' - ndisplayed = 0 - elif dev == DEVICE.TIMER0: - try: - captureData, fieldID = v.GetCaptureData() - except sv.error, val: - if val <> 'no data available': - print val - continue - if fieldID - lastfieldID <> 2*samplingrate: - print lastfieldID, fieldID - lastfieldID = fieldID - if svci[0] == SV.RGB8_FRAMES: - rgbbuf = captureData.InterleaveFields(1) - else: - rgbbuf = captureData.YUVtoRGB(1) - captureData.UnlockCaptureData() - gl.lrectwrite(0, 0, width-1, height-1, rgbbuf) - ndisplayed = ndisplayed + 1 - elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - v.EndContinuousCapture() - v.CloseVideo() - gl.winclose(win) - print fieldID, ndisplayed, svci[4] - print 'lost', fieldID/(svci[4]*2) - ndisplayed, - print 'frames' - return - -main() diff --git a/Demo/sgi/sv/rgbgrab.py b/Demo/sgi/sv/rgbgrab.py deleted file mode 100755 index 8013a531f4..0000000000 --- a/Demo/sgi/sv/rgbgrab.py +++ /dev/null @@ -1,81 +0,0 @@ -import sys -import sv, SV -import gl, GL, DEVICE -import time - -def main(): - v = sv.OpenVideo() - # Determine maximum window size based on signal standard - param = [SV.BROADCAST, 0] - v.GetParam(param) - if param[1] == SV.PAL: - width = SV.PAL_XMAX - height = SV.PAL_YMAX - elif param[1] == SV.NTSC: - width = SV.NTSC_XMAX - height = SV.NTSC_YMAX - else: - print 'Unknown video standard', param[1] - sys.exit(1) - - # Initially all windows are half size - grabwidth, grabheight = width/2, height/2 - - # Open still window - gl.foreground() - gl.prefsize(grabwidth, grabheight) - still_win = gl.winopen('Grabbed frame') - gl.keepaspect(width, height) - gl.maxsize(width, height) - gl.winconstraints() - gl.RGBmode() - gl.gconfig() - gl.clear() - gl.pixmode(GL.PM_SIZE, 8) - - # Open live window - gl.foreground() - gl.prefsize(grabwidth, grabheight) - live_win = gl.winopen('Live video') - gl.keepaspect(width, height) - gl.maxsize(width, height) - gl.winconstraints() - - # Bind live video - v.SetSize(gl.getsize()) - v.BindGLWindow(live_win, SV.IN_REPLACE) - - print 'Use leftmouse to grab frame' - - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - frame = None - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE and val == 0: - w, h, fields = v.CaptureOneFrame(SV.RGB8_FRAMES, \ - grabwidth, grabheight) - frame = sv.InterleaveFields(1, fields, w, h) - gl.winset(still_win) - gl.lrectwrite(0, 0, w - 1, h - 1, frame) - gl.winset(live_win) - if dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - v.CloseVideo() - gl.winclose(live_win) - gl.winclose(still_win) - break - if dev == DEVICE.REDRAW and val == still_win: - gl.winset(still_win) - gl.reshapeviewport() - gl.clear() - grabwidth, grabheight = gl.getsize() - if frame: - gl.lrectwrite(0, 0, w - 1, h - 1, frame) - gl.winset(live_win) - if dev == DEVICE.REDRAW and val == live_win: - v.SetSize(gl.getsize()) - v.BindGLWindow(live_win, SV.IN_REPLACE) - -main() diff --git a/Demo/sgi/sv/simpleinput.py b/Demo/sgi/sv/simpleinput.py deleted file mode 100755 index 97b75fafb0..0000000000 --- a/Demo/sgi/sv/simpleinput.py +++ /dev/null @@ -1,22 +0,0 @@ -import sv, SV -import gl, DEVICE - -def main(): - gl.foreground() - gl.prefsize(SV.PAL_XMAX, SV.PAL_YMAX) - win = gl.winopen('video test') - v = sv.OpenVideo() - params = [SV.VIDEO_MODE, SV.COMP, SV.BROADCAST, SV.PAL] - v.SetParam(params) - v.BindGLWindow(win, SV.IN_REPLACE) - gl.qdevice(DEVICE.ESCKEY) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - while 1: - dev, val = gl.qread() - if dev in (DEVICE.ESCKEY, DEVICE.WINSHUT, DEVICE.WINQUIT): - v.CloseVideo() - gl.winclose(win) - return - -main() diff --git a/Demo/sgi/video/.cvsignore b/Demo/sgi/video/.cvsignore deleted file mode 100755 index fb9700bf02..0000000000 --- a/Demo/sgi/video/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -i2v -v2i diff --git a/Demo/sgi/video/DisplayVideoIn.py b/Demo/sgi/video/DisplayVideoIn.py deleted file mode 100755 index 6dbc7bcc38..0000000000 --- a/Demo/sgi/video/DisplayVideoIn.py +++ /dev/null @@ -1,99 +0,0 @@ -# Live video input from display class. - -import gl -import GL - -# The live video input class. -# Only instantiate this if have_video is true! - -class DisplayVideoIn: - - # Initialize an instance. Arguments: - # vw, vh: size of the video window data to be captured. - # position defaults to 0, 0 but can be set later - def __init__(self, pktmax, vw, vh, type): - self.pktmax = pktmax - self.realwidth, self.realheight = vw, vh - if type <> 'rgb': - raise 'Incorrent video data type', type - self.type = type - self.width = vw - self.height = vh - # - # Open dummy window - # - gl.foreground() - gl.noport() - self.wid = gl.winopen('DisplayVideoIn') - - self.x0 = 0 - self.x1 = self.x0 + self.width - 1 - self.y0 = 0 - self.y1 = self.y0 + self.height - 1 - # Compute # full lines per packet - self.lpp = pktmax / self.linewidth() - if self.lpp <= 0: - raise 'No lines in packet', self.linewidth() - self.pktsize = self.lpp*self.linewidth() - self.data = None - self.old_data = None - self.dataoffset = 0 - self.lpos = 0 - self.hints = 0 - - # Change the size of the video being displayed. - - def resizevideo(self, vw, vh): - self.width = vw - self.height = vh - self.x1 = self.x0 + self.width - 1 - self.y1 = self.y0 + self.height - 1 - - def positionvideo(self, x, y): - self.x0 = x - self.y0 = y - self.x1 = self.x0 + self.width - 1 - self.y1 = self.y0 + self.height - 1 - - # Remove an instance. - # This turns off continuous capture. - - def close(self): - gl.winclose(self.wid) - - # Get the length in bytes of a video line - def linewidth(self): - return self.width*4 - - # Get the next video packet. - # This returns (lpos, data) where: - # - lpos is the line position - # - data is a piece of data - # The dimensions of data are: - # - pixel depth = 1 byte - # - scan line width = self.width (the vw argument to __init__()) - # - number of scan lines = self.lpp (PKTMAX / vw) - - def getnextpacket(self): - if not self.data or self.dataoffset >= len(self.data): - self.old_data = self.data - self.data = gl.readdisplay(self.x0, self.y0, \ - self.x1, self.y1, self.hints) - self.dataoffset = 0 - self.lpos = 0 - data = self.data[self.dataoffset:self.dataoffset+self.pktsize] - while self.old_data and \ - self.dataoffset+self.pktsize < len(self.data): - odata = self.old_data[self.dataoffset: \ - self.dataoffset+self.pktsize] - if odata <> data: - break - print 'skip', self.lpos - self.lpos = self.lpos + self.lpp - self.dataoffset = self.dataoffset + self.pktsize - data = self.data[self.dataoffset:\ - self.dataoffset+self.pktsize] - lpos = self.lpos - self.dataoffset = self.dataoffset + self.pktsize - self.lpos = self.lpos + self.lpp - return lpos, data diff --git a/Demo/sgi/video/Dsend.py b/Demo/sgi/video/Dsend.py deleted file mode 100755 index da94c6f78a..0000000000 --- a/Demo/sgi/video/Dsend.py +++ /dev/null @@ -1,188 +0,0 @@ -#!/ufs/guido/bin/sgi/python - -# Send live video UDP packets. -# Usage: Vsend [-b] [-h height] [-p port] [-s size] [-t ttl] [-w width] -# [host] .. - -import sys -import time -import struct -import string -import math -from socket import * -from SOCKET import * -import gl, GL, DEVICE -sys.path.append('/ufs/guido/src/video') -import DisplayVideoIn -import LiveVideoOut -import SV -import getopt -from IN import * - -from senddefs import * - -def usage(msg): - print msg - print 'usage: Vsend [-b] [-h height] [-p port] [-s size] [-t ttl] [-c type] [-m]', - print '[-w width] [host] ...' - print '-b : broadcast on local net' - print '-h height : window height (default ' + `DEFHEIGHT` + ')' - print '-p port : port to use (default ' + `DEFPORT` + ')' - print '-t ttl : time-to-live (multicast only; default 1)' - print '-s size : max packet size (default ' + `DEFPKTMAX` + ')' - print '-S size : use this packet size/window size' - print '-w width : window width (default ' + `DEFWIDTH` + ')' - print '-v : print packet rate' - print '-x xpos : set x position' - print '-y ypos : set y position' - print '[host] ...: host(s) to send to (default multicast to ' + \ - DEFMCAST + ')' - sys.exit(2) - - -def main(): - sys.stdout = sys.stderr - - hosts = [] - port = DEFPORT - ttl = -1 - pktmax = DEFPKTMAX - width = DEFWIDTH - height = DEFHEIGHT - vtype = 'rgb' - verbose = 0 - xpos = ypos = 0 - - try: - opts, args = getopt.getopt(sys.argv[1:], 'bh:p:s:S:t:w:vx:y:') - except getopt.error, msg: - usage(msg) - - try: - for opt, optarg in opts: - if opt == '-p': - port = string.atoi(optarg) - if opt == '-b': - host = '' - if opt == '-t': - ttl = string.atoi(optarg) - if opt == '-S': - pktmax = string.atoi(optarg) - vidmax = SV.PAL_XMAX*SV.PAL_YMAX - if vidmax <= pktmax: - width = SV.PAL_XMAX - height = SV.PAL_YMAX - pktmax = vidmax - else: - factor = float(vidmax)/float(pktmax) - factor = math.sqrt(factor) - width = int(SV.PAL_XMAX/factor)-7 - height = int(SV.PAL_YMAX/factor)-5 - print 'video:',width,'x',height, - print 'pktsize',width*height,'..', - print pktmax - if opt == '-s': - pktmax = string.atoi(optarg) - if opt == '-w': - width = string.atoi(optarg) - if opt == '-h': - height = string.atoi(optarg) - if opt == '-c': - vtype = optarg - if opt == '-v': - verbose = 1 - if opt == '-x': - xpos = string.atoi(optarg) - if opt == '-y': - ypos = string.atoi(optarg) - except string.atoi_error, msg: - usage('bad integer: ' + msg) - - for host in args: - hosts.append(gethostbyname(host)) - - if not hosts: - hosts.append(gethostbyname(DEFMCAST)) - - gl.foreground() - gl.prefsize(width, height) - gl.stepunit(8, 6) - wid = gl.winopen('Vsend') - gl.keepaspect(width, height) - gl.stepunit(8, 6) - gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) - gl.winconstraints() - gl.qdevice(DEVICE.ESCKEY) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINFREEZE) - gl.qdevice(DEVICE.WINTHAW) - width, height = gl.getsize() - - lvo = LiveVideoOut.LiveVideoOut(wid, width, height, vtype) - - lvi = DisplayVideoIn.DisplayVideoIn(pktmax, width, height, vtype) - - if xpos or ypos: - lvi.positionvideo(xpos, ypos) - - s = socket(AF_INET, SOCK_DGRAM) - s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) - if ttl >= 0: - s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, chr(ttl)) - - frozen = 0 - - lasttime = int(time.time()) - nframe = 0 - while 1: - - if gl.qtest(): - dev, val = gl.qread() - if dev in (DEVICE.ESCKEY, \ - DEVICE.WINSHUT, DEVICE.WINQUIT): - break - if dev == DEVICE.WINFREEZE: - frozen = 1 - if dev == DEVICE.WINTHAW: - frozen = 0 - if dev == DEVICE.REDRAW: - w, h = gl.getsize() - x, y = gl.getorigin() - if (w, h) <> (width, height): - width, height = w, h - lvi.resizevideo(width, height) - lvo.resizevideo(width, height) - - rv = lvi.getnextpacket() - if not rv: - time.sleep(0.010) - continue - - pos, data = rv - print pos, len(data) # DBG - - if not frozen: - lvo.putnextpacket(pos, data) - - hdr = struct.pack('hhh', pos, width, height) - for host in hosts: - try: - # print len(hdr+data) # DBG - s.sendto(hdr + data, (host, port)) - except error, msg: # really socket.error - if msg[0] <> 121: # no buffer space available - raise error, msg # re-raise it - print 'Warning:', msg[1] - if pos == 0 and verbose: - nframe = nframe+1 - if int(time.time()) <> lasttime: - print nframe / (time.time()-lasttime), 'fps' - nframe = 0 - lasttime = int(time.time()) - - lvi.close() - lvo.close() - - -main() diff --git a/Demo/sgi/video/IN.py b/Demo/sgi/video/IN.py deleted file mode 100755 index ffc2852596..0000000000 --- a/Demo/sgi/video/IN.py +++ /dev/null @@ -1,54 +0,0 @@ -IPPROTO_IP = 0 -IPPROTO_ICMP = 1 -IPPROTO_IGMP = 2 -IPPROTO_GGP = 3 -IPPROTO_TCP = 6 -IPPROTO_EGP = 8 -IPPROTO_PUP = 12 -IPPROTO_UDP = 17 -IPPROTO_IDP = 22 -IPPROTO_TP = 29 -IPPROTO_XTP = 36 -IPPROTO_EON = 80 -IPPROTO_RAW = 255 -IPPROTO_MAX = 256 -IPPORT_RESERVED = 1024 -IPPORT_USERRESERVED = 5000 -IN_CLASSA_NET = 0xff000000 -IN_CLASSA_NSHIFT = 24 -IN_CLASSA_HOST = 0x00ffffff -IN_CLASSA_MAX = 128 -IN_CLASSB_NET = 0xffff0000 -IN_CLASSB_NSHIFT = 16 -IN_CLASSB_HOST = 0x0000ffff -IN_CLASSB_MAX = 65536 -IN_CLASSC_NET = 0xffffff00 -IN_CLASSC_NSHIFT = 8 -IN_CLASSC_HOST = 0x000000ff -IN_CLASSD_NET = 0xf0000000 -IN_CLASSD_NSHIFT = 28 -IN_CLASSD_HOST = 0x0fffffff -INADDR_ANY = 0x00000000 -INADDR_BROADCAST = 0xffffffff -INADDR_LOOPBACK = 0x7F000001 -INADDR_UNSPEC_GROUP = 0xe0000000 -INADDR_ALLHOSTS_GROUP = 0xe0000001 -INADDR_MAX_LOCAL_GROUP = 0xe00000ff -INADDR_NONE = 0xffffffff -IN_LOOPBACKNET = 127 -IP_OPTIONS = 1 -IP_HDRINCL = 7 -IP_TOS = 8 -IP_TTL = 9 -IP_RECVOPTS = 10 -IP_RECVRETOPTS = 11 -IP_RECVDSTADDR = 12 -IP_RETOPTS = 13 -IP_MULTICAST_IF = 2 -IP_MULTICAST_TTL = 3 -IP_MULTICAST_LOOP = 4 -IP_ADD_MEMBERSHIP = 5 -IP_DROP_MEMBERSHIP = 6 -IP_DEFAULT_MULTICAST_TTL = 1 -IP_DEFAULT_MULTICAST_LOOP = 1 -IP_MAX_MEMBERSHIPS = 20 diff --git a/Demo/sgi/video/LiveVideoIn.py b/Demo/sgi/video/LiveVideoIn.py deleted file mode 100755 index 661ea738b2..0000000000 --- a/Demo/sgi/video/LiveVideoIn.py +++ /dev/null @@ -1,139 +0,0 @@ -# Live video input class. -# Note that importing this module attempts to initialize video. - - -# Check if video is available. -# There are three reasons for failure here: -# (1) this version of Python may not have the sv or imageop modules; -# (2) this machine may not have a video board; -# (3) initializing the video board may fail for another reason. -# The global variable have_video is set to true iff we reall do have video. - -try: - import sv - import SV - import imageop - try: - v = sv.OpenVideo() - have_video = 1 - except sv.error: - have_video = 0 -except ImportError: - have_video = 0 - - -# The live video input class. -# Only instantiate this if have_video is true! - -class LiveVideoIn: - - # Initialize an instance. Arguments: - # vw, vh: size of the video window data to be captured. - # For some reason, vw MUST be a multiple of 4. - # Note that the data has to be cropped unless vw and vh are - # just right for the video board (vw:vh == 4:3 and vh even). - - def __init__(self, pktmax, vw, vh, type): - if not have_video: - raise RuntimeError, 'no video available' - if vw % 4 != 0: - raise ValueError, 'vw must be a multiple of 4' - self.pktmax = pktmax - realvw = vh*SV.PAL_XMAX/SV.PAL_YMAX - if realvw < vw: - realvw = vw - self.realwidth, self.realheight = v.QuerySize(realvw, vh) - if not type in ('rgb8', 'grey', 'mono', 'grey2', 'grey4'): - raise 'Incorrent video data type', type - self.type = type - if type in ('grey', 'grey4', 'grey2', 'mono'): - v.SetParam([SV.COLOR, SV.MONO, SV.INPUT_BYPASS, 1]) - else: - v.SetParam([SV.COLOR, SV.DEFAULT_COLOR, \ - SV.INPUT_BYPASS, 0]) - # Initialize capture - (mode, self.realwidth, self.realheight, qsize, rate) = \ - v.InitContinuousCapture(SV.RGB8_FRAMES, \ - self.realwidth, self.realheight, 1, 2) - self.width = vw - self.height = vh - self.x0 = (self.realwidth-self.width)/2 - self.x1 = self.x0 + self.width - 1 - self.y0 = (self.realheight-self.height)/2 - self.y1 = self.y0 + self.height - 1 - # Compute # full lines per packet - self.lpp = pktmax / self.linewidth() - self.pktsize = self.lpp*self.linewidth() - self.data = None - self.dataoffset = 0 - self.lpos = 0 - self.justright = (self.realwidth == self.width and \ - self.realheight == self.height) -## if not self.justright: -## print 'Want:', self.width, 'x', self.height, -## print '; grab:', self.realwidth, 'x', self.realheight - - # Change the size of the video being displayed. - - def resizevideo(self, vw, vh): - self.close() - self.__init__(self.pktmax, vw, vh, self.type) - - # Remove an instance. - # This turns off continuous capture. - - def close(self): - v.EndContinuousCapture() - - # Get the length in bytes of a video line - def linewidth(self): - if self.type == 'mono': - return (self.width+7)/8 - elif self.type == 'grey2': - return (self.width+3)/4 - elif self.type == 'grey4': - return (self.width+1)/2 - else: - return self.width - - # Get the next video packet. - # This returns (lpos, data) where: - # - lpos is the line position - # - data is a piece of data - # The dimensions of data are: - # - pixel depth = 1 byte - # - scan line width = self.width (the vw argument to __init__()) - # - number of scan lines = self.lpp (PKTMAX / vw) - - def getnextpacket(self): - if not self.data or self.dataoffset >= len(self.data): - try: - cd, id = v.GetCaptureData() - except sv.error: - return None - data = cd.InterleaveFields(1) - cd.UnlockCaptureData() - if self.justright: - self.data = data - else: - self.data = imageop.crop(data, 1, \ - self.realwidth, \ - self.realheight, \ - self.x0, self.y0, \ - self.x1, self.y1) - self.lpos = 0 - self.dataoffset = 0 - if self.type == 'mono': - self.data = imageop.dither2mono(self.data, \ - self.width, self.height) - elif self.type == 'grey2': - self.data = imageop.dither2grey2(self.data, \ - self.width, self.height) - elif self.type == 'grey4': - self.data = imageop.grey2grey4(self.data, \ - self.width, self.height) - data = self.data[self.dataoffset:self.dataoffset+self.pktsize] - lpos = self.lpos - self.dataoffset = self.dataoffset + self.pktsize - self.lpos = self.lpos + self.lpp - return lpos, data diff --git a/Demo/sgi/video/LiveVideoOut.py b/Demo/sgi/video/LiveVideoOut.py deleted file mode 100755 index 6ee1846d41..0000000000 --- a/Demo/sgi/video/LiveVideoOut.py +++ /dev/null @@ -1,130 +0,0 @@ -# Live video output (display video on the screen, presumably from the net) - -import gl -from VFile import Displayer - - -# Video output (displayer) class. - -class LiveVideoOut: - - # Call this to initialize things. Arguments: - # wid: the window id where the video is to be displayed (centered) - # vw, vh: size of the video image to be displayed - - def __init__(self, wid, vw, vh, type): - ##print 'Init', wid, xywh - ##print 'video', vw, vw - self.vw = vw - self.vh = vh - self.disp = Displayer() - if not type in ('rgb', 'rgb8', 'grey', 'mono', 'grey2', \ - 'grey4'): - raise 'Incorrent live video output type', type - if type == 'rgb': - info = (type, vw, vh, 0, 32, 0, 0, 0, 0) - else: - info = (type, vw, vh, 1, 8, 0, 0, 0, 0) - self.disp.setinfo(info) - self.wid = wid - oldwid = gl.winget() - gl.winset(wid) - self.disp.initcolormap() - self.reshapewindow() - gl.winset(oldwid) - - # Call this in response to every REDRAW event for the window - # or if the window size has changed for other reasons. - - def reshapewindow(self): - oldwid = gl.winget() - gl.winset(self.wid) - gl.reshapeviewport() - w, h = gl.getsize() - self.disp.xorigin = (w-self.vw)/2 - self.disp.yorigin = (h-self.vh)/2 - self.disp.clear() - gl.winset(oldwid) - - # Call this to change the size of the video images being displayed. - # Implies reshapewindow(). - - def resizevideo(self, vw, vh): - self.vw, self.vh = vw, vh - self.disp.setsize(vw, vh) - self.reshapewindow() - - # Return the number of bytes in one video line - def linewidth(self): - if self.disp.format == 'rgb': - return self.vw*4 - if self.disp.format == 'mono': - return (self.vw+7)/8 - elif self.disp.format == 'grey2': - return (self.vw+3)/4 - elif self.disp.format == 'grey4': - return (self.vw+1)/2 - else: - return self.vw - - # Call this to display the next video packet. Arguments: - # pos: line number where the packet begins - # data: image data of the packet - # (these correspond directly to the return values from - # LiveVideoIn.getnextpacket()). - - def putnextpacket(self, pos, data): - nline = len(data)/self.linewidth() - if nline*self.linewidth() <> len(data): - print 'Incorrect-sized video fragment ignored' - return - oldwid = gl.winget() - gl.winset(self.wid) - self.disp.showpartframe(data, None, (0, pos, self.vw, nline)) - gl.winset(oldwid) - - # Call this to close the window. - - def close(self): - pass - - # Call this to set optional mirroring of video - def setmirror(self, mirrored): - f, w, h, pf, c0, c1, c2, o, cp = self.disp.getinfo() - if type(pf) == type(()): - xpf, ypf = pf - else: - xpf = ypf = pf - xpf = abs(xpf) - if mirrored: - xpf = -xpf - info = (f, w, h, (xpf, ypf), c0, c1, c2, o, cp) - self.disp.setinfo(info) - self.disp.initcolormap() - self.disp.clear() - -# -# This derived class has one difference with the base class: the video is -# not displayed until an entire image has been gotten -# -class LiveVideoOutSlow(LiveVideoOut): - - # Reshapewindow - Realloc buffer. - # (is also called by __init__() indirectly) - - def reshapewindow(self): - LiveVideoOut.reshapewindow(self) - self.buffer = '\0'*self.linewidth()*self.vh - self.isbuffered = [] - - # putnextpacket - buffer incoming data until a complete - # image has been received - - def putnextpacket(self, pos, data): - if pos in self.isbuffered or pos == 0: - LiveVideoOut.putnextpacket(self, 0, self.buffer) - self.isbuffered = [] - self.isbuffered.append(pos) - bpos = pos * self.linewidth() - epos = bpos + len(data) - self.buffer = self.buffer[:bpos] + data + self.buffer[epos:] diff --git a/Demo/sgi/video/Makefile b/Demo/sgi/video/Makefile deleted file mode 100755 index 266ea52587..0000000000 --- a/Demo/sgi/video/Makefile +++ /dev/null @@ -1,7 +0,0 @@ -all: v2i i2v - -v2i: v2i.o - $(CC) v2i.o -limage -o v2i - -i2v: i2v.o - $(CC) i2v.o -limage -o i2v diff --git a/Demo/sgi/video/OldVcopy.py b/Demo/sgi/video/OldVcopy.py deleted file mode 100755 index 61461f40a6..0000000000 --- a/Demo/sgi/video/OldVcopy.py +++ /dev/null @@ -1,148 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -# Copy a video file, interactively, frame-by-frame. - -import sys -import getopt -from gl import * -from DEVICE import * -import VFile -import VGrabber -import string -import imageop - -def report(time, iframe): - print 'Frame', iframe, ': t =', time - -def usage(): - sys.stderr.write('usage: Vcopy [-t type] [-m treshold] [-a] infile outfile\n') - sys.stderr.write('-t Convert to other type\n') - sys.stderr.write('-a Automatic\n') - sys.stderr.write('-m Convert grey to mono with treshold\n') - sys.stderr.write('-d Convert grey to mono with dithering\n') - sys.exit(2) - -def help(): - print 'Command summary:' - print 'n get next image from input' - print 'w write current image to output' - -class GrabbingVoutFile(VFile.VoutFile, VGrabber.VGrabber): - pass - -def main(): - foreground() - try: - opts, args = getopt.getopt(sys.argv[1:], 't:am:d') - except getopt.error, msg: - print msg - usage() - if len(args) <> 2: - usage() - [ifile, ofile] = args - print 'open film ', ifile - ifilm = VFile.VinFile(ifile) - print 'open output ', ofile - ofilm = GrabbingVoutFile(ofile) - - ofilm.setinfo(ifilm.getinfo()) - - use_grabber = 0 - continuous = 0 - tomono = 0 - tomonodither = 0 - for o, a in opts: - if o == '-t': - ofilm.format = a - use_grabber = 1 - if o == '-a': - continuous = 1 - if o == '-m': - if ifilm.format <> 'grey': - print '-m only supported for greyscale' - sys.exit(1) - tomono = 1 - treshold = string.atoi(a) - ofilm.format = 'mono' - if o == '-d': - if ifilm.format <> 'grey': - print '-m only supported for greyscale' - sys.exit(1) - tomonodither = 1 - ofilm.format = 'mono' - - ofilm.writeheader() - # - prefsize(ifilm.width, ifilm.height) - w = winopen(ifile) - qdevice(KEYBD) - qdevice(ESCKEY) - qdevice(WINQUIT) - qdevice(WINSHUT) - print 'qdevice calls done' - # - help() - # - time, data, cdata = ifilm.getnextframe() - ifilm.showframe(data, cdata) - iframe = 1 - report(time, iframe) - # - while 1: - if continuous: - dev = KEYBD - else: - dev, val = qread() - if dev in (ESCKEY, WINQUIT, WINSHUT): - break - if dev == REDRAW: - reshapeviewport() - elif dev == KEYBD: - if continuous: - c = '0' - else: - c = chr(val) - #XXX Debug - if c == 'R': - c3i(255,0,0) - clear() - if c == 'G': - c3i(0,255,0) - clear() - if c == 'B': - c3i(0,0,255) - clear() - if c == 'w' or continuous: - if use_grabber: - try: - data, cdata = ofilm.grabframe() - except VFile.Error, msg: - print msg - break - if tomono: - data = imageop.grey2mono(data, \ - ifilm.width, ifilm.height, \ - treshold) - if tomonodither: - data = imageop.dither2mono(data, \ - ifilm.width, ifilm.height) - ofilm.writeframe(time, data, cdata) - print 'Frame', iframe, 'written.' - if c == 'n' or continuous: - try: - time,data,cdata = ifilm.getnextframe() - ifilm.showframe(data, cdata) - iframe = iframe+1 - report(time, iframe) - except EOFError: - print 'EOF' - if continuous: - break - ringbell() - elif dev == INPUTCHANGE: - pass - else: - print '(dev, val) =', (dev, val) - ofilm.close() - -main() diff --git a/Demo/sgi/video/README b/Demo/sgi/video/README deleted file mode 100644 index 6abe698795..0000000000 --- a/Demo/sgi/video/README +++ /dev/null @@ -1,113 +0,0 @@ -CMIF video tools -================ - -This directory contains Python and C programs to manipulate files -containing digitized video in the "CMIF video format". - -An introduction to using the basic tools is in the file "video.doc". - -A description of the video file format is in the file "cmif-film.ms" -(troff/nroff -ms input). - - -History -------- - -We started this in October 1991, when we had a large framegrabber -board on loan from SGI for a few weeks: we developed a movie recording -program and added numerous features, including still frame capture and -synchronous sound recording using a second machine (the machine -holding the framegrabber board didn't have audio). - -During the following months, when we started using and processing the -recorded film fragments, the "CMIF video format" was revised several -times, and we eventually created an object-oriented interface for -reading and writing various incarnations of these files, called VFile. -(This module is also used by our flagship application, the CMIF -editor, not in this directory but in /ufs/guido/mm/.) - -When we got our own Indigo entry-level video board (in June 1992) and -a version of the Irix video library that supported capturing PAL -format (in August 1992), Sjoerd added an interface to the video -library to Python (sv) and Guido wrote Vrec.py (based upon a still -frame grabber by Sjoerd, in turn based upon SGI demo code in C) to -record a movie using it. Vrec was soon followed by modernized -versions of the other programs (Vinfo, Vplay, Vtime) and an -interactive editor (Vedit). Finally, VFile was rewritten for more -modularity, functionality and robustness, and various other tools were -added as needed. Also, new options were added to existing tools, and -several new video file formats were added. - - Guido van Rossum - Jack Jansen - Sjoerd Mullender - - -Overview of files ------------------ - -cmif-film.ms description of the CMIF video file format (more than a - little out of date -- read the source for VFile for - more info about new file formats) - - -These are programs with a command line interface: - -Vrec.py record video movies using the Indigo video library and - board - -Vplay.py play video movies - -Vinfo.py show statistics on movies - -Vtime.py Copy a video file, manipulating the time codes (e.g. - faster/slower, or regenerate time codes, or drop - frames too close apart) - -Vcopy.py Universal video file copying tool. Can manipulate the - time codes, change the type, size, and packfactor. - Subsumes Vtime.py. - -Vmkjpeg.py compress an rgb or grey video file to jpeg[grey] format - -Vunjpeg.py expand a jpeg[grey] video file to rgb or grey format - -Vfix.py truncate the scan line width of a video file to - a multiple of 4 ('grey' images only) - -Vedit.py interactive video editing program (uses the FORMS library) - -Vsend.py unicast or multicast live video as UDP packets - -Vreceive.py receive transmissions from Vsend - -Vaddcache.py add a "cached index" to a video file, for faster playing - -Vrecb.py like Vrec.py but uses "burst capture" -- somewhat specialized - -Dsend.py like Vsend.py but sends screen snapshots (to Vreceive.py) - -DisplayVideoIn.py Like LiveVideoIn.py but reads screen snapshots - -rgb2video.py combine a sequence of rgb image files into a CMIF video file - -video2rgb.py split a CMIF video file into a sequence of rgb image files - - -These modules and files are used by the above programs: - -VFile.py classes that read and write CMIF video files - -Viewer.py two viewer classes used by Vedit - -LiveVideoIn.py live video input class, used by Vsend - -LiveVideoOut.py live video output class, used by Vsend and Vreceive - -imgconv.py Image conversion subroutines for rgb2video.py - -senddefs.py Defaults shared by Vsend and Vreceice - -watchcursor.py Generally useful module to define a watch cursor in GL - -VeditForm.fd FORMS' fdesign definition for Vedit's form diff --git a/Demo/sgi/video/VCR.py b/Demo/sgi/video/VCR.py deleted file mode 100755 index 535a7da3eb..0000000000 --- a/Demo/sgi/video/VCR.py +++ /dev/null @@ -1,534 +0,0 @@ -import fcntl -import IOCTL -from IOCTL import * -import sys -import struct -import select -import posix -import time - -DEVICE='/dev/ttyd2' - -class UnixFile: - def open(self, name, mode): - self.fd = posix.open(name, mode) - return self - - def read(self, len): - return posix.read(self.fd, len) - - def write(self, data): - dummy = posix.write(self.fd, data) - - def flush(self): - pass - - def fileno(self): - return self.fd - - def close(self): - dummy = posix.close(self.fd) - -def packttyargs(*args): - if type(args) <> type(()): - raise 'Incorrect argtype for packttyargs' - if type(args[0]) == type(1): - iflag, oflag, cflag, lflag, line, chars = args - elif type(args[0]) == type(()): - if len(args) <> 1: - raise 'Only 1 argument expected' - iflag, oflag, cflag, lflag, line, chars = args[0] - elif type(args[0]) == type([]): - if len(args) <> 1: - raise 'Only 1 argument expected' - [iflag, oflag, cflag, lflag, line, chars] = args[0] - str = struct.pack('hhhhb', iflag, oflag, cflag, lflag, line) - for c in chars: - str = str + c - return str - -def nullttyargs(): - chars = ['\0']*IOCTL.NCCS - return packttyargs(0, 0, 0, 0, 0, chars) - -def unpackttyargs(str): - args = str[:-IOCTL.NCCS] - rawchars = str[-IOCTL.NCCS:] - chars = [] - for c in rawchars: - chars.append(c) - iflag, oflag, cflag, lflag, line = struct.unpack('hhhhb', args) - return (iflag, oflag, cflag, lflag, line, chars) - -def initline(name): - fp = UnixFile().open(name, 2) - ofp = fp - fd = fp.fileno() - rv = fcntl.ioctl(fd, IOCTL.TCGETA, nullttyargs()) - iflag, oflag, cflag, lflag, line, chars = unpackttyargs(rv) - iflag = iflag & ~(INPCK|ISTRIP|INLCR|IUCLC|IXON|IXOFF) - oflag = oflag & ~OPOST - cflag = B9600|CS8|CREAD|CLOCAL - lflag = lflag & ~(ISIG|ICANON|ECHO|TOSTOP) - chars[VMIN] = chr(1) - chars[VTIME] = chr(0) - arg = packttyargs(iflag, oflag, cflag, lflag, line, chars) - dummy = fcntl.ioctl(fd, IOCTL.TCSETA, arg) - return fp, ofp - -# -# -error = 'VCR.error' - -# Commands/replies: -COMPLETION = '\x01' -ACK ='\x0a' -NAK ='\x0b' - -NUMBER_N = 0x30 -ENTER = '\x40' - -EXP_7= '\xde' -EXP_8= '\xdf' - -CL ='\x56' -CTRL_ENABLE = EXP_8 + '\xc6' -SEARCH_DATA = EXP_8 + '\x93' -ADDR_SENSE = '\x60' - -PLAY ='\x3a' -STOP ='\x3f' -EJECT='\x2a' -FF ='\xab' -REW ='\xac' -STILL='\x4f' -STEP_FWD ='\x2b' # Was: '\xad' -FM_SELECT=EXP_8 + '\xc8' -FM_STILL=EXP_8 + '\xcd' -PREVIEW=EXP_7 + '\x9d' -REVIEW=EXP_7 + '\x9e' -DM_OFF=EXP_8 + '\xc9' -DM_SET=EXP_8 + '\xc4' -FWD_SHUTTLE='\xb5' -REV_SHUTTLE='\xb6' -EM_SELECT=EXP_8 + '\xc0' -N_FRAME_REC=EXP_8 + '\x92' -SEARCH_PREROLL=EXP_8 + '\x90' -EDIT_PB_STANDBY=EXP_8 + '\x96' -EDIT_PLAY=EXP_8 + '\x98' -AUTO_EDIT=EXP_7 + '\x9c' - -IN_ENTRY=EXP_7 + '\x90' -IN_ENTRY_RESET=EXP_7 + '\x91' -IN_ENTRY_SET=EXP_7 + '\x98' -IN_ENTRY_INC=EXP_7 + '\x94' -IN_ENTRY_DEC=EXP_7 + '\x95' -IN_ENTRY_SENSE=EXP_7 + '\x9a' - -OUT_ENTRY=EXP_7 + '\x92' -OUT_ENTRY_RESET=EXP_7 + '\x93' -OUT_ENTRY_SET=EXP_7 + '\x99' -OUT_ENTRY_INC=EXP_7 + '\x96' -OUT_ENTRY_DEC=EXP_7 + '\x98' -OUT_ENTRY_SENSE=EXP_7 + '\x9b' - -MUTE_AUDIO = '\x24' -MUTE_AUDIO_OFF = '\x25' -MUTE_VIDEO = '\x26' -MUTE_VIDEO_OFF = '\x27' -MUTE_AV = EXP_7 + '\xc6' -MUTE_AV_OFF = EXP_7 + '\xc7' - -DEBUG=0 - -class VCR: - def __init__(self): - self.ifp, self.ofp = initline(DEVICE) - self.busy_cmd = None - self.async = 0 - self.cb = None - self.cb_arg = None - - def _check(self): - if self.busy_cmd: - raise error, 'Another command active: '+self.busy_cmd - - def _endlongcmd(self, name): - if not self.async: - self.waitready() - return 1 - self.busy_cmd = name - return 'VCR BUSY' - - def fileno(self): - return self.ifp.fileno() - - def setasync(self, async): - self.async = async - - def setcallback(self, cb, arg): - self.setasync(1) - self.cb = cb - self.cb_arg = arg - - def poll(self): - if not self.async: - raise error, 'Can only call poll() in async mode' - if not self.busy_cmd: - return - if self.testready(): - if self.cb: - apply(self.cb, (self.cb_arg,)) - - def _cmd(self, cmd): - if DEBUG: - print '>>>',`cmd` - self.ofp.write(cmd) - self.ofp.flush() - - def _waitdata(self, len, tout): - rep = '' - while len > 0: - if tout == None: - ready, d1, d2 = select.select( \ - [self.ifp], [], []) - else: - ready, d1, d2 = select.select( \ - [self.ifp], [], [], tout) - if ready == []: -## if rep: -## print 'FLUSHED:', `rep` - return None - data = self.ifp.read(1) - if DEBUG: - print '<<<',`data` - if data == NAK: - return NAK - rep = rep + data - len = len - 1 - return rep - - def _reply(self, len): - data = self._waitdata(len, 10) - if data == None: - raise error, 'Lost contact with VCR' - return data - - def _getnumber(self, len): - data = self._reply(len) - number = 0 - for c in data: - digit = ord(c) - NUMBER_N - if digit < 0 or digit > 9: - raise error, 'Non-digit in number'+`c` - number = number*10 + digit - return number - - def _iflush(self): - dummy = self._waitdata(10000, 0) -## if dummy: -## print 'IFLUSH:', dummy - - def simplecmd(self,cmd): - self._iflush() - for ch in cmd: - self._cmd(ch) - rep = self._reply(1) - if rep == NAK: - return 0 - elif rep <> ACK: - raise error, 'Unexpected reply:' + `rep` - return 1 - - def replycmd(self, cmd): - if not self.simplecmd(cmd[:-1]): - return 0 - self._cmd(cmd[-1]) - - def _number(self, number, digits): - if number < 0: - raise error, 'Unexpected negative number:'+ `number` - maxnum = pow(10, digits) - if number > maxnum: - raise error, 'Number too big' - while maxnum > 1: - number = number % maxnum - maxnum = maxnum / 10 - digit = number / maxnum - ok = self.simplecmd(chr(NUMBER_N + digit)) - if not ok: - raise error, 'Error while transmitting number' - - def initvcr(self, *optarg): - timeout = None - if optarg <> (): - timeout = optarg[0] - starttime = time.time() - self.busy_cmd = None - self._iflush() - while 1: -## print 'SENDCL' - self._cmd(CL) - rep = self._waitdata(1, 2) -## print `rep` - if rep in ( None, CL, NAK ): - if timeout: - if time.time() - starttime > timeout: - raise error, \ - 'No reply from VCR' - continue - break - if rep <> ACK: - raise error, 'Unexpected reply:' + `rep` - dummy = self.simplecmd(CTRL_ENABLE) - - def waitready(self): - rep = self._waitdata(1, None) - if rep == None: - raise error, 'Unexpected None reply from waitdata' - if rep not in (COMPLETION, ACK): - self._iflush() - raise error, 'Unexpected waitready reply:' + `rep` - self.busy_cmd = None - - def testready(self): - rep = self._waitdata(1, 0) - if rep == None: - return 0 - if rep not in (COMPLETION, ACK): - self._iflush() - raise error, 'Unexpected waitready reply:' + `rep` - self.busy_cmd = None - return 1 - - def play(self): return self.simplecmd(PLAY) - def stop(self): return self.simplecmd(STOP) - def ff(self): return self.simplecmd(FF) - def rew(self): return self.simplecmd(REW) - def eject(self):return self.simplecmd(EJECT) - def still(self):return self.simplecmd(STILL) - def step(self): return self.simplecmd(STEP_FWD) - - def goto(self, (h, m, s, f)): - if not self.simplecmd(SEARCH_DATA): - return 0 - self._number(h, 2) - self._number(m, 2) - self._number(s, 2) - self._number(f, 2) - if not self.simplecmd(ENTER): - return 0 - return self._endlongcmd('goto') - - # XXXX TC_SENSE doesn't seem to work - def faulty_where(self): - self._check() - self._cmd(TC_SENSE) - h = self._getnumber(2) - m = self._getnumber(2) - s = self._getnumber(2) - f = self._getnumber(2) - return (h, m, s, f) - - def where(self): - return self.addr2tc(self.sense()) - - def sense(self): - self._check() - self._cmd(ADDR_SENSE) - num = self._getnumber(5) - return num - - def addr2tc(self, num): - f = num % 25 - num = num / 25 - s = num % 60 - num = num / 60 - m = num % 60 - h = num / 60 - return (h, m, s, f) - - def tc2addr(self, (h, m, s, f)): - return ((h*60 + m)*60 + s)*25 + f - - def fmmode(self, mode): - self._check() - if mode == 'off': - arg = 0 - elif mode == 'buffer': - arg = 1 - elif mode == 'dnr': - arg = 2 - else: - raise error, 'fmmode arg should be off, buffer or dnr' - if not self.simplecmd(FM_SELECT): - return 0 - self._number(arg, 1) - if not self.simplecmd(ENTER): - return 0 - return 1 - - def mute(self, mode, value): - self._check() - if mode == 'audio': - cmds = (MUTE_AUDIO_OFF, MUTE_AUDIO) - elif mode == 'video': - cmds = (MUTE_VIDEO_OFF, MUTE_VIDEO) - elif mode == 'av': - cmds = (MUTE_AV_OFF, MUTE_AV) - else: - raise error, 'mute type should be audio, video or av' - cmd = cmds[value] - return self.simplecmd(cmd) - - def editmode(self, mode): - self._check() - if mode == 'off': - a0 = a1 = a2 = 0 - elif mode == 'format': - a0 = 4 - a1 = 7 - a2 = 4 - elif mode == 'asmbl': - a0 = 1 - a1 = 7 - a2 = 4 - elif mode == 'insert-video': - a0 = 2 - a1 = 4 - a2 = 0 - else: - raise 'editmode should be off,format,asmbl or insert-video' - if not self.simplecmd(EM_SELECT): - return 0 - self._number(a0, 1) - self._number(a1, 1) - self._number(a2, 1) - if not self.simplecmd(ENTER): - return 0 - return 1 - - def autoedit(self): - self._check() - return self._endlongcmd(AUTO_EDIT) - - def nframerec(self, num): - if not self.simplecmd(N_FRAME_REC): - return 0 - self._number(num, 4) - if not self.simplecmd(ENTER): - return 0 - return self._endlongcmd('nframerec') - - def fmstill(self): - if not self.simplecmd(FM_STILL): - return 0 - return self._endlongcmd('fmstill') - - def preview(self): - if not self.simplecmd(PREVIEW): - return 0 - return self._endlongcmd('preview') - - def review(self): - if not self.simplecmd(REVIEW): - return 0 - return self._endlongcmd('review') - - def search_preroll(self): - if not self.simplecmd(SEARCH_PREROLL): - return 0 - return self._endlongcmd('search_preroll') - - def edit_pb_standby(self): - if not self.simplecmd(EDIT_PB_STANDBY): - return 0 - return self._endlongcmd('edit_pb_standby') - - def edit_play(self): - if not self.simplecmd(EDIT_PLAY): - return 0 - return self._endlongcmd('edit_play') - - def dmcontrol(self, mode): - self._check() - if mode == 'off': - return self.simplecmd(DM_OFF) - if mode == 'multi freeze': - num = 1000 - elif mode == 'zoom freeze': - num = 2000 - elif mode == 'digital slow': - num = 3000 - elif mode == 'freeze': - num = 4011 - else: - raise error, 'unknown dmcontrol argument: ' + `mode` - if not self.simplecmd(DM_SET): - return 0 - self._number(num, 4) - if not self.simplecmd(ENTER): - return 0 - return 1 - - def fwdshuttle(self, num): - if not self.simplecmd(FWD_SHUTTLE): - return 0 - self._number(num, 1) - return 1 - - def revshuttle(self, num): - if not self.simplecmd(REV_SHUTTLE): - return 0 - self._number(num, 1) - return 1 - - def getentry(self, which): - self._check() - if which == 'in': - cmd = IN_ENTRY_SENSE - elif which == 'out': - cmd = OUT_ENTRY_SENSE - self.replycmd(cmd) - h = self._getnumber(2) - m = self._getnumber(2) - s = self._getnumber(2) - f = self._getnumber(2) - return (h, m, s, f) - - def inentry(self, arg): - return self.ioentry(arg, (IN_ENTRY, IN_ENTRY_RESET, \ - IN_ENTRY_SET, IN_ENTRY_INC, IN_ENTRY_DEC)) - - def outentry(self, arg): - return self.ioentry(arg, (OUT_ENTRY, OUT_ENTRY_RESET, \ - OUT_ENTRY_SET, OUT_ENTRY_INC, OUT_ENTRY_DEC)) - - def ioentry(self, arg, (Load, Clear, Set, Inc, Dec)): - self._check() - if type(arg) == type(()): - h, m, s, f = arg - if not self.simplecmd(Set): - return 0 - self._number(h,2) - self._number(m,2) - self._number(s,2) - self._number(f,2) - if not self.simplecmd(ENTER): - return 0 - return 1 - elif arg == 'reset': - cmd = Clear - elif arg == 'load': - cmd = Load - elif arg == '+': - cmd = Inc - elif arg == '-': - cmd = Dec - else: - raise error, 'Arg should be +,-,reset,load or (h,m,s,f)' - return self.simplecmd(cmd) - - def cancel(self): - d = self.simplecmd(CL) - self.busy_cmd = None diff --git a/Demo/sgi/video/VFile.py b/Demo/sgi/video/VFile.py deleted file mode 100755 index d6c9fc4662..0000000000 --- a/Demo/sgi/video/VFile.py +++ /dev/null @@ -1,1193 +0,0 @@ -# Classes to read and write CMIF video files. -# (For a description of the CMIF video format, see cmif-file.ms.) - - -# Layers of functionality: -# -# VideoParams: maintain essential parameters of a video file -# Displayer: display a frame in a window (with some extra parameters) -# BasicVinFile: read a CMIF video file -# BasicVoutFile: write a CMIF video file -# VinFile: BasicVinFile + Displayer -# VoutFile: BasicVoutFile + Displayer -# -# XXX Future extension: -# BasicVinoutFile: supports overwriting of individual frames - - -# Imported modules - -import sys -try: - import gl - import GL - import GET - no_gl = 0 -except ImportError: - no_gl = 1 -import colorsys -import imageop - - -# Exception raised for various occasions - -Error = 'VFile.Error' # file format errors -CallError = 'VFile.CallError' # bad call -AssertError = 'VFile.AssertError' # internal malfunction - - -# Max nr. of colormap entries to use - -MAXMAP = 4096 - 256 - - -# Parametrizations of colormap handling based on color system. -# (These functions are used via eval with a constructed argument!) - -def conv_grey(l, x, y): - return colorsys.yiq_to_rgb(l, 0, 0) - -def conv_grey4(l, x, y): - return colorsys.yiq_to_rgb(l*17, 0, 0) - -def conv_mono(l, x, y): - return colorsys.yiq_to_rgb(l*255, 0, 0) - -def conv_yiq(y, i, q): - return colorsys.yiq_to_rgb(y, (i-0.5)*1.2, q-0.5) - -def conv_hls(l, h, s): - return colorsys.hls_to_rgb(h, l, s) - -def conv_hsv(v, h, s): - return colorsys.hsv_to_rgb(h, s, v) - -def conv_rgb(r, g, b): - raise Error, 'Attempt to make RGB colormap' - -def conv_rgb8(rgb, d1, d2): - rgb = int(rgb*255.0) - r = (rgb >> 5) & 0x07 - g = (rgb ) & 0x07 - b = (rgb >> 3) & 0x03 - return (r/7.0, g/7.0, b/3.0) - -def conv_jpeg(r, g, b): - raise Error, 'Attempt to make RGB colormap (jpeg)' - -conv_jpeggrey = conv_grey -conv_grey2 = conv_grey - - -# Choose one of the above based upon a color system name - -def choose_conversion(format): - try: - return eval('conv_' + format) - except: - raise Error, 'Unknown color system: ' + `format` - - -# Inverses of the above - -def inv_grey(r, g, b): - y, i, q = colorsys.rgb_to_yiq(r, g, b) - return y, 0, 0 - -def inv_yiq(r, g, b): - y, i, q = colorsys.rgb_to_yiq(r, g, b) - return y, i/1.2 + 0.5, q + 0.5 - -def inv_hls(r, g, b): - h, l, s = colorsys.rgb_to_hls(r, g, b) - return l, h, s - -def inv_hsv(r, g, b): - h, s, v = colorsys.rgb_to_hsv(r, g, b) - return v, h, s - -def inv_rgb(r, g, b): - raise Error, 'Attempt to invert RGB colormap' - -def inv_rgb8(r, g, b): - r = int(r*7.0) - g = int(g*7.0) - b = int(b*7.0) - rgb = ((r&7) << 5) | ((b&3) << 3) | (g&7) - return rgb / 255.0, 0, 0 - -def inv_jpeg(r, g, b): - raise Error, 'Attempt to invert RGB colormap (jpeg)' - -inv_jpeggrey = inv_grey - - -# Choose one of the above based upon a color system name - -def choose_inverse(format): - try: - return eval('inv_' + format) - except: - raise Error, 'Unknown color system: ' + `format` - - -# Predicate to see whether this is an entry level (non-XS) Indigo. -# If so we can lrectwrite 8-bit wide pixels into a window in RGB mode - -def is_entry_indigo(): - # XXX hack, hack. We should call gl.gversion() but that doesn't - # exist in earlier Python versions. Therefore we check the number - # of bitplanes *and* the size of the monitor. - xmax = gl.getgdesc(GL.GD_XPMAX) - if xmax <> 1024: return 0 - ymax = gl.getgdesc(GL.GD_YPMAX) - if ymax != 768: return 0 - r = gl.getgdesc(GL.GD_BITS_NORM_SNG_RED) - g = gl.getgdesc(GL.GD_BITS_NORM_SNG_GREEN) - b = gl.getgdesc(GL.GD_BITS_NORM_SNG_BLUE) - return (r, g, b) == (3, 3, 2) - - -# Predicate to see whether this machine supports pixmode(PM_SIZE) with -# values 1 or 4. -# -# XXX Temporarily disabled, since it is unclear which machines support -# XXX which pixelsizes. -# -# XXX The XS appears to support 4 bit pixels, but (looking at osview) it -# XXX seems as if the conversion is done by the kernel (unpacking ourselves -# XXX is faster than using PM_SIZE=4) - -def support_packed_pixels(): - return 0 # To be architecture-dependent - - - -# Tables listing bits per pixel for some formats - -bitsperpixel = { \ - 'rgb': 32, \ - 'rgb8': 8, \ - 'grey': 8, \ - 'grey4': 4, \ - 'grey2': 2, \ - 'mono': 1, \ - 'compress': 32, \ -} - -bppafterdecomp = {'jpeg': 32, 'jpeggrey': 8} - - -# Base class to manage video format parameters - -class VideoParams: - - # Initialize an instance. - # Set all parameters to something decent - # (except width and height are set to zero) - - def __init__(self): - # Essential parameters - self.frozen = 0 # if set, can't change parameters - self.format = 'grey' # color system used - # Choose from: grey, rgb, rgb8, hsv, yiq, hls, jpeg, jpeggrey, - # mono, grey2, grey4 - self.width = 0 # width of frame - self.height = 0 # height of frame - self.packfactor = 1, 1 # expansion using rectzoom - # Colormap info - self.c0bits = 8 # bits in first color dimension - self.c1bits = 0 # bits in second color dimension - self.c2bits = 0 # bits in third color dimension - self.offset = 0 # colormap index offset (XXX ???) - self.chrompack = 0 # set if separate chrominance data - self.setderived() - self.decompressor = None - - # Freeze the parameters (disallow changes) - - def freeze(self): - self.frozen = 1 - - # Unfreeze the parameters (allow changes) - - def unfreeze(self): - self.frozen = 0 - - # Set some values derived from the standard info values - - def setderived(self): - if self.frozen: raise AssertError - if bitsperpixel.has_key(self.format): - self.bpp = bitsperpixel[self.format] - else: - self.bpp = 0 - xpf, ypf = self.packfactor - self.xpf = abs(xpf) - self.ypf = abs(ypf) - self.mirror_image = (xpf < 0) - self.upside_down = (ypf < 0) - self.realwidth = self.width / self.xpf - self.realheight = self.height / self.ypf - - # Set colormap info - - def setcmapinfo(self): - stuff = 0, 0, 0, 0, 0 - if self.format in ('rgb8', 'grey'): - stuff = 8, 0, 0, 0, 0 - if self.format == 'grey4': - stuff = 4, 0, 0, 0, 0 - if self.format == 'grey2': - stuff = 2, 0, 0, 0, 0 - if self.format == 'mono': - stuff = 1, 0, 0, 0, 0 - self.c0bits, self.c1bits, self.c2bits, \ - self.offset, self.chrompack = stuff - - # Set the frame width and height (e.g. from gl.getsize()) - - def setsize(self, width, height): - if self.frozen: raise CallError - width = (width/self.xpf)*self.xpf - height = (height/self.ypf)*self.ypf - self.width, self.height = width, height - self.setderived() - - # Retrieve the frame width and height (e.g. for gl.prefsize()) - - def getsize(self): - return (self.width, self.height) - - # Set the format - - def setformat(self, format): - if self.frozen: raise CallError - self.format = format - self.setderived() - self.setcmapinfo() - - # Get the format - - def getformat(self): - return self.format - - # Set the packfactor - - def setpf(self, pf): - if self.frozen: raise CallError - if type(pf) == type(1): - pf = (pf, pf) - if type(pf) is not type(()) or len(pf) <> 2: raise CallError - self.packfactor = pf - self.setderived() - - # Get the packfactor - - def getpf(self): - return self.packfactor - - # Set all parameters - - def setinfo(self, values): - if self.frozen: raise CallError - self.setformat(values[0]) - self.setpf(values[3]) - self.setsize(values[1], values[2]) - (self.c0bits, self.c1bits, self.c2bits, \ - self.offset, self.chrompack) = values[4:9] - if self.format == 'compress' and len(values) > 9: - self.compressheader = values[9] - self.setderived() - - # Retrieve all parameters in a format suitable for a subsequent - # call to setinfo() - - def getinfo(self): - return (self.format, self.width, self.height, self.packfactor,\ - self.c0bits, self.c1bits, self.c2bits, self.offset, \ - self.chrompack) - - def getcompressheader(self): - return self.compressheader - - def setcompressheader(self, ch): - self.compressheader = ch - - # Write the relevant bits to stdout - - def printinfo(self): - print 'Format: ', self.format - print 'Size: ', self.width, 'x', self.height - print 'Pack: ', self.packfactor, '; chrom:', self.chrompack - print 'Bpp: ', self.bpp - print 'Bits: ', self.c0bits, self.c1bits, self.c2bits - print 'Offset: ', self.offset - - # Calculate data size, if possible - # (Not counting frame header or cdata size) - - def calcframesize(self): - if not self.bpp: raise CallError - size = self.width/self.xpf * self.height/self.ypf - size = (size * self.bpp + 7) / 8 - return size - - # Decompress a possibly compressed frame. This method is here - # since you sometimes want to use it on a VFile instance and sometimes - # on a Displayer instance. - # - # XXXX This should also handle jpeg. Actually, the whole mechanism - # should be much more of 'ihave/iwant' style, also allowing you to - # read, say, greyscale images from a color movie. - - def decompress(self, data): - if self.format <> 'compress': - return data - if not self.decompressor: - import cl, CL - scheme = cl.QueryScheme(self.compressheader) - self.decompressor = cl.OpenDecompressor(scheme) - headersize = self.decompressor.ReadHeader(self.compressheader) - width = self.decompressor.GetParam(CL.IMAGE_WIDTH) - height = self.decompressor.GetParam(CL.IMAGE_HEIGHT) - params = [CL.ORIGINAL_FORMAT, CL.RGBX, \ - CL.ORIENTATION, CL.BOTTOM_UP, \ - CL.FRAME_BUFFER_SIZE, width*height*CL.BytesPerPixel(CL.RGBX)] - self.decompressor.SetParams(params) - data = self.decompressor.Decompress(1, data) - return data - - -# Class to display video frames in a window. -# It is the caller's responsibility to ensure that the correct window -# is current when using showframe(), initcolormap(), clear() and clearto() - -class Displayer(VideoParams): - - # Initialize an instance. - # This does not need a current window - - def __init__(self): - if no_gl: - raise RuntimeError, \ - 'no gl module available, so cannot display' - VideoParams.__init__(self) - # User-settable parameters - self.magnify = 1.0 # frame magnification factor - self.xorigin = 0 # x frame offset - self.yorigin = 0 # y frame offset (from bottom) - self.quiet = 0 # if set, don't print messages - self.fallback = 1 # allow fallback to grey - # Internal flags - self.colormapinited = 0 # must initialize window - self.skipchrom = 0 # don't skip chrominance data - self.color0 = None # magic, used by clearto() - self.fixcolor0 = 0 # don't need to fix color0 - self.mustunpack = (not support_packed_pixels()) - - # setinfo() must reset some internal flags - - def setinfo(self, values): - VideoParams.setinfo(self, values) - self.colormapinited = 0 - self.skipchrom = 0 - self.color0 = None - self.fixcolor0 = 0 - - # Show one frame, initializing the window if necessary - - def showframe(self, data, chromdata): - self.showpartframe(data, chromdata, \ - (0,0,self.width,self.height)) - - def showpartframe(self, data, chromdata, (x,y,w,h)): - pmsize = self.bpp - xpf, ypf = self.xpf, self.ypf - if self.upside_down: - gl.pixmode(GL.PM_TTOB, 1) - if self.mirror_image: - gl.pixmode(GL.PM_RTOL, 1) - if self.format in ('jpeg', 'jpeggrey'): - import jpeg - data, width, height, bytes = jpeg.decompress(data) - pmsize = bytes*8 - elif self.format == 'compress': - data = self.decompress(data) - pmsize = 32 - elif self.format in ('mono', 'grey4'): - if self.mustunpack: - if self.format == 'mono': - data = imageop.mono2grey(data, \ - w/xpf, h/ypf, 0x20, 0xdf) - elif self.format == 'grey4': - data = imageop.grey42grey(data, \ - w/xpf, h/ypf) - pmsize = 8 - elif self.format == 'grey2': - data = imageop.grey22grey(data, w/xpf, h/ypf) - pmsize = 8 - if not self.colormapinited: - self.initcolormap() - if self.fixcolor0: - gl.mapcolor(self.color0) - self.fixcolor0 = 0 - xfactor = yfactor = self.magnify - xfactor = xfactor * xpf - yfactor = yfactor * ypf - if chromdata and not self.skipchrom: - cp = self.chrompack - cx = int(x*xfactor*cp) + self.xorigin - cy = int(y*yfactor*cp) + self.yorigin - cw = (w+cp-1)/cp - ch = (h+cp-1)/cp - gl.rectzoom(xfactor*cp, yfactor*cp) - gl.pixmode(GL.PM_SIZE, 16) - gl.writemask(self.mask - ((1 << self.c0bits) - 1)) - gl.lrectwrite(cx, cy, cx + cw - 1, cy + ch - 1, \ - chromdata) - # - if pmsize < 32: - gl.writemask((1 << self.c0bits) - 1) - gl.pixmode(GL.PM_SIZE, pmsize) - w = w/xpf - h = h/ypf - x = x/xpf - y = y/ypf - gl.rectzoom(xfactor, yfactor) - x = int(x*xfactor)+self.xorigin - y = int(y*yfactor)+self.yorigin - gl.lrectwrite(x, y, x + w - 1, y + h - 1, data) - gl.gflush() - - # Initialize the window: set RGB or colormap mode as required, - # fill in the colormap, and clear the window - - def initcolormap(self): - self.colormapinited = 1 - self.color0 = None - self.fixcolor0 = 0 - if self.format in ('rgb', 'jpeg', 'compress'): - self.set_rgbmode() - gl.RGBcolor(200, 200, 200) # XXX rather light grey - gl.clear() - return - # This only works on an Entry-level Indigo from IRIX 4.0.5 - if self.format == 'rgb8' and is_entry_indigo() and \ - gl.gversion() == 'GL4DLG-4.0.': # Note trailing '.'! - self.set_rgbmode() - gl.RGBcolor(200, 200, 200) # XXX rather light grey - gl.clear() - gl.pixmode(GL.PM_SIZE, 8) - return - self.set_cmode() - self.skipchrom = 0 - if self.offset == 0: - self.mask = 0x7ff - else: - self.mask = 0xfff - if not self.quiet: - sys.stderr.write('Initializing color map...') - self._initcmap() - gl.clear() - if not self.quiet: - sys.stderr.write(' Done.\n') - - # Set the window in RGB mode (may be overridden for Glx window) - - def set_rgbmode(self): - gl.RGBmode() - gl.gconfig() - - # Set the window in colormap mode (may be overridden for Glx window) - - def set_cmode(self): - gl.cmode() - gl.gconfig() - - # Clear the window to a default color - - def clear(self): - if not self.colormapinited: raise CallError - if gl.getdisplaymode() in (GET.DMRGB, GET.DMRGBDOUBLE): - gl.RGBcolor(200, 200, 200) # XXX rather light grey - gl.clear() - return - gl.writemask(0xffffffff) - gl.clear() - - # Clear the window to a given RGB color. - # This may steal the first color index used; the next call to - # showframe() will restore the intended mapping for that index - - def clearto(self, r, g, b): - if not self.colormapinited: raise CallError - if gl.getdisplaymode() in (GET.DMRGB, GET.DMRGBDOUBLE): - gl.RGBcolor(r, g, b) - gl.clear() - return - index = self.color0[0] - self.fixcolor0 = 1 - gl.mapcolor(index, r, g, b) - gl.writemask(0xffffffff) - gl.clear() - gl.gflush() - - # Do the hard work for initializing the colormap (internal). - # This also sets the current color to the first color index - # used -- the caller should never change this since it is used - # by clear() and clearto() - - def _initcmap(self): - map = [] - if self.format in ('mono', 'grey4') and self.mustunpack: - convcolor = conv_grey - else: - convcolor = choose_conversion(self.format) - maxbits = gl.getgdesc(GL.GD_BITS_NORM_SNG_CMODE) - if maxbits > 11: - maxbits = 11 - c0bits = self.c0bits - c1bits = self.c1bits - c2bits = self.c2bits - if c0bits+c1bits+c2bits > maxbits: - if self.fallback and c0bits < maxbits: - # Cannot display frames in this mode, use grey - self.skipchrom = 1 - c1bits = c2bits = 0 - convcolor = choose_conversion('grey') - else: - raise Error, 'Sorry, '+`maxbits`+ \ - ' bits max on this machine' - maxc0 = 1 << c0bits - maxc1 = 1 << c1bits - maxc2 = 1 << c2bits - if self.offset == 0 and maxbits == 11: - offset = 2048 - else: - offset = self.offset - if maxbits <> 11: - offset = offset & ((1< type(()): - raise Error, filename + ': Bad (w,h,pf) info' - if len(x) == 3: - width, height, packfactor = x - if packfactor == 0 and version < 3.0: - format = 'rgb' - c0bits = 0 - elif len(x) == 2 and version <= 1.0: - width, height = x - packfactor = 2 - else: - raise Error, filename + ': Bad (w,h,pf) info' - if type(packfactor) is type(0): - if packfactor == 0: packfactor = 1 - xpf = ypf = packfactor - else: - xpf, ypf = packfactor - if upside_down: - ypf = -ypf - packfactor = (xpf, ypf) - xpf = abs(xpf) - ypf = abs(ypf) - width = (width/xpf) * xpf - height = (height/ypf) * ypf - # - # Return (version, values) - # - values = (format, width, height, packfactor, \ - c0bits, c1bits, c2bits, offset, chrompack, compressheader) - return (version, values) - - -# Read a *frame* header -- separate functions per version. -# Return (timecode, datasize, chromdatasize). -# Raise EOFError if end of data is reached. -# Raise Error if data is bad. - -def readv0frameheader(fp): - line = fp.readline() - if not line or line == '\n': raise EOFError - try: - t = eval(line[:-1]) - except: - raise Error, 'Bad 0.0 frame header' - return (t, 0, 0) - -def readv1frameheader(fp): - line = fp.readline() - if not line or line == '\n': raise EOFError - try: - t, datasize = eval(line[:-1]) - except: - raise Error, 'Bad 1.0 frame header' - return (t, datasize, 0) - -def readv2frameheader(fp): - line = fp.readline() - if not line or line == '\n': raise EOFError - try: - t, datasize = eval(line[:-1]) - except: - raise Error, 'Bad 2.0 frame header' - return (t, datasize, 0) - -def readv3frameheader(fp): - line = fp.readline() - if not line or line == '\n': raise EOFError - try: - t, datasize, chromdatasize = x = eval(line[:-1]) - except: - raise Error, 'Bad 3.[01] frame header' - return x - - -# Write a CMIF video file header (always version 3.1) - -def writefileheader(fp, values): - (format, width, height, packfactor, \ - c0bits, c1bits, c2bits, offset, chrompack) = values - # - # Write identifying header - # - fp.write('CMIF video 3.1\n') - # - # Write color encoding info - # - if format in ('rgb', 'jpeg'): - data = (format, 0) - elif format in ('grey', 'jpeggrey', 'mono', 'grey2', 'grey4'): - data = (format, c0bits) - else: - data = (format, (c0bits, c1bits, c2bits, chrompack, offset)) - fp.write(`data`+'\n') - # - # Write frame geometry info - # - data = (width, height, packfactor) - fp.write(`data`+'\n') - -def writecompressfileheader(fp, cheader, values): - (format, width, height, packfactor, \ - c0bits, c1bits, c2bits, offset, chrompack) = values - # - # Write identifying header - # - fp.write('CMIF video 3.1\n') - # - # Write color encoding info - # - data = (format, cheader) - fp.write(`data`+'\n') - # - # Write frame geometry info - # - data = (width, height, packfactor) - fp.write(`data`+'\n') - - -# Basic class for reading CMIF video files - -class BasicVinFile(VideoParams): - - def __init__(self, filename): - if type(filename) != type(''): - fp = filename - filename = '???' - elif filename == '-': - fp = sys.stdin - else: - fp = open(filename, 'r') - self.initfp(fp, filename) - - def initfp(self, fp, filename): - VideoParams.__init__(self) - self.fp = fp - self.filename = filename - self.version, values = readfileheader(fp, filename) - self.setinfo(values) - self.freeze() - if self.version == 0.0: - w, h, pf = self.width, self.height, self.packfactor - if pf == 0: - self._datasize = w*h*4 - else: - self._datasize = (w/pf) * (h/pf) - self._readframeheader = self._readv0frameheader - elif self.version == 1.0: - self._readframeheader = readv1frameheader - elif self.version == 2.0: - self._readframeheader = readv2frameheader - elif self.version in (3.0, 3.1): - self._readframeheader = readv3frameheader - else: - raise Error, \ - filename + ': Bad version: ' + `self.version` - self.framecount = 0 - self.atframeheader = 1 - self.eofseen = 0 - self.errorseen = 0 - try: - self.startpos = self.fp.tell() - self.canseek = 1 - except IOError: - self.startpos = -1 - self.canseek = 0 - - def _readv0frameheader(self, fp): - t, ds, cs = readv0frameheader(fp) - ds = self._datasize - return (t, ds, cs) - - def close(self): - self.fp.close() - del self.fp - del self._readframeheader - - def rewind(self): - if not self.canseek: - raise Error, self.filename + ': can\'t seek' - self.fp.seek(self.startpos) - self.framecount = 0 - self.atframeheader = 1 - self.eofseen = 0 - self.errorseen = 0 - - def warmcache(self): - print '[BasicVinFile.warmcache() not implemented]' - - def printinfo(self): - print 'File: ', self.filename - print 'Size: ', getfilesize(self.filename) - print 'Version: ', self.version - VideoParams.printinfo(self) - - def getnextframe(self): - t, ds, cs = self.getnextframeheader() - data, cdata = self.getnextframedata(ds, cs) - return (t, data, cdata) - - def skipnextframe(self): - t, ds, cs = self.getnextframeheader() - self.skipnextframedata(ds, cs) - return t - - def getnextframeheader(self): - if self.eofseen: raise EOFError - if self.errorseen: raise CallError - if not self.atframeheader: raise CallError - self.atframeheader = 0 - try: - return self._readframeheader(self.fp) - except Error, msg: - self.errorseen = 1 - # Patch up the error message - raise Error, self.filename + ': ' + msg - except EOFError: - self.eofseen = 1 - raise EOFError - - def getnextframedata(self, ds, cs): - if self.eofseen: raise EOFError - if self.errorseen: raise CallError - if self.atframeheader: raise CallError - if ds: - data = self.fp.read(ds) - if len(data) < ds: - self.eofseen = 1 - raise EOFError - else: - data = '' - if cs: - cdata = self.fp.read(cs) - if len(cdata) < cs: - self.eofseen = 1 - raise EOFError - else: - cdata = '' - self.atframeheader = 1 - self.framecount = self.framecount + 1 - return (data, cdata) - - def skipnextframedata(self, ds, cs): - if self.eofseen: raise EOFError - if self.errorseen: raise CallError - if self.atframeheader: raise CallError - # Note that this won't raise EOFError for a partial frame - # since there is no easy way to tell whether a seek - # ended up beyond the end of the file - if self.canseek: - self.fp.seek(ds + cs, 1) # Relative seek - else: - dummy = self.fp.read(ds + cs) - del dummy - self.atframeheader = 1 - self.framecount = self.framecount + 1 - - -# Subroutine to return a file's size in bytes - -def getfilesize(filename): - import os, stat - try: - st = os.stat(filename) - return st[stat.ST_SIZE] - except os.error: - return 0 - - -# Derived class implementing random access and index cached in the file - -class RandomVinFile(BasicVinFile): - - def initfp(self, fp, filename): - BasicVinFile.initfp(self, fp, filename) - self.index = [] - - def warmcache(self): - if len(self.index) == 0: - try: - self.readcache() - except Error: - self.buildcache() - else: - print '[RandomVinFile.warmcache(): too late]' - self.rewind() - - def buildcache(self): - self.index = [] - self.rewind() - while 1: - try: dummy = self.skipnextframe() - except EOFError: break - self.rewind() - - def writecache(self): - # Raises IOerror if the file is not seekable & writable! - import marshal - if len(self.index) == 0: - self.buildcache() - if len(self.index) == 0: - raise Error, self.filename + ': No frames' - self.fp.seek(0, 2) - self.fp.write('\n/////CMIF/////\n') - pos = self.fp.tell() - data = `pos` - data = '\n-*-*-CMIF-*-*-\n' + data + ' '*(15-len(data)) + '\n' - try: - marshal.dump(self.index, self.fp) - self.fp.write(data) - self.fp.flush() - finally: - self.rewind() - - def readcache(self): - # Raises Error if there is no cache in the file - import marshal - if len(self.index) <> 0: - raise CallError - self.fp.seek(-32, 2) - data = self.fp.read() - if data[:16] <> '\n-*-*-CMIF-*-*-\n' or data[-1:] <> '\n': - self.rewind() - raise Error, self.filename + ': No cache' - pos = eval(data[16:-1]) - self.fp.seek(pos) - try: - self.index = marshal.load(self.fp) - except TypeError: - self.rewind() - raise Error, self.filename + ': Bad cache' - self.rewind() - - def getnextframeheader(self): - if self.framecount < len(self.index): - return self._getindexframeheader(self.framecount) - if self.framecount > len(self.index): - raise AssertError, \ - 'managed to bypass index?!?' - rv = BasicVinFile.getnextframeheader(self) - if self.canseek: - pos = self.fp.tell() - self.index.append(rv, pos) - return rv - - def getrandomframe(self, i): - t, ds, cs = self.getrandomframeheader(i) - data, cdata = self.getnextframedata(ds, cs) - return t, data, cdata - - def getrandomframeheader(self, i): - if i < 0: raise ValueError, 'negative frame index' - if not self.canseek: - raise Error, self.filename + ': can\'t seek' - if i < len(self.index): - return self._getindexframeheader(i) - if len(self.index) > 0: - rv = self.getrandomframeheader(len(self.index)-1) - else: - self.rewind() - rv = self.getnextframeheader() - while i > self.framecount: - self.skipnextframedata() - rv = self.getnextframeheader() - return rv - - def _getindexframeheader(self, i): - (rv, pos) = self.index[i] - self.fp.seek(pos) - self.framecount = i - self.atframeheader = 0 - self.eofseen = 0 - self.errorseen = 0 - return rv - - -# Basic class for writing CMIF video files - -class BasicVoutFile(VideoParams): - - def __init__(self, filename): - if type(filename) != type(''): - fp = filename - filename = '???' - elif filename == '-': - fp = sys.stdout - else: - fp = open(filename, 'w') - self.initfp(fp, filename) - - def initfp(self, fp, filename): - VideoParams.__init__(self) - self.fp = fp - self.filename = filename - self.version = 3.1 # In case anyone inquries - - def flush(self): - self.fp.flush() - - def close(self): - self.fp.close() - del self.fp - - def prealloc(self, nframes): - if not self.frozen: raise CallError - data = '\xff' * (self.calcframesize() + 64) - pos = self.fp.tell() - for i in range(nframes): - self.fp.write(data) - self.fp.seek(pos) - - def writeheader(self): - if self.frozen: raise CallError - if self.format == 'compress': - writecompressfileheader(self.fp, self.compressheader, \ - self.getinfo()) - else: - writefileheader(self.fp, self.getinfo()) - self.freeze() - self.atheader = 1 - self.framecount = 0 - - def rewind(self): - self.fp.seek(0) - self.unfreeze() - self.atheader = 1 - self.framecount = 0 - - def printinfo(self): - print 'File: ', self.filename - VideoParams.printinfo(self) - - def writeframe(self, t, data, cdata): - if data: ds = len(data) - else: ds = 0 - if cdata: cs = len(cdata) - else: cs = 0 - self.writeframeheader(t, ds, cs) - self.writeframedata(data, cdata) - - def writeframeheader(self, t, ds, cs): - if not self.frozen: self.writeheader() - if not self.atheader: raise CallError - data = `(t, ds, cs)` - n = len(data) - if n < 63: data = data + ' '*(63-n) - self.fp.write(data + '\n') - self.atheader = 0 - - def writeframedata(self, data, cdata): - if not self.frozen or self.atheader: raise CallError - if data: self.fp.write(data) - if cdata: self.fp.write(cdata) - self.atheader = 1 - self.framecount = self.framecount + 1 - - -# Classes that combine files with displayers: - -class VinFile(RandomVinFile, Displayer): - - def initfp(self, fp, filename): - Displayer.__init__(self) - RandomVinFile.initfp(self, fp, filename) - - def shownextframe(self): - t, data, cdata = self.getnextframe() - self.showframe(data, cdata) - return t - - -class VoutFile(BasicVoutFile, Displayer): - - def initfp(self, fp, filename): - Displayer.__init__(self) -## Grabber.__init__(self) # XXX not needed - BasicVoutFile.initfp(self, fp, filename) - - -# Simple test program (VinFile only) - -def test(): - import time - if sys.argv[1:]: filename = sys.argv[1] - else: filename = 'film.video' - vin = VinFile(filename) - vin.printinfo() - gl.foreground() - gl.prefsize(vin.getsize()) - wid = gl.winopen(filename) - vin.initcolormap() - t0 = time.time() - while 1: - try: t, data, cdata = vin.getnextframe() - except EOFError: break - dt = t0 + t - time.time() - if dt > 0: time.time(dt) - vin.showframe(data, cdata) - time.sleep(2) diff --git a/Demo/sgi/video/VGrabber.py b/Demo/sgi/video/VGrabber.py deleted file mode 100755 index 242ebf2231..0000000000 --- a/Demo/sgi/video/VGrabber.py +++ /dev/null @@ -1,80 +0,0 @@ -# Class to grab frames from a window. -# (This has fewer user-settable parameters than Displayer.) -# It is the caller's responsibility to initialize the window and to -# ensure that it is current when using grabframe() - -import gl, GL -import VFile -import GET -from VFile import Error - -class VGrabber(VFile.VideoParams): - - # XXX The constructor of VideoParams is just fine, for now - - # Grab a frame. - # Return (data, chromdata) just like getnextframe(). - - def grabframe(self): - grabber = choose_grabber(self.format) - return grabber(self.width, self.height, self.packfactor) - - -# Choose one of the grabber functions below based upon a color system name - -def choose_grabber(format): - try: - return eval('grab_' + format) - except: - raise Error, 'Unknown color system: ' + `format` - - -# Routines to grab data, per color system (only a few really supported). -# (These functions are used via eval with a constructed argument!) - -def grab_rgb(w, h, pf): - if gl.getdisplaymode() <> GET.DMRGB: - raise Error, 'Sorry, can only grab rgb in single-buf rgbmode' - if pf <> (1, 1): - raise Error, 'Sorry, only grab rgb with packfactor (1,1)' - return gl.lrectread(0, 0, w-1, h-1), None - -def grab_rgb8(w, h, pf): - if gl.getdisplaymode() <> GET.DMRGB: - raise Error, 'Sorry, can only grab rgb8 in single-buf rgbmode' - if pf <> (1, 1): - raise Error, 'Sorry, can only grab rgb8 with packfactor (1,1)' - if not VFile.is_entry_indigo(): - raise Error, 'Sorry, can only grab rgb8 on entry level Indigo' - # XXX Dirty Dirty here. - # XXX Set buffer to cmap mode, grab image and set it back. - gl.cmode() - gl.gconfig() - gl.pixmode(GL.PM_SIZE, 8) - data = gl.lrectread(0, 0, w-1, h-1) - data = data[:w*h] # BUG FIX for python lrectread - gl.RGBmode() - gl.gconfig() - gl.pixmode(GL.PM_SIZE, 32) - return data, None - -def grab_grey(w, h, pf): - raise Error, 'Sorry, grabbing grey not implemented' - -def grab_yiq(w, h, pf): - raise Error, 'Sorry, grabbing yiq not implemented' - -def grab_hls(w, h, pf): - raise Error, 'Sorry, grabbing hls not implemented' - -def grab_hsv(w, h, pf): - raise Error, 'Sorry, grabbing hsv not implemented' - -def grab_jpeg(w, h, pf): - data, dummy = grab_rgb(w, h, pf) - import jpeg - data = jpeg.compress(data, w, h, 4) - return data, None - -def grab_jpeggrey(w, h, pf): - raise Error, 'sorry, grabbing jpeggrey not implemented' diff --git a/Demo/sgi/video/Vaddcache.py b/Demo/sgi/video/Vaddcache.py deleted file mode 100755 index 6428fcbce3..0000000000 --- a/Demo/sgi/video/Vaddcache.py +++ /dev/null @@ -1,80 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -# Add a cache to each of the files given as command line arguments - - -# Usage: -# -# Vaddcache [file] ... - - -# Options: -# -# file ... : file(s) to modify; default film.video - - -import sys -sys.path.append('/ufs/guido/src/video') -import VFile -import getopt - - -# Global options - -# None - - -# Main program -- mostly command line parsing - -def main(): - opts, args = getopt.getopt(sys.argv[1:], '') - if not args: - args = ['film.video'] - sts = 0 - for filename in args: - if process(filename): - sts = 1 - sys.exit(sts) - - -# Process one file - -def process(filename): - try: - fp = open(filename, 'r+') - vin = VFile.RandomVinFile(fp) - vin.filename = filename - except IOError, msg: - sys.stderr.write(filename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(filename + ': EOF in video file\n') - return 1 - - try: - vin.readcache() - hascache = 1 - except VFile.Error: - hascache = 0 - - if hascache: - sys.stderr.write(filename + ': already has a cache\n') - vin.close() - return 1 - - vin.printinfo() - vin.warmcache() - vin.writecache() - vin.close() - return 0 - - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/Vb.py b/Demo/sgi/video/Vb.py deleted file mode 100755 index 093bcf7ed0..0000000000 --- a/Demo/sgi/video/Vb.py +++ /dev/null @@ -1,963 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -# Video bag of tricks: record video(+audio) in various formats and modes - -# XXX To do: -# - audio -# - improve user interface -# - help button? -# - command line options to set initial settings -# - save settings in a file -# - ...? - -import sys -import time -import getopt -import string -import os -sts = os.system('makemap') # Must be before "import fl" to work -import sgi -import gl -import GL -import DEVICE -import fl -import FL -import flp -import watchcursor -import sv -import SV -import VFile -import VGrabber -import imageop -sys.path.append('/ufs/jack/src/av/vcr') -import VCR -try: - import cl - import CL -except ImportError: - cl = None - -ARROW = 0 -WATCH = 1 -watchcursor.defwatch(WATCH) - -def main(): -## fl.set_graphics_mode(0, 1) - vb = VideoBagOfTricks() - while 1: - dummy = fl.do_forms() - [dummy] - -StopCapture = 'StopCapture' - -VideoFormatLabels = ['Video off', 'rgb8', 'grey8', 'grey4', 'grey2', \ - 'grey2 dith', 'mono dith', 'mono thresh', 'rgb24', 'rgb24-jpeg', \ - 'compress'] -VideoFormats = ['', 'rgb8', 'grey', 'grey4', 'grey2', \ - 'grey2', 'mono', 'mono', 'rgb', 'jpeg', 'compress'] - -VideoModeLabels = ['Continuous', 'Burst', 'Single frame', 'VCR sync'] -[VM_CONT, VM_BURST, VM_SINGLE, VM_VCR] = range(1, 5) - -AudioFormatLabels = ['Audio off', \ - '16 bit mono', '16 bit stereo', '8 bit mono', '8 bit stereo'] -[A_OFF, A_16_MONO, A_16_STEREO, A_8_MONO, A_8_STEREO] = range(1, 6) - -VcrSpeedLabels = ['normal', '1/3', '1/5', '1/10', '1/30', 'single-step'] -VcrSpeeds = [None, 5, 4, 3, 2, 1, 0] - -RgbSizeLabels = ['full', 'quarter', 'sixteenth'] - -# init file stuff: -if os.environ.has_key('HOME'): - HOME=os.environ['HOME'] -else: - HOME='.' -VB_INIT_FILE=HOME + '/.Vb_init' - -VB_INIT_KEYS=['vfile', 'vmode', 'mono_thresh', 'vformat', 'comp_scheme', \ - 'rgb24_size', 'afile', 'aformat'] - -class VideoBagOfTricks: - - # Init/close stuff - - def __init__(self): - self.window = None - formdef = flp.parse_form('VbForm', 'form') - flp.create_full_form(self, formdef) - self.setdefaults() - if self.vmode <> VM_CONT: - self.g_cont.hide_object() - if self.vmode <> VM_BURST: - self.g_burst.hide_object() - if self.vmode <> VM_SINGLE: - self.g_single.hide_object() - if self.vmode <> VM_VCR: - self.g_vcr.hide_object() - if self.vformat <> 'compress': - self.g_compress.hide_object() - - self.openvideo() - self.makewindow() - self.bindvideo() - if self.use_24: - self.optfullsizewindow() - self.showform() - fl.set_event_call_back(self.do_event) - - def close(self): - self.close_video() - self.close_audio() - self.savedefaults() - raise SystemExit, 0 - - def showform(self): - # Get position of video window - gl.winset(self.window) - x, y = gl.getorigin() - width, height = gl.getsize() - # Calculate position of form window - x1 = x + width + 10 - x2 = x1 + int(self.form.w) - 1 - y2 = y + height - 1 - y1 = y2 - int(self.form.h) + 1 - # Position and show form window - gl.prefposition(x1, x2, y1, y2) - self.form.show_form(FL.PLACE_FREE, FL.TRUE, 'Vb Control') - - def getdefaultdefaults(self): - # Video defaults - self.vfile = 'film.video' - self.vmode = VM_CONT - self.mono_thresh = 128 - self.vformat = 'rgb8' - self.comp_scheme = 'Uncompressed' - self.rgb24_size = 1 - # Missing: drop, rate, maxmem, nframes, rate, vcrspeed - # Audio defaults: - self.afile = 'film.aiff' - self.aformat = A_OFF - - def getdefaults(self): - self.getdefaultdefaults() - # XXXX Read defaults file and override. - try: - fp = open(VB_INIT_FILE, 'r') - except IOError: - print 'Vb: no init file' - self.initcont = {} - return - data = fp.read(1000000) - try: - self.initcont = eval(data) - except: - print 'Vb: Ill-formatted init file' - self.initcont = {} - for k in self.initcont.keys(): - if hasattr(self, k): - setattr(self, k, self.initcont[k]) - - def savedefaults(self): - newdb = {} - for k in VB_INIT_KEYS: - newdb[k] = getattr(self, k) - if newdb <> self.initcont: - try: - fp = open(VB_INIT_FILE, 'w') - except IOError: - print 'Vb: Cannot create', VB_INIT_FILE - return - fp.write(`newdb`) - fp.close() - - def setdefaults(self): - self.getdefaults() - self.vcr = None - self.vout = None - self.capturing = 0 - self.c_vformat.clear_choice() - for label in VideoFormatLabels: - self.c_vformat.addto_choice(label) - self.c_vformat.set_choice(1 + VideoFormats.index(self.vformat)) - self.c_vmode.clear_choice() - for label in VideoModeLabels: - self.c_vmode.addto_choice(label) - self.c_vmode.set_choice(self.vmode) - self.get_vformat() - self.b_drop.set_button(1) - self.in_rate.set_input('2') - self.in_maxmem.set_input('1.0') - self.in_nframes.set_input('0') - self.in_nframes_vcr.set_input('1') - self.in_rate_vcr.set_input('1') - self.c_vcrspeed.clear_choice() - for label in VcrSpeedLabels: - self.c_vcrspeed.addto_choice(label) - self.c_vcrspeed.set_choice(4) - self.c_rgb24_size.clear_choice() - for label in RgbSizeLabels: - self.c_rgb24_size.addto_choice(label) - self.c_rgb24_size.set_choice(self.rgb24_size) - if cl: - algs = cl.QueryAlgorithms(CL.VIDEO) - self.all_comp_schemes = [] - for i in range(0, len(algs), 2): - if algs[i+1] in (CL.COMPRESSOR, CL.CODEC): - self.all_comp_schemes.append(algs[i]) - self.c_cformat.clear_choice() - for label in self.all_comp_schemes: - self.c_cformat.addto_choice(label) - i = self.all_comp_schemes.index(self.comp_scheme) - self.c_cformat.set_choice(i+1) - # Audio defaults - self.aout = None - self.aport = None - self.c_aformat.clear_choice() - for label in AudioFormatLabels: - self.c_aformat.addto_choice(label) - self.c_aformat.set_choice(self.aformat) - self.get_aformat() - - def openvideo(self): - try: - self.video = sv.OpenVideo() - except sv.error, msg: - print 'Error opening video:', msg - self.video = None - param = [SV.BROADCAST, SV.PAL] - if self.video: self.video.GetParam(param) - if param[1] == SV.PAL: - x = SV.PAL_XMAX - y = SV.PAL_YMAX - elif param[1] == SV.NTSC: - x = SV.NTSC_XMAX - y = SV.NTSC_YMAX - else: - print 'Unknown video standard:', param[1] - sys.exit(1) - self.maxx, self.maxy = x, y - self.curx = 256 - self.cury = 256*3/4 - - def makewindow(self): - x, y = self.maxx, self.maxy - gl.foreground() - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - width = self.curx - height = self.cury - if width and height: - # Place the window at (150, 150) from top left - # (the video board likes this location...) - x1 = 150 - x2 = x1+width-1 - SCRHEIGHT = 768 - y2 = SCRHEIGHT-1-150 - y1 = y2-height+1 - gl.prefposition(x1, x2, y1, y2) - self.window = gl.winopen('Vb video') - self.settitle() - if width: - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - gl.winconstraints() - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - - def optfullsizewindow(self): - if not self.window: - return - gl.winset(self.window) - if self.use_24: - x, y = self.maxx, self.maxy - else: - x, y = self.curx, self.cury - left, bottom = gl.getorigin() - width, height = gl.getsize() - bottom = bottom+height-y - gl.prefposition(left, left+x-1, bottom, bottom+y-1) - gl.winconstraints() - if not self.use_24: - gl.keepaspect(x, y) - gl.stepunit(8, 6) - gl.maxsize(self.maxx, self.maxy) - gl.winconstraints() - self.bindvideo() - - def bindvideo(self): - if not self.video: return - x, y = gl.getsize() - if not self.use_24: - self.curx, self.cury = x, y - self.video.SetSize(x, y) - drop = self.b_drop.get_button() - if drop: - param = [SV.FIELDDROP, 1, SV.GENLOCK, SV.GENLOCK_OFF] - else: - param = [SV.FIELDDROP, 0, SV.GENLOCK, SV.GENLOCK_ON] - if self.rgb: - param = param+[SV.COLOR, SV.DEFAULT_COLOR, \ - SV.DITHER, 1, \ - SV.INPUT_BYPASS, 0] - else: - param = param+[SV.COLOR, SV.MONO, SV.DITHER, 0, \ - SV.INPUT_BYPASS, 1] - self.video.BindGLWindow(self.window, SV.IN_REPLACE) - self.video.SetParam(param) - - def rebindvideo(self): - gl.winset(self.window) - self.bindvideo() - - def reset(self): - self.close_video() - self.close_audio() - if self.vcr: - try: - ok = self.vcr.still() - except VCR.error: - pass - self.vcr = None - self.b_capture.set_button(0) - - # Event handler (catches resize of video window) - - def do_event(self, dev, val): - #print 'Event:', dev, val - if dev in (DEVICE.WINSHUT, DEVICE.WINQUIT): - self.close() - if dev == DEVICE.REDRAW and val == self.window: - self.rebindvideo() - self.settitle() - - # Video controls: format, mode, file - - def cb_vformat(self, *args): - self.reset() - self.get_vformat() - if self.mono_use_thresh: - s = `self.mono_thresh` - s = fl.show_input('Please enter mono threshold', s) - if s: - try: - self.mono_thresh = string.atoi(s) - except string.atoi_error: - fl.show_message('Bad input, using', \ - `self.mono_thresh`, '') - self.rebindvideo() - - def cb_cformat(self, *args): - i = self.c_cformat.get_choice() - self.comp_scheme = self.all_comp_schemes[i-1] - - - def cb_vmode(self, *args): - if self.vcr: - self.vcr = None - self.vmode = self.c_vmode.get_choice() - self.form.freeze_form() - self.g_cont.hide_object() - self.g_burst.hide_object() - self.g_single.hide_object() - self.g_vcr.hide_object() - if self.vmode == VM_CONT: - self.g_cont.show_object() - elif self.vmode == VM_BURST: - self.g_burst.show_object() - elif self.vmode == VM_SINGLE: - self.g_single.show_object() - elif self.vmode == VM_VCR: - self.g_vcr.show_object() - self.form.unfreeze_form() - - def cb_vfile(self, *args): - filename = self.vfile - hd, tl = os.path.split(filename) - filename = fl.file_selector('Video save file:', hd, '', tl) - if filename: - self.reset() - hd, tl = os.path.split(filename) - if hd == os.getcwd(): - filename = tl - self.vfile = filename - - # Video mode specific video controls - - def cb_rate(self, *args): - pass - - def cb_drop(self, *args): - self.rebindvideo() - - def cb_maxmem(self, *args): - pass - - def cb_nframes(self, *args): - pass - - def cb_fps(self, *args): - pass - - def cb_nframes_vcr(self, *args): - pass - - def cb_rate_vcr(self, *args): - pass - - def cb_vcrspeed(self, *args): - pass - - def cb_rgb24_size(self, *args): - i = self.c_rgb24_size.get_choice() - if i: - self.rgb24_size = i - - # Audio controls: format, file - - def cb_aformat(self, *args): - self.get_aformat() - - def cb_afile(self, *args): - filename = self.afile - hd, tl = os.path.split(filename) - filename = fl.file_selector('Audio save file:', hd, '', tl) - if filename: - self.reset() - hd, tl = os.path.split(filename) - if hd == os.getcwd(): - filename = tl - self.afile = filename - - # General controls: capture, reset, play, quit - - def cb_capture(self, *args): - if self.capturing: - raise StopCapture - if not self.b_capture.get_button(): - return - if not self.video or not self.vformat: - gl.ringbell() - return - if self.vmode == VM_CONT: - self.cont_capture() - elif self.vmode == VM_BURST: - self.burst_capture() - elif self.vmode == VM_SINGLE: - self.single_capture(None, None) - elif self.vmode == VM_VCR: - self.vcr_capture() - - def cb_reset(self, *args): - self.reset() - - def cb_play(self, *args): - self.reset() - sts = os.system('Vplay -q ' + self.vfile + ' &') - - def cb_quit(self, *args): - self.close() - - # Capture routines - - def burst_capture(self): - self.setwatch() - gl.winset(self.window) - x, y = gl.getsize() - if self.use_24: - fl.show_message('Sorry, no 24 bit continuous capture yet', '', '') - return - vformat = SV.RGB8_FRAMES - nframes = self.getint(self.in_nframes, 0) - if nframes == 0: - maxmem = self.getint(self.in_maxmem, 1.0) - memsize = int(maxmem * 1024 * 1024) - nframes = self.calcnframes(memsize) - info = (vformat, x, y, nframes, 1) - try: - info2, data, bitvec = self.video.CaptureBurst(info) - except sv.error, msg: - self.b_capture.set_button(0) - self.setarrow() - fl.show_message('Capture error:', str(msg), '') - return - if info <> info2: print info, '<>', info2 - self.save_burst(info2, data, bitvec) - self.setarrow() - - def calcnframes(self, memsize): - gl.winset(self.window) - x, y = gl.getsize() - pixels = x*y - pixels = pixels/2 # XXX always assume fields - if self.mono or self.grey: - n = memsize/pixels - else: - n = memsize/(4*pixels) - return max(1, n) - - def save_burst(self, info, data, bitvec): - (vformat, x, y, nframes, rate) = info - self.open_if_closed() - fieldsize = x*y/2 - nskipped = 0 - realframeno = 0 - tpf = 1000 / 50.0 # XXX - for frameno in range(0, nframes*2): - if frameno <> 0 and \ - bitvec[frameno] == bitvec[frameno-1]: - nskipped = nskipped + 1 - continue - # - # Save field. - # XXX Works only for fields and top-to-bottom - # - start = frameno*fieldsize - field = data[start:start+fieldsize] - realframeno = realframeno + 1 - fn = int(realframeno*tpf) - if not self.write_frame(fn, field): - break - - def cont_capture(self): - saved_label = self.b_capture.label - self.b_capture.label = 'Stop\n' + saved_label - self.open_if_closed() - self.init_cont() - fps = 59.64 # Fields per second - # XXX (fps of Indigo monitor, not of PAL or NTSC!) - tpf = 1000.0 / fps # Time per field in msec - self.capturing = 1 - self.start_audio() - while 1: - try: - void = fl.check_forms() - except StopCapture: - break - try: - cd, id = self.video.GetCaptureData() - except sv.error: - sgi.nap(1) - continue - id = id + 2*self.rate - data = cd.InterleaveFields(1) - cd.UnlockCaptureData() - t = id*tpf - if not self.write_frame(t, data): - break - self.stop_audio() - self.capturing = 0 - self.end_cont() - if self.aout: - # If recording audio, can't capture multiple sequences - self.reset() - self.b_capture.label = saved_label - - def single_capture(self, stepfunc, timecode): - self.open_if_closed() - self.init_cont() - while 1: - try: - cd, id = self.video.GetCaptureData() - break - except sv.error: - pass - sgi.nap(1) - if stepfunc: # This might step the video - d=stepfunc() # to the next frame - if not self.use_24: - data = cd.InterleaveFields(1) - else: - x, y = self.vout.getsize() - if self.use_compress: - if self.rgb24_size == 1: - data = cd.YUVtoYUV422DC(0) - elif self.rgb24_size == 2: - data = cd.YUVtoYUV422DC_quarter(1) - x = x/2 - y = y/2 - elif self.rgb24_size == 3: - data = cd.YUVtoYUV422DC_sixteenth(1) - x = x/4 - y = y/4 - else: - data = cd.YUVtoRGB(1) - if self.maxx*self.maxy*4 <> len(data): - print 'maxx,maxy,exp,got=', self.maxx, - print self.maxy,self.maxx*self.maxy*4, - print len(data) - fl.showmessage('Wrong sized data') - return 0 - if self.rgb24_size <> 1: - data = imageop.scale(data, 4, \ - self.maxx, self.maxy, x, y) - if self.use_jpeg: - import jpeg - data = jpeg.compress(data, x, y, 4) - if self.use_compress: - data = self.compressor.Compress(1, data) - cd.UnlockCaptureData() - self.end_cont() - if timecode == None: - timecode = (self.nframes+1) * (1000/25) - return self.write_frame(timecode, data) - - def vcr_capture(self): - if not self.vcr: - try: - print 'Connecting to VCR ...' - self.vcr = VCR.VCR() - print 'Waiting for VCR to come online ...' - self.vcr.initvcr() - print 'Preparing VCR ...' - if not (self.vcr.fmmode('dnr') and \ - self.vcr.dmcontrol('digital slow')): - self.vcr_error('digital slow failed') - return - print 'VCR OK.' - except VCR.error, msg: - self.vcr = None - self.vcr_error(msg) - return - if not self.vcr.still(): - self.vcr_error('still failed') - return - self.open_if_closed() - rate = self.getint(self.in_rate_vcr, 1) - rate = max(rate, 1) - vcrspeed = self.c_vcrspeed.get_choice() - vcrspeed = VcrSpeeds[vcrspeed] - if vcrspeed == 0: - stepfunc = self.vcr.step - else: - stepfunc = None - self.speed_factor = rate - addr = start_addr = self.vcr.sense() - if not self.single_capture(None, 0): - return - print 'captured %02d:%02d:%02d:%02d' % self.vcr.addr2tc(addr) - count = self.getint(self.in_nframes_vcr, 1) - 1 - if count <= 0: - while rate > 0: - if not self.vcr.step(): - self.vcr_error('step failed') - here = self.vcr.sense() - if here > addr: - rate = rate - (here - addr) - addr = here - return - if not self.vcr.fwdshuttle(vcrspeed): - self.vcr_error('fwd shuttle failed') - return - cycle = 0 - while count > 0: - try: - here = self.vcr.sense() - except VCR.error, msg: - self.vcr_error(msg) - break - if here <> addr: - if here <> addr+1: - print 'Missed', here-addr-1, - print 'frame' + 's'*(here-addr-1 <> 1) - cycle = (cycle+1) % rate - if cycle == 0: - tc = (here-start_addr)*40 - if not self.single_capture(stepfunc, \ - tc): - break - print 'captured %02d:%02d:%02d:%02d' \ - % self.vcr.addr2tc(here) - count = count -1 - addr = here - if self.vcr and not self.vcr.still(): - self.vcr_error('still failed') - - def vcr_error(self, msg): - self.reset() - fl.show_message('VCR error:', str(msg), '') - - # Init/end continuous capture mode - - def init_cont(self): - qsize = 1 - if self.vmode == VM_CONT: - self.rate = self.getint(self.in_rate, 2) - else: - self.rate = 2 - x, y = self.vout.getsize() - if self.use_24: - info = (SV.YUV411_FRAMES, x, y, qsize, self.rate) - else: - info = (SV.RGB8_FRAMES, x, y, qsize, self.rate) - info2 = self.video.InitContinuousCapture(info) - if info2 <> info: - # XXX This is really only debug info - print 'Info mismatch: requested', info, 'got', info2 - - def end_cont(self): - self.video.EndContinuousCapture() - - # Misc stuff - - def settitle(self): - gl.winset(self.window) - x, y = gl.getsize() - title = 'Vb ' + self.vfile + ' (%dx%d)' % (x, y) - gl.wintitle(title) - - def get_vformat(self): - i = self.c_vformat.get_choice() - label = VideoFormatLabels[i-1] - format = VideoFormats[i-1] - if format == 'compress' and cl == None: - fl.show_message('Sorry, no compression library support') - format = '' - label = 'Video off' - self.vformat = format - if self.vformat == '': - self.form.freeze_form() - self.g_video.hide_object() - self.g_cont.hide_object() - self.g_burst.hide_object() - self.g_single.hide_object() - self.form.unfreeze_form() - else: - self.g_video.show_object() - if self.vmode == VM_CONT: - self.g_cont.show_object() - elif self.vmode == VM_BURST: - self.g_burst.show_object() - elif self.vmode == VM_SINGLE: - self.g_single.show_object() - # - self.rgb = (format[:3] == 'rgb' or format == 'compress') - self.mono = (format == 'mono') - self.grey = (format[:4] == 'grey') - self.use_24 = (format in ('rgb', 'jpeg', 'compress')) - if self.use_24: - self.g_rgb24.show_object() - else: - self.g_rgb24.hide_object() - self.use_jpeg = (format == 'jpeg') - self.mono_use_thresh = (label == 'mono thresh') - self.use_compress = (format == 'compress') - if self.use_compress: - self.g_compress.show_object() - else: - self.g_compress.hide_object() - s = format[4:] - if self.grey and s: - self.greybits = string.atoi(s) - else: - self.greybits = 8 - if label == 'grey2 dith': - self.greybits = -2 - # - convertor = None - if self.grey: - if self.greybits == 2: - convertor = imageop.grey2grey2 - elif self.greybits == 4: - convertor = imageop.grey2grey4 - elif self.greybits == -2: - convertor = imageop.dither2grey2 - self.convertor = convertor - self.optfullsizewindow() - - def get_aformat(self): - self.reset() - self.aformat = self.c_aformat.get_choice() - if self.aformat == A_OFF: - self.g_audio.hide_object() - else: - self.g_audio.show_object() - - def init_compressor(self, w, h): - self.compressor = None - scheme = cl.QuerySchemeFromName(CL.VIDEO, self.comp_scheme) - self.compressor = cl.OpenCompressor(scheme) - parambuf = [CL.IMAGE_WIDTH, w, \ - CL.IMAGE_HEIGHT, h, \ - CL.ORIGINAL_FORMAT, CL.YUV422DC] - self.compressor.SetParams(parambuf) - return self.compressor.Compress(0, '') - - def open_if_closed(self): - if not self.vout: - self.open_video() - if not self.aout: - self.open_audio() - - # File I/O handling - - def open_video(self): - self.close_video() - gl.winset(self.window) - x, y = gl.getsize() - if self.use_24: - if self.rgb24_size == 2: - x, y = x/2, y/2 - elif self.rgb24_size == 3: - x, y = x/4, y/4 - vout = VFile.VoutFile(self.vfile) - vout.setformat(self.vformat) - if self.vformat == 'compress': - cheader = self.init_compressor(x, y) - vout.setcompressheader(cheader) - vout.setsize(x, y) - if self.vmode == VM_BURST: - vout.setpf((1, -2)) - vout.writeheader() - self.vout = vout - self.nframes = 0 - self.speed_factor = 1 - self.t_nframes.label = `self.nframes` - - def write_frame(self, t, data): - t = t * self.speed_factor - if not self.vout: - gl.ringbell() - return 0 - if self.convertor: - data = self.convertor(data, len(data), 1) - elif self.mono: - if self.mono_use_thresh: - data = imageop.grey2mono(data, \ - len(data), 1,\ - self.mono_thresh) - else: - data = imageop.dither2mono(data, \ - len(data), 1) - try: - self.vout.writeframe(int(t), data, None) - except IOError, msg: - self.reset() - if msg == (0, 'Error 0'): - msg = 'disk full??' - fl.show_message('IOError', str(msg), '') - return 0 - self.nframes = self.nframes + 1 - self.t_nframes.label = `self.nframes` - return 1 - - def close_video(self): - if not self.vout: - return - self.nframes = 0 - self.t_nframes.label = '' - try: - self.vout.close() - except IOError, msg: - if msg == (0, 'Error 0'): - msg = 'disk full??' - fl.show_message('IOError', str(msg), '') - self.vout = None - self.compressor = None - - # Watch cursor handling - - def setwatch(self): - gl.winset(self.form.window) - gl.setcursor(WATCH, 0, 0) - gl.winset(self.window) - gl.setcursor(WATCH, 0, 0) - - def setarrow(self): - gl.winset(self.form.window) - gl.setcursor(ARROW, 0, 0) - gl.winset(self.window) - gl.setcursor(ARROW, 0, 0) - - # Numeric field handling - - def getint(self, field, default): - try: - value = string.atoi(field.get_input()) - except string.atoi_error: - value = default - field.set_input(`value`) - return value - - def getfloat(self, field, default): - try: - value = float(eval(field.get_input())) - except: - value = float(default) - field.set_input(`value`) - return value - - # Audio stuff - - def open_audio(self): - if self.aformat == A_OFF: - return - import aifc - import al - import AL - import thread - self.close_audio() - params = [AL.INPUT_RATE, 0] - al.getparams(AL.DEFAULT_DEVICE, params) - rate = params[1] - self.aout = aifc.open(self.afile, 'w') - if self.aformat in (A_16_STEREO, A_8_STEREO): - nch = AL.STEREO - else: - nch = AL.MONO - if self.aformat in (A_16_STEREO, A_16_MONO): - width = AL.SAMPLE_16 - else: - width = AL.SAMPLE_8 - self.aout.setnchannels(nch) - self.aout.setsampwidth(width) - self.aout.setframerate(rate) - c = al.newconfig() - c.setqueuesize(8000) - c.setchannels(nch) - c.setwidth(width) - self.aport = al.openport('Vb audio record', 'r', c) - self.audio_stop = 0 - self.audio_ok = 0 - self.audio_busy = 1 - thread.start_new_thread(self.record_audio, ()) - - def start_audio(self): - if self.aformat == A_OFF: - return - self.audio_ok = 1 - - def record_audio(self, *args): - # This function runs in a separate thread - # Currently no semaphores are used - while not self.audio_stop: - data = self.aport.readsamps(4000) - if self.audio_ok: - self.aout.writeframes(data) - data = None - self.audio_busy = 0 - - def stop_audio(self): - self.audio_ok = 0 - - def close_audio(self): - if self.aout: - self.audio_ok = 0 - self.audio_stop = 1 - while self.audio_busy: - time.sleep(0.1) - self.aout.close() - self.aout = None - if self.aport: - self.aport.closeport() - self.aport = None - - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' - sys.exit(1) diff --git a/Demo/sgi/video/VbForm.fd b/Demo/sgi/video/VbForm.fd deleted file mode 100644 index fd9759fb14..0000000000 --- a/Demo/sgi/video/VbForm.fd +++ /dev/null @@ -1,615 +0,0 @@ -Magic: 12321 - -Internal Form Definition File - (do not change) - -Number of forms: 1 - -=============== FORM =============== -Name: form -Width: 450.000000 -Height: 260.000000 -Number of Objects: 40 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 450.000000 260.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 11 -type: 5 -box: 330.000000 150.000000 110.000015 60.000004 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 1 -size: 11.000000 -lcol: 0 -label: Capture -name: b_capture -callback: cb_capture -argument: 0 - --------------------- -class: 11 -type: 0 -box: 330.000000 10.000000 110.000008 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Quit -name: b_quit -callback: cb_quit -argument: 0 - --------------------- -class: 11 -type: 0 -box: 330.000000 50.000000 110.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Playback -name: b_play -callback: cb_play -argument: 0 - --------------------- -class: 42 -type: 0 -box: 80.000000 220.000000 120.000000 30.000000 -boxtype: 5 -colors: 7 0 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: Format: -name: c_vformat -callback: cb_vformat -argument: 0 - --------------------- -class: 11 -type: 0 -box: 330.000000 220.000000 110.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Reset -name: b_reset -callback: cb_reset -argument: 0 - --------------------- -class: 42 -type: 0 -box: 80.000000 50.000000 120.000000 30.000000 -boxtype: 5 -colors: 7 0 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: Format: -name: c_aformat -callback: cb_aformat -argument: 0 - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 1668246586 540019308 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_audio -callback: -argument: - --------------------- -class: 11 -type: 0 -box: 10.000000 10.000000 190.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Set audio file... -name: b_afile -callback: cb_afile -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 876099360 892416522 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 1147496041 1852404841 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_video -callback: -argument: - --------------------- -class: 42 -type: 0 -box: 80.000000 180.000000 120.000000 30.000000 -boxtype: 5 -colors: 7 0 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: Mode: -name: c_vmode -callback: cb_vmode -argument: 0 - --------------------- -class: 11 -type: 0 -box: 10.000000 90.000000 190.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Set video file... -name: b_vfile -callback: cb_vfile -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 544171552 1331849829 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_single -callback: -argument: - --------------------- -class: 31 -type: 2 -box: 220.000000 150.000000 100.000000 30.000000 -boxtype: 2 -colors: 13 5 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: Frames/sec -name: in_fps -callback: cb_fps -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_burst -callback: -argument: - --------------------- -class: 31 -type: 1 -box: 220.000000 150.000000 100.000000 30.000000 -boxtype: 2 -colors: 13 5 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: Max Mbytes: -name: in_maxmem -callback: cb_maxmem -argument: 0 - --------------------- -class: 31 -type: 2 -box: 220.000000 90.000000 100.000000 30.000000 -boxtype: 2 -colors: 13 5 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: Nr. of frames: -name: in_nframes -callback: cb_nframes -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_cont -callback: -argument: - --------------------- -class: 31 -type: 2 -box: 250.000000 150.000000 40.000000 30.000000 -boxtype: 2 -colors: 13 5 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: Capture rate: -name: in_rate -callback: cb_rate -argument: 0 - --------------------- -class: 2 -type: 0 -box: 220.000000 150.000000 30.000000 30.000000 -boxtype: 0 -colors: 47 47 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: 1/ -name: -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 290.000000 150.000000 30.000000 30.000000 -boxtype: 0 -colors: 47 47 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: fr -name: -callback: -argument: - --------------------- -class: 13 -type: 0 -box: 220.000000 90.000000 100.000000 30.000000 -boxtype: 0 -colors: 7 3 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Fielddrop -name: b_drop -callback: cb_drop -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 330.000000 90.000000 110.000000 30.000002 -boxtype: 2 -colors: 47 47 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: t_nframes -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 330.000000 120.000000 110.000000 30.000000 -boxtype: 0 -colors: 47 47 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: Frames done: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 640 235 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_vcr -callback: -argument: - --------------------- -class: 31 -type: 2 -box: 220.000000 90.000000 100.000000 30.000000 -boxtype: 2 -colors: 13 5 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: # frames wtd: -name: in_nframes_vcr -callback: cb_nframes_vcr -argument: 0 - --------------------- -class: 31 -type: 2 -box: 220.000000 150.000000 100.000000 30.000000 -boxtype: 2 -colors: 13 5 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: Sample rate: -name: in_rate_vcr -callback: cb_rate_vcr -argument: 0 - --------------------- -class: 42 -type: 0 -box: 220.000000 10.000000 100.000000 30.000000 -boxtype: 5 -colors: 7 0 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: VCR speed: -name: c_vcrspeed -callback: cb_vcrspeed -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 640 235 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 58720287 33751040 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_rgb24 -callback: -argument: - --------------------- -class: 42 -type: 0 -box: 260.000000 220.000000 60.000000 30.000000 -boxtype: 5 -colors: 7 0 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: Size: -name: c_rgb24_size -callback: cb_rgb24_size -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 10.000000 -lcol: 0 -label: -name: g_compress -callback: -argument: - --------------------- -class: 42 -type: 0 -box: 80.000000 140.000000 120.000000 30.000000 -boxtype: 5 -colors: 7 0 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: Scheme: -name: c_cformat -callback: cb_cformat -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 10.000000 -lcol: 0 -label: -name: -callback: -argument: - -============================== -create_the_forms diff --git a/Demo/sgi/video/Vcopy.py b/Demo/sgi/video/Vcopy.py deleted file mode 100755 index 59c06a0f69..0000000000 --- a/Demo/sgi/video/Vcopy.py +++ /dev/null @@ -1,291 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -# Universal (non-interactive) CMIF video file copier. - - -# Possibilities: -# -# - Manipulate the time base: -# = resample at a fixed rate -# = divide the time codes by a speed factor (to make it go faster/slower) -# = drop frames that are less than n msec apart (to accomodate slow players) -# - Convert to a different format -# - Magnify (scale) the image - - -# Usage function (keep this up-to-date if you change the program!) - -def usage(): - print 'Usage: Vcopy [options] [infile [outfile]]' - print - print 'Options:' - print - print '-t type : new image type (default unchanged)' - print - print '-M magnify : image magnification factor (default unchanged)' - print '-w width : output image width (default height*4/3 if -h used)' - print '-h height : output image height (default width*3/4 if -w used)' - print - print '-p pf : new x and y packfactor (default unchanged)' - print '-x xpf : new x packfactor (default unchanged)' - print '-y ypf : new y packfactor (default unchanged)' - print - print '-m delta : drop frames closer than delta msec (default 0)' - print '-r delta : regenerate input time base delta msec apart' - print '-s speed : speed change factor (default unchanged)' - print - print 'infile : input file (default film.video)' - print 'outfile : output file (default out.video)' - - -import sys -sys.path.append('/ufs/guido/src/video') - -import VFile -import imgconv -import imageop -import getopt -import string - - -# Global options - -speed = 1.0 -mindelta = 0 -regen = None -newpf = None -newtype = None -magnify = None -newwidth = None -newheight = None - - -# Function to turn a string into a float - -atof_error = 'atof_error' # Exception if it fails - -def atof(s): - try: - return float(eval(s)) - except: - raise atof_error - - -# Main program -- mostly command line parsing - -def main(): - global speed, mindelta, regen, newpf, newtype, \ - magnify, newwidth, newheight - - # Parse command line - try: - opts, args = getopt.getopt(sys.argv[1:], \ - 'M:h:m:p:r:s:t:w:x:y:') - except getopt.error, msg: - sys.stdout = sys.stderr - print 'Error:', msg, '\n' - usage() - sys.exit(2) - - xpf = ypf = None - - # Interpret options - try: - for opt, arg in opts: - if opt == '-M': magnify = atof(arg) - if opt == '-h': height = string.atoi(arg) - if opt == '-m': mindelta = string.atoi(arg) - if opt == '-p': xpf = ypf = string.atoi(arg) - if opt == '-r': regen = string.atoi(arg) - if opt == '-s': speed = atof(arg) - if opt == '-t': newtype = arg - if opt == '-w': newwidth = string.atoi(arg) - if opt == '-x': xpf = string.atoi(arg) - if opt == '-y': ypf = string.atoi(arg) - except string.atoi_error: - sys.stdout = sys.stderr - print 'Option', opt, 'requires integer argument' - sys.exit(2) - except atof_error: - sys.stdout = sys.stderr - print 'Option', opt, 'requires float argument' - sys.exit(2) - - if xpf or ypf: - newpf = (xpf, ypf) - - if newwidth or newheight: - if magnify: - sys.stdout = sys.stderr - print 'Options -w or -h are incompatible with -M' - sys.exit(2) - if not newheight: - newheight = newwidth * 3 / 4 - elif not newwidth: - newwidth = newheight * 4 / 3 - - # Check filename arguments - if len(args) < 1: - args.append('film.video') - if len(args) < 2: - args.append('out.video') - if len(args) > 2: - usage() - sys.exit(2) - if args[0] == args[1]: - sys.stderr.write('Input file can\'t be output file\n') - sys.exit(2) - - # Do the right thing - sts = process(args[0], args[1]) - - # Exit - sys.exit(sts) - - -# Copy one file to another - -def process(infilename, outfilename): - global newwidth, newheight, newpf - - try: - vin = VFile.BasicVinFile(infilename) - except IOError, msg: - sys.stderr.write(infilename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(infilename + ': EOF in video file\n') - return 1 - - try: - vout = VFile.BasicVoutFile(outfilename) - except IOError, msg: - sys.stderr.write(outfilename + ': I/O error: ' + `msg` + '\n') - return 1 - - print '=== input file ===' - vin.printinfo() - - vout.setinfo(vin.getinfo()) - - scale = 0 - flip = 0 - decompress = 0 - - vinfmt = vin.format - if vinfmt == 'compress': - if not newtype or newtype == 'compress': - # compressed->compressed: copy compression header - vout.setcompressheader(vin.getcompressheader()) - else: - # compressed->something else: go via rgb-24 - decompress = 1 - vinfmt = 'rgb' - elif newtype == 'compress': - # something else->compressed: not implemented - sys.stderr.write('Sorry, conversion to compressed not yet implemented\n') - return 1 - if newtype: - vout.setformat(newtype) - try: - convert = imgconv.getconverter(vinfmt, vout.format) - except imgconv.error, msg: - sys.stderr.write(str(msg) + '\n') - return 1 - - if newpf: - xpf, ypf = newpf - if not xpf: xpf = vin.xpf - if not ypf: ypf = vout.ypf - newpf = (xpf, ypf) - vout.setpf(newpf) - - if newwidth and newheight: - scale = 1 - - if vin.upside_down <> vout.upside_down or \ - vin.mirror_image <> vout.mirror_image: - flip = 1 - - inwidth, inheight = vin.getsize() - inwidth = inwidth / vin.xpf - inheight = inheight / vin.ypf - - if magnify: - newwidth = int(vout.width * magnify) - newheight = int(vout.height * magnify) - scale = 1 - - if scale: - vout.setsize(newwidth, newheight) - else: - newwidth, newheight = vout.getsize() - - if vin.packfactor <> vout.packfactor: - scale = 1 - - if scale or flip: - if vout.bpp not in (8, 32): - sys.stderr.write('Can\'t scale or flip this type\n') - return 1 - - newwidth = newwidth / vout.xpf - newheight = newheight / vout.ypf - - print '=== output file ===' - vout.printinfo() - vout.writeheader() - - told = 0 - nin = 0 - nout = 0 - tin = 0 - tout = 0 - - while 1: - try: - tin, data, cdata = vin.getnextframe() - except EOFError: - break - if decompress: - data = vin.decompress(data) - nin = nin + 1 - if regen: - tout = nin * regen - else: - tout = tin - tout = int(tout / speed) - if tout - told < mindelta: - continue - told = tout - if newtype: - data = convert(data, inwidth, inheight) - if scale: - data = imageop.scale(data, vout.bpp/8, \ - inwidth, inheight, newwidth, newheight) - if flip: - x0, y0 = 0, 0 - x1, y1 = newwidth-1, newheight-1 - if vin.upside_down <> vout.upside_down: - y1, y0 = y0, y1 - if vin.mirror_image <> vout.mirror_image: - x1, x0 = x0, x1 - data = imageop.crop(data, vout.bpp/8, \ - newwidth, newheight, x0, y0, x1, y1) - print 'Writing frame', nout - vout.writeframe(tout, data, cdata) - nout = nout + 1 - - vout.close() - vin.close() - - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/VcrIndex.py b/Demo/sgi/video/VcrIndex.py deleted file mode 100755 index 80212ee561..0000000000 --- a/Demo/sgi/video/VcrIndex.py +++ /dev/null @@ -1,327 +0,0 @@ -# -# A VCR index. -# -import os -import string - -error='VcrIndex.error' -VERSION_STRING='#!VcrIndex 1.1\n' -PREV_VERSION_STRING='#!VcrIndex 1.0\n' - -class VcrIndex: - def __init__(self, name): - self.curmovie = None - self.curscene = None - self.modified = 0 - self.filename = name - self.basename = os.path.basename(name) - self.editable = [] - if not name: - self.movies = {} - return - try: - fp = open(name, 'r') - except IOError: - self.movies = {} - return - header = fp.readline() - if header == PREV_VERSION_STRING: - print 'Converting old-format database...' - data = fp.read(100000) - self.movies = eval(data) - for m in self.movies.keys(): - d = self.movies[m] - newd = {} - for s in d.keys(): - newsd = {} - newsd['START'] = d[s] - if s == 'START': - s = '-ALL-' - newd[s] = newsd - - self.movies[m] = newd - print 'Done.' - return - if header <> VERSION_STRING: - print 'VcrIndex: incorrect version string:', header - self.movies = {} - return - data = fp.read(100000) - self.movies = eval(data) - # - # Save database to given file (or same file as read from if no - # filename given). - # - def save(self, name): - if not name: - name = self.filename - if not name: - raise error, 'No filename given' - self.filename = name - bupname = name + '~' - try: - os.unlink(bupname) - except os.error: - pass - try: - os.rename(name, bupname) - except os.error: - pass - fp = open(name, 'w') - data = str(self.movies) - fp.write(VERSION_STRING) - fp.write(data) - fp.write('\n') - fp.close() - self.modified = 0 - # - # Get a list of movie names in tape order - # - def get_movienames(self): - names = self.movies.keys() - sorted = [] - for name in names: - sorted.append(self.movies[name]['-ALL-']['START'], name) - sorted.sort() - rv = [] - for pos, name in sorted: - rv.append(name) - return rv - # - # Get a list of scene names in tape order - # - def get_scenenames(self): - if not self.curmovie: - return [] - scenedict = self.movies[self.curmovie] - names = scenedict.keys() - sorted = [] - for name in names: - sorted.append(scenedict[name], name) - sorted.sort() - rv = [] - for pos, name in sorted: - rv.append(name) - return rv - # - # Get a list of scene ids (format '00:02:32:12 name') in tape order - # - def get_sceneids(self): - if not self.curmovie: - return [] - scenedict = self.movies[self.curmovie] - names = scenedict.keys() - sorted = [] - for name in names: - sorted.append(scenedict[name]['START'], name) - sorted.sort() - rv = [] - for pos, name in sorted: - str = '%02d:%02d:%02d:%02d ' % pos - rv.append(str + name) - return rv - # - # Does a movie exist? - # - def movie_exists(self, name): - return self.movies.has_key(name) - # - # Select a movie. - # - def movie_select(self, name): - if not self.movies.has_key(name): - raise error, 'No such movie: '+name - self.curmovie = name - self.curscene = None - # - # Get movie dictionary, or raise an error if no current movie. - # - def _getmoviedict(self): - if not self.curmovie: - raise error, 'No current movie' - return self.movies[self.curmovie] - # - # Rename a movie. - # - def movie_rename(self, newname): - scenedict = self._getmoviedict() - if self.movie_exists(newname): - raise error, 'Movie already exists: '+newname - del self.movies[self.curmovie] - self.movies[newname] = scenedict - self.curmovie = newname - self.modified = 1 - # - # Copy a movie. - # - def movie_copy(self, newname): - scenedict = self._getmoviedict() - if self.movie_exists(newname): - raise error, 'Movie already exists: '+newname - newdict = {} - for k in scenedict.keys(): - olddata = scenedict[k] - newdata = {} - for i in olddata.keys(): - newdata[i] = olddata[i] - newdict[k] = newdata - self.movies[newname] = newdict - self.curmovie = newname - self.modified = 1 - # - # Delete a movie. - # - def movie_delete(self): - if not self.curmovie: - raise error, 'No current movie' - del self.movies[self.curmovie] - self.curmovie = None - self.curscene = None - self.modified = 1 - # - # Create a new movie. - # - def movie_new(self, name, pos): - if self.movie_exists(name): - raise error, 'Movie already exists: '+name - newdict = {} - newsdict = {} - newsdict['START'] = pos - newdict['-ALL-'] = newsdict - self.movies[name] = newdict - self.curmovie = name - self.curscene = None - self.modified = 1 - # - # Does a scene exist? - # - def scene_exists(self, name): - scenedict = self._getmoviedict() - return scenedict.has_key(name) - # - # Select a current scene. - # - def scene_select(self, name): - scenedict = self._getmoviedict() - if not scenedict.has_key(name): - raise error, 'No such scene: '+name - self.curscene = name - # - # Rename a scene. - # - def scene_rename(self, newname): - scenedict = self._getmoviedict() - if not self.curscene: - raise error, 'No current scene' - if scenedict.has_key(newname): - raise error, 'Scene already exists: '+newname - if self.curscene == '-ALL-': - raise error, 'Cannot rename -ALL-' - scenedict[newname] = scenedict[self.curscene] - del scenedict[self.curscene] - self.curscene = newname - self.modified = 1 - # - # Copy a scene. - # - def scene_copy(self, newname): - scenedict = self._getmoviedict() - if not self.curscene: - raise error, 'No current scene' - if scenedict.has_key(newname): - raise error, 'Scene already exists: '+newname - scenedict[newname] = scenedict[self.curscene] - self.curscene = newname - self.modified = 1 - # - # Delete a scene. - # - def scene_delete(self): - scenedict = self._getmoviedict() - if not self.curscene: - raise error, 'No current scene' - if self.curscene == '-ALL-': - raise error, 'Cannot delete -ALL-' - del scenedict[self.curscene] - self.curscene = None - self.modified = 1 - # - # Add a new scene. - # - def scene_new(self, newname, pos): - scenedict = self._getmoviedict() - if scenedict.has_key(newname): - raise error, 'Scene already exists: '+newname - newdict = {} - newdict['START'] = pos - scenedict[newname] = newdict - self.curscene = newname - self.modified = 1 - # - # Get scene data. - # - def _getscenedata(self): - scenedict = self._getmoviedict() - if not self.curscene: - raise error, 'No current scene' - return scenedict[self.curscene] - # - # Data manipulation routines. - # - def pos_get(self): - return self._getscenedata()['START'] - # - def pos_set(self, pos): - data = self._getscenedata() - data['START'] = pos - self.modified = 1 - # - def comment_get(self): - data = self._getscenedata() - if data.has_key('COMMENT'): - return data['COMMENT'] - else: - return '' - # - def comment_set(self, comment): - data = self._getscenedata() - data['COMMENT'] = comment - self.modified = 1 - # - # Get the scene id of the current scene. - # - def get_cursceneid(self): - pos = self._getscenedata()['START'] - str = '%02d:%02d:%02d:%02d ' % pos - return str + self.curscene - # - # Convert a scene id to a scene name. - # - def scene_id2name(self, id): - pos = string.find(id, ' ') - if pos <= 0: - raise error, 'Not a scene id: '+id - return id[pos+1:] - # - # Select a scene given a position. - # - def pos_select(self, pos): - prevmovie = None - movies = self.get_movienames() - for movie in movies: - mpos = self.movies[movie]['-ALL-']['START'] - if mpos > pos: - break - prevmovie = movie - if not prevmovie: - raise error, 'Scene before BOT' - - self.movie_select(prevmovie) - scenes = self.get_scenenames() - scenedict = self._getmoviedict() - prevscene = 'START' - for scene in scenes: - if scenedict[scene]['START'] > pos: - break - prevscene = scene - self.scene_select(prevscene) diff --git a/Demo/sgi/video/Vedit.py b/Demo/sgi/video/Vedit.py deleted file mode 100755 index 0174e9f8d8..0000000000 --- a/Demo/sgi/video/Vedit.py +++ /dev/null @@ -1,301 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -# Edit CMIF movies interactively -- copy one or more files to an output file - - -# XXX To do: -# -# - convert between formats (grey, rgb, rgb8, ...) -# - change size -# - cut out a given area of the image -# - change time base (a la Vtime) - - -import sys -import os -import gl, GL, DEVICE -import fl, FL -import flp -import Viewer -import getopt -import string -import watchcursor - -ARROW = 0 -WATCH = 1 -watchcursor.defwatch(WATCH) - - -def main(): - qsize = 40 - opts, args = getopt.getopt(sys.argv[1:], 'q:') - for o, a in opts: - if o == '-q': - qsize = string.atoi(a) - ed = Editor(qsize) - if args[0:]: - ed.open_input(args[0]) - if args[1:]: - ed.open_output(args[1]) - while 1: - dummy = fl.do_forms() - - -class Editor: - - def __init__(self, qsize): - self.qsize = qsize - self.vin = None - self.vout = None - self.ifile = '' - self.ofile = '' - formdef = flp.parse_form('VeditForm', 'form') - flp.create_full_form(self, formdef) - self.form.show_form(FL.PLACE_SIZE, FL.TRUE, 'Vedit') - fl.set_event_call_back(self.do_event) - - def do_event(self, dev, val): - if dev == DEVICE.REDRAW: - if self.vin: - self.vin.redraw(val) - if self.vout: - self.vout.redraw(val) - - def busy(self): - gl.winset(self.form.window) - gl.setcursor(WATCH, 0, 0) - - def ready(self): - gl.winset(self.form.window) - gl.setcursor(ARROW, 0, 0) - - - def iocheck(self): - self.msg('') - if self.vin == None and self.vout == None: - self.err('Please open input and output files first') - return 0 - return self.icheck() and self.ocheck() - - def icheck(self): - self.msg('') - if self.vin == None: - self.err('Please open an input file first') - return 0 - return 1 - - def ocheck(self): - self.msg('') - if self.vout == None: - self.err('Please open an output file first') - return 0 - return 1 - - - def cb_in_new(self, *args): - self.msg('') - hd, tl = os.path.split(self.ifile) - filename = fl.file_selector('Input video file', hd, '', tl) - if not filename: return - self.open_input(filename) - - def cb_in_close(self, *args): - self.msg('') - self.close_input() - - def cb_in_skip(self, *args): - if not self.icheck(): return - if not self.vin.get(): self.err('End of input file') - self.ishow() - - def cb_in_back(self, *args): - if not self.icheck(): return - if not self.vin.backup(): self.err('Begin of input file') - self.ishow() - - def cb_in_slider(self, *args): - if not self.icheck(): return - left, pos, right = self.vin.qinfo() - i = int(self.in_slider.get_slider_value()) - i = max(i, left) - i = min(i, right) - if i == pos: return - if not self.vin.seek(i): - self.err('Input seek failed') - self.ishow() - - def cb_in_rewind(self, *args): - if not self.icheck(): return - self.vin.rewind() - self.ishow() - - - def cb_copy(self, *args): - if not self.iocheck(): return - data = self.vin.get() - if not data: - self.err('End of input file') - self.ishow() - return - if self.vout.getinfo() <> self.vin.getinfo(): - print 'Copying info...' - self.vout.setinfo(self.vin.getinfo()) - if self.vin.format == 'compress': - self.vout.setcompressheader(\ - self.vin.getcompressheader()) - self.vout.put(data) - self.oshow() - self.ishow() - - def cb_uncopy(self, *args): - if not self.iocheck(): return - if not self.vout.backup(): - self.err('Output buffer exhausted') - return - self.oshow() - if not self.vin.backup(): - self.err('Begin of input file') - return - self.ishow() - - - def cb_out_new(self, *args): - self.msg('') - hd, tl = os.path.split(self.ofile) - filename = fl.file_selector('Output video file', hd, '', tl) - if not filename: return - self.open_output(filename) - - def cb_out_close(self, *args): - self.msg('') - self.close_output() - - def cb_out_skip(self, *args): - if not self.ocheck(): return - if not self.vout.forward(): self.err('Output buffer exhausted') - self.oshow() - - def cb_out_back(self, *args): - if not self.ocheck(): return - if not self.vout.backup(): self.err('Output buffer exhausted') - self.oshow() - - def cb_out_slider(self, *args): - if not self.ocheck(): return - i = int(self.out_slider.get_slider_value()) - left, pos, right = self.vout.qinfo() - i = int(self.out_slider.get_slider_value()) - i = max(i, left) - i = min(i, right) - if i == pos: return - if not self.vout.seek(i): - self.err('Output seek failed') - self.oshow() - - def cb_out_trunc(self, *arcs): - if not self.ocheck(): return - self.vout.trunc() - self.oshow() - - def cb_out_rewind(self, *args): - if not self.ocheck(): return - self.vout.rewind() - self.oshow() - - - def cb_quit(self, *args): - self.close_input() - self.close_output() - sys.exit(0) - - - def open_input(self, filename): - self.ifile = filename - basename = os.path.split(filename)[1] - title = 'in: ' + basename - try: - vin = Viewer.InputViewer(filename, title) - except: - self.err('Can\'t open input file', filename) - return - self.close_input() - self.vin = vin - self.in_file.label = basename - self.ishow() - - def close_input(self): - if self.vin: - self.busy() - self.msg('Closing input file...') - self.vin.close() - self.ready() - self.msg('') - self.vin = None - self.in_file.label = '(none)' - self.format('in') - - def ishow(self): - self.vin.show() - self.format('in') - - def open_output(self, filename): - self.ofile = filename - basename = os.path.split(filename)[1] - title = 'out: ' + basename - try: - vout = Viewer.OutputViewer(filename, \ - title, self.qsize) - except: - self.err('Can\'t open output file', filename) - return - self.close_output() - self.vout = vout - self.out_file.label = basename - if self.vin: - self.vout.setinfo(self.vin.getinfo()) - self.oshow() - - def close_output(self): - if self.vout: - self.busy() - self.msg('Closing output file...') - self.vout.close() - self.ready() - self.msg('') - self.vout = None - self.out_file.label = '(none)' - self.format('out') - - def oshow(self): - self.vout.show() - self.format('out') - - - def msg(self, *args): - str = string.strip(string.join(args)) - self.msg_area.label = str - - def err(self, *args): - gl.ringbell() - apply(self.msg, args) - - def format(self, io): - v = getattr(self, 'v' + io) - if v == None: - left = right = pos = 0 - else: - left, pos, right = v.qinfo() - getattr(self, io + '_info1').label = `left` - getattr(self, io + '_info2').label = `pos` - getattr(self, io + '_info3').label = `right` - sl = getattr(self, io + '_slider') - self.form.freeze_form() - sl.set_slider_bounds(left, right) - sl.set_slider_value(pos) - self.form.unfreeze_form() - - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/VeditForm.fd b/Demo/sgi/video/VeditForm.fd deleted file mode 100644 index ba59de4d4f..0000000000 --- a/Demo/sgi/video/VeditForm.fd +++ /dev/null @@ -1,435 +0,0 @@ -Magic: 12321 - -Internal Form Definition File - (do not change) - -Number of forms: 1 - -=============== FORM =============== -Name: form -Width: 510.000000 -Height: 350.000000 -Number of Objects: 28 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 510.000000 350.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 1 -type: 6 -box: 10.000000 130.000000 240.000000 209.999985 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 1 -type: 6 -box: 260.000000 130.000000 240.000000 209.999985 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 10.000000 10.000000 430.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: CMIF Video Editor, by Guido van Rossum -name: msg_area -callback: -argument: - --------------------- -class: 11 -type: 4 -box: 200.000000 90.000000 120.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -> Copy -> -name: -callback: cb_copy -argument: 0 - --------------------- -class: 11 -type: 4 -box: 210.000000 220.000000 30.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: @> -name: -callback: cb_in_skip -argument: 0 - --------------------- -class: 11 -type: 0 -box: 20.000000 140.000000 220.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Rewind -name: -callback: cb_in_rewind -argument: 0 - --------------------- -class: 11 -type: 0 -box: 270.000000 140.000000 100.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Reset -name: -callback: cb_out_rewind -argument: 0 - --------------------- -class: 11 -type: 0 -box: 20.000000 260.000000 160.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: New input file... -name: -callback: cb_in_new -argument: 0 - --------------------- -class: 11 -type: 0 -box: 330.000000 260.000000 160.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: New output file... -name: -callback: cb_out_new -argument: 0 - --------------------- -class: 2 -type: 0 -box: 20.000000 300.000000 220.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: (none) -name: in_file -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 270.000000 300.000000 220.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: (none) -name: out_file -callback: -argument: - --------------------- -class: 11 -type: 0 -box: 450.000000 10.000000 50.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Quit -name: -callback: cb_quit -argument: 0 - --------------------- -class: 11 -type: 4 -box: 270.000000 220.000000 30.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: @< -name: -callback: cb_out_back -argument: 0 - --------------------- -class: 11 -type: 4 -box: 20.000000 220.000000 30.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: @< -name: -callback: cb_in_back -argument: 0 - --------------------- -class: 11 -type: 4 -box: 460.000000 220.000000 30.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: @> -name: -callback: cb_out_skip -argument: 0 - --------------------- -class: 11 -type: 4 -box: 200.000000 50.000000 120.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Uncopy -name: -callback: cb_uncopy -argument: 0 - --------------------- -class: 11 -type: 0 -box: 190.000000 260.000000 50.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Close -name: -callback: cb_in_close -argument: 0 - --------------------- -class: 11 -type: 0 -box: 270.000000 260.000000 50.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Close -name: -callback: cb_out_close -argument: 0 - --------------------- -class: 21 -type: 1 -box: 60.000000 220.000000 140.000000 30.000000 -boxtype: 2 -colors: 47 47 -alignment: 1 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: in_slider -callback: cb_in_slider -argument: 0 - --------------------- -class: 21 -type: 1 -box: 310.000000 220.000000 140.000000 30.000000 -boxtype: 2 -colors: 47 47 -alignment: 1 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: out_slider -callback: cb_out_slider -argument: 0 - --------------------- -class: 2 -type: 0 -box: 20.000000 180.000000 30.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 8.000000 -lcol: 0 -label: -name: in_info1 -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 100.000000 180.000000 60.000004 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: in_info2 -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 210.000000 180.000000 30.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 8.000000 -lcol: 0 -label: -name: in_info3 -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 270.000000 180.000000 30.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 8.000000 -lcol: 0 -label: -name: out_info1 -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 350.000000 180.000000 60.000004 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: out_info2 -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 460.000000 180.000000 30.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 8.000000 -lcol: 0 -label: -name: out_info3 -callback: -argument: - --------------------- -class: 11 -type: 0 -box: 390.000000 140.000000 100.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Truncate -name: -callback: cb_out_trunc -argument: 0 - -============================== -create_the_forms diff --git a/Demo/sgi/video/Vfix.py b/Demo/sgi/video/Vfix.py deleted file mode 100755 index 6b2602399c..0000000000 --- a/Demo/sgi/video/Vfix.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/ufs/guido/bin/sgi/python - -# Copy a video file, fixing the line width to be a multiple of 4 - - -# Usage: -# -# Vfix [infile [outfile]] - - -# Options: -# -# infile : input file (default film.video) -# outfile : output file (default out.video) - - -import sys -import imageop -sys.path.append('/ufs/guido/src/video') -import VFile - - -# Main program -- mostly command line parsing - -def main(): - args = sys.argv[1:] - if len(args) < 1: - args.append('film.video') - if len(args) < 2: - args.append('out.video') - if len(args) > 2: - sys.stderr.write('usage: Vfix [infile [outfile]]\n') - sys.exit(2) - sts = process(args[0], args[1]) - sys.exit(sts) - - -# Copy one file to another - -def process(infilename, outfilename): - try: - vin = VFile.BasicVinFile(infilename) - except IOError, msg: - sys.stderr.write(infilename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(infilename + ': EOF in video file\n') - return 1 - - try: - vout = VFile.BasicVoutFile(outfilename) - except IOError, msg: - sys.stderr.write(outfilename + ': I/O error: ' + `msg` + '\n') - return 1 - - info = vin.getinfo() - if info[0] <> 'grey': - sys.stderr.write('Vfix: input not in grey format\n') - return 1 - vout.setinfo(info) - inwidth, height = vin.getsize() - pf = vin.packfactor - if (inwidth/pf)%4 == 0: - sys.stderr.write('Vfix: fix not necessary\n') - return 1 - outwidth = (inwidth/pf/4)*4*pf - print 'inwidth =', inwidth, 'outwidth =', outwidth - vout.setsize(outwidth, height) - vout.writeheader() - n = 0 - try: - while 1: - t, data, cdata = vin.getnextframe() - n = n + 1 - sys.stderr.write('Frame ' + `n` + '...') - data = imageop.crop(data, 1, inwidth/pf, height/pf, \ - 0, 0, outwidth/pf-1, height/pf-1) - vout.writeframe(t, data, None) - sys.stderr.write('\n') - except EOFError: - pass - return 0 - - -# Don't forget to call the main program - -main() diff --git a/Demo/sgi/video/Vgeneric.py b/Demo/sgi/video/Vgeneric.py deleted file mode 100755 index 182adbe2ca..0000000000 --- a/Demo/sgi/video/Vgeneric.py +++ /dev/null @@ -1,2 +0,0 @@ -import sys, posixpath -exec('import ' + posixpath.basename(sys.argv[0]) + '\n') diff --git a/Demo/sgi/video/Viewer.py b/Demo/sgi/video/Viewer.py deleted file mode 100755 index 07cba54cec..0000000000 --- a/Demo/sgi/video/Viewer.py +++ /dev/null @@ -1,255 +0,0 @@ -import gl, GL -import VFile -import os - - -class InputViewer: - - def __init__(self, filename, title, *args): - try: - self.vin = VFile.VinFile(filename) - except (EOFError, VFile.Error): - raise IOError, 'bad video input file' - self.vin.warmcache() - if not title: - title = os.path.split(filename)[1] - self.filename = filename - self.title = title - self.qsize = len(self.vin.index) - gl.foreground() - gl.prefsize(self.vin.width, self.vin.height) - self.wid = -1 - self.reset() - - def close(self): - self.vin.close() - if self.wid > 0: - gl.winclose(self.wid) - - def rewind(self): - self.vin.rewind() - self.reset() - - def getinfo(self): - return self.vin.getinfo() - - # Internal - def reset(self): - if self.wid > 0: - gl.winset(self.wid) - gl.clear() - self.vin.initcolormap() - self.qindex = 0 - - def show(self): - if self.wid < 0: - gl.foreground() - gl.prefsize(self.vin.width, self.vin.height) - self.wid = gl.winopen(self.title) - gl.clear() - self.vin.initcolormap() - gl.winset(self.wid) - if self.qindex >= self.qsize: - self.vin.clear() - return - dt, d, cd = self.vin.getrandomframe(self.qindex) - self.vin.showframe(d, cd) - - def redraw(self, wid): - if wid == self.wid >= 0: - gl.winset(self.wid) - gl.reshapeviewport() - self.vin.clear() - self.show() - - def get(self): - if self.qindex >= self.qsize: - return None - if self.qindex > 0: - prevt, ds, cs = \ - self.vin.getrandomframeheader(self.qindex-1) - else: - prevt = 0 - t, data, cdata = self.vin.getrandomframe(self.qindex) - self.qindex = self.qindex + 1 - return t-prevt, data, cdata - - def backup(self): - if self.qindex == 0: - return 0 - self.qindex = self.qindex - 1 - return 1 - - def seek(self, i): - if not 0 <= i <= self.qsize: - return 0 - self.qindex = i - return 1 - - def tell(self): - return self.qindex - - def qsizes(self): - return self.qindex, self.qsize - self.qindex - - def qinfo(self): - return 0, self.qindex, self.qsize - - -class OutputViewer: - - def __init__(self, filename, title, qsize): - try: - self.vout = VFile.VoutFile(filename) - except (EOFError, VFile.Error): - raise IOError, 'bad video output file' - if not title: - title = os.path.split(filename)[1] - self.filename = filename - self.title = title - self.qsize = qsize - gl.foreground() - self.wid = -1 - self.reset() - - def close(self): - while self.queue: - self.flushq() - self.vout.close() - if self.wid > 0: - gl.winclose(self.wid) - - def rewind(self): - info = self.vout.getinfo() - self.vout.close() - self.vout = VFile.VoutFile(self.filename) - self.vout.setinfo(info) - self.reset() - - def getinfo(self): - return self.vout.getinfo() - - def setinfo(self, info): - if info == self.getinfo(): return # No change - self.vout.setinfo(info) - if self.wid > 0: - gl.winclose(self.wid) - self.wid = -1 - - # Internal - def reset(self): - if self.wid > 0: - gl.winset(self.wid) - gl.clear() - self.vout.initcolormap() - self.queue = [] - self.spares = [] - self.written = 0 - self.lastt = 0 - - # Internal - def flushq(self): - if self.written == 0: - self.vout.writeheader() - dt, d, cd = self.queue[0] - self.lastt = self.lastt + dt - self.vout.writeframe(self.lastt, d, cd) - del self.queue[0] - self.written = self.written + 1 - - def show(self): - if self.wid < 0: - gl.foreground() - gl.prefsize(self.vout.width, self.vout.height) - self.wid = gl.winopen(self.title) - gl.clear() - self.vout.initcolormap() - gl.winset(self.wid) - if not self.queue: - self.vout.clear() - return - dt, d, cd = self.queue[-1] - self.vout.showframe(d, cd) - - def redraw(self, wid): - if wid == self.wid >= 0: - gl.winset(self.wid) - gl.reshapeviewport() - self.vout.clear() - self.show() - - def backup(self): - if len(self.queue) < 1: return 0 - self.spares.insert(0, self.queue[-1]) - del self.queue[-1] - return 1 - - def forward(self): - if not self.spares: return 0 - self.queue.append(self.spares[0]) - del self.spares[0] - return 1 - - def put(self, item): - self.queue.append(item) - self.spares = [] - while len(self.queue) > self.qsize: - self.flushq() - - def seek(self, i): - i = i - self.written - if not 0 <= i <= len(self.queue) + len(self.spares): - return 0 - while i < len(self.queue): - if not self.backup(): - return 0 - while i > len(self.queue): - if not self.forward(): - return 0 - return 1 - - def trunc(self): - del self.spares[:] - - def tell(self): - return self.written + len(self.queue) - - def qsizes(self): - return len(self.queue), len(self.spares) - - def qinfo(self): - first = self.written - pos = first + len(self.queue) - last = pos + len(self.spares) - return first, pos, last - - -def test(): - import sys - a = InputViewer(sys.argv[1], '') - b = OutputViewer(sys.argv[2], '') - b.setinfo(a.getinfo()) - - while 1: - a.show() - data = a.get() - if data is None: - break - b.put(data) - b.show() - - while a.backup(): - data = a.get() - b.put(data) - b.show() - if a.backup(): a.show() - - while 1: - data = a.get() - if data is None: - break - b.put(data) - b.show() - a.show() - - b.close() diff --git a/Demo/sgi/video/Vinfo.py b/Demo/sgi/video/Vinfo.py deleted file mode 100755 index c4177dc842..0000000000 --- a/Demo/sgi/video/Vinfo.py +++ /dev/null @@ -1,174 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -# Print some info about a CMIF movie file - - -# Usage: -# -# Vinfo [-d] [-q] [-s] [-t] [file] ... - - -# Options: -# -# -d : print deltas between frames instead of frame times -# -q : quick: don't read the frames -# -s : don't print times (but do count frames and print the total) -# -t : terse (one line/file, implies -s) -# file ... : file(s) to inspect; default film.video - - -import sys -sys.path.append('/ufs/guido/src/video') -import VFile -import getopt -import string - - -# Global options - -short = 0 -quick = 0 -delta = 0 -terse = 0 -maxwidth = 10 - - -# Main program -- mostly command line parsing - -def main(): - global short, quick, delta, terse, maxwidth - try: - opts, args = getopt.getopt(sys.argv[1:], 'dqst') - except getopt.error, msg: - sys.stdout = sys.stderr - print msg - print 'usage: Vinfo [-d] [-q] [-s] [-t] [file] ...' - sys.exit(2) - for opt, arg in opts: - if opt == '-q': - quick = 1 - if opt == '-d': - delta = 1 - if opt == '-s': - short = 1 - if opt == '-t': - terse = short = 1 - if not args: - args = ['film.video'] - for filename in args: - maxwidth = max(maxwidth, len(filename)) - sts = 0 - for filename in args: - if process(filename): - sts = 1 - sys.exit(sts) - - -# Process one file - -def process(filename): - try: - vin = VFile.RandomVinFile(filename) - except IOError, msg: - sys.stderr.write(filename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(filename + ': EOF in video file\n') - return 1 - - if terse: - print string.ljust(filename, maxwidth), - kbytes = (VFile.getfilesize(filename) + 1023) / 1024 - print string.rjust(`kbytes`, 5) + 'K', - print ' ', string.ljust(`vin.version`, 5), - print string.ljust(vin.format, 8), - print string.rjust(`vin.width`, 4), - print string.rjust(`vin.height`, 4), - if type(vin.packfactor) == type(()): - xpf, ypf = vin.packfactor - s = string.rjust(`xpf`, 2) + ',' + \ - string.rjust(`ypf`, 2) - else: - s = string.rjust(`vin.packfactor`, 2) - if type(vin.packfactor) == type(0) and \ - vin.format not in ('rgb', 'jpeg') and \ - (vin.width/vin.packfactor) % 4 <> 0: - s = s + '! ' - else: - s = s + ' ' - print s, - sys.stdout.flush() - else: - vin.printinfo() - - if quick: - if terse: - print - vin.close() - return 0 - - try: - vin.readcache() - if not terse: - print '[Using cached index]' - except VFile.Error: - if not terse: - print '[Constructing index on the fly]' - - if not short: - if delta: - print 'Frame time deltas:', - else: - print 'Frame times:', - - n = 0 - t = 0 - told = 0 - datasize = 0 - while 1: - try: - t, ds, cs = vin.getnextframeheader() - vin.skipnextframedata(ds, cs) - except EOFError: - break - datasize = datasize + ds - if cs: datasize = datasize + cs - if not short: - if n%8 == 0: - sys.stdout.write('\n') - if delta: - sys.stdout.write('\t' + `t - told`) - told = t - else: - sys.stdout.write('\t' + `t`) - n = n+1 - - if not short: print - - if terse: - print string.rjust(`n`, 6), - if t: print string.rjust(`int(n*10000.0/t)*0.1`, 5), - print - else: - print 'Total', n, 'frames in', t*0.001, 'sec.', - if t: print '-- average', int(n*10000.0/t)*0.1, 'frames/sec', - print - print 'Total data', 0.1 * int(datasize / 102.4), 'Kbytes', - if t: - print '-- average', - print 0.1 * int(datasize / 0.1024 / t), 'Kbytes/sec', - print - - vin.close() - return 0 - - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/Vmkjpeg.py b/Demo/sgi/video/Vmkjpeg.py deleted file mode 100755 index 4e4c28ebf4..0000000000 --- a/Demo/sgi/video/Vmkjpeg.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/ufs/guido/bin/sgi/python - -# Compress an rgb or grey video file to jpeg format - - -# Usage: -# -# Vmkjpeg [infile [outfile]] - - -# Options: -# -# infile : input file (default film.video) -# outfile : output file (default out.video) - - -import sys -import jpeg -sys.path.append('/ufs/guido/src/video') -import VFile - - -# Main program -- mostly command line parsing - -def main(): - args = sys.argv[1:] - if len(args) < 1: - args.append('film.video') - if len(args) < 2: - args.append('out.video') - if len(args) > 2: - sys.stderr.write('usage: Vmkjpeg [infile [outfile]]\n') - sys.exit(2) - sts = process(args[0], args[1]) - sys.exit(sts) - - -# Copy one file to another - -def process(infilename, outfilename): - try: - vin = VFile.BasicVinFile(infilename) - except IOError, msg: - sys.stderr.write(infilename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(infilename + ': EOF in video file\n') - return 1 - - try: - vout = VFile.BasicVoutFile(outfilename) - except IOError, msg: - sys.stderr.write(outfilename + ': I/O error: ' + `msg` + '\n') - return 1 - - info = vin.getinfo() - if info[0] == 'rgb': - width, height = vin.getsize() - bytes = 4 - format = 'jpeg' - elif info[0] == 'grey': - width, height = vin.getsize() - pf = vin.packfactor - width, height = width / pf, height / pf - bytes = 1 - format = 'jpeggrey' - else: - sys.stderr.write('Vmkjpeg: input not in rgb or grey format\n') - return 1 - info = (format,) + info[1:] - vout.setinfo(info) - vout.writeheader() - n = 0 - try: - while 1: - t, data, cdata = vin.getnextframe() - n = n + 1 - sys.stderr.write('Frame ' + `n` + '...') - data = jpeg.compress(data, width, height, bytes) - vout.writeframe(t, data, None) - sys.stderr.write('\n') - except EOFError: - pass - return 0 - - -# Don't forget to call the main program - -main() diff --git a/Demo/sgi/video/Vplay.py b/Demo/sgi/video/Vplay.py deleted file mode 100755 index 79b3ad41d3..0000000000 --- a/Demo/sgi/video/Vplay.py +++ /dev/null @@ -1,355 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -# Play CMIF movie files - - -# Help function - -def help(): - print 'Usage: Vplay [options] [file] ...' - print - print 'Options:' - print '-M magnify : magnify the image by the given factor' - print '-d : write some debug stuff on stderr' - print '-l : loop, playing the movie over and over again' - print '-m delta : drop frames closer than delta seconds (default 0.)' - print '-n : don\'t wait after each file' - print '-q : quiet, no informative messages' - print '-r delta : regenerate input time base delta seconds apart' - print '-s speed : speed change factor (default 1.0)' - print '-t : use a 2nd thread for read-ahead' - print '-x left : window offset from left of screen' - print '-y top : window offset from top of screen' - print '-w width : window width' - print '-h height : window height' - print '-b color : background color (white,black or (r,g,b))' - print 'file ... : file(s) to play; default film.video' - print - print 'User interface:' - print 'Press the left mouse button to stop or restart the movie.' - print 'Press ESC or use the window manager Close or Quit command' - print 'to close the window and play the next file (if any).' - - -# Imported modules - -import sys -sys.path.append('/ufs/guido/src/video') # Increase chance of finding VFile -import VFile -import time -import gl, GL -from DEVICE import REDRAW, ESCKEY, LEFTMOUSE, WINSHUT, WINQUIT -import getopt -import string - - -# Global options - -debug = 0 -looping = 0 -magnify = 1 -mindelta = 0 -nowait = 0 -quiet = 0 -regen = None -speed = 1.0 -threading = 0 -xoff = yoff = None -xwsiz = ywsiz = None -bgcolor = None - - -# Main program -- mostly command line parsing - -def main(): - global debug, looping, magnify, mindelta, nowait, quiet, regen, speed - global threading, xoff, yoff, xwsiz, ywsiz, bgcolor - - # Parse command line - try: - opts, args = getopt.getopt(sys.argv[1:], \ - 'M:dlm:nqr:s:tx:y:w:h:b:') - except getopt.error, msg: - sys.stdout = sys.stderr - print 'Error:', msg, '\n' - help() - sys.exit(2) - - # Interpret options - try: - for opt, arg in opts: - if opt == '-M': magnify = float(eval(arg)) - if opt == '-d': debug = debug + 1 - if opt == '-l': looping = 1 - if opt == '-m': mindelta = float(eval(arg)) - if opt == '-n': nowait = 1 - if opt == '-q': quiet = 1 - if opt == '-r': regen = float(eval(arg)) - if opt == '-s': - try: - speed = float(eval(arg)) - except: - sys.stdout = sys.stderr - print 'Option -s needs float argument' - sys.exit(2) - if opt == '-t': - try: - import thread - threading = 1 - except ImportError: - print 'Sorry, this version of Python', - print 'does not support threads:', - print '-t ignored' - if opt == '-x': xoff = string.atoi(arg) - if opt == '-y': yoff = string.atoi(arg) - if opt == '-w': xwsiz = string.atoi(arg) - if opt == '-h': ywsiz = string.atoi(arg) - if opt == '-b': - if arg == 'black': - bgcolor = (0,0,0) - elif arg == 'white': - bgcolor = (255,255,255) - else: - try: - bgcolor = eval(arg) - xxr, xxg, xxb = bgcolor - except: - print '-b needs (r,g,b) tuple' - sys.exit(2) - except string.atoi_error: - sys.stdout = sys.stderr - print 'Option', opt, 'requires integer argument' - sys.exit(2) - - # Check validity of certain options combinations - if nowait and looping: - print 'Warning: -n and -l are mutually exclusive; -n ignored' - nowait = 0 - if xoff <> None and yoff == None: - print 'Warning: -x without -y ignored' - if xoff == None and yoff <> None: - print 'Warning: -y without -x ignored' - - # Process all files - if not args: args = ['film.video'] - sts = 0 - for filename in args: - sts = (process(filename) or sts) - - # Exit with proper exit status - sys.exit(sts) - - -# Process one movie file - -def process(filename): - try: - vin = VFile.VinFile(filename) - except IOError, msg: - sys.stderr.write(filename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(filename + ': EOF in video header\n') - return 1 - - if not quiet: - vin.printinfo() - - gl.foreground() - - width, height = int(vin.width * magnify), int(vin.height * magnify) - xborder = yborder = 0 - if xwsiz: - vin.xorigin = (xwsiz - width)/2 - width = xwsiz - if ywsiz: - vin.yorigin = (ywsiz - height)/2 - height = ywsiz - if xoff <> None and yoff <> None: - scrheight = gl.getgdesc(GL.GD_YPMAX) - gl.prefposition(xoff, xoff+width-1, \ - scrheight-yoff-height, scrheight-yoff-1) - else: - gl.prefsize(width, height) - - win = gl.winopen(filename) - gl.clear() - - if quiet: vin.quiet = 1 - vin.initcolormap() - - if bgcolor: - r, g, b = bgcolor - vin.clearto(r,g,b) - - gl.qdevice(ESCKEY) - gl.qdevice(WINSHUT) - gl.qdevice(WINQUIT) - gl.qdevice(LEFTMOUSE) - - stop = 0 - - while not stop: - gl.wintitle(filename) - stop = (playonce(vin) or nowait) - gl.wintitle('(done) ' + filename) - if not looping: - while not stop: - dev, val = gl.qread() - if dev == REDRAW: - if bgcolor: - r,g,b = bgcolor - vin.clearto(r,g,b) - else: - vin.clear() - if dev == LEFTMOUSE and val == 1: - break # Continue outer loop - if dev == ESCKEY and val == 1 or \ - dev in (WINSHUT, WINQUIT): - stop = 1 - - # Set xoff, yoff for the next window from the current window - global xoff, yoff - xoff, yoff = gl.getorigin() - width, height = gl.getsize() - scrheight = gl.getgdesc(GL.GD_YPMAX) - yoff = scrheight - yoff - height - gl.winclose(win) - - return 0 - - -# Play a movie once; return 1 if user wants to stop, 0 if not - -def playonce(vin): - vin.rewind() - vin.colormapinited = 1 - vin.magnify = magnify - - if threading: - MAXSIZE = 20 # Don't read ahead too much - import thread - import Queue - queue = Queue.Queue(MAXSIZE) - stop = [] - thread.start_new_thread(read_ahead, (vin, queue, stop)) - # Get the read-ahead thread going - while queue.qsize() < MAXSIZE/2 and not stop: - time.sleep(0.100) - - tin = 0 - toffset = 0 - oldtin = 0 - told = 0 - nin = 0 - nout = 0 - nlate = 0 - nskipped = 0 - data = None - - tlast = t0 = time.time() - - while 1: - if gl.qtest(): - dev, val = gl.qread() - if dev == ESCKEY and val == 1 or \ - dev in (WINSHUT, WINQUIT) or \ - dev == LEFTMOUSE and val == 1: - if debug: sys.stderr.write('\n') - if threading: - stop.append(None) - while 1: - item = queue.get() - if item == None: break - return (dev != LEFTMOUSE) - if dev == REDRAW: - gl.reshapeviewport() - if data: vin.showframe(data, cdata) - if threading: - if debug and queue.empty(): sys.stderr.write('.') - item = queue.get() - if item == None: break - tin, data, cdata = item - else: - try: - tin, size, csize = vin.getnextframeheader() - except EOFError: - break - tin = tin*0.001 - nin = nin+1 - if tin+toffset < oldtin: - print 'Fix reversed time:', oldtin, 'to', tin - toffset = oldtin - tin - tin = tin + toffset - oldtin = tin - if regen: tout = nin * regen - else: tout = tin - tout = tout / speed - if tout - told < mindelta: - nskipped = nskipped + 1 - if not threading: - vin.skipnextframedata(size, csize) - else: - if not threading: - try: - data, cdata = \ - vin.getnextframedata(size, csize) - except EOFError: - if not quiet: - print '[incomplete last frame]' - break - now = time.time() - dt = (tout-told) - (now-tlast) - told = tout - if debug: sys.stderr.write(`round(dt, 3)` + ' ') - if dt < 0: nlate = nlate + 1 - if dt > 0: - time.sleep(dt) - now = time.time() - tlast = now - vin.showframe(data, cdata) - nout = nout + 1 - - t1 = time.time() - - if debug: sys.stderr.write('\n') - - if quiet: return 0 - - print 'Recorded:', nin, 'frames in', round(tin, 3), 'sec.', - if tin: print '-- average', round(nin/tin, 1), 'frames/sec', - print - - if nskipped: print 'Skipped', nskipped, 'frames' - - tout = t1-t0 - print 'Played:', nout, - print 'frames in', round(tout, 3), 'sec.', - if tout: print '-- average', round(nout/tout, 1), 'frames/sec', - print - - if nlate: print 'There were', nlate, 'late frames' - - return 0 - - -# Read-ahead thread - -def read_ahead(vin, queue, stop): - try: - while not stop: queue.put(vin.getnextframe()) - except EOFError: - pass - queue.put(None) - stop.append(None) - - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/Vrec.py b/Demo/sgi/video/Vrec.py deleted file mode 100755 index 9d90a8073d..0000000000 --- a/Demo/sgi/video/Vrec.py +++ /dev/null @@ -1,413 +0,0 @@ -#! /ufs/guido/bin/sgi/python -#! /ufs/guido/bin/sgi/python-405 - -# Capture a CMIF movie using the Indigo video library and board - -# The CMIF video file format is documented in cmif-film.ms. -# Audio data is recorded in AIFF format, using the input sampling -# rate, source and volume set by the audio panel, in mono, 8 -# bits/sample. - - -# Usage and help functions (keep this up-to-date if you change the program!) - -def usage(): - print 'Usage: Vrec [options] [moviefile [audiofile]]' - print - print 'Options:' - print '-a : record audio as well' - print '-q queuesize : set the capture queue size (default 2)' - print '-r rate : capture 1 out of every "rate" frames', \ - '(default and min 2)' - print '-w width : initial window width', \ - '(default 256, use 0 for interactive placement)' - print '-n : Don\'t write to file, only timing info' - print '-d : drop fields if needed' - print '-g bits : greyscale (2, 4 or 8 bits)' - print '-G : 2-bit greyscale dithered' - print '-m : monochrome dithered' - print '-M value : monochrome tresholded with value' - print '-f : Capture fields (in stead of frames)' - print '-P frames : preallocate space for "frames" frames' - print 'moviefile : here goes the movie data (default film.video)' - print 'audiofile : with -a, here goes the audio data', \ - '(default film.aiff)' - -def help(): - print 'Press the left mouse button to start recording, release it to' - print 'end recording. You can record as many times as you wish, but' - print 'each recording overwrites the output file(s) -- only the last' - print 'recording is kept.' - print - print 'Press ESC or use the window manager Quit or Close window option' - print 'to quit. If you quit before recording anything, the output' - print 'file(s) are not touched.' - - -# Imported modules - -import sys -sys.path.append('/ufs/guido/src/video') -import sv, SV -import VFile -import gl, GL, DEVICE -import al, AL -import time -import posix -import getopt -import string -import imageop -import sgi - - -# Main program - -def main(): - format = SV.RGB8_FRAMES - qsize = 2 - audio = 0 - rate = 2 - width = 0 - norecord = 0 - drop = 0 - mono = 0 - grey = 0 - greybits = 0 - monotreshold = -1 - fields = 0 - preallocspace = 0 - - # Parse command line - try: - opts, args = getopt.getopt(sys.argv[1:], 'aq:r:w:ndg:mM:GfP:') - except getopt.error, msg: - sys.stdout = sys.stderr - print 'Error:', msg, '\n' - usage() - sys.exit(2) - - # Interpret options - try: - for opt, arg in opts: - if opt == '-a': - audio = 1 - elif opt == '-q': - qsize = string.atoi(arg) - elif opt == '-r': - rate = string.atoi(arg) - if rate < 2: - sys.stderr.write( \ - '-r rate must be >= 2\n') - sys.exit(2) - elif opt == '-w': - width = string.atoi(arg) - elif opt == '-n': - norecord = 1 - elif opt == '-d': - drop = 1 - elif opt == '-g': - grey = 1 - greybits = string.atoi(arg) - if not greybits in (2, 4, 8): - sys.stderr.write( \ - 'Only 2, 4 or 8 bit greyscale supported\n') - sys.exit(2) - elif opt == '-G': - grey = 1 - greybits = -2 - elif opt == '-m': - mono = 1 - elif opt == '-M': - mono = 1 - monotreshold = string.atoi(arg) - elif opt == '-f': - fields = 1 - elif opt == '-P': - preallocspace = string.atoi(arg) - except string.atoi_error: - sys.stdout = sys.stderr - print 'Option', opt, 'requires integer argument' - sys.exit(2) - - # Check excess arguments - # If norecord is on, refuse filename arguments - if norecord: - if args: - sys.stdout = sys.stderr - print 'With -n, no filename arguments are used\n' - usage() - sys.exit(2) - elif args[2:]: - sys.stdout = sys.stderr - print 'Too many filename arguments\n' - usage() - sys.exit(2) - - # Process file arguments - if args: - filename = args[0] - else: - filename = 'film.video' - - if args[1:] and not audio: - sys.stderr.write('-a turned on by appearance of 2nd file\n') - audio = 1 - - if audio: - if args[1:]: - audiofilename = args[1] - else: - audiofilename = 'film.aiff' - else: - audiofilename = None - - if norecord: - filename = audiofilename = '' - - # Open video - v = sv.OpenVideo() - # Determine maximum window size based on signal standard - param = [SV.BROADCAST, 0] - v.GetParam(param) - if param[1] == SV.PAL: - x = SV.PAL_XMAX - y = SV.PAL_YMAX - elif param[1] == SV.NTSC: - x = SV.NTSC_XMAX - y = SV.NTSC_YMAX - else: - print 'Unknown video standard', param[1] - sys.exit(1) - - gl.foreground() - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - if width: - height = width*3/4 - x1 = 150 - x2 = x1 + width-1 - y2 = 768-150 - y1 = y2-height+1 - gl.prefposition(x1, x2, y1, y2) - win = gl.winopen(filename) - if width: - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - gl.winconstraints() - x, y = gl.getsize() - print x, 'x', y - - v.SetSize(x, y) - - if drop: - param = [SV.FIELDDROP, 1, SV.GENLOCK, SV.GENLOCK_OFF] - else: - param = [SV.FIELDDROP, 0, SV.GENLOCK, SV.GENLOCK_ON] - if mono or grey: - param = param+[SV.COLOR, SV.MONO, SV.DITHER, 0, \ - SV.INPUT_BYPASS, 1] - else: - param = param+[SV.COLOR, SV.DEFAULT_COLOR, SV.INPUT_BYPASS, 0] - - v.BindGLWindow(win, SV.IN_REPLACE) - v.SetParam(param) - - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - - help() - - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE: - if val == 1: - info = format, x, y, qsize, rate - record(v, info, filename, audiofilename,\ - mono, grey, greybits, monotreshold, \ - fields, preallocspace) - elif dev == DEVICE.REDRAW: - # Window resize (or move) - x, y = gl.getsize() - print x, 'x', y - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - # Quit - v.CloseVideo() - gl.winclose(win) - break - - -# Record until the mouse is released (or any other GL event) -# XXX audio not yet supported - -def record(v, info, filename, audiofilename, mono, grey, greybits, \ - monotreshold, fields, preallocspace): - import thread - format, x, y, qsize, rate = info - fps = 59.64 # Fields per second - # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) - tpf = 1000.0 / fps # Time per field in msec - if filename: - vout = VFile.VoutFile(filename) - if mono: - format = 'mono' - elif grey and greybits == 8: - format = 'grey' - elif grey: - format = 'grey'+`abs(greybits)` - else: - format = 'rgb8' - vout.setformat(format) - vout.setsize(x, y) - if fields: - vout.setpf((1, -2)) - vout.writeheader() - if preallocspace: - print 'Preallocating space...' - vout.prealloc(preallocspace) - print 'done.' - MAXSIZE = 20 # XXX should be a user option - import Queue - queue = Queue.Queue(MAXSIZE) - done = thread.allocate_lock() - done.acquire_lock() - convertor = None - if grey: - if greybits == 2: - convertor = imageop.grey2grey2 - elif greybits == 4: - convertor = imageop.grey2grey4 - elif greybits == -2: - convertor = imageop.dither2grey2 - thread.start_new_thread(saveframes, \ - (vout, queue, done, mono, monotreshold, convertor)) - if audiofilename: - audiodone = thread.allocate_lock() - audiodone.acquire_lock() - audiostop = [] - initaudio(audiofilename, audiostop, audiodone) - gl.wintitle('(rec) ' + filename) - lastid = 0 - t0 = time.time() - count = 0 - ids = [] - v.InitContinuousCapture(info) - while not gl.qtest(): - try: - cd, id = v.GetCaptureData() - except sv.error: - #time.sleep(0.010) # XXX is this necessary? - sgi.nap(1) # XXX Try by Jack - continue - ids.append(id) - - id = id + 2*rate -## if id <> lastid + 2*rate: -## print lastid, id - lastid = id - count = count+1 - if fields: - data1, data2 = cd.GetFields() - cd.UnlockCaptureData() - if filename: - queue.put((data1, int(id*tpf))) - queue.put((data2, int((id+1)*tpf))) - else: - data = cd.InterleaveFields(1) - cd.UnlockCaptureData() - if filename: - queue.put((data, int(id*tpf))) - t1 = time.time() - gl.wintitle('(busy) ' + filename) - print lastid, 'fields in', round(t1-t0, 3), 'sec', - print '--', round(lastid/(t1-t0), 1), 'fields/sec' - print 'Captured',count*2, 'fields,', - print round(count*2/(t1-t0), 1), 'f/s', - if lastid: - print '(', - print round(count*200.0/lastid), '%, or', - print round(count*rate*200.0/lastid), '% of wanted rate )', - print - if ids: - print 'Ids:', - t0 = ids[0] - del ids[0] - for t1 in ids: - print t1-t0, - t0 = t1 - print - if filename and audiofilename: - audiostop.append(None) - audiodone.acquire_lock() - v.EndContinuousCapture() - if filename: - queue.put(None) # Sentinel - done.acquire_lock() - gl.wintitle('(done) ' + filename) - - -# Thread to save the frames to the file - -def saveframes(vout, queue, done, mono, monotreshold, convertor): - while 1: - x = queue.get() - if not x: - break - data, t = x - if convertor: - data = convertor(data, len(data), 1) - elif mono and monotreshold >= 0: - data = imageop.grey2mono(data, len(data), 1,\ - monotreshold) - elif mono: - data = imageop.dither2mono(data, len(data), 1) - vout.writeframe(t, data, None) - sys.stderr.write('Done writing video\n') - vout.close() - done.release_lock() - - -# Initialize audio recording - -AQSIZE = 8000 # XXX should be a user option - -def initaudio(filename, stop, done): - import thread, aifc - afile = aifc.open(filename, 'w') - afile.setnchannels(AL.MONO) - afile.setsampwidth(AL.SAMPLE_8) - params = [AL.INPUT_RATE, 0] - al.getparams(AL.DEFAULT_DEVICE, params) - print 'audio sampling rate =', params[1] - afile.setframerate(params[1]) - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(AQSIZE) - c.setwidth(AL.SAMPLE_8) - aport = al.openport(filename, 'r', c) - thread.start_new_thread(audiorecord, (afile, aport, stop, done)) - - -# Thread to record audio samples - -def audiorecord(afile, aport, stop, done): - while not stop: - data = aport.readsamps(AQSIZE/2) - afile.writesampsraw(data) - del data - afile.close() - print 'Done writing audio' - done.release_lock() - - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/Vrecb.py b/Demo/sgi/video/Vrecb.py deleted file mode 100755 index ca81753ae6..0000000000 --- a/Demo/sgi/video/Vrecb.py +++ /dev/null @@ -1,429 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -# Capture a CMIF movie using the Indigo video library and board in burst mode - - -# User interface: -# -# Start the application. Resize the window to the desired movie size. -# Press the left mouse button to start recording, release it to end -# recording. You can record as many times as you wish, but each time -# you overwrite the output file(s), so only the last recording is -# kept. -# -# Press ESC or select the window manager Quit or Close window option -# to quit. If you quit before recording anything, the output file(s) -# are not touched. - - -import sys -sys.path.append('/ufs/guido/src/video') -import sv, SV -import VFile -import gl, GL, DEVICE -import al, AL -import time -import posix -import getopt -import string -import imageop -import sgi - - -# Usage and help functions (keep this up-to-date if you change the program!) - -def usage(): - print 'Usage: Vrecb [options] [moviefile [audiofile]]' - print - print 'Options:' - print '-a : record audio as well' - print '-r rate : capture 1 out of every "rate" frames', \ - '(default and min 1)' - print '-w width : initial window width', \ - '(default 256, use 0 for interactive placement)' - print '-d : drop fields if needed' - print '-g bits : greyscale (2, 4 or 8 bits)' - print '-G : 2-bit greyscale dithered' - print '-m : monochrome dithered' - print '-M value : monochrome tresholded with value' - print '-f : Capture fields (instead of frames)' - print '-n number : Capture this many frames (default 60)' - print '-N memsize : Capture frames fitting in this many kbytes' - print 'moviefile : here goes the movie data (default film.video)' - -def help(): - print 'Press the left mouse button to start recording.' - print 'Recording time is determined by the -n option.' - print 'You can record as many times as you wish, but each' - print 'recording overwrites the output file(s) -- only the' - print 'last recording is kept.' - print - print 'Press ESC or use the window manager Quit or Close window option' - print 'to quit. If you quit before recording anything, the output' - print 'file(s) are not touched.' - - -# Main program - -def main(): - format = SV.RGB8_FRAMES - audio = 0 - rate = 1 - width = 256 - drop = 0 - mono = 0 - grey = 0 - greybits = 0 - monotreshold = -1 - fields = 0 - number = 0 - memsize = 0 - - try: - opts, args = getopt.getopt(sys.argv[1:], 'ar:w:dg:mM:Gfn:N:') - except getopt.error, msg: - sys.stdout = sys.stderr - print 'Error:', msg, '\n' - usage() - sys.exit(2) - - try: - for opt, arg in opts: - if opt == '-a': - audio = 1 - if opt == '-r': - rate = string.atoi(arg) - if rate < 1: - sys.stderr.write('-r rate must be >= 1\n') - sys.exit(2) - elif opt == '-w': - width = string.atoi(arg) - elif opt == '-d': - drop = 1 - elif opt == '-g': - grey = 1 - greybits = string.atoi(arg) - if not greybits in (2,4,8): - sys.stderr.write( \ - 'Only 2, 4 or 8 bit greyscale supported\n') - sys.exit(2) - elif opt == '-G': - grey = 1 - greybits = -2 - elif opt == '-m': - mono = 1 - elif opt == '-M': - mono = 1 - monotreshold = string.atoi(arg) - elif opt == '-f': - fields = 1 - elif opt == '-n': - number = string.atoi(arg) - elif opt == '-N': - memsize = string.atoi(arg) - if 0 < memsize < 1024: - memsize = memsize * 1024 - if 0 < memsize < 1024*1024: - memsize = memsize * 1024 - print 'memsize', memsize - except string.atoi_error: - sys.stdout = sys.stderr - print 'Option', opt, 'requires integer argument' - sys.exit(2) - - if number <> 0 and memsize <> 0: - sys.stderr.write('-n and -N are mutually exclusive\n') - sys.exit(2) - if number == 0 and memsize == 0: - number = 60 - - if not fields: - print '-f option assumed until somebody fixes it' - fields = 1 - - if args[2:]: - sys.stderr.write('usage: Vrecb [options] [file [audiofile]]\n') - sys.exit(2) - - if args: - filename = args[0] - else: - filename = 'film.video' - - if args[1:] and not audio: - sys.stderr.write('-a turned on by appearance of 2nd file\n') - audio = 1 - - if audio: - if args[1:]: - audiofilename = args[1] - else: - audiofilename = 'film.aiff' - else: - audiofilename = None - - v = sv.OpenVideo() - # Determine maximum window size based on signal standard - param = [SV.BROADCAST, 0] - v.GetParam(param) - if param[1] == SV.PAL: - x = SV.PAL_XMAX - y = SV.PAL_YMAX - elif param[1] == SV.NTSC: - x = SV.NTSC_XMAX - y = SV.NTSC_YMAX - else: - print 'Unknown video standard', param[1] - sys.exit(1) - - gl.foreground() - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - if width: - height = width*3/4 - x1 = 150 - x2 = x1 + width-1 - y2 = 768-150 - y1 = y2-height+1 - gl.prefposition(x1, x2, y1, y2) - win = gl.winopen(filename) - if width: - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - gl.winconstraints() - x, y = gl.getsize() - print x, 'x', y - if memsize: - number = calcnumber(x, y, grey or mono, memsize) - print number, 'frames' - v.SetSize(x, y) - - if drop: - param = [SV.FIELDDROP, 1, SV.GENLOCK, SV.GENLOCK_OFF] - else: - param = [SV.FIELDDROP, 0, SV.GENLOCK, SV.GENLOCK_ON] - if mono or grey: - param = param+[SV.COLOR, SV.MONO, SV.DITHER, 0, \ - SV.INPUT_BYPASS, 1] - else: - param = param+[SV.COLOR, SV.DEFAULT_COLOR, SV.INPUT_BYPASS, 0] - - v.BindGLWindow(win, SV.IN_REPLACE) - v.SetParam(param) - - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - - help() - - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE: - if val == 1: - info = format, x, y, number, rate - record(v, info, filename, audiofilename, \ - mono, grey, \ - greybits, monotreshold, fields) - elif dev == DEVICE.REDRAW: - # Window resize (or move) - x, y = gl.getsize() - print x, 'x', y - if memsize: - number = calcnumber(x, y, grey or mono, memsize) - print number, 'frames' - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - # Quit - v.CloseVideo() - gl.winclose(win) - break - - -def calcnumber(x, y, grey, memsize): - pixels = x*y - pixels = pixels/2 # XXX always assume fields - if grey: n = memsize/pixels - else: n = memsize/(4*pixels) - return max(1, n) - - -# Record until the mouse is released (or any other GL event) -# XXX audio not yet supported - -def record(v, info, filename, audiofilename, \ - mono, grey, greybits, monotreshold, fields): - import thread - format, x, y, number, rate = info - fps = 59.64 # Fields per second - # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) - tpf = 1000.0 / fps # Time per field in msec - # - # Go grab - # - if audiofilename: - gl.wintitle('(start audio) ' + filename) - audiodone = thread.allocate_lock() - audiodone.acquire_lock() - audiostart = thread.allocate_lock() - audiostart.acquire_lock() - audiostop = [] - initaudio(audiofilename, audiostop, audiostart, audiodone) - audiostart.acquire_lock() - gl.wintitle('(rec) ' + filename) - try: - ninfo, data, bitvec = v.CaptureBurst(info) - except sv.error, arg: - print 'CaptureBurst failed:', arg - print 'info:', info - gl.wintitle(filename) - return - gl.wintitle('(save) '+ filename) - # - # Check results - # - if info <> ninfo: - print 'Sorry, format changed.' - print 'Wanted:',info - print 'Got :',ninfo - gl.wintitle(filename) - return - # print bitvec - if x*y*number <> len(data): - print 'Funny data length: wanted',x,'*',y,'*', number,'=',\ - x*y*number,'got',len(data) - gl.wintitle(filename) - return - # - # Save - # - if filename and audiofilename: - audiostop.append(None) - audiodone.acquire_lock() - if filename: - # - # Construct header and write it - # - try: - vout = VFile.VoutFile(filename) - except IOError, msg: - print filename, ':', msg - sys.exit(1) - if mono: - vout.format = 'mono' - elif grey and greybits == 8: - vout.format = 'grey' - elif grey: - vout.format = 'grey'+`abs(greybits)` - else: - vout.format = 'rgb8' - vout.width = x - vout.height = y - if fields: - vout.packfactor = (1,-2) - else: - print 'Sorry, can only save fields at the moment' - print '(i.e. you *must* use the -f option)' - gl.wintitle(filename) - return - vout.writeheader() - # - # Compute convertor, if needed - # - convertor = None - if grey: - if greybits == 2: - convertor = imageop.grey2grey2 - elif greybits == 4: - convertor = imageop.grey2grey4 - elif greybits == -2: - convertor = imageop.dither2grey2 - fieldsize = x*y/2 - nskipped = 0 - realframeno = 0 - tpf = 1000 / 50.0 #XXXX - # Trying to find the pattern in frame skipping - okstretch = 0 - skipstretch = 0 - for frameno in range(0, number*2): - if frameno <> 0 and \ - bitvec[frameno] == bitvec[frameno-1]: - nskipped = nskipped + 1 - if okstretch: - print okstretch, 'ok', - okstretch = 0 - skipstretch = skipstretch + 1 - continue - if skipstretch: - print skipstretch, 'skipped' - skipstretch = 0 - okstretch = okstretch + 1 - # - # Save field. - # XXXX Works only for fields and top-to-bottom - # - start = frameno*fieldsize - field = data[start:start+fieldsize] - if convertor: - field = convertor(field, len(field), 1) - elif mono and monotreshold >= 0: - field = imageop.grey2mono( \ - field, len(field), 1, monotreshold) - elif mono: - field = imageop.dither2mono( \ - field, len(field), 1) - realframeno = realframeno + 1 - vout.writeframe(int(realframeno*tpf), field, None) - print okstretch, 'ok', - print skipstretch, 'skipped' - print 'Skipped', nskipped, 'duplicate frames' - vout.close() - - gl.wintitle('(done) ' + filename) -# Initialize audio recording - -AQSIZE = 8*8000 # XXX should be a user option - -def initaudio(filename, stop, start, done): - import thread, aifc - afile = aifc.open(filename, 'w') - afile.setnchannels(AL.MONO) - afile.setsampwidth(AL.SAMPLE_8) - params = [AL.INPUT_RATE, 0] - al.getparams(AL.DEFAULT_DEVICE, params) - print 'audio sampling rate =', params[1] - afile.setframerate(params[1]) - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(AQSIZE) - c.setwidth(AL.SAMPLE_8) - aport = al.openport(filename, 'r', c) - thread.start_new_thread(audiorecord, (afile, aport, stop, start, done)) - - -# Thread to record audio samples - -def audiorecord(afile, aport, stop, start, done): - start.release_lock() - leeway = 4 - while leeway > 0: - if stop: - leeway = leeway - 1 - data = aport.readsamps(AQSIZE/8) - afile.writesampsraw(data) - del data - afile.close() - print 'Done writing audio' - done.release_lock() - - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/Vrecc.py b/Demo/sgi/video/Vrecc.py deleted file mode 100755 index 6a539f8192..0000000000 --- a/Demo/sgi/video/Vrecc.py +++ /dev/null @@ -1,281 +0,0 @@ -#! /ufs/guido/bin/sgi/python-405 -#! /ufs/guido/bin/sgi/python - -# Capture a continuous CMIF movie using the Indigo video library and board - - -# Usage: -# -# makemovie [-r rate] [-w width] [moviefile] - - -# Options: -# -# -r rate : capture 1 out of every 'rate' frames (default 1) -# -w width : initial window width (default interactive placement) -# -d : drop fields if needed -# -g bits : greyscale (2, 4 or 8 bits) -# -G : 2-bit greyscale dithered -# -m : monochrome dithered -# -M value : monochrome tresholded with value -# -f : Capture fields (in stead of frames) -# -n number : Capture 'number' fields (default 60) -# -# moviefile : here goes the movie data (default film.video); -# the format is documented in cmif-film.ms - - -# User interface: -# -# Start the application. Resize the window to the desired movie size. -# Press the left mouse button to start recording, release it to end -# recording. You can record as many times as you wish, but each time -# you overwrite the output file(s), so only the last recording is -# kept. -# -# Press ESC or select the window manager Quit or Close window option -# to quit. If you quit before recording anything, the output file(s) -# are not touched. - - -import sys -sys.path.append('/ufs/guido/src/video') -import sv, SV -import VFile -import gl, GL, DEVICE -import al, AL -import time -import posix -import getopt -import string -import imageop -import sgi - -# Main program - -def main(): - format = SV.RGB8_FRAMES - rate = 1 - width = 0 - drop = 0 - mono = 0 - grey = 0 - greybits = 0 - monotreshold = -1 - fields = 0 - number = 60 - - opts, args = getopt.getopt(sys.argv[1:], 'r:w:dg:mM:Gfn:') - for opt, arg in opts: - if opt == '-r': - rate = string.atoi(arg) - if rate < 2: - sys.stderr.write('-r rate must be >= 2\n') - sys.exit(2) - elif opt == '-w': - width = string.atoi(arg) - elif opt == '-d': - drop = 1 - elif opt == '-g': - grey = 1 - greybits = string.atoi(arg) - if not greybits in (2,4,8): - print 'Only 2, 4 or 8 bit greyscale supported' - elif opt == '-G': - grey = 1 - greybits = -2 - elif opt == '-m': - mono = 1 - elif opt == '-M': - mono = 1 - monotreshold = string.atoi(arg) - elif opt == '-f': - fields = 1 - elif opt == '-n': - number = string.atoi(arg) - - if args[2:]: - sys.stderr.write('usage: Vrec [options] [file]\n') - sys.exit(2) - - if args: - filename = args[0] - else: - filename = 'film.video' - - v = sv.OpenVideo() - # Determine maximum window size based on signal standard - param = [SV.BROADCAST, 0] - v.GetParam(param) - if param[1] == SV.PAL: - x = SV.PAL_XMAX - y = SV.PAL_YMAX - elif param[1] == SV.NTSC: - x = SV.NTSC_XMAX - y = SV.NTSC_YMAX - else: - print 'Unknown video standard', param[1] - sys.exit(1) - - gl.foreground() - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - if width: - gl.prefsize(width, width*3/4) - win = gl.winopen(filename) - if width: - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - gl.winconstraints() - x, y = gl.getsize() - print x, 'x', y - - v.SetSize(x, y) - - if drop: - param = [SV.FIELDDROP, 1, SV.GENLOCK, SV.GENLOCK_OFF] - else: - param = [SV.FIELDDROP, 0, SV.GENLOCK, SV.GENLOCK_ON] - if mono or grey: - param = param+[SV.COLOR, SV.MONO, SV.INPUT_BYPASS, 1] - else: - param = param+[SV.COLOR, SV.DEFAULT_COLOR, SV.INPUT_BYPASS, 0] - v.SetParam(param) - - v.BindGLWindow(win, SV.IN_REPLACE) - - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - - print 'Press left mouse to start recording' - - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE: - if val == 1: - info = format, x, y, number, rate - record(v, info, filename, mono, grey, \ - greybits, monotreshold, fields) - elif dev == DEVICE.REDRAW: - # Window resize (or move) - x, y = gl.getsize() - print x, 'x', y - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - # Quit - v.CloseVideo() - gl.winclose(win) - break - - -# Record until the mouse is released (or any other GL event) -# XXX audio not yet supported - -def record(v, info, filename, mono, grey, greybits, monotreshold, fields): - import thread - format, x, y, number, rate = info - fps = 59.64 # Fields per second - # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) - tpf = 1000.0 / fps # Time per field in msec - # - # Go grab - # - gl.wintitle('(rec) ' + filename) - try: - ninfo, data, bitvec = v.CaptureBurst(info) - except sv.error, arg: - print 'CaptureBurst failed:', arg - print 'info:', info - gl.wintitle(filename) - return - gl.wintitle('(save) '+ filename) - # - # Check results - # - if info <> ninfo: - print 'Sorry, format changed.' - print 'Wanted:',info - print 'Got :',ninfo - gl.wintitle(filename) - return - # print bitvec - if x*y*number <> len(data): - print 'Funny data length: wanted',x,'*',y,'*', number,'=',\ - x*y*number,'got',len(data) - gl.wintitle(filename) - return - # - # Save - # - if filename: - # - # Construct header and write it - # - vout = VFile.VoutFile().init(filename) - if mono: - vout.format = 'mono' - elif grey and greybits == 8: - vout.format = 'grey' - elif grey: - vout.format = 'grey'+`abs(greybits)` - else: - vout.format = 'rgb8' - vout.width = x - vout.height = y - if fields: - vout.packfactor = (1,-2) - else: - print 'Sorry, can only save fields at the moment' - gl.wintitle(filename) - return - vout.writeheader() - # - # Compute convertor, if needed - # - convertor = None - if grey: - if greybits == 2: - convertor = imageop.grey2grey2 - elif greybits == 4: - convertor = imageop.grey2grey4 - elif greybits == -2: - convertor = imageop.dither2grey2 - fieldsize = x*y/2 - nskipped = 0 - realframeno = 0 - tpf = 1000 / 50.0 #XXXX - for frameno in range(0, number*2): - if frameno <> 0 and \ - bitvec[frameno] == bitvec[frameno-1]: - nskipped = nskipped + 1 - continue - # - # Save field. - # XXXX Works only for fields and top-to-bottom - # - start = frameno*fieldsize - field = data[start:start+fieldsize] - if convertor: - field = convertor(field, x, y) - elif mono and monotreshold >= 0: - field = imageop.grey2mono(field, x, y, \ - 1, monotreshold) - elif mono: - field = imageop.dither2mono(field, x, y) - vout.writeframe(int(realframeno*tpf), field, None) - print 'Skipped',nskipped,'duplicate frames' - vout.close() - - gl.wintitle('(done) ' + filename) - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/Vreceive.py b/Demo/sgi/video/Vreceive.py deleted file mode 100755 index f72c6a5920..0000000000 --- a/Demo/sgi/video/Vreceive.py +++ /dev/null @@ -1,135 +0,0 @@ -#!/ufs/guido/bin/sgi/python - -# Receive live video UDP packets. -# Usage: Vreceive [port] - -import sys -import struct -from socket import * # syscalls and support functions -from SOCKET import * # -from IN import * # -import select -import struct -import gl, GL, DEVICE -sys.path.append('/ufs/guido/src/video') -import LiveVideoOut -import regsub -import getopt - -from senddefs import * - - -# Print usage message and exit(2). - -def usage(msg): - print msg - print 'usage: Vreceive [-m mcastgrp] [-p port] [-c type]' - print '-m mcastgrp: multicast group (default ' + `DEFMCAST` + ')' - print '-p port : port (default ' + `DEFPORT` + ')' - print '-c type : signal type: rgb8, grey or mono (default rgb8)' - sys.exit(2) - - -# Main program: parse options and main loop. - -def main(): - - sys.stdout = sys.stderr - - group = DEFMCAST - port = DEFPORT - width = DEFWIDTH - height = DEFHEIGHT - vtype = 'rgb8' - - try: - opts, args = getopt.getopt(sys.argv[1:], 'm:p:c:') - except getopt.error, msg: - usage(msg) - - try: - for opt, optarg in opts: - if opt == '-p': - port = string.atoi(optarg) - if opt == '-m': - group = gethostbyname(optarg) - if opt == '-c': - vtype = optarg - except string.atoi_error, msg: - usage('bad integer: ' + msg) - - s = opensocket(group, port) - - gl.foreground() - gl.prefsize(width, height) - wid = gl.winopen('Vreceive') - gl.winconstraints() - gl.qdevice(DEVICE.ESCKEY) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.WINQUIT) - - lvo = LiveVideoOut.LiveVideoOut(wid, width, height, vtype) - - ifdlist = [gl.qgetfd(), s.fileno()] - ofdlist = [] - xfdlist = [] - timeout = 1.0 - selectargs = (ifdlist, ofdlist, xfdlist, timeout) - - while 1: - - if gl.qtest(): - dev, val = gl.qread() - if dev in (DEVICE.ESCKEY, \ - DEVICE.WINSHUT, DEVICE.WINQUIT): - break - if dev == DEVICE.REDRAW: - lvo.reshapewindow() - elif s.avail(): - data = s.recv(16*1024) - pos, w, h = struct.unpack('hhh', data[:6]) - if (w, h) <> (width, height): - x, y = gl.getorigin() - y = y + height - h - gl.winposition(x, x+w-1, y, y+h-1) - width, height = w, h - lvo.resizevideo(width, height) - lvo.putnextpacket(pos, data[6:]) - else: - x = select.select(selectargs) - - lvo.close() - - -# Subroutine to create and properly initialize the receiving socket - -def opensocket(group, port): - - # Create the socket - s = socket(AF_INET, SOCK_DGRAM) - - # Allow multiple copies of this program on one machine - s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1) # (Not strictly needed) - - # Bind the port to it - s.bind('', port) - - # Look up the group once - group = gethostbyname(group) - - # Construct binary group address - group_bytes = eval(regsub.gsub('\.', ',', group)) - grpaddr = 0 - for byte in group_bytes: grpaddr = (grpaddr << 8) | byte - - # Construct struct mreq from grpaddr and ifaddr - ifaddr = INADDR_ANY - mreq = struct.pack('ll', grpaddr, ifaddr) - - # Add group membership - s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) - - return s - - -main() diff --git a/Demo/sgi/video/Vsend.py b/Demo/sgi/video/Vsend.py deleted file mode 100755 index 223bbf302b..0000000000 --- a/Demo/sgi/video/Vsend.py +++ /dev/null @@ -1,152 +0,0 @@ -#!/ufs/guido/bin/sgi/python - -# Send live video UDP packets. -# Usage: Vsend [-b] [-h height] [-p port] [-s size] [-t ttl] [-w width] -# [host] .. - -import sys -import time -import struct -import string -from socket import * -from SOCKET import * -import gl, GL, DEVICE -sys.path.append('/ufs/guido/src/video') -import LiveVideoIn -import LiveVideoOut -import SV -import getopt -from IN import * - -from senddefs import * - -def usage(msg): - print msg - print 'usage: Vsend [-b] [-h height] [-p port] [-s size] [-t ttl] [-c type] [-m]', - print '[-w width] [host] ...' - print '-b : broadcast on local net' - print '-h height : window height (default ' + `DEFHEIGHT` + ')' - print '-p port : port to use (default ' + `DEFPORT` + ')' - print '-t ttl : time-to-live (multicast only; default 1)' - print '-s size : max packet size (default ' + `DEFPKTMAX` + ')' - print '-w width : window width (default ' + `DEFWIDTH` + ')' - print '-c type : Type: rgb8, mono or grey (default rgb8)' - print '[host] ...: host(s) to send to (default multicast to ' + \ - DEFMCAST + ')' - sys.exit(2) - - -def main(): - sys.stdout = sys.stderr - - hosts = [] - port = DEFPORT - ttl = -1 - pktmax = DEFPKTMAX - width = DEFWIDTH - height = DEFHEIGHT - vtype = 'rgb8' - - try: - opts, args = getopt.getopt(sys.argv[1:], 'bh:p:s:t:w:c:') - except getopt.error, msg: - usage(msg) - - try: - for opt, optarg in opts: - if opt == '-p': - port = string.atoi(optarg) - if opt == '-b': - host = '' - if opt == '-t': - ttl = string.atoi(optarg) - if opt == '-s': - pktmax = string.atoi(optarg) - if opt == '-w': - width = string.atoi(optarg) - if opt == '-h': - height = string.atoi(optarg) - if opt == '-c': - vtype = optarg - except string.atoi_error, msg: - usage('bad integer: ' + msg) - - for host in args: - hosts.append(gethostbyname(host)) - - if not hosts: - hosts.append(gethostbyname(DEFMCAST)) - - if not LiveVideoIn.have_video: - print 'Sorry, no video available (use python-405)' - sys.exit(1) - - gl.foreground() - gl.prefsize(width, height) - gl.stepunit(8, 6) - wid = gl.winopen('Vsend') - gl.keepaspect(width, height) - gl.stepunit(8, 6) - gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) - gl.winconstraints() - gl.qdevice(DEVICE.ESCKEY) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINFREEZE) - gl.qdevice(DEVICE.WINTHAW) - width, height = gl.getsize() - - lvo = LiveVideoOut.LiveVideoOut(wid, width, height, vtype) - - lvi = LiveVideoIn.LiveVideoIn(pktmax, width, height, vtype) - - s = socket(AF_INET, SOCK_DGRAM) - s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) - if ttl >= 0: - s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, chr(ttl)) - - frozen = 0 - - while 1: - - if gl.qtest(): - dev, val = gl.qread() - if dev in (DEVICE.ESCKEY, \ - DEVICE.WINSHUT, DEVICE.WINQUIT): - break - if dev == DEVICE.WINFREEZE: - frozen = 1 - if dev == DEVICE.WINTHAW: - frozen = 0 - if dev == DEVICE.REDRAW: - w, h = gl.getsize() - x, y = gl.getorigin() - if (w, h) <> (width, height): - width, height = w, h - lvi.resizevideo(width, height) - lvo.resizevideo(width, height) - - rv = lvi.getnextpacket() - if not rv: - time.sleep(0.010) - continue - - pos, data = rv - - if not frozen: - lvo.putnextpacket(pos, data) - - hdr = struct.pack('hhh', pos, width, height) - for host in hosts: - try: - s.sendto(hdr + data, (host, port)) - except error, msg: # really socket.error - if msg[0] <> 121: # no buffer space available - raise error, msg # re-raise it - print 'Warning:', msg[1] - - lvi.close() - lvo.close() - - -main() diff --git a/Demo/sgi/video/Vstat.py b/Demo/sgi/video/Vstat.py deleted file mode 100755 index cc0ecfb54a..0000000000 --- a/Demo/sgi/video/Vstat.py +++ /dev/null @@ -1,23 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -# Print the value of all video parameters - -import sys -import sv, SV - -def main(): - v = sv.OpenVideo() - for name in dir(SV): - const = getattr(SV, name) - if type(const) is type(0): - sys.stdout.flush() - params = [const, 0] - try: - v.GetParam(params) - except sv.error, msg: -## print name, msg - continue - print name, params - -main() - diff --git a/Demo/sgi/video/Vtime.py b/Demo/sgi/video/Vtime.py deleted file mode 100755 index be161ccb67..0000000000 --- a/Demo/sgi/video/Vtime.py +++ /dev/null @@ -1,117 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -# Manipulate the time base of CMIF movies - - -# Possibilities: -# -# - resample at a fixed rate -# - divide the time codes by a speed factor (to make it go faster/slower) -# - drop frames that are less than n msec apart (to accomodate slow players) - - -# Usage: -# -# Vtime [-m msec] [-r msec] [-s speed] [infile [outfile]] - - -# Options: -# -# -m n : drop frames closer than n msec (default 0) -# -r n : regenerate input time base n msec apart -# -s speed : speed change factor after other processing (default 1.0) -# infile : input file (default film.video) -# outfile : output file (default out.video) - - -import sys -sys.path.append('/ufs/guido/src/video') -import VFile -import getopt -import string - - -# Global options - -speed = 1.0 -mindelta = 0 -regen = None - - -# Main program -- mostly command line parsing - -def main(): - global speed, mindelta - opts, args = getopt.getopt(sys.argv[1:], 'm:r:s:') - for opt, arg in opts: - if opt == '-m': - mindelta = string.atoi(arg) - elif opt == '-r': - regen = string.atoi(arg) - elif opt == '-s': - speed = float(eval(arg)) - if len(args) < 1: - args.append('film.video') - if len(args) < 2: - args.append('out.video') - if len(args) > 2: - sys.stderr.write('usage: Vtime [options] [infile [outfile]]\n') - sys.exit(2) - sts = process(args[0], args[1]) - sys.exit(sts) - - -# Copy one file to another - -def process(infilename, outfilename): - try: - vin = VFile.BasicVinFile(infilename) - except IOError, msg: - sys.stderr.write(infilename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(infilename + ': EOF in video file\n') - return 1 - - try: - vout = VFile.BasicVoutFile(outfilename) - except IOError, msg: - sys.stderr.write(outfilename + ': I/O error: ' + `msg` + '\n') - return 1 - - vout.setinfo(vin.getinfo()) - vout.writeheader() - - told = 0 - nin = 0 - nout = 0 - tin = 0 - tout = 0 - - while 1: - try: - tin, data, cdata = vin.getnextframe() - except EOFError: - break - nin = nin + 1 - if regen: - tout = nin * regen - else: - tout = tin - tout = int(tout / speed) - if tout - told < mindelta: - continue - told = tout - vout.writeframe(tout, data, cdata) - nout = nout + 1 - - vout.close() - vin.close() - - -# Don't forget to call the main program - -main() diff --git a/Demo/sgi/video/Vunjpeg.py b/Demo/sgi/video/Vunjpeg.py deleted file mode 100755 index 9f21f959ff..0000000000 --- a/Demo/sgi/video/Vunjpeg.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/ufs/guido/bin/sgi/python - -# Decompress a jpeg or jpeggrey video file to rgb format - - -# Usage: -# -# Vunjpeg [infile [outfile]] - - -# Options: -# -# infile : input file (default film.video) -# outfile : output file (default out.video) - - -import sys -import jpeg -sys.path.append('/ufs/guido/src/video') -import VFile - - -# Main program -- mostly command line parsing - -def main(): - args = sys.argv[1:] - if len(args) < 1: - args.append('film.video') - if len(args) < 2: - args.append('out.video') - if len(args) > 2: - sys.stderr.write('usage: Vunjpeg [infile [outfile]]\n') - sys.exit(2) - sts = process(args[0], args[1]) - sys.exit(sts) - - -# Copy one file to another - -def process(infilename, outfilename): - try: - vin = VFile.BasicVinFile(infilename) - except IOError, msg: - sys.stderr.write(infilename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(infilename + ': EOF in video file\n') - return 1 - - try: - vout = VFile.BasicVoutFile(outfilename) - except IOError, msg: - sys.stderr.write(outfilename + ': I/O error: ' + `msg` + '\n') - return 1 - - info = vin.getinfo() - if info[0] == 'jpeg': - format = 'rgb' - width, height = vin.getsize() - bytes = 4 - elif info[0] == 'jpeggrey': - format = 'grey' - width, height = vin.getsize() - pf = vin.packfactor - width, height = width/pf, height/pf - bytes = 1 - else: - sys.stderr.write('Vunjpeg: input not in jpeg[grey] format\n') - return 1 - info = (format,) + info[1:] - vout.setinfo(info) - vout.writeheader() - sts = 0 - n = 0 - try: - while 1: - t, data, cdata = vin.getnextframe() - n = n + 1 - sys.stderr.write('Frame ' + `n` + '...') - data, w, h, b = jpeg.decompress(data) - if (w, h, b) <> (width, height, bytes): - sys.stderr.write('jpeg data has wrong size\n') - sts = 1 - else: - vout.writeframe(t, data, None) - sys.stderr.write('\n') - except EOFError: - pass - return sts - - -# Don't forget to call the main program - -main() diff --git a/Demo/sgi/video/aplay.py b/Demo/sgi/video/aplay.py deleted file mode 100755 index 7b1002722c..0000000000 --- a/Demo/sgi/video/aplay.py +++ /dev/null @@ -1,167 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -# Play synchronous video and audio. -# Highly experimental! - -import sys -import getopt -import string -import os - -import VFile -import aifc - -import gl, GL, DEVICE -import al, AL - - -def usage(): - sys.stderr.write( \ - 'usage: aplay [-o offset] [-q qsize] videofile audiofile\n') - sys.exit(2) - -def main(): - offset = 0 - qsize = 0 # This defaults to 1/10 second of sound - videofile = 'film.video' - audiofile = 'film.aiff' - - try: - opts, args = getopt.getopt(sys.argv[1:], 'o:q:') - except getopt.error, msg: - sys.stderr.write(msg + '\n') - usage() - - try: - for o, a in opts: - if o == '-o': - offset = string.atoi(a) - if o == '-q': - qsize = string.atoi(a) - except string.atoi_error: - sys.stderr.write(o + ' arg must be integer\n') - usage() - - if len(args) > 2: - usage() - - if args: videofile = args[0] - if args[1:]: audiofile = args[1] - - if not os.path.exists(videofile) and \ - os.path.exists(videofile + '.video'): - if not args[1:] and os.path.exists(videofile + '.aiff'): - audiofile = videofile + '.aiff' - videofile = videofile + '.video' - - print 'Opening video input file..' - vin = VFile.VinFile(videofile) - - print 'Opening audio input file..' - ain = aifc.open(audiofile, 'r') - print 'rate :', ain.getframerate() - print 'channels:', ain.getnchannels() - print 'frames :', ain.getnframes() - print 'width :', ain.getsampwidth() - print 'kbytes :', \ - ain.getnframes() * ain.getnchannels() * ain.getsampwidth() - - print 'Opening audio output port..' - c = al.newconfig() - c.setchannels(ain.getnchannels()) - c.setwidth(ain.getsampwidth()) - nullsample = '\0' * ain.getsampwidth() - samples_per_second = ain.getnchannels() * ain.getframerate() - if qsize <= 0: qsize = samples_per_second / 10 - qsize = max(qsize, 512) - c.setqueuesize(qsize) - saveparams = [AL.OUTPUT_RATE, 0] - al.getparams(AL.DEFAULT_DEVICE, saveparams) - newparams = [AL.OUTPUT_RATE, ain.getframerate()] - al.setparams(AL.DEFAULT_DEVICE, newparams) - aport = al.openport(audiofile, 'w', c) - - print 'Opening video output window..' - gl.foreground() - gl.prefsize(vin.width, vin.height) - wid = gl.winopen(videofile + ' + ' + audiofile) - gl.clear() - vin.initcolormap() - - print 'Playing..' - gl.qdevice(DEVICE.ESCKEY) - gl.qdevice(DEVICE.LEFTARROWKEY) - gl.qdevice(DEVICE.RIGHTARROWKEY) -## gl.qdevice(DEVICE.UPARROWKEY) -## gl.qdevice(DEVICE.DOWNARROWKEY) - gl.qdevice(DEVICE.SPACEKEY) - - while 1: - samples_written = 0 - samples_read = 0 - lastt = 0 - pause = 0 - while 1: - if gl.qtest(): - dev, val = gl.qread() - if val == 1: - if dev == DEVICE.ESCKEY: - sys.exit(0) - elif dev == DEVICE.LEFTARROWKEY: - offset = offset - 100 - print 'offset =', offset - elif dev == DEVICE.RIGHTARROWKEY: - offset = offset + 100 - print 'offset =', offset - elif dev == DEVICE.SPACEKEY: - pause = (not pause) - - if pause: - continue - - try: - t, data, cdata = vin.getnextframe() - except EOFError: - break - t = int(t) - dt = t - lastt - lastt = t - target = samples_per_second * t / 1000 - n = target - samples_written + qsize - offset - if n > 0: - # This call will block until the time is right: - try: - samples = ain.readframes(n) - except EOFError: - samples = '' - k = len(samples) / len(nullsample) - samples_read = samples_read + k - if k < n: - samples = samples + (n-k) * nullsample - aport.writesamps(samples) - samples_written = samples_written + n - vin.showframe(data, cdata) - - while 1: - try: - samples = ain.readframes(qsize) - except EOFError: - break - if not samples: - break - aport.writesamps(samples) - k = len(samples) / len(nullsample) - samples_read = samples_read + k - samples_written = samples_written + k - - print samples_read, 'samples ==', - print samples_read * 1.0 / samples_per_second, 'sec.' - print lastt, 'milliseconds' - - print 'Restarting..' - ain.close() - ain = aifc.open(audiofile, 'r') - vin.rewind() - - -main() diff --git a/Demo/sgi/video/cam.py b/Demo/sgi/video/cam.py deleted file mode 100755 index fa8966f8b3..0000000000 --- a/Demo/sgi/video/cam.py +++ /dev/null @@ -1,129 +0,0 @@ -import sys -from socket import * -from gl import * -from GL import * -from DEVICE import * -from time import millitimer - -HS = 40 # Header size (must be same as in tv.py) - -# Rely on UDP packet (de)fragmentation for smoother images -# (Changed for broadcast) -MAX = 16000 - -PF = 2 # Default packfactor - -# Default receiver station is voorn. -# Kwik has no yellow pages, so... -HOST = '192.16.201.121' -PORT = 5555 - -if sys.argv[1:]: - PF = eval(sys.argv[1]) - -if sys.argv[2:]: - HOST = sys.argv[2] - if HOST == 'all': - HOST = '' - MAX = 1400 - -PF2 = PF*PF - -def main(): - centerx, centery = 400, 300 - - foreground() - wid = winopen('cam') - RGBmode() - doublebuffer() - gconfig() - qdevice(ESCKEY) - - w, h = getsize() - ortho2(0, w, 0, h) - w = w/PF*PF - h = h/PF*PF - - readsource(SRC_FRAMEGRABBER) - - s = socket(AF_INET, SOCK_DGRAM) - if HOST == '': - s.allowbroadcast(1) - addr = HOST, PORT - - bytesperline = w/PF2 - linesperchunk = MAX/bytesperline - linesperchunk = linesperchunk/PF*PF - nchunks = (h+linesperchunk-1)/linesperchunk - - print 'MAX=', MAX, - print 'linesperchunk=', linesperchunk, - print 'nchunks=', nchunks, - print 'w=', w, 'h=', h - - x1, x2 = 0, w-1 - - t1 = millitimer() - nframes = 0 - fps = 0 - - msg = '' - - while 1: - while qtest(): - dev, val = qread() - if dev == REDRAW: - reshapeviewport() - w, h = getsize() - ortho2(0, w, 0, h) - w = w/PF*PF - h = h/PF*PF - - bytesperline = w/PF2 - linesperchunk = MAX/bytesperline - linesperchunk = linesperchunk/PF*PF - nchunks = (h+linesperchunk-1)/linesperchunk - - print 'MAX=', MAX, - print 'linesperchunk=', linesperchunk, - print 'nchunks=', nchunks, - print 'w=', w, 'h=', h - - x1, x2 = 0, w-1 - - fps = 0 - - elif dev == ESCKEY: - winclose(wid) - return - - readsource(SRC_FRAMEGRABBER) - - nframes = nframes+1 - if nframes >= fps: - t2 = millitimer() - if t2 <> t1: - fps = int(10000.0*nframes/(t2-t1)) * 0.1 - msg = `fps` + ' frames/sec' - t1 = t2 - nframes = 0 - - RGBcolor(255,255,255) - cmov2i(9,9) - charstr(msg) - - swapbuffers() - rectcopy(centerx-w/2, centery-w/2, centerx+w/2, centery+w/2, 0, 0) - - for i in range(nchunks): - y1 = i*linesperchunk - y2 = y1 + linesperchunk-1 - if y2 >= h: y2 = h-1 - data = lrectread(x1, y1, x2, y2) - data2 = packrect(x2-x1+1, y2-y1+1, PF, data) - prefix = `w, h, PF, x1, y1, x2, y2` - prefix = prefix + ' ' * (HS-len(prefix)) - data3 = prefix + data2 - s.sendto(data3, addr) - -main() diff --git a/Demo/sgi/video/camcorder.py b/Demo/sgi/video/camcorder.py deleted file mode 100755 index 9b7618c436..0000000000 --- a/Demo/sgi/video/camcorder.py +++ /dev/null @@ -1,266 +0,0 @@ -from gl import * -from GL import * -from DEVICE import * -import time -import sys -import getopt -import socket -import posix -import vtime - -# Preallocation parameter -PREALLOC = 4 # Megabyte - -# Sync audio parameters -SYNCPORT = 10000 -CTLPORT = 10001 - -from vpregs import * - -class Struct(): pass -epoch = Struct() - -def getvideosize(): - w = getvideo(VP_WIDTH) - h = getvideo(VP_HEIGHT) - print 'WIDTH,HEIGHT:', w, h - print 'GB{X,Y}ORG:', getvideo(VP_GBXORG), getvideo(VP_GBYORG) - print 'FB{X,Y}ORG:', getvideo(VP_FBXORG), getvideo(VP_FBYORG) - x = 0 - y = 0 - return x,y,w,h - -framelist = [] - -def prealloc(w, h): - nbytes = w*h*4 - limit = PREALLOC*1024*1024 - total = 0 - list = [] - print 'Prealloc to', PREALLOC, 'Megabytes...' - while total+nbytes <= limit: - list.append('x'*nbytes) - total = total + nbytes - print 'Done.' - -def grabframe(f,x,y,w,h,pf): - readsource(SRC_FRONT) - if pf: - w = w/pf*pf - h = h/pf*pf - data = lrectread(x,y,x+w-1,y+h-1) - t = time.millitimer()-epoch.epoch - framelist.append(data, t) - readsource(SRC_FRAMEGRABBER) - -def saveframes(f, w, h, pf): - for data, t in framelist: - if pf: - w = w/pf*pf - h = h/pf*pf - data = packrect(w,h,pf,data) - f.write(`t` + ',' + `len(data)` + '\n') - f.write(data) - framelist[:] = [] - -def saveframe(f,x,y,w,h,pf, notime): - readsource(SRC_FRONT) - if pf: - w = w/pf*pf - h = h/pf*pf - data = lrectread(x,y,x+w-1,y+h-1) - if pf: data = packrect(w,h,pf,data) - if notime: t = 0 - else: t = time.millitimer()-epoch.epoch - f.write(`t` + ',' + `len(data)` + '\n') - f.write(data) - readsource(SRC_FRAMEGRABBER) - -def drawframe(x,y,w,h,col): - drawmode(OVERDRAW) - color(col) - bgnline() - v2i(x-1,y-1) ; v2i(x+w,y-1); v2i(x+w,y+h); v2i(x-1,y+h); v2i(x-1,y-1) - endline() - drawmode(NORMALDRAW) - -def usage(): - sys.stderr.write('Usage: camcorder ' + \ - '[-c] [-p packfactor] [-a audiomachine [-s]] [outputfile]\n') - sys.exit(2) - -def wrheader(f, w, h, pf): - f.write('CMIF video 1.0\n') - f.write(`w,h,pf` + '\n') - print 'width,height,pf:', w, h, pf, - if pf == 0: pf = 4 - print '(i.e.,', w*h*pf, 'bytes/frame)' - -def main(): - foreground() - pf = 2 - ausync = 0 - austart = 0 - optlist, args = getopt.getopt(sys.argv[1:],'ca:sp:') - for opt, arg in optlist: - if opt == '-c': - pf = 0 - elif opt == '-a': - ausync = 1 - aumachine = arg - elif opt == '-s': - austart = 1 - elif opt == '-p': - pf = int(eval(arg)) - else: - usage() - if args: - if len(args) > 1: - print 'Too many arguments' - usage() - filename = args[0] - else: - filename = 'film.video' - if austart: - if not ausync: - print 'Cannot use -s without -a' - usage() - print 'Starting audio recorder...' - posix.system('rsh '+aumachine+' syncrecord '+socket.gethostname()+' &') - if ausync: - print 'Syncing to audio recorder...' - globtime = vtime.VTime().init(1,aumachine,SYNCPORT) - ctl = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) - ctl.bind((socket.gethostname(),CTLPORT)) - aua = (socket.gethostbyname(aumachine), CTLPORT) - print 'Done.' - vidx, vidy, w, h = getvideosize() - #prefsize(w,h) - winx, winy = 1280-w-10, 1024-h-30 - prefposition(winx,winx+w-1,winy,winy+h-1) - win = winopen(filename) - f = open(filename, 'w') - w, h = getsize() - realw, realh = w, h - ####doublebuffer() - RGBmode() - gconfig() - qdevice(LEFTMOUSE) - qdevice(RKEY) - qdevice(SKEY) - qdevice(CKEY) - qdevice(PKEY) - qdevice(ESCKEY) - qdevice(WINQUIT) - qdevice(WINSHUT) - inrunning = 1 - outrunning = 0 - stop = 'stop' - readsource(SRC_FRAMEGRABBER) - mousing = 0 - epoch.epoch = time.millitimer() - stoptime = epoch.epoch - sizewritten = 0 - x, y = realw/4, realh/4 - w, h = w/2, h/2 - prealloc(w, h) - try: - drawframe(x,y,w,h,1) - nframe = 0 - num = 0 - while 1: - insingle = 0 - outsingle = 0 - if mousing: - drawframe(x,y,w,h,0) - ox, oy = getorigin() - if sizewritten: - x = getvaluator(MOUSEX)-ox - y = getvaluator(MOUSEY)-oy - else: - w = getvaluator(MOUSEX)-x-ox - h = getvaluator(MOUSEY)-y-oy - drawframe(x,y,w,h,1) - if qtest() or \ - not (mousing or inrunning or insingle or outrunning or outsingle): - ev, val = qread() - if ev == LEFTMOUSE and val == 1: - drawframe(x,y,w,h,0) - mousing = 1 - ox, oy = getorigin() - x = getvaluator(MOUSEX)-ox - y = getvaluator(MOUSEY)-oy - elif ev == LEFTMOUSE and val == 0: - if h < 0: - y, h = y+h, -h - if w < 0: - x, w = x+w, -w - mousing = 0 - if not sizewritten: - wrheader(f, w, h, pf) - sizewritten = 1 - prealloc(w, h) - elif ev == RKEY and val == 1: - if not inrunning: - ringbell() - else: - outrunning = 1 - wasstopped = time.millitimer() - stoptime - epoch.epoch = epoch.epoch + wasstopped - nframe = 0 - starttime = time.millitimer() - if ausync: - ctl.sendto(`(1,starttime)`, aua) - elif ev == PKEY and val == 1 and outrunning: - outrunning = 0 - stoptime = time.millitimer() - if ausync: - ctl.sendto(`(0,stoptime)`, aua) - fps = nframe * 1000.0 / (time.millitimer()-starttime) - print 'Recorded', nframe, - print 'frames at', 0.1*int(fps*10),'frames/sec' - print 'Saving...' - saveframes(f, w, h, pf) - print 'Done.' - elif ev == PKEY and val == 1 and not outrunning: - outsingle = 1 - elif ev == CKEY and val == 1: - inrunning = 1 - elif ev == SKEY and val == 1: - if outrunning: - ringbell() - elif inrunning: - inrunning = 0 - else: - insingle = 1 - elif ev in (ESCKEY, WINQUIT, WINSHUT): - if ausync: - ctl.sendto(`(2,time.millitimer())`, aua) - raise stop - elif ev == REDRAW: - drawframe(x,y,w,h,0) - reshapeviewport() - drawframe(x,y,w,h,1) - if inrunning or insingle: - if outrunning: - rectcopy(vidx+x,vidy+y,vidx+x+w-1,vidy+y+h-1,x,y) - else: - rectcopy(vidx,vidy,vidx+realw-1,vidx+realh-1,0,0) - ####swapbuffers() - if outrunning or outsingle: - nframe = nframe + 1 - if not sizewritten: - wrheader(f, w, h, pf) - sizewritten = 1 - if outrunning: - grabframe(f, x, y, w, h, pf) - else: - saveframe(f, x, y, w, h, pf, outsingle) - except stop: - pass - finally: - drawmode(OVERDRAW) - color(0) - clear() - -main() diff --git a/Demo/sgi/video/cmif-film.ms b/Demo/sgi/video/cmif-film.ms deleted file mode 100755 index aa114d9788..0000000000 --- a/Demo/sgi/video/cmif-film.ms +++ /dev/null @@ -1,200 +0,0 @@ -.de PP -.LP -.. -.de pT -.IP \fB\\$1\fP -.. -.TL -CMIF video file format -.AU -Jack Jansen -(Version of 27-Feb-92) -.SH -Introduction -.PP -The CMIF video format was invented to allow various applications -to exchange video data. The format consists of -a header containing global information (like data format) -followed by a sequence of frames, each consisting of a header -followed by the actual frame data. -All information except pixel data is -encoded in ASCII. Pixel data is \fIalways\fP encoded in Silicon Graphics -order, which means that the first pixel in the frame is the lower left -pixel on the screen. -.PP -All ASCII data except the first line of the file -is in python format. This means that -outer parentheses can be ommitted, and parentheses around a tuple with -one element can also be omitted. So, the lines -.IP -.ft C -.nf -('grey',(4)) -('grey',4) -'grey',4 -.LP -have the same meaning. -To ease parsing in C programs, however, it is advised that there are -no parenteses around single items, and that there are parentheses around -lists. So, the second format above is preferred. -.PP -The current version is version 3, but this document will also explain -shortly what the previous formats looked like. -.SH -Header. -.PP -The header consists of three lines. The first line identifies the file -as a CMIF video file, and gives the version number. -It looks as follows: -.IP -.ft C -CMIF video 3.0 -.LP -All programs expect the layout to be exactly like this, so no -extra spaces, etc. should be added. -.PP -The second line specifies the data format. Its format is a python -tuple with two members. The first member is a string giving the format -type and the second is a tuple containing type-specific information. -The following formats are currently understood: -.pT rgb -The video data is 24 bit RGB packed into 32 bit words. -R is the least significant byte, then G and then B. The top byte is -unused. -.IP -There is no type-specific information, so the complete data format -line is -.IP -.ft C -('rgb',()) -.pT grey -The video data is greyscale, at most 8 bits. Data is packed into -8 bit bytes (in the low-order bits). The extra information is the -number of significant bits, so an example data format line is -.IP -.ft C -('grey',(6)) -.pT yiq -The video data is in YIQ format. This is a format that has one luminance -component, Y, and two chrominance components, I and Q. The luminance and -chrominance components are encoded in \fItwo\fP pixel arrays: first an -array of 8-bit luminance values followed by a array of 16 bit chrominance -values. See the section on chrominance coding for details. -.IP -The type specific part contains the number of bits for Y, I and Q, -the chrominance packfactor and the colormap offset. So, a sample format -information line of -.IP -.ft C -('yiq',(5,3,3,2,1024)) -.IP -means that the pictures have 5 bit Y values (in the luminance array), -3 bits of I and Q each (in the chrominance array), chrominance data -is packed for 2x2 pixels, and the first colormap index used is 1024. -.pT hls -The video data is in HLS format. L is the luminance component, H and S -are the chrominance components. The data format and type specific information -are the same as for the yiq format. -.pT hsv -The video data is in HSV format. V is the luminance component, H and S -are the chrominance components. Again, data format and type specific -information are the same as for the yiq format. -.pT rgb8 -The video data is in 8 bit dithered rgb format. This is the format -used internally by the Indigo. bit 0-2 are green, bit 3-4 are blue and -bit 5-7 are red. Because rgb8 is treated more-or-less like yiq format -internally the type-specific information is the same, with zeroes for -the (unused) chrominance sizes: -.IP -.ft C -('rgb8',(8,0,0,0,0)) -.PP -The third header line contains width and height of the video image, -in pixels, and the pack factor of the picture. For compatability, RGB -images must have a pack factor of 0 (zero), and non-RGB images must -have a pack factor of at least 1. -The packfactor is the amount of compression done on the original video -signal to obtain pictures. In other words, if only one out of three pixels -and lines is stored (so every 9 original pixels have one pixel in the -data) the packfactor is three. Width and height are the size of the -\fIoriginal\fP picture. -Viewers are expected to enlarge the picture so it is shown in the -original size. RGB videos cannot be packed. -So, a size line like -.IP -.ft C -200,200,2 -.LP -means that this was a 200x200 picture that is stored as 100x100 pixels. -.SH -Frame header -.PP -Each frame is preceded by a single header line. This line contains timing information -and optional size information. The time information is mandatory, and -contains the time this frame should be displayed, in milliseconds since -the start of the film. Frames should be stored in chronological order. -.PP -An optional second number is interpreted as the size of the luminance -data in bytes. Currently this number, if present, should always be the -same as \fCwidth*height/(packfactor*packfactor)\fP (times 4 for RGB -data), but this might change if we come up with variable-length encoding -for frame data. -.PP -An optional third number is the size of the chrominance data -in bytes. If present, the number should be equal to -.ft C -luminance_size2*/(chrompack*chrompack). -.SH -Frame data -.PP -For RGB films, the frame data is an array of 32 bit pixels containing -RGB data in the lower 24 bits. For greyscale films, the frame data -is an array of 8 bit pixels. For split luminance/chrominance films the -data consists of two parts: first an array of 8 bit luminance values -followed by an array of 16 bit chrominance values. -.PP -For all data formats, the data is stored left-to-right, bottom-to-top. -.SH -Chrominance coding -.PP -Since the human eye is apparently more sensitive to luminance changes -than to chrominance changes we support a coding where we split the luminance -and chrominance components of the video image. The main point of this -is that it allows us to transmit chrominance data in a coarser granularity -than luminance data, for instance one chrominance pixel for every -2x2 luminance pixels. According to the theory this should result in an -acceptable picture while reducing the data by a fair amount. -.PP -The coding of split chrominance/luminance data is a bit tricky, to -make maximum use of the graphics hardware on the Personal Iris. Therefore, -there are the following constraints on the number of bits used: -.IP - -No more than 8 luminance bits, -.IP - -No more than 11 bits total, -.IP - -The luminance bits are in the low-end of the data word, and are stored -as 8 bit bytes, -.IP - -The two sets of chrominance bits are stored in 16 bit words, correctly -aligned, -.IP - -The color map offset is added to the chrominance data. The offset should -be at most 4096-256-2**(total number of bits). To reduce interference with -other applications the offset should be at least 1024. -.LP -So, as an example, an HLS video with 5 bits L, 4 bits H, 2 bits S and an -offset of 1024 will look as follows in-core and in-file: -.IP -.nf -.ft C - 31 15 11 10 9 8 5 4 0 - +-----------------------------------+ -incore + 0+ 1+ S + H + L + - +-----------------------------------+ - +----------+ -L-array + 0 + L + - +----------+ - +-----------------------+ -C-array + 0+ 1+ S + H + 0 + - +-----------------------+ diff --git a/Demo/sgi/video/colorsys.py b/Demo/sgi/video/colorsys.py deleted file mode 100755 index dd3a033b26..0000000000 --- a/Demo/sgi/video/colorsys.py +++ /dev/null @@ -1,106 +0,0 @@ -# -# Module color - do color conversions -# - -ONE_THIRD=1.0/3.0 -ONE_SIXTH=1.0/6.0 -TWO_THIRD=2.0/3.0 - -def rgb_to_yiq(r,g,b): - y = 0.3*r + 0.59*g + 0.11*b - i = 0.6*r - 0.28*g - 0.32*b - q = 0.21*r- 0.52*g + 0.31*b - return (y,i,q) -def yiq_to_rgb(y,i,q): - r = y + 0.948262*i + 0.624013*q - g = y - 0.276066*i - 0.639810*q - b = y - 1.105450*i + 1.729860*q - if r < 0.0: r = 0.0 - if g < 0.0: g = 0.0 - if b < 0.0: b = 0.0 - if r > 1.0: r = 1.0 - if g > 1.0: g = 1.0 - if b > 1.0: b = 1.0 - return (r,g,b) - -def _v(m1,m2,hue): - if hue >= 1.0: hue = hue - 1.0 - if hue < 0.0: hue = hue + 1.0 - if hue < ONE_SIXTH: - return m1 + (m2-m1)*hue*6.0 - if hue < 0.5: - return m2 - if hue < TWO_THIRD: - return m1 + (m2-m1)*(TWO_THIRD-hue)*6.0 - return m1 - -def rgb_to_hls(r,g,b): - maxc = max(r,g,b) - minc = min(r,g,b) - l = (minc+maxc)/2.0 - if minc == maxc: - return 0.0, l, 0.0 - if l <= 0.5: - s = (maxc-minc)/(maxc+minc) - else: - s = (maxc-minc)/(2-maxc-minc) - rc = (maxc-r)/(maxc-minc) - gc = (maxc-g)/(maxc-minc) - bc = (maxc-b)/(maxc-minc) - if r == maxc: - h = bc-gc - elif g == maxc: - h = 2.0+rc-bc - else: - h = 4.0+gc-rc - h = h/6.0 - if h < 0.0: - h = h + 1.0 - return h,l,s -def hls_to_rgb(h,l,s): - if s == 0.0: - return l,l,l - if l <= 0.5: - m2 = l * (1.0+s) - else: - m2 = l+s-(l*s) - m1 = 2.0*l - m2 - return (_v(m1,m2,h+ONE_THIRD), _v(m1,m2,h), _v(m1,m2,h-ONE_THIRD)) - -def rgb_to_hsv(r,g,b): - maxc = max(r,g,b) - minc = min(r,g,b) - v = maxc - if minc == maxc: - return 0.0, 0.0, v - s = (maxc-minc)/maxc - rc = (maxc-r)/(maxc-minc) - gc = (maxc-g)/(maxc-minc) - bc = (maxc-b)/(maxc-minc) - if r == maxc: - h = bc-gc - elif g == maxc: - h = 2.0+rc-bc - else: - h = 4.0+gc-rc - h = h/6.0 - if h < 0.0: - h = h + 1.0 - return h,s,v -def hsv_to_rgb(h,s,v): - if s == 0.0: - return v,v,v - i = int(h*6.0) - f = (h*6.0)-i - p = v*(1.0-s) - q = v*(1.0-s*f) - t = v*(1.0-s*(1.0-f)) - if i in (0,6): return v,t,p - if i == 1: return q,v,p - if i == 2: return p,v,t - if i == 3: return p,q,v - if i == 4: return t,p,v - if i == 5: return v,p,q - print i, h, f - print h, s, v - raise 'Bad color' diff --git a/Demo/sgi/video/i2v.c b/Demo/sgi/video/i2v.c deleted file mode 100755 index 21dfabe2b2..0000000000 --- a/Demo/sgi/video/i2v.c +++ /dev/null @@ -1,80 +0,0 @@ -/* - * i2v -- image-to-video. - * Convert an SGI image file to a format that is immediately usable - * by lrectwrite. - * The header of the file contains a description (in ASCII) - * padded to 8196 byte for fast access of the rest of the file. - * - * Based upon "showimg.c" by Paul Haeberli. - * --Guido van Rossum, CWI, Amsterdam - */ -#include -#include -#include -#include - -unsigned short rs[8192]; -unsigned short gs[8192]; -unsigned short bs[8192]; - -IMAGE *image; -int xsize, ysize, zsize; -FILE *fp; - -char header[100]; -char *progname = "i2v"; - -main(argc,argv) -int argc; -char **argv; -{ - int y; - if (argc > 0) progname = argv[0]; - if( argc != 3 ) { - fprintf(stderr, "usage: %s infile outfile\n", progname); - exit(2); - } - if( (image=iopen(argv[1],"r")) == NULL ) { - fprintf(stderr, "%s: can't open input file %s\n",progname, argv[1]); - exit(1); - } - xsize = image->xsize; - ysize = image->ysize; - zsize = image->zsize; - if ((fp = fopen(argv[2], "w")) == NULL) { - fprintf(stderr,"%s: can't open output file %s\n", progname, argv[2]); - exit(1); - } - fprintf(fp, "CMIF video 1.0\n"); - fprintf(fp, "(%d, %d, %d)\n", xsize, ysize, 0); - fprintf(fp, "0, %ld\n", (long)xsize * (long)ysize * sizeof(long)); - fflush(fp); - for(y = 0; y < ysize; y++) { - if(zsize<3) { - getrow(image, rs, y, 0); - writepacked(xsize, rs, rs, rs); - } else { - getrow(image, rs, y, 0); - getrow(image, gs, y, 1); - getrow(image, bs, y, 2); - writepacked(xsize, rs, gs, bs); - } - } - exit(0); -} - -writepacked(n, rsptr, gsptr, bsptr) - int n; - short *rsptr, *gsptr, *bsptr; -{ - long parray[8192]; - long *pptr = parray; - int i = n; - while (--i >= 0) { - *pptr++ = *rsptr++ | (*gsptr++<<8) | (*bsptr++<<16); - } - if (fwrite((char *) parray, sizeof(long), n, fp) != n) { - perror("fwrite"); - exit(1); - } -} diff --git a/Demo/sgi/video/imgconv.py b/Demo/sgi/video/imgconv.py deleted file mode 100755 index 291fdc8125..0000000000 --- a/Demo/sgi/video/imgconv.py +++ /dev/null @@ -1,140 +0,0 @@ -import imageop - -error = 'imgconv.error' - -LOSSY = 1 -NOT_LOSSY = 0 - -def null(img, x, y): - return img - -def mono2grey(img, x, y): - return imageop.mono2grey(img, x, y, 0, 255) - -def grey2jpeggrey(img, x, y): - import jpeg - return jpeg.compress(img, x, y, 1) - -def rgb2jpeg(img, x, y): - import jpeg - return jpeg.compress(img, x, y, 4) - -def jpeggrey2grey(img, width, height): - import jpeg - data, width, height, bytesperpixel = jpeg.decompress(img) - if bytesperpixel <> 1: raise RuntimeError, 'not greyscale jpeg' - return data - -def jpeg2rgb(img, width, height): - import cl, CL - import jpeg - data, width, height, bytesperpixel = jpeg.decompress(img) - if bytesperpixel <> 4: raise RuntimeError, 'not rgb jpeg' - return data - -converters = [ \ - ('grey', 'grey4', imageop.grey2grey4, LOSSY), \ - ('grey', 'grey2', imageop.dither2grey2, LOSSY), \ - ('grey', 'mono', imageop.dither2mono, LOSSY), \ - ('mono', 'grey', mono2grey, NOT_LOSSY), \ - ('grey2', 'grey', imageop.grey22grey, NOT_LOSSY), \ - ('grey4', 'grey', imageop.grey42grey, NOT_LOSSY), \ - ('rgb', 'rgb8', imageop.rgb2rgb8, LOSSY), \ - ('rgb8', 'rgb', imageop.rgb82rgb, NOT_LOSSY), \ - ('rgb', 'grey', imageop.rgb2grey, LOSSY), \ - ('grey', 'rgb', imageop.grey2rgb, NOT_LOSSY), \ - ('jpeggrey','grey',jpeggrey2grey, NOT_LOSSY), \ - ('grey', 'jpeggrey',grey2jpeggrey, LOSSY), \ - ('jpeg', 'rgb', jpeg2rgb, NOT_LOSSY), \ - ('rgb', 'jpeg', rgb2jpeg, LOSSY), \ -] - -built = {} - -def addconverter(fcs, tcs, lossy, func): - for i in range(len(converters)): - ifcs, itcs, irtn, ilossy = converters[i] - if (fcs, tcs) == (ifcs, itcs): - converters[i] = (fcs, tcs, func, lossy) - return - converters.append((fcs,tcs,lossy,func)) - -def getconverter(fcs, tcs): - # - # If formats are the same return the dummy converter - # - if fcs == tcs: return null - # - # Otherwise, if we have a converter return that one - # - for ifcs, itcs, irtn, ilossy in converters: - if (fcs, tcs) == (ifcs, itcs): - return irtn - # - # Finally, we try to create a converter - # - if not built.has_key(fcs): - built[fcs] = enumerate_converters(fcs) - if not built[fcs].has_key(tcs): - raise error, 'Sorry, conversion from '+fcs+' to '+tcs+ \ - ' is not implemented' - if len(built[fcs][tcs]) == 3: - # - # Converter not instantiated yet - # - built[fcs][tcs].append(instantiate_converter(built[fcs][tcs])) - cf = built[fcs][tcs][3] - return cf - -def enumerate_converters(fcs): - cvs = {} - formats = [fcs] - steps = 0 - while 1: - workdone = 0 - for ifcs, itcs, irtn, ilossy in converters: - if ifcs == fcs: - template = [ilossy, 1, [irtn]] - elif cvs.has_key(ifcs): - template = cvs[ifcs][:] - template[2] = template[2][:] - if ilossy: - template[0] = ilossy - template[1] = template[1] + 1 - template[2].append(irtn) - else: - continue - if not cvs.has_key(itcs): - cvs[itcs] = template - workdone = 1 - else: - previous = cvs[itcs] - if template < previous: - cvs[itcs] = template - workdone = 1 - if not workdone: - break - steps = steps + 1 - if steps > len(converters): - print '------------------loop in emunerate_converters--------' - print 'CONVERTERS:' - print converters - print 'RESULTS:' - print cvs - raise error, 'Internal error - loop' - return cvs - -def instantiate_converter(args): - list = args[2] - cl = RtConverters(list) - args.append(cl.convert) - return args - -class RtConverters: - def __init__(self, list): - self.list = list - - def convert(self, img, w, h): - for cv in self.list: - img = cv(img, w, h) - return img diff --git a/Demo/sgi/video/makemovie.py b/Demo/sgi/video/makemovie.py deleted file mode 100755 index 5cb41cde2e..0000000000 --- a/Demo/sgi/video/makemovie.py +++ /dev/null @@ -1,218 +0,0 @@ -#! /ufs/guido/bin/sgi/python -#! /ufs/guido/src/video/py - -# Capture a CMIF movie using the Indigo video library and board - - -# Usage: -# -# makemovie [-q queuesize] [-t recordtime] [-a] [moviefile [audiofile]] - - -# Options: -# -# -q queuesize : set the capture queue size (default and max 16) -# -t recordtime : set the record time in seconds (default 5 seconds) -# -a : record audio as well -# moviefile : here goes the movie data (default film.video); -# the format is documented in cmif-film.ms -# audiofile : with -a, here goes the audio data (default film.aiff); -# audio data is recorded in AIFF format, using the -# input sampling rate, source and volume set by the -# audio panel, in mono, 8 bits/sample - - -# User interface: -# -# Start the application. Resize the window to the desired movie size. -# Click the left mouse button to start recording (recording starts -# when you release the mouse button). Recording time is specified by -# the -t option (XXX this should change). -# -# Press ESC or select the window manager Quit or Close window option -# to quit. (You can do this without recording -- then the output -# files are untouched.) -# -# (It is possible to record more than once; but this doesn't set the -# time stamps correctly yet, and doesn't work at all with audio. So -# don't use.) - - -# XXX To do: -# -# fix timestamps for second and further recordings -# fix audio " " " " " -# flush audio buffer when recording starts -# make code more readable - - -import sys -sys.path.append('/ufs/guido/src/video') -import sv, SV -import VFile -import gl, GL, DEVICE -import al, AL -import time -import posix -import getopt -import string - - -def main(): - QSIZE = 16 - TIME = 5 - audio = 0 - - opts, args = getopt.getopt(sys.argv[1:], 'aq:t:') - for opt, arg in opts: - if opt == '-a': - audio = 1 - elif opt == '-q': - QSIZE = string.atoi(arg) - elif opt == '-t': - TIME = string.atoi(arg) - - if args: - filename = args[0] - else: - filename = 'film.video' - - if audio: - if args[1:]: - audiofilename = args[1] - else: - audiofilename = 'film.aiff' - - gl.foreground() - - x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 - print x, 'x', y - - gl.minsize(40, 30) - gl.stepunit(8, 6) - gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) - gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) - win = gl.winopen(filename) - x, y = gl.getsize() - print x, 'x', y - - v = sv.OpenVideo() - v.BindGLWindow(win, SV.IN_REPLACE) - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - - v.SetCaptureFormat(SV.RGB_FRAMES) - v.SetCaptureMode(SV.BLOCKING_CAPTURE) - v.SetQueueSize(QSIZE) - v.InitCapture() - if v.GetQueueSize() != QSIZE: - QSIZE = v.GetQueueSize() - print 'Warning: QSIZE reduced to', QSIZE - - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - - print 'Click left mouse to start recording', TIME, 'seconds' - ofile = None - afile = None - # Mouse down opens the file & freezes window - # Mouse up starts recording frames - - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE: - # Start recording - if val == 1: - # Mouse down -- preparations - if ofile == None: - ofile = VFile.VoutFile().init(filename) - ofile.format = 'rgb8' - ofile.width = x - ofile.height = y - ofile.writeheader() - # XXX other format bits? - # The window can't be resized from now - gl.prefsize(x, y) - gl.winconstraints() - gl.wintitle('* ' + filename) - if audio: - afile = initaudio(audiofilename) - continue - # Mouse up -- start actual recording - global recording, stop_recording - if audio: - stop_recording = 0 - recording.release() - t0 = time.millitimer() - v.StartCapture() - while 1: - t = time.millitimer() - t0 - if t >= TIME*1000: - break - if v.GetCaptured() > 2: - doframe(v, ofile, x, y, t) - v.StopCapture() - stop_recording = 1 - while v.GetCaptured() > 0: - doframe(v, ofile, x, y, t) - t = time.millitimer() - t0 - gl.wintitle(filename) - elif dev == DEVICE.REDRAW: - # Window resize (or move) - x, y = gl.getsize() - print x, 'x', y - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - # Quit - if ofile: - ofile.close() - if afile: - afile.destroy() - posix._exit(0) - # EndCapture dumps core... - v.EndCapture() - v.CloseVideo() - gl.winclose(win) - -def doframe(v, ofile, x, y, t): - cd, start = v.GetCaptureData() - data = cd.interleave(x, y) - cd.UnlockCaptureData() - ofile.writeframe(t, data, None) - -AQSIZE = 16000 - -def initaudio(filename): - import thread, aiff - global recording, stop_recording - afile = aiff.Aiff().init(filename, 'w') - afile.nchannels = AL.MONO - afile.sampwidth = AL.SAMPLE_8 - params = [AL.INPUT_RATE, 0] - al.getparams(AL.DEFAULT_DEVICE, params) - print 'rate =', params[1] - afile.samprate = params[1] - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(AQSIZE) - c.setwidth(AL.SAMPLE_8) - aport = al.openport(filename, 'r', c) - recording = thread.allocate_lock() - recording.acquire() - stop_recording = 0 - thread.start_new_thread(recorder, (afile, aport)) - return afile - -def recorder(afile, aport): - # XXX recording more than one fragment doesn't work - # XXX (the thread never dies) - recording.acquire() - while not stop_recording: - data = aport.readsamps(AQSIZE/2) - afile.writesampsraw(data) - del data - -main() diff --git a/Demo/sgi/video/rgb2video.py b/Demo/sgi/video/rgb2video.py deleted file mode 100755 index b6c34ebc35..0000000000 --- a/Demo/sgi/video/rgb2video.py +++ /dev/null @@ -1,79 +0,0 @@ -import sys -import VFile -import getopt -import imgfile -import string -import imgconv - -def main(): - format = None - interval = 40 - outfile = 'film.video' - - try: - opts, args = getopt.getopt(sys.argv[1:], 'f:i:o:') - except getopt.error: - usage() - sys.exit(1) - for opt, arg in opts: - if opt == '-f': - format = arg - elif opt == '-i': - interval = string.atoi(arg) - elif opt == '-o': - outfile = arg - else: - usage() - sys.exit(1) - if not args: - usage() - sys.exit(1) - - xsize, ysize, zsize = imgfile.getsizes(args[0]) - nxsize = xsize - - if zsize == 3: - oformat = 'rgb' - elif zsize == 1: - oformat = 'grey' - if xsize % 4: - addbytes = 4-(xsize%4) - nxsize = xsize + addbytes - print 'rgb2video: add',addbytes,'pixels per line' - else: - print 'rgb2video: incorrect number of planes:',zsize - sys.exit(1) - - if format == None: - format = oformat - cfunc = imgconv.getconverter(oformat, format) - - vout = VFile.VoutFile(outfile) - vout.format = format - vout.width = nxsize - vout.height = ysize - vout.writeheader() - t = 0 - sys.stderr.write('Processing ') - for img in args: - sys.stderr.write(img + ' ') - if imgfile.getsizes(img) <> (xsize, ysize, zsize): - print 'rgb2video: Image is different size:', img - sys.exit(1) - data = imgfile.read(img) - if xsize <> nxsize: - ndata = '' - for i in range(0,len(data), xsize): - curline = data[i:i+xsize] - ndata = ndata + curline + ('\0'*(nxsize-xsize)) - data = ndata - vout.writeframe(t, cfunc(data, nxsize, ysize), None) - t = t + interval - sys.stderr.write('\n') - vout.close() - -def usage(): - print 'Usage: rgb2video [-o output] [-i frameinterval] [-f format] rgbfile ...' - -main() - diff --git a/Demo/sgi/video/senddefs.py b/Demo/sgi/video/senddefs.py deleted file mode 100755 index c3ce2cd1e9..0000000000 --- a/Demo/sgi/video/senddefs.py +++ /dev/null @@ -1,11 +0,0 @@ -# Defaults shared by Vsend and Vreceice - -DEFMCAST = '225.0.0.250' -DEFPORT = 5555 - -PKTMAX_UCAST = 16*1024 - 6 -PKTMAX_BCAST = 1450 -DEFPKTMAX = PKTMAX_BCAST - -DEFWIDTH = 400 -DEFHEIGHT = 300 diff --git a/Demo/sgi/video/squash.c b/Demo/sgi/video/squash.c deleted file mode 100755 index d5ea946924..0000000000 --- a/Demo/sgi/video/squash.c +++ /dev/null @@ -1,130 +0,0 @@ -#include - -long *bm; -long h, w; -long factor; - -#define OC(x,xi) ((x)*factor+(xi)) -#define BM(x,xi,y,yi) bm[OC(y,yi)*w+OC(x,xi)] - -#define COMP(r,g,b) ((r) | ((g)<<8) | ((b) << 16)) - -#define R(comp) ((comp) & 0xff) -#define G(comp) (((comp)>>8) & 0xff) -#define B(comp) (((comp)>>16) & 0xff) - -main(argc, argv) - char **argv; -{ - char lbuf[100]; - int nh, nw; - int x, y, xi, yi; - int num; - int r, g, b; - long data; - long *nbm, *nbmp; - int i; - int bits, mask, roundbit, addbit; - int pf; - int newfmt = 0; - - if( argc != 2 && argc != 3) { - fprintf(stderr, "Usage: squash factor [bits]\n"); - exit(1); - } - factor = atoi(argv[1]); - if ( argc > 2 ) { - bits = atoi(argv[2]); - mask = (1 << bits) - 1; - mask <<= (8-bits); - roundbit = 1 << (7-bits); - addbit = 1 << (8-bits); - fprintf(stderr, "%x %x %x\n", mask, roundbit, addbit); - } else { - mask = 0xff; - roundbit = 0; - addbit = 0; - } - gets(lbuf); - if ( strncmp( lbuf, "CMIF", 4) == 0 ) { - newfmt = 1; - gets(lbuf); - if( sscanf(lbuf, "(%d,%d,%d)", &w, &h, &pf) != 3) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - if ( pf != 0 ) { - fprintf(stderr, "%s: packed file\n", argv[0]); - exit(1); - } - } else { - if ( sscanf(lbuf, "(%d,%d)", &w, &h) != 2) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - } - nh = h / factor; - nw = w / factor; - if ( newfmt ) - printf("CMIF video 1.0\n(%d,%d,%d)\n", nw, nh, 0); - else - printf("(%d,%d)\n", nw, nh); - if ( (bm = (long *)malloc(h*w*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - if ( (nbm = (long *)malloc(nh*nw*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - while( !feof(stdin) ) { - { int t, s; - gets(lbuf); - if ( feof(stdin) ) break; - if ( sscanf(lbuf, "%d,%d", &t,&s) == 2) { - if ( s != h*w*4 ) { - fprintf(stderr, "Size changed from %d to %d: %s\n",4*h*w,s, lbuf); - exit(1); - } - printf("%d, %d\n", t, nh*nw*4); - } else { - puts(lbuf); - } - } - fprintf(stderr, "Reading %d\n", h*w*sizeof(long)); - if ( (i=fread(bm, 1, h*w*sizeof(long), stdin)) != h*w*sizeof(long)) { - fprintf(stderr, "%s: short read, %d wanted %d\n", argv[0], - i, h*w*sizeof(long)); - exit(1); - } - nbmp = nbm; - for( y=0; y - -long *bm; -long h, w; -long factor; - -#define OC(x,xi) ((x)*factor+(xi)) -#define BM(x,xi,y,yi) bm[OC(y,yi)*w+OC(x,xi)] - -#define COMP(r,g,b) ((r) | ((g)<<8) | ((b) << 16)) - -#define R(comp) ((comp) & 0xff) -#define G(comp) (((comp)>>8) & 0xff) -#define B(comp) (((comp)>>16) & 0xff) - -main(argc, argv) - char **argv; -{ - char lbuf[100]; - int nh, nw; - int x, y, xi, yi; - int num; - int r, g, b; - long data; - long *nbm, *nbmp; - int i; - - if( argc != 2) { - fprintf(stderr, "Usage: squash factor\n"); - exit(1); - } - factor = atoi(argv[1]); - gets(lbuf); - if ( sscanf(lbuf, "(%d,%d)", &w, &h) != 2) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - nh = h / factor; - nw = w / factor; - printf("(%d,%d)\n", nw, nh); - if ( (bm = (long *)malloc(h*w*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - if ( (nbm = (long *)malloc(nh*nw*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - while( !feof(stdin) ) { - gets(lbuf); - if ( feof(stdin) ) break; - puts(lbuf); - fprintf(stderr, "Reading %d\n", h*w*sizeof(long)); - if ( (i=fread(bm, 1, h*w*sizeof(long), stdin)) != h*w*sizeof(long)) { - fprintf(stderr, "%s: short read, %d wanted %d\n", argv[0], - i, h*w*sizeof(long)); - exit(1); - } - nbmp = nbm; - for( y=0; y size: - raise EOFError - dostat(w2, h2, data) - nframes = nframes+1 - t1 = millitimer() - - t = 0.001 * (t1-t0) - fps = 0.1 * int(10*nframes/t) - print nframes, 'frames in', t, 'sec. =', fps, 'frames/sec.' - -def dostat(w, h, data): - print - stat3(w, h, data) - -# Statistic op 1: frequencies of byte values -def stat1(w, h, data): - bins = [0]*256 - for c in data: - i = ord(c) - bins[i] = bins[i]+1 - prbins(bins) - -def prbins(bins): - import string - s = '' - tot = 0 - for i in range(256): - tot = tot + bins[i] - s = s + string.rjust(`bins[i]`, 4) - if len(s) >= 4*16: - print s, string.rjust(`tot`, 7) - s = '' - tot = 0 - -# Statistic op 2: run lengths -def stat2(w, h, data): - runs = [] - for y in range(h): - count, value = 0, ord(data[y*w]) - for c in data[y*w : y*w+w]: - i = ord(c) - if i <> value: - runs.append(count, value) - count, value = 0, i - count = count+1 - runs.append(count, value) - print len(runs), 'runs =', 0.1 * (10*w*h/len(runs)), 'bytes/run' - -# Statistic op 3: frequencies of byte differences -def stat3(w, h, data): - bins = [0]*256 - prev = 0 - for c in data: - i = ord(c) - delta = divmod(i-prev, 256)[1] - prev = i - bins[delta] = bins[delta]+1 - prbins(bins) - -# Try packing -def packblock(w, h, data): - res = '' - for y in range(h): - res = res + packline(data[y*w : y*w+w]) - return res - -def packline(line): - bytes = [] - for c in line: - bytes.append(ord(c)) - prev = bytes[0] - i, n = 1, len(bytes) - while i < n: - for pack in (0, 2, 4, 8): - if pack == 0: - lo, hi = 0, 0 - else: - hi = pow(2, pack-1)-1 - lo = -hi-1 - p = prev - j = i - count = 0 - while j < n: - x = bytes[j] - delta = byte(x-p) - if not lo <= delta <= hi: - break - p = x - j = j+1 - -def byte(x): return divmod(x, 256)[1] - -main() diff --git a/Demo/sgi/video/svgrab24.c b/Demo/sgi/video/svgrab24.c deleted file mode 100755 index 3418b145da..0000000000 --- a/Demo/sgi/video/svgrab24.c +++ /dev/null @@ -1,97 +0,0 @@ -/* - * svgrab24 - Grab the current video input image into an rgb file. - * - * Jack Jansen, CWI, May 93. - * - * Adapted from grabone.c - */ - -#ident "$Revision$" - -#include -#include -#include -#include -#include -#include -#include - -main(int argc, char *argv[]) -{ - SVhandle V; - svCaptureInfo ci; - boolean debug; - int ch, errflg; - int bufferSize; - long *buffer; - IMAGE *imgfile; - short *r, *g, *b; - int x, y; - char *ProgName = argv[0]; - - debug = FALSE; - ci.format = SV_RGB32_FRAMES; - ci.width = 0; - ci.height = 0; - ci.size = 1; - - argv++; argc--; - if ( argc > 2 && strcmp(argv[0], "-w") == 0) { - ci.width = atoi(argv[1]); - argc -= 2; - argv += 2; - } - if ( argc != 1 ) { - fprintf(stderr, "Usage: %s [-w width] rgbfilename\n", ProgName); - exit(1); - } - - /* Open video device */ - if ((V = svOpenVideo()) == NULL) { - svPerror("open"); - exit(1); - } - - if (svQueryCaptureBufferSize(V, &ci, &bufferSize) < 0) { - svPerror("svQueryCaptureBufferSize"); - exit(1); - } - buffer = malloc(bufferSize); - - if (svCaptureOneFrame(V, ci.format, &ci.width, &ci.height, buffer) < 0) { - svPerror("svCaptureOneFrame"); - exit(1); - } - if (debug) { - printf("captured size: %d by %d\n", ci.width, ci.height); - } - - if ( (imgfile=iopen(argv[0], "w", RLE(1), 3, ci.width, ci.height, 3)) == 0) { - perror(argv[1]); - exit(1); - } - r = (short *)malloc(ci.width*sizeof(short)); - g = (short *)malloc(ci.width*sizeof(short)); - b = (short *)malloc(ci.width*sizeof(short)); - if ( !r || !g || !b ) { - fprintf(stderr, "%s: malloc failed\n", ProgName); - exit(1); - } - for(y=0; y>8) & 0xff; - b[x] = (data>>16) & 0xff; - } - if ( putrow(imgfile, r, y, 0) == 0 || - putrow(imgfile, g, y, 1) == 0 || - putrow(imgfile, b, y, 2) == 0) { - fprintf(stderr, "%s: putrow failed\n", ProgName); - exit(1); - } - } - iclose(imgfile); - exit(0); -} diff --git a/Demo/sgi/video/syncaudio.py b/Demo/sgi/video/syncaudio.py deleted file mode 100755 index fd09d2879c..0000000000 --- a/Demo/sgi/video/syncaudio.py +++ /dev/null @@ -1,94 +0,0 @@ -import AL -import al -import sys -import vtime -import socket -import time - - -SLEEPTIME = 500 # 500 ms sleeps -SAMPLEFREQ = 16000 # 16Khz samples -SAMPLERATE = AL.RATE_16000 -NEEDBUFFERED = SAMPLEFREQ # Buffer 1 second of sound -BUFFERSIZE = NEEDBUFFERED*4 # setqueuesize() par for 2 second sound - -AVSYNCPORT = 10000 # Port for time syncing -AVCTLPORT = 10001 # Port for record start/stop - -def main(): - if len(sys.argv) <> 3: - print 'Usage: ', sys.argv[0], 'videohostname soundfile' - sys.exit(1) - # - ofile = open(sys.argv[2], 'w') - # - globaltime = vtime.VTime().init(0,sys.argv[1],AVSYNCPORT) - # - ctl = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) - ctl.bind((socket.gethostname(),AVCTLPORT)) - # - inp = openmic() - # - out = 0 # Open aiff file - # - while 1: - if mainloop(None, ctl, inp, out, globaltime): - break - if mainloop(ofile, ctl, inp, out, globaltime): - break - pass # Close aiff file - sys.exit(0) -# -def openmic(): - conf = al.newconfig() - conf.setqueuesize(BUFFERSIZE) - conf.setwidth(AL.SAMPLE_16) - conf.setchannels(AL.MONO) - return al.openport('micr','r',conf) -# -def mainloop(ofile, ctl, inp, out, globaltime): - # - # Wait for sync packet, keeping 1-2 seconds of sound in the - # buffer - # - totsamps = 0 - totbytes = 0 - starttime = time.millitimer() - while 1: - time.millisleep(SLEEPTIME) - if ctl.avail(): - break - nsamples = inp.getfilled()-NEEDBUFFERED - if nsamples>0: - data = inp.readsamps(nsamples) - totsamps = totsamps + nsamples - totbytes = totbytes + len(data) - if ofile <> None: - ofile.write(data) - # - # Compute his starttime and the timestamp of the first byte in the - # buffer. Discard all buffered data upto his starttime - # - startstop,histime = eval(ctl.recv(100)) - if (ofile == None and startstop == 0) or \ - (ofile <> None and startstop == 1): - print 'Sync error: saving=',save,' request=',startstop - sys.exit(1) - filllevel = inp.getfilled() - filltime = time.millitimer() - filltime = filltime - filllevel / (SAMPLEFREQ/1000) - starttime = globaltime.his2mine(histime) - nsamples = starttime - filltime - if nsamples < 0: - print 'Start/stop signal came too late' - sys.exit(1) - nsamples = nsamples * (SAMPLEFREQ / 1000) - data = inp.readsamps(nsamples) - totsamps = totsamps + nsamples - totbytes = totbytes + len(data) - print 'Time: ', time.millitimer()-starttime, ', Bytes: ', totbytes, ', Samples: ', totsamps - if ofile <> None: - ofile.write(data) - return (startstop == 2) - -main() diff --git a/Demo/sgi/video/tomono.c b/Demo/sgi/video/tomono.c deleted file mode 100755 index 546af68afd..0000000000 --- a/Demo/sgi/video/tomono.c +++ /dev/null @@ -1,165 +0,0 @@ -#include - -long *bm; -long *nbm; -long h, w; -int nh, nw; -long factor; - -#define OC(x,xi) ((x)*factor+(xi)) -#define BM(x,xi,y,yi) bm[OC(y,yi)*w+OC(x,xi)] - -#define COMP(r,g,b) ((r) | ((g)<<8) | ((b) << 16)) - -#define R(comp) ((comp) & 0xff) -#define G(comp) (((comp)>>8) & 0xff) -#define B(comp) (((comp)>>16) & 0xff) - -#define CHOICEFUNC(np1, np2) ( random() & 1 ) - -int inlevels = 3*255; -int outlevels = 1; - -main(argc, argv) - char **argv; -{ - char lbuf[100]; - int x, y, xi, yi; - int num; - int r, g, b; - long data; - int i; - double greyness; - int inpixels, outpixels; - int resid; - - setvbuf(stdout, 0, _IOFBF, 1024*128); - if( argc != 2) { - fprintf(stderr, "Usage: tomono factor\n"); - exit(1); - } - factor = atoi(argv[1]); - gets(lbuf); - if ( sscanf(lbuf, "(%d,%d)", &w, &h) != 2) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - nh = h / factor; - nw = w / factor; - printf("(%d,%d)\n", nw, nh); - if ( (bm = (long *)malloc(h*w*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - if ( (nbm = (long *)malloc(nh*nw*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - while( !feof(stdin) ) { - gets(lbuf); - if ( feof(stdin) ) break; - puts(lbuf); - fprintf(stderr, "Reading %d\n", h*w*sizeof(long)); - if ( (i=fread(bm, 1, h*w*sizeof(long), stdin)) != h*w*sizeof(long)) { - fprintf(stderr, "%s: short read, %d wanted %d\n", argv[0], - i, h*w*sizeof(long)); - exit(1); - } - /* - ** Compute picture blackness. - */ - inpixels = 0; - inpixels = countpixels(0,0,w,h); - greyness = (double)inpixels/(h*w*inlevels); - fprintf(stderr, "%3.1f%% grey\n", 100.0*greyness); - outpixels = (int)(greyness*outlevels*nh*nw); - fprintf(stderr, "Inpixels: %d (%d) Outpixels %d\n", inpixels, inpixels/inlevels, outpixels); - resid = fillpixels(0,0,nw,nh,0,0,w,h,outpixels); - if ( resid > 1 ) fprintf(stderr, "Residue: %d pixels\n", resid); - fprintf(stderr, "Writing %d\n", (nh*nw)*sizeof(long)); - fwrite(nbm, 1, (nh*nw)*sizeof(long), stdout); - } - exit(0); -} - -countpixels(x0,y0,x1,y1) -{ - int x, y, tot, data; - - tot = 0; - for( y=y0; y= x1 && y0+1 >= y1 ) { - if ( npixels ) { - nbm[y0*nw+x0] = 0xffffff; -/* fprintf(stderr, "->%d,%d\n", x0,y0); */ - return npixels - 1; - } - return 0; - } - if ( x1-x0 < y1-y0 ) { - if ( y1 - y0 <= 2 ) - m = y0 + 1; - else - m = y0+1+(random()%(y1-y0-1)); -/* fprintf(stderr,"%d,%d %d,%d Y %d\n", x0, x1, y0, y1, m); */ - /* om = (oy0+oy1)/2; */ om = m; - p1 = countpixels(ox0,oy0,ox1,om); - p2 = countpixels(ox0,om,ox1,oy1); - np1 = (int)(((float)p1/(p1+p2))*npixels); - np2 = (int)(((float)p2/(p1+p2))*npixels); - rp = npixels - np1 - np2; - if ( rp ) { - np1 += rp/2; - rp = rp - rp/2; - np2 += rp; - } - resid = 0; - if ( CHOICEFUNC(np1, np2) ) { - resid = fillpixels(x0,y0,x1,m,ox0,oy0,ox1,om,np1+resid); - resid = fillpixels(x0,m,x1,y1,ox0,om,ox1,oy1,np2+resid); - } else { - resid = fillpixels(x0,m,x1,y1,ox0,om,ox1,oy1,np2+resid); - resid = fillpixels(x0,y0,x1,m,ox0,oy0,ox1,om,np1+resid); - } - } else { - if ( x1 - x0 <= 2 ) - m = x0 + 1; - else - m = x0+1+(random()%(x1-x0-1)); -/* fprintf(stderr,"%d,%d %d,%d X %d\n", x0, x1, y0, y1, m); */ - /* om = (ox0+ox1)/2; */ om = m; - p1 = countpixels(ox0,oy0,om,oy1); - p2 = countpixels(om,oy0,ox1,oy1); - np1 = (int)(((float)p1/(p1+p2))*npixels); - np2 = (int)(((float)p2/(p1+p2))*npixels); - rp = npixels - np1 - np2; - if ( rp ) { - np1 += rp/2; - rp = rp - rp/2; - np2 += rp; - } - resid = 0; - if ( CHOICEFUNC(np1, np2) ) { - resid = fillpixels(x0,y0,m,y1,ox0,oy0,om,oy1,np1+resid); - resid = fillpixels(m,y0,x1,y1,om,oy0,ox1,oy1,np2+resid); - } else { - resid = fillpixels(m,y0,x1,y1,om,oy0,ox1,oy1,np2+resid); - resid = fillpixels(x0,y0,m,y1,ox0,oy0,om,oy1,np1+resid); - } - } - return resid; -} diff --git a/Demo/sgi/video/tv.py b/Demo/sgi/video/tv.py deleted file mode 100755 index da4bacbb63..0000000000 --- a/Demo/sgi/video/tv.py +++ /dev/null @@ -1,79 +0,0 @@ -import string - -from socket import * -from gl import * -from GL import * -from DEVICE import * -from time import millisleep, millitimer - -PORT = 5555 - -PF = 2 # packfactor -HS = 40 # Header size - -def testimage(): - RGBcolor(0, 0, 0) - clear() - RGBcolor(0, 255, 0) - cmov2i(10, 10) - charstr('Waiting...') - -def reshape(): - reshapeviewport() - w, h = getsize() - ortho2(0, w, 0, h) - testimage() - return w, h - -def main(): - s = socket(AF_INET, SOCK_DGRAM) - s.bind('', PORT) - - foreground() - wid = winopen('tv') - RGBmode() - gconfig() - qdevice(ESCKEY) - - oldw, oldh = getsize() - ortho2(0, oldw, 0, oldh) - testimage() - - t1 = millitimer() - - while 1: - if qtest(): - dev, val = qread() - if dev == ESCKEY: - winclose(wid) - return - elif dev == REDRAW: - oldw, oldh = reshape() - elif s.avail(): - data = s.recv(17000) - header = string.strip(data[:HS]) - w, h, pf, x1, y1, x2, y2 = eval(header) - if (w, h) <> (oldw, oldh): - x, y = getorigin() - x, y = x-1, y+21 # TWM correction - winposition(x, x+w-1, y+oldh-h, y+oldh-1) - oldw, oldh = reshape() - data2 = data[HS:] - dx = (x2-x1+1)/pf - dy = (y2-y1+1)/pf - data3 = unpackrect(dx, dy, 1, data2) - rectzoom(pf, pf) - lrectwrite(x1, y1, x1+dx-1, y1+dy-1, data3) - t1 = millitimer() - else: - t2 = millitimer() - if t2-t1 >= 5000: - testimage() - t1 = t2 - else: - millisleep(10) - - winclose(wid) - return data - -main() diff --git a/Demo/sgi/video/v2i.c b/Demo/sgi/video/v2i.c deleted file mode 100755 index 5f8f3b5dec..0000000000 --- a/Demo/sgi/video/v2i.c +++ /dev/null @@ -1,79 +0,0 @@ -/* Convert the first image of a CMIF video movie file to SGI .rgb format. - usage: v2i videofile imagefile [planemask] - link with -limage -*/ - -#include -#include - -long bm[1280]; -short rb[1280], gb[1280], bb[1280]; -long w, h, pf; - -#define R(comp) ((comp) & 0xff) -#define G(comp) (((comp)>>8) & 0xff) -#define B(comp) (((comp)>>16) & 0xff) - -main(argc, argv) - char **argv; -{ - char lbuf[100]; - int x, y; - int i; - IMAGE * of; - int pmask; - - if( argc != 3 && argc != 4) { - fprintf(stderr, "Usage: v2i videofile imgfile [planemask]\n"); - exit(2); - } - if ( argc == 4) - pmask = atoi(argv[3]); - else - pmask = 7; - if ( freopen(argv[1], "r", stdin) == NULL ) { - perror(argv[1]); - exit(1); - } - if (fgets(lbuf, sizeof lbuf, stdin) == NULL) { - fprintf(stderr, "Immediate EOF\n"); - exit(1); - } - if (strncmp(lbuf, "CMIF", 4) == 0) { - /* Skip optional header line */ - if (fgets(lbuf, sizeof lbuf, stdin) == NULL) { - fprintf(stderr, "Immediate EOF after header\n"); - exit(1); - } - } - pf = 2; /* Default */ - if ( sscanf(lbuf, "(%d,%d,%d)", &w, &h, &pf) < 2) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - fgets(lbuf, sizeof lbuf, stdin); /* Skip time info */ - if ( w > 1280 ) { - fprintf(stderr, "%s: Sorry, too wide\n", argv[0]); - exit(1); - } - if ( (of=iopen(argv[2], "w", RLE(1), 3, w, h, 3)) == 0) { - perror(argv[2]); - exit(1); - } - for( y=0; y 2: - usage() - [ifile, ofile] = args - print 'open film ', ifile - ifilm = VFile.VinFile().init(ifile) - print 'open output ', ofile - ofilm = VFile.VoutFile().init(ofile) - - ofilm.setinfo(ifilm.getinfo()) - - use_grabber = 0 - continuous = 0 - tomono = 0 - tomonodither = 0 - for o, a in opts: - if o == '-t': - ofilm.format = a - use_grabber = 1 - if o == '-a': - continuous = 1 - if o == '-m': - if ifilm.format <> 'grey': - print '-m only supported for greyscale' - sys.exit(1) - tomono = 1 - treshold = string.atoi(a) - ofilm.format = 'mono' - if o == '-d': - if ifilm.format <> 'grey': - print '-m only supported for greyscale' - sys.exit(1) - tomonodither = 1 - ofilm.format = 'mono' - - ofilm.writeheader() - # - prefsize(ifilm.width, ifilm.height) - w = winopen(ifile) - qdevice(KEYBD) - qdevice(ESCKEY) - qdevice(WINQUIT) - qdevice(WINSHUT) - print 'qdevice calls done' - # - help() - # - time, data, cdata = ifilm.getnextframe() - ifilm.showframe(data, cdata) - iframe = 1 - report(time, iframe) - # - while 1: - if continuous: - dev = KEYBD - else: - dev, val = qread() - if dev in (ESCKEY, WINQUIT, WINSHUT): - break - if dev == REDRAW: - reshapeviewport() - elif dev == KEYBD: - if continuous: - c = '0' - else: - c = chr(val) - #XXX Debug - if c == 'R': - c3i(255,0,0) - clear() - if c == 'G': - c3i(0,255,0) - clear() - if c == 'B': - c3i(0,0,255) - clear() - if c == 'w' or continuous: - if use_grabber: - data, cdata = ofilm.grabframe() - if tomono: - data = imageop.grey2mono(data, \ - ifilm.width, ifilm.height, \ - treshold) - if tomonodither: - data = imageop.dither2mono(data, \ - ifilm.width, ifilm.height) - ofilm.writeframe(time, data, cdata) - print 'Frame', iframe, 'written.' - if c == 'n' or continuous: - try: - time,data,cdata = ifilm.getnextframe() - ifilm.showframe(data, cdata) - iframe = iframe+1 - report(time, iframe) - except EOFError: - print 'EOF' - if continuous: - break - ringbell() - elif dev == INPUTCHANGE: - pass - else: - print '(dev, val) =', (dev, val) - ofilm.close() - -main() diff --git a/Demo/sgi/video/video.doc b/Demo/sgi/video/video.doc deleted file mode 100755 index 982c008f7e..0000000000 --- a/Demo/sgi/video/video.doc +++ /dev/null @@ -1,109 +0,0 @@ - CMIF video tools - -This document gives a quick introduction to some of the tools useful -for recording, editing and playing back video data in CMIF video -format. All the tools mentioned currently live in /ufs/guido/bin/sgi. -A description of the CMIF video file format can be found in -/ufs/jack/cmif-film.ms. - - Recording video - -There are two tools to record video, Vrec and and Vrecb. Vrec does -continuous capture, but can capture at most 15 frames per second. -Vrecb uses burst capture, enabling it to capture all frames. It -captures to main memory, however, so it cannot handle long video -fragments. The following options are common to both programs: - - -r rate Capture one out of 'rate' frames. Default (and - minimum) is 1 for Vrecb, 2 for Vrec. There are some - caveats for recording PAL, see below. - -w width Set initial window width (and height, implicitly). - -g bits Create greyscale film in stead of 8-bit dithered color - film. Allowable values for 'bits' are 2, 4 or 8. - -m Create monochrome dithered film. These look horrible. - -M threshold Create monochrome thresholded film with specified - threshold (in range 0..255). - -G Create 2-bit dithered greyscale film. - -f Capture fields in stead of frames. The film is created - in such a way that the picture will be suitably - enlarged on playback, so aspect ratio, etc. are - maintained. - -d Drop fields if they would cause data from two video - fields to be combined. See the section on PAL for more - details. - -Options for Vrec: - -a Record audio as well. You will have to twiddle audio - and video later if you want lipsync playback. - -q queuesize Set size of the video board circular buffer. A little - experimentation with this may lead to more video being - captured, but not always. - -P frames Preallocate diskspace for 'frames' images. This may - enable you to capture more frames. - -Options for Vrecb: - -n number Capture 'number' frames. Default is 60 (2 seconds). - -Both programs accept a filename to store the video on (default -film.video) and Vrec also accepts an audio file name (default -film.aiff). When you want to record you press the left mouse button. -Vrec stops recording when you release the mouse button and Vrecb stops -after the predetermined number of frames have been recorded. During -recording the picture may look funny, but do not let this worry you, -the film will be ok. - -After recording and saving, Vrec will print the deltas of the field -numbers recorded. A list of '4 4 4 4'... means that all possible -frames (one out of two) have been recorded. Vrecb will tell you how -many duplicate fields have been skipped. See below on PAL useage -again. - - PAL caveats - -The IndigoVideo board converts the incoming video signal to the 60Hz -(59.something, actually) display rate. All further operations, -including capture, are done with respect to display rate. This is -especially bothersome in the case of PAL video, since it means one out -of 5 frames will be duplicated. Together with the fact that, in -continuous capture, you can only capture every second frame this leads -to strange and wondrous effects. The frame numbers returned by the -video board (and displayed by Vrec) are display frame numbers, and so -bear only a very complicated (and probably non-deterministic) relation -to PAL frame numbers. For recording simple videos this is probably no -problem. You can use Vrec and try using -d to see which gives the best -result. On the other hand, if you need every frame and no duplicates -either you have to use Vrecb and supply the -d and -f option. This -will give you exactly the fields as they appeared on the PAL tape. - - Video playback - -The easiest way to play back a video is to use Vplay. Calling it with -an argument of -? will make it list all its options. A few options may -need a bit of explanation: - -M magnify Magnify the images by the given factor. This still - takes any magnification specified in the film (if it - is a field film, for instance) in account. - -w width and - -h height Normally the window will be the correct size for the - film. You can set height and width, though, if you - want the window to be bigger. This is especially - useful if you want to record the film back to - videotape, since you can playback in a window that is - bigger than PAL size with a black background and you - will have no distracting window-manager thingies on - your videotape. - - Video Editing - -Vedit is a (very simple) video editor that allows you to select images -from the input movie and copy them to an output movie. Both input and -output films have a modest buffer that you can move around in. - -Vaddcache takes a movie and adds a frame location cache to it. This -will make some other programs run faster. - -rgb2video converts a set of SGI .rgb files to a movie. - -There are a few programs that can do image format conversion on movies -(i.e. convert an 8-bit dithered RGB movie to a greyscale movie), but -nothing very complete yet. Look at Vcopy.py for more information. diff --git a/Demo/sgi/video/video.py b/Demo/sgi/video/video.py deleted file mode 100755 index 1b81bd83f7..0000000000 --- a/Demo/sgi/video/video.py +++ /dev/null @@ -1,218 +0,0 @@ -import getopt -from gl import * -from GL import * -from DEVICE import * -import time -import sys -import al -import AL - -sys.path.append('/ufs/guido/src/video') # Increase chance to find colorsys -import colorsys - -BUFFERSIZE = 32000 - -class Struct(): pass -epoch = Struct() -epoch.correcttiming = 1 -EndOfFile = 'End of file' -bye = 'bye' - -def openspkr(): - conf = al.newconfig() - conf.setqueuesize(BUFFERSIZE) - conf.setwidth(AL.SAMPLE_16) - conf.setchannels(AL.MONO) - return al.openport('spkr','w',conf) - -def openvideo(name): - try: - f = open(name, 'r') - except: - sys.stderr.write(name + ': cannot open\n') - sys.exit(1) - line = f.readline() - if not line: raise EndOfFile - colorinfo = (8, 0, 0, 0) - if line[:4] == 'CMIF': - if line[:14] == 'CMIF video 2.0': - line = f.readline() - colorinfo = eval(line[:-1]) - line = f.readline() - x = eval(line[:-1]) - if len(x) == 3: w, h, pf = x - else: w, h = x; pf = 2 - if pf and w/pf % 4 <> 0: - sys.stderr.write( \ - 'warning: stride not a multiple of 4 -- may not work on Indigo XS\n') - return f, w, h, pf, colorinfo - -def loadframe(f,w,h,pf,af,spkr, (ybits,ibits,qbits,chrompack),mf): - line = f.readline() - if line == '': - raise EndOfFile - x = eval(line[:-1]) - if type(x) == type(0) or type(x) == type(0.0): - tijd = x - if pf == 0: - size = w*h*4 - else: - size = (w/pf) * (h/pf) - else: - tijd, size = x - data = f.read(size) - if len(data) <> size: - raise EndOfFile - if pf: - w = w/pf - h = h/pf - if chrompack: - cw = (w+chrompack-1)/chrompack - ch = (h+chrompack-1)/chrompack - chromdata = f.read(2*cw*ch) - rectzoom(pf*chrompack*mf,pf*chrompack*mf) - pixmode(PM_SIZE,16) - writemask(0x7ff - ((1< 1: - rectzoom(mf,mf) - lrectwrite(0,0,w-1,h-1,data) - # This is ugly here, but the only way to get the two - # channels started in sync - #if af <> None: - # playsound(af,spkr) - ct = time.millitimer() - epoch.epoch - if epoch.correcttiming and tijd > 0 and ct < tijd: - time.millisleep(tijd-ct) - #swapbuffers() - return tijd - -def initcmap(ybits,ibits,qbits,chrompack): - if ybits+ibits+qbits > 11: - raise 'Sorry, 11 bits max' - maxy = pow(2,ybits) - maxi = pow(2,ibits) - maxq = pow(2,qbits) - for i in range(2048,4096-256): - mapcolor(i, 0, 255, 0) - for y in range(maxy): - yv = float(y)/float(maxy-1) - for i in range(maxi): - if maxi == 1: iv = 0 - else: iv = (float(i)/float(maxi-1))-0.5 - for q in range(maxq): - if maxq == 1: qv = 0 - else: qv = (float(q)/float(maxq-1))-0.5 - index = 2048 + y + (i << ybits) + (q << (ybits+ibits)) - rv,gv,bv = colorsys.yiq_to_rgb(yv,iv,qv) - r,g,b = int(rv*255.0), int(gv*255.0), int(bv*255.0) - if index < 4096 - 256: - mapcolor(index, r,g,b) - -def playsound(af, spkr): - nsamp = spkr.getfillable() - data = af.read(nsamp*2) - spkr.writesamps(data) - -def main(): - looping = 0 - packfactor = 0 - magfactor = 1 - try: - opts, args = getopt.getopt(sys.argv[1:], 'm:p:lF') - except getopt.error: - sys.stderr.write('usage: video ' + \ - '[-l] [-p pf] [-m mag] [-F] [moviefile [soundfile [skipbytes]]]\n') - sys.exit(2) - for opt, arg in opts: - if opt == '-m': - magfactor = int(eval(arg)) - elif opt == '-p': - packfactor = int(eval(arg)) - elif opt == '-l': - looping = 1 - elif opt == '-F': - epoch.correcttiming = 0 - if args: - filename = args[0] - else: - filename = 'film.video' - f, w, h, pf, cinfo = openvideo(filename) - if 0 < packfactor <> pf: - w = w/pf*packfactor - h = h/pf*packfactor - pf = packfactor - if args[1:]: - audiofilename = args[1] - af = open(audiofilename, 'r') - spkr = openspkr() - afskip = 0 - if args[2:]: - afskip = eval(args[2]) - af.seek(afskip) - else: - af, spkr = None, None - foreground() - prefsize(w*magfactor,h*magfactor) - win = winopen(filename) - if pf: - #doublebuffer() - cmode() - else: - RGBmode() - #doublebuffer() - gconfig() - if pf: - initcmap(cinfo) - color(2048) - clear() - writemask(2047) - pixmode(PM_SIZE,8) # 8 bit pixels - qdevice(ESCKEY) - qdevice(WINSHUT) - qdevice(WINQUIT) - running = 1 - epoch.epoch = time.millitimer() - nframe = 0 - tijd = 1 - if looping: - looping = f.tell() - try: - while 1: - if running: - try: - tijd = loadframe(f, w, h, pf, af, spkr, cinfo,magfactor) - nframe = nframe + 1 - except EndOfFile: - running = 0 - t = time.millitimer() - if tijd > 0: - print 'Recorded at', - print 0.1 * int(nframe * 10000.0 / tijd), - print 'frames/sec' - print 'Played', nframe, 'frames at', - print 0.1 * int(nframe * 10000.0 / (t-epoch.epoch)), - print 'frames/sec' - if looping: - f.seek(looping) - epoch.epoch = time.millitimer() - nframe = 0 - running = 1 - if af <> None: - af.seek(afskip) - if af <> None: - playsound(af,spkr) - if not running or qtest(): - dev, val = qread() - if dev in (ESCKEY, WINSHUT, WINQUIT): - raise bye - elif dev == REDRAW: - reshapeviewport() - except bye: - pass - -main() diff --git a/Demo/sgi/video/video2rgb.py b/Demo/sgi/video/video2rgb.py deleted file mode 100755 index 7070a93342..0000000000 --- a/Demo/sgi/video/video2rgb.py +++ /dev/null @@ -1,159 +0,0 @@ -#! /ufs/guido/bin/sgi/python - -# Convert CMIF movie file(s) to a sequence of rgb images - - -# Help function - -def help(): - print 'Usage: video2rgb [options] [file] ...' - print - print 'Options:' - print '-q : quiet, no informative messages' - print '-m : create monochrome (greyscale) image files' - print '-f prefix : create image files with names "prefix0000.rgb"' - print 'file ... : file(s) to convert; default film.video' - - -# Imported modules - -import sys -sys.path.append('/ufs/jack/src/av/video') # Increase chance of finding VFile -import VFile -import time -import getopt -import string -import imgfile -import imgconv - - -# Global options - -quiet = 0 -prefix = 'film' -seqno = 0 -mono = 0 - - -# Main program -- mostly command line parsing - -def main(): - global quiet, prefix, mono - - # Parse command line - try: - opts, args = getopt.getopt(sys.argv[1:], 'qmf:') - except getopt.error, msg: - sys.stdout = sys.stderr - print 'Error:', msg, '\n' - help() - sys.exit(2) - - # Interpret options - try: - for opt, arg in opts: - if opt == '-q': quiet = 1 - if opt == '-f': prefix = arg - if opt == '-m': mono = 1 - except string.atoi_error: - sys.stdout = sys.stderr - print 'Option', opt, 'requires integer argument' - sys.exit(2) - - # Process all files - if not args: args = ['film.video'] - sts = 0 - for filename in args: - sts = (process(filename) or sts) - - # Exit with proper exit status - sys.exit(sts) - - -# Process one movie file - -def process(filename): - try: - vin = VFile.VinFile(filename) - except IOError, msg: - sys.stderr.write(filename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(filename + ': EOF in video header\n') - return 1 - - if not quiet: - vin.printinfo() - - width, height = int(vin.width), int(vin.height) - - try: - if mono: - cf = imgconv.getconverter(vin.format, 'grey') - else: - cf = imgconv.getconverter(vin.format, 'rgb') - except imgconv.error: - print 'Sorry, no converter available for type',vin.format - return - - if mono: - depth = 1 - bpp = 1 - else: - depth = 3 - bpp = 4 - - convert(vin, cf, width, height, depth, bpp, vin.packfactor) - -def convert(vin, cf, width, height, depth, bpp, pf): - global seqno - - if type(pf) == type(()): - xpf, ypf = pf - elif pf == 0: - xpf = ypf = 1 - else: - xpf = ypf = pf - while 1: - try: - time, data, cdata = vin.getnextframe() - except EOFError: - return - if cdata: - print 'Film contains chromdata!' - return - data = cf(data, width/xpf, height/abs(ypf)) - if pf: - data = applypackfactor(data, width, height, pf, bpp) - s = `seqno` - s = '0'*(4-len(s)) + s - fname = prefix + s + '.rgb' - seqno = seqno + 1 - if not quiet: - print 'Writing',fname,'...' - imgfile.write(fname, data, width, height, depth) - -def applypackfactor(image, w, h, pf, bpp): - import imageop - if type(pf) == type(()): - xpf, ypf = pf - elif pf == 0: - xpf = ypf = 1 - else: - xpf = ypf = pf - w1 = w/xpf - h1 = h/abs(ypf) - if ypf < 0: - ypf = -ypf - image = imageop.crop(image, bpp, w1, h1, 0, h1-1, w1-1, 0) - return imageop.scale(image, bpp, w1, h1, w, h) - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/vinfo.py b/Demo/sgi/video/vinfo.py deleted file mode 100755 index 7f98237a97..0000000000 --- a/Demo/sgi/video/vinfo.py +++ /dev/null @@ -1,90 +0,0 @@ -from gl import * -from GL import * -from DEVICE import * -import time -import sys -import getopt - -class Struct(): pass -epoch = Struct() -EndOfFile = 'End of file' -bye = 'bye' - -def openvideo(filename): - f = open(filename, 'r') - line = f.readline() - if not line: raise EndOfFile - if line[:4] == 'CMIF': line = f.readline() - x = eval(line[:-1]) - if len(x) == 3: w, h, pf = x - else: w, h = x; pf = 2 - return f, w, h, pf - -def loadframe(f, w, h, pf): - line = f.readline() - if line == '': - raise EndOfFile - x = eval(line[:-1]) - if type(x) == type(0) or type(x) == type(0.0): - tijd = x - if pf == 0: - size = w*h*4 - else: - size = (w/pf) * (h/pf) - else: - tijd, size = x - f.seek(size, 1) - return tijd - -def main(): - delta = 0 - short = 0 - try: - opts, names = getopt.getopt(sys.argv[1:], 'ds') - except getopt.error, msg: - sys.stderr.write(msg + '\n') - sys.stderr.write('usage: vinfo [-d] [-s] [file] ...\n') - sys.exit(2) - for opt, arg in opts: - if opt == '-d': delta = 1 # print delta between frames - elif opt == '-s': short = 1 # short: don't print times - if names == []: - names = ['film.video'] - for name in names: - try: - f, w, h, pf = openvideo(name) - except: - sys.stderr.write(name + ': cannot open\n') - continue - if pf == 0: - size = w*h*4 - else: - size = (w/pf) * (h/pf) - print name, ':', w, 'x', h, '; pf =', pf, ', size =', size, - if pf == 0: - print '(color)', - else: - print '(' + `(w/pf)` + 'x' + `(h/pf)` + ')', - if (w/pf)%4 <> 0: print '!!!', - print - num = 0 - try: - otijd = 0 - while not short: - try: - tijd = loadframe(f, w, h, pf) - if delta: print '\t' + `tijd-otijd`, - else: print '\t' + `tijd`, - otijd = tijd - num = num + 1 - if num % 8 == 0: - print - except EndOfFile: - raise bye - except bye: - pass - if num % 8 <> 0: - print - f.close() - -main() diff --git a/Demo/sgi/video/vpregs.py b/Demo/sgi/video/vpregs.py deleted file mode 100755 index d33f1fe93e..0000000000 --- a/Demo/sgi/video/vpregs.py +++ /dev/null @@ -1,28 +0,0 @@ -VID_VP = 0x1000000 - -# Set vp1 register tokens -VP_GBXORG = (VID_VP +0x01) -VP_GBYORG = (VID_VP +0x02) -VP_FBXORG = (VID_VP +0x03) -VP_FBYORG = (VID_VP +0x04) -VP_WIDTH = (VID_VP +0x05) -VP_HEIGHT = (VID_VP +0x06) -VP_PIXCNT = (VID_VP +0x07) -VP_HBLANK = (VID_VP +0x08) -VP_VBLANK = (VID_VP +0x09) -VP_BRITE = (VID_VP +0x0A) -VP_CONT = (VID_VP +0x0B) -VP_HUE = (VID_VP +0x0C) -VP_SAT = (VID_VP +0x0D) -VP_ALPHA = (VID_VP +0X0E) -VP_FGMODE = (VID_VP +0x0F) -VP_MAPSRC = (VID_VP +0x10) -VP_MAPADD = (VID_VP +0x11) -VP_MAPRED = (VID_VP +0x12) -VP_MAPGREEN = (VID_VP +0x13) -VP_MAPBLUE = (VID_VP +0x14) -VP_MAPSTROBE = (VID_VP +0x15) -VP_DIGVAL = (VID_VP +0x16) -VP_STATUS0 = (VID_VP +0x17) -VP_STATUS1 = (VID_VP +0x18) -VP_CMD = (VID_VP +0x19) diff --git a/Demo/sgi/video/vtime.py b/Demo/sgi/video/vtime.py deleted file mode 100755 index c333e57983..0000000000 --- a/Demo/sgi/video/vtime.py +++ /dev/null @@ -1,106 +0,0 @@ -# -# Module vtime - Keep virtual time between two nodes. -# -# We try for synchronised clocks by sending a packet of the for -# (1,mytime,0) to the other side, and waiting (at most) a second for -# a reply. This reply has the form (2,mytime,histime), and we can -# estimate the time difference by defining histime to be exactly half-way -# between the time we sent our message and got our reply. We send a -# final (3,mynewtime,histime) message to allow the other side to do the -# same computations. -# -# Note that the protocol suffers heavily from the 2-army problem. -# It'll have to do until I can read up on time-sync protocols, though. -# -from socket import * -import time - -MSGSIZE = 100 -MSGTIMEOUT = 1000 - -recv_timeout = 'receive timeout' -bad_connect = 'Bad connection' - -def timeavg(a,b): - return int((long(a)+b)/2L) -def tryrecv(s): - cnt = 0 - while 1: - if s.avail(): - return s.recvfrom(MSGSIZE) - time.millisleep(100) - cnt = cnt + 100 - if cnt > MSGTIMEOUT: - raise recv_timeout - -class VTime(): - def init(self,(client,host,port)): - s = socket(AF_INET, SOCK_DGRAM) - host = gethostbyname(host) - localhost = gethostbyname(gethostname()) - raddr = (host,port) - s.bind((localhost,port)) - if client: - # - # We loop here because we want the *second* measurement - # for accuracy - for loopct in (0,2): - curtijd = time.millitimer() - check = `(loopct,curtijd,0)` - s.sendto(check,raddr) - while 1: - try: - if loopct: - data, other = s.recvfrom(MSGSIZE) - else: - data, other = tryrecv(s) - newtijd = time.millitimer() - if other <> raddr: - print 'Someone else syncing to us: ', other - raise bad_connect - data = eval(data) - if data[:2] == (loopct+1,curtijd): - break - if data[0] <> 2: - print 'Illegal sync reply: ', data - raise bad_connect - except recv_timeout: - curtijd = time.millitimer() - check = `(loopct,curtijd,0)` - s.sendto(check,raddr) - histime = data[2] - s.sendto(`(4,newtijd,histime)`,raddr) - mytime = timeavg(curtijd,newtijd) - #mytime = curtijd - self.timediff = histime - mytime - else: - while 1: - data,other = s.recvfrom(MSGSIZE) - if other <> raddr: - print 'Someone else syncing to us: ', other, ' Wanted ', raddr - raise bad_connect - data = eval(data) - if data[0] in (0,2): - curtijd = time.millitimer() - s.sendto(`(data[0]+1,data[1],curtijd)`,raddr) - elif data[0] == 4: - newtijd = time.millitimer() - histime = data[1] - mytime = timeavg(curtijd,newtijd) - #mytime = curtijd - self.timediff = histime-mytime - break - else: - print 'Funny data: ', data - raise bad_connect - return self - # - def his2mine(self,tijd): - return tijd - self.timediff - # - def mine2his(self, tijd): - return tijd + self.timediff - -def test(clt, host, port): - xx = VTime().init(clt,host,port) - print 'Time diff: ', xx.his2mine(0) diff --git a/Demo/sgi/video/watchcursor.py b/Demo/sgi/video/watchcursor.py deleted file mode 100755 index aae3f85d50..0000000000 --- a/Demo/sgi/video/watchcursor.py +++ /dev/null @@ -1,45 +0,0 @@ -# Define a 16x16 cursor looking like a watch - -# X11 bitmap file: -##define x_width 16 -##define x_height 16 -#static char x_bits[] = { -# 0xf0, 0x0f, 0xf8, 0x1f, 0x1c, 0x38, 0x8e, 0x71, 0x87, 0xe1, 0x83, 0xc1, -# 0x83, 0xc1, 0xf3, 0xc1, 0xf3, 0xc1, 0x03, 0xc0, 0x03, 0xc0, 0x07, 0xe0, -# 0x0e, 0x70, 0x1c, 0x38, 0xf8, 0x1f, 0xf0, 0x0f}; - - -watch = [ \ - 0x0ff0,\ - 0x1ff8,\ - 0x381c,\ - 0x718e,\ - 0xe187,\ - 0xc183,\ - 0xc183,\ - 0xc1f3,\ - 0xc1f3,\ - 0xc003,\ - 0xc003,\ - 0xe007,\ - 0x700e,\ - 0x381c,\ - 0x1ff8,\ - 0x0ff0,\ - ] - -watch.reverse() # Turn it upside-down - -def defwatch(index): - import gl - gl.defcursor(index, watch*8) - gl.curorigin(index, 8, 8) - -def test(): - import gl - gl.foreground() - gl.winopen('test watchcursor') - defwatch(1) - gl.setcursor(1, 0, 0) - import time - time.sleep(10) diff --git a/Demo/sockets/ChangeLog b/Demo/sockets/ChangeLog deleted file mode 100755 index c1d41b1f67..0000000000 --- a/Demo/sockets/ChangeLog +++ /dev/null @@ -1,35 +0,0 @@ -Mon Nov 16 17:55:30 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* Restructured mcast. - -Tue Nov 3 13:08:41 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* Fixed ftp.py to use 'global' instead of a hack - -25-Oct-1992 - -* Added gopher.py - -2-Oct-1992 - -* Changed /usr/local/python to /usr/local/bin/python - -Thu Sep 24 12:33:56 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* Improved computation of mcast group bytes (use regsub.gsub()) - -Tue Sep 8 23:20:51 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* Added mcast.py and IN.py. - -* Use setsockopt() instead of allowbroadcast() in broadcast.py. - -Mon Aug 10 12:45:43 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* README: added broadcast.py, ftp.py, radio.py - -------------------------------------------------------------------------------- -^^^ Log entries after release of 0.9.6 ^^^ -------------------------------------------------------------------------------- - - diff --git a/Demo/sockets/README b/Demo/sockets/README deleted file mode 100644 index e844ac6be7..0000000000 --- a/Demo/sockets/README +++ /dev/null @@ -1,20 +0,0 @@ -This directory contains some demonstrations of the socket module: - -broadcast.py Broadcast the time to radio.py. -echosvr.py About the simplest TCP server possible. -finger.py Client for the 'finger' protocol. -ftp.py A very simple ftp client. -gopher.py A simple gopher client. -telnet.py Client for the 'telnet' protocol. -throughput.py Client and server to measure TCP throughput. -udpecho.py Client and server for the UDP echo protocol. -radio.py Receive time broadcasts from broadcast.py. - -The following file is only relevant on SGI machines (or other systems -that support multicast): - -mcast.py A Python translation of - /usr/people/4Dgifts/examples/network/mcast.c - (Note that IN.py is in ../../lib/sgi.) - -See also ../../lib/nntp.py for another example of socket code. diff --git a/Demo/sockets/broadcast.py b/Demo/sockets/broadcast.py deleted file mode 100755 index a02b081a2e..0000000000 --- a/Demo/sockets/broadcast.py +++ /dev/null @@ -1,17 +0,0 @@ -# Send UDP broadcast packets - -MYPORT = 50000 - -import sys, time -from socket import * - -s = socket(AF_INET, SOCK_DGRAM) -s.bind(('', 0)) -s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) - -while 1: - data = `time.time()` + '\n' - s.sendto(data, ('', MYPORT)) - time.sleep(2) - - diff --git a/Demo/sockets/echosvr.py b/Demo/sockets/echosvr.py deleted file mode 100755 index acf0a393df..0000000000 --- a/Demo/sockets/echosvr.py +++ /dev/null @@ -1,31 +0,0 @@ -#! /usr/local/bin/python - -# Python implementation of an 'echo' tcp server: echo all data it receives. -# -# This is the simplest possible server, servicing a single request only. - -import sys -from socket import * - -# The standard echo port isn't very useful, it requires root permissions! -# ECHO_PORT = 7 -ECHO_PORT = 50000 + 7 -BUFSIZE = 1024 - -def main(): - if len(sys.argv) > 1: - port = int(eval(sys.argv[1])) - else: - port = ECHO_PORT - s = socket(AF_INET, SOCK_STREAM) - s.bind('', port) - s.listen(1) - conn, (remotehost, remoteport) = s.accept() - print 'connected by', remotehost, remoteport - while 1: - data = conn.recv(BUFSIZE) - if not data: - break - conn.send(data) - -main() diff --git a/Demo/sockets/finger.py b/Demo/sockets/finger.py deleted file mode 100755 index 71e307ffa6..0000000000 --- a/Demo/sockets/finger.py +++ /dev/null @@ -1,58 +0,0 @@ -#! /usr/local/bin/python - -# Python interface to the Internet finger daemon. -# -# Usage: finger [options] [user][@host] ... -# -# If no host is given, the finger daemon on the local host is contacted. -# Options are passed uninterpreted to the finger daemon! - - -import sys, string -from socket import * - - -# Hardcode the number of the finger port here. -# It's not likely to change soon... -# -FINGER_PORT = 79 - - -# Function to do one remote finger invocation. -# Output goes directly to stdout (although this can be changed). -# -def finger(host, args): - s = socket(AF_INET, SOCK_STREAM) - s.connect(host, FINGER_PORT) - s.send(args + '\n') - while 1: - buf = s.recv(1024) - if not buf: break - sys.stdout.write(buf) - sys.stdout.flush() - - -# Main function: argument parsing. -# -def main(): - options = '' - i = 1 - while i < len(sys.argv) and sys.argv[i][:1] == '-': - options = options + sys.argv[i] + ' ' - i = i+1 - args = sys.argv[i:] - if not args: - args = [''] - for arg in args: - if '@' in arg: - at = string.index(arg, '@') - host = arg[at+1:] - arg = arg[:at] - else: - host = '' - finger(host, options + arg) - - -# Call the main function. -# -main() diff --git a/Demo/sockets/ftp.py b/Demo/sockets/ftp.py deleted file mode 100755 index 2d492398c7..0000000000 --- a/Demo/sockets/ftp.py +++ /dev/null @@ -1,146 +0,0 @@ -# A simple FTP client. -# -# The information to write this program was gathered from RFC 959, -# but this is not a complete implementation! Yet it shows how a simple -# FTP client can be built, and you are welcome to extend it to suit -# it to your needs... -# -# How it works (assuming you've read the RFC): -# -# User commands are passed uninterpreted to the server. However, the -# user never needs to send a PORT command. Rather, the client opens a -# port right away and sends the appropriate PORT command to the server. -# When a response code 150 is received, this port is used to receive -# the data (which is written to stdout in this version), and when the -# data is exhausted, a new port is opened and a corresponding PORT -# command sent. In order to avoid errors when reusing ports quickly -# (and because there is no s.getsockname() method in Python yet) we -# cycle through a number of ports in the 50000 range. - - -import sys, posix, string -from socket import * - - -BUFSIZE = 1024 - -# Default port numbers used by the FTP protocol. -# -FTP_PORT = 21 -FTP_DATA_PORT = FTP_PORT - 1 - -# Change the data port to something not needing root permissions. -# -FTP_DATA_PORT = FTP_DATA_PORT + 50000 - - -# Main program (called at the end of this file). -# -def main(): - hostname = sys.argv[1] - control(hostname) - - -# Control process (user interface and user protocol interpreter). -# -def control(hostname): - # - # Create control connection - # - s = socket(AF_INET, SOCK_STREAM) - s.connect(hostname, FTP_PORT) - f = s.makefile('r') # Reading the replies is easier from a file... - # - # Control loop - # - r = None - while 1: - code = getreply(f) - if code in ('221', 'EOF'): break - if code == '150': - getdata(r) - code = getreply(f) - r = None - if not r: - r = newdataport(s, f) - cmd = getcommand() - if not cmd: break - s.send(cmd + '\r\n') - - -# Create a new data port and send a PORT command to the server for it. -# (Cycle through a number of ports to avoid problems with reusing -# a port within a short time.) -# -nextport = 0 -# -def newdataport(s, f): - global nextport - port = nextport + FTP_DATA_PORT - nextport = (nextport+1) % 16 - r = socket(AF_INET, SOCK_STREAM) - r.bind(gethostbyname(gethostname()), port) - r.listen(1) - sendportcmd(s, f, port) - return r - - -# Send an appropriate port command. -# -def sendportcmd(s, f, port): - hostname = gethostname() - hostaddr = gethostbyname(hostname) - hbytes = string.splitfields(hostaddr, '.') - pbytes = [`port/256`, `port%256`] - bytes = hbytes + pbytes - cmd = 'PORT ' + string.joinfields(bytes, ',') - s.send(cmd + '\r\n') - code = getreply(f) - - -# Process an ftp reply and return the 3-digit reply code (as a string). -# The reply should be a line of text starting with a 3-digit number. -# If the 4th char is '-', it is a multi-line reply and is -# terminate by a line starting with the same 3-digit number. -# Any text while receiving the reply is echoed to the file. -# -def getreply(f): - line = f.readline() - if not line: return 'EOF' - print line, - code = line[:3] - if line[3:4] == '-': - while 1: - line = f.readline() - if not line: break # Really an error - print line, - if line[:3] == code and line[3:4] != '-': break - return code - - -# Get the data from the data connection. -# -def getdata(r): - print '(accepting data connection)' - conn, host = r.accept() - print '(data connection accepted)' - while 1: - data = conn.recv(BUFSIZE) - if not data: break - sys.stdout.write(data) - print '(end of data connection)' - -# Get a command from the user. -# -def getcommand(): - try: - while 1: - line = raw_input('ftp.py> ') - if line: return line - except EOFError: - return '' - - -# Call the main program. -# -main() diff --git a/Demo/sockets/gopher.py b/Demo/sockets/gopher.py deleted file mode 100755 index f30ab0f1c8..0000000000 --- a/Demo/sockets/gopher.py +++ /dev/null @@ -1,347 +0,0 @@ -#! /usr/local/bin/python - -# A simple gopher client. -# -# Usage: gopher [ [selector] host [port] ] - -import string -import sys -import os -import socket - -# Default selector, host and port -DEF_SELECTOR = '' -DEF_HOST = 'gopher.micro.umn.edu' -DEF_PORT = 70 - -# Recognized file types -T_TEXTFILE = '0' -T_MENU = '1' -T_CSO = '2' -T_ERROR = '3' -T_BINHEX = '4' -T_DOS = '5' -T_UUENCODE = '6' -T_SEARCH = '7' -T_TELNET = '8' -T_BINARY = '9' -T_REDUNDANT = '+' -T_SOUND = 's' - -# Dictionary mapping types to strings -typename = {'0': '', '1': '', '2': '', '3': '', \ - '4': '', '5': '', '6': '', '7': '', \ - '8': '', '9': '', '+': '', 's': ''} - -# Oft-used characters and strings -CRLF = '\r\n' -TAB = '\t' - -# Open a TCP connection to a given host and port -def open_socket(host, port): - if not port: - port = DEF_PORT - elif type(port) == type(''): - port = string.atoi(port) - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.connect((host, port)) - return s - -# Send a selector to a given host and port, return a file with the reply -def send_request(selector, host, port): - s = open_socket(host, port) - s.send(selector + CRLF) - s.shutdown(1) - return s.makefile('r') - -# Get a menu in the form of a list of entries -def get_menu(selector, host, port): - f = send_request(selector, host, port) - list = [] - while 1: - line = f.readline() - if not line: - print '(Unexpected EOF from server)' - break - if line[-2:] == CRLF: - line = line[:-2] - elif line[-1:] in CRLF: - line = line[:-1] - if line == '.': - break - if not line: - print '(Empty line from server)' - continue - typechar = line[0] - parts = string.splitfields(line[1:], TAB) - if len(parts) < 4: - print '(Bad line from server:', `line`, ')' - continue - if len(parts) > 4: - print '(Extra info from server:', parts[4:], ')' - parts.insert(0, typechar) - list.append(parts) - f.close() - return list - -# Get a text file as a list of lines, with trailing CRLF stripped -def get_textfile(selector, host, port): - list = [] - get_alt_textfile(selector, host, port, list.append) - return list - -# Get a text file and pass each line to a function, with trailing CRLF stripped -def get_alt_textfile(selector, host, port, func): - f = send_request(selector, host, port) - while 1: - line = f.readline() - if not line: - print '(Unexpected EOF from server)' - break - if line[-2:] == CRLF: - line = line[:-2] - elif line[-1:] in CRLF: - line = line[:-1] - if line == '.': - break - if line[:2] == '..': - line = line[1:] - func(line) - f.close() - -# Get a binary file as one solid data block -def get_binary(selector, host, port): - f = send_request(selector, host, port) - data = f.read() - f.close() - return data - -# Get a binary file and pass each block to a function -def get_alt_binary(selector, host, port, func, blocksize): - f = send_request(selector, host, port) - while 1: - data = f.read(blocksize) - if not data: - break - func(data) - -# A *very* simple interactive browser - -# Browser main command, has default arguments -def browser(*args): - selector = DEF_SELECTOR - host = DEF_HOST - port = DEF_PORT - n = len(args) - if n > 0 and args[0]: - selector = args[0] - if n > 1 and args[1]: - host = args[1] - if n > 2 and args[2]: - port = args[2] - if n > 3: - raise RuntimeError, 'too many args' - try: - browse_menu(selector, host, port) - except socket.error, msg: - print 'Socket error:', msg - sys.exit(1) - except KeyboardInterrupt: - print '\n[Goodbye]' - -# Browse a menu -def browse_menu(selector, host, port): - list = get_menu(selector, host, port) - while 1: - print '----- MENU -----' - print 'Selector:', `selector` - print 'Host:', host, ' Port:', port - print - for i in range(len(list)): - item = list[i] - typechar, description = item[0], item[1] - print string.rjust(`i+1`, 3) + ':', description, - if typename.has_key(typechar): - print typename[typechar] - else: - print '' - print - while 1: - try: - str = raw_input('Choice [CR == up a level]: ') - except EOFError: - print - return - if not str: - return - try: - choice = string.atoi(str) - except string.atoi_error: - print 'Choice must be a number; try again:' - continue - if not 0 < choice <= len(list): - print 'Choice out of range; try again:' - continue - break - item = list[choice-1] - typechar = item[0] - [i_selector, i_host, i_port] = item[2:5] - if typebrowser.has_key(typechar): - browserfunc = typebrowser[typechar] - try: - browserfunc(i_selector, i_host, i_port) - except (IOError, socket.error): - print '***', sys.exc_type, ':', sys.exc_value - else: - print 'Unsupported object type' - -# Browse a text file -def browse_textfile(selector, host, port): - x = None - try: - p = os.popen('${PAGER-more}', 'w') - x = SaveLines(p) - get_alt_textfile(selector, host, port, x.writeln) - except IOError, msg: - print 'IOError:', msg - if x: - x.close() - f = open_savefile() - if not f: - return - x = SaveLines(f) - try: - get_alt_textfile(selector, host, port, x.writeln) - print 'Done.' - except IOError, msg: - print 'IOError:', msg - x.close() - -# Browse a search index -def browse_search(selector, host, port): - while 1: - print '----- SEARCH -----' - print 'Selector:', `selector` - print 'Host:', host, ' Port:', port - print - try: - query = raw_input('Query [CR == up a level]: ') - except EOFError: - print - break - query = string.strip(query) - if not query: - break - if '\t' in query: - print 'Sorry, queries cannot contain tabs' - continue - browse_menu(selector + TAB + query, host, port) - -# "Browse" telnet-based information, i.e. open a telnet session -def browse_telnet(selector, host, port): - if selector: - print 'Log in as', `selector` - if type(port) <> type(''): - port = `port` - sts = os.system('set -x; exec telnet ' + host + ' ' + port) - if sts: - print 'Exit status:', sts - -# "Browse" a binary file, i.e. save it to a file -def browse_binary(selector, host, port): - f = open_savefile() - if not f: - return - x = SaveWithProgress(f) - get_alt_binary(selector, host, port, x.write, 8*1024) - x.close() - -# "Browse" a sound file, i.e. play it or save it -def browse_sound(selector, host, port): - browse_binary(selector, host, port) - -# Dictionary mapping types to browser functions -typebrowser = {'0': browse_textfile, '1': browse_menu, \ - '4': browse_binary, '5': browse_binary, '6': browse_textfile, \ - '7': browse_search, \ - '8': browse_telnet, '9': browse_binary, 's': browse_sound} - -# Class used to save lines, appending a newline to each line -class SaveLines: - def __init__(self, f): - self.f = f - def writeln(self, line): - self.f.write(line + '\n') - def close(self): - sts = self.f.close() - if sts: - print 'Exit status:', sts - -# Class used to save data while showing progress -class SaveWithProgress: - def __init__(self, f): - self.f = f - def write(self, data): - sys.stdout.write('#') - sys.stdout.flush() - self.f.write(data) - def close(self): - print - sts = self.f.close() - if sts: - print 'Exit status:', sts - -# Ask for and open a save file, or return None if not to save -def open_savefile(): - try: - savefile = raw_input( \ - 'Save as file [CR == don\'t save; |pipeline or ~user/... OK]: ') - except EOFError: - print - return None - savefile = string.strip(savefile) - if not savefile: - return None - if savefile[0] == '|': - cmd = string.strip(savefile[1:]) - try: - p = os.popen(cmd, 'w') - except IOError, msg: - print `cmd`, ':', msg - return None - print 'Piping through', `cmd`, '...' - return p - if savefile[0] == '~': - savefile = os.path.expanduser(savefile) - try: - f = open(savefile, 'w') - except IOError, msg: - print `savefile`, ':', msg - return None - print 'Saving to', `savefile`, '...' - return f - -# Test program -def test(): - if sys.argv[4:]: - print 'usage: gopher [ [selector] host [port] ]' - sys.exit(2) - elif sys.argv[3:]: - browser(sys.argv[1], sys.argv[2], sys.argv[3]) - elif sys.argv[2:]: - try: - port = string.atoi(sys.argv[2]) - selector = '' - host = sys.argv[1] - except string.atoi_error: - selector = sys.argv[1] - host = sys.argv[2] - port = '' - browser(selector, host, port) - elif sys.argv[1:]: - browser('', sys.argv[1]) - else: - browser() - -# Call the test program as a main program -test() diff --git a/Demo/sockets/mcast.py b/Demo/sockets/mcast.py deleted file mode 100755 index 4cd870657b..0000000000 --- a/Demo/sockets/mcast.py +++ /dev/null @@ -1,94 +0,0 @@ -# Send/receive UDP multicast packets. -# Requires that your OS kernel supports IP multicast. -# This is built-in on SGI, still optional for most other vendors. -# -# Usage: -# mcast -s (sender) -# mcast -b (sender, using broadcast instead multicast) -# mcast (receivers) - -MYPORT = 8123 -MYGROUP = '225.0.0.250' - -import sys -import time -import struct -import regsub -from socket import * - - -# Main program -def main(): - flags = sys.argv[1:] - # - if flags: - sender(flags[0]) - else: - receiver() - - -# Sender subroutine (only one per local area network) -def sender(flag): - s = socket(AF_INET, SOCK_DGRAM) - if flag == '-b': - s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) - mygroup = '' - else: - mygroup = MYGROUP - ttl = struct.pack('b', 1) # Time-to-live - s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl) - while 1: - data = `time.time()` -## data = data + (1400 - len(data)) * '\0' - s.sendto(data, (mygroup, MYPORT)) - time.sleep(1) - - -# Receiver subroutine (as many as you like) -def receiver(): - # Open and initialize the socket - s = openmcastsock(MYGROUP, MYPORT) - # - # Loop, printing any data we receive - while 1: - data, sender = s.recvfrom(1500) - while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's - print sender, ':', `data` - - -# Open a UDP socket, bind it to a port and select a multicast group -def openmcastsock(group, port): - # Import modules used only here - import regsub - import struct - # - # Create a socket - s = socket(AF_INET, SOCK_DGRAM) - # - # Allow multiple copies of this program on one machine - # (not strictly needed) - s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1) - # - # Bind it to the port - s.bind(('', port)) - # - # Look up multicast group address in name server - # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format) - group = gethostbyname(group) - # - # Construct binary group address - bytes = eval(regsub.gsub('\.', ',', group)) - grpaddr = 0 - for byte in bytes: grpaddr = (grpaddr << 8) | byte - # - # Construct struct mreq from grpaddr and ifaddr - ifaddr = INADDR_ANY - mreq = struct.pack('ll', grpaddr, ifaddr) - # - # Add group membership - s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) - # - return s - - -main() diff --git a/Demo/sockets/radio.py b/Demo/sockets/radio.py deleted file mode 100755 index 6131d40053..0000000000 --- a/Demo/sockets/radio.py +++ /dev/null @@ -1,14 +0,0 @@ -# Receive UDP packets transmitted by a broadcasting service - -MYPORT = 50000 - -import sys -from socket import * - -s = socket(AF_INET, SOCK_DGRAM) -s.bind(('', MYPORT)) - -while 1: - data, wherefrom = s.recvfrom(1500, 0) - sys.stderr.write(`wherefrom` + '\n') - sys.stdout.write(data) diff --git a/Demo/sockets/rpython.py b/Demo/sockets/rpython.py deleted file mode 100755 index 9548301893..0000000000 --- a/Demo/sockets/rpython.py +++ /dev/null @@ -1,35 +0,0 @@ -#! /usr/local/bin/python - -# Remote python client. -# Execute Python commands remotely and send output back. - -import sys -import string -from socket import * - -PORT = 4127 -BUFSIZE = 1024 - -def main(): - if len(sys.argv) < 3: - print "usage: rpython host command" - sys.exit(2) - host = sys.argv[1] - port = PORT - i = string.find(host, ':') - if i >= 0: - port = string.atoi(port[i+1:]) - host = host[:i] - command = string.join(sys.argv[2:]) - s = socket(AF_INET, SOCK_STREAM) - s.connect((host, port)) - s.send(command) - s.shutdown(1) - reply = '' - while 1: - data = s.recv(BUFSIZE) - if not data: break - reply = reply + data - print reply, - -main() diff --git a/Demo/sockets/rpythond.py b/Demo/sockets/rpythond.py deleted file mode 100755 index f67570bc95..0000000000 --- a/Demo/sockets/rpythond.py +++ /dev/null @@ -1,52 +0,0 @@ -#! /usr/local/bin/python - -# Remote python server. -# Execute Python commands remotely and send output back. -# WARNING: This version has a gaping security hole -- it accepts requests -# from any host on the Internet! - -import sys -from socket import * -import StringIO -import traceback - -PORT = 4127 -BUFSIZE = 1024 - -def main(): - if len(sys.argv) > 1: - port = int(eval(sys.argv[1])) - else: - port = PORT - s = socket(AF_INET, SOCK_STREAM) - s.bind('', port) - s.listen(1) - while 1: - conn, (remotehost, remoteport) = s.accept() - print 'connected by', remotehost, remoteport - request = '' - while 1: - data = conn.recv(BUFSIZE) - if not data: - break - request = request + data - reply = execute(request) - conn.send(reply) - conn.close() - -def execute(request): - stdout = sys.stdout - stderr = sys.stderr - sys.stdout = sys.stderr = fakefile = StringIO.StringIO() - try: - try: - exec request in {}, {} - except: - print - traceback.print_exc(100) - finally: - sys.stderr = stderr - sys.stdout = stdout - return fakefile.getvalue() - -main() diff --git a/Demo/sockets/telnet.py b/Demo/sockets/telnet.py deleted file mode 100755 index 3bb36efdc2..0000000000 --- a/Demo/sockets/telnet.py +++ /dev/null @@ -1,109 +0,0 @@ -#! /usr/local/bin/python - -# Minimal interface to the Internet telnet protocol. -# -# It refuses all telnet options and does not recognize any of the other -# telnet commands, but can still be used to connect in line-by-line mode. -# It's also useful to play with a number of other services, -# like time, finger, smtp and even ftp. -# -# Usage: telnet host [port] -# -# The port may be a service name or a decimal port number; -# it defaults to 'telnet'. - - -import sys, posix, time -from socket import * - -BUFSIZE = 1024 - -# Telnet protocol characters - -IAC = chr(255) # Interpret as command -DONT = chr(254) -DO = chr(253) -WONT = chr(252) -WILL = chr(251) - -def main(): - host = sys.argv[1] - try: - hostaddr = gethostbyname(host) - except error: - sys.stderr.write(sys.argv[1] + ': bad host name\n') - sys.exit(2) - # - if len(sys.argv) > 2: - servname = sys.argv[2] - else: - servname = 'telnet' - # - if '0' <= servname[:1] <= '9': - port = eval(servname) - else: - try: - port = getservbyname(servname, 'tcp') - except error: - sys.stderr.write(servname + ': bad tcp service name\n') - sys.exit(2) - # - s = socket(AF_INET, SOCK_STREAM) - # - try: - s.connect(host, port) - except error, msg: - sys.stderr.write('connect failed: ' + `msg` + '\n') - sys.exit(1) - # - pid = posix.fork() - # - if pid == 0: - # child -- read stdin, write socket - while 1: - line = sys.stdin.readline() - s.send(line) - else: - # parent -- read socket, write stdout - iac = 0 # Interpret next char as command - opt = '' # Interpret next char as option - while 1: - data = s.recv(BUFSIZE) - if not data: - # EOF; kill child and exit - sys.stderr.write( '(Closed by remote host)\n') - posix.kill(pid, 9) - sys.exit(1) - cleandata = '' - for c in data: - if opt: - print ord(c) - s.send(opt + c) - opt = '' - elif iac: - iac = 0 - if c == IAC: - cleandata = cleandata + c - elif c in (DO, DONT): - if c == DO: print '(DO)', - else: print '(DONT)', - opt = IAC + WONT - elif c in (WILL, WONT): - if c == WILL: print '(WILL)', - else: print '(WONT)', - opt = IAC + DONT - else: - print '(command)', ord(c) - elif c == IAC: - iac = 1 - print '(IAC)', - else: - cleandata = cleandata + c - sys.stdout.write(cleandata) - sys.stdout.flush() - - -try: - main() -except KeyboardInterrupt: - pass diff --git a/Demo/sockets/throughput.py b/Demo/sockets/throughput.py deleted file mode 100755 index fd946b44ec..0000000000 --- a/Demo/sockets/throughput.py +++ /dev/null @@ -1,93 +0,0 @@ -#! /usr/local/bin/python - -# Test network throughput. -# -# Usage: -# 1) on host_A: throughput -s [port] # start a server -# 2) on host_B: throughput -c count host_A [port] # start a client -# -# The server will service multiple clients until it is killed. -# -# The client performs one transfer of count*BUFSIZE bytes and -# measures the time it takes (roundtrip!). - - -import sys, time -from socket import * - -MY_PORT = 50000 + 42 - -BUFSIZE = 1024 - - -def main(): - if len(sys.argv) < 2: - usage() - if sys.argv[1] == '-s': - server() - elif sys.argv[1] == '-c': - client() - else: - usage() - - -def usage(): - sys.stdout = sys.stderr - print 'Usage: (on host_A) throughput -s [port]' - print 'and then: (on host_B) throughput -c count host_A [port]' - sys.exit(2) - - -def server(): - if len(sys.argv) > 2: - port = eval(sys.argv[2]) - else: - port = MY_PORT - s = socket(AF_INET, SOCK_STREAM) - s.bind('', port) - s.listen(1) - print 'Server ready...' - while 1: - conn, (host, remoteport) = s.accept() - while 1: - data = conn.recv(BUFSIZE) - if not data: - break - del data - conn.send('OK\n') - conn.close() - print 'Done with', host, 'port', remoteport - - -def client(): - if len(sys.argv) < 4: - usage() - count = int(eval(sys.argv[2])) - host = sys.argv[3] - if len(sys.argv) > 4: - port = eval(sys.argv[4]) - else: - port = MY_PORT - testdata = 'x' * (BUFSIZE-1) + '\n' - t1 = time.time() - s = socket(AF_INET, SOCK_STREAM) - t2 = time.time() - s.connect(host, port) - t3 = time.time() - i = 0 - while i < count: - i = i+1 - s.send(testdata) - s.shutdown(1) # Send EOF - t4 = time.time() - data = s.recv(BUFSIZE) - t5 = time.time() - print data - print 'Raw timers:', t1, t2, t3, t4, t5 - print 'Intervals:', t2-t1, t3-t2, t4-t3, t5-t4 - print 'Total:', t5-t1 - print 'Throughput:', round((BUFSIZE*count*0.001) / (t5-t1), 3), - print 'K/sec.' - - -main() diff --git a/Demo/sockets/udpecho.py b/Demo/sockets/udpecho.py deleted file mode 100755 index 8839eb8057..0000000000 --- a/Demo/sockets/udpecho.py +++ /dev/null @@ -1,63 +0,0 @@ -#! /usr/local/bin/python - -# Client and server for udp (datagram) echo. -# -# Usage: udpecho -s [port] (to start a server) -# or: udpecho -c host [port] 2: - port = eval(sys.argv[2]) - else: - port = ECHO_PORT - s = socket(AF_INET, SOCK_DGRAM) - s.bind('', port) - print 'udp echo server ready' - while 1: - data, addr = s.recvfrom(BUFSIZE) - print 'server received', `data`, 'from', `addr` - s.sendto(data, addr) - -def client(): - if len(sys.argv) < 3: - usage() - host = sys.argv[2] - if len(sys.argv) > 3: - port = eval(sys.argv[3]) - else: - port = ECHO_PORT - addr = host, port - s = socket(AF_INET, SOCK_DGRAM) - s.bind('', 0) - print 'udp echo client ready, reading stdin' - while 1: - line = sys.stdin.readline() - if not line: - break - s.sendto(line, addr) - data, fromaddr = s.recvfrom(BUFSIZE) - print 'client received', `data`, 'from', `fromaddr` - -main() diff --git a/Demo/stdwin/FormTest.py b/Demo/stdwin/FormTest.py deleted file mode 100755 index ce62802ebf..0000000000 --- a/Demo/stdwin/FormTest.py +++ /dev/null @@ -1,30 +0,0 @@ -#! /usr/local/bin/python - -testlabels = 'Name', 'Address', 'City', 'Country', 'Comments' - -def main(): - import stdwin - from WindowParent import WindowParent, MainLoop - from FormSplit import FormSplit - from Buttons import Label - from TextEdit import TextEdit - # - stdwin.setdefscrollbars(0, 0) - # - w = WindowParent().create('FormTest', (0, 0)) - f = FormSplit().create(w) - # - h, v = 0, 0 - for label in testlabels: - f.placenext(h, v) - lbl = Label().definetext(f, label) - f.placenext(h + 100, v) - txt = TextEdit().createboxed(f, (40, 2), (2, 2)) - #txt = TextEdit().create(f, (40, 2)) - v = v + 2*stdwin.lineheight() + 10 - # - w.realize() - # - MainLoop() - -main() diff --git a/Demo/stdwin/README b/Demo/stdwin/README deleted file mode 100644 index 5291225076..0000000000 --- a/Demo/stdwin/README +++ /dev/null @@ -1,18 +0,0 @@ -Contents of this directory: - -FormTest.py Show how a form can be built to enter multiple fields -RadioGroups.py Show how to use multiple groups of radio buttons -TestCSplit.py Test CSplit widget (a clock-like split) -TestDirList.py Test DirList widget (lists directory contents) -TestFormSplit.py Test FormSplit widget (arbitrary grouping) -TestSched.py Test WindowSched widget (event scheduling) -TestTextEdit.py Test TextEdit widget (probably doen't work any more) -clock.py A simple clock, with alarm -jukebox.py Play audio files (SGI only, needs SOX and SFPLAY) -lpwin.py Watch line printer queues -microedit.py The smallest window editor -miniedit.py A small multi-window editor -python.py A window interface to the Python interpreter -wdiff.py A window-based directory diff - -See ../ibrowse for another demo written using stdwin. diff --git a/Demo/stdwin/RadioGroups.py b/Demo/stdwin/RadioGroups.py deleted file mode 100755 index fcd693f65b..0000000000 --- a/Demo/stdwin/RadioGroups.py +++ /dev/null @@ -1,98 +0,0 @@ -#! /usr/local/bin/python - -# radiogroups.py -# -# Demonstrate multiple groups of radio buttons - -import stdwin -from Buttons import * -from WindowParent import WindowParent, MainLoop -from HVSplit import HSplit, VSplit - -def main(): - # - # Create the widget hierarchy, top-down - # - # 1. Create the window - # - window = WindowParent().create('Radio Groups', (0, 0)) - # - # 2. Create a horizontal split to contain the groups - # - topsplit = HSplit().create(window) - # - # 3. Create vertical splits, one for each group - # - group1 = VSplit().create(topsplit) - group2 = VSplit().create(topsplit) - group3 = VSplit().create(topsplit) - # - # 4. Create individual radio buttons, each in their own split - # - b11 = RadioButton().definetext(group1, 'Group 1 button 1') - b12 = RadioButton().definetext(group1, 'Group 1 button 2') - b13 = RadioButton().definetext(group1, 'Group 1 button 3') - # - b21 = RadioButton().definetext(group2, 'Group 2 button 1') - b22 = RadioButton().definetext(group2, 'Group 2 button 2') - b23 = RadioButton().definetext(group2, 'Group 2 button 3') - # - b31 = RadioButton().definetext(group3, 'Group 3 button 1') - b32 = RadioButton().definetext(group3, 'Group 3 button 2') - b33 = RadioButton().definetext(group3, 'Group 3 button 3') - # - # 5. Define the grouping for the radio buttons. - # Note: this doesn't have to be the same as the - # grouping is splits (although it usually is). - # Also set the 'hook' procedure for each button - # - list1 = [b11, b12, b13] - list2 = [b21, b22, b23] - list3 = [b31, b32, b33] - # - for b in list1: - b.group = list1 - b.on_hook = myhook - for b in list2: - b.group = list2 - b.on_hook = myhook - for b in list3: - b.group = list3 - b.on_hook = myhook - # - # 6. Select a default button in each group - # - b11.select(1) - b22.select(1) - b33.select(1) - # - # 6. Realize the window - # - window.realize() - # - # 7. Dispatch events until the window is closed - # - MainLoop() - # - # 8. Report final selections - # - print 'You selected the following choices:' - if b11.selected: print '1.1' - if b12.selected: print '1.2' - if b13.selected: print '1.3' - if b21.selected: print '2.1' - if b22.selected: print '2.2' - if b23.selected: print '2.3' - if b31.selected: print '3.1' - if b32.selected: print '3.2' - if b33.selected: print '3.3' - - -# My 'hook' procedure -# This is placed as 'hook' attribute on each button. -# The example just prints the title of the selected button. -# -def myhook(self): - print 'Selected:', self.text - -main() diff --git a/Demo/stdwin/TestCSplit.py b/Demo/stdwin/TestCSplit.py deleted file mode 100755 index 9297e46b60..0000000000 --- a/Demo/stdwin/TestCSplit.py +++ /dev/null @@ -1,25 +0,0 @@ -#! /usr/local/bin/python - -# TestCSplit - -import stdwin -from WindowParent import WindowParent, MainLoop -from Buttons import PushButton - -def main(n): - from CSplit import CSplit - # - stdwin.setdefscrollbars(0, 0) - # - the_window = WindowParent().create('TestCSplit', (0, 0)) - the_csplit = CSplit().create(the_window) - # - for i in range(n): - the_child = PushButton().define(the_csplit) - the_child.settext(`(i+n-1)%n+1`) - # - the_window.realize() - # - MainLoop() - -main(12) diff --git a/Demo/stdwin/TestDirList.py b/Demo/stdwin/TestDirList.py deleted file mode 100755 index 7fb45ae4d0..0000000000 --- a/Demo/stdwin/TestDirList.py +++ /dev/null @@ -1,18 +0,0 @@ -#! /usr/local/bin/python - -# TestDirList - -from DirList import DirListWindow -from WindowParent import MainLoop - -def main(): - import sys - args = sys.argv[1:] - if not args: - args = ['.'] - # Mac: args = [':'] - for arg in args: - w = DirListWindow().create(arg) - MainLoop() - -main() diff --git a/Demo/stdwin/TestFormSplit.py b/Demo/stdwin/TestFormSplit.py deleted file mode 100755 index 2750378311..0000000000 --- a/Demo/stdwin/TestFormSplit.py +++ /dev/null @@ -1,27 +0,0 @@ -#! /usr/local/bin/python - -# TestFormSplit - -import stdwin -from WindowParent import WindowParent, MainLoop -from Buttons import PushButton - -def main(n): - from FormSplit import FormSplit - # - stdwin.setdefscrollbars(1, 1) - # - the_window = WindowParent().create('TestFormSplit', (0, 0)) - the_form = FormSplit().create(the_window) - # - for i in range(n): - if i % 3 == 0: - the_form.placenext(i*40, 0) - the_child = PushButton().define(the_form) - the_child.settext('XXX-' + `i` + '-YYY') - # - the_window.realize() - # - MainLoop() - -main(6) diff --git a/Demo/stdwin/TestSched.py b/Demo/stdwin/TestSched.py deleted file mode 100755 index f6bbe23688..0000000000 --- a/Demo/stdwin/TestSched.py +++ /dev/null @@ -1,38 +0,0 @@ -#! /usr/local/bin/python - -# TestSched - -import stdwin -from WindowParent import WindowParent, MainLoop -import WindowSched -from Buttons import PushButton - -def my_ringer(child): - child.my_id = None - stdwin.fleep() - -def my_hook(child): - # schedule for the bell to ring in N seconds; cancel previous - if child.my_id: - WindowSched.cancel(child.my_id) - child.my_id = \ - WindowSched.enter(child.my_number*1000, 0, my_ringer, (child,)) - -def main(n): - from CSplit import CSplit - - window = WindowParent().create('TestSched', (0, 0)) - csplit = CSplit().create(window) - - for i in range(n): - child = PushButton().define(csplit) - child.my_number = i - child.my_id = None - child.settext(`(i+n-1)%n+1`) - child.hook = my_hook - - window.realize() - - WindowSched.run() - -main(12) diff --git a/Demo/stdwin/TestTextEdit.py b/Demo/stdwin/TestTextEdit.py deleted file mode 100755 index 9f4c86117d..0000000000 --- a/Demo/stdwin/TestTextEdit.py +++ /dev/null @@ -1,13 +0,0 @@ -#! /usr/local/bin/python - -# Test TextEdit widgets - -def main(): - from TextEdit import TextEdit - from WindowParent import WindowParent, MainLoop - w = WindowParent().create('Test TextEdit', (0, 0)) - t = TextEdit().create(w, (40, 4)) - w.realize() - MainLoop() - -main() diff --git a/Demo/stdwin/clock.py b/Demo/stdwin/clock.py deleted file mode 100755 index 4328b7b40c..0000000000 --- a/Demo/stdwin/clock.py +++ /dev/null @@ -1,193 +0,0 @@ -#! /usr/local/bin/python - -# 'clock' -- A simple alarm clock - -# The alarm can be set at 5 minute intervals on a 12 hour basis. -# It is controlled with the mouse: -# - Click and drag around the circle to set the alarm. -# - Click far outside the circle to clear the alarm. -# - Click near the center to set the alarm at the last time set. -# The alarm time is indicated by a small triangle just outside the circle, -# and also by a digital time at the bottom. -# The indicators disappear when the alarm is not set. -# When the alarm goes off, it beeps every minute for five minutes, -# and the clock turns into inverse video. -# Click or activate the window to turn the ringing off. - -import stdwin -from stdwinevents import WE_MOUSE_DOWN, WE_MOUSE_MOVE, WE_MOUSE_UP, \ - WE_TIMER, WE_DRAW, WE_SIZE, WE_CLOSE, WE_ACTIVATE -import mainloop -import time -from math import sin, cos, atan2, pi, sqrt - -DEFWIDTH, DEFHEIGHT = 200, 200 - -MOUSE_EVENTS = (WE_MOUSE_DOWN, WE_MOUSE_MOVE, WE_MOUSE_UP) -ORIGIN = 0, 0 -FARAWAY = 2000, 2000 -EVERYWHERE = ORIGIN, FARAWAY - - -def main(): - win = makewindow() - del win - mainloop.mainloop() - -def makewindow(): - stdwin.setdefwinsize(DEFWIDTH, DEFHEIGHT + stdwin.lineheight()) - win = stdwin.open('clock') - setdimensions(win) - win.set = 1 # True when alarm is set - win.time = 11*60 + 40 # Time when alarm must go off - win.ring = 0 # True when alarm is ringing - win.dispatch = cdispatch - mainloop.register(win) - settimer(win) - return win - -def cdispatch(event): - type, win, detail = event - if type == WE_DRAW: - drawproc(win, detail) - elif type == WE_TIMER: - settimer(win) - drawproc(win, EVERYWHERE) - elif type in MOUSE_EVENTS: - mouseclick(win, type, detail) - elif type == WE_ACTIVATE: - if win.ring: - # Turn the ringing off - win.ring = 0 - win.begindrawing().invert(win.mainarea) - elif type == WE_SIZE: - win.change(EVERYWHERE) - setdimensions(win) - elif type == WE_CLOSE: - mainloop.unregister(win) - win.close() - -def setdimensions(win): - width, height = win.getwinsize() - height = height - stdwin.lineheight() - if width < height: size = width - else: size = height - halfwidth = width/2 - halfheight = height/2 - win.center = halfwidth, halfheight - win.radius = size*45/100 - win.width = width - win.height = height - win.corner = width, height - win.mainarea = ORIGIN, win.corner - win.lineheight = stdwin.lineheight() - win.farcorner = width, height + win.lineheight - win.statusarea = (0, height), win.farcorner - win.fullarea = ORIGIN, win.farcorner - -def settimer(win): - now = time.time() - hours, minutes, seconds = win.times = calctime(now) - delay = 61 - seconds - win.settimer(10 * delay) - minutes = minutes + hours*60 - if win.ring: - # Is it time to stop the alarm ringing? - since = (minutes - win.time + 720) % 720 - if since >= 5: - # Stop it now - win.ring = 0 - else: - # Ring again, once every minute - stdwin.fleep() - elif win.set and minutes == win.time: - # Start the alarm ringing - win.ring = 1 - stdwin.fleep() - -def drawproc(win, area): - hours, minutes, seconds = win.times - d = win.begindrawing() - d.cliprect(area) - d.erase(EVERYWHERE) - d.circle(win.center, win.radius) - d.line(win.center, calcpoint(win, hours*30 + minutes/2, 0.6)) - d.line(win.center, calcpoint(win, minutes*6, 1.0)) - str = "%02d:%02d" % (hours, minutes) - p = (win.width - d.textwidth(str))/2, win.height * 3 / 4 - d.text(p, str) - if win.set: - drawalarm(win, d) - drawalarmtime(win, d) - if win.ring: - d.invert(win.mainarea) - -def mouseclick(win, type, detail): - d = win.begindrawing() - if win.ring: - # First turn the ringing off - win.ring = 0 - d.invert(win.mainarea) - h, v = detail[0] - ch, cv = win.center - x, y = h-ch, cv-v - dist = sqrt(x*x + y*y) / float(win.radius) - if dist > 1.2: - if win.set: - drawalarm(win, d) - erasealarmtime(win, d) - win.set = 0 - elif dist < 0.8: - if not win.set: - win.set = 1 - drawalarm(win, d) - drawalarmtime(win, d) - else: - # Convert to half-degrees (range 0..720) - alpha = atan2(y, x) - hdeg = alpha*360.0/pi - hdeg = 180.0 - hdeg - hdeg = (hdeg + 720.0) % 720.0 - atime = 5*int(hdeg/5.0 + 0.5) - if atime <> win.time or not win.set: - if win.set: - drawalarm(win, d) - erasealarmtime(win, d) - win.set = 1 - win.time = atime - drawalarm(win, d) - drawalarmtime(win, d) - -def drawalarm(win, d): - p1 = calcpoint(win, float(win.time)/2.0, 1.02) - p2 = calcpoint(win, float(win.time)/2.0 - 4.0, 1.1) - p3 = calcpoint(win, float(win.time)/2.0 + 4.0, 1.1) - d.xorline(p1, p2) - d.xorline(p2, p3) - d.xorline(p3, p1) - -def erasealarmtime(win, d): - d.erase(win.statusarea) - -def drawalarmtime(win, d): - # win.time is in the range 0..720 with origin at 12 o'clock - # Convert to hours (0..12) and minutes (12*(0..60)) - hh = win.time/60 - mm = win.time%60 - str = 'Alarm@%02d:%02d' % (hh, mm) - p1 = (win.width - d.textwidth(str))/2, win.height - d.text(p1, str) - -def calcpoint(win, degrees, size): - alpha = pi/2.0 - float(degrees) * pi/180.0 - x, y = cos(alpha), sin(alpha) - h, v = win.center - r = float(win.radius) - return h + int(x*size*r), v - int(y*size*r) - -def calctime(now): - hours, minutes, seconds = time.localtime(now)[3:6] - hours = hours % 12 - return hours, minutes, seconds - -main() diff --git a/Demo/stdwin/ibrowse/README b/Demo/stdwin/ibrowse/README deleted file mode 100644 index 22e403928d..0000000000 --- a/Demo/stdwin/ibrowse/README +++ /dev/null @@ -1,34 +0,0 @@ -This directory contains a browser written in Python for "Info files" -as used by the Emacs documentation system. The browser requires that -Python is built with the "stdwin" option and runs under X11 or the -Mac window system. - -Now you can read Info files even if you can't spare the memory, time or -disk space to run Emacs. (I have used this extensively on a Macintosh -with 1 Megabyte main memory and a 20 Meg harddisk.) - -You can give this to someone with great fear of complex computer -systems, as long as they can use a mouse. - -Another reason to use this is to encourage the use of Info for on-line -documentation of software that is not related to Emacs or GNU. -(In particular, I plan to redo the Python and STDWIN documentation -in texinfo.) - -The main program is in file "ib.py"; this accepts a file name and a -node name as optional command line arguments, i.e., its usage is - - python ib.py [file [node]] - - -Configuration: - -- The pathname of the directory (or directories) containing -the standard Info files should be set by editing the -value assigned to INFOPATH in module ifile.py. - -- The default font should be set by editing the value of FONT -in this module (ibrowse.py). - -- For fastest I/O, you may look at BLOCKSIZE and a few other -constants in ifile.py. diff --git a/Demo/stdwin/ibrowse/dir b/Demo/stdwin/ibrowse/dir deleted file mode 100755 index 21d1989cac..0000000000 --- a/Demo/stdwin/ibrowse/dir +++ /dev/null @@ -1,62 +0,0 @@ --*- Text -*- -This is the file .../ibrowse/dir, which contains the topmost node of the -Info hierarchy. The first time you invoke Ibrowse you start off -looking at that node, which is (dir)Top. (This is a copy of the Info -dir node, except that the reference to Info is replaced by one to Ibrowse.) - -File: dir Node: Top This is the top of the INFO tree - This (the Directory node) gives a menu of major topics. - Typing "d" returns here, "q" exits, "?" lists all INFO commands, "h" - gives a primer for first-timers, "mTexinfo" visits Texinfo topic, - etc. - --- PLEASE ADD DOCUMENTATION TO THIS TREE. (See INFO topic first.) --- - -* Menu: The list of major topics begins on the next line. - -* Ibrowse: (ibrowse). Documentation browsing system. - -* Emacs: (emacs). The extensible self-documenting text editor. - -* VIP: (vip). A VI-emulation for Emacs. - -* Texinfo: (texinfo). - With one source file, make either a printed manual - (through TeX) or an Info file (through texinfo). - Full documentation in this menu item. - -* Termcap: (termcap). - The termcap library, which enables application programs - to handle all types of character-display terminals. - -* Regex: (regex). - The GNU regular expression library. - -* Bison: (bison.info). - The GNU yacc-compatible parser generator. - -* GCC: (gcc.info). - The GNU C compiler. - -* G++: (g-whiz). - The GNU C++ compiler. - -* LibG++: (libg++). - The GNU C++ library. - -* GDB: (gdb.info). - The GNU debugger. - -* CPP: (cpp.info). - The GNU C preprocessor. - -* Lispref: (lispref). - The GNU Emacs Lisp reference manual. - -* Make: (make-info). - The GNU make program. - -* M4: (m4). - The GNU m4 program. - -* Gawk: (gawk-info). - GNU awk. diff --git a/Demo/stdwin/ibrowse/ib b/Demo/stdwin/ibrowse/ib deleted file mode 100755 index 04cb790732..0000000000 --- a/Demo/stdwin/ibrowse/ib +++ /dev/null @@ -1,2 +0,0 @@ -: ${ARCH}=`arch` -exec /ufs/guido/bin/$ARCH/python ib.py ${1+"$@"} diff --git a/Demo/stdwin/ibrowse/ib.py b/Demo/stdwin/ibrowse/ib.py deleted file mode 100755 index 588270ed49..0000000000 --- a/Demo/stdwin/ibrowse/ib.py +++ /dev/null @@ -1,21 +0,0 @@ -#! /usr/local/bin/python - -# Call ibrowse (the info file browser) under UNIX. - -import sys -import ibrowse - -if len(sys.argv) > 1: - file = sys.argv[1] - if len(sys.argv) > 2: - if len(sys.argv) > 3: - sys.stdout = sys.stderr - print 'usage:', sys.argv[0], '[file [node]]' - sys.exit(2) - else: - node = sys.argv[2] - else: - node = '' - ibrowse.start('(' + file + ')' + node) -else: - ibrowse.main() diff --git a/Demo/stdwin/ibrowse/ibrowse b/Demo/stdwin/ibrowse/ibrowse deleted file mode 100755 index 8b0dcde30e..0000000000 --- a/Demo/stdwin/ibrowse/ibrowse +++ /dev/null @@ -1,719 +0,0 @@ -This file documents the ibrowse program. -*-Text-*- -The H command of ibrowse goes to the node Help in this file. - -File: ibrowse Node: Top Up: (DIR) Next: Expert - -Ibrowse is a program for reading documentation, which you are using now. -** Ibrowse uses the file format of the Emacs Info program, and its -** commands are similar, but not identical. - -To learn how to use Ibrowse, type the command "h". It will bring you -to a programmed instruction sequence. - -* Menu: - -* Expert:: Advanced Ibrowse commands: c, k, g, s, 1 - 9, arrows. -* Add:: Describes how to add new nodes to the hierarchy. - Also tells what nodes look like. -* Menus:: How to add to or create menus in Info nodes. -* Cross-refs:: How to add cross-references to Info nodes. -* Tags:: How to make tag tables for Info files. -* Checking:: How to check the consistency of an Info file. -* Texinfo: (texinfo). - How to generate an Info file and a printed manual - from the same source file. - -File: ibrowse Node: Summary Next: Help - -Ibrowse is a Python program for browsing through the Emacs Info -documentation tree. Documentation in Info is divided into "nodes", -each of which discusses one topic and contains references to other -nodes which discuss related topics. Ibrowse has commands to follow the -references and show you other nodes. - -h Invoke the Ibrowse tutorial. -? Display this Summary node. -q Quit Ibrowse. -w Close current window. - -Selecting other nodes: -n Move to the "next" node of this node. -p Move to the "previous" node of this node. -m Pick menu item specified by name (or abbreviation). -1-9 Pick first..ninth in node's menu. - Menu items select nodes that are "subsections" of this node. -u Move "up" from this node (i.e., from a subsection to a section). -f Follow a cross reference by name (or abbrev). Type `l' to get back. -l Move back to the last node you were in. - -Moving within a node: -Space Scroll forward a full screen. DEL, BS Scroll backward. -b Go to beginning of node. - -Advanced commands: -k Clone current window (create an independent duplicate). -c Copy text selection to clipboard (for paste in another application). -g Move to node specified by name. - You may include a filename as well, as (FILENAME)NODENAME. -d Go to the main directory of Info files. -t Go to Top node of this file. -s Search through this Info file for node with specified regexp. - -File: ibrowse Node: Help-Small-Screen Next: Help - -Since your terminal has an unusually small number of lines on its -screen, it is necessary to give you special advice at the beginning. - -If you see the text "--All----" at near the bottom right corner of -the screen, it means the entire text you are looking at fits on the -screen. If you see "--Top----" instead, it means that there is more -text below that does not fit. To move forward through the text and -see another screen full, press the Space bar. To move back up, press -the key labeled Rubout or Delete or DEL. - -Here are 40 lines of junk, so you can try Spaces and Rubout and -see what they do. At the end are instructions of what you should do -next. - -This is line 17 -This is line 18 -This is line 19 -This is line 20 -This is line 21 -This is line 22 -This is line 23 -This is line 24 -This is line 25 -This is line 26 -This is line 27 -This is line 28 -This is line 29 -This is line 30 -This is line 31 -This is line 32 -This is line 33 -This is line 34 -This is line 35 -This is line 36 -This is line 37 -This is line 38 -This is line 39 -This is line 40 -This is line 41 -This is line 42 -This is line 43 -This is line 44 -This is line 45 -This is line 46 -This is line 47 -This is line 48 -This is line 49 -This is line 50 -This is line 51 -This is line 52 -This is line 53 -This is line 54 -This is line 55 -This is line 56 - -If you have managed to get here, go back to the beginning with -Rubout, and come back here again, then you understand Space and -Rubout. So now type an "n"--just one character; don't type the -quotes and don't type a Return afterward-- to get to the normal start -of the course. - -File: ibrowse Node: Help Next: Help-P Previous: Help-Small-Screen - -You are talking to the program Ibrowse, for reading documentation. - - Right now you are looking at one "Node" of Information. -A node contains text describing a specific topic at a specific -level of detail. This node's topic is "how to use Ibrowse". - - The top line of a node is its "header". This node's header (look at -it now) says that it is the node named "Help" in the file "ibrowse". -It says that the Next node after this one is the node called "Help-P". -An advanced Ibrowse command lets you go to any node whose name you know. - - Besides a "Next", a node can have a "Previous" or an "Up". -This node has a "Previous" but no "Up", as you can see. - - Now it's time to move on to the Next node, named "Help-P". - ->> Type "n" to move there. Type just one character; - don't type the quotes and don't type a Return afterward. - -">>" in the margin means it is really time to try a command. - -File: ibrowse Node: Help-P Next: Help-Page Previous: Help - -This node is called "Help-P". The "Previous" node, as you see, is -"Help", which is the one you just came from using the "N" command. -Another "N" command now would take you to the Next node, "Help-Page". - ->> But don't do that yet. First, try the "p" command, which takes -you to the Previous node. When you get there, you can do an "n" -again to return here. - - This all probably seems insultingly simple so far, but DON'T be -led into skimming. Things will get more complicated soon. Also, -don't try a new command until you are told it's time to. Otherwise, -you may make Ibrowse skip past an important warning that was coming up. - ->> Now do an "n" to get to the node "Help-Page" and learn more. - -File: ibrowse Node: Help-Page Next: Help-M Previous: Help-P - -Space, Backspace, and B commands. - - This node's header tells you that you are now at node "Help-Page", and -that "P" would get you back to "Help-P". The line starting "Space," -is a "Title", saying what the node is about (most nodes have titles). - - This is a big node and it doesn't all fit on your display screen. -You can tell that there is more that isn't visible because you -the scroll bar on the side of the window has become active (gray). - - The Space, Backspace and B commands exist to allow you to "move -around" in a node that doesn't all fit on the screen at once. -Space moves forward, to show what was below the bottom of the screen. -Backspace moves backward, to show what was above the top of the screen -(there isn't anything above the top until you have typed some spaces). - ->> Now try typing a Space (afterward, type a Backspace to return here). - - When you type the space, the two lines that were at the bottom of the -screen appear at the top, followed by more lines. Backspace takes the -two lines from the top and moves them to the bottom, USUALLY, but if -there are not a full screen's worth of lines above them they may not -make it all the way to the bottom. - - If you type a Space when there is no more to see, it will ring the -bell and otherwise do nothing. The same goes for a Backspace when -the header of the node is visible. - - Of course you can use the mouse and directly move the scroll bar -as well, but Ibrowse has keyboard commands for almost everything, -including scrolling. These keyboard commands are called "shortcuts", -because it generally takes less effort to press a key on the -keyboard than to move the mouse. On the other hand, if you are -an infrequent user of Ibrowse, you can do everything with the -mouse that you can do with the keyboard. Just look in the menus -(I'm sure you must know how to use the menus on this system, or -else you couldn't have gotten this far...). In fact you'll see that -the commands and shortcuts listed in the menus are the same as those -described in this course. You can use the shortcuts either with or -without the "Command" or "Meta" key. - - Two menus are always available: the "Ibrowse" menu contains commands -pertaining to the Ibrowse program at large, while the "Navigation" menu -contains commands that move around between nodes. There may be other -menus; these will be explained later. - - To move back to the beginning of the node you are on, you can type -a lot of Backspaces. You can also type simply "b" for beginning. ->> Try that now. (I have put in enough verbiage to make sure you are - not on the first screenful now). Then come back, with Spaces. - - You have just learned a considerable number of commands. If you -want to use one but have trouble remembering which, just pull down -the menus to get a summary of commands and shortcuts. Some additional -shortcuts (not listed in the menus) are listed by the "Short help" -command. This brings up a dialog box which you can acknowledge -by clicking the OK button or pressing the Return key. - - From now on, you will encounter large nodes without warning, and -will be expected to know how to use Space and Backspace to move -around in them without being told. Since you could change the -size of the window used, it would be impossible to warn you anyway. - ->> Now type "n" to see the description of the "m" command. - -File: ibrowse Node: Help-M Next: Help-Adv Previous: Help-Page - -Menus and the "m" command - - With only the "n" and "p" commands for moving between nodes, nodes -are restricted to a linear sequence. Menus allow a branching -structure. A menu is a list of other nodes you can move to. It is -actually just part of the text of the node formatted specially so that -Ibrowse can interpret it. The beginning of a menu is always identified -by a line which starts with "* Menu:". A node contains a menu if and -only if it has a line in it which starts that way. The only menu you -can use at any moment is the one in the node you are in. To use a -menu in any other node, you must move to that node first. - - (There is an unfortunate confusion of terms here. "Menu" may refer -to one of the Ibrowse menus at the top, such as as the "Ibrowse" and -"Navigation" menus explained in the previous node, or to the menu in -a node. Where confusion is possible, these will be disambiguated by -calling them "Ibrowse menus" or "node menu".) - - After the start of the menu, each line that starts with a "*" -identifies one subtopic. The line will usually contain a brief name -for the subtopic (followed by a ":"), the name of the node that talks -about that subtopic, and optionally some further description of the -subtopic. Lines in the menu that don't start with a "*" have no -special meaning - they are only for the human reader's benefit and do -not define additional subtopics. Here is an example: -* Foo: FOO's Node This tells about FOO -The subtopic name is Foo, and the node describing it is "FOO's Node". -The rest of the line is just for the reader's Information. -[[ But this line is not a real menu item, simply because there is -no line above it which starts with "* Menu:".]] - - When you use a menu to go to another node (in a way that will be -described soon), what you specify is the subtopic name, the first -thing in the menu line. Ibrowse uses it to find the menu line, extracts -the node name from it, and goes to that node. The reason that there -is both a subtopic name and a node name is that the node name must be -meaningful to the computer and may therefore have to be ugly looking. -The subtopic name can be chosen just to be convenient for the user to -specify. Often the node name is convenient for the user to specify -and so both it and the subtopic name are the same. There is an -abbreviation for this: -* Foo:: This tells about FOO -This means that the subtopic name and node name are the same; they are -both "Foo". - ->> Now use Spaces to find the menu in this node, then come back to -the front with a "b". As you see, a menu is actually visible -in its node. If you can't find a menu in a node by looking at it, -then the node doesn't have a menu and the "m" command is not available. - - (Actually, a quicker way to see if there is a node menu, is to look -for an Ibrowse menu at the top named "Menu".) - - The command to go to one of the subnodes is "m" - but DON'T DO IT -YET! Before you use "m", you must understand the difference between -commands and arguments. So far, you have learned several commands -that do not need arguments. When you type one, Ibrowse processes it and -is instantly ready for another command. The "m" command is different: -it is incomplete without the NAME OF THE SUBTOPIC. Once you have -typed "m", Ibrowse wants to read the subtopic name. - - Thanks to modern user interface technology, this will be obvious: -you are prompted for the subtopic name in a dialog box. When you are -finished typing the name, press Return or click the OK button. You can -cancel the dialog box by clicking the Cancel button. The first subtopic -is provided as a default choice, so if you want to go there, you can -just press Return. - - You can abbreviate the subtopic name. If the abbreviation is not -unique, the first matching subtopic is chosen. Some menus will put -the shortest possible abbreviation for each subtopic name in capital -letters, so you can see how much you need to type. It does not -matter whether you use upper case or lower case when you type the -subtopic. You should not put any spaces at the end, or inside of the -item name, except for one space where a space appears in the item in -the menu. - - Here is a menu to give you a chance to practice. - -* Menu: The menu starts here. - -This menu gives you three ways of going to one place, Help-FOO. - -* Foo: Help-FOO A node you can visit for fun -* Bar: Help-FOO Strange! two ways to get to the same place. -* Help-FOO:: And yet another! - ->> Now type just an "m" and see what happens. (Read ahead before ->> trying this out, as the dialog box will probably cover these ->> instructions!) - - Now you are "inside" an "m" command. Commands can't be used now; -the next thing you will type must be the name of a subtopic. - - You can change your mind about doing the "m" by clicking the Cancel -button. ->> Try that now; notice the dialog box disappear. ->> Then type another "m". - ->> Now type "BAR", the item name. Don't type Return yet. - - While you are typing the item name, you can use the Backspace -key to cancel one character at a time if you make a mistake. ->> Type one to cancel the "R". You could type another "R" to -replace it. You don't have to, since "BA" is a valid abbreviation. ->> Now you are ready to go. Type a Return. - - After visiting Help-FOO, you should return here (it will tell how). - ->> Type "n" to see more commands. - -File: ibrowse Node: Help-FOO Up: Help-M - -The "u" command - - Congratulations! This is the node Help-FOO. Unlike the other -nodes you have seen, this one has an "Up": "Help-M", the node you -just came from via the "m" command. This is the usual convention-- -the nodes you reach from a menu have Ups that lead back to the menu. -Menus move Down in the tree, and Up moves Up. Previous, on the other -hand, is usually used to "stay on the same level but go backwards". - - You can go back to the node Help-M by typing the command -"u" for "Up". That will put you at the FRONT of the node - to get -back to where you were reading you will have to type some Spaces. - ->> Now type "u" to move back up to Help-M. - -File: ibrowse Node: Help-Adv Next: Help-Q Previous: Help-M - -Some advanced Ibrowse commands - - The course is almost over, so please stick with it to the end. - - If you have been moving around to different nodes and wish to -retrace your steps, the "l" command ("l" for "last") will do that, one -node at a time. If you have been following directions, an "l" command -now will get you back to Help-M. Another "l" command would undo the "u" -and get you back to Help-FOO. Another "l" would undo the M and get you -back to Help-M. - ->> Try typing three "l"'s, pausing in between to see what each "l" does. -Then follow directions again and you will end up back here. - - Note the difference between "l" and "p": "l" moves to where YOU -last were, whereas "p" always moves to the node which the header says -is the "Previous" node (from this node, to Help-M). - - The "d" command gets you instantly to the Directory node. -This node, which is the first one you saw when you entered Ibrowse, -has a menu which leads (directly, or indirectly through other menus), -to all the nodes that exist. - ->> Try doing a "d", then do an "l" to return here (yes, DO return). - - Sometimes, in Ibrowse documentation, you will see a cross reference. -Cross references look like this: *Note Cross: Help-Cross. That is a -real, live cross reference which is named "Cross" and points at the -node named "Help-Cross". - - If you wish to follow a cross reference, you must use the "f" -command. The "f" prompts for the cross reference name (in this case, -"Cross") with a dialog box. - ->> Type "f", followed by "Cross", and a Return. - - The "f" command allows abbreviations just like "m". - - To get a list of all the cross references in the current node, -look in the Ibrowse menu at the top labeled "Footnotes". This menu is -only present if there are cross references in the current node, and -can be used to directly follow a cross reference, just like the "Menu" -menu is another way to choose an item of the node's menu. - ->> Now type "n" to see the last node of the course. - -File: ibrowse Node: Help-Cross - - This is the node reached by the cross reference named "Cross". - - While this node is specifically intended to be reached by a cross -reference, most cross references lead to nodes that "belong" someplace -else far away in the structure of Ibrowse. So you can't expect the -footnote to have a Next, Previous or Up pointing back to where you -came from. In general, the "l" (el) command is the only way to get -back there. - ->> Type "l" to return to the node where the cross reference was. - -File: ibrowse Node: Help-Q Previous: Help-Adv Up: Top - - To get out of Ibrowse, type "q" for "Quit". All Ibrowse windows -will be closed (on UNIX, only those managed by the same process). -To close just one window, use the standard method of closing windows -on your system; you can also use "w". - - This is the end of the course on using Ibrowse. There are some other -commands that are not essential or meant for experienced users; they -are useful, and you can find them by looking in the directory for -documentation on Ibrowse. Finding them will be a good exercise in using -Ibrowse in the usual manner. - ->> Close this window and find back the window where you typed "h" - to enter this tutorial. - Then type "d" to go to the Ibrowse directory node if necessary, - and choose the "Ibrowse" menu item, to get to the node about - Ibrowse and see what other help is available. - -File: ibrowse, Node: Expert, Up: Top, Previous: Top, Next: Add - -Some Advanced Ibrowse Commands ("c", "k", "g", "s", "1" - "9", arrows). - -The "c" command lets you copy text from the window to the clipboard. -You must first select the text to be copied with the mouse. - -The "k" command means "klone" (we are running out of letters now...). -It creates a new Ibrowse window, showing the same node as the current. -You can then make an excursion in the new window to different nodes or -files, while the old window keeps showing the original node. Each -window has its own history for use by the "l" command. - -If you know a node's name, you can go there with the "g" command. -This prompts for a node name with a dialog box. Entering, "Top" -would go to the node called Top in this file (its directory node). -Pressing "g" again and entering "Expert" would come back here. - -Unlike "m", "g" does not allow the use of abbreviations. - -To go to a node in another file, you can include the filename in the -node name by putting it at the front, in parentheses. Thus, -"(dir)Top" would go to the Ibrowse Directory node, which is -node Top in the file dir. - -The node name "*" specifies the whole file. So you can look at all -of the current file by typing "*" or all of any other file -with "(FILENAME)*". - -File names are converted to lower case before they are tried; this -is necessary to be compatible with Emacs Info. (File names are -generally relative to the Info directory, but needn't be.) - -The "s" command allows you to search a whole file for a regular -expression. Unlike the corresponding Emacs Info command, it will -not search beyond the end of the current node. - -Regular expressions are like in UNIX egrep; if you don't know what -regular expressions are, limit your search strings to letters, digits -and spaces. Searches in Ibrowse are case-sensitive; searching for -"foo" will not find "Foo" or "FOO"! - -A description of regular expressions as they occur in Emacs is -available. (*Note Emacs Regular Expressions: (regex)syntax.) -Ibrowse regular expressions are slightly different: the meaning -of \( \| \) is swapped with that of ( | ), and there are no -escapes to handle "words" specially. - -Searching starts after the current focus position. The "B" command -resets the focus to the beginning of the file, but space and backspace -leave it unchanged (so they may render the focus invisible). - -If you grudge the system each character of type-in it requires, -you might like to use the commands "1", "2", "3", through "9". -They are short for the first nine entries of the node menu. - -The left, right and up arrow keys are duplicates of "p", "n" and "u". - -The down arrow key, as well as the Return key, goes to the first item -of the node's menu if there is one, else it executes "n". This is a -quick way to visit all nodes in a tree in pre-order: use Return to go -down and right as far as possible, then use "u" and "n" to go right -at the next higher level. - -File: ibrowse, Node: Add, Up: Top, Previous: Expert, Next: Menus - -To add a new topic to the list in the directory, you must - 1) enter the Emacs text editor. *Note Emacs: (emacs). - 2) create a node, in some file, to document that topic. - 3) put that topic in the menu in the directory. *Note Menu: Menus. - - The new node can live in an existing documentation file, or in a new -one. It must have a ^_ character before it (invisible to the user; -this node has one but you can't see it), and it ends with either a ^_, -or the end of file. A nice way to make a node boundary be a -page boundary as well is to put a ^L RIGHT AFTER the ^_. - - The ^_ starting a node must be followed by a newline or a ^L newline, -after which comes the node's header line. The header line must give -the node's name (by which Ibrowse will find it), and state the names of -the Next, Previous, and Up nodes (if there are any). As you can see, -this node's Up node is the node Top, which points at all the -documentation for Ibrowse. The Next node is "Menus". - - The keywords "Node", "Previous", "Up" and "Next", may appear in -any order, anywhere in the header line, but the recommended order is -the one in this sentence. Each keyword must be followed by a colon, -spaces and tabs, and then the appropriate name. The name may be -terminated with a tab, a comma, or a newline. A space does not end -it; node names may contain spaces. The case of letters in the names -is insignificant. "Previous" can be abbreviated to "Prev". - - A node name has two forms. A node in the current file is named by -what appears after the "Node: " in that node's first line. For -example, this node's name is "Add". A node in another file is named -by "(FILENAME)NODE-WITHIN-FILE", as in "(ibrowse)Add" for this node. -If the file name is relative, it is taken starting from the standard -Info file directory of your site. The name "(FILENAME)Top" can be -abbreviated to just "(FILENAME)". By convention, the name "Top" is -used for the "highest" node in any single file - the node whose "Up" -points out of the file. The Directory node is "(dir)". The Top node -of a document file listed in the Directory should have an "Up: (dir)" -in it. - - The node name "*" is special: it refers to the entire file. Thus, -g* will show you the whole current file. The use of the node * is to -make it possible to make old-fashioned, unstructured files into nodes -of the tree. Footnotes and node menus appearing in a file are disabled -when it is viewed in this way. - - The "Node:" name, in which a node states its own name, must not -contain a filename, since Ibrowse when searching for a node does not -expect one to be there. The Next, Previous and Up names may contain -them. In this node, since the Up node is in the same file, it was not -necessary to use one. - - Note that the nodes in this file have a File name in the header -line. The File names are ignored by Ibrowse, but they serve as -comments to help identify the node for the user. - -File: ibrowse, Node: Menus, Previous: Add, Up: Top, Next: Cross-refs - -How to Create Menus: - - Any node in the Ibrowse hierarchy may have a MENU--a list of subnodes. -The "m" command searches the current node's menu for the topic which it -reads from the terminal. - - A menu begins with a line starting with "* Menu:". The rest of the -line is a comment. After the starting line, every line that begins -with a "* " lists a single topic. The name of the topic--the arg -that the user must give to the "m" command to select this topic-- -comes right after the star and space, and is followed by -a colon, spaces and tabs, and the name of the node which discusses -that topic. The node name, like node names following Next, -Previous and Up, may be terminated with a tab, comma, or newline; -it may also be terminated with a period. - - If the node name and topic name are the same, than rather than -giving the name twice, the abbreviation "* NAME::" may be used -(and should be used, whenever possible, as it reduces the visual -clutter in the menu). - - It is considerate to choose the topic names so that they differ -from each other very near the beginning--this allows the user to type -short abbreviations. In a long menu, it is a good idea to capitalize -the beginning of each item name which is the minimum acceptable -abbreviation for it (a long menu is more than 5 or so entries). - - The node's listed in a node's menu are called its "subnodes", and -it is their "superior". They should each have an "Up:" pointing at -the superior. It is often useful to arrange all or most of the -subnodes in a sequence of Next's/Previous's so that someone who -wants to see them all need not keep revisiting the Menu. - - The Info Directory is simply the menu of the node "(dir)Top"--that -is, node Top in file .../info/dir. You can put new entries in that -menu just like any other menu. The Info Directory is NOT the same as -the file directory called "info". It happens that many of Ibrowse's -files live on that file directory, but they don't have to; and files -on that directory are not automatically listed in the Info Directory -node. - - The Ibrowse program uses a second directory called .../ibrowse, -which contains versions of the "dir" and "info" files adapted to -Ibrowse (the latter renamed to "ibrowse", obviously). It searches -any file first in the "ibrowse", then in the "info" directory. -(Actually, the search path is configurable.) - - Also, although the Info node graph is claimed to be a "hierarchy", -in fact it can be ANY directed graph. Shared structures and pointer -cycles are perfectly possible, and can be used if they are -appropriate to the meaning to be expressed. There is no need for all -the nodes in a file to form a connected structure. In fact, this -file has two connected components. You are in one of them, which is -under the node Top; the other contains the node Help which the "h" -command goes to. In fact, since there is no garbage collector, -nothing terrible happens if a substructure is not pointed to, but -such a substructure will be rather useless since nobody will ever -find out that it exists. - -File: ibrowse, Node: Cross-refs, Previous: Menus, Up: Top, Next: Tags - -Creating Cross References: - - A cross reference can be placed anywhere in the text, unlike a menu -item which must go at the front of a line. A cross reference looks -like a menu item except that it has "*note" instead of "*". It CANNOT -be terminated by a ")", because ")"'s are so often part of node names. -If you wish to enclose a cross reference in parentheses, terminate it -with a period first. Here are two examples of cross references pointers: - - *Note details: commands. (See *note 3: Full Proof.) - -They are just examples. The places they "lead to" don't really exist! - -File: ibrowse, Node: Tags, Previous: Cross-refs, Up: Top, Next: Checking - -Tag Tables for Info Files: - - You can speed up the access to nodes of a large Info file by giving -it a tag table. Unlike the tag table for a program, the tag table for -an Info file lives inside the file itself and will automatically be -used whenever Ibrowse reads in the file. - - To make a tag table, go to a node in the file using Emacs Info and type -M-x Info-tagify. Then you must use C-x C-s to save the file. - - Once the Info file has a tag table, you must make certain it is up -to date. If, as a result of deletion of text, any node moves back -more than a thousand characters in the file from the position -recorded in the tag table, Ibrowse will no longer be able to find that -node. To update the tag table, use the Info-tagify command again. - - An Info file tag table appears at the end of the file and looks like -this: - -^_^L -Tag Table: -File: ibrowse, Node: Cross-refs21419 -File: ibrowse, Node: Tags22145 -^_ -End Tag Table - -Note that it contains one line per node, and this line contains -the beginning of the node's header (ending just after the node name), -a rubout (DEL) character, and the character position in the file of the -beginning of the node. The words "Tag Table" may occur in lower case -as well. - -It is also possible for an extra level of indirection to be present. -In this case, the first line of the Tag table contains the string -"(Indirect)", and preceding the tag table is another "pseudo node" -whose header reads "Indirect:". Each following line has the form -"filename: offset", meaning that nodes at that offset or larger (but -less than the offset in the next line) really occur in the file named -here, and that the file's offset should be subtracted from the node's -offset. (Indirect tables are created by texinfo for large files. -*Note Texinfo: (texinfo). *Note Splitting files: (texinfo)Splitting.) - -File: ibrowse, Node: Checking, Previous: Tags, Up: Top - -Checking an Info File: - - When creating an Info file, it is easy to forget the name of a node -when you are making a pointer to it from another node. If you put in -the wrong name for a node, this will not be detected until someone -tries to go through the pointer using Ibrowse. Verification of the Info -file is an automatic process which checks all pointers to nodes and -reports any pointers which are invalid. Every Next, Previous, and Up -is checked, as is every menu item and every cross reference. In addition, -any Next which doesn't have a Previous pointing back is reported. -Only pointers within the file are checked, because checking pointers -to other files would be terribly slow. But those are usually few. - - To check an Info file, do M-x Info-validate while looking at any -node of the file with Emacs Info. - -Tag table: -Node: Top117 -Node: Summary952 -Node: Help-Small-Screen997 -Node: Help2628 -Node: Help-P3588 -Node: Help-Page4348 -Node: Help-M7763 -Node: Help-FOO13183 -Node: Help-Adv13887 -Node: Help-Cross15923 -Node: Help-Q16443 -Node: Expert17326 -Node: Add20280 -Node: Menus23273 -Node: Cross-refs26394 -Node: Tags27050 -Node: Checking28966 - -End tag table diff --git a/Demo/stdwin/ibrowse/ibrowse.py b/Demo/stdwin/ibrowse/ibrowse.py deleted file mode 100755 index 41574adba7..0000000000 --- a/Demo/stdwin/ibrowse/ibrowse.py +++ /dev/null @@ -1,617 +0,0 @@ -# Browser for "Info files" as used by the Emacs documentation system. -# -# Now you can read Info files even if you can't spare the memory, time or -# disk space to run Emacs. (I have used this extensively on a Macintosh -# with 1 Megabyte main memory and a 20 Meg harddisk.) -# -# You can give this to someone with great fear of complex computer -# systems, as long as they can use a mouse. -# -# Another reason to use this is to encourage the use of Info for on-line -# documentation of software that is not related to Emacs or GNU. -# (In particular, I plan to redo the Python and STDWIN documentation -# in texinfo.) - - -# NB: this is not a self-executing script. You must startup Python, -# import ibrowse, and call ibrowse.main(). On UNIX, the script 'ib' -# runs the browser. - - -# Configuration: -# -# - The pathname of the directory (or directories) containing -# the standard Info files should be set by editing the -# value assigned to INFOPATH in module ifile.py. -# -# - The default font should be set by editing the value of FONT -# in this module (ibrowse.py). -# -# - For fastest I/O, you may look at BLOCKSIZE and a few other -# constants in ifile.py. - - -# This is a fairly large Python program, split in the following modules: -# -# ibrowse.py Main program and user interface. -# This is the only module that imports stdwin. -# -# ifile.py This module knows about the format of Info files. -# It is imported by all of the others. -# -# itags.py This module knows how to read prebuilt tag tables, -# including indirect ones used by large texinfo files. -# -# icache.py Caches tag tables and visited nodes. - - -# XXX There should really be a different tutorial, as the user interface -# XXX differs considerably from Emacs... - - -import sys -import regexp -import stdwin -from stdwinevents import * -import string -from ifile import NoSuchFile, NoSuchNode -import icache - - -# Default font. -# This should be an acceptable argument for stdwin.setfont(); -# on the Mac, this can be a pair (fontname, pointsize), while -# under X11 it should be a standard X11 font name. -# For best results, use a constant width font like Courier; -# many Info files contain tabs that don't align with other text -# unless all characters have the same width. -# -#FONT = ('Monaco', 9) # Mac -FONT = '-schumacher-clean-medium-r-normal--14-140-75-75-c-70-iso8859-1' # X11 - - -# Try not to destroy the list of windows when reload() is used. -# This is useful during debugging, and harmless in production... -# -try: - dummy = windows - del dummy -except NameError: - windows = [] - - -# Default main function -- start at the '(dir)' node. -# -def main(): - start('(dir)') - - -# Start at an arbitrary node. -# The default file is 'ibrowse'. -# -def start(ref): - stdwin.setdefscrollbars(0, 1) - stdwin.setfont(FONT) - stdwin.setdefwinsize(76*stdwin.textwidth('x'), 22*stdwin.lineheight()) - makewindow('ibrowse', ref) - mainloop() - - -# Open a new browser window. -# Arguments specify the default file and a node reference -# (if the node reference specifies a file, the default file is ignored). -# -def makewindow(file, ref): - win = stdwin.open('Info file Browser, by Guido van Rossum') - win.mainmenu = makemainmenu(win) - win.navimenu = makenavimenu(win) - win.textobj = win.textcreate((0, 0), win.getwinsize()) - win.file = file - win.node = '' - win.last = [] - win.pat = '' - win.dispatch = idispatch - win.nodemenu = None - win.footmenu = None - windows.append(win) - imove(win, ref) - -# Create the 'Ibrowse' menu for a new browser window. -# -def makemainmenu(win): - mp = win.menucreate('Ibrowse') - mp.callback = [] - additem(mp, 'New window (clone)', 'K', iclone) - additem(mp, 'Help (tutorial)', 'H', itutor) - additem(mp, 'Command summary', '?', isummary) - additem(mp, 'Close this window', 'W', iclose) - additem(mp, '', '', None) - additem(mp, 'Copy to clipboard', 'C', icopy) - additem(mp, '', '', None) - additem(mp, 'Search regexp...', 'S', isearch) - additem(mp, '', '', None) - additem(mp, 'Reset node cache', '', iresetnodecache) - additem(mp, 'Reset entire cache', '', iresetcache) - additem(mp, '', '', None) - additem(mp, 'Quit', 'Q', iquit) - return mp - -# Create the 'Navigation' menu for a new browser window. -# -def makenavimenu(win): - mp = win.menucreate('Navigation') - mp.callback = [] - additem(mp, 'Menu item...', 'M', imenu) - additem(mp, 'Follow reference...', 'F', ifollow) - additem(mp, 'Go to node...', 'G', igoto) - additem(mp, '', '', None) - additem(mp, 'Next node in tree', 'N', inext) - additem(mp, 'Previous node in tree', 'P', iprev) - additem(mp, 'Up in tree', 'U', iup) - additem(mp, 'Last visited node', 'L', ilast) - additem(mp, 'Top of tree', 'T', itop) - additem(mp, 'Directory node', 'D', idir) - return mp - -# Add an item to a menu, and a function to its list of callbacks. -# (Specifying all in one call is the only way to keep the menu -# and the list of callbacks in synchrony.) -# -def additem(mp, text, shortcut, function): - if shortcut: - mp.additem(text, shortcut) - else: - mp.additem(text) - mp.callback.append(function) - - -# Stdwin event processing main loop. -# Return when there are no windows left. -# Note that windows not in the windows list don't get their events. -# -def mainloop(): - while windows: - event = stdwin.getevent() - if event[1] in windows: - try: - event[1].dispatch(event) - except KeyboardInterrupt: - # The user can type Control-C (or whatever) - # to leave the browser without closing - # the window. Mainly useful for - # debugging. - break - except: - # During debugging, it was annoying if - # every mistake in a callback caused the - # whole browser to crash, hence this - # handler. In a production version - # it may be better to disable this. - # - msg = sys.exc_type - if sys.exc_value: - val = sys.exc_value - if type(val) <> type(''): - val = `val` - msg = msg + ': ' + val - msg = 'Oops, an exception occurred: ' + msg - event = None - stdwin.message(msg) - event = None - - -# Handle one event. The window is taken from the event's window item. -# This function is placed as a method (named 'dispatch') on the window, -# so the main loop will be able to handle windows of a different kind -# as well, as long as they are all placed in the list of windows. -# -def idispatch(event): - type, win, detail = event - if type == WE_CHAR: - if not keybindings.has_key(detail): - detail = string.lower(detail) - if keybindings.has_key(detail): - keybindings[detail](win) - return - if detail in '0123456789': - i = eval(detail) - 1 - if i < 0: i = len(win.menu) + i - if 0 <= i < len(win.menu): - topic, ref = win.menu[i] - imove(win, ref) - return - stdwin.fleep() - return - if type == WE_COMMAND: - if detail == WC_LEFT: - iprev(win) - elif detail == WC_RIGHT: - inext(win) - elif detail == WC_UP: - iup(win) - elif detail == WC_DOWN: - idown(win) - elif detail == WC_BACKSPACE: - ibackward(win) - elif detail == WC_RETURN: - idown(win) - else: - stdwin.fleep() - return - if type == WE_MENU: - mp, item = detail - if mp == None: - pass # A THINK C console menu was selected - elif mp in (win.mainmenu, win.navimenu): - mp.callback[item](win) - elif mp == win.nodemenu: - topic, ref = win.menu[item] - imove(win, ref) - elif mp == win.footmenu: - topic, ref = win.footnotes[item] - imove(win, ref) - return - if type == WE_SIZE: - win.textobj.move((0, 0), win.getwinsize()) - (left, top), (right, bottom) = win.textobj.getrect() - win.setdocsize(0, bottom) - return - if type == WE_CLOSE: - iclose(win) - return - if not win.textobj.event(event): - pass - - -# Paging callbacks - -def ibeginning(win): - win.setorigin(0, 0) - win.textobj.setfocus(0, 0) # To restart searches - -def iforward(win): - lh = stdwin.lineheight() # XXX Should really use the window's... - h, v = win.getorigin() - docwidth, docheight = win.getdocsize() - width, height = win.getwinsize() - if v + height >= docheight: - stdwin.fleep() - return - increment = max(lh, ((height - 2*lh) / lh) * lh) - v = v + increment - win.setorigin(h, v) - -def ibackward(win): - lh = stdwin.lineheight() # XXX Should really use the window's... - h, v = win.getorigin() - if v <= 0: - stdwin.fleep() - return - width, height = win.getwinsize() - increment = max(lh, ((height - 2*lh) / lh) * lh) - v = max(0, v - increment) - win.setorigin(h, v) - - -# Ibrowse menu callbacks - -def iclone(win): - stdwin.setdefwinsize(win.getwinsize()) - makewindow(win.file, win.node) - -def itutor(win): - # The course looks best at 76x22... - stdwin.setdefwinsize(76*stdwin.textwidth('x'), 22*stdwin.lineheight()) - makewindow('ibrowse', 'Help') - -def isummary(win): - stdwin.setdefwinsize(76*stdwin.textwidth('x'), 22*stdwin.lineheight()) - makewindow('ibrowse', 'Summary') - -def iclose(win): - # - # Remove the window from the windows list so the mainloop - # will notice if all windows are gone. - # Delete the textobj since it constitutes a circular reference - # to the window which would prevent it from being closed. - # (Deletion is done by assigning None to avoid crashes - # when closing a half-initialized window.) - # - if win in windows: - windows.remove(win) - win.textobj = None - -def icopy(win): - focustext = win.textobj.getfocustext() - if not focustext: - stdwin.fleep() - else: - stdwin.rotatecutbuffers(1) - stdwin.setcutbuffer(0, focustext) - # XXX Should also set the primary selection... - -def isearch(win): - try: - pat = stdwin.askstr('Search pattern:', win.pat) - except KeyboardInterrupt: - return - if not pat: - pat = win.pat - if not pat: - stdwin.message('No previous pattern') - return - try: - cpat = regexp.compile(pat) - except regexp.error, msg: - stdwin.message('Bad pattern: ' + msg) - return - win.pat = pat - f1, f2 = win.textobj.getfocus() - text = win.text - match = cpat.match(text, f2) - if not match: - stdwin.fleep() - return - a, b = match[0] - win.textobj.setfocus(a, b) - - -def iresetnodecache(win): - icache.resetnodecache() - -def iresetcache(win): - icache.resetcache() - -def iquit(win): - for win in windows[:]: - iclose(win) - - -# Navigation menu callbacks - -def imenu(win): - ichoice(win, 'Menu item (abbreviated):', win.menu, whichmenuitem(win)) - -def ifollow(win): - ichoice(win, 'Follow reference named (abbreviated):', \ - win.footnotes, whichfootnote(win)) - -def igoto(win): - try: - choice = stdwin.askstr('Go to node (full name):', '') - except KeyboardInterrupt: - return - if not choice: - stdwin.message('Sorry, Go to has no default') - return - imove(win, choice) - -def inext(win): - prev, next, up = win.header - if next: - imove(win, next) - else: - stdwin.fleep() - -def iprev(win): - prev, next, up = win.header - if prev: - imove(win, prev) - else: - stdwin.fleep() - -def iup(win): - prev, next, up = win.header - if up: - imove(win, up) - else: - stdwin.fleep() - -def ilast(win): - if not win.last: - stdwin.fleep() - else: - i = len(win.last)-1 - lastnode, lastfocus = win.last[i] - imove(win, lastnode) - if len(win.last) > i+1: - # The move succeeded -- restore the focus - win.textobj.setfocus(lastfocus) - # Delete the stack top even if the move failed, - # else the whole stack would remain unreachable - del win.last[i:] # Delete the entry pushed by imove as well! - -def itop(win): - imove(win, '') - -def idir(win): - imove(win, '(dir)') - - -# Special and generic callbacks - -def idown(win): - if win.menu: - default = whichmenuitem(win) - for topic, ref in win.menu: - if default == topic: - break - else: - topic, ref = win.menu[0] - imove(win, ref) - else: - inext(win) - -def ichoice(win, prompt, list, default): - if not list: - stdwin.fleep() - return - if not default: - topic, ref = list[0] - default = topic - try: - choice = stdwin.askstr(prompt, default) - except KeyboardInterrupt: - return - if not choice: - return - choice = string.lower(choice) - n = len(choice) - for topic, ref in list: - topic = string.lower(topic) - if topic[:n] == choice: - imove(win, ref) - return - stdwin.message('Sorry, no topic matches ' + `choice`) - - -# Follow a reference, in the same window. -# -def imove(win, ref): - savetitle = win.gettitle() - win.settitle('Looking for ' + ref + '...') - # - try: - file, node, header, menu, footnotes, text = \ - icache.get_node(win.file, ref) - except NoSuchFile, file: - win.settitle(savetitle) - stdwin.message(\ - 'Sorry, I can\'t find a file named ' + `file` + '.') - return - except NoSuchNode, node: - win.settitle(savetitle) - stdwin.message(\ - 'Sorry, I can\'t find a node named ' + `node` + '.') - return - # - win.settitle('Found (' + file + ')' + node + '...') - # - if win.file and win.node: - lastnode = '(' + win.file + ')' + win.node - win.last.append(lastnode, win.textobj.getfocus()) - win.file = file - win.node = node - win.header = header - win.menu = menu - win.footnotes = footnotes - win.text = text - # - win.setorigin(0, 0) # Scroll to the beginnning - win.textobj.settext(text) - win.textobj.setfocus(0, 0) - (left, top), (right, bottom) = win.textobj.getrect() - win.setdocsize(0, bottom) - # - if win.footmenu: win.footmenu.close() - if win.nodemenu: win.nodemenu.close() - win.footmenu = None - win.nodemenu = None - # - win.menu = menu - if menu: - win.nodemenu = win.menucreate('Menu') - digit = 1 - for topic, ref in menu: - if digit < 10: - win.nodemenu.additem(topic, `digit`) - else: - win.nodemenu.additem(topic) - digit = digit + 1 - # - win.footnotes = footnotes - if footnotes: - win.footmenu = win.menucreate('Footnotes') - for topic, ref in footnotes: - win.footmenu.additem(topic) - # - win.settitle('(' + win.file + ')' + win.node) - - -# Find menu item at focus -# -findmenu = regexp.compile('^\* [mM]enu:').match -findmenuitem = regexp.compile( \ - '^\* ([^:]+):[ \t]*(:|\([^\t]*\)[^\t,\n.]*|[^:(][^\t,\n.]*)').match -# -def whichmenuitem(win): - if not win.menu: - return '' - match = findmenu(win.text) - if not match: - return '' - a, b = match[0] - i = b - f1, f2 = win.textobj.getfocus() - lastmatch = '' - while i < len(win.text): - match = findmenuitem(win.text, i) - if not match: - break - (a, b), (a1, b1), (a2, b2) = match - if a > f1: - break - lastmatch = win.text[a1:b1] - i = b - return lastmatch - - -# Find footnote at focus -# -findfootnote = \ - regexp.compile('\*[nN]ote ([^:]+):[ \t]*(:|[^:][^\t,\n.]*)').match -# -def whichfootnote(win): - if not win.footnotes: - return '' - i = 0 - f1, f2 = win.textobj.getfocus() - lastmatch = '' - while i < len(win.text): - match = findfootnote(win.text, i) - if not match: - break - (a, b), (a1, b1), (a2, b2) = match - if a > f1: - break - lastmatch = win.text[a1:b1] - i = b - return lastmatch - - -# Now all the "methods" are defined, we can initialize the table -# of key bindings. -# -keybindings = {} - -# Window commands - -keybindings['k'] = iclone -keybindings['h'] = itutor -keybindings['?'] = isummary -keybindings['w'] = iclose - -keybindings['c'] = icopy - -keybindings['s'] = isearch - -keybindings['q'] = iquit - -# Navigation commands - -keybindings['m'] = imenu -keybindings['f'] = ifollow -keybindings['g'] = igoto - -keybindings['n'] = inext -keybindings['p'] = iprev -keybindings['u'] = iup -keybindings['l'] = ilast -keybindings['d'] = idir -keybindings['t'] = itop - -# Paging commands - -keybindings['b'] = ibeginning -keybindings['.'] = ibeginning -keybindings[' '] = iforward diff --git a/Demo/stdwin/ibrowse/icache.py b/Demo/stdwin/ibrowse/icache.py deleted file mode 100755 index 0629bf9f61..0000000000 --- a/Demo/stdwin/ibrowse/icache.py +++ /dev/null @@ -1,74 +0,0 @@ -# Cache management for info file processing. -# The function get_node() is the standard interface; -# its signature is the same as ifile.get_node() but it uses -# the cache and supports indirect tag tables. - - -import string -import ifile -from ifile import NoSuchNode, NoSuchFile -import itags - - -# Special hack to save the cache when using reload(). -# This can just be "cache = {}" in a production version. -# -try: - dummy = cache - del dummy -except NameError: - cache = {} - - -# Clear the entire cache. -# -def resetcache(): - for key in cache.keys(): - del cache[key] - - -# Clear the node info from the cache (the most voluminous data). -# -def resetnodecache(): - for key in cache.keys(): - tags, nodes = cache[key] - cache[key] = tags, {} - - -# Get a node. -# -def get_node(curfile, ref): - file, node = ifile.parse_ref(curfile, ref) - file = string.lower(file) - node = string.lower(node) - if node == '*': - # Don't cache whole file references; - # reading the data is faster than displaying it anyway. - return ifile.get_whole_file(file) # May raise NoSuchFile - if not cache.has_key(file): - cache[file] = get_tags(file), {} # May raise NoSuchFile - tags, nodes = cache[file] - if not nodes.has_key(node): - if not tags.has_key(node): - raise NoSuchNode, ref - file1, offset, line = tags[node] - if not file1: - file1 = file - file1, node1, header, menu, footnotes, text = \ - ifile.get_file_node(file1, offset, node) - nodes[node] = file, node1, header, menu, footnotes, text - return nodes[node] - - -# Get the tag table for a file. -# Either construct one or get the one found in the file. -# Raise NoSuchFile if the file isn't found. -# -def get_tags(file): - f = ifile.try_open(file) # May raise NoSuchFile - tags = itags.get_tags(f) - if not tags: - ###print 'Scanning file...' - f.seek(0) - tags = ifile.make_tags(f) - return tags diff --git a/Demo/stdwin/ibrowse/ifile.py b/Demo/stdwin/ibrowse/ifile.py deleted file mode 100755 index 1ea880ea27..0000000000 --- a/Demo/stdwin/ibrowse/ifile.py +++ /dev/null @@ -1,328 +0,0 @@ -# Tools for info file processing. - -# XXX Need to be more careful with reading ahead searching for nodes. - - -import regexp -import string - - -# Exported exceptions. -# -NoSuchFile = 'no such file' -NoSuchNode = 'no such node' - - -# The search path for info files; this is site-specific. -# Directory names should end in a partname delimiter, -# so they can simply be concatenated to a relative pathname. -# -#INFOPATH = ['', ':Info.Ibrowse:', ':Info:'] # Mac -INFOPATH = ['', '/usr/local/emacs/info/'] # X11 on UNIX - - -# Tunable constants. -# -BLOCKSIZE = 512 # Qty to align reads to, if possible -FUZZ = 2*BLOCKSIZE # Qty to back-up before searching for a node -CHUNKSIZE = 4*BLOCKSIZE # Qty to read at once when reading lots of data - - -# Regular expressions used. -# Note that it is essential that Python leaves unrecognized backslash -# escapes in a string so they can be seen by regexp.compile! -# -findheader = regexp.compile('\037\014?\n(.*\n)').match -findescape = regexp.compile('\037').match -parseheader = regexp.compile('[nN]ode:[ \t]*([^\t,\n]*)').match -findfirstline = regexp.compile('^.*\n').match -findnode = regexp.compile('[nN]ode:[ \t]*([^\t,\n]*)').match -findprev = regexp.compile('[pP]rev[ious]*:[ \t]*([^\t,\n]*)').match -findnext = regexp.compile('[nN]ext:[ \t]*([^\t,\n]*)').match -findup = regexp.compile('[uU]p:[ \t]*([^\t,\n]*)').match -findmenu = regexp.compile('^\* [mM]enu:').match -findmenuitem = regexp.compile( \ - '^\* ([^:]+):[ \t]*(:|\([^\t]*\)[^\t,\n.]*|[^:(][^\t,\n.]*)').match -findfootnote = regexp.compile( \ - '\*[nN]ote ([^:]+):[ \t]*(:|[^:][^\t,\n.]*)').match -parsenoderef = regexp.compile('^\((.*)\)(.*)$').match - - -# Get a node and all information pertaining to it. -# This doesn't work if there is an indirect tag table, -# and in general you are better off using icache.get_node() instead. -# Functions get_whole_file() and get_file_node() provide part -# functionality used by icache. -# Raise NoSuchFile or NoSuchNode as appropriate. -# -def get_node(curfile, ref): - file, node = parse_ref(curfile, ref) - if node == '*': - return get_whole_file(file) - else: - return get_file_node(file, 0, node) -# -def get_whole_file(file): - f = try_open(file) # May raise NoSuchFile - text = f.read() - header, menu, footnotes = ('', '', ''), [], [] - return file, '*', header, menu, footnotes, text -# -def get_file_node(file, offset, node): - f = try_open(file) # May raise NoSuchFile - text = find_node(f, offset, node) # May raise NoSuchNode - node, header, menu, footnotes = analyze_node(text) - return file, node, header, menu, footnotes, text - - -# Parse a node reference into a file (possibly default) and node name. -# Possible reference formats are: "NODE", "(FILE)", "(FILE)NODE". -# Default file is the curfile argument; default node is Top. -# A node value of '*' is a special case: the whole file should -# be interpreted (by the caller!) as a single node. -# -def parse_ref(curfile, ref): - match = parsenoderef(ref) - if not match: - file, node = curfile, ref - else: - (a, b), (a1, b1), (a2, b2) = match - file, node = ref[a1:b1], ref[a2:b2] - if not file: - file = curfile # (Is this necessary?) - if not node: - node = 'Top' - return file, node - - -# Extract node name, links, menu and footnotes from the node text. -# -def analyze_node(text): - # - # Get node name and links from the header line - # - match = findfirstline(text) - if match: - (a, b) = match[0] - line = text[a:b] - else: - line = '' - node = get_it(text, findnode) - prev = get_it(text, findprev) - next = get_it(text, findnext) - up = get_it(text, findup) - # - # Get the menu items, if there is a menu - # - menu = [] - match = findmenu(text) - if match: - (a, b) = match[0] - while 1: - match = findmenuitem(text, b) - if not match: - break - (a, b), (a1, b1), (a2, b2) = match - topic, ref = text[a1:b1], text[a2:b2] - if ref == ':': - ref = topic - menu.append(topic, ref) - # - # Get the footnotes - # - footnotes = [] - b = 0 - while 1: - match = findfootnote(text, b) - if not match: - break - (a, b), (a1, b1), (a2, b2) = match - topic, ref = text[a1:b1], text[a2:b2] - if ref == ':': - ref = topic - footnotes.append(topic, ref) - # - return node, (prev, next, up), menu, footnotes -# -def get_it(line, matcher): - match = matcher(line) - if not match: - return '' - else: - (a, b), (a1, b1) = match - return line[a1:b1] - - -# Find a node in an open file. -# The offset (from the tags table) is a hint about the node's position. -# Pass zero if there is no tags table. -# Raise NoSuchNode if the node isn't found. -# NB: This seeks around in the file. -# -def find_node(f, offset, node): - node = string.lower(node) # Just to be sure - # - # Position a little before the given offset, - # so we may find the node even if it has moved around - # in the file a little. - # - offset = max(0, ((offset-FUZZ) / BLOCKSIZE) * BLOCKSIZE) - f.seek(offset) - # - # Loop, hunting for a matching node header. - # - while 1: - buf = f.read(CHUNKSIZE) - if not buf: - break - i = 0 - while 1: - match = findheader(buf, i) - if match: - (a,b), (a1,b1) = match - start = a1 - line = buf[a1:b1] - i = b - match = parseheader(line) - if match: - (a,b), (a1,b1) = match - key = string.lower(line[a1:b1]) - if key == node: - # Got it! Now read the rest. - return read_node(f, buf[start:]) - elif findescape(buf, i): - next = f.read(CHUNKSIZE) - if not next: - break - buf = buf + next - else: - break - # - # If we get here, we didn't find it. Too bad. - # - raise NoSuchNode, node - - -# Finish off getting a node (subroutine for find_node()). -# The node begins at the start of buf and may end in buf; -# if it doesn't end there, read additional data from f. -# -def read_node(f, buf): - i = 0 - match = findescape(buf, i) - while not match: - next = f.read(CHUNKSIZE) - if not next: - end = len(buf) - break - i = len(buf) - buf = buf + next - match = findescape(buf, i) - else: - # Got a match - (a, b) = match[0] - end = a - # Strip trailing newlines - while end > 0 and buf[end-1] == '\n': - end = end-1 - buf = buf[:end] - return buf - - -# Read reverse starting at offset until the beginning of a node is found. -# Then return a buffer containing the beginning of the node, -# with f positioned just after the buffer. -# The buffer will contain at least the full header line of the node; -# the caller should finish off with read_node() if it is the right node. -# (It is also possible that the buffer extends beyond the node!) -# Return an empty string if there is no node before the given offset. -# -def backup_node(f, offset): - start = max(0, ((offset-CHUNKSIZE) / BLOCKSIZE) * BLOCKSIZE) - end = offset - while start < end: - f.seek(start) - buf = f.read(end-start) - i = 0 - hit = -1 - while 1: - match = findheader(buf, i) - if match: - (a,b), (a1,b1) = match - hit = a1 - i = b - elif end < offset and findescape(buf, i): - next = f.read(min(offset-end, BLOCKSIZE)) - if not next: - break - buf = buf + next - end = end + len(next) - else: - break - if hit >= 0: - return buf[hit:] - end = start - start = max(0, end - CHUNKSIZE) - return '' - - -# Make a tag table for the given file by scanning the file. -# The file must be open for reading, and positioned at the beginning -# (or wherever the hunt for tags must begin; it is read till the end). -# -def make_tags(f): - tags = {} - while 1: - offset = f.tell() - buf = f.read(CHUNKSIZE) - if not buf: - break - i = 0 - while 1: - match = findheader(buf, i) - if match: - (a,b), (a1,b1) = match - start = offset+a1 - line = buf[a1:b1] - i = b - match = parseheader(line) - if match: - (a,b), (a1,b1) = match - key = string.lower(line[a1:b1]) - if tags.has_key(key): - print 'Duplicate node:', - print key - tags[key] = '', start, line - elif findescape(buf, i): - next = f.read(CHUNKSIZE) - if not next: - break - buf = buf + next - else: - break - return tags - - -# Try to open a file, return a file object if succeeds. -# Raise NoSuchFile if the file can't be opened. -# Should treat absolute pathnames special. -# -def try_open(file): - for dir in INFOPATH: - try: - return open(dir + file, 'r') - except IOError: - pass - raise NoSuchFile, file - - -# A little test for the speed of make_tags(). -# -TESTFILE = 'texinfo-1' -def test_make_tags(): - import time - f = try_open(TESTFILE) - t1 = time.millitimer() - tags = make_tags(f) - t2 = time.millitimer() - print 'Making tag table for', `TESTFILE`, 'took', t2-t1, 'msec.' diff --git a/Demo/stdwin/ibrowse/itags.py b/Demo/stdwin/ibrowse/itags.py deleted file mode 100755 index f30f3fd5a1..0000000000 --- a/Demo/stdwin/ibrowse/itags.py +++ /dev/null @@ -1,127 +0,0 @@ -# Utility module for 'icache.py': interpret tag tables and indirect nodes. - -# (This module is a bit chatty when confronted with the unexpected.) - - -import regexp -import string -import ifile - - -# Get the tag table of an open file, as a dictionary. -# Seeks around in the file; after reading, the position is undefined. -# Return an empty tag table if none is found. -# -def get_tags(f): - # - # First see if the last "node" is the end of tag table marker. - # - f.seek(0, 2) # Seek to EOF - end = f.tell() - buf = ifile.backup_node(f, end) - if not labelmatch(buf, 0, 'end tag table\n'): - return {} # No succes - # - # Next backup to the previous "node" -- the tag table itself. - # - ###print 'Getting prebuilt tag table...' - end = f.tell() - len(buf) - buf = ifile.backup_node(f, end) - label = 'tag table:\n' - if not labelmatch(buf, 0, label): - print 'Weird: end tag table marker but no tag table?' - print 'Node begins:', `buf[:50]` - return {} - # - # Now read the whole tag table. - # - end = f.tell() - len(buf) # Do this first! - buf = ifile.read_node(f, buf) - # - # First check for an indirection table. - # - indirlist = [] - if labelmatch(buf, len(label), '(indirect)\n'): - indirbuf = ifile.backup_node(f, end) - if not labelmatch(indirbuf, 0, 'indirect:\n'): - print 'Weird: promised indirection table not found' - print 'Node begins:', `indirbuf[:50]` - # Carry on. Things probably won't work though. - else: - indirbuf = ifile.read_node(f, indirbuf) - indirlist = parse_indirlist(indirbuf) - # - # Now parse the tag table. - # - findtag = regexp.compile('^(.*[nN]ode:[ \t]*(.*))\177([0-9]+)$').match - i = 0 - tags = {} - while 1: - match = findtag(buf, i) - if not match: - break - (a,b), (a1,b1), (a2,b2), (a3,b3) = match - i = b - line = buf[a1:b1] - node = string.lower(buf[a2:b2]) - offset = eval(buf[a3:b3]) # XXX What if it overflows? - if tags.has_key(node): - print 'Duplicate key in tag table:', `node` - file, offset = map_offset(offset, indirlist) - tags[node] = file, offset, line - # - return tags - - -# Return true if buf[i:] begins with a label, after lower case conversion. -# The label argument must be in lower case. -# -def labelmatch(buf, i, label): - return string.lower(buf[i:i+len(label)]) == label - - -# Parse the indirection list. -# Return a list of (filename, offset) pairs ready for use. -# -def parse_indirlist(buf): - list = [] - findindir = regexp.compile('^(.+):[ \t]*([0-9]+)$').match - i = 0 - while 1: - match = findindir(buf, i) - if not match: - break - (a,b), (a1,b1), (a2,b2) = match - file = buf[a1:b1] - offset = eval(buf[a2:b2]) # XXX What if this gets overflow? - list.append(file, offset) - i = b - return list - - -# Map an offset through the indirection list. -# Return (filename, new_offset). -# If the list is empty, return the given offset and an empty file name. -# -def map_offset(offset, indirlist): - if not indirlist: - return '', offset - # - # XXX This could be done more elegant. - # - filex, offx = indirlist[0] - for i in range(len(indirlist)): - file1, off1 = indirlist[i] - if i+1 >= len(indirlist): - file2, off2 = '', 0x7fffffff - else: - file2, off2 = indirlist[i+1] - if off1 <= offset < off2: - # Add offx+2 to compensate for extra header. - # No idea whether this is always correct. - return file1, offset-off1 + offx+2 - # - # XXX Shouldn't get here. - # - print 'Oops, map_offset fell through' - return '', offset # Not likely to get good results diff --git a/Demo/stdwin/jukebox.py b/Demo/stdwin/jukebox.py deleted file mode 100755 index e218e666c7..0000000000 --- a/Demo/stdwin/jukebox.py +++ /dev/null @@ -1,413 +0,0 @@ -#! /usr/local/bin/python - -# XXX This only works on SGIs running IRIX 4.0 or higher - -# JUKEBOX: browse directories full of sampled sound files. -# -# One or more "list windows" display the files and subdirectories of -# the arguments. Double-clicking on a subdirectory opens a new window -# displaying its contents (and so on recursively). Double clicking -# on a file plays it as a sound file (assuming it is one). -# -# Playing is asynchronous: the application keeps listening for events -# while the sample is playing, so you can cancel playing or start a -# new sample right away. Synchronous playing is available through the -# -s option. -# -# The control window displays a "stop button" that cancel the current -# play request. -# -# Most sound file formats recognized by SOX or SFPLAY are recognized. -# Since conversion is costly, converted files are cached in -# /usr/tmp/@j* until the user quits or changes the sampling rate via -# the Rate menu. - -import commands -import getopt -import os -from stat import * -import rand -import stdwin -from stdwinevents import * -import sys -import tempfile -import sndhdr - -from WindowParent import WindowParent -from Buttons import PushButton - -# Pathnames - -DEF_DB = '/usr/local/sounds' # Default directory of sounds -SOX = '/usr/local/bin/sox' # Sound format conversion program -SFPLAY = '/usr/sbin/sfplay' # Sound playing program - - -# Global variables - -class struct: pass # Class to define featureless structures - -G = struct() # Holds writable global variables - - -# Main program - -def main(): - G.synchronous = 0 # If set, use synchronous audio.write() - G.debug = 0 # If set, print debug messages - G.busy = 0 # Set while asynchronous playing is active - G.windows = [] # List of open windows, except control - G.mode = '' # File type (default any that sfplay knows) - G.rate = 0 # Sampling rate (default " " " ") - G.tempprefix = tempfile.mktemp() - # - try: - optlist, args = getopt.getopt(sys.argv[1:], 'dr:st:') - except getopt.error, msg: - sys.stdout = sys.stderr - print msg - print 'usage: jukebox [-d] [-s] [-t type] [-r rate]' - print ' -d debugging (-dd event debugging)' - print ' -s synchronous playing' - print ' -t type file type' - print ' -r rate sampling rate' - sys.exit(2) - # - for optname, optarg in optlist: - if optname == '-d': - G.debug = G.debug + 1 - elif optname == '-r': - G.rate = int(eval(optarg)) - elif optname == '-s': - G.synchronous = 1 - elif optname == '-t': - G.mode = optarg - # - if G.debug: - for name in G.__dict__.keys(): - print 'G.' + name, '=', `G.__dict__[name]` - # - if not args: - args = [DEF_DB] - # - G.cw = opencontrolwindow() - for dirname in args: - G.windows.append(openlistwindow(dirname)) - # - # - try: - maineventloop() - finally: - clearcache() - killchild() - -# Entries in Rate menu: -rates = ['default', '7350', \ - '8000', '11025', '16000', '22050', '32000', '41000', '48000'] - -def maineventloop(): - mouse_events = WE_MOUSE_DOWN, WE_MOUSE_MOVE, WE_MOUSE_UP - while G.windows: - try: - type, w, detail = event = stdwin.getevent() - except KeyboardInterrupt: - killchild() - continue - if w == G.cw.win: - if type == WE_CLOSE: - return - if type == WE_TIMER: - checkchild() - if G.busy: - G.cw.win.settimer(1) - elif type == WE_MENU: - menu, item = detail - if menu is G.ratemenu: - clearcache() - if item == 0: - G.rate = 0 - else: - G.rate = eval(rates[item]) - for i in range(len(rates)): - menu.check(i, (i == item)) - else: - G.cw.dispatch(event) - else: - if type == WE_DRAW: - w.drawproc(w, detail) - elif type in mouse_events: - w.mouse(w, type, detail) - elif type == WE_CLOSE: - w.close(w) - del w, event - else: - if G.debug > 1: print type, w, detail - -def checkchild(): - if G.busy: - waitchild(1) - -def killchild(): - if G.busy: - os.kill(G.busy, 9) - waitchild(0) - -def waitchild(options): - pid, sts = os.waitpid(G.busy, options) - if pid == G.busy: - G.busy = 0 - G.stop.enable(0) - - -# Control window -- to set gain and cancel play operations in progress - -def opencontrolwindow(): - stdwin.setdefscrollbars(0, 0) - cw = WindowParent().create('Jukebox', (0, 0)) - # - stop = PushButton().definetext(cw, ' Stop ') - stop.hook = stop_hook - stop.enable(0) - G.stop = stop - # - cw.realize() - # - G.ratemenu = cw.win.menucreate('Rate') - for r in rates: - G.ratemenu.additem(r) - if G.rate == 0: - G.ratemenu.check(0, 1) - else: - for i in len(range(rates)): - if rates[i] == `G.rate`: - G.ratemenu.check(i, 1) - # - return cw - -def stop_hook(self): - killchild() - - -# List windows -- to display list of files and subdirectories - -def openlistwindow(dirname): - list = os.listdir(dirname) - list.sort() - i = 0 - while i < len(list): - if list[i][0] == '.': - del list[i] - else: - i = i+1 - for i in range(len(list)): - fullname = os.path.join(dirname, list[i]) - if os.path.isdir(fullname): - info = '/' - else: - try: - size = os.stat(fullname)[ST_SIZE] - info = `(size + 1023)/1024` + 'k' - except IOError: - info = '???' - info = '(' + info + ')' - list[i] = list[i], info - width = maxwidth(list) - # width = width + stdwin.textwidth(' ') # XXX X11 stdwin bug workaround - height = len(list) * stdwin.lineheight() - stdwin.setdefwinsize(width, min(height, 500)) - stdwin.setdefscrollbars(0, 1) - w = stdwin.open(dirname) - stdwin.setdefwinsize(0, 0) - w.setdocsize(width, height) - w.drawproc = drawlistwindow - w.mouse = mouselistwindow - w.close = closelistwindow - w.dirname = dirname - w.list = list - w.selected = -1 - return w - -def maxwidth(list): - width = 1 - for name, info in list: - w = stdwin.textwidth(name + ' ' + info) - if w > width: width = w - return width - -def drawlistwindow(w, area): -## (left, top), (right, bottom) = area - d = w.begindrawing() - d.erase((0, 0), (1000, 10000)) - lh = d.lineheight() - h, v = 0, 0 - for name, info in w.list: - if info == '/': - text = name + '/' - else: - text = name + ' ' + info - d.text((h, v), text) - v = v + lh - showselection(w, d) - d.close() - -def hideselection(w, d): - if w.selected >= 0: - invertselection(w, d) - -def showselection(w, d): - if w.selected >= 0: - invertselection(w, d) - -def invertselection(w, d): - lh = d.lineheight() - h1, v1 = p1 = 0, w.selected*lh - h2, v2 = p2 = 1000, v1 + lh - d.invert(p1, p2) - -def mouselistwindow(w, type, detail): - (h, v), clicks, button = detail[:3] - d = w.begindrawing() - lh = d.lineheight() - if 0 <= v < lh*len(w.list): - i = v / lh - else: - i = -1 - if w.selected <> i: - hideselection(w, d) - w.selected = i - showselection(w, d) - d.close() - if type == WE_MOUSE_DOWN and clicks >= 2 and i >= 0: - setcursors('watch') - name, info = w.list[i] - fullname = os.path.join(w.dirname, name) - if info == '/': - if clicks == 2: - G.windows.append(openlistwindow(fullname)) - else: - playfile(fullname) - setcursors('cross') - -def closelistwindow(w): - G.windows.remove(w) - -def setcursors(cursor): - for w in G.windows: - w.setwincursor(cursor) - G.cw.win.setwincursor(cursor) - - -# Playing tools - -cache = {} - -def clearcache(): - for x in cache.keys(): - cmd = 'rm -f ' + cache[x] - if G.debug: print cmd - sts = os.system(cmd) - if sts: - print cmd - print 'Exit status', sts - del cache[x] - -validrates = (8000, 11025, 16000, 22050, 32000, 44100, 48000) - -def playfile(filename): - killchild() - try: - tuple = sndhdr.what(filename) - except IOError, msg: - print 'Can\'t open', filename, msg - stdwin.fleep() - return - raw = 0 - if tuple: - mode, rate = tuple[:2] - if rate == 0: - rate = G.rate - if rate == 0: - rate = 8000 - else: - mode = G.mode - rate = G.rate - if G.debug: print 'mode =', mode, 'rate =', rate - if mode in ('au', 'aiff', 'wav', 'aifc', 'ul', 'ub', 'sb') and \ - rate in validrates: - tempname = filename - if mode in ('ul', 'ub', 'sb'): - raw = 1 - elif cache.has_key(filename): - tempname = cache[filename] - else: - tempname = G.tempprefix + `rand.rand()` + '.aiff' - cmd = SOX - if G.debug: - cmd = cmd + ' -V' - if mode <> '': - cmd = cmd + ' -t ' + mode - cmd = cmd + ' ' + commands.mkarg(filename) - cmd = cmd + ' -t aiff' - if rate not in validrates: - rate = 32000 - if rate: - cmd = cmd + ' -r ' + `rate` - cmd = cmd + ' ' + tempname - if G.debug: print cmd - sts = os.system(cmd) - if sts: - print cmd - print 'Exit status', sts - stdwin.fleep() - try: - os.unlink(tempname) - except: - pass - return - cache[filename] = tempname - if raw: - pid = sfplayraw(tempname, tuple) - else: - pid = sfplay(tempname, []) - if G.synchronous: - sts = os.wait(pid, 0) - else: - G.busy = pid - G.stop.enable(1) - G.cw.win.settimer(1) - -def sfplayraw(filename, tuple): - args = ['-i'] - type, rate, channels, frames, bits = tuple - if type == 'ul': - args.append('mulaw') - elif type == 'ub': - args = args + ['integer', '8', 'unsigned'] - elif type == 'sb': - args = args + ['integer', '8', '2scomp'] - else: - print 'sfplayraw: warning: unknown type in', tuple - if channels > 1: - args = args + ['channels', `channels`] - if not rate: - rate = G.rate - if rate: - args = args + ['rate', `rate`] - args.append('end') - return sfplay(filename, args) - -def sfplay(filename, args): - if G.debug: - args = ['-p'] + args - args = [SFPLAY, '-r'] + args + [filename] - if G.debug: print 'sfplay:', args - pid = os.fork() - if pid == 0: - # Child - os.execv(SFPLAY, args) - # NOTREACHED - else: - # Parent - return pid - -main() diff --git a/Demo/stdwin/lpwin.py b/Demo/stdwin/lpwin.py deleted file mode 100755 index eaf98bea34..0000000000 --- a/Demo/stdwin/lpwin.py +++ /dev/null @@ -1,198 +0,0 @@ -#! /usr/local/bin/python - -# Watch line printer queues (only works with BSD 4.3 lpq). -# -# This brings up a window containing one line per printer argument. -# -# Each line gives a small summary of the printer's status and queue. -# The status tries to give as much relevant information as possible, -# and gives extra info if you have jobs in the queue. -# -# The line's background color gives a hint at the status: navajo white -# for idle, green if your job is now printing, yellow/orange for -# small/large queue, red for errors. -# -# To reduce the duration of the unresponsive time while it is waiting -# for an lpq subprocess to finish, it polls one printer every -# delay/len(printers) seconds. A tiny dot indicates the last printer -# updated. Hit the mouse button in the window to update the next one. -# -# To do: -# - add an argument to override the default delay -# - add arguments to override the default colors -# - better heuristic for small/large queue (and more colors!) -# - mouse clicks should update the printer clicked in -# - better visual appearance, e.g., boxes around the lines? - -import posix -import sys -import time -import string - -import stdwin -from stdwinevents import * -import mainloop - -# Default parameters -DEF_PRINTER = 'oce' # This is CWI specific! -DEF_DELAY = 10 - -# Color assignments -c_unknown = stdwin.fetchcolor('white') -c_idle = stdwin.fetchcolor('navajo white') -c_ontop = stdwin.fetchcolor('green') -c_smallqueue = stdwin.fetchcolor('yellow') -c_bigqueue = stdwin.fetchcolor('orange') -c_error = stdwin.fetchcolor('red') - -def main(): - delay = DEF_DELAY - # - try: - thisuser = posix.environ['LOGNAME'] - except: - thisuser = posix.environ['USER'] - # - printers = sys.argv[1:] - if printers: - # Strip '-P' from printer names just in case - # the user specified it... - for i in range(len(printers)): - if printers[i][:2] == '-P': - printers[i] = printers[i][2:] - else: - if posix.environ.has_key('PRINTER'): - printers = [posix.environ['PRINTER']] - else: - printers = [DEF_PRINTER] - # - width = stdwin.textwidth('in')*20 - height = len(printers) * stdwin.lineheight() + 5 - stdwin.setdefwinsize(width, height) - stdwin.setdefscrollbars(0, 0) - # - win = stdwin.open('lpwin') - # - win.printers = printers - win.colors = [c_unknown] * len(printers) - win.texts = printers[:] - win.next = 0 - win.delay = DEF_DELAY - win.thisuser = thisuser - win.dispatch = lpdispatch - # - win.settimer(1) - # - mainloop.register(win) - mainloop.mainloop() - -def lpdispatch(event): - type, win, detail = event - if type == WE_CLOSE or type == WE_CHAR and detail in ('q', 'Q'): - mainloop.unregister(win) - elif type == WE_DRAW: - drawproc(win) - elif type == WE_TIMER: - update(win) - win.change((0,0), (10000, 10000)) - elif type == WE_MOUSE_UP: - win.settimer(1) - -def drawproc(win): - d = win.begindrawing() - offset = d.textwidth('.') - h, v = 0, 0 - for i in range(len(win.printers)): - text = win.texts[i] - color = win.colors[i] - d.setbgcolor(color) - d.erase((h, v), (h+10000, v+d.lineheight())) - if (i+1) % len(win.printers) == win.next and color <> c_unknown: - d.text((h, v), '.') - d.text((h+offset, v), text) - v = v + d.lineheight() - -def update(win): - i = win.next - win.next = (i+1) % len(win.printers) - win.texts[i], win.colors[i] = makestatus(win.printers[i], win.thisuser) - win.settimer(int(win.delay * 10.0 / len(win.printers))) - -def makestatus(name, thisuser): - pipe = posix.popen('lpq -P' + name + ' 2>&1', 'r') - lines = [] - users = {} - aheadbytes = 0 - aheadjobs = 0 - userseen = 0 - totalbytes = 0 - totaljobs = 0 - color = c_unknown - while 1: - line = pipe.readline() - if not line: break - fields = string.split(line) - n = len(fields) - if len(fields) >= 6 and fields[n-1] == 'bytes': - rank = fields[0] - user = fields[1] - job = fields[2] - files = fields[3:-2] - bytes = eval(fields[n-2]) - if user == thisuser: - userseen = 1 - if aheadjobs == 0: - color = c_ontop - elif not userseen: - aheadbytes = aheadbytes + bytes - aheadjobs = aheadjobs + 1 - totalbytes = totalbytes + bytes - totaljobs = totaljobs + 1 - if color == c_unknown: - color = c_smallqueue - elif color == c_smallqueue: - color = c_bigqueue - if users.has_key(user): - ujobs, ubytes = users[user] - else: - ujobs, ubytes = 0, 0 - ujobs = ujobs + 1 - ubytes = ubytes + bytes - users[user] = ujobs, ubytes - else: - if fields and fields[0] <> 'Rank': - line = string.strip(line) - if line == 'no entries': - line = name + ': idle' - if color == c_unknown: - color = c_idle - elif line[-22:] == ' is ready and printing': - line = line[:-22] - else: - line = name + ': ' + line - color = c_error - lines.append(line) - # - if totaljobs: - line = `(totalbytes+1023)/1024` + ' K' - if totaljobs <> len(users): - line = line + ' (' + `totaljobs` + ' jobs)' - if len(users) == 1: - line = line + ' for ' + users.keys()[0] - else: - line = line + ' for ' + `len(users)` + ' users' - if userseen: - if aheadjobs == 0: - line = line + ' (' + thisuser + ' first)' - else: - line = line + ' (' + `(aheadbytes+1023)/1024` - line = line + ' K before ' + thisuser + ')' - lines.append(line) - # - sts = pipe.close() - if sts: - lines.append('lpq exit status ' + `sts`) - color = c_error - return string.joinfields(lines, ': '), color - -main() diff --git a/Demo/stdwin/microedit.py b/Demo/stdwin/microedit.py deleted file mode 100755 index eca093a188..0000000000 --- a/Demo/stdwin/microedit.py +++ /dev/null @@ -1,183 +0,0 @@ -#! /usr/local/bin/python - -# A minimal single-window text editor using STDWIN's text objects. -# -# Usage: microedit file -# -# This is not intended as a real application but as an introduction -# to STDWIN programming in Python, especially text objects. -# Once you understand microedit.py, study miniedit.py to learn -# about multiple windows and menus, cut and paste, etc. - - -import sys -import stdwin -from stdwinevents import * - - -# Main program -# -def main(): - # - # Get the filename argument and read its contents as one very - # large string. - # An exception will terminate the program if there is no argument - # or if the file could not be read... - # - filename = sys.argv[1] - fp = open(filename, 'r') - contents = fp.read() - del fp # Close the file - # - # Create the window, using the filename as window title - # - window = stdwin.open(filename) - # - # Add a simple File menu to the window with two items - # - filemenu = window.menucreate('File') - filemenu.additem('Save', 'S') # Item 0 (shortcut Meta-S) - filemenu.additem('Save As...') # Item 1 - # - # Create a text object occupying the entire window - # and fill it with the file's contents - # - corner = window.getwinsize() # (width, height) - area = (0, 0), corner # Rectangle as large as the window - text = window.textcreate(area) - text.settext(contents) - del contents # Get rid of contents object - fix_textsize(window, text) # Set document size accordingly - # - # Main event loop -- stop if a close request comes in. - # - # STDWIN applications should regularly call stdwin.getevent() - # otherwise the windows won't function as expected. - # - while 1: - # - # Get the next event - # - type, w, detail = e = stdwin.getevent() - # - # Event decoding switch - # - if type == WE_CLOSE: - break # Stop (no check for saved file!) - elif type == WE_SIZE: - # - # The window was resized -- - # let the text object recompute the line breaks - # and change the document size accordingly, - # so scroll bars will work - # - fix_textsize(window, text) - elif type == WE_MENU: - # - # Execute a file menu request (our only menu) - # - menu, item = detail - if item == 0: - # - # "Save": save to the current filename - # - dummy = save_file(window, text, filename) - elif item == 1: - # - # "Save As": ask a new filename, save to it, - # and make it the current filename - # - # NB: askfile raises KeyboardInterrupt - # if the user cancels the dialog, hence - # the try statement - # - try: - newfile = stdwin.askfile( \ - 'Save as:', filename, 1) - except KeyboardInterrupt: - newfile = '' - if newfile: - if save_file(window, text, newfile): - filename = newfile - window.settitle(filename) - elif text.event(e): - # - # The text object has handled the event. - # Fix the document size if necessary. - # Note: this sometimes fixes the size - # unnecessarily, e.g., for arrow keys. - # - if type in (WE_CHAR, WE_COMMAND): - fix_docsize(window, text) - - -# Save the window's contents to the filename. -# If the open() fails, put up a warning message and return 0; -# if the save succeeds, return 1. -# -def save_file(window, text, filename): - # - # Open the file for writing, handling exceptions - # - try: - fp = open(filename, 'w') - except RuntimeError: - stdwin.message('Cannot create ' + filename) - return 0 - # - # Get the contents of the text object as one very long string - # - contents = text.gettext() - # - # Write the contents to the file - # - fp.write(contents) - # - # The file is automatically closed when this routine returns - # - return 1 - - -# Change the size of the text object to fit in the window, -# and then fix the window's document size to fit around the text object. -# -def fix_textsize(window, text): - # - # Compute a rectangle as large as the window - # - corner = window.getwinsize() # (width, height) - area = (0, 0), (corner) - # - # Move the text object to this rectangle. - # Note: text.move() ignores the bottom coordinate! - # - text.move(area) - # - # Now fix the document size accordingly - # - fix_docsize(window, text) - - -# Fix the document size, after the text has changed -# -def fix_docsize(window, text): - # - # Get the actual rectangle occupied by the text object. - # This has the same left, top and right, but a different bottom. - # - area = text.getrect() - # - # Compute the true height of the text object - # - origin, corner = area - width, height = corner - # - # Set the document height to the text object's height. - # The width is zero since we don't want a horizontal scroll bar. - # - window.setdocsize(0, height) - - -# Once all functions are defined, call main() -# -main() diff --git a/Demo/stdwin/miniedit.py b/Demo/stdwin/miniedit.py deleted file mode 100755 index 3d4aeeaa0d..0000000000 --- a/Demo/stdwin/miniedit.py +++ /dev/null @@ -1,356 +0,0 @@ -#! /usr/local/bin/python - -# A miniature multi-window editor using STDWIN's text objects. -# -# Usage: miniedit [file] ... -# -# The user interface is similar to that of the miniedit demo application -# in C that comes with STDWIN. -# -# XXX need to comment the functions -# XXX Not yet implemented: -# disabling menu entries for inapplicable actions -# Find operations - - -import sys -import stdwin -from stdwinevents import * - - -# Constant: list of WE_COMMAND events that (may) change the text buffer -# so we can decide whether to set the 'changed' flag. -# Note that it is possible for such a command to fail (a backspace -# at the beginning of the buffer) but we'll set the changed flag anyway -# -- it's too complicated to check this condition right now. -# -changing = [WC_RETURN, WC_TAB, WC_BACKSPACE] - - -# The list of currently open windows; -# this is maintained so we can stop when there are no windows left -# -windows = [] - - -# A note on window data attributes (set by open_window): -# -# w.textobject the window's text object -# w.changed true when the window's text is changed -# w.filename filename connected to the window; '' if none - - -# Main program -# -def main(): - # - # Set a reasonable default window size. - # If we are using a fixed-width font this will open a 80x24 window; - # for variable-width fonts we approximate this based on an average - # - stdwin.setdefwinsize(40*stdwin.textwidth('in'), 24*stdwin.lineheight()) - # - # Create global menus (as local variables) - # - filemenu = make_file_menu(stdwin) - editmenu = make_edit_menu(stdwin) - findmenu = make_find_menu(stdwin) - # - # Get the list of files from the command line (maybe none) - # - files = sys.argv[1:] - # - # Open any files -- errors will be reported but do won't stop us - # - for filename in files: - open_file(filename) - # - # If there were no files, or none of them could be opened, - # put up a dialog asking for a filename - # - if not windows: - try: - open_dialog(None) - except KeyboardInterrupt: - pass # User cancelled - # - # If the dialog was cancelled, create an empty new window - # - if not windows: - new_window(None) - # - # Main event loop -- stop when we have no open windows left - # - while windows: - # - # Get the next event -- ignore interrupts - # - try: - type, window, detail = event = stdwin.getevent() - except KeyboardInterrupt: - type, window, detail = event = WE_NONE, None, None - # - # Event decoding switch - # - if not window: - pass # Ignore such events - elif type == WE_MENU: - # - # Execute menu operation - # - menu, item = detail - try: - menu.actions[item](window) - except KeyboardInterrupt: - pass # User cancelled - elif type == WE_CLOSE: - # - # Close a window - # - try: - close_dialog(window) - except KeyboardInterrupt: - pass # User cancelled - elif type == WE_SIZE: - # - # A window was resized -- - # let the text object recompute the line breaks - # and change the document size accordingly, - # so scroll bars will work - # - fix_textsize(window) - elif window.textobject.event(event): - # - # The event was eaten by the text object -- - # set the changed flag if not already set - # - if type == WE_CHAR or \ - type == WE_COMMAND and detail in changing: - window.changed = 1 - fix_docsize(window) - # - # Delete all objects that may still reference the window - # in the event -- this is needed otherwise the window - # won't actually be closed and may receive further - # events, which will confuse the event decoder - # - del type, window, detail, event - - -def make_file_menu(object): - menu = object.menucreate('File') - menu.actions = [] - additem(menu, 'New', 'N', new_window) - additem(menu, 'Open..', 'O', open_dialog) - additem(menu, '', '', None) - additem(menu, 'Save', 'S', save_dialog) - additem(menu, 'Save As..', '', save_as_dialog) - additem(menu, 'Save a Copy..', '', save_copy_dialog) - additem(menu, 'Revert', 'R', revert_dialog) - additem(menu, 'Quit', 'Q', quit_dialog) - return menu - - -def make_edit_menu(object): - menu = object.menucreate('Edit') - menu.actions = [] - additem(menu, 'Cut', 'X', do_cut) - additem(menu, 'Copy', 'C', do_copy) - additem(menu, 'Paste', 'V', do_paste) - additem(menu, 'Clear', 'B', do_clear) - additem(menu, 'Select All', 'A', do_select_all) - return menu - - -def make_find_menu(object): - menu = object.menucreate('Find') - menu.actions = [] - # XXX - return menu - - -def additem(menu, text, shortcut, function): - if shortcut: - menu.additem(text, shortcut) - else: - menu.additem(text) - menu.actions.append(function) - - -def open_dialog(current_ignored): - filename = stdwin.askfile('Open file:', '', 0) - open_file(filename) - - -def open_file(filename): - try: - fp = open(filename, 'r') - except RuntimeError: - stdwin.message(filename + ': cannot open') - return # Error, forget it - try: - contents = fp.read() - except RuntimeError: - stdwin.message(filename + ': read error') - return # Error, forget it - del fp # Close the file - open_window(filename, filename, contents) - - -def new_window(current_ignored): - open_window('', 'Untitled', '') - - -def open_window(filename, title, contents): - try: - window = stdwin.open(title) - except RuntimeError: - stdwin.message('cannot open new window') - return # Error, forget it - window.textobject = window.textcreate((0, 0), window.getwinsize()) - window.textobject.settext(contents) - window.changed = 0 - window.filename = filename - fix_textsize(window) - windows.append(window) - - -def quit_dialog(window): - for window in windows[:]: - close_dialog(window) - - -def close_dialog(window): - if window.changed: - prompt = 'Save changes to ' + window.gettitle() + ' ?' - if stdwin.askync(prompt, 1): - save_dialog(window) - if window.changed: - return # Save failed (not) cancelled - windows.remove(window) - del window.textobject - - -def save_dialog(window): - if not window.filename: - save_as_dialog(window) - return - if save_file(window, window.filename): - window.changed = 0 - - -def save_as_dialog(window): - prompt = 'Save ' + window.gettitle() + ' as:' - filename = stdwin.askfile(prompt, window.filename, 1) - if save_file(window, filename): - window.filename = filename - window.settitle(filename) - window.changed = 0 - - -def save_copy_dialog(window): - prompt = 'Save a copy of ' + window.gettitle() + ' as:' - filename = stdwin.askfile(prompt, window.filename, 1) - void = save_file(window, filename) - - -def save_file(window, filename): - try: - fp = open(filename, 'w') - except RuntimeError: - stdwin.message(filename + ': cannot create') - return 0 - contents = window.textobject.gettext() - try: - fp.write(contents) - except RuntimeError: - stdwin.message(filename + ': write error') - return 0 - return 1 - - -def revert_dialog(window): - if not window.filename: - stdwin.message('This window has no file to revert from') - return - if window.changed: - prompt = 'Really read ' + window.filename + ' back from file?' - if not stdwin.askync(prompt, 1): - return - try: - fp = open(window.filename, 'r') - except RuntimeError: - stdwin.message(filename + ': cannot open') - return - contents = fp.read() - del fp # Close the file - window.textobject.settext(contents) - window.changed = 0 - fix_docsize(window) - - -def fix_textsize(window): - corner = window.getwinsize() - area = (0, 0), (corner) - window.textobject.move(area) - fix_docsize(window) - - -def fix_docsize(window): - area = window.textobject.getrect() - origin, corner = area - width, height = corner - window.setdocsize(0, height) - - -def do_cut(window): - selection = window.textobject.getfocustext() - if not selection: - stdwin.fleep() # Nothing to cut - elif not window.setselection(WS_PRIMARY, selection): - stdwin.fleep() # Window manager glitch... - else: - stdwin.rotatecutbuffers(1) - stdwin.setcutbuffer(0, selection) - window.textobject.replace('') - window.changed = 1 - fix_docsize(window) - - -def do_copy(window): - selection = window.textobject.getfocustext() - if not selection: - stdwin.fleep() # Nothing to cut - elif not window.setselection(WS_PRIMARY, selection): - stdwin.fleep() # Window manager glitch... - else: - stdwin.rotatecutbuffers(1) - stdwin.setcutbuffer(0, selection) - - -def do_paste(window): - selection = stdwin.getselection(WS_PRIMARY) - if not selection: - selection = stdwin.getcutbuffer(0) - if not selection: - stdwin.fleep() # Nothing to paste - else: - window.textobject.replace(selection) - window.changed = 1 - fix_docsize(window) - -def do_clear(window): - first, last = window.textobject.getfocus() - if first == last: - stdwin.fleep() # Nothing to clear - else: - window.textobject.replace('') - window.changed = 1 - fix_docsize(window) - - -def do_select_all(window): - window.textobject.setfocus(0, 0x7fffffff) # XXX Smaller on the Mac! - - -main() diff --git a/Demo/stdwin/python.py b/Demo/stdwin/python.py deleted file mode 100755 index 29b0495fd7..0000000000 --- a/Demo/stdwin/python.py +++ /dev/null @@ -1,449 +0,0 @@ -#! /usr/local/bin/python - -# A STDWIN-based front end for the Python interpreter. -# -# This is useful if you want to avoid console I/O and instead -# use text windows to issue commands to the interpreter. -# -# It supports multiple interpreter windows, each with its own context. -# -# BUGS AND CAVEATS: -# -# This was written long ago as a demonstration, and slightly hacked to -# keep it up-to-date, but never as an industry-strength alternative -# interface to Python. It should be rewritten using more classes, and -# merged with something like wdb. -# -# Although this supports multiple windows, the whole application -# is deaf and dumb when a command is running in one window. -# -# Interrupt is (ab)used to signal EOF on input requests. -# -# On UNIX (using X11), interrupts typed in the window will not be -# seen until the next input or output operation. When you are stuck -# in an infinite loop, try typing ^C in the shell window where you -# started this interpreter. (On the Mac, interrupts work normally.) - - -import sys -import stdwin -from stdwinevents import * -import rand -import mainloop -import os - - -# Stack of windows waiting for [raw_]input(). -# Element [0] is the top. -# If there are multiple windows waiting for input, only the -# one on top of the stack can accept input, because the way -# raw_input() is implemented (using recursive mainloop() calls). -# -inputwindows = [] - - -# Exception raised when input is available -# -InputAvailable = 'input available for raw_input (not an error)' - - -# Main program -- create the window and call the mainloop -# -def main(): - # Hack so 'import python' won't load another copy - # of this if we were loaded though 'python python.py'. - # (Should really look at sys.argv[0]...) - if 'inputwindows' in dir(sys.modules['__main__']) and \ - sys.modules['__main__'].inputwindows is inputwindows: - sys.modules['python'] = sys.modules['__main__'] - # - win = makewindow() - mainloop.mainloop() - - -# Create a new window -# -def makewindow(): - # stdwin.setdefscrollbars(0, 1) # Not in Python 0.9.1 - # stdwin.setfont('monaco') # Not on UNIX! and not Python 0.9.1 - # width, height = stdwin.textwidth('in')*40, stdwin.lineheight()*24 - # stdwin.setdefwinsize(width, height) - win = stdwin.open('Python interpreter ready') - win.editor = win.textcreate((0,0), win.getwinsize()) - win.globals = {} # Dictionary for user's globals - win.command = '' # Partially read command - win.busy = 0 # Ready to accept a command - win.auto = 1 # [CR] executes command - win.insertOutput = 1 # Insert output at focus - win.insertError = 1 # Insert error output at focus - win.setwincursor('ibeam') - win.filename = '' # Empty if no file for this window - makefilemenu(win) - makeeditmenu(win) - win.dispatch = pdispatch # Event dispatch function - mainloop.register(win) - return win - - -# Make a 'File' menu -# -def makefilemenu(win): - win.filemenu = mp = win.menucreate('File') - mp.callback = [] - additem(mp, 'New', 'N', do_new) - additem(mp, 'Open...', 'O', do_open) - additem(mp, '', '', None) - additem(mp, 'Close', 'W', do_close) - additem(mp, 'Save', 'S', do_save) - additem(mp, 'Save as...', '', do_saveas) - additem(mp, '', '', None) - additem(mp, 'Quit', 'Q', do_quit) - - -# Make an 'Edit' menu -# -def makeeditmenu(win): - win.editmenu = mp = win.menucreate('Edit') - mp.callback = [] - additem(mp, 'Cut', 'X', do_cut) - additem(mp, 'Copy', 'C', do_copy) - additem(mp, 'Paste', 'V', do_paste) - additem(mp, 'Clear', '', do_clear) - additem(mp, '', '', None) - win.iauto = len(mp.callback) - additem(mp, 'Autoexecute', '', do_auto) - mp.check(win.iauto, win.auto) - win.insertOutputNum = len(mp.callback) - additem(mp, 'Insert Output', '', do_insertOutputOption) - win.insertErrorNum = len(mp.callback) - additem(mp, 'Insert Error', '', do_insertErrorOption) - additem(mp, 'Exec', '\r', do_exec) - - -# Helper to add a menu item and callback function -# -def additem(mp, text, shortcut, handler): - if shortcut: - mp.additem(text, shortcut) - else: - mp.additem(text) - mp.callback.append(handler) - - -# Dispatch a single event to the interpreter. -# Resize events cause a resize of the editor. -# Some events are treated specially. -# Most other events are passed directly to the editor. -# -def pdispatch(event): - type, win, detail = event - if not win: - win = stdwin.getactive() - if not win: return - if type == WE_CLOSE: - do_close(win) - return - elif type == WE_SIZE: - win.editor.move((0, 0), win.getwinsize()) - elif type == WE_COMMAND and detail == WC_RETURN: - if win.auto: - do_exec(win) - else: - void = win.editor.event(event) - elif type == WE_COMMAND and detail == WC_CANCEL: - if win.busy: - raise KeyboardInterrupt - else: - win.command = '' - settitle(win) - elif type == WE_MENU: - mp, item = detail - mp.callback[item](win) - else: - void = win.editor.event(event) - if win in mainloop.windows: - # May have been deleted by close... - win.setdocsize(0, win.editor.getrect()[1][1]) - if type in (WE_CHAR, WE_COMMAND): - win.editor.setfocus(win.editor.getfocus()) - - -# Helper to set the title of the window -# -def settitle(win): - if win.filename == '': - win.settitle('Python interpreter ready') - else: - win.settitle(win.filename) - - -# Helper to replace the text of the focus -# -def replace(win, text): - win.editor.replace(text) - # Resize the window to display the text - win.setdocsize(0, win.editor.getrect()[1][1]) # update the size before - win.editor.setfocus(win.editor.getfocus()) # move focus to the change - - -# File menu handlers -# -def do_new(win): - win = makewindow() -# -def do_open(win): - try: - filename = stdwin.askfile('Open file', '', 0) - win = makewindow() - win.filename = filename - win.editor.replace(open(filename, 'r').read()) - win.editor.setfocus(0, 0) - win.settitle(win.filename) - # - except KeyboardInterrupt: - pass # Don't give an error on cancel -# -def do_save(win): - try: - if win.filename == '': - win.filename = stdwin.askfile('Open file', '', 1) - f = open(win.filename, 'w') - f.write(win.editor.gettext()) - # - except KeyboardInterrupt: - pass # Don't give an error on cancel - -def do_saveas(win): - currentFilename = win.filename - win.filename = '' - do_save(win) # Use do_save with empty filename - if win.filename == '': # Restore the name if do_save did not set it - win.filename = currentFilename -# -def do_close(win): - if win.busy: - stdwin.message('Can\'t close busy window') - return # need to fail if quitting?? - win.editor = None # Break circular reference - #del win.editmenu # What about the filemenu?? - mainloop.unregister(win) - win.close() -# -def do_quit(win): - # Call win.dispatch instead of do_close because there - # may be 'alien' windows in the list. - for win in mainloop.windows[:]: - mainloop.dispatch((WE_CLOSE, win, None)) - # need to catch failed close - - -# Edit menu handlers -# -def do_cut(win): - text = win.editor.getfocustext() - if not text: - stdwin.fleep() - return - stdwin.setcutbuffer(0, text) - replace(win, '') -# -def do_copy(win): - text = win.editor.getfocustext() - if not text: - stdwin.fleep() - return - stdwin.setcutbuffer(0, text) -# -def do_paste(win): - text = stdwin.getcutbuffer(0) - if not text: - stdwin.fleep() - return - replace(win, text) -# -def do_clear(win): - replace(win, '') - - -# These would be better in a preferences dialog: -# -def do_auto(win): - win.auto = (not win.auto) - win.editmenu.check(win.iauto, win.auto) -# -def do_insertOutputOption(win): - win.insertOutput = (not win.insertOutput) - title = ['Append Output', 'Insert Output'][win.insertOutput] - win.editmenu.setitem(win.insertOutputNum, title) -# -def do_insertErrorOption(win): - win.insertError = (not win.insertError) - title = ['Error Dialog', 'Insert Error'][win.insertError] - win.editmenu.setitem(win.insertErrorNum, title) - - -# Extract a command from the editor and execute it, or pass input to -# an interpreter waiting for it. -# Incomplete commands are merely placed in the window's command buffer. -# All exceptions occurring during the execution are caught and reported. -# (Tracebacks are currently not possible, as the interpreter does not -# save the traceback pointer until it reaches its outermost level.) -# -def do_exec(win): - if win.busy: - if win not in inputwindows: - stdwin.message('Can\'t run recursive commands') - return - if win <> inputwindows[0]: - stdwin.message('Please complete recursive input first') - return - # - # Set text to the string to execute. - a, b = win.editor.getfocus() - alltext = win.editor.gettext() - n = len(alltext) - if a == b: - # There is no selected text, just an insert point; - # so execute the current line. - while 0 < a and alltext[a-1] <> '\n': # Find beginning of line - a = a-1 - while b < n and alltext[b] <> '\n': # Find end of line after b - b = b+1 - text = alltext[a:b] + '\n' - else: - # Execute exactly the selected text. - text = win.editor.getfocustext() - if text[-1:] <> '\n': # Make sure text ends with \n - text = text + '\n' - while b < n and alltext[b] <> '\n': # Find end of line after b - b = b+1 - # - # Set the focus to expect the output, since there is always something. - # Output will be inserted at end of line after current focus, - # or appended to the end of the text. - b = [n, b][win.insertOutput] - win.editor.setfocus(b, b) - # - # Make sure there is a preceeding newline. - if alltext[b-1:b] <> '\n': - win.editor.replace('\n') - # - # - if win.busy: - # Send it to raw_input() below - raise InputAvailable, text - # - # Like the real Python interpreter, we want to execute - # single-line commands immediately, but save multi-line - # commands until they are terminated by a blank line. - # Unlike the real Python interpreter, we don't do any syntax - # checking while saving up parts of a multi-line command. - # - # The current heuristic to determine whether a command is - # the first line of a multi-line command simply checks whether - # the command ends in a colon (followed by a newline). - # This is not very robust (comments and continuations will - # confuse it), but it is usable, and simple to implement. - # (It even has the advantage that single-line loops etc. - # don't need te be terminated by a blank line.) - # - if win.command: - # Already continuing - win.command = win.command + text - if win.command[-2:] <> '\n\n': - win.settitle('Unfinished command...') - return # Need more... - else: - # New command - win.command = text - if text[-2:] == ':\n': - win.settitle('Unfinished command...') - return - command = win.command - win.command = '' - win.settitle('Executing command...') - # - # Some hacks: - # - The standard files are replaced by an IOWindow instance. - # - A 2nd argument to exec() is used to specify the directory - # holding the user's global variables. (If this wasn't done, - # the exec would be executed in the current local environment, - # and the user's assignments to globals would be lost...) - # - save_stdin = sys.stdin - save_stdout = sys.stdout - save_stderr = sys.stderr - try: - sys.stdin = sys.stdout = sys.stderr = IOWindow(win) - win.busy = 1 - try: - exec(command, win.globals) - except KeyboardInterrupt: - print '[Interrupt]' - except: - if type(sys.exc_type) == type(''): - msg = sys.exc_type - else: msg = sys.exc_type.__name__ - if sys.exc_value <> None: - msg = msg + ': ' + `sys.exc_value` - if win.insertError: - stdwin.fleep() - replace(win, msg + '\n') - else: - win.settitle('Unhandled exception') - stdwin.message(msg) - finally: - # Restore redirected I/O in *all* cases - win.busy = 0 - sys.stderr = save_stderr - sys.stdout = save_stdout - sys.stdin = save_stdin - settitle(win) - - -# Class emulating file I/O from/to a window -# -class IOWindow: - # - def __init__(self, win): - self.win = win - # - def readline(self, *unused_args): - n = len(inputwindows) - save_title = self.win.gettitle() - title = n*'(' + 'Requesting input...' + ')'*n - self.win.settitle(title) - inputwindows.insert(0, self.win) - try: - try: - mainloop.mainloop() - finally: - del inputwindows[0] - self.win.settitle(save_title) - except InputAvailable, val: # See do_exec above - return val - except KeyboardInterrupt: - raise EOFError # Until we have a "send EOF" key - # If we didn't catch InputAvailable, something's wrong... - raise EOFError - # - def write(self, text): - mainloop.check() - replace(self.win, text) - mainloop.check() - - -# Currently unused function to test a command's syntax without executing it -# -def testsyntax(s): - import string - lines = string.splitfields(s, '\n') - for i in range(len(lines)): lines[i] = '\t' + lines[i] - lines.insert(0, 'if 0:') - lines.append('') - exec(string.joinfields(lines, '\n')) - - -# Call the main program -# -main() diff --git a/Demo/stdwin/wdiff.py b/Demo/stdwin/wdiff.py deleted file mode 100755 index 60be86dcf6..0000000000 --- a/Demo/stdwin/wdiff.py +++ /dev/null @@ -1,484 +0,0 @@ -#! /usr/local/bin/python - -# A window-oriented recursive diff utility. -# NB: This uses undocumented window classing modules. - -# TO DO: -# - faster update after moving/copying one file -# - diff flags (-b, etc.) should be global or maintained per window -# - use a few fixed windows instead of creating new ones all the time -# - ways to specify patterns to skip -# (best by pointing at a file and clicking a special menu entry!) -# - add rcsdiff menu commands -# - add a way to view status of selected files without opening them -# - add a way to diff two files with different names -# - add a way to rename files -# - keep backups of overwritten/deleted files -# - a way to mark specified files as uninteresting for dircmp - -import sys -import os -import rand -import commands -import dircache -import statcache -import cmp -import cmpcache -import stdwin -import gwin -import textwin -import filewin -import tablewin -import anywin - -mkarg = commands.mkarg -mk2arg = commands.mk2arg - -# List of names to ignore in dircmp() -# -skiplist = ['RCS', 'CVS', '.Amake', 'tags', 'TAGS', '.', '..'] - -# Function to determine whether a name should be ignored in dircmp(). -# -def skipthis(file): - return file[-1:] == '~' or file in skiplist - - -def anydiff(a, b, flags): # Display differences between any two objects - print 'diff', flags, a, b - if os.path.isdir(a) and os.path.isdir(b): - w = dirdiff(a, b, flags) - else: - w = filediff(a, b, flags) - addstatmenu(w, [a, b]) - w.original_close = w.close - w.close = close_dirwin - return w - -def close_dirwin(w): - close_subwindows(w, (), 0) - w.original_close(w) - -def filediff(a, b, flags): # Display differences between two text files - diffcmd = 'diff' - if flags: diffcmd = diffcmd + mkarg(flags) - diffcmd = diffcmd + mkarg(a) + mkarg(b) - difftext = commands.getoutput(diffcmd) - return textwin.open_readonly(mktitle(a, b), difftext) - -def dirdiff(a, b, flags): # Display differences between two directories - data = diffdata(a, b, flags) - w = tablewin.open(mktitle(a, b), data) - w.flags = flags - w.a = a - w.b = b - addviewmenu(w) - addactionmenu(w) - return w - -def diffdata(a, b, flags): # Compute directory differences. - # - a_only = [('A only:', header_action), ('', header_action)] - b_only = [('B only:', header_action), ('', header_action)] - ab_diff = [('A <> B:', header_action), ('', header_action)] - ab_same = [('A == B:', header_action), ('', header_action)] - data = [a_only, b_only, ab_diff, ab_same] - # - a_list = dircache.listdir(a)[:] - b_list = dircache.listdir(b)[:] - dircache.annotate(a, a_list) - dircache.annotate(b, b_list) - a_list.sort() - b_list.sort() - # - for x in a_list: - if x in ['./', '../']: - pass - elif x not in b_list: - a_only.append(x, a_only_action) - else: - ax = os.path.join(a, x) - bx = os.path.join(b, x) - if os.path.isdir(ax) and os.path.isdir(bx): - if flags == '-r': - same = dircmp(ax, bx) - else: - same = 0 - else: - try: - same = cmp.cmp(ax, bx) - except (RuntimeError, os.error): - same = 0 - if same: - ab_same.append(x, ab_same_action) - else: - ab_diff.append(x, ab_diff_action) - # - for x in b_list: - if x in ['./', '../']: - pass - elif x not in a_list: - b_only.append(x, b_only_action) - # - return data - -# Re-read the directory. -# Attempt to find the selected item back. - -def update(w): - setbusy(w) - icol, irow = w.selection - if 0 <= icol < len(w.data) and 2 <= irow < len(w.data[icol]): - selname = w.data[icol][irow][0] - else: - selname = '' - statcache.forget_dir(w.a) - statcache.forget_dir(w.b) - tablewin.select(w, (-1, -1)) - tablewin.update(w, diffdata(w.a, w.b, w.flags)) - if selname: - for icol in range(len(w.data)): - for irow in range(2, len(w.data[icol])): - if w.data[icol][irow][0] == selname: - tablewin.select(w, (icol, irow)) - break - -# Action functions for table items in directory diff windows - -def header_action(w, string, (icol, irow), (pos, clicks, button, mask)): - tablewin.select(w, (-1, -1)) - -def a_only_action(w, string, (icol, irow), (pos, clicks, button, mask)): - tablewin.select(w, (icol, irow)) - if clicks == 2: - w2 = anyopen(os.path.join(w.a, string)) - if w2: - w2.parent = w - -def b_only_action(w, string, (icol, irow), (pos, clicks, button, mask)): - tablewin.select(w, (icol, irow)) - if clicks == 2: - w2 = anyopen(os.path.join(w.b, string)) - if w2: - w2.parent = w - -def ab_diff_action(w, string, (icol, irow), (pos, clicks, button, mask)): - tablewin.select(w, (icol, irow)) - if clicks == 2: - w2 = anydiff(os.path.join(w.a, string), os.path.join(w.b, string),'') - w2.parent = w - -def ab_same_action(w, string, sel, detail): - ax = os.path.join(w.a, string) - if os.path.isdir(ax): - ab_diff_action(w, string, sel, detail) - else: - a_only_action(w, string, sel, detail) - -def anyopen(name): # Open any kind of document, ignore errors - try: - w = anywin.open(name) - except (RuntimeError, os.error): - stdwin.message('Can\'t open ' + name) - return 0 - addstatmenu(w, [name]) - return w - -def dircmp(a, b): # Compare whether two directories are the same - # To make this as fast as possible, it uses the statcache - print ' dircmp', a, b - a_list = dircache.listdir(a) - b_list = dircache.listdir(b) - for x in a_list: - if skipthis(x): - pass - elif x not in b_list: - return 0 - else: - ax = os.path.join(a, x) - bx = os.path.join(b, x) - if statcache.isdir(ax) and statcache.isdir(bx): - if not dircmp(ax, bx): return 0 - else: - try: - if not cmpcache.cmp(ax, bx): return 0 - except (RuntimeError, os.error): - return 0 - for x in b_list: - if skipthis(x): - pass - elif x not in a_list: - return 0 - return 1 - - -# View menu (for dir diff windows only) - -def addviewmenu(w): - w.viewmenu = m = w.menucreate('View') - m.action = [] - add(m, 'diff -r A B', diffr_ab) - add(m, 'diff A B', diff_ab) - add(m, 'diff -b A B', diffb_ab) - add(m, 'diff -c A B', diffc_ab) - add(m, 'gdiff A B', gdiff_ab) - add(m, ('Open A ', 'A'), open_a) - add(m, ('Open B ', 'B'), open_b) - add(m, 'Rescan', rescan) - add(m, 'Rescan -r', rescan_r) - -# Action menu (for dir diff windows only) - -def addactionmenu(w): - w.actionmenu = m = w.menucreate('Action') - m.action = [] - add(m, 'cp A B', cp_ab) - add(m, 'rm B', rm_b) - add(m, '', nop) - add(m, 'cp B A', cp_ba) - add(m, 'rm A', rm_a) - -# Main menu (global): - -def mainmenu(): - m = stdwin.menucreate('Wdiff') - m.action = [] - add(m, ('Quit wdiff', 'Q'), quit_wdiff) - add(m, 'Close subwindows', close_subwindows) - return m - -def add(m, text, action): - m.additem(text) - m.action.append(action) - -def quit_wdiff(w, m, item): - if askyesno('Really quit wdiff altogether?', 1): - sys.exit(0) - -def close_subwindows(w, m, item): - while 1: - for w2 in gwin.windows: - if w2.parent == w: - close_subwindows(w2, m, item) - w2.close(w2) - break # inner loop, continue outer loop - else: - break # outer loop - -def diffr_ab(w, m, item): - dodiff(w, '-r') - -def diff_ab(w, m, item): - dodiff(w, '') - -def diffb_ab(w, m, item): - dodiff(w, '-b') - -def diffc_ab(w, m, item): - dodiff(w, '-c') - -def gdiff_ab(w, m, item): # Call SGI's gdiff utility - x = getselection(w) - if x: - a, b = os.path.join(w.a, x), os.path.join(w.b, x) - if os.path.isdir(a) or os.path.isdir(b): - stdwin.fleep() # This is for files only - else: - diffcmd = 'gdiff' - diffcmd = diffcmd + mkarg(a) + mkarg(b) + ' &' - print diffcmd - sts = os.system(diffcmd) - if sts: print 'Exit status', sts - -def dodiff(w, flags): - x = getselection(w) - if x: - w2 = anydiff(os.path.join(w.a, x), os.path.join(w.b, x), flags) - w2.parent = w - -def open_a(w, m, item): - x = getselection(w) - if x: - w2 = anyopen(os.path.join(w.a, x)) - if w2: - w2.parent = w - -def open_b(w, m, item): - x = getselection(w) - if x: - w2 = anyopen(os.path.join(w.b, x)) - if w2: - w2.parent = w - -def rescan(w, m, item): - w.flags = '' - update(w) - -def rescan_r(w, m, item): - w.flags = '-r' - update(w) - -def rm_a(w, m, item): - x = getselection(w) - if x: - if x[-1:] == '/': x = x[:-1] - x = os.path.join(w.a, x) - if os.path.isdir(x): - if askyesno('Recursively remove A directory ' + x, 1): - runcmd('rm -rf' + mkarg(x)) - else: - runcmd('rm -f' + mkarg(x)) - update(w) - -def rm_b(w, m, item): - x = getselection(w) - if x: - if x[-1:] == '/': x = x[:-1] - x = os.path.join(w.b, x) - if os.path.isdir(x): - if askyesno('Recursively remove B directory ' + x, 1): - runcmd('rm -rf' + mkarg(x)) - else: - runcmd('rm -f' + mkarg(x)) - update(w) - -def cp_ab(w, m, item): - x = getselection(w) - if x: - if x[-1:] == '/': x = x[:-1] - ax = os.path.join(w.a, x) - bx = os.path.join(w.b, x) - if os.path.isdir(ax): - if os.path.exists(bx): - m = 'Can\'t copy directory to existing target' - stdwin.message(m) - return - runcmd('cp -r' + mkarg(ax) + mkarg(w.b)) - else: - runcmd('cp' + mkarg(ax) + mk2arg(w.b, x)) - update(w) - -def cp_ba(w, m, item): - x = getselection(w) - if x: - if x[-1:] == '/': x = x[:-1] - ax = os.path.join(w.a, x) - bx = os.path.join(w.b, x) - if os.path.isdir(bx): - if os.path.exists(ax): - m = 'Can\'t copy directory to existing target' - stdwin.message(m) - return - runcmd('cp -r' + mkarg(bx) + mkarg(w.a)) - else: - runcmd('cp' + mk2arg(w.b, x) + mkarg(ax)) - update(w) - -def nop(args): - pass - -def getselection(w): - icol, irow = w.selection - if 0 <= icol < len(w.data): - if 0 <= irow < len(w.data[icol]): - return w.data[icol][irow][0] - stdwin.message('no selection') - return '' - -def runcmd(cmd): - print cmd - sts, output = commands.getstatusoutput(cmd) - if sts or output: - if not output: - output = 'Exit status ' + `sts` - stdwin.message(output) - - -# Status menu (for all kinds of windows) - -def addstatmenu(w, files): - w.statmenu = m = w.menucreate('Stat') - m.files = files - m.action = [] - for file in files: - m.additem(commands.getstatus(file)) - m.action.append(stataction) - -def stataction(w, m, item): # Menu item action for stat menu - file = m.files[item] - try: - m.setitem(item, commands.getstatus(file)) - except os.error: - stdwin.message('Can\'t get status for ' + file) - - -# Compute a suitable window title from two paths - -def mktitle(a, b): - if a == b: return a - i = 1 - while a[-i:] == b[-i:]: i = i+1 - i = i-1 - if not i: - return a + ' ' + b - else: - return '{' + a[:-i] + ',' + b[:-i] + '}' + a[-i:] - - -# Ask a confirmation question - -def askyesno(prompt, default): - try: - return stdwin.askync(prompt, default) - except KeyboardInterrupt: - return 0 - - -# Display a message "busy" in a window, and mark it for updating - -def setbusy(w): - left, top = w.getorigin() - width, height = w.getwinsize() - right, bottom = left + width, top + height - d = w.begindrawing() - d.erase((0, 0), (10000, 10000)) - text = 'Busy...' - textwidth = d.textwidth(text) - textheight = d.lineheight() - h, v = left + (width-textwidth)/2, top + (height-textheight)/2 - d.text((h, v), text) - del d - w.change((0, 0), (10000, 10000)) - - -# Main function - -def main(): - print 'wdiff: warning: this program does NOT make backups' - argv = sys.argv - flags = '' - if len(argv) >= 2 and argv[1][:1] == '-': - flags = argv[1] - del argv[1] - stdwin.setdefscrollbars(0, 1) - m = mainmenu() # Create menu earlier than windows - if len(argv) == 2: # 1 argument - w = anyopen(argv[1]) - if not w: return - elif len(argv) == 3: # 2 arguments - w = anydiff(argv[1], argv[2], flags) - w.parent = () - else: - sys.stdout = sys.stderr - print 'usage:', argv[0], '[diff-flags] dir-1 [dir-2]' - sys.exit(2) - del w # It's preserved in gwin.windows - while 1: - try: - gwin.mainloop() - break - except KeyboardInterrupt: - pass # Just continue... - -# Start the main function (this is a script) -main() diff --git a/Demo/threads/Generator.py b/Demo/threads/Generator.py deleted file mode 100644 index fbba06ad0b..0000000000 --- a/Demo/threads/Generator.py +++ /dev/null @@ -1,84 +0,0 @@ -# Generator implementation using threads - -import thread - -Killed = 'Generator.Killed' - -class Generator: - # Constructor - def __init__(self, func, args): - self.getlock = thread.allocate_lock() - self.putlock = thread.allocate_lock() - self.getlock.acquire() - self.putlock.acquire() - self.func = func - self.args = args - self.done = 0 - self.killed = 0 - thread.start_new_thread(self._start, ()) - # Internal routine - def _start(self): - try: - self.putlock.acquire() - if not self.killed: - try: - apply(self.func, (self,) + self.args) - except Killed: - pass - finally: - if not self.killed: - self.done = 1 - self.getlock.release() - # Called by producer for each value; raise Killed if no more needed - def put(self, value): - if self.killed: - raise TypeError, 'put() called on killed generator' - self.value = value - self.getlock.release() # Resume consumer thread - self.putlock.acquire() # Wait for next get() call - if self.killed: - raise Killed - # Called by producer to get next value; raise EOFError if no more - def get(self): - if self.killed: - raise TypeError, 'get() called on killed generator' - self.putlock.release() # Resume producer thread - self.getlock.acquire() # Wait for value to appear - if self.done: - raise EOFError # Say there are no more values - return self.value - # Called by consumer if no more values wanted - def kill(self): - if self.killed: - raise TypeError, 'kill() called on killed generator' - self.killed = 1 - self.putlock.release() - # Clone constructor - def clone(self): - return Generator(self.func, self.args) - -def pi(g): - k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L - while 1: - # Next approximation - p, q, k = k*k, 2L*k+1L, k+1L - a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 - # Print common digits - d, d1 = a/b, a1/b1 - while d == d1: - g.put(int(d)) - a, a1 = 10L*(a%b), 10L*(a1%b1) - d, d1 = a/b, a1/b1 - -def test(): - g = Generator(pi, ()) - g.kill() - g = Generator(pi, ()) - for i in range(10): print g.get(), - print - h = g.clone() - g.kill() - while 1: - print h.get(), - -test() diff --git a/Demo/threads/README b/Demo/threads/README deleted file mode 100644 index 81bac931a3..0000000000 --- a/Demo/threads/README +++ /dev/null @@ -1,14 +0,0 @@ -This directory contains some demonstrations of the thread module. -This module is only available, optionally, for a few platforms: SGI -IRIX 4 and IRIX 5, SunOS 4 (not completely functioning), Solaris 2, -and supposedly any platform that supports Posix Threads (currently -only tested with KSR's implementation). See ../../Python/thread.c. - -These are mostly "proof of concept" type applications: - -bug.py Demonstrate a bug with importing modules in threads. -condition.py Condition variables test by Tim Peters. -find.py Parallelized "find(1)" (looks for directories). -Generator.py Generator class implemented with threads. -telnet.py Version of ../sockets/telnet.py using threads. -wpi.py Version of ../scripts/pi.py using threads and stdwin. diff --git a/Demo/threads/bug.py b/Demo/threads/bug.py deleted file mode 100644 index 5860536f17..0000000000 --- a/Demo/threads/bug.py +++ /dev/null @@ -1,69 +0,0 @@ -# The following self-contained little program usually freezes with most -# threads reporting -# -# Unhandled exception in thread: -# Traceback (innermost last): -# File "importbug.py", line 6 -# x = whrandom.randint(1,3) -# AttributeError: randint -# -# Here's the program; it doesn't use anything from the attached module: - -import thread - -def task(): - global N - import whrandom - x = whrandom.randint(1,3) - a.acquire() - N = N - 1 - if N == 0: done.release() - a.release() - -a = thread.allocate_lock() -done = thread.allocate_lock() -N = 10 - -done.acquire() -for i in range(N): - thread.start_new_thread(task, ()) -done.acquire() -print 'done' - - -# Sticking an acquire/release pair around the 'import' statement makes the -# problem go away. -# -# I believe that what happens is: -# -# 1) The first thread to hit the import atomically reaches, and executes -# most of, get_module. In particular, it finds Lib/whrandom.pyc, -# installs its name in sys.modules, and executes -# -# v = eval_code(co, d, d, d, (object *)NULL); -# -# to initialize the module. -# -# 2) eval_code "ticker"-slices the 1st thread out, and gives another thread -# a chance. When this 2nd thread hits the same 'import', import_module -# finds 'whrandom' in sys.modules, so just proceeds. -# -# 3) But the 1st thread is still "in the middle" of executing whrandom.pyc. -# So the 2nd thread has a good chance of trying to look up 'randint' -# before the 1st thread has placed it in whrandom's dict. -# -# 4) The more threads there are, the more likely that at least one of them -# will do this before the 1st thread finishes the import work. -# -# If that's right, a perhaps not-too-bad workaround would be to introduce a -# static "you can't interrupt this thread" flag in ceval.c, check it before -# giving up interpreter_lock, and have IMPORT_NAME set it & restore (plain -# clearing would not work) it around its call to import_module. To its -# credit, there's something wonderfully perverse about fixing a race via an -# unprotected static . -# -# as-with-most-other-things-(pseudo-)parallel-programming's-more-fun- -# in-python-too!-ly y'rs - tim -# -# Tim Peters tim@ksr.com -# not speaking for Kendall Square Research Corp diff --git a/Demo/threads/condition.py b/Demo/threads/condition.py deleted file mode 100755 index 4e999798a2..0000000000 --- a/Demo/threads/condition.py +++ /dev/null @@ -1,475 +0,0 @@ -# Defines classes that provide synchronization objects. Note that use of -# this module requires that your Python support threads. -# -# condition() # a POSIX-like condition-variable object -# barrier(n) # an n-thread barrier -# event() # an event object -# semaphore(n=1)# a semaphore object, with initial count n -# -# CONDITIONS -# -# A condition object is created via -# import this_module -# your_condition_object = this_module.condition() -# -# Methods: -# .acquire() -# acquire the lock associated with the condition -# .release() -# release the lock associated with the condition -# .wait() -# block the thread until such time as some other thread does a -# .signal or .broadcast on the same condition, and release the -# lock associated with the condition. The lock associated with -# the condition MUST be in the acquired state at the time -# .wait is invoked. -# .signal() -# wake up exactly one thread (if any) that previously did a .wait -# on the condition; that thread will awaken with the lock associated -# with the condition in the acquired state. If no threads are -# .wait'ing, this is a nop. If more than one thread is .wait'ing on -# the condition, any of them may be awakened. -# .broadcast() -# wake up all threads (if any) that are .wait'ing on the condition; -# the threads are woken up serially, each with the lock in the -# acquired state, so should .release() as soon as possible. If no -# threads are .wait'ing, this is a nop. -# -# Note that if a thread does a .wait *while* a signal/broadcast is -# in progress, it's guaranteeed to block until a subsequent -# signal/broadcast. -# -# Secret feature: `broadcast' actually takes an integer argument, -# and will wake up exactly that many waiting threads (or the total -# number waiting, if that's less). Use of this is dubious, though, -# and probably won't be supported if this form of condition is -# reimplemented in C. -# -# DIFFERENCES FROM POSIX -# -# + A separate mutex is not needed to guard condition data. Instead, a -# condition object can (must) be .acquire'ed and .release'ed directly. -# This eliminates a common error in using POSIX conditions. -# -# + Because of implementation difficulties, a POSIX `signal' wakes up -# _at least_ one .wait'ing thread. Race conditions make it difficult -# to stop that. This implementation guarantees to wake up only one, -# but you probably shouldn't rely on that. -# -# PROTOCOL -# -# Condition objects are used to block threads until "some condition" is -# true. E.g., a thread may wish to wait until a producer pumps out data -# for it to consume, or a server may wish to wait until someone requests -# its services, or perhaps a whole bunch of threads want to wait until a -# preceding pass over the data is complete. Early models for conditions -# relied on some other thread figuring out when a blocked thread's -# condition was true, and made the other thread responsible both for -# waking up the blocked thread and guaranteeing that it woke up with all -# data in a correct state. This proved to be very delicate in practice, -# and gave conditions a bad name in some circles. -# -# The POSIX model addresses these problems by making a thread responsible -# for ensuring that its own state is correct when it wakes, and relies -# on a rigid protocol to make this easy; so long as you stick to the -# protocol, POSIX conditions are easy to "get right": -# -# A) The thread that's waiting for some arbitrarily-complex condition -# (ACC) to become true does: -# -# condition.acquire() -# while not (code to evaluate the ACC): -# condition.wait() -# # That blocks the thread, *and* releases the lock. When a -# # condition.signal() happens, it will wake up some thread that -# # did a .wait, *and* acquire the lock again before .wait -# # returns. -# # -# # Because the lock is acquired at this point, the state used -# # in evaluating the ACC is frozen, so it's safe to go back & -# # reevaluate the ACC. -# -# # At this point, ACC is true, and the thread has the condition -# # locked. -# # So code here can safely muck with the shared state that -# # went into evaluating the ACC -- if it wants to. -# # When done mucking with the shared state, do -# condition.release() -# -# B) Threads that are mucking with shared state that may affect the -# ACC do: -# -# condition.acquire() -# # muck with shared state -# condition.release() -# if it's possible that ACC is true now: -# condition.signal() # or .broadcast() -# -# Note: You may prefer to put the "if" clause before the release(). -# That's fine, but do note that anyone waiting on the signal will -# stay blocked until the release() is done (since acquiring the -# condition is part of what .wait() does before it returns). -# -# TRICK OF THE TRADE -# -# With simpler forms of conditions, it can be impossible to know when -# a thread that's supposed to do a .wait has actually done it. But -# because this form of condition releases a lock as _part_ of doing a -# wait, the state of that lock can be used to guarantee it. -# -# E.g., suppose thread A spawns thread B and later wants to wait for B to -# complete: -# -# In A: In B: -# -# B_done = condition() ... do work ... -# B_done.acquire() B_done.acquire(); B_done.release() -# spawn B B_done.signal() -# ... some time later ... ... and B exits ... -# B_done.wait() -# -# Because B_done was in the acquire'd state at the time B was spawned, -# B's attempt to acquire B_done can't succeed until A has done its -# B_done.wait() (which releases B_done). So B's B_done.signal() is -# guaranteed to be seen by the .wait(). Without the lock trick, B -# may signal before A .waits, and then A would wait forever. -# -# BARRIERS -# -# A barrier object is created via -# import this_module -# your_barrier = this_module.barrier(num_threads) -# -# Methods: -# .enter() -# the thread blocks until num_threads threads in all have done -# .enter(). Then the num_threads threads that .enter'ed resume, -# and the barrier resets to capture the next num_threads threads -# that .enter it. -# -# EVENTS -# -# An event object is created via -# import this_module -# your_event = this_module.event() -# -# An event has two states, `posted' and `cleared'. An event is -# created in the cleared state. -# -# Methods: -# -# .post() -# Put the event in the posted state, and resume all threads -# .wait'ing on the event (if any). -# -# .clear() -# Put the event in the cleared state. -# -# .is_posted() -# Returns 0 if the event is in the cleared state, or 1 if the event -# is in the posted state. -# -# .wait() -# If the event is in the posted state, returns immediately. -# If the event is in the cleared state, blocks the calling thread -# until the event is .post'ed by another thread. -# -# Note that an event, once posted, remains posted until explicitly -# cleared. Relative to conditions, this is both the strength & weakness -# of events. It's a strength because the .post'ing thread doesn't have to -# worry about whether the threads it's trying to communicate with have -# already done a .wait (a condition .signal is seen only by threads that -# do a .wait _prior_ to the .signal; a .signal does not persist). But -# it's a weakness because .clear'ing an event is error-prone: it's easy -# to mistakenly .clear an event before all the threads you intended to -# see the event get around to .wait'ing on it. But so long as you don't -# need to .clear an event, events are easy to use safely. -# -# SEMAPHORES -# -# A semaphore object is created via -# import this_module -# your_semaphore = this_module.semaphore(count=1) -# -# A semaphore has an integer count associated with it. The initial value -# of the count is specified by the optional argument (which defaults to -# 1) passed to the semaphore constructor. -# -# Methods: -# -# .p() -# If the semaphore's count is greater than 0, decrements the count -# by 1 and returns. -# Else if the semaphore's count is 0, blocks the calling thread -# until a subsequent .v() increases the count. When that happens, -# the count will be decremented by 1 and the calling thread resumed. -# -# .v() -# Increments the semaphore's count by 1, and wakes up a thread (if -# any) blocked by a .p(). It's an (detected) error for a .v() to -# increase the semaphore's count to a value larger than the initial -# count. - -import thread - -class condition: - def __init__(self): - # the lock actually used by .acquire() and .release() - self.mutex = thread.allocate_lock() - - # lock used to block threads until a signal - self.checkout = thread.allocate_lock() - self.checkout.acquire() - - # internal critical-section lock, & the data it protects - self.idlock = thread.allocate_lock() - self.id = 0 - self.waiting = 0 # num waiters subject to current release - self.pending = 0 # num waiters awaiting next signal - self.torelease = 0 # num waiters to release - self.releasing = 0 # 1 iff release is in progress - - def acquire(self): - self.mutex.acquire() - - def release(self): - self.mutex.release() - - def wait(self): - mutex, checkout, idlock = self.mutex, self.checkout, self.idlock - if not mutex.locked(): - raise ValueError, \ - "condition must be .acquire'd when .wait() invoked" - - idlock.acquire() - myid = self.id - self.pending = self.pending + 1 - idlock.release() - - mutex.release() - - while 1: - checkout.acquire(); idlock.acquire() - if myid < self.id: - break - checkout.release(); idlock.release() - - self.waiting = self.waiting - 1 - self.torelease = self.torelease - 1 - if self.torelease: - checkout.release() - else: - self.releasing = 0 - if self.waiting == self.pending == 0: - self.id = 0 - idlock.release() - mutex.acquire() - - def signal(self): - self.broadcast(1) - - def broadcast(self, num = -1): - if num < -1: - raise ValueError, '.broadcast called with num ' + `num` - if num == 0: - return - self.idlock.acquire() - if self.pending: - self.waiting = self.waiting + self.pending - self.pending = 0 - self.id = self.id + 1 - if num == -1: - self.torelease = self.waiting - else: - self.torelease = min( self.waiting, - self.torelease + num ) - if self.torelease and not self.releasing: - self.releasing = 1 - self.checkout.release() - self.idlock.release() - -class barrier: - def __init__(self, n): - self.n = n - self.togo = n - self.full = condition() - - def enter(self): - full = self.full - full.acquire() - self.togo = self.togo - 1 - if self.togo: - full.wait() - else: - self.togo = self.n - full.broadcast() - full.release() - -class event: - def __init__(self): - self.state = 0 - self.posted = condition() - - def post(self): - self.posted.acquire() - self.state = 1 - self.posted.broadcast() - self.posted.release() - - def clear(self): - self.posted.acquire() - self.state = 0 - self.posted.release() - - def is_posted(self): - self.posted.acquire() - answer = self.state - self.posted.release() - return answer - - def wait(self): - self.posted.acquire() - if not self.state: - self.posted.wait() - self.posted.release() - -class semaphore: - def __init__(self, count=1): - if count <= 0: - raise ValueError, 'semaphore count %d; must be >= 1' % count - self.count = count - self.maxcount = count - self.nonzero = condition() - - def p(self): - self.nonzero.acquire() - while self.count == 0: - self.nonzero.wait() - self.count = self.count - 1 - self.nonzero.release() - - def v(self): - self.nonzero.acquire() - if self.count == self.maxcount: - raise ValueError, '.v() tried to raise semaphore count above ' \ - 'initial value ' + `maxcount` - self.count = self.count + 1 - self.nonzero.signal() - self.nonzero.release() - -# The rest of the file is a test case, that runs a number of parallelized -# quicksorts in parallel. If it works, you'll get about 600 lines of -# tracing output, with a line like -# test passed! 209 threads created in all -# as the last line. The content and order of preceding lines will -# vary across runs. - -def _new_thread(func, *args): - global TID - tid.acquire(); id = TID = TID+1; tid.release() - io.acquire(); alive.append(id); \ - print 'starting thread', id, '--', len(alive), 'alive'; \ - io.release() - thread.start_new_thread( func, (id,) + args ) - -def _qsort(tid, a, l, r, finished): - # sort a[l:r]; post finished when done - io.acquire(); print 'thread', tid, 'qsort', l, r; io.release() - if r-l > 1: - pivot = a[l] - j = l+1 # make a[l:j] <= pivot, and a[j:r] > pivot - for i in range(j, r): - if a[i] <= pivot: - a[j], a[i] = a[i], a[j] - j = j + 1 - a[l], a[j-1] = a[j-1], pivot - - l_subarray_sorted = event() - r_subarray_sorted = event() - _new_thread(_qsort, a, l, j-1, l_subarray_sorted) - _new_thread(_qsort, a, j, r, r_subarray_sorted) - l_subarray_sorted.wait() - r_subarray_sorted.wait() - - io.acquire(); print 'thread', tid, 'qsort done'; \ - alive.remove(tid); io.release() - finished.post() - -def _randarray(tid, a, finished): - io.acquire(); print 'thread', tid, 'randomizing array'; \ - io.release() - for i in range(1, len(a)): - wh.acquire(); j = randint(0,i); wh.release() - a[i], a[j] = a[j], a[i] - io.acquire(); print 'thread', tid, 'randomizing done'; \ - alive.remove(tid); io.release() - finished.post() - -def _check_sort(a): - if a != range(len(a)): - raise ValueError, ('a not sorted', a) - -def _run_one_sort(tid, a, bar, done): - # randomize a, and quicksort it - # for variety, all the threads running this enter a barrier - # at the end, and post `done' after the barrier exits - io.acquire(); print 'thread', tid, 'randomizing', a; \ - io.release() - finished = event() - _new_thread(_randarray, a, finished) - finished.wait() - - io.acquire(); print 'thread', tid, 'sorting', a; io.release() - finished.clear() - _new_thread(_qsort, a, 0, len(a), finished) - finished.wait() - _check_sort(a) - - io.acquire(); print 'thread', tid, 'entering barrier'; \ - io.release() - bar.enter() - io.acquire(); print 'thread', tid, 'leaving barrier'; \ - io.release() - io.acquire(); alive.remove(tid); io.release() - bar.enter() # make sure they've all removed themselves from alive - ## before 'done' is posted - bar.enter() # just to be cruel - done.post() - -def test(): - global TID, tid, io, wh, randint, alive - import whrandom - randint = whrandom.randint - - TID = 0 # thread ID (1, 2, ...) - tid = thread.allocate_lock() # for changing TID - io = thread.allocate_lock() # for printing, and 'alive' - wh = thread.allocate_lock() # for calls to whrandom - alive = [] # IDs of active threads - - NSORTS = 5 - arrays = [] - for i in range(NSORTS): - arrays.append( range( (i+1)*10 ) ) - - bar = barrier(NSORTS) - finished = event() - for i in range(NSORTS): - _new_thread(_run_one_sort, arrays[i], bar, finished) - finished.wait() - - print 'all threads done, and checking results ...' - if alive: - raise ValueError, ('threads still alive at end', alive) - for i in range(NSORTS): - a = arrays[i] - if len(a) != (i+1)*10: - raise ValueError, ('length of array', i, 'screwed up') - _check_sort(a) - - print 'test passed!', TID, 'threads created in all' - -if __name__ == '__main__': - test() - -# end of module diff --git a/Demo/threads/find.py b/Demo/threads/find.py deleted file mode 100644 index 940360abdf..0000000000 --- a/Demo/threads/find.py +++ /dev/null @@ -1,152 +0,0 @@ -# A parallelized "find(1)" using the thread module (SGI only for now). - -# This demonstrates the use of a work queue and worker threads. -# It really does do more stats/sec when using multiple threads, -# although the improvement is only about 20-30 percent. - -# I'm too lazy to write a command line parser for the full find(1) -# command line syntax, so the predicate it searches for is wired-in, -# see function selector() below. (It currently searches for files with -# group or world write permission.) - -# Usage: parfind.py [-w nworkers] [directory] ... -# Default nworkers is 4, maximum appears to be 8 (on Irix 4.0.2) - - -import sys -import getopt -import string -import time -import os -from stat import * -import thread - - -# Work queue class. Usage: -# wq = WorkQ() -# wq.addwork(func, (arg1, arg2, ...)) # one or more calls -# wq.run(nworkers) -# The work is done when wq.run() completes. -# The function calls executed by the workers may add more work. -# Don't use keyboard interrupts! - -class WorkQ: - - # Invariants: - - # - busy and work are only modified when mutex is locked - # - len(work) is the number of jobs ready to be taken - # - busy is the number of jobs being done - # - todo is locked iff there is no work and somebody is busy - - def __init__(self): - self.mutex = thread.allocate() - self.todo = thread.allocate() - self.todo.acquire() - self.work = [] - self.busy = 0 - - def addwork(self, func, args): - job = (func, args) - self.mutex.acquire() - self.work.append(job) - self.mutex.release() - if len(self.work) == 1: - self.todo.release() - - def _getwork(self): - self.todo.acquire() - self.mutex.acquire() - if self.busy == 0 and len(self.work) == 0: - self.mutex.release() - self.todo.release() - return None - job = self.work[0] - del self.work[0] - self.busy = self.busy + 1 - self.mutex.release() - if len(self.work) > 0: - self.todo.release() - return job - - def _donework(self): - self.mutex.acquire() - self.busy = self.busy - 1 - if self.busy == 0 and len(self.work) == 0: - self.todo.release() - self.mutex.release() - - def _worker(self): - while 1: - job = self._getwork() - if not job: - break - func, args = job - apply(func, args) - self._donework() - - def run(self, nworkers): - if not self.work: - return # Nothing to do - for i in range(nworkers-1): - thread.start_new(self._worker, ()) - self._worker() - self.todo.acquire() - - -# Main program - -def main(): - nworkers = 4 - opts, args = getopt.getopt(sys.argv[1:], '-w:') - for opt, arg in opts: - if opt == '-w': - nworkers = string.atoi(arg) - if not args: - args = [os.curdir] - - wq = WorkQ() - for dir in args: - wq.addwork(find, (dir, selector, wq)) - - t1 = time.time() - wq.run(nworkers) - t2 = time.time() - - sys.stderr.write('Total time ' + `t2-t1` + ' sec.\n') - - -# The predicate -- defines what files we look for. -# Feel free to change this to suit your purpose - -def selector(dir, name, fullname, stat): - # Look for group or world writable files - return (stat[ST_MODE] & 0022) != 0 - - -# The find procedure -- calls wq.addwork() for subdirectories - -def find(dir, pred, wq): - try: - names = os.listdir(dir) - except os.error, msg: - print `dir`, ':', msg - return - for name in names: - if name not in (os.curdir, os.pardir): - fullname = os.path.join(dir, name) - try: - stat = os.lstat(fullname) - except os.error, msg: - print `fullname`, ':', msg - continue - if pred(dir, name, fullname, stat): - print fullname - if S_ISDIR(stat[ST_MODE]): - if not os.path.ismount(fullname): - wq.addwork(find, (fullname, pred, wq)) - - -# Call the main program - -main() diff --git a/Demo/threads/sync.py b/Demo/threads/sync.py deleted file mode 100644 index 3044724ae4..0000000000 --- a/Demo/threads/sync.py +++ /dev/null @@ -1,603 +0,0 @@ -# Defines classes that provide synchronization objects. Note that use of -# this module requires that your Python support threads. -# -# condition(lock=None) # a POSIX-like condition-variable object -# barrier(n) # an n-thread barrier -# event() # an event object -# semaphore(n=1) # a semaphore object, with initial count n -# mrsw() # a multiple-reader single-writer lock -# -# CONDITIONS -# -# A condition object is created via -# import this_module -# your_condition_object = this_module.condition(lock=None) -# -# As explained below, a condition object has a lock associated with it, -# used in the protocol to protect condition data. You can specify a -# lock to use in the constructor, else the constructor will allocate -# an anonymous lock for you. Specifying a lock explicitly can be useful -# when more than one condition keys off the same set of shared data. -# -# Methods: -# .acquire() -# acquire the lock associated with the condition -# .release() -# release the lock associated with the condition -# .wait() -# block the thread until such time as some other thread does a -# .signal or .broadcast on the same condition, and release the -# lock associated with the condition. The lock associated with -# the condition MUST be in the acquired state at the time -# .wait is invoked. -# .signal() -# wake up exactly one thread (if any) that previously did a .wait -# on the condition; that thread will awaken with the lock associated -# with the condition in the acquired state. If no threads are -# .wait'ing, this is a nop. If more than one thread is .wait'ing on -# the condition, any of them may be awakened. -# .broadcast() -# wake up all threads (if any) that are .wait'ing on the condition; -# the threads are woken up serially, each with the lock in the -# acquired state, so should .release() as soon as possible. If no -# threads are .wait'ing, this is a nop. -# -# Note that if a thread does a .wait *while* a signal/broadcast is -# in progress, it's guaranteeed to block until a subsequent -# signal/broadcast. -# -# Secret feature: `broadcast' actually takes an integer argument, -# and will wake up exactly that many waiting threads (or the total -# number waiting, if that's less). Use of this is dubious, though, -# and probably won't be supported if this form of condition is -# reimplemented in C. -# -# DIFFERENCES FROM POSIX -# -# + A separate mutex is not needed to guard condition data. Instead, a -# condition object can (must) be .acquire'ed and .release'ed directly. -# This eliminates a common error in using POSIX conditions. -# -# + Because of implementation difficulties, a POSIX `signal' wakes up -# _at least_ one .wait'ing thread. Race conditions make it difficult -# to stop that. This implementation guarantees to wake up only one, -# but you probably shouldn't rely on that. -# -# PROTOCOL -# -# Condition objects are used to block threads until "some condition" is -# true. E.g., a thread may wish to wait until a producer pumps out data -# for it to consume, or a server may wish to wait until someone requests -# its services, or perhaps a whole bunch of threads want to wait until a -# preceding pass over the data is complete. Early models for conditions -# relied on some other thread figuring out when a blocked thread's -# condition was true, and made the other thread responsible both for -# waking up the blocked thread and guaranteeing that it woke up with all -# data in a correct state. This proved to be very delicate in practice, -# and gave conditions a bad name in some circles. -# -# The POSIX model addresses these problems by making a thread responsible -# for ensuring that its own state is correct when it wakes, and relies -# on a rigid protocol to make this easy; so long as you stick to the -# protocol, POSIX conditions are easy to "get right": -# -# A) The thread that's waiting for some arbitrarily-complex condition -# (ACC) to become true does: -# -# condition.acquire() -# while not (code to evaluate the ACC): -# condition.wait() -# # That blocks the thread, *and* releases the lock. When a -# # condition.signal() happens, it will wake up some thread that -# # did a .wait, *and* acquire the lock again before .wait -# # returns. -# # -# # Because the lock is acquired at this point, the state used -# # in evaluating the ACC is frozen, so it's safe to go back & -# # reevaluate the ACC. -# -# # At this point, ACC is true, and the thread has the condition -# # locked. -# # So code here can safely muck with the shared state that -# # went into evaluating the ACC -- if it wants to. -# # When done mucking with the shared state, do -# condition.release() -# -# B) Threads that are mucking with shared state that may affect the -# ACC do: -# -# condition.acquire() -# # muck with shared state -# condition.release() -# if it's possible that ACC is true now: -# condition.signal() # or .broadcast() -# -# Note: You may prefer to put the "if" clause before the release(). -# That's fine, but do note that anyone waiting on the signal will -# stay blocked until the release() is done (since acquiring the -# condition is part of what .wait() does before it returns). -# -# TRICK OF THE TRADE -# -# With simpler forms of conditions, it can be impossible to know when -# a thread that's supposed to do a .wait has actually done it. But -# because this form of condition releases a lock as _part_ of doing a -# wait, the state of that lock can be used to guarantee it. -# -# E.g., suppose thread A spawns thread B and later wants to wait for B to -# complete: -# -# In A: In B: -# -# B_done = condition() ... do work ... -# B_done.acquire() B_done.acquire(); B_done.release() -# spawn B B_done.signal() -# ... some time later ... ... and B exits ... -# B_done.wait() -# -# Because B_done was in the acquire'd state at the time B was spawned, -# B's attempt to acquire B_done can't succeed until A has done its -# B_done.wait() (which releases B_done). So B's B_done.signal() is -# guaranteed to be seen by the .wait(). Without the lock trick, B -# may signal before A .waits, and then A would wait forever. -# -# BARRIERS -# -# A barrier object is created via -# import this_module -# your_barrier = this_module.barrier(num_threads) -# -# Methods: -# .enter() -# the thread blocks until num_threads threads in all have done -# .enter(). Then the num_threads threads that .enter'ed resume, -# and the barrier resets to capture the next num_threads threads -# that .enter it. -# -# EVENTS -# -# An event object is created via -# import this_module -# your_event = this_module.event() -# -# An event has two states, `posted' and `cleared'. An event is -# created in the cleared state. -# -# Methods: -# -# .post() -# Put the event in the posted state, and resume all threads -# .wait'ing on the event (if any). -# -# .clear() -# Put the event in the cleared state. -# -# .is_posted() -# Returns 0 if the event is in the cleared state, or 1 if the event -# is in the posted state. -# -# .wait() -# If the event is in the posted state, returns immediately. -# If the event is in the cleared state, blocks the calling thread -# until the event is .post'ed by another thread. -# -# Note that an event, once posted, remains posted until explicitly -# cleared. Relative to conditions, this is both the strength & weakness -# of events. It's a strength because the .post'ing thread doesn't have to -# worry about whether the threads it's trying to communicate with have -# already done a .wait (a condition .signal is seen only by threads that -# do a .wait _prior_ to the .signal; a .signal does not persist). But -# it's a weakness because .clear'ing an event is error-prone: it's easy -# to mistakenly .clear an event before all the threads you intended to -# see the event get around to .wait'ing on it. But so long as you don't -# need to .clear an event, events are easy to use safely. -# -# SEMAPHORES -# -# A semaphore object is created via -# import this_module -# your_semaphore = this_module.semaphore(count=1) -# -# A semaphore has an integer count associated with it. The initial value -# of the count is specified by the optional argument (which defaults to -# 1) passed to the semaphore constructor. -# -# Methods: -# -# .p() -# If the semaphore's count is greater than 0, decrements the count -# by 1 and returns. -# Else if the semaphore's count is 0, blocks the calling thread -# until a subsequent .v() increases the count. When that happens, -# the count will be decremented by 1 and the calling thread resumed. -# -# .v() -# Increments the semaphore's count by 1, and wakes up a thread (if -# any) blocked by a .p(). It's an (detected) error for a .v() to -# increase the semaphore's count to a value larger than the initial -# count. -# -# MULTIPLE-READER SINGLE-WRITER LOCKS -# -# A mrsw lock is created via -# import this_module -# your_mrsw_lock = this_module.mrsw() -# -# This kind of lock is often useful with complex shared data structures. -# The object lets any number of "readers" proceed, so long as no thread -# wishes to "write". When a (one or more) thread declares its intention -# to "write" (e.g., to update a shared structure), all current readers -# are allowed to finish, and then a writer gets exclusive access; all -# other readers & writers are blocked until the current writer completes. -# Finally, if some thread is waiting to write and another is waiting to -# read, the writer takes precedence. -# -# Methods: -# -# .read_in() -# If no thread is writing or waiting to write, returns immediately. -# Else blocks until no thread is writing or waiting to write. So -# long as some thread has completed a .read_in but not a .read_out, -# writers are blocked. -# -# .read_out() -# Use sometime after a .read_in to declare that the thread is done -# reading. When all threads complete reading, a writer can proceed. -# -# .write_in() -# If no thread is writing (has completed a .write_in, but hasn't yet -# done a .write_out) or reading (similarly), returns immediately. -# Else blocks the calling thread, and threads waiting to read, until -# the current writer completes writing or all the current readers -# complete reading; if then more than one thread is waiting to -# write, one of them is allowed to proceed, but which one is not -# specified. -# -# .write_out() -# Use sometime after a .write_in to declare that the thread is done -# writing. Then if some other thread is waiting to write, it's -# allowed to proceed. Else all threads (if any) waiting to read are -# allowed to proceed. -# -# .write_to_read() -# Use instead of a .write_in to declare that the thread is done -# writing but wants to continue reading without other writers -# intervening. If there are other threads waiting to write, they -# are allowed to proceed only if the current thread calls -# .read_out; threads waiting to read are only allowed to proceed -# if there are are no threads waiting to write. (This is a -# weakness of the interface!) - -import thread - -class condition: - def __init__(self, lock=None): - # the lock actually used by .acquire() and .release() - if lock is None: - self.mutex = thread.allocate_lock() - else: - if hasattr(lock, 'acquire') and \ - hasattr(lock, 'release'): - self.mutex = lock - else: - raise TypeError, 'condition constructor requires ' \ - 'a lock argument' - - # lock used to block threads until a signal - self.checkout = thread.allocate_lock() - self.checkout.acquire() - - # internal critical-section lock, & the data it protects - self.idlock = thread.allocate_lock() - self.id = 0 - self.waiting = 0 # num waiters subject to current release - self.pending = 0 # num waiters awaiting next signal - self.torelease = 0 # num waiters to release - self.releasing = 0 # 1 iff release is in progress - - def acquire(self): - self.mutex.acquire() - - def release(self): - self.mutex.release() - - def wait(self): - mutex, checkout, idlock = self.mutex, self.checkout, self.idlock - if not mutex.locked(): - raise ValueError, \ - "condition must be .acquire'd when .wait() invoked" - - idlock.acquire() - myid = self.id - self.pending = self.pending + 1 - idlock.release() - - mutex.release() - - while 1: - checkout.acquire(); idlock.acquire() - if myid < self.id: - break - checkout.release(); idlock.release() - - self.waiting = self.waiting - 1 - self.torelease = self.torelease - 1 - if self.torelease: - checkout.release() - else: - self.releasing = 0 - if self.waiting == self.pending == 0: - self.id = 0 - idlock.release() - mutex.acquire() - - def signal(self): - self.broadcast(1) - - def broadcast(self, num = -1): - if num < -1: - raise ValueError, '.broadcast called with num ' + `num` - if num == 0: - return - self.idlock.acquire() - if self.pending: - self.waiting = self.waiting + self.pending - self.pending = 0 - self.id = self.id + 1 - if num == -1: - self.torelease = self.waiting - else: - self.torelease = min( self.waiting, - self.torelease + num ) - if self.torelease and not self.releasing: - self.releasing = 1 - self.checkout.release() - self.idlock.release() - -class barrier: - def __init__(self, n): - self.n = n - self.togo = n - self.full = condition() - - def enter(self): - full = self.full - full.acquire() - self.togo = self.togo - 1 - if self.togo: - full.wait() - else: - self.togo = self.n - full.broadcast() - full.release() - -class event: - def __init__(self): - self.state = 0 - self.posted = condition() - - def post(self): - self.posted.acquire() - self.state = 1 - self.posted.broadcast() - self.posted.release() - - def clear(self): - self.posted.acquire() - self.state = 0 - self.posted.release() - - def is_posted(self): - self.posted.acquire() - answer = self.state - self.posted.release() - return answer - - def wait(self): - self.posted.acquire() - if not self.state: - self.posted.wait() - self.posted.release() - -class semaphore: - def __init__(self, count=1): - if count <= 0: - raise ValueError, 'semaphore count %d; must be >= 1' % count - self.count = count - self.maxcount = count - self.nonzero = condition() - - def p(self): - self.nonzero.acquire() - while self.count == 0: - self.nonzero.wait() - self.count = self.count - 1 - self.nonzero.release() - - def v(self): - self.nonzero.acquire() - if self.count == self.maxcount: - raise ValueError, '.v() tried to raise semaphore count above ' \ - 'initial value ' + `maxcount` - self.count = self.count + 1 - self.nonzero.signal() - self.nonzero.release() - -class mrsw: - def __init__(self): - # critical-section lock & the data it protects - self.rwOK = thread.allocate_lock() - self.nr = 0 # number readers actively reading (not just waiting) - self.nw = 0 # number writers either waiting to write or writing - self.writing = 0 # 1 iff some thread is writing - - # conditions - self.readOK = condition(self.rwOK) # OK to unblock readers - self.writeOK = condition(self.rwOK) # OK to unblock writers - - def read_in(self): - self.rwOK.acquire() - while self.nw: - self.readOK.wait() - self.nr = self.nr + 1 - self.rwOK.release() - - def read_out(self): - self.rwOK.acquire() - if self.nr <= 0: - raise ValueError, \ - '.read_out() invoked without an active reader' - self.nr = self.nr - 1 - if self.nr == 0: - self.writeOK.signal() - self.rwOK.release() - - def write_in(self): - self.rwOK.acquire() - self.nw = self.nw + 1 - while self.writing or self.nr: - self.writeOK.wait() - self.writing = 1 - self.rwOK.release() - - def write_out(self): - self.rwOK.acquire() - if not self.writing: - raise ValueError, \ - '.write_out() invoked without an active writer' - self.writing = 0 - self.nw = self.nw - 1 - if self.nw: - self.writeOK.signal() - else: - self.readOK.broadcast() - self.rwOK.release() - - def write_to_read(self): - self.rwOK.acquire() - if not self.writing: - raise ValueError, \ - '.write_to_read() invoked without an active writer' - self.writing = 0 - self.nw = self.nw - 1 - self.nr = self.nr + 1 - if not self.nw: - self.readOK.broadcast() - self.rwOK.release() - -# The rest of the file is a test case, that runs a number of parallelized -# quicksorts in parallel. If it works, you'll get about 600 lines of -# tracing output, with a line like -# test passed! 209 threads created in all -# as the last line. The content and order of preceding lines will -# vary across runs. - -def _new_thread(func, *args): - global TID - tid.acquire(); id = TID = TID+1; tid.release() - io.acquire(); alive.append(id); \ - print 'starting thread', id, '--', len(alive), 'alive'; \ - io.release() - thread.start_new_thread( func, (id,) + args ) - -def _qsort(tid, a, l, r, finished): - # sort a[l:r]; post finished when done - io.acquire(); print 'thread', tid, 'qsort', l, r; io.release() - if r-l > 1: - pivot = a[l] - j = l+1 # make a[l:j] <= pivot, and a[j:r] > pivot - for i in range(j, r): - if a[i] <= pivot: - a[j], a[i] = a[i], a[j] - j = j + 1 - a[l], a[j-1] = a[j-1], pivot - - l_subarray_sorted = event() - r_subarray_sorted = event() - _new_thread(_qsort, a, l, j-1, l_subarray_sorted) - _new_thread(_qsort, a, j, r, r_subarray_sorted) - l_subarray_sorted.wait() - r_subarray_sorted.wait() - - io.acquire(); print 'thread', tid, 'qsort done'; \ - alive.remove(tid); io.release() - finished.post() - -def _randarray(tid, a, finished): - io.acquire(); print 'thread', tid, 'randomizing array'; \ - io.release() - for i in range(1, len(a)): - wh.acquire(); j = randint(0,i); wh.release() - a[i], a[j] = a[j], a[i] - io.acquire(); print 'thread', tid, 'randomizing done'; \ - alive.remove(tid); io.release() - finished.post() - -def _check_sort(a): - if a != range(len(a)): - raise ValueError, ('a not sorted', a) - -def _run_one_sort(tid, a, bar, done): - # randomize a, and quicksort it - # for variety, all the threads running this enter a barrier - # at the end, and post `done' after the barrier exits - io.acquire(); print 'thread', tid, 'randomizing', a; \ - io.release() - finished = event() - _new_thread(_randarray, a, finished) - finished.wait() - - io.acquire(); print 'thread', tid, 'sorting', a; io.release() - finished.clear() - _new_thread(_qsort, a, 0, len(a), finished) - finished.wait() - _check_sort(a) - - io.acquire(); print 'thread', tid, 'entering barrier'; \ - io.release() - bar.enter() - io.acquire(); print 'thread', tid, 'leaving barrier'; \ - io.release() - io.acquire(); alive.remove(tid); io.release() - bar.enter() # make sure they've all removed themselves from alive - ## before 'done' is posted - bar.enter() # just to be cruel - done.post() - -def test(): - global TID, tid, io, wh, randint, alive - import whrandom - randint = whrandom.randint - - TID = 0 # thread ID (1, 2, ...) - tid = thread.allocate_lock() # for changing TID - io = thread.allocate_lock() # for printing, and 'alive' - wh = thread.allocate_lock() # for calls to whrandom - alive = [] # IDs of active threads - - NSORTS = 5 - arrays = [] - for i in range(NSORTS): - arrays.append( range( (i+1)*10 ) ) - - bar = barrier(NSORTS) - finished = event() - for i in range(NSORTS): - _new_thread(_run_one_sort, arrays[i], bar, finished) - finished.wait() - - print 'all threads done, and checking results ...' - if alive: - raise ValueError, ('threads still alive at end', alive) - for i in range(NSORTS): - a = arrays[i] - if len(a) != (i+1)*10: - raise ValueError, ('length of array', i, 'screwed up') - _check_sort(a) - - print 'test passed!', TID, 'threads created in all' - -if __name__ == '__main__': - test() - -# end of module diff --git a/Demo/threads/telnet.py b/Demo/threads/telnet.py deleted file mode 100644 index f63d9550bf..0000000000 --- a/Demo/threads/telnet.py +++ /dev/null @@ -1,114 +0,0 @@ -# Minimal interface to the Internet telnet protocol. -# -# *** modified to use threads *** -# -# It refuses all telnet options and does not recognize any of the other -# telnet commands, but can still be used to connect in line-by-line mode. -# It's also useful to play with a number of other services, -# like time, finger, smtp and even ftp. -# -# Usage: telnet host [port] -# -# The port may be a service name or a decimal port number; -# it defaults to 'telnet'. - - -import sys, os, time -from socket import * -import thread - -BUFSIZE = 8*1024 - -# Telnet protocol characters - -IAC = chr(255) # Interpret as command -DONT = chr(254) -DO = chr(253) -WONT = chr(252) -WILL = chr(251) - -def main(): - if len(sys.argv) != 2: - sys.stderr.write('usage: telnet hostname\n') - sys.exit(2) - host = sys.argv[1] - try: - hostaddr = gethostbyname(host) - except error: - sys.stderr.write(sys.argv[1] + ': bad host name\n') - sys.exit(2) - # - if len(sys.argv) > 2: - servname = sys.argv[2] - else: - servname = 'telnet' - # - if '0' <= servname[:1] <= '9': - port = eval(servname) - else: - try: - port = getservbyname(servname, 'tcp') - except error: - sys.stderr.write(servname + ': bad tcp service name\n') - sys.exit(2) - # - s = socket(AF_INET, SOCK_STREAM) - # - try: - s.connect(host, port) - except error, msg: - sys.stderr.write('connect failed: ' + `msg` + '\n') - sys.exit(1) - # - thread.start_new(child, (s,)) - parent(s) - -def parent(s): - # read socket, write stdout - iac = 0 # Interpret next char as command - opt = '' # Interpret next char as option - while 1: - data, dummy = s.recvfrom(BUFSIZE) - if not data: - # EOF -- exit - sys.stderr.write( '(Closed by remote host)\n') - sys.exit(1) - cleandata = '' - for c in data: - if opt: - print ord(c) -## print '(replying: ' + `opt+c` + ')' - s.send(opt + c) - opt = '' - elif iac: - iac = 0 - if c == IAC: - cleandata = cleandata + c - elif c in (DO, DONT): - if c == DO: print '(DO)', - else: print '(DONT)', - opt = IAC + WONT - elif c in (WILL, WONT): - if c == WILL: print '(WILL)', - else: print '(WONT)', - opt = IAC + DONT - else: - print '(command)', ord(c) - elif c == IAC: - iac = 1 - print '(IAC)', - else: - cleandata = cleandata + c - sys.stdout.write(cleandata) - sys.stdout.flush() -## print 'Out:', `cleandata` - -def child(s): - # read stdin, write socket - while 1: - line = sys.stdin.readline() -## print 'Got:', `line` - if not line: break - s.send(line) - -main() diff --git a/Demo/threads/wpi.py b/Demo/threads/wpi.py deleted file mode 100644 index d4c0ef9b6d..0000000000 --- a/Demo/threads/wpi.py +++ /dev/null @@ -1,80 +0,0 @@ -# Display digits of pi in a window, calculating in a separate thread. -# Compare ../scripts/pi.py. - -import sys -import time -import thread -import stdwin -from stdwinevents import * - -ok = 1 - -digits = [] - -def worker(): - k, a, b, a1, b1 = 2l, 4l, 1l, 12l, 4l - while ok: - # Next approximation - p, q, k = k*k, 2l*k+1l, k+1l - a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 - # Print common digits - d, d1 = a/b, a1/b1 - #print a, b, a1, b1 - while d == d1: - digits.append(`int(d)`) - a, a1 = 10l*(a%b), 10l*(a1%b1) - d, d1 = a/b, a1/b1 - -def main(): - global ok - digits_seen = 0 - thread.start_new_thread(worker, ()) - tw = stdwin.textwidth('0 ') - lh = stdwin.lineheight() - stdwin.setdefwinsize(20 * tw, 20 * lh) - stdwin.setdefscrollbars(0, 1) - win = stdwin.open('digits of pi') - options = win.menucreate('Options') - options.additem('Auto scroll') - autoscroll = 1 - options.check(0, autoscroll) - while 1: - win.settimer(1) - type, w, detail = stdwin.getevent() - if type == WE_CLOSE: - ok = 0 - sys.exit(0) - elif type == WE_DRAW: - (left, top), (right, bottom) = detail - digits_seen = len(digits) - d = win.begindrawing() - for i in range(digits_seen): - h = (i % 20) * tw - v = (i / 20) * lh - if top-lh < v < bottom: - d.text((h, v), digits[i]) - d.close() - elif type == WE_TIMER: - n = len(digits) - if n > digits_seen: - win.settitle(`n` + ' digits of pi') - d = win.begindrawing() - for i in range(digits_seen, n): - h = (i % 20) * tw - v = (i / 20) * lh - d.text((h, v), digits[i]) - d.close() - digits_seen = n - height = (v + 20*lh) / (20*lh) * (20*lh) - win.setdocsize(0, height) - if autoscroll: - win.show((0, v), (h+tw, v+lh)) - elif type == WE_MENU: - menu, item = detail - if menu == options: - if item == 0: - autoscroll = (not autoscroll) - options.check(0, autoscroll) - - -main() diff --git a/Demo/tkinter/README b/Demo/tkinter/README deleted file mode 100644 index 9fa7cb4e24..0000000000 --- a/Demo/tkinter/README +++ /dev/null @@ -1,11 +0,0 @@ -Several collections of example code for Tkinter. - -See the toplevel README for an explanation of the difference between -Tkinter and _tkinter, how to enable the Python Tk interface, and where -to get Matt Conway's lifesaver document. - -Subdirectories: - -guido my original example set (fairly random collection) -matt Matt Conway's examples, to go with his lifesaver document -www a progressing sequence of www clients using Tk diff --git a/Demo/tkinter/Tree.py b/Demo/tkinter/Tree.py deleted file mode 100644 index 010fbd4796..0000000000 --- a/Demo/tkinter/Tree.py +++ /dev/null @@ -1,23 +0,0 @@ -from Tkinter import * - -class Tree: - - def __init__(self, master, cnf = {}): - self.master = master - self.outerframe = Frame(self.master, - {'name': 'outerframe', - Pack: {}, - }) - self.innerframe = Frame(self.outerframe, - {'name': 'innerframe', - Pack: {'side': 'left', - 'fill': 'y'}, - }) - self.button = Menubutton(self.innerframe, - {'name': 'button', - Pack: {}, - }) - # menu? - - def addchild(self): - return Tree(self.outerframe, {}) diff --git a/Demo/tkinter/guido/AttrDialog.py b/Demo/tkinter/guido/AttrDialog.py deleted file mode 100755 index 2b501c70b6..0000000000 --- a/Demo/tkinter/guido/AttrDialog.py +++ /dev/null @@ -1,463 +0,0 @@ - -# The options of a widget are described by the following attributes -# of the Pack and Widget dialogs: -# -# Dialog.current: {name: value} -# -- changes during Widget's lifetime -# -# Dialog.options: {name: (default, klass)} -# -- depends on widget class only -# -# Dialog.classes: {klass: (v0, v1, v2, ...) | 'boolean' | 'other'} -# -- totally static, though different between PackDialog and WidgetDialog -# (but even that could be unified) - -from Tkinter import * - -class Option: - - varclass = StringVar # May be overridden - - def __init__(self, dialog, option): - self.dialog = dialog - self.option = option - self.master = dialog.top - self.default, self.klass = dialog.options[option] - self.var = self.varclass(self.master) - self.frame = Frame(self.master, - {Pack: {'expand': 0, 'fill': 'x'}}) - self.label = Label(self.frame, - {'text': option + ':', - Pack: {'side': 'left'}, - }) - self.update() - self.addoption() - - def refresh(self): - self.dialog.refresh() - self.update() - - def update(self): - try: - self.current = self.dialog.current[self.option] - except KeyError: - self.current = self.default - self.var.set(self.current) - - def set(self, e=None): # Should be overridden - pass - -class BooleanOption(Option): - - varclass = BooleanVar - - def addoption(self): - self.button = Checkbutton(self.frame, - {'text': 'on/off', - 'onvalue': '1', - 'offvalue': '0', - 'variable': self.var, - 'relief': 'raised', - 'borderwidth': 2, - 'command': self.set, - Pack: {'side': 'right'}, - }) - -class EnumOption(Option): - - def addoption(self): - self.button = Menubutton(self.frame, - {'textvariable': self.var, - 'relief': 'raised', - 'borderwidth': 2, - Pack: {'side': 'right'}, - }) - self.menu = Menu(self.button) - self.button['menu'] = self.menu - for v in self.dialog.classes[self.klass]: - self.menu.add_radiobutton( - {'label': v, - 'variable': self.var, - 'value': v, - 'command': self.set, - }) - -class StringOption(Option): - - def addoption(self): - self.entry = Entry(self.frame, - {'textvariable': self.var, - 'width': 10, - 'relief': 'sunken', - 'borderwidth': 2, - Pack: {'side': 'right', - 'fill': 'x', 'expand': 1}, - }) - self.entry.bind('', self.set) - -class ReadonlyOption(Option): - - def addoption(self): - self.label = Label(self.frame, - {'textvariable': self.var, - 'anchor': 'e', - Pack: {'side': 'right'}}) - -class Dialog: - - def __init__(self, master): - self.master = master - self.fixclasses() - self.refresh() - self.top = Toplevel(self.master) - self.top.title(self.__class__.__name__) - self.top.minsize(1, 1) - self.addchoices() - - def refresh(self): pass # Must override - - def fixclasses(self): pass # May override - - def addchoices(self): - self.choices = {} - list = [] - for k, dc in self.options.items(): - list.append(k, dc) - list.sort() - for k, (d, c) in list: - try: - cl = self.classes[c] - except KeyError: - cl = 'unknown' - if type(cl) == TupleType: - cl = self.enumoption - elif cl == 'boolean': - cl = self.booleanoption - elif cl == 'readonly': - cl = self.readonlyoption - else: - cl = self.stringoption - self.choices[k] = cl(self, k) - - # Must override: - options = {} - classes = {} - - # May override: - booleanoption = BooleanOption - stringoption = StringOption - enumoption = EnumOption - readonlyoption = ReadonlyOption - -class PackDialog(Dialog): - - def __init__(self, widget): - self.widget = widget - Dialog.__init__(self, widget) - - def refresh(self): - self.current = self.widget.newinfo() - self.current['.class'] = self.widget.winfo_class() - self.current['.name'] = self.widget._w - - class packoption: # Mix-in class - def set(self, e=None): - self.current = self.var.get() - try: - Pack.config(self.dialog.widget, - {self.option: self.current}) - except TclError, msg: - print msg - self.refresh() - - class booleanoption(packoption, BooleanOption): pass - class enumoption(packoption, EnumOption): pass - class stringoption(packoption, StringOption): pass - class readonlyoption(packoption, ReadonlyOption): pass - - options = { - '.class': (None, 'Class'), - '.name': (None, 'Name'), - 'after': (None, 'Widget'), - 'anchor': ('center', 'Anchor'), - 'before': (None, 'Widget'), - 'expand': ('no', 'Boolean'), - 'fill': ('none', 'Fill'), - 'in': (None, 'Widget'), - 'ipadx': (0, 'Pad'), - 'ipady': (0, 'Pad'), - 'padx': (0, 'Pad'), - 'pady': (0, 'Pad'), - 'side': ('top', 'Side'), - } - - classes = { - 'Anchor': ('n','ne', 'e','se', 's','sw', 'w','nw', 'center'), - 'Boolean': 'boolean', - 'Class': 'readonly', - 'Expand': 'boolean', - 'Fill': ('none', 'x', 'y', 'both'), - 'Name': 'readonly', - 'Pad': 'pixel', - 'Side': ('top', 'right', 'bottom', 'left'), - 'Widget': 'readonly', - } - -class RemotePackDialog(PackDialog): - - def __init__(self, master, app, widget): - self.master = master - self.app = app - self.widget = widget - self.refresh() - self.top = Toplevel(self.master) - self.top.title(self.app + ' PackDialog') - self.top.minsize(1, 1) - self.addchoices() - - def refresh(self): - try: - words = self.master.tk.splitlist( - self.master.send(self.app, - 'pack', - 'newinfo', - self.widget)) - except TclError, msg: - print msg - return - dict = {} - for i in range(0, len(words), 2): - key = words[i][1:] - value = words[i+1] - dict[key] = value - dict['.class'] = self.master.send(self.app, - 'winfo', - 'class', - self.widget) - dict['.name'] = self.widget - self.current = dict - - class remotepackoption: # Mix-in class - def set(self, e=None): - self.current = self.var.get() - try: - self.dialog.master.send( - self.dialog.app, - 'pack', - 'config', - self.dialog.widget, - '-'+self.option, - self.dialog.master.tk.merge( - self.current)) - except TclError, msg: - print msg - self.refresh() - - class booleanoption(remotepackoption, BooleanOption): pass - class enumoption(remotepackoption, EnumOption): pass - class stringoption(remotepackoption, StringOption): pass - class readonlyoption(remotepackoption, ReadonlyOption): pass - -class WidgetDialog(Dialog): - - def __init__(self, widget): - self.widget = widget - self.klass = widget.winfo_class() - Dialog.__init__(self, widget) - - def fixclasses(self): - if self.addclasses.has_key(self.klass): - classes = {} - for c in (self.classes, - self.addclasses[self.klass]): - for k in c.keys(): - classes[k] = c[k] - self.classes = classes - - def refresh(self): - self.configuration = self.widget.config() - self.update() - self.current['.class'] = self.widget.winfo_class() - self.current['.name'] = self.widget._w - - def update(self): - self.current = {} - self.options = {} - for k, v in self.configuration.items(): - if len(v) > 4: - self.current[k] = v[4] - self.options[k] = v[3], v[2] # default, klass - self.options['.class'] = (None, 'Class') - self.options['.name'] = (None, 'Name') - - class widgetoption: # Mix-in class - def set(self, e=None): - self.current = self.var.get() - try: - self.dialog.widget[self.option] = self.current - except TclError, msg: - print msg - self.refresh() - - class booleanoption(widgetoption, BooleanOption): pass - class enumoption(widgetoption, EnumOption): pass - class stringoption(widgetoption, StringOption): pass - class readonlyoption(widgetoption, ReadonlyOption): pass - - # Universal classes - classes = { - 'Anchor': ('n','ne', 'e','se', 's','sw', 'w','nw', 'center'), - 'Aspect': 'integer', - 'Background': 'color', - 'Bitmap': 'bitmap', - 'BorderWidth': 'pixel', - 'Class': 'readonly', - 'CloseEnough': 'double', - 'Command': 'command', - 'Confine': 'boolean', - 'Cursor': 'cursor', - 'CursorWidth': 'pixel', - 'DisabledForeground': 'color', - 'ExportSelection': 'boolean', - 'Font': 'font', - 'Foreground': 'color', - 'From': 'integer', - 'Geometry': 'geometry', - 'Height': 'pixel', - 'InsertWidth': 'time', - 'Justify': ('left', 'center', 'right'), - 'Label': 'string', - 'Length': 'pixel', - 'MenuName': 'widget', - 'Name': 'readonly', - 'OffTime': 'time', - 'OnTime': 'time', - 'Orient': ('horizontal', 'vertical'), - 'Pad': 'pixel', - 'Relief': ('raised', 'sunken', 'flat', 'ridge', 'groove'), - 'RepeatDelay': 'time', - 'RepeatInterval': 'time', - 'ScrollCommand': 'command', - 'ScrollIncrement': 'pixel', - 'ScrollRegion': 'rectangle', - 'ShowValue': 'boolean', - 'SetGrid': 'boolean', - 'Sliderforeground': 'color', - 'SliderLength': 'pixel', - 'Text': 'string', - 'TickInterval': 'integer', - 'To': 'integer', - 'Underline': 'index', - 'Variable': 'variable', - 'Value': 'string', - 'Width': 'pixel', - 'Wrap': ('none', 'char', 'word'), - } - - # Classes that (may) differ per widget type - _tristate = {'State': ('normal', 'active', 'disabled')} - _bistate = {'State': ('normal', 'disabled')} - addclasses = { - 'Button': _tristate, - 'Radiobutton': _tristate, - 'Checkbutton': _tristate, - 'Entry': _bistate, - 'Text': _bistate, - 'Menubutton': _tristate, - 'Slider': _bistate, - } - -class RemoteWidgetDialog(WidgetDialog): - - def __init__(self, master, app, widget): - self.app = app - self.widget = widget - self.klass = master.send(self.app, - 'winfo', - 'class', - self.widget) - Dialog.__init__(self, master) - - def refresh(self): - try: - items = self.master.tk.splitlist( - self.master.send(self.app, - self.widget, - 'config')) - except TclError, msg: - print msg - return - dict = {} - for item in items: - words = self.master.tk.splitlist(item) - key = words[0][1:] - value = (key,) + words[1:] - dict[key] = value - self.configuration = dict - self.update() - self.current['.class'] = self.klass - self.current['.name'] = self.widget - - class remotewidgetoption: # Mix-in class - def set(self, e=None): - self.current = self.var.get() - try: - self.dialog.master.send( - self.dialog.app, - self.dialog.widget, - 'config', - '-'+self.option, - self.current) - except TclError, msg: - print msg - self.refresh() - - class booleanoption(remotewidgetoption, BooleanOption): pass - class enumoption(remotewidgetoption, EnumOption): pass - class stringoption(remotewidgetoption, StringOption): pass - class readonlyoption(remotewidgetoption, ReadonlyOption): pass - -def test(): - import sys - root = Tk() - root.minsize(1, 1) - if sys.argv[1:]: - remotetest(root, sys.argv[1]) - else: - frame = Frame(root, {'name': 'frame', - Pack: {'expand': 1, 'fill': 'both'}, - }) - button = Button(frame, {'name': 'button', - 'text': 'button', - Pack: {'expand': 1}}) - canvas = Canvas(frame, {'name': 'canvas', - Pack: {}}) - fpd = PackDialog(frame) - fwd = WidgetDialog(frame) - bpd = PackDialog(button) - bwd = WidgetDialog(button) - cpd = PackDialog(canvas) - cwd = WidgetDialog(canvas) - root.mainloop() - -def remotetest(root, app): - from listtree import listtree - list = listtree(root, app) - list.bind('', opendialogs) - list.app = app # Pass it on to handler - -def opendialogs(e): - import string - list = e.widget - sel = list.curselection() - for i in sel: - item = list.get(i) - widget = string.split(item)[0] - RemoteWidgetDialog(list, list.app, widget) - if widget == '.': continue - try: - RemotePackDialog(list, list.app, widget) - except TclError, msg: - print msg - -test() diff --git a/Demo/tkinter/guido/ManPage.py b/Demo/tkinter/guido/ManPage.py deleted file mode 100755 index 4f0af8c42a..0000000000 --- a/Demo/tkinter/guido/ManPage.py +++ /dev/null @@ -1,220 +0,0 @@ -# Widget to display a man page - -import regex -from Tkinter import * -from Tkinter import _tkinter -from ScrolledText import ScrolledText - -# XXX These fonts may have to be changed to match your system -BOLDFONT = '*-Courier-Bold-R-Normal-*-120-*' -ITALICFONT = '*-Courier-Medium-O-Normal-*-120-*' - -# XXX Recognizing footers is system dependent -# (This one works for IRIX 5.2 and Solaris 2.2) -footerprog = regex.compile( - '^ Page [1-9][0-9]*[ \t]+\|^.*Last change:.*[1-9][0-9]*\n') -emptyprog = regex.compile('^[ \t]*\n') -ulprog = regex.compile('^[ \t]*[Xv!_][Xv!_ \t]*\n') - -# Basic Man Page class -- does not disable editing -class EditableManPage(ScrolledText): - - # Initialize instance - def __init__(self, master=None, cnf={}): - # Initialize base class - ScrolledText.__init__(self, master, cnf) - - # Define tags for formatting styles - self.tag_config('X', {'underline': 1}) - self.tag_config('!', {'font': BOLDFONT}) - self.tag_config('_', {'font': ITALICFONT}) - - # Set state to idle - self.fp = None - self.lineno = 0 - - # Test whether we are busy parsing a file - def busy(self): - return self.fp != None - - # Ensure we're not busy - def kill(self): - if self.busy(): - self._endparser() - - # Parse a file, in the background - def asyncparsefile(self, fp): - self._startparser(fp) - self.tk.createfilehandler(fp, _tkinter.READABLE, - self._filehandler) - - parsefile = asyncparsefile # Alias - - # I/O handler used by background parsing - def _filehandler(self, fp, mask): - nextline = self.fp.readline() - if not nextline: - self._endparser() - return - self._parseline(nextline) - - # Parse a file, now (cannot be aborted) - def syncparsefile(self, fp): - from select import select - def avail(fp=fp, tout=0.0, select=select): - return select([fp], [], [], tout)[0] - height = self.getint(self['height']) - self._startparser(fp) - while 1: - nextline = fp.readline() - if not nextline: - break - self._parseline(nextline) - self._endparser() - - # Initialize parsing from a particular file -- must not be busy - def _startparser(self, fp): - if self.busy(): - raise RuntimeError, 'startparser: still busy' - fp.fileno() # Test for file-ness - self.fp = fp - self.lineno = 0 - self.ok = 0 - self.empty = 0 - self.buffer = None - savestate = self['state'] - self['state'] = 'normal' - self.delete('1.0', 'end') - self['state'] = savestate - - # End parsing -- must be busy, need not be at EOF - def _endparser(self): - if not self.busy(): - raise RuntimeError, 'endparser: not busy' - if self.buffer: - self._parseline('') - try: - self.tk.deletefilehandler(self.fp) - except TclError, msg: - pass - self.fp.close() - self.fp = None - del self.ok, self.empty, self.buffer - - # Parse a single line - def _parseline(self, nextline): - if not self.buffer: - # Save this line -- we need one line read-ahead - self.buffer = nextline - return - if emptyprog.match(self.buffer) >= 0: - # Buffered line was empty -- set a flag - self.empty = 1 - self.buffer = nextline - return - textline = self.buffer - if ulprog.match(nextline) >= 0: - # Next line is properties for buffered line - propline = nextline - self.buffer = None - else: - # Next line is read-ahead - propline = None - self.buffer = nextline - if not self.ok: - # First non blank line after footer must be header - # -- skip that too - self.ok = 1 - self.empty = 0 - return - if footerprog.match(textline) >= 0: - # Footer -- start skipping until next non-blank line - self.ok = 0 - self.empty = 0 - return - savestate = self['state'] - self['state'] = 'normal' - if TkVersion >= 4.0: - self.mark_set('insert', 'end-1c') - else: - self.mark_set('insert', 'end') - if self.empty: - # One or more previous lines were empty - # -- insert one blank line in the text - self._insert_prop('\n') - self.lineno = self.lineno + 1 - self.empty = 0 - if not propline: - # No properties - self._insert_prop(textline) - else: - # Search for properties - p = '' - j = 0 - for i in range(min(len(propline), len(textline))): - if propline[i] != p: - if j < i: - self._insert_prop(textline[j:i], p) - j = i - p = propline[i] - self._insert_prop(textline[j:]) - self.lineno = self.lineno + 1 - self['state'] = savestate - - # Insert a string at the end, with at most one property (tag) - def _insert_prop(self, str, prop = ' '): - here = self.index(AtInsert()) - self.insert(AtInsert(), str) - if TkVersion <= 4.0: - tags = self.tag_names(here) - for tag in tags: - self.tag_remove(tag, here, AtInsert()) - if prop != ' ': - self.tag_add(prop, here, AtInsert()) - -# Readonly Man Page class -- disables editing, otherwise the same -class ReadonlyManPage(EditableManPage): - - # Initialize instance - def __init__(self, master=None, cnf={}): - EditableManPage.__init__(self, master, - (cnf, {'state': 'disabled'})) - -# Alias -ManPage = ReadonlyManPage - -# Test program. -# usage: ManPage [manpage]; or ManPage [-f] file -# -f means that the file is nroff -man output run through ul -i -def test(): - import os - import sys - # XXX This directory may be different on your system - MANDIR = '/usr/local/man/mann' - DEFAULTPAGE = 'Tcl' - formatted = 0 - if sys.argv[1:] and sys.argv[1] == '-f': - formatted = 1 - del sys.argv[1] - if sys.argv[1:]: - name = sys.argv[1] - else: - name = DEFAULTPAGE - if not formatted: - if name[-2:-1] != '.': - name = name + '.n' - name = os.path.join(MANDIR, name) - root = Tk() - root.minsize(1, 1) - manpage = ManPage(root, {'relief': 'sunken', 'bd': 2, - Pack: {'expand': 1, 'fill': 'both'}}) - if formatted: - fp = open(name, 'r') - else: - fp = os.popen('nroff -man %s | ul -i' % name, 'r') - manpage.parsefile(fp) - root.mainloop() - -# Run the test program when called as a script -if __name__ == '__main__': - test() diff --git a/Demo/tkinter/guido/MimeViewer.py b/Demo/tkinter/guido/MimeViewer.py deleted file mode 100755 index 06b7a882ed..0000000000 --- a/Demo/tkinter/guido/MimeViewer.py +++ /dev/null @@ -1,143 +0,0 @@ -#! /usr/local/bin/python - -# View a single MIME multipart message. -# Display each part as a box. - -import string -from types import * -from Tkinter import * -from ScrolledText import ScrolledText - -class MimeViewer: - def __init__(self, parent, title, msg): - self.title = title - self.msg = msg - self.frame = Frame(parent, {'relief': 'raised', 'bd': 2}) - self.frame.packing = {'expand': 0, 'fill': 'both'} - self.button = Checkbutton(self.frame, - {'text': title, - 'command': self.toggle}) - self.button.pack({'anchor': 'w'}) - headertext = msg.getheadertext( - lambda x: x != 'received' and x[:5] != 'x400-') - height = countlines(headertext, 4) - if height: - self.htext = ScrolledText(self.frame, - {'height': height, - 'width': 80, - 'wrap': 'none', - 'relief': 'raised', - 'bd': 2}) - self.htext.packing = {'expand': 1, 'fill': 'both', - 'after': self.button} - self.htext.insert('end', headertext) - else: - self.htext = Frame(self.frame, - {'relief': 'raised', 'bd': 2}) - self.htext.packing = {'side': 'top', - 'ipady': 2, - 'fill': 'x', - 'after': self.button} - body = msg.getbody() - if type(body) == StringType: - self.pad = None - height = countlines(body, 10) - if height: - self.btext = ScrolledText(self.frame, - {'height': height, - 'width': 80, - 'wrap': 'none', - 'relief': 'raised', - 'bd': 2}) - self.btext.packing = {'expand': 1, - 'fill': 'both'} - self.btext.insert('end', body) - else: - self.btext = None - self.parts = None - else: - self.pad = Frame(self.frame, - {'relief': 'flat', 'bd': 2}) - self.pad.packing = {'side': 'left', 'ipadx': 10, - 'fill': 'y', 'after': self.htext} - self.parts = [] - for i in range(len(body)): - p = MimeViewer(self.frame, - '%s.%d' % (title, i+1), - body[i]) - self.parts.append(p) - self.btext = None - self.collapsed = 1 - def pack(self): - self.frame.pack(self.frame.packing) - def destroy(self): - self.frame.destroy() - def show(self): - if self.collapsed: - self.button.invoke() - def toggle(self): - if self.collapsed: - self.explode() - else: - self.collapse() - def collapse(self): - self.collapsed = 1 - for comp in self.htext, self.btext, self.pad: - if comp: - comp.forget() - if self.parts: - for part in self.parts: - part.frame.forget() - self.frame.pack({'expand': 0}) - def explode(self): - self.collapsed = 0 - for comp in self.htext, self.btext, self.pad: - if comp: comp.pack(comp.packing) - if self.parts: - for part in self.parts: - part.pack() - self.frame.pack({'expand': 1}) - -def countlines(str, limit): - i = 0 - n = 0 - while n < limit: - i = string.find(str, '\n', i) - if i < 0: break - n = n+1 - i = i+1 - return n - -def main(): - import sys - import getopt - import mhlib - opts, args = getopt.getopt(sys.argv[1:], '') - for o, a in opts: - pass - message = None - folder = 'inbox' - for arg in args: - if arg[:1] == '+': - folder = arg[1:] - else: - message = string.atoi(arg) - - mh = mhlib.MH() - f = mh.openfolder(folder) - if not message: - message = f.getcurrent() - m = f.openmessage(message) - - root = Tk() - tk = root.tk - - top = MimeViewer(root, '+%s/%d' % (folder, message), m) - top.pack() - top.show() - - root.minsize(1, 1) - - tk.mainloop() - -if __name__ == '__main__': main() diff --git a/Demo/tkinter/guido/ShellWindow.py b/Demo/tkinter/guido/ShellWindow.py deleted file mode 100755 index 93a13d62cf..0000000000 --- a/Demo/tkinter/guido/ShellWindow.py +++ /dev/null @@ -1,164 +0,0 @@ -import os -import sys -import string -from Tkinter import * -from ScrolledText import ScrolledText -from Dialog import Dialog -import signal - -TK_READABLE = 1 -TK_WRITABLE = 2 -TK_EXCEPTION = 4 - -BUFSIZE = 512 - -class ShellWindow(ScrolledText): - - def __init__(self, master = None, cnf = {}): - try: - shell = cnf['shell'] - del cnf['shell'] - except KeyError: - try: - shell = os.environ['SHELL'] - except KeyError: - shell = '/bin/sh' - shell = shell + ' -i' - args = string.split(shell) - shell = args[0] - - ScrolledText.__init__(self, master, cnf) - self.pos = '1.0' - self.bind('', self.inputhandler) - self.bind('', self.sigint) - self.bind('', self.sigterm) - self.bind('', self.sigkill) - self.bind('', self.sendeof) - - self.pid, self.fromchild, self.tochild = spawn(shell, args) - self.tk.createfilehandler(self.fromchild, TK_READABLE, - self.outputhandler) - - def outputhandler(self, file, mask): - data = os.read(file, BUFSIZE) - if not data: - self.tk.deletefilehandler(file) - pid, sts = os.waitpid(self.pid, 0) - print 'pid', pid, 'status', sts - self.pid = None - detail = sts>>8 - cause = sts & 0xff - if cause == 0: - msg = "exit status %d" % detail - else: - msg = "killed by signal %d" % (cause & 0x7f) - if cause & 0x80: - msg = msg + " -- core dumped" - Dialog(self.master, { - 'text': msg, - 'title': "Exit status", - 'bitmap': 'warning', - 'default': 0, - 'strings': ('OK',), - }) - return - self.insert('end', data) - self.pos = self.index('end') - self.yview_pickplace('end') - - def inputhandler(self, *args): - if not self.pid: - Dialog(self.master, { - 'text': "No active process", - 'title': "No process", - 'bitmap': 'error', - 'default': 0, - 'strings': ('OK',), - }) - return - self.insert('end', '\n') - line = self.get(self.pos, 'end') - self.pos = self.index('end') - os.write(self.tochild, line) - - def sendeof(self, *args): - if not self.pid: - Dialog(self.master, { - 'text': "No active process", - 'title': "No process", - 'bitmap': 'error', - 'default': 0, - 'strings': ('OK',), - }) - return - os.close(self.tochild) - - def sendsig(self, sig): - if not self.pid: - Dialog(self.master, { - 'text': "No active process", - 'title': "No process", - 'bitmap': 'error', - 'default': 0, - 'strings': ('OK',), - }) - return - os.kill(self.pid, sig) - - def sigint(self, *args): - self.sendsig(signal.SIGINT) - - def sigquit(self, *args): - self.sendsig(signal.SIGQUIT) - - def sigterm(self, *args): - self.sendsig(signal.SIGTERM) - - def sigkill(self, *args): - self.sendsig(signal.SIGKILL) - -MAXFD = 100 # Max number of file descriptors (os.getdtablesize()???) - -def spawn(prog, args): - p2cread, p2cwrite = os.pipe() - c2pread, c2pwrite = os.pipe() - pid = os.fork() - if pid == 0: - # Child - os.close(0) - os.close(1) - os.close(2) - if os.dup(p2cread) <> 0: - sys.stderr.write('popen2: bad read dup\n') - if os.dup(c2pwrite) <> 1: - sys.stderr.write('popen2: bad write dup\n') - if os.dup(c2pwrite) <> 2: - sys.stderr.write('popen2: bad write dup\n') - for i in range(3, MAXFD): - try: - os.close(i) - except: - pass - try: - os.execvp(prog, args) - finally: - print 'execvp failed' - os._exit(1) - os.close(p2cread) - os.close(c2pwrite) - return pid, c2pread, p2cwrite - -def test(): - shell = string.join(sys.argv[1:]) - cnf = {} - if shell: - cnf['shell'] = shell - root = Tk() - root.minsize(1, 1) - w = ShellWindow(root, cnf) - w.pack({'expand': 1, 'fill': 'both'}) - w.focus_set() - w.tk.mainloop() - -if __name__ == '__main__': - test() diff --git a/Demo/tkinter/guido/dialog.py b/Demo/tkinter/guido/dialog.py deleted file mode 100755 index 27cddf0c82..0000000000 --- a/Demo/tkinter/guido/dialog.py +++ /dev/null @@ -1,118 +0,0 @@ -#! /usr/local/bin/python - -# A Python function that generates dialog boxes with a text message, -# optional bitmap, and any number of buttons. -# Cf. Ousterhout, Tcl and the Tk Toolkit, Figs. 27.2-3, pp. 269-270. - -from Tkinter import * - -def dialog(master, title, text, bitmap, default, *args): - - # 1. Create the top-level window and divide it into top - # and bottom parts. - - w = Toplevel(master, {'class': 'Dialog'}) - w.title(title) - w.iconname('Dialog') - - top = Frame(w, {'relief': 'raised', 'bd': 1, - Pack: {'side': 'top', 'fill': 'both'}}) - bot = Frame(w, {'relief': 'raised', 'bd': 1, - Pack: {'side': 'bottom', 'fill': 'both'}}) - - # 2. Fill the top part with the bitmap and message. - - msg = Message(top, - {'width': '3i', - 'text': text, - 'font': '-Adobe-Times-Medium-R-Normal-*-180-*', - Pack: {'side': 'right', 'expand': 1, - 'fill': 'both', - 'padx': '3m', 'pady': '3m'}}) - if bitmap: - bm = Label(top, {'bitmap': bitmap, - Pack: {'side': 'left', - 'padx': '3m', 'pady': '3m'}}) - - # 3. Create a row of buttons at the bottom of the dialog. - - buttons = [] - i = 0 - for but in args: - b = Button(bot, {'text': but, - 'command': ('set', 'button', i)}) - buttons.append(b) - if i == default: - bd = Frame(bot, {'relief': 'sunken', 'bd': 1, - Pack: {'side': 'left', 'expand': 1, - 'padx': '3m', 'pady': '2m'}}) - b.lift() - b.pack ({'in': bd, 'side': 'left', - 'padx': '2m', 'pady': '2m', - 'ipadx': '2m', 'ipady': '1m'}) - else: - b.pack ({'side': 'left', 'expand': 1, - 'padx': '3m', 'pady': '3m', - 'ipady': '2m', 'ipady': '1m'}) - i = i+1 - - # 4. Set up a binding for , if there's a default, - # set a grab, and claim the focus too. - - if default >= 0: - w.bind('', - lambda e, b=buttons[default], i=default: - (b.flash(), - b.setvar('button', i))) - - oldFocus = w.tk.call('focus') # XXX - w.grab_set() - w.focus() - - # 5. Wait for the user to respond, then restore the focus - # and return the index of the selected button. - - w.waitvar('button') - w.destroy() - w.tk.call('focus', oldFocus) # XXX - return w.getint(w.getvar('button')) - -# The rest is the test program. - -def go(): - i = dialog(mainWidget, - 'Not Responding', - "The file server isn't responding right now; " - "I'll keep trying.", - '', - -1, - 'OK') - print 'pressed button', i - i = dialog(mainWidget, - 'File Modified', - 'File "tcl.h" has been modified since ' - 'the last time it was saved. ' - 'Do you want to save it before exiting the application?', - 'warning', - 0, - 'Save File', - 'Discard Changes', - 'Return To Editor') - print 'pressed button', i - -def test(): - import sys - global mainWidget - mainWidget = Frame() - Pack.config(mainWidget) - start = Button(mainWidget, - {'text': 'Press Here To Start', 'command': go}) - start.pack() - endit = Button(mainWidget, - {'text': 'Exit', - 'command': 'exit', - Pack: {'fill' : 'both'}}) - mainWidget.mainloop() - -if __name__ == '__main__': - test() diff --git a/Demo/tkinter/guido/electrons.py b/Demo/tkinter/guido/electrons.py deleted file mode 100755 index 5f6c8b589d..0000000000 --- a/Demo/tkinter/guido/electrons.py +++ /dev/null @@ -1,90 +0,0 @@ -#! /usr/local/bin/python - -# Simulate "electrons" migrating across the screen. -# An optional bitmap file in can be in the background. -# -# Usage: electrons [n [bitmapfile]] -# -# n is the number of electrons to animate; default is 4, maximum 15. -# -# The bitmap file can be any X11 bitmap file (look in -# /usr/include/X11/bitmaps for samples); it is displayed as the -# background of the animation. Default is no bitmap. - -# This uses Steen Lumholt's Tk interface -from Tkinter import * - - - -# The graphical interface -class Electrons: - - # Create our objects - def __init__(self, n, bitmap = None): - self.n = n - self.tk = tk = Tk() - self.canvas = c = Canvas(tk) - c.pack() - width, height = tk.getint(c['width']), tk.getint(c['height']) - - # Add background bitmap - if bitmap: - self.bitmap = c.create_bitmap(width/2, height/2, - {'bitmap': bitmap, - 'foreground': 'blue'}) - - self.pieces = {} - x1, y1, x2, y2 = 10,70,14,74 - for i in range(n,0,-1): - p = c.create_oval(x1, y1, x2, y2, - {'fill': 'red'}) - self.pieces[i] = p - y1, y2 = y1 +2, y2 + 2 - self.tk.update() - - def random_move(self,n): - for i in range(1,n+1): - p = self.pieces[i] - c = self.canvas - import rand - x = rand.choice(range(-2,4)) - y = rand.choice(range(-3,4)) - c.move(p, x, y) - self.tk.update() - # Run -- never returns - def run(self): - while 1: - self.random_move(self.n) - self.tk.mainloop() # Hang around... - -# Main program -def main(): - import sys, string - - # First argument is number of pegs, default 4 - if sys.argv[1:]: - n = string.atoi(sys.argv[1]) - else: - n = 30 - - # Second argument is bitmap file, default none - if sys.argv[2:]: - bitmap = sys.argv[2] - # Reverse meaning of leading '@' compared to Tk - if bitmap[0] == '@': bitmap = bitmap[1:] - else: bitmap = '@' + bitmap - else: - bitmap = None - - # Create the graphical objects... - h = Electrons(n, bitmap) - - # ...and run! - h.run() - - -# Call main when run as script -if __name__ == '__main__': - main() - - diff --git a/Demo/tkinter/guido/hanoi.py b/Demo/tkinter/guido/hanoi.py deleted file mode 100755 index 848e8e5ab3..0000000000 --- a/Demo/tkinter/guido/hanoi.py +++ /dev/null @@ -1,155 +0,0 @@ -# Animated Towers of Hanoi using Tk with optional bitmap file in -# background. -# -# Usage: tkhanoi [n [bitmapfile]] -# -# n is the number of pieces to animate; default is 4, maximum 15. -# -# The bitmap file can be any X11 bitmap file (look in -# /usr/include/X11/bitmaps for samples); it is displayed as the -# background of the animation. Default is no bitmap. - -# This uses Steen Lumholt's Tk interface -from Tkinter import * - - -# Basic Towers-of-Hanoi algorithm: move n pieces from a to b, using c -# as temporary. For each move, call report() -def hanoi(n, a, b, c, report): - if n <= 0: return - hanoi(n-1, a, c, b, report) - report(n, a, b) - hanoi(n-1, c, b, a, report) - - -# The graphical interface -class Tkhanoi: - - # Create our objects - def __init__(self, n, bitmap = None): - self.n = n - self.tk = tk = Tk() - self.canvas = c = Canvas(tk) - c.pack() - width, height = tk.getint(c['width']), tk.getint(c['height']) - - # Add background bitmap - if bitmap: - self.bitmap = c.create_bitmap(width/2, height/2, - {'bitmap': bitmap, - 'foreground': 'blue'}) - - # Generate pegs - pegwidth = 10 - pegheight = height/2 - pegdist = width/3 - x1, y1 = (pegdist-pegwidth)/2, height*1/3 - x2, y2 = x1+pegwidth, y1+pegheight - self.pegs = [] - p = c.create_rectangle(x1, y1, x2, y2, {'fill': 'black'}) - self.pegs.append(p) - x1, x2 = x1+pegdist, x2+pegdist - p = c.create_rectangle(x1, y1, x2, y2, {'fill': 'black'}) - self.pegs.append(p) - x1, x2 = x1+pegdist, x2+pegdist - p = c.create_rectangle(x1, y1, x2, y2, {'fill': 'black'}) - self.pegs.append(p) - self.tk.update() - - # Generate pieces - pieceheight = pegheight/16 - maxpiecewidth = pegdist*2/3 - minpiecewidth = 2*pegwidth - self.pegstate = [[], [], []] - self.pieces = {} - x1, y1 = (pegdist-maxpiecewidth)/2, y2-pieceheight-2 - x2, y2 = x1+maxpiecewidth, y1+pieceheight - dx = (maxpiecewidth-minpiecewidth) / (2*max(1, n-1)) - for i in range(n, 0, -1): - p = c.create_rectangle(x1, y1, x2, y2, - {'fill': 'red'}) - self.pieces[i] = p - self.pegstate[0].append(i) - x1, x2 = x1 + dx, x2-dx - y1, y2 = y1 - pieceheight-2, y2-pieceheight-2 - self.tk.update() - self.tk.after(25) - - # Run -- never returns - def run(self): - while 1: - hanoi(self.n, 0, 1, 2, self.report) - hanoi(self.n, 1, 2, 0, self.report) - hanoi(self.n, 2, 0, 1, self.report) - hanoi(self.n, 0, 2, 1, self.report) - hanoi(self.n, 2, 1, 0, self.report) - hanoi(self.n, 1, 0, 2, self.report) - - # Reporting callback for the actual hanoi function - def report(self, i, a, b): - if self.pegstate[a][-1] != i: raise RuntimeError # Assertion - del self.pegstate[a][-1] - p = self.pieces[i] - c = self.canvas - - # Lift the piece above peg a - ax1, ay1, ax2, ay2 = c.bbox(self.pegs[a]) - while 1: - x1, y1, x2, y2 = c.bbox(p) - if y2 < ay1: break - c.move(p, 0, -1) - self.tk.update() - - # Move it towards peg b - bx1, by1, bx2, by2 = c.bbox(self.pegs[b]) - newcenter = (bx1+bx2)/2 - while 1: - x1, y1, x2, y2 = c.bbox(p) - center = (x1+x2)/2 - if center == newcenter: break - if center > newcenter: c.move(p, -1, 0) - else: c.move(p, 1, 0) - self.tk.update() - - # Move it down on top of the previous piece - pieceheight = y2-y1-2 - newbottom = by2 - pieceheight*len(self.pegstate[b]) - 2 - while 1: - x1, y1, x2, y2 = c.bbox(p) - if y2 >= newbottom: break - c.move(p, 0, 1) - self.tk.update() - - # Update peg state - self.pegstate[b].append(i) - - -# Main program -def main(): - import sys, string - - # First argument is number of pegs, default 4 - if sys.argv[1:]: - n = string.atoi(sys.argv[1]) - else: - n = 4 - - # Second argument is bitmap file, default none - if sys.argv[2:]: - bitmap = sys.argv[2] - # Reverse meaning of leading '@' compared to Tk - if bitmap[0] == '@': bitmap = bitmap[1:] - else: bitmap = '@' + bitmap - else: - bitmap = None - - # Create the graphical objects... - h = Tkhanoi(n, bitmap) - - # ...and run! - h.run() - - -# Call main when run as script -if __name__ == '__main__': - main() diff --git a/Demo/tkinter/guido/hello.py b/Demo/tkinter/guido/hello.py deleted file mode 100755 index 237204fab8..0000000000 --- a/Demo/tkinter/guido/hello.py +++ /dev/null @@ -1,17 +0,0 @@ -# Display hello, world in a button; clicking it quits the program - -import sys -from Tkinter import * - -def main(): - root = Tk() - button = Button(root) - button['text'] = 'Hello, world' - button['command'] = quit_callback # See below - button.pack() - root.mainloop() - -def quit_callback(): - sys.exit(0) - -main() diff --git a/Demo/tkinter/guido/imagedraw.py b/Demo/tkinter/guido/imagedraw.py deleted file mode 100755 index d3dba4565c..0000000000 --- a/Demo/tkinter/guido/imagedraw.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Draw on top of an image""" - -from Tkinter import * -import sys - -def main(): - filename = sys.argv[1] - root = Tk() - img = PhotoImage(file=filename) - w, h = img.width(), img.height() - canv = Canvas(root, width=w, height=h) - canv.create_image(0, 0, anchor=NW, image=img) - canv.pack() - canv.bind('', blob) - root.mainloop() - -def blob(event): - x, y = event.x, event.y - canv = event.widget - r = 5 - canv.create_oval(x-r, y-r, x+r, y+r, fill='red', outline="") - -main() diff --git a/Demo/tkinter/guido/imageview.py b/Demo/tkinter/guido/imageview.py deleted file mode 100755 index d6efed0b2b..0000000000 --- a/Demo/tkinter/guido/imageview.py +++ /dev/null @@ -1,12 +0,0 @@ -from Tkinter import * -import sys - -def main(): - filename = sys.argv[1] - root = Tk() - img = PhotoImage(file=filename) - label = Label(root, image=img) - label.pack() - root.mainloop() - -main() diff --git a/Demo/tkinter/guido/kill.py b/Demo/tkinter/guido/kill.py deleted file mode 100755 index 8f45a29bb9..0000000000 --- a/Demo/tkinter/guido/kill.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/local/bin/python -# Tkinter interface to Linux `kill' command. - -from Tkinter import * -from string import splitfields -from string import split -import commands -import posix - -class BarButton(Menubutton): - _CNF = {Pack: {'side': 'left'}} - def __init__(self, master=None, cnf={}): - Menubutton.__init__(self, master, (self._CNF, cnf)) - self.menu = Menu(self, {'name': 'menu'}) - self['menu'] = self.menu - -class Kill(Frame): - # List of (name, option, pid_column) - format_list = [('Default', '', 0), - ('Long', '-l', 2), - ('User', '-u', 1), - ('Jobs', '-j', 1), - ('Signal', '-s', 1), - ('Memory', '-m', 0), - ('VM', '-v', 0), - ('Hex', '-X', 0)] - def kill(self, selected): - c = self.format_list[self.format.get()][2] - pid = split(selected)[c] - posix.system('kill' + ' -9 ' + pid) - self.do_update() - def do_update(self): - name, option, column = self.format_list[self.format.get()] - s = commands.getoutput('ps -w ' + option) - list = splitfields(s, '\n') - self.header.set(list[0]) - del list[0] - y = self.frame.vscroll.get()[2] - self.frame.list.delete(0, AtEnd()) - for line in list: - self.frame.list.insert(0, line) - self.frame.list.yview(y) - def do_motion(self, e): - e.widget.select_from(e.widget.nearest(e.y)) - def do_leave(self, e): - e.widget.select_clear() - def do_1(self, e): - self.kill(e.widget.get(e.widget.nearest(e.y))) - def __init__(self, master=None, cnf={}): - Frame.__init__(self, master, cnf) - self.pack({'expand': 'yes', 'fill': 'both'}) - self.bar = Frame( - self, - {'name': 'bar', - 'relief': 'raised', - 'bd': 2, - Pack: {'side': 'top', - 'fill': 'x'}}) - self.bar.file = BarButton(self.bar, {'text': 'File'}) - self.bar.file.menu.add_command( - {'label': 'Quit', 'command': self.quit}) - self.bar.view = BarButton(self.bar, {'text': 'View'}) - self.format = IntVar(self) - self.format.set(2) - for num in range(len(self.format_list)): - self.bar.view.menu.add_radiobutton( - {'label': self.format_list[num][0], - 'command': self.do_update, - 'variable': self.format, - 'value': num}) - #self.bar.view.menu.add_separator() - #XXX ... - self.bar.tk_menuBar(self.bar.file, self.bar.view) - self.frame = Frame( - self, - {'relief': 'raised', 'bd': 2, - Pack: {'side': 'top', - 'expand': 'yes', - 'fill': 'both'}}) - self.header = StringVar(self) - self.frame.label = Label( - self.frame, - {'relief': 'flat', - 'anchor': 'nw', - 'borderwidth': 0, - 'textvariable': self.header, - Pack: {'side': 'top', - 'fill': 'x'}}) - self.frame.vscroll = Scrollbar( - self.frame, - {'orient': 'vertical'}) - self.frame.list = Listbox( - self.frame, - {'relief': 'sunken', - 'selectbackground': '#eed5b7', - 'selectborderwidth': 0, - 'yscroll': self.frame.vscroll.set}) - self.frame.vscroll['command'] = self.frame.list.yview - self.frame.vscroll.pack({'side': 'right', 'fill': 'y'}) - self.frame.list.pack( - {'side': 'top', - 'expand': 'yes', - 'fill': 'both'}) - self.update = Button( - self, - {'text': 'Update', - 'command': self.do_update, - Pack: {'expand': 'yes', - 'fill': 'x'}}) - self.frame.list.bind('', self.do_motion) - self.frame.list.bind('', self.do_leave) - self.frame.list.bind('<1>', self.do_1) - self.do_update() - -if __name__ == '__main__': - kill = Kill(None, {'bd': 5}) - kill.winfo_toplevel().title('Tkinter Process Killer') - kill.winfo_toplevel().minsize(1, 1) - kill.mainloop() - diff --git a/Demo/tkinter/guido/listtree.py b/Demo/tkinter/guido/listtree.py deleted file mode 100755 index c5e3bc526d..0000000000 --- a/Demo/tkinter/guido/listtree.py +++ /dev/null @@ -1,36 +0,0 @@ -# List a remote app's widget tree (names and classes only) - -import sys -import string - -from Tkinter import * - -def listtree(master, app): - list = Listbox(master, {'name': 'list', - Pack: {'expand': 1, 'fill': 'both'}}) - listnodes(list, app, '.', 0) - return list - -def listnodes(list, app, widget, level): - klass = list.send(app, 'winfo', 'class', widget) -## i = string.rindex(widget, '.') -## list.insert('end', '%s%s (%s)' % ((level-1)*'. ', widget[i:], klass)) - list.insert('end', '%s (%s)' % (widget, klass)) - children = list.tk.splitlist( - list.send(app, 'winfo', 'children', widget)) - for c in children: - listnodes(list, app, c, level+1) - -def main(): - if not sys.argv[1:]: - sys.stderr.write('Usage: listtree appname\n') - sys.exit(2) - app = sys.argv[1] - tk = Tk() - tk.minsize(1, 1) - f = Frame(tk, {'name': 'f', Pack: {'expand': 1, 'fill': 'both'}}) - list = listtree(f, app) - tk.mainloop() - -if __name__ == '__main__': - main() diff --git a/Demo/tkinter/guido/mbox.py b/Demo/tkinter/guido/mbox.py deleted file mode 100755 index 338231147b..0000000000 --- a/Demo/tkinter/guido/mbox.py +++ /dev/null @@ -1,285 +0,0 @@ -#! /usr/local/bin/python - -# Scan MH folder, display results in window - -import os -import sys -import regex -import getopt -import string -import mhlib - -from Tkinter import * - -from dialog import dialog - -mailbox = os.environ['HOME'] + '/Mail' - -def main(): - global root, tk, top, mid, bot - global folderbox, foldermenu, scanbox, scanmenu, viewer - global folder, seq - global mh, mhf - - # Parse command line options - - folder = 'inbox' - seq = 'all' - try: - opts, args = getopt.getopt(sys.argv[1:], '') - except getopt.error, msg: - print msg - sys.exit(2) - for arg in args: - if arg[:1] == '+': - folder = arg[1:] - else: - seq = arg - - # Initialize MH - - mh = mhlib.MH() - mhf = mh.openfolder(folder) - - # Build widget hierarchy - - root = Tk() - tk = root.tk - - top = Frame(root) - top.pack({'expand': 1, 'fill': 'both'}) - - # Build right part: folder list - - right = Frame(top) - right.pack({'fill': 'y', 'side': 'right'}) - - folderbar = Scrollbar(right, {'relief': 'sunken', 'bd': 2}) - folderbar.pack({'fill': 'y', 'side': 'right'}) - - folderbox = Listbox(right, {'exportselection': 0}) - folderbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) - - foldermenu = Menu(root) - foldermenu.add('command', - {'label': 'Open Folder', - 'command': open_folder}) - foldermenu.add('separator') - foldermenu.add('command', - {'label': 'Quit', - 'command': 'exit'}) - foldermenu.bind('', folder_unpost) - - folderbox['yscrollcommand'] = (folderbar, 'set') - folderbar['command'] = (folderbox, 'yview') - folderbox.bind('', open_folder, 1) - folderbox.bind('<3>', folder_post) - - # Build left part: scan list - - left = Frame(top) - left.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) - - scanbar = Scrollbar(left, {'relief': 'sunken', 'bd': 2}) - scanbar.pack({'fill': 'y', 'side': 'right'}) - - scanbox = Listbox(left, {'font': 'fixed'}) - scanbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) - - scanmenu = Menu(root) - scanmenu.add('command', - {'label': 'Open Message', - 'command': open_message}) - scanmenu.add('command', - {'label': 'Remove Message', - 'command': remove_message}) - scanmenu.add('command', - {'label': 'Refile Message', - 'command': refile_message}) - scanmenu.add('separator') - scanmenu.add('command', - {'label': 'Quit', - 'command': 'exit'}) - scanmenu.bind('', scan_unpost) - - scanbox['yscrollcommand'] = (scanbar, 'set') - scanbar['command'] = (scanbox, 'yview') - scanbox.bind('', open_message) - scanbox.bind('<3>', scan_post) - - # Separator between middle and bottom part - - rule2 = Frame(root, {'bg': 'black'}) - rule2.pack({'fill': 'x'}) - - # Build bottom part: current message - - bot = Frame(root) - bot.pack({'expand': 1, 'fill': 'both'}) - # - viewer = None - - # Window manager commands - - root.minsize(800, 1) # Make window resizable - - # Fill folderbox with text - - setfolders() - - # Fill scanbox with text - - rescan() - - # Enter mainloop - - root.mainloop() - -def folder_post(e): - x, y = e.x_root, e.y_root - foldermenu.post(x - 10, y - 10) - foldermenu.grab_set() - -def folder_unpost(e): - tk.call('update', 'idletasks') - foldermenu.grab_release() - foldermenu.unpost() - foldermenu.invoke('active') - -def scan_post(e): - x, y = e.x_root, e.y_root - scanmenu.post(x - 10, y - 10) - scanmenu.grab_set() - -def scan_unpost(e): - tk.call('update', 'idletasks') - scanmenu.grab_release() - scanmenu.unpost() - scanmenu.invoke('active') - -scanparser = regex.compile('^ *\([0-9]+\)') - -def open_folder(e=None): - global folder, mhf - sel = folderbox.curselection() - if len(sel) != 1: - if len(sel) > 1: - msg = "Please open one folder at a time" - else: - msg = "Please select a folder to open" - dialog(root, "Can't Open Folder", msg, "", 0, "OK") - return - i = sel[0] - folder = folderbox.get(i) - mhf = mh.openfolder(folder) - rescan() - -def open_message(e=None): - global viewer - sel = scanbox.curselection() - if len(sel) != 1: - if len(sel) > 1: - msg = "Please open one message at a time" - else: - msg = "Please select a message to open" - dialog(root, "Can't Open Message", msg, "", 0, "OK") - return - cursor = scanbox['cursor'] - scanbox['cursor'] = 'watch' - tk.call('update', 'idletasks') - i = sel[0] - line = scanbox.get(i) - if scanparser.match(line) >= 0: - num = string.atoi(scanparser.group(1)) - m = mhf.openmessage(num) - if viewer: viewer.destroy() - from MimeViewer import MimeViewer - viewer = MimeViewer(bot, '+%s/%d' % (folder, num), m) - viewer.pack() - viewer.show() - scanbox['cursor'] = cursor - -def interestingheader(header): - return header != 'received' - -def remove_message(e=None): - itop = scanbox.nearest(0) - sel = scanbox.curselection() - if not sel: - dialog(root, "No Message To Remove", - "Please select a message to remove", "", 0, "OK") - return - todo = [] - for i in sel: - line = scanbox.get(i) - if scanparser.match(line) >= 0: - todo.append(string.atoi(scanparser.group(1))) - mhf.removemessages(todo) - rescan() - fixfocus(min(todo), itop) - -lastrefile = '' -tofolder = None -def refile_message(e=None): - global lastrefile, tofolder - itop = scanbox.nearest(0) - sel = scanbox.curselection() - if not sel: - dialog(root, "No Message To Refile", - "Please select a message to refile", "", 0, "OK") - return - foldersel = folderbox.curselection() - if len(foldersel) != 1: - if not foldersel: - msg = "Please select a folder to refile to" - else: - msg = "Please select exactly one folder to refile to" - dialog(root, "No Folder To Refile", msg, "", 0, "OK") - return - refileto = folderbox.get(foldersel[0]) - todo = [] - for i in sel: - line = scanbox.get(i) - if scanparser.match(line) >= 0: - todo.append(string.atoi(scanparser.group(1))) - if lastrefile != refileto or not tofolder: - lastrefile = refileto - tofolder = None - tofolder = mh.openfolder(lastrefile) - mhf.refilemessages(todo, tofolder) - rescan() - fixfocus(min(todo), itop) - -def fixfocus(near, itop): - n = scanbox.size() - for i in range(n): - line = scanbox.get(`i`) - if scanparser.match(line) >= 0: - num = string.atoi(scanparser.group(1)) - if num >= near: - break - else: - i = 'end' - scanbox.select_from(i) - scanbox.yview(itop) - -def setfolders(): - folderbox.delete(0, 'end') - for fn in mh.listallfolders(): - folderbox.insert('end', fn) - -def rescan(): - global viewer - if viewer: - viewer.destroy() - viewer = None - scanbox.delete(0, 'end') - for line in scanfolder(folder, seq): - scanbox.insert('end', line) - -def scanfolder(folder = 'inbox', sequence = 'all'): - return map( - lambda line: line[:-1], - os.popen('scan +%s %s' % (folder, sequence), 'r').readlines()) - -main() diff --git a/Demo/tkinter/guido/rmt.py b/Demo/tkinter/guido/rmt.py deleted file mode 100755 index 25b84e2203..0000000000 --- a/Demo/tkinter/guido/rmt.py +++ /dev/null @@ -1,159 +0,0 @@ -#! /usr/local/bin/python - -# A Python program implementing rmt, an application for remotely -# controlling other Tk applications. -# Cf. Ousterhout, Tcl and the Tk Toolkit, Figs. 27.5-8, pp. 273-276. - -# Note that because of forward references in the original, we -# sometimes delay bindings until after the corresponding procedure is -# defined. We also introduce names for some unnamed code blocks in -# the original because of restrictions on lambda forms in Python. - -# XXX This should be written in a more Python-like style!!! - -from Tkinter import * - -# 1. Create basic application structure: menu bar on top of -# text widget, scrollbar on right. - -root = Tk() -tk = root.tk -mBar = Frame(root, {'relief': 'raised', 'bd': 2, - Pack: {'side': 'top', 'fill': 'x'}}) -f = Frame(root) -f.pack({'expand': 1, 'fill': 'both'}) -s = Scrollbar(f, {'relief': 'flat', - Pack: {'side': 'right', 'fill': 'y'}}) -t = Text(f, {'relief': 'raised', 'bd': 2, 'yscrollcommand': (s, 'set'), - 'setgrid': 1, - Pack: {'side': 'left', 'fill': 'both', 'expand': 1}}) - -t.tag_config('bold', {'font': '-Adobe-Courier-Bold-R-Normal-*-120-*'}) -s['command'] = (t, 'yview') -root.title('Tk Remote Controller') -root.iconname('Tk Remote') - -# 2. Create menu button and menus. - -file = Menubutton(mBar, {'text': 'File', 'underline': 0, - Pack: {'side': 'left'}}) -file_m = Menu(file) -file['menu'] = file_m -file_m_apps = Menu(file_m) -file_m.add('cascade', {'label': 'Select Application', 'underline': 0, - 'menu': file_m_apps}) -file_m.add('command', {'label': 'Quit', 'underline': 0, 'command': 'exit'}) - -# 3. Create bindings for text widget to allow commands to be -# entered and information to be selected. New characters -# can only be added at the end of the text (can't ever move -# insertion point). - -def single1(e): - x = e.x - y = e.y - t.setvar('tk_priv(selectMode)', 'char') - t.mark_set('anchor', At(x, y)) - # Should focus W -t.bind('<1>', single1) - -def double1(e): - x = e.x - y = e.y - t.setvar('tk_priv(selectMode)', 'word') - t.tk_textSelectTo(At(x, y)) -t.bind('', double1) - -def triple1(e): - x = e.x - y = e.y - t.setvar('tk_priv(selectMode)', 'line') - t.tk_textSelectTo(At(x, y)) -t.bind('', triple1) - -def returnkey(e): - t.insert(AtInsert(), '\n') - invoke() -t.bind('', returnkey) - -def controlv(e): - t.insert(AtInsert(), t.selection_get()) - t.yview_pickplace(AtInsert()) - if t.index(AtInsert())[-2:] == '.0': - invoke() -t.bind('', controlv) - -# 4. Procedure to backspace over one character, as long as -# the character isn't part of the prompt. - -def backspace(e): - if t.index('promptEnd') != t.index('insert - 1 char'): - t.delete('insert - 1 char', AtInsert()) - t.yview_pickplace(AtInsert()) -t.bind('', backspace) -t.bind('', backspace) -t.bind('', backspace) - - -# 5. Procedure that's invoked when return is typed: if -# there's not yet a complete command (e.g. braces are open) -# then do nothing. Otherwise, execute command (locally or -# remotely), output the result or error message, and issue -# a new prompt. - -def invoke(): - cmd = t.get('promptEnd + 1 char', AtInsert()) - if t.getboolean(tk.call('info', 'complete', cmd)): # XXX - if app == root.winfo_name(): - msg = tk.call('eval', cmd) # XXX - else: - msg = t.send(app, cmd) - if msg: - t.insert(AtInsert(), msg + '\n') - prompt() - t.yview_pickplace(AtInsert()) - -def prompt(): - t.insert(AtInsert(), app + ': ') - t.mark_set('promptEnd', 'insert - 1 char') - t.tag_add('bold', 'insert linestart', 'promptEnd') - -# 6. Procedure to select a new application. Also changes -# the prompt on the current command line to reflect the new -# name. - -def newApp(appName): - global app - app = appName - t.delete('promptEnd linestart', 'promptEnd') - t.insert('promptEnd', appName + ':') - t.tag_add('bold', 'promptEnd linestart', 'promptEnd') - -def fillAppsMenu(): - file_m_apps.add('command') - file_m_apps.delete(0, 'last') - names = root.winfo_interps() - names = map(None, names) # convert tuple to list - names.sort() - for name in names: - try: - root.send(name, 'winfo name .') - except TclError: - # Inoperative window -- ignore it - pass - else: - file_m_apps.add('command', {'label': name, - 'command': - lambda name=name: - newApp(name)}) - -file_m_apps['postcommand'] = fillAppsMenu -mBar.tk_menuBar(file) - -# 7. Miscellaneous initialization. - -app = root.winfo_name() -prompt() -t.focus() - -root.mainloop() diff --git a/Demo/tkinter/guido/svkill.py b/Demo/tkinter/guido/svkill.py deleted file mode 100755 index 2881afd05c..0000000000 --- a/Demo/tkinter/guido/svkill.py +++ /dev/null @@ -1,149 +0,0 @@ -#! /usr/local/bin/python - -# Tkinter interface to SYSV `ps' and `kill' commands. - -from Tkinter import * - -if TkVersion < 4.0: - raise ImportError, "This version of svkill requires Tk 4.0 or later" - -from string import splitfields -from string import split -import commands -import os - -user = os.environ['LOGNAME'] - -class BarButton(Menubutton): - def __init__(self, master=None, cnf={}): - Menubutton.__init__(self, master, cnf) - self.pack(side='left') - self.menu = Menu(self, {'name': 'menu'}) - self['menu'] = self.menu - -class Kill(Frame): - # List of (name, option, pid_column) - view_list = [ - ('Default', ''), - ('Every (-e)', '-e'), - ('Non process group leaders (-d)', '-d'), - ('Non leaders with tty (-a)', '-a'), - ('For this user (-u %s)' % user, '-u %s' % user), - ] - format_list = [ - ('Default', '', 0), - ('Long (-l)', '-l', 3), - ('Full (-f)', '-f', 1), - ('Full Long (-f -l)', '-l -f', 3), - ('Session and group ID (-j)', '-j', 0), - ('Scheduler properties (-c)', '-c', 0), - ] - def kill(self, selected): - c = self.format_list[self.format.get()][2] - pid = split(selected)[c] - os.system('kill' + ' -9 ' + pid) - self.do_update() - def do_update(self): - format = self.format_list[self.format.get()][1] - view = self.view_list[self.view.get()][1] - s = commands.getoutput('ps %s %s' % (view, format)) - list = splitfields(s, '\n') - self.header.set(list[0] + ' ') - del list[0] - self.frame.list.delete(0, AtEnd()) - for line in list: - self.frame.list.insert(0, line) - def do_motion(self, e): - e.widget.select_clear('0', 'end') - e.widget.select_set(e.widget.nearest(e.y)) - def do_leave(self, e): - e.widget.select_clear('0', 'end') - def do_1(self, e): - self.kill(e.widget.get(e.widget.nearest(e.y))) - def __init__(self, master=None, cnf={}): - Frame.__init__(self, master, cnf) - self.pack({'expand': 'yes', 'fill': 'both'}) - self.bar = Frame( - self, - {'name': 'bar', - 'relief': 'raised', - 'bd': 2, - Pack: {'side': 'top', - 'fill': 'x'}}) - self.bar.file = BarButton(self.bar, {'text': 'File'}) - self.bar.file.menu.add_command( - {'label': 'Quit', 'command': self.quit}) - self.bar.view = BarButton(self.bar, {'text': 'View'}) - self.bar.format = BarButton(self.bar, {'text': 'Format'}) - self.view = IntVar(self) - self.view.set(0) - self.format = IntVar(self) - self.format.set(0) - for num in range(len(self.view_list)): - label, option = self.view_list[num] - self.bar.view.menu.add_radiobutton( - {'label': label, - 'command': self.do_update, - 'variable': self.view, - 'value': num}) - for num in range(len(self.format_list)): - label, option, col = self.format_list[num] - self.bar.format.menu.add_radiobutton( - {'label': label, - 'command': self.do_update, - 'variable': self.format, - 'value': num}) - self.bar.tk_menuBar(self.bar.file, - self.bar.view, - self.bar.format) - self.frame = Frame( - self, - {'relief': 'raised', 'bd': 2, - Pack: {'side': 'top', - 'expand': 'yes', - 'fill': 'both'}}) - self.header = StringVar(self) - self.frame.label = Label( - self.frame, - {'relief': 'flat', - 'anchor': 'nw', - 'borderwidth': 0, - 'font': '*-Courier-Bold-R-Normal-*-120-*', - 'textvariable': self.header, - Pack: {'side': 'top', - 'fill': 'y', - 'anchor': 'w'}}) - self.frame.vscroll = Scrollbar( - self.frame, - {'orient': 'vertical'}) - self.frame.list = Listbox( - self.frame, - {'relief': 'sunken', - 'font': '*-Courier-Medium-R-Normal-*-120-*', - 'width': 40, 'height': 10, - 'selectbackground': '#eed5b7', - 'selectborderwidth': 0, - 'selectmode': 'browse', - 'yscroll': self.frame.vscroll.set}) - self.frame.vscroll['command'] = self.frame.list.yview - self.frame.vscroll.pack({'side': 'right', 'fill': 'y'}) - self.frame.list.pack( - {'side': 'top', - 'expand': 'yes', - 'fill': 'both'}) - self.update = Button( - self, - {'text': 'Update', - 'command': self.do_update, - Pack: {'expand': 'no', - 'fill': 'x'}}) - self.frame.list.bind('', self.do_motion) - self.frame.list.bind('', self.do_leave) - self.frame.list.bind('<1>', self.do_1) - self.do_update() - -if __name__ == '__main__': - kill = Kill(None, {'bd': 5}) - kill.winfo_toplevel().title('Tkinter Process Killer (SYSV)') - kill.winfo_toplevel().minsize(1, 1) - kill.mainloop() diff --git a/Demo/tkinter/guido/tkman.py b/Demo/tkinter/guido/tkman.py deleted file mode 100755 index cd604877e6..0000000000 --- a/Demo/tkinter/guido/tkman.py +++ /dev/null @@ -1,255 +0,0 @@ -#! /home/guido/bin.sgi/python -#! /usr/local/bin/python - -# Tk man page browser -- currently only shows the Tcl/Tk man pages - -import sys -import os -import string -import regex -from Tkinter import * - -import addpack -addpack.addpack('/ufs/guido/src/python/Demo/guido/tkinter') -from ManPage import ManPage - -MANNDIR = '/usr/local/man/mann' -MAN3DIR = '/usr/local/man/man3' -MANNDIR = '/depot/sundry/man/mann' -MAN3DIR = '/depot/sundry/man/man3' - -def listmanpages(mandir): - files = os.listdir(mandir) - names = [] - for file in files: - if file[-2:-1] == '.' and (file[-1] in 'ln123456789'): - names.append(file[:-2]) - names.sort() - return names - -class SelectionBox: - - def __init__(self, master=None): - self.choices = [] - - self.frame = Frame(master, { - 'name': 'frame', - Pack: {'expand': 1, 'fill': 'both'}}) - self.master = self.frame.master - self.subframe = Frame(self.frame, { - 'name': 'subframe', - Pack: {'expand': 0, 'fill': 'both'}}) - self.leftsubframe = Frame(self.subframe, { - 'name': 'leftsubframe', - Pack: {'side': 'left', 'expand': 1, 'fill': 'both'}}) - self.rightsubframe = Frame(self.subframe, { - 'name': 'rightsubframe', - Pack: {'side': 'right', 'expand': 1, 'fill': 'both'}}) - self.chaptervar = StringVar(master) - self.chapter = Menubutton(self.rightsubframe, - {'name': 'chapter', - 'text': 'Directory', - 'relief': 'raised', 'bd': 2, - Pack: {'side': 'top'}}) - self.chaptermenu = Menu(self.chapter, {'name': 'chaptermenu'}) - self.chaptermenu.add_radiobutton({'label': 'C functions', - 'value': MAN3DIR, - 'variable': self.chaptervar, - 'command': self.newchapter}) - self.chaptermenu.add_radiobutton({'label': 'Tcl/Tk functions', - 'value': MANNDIR, - 'variable': self.chaptervar, - 'command': self.newchapter}) - self.chapter['menu'] = self.chaptermenu - self.listbox = Listbox(self.rightsubframe, - {'name': 'listbox', - 'relief': 'sunken', 'bd': 2, - 'width': 20, 'height': 5, - Pack: {'expand': 1, 'fill': 'both'}}) - self.l1 = Button(self.leftsubframe, - {'name': 'l1', - 'text': 'Display manual page named:', - 'command': self.entry_cb, - Pack: {'side': 'top'}}) - self.entry = Entry(self.leftsubframe, - {'name': 'entry', - 'relief': 'sunken', 'bd': 2, - 'width': 20, - Pack: {'side': 'top', - 'expand': 0, 'fill': 'x'}}) - self.l2frame = Frame(self.leftsubframe, - {'name': 'l2frame', - Pack: {'expand': 0, 'fill': 'none'}}) - self.l2 = Button(self.l2frame, - {'name': 'l2', - 'text': 'Search regexp:', - 'command': self.search_cb, - Pack: {'side': 'left'}}) - self.casesense = Checkbutton(self.l2frame, - {'name': 'casesense', - 'text': 'Case sensitive', - 'variable': 'casesense', - 'relief': 'flat', - Pack: {'side': 'left'}}) - self.search = Entry(self.leftsubframe, - {'name': 'search', - 'relief': 'sunken', 'bd': 2, - 'width': 20, - Pack: {'side': 'top', - 'expand': 0, 'fill': 'x'}}) - self.title = Label(self.leftsubframe, - {'name': 'title', - 'text': '(none)', - Pack: {'side': 'bottom'}}) - self.text = ManPage(self.frame, - {'name': 'text', - 'relief': 'sunken', 'bd': 2, - 'wrap': 'none', 'width': 72, - 'selectbackground': 'pink', - Pack: {'expand': 1, 'fill': 'both'}}) - - self.entry.bind('', self.entry_cb) - self.search.bind('', self.search_cb) - self.listbox.bind('', self.listbox_cb) - - self.entry.bind('', self.entry_tab) - self.search.bind('', self.search_tab) - self.text.bind('', self.text_tab) - - self.entry.focus_set() - - self.chaptervar.set(MANNDIR) - self.newchapter() - - def newchapter(self): - mandir = self.chaptervar.get() - self.choices = [] - self.addlist(listmanpages(mandir)) - - def addchoice(self, choice): - if choice not in self.choices: - self.choices.append(choice) - self.choices.sort() - self.update() - - def addlist(self, list): - self.choices[len(self.choices):] = list - self.choices.sort() - self.update() - - def entry_cb(self, *e): - self.update() - - def listbox_cb(self, e): - selection = self.listbox.curselection() - if selection and len(selection) == 1: - name = self.listbox.get(selection[0]) - self.show_page(name) - - def search_cb(self, *e): - self.search_string(self.search.get()) - - def entry_tab(self, e): - self.search.focus_set() - - def search_tab(self, e): - self.entry.focus_set() - - def text_tab(self, e): - self.entry.focus_set() - - def updatelist(self): - key = self.entry.get() - ok = filter(lambda name, key=key, n=len(key): name[:n]==key, - self.choices) - if not ok: - self.frame.bell() - self.listbox.delete(0, AtEnd()) - exactmatch = 0 - for item in ok: - if item == key: exactmatch = 1 - self.listbox.insert(AtEnd(), item) - if exactmatch: - return key - n = self.listbox.size() - if n == 1: - return self.listbox.get(0) - # Else return None, meaning not a unique selection - - def update(self): - name = self.updatelist() - if name: - self.show_page(name) - self.entry.delete(0, AtEnd()) - self.updatelist() - - def show_page(self, name): - file = '%s/%s.?' % (self.chaptervar.get(), name) - fp = os.popen('nroff -man %s | ul -i' % file, 'r') - self.text.kill() - self.title['text'] = name - self.text.parsefile(fp) - - def search_string(self, search): - if not search: - self.frame.bell() - print 'Empty search string' - return - if self.frame.tk.getvar('casesense') != '1': - map = regex.casefold - else: - map = None - try: - if map: - prog = regex.compile(search, map) - else: - prog = regex.compile(search) - except regex.error, msg: - self.frame.bell() - print 'Regex error:', msg - return - here = self.text.index(AtInsert()) - lineno = string.atoi(here[:string.find(here, '.')]) - end = self.text.index(AtEnd()) - endlineno = string.atoi(end[:string.find(end, '.')]) - wraplineno = lineno - found = 0 - while 1: - lineno = lineno + 1 - if lineno > endlineno: - if wraplineno <= 0: - break - endlineno = wraplineno - lineno = 0 - wraplineno = 0 - line = self.text.get('%d.0 linestart' % lineno, - '%d.0 lineend' % lineno) - i = prog.search(line) - if i >= 0: - found = 1 - n = max(1, len(prog.group(0))) - try: - self.text.tag_remove('sel', - AtSelFirst(), - AtSelLast()) - except TclError: - pass - self.text.tag_add('sel', - '%d.%d' % (lineno, i), - '%d.%d' % (lineno, i+n)) - self.text.mark_set(AtInsert(), - '%d.%d' % (lineno, i)) - self.text.yview_pickplace(AtInsert()) - break - if not found: - self.frame.bell() - -def main(): - root = Tk() - sb = SelectionBox(root) - if sys.argv[1:]: - sb.show_page(sys.argv[1]) - root.minsize(1, 1) - root.mainloop() - -main() diff --git a/Demo/tkinter/guido/wish.py b/Demo/tkinter/guido/wish.py deleted file mode 100755 index 4f6fdee903..0000000000 --- a/Demo/tkinter/guido/wish.py +++ /dev/null @@ -1,27 +0,0 @@ -# This is about all it requires to write a wish shell in Python! - -import _tkinter -import os - -tk = _tkinter.create(os.environ['DISPLAY'], 'wish', 'Tk', 1) -tk.call('update') - -cmd = '' - -while 1: - if cmd: prompt = '' - else: prompt = '% ' - try: - line = raw_input(prompt) - except EOFError: - break - cmd = cmd + (line + '\n') - if tk.getboolean(tk.call('info', 'complete', cmd)): - tk.record(line) - try: - result = tk.call('eval', cmd) - except _tkinter.TclError, msg: - print 'TclError:', msg - else: - if result: print result - cmd = '' diff --git a/Demo/tkinter/matt/00-HELLO-WORLD.py b/Demo/tkinter/matt/00-HELLO-WORLD.py deleted file mode 100644 index 9e8ccf43e1..0000000000 --- a/Demo/tkinter/matt/00-HELLO-WORLD.py +++ /dev/null @@ -1,30 +0,0 @@ -from Tkinter import * - -# note that there is no explicit call to start Tk. -# Tkinter is smart enough to start the system if it's not already going. - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - - self.QUIT.pack({'side': 'left', 'fill': 'both'}) - - - # a hello button - self.hi_there = Button(self, {'text': 'Hello', - 'command' : self.printit}) - self.hi_there.pack({'side': 'left'}) - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() -test.mainloop() diff --git a/Demo/tkinter/matt/README b/Demo/tkinter/matt/README deleted file mode 100644 index eb9d30246d..0000000000 --- a/Demo/tkinter/matt/README +++ /dev/null @@ -1,30 +0,0 @@ -This directory contains some ad-hoc examples of Tkinter widget -creation. The files named - - *-simple.py - -are the ones to start with if you're looking for a bare-bones usage of -a widget. The other files are meant to show common usage patters that -are a tad more involved. - -If you have a suggestion for an example program, please send mail to - - conway@virginia.edu - -and I'll include it. - - -matt - -TODO -------- -The X selection -Dialog Boxes -More canvas examples -Message widgets -Text Editors -Scrollbars -Listboxes - - - diff --git a/Demo/tkinter/matt/animation-simple.py b/Demo/tkinter/matt/animation-simple.py deleted file mode 100644 index 015879311d..0000000000 --- a/Demo/tkinter/matt/animation-simple.py +++ /dev/null @@ -1,36 +0,0 @@ -from Tkinter import * - -# This program shows how to use the "after" function to make animation. - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - self.QUIT.pack({'side': 'left', 'fill': 'both'}) - - self.draw = Canvas(self, {"width" : "5i", "height" : "5i"}) - - # all of these work.. - self.draw.create_polygon("0", "0", "10", "0", "10", "10", "0" , "10", {"tags" : "thing"}) - self.draw.pack({'side': 'left'}) - - def moveThing(self, *args): - # move 1/10 of an inch every 1/10 sec (1" per second, smoothly) - self.draw.move("thing", "0.01i", "0.01i") - self.after(10, self.moveThing) - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - self.after(10, self.moveThing) - - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/animation-w-velocity-ctrl.py b/Demo/tkinter/matt/animation-w-velocity-ctrl.py deleted file mode 100644 index d16e8a0e4b..0000000000 --- a/Demo/tkinter/matt/animation-w-velocity-ctrl.py +++ /dev/null @@ -1,51 +0,0 @@ -from Tkinter import * - -# this is the same as simple-demo-1.py, but uses -# subclassing. -# note that there is no explicit call to start Tk. -# Tkinter is smart enough to start the system if it's not already going. - - - - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - self.QUIT.pack({'side': 'bottom', 'fill': 'both'}) - - self.draw = Canvas(self, {"width" : "5i", "height" : "5i"}) - - self.speed = Scale(self, {"orient": "horiz", - "from" : -100, - "to" : 100}) - - self.speed.pack({'side': 'bottom', "fill" : "x"}) - - # all of these work.. - self.draw.create_polygon("0", "0", "10", "0", "10", "10", "0" , "10", {"tags" : "thing"}) - self.draw.pack({'side': 'left'}) - - def moveThing(self, *args): - velocity = self.speed.get() - str = float(velocity) / 1000.0 - str = `str` + "i" - self.draw.move("thing", str, str) - self.after(10, self.moveThing) - - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - self.after(10, self.moveThing) - - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/bind-w-mult-calls-p-type.py b/Demo/tkinter/matt/bind-w-mult-calls-p-type.py deleted file mode 100644 index 62beb09697..0000000000 --- a/Demo/tkinter/matt/bind-w-mult-calls-p-type.py +++ /dev/null @@ -1,43 +0,0 @@ -from Tkinter import * -import string - -# This program shows how to use a simple type-in box - -class App(Frame): - def __init__(self, master=None): - Frame.__init__(self, master) - self.pack() - - self.entrythingy = Entry() - self.entrythingy.pack() - - # and here we get a callback when the user hits return. we could - # make the key that triggers the callback anything we wanted to. - # other typical options might be or (for anything) - self.entrythingy.bind('', self.print_contents) - - # Note that here is where we bind a completely different callback to - # the same event. We pass "+" here to indicate that we wish to ADD - # this callback to the list associated with this event type. Not specifying "+" would - # simply override whatever callback was defined on this event. - self.entrythingy.bind('', self.print_something_else, "+") - - def print_contents(self, event): - print "hi. contents of entry is now ---->", self.entrythingy.get() - - - def print_something_else(self, event): - print "hi. Now doing something completely different" - - -root = App() -root.master.title("Foo") -root.mainloop() - - - -# secret tip for experts: if you pass *any* non-false value as -# the third parameter to bind(), Tkinter.py will accumulate -# callbacks instead of overwriting. I use "+" here because that's -# the Tk notation for getting this sort of behavior. The perfect GUI -# interface would use a less obscure notation. diff --git a/Demo/tkinter/matt/canvas-demo-simple.py b/Demo/tkinter/matt/canvas-demo-simple.py deleted file mode 100644 index c8ebfa750d..0000000000 --- a/Demo/tkinter/matt/canvas-demo-simple.py +++ /dev/null @@ -1,30 +0,0 @@ -from Tkinter import * - -# this program creates a canvas and puts a single polygon on the canvas - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - self.QUIT.pack({'side': 'bottom', 'fill': 'both'}) - - self.draw = Canvas(self, {"width" : "5i", "height" : "5i"}) - - # see the other demos for other ways of specifying coords for a polygon - self.draw.create_polygon("0i", "0i", "3i", "0i", "3i", "3i", "0i" , "3i") - - self.draw.pack({'side': 'left'}) - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/canvas-gridding.py b/Demo/tkinter/matt/canvas-gridding.py deleted file mode 100644 index 352408440e..0000000000 --- a/Demo/tkinter/matt/canvas-gridding.py +++ /dev/null @@ -1,60 +0,0 @@ -from Tkinter import * - -# this is the same as simple-demo-1.py, but uses -# subclassing. -# note that there is no explicit call to start Tk. -# Tkinter is smart enough to start the system if it's not already going. - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'bg': 'red', - 'fg': 'white', - 'height' : 3, - 'command': self.quit}) - self.QUIT.pack({'side': 'bottom', 'fill': 'both'}) - - self.canvasObject = Canvas(self, {"width" : "5i", "height" : "5i"}) - self.canvasObject.pack({'side': 'left'}) - - def mouseDown(self, event): - # canvas x and y take the screen coords from the event and translate - # them into the coordinate system of the canvas object - self.startx = self.canvasObject.canvasx(event.x, self.griddingSize) - self.starty = self.canvasObject.canvasy(event.y, self.griddingSize) - - def mouseMotion(self, event): - # canvas x and y take the screen coords from the event and translate - # them into the coordinate system of the canvas object - x = self.canvasObject.canvasx(event.x, self.griddingsize) - y = self.canvasObject.canvasy(event.y, self.griddingsize) - - if (self.startx != event.x) and (self.starty != event.y) : - self.canvasObject.delete(self.rubberbandBox) - self.rubberbandBox = self.canvasObject.create_rectangle(self.startx, self.starty, x, y) - # this flushes the output, making sure that - # the rectangle makes it to the screen - # before the next event is handled - self.update_idletasks() - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - - # this is a "tagOrId" for the rectangle we draw on the canvas - self.rubberbandBox = None - - # this is the size of the gridding squares - self.griddingSize = 50 - - Widget.bind(self.canvasObject, "", self.mouseDown) - Widget.bind(self.canvasObject, "", self.mouseMotion) - - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/canvas-moving-or-creating.py b/Demo/tkinter/matt/canvas-moving-or-creating.py deleted file mode 100644 index f58cc9738b..0000000000 --- a/Demo/tkinter/matt/canvas-moving-or-creating.py +++ /dev/null @@ -1,70 +0,0 @@ -from Tkinter import * - -# this file demonstrates a more sophisticated movement -- -# move dots or create new ones if you click outside the dots - -class Test(Frame): - ################################################################### - ###### Event callbacks for THE CANVAS (not the stuff drawn on it) - ################################################################### - def mouseDown(self, event): - # see if we're inside a dot. If we are, it - # gets tagged as "current" for free by tk. - - if not event.widget.find_withtag("current"): - # there is no dot here, so we can make one, - # and bind some interesting behavior to it. - # ------ - - # create a dot, and mark it as current - fred = self.draw.create_oval(event.x - 10, event.y -10, event.x +10, event.y + 10, - {"fill" : "green", "tag" : "current"}) - - self.draw.bind(fred, "", self.mouseEnter) - self.draw.bind(fred, "", self.mouseLeave) - - self.lastx = event.x - self.lasty = event.y - - - def mouseMove(self, event): - self.draw.move("current", event.x - self.lastx, event.y - self.lasty) - self.lastx = event.x - self.lasty = event.y - - ################################################################### - ###### Event callbacks for canvas ITEMS (stuff drawn on the canvas) - ################################################################### - def mouseEnter(self, event): - # the "current" tag is applied to the object the cursor is over. - # this happens automatically. - self.draw.itemconfig("current", {"fill" : "red"}) - - def mouseLeave(self, event): - # the "current" tag is applied to the object the cursor is over. - # this happens automatically. - self.draw.itemconfig("current", {"fill" : "blue"}) - - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - self.QUIT.pack({'side': 'left', 'fill': 'both'}) - self.draw = Canvas(self, {"width" : "5i", "height" : "5i"}) - self.draw.pack({'side': 'left'}) - - - Widget.bind(self.draw, "<1>", self.mouseDown) - Widget.bind(self.draw, "", self.mouseMove) - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() -test.mainloop() - - - diff --git a/Demo/tkinter/matt/canvas-moving-w-mouse.py b/Demo/tkinter/matt/canvas-moving-w-mouse.py deleted file mode 100644 index f07e6589dd..0000000000 --- a/Demo/tkinter/matt/canvas-moving-w-mouse.py +++ /dev/null @@ -1,59 +0,0 @@ -from Tkinter import * - -# this file demonstrates the movement of a single canvas item under mouse control - -class Test(Frame): - ################################################################### - ###### Event callbacks for THE CANVAS (not the stuff drawn on it) - ################################################################### - def mouseDown(self, event): - # remember where the mouse went down - self.lastx = event.x - self.lasty = event.y - - - def mouseMove(self, event): - # whatever the mouse is over gets tagged as "current" for free by tk. - self.draw.move("current", event.x - self.lastx, event.y - self.lasty) - self.lastx = event.x - self.lasty = event.y - - ################################################################### - ###### Event callbacks for canvas ITEMS (stuff drawn on the canvas) - ################################################################### - def mouseEnter(self, event): - # the "current" tag is applied to the object the cursor is over. - # this happens automatically. - self.draw.itemconfig("current", {"fill" : "red"}) - - def mouseLeave(self, event): - # the "current" tag is applied to the object the cursor is over. - # this happens automatically. - self.draw.itemconfig("current", {"fill" : "blue"}) - - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - self.QUIT.pack({'side': 'left', 'fill': 'both'}) - self.draw = Canvas(self, {"width" : "5i", "height" : "5i"}) - self.draw.pack({'side': 'left'}) - - - fred = self.draw.create_oval(0, 0, 20, 20, - {"fill" : "green", "tag" : "selected"}) - - self.draw.tag_bind(fred, "", self.mouseEnter) - self.draw.tag_bind(fred, "", self.mouseLeave) - - Widget.bind(self.draw, "<1>", self.mouseDown) - Widget.bind(self.draw, "", self.mouseMove) - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() -test.mainloop() diff --git a/Demo/tkinter/matt/canvas-mult-item-sel.py b/Demo/tkinter/matt/canvas-mult-item-sel.py deleted file mode 100644 index 1e49ba667c..0000000000 --- a/Demo/tkinter/matt/canvas-mult-item-sel.py +++ /dev/null @@ -1,85 +0,0 @@ -from Tkinter import * - -# allows moving dots with multiple selection. - -SELECTED_COLOR = "red" -UNSELECTED_COLOR = "blue" - -class Test(Frame): - ################################################################### - ###### Event callbacks for THE CANVAS (not the stuff drawn on it) - ################################################################### - def mouseDown(self, event): - # see if we're inside a dot. If we are, it - # gets tagged as "current" for free by tk. - - if not event.widget.find_withtag("current"): - # we clicked outside of all dots on the canvas. unselect all. - - # re-color everything back to an unselected color - self.draw.itemconfig("selected", {"fill" : UNSELECTED_COLOR}) - # unselect everything - self.draw.dtag("selected") - else: - # mark as "selected" the thing the cursor is under - self.draw.addtag("selected", "withtag", "current") - # color it as selected - self.draw.itemconfig("selected", {"fill": SELECTED_COLOR}) - - self.lastx = event.x - self.lasty = event.y - - - def mouseMove(self, event): - self.draw.move("selected", event.x - self.lastx, event.y - self.lasty) - self.lastx = event.x - self.lasty = event.y - - def makeNewDot(self): - # create a dot, and mark it as current - fred = self.draw.create_oval(0, 0, 20, 20, - {"fill" : SELECTED_COLOR, "tag" : "current"}) - # and make it selected - self.draw.addtag("selected", "withtag", "current") - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - - ################ - # make the canvas and bind some behavior to it - ################ - self.draw = Canvas(self, {"width" : "5i", "height" : "5i"}) - Widget.bind(self.draw, "<1>", self.mouseDown) - Widget.bind(self.draw, "", self.mouseMove) - - - # and other things..... - self.button = Button(self, {"text" : "make a new dot", - "command" : self.makeNewDot, - "fg" : "blue"}) - - self.label = Message(self, - {"width" : "5i", - "text" : SELECTED_COLOR + " dots are selected and can be dragged.\n" + - UNSELECTED_COLOR + " are not selected.\n" + - "Click in a dot to select it.\n" + - "Click on empty space to deselect all dots." }) - - self.QUIT.pack({'side': 'bottom', 'fill': 'both'}) - self.label.pack({"side" : "bottom", "fill" : "x", "expand" : 1}) - self.button.pack({"side" : "bottom", "fill" : "x"}) - self.draw.pack({'side': 'left'}) - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() -test.mainloop() - - - diff --git a/Demo/tkinter/matt/canvas-reading-tag-info.py b/Demo/tkinter/matt/canvas-reading-tag-info.py deleted file mode 100644 index 14786214d5..0000000000 --- a/Demo/tkinter/matt/canvas-reading-tag-info.py +++ /dev/null @@ -1,51 +0,0 @@ -from Tkinter import * - - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - self.QUIT.pack({'side': 'bottom', 'fill': 'both'}) - - self.drawing = Canvas(self, {"width" : "5i", "height" : "5i"}) - - # make a shape - pgon = self.drawing.create_polygon("10", "10", "110", "10", "110", "110", "10" , "110", - {"fill" : "red", - "tags" : "weee foo groo"}) - - # this is how you query an object for its attributes - # config options FOR CANVAS ITEMS always come back in tuples of length 5. - # 0 attribute name - # 1 BLANK - # 2 BLANK - # 3 default value - # 4 current value - # the blank spots are for consistency with the config command that - # is used for widgets. (remember, this is for ITEMS drawn - # on a canvas widget, not widgets) - option_value = self.drawing.itemconfig(pgon, "stipple") - print "pgon's current stipple value is -->", option_value[4], "<--" - option_value = self.drawing.itemconfig(pgon, "fill") - print "pgon's current fill value is -->", option_value[4], "<-- when he is usually colored -->", option_value[3], "<--" - - ## here we print out all the tags associated with this object - option_value = self.drawing.itemconfig(pgon, "tags") - print "pgon's tags are", option_value[4] - - self.drawing.pack({'side': 'left'}) - - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/canvas-w-widget-draw-el.py b/Demo/tkinter/matt/canvas-w-widget-draw-el.py deleted file mode 100644 index 5453859231..0000000000 --- a/Demo/tkinter/matt/canvas-w-widget-draw-el.py +++ /dev/null @@ -1,39 +0,0 @@ -from Tkinter import * - -# this file demonstrates the creation of widgets as part of a canvas object - -class Test(Frame): - def printhi(self): - print "hi" - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - self.QUIT.pack({'side': 'bottom', 'fill': 'both'}) - - self.draw = Canvas(self, {"width" : "5i", "height" : "5i"}) - - self.button = Button(self, {"text" : "this is a button", - "command" : self.printhi}) - - # note here the coords are given in pixels (form the - # upper right and corner of the window, as usual for X) - # but might just have well been given in inches or points or - # whatever...use the "anchor" option to control what point of the - # widget (in this case the button) gets mapped to the given x, y. - # you can specify corners, edges, center, etc... - self.draw.create_window(300, 300, {"window" : self.button}) - - self.draw.pack({'side': 'left'}) - - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/canvas-with-scrollbars.py b/Demo/tkinter/matt/canvas-with-scrollbars.py deleted file mode 100644 index d2498222ee..0000000000 --- a/Demo/tkinter/matt/canvas-with-scrollbars.py +++ /dev/null @@ -1,67 +0,0 @@ -from Tkinter import * - -# This example program creates a scroling canvas, and demonstrates -# how to tie scrollbars and canvses together. The mechanism -# is analogus for listboxes and other widgets with -# "xscroll" and "yscroll" configuration options. - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - self.question = Label(self, {"text": "Can Find The BLUE Square??????", - Pack : {"side" : "top"}}) - - self.QUIT = Button(self, {'text': 'QUIT', - 'bg': 'red', - "height" : "3", - 'command': self.quit}) - self.QUIT.pack({'side': 'bottom', 'fill': 'both'}) - spacer = Frame(self, {"height" : "0.25i", - Pack : {"side" : "bottom"}}) - - # notice that the scroll region (20" x 20") is larger than - # displayed size of the widget (5" x 5") - self.draw = Canvas(self, {"width" : "5i", - "height" : "5i", - "bg" : "white", - "scrollregion" : "0i 0i 20i 20i"}) - - - self.draw.scrollX = Scrollbar(self, {"orient" : "horizontal"}) - self.draw.scrollY = Scrollbar(self, {"orient" : "vertical"}) - - # now tie the three together. This is standard boilerplate text - self.draw['xscrollcommand'] = self.draw.scrollX.set - self.draw['yscrollcommand'] = self.draw.scrollY.set - self.draw.scrollX['command'] = self.draw.xview - self.draw.scrollY['command'] = self.draw.yview - - # draw something. Note that the first square - # is visible, but you need to scroll to see the second one. - self.draw.create_polygon("0i", "0i", "3.5i", "0i", "3.5i", "3.5i", "0i" , "3.5i") - self.draw.create_polygon("10i", "10i", "13.5i", "10i", "13.5i", "13.5i", "10i" , "13.5i", "-fill", "blue") - - - # pack 'em up - self.draw.scrollX.pack({'side': 'bottom', - "fill" : "x"}) - self.draw.scrollY.pack({'side': 'right', - "fill" : "y"}) - self.draw.pack({'side': 'left'}) - - - def scrollCanvasX(self, *args): - print "scrolling", args - print self.draw.scrollX.get() - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/dialog-box.py b/Demo/tkinter/matt/dialog-box.py deleted file mode 100644 index e40c72eef5..0000000000 --- a/Demo/tkinter/matt/dialog-box.py +++ /dev/null @@ -1,65 +0,0 @@ -from Tkinter import * - -# this shows how to create a new window with a button in it that can create new windows - -class Test(Frame): - def printit(self): - print "hi" - - def makeWindow(self): - # there is no Tkinter interface to the dialog box. Making one would mean putting - # a few wrapper functions in the Tkinter.py file. - # even better is to put in a SUIT-like selection of commonly-used dialogs. - # the parameters to this call are as follows: - - fred = Toplevel() # a toplevel window that the dialog goes into - - - # this function returns the index of teh button chosen. In this case, 0 for "yes" and 1 for "no" - - print self.tk.call("tk_dialog", # the command name - fred, # the name of a toplevel window - "fred the dialog box", # the title on the window - "click on a choice", # the message to appear in the window - "info", # the bitmap (if any) to appear. If no bitmap is desired, pass "" - # legal values here are: - # string what it looks like - # ---------------------------------------------- - # error a circle with a slash through it - # grey25 grey square - # grey50 darker grey square - # hourglass use for "wait.." - # info a large, lower case "i" - # questhead a human head with a "?" in it - # question a large "?" - # warning a large "!" - # @fname any X bitmap where fname is the path to the file - # - "0", # the index of the default button choice. hitting return selects this - "yes", "no") # all remaining parameters are the labels for the - # buttons that appear left to right in the dialog box - - - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - - self.QUIT.pack({'side': 'left', 'fill': 'both'}) - - - # a hello button - self.hi_there = Button(self, {'text': 'Make a New Window', - 'command' : self.makeWindow}) - self.hi_there.pack({'side': 'left'}) - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.windownum = 0 - self.createWidgets() - -test = Test() -test.mainloop() diff --git a/Demo/tkinter/matt/entry-simple.py b/Demo/tkinter/matt/entry-simple.py deleted file mode 100644 index cf82b89ce9..0000000000 --- a/Demo/tkinter/matt/entry-simple.py +++ /dev/null @@ -1,25 +0,0 @@ -from Tkinter import * -import string - -# This program shows how to use a simple type-in box - -class App(Frame): - def __init__(self, master=None): - Frame.__init__(self, master) - self.pack() - - self.entrythingy = Entry() - self.entrythingy.pack() - - # and here we get a callback when the user hits return. we could - # make the key that triggers the callback anything we wanted to. - # other typical options might be or (for anything) - self.entrythingy.bind('', self.print_contents) - - def print_contents(self, event): - print "hi. contents of entry is now ---->", self.entrythingy.get() - -root = App() -root.master.title("Foo") -root.mainloop() - diff --git a/Demo/tkinter/matt/entry-with-shared-variable.py b/Demo/tkinter/matt/entry-with-shared-variable.py deleted file mode 100644 index 5eb8c5ae62..0000000000 --- a/Demo/tkinter/matt/entry-with-shared-variable.py +++ /dev/null @@ -1,47 +0,0 @@ -from Tkinter import * -import string - -# This program shows how to make a typein box shadow a program variable. - -class App(Frame): - def __init__(self, master=None): - Frame.__init__(self, master) - self.pack() - - self.entrythingy = Entry() - self.entrythingy.pack() - - self.button = Button(self, {"text" : "Uppercase The Entry", "command" : self.upper}) - self.button.pack() - - - # here we have the text in the entry widget tied to a variable. - # changes in the variable are echoed in the widget and vice versa. - # Very handy. - # there are other Variable types. See Tkinter.py for all - # the other variable types that can be shadowed - self.contents = StringVar() - self.contents.set("this is a variable") - self.entrythingy.config({"textvariable":self.contents}) - - # and here we get a callback when the user hits return. we could - # make the key that triggers the callback anything we wanted to. - # other typical options might be or (for anything) - self.entrythingy.bind('', self.print_contents) - - def upper(self): - # notice here, we don't actually refer to the entry box. - # we just operate on the string variable and we - # because it's being looked at by the entry widget, changing - # the variable changes the entry widget display automatically. - # the strange get/set operators are clunky, true... - str = string.upper(self.contents.get()) - self.contents.set(str) - - def print_contents(self, event): - print "hi. contents of entry is now ---->", self.contents.get() - -root = App() -root.master.title("Foo") -root.mainloop() - diff --git a/Demo/tkinter/matt/killing-window-w-wm.py b/Demo/tkinter/matt/killing-window-w-wm.py deleted file mode 100644 index 6ec3464f2f..0000000000 --- a/Demo/tkinter/matt/killing-window-w-wm.py +++ /dev/null @@ -1,43 +0,0 @@ -from Tkinter import * - -# This file shows how to trap the killing of a window -# when the user uses window manager menus (typ. upper left hand corner -# menu in the decoration border). - - -### ******* this isn't really called -- read the comments -def my_delete_callback(): - print "whoops -- tried to delete me!" - -class Test(Frame): - def deathHandler(self, event): - print self, "is now getting nuked. performing some save here...." - - def createWidgets(self): - # a hello button - self.hi_there = Button(self, {'text': 'Hello'}) - self.hi_there.pack({'side': 'left'}) - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - - ### - ### PREVENT WM kills from happening - ### - - # the docs would have you do this: - -# self.master.protocol("WM_DELETE_WINDOW", my_delete_callback) - - # unfortunately, some window managers will not send this request to a window. - # the "protocol" function seems incapable of trapping these "aggressive" window kills. - # this line of code catches everything, tho. The window is deleted, but you have a chance - # of cleaning up first. - self.bind_all("", self.deathHandler) - - -test = Test() -test.mainloop() diff --git a/Demo/tkinter/matt/menu-all-types-of-entries.py b/Demo/tkinter/matt/menu-all-types-of-entries.py deleted file mode 100644 index 5341ca2b6f..0000000000 --- a/Demo/tkinter/matt/menu-all-types-of-entries.py +++ /dev/null @@ -1,268 +0,0 @@ -from Tkinter import * - -# some vocabulary to keep from getting confused. This terminology -# is something I cooked up for this file, but follows the man pages -# pretty closely -# -# -# -# This is a MENUBUTTON -# V -# +-------------+ -# | | -# -# +------------++------------++------------+ -# | || || | -# | File || Edit || Options | <-------- the MENUBAR -# | || || | -# +------------++------------++------------+ -# | New... | -# | Open... | -# | Print | -# | | <-------- This is a MENU. The lines of text in the menu are -# | | MENU ENTRIES -# | +---------------+ -# | Open Files > | file1 | -# | | file2 | -# | | another file | <------ this cascading part is also a MENU -# +----------------| | -# | | -# | | -# | | -# +---------------+ - - - -# some miscellaneous callbacks -def new_file(): - print "opening new file" - - -def open_file(): - print "opening OLD file" - -def print_something(): - print "picked a menu item" - - - -anchovies = 0 - -def print_anchovies(): - global anchovies - anchovies = not anchovies - print "anchovies?", anchovies - -def makeCommandMenu(): - # make menu button - Command_button = Menubutton(mBar, {'text': 'Simple Button Commands', - 'underline': 0, - Pack: {'side': 'left', - 'padx': '2m'}}) - - # make the pulldown part of the File menu. The parameter passed is the master. - # we attach it to the button as a python attribute called "menu" by convention. - # hopefully this isn't too confusing... - Command_button.menu = Menu(Command_button) - - - # just to be cute, let's disable the undo option: - Command_button.menu.add('command', {"label" : "Undo"} ) - # undo is the 0th entry... - Command_button.menu.entryconfig(0, {"state" : "disabled"}) - - Command_button.menu.add('command', {'label': 'New...', - - 'underline': 0, - 'command' : new_file}) - - - Command_button.menu.add('command', {'label': 'Open...', - 'underline': 0, - 'command' : open_file}) - - Command_button.menu.add('command', {'label': 'Different Font', - 'underline': 0, - 'font' : '-*-helvetica-*-r-*-*-*-180-*-*-*-*-*-*', - 'command' : print_something}) - - # we can make bitmaps be menu entries too. File format is X11 bitmap. - # if you use XV, save it under X11 bitmap format. duh-uh.,.. -# Command_button.menu.add('command', {'bitmap' : '@/home/mjc4y/ftp/tcl/tk3.6/library/demos/bitmaps/face'}) - Command_button.menu.add('command', {'bitmap' : '@/home/mjc4y/dilbert/project.status.is.doomed.last.panel.bm'}) - - # this is just a line - Command_button.menu.add('separator') - - # change the color - Command_button.menu.add('command', {'label': 'Quit', - 'underline': 0, - 'background' : 'red', - 'activebackground' : 'green', - 'command': 'exit'}) - - - # set up a pointer from the file menubutton back to the file menu - Command_button['menu'] = Command_button.menu - - return Command_button - - - -def makeCascadeMenu(): - # make menu button - Cascade_button = Menubutton(mBar, {'text': 'Cascading Menus', - 'underline': 0, - Pack: {'side': 'left', - 'padx': '2m'}}) - - # the primary pulldown - Cascade_button.menu = Menu(Cascade_button) - - # this is the menu that cascades from the primary pulldown.... - Cascade_button.menu.choices = Menu(Cascade_button.menu) - - # ...and this is a menu that cascades from that. - Cascade_button.menu.choices.wierdones = Menu(Cascade_button.menu.choices) - - # then you define the menus from the deepest level on up. - Cascade_button.menu.choices.wierdones.add('command', {'label' : 'avacado'}) - Cascade_button.menu.choices.wierdones.add('command', {'label' : 'belgian endive'}) - Cascade_button.menu.choices.wierdones.add('command', {'label' : 'beefaroni'}) - - # definition of the menu one level up... - Cascade_button.menu.choices.add('command', {'label' : 'Chocolate'}) - Cascade_button.menu.choices.add('command', {'label' : 'Vanilla'}) - Cascade_button.menu.choices.add('command', {'label' : 'TuttiFruiti'}) - Cascade_button.menu.choices.add('command', {'label' : 'WopBopaLoopBapABopBamBoom'}) - Cascade_button.menu.choices.add('command', {'label' : 'Rocky Road'}) - Cascade_button.menu.choices.add('command', {'label' : 'BubbleGum'}) - Cascade_button.menu.choices.add('cascade', {'label' : 'Wierd Flavors', - 'menu' : Cascade_button.menu.choices.wierdones}) - - # and finally, the definition for the top level - Cascade_button.menu.add('cascade', {'label' : 'more choices', - 'menu' : Cascade_button.menu.choices}) - - - Cascade_button['menu'] = Cascade_button.menu - - return Cascade_button - -def makeCheckbuttonMenu(): - global fred - # make menu button - Checkbutton_button = Menubutton(mBar, {'text': 'Checkbutton Menus', - 'underline': 0, - Pack: {'side': 'left', - 'padx': '2m'}}) - - # the primary pulldown - Checkbutton_button.menu = Menu(Checkbutton_button) - - # and all the check buttons. Note that the "variable" "onvalue" and "offvalue" options - # are not supported correctly at present. You have to do all your application - # work through the calback. - Checkbutton_button.menu.add('checkbutton', {'label': 'Pepperoni'}) - Checkbutton_button.menu.add('checkbutton', {'label': 'Sausage'}) - Checkbutton_button.menu.add('checkbutton', {'label': 'Extra Cheese'}) - - # so here's a callback - Checkbutton_button.menu.add('checkbutton', {'label': 'Anchovy', - 'command' : print_anchovies}) - - # and start with anchovies selected to be on. Do this by - # calling invoke on this menu option. To refer to the "anchovy" menu - # entry we need to know it's index. To do this, we use the index method - # which takes arguments of several forms: - # - # argument what it does - # ----------------------------------- - # a number -- this is useless. - # "last" -- last option in the menu - # "none" -- used with the activate command. see the man page on menus - # "active" -- the currently active menu option. A menu option is made active - # with the 'activate' method - # "@number" -- where 'number' is an integer and is treated like a y coordinate in pixels - # string pattern -- this is the option used below, and attempts to match "labels" using the - # rules of Tcl_StringMatch - Checkbutton_button.menu.invoke(Checkbutton_button.menu.index('Anchovy')) - - # set up a pointer from the file menubutton back to the file menu - Checkbutton_button['menu'] = Checkbutton_button.menu - - return Checkbutton_button - - -def makeRadiobuttonMenu(): - # make menu button - Radiobutton_button = Menubutton(mBar, {'text': 'Radiobutton Menus', - 'underline': 0, - Pack: {'side': 'left', - 'padx': '2m'}}) - - # the primary pulldown - Radiobutton_button.menu = Menu(Radiobutton_button) - - # and all the Radio buttons. Note that the "variable" "onvalue" and "offvalue" options - # are not supported correctly at present. You have to do all your application - # work through the calback. - Radiobutton_button.menu.add('radiobutton', {'label': 'Republican'}) - Radiobutton_button.menu.add('radiobutton', {'label': 'Democrat'}) - Radiobutton_button.menu.add('radiobutton', {'label': 'Libertarian'}) - Radiobutton_button.menu.add('radiobutton', {'label': 'Commie'}) - Radiobutton_button.menu.add('radiobutton', {'label': 'Facist'}) - Radiobutton_button.menu.add('radiobutton', {'label': 'Labor Party'}) - Radiobutton_button.menu.add('radiobutton', {'label': 'Torie'}) - Radiobutton_button.menu.add('radiobutton', {'label': 'Independent'}) - Radiobutton_button.menu.add('radiobutton', {'label': 'Anarchist'}) - Radiobutton_button.menu.add('radiobutton', {'label': 'No Opinion'}) - - # set up a pointer from the file menubutton back to the file menu - Radiobutton_button['menu'] = Radiobutton_button.menu - - return Radiobutton_button - - -def makeDisabledMenu(): - Dummy_button = Menubutton(mBar, {'text': 'Dead Menu', - 'underline': 0, - Pack: {'side': 'left', - 'padx': '2m'}}) - - # this is the standard way of turning off a whole menu - Dummy_button["state"] = "disabled" - return Dummy_button - -################################################# -#### Main starts here ... -root = Tk() - - -# make a menu bar -mBar = Frame(root, {'relief': 'raised', - 'bd': 2, - Pack: {'side': 'top', - 'fill': 'x'}}) - -Command_button = makeCommandMenu() -Cascade_button = makeCascadeMenu() -Checkbutton_button = makeCheckbuttonMenu() -Radiobutton_button = makeRadiobuttonMenu() -NoMenu = makeDisabledMenu() - -# finally, install the buttons in the menu bar. -# This allows for scanning from one menubutton to the next. -mBar.tk_menuBar(Command_button, Cascade_button, Checkbutton_button, Radiobutton_button, NoMenu) - - -root.title('menu demo') -root.iconname('menu demo') - -root.mainloop() - - - - - - diff --git a/Demo/tkinter/matt/menu-simple.py b/Demo/tkinter/matt/menu-simple.py deleted file mode 100644 index 1f46e2116a..0000000000 --- a/Demo/tkinter/matt/menu-simple.py +++ /dev/null @@ -1,132 +0,0 @@ -from Tkinter import * - -# some vocabulary to keep from getting confused. This terminology -# is something I cooked up for this file, but follows the man pages -# pretty closely -# -# -# -# This is a MENUBUTTON -# V -# +-------------+ -# | | -# -# +------------++------------++------------+ -# | || || | -# | File || Edit || Options | <-------- the MENUBAR -# | || || | -# +------------++------------++------------+ -# | New... | -# | Open... | -# | Print | -# | | <------ This is a MENU. The lines of text in the menu are -# | | MENU ENTRIES -# | +---------------+ -# | Open Files > | file1 | -# | | file2 | -# | | another file | <------ this cascading part is also a MENU -# +----------------| | -# | | -# | | -# | | -# +---------------+ - - - -def new_file(): - print "opening new file" - - -def open_file(): - print "opening OLD file" - - -def makeFileMenu(): - # make menu button : "File" - File_button = Menubutton(mBar, {'text': 'File', - 'underline': 0, - Pack: {'side': 'left', - 'padx': '1m'}}) - - # make the pulldown part of the File menu. The parameter passed is the master. - # we attach it to the File button as a python attribute called "menu" by convention. - # hopefully this isn't too confusing... - File_button.menu = Menu(File_button) - - # add an item. The first param is a menu entry type, - # must be one of: "cascade", "checkbutton", "command", "radiobutton", "seperator" - # see menu-demo-2.py for examples of use - File_button.menu.add('command', {'label': 'New...', - 'underline': 0, - 'command' : new_file}) - - - File_button.menu.add('command', {'label': 'Open...', - 'underline': 0, - 'command' : open_file}) - - File_button.menu.add('command', {'label': 'Quit', - 'underline': 0, - 'command': 'exit'}) - - - # set up a pointer from the file menubutton back to the file menu - File_button['menu'] = File_button.menu - - return File_button - - - -def makeEditMenu(): - Edit_button = Menubutton(mBar, {'text': 'Edit', - 'underline': 0, - Pack: {'side': 'left', - 'padx' : '1m'}}) - Edit_button.menu = Menu(Edit_button) - - # just to be cute, let's disable the undo option: - Edit_button.menu.add('command', {"label" : "Undo"} ) - # undo is the 0th entry... - Edit_button.menu.entryconfig(0, {"state" : "disabled"}) - - # and these are just for show. No "command" callbacks attached. - Edit_button.menu.add('command', {"label" : "Cut"} ) - Edit_button.menu.add('command', {"label" : "Copy"} ) - Edit_button.menu.add('command', {"label" : "Paste"} ) - - # set up a pointer from the file menubutton back to the file menu - Edit_button['menu'] = Edit_button.menu - - return Edit_button - - -################################################# - -#### Main starts here ... -root = Tk() - - -# make a menu bar -mBar = Frame(root, {'relief': 'raised', - 'bd': 2, - Pack: {'side': 'top', - 'fill': 'x'}}) - -File_button = makeFileMenu() -Edit_button = makeEditMenu() - -# finally, install the buttons in the menu bar. -# This allows for scanning from one menubutton to the next. -mBar.tk_menuBar(File_button, Edit_button) - - -root.title('menu demo') -root.iconname('packer') - -root.mainloop() - - - - - - diff --git a/Demo/tkinter/matt/not-what-you-might-think-1.py b/Demo/tkinter/matt/not-what-you-might-think-1.py deleted file mode 100644 index 6f5481edd3..0000000000 --- a/Demo/tkinter/matt/not-what-you-might-think-1.py +++ /dev/null @@ -1,32 +0,0 @@ -from Tkinter import * - - -class Test(Frame): - def createWidgets(self): - - self.Gpanel = Frame(self, {'width': '1i', - 'height' : '1i', - 'bg' : 'green'}) - self.Gpanel.pack({'side' : 'left'}) - - - # a QUIT button - self.Gpanel.QUIT = Button(self.Gpanel, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - self.Gpanel.QUIT.pack( {'side': 'left'}) - - - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() - -test.master.title('packer demo') -test.master.iconname('packer') - -test.mainloop() diff --git a/Demo/tkinter/matt/not-what-you-might-think-2.py b/Demo/tkinter/matt/not-what-you-might-think-2.py deleted file mode 100644 index dd6c2ecdc9..0000000000 --- a/Demo/tkinter/matt/not-what-you-might-think-2.py +++ /dev/null @@ -1,37 +0,0 @@ -from Tkinter import * - - -class Test(Frame): - def createWidgets(self): - - self.Gpanel = Frame(self, {'width': '1i', - 'height' : '1i', - 'bg' : 'green'}) - - # this line turns off the recalculation of geometry by masters. - self.Gpanel.tk.call('pack', 'propagate', str(self.Gpanel), "0") - - self.Gpanel.pack({'side' : 'left'}) - - - - # a QUIT button - self.Gpanel.QUIT = Button(self.Gpanel, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - self.Gpanel.QUIT.pack( {'side': 'left'}) - - - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() - -test.master.title('packer demo') -test.master.iconname('packer') - -test.mainloop() diff --git a/Demo/tkinter/matt/packer-and-placer-together.py b/Demo/tkinter/matt/packer-and-placer-together.py deleted file mode 100644 index 64b38216a6..0000000000 --- a/Demo/tkinter/matt/packer-and-placer-together.py +++ /dev/null @@ -1,50 +0,0 @@ -from Tkinter import * - -# This is a program that tests the placer geom manager in conjunction with -# the packer. The background (green) is packed, while the widget inside is placed - - -def do_motion(event): - app.button.place({'x' : event.x, - 'y' : event.y}) - -def dothis(): - print 'calling me!' - -def createWidgets(top): - # make a frame. Note that the widget is 200 x 200 - # and the window containing is 400x400. We do this - # simply to show that this is possible. The rest of the - # area is inaccesssible. - f = Frame(top, {'width' : '200', - 'height' : '200', - 'bg' : 'green'}) - - # note that we use a different manager here. - # This way, the top level frame widget resizes when the - # application window does. - f.pack({'fill' : 'both', - 'expand' : 1}) - - # now make a button - f.button = Button(f, {'fg' : 'red', - 'text' : 'amazing', - 'command' : dothis}) - - # and place it so that the nw corner is - # 1/2 way along the top X edge of its' parent - f.button.place({'relx' : '0.5', - 'rely' : '0.0', - 'anchor' : 'nw'}) - - # allow the user to move the button SUIT-style. - f.bind('', do_motion) - - return f - -root = Tk() -app = createWidgets(root) -root.geometry("400x400") -root.maxsize(1000, 1000) -root.mainloop() - diff --git a/Demo/tkinter/matt/packer-simple.py b/Demo/tkinter/matt/packer-simple.py deleted file mode 100644 index 4519a72df4..0000000000 --- a/Demo/tkinter/matt/packer-simple.py +++ /dev/null @@ -1,35 +0,0 @@ -from Tkinter import * - - -class Test(Frame): - def printit(self): - print self.hi_there["command"] - - def createWidgets(self): - # a hello button - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - - self.QUIT.pack({'side': 'left', 'fill': 'both'}) - - - self.hi_there = Button(self, {'text': 'Hello', - 'command' : self.printit}) - self.hi_there.pack({'side': 'left'}) - - # note how Packer defaults to {'side': 'top'} - - self.guy2 = Button(self, {'text': 'button 2'}) - self.guy2.pack() - - self.guy3 = Button(self, {'text': 'button 3'}) - self.guy3.pack() - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() -test.mainloop() diff --git a/Demo/tkinter/matt/placer-simple.py b/Demo/tkinter/matt/placer-simple.py deleted file mode 100644 index 724cb97fdf..0000000000 --- a/Demo/tkinter/matt/placer-simple.py +++ /dev/null @@ -1,48 +0,0 @@ -from Tkinter import * - -# This is a program that tests the placer geom manager - -def do_motion(event): - app.button.place({'x' : event.x, - 'y' : event.y}) - -def dothis(): - print 'calling me!' - -def createWidgets(top): - # make a frame. Note that the widget is 200 x 200 - # and the window containing is 400x400. We do this - # simply to show that this is possible. The rest of the - # area is inaccesssible. - f = Frame(top, {'width' : '200', - 'height' : '200', - 'bg' : 'green'}) - - # place it so the upper left hand corner of - # the frame is in the upper left corner of - # the parent - f.place({'relx' : '0.0', - 'rely' : '0.0'}) - - # now make a button - f.button = Button(f, {'fg' : 'red', - 'text' : 'amazing', - 'command' : dothis}) - - # and place it so that the nw corner is - # 1/2 way along the top X edge of its' parent - f.button.place({'relx' : '0.5', - 'rely' : '0.0', - 'anchor' : 'nw'}) - - # allow the user to move the button SUIT-style. - f.bind('', do_motion) - - return f - -root = Tk() -app = createWidgets(root) -root.geometry("400x400") -root.maxsize(1000, 1000) -root.mainloop() - diff --git a/Demo/tkinter/matt/pong-demo-1.py b/Demo/tkinter/matt/pong-demo-1.py deleted file mode 100644 index 7d405c1654..0000000000 --- a/Demo/tkinter/matt/pong-demo-1.py +++ /dev/null @@ -1,59 +0,0 @@ -from Tkinter import * - -import string - - -class Pong(Frame): - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - self.QUIT.pack({'side': 'left', 'fill': 'both'}) - - ## The playing field - self.draw = Canvas(self, {"width" : "5i", "height" : "5i"}) - - ## The speed control for the ball - self.speed = Scale(self, {"orient": "horiz", - "label" : "ball speed", - "from" : -100, - "to" : 100}) - - self.speed.pack({'side': 'bottom', "fill" : "x"}) - - # The ball - self.ball = self.draw.create_oval("0i", "0i", "0.10i", "0.10i", {"fill" : "red"}) - self.x = 0.05 - self.y = 0.05 - self.velocity_x = 0.3 - self.velocity_y = 0.5 - - self.draw.pack({'side': 'left'}) - - - def moveBall(self, *args): - if (self.x > 5.0) or (self.x < 0.0): - self.velocity_x = -1.0 * self.velocity_x - if (self.y > 5.0) or (self.y < 0.0): - self.velocity_y = -1.0 * self.velocity_y - - deltax = (self.velocity_x * self.speed.get() / 100.0) - deltay = (self.velocity_y * self.speed.get() / 100.0) - self.x = self.x + deltax - self.y = self.y + deltay - - self.draw.move(self.ball, `deltax` + "i", `deltay` + "i") - self.after(10, self.moveBall) - - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - self.after(10, self.moveBall) - - -game = Pong() - -game.mainloop() diff --git a/Demo/tkinter/matt/printing-coords-of-items.py b/Demo/tkinter/matt/printing-coords-of-items.py deleted file mode 100644 index 2440378d80..0000000000 --- a/Demo/tkinter/matt/printing-coords-of-items.py +++ /dev/null @@ -1,69 +0,0 @@ -from Tkinter import * - -# this file demonstrates the creation of widgets as part of a canvas object - -class Test(Frame): - ################################################################### - ###### Event callbacks for THE CANVAS (not the stuff drawn on it) - ################################################################### - def mouseDown(self, event): - # see if we're inside a dot. If we are, it - # gets tagged as "current" for free by tk. - - if not event.widget.find_withtag("current"): - # there is no dot here, so we can make one, - # and bind some interesting behavior to it. - # ------ - - # create a dot, and mark it as current - fred = self.draw.create_oval(event.x - 10, event.y -10, event.x +10, event.y + 10, - {"fill" : "green", "tag" : "current"}) - - self.draw.bind(fred, "", self.mouseEnter) - self.draw.bind(fred, "", self.mouseLeave) - - self.lastx = event.x - self.lasty = event.y - - - def mouseMove(self, event): - self.draw.move("current", event.x - self.lastx, event.y - self.lasty) - self.lastx = event.x - self.lasty = event.y - - ################################################################### - ###### Event callbacks for canvas ITEMS (stuff drawn on the canvas) - ################################################################### - def mouseEnter(self, event): - # the "current" tag is applied to the object the cursor is over. - # this happens automatically. - self.draw.itemconfig("current", {"fill" : "red"}) - print self.tk.splitlist(self.draw.coords("current")) - - def mouseLeave(self, event): - # the "current" tag is applied to the object the cursor is over. - # this happens automatically. - self.draw.itemconfig("current", {"fill" : "blue"}) - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - self.QUIT.pack({'side': 'left', 'fill': 'both'}) - self.draw = Canvas(self, {"width" : "5i", "height" : "5i"}) - self.draw.pack({'side': 'left'}) - - - Widget.bind(self.draw, "<1>", self.mouseDown) - Widget.bind(self.draw, "", self.mouseMove) - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() -test.mainloop() - - - diff --git a/Demo/tkinter/matt/radiobutton-simple.py b/Demo/tkinter/matt/radiobutton-simple.py deleted file mode 100644 index a94a74c591..0000000000 --- a/Demo/tkinter/matt/radiobutton-simple.py +++ /dev/null @@ -1,66 +0,0 @@ -from Tkinter import * - -# This is a demo program that shows how to -# create radio buttons and how to get other widgets to -# share the information in a radio button. -# -# There are other ways of doing this too, but -# the "variable" option of radiobuttons seems to be the easiest. -# -# note how each button has a value it sets the variable to as it gets hit. - - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - - self.flavor = StringVar() - self.flavor.set("chocolate") - - self.radioframe = Frame(self) - self.radioframe.pack() - - # 'text' is the label - # 'variable' is the name of the variable that all these radio buttons share - # 'value' is the value this variable takes on when the radio button is selected - # 'anchor' makes the text appear left justified (default is centered. ick) - self.radioframe.choc = Radiobutton (self.radioframe, {"text" : "Chocolate Flavor", - "variable" : self.flavor, - "value" : "chocolate", - "anchor" : "w", - Pack : {"side" : "top", "fill" : "x"}}) - - self.radioframe.straw = Radiobutton (self.radioframe, {"text" : "Strawberry Flavor", - "variable" : self.flavor, - "anchor" : "w", - "value" : "strawberry", - Pack : {"side" : "top", "fill" : "x"}}) - - self.radioframe.lemon = Radiobutton (self.radioframe, {"text" : "Lemon Flavor", - "anchor" : "w", - "variable" : self.flavor, - "value" : "lemon", - Pack : {"side" : "top", "fill" : "x"}}) - - - # this is a text entry that lets you type in the name of a flavor too. - self.entry = Entry(self, {"textvariable" : self.flavor, - Pack : {"side" : "top", "fill" : "x"}}) - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - - self.QUIT.pack({'side': 'bottom', 'fill': 'both'}) - - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/rubber-band-box-demo-1.py b/Demo/tkinter/matt/rubber-band-box-demo-1.py deleted file mode 100644 index 8d382ca3f7..0000000000 --- a/Demo/tkinter/matt/rubber-band-box-demo-1.py +++ /dev/null @@ -1,57 +0,0 @@ -from Tkinter import * - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'bg': 'red', - 'fg': 'white', - 'height' : 3, - 'command': self.quit}) - self.QUIT.pack({'side': 'bottom', 'fill': 'both'}) - - self.canvasObject = Canvas(self, {"width" : "5i", "height" : "5i"}) - self.canvasObject.pack({'side': 'left'}) - - def mouseDown(self, event): - # canvas x and y take the screen coords from the event and translate - # them into the coordinate system of the canvas object - self.startx = self.canvasObject.canvasx(event.x) - self.starty = self.canvasObject.canvasy(event.y) - - def mouseMotion(self, event): - # canvas x and y take the screen coords from the event and translate - # them into the coordinate system of the canvas object - x = self.canvasObject.canvasx(event.x) - y = self.canvasObject.canvasy(event.y) - - if (self.startx != event.x) and (self.starty != event.y) : - self.canvasObject.delete(self.rubberbandBox) - self.rubberbandBox = self.canvasObject.create_rectangle(self.startx, self.starty, x, y) - # this flushes the output, making sure that - # the rectangle makes it to the screen - # before the next event is handled - self.update_idletasks() - - def mouseUp(self, event): - self.canvasObject.delete(self.rubberbandBox) - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - - # this is a "tagOrId" for the rectangle we draw on the canvas - self.rubberbandBox = None - - # and the bindings that make it work.. - Widget.bind(self.canvasObject, "", self.mouseDown) - Widget.bind(self.canvasObject, "", self.mouseMotion) - Widget.bind(self.canvasObject, "", self.mouseUp) - - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/rubber-line-demo-1.py b/Demo/tkinter/matt/rubber-line-demo-1.py deleted file mode 100644 index 8dd107033e..0000000000 --- a/Demo/tkinter/matt/rubber-line-demo-1.py +++ /dev/null @@ -1,50 +0,0 @@ -from Tkinter import * - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'bg': 'red', - 'fg': 'white', - 'height' : 3, - 'command': self.quit}) - self.QUIT.pack({'side': 'bottom', 'fill': 'both'}) - - self.canvasObject = Canvas(self, {"width" : "5i", "height" : "5i"}) - self.canvasObject.pack({'side': 'left'}) - - def mouseDown(self, event): - # canvas x and y take the screen coords from the event and translate - # them into the coordinate system of the canvas object - self.startx = self.canvasObject.canvasx(event.x) - self.starty = self.canvasObject.canvasy(event.y) - - def mouseMotion(self, event): - # canvas x and y take the screen coords from the event and translate - # them into the coordinate system of the canvas object - x = self.canvasObject.canvasx(event.x) - y = self.canvasObject.canvasy(event.y) - - if (self.startx != event.x) and (self.starty != event.y) : - self.canvasObject.delete(self.rubberbandLine) - self.rubberbandLine = self.canvasObject.create_line(self.startx, self.starty, x, y) - # this flushes the output, making sure that - # the rectangle makes it to the screen - # before the next event is handled - self.update_idletasks() - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - # this is a "tagOrId" for the rectangle we draw on the canvas - self.rubberbandLine = None - Widget.bind(self.canvasObject, "", self.mouseDown) - Widget.bind(self.canvasObject, "", self.mouseMotion) - - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/slider-demo-1.py b/Demo/tkinter/matt/slider-demo-1.py deleted file mode 100644 index 0d487ab632..0000000000 --- a/Demo/tkinter/matt/slider-demo-1.py +++ /dev/null @@ -1,40 +0,0 @@ -from Tkinter import * - -# shows how to make a slider, set and get its value under program control - - -class Test(Frame): - def print_value(self, val): - print "slider now at", val - - def reset(self): - self.slider.set(0) - - def createWidgets(self): - self.slider = Scale(self, {"from" : 0, - 'to': 100, - "orient" : "horizontal", - "length" : "3i", - "label" : "happy slider", - 'command' : self.print_value}) - - self.reset = Button(self, {'text': 'reset slider', - 'command': self.reset}) - - - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - - - self.slider.pack({'side': 'left'}) - self.reset.pack({'side': 'left'}) - self.QUIT.pack({'side': 'left', 'fill': 'both'}) - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() -test.mainloop() diff --git a/Demo/tkinter/matt/subclass-existing-widgets.py b/Demo/tkinter/matt/subclass-existing-widgets.py deleted file mode 100644 index 3a0e196434..0000000000 --- a/Demo/tkinter/matt/subclass-existing-widgets.py +++ /dev/null @@ -1,33 +0,0 @@ -from Tkinter import * - -# This is a program that makes a simple two button application - - -class New_Button(Button): - def callback(self): - print self.counter - self.counter = self.counter + 1 - -def createWidgets(top): - f = Frame(top) - f.pack() - f.QUIT = Button(f, {'text': 'QUIT', - 'fg': 'red', - 'command': top.quit}) - - f.QUIT.pack({'side': 'left', 'fill': 'both'}) - - - # a hello button - f.hi_there = New_Button(f, {'text': 'Hello'}) - # we do this on a different line because we need to reference f.hi_there - f.hi_there.config({'command' : f.hi_there.callback}) - f.hi_there.pack({'side': 'left'}) - f.hi_there.counter = 43 - - - -root = Tk() -createWidgets(root) -root.mainloop() - diff --git a/Demo/tkinter/matt/two-radio-groups.py b/Demo/tkinter/matt/two-radio-groups.py deleted file mode 100644 index f65c8a9c49..0000000000 --- a/Demo/tkinter/matt/two-radio-groups.py +++ /dev/null @@ -1,118 +0,0 @@ -from Tkinter import * - -# The way to think about this is that each radio button menu -# controls a different variable -- clicking on one of the -# mutually exclusive choices in a radiobutton assigns some value -# to an application variable you provide. When you define a -# radiobutton menu choice, you have the option of specifying the -# name of a varaible and value to assign to that variable when -# that choice is selected. This clever mechanism relieves you, -# the programmer, from having to write a dumb callback that -# probably wouldn't have done anything more than an assignment -# anyway. The Tkinter options for this follow their Tk -# counterparts: -# {"variable" : my_flavor_variable, "value" : "strawberry"} -# where my_flavor_variable is an instance of one of the -# subclasses of Variable, provided in Tkinter.py (there is -# StringVar(), IntVar(), DoubleVar() and BooleanVar() to choose -# from) - - - -def makePoliticalParties(): - # make menu button - Radiobutton_button = Menubutton(mBar, {'text': 'Political Party', - 'underline': 0, - Pack: {'side': 'left', - 'padx': '2m'}}) - - # the primary pulldown - Radiobutton_button.menu = Menu(Radiobutton_button) - - Radiobutton_button.menu.add('radiobutton', {'label': 'Republican', - 'variable' : party, - 'value' : 1}) - - Radiobutton_button.menu.add('radiobutton', {'label': 'Democrat', - 'variable' : party, - 'value' : 2}) - - Radiobutton_button.menu.add('radiobutton', {'label': 'Libertarian', - 'variable' : party, - 'value' : 3}) - - party.set(2) - - # set up a pointer from the file menubutton back to the file menu - Radiobutton_button['menu'] = Radiobutton_button.menu - - return Radiobutton_button - - -def makeFlavors(): - # make menu button - Radiobutton_button = Menubutton(mBar, {'text': 'Flavors', - 'underline': 0, - Pack: {'side': 'left', - 'padx': '2m'}}) - # the primary pulldown - Radiobutton_button.menu = Menu(Radiobutton_button) - - Radiobutton_button.menu.add('radiobutton', {'label': 'Strawberry', - 'variable' : flavor, - 'value' : 'Strawberry'}) - - Radiobutton_button.menu.add('radiobutton', {'label': 'Chocolate', - 'variable' : flavor, - 'value' : 'Chocolate'}) - - Radiobutton_button.menu.add('radiobutton', {'label': 'Rocky Road', - 'variable' : flavor, - 'value' : 'Rocky Road'}) - - # choose a default - flavor.set("Chocolate") - - # set up a pointer from the file menubutton back to the file menu - Radiobutton_button['menu'] = Radiobutton_button.menu - - return Radiobutton_button - - -def printStuff(): - print "party is", party.get() - print "flavor is", flavor.get() - print "" - -################################################# -#### Main starts here ... -root = Tk() - - -# make a menu bar -mBar = Frame(root, {'relief': 'raised', - 'bd': 2, - Pack: {'side': 'top', - 'fill': 'x'}}) - -# make two application variables, -# one to control each radio button set -party = IntVar() -flavor = StringVar() - -Radiobutton_button = makePoliticalParties() -Radiobutton_button2 = makeFlavors() - -# finally, install the buttons in the menu bar. -# This allows for scanning from one menubutton to the next. -mBar.tk_menuBar(Radiobutton_button, Radiobutton_button2) - -b = Button(root, {"text": "print party and flavor", - "command" : printStuff, - "fg": "red"}) -b.pack({"side" : "top"}) - -root.title('menu demo') -root.iconname('menu demo') - -root.mainloop() diff --git a/Demo/tkinter/matt/window-creation-more.py b/Demo/tkinter/matt/window-creation-more.py deleted file mode 100644 index e8d4a35d95..0000000000 --- a/Demo/tkinter/matt/window-creation-more.py +++ /dev/null @@ -1,37 +0,0 @@ -from Tkinter import * - -# this shows how to create a new window with a button in it that can create new windows - -class Test(Frame): - def printit(self): - print "hi" - - def makeWindow(self): - fred = Toplevel() - fred.label = Button(fred, {'text': "This is window number " + `self.windownum` + "." , - 'command' : self.makeWindow}) - fred.label.pack() - self.windownum = self.windownum + 1 - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - - self.QUIT.pack({'side': 'left', 'fill': 'both'}) - - - # a hello button - self.hi_there = Button(self, {'text': 'Make a New Window', - 'command' : self.makeWindow}) - self.hi_there.pack({'side': 'left'}) - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.windownum = 0 - self.createWidgets() - -test = Test() -test.mainloop() diff --git a/Demo/tkinter/matt/window-creation-simple.py b/Demo/tkinter/matt/window-creation-simple.py deleted file mode 100644 index d881abef65..0000000000 --- a/Demo/tkinter/matt/window-creation-simple.py +++ /dev/null @@ -1,34 +0,0 @@ -from Tkinter import * - -# this shows how to spawn off new windows at a button press - -class Test(Frame): - def printit(self): - print "hi" - - def makeWindow(self): - fred = Toplevel() - fred.label = Label(fred, {'text': "Here's a new window",}) - fred.label.pack() - - def createWidgets(self): - self.QUIT = Button(self, {'text': 'QUIT', - 'fg': 'red', - 'command': self.quit}) - - self.QUIT.pack({'side': 'left', 'fill': 'both'}) - - - # a hello button - self.hi_there = Button(self, {'text': 'Make a New Window', - 'command' : self.makeWindow}) - self.hi_there.pack({'side': 'left'}) - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() -test.mainloop() diff --git a/Demo/tkinter/matt/window-creation-w-location.py b/Demo/tkinter/matt/window-creation-w-location.py deleted file mode 100644 index 8f9ad471cc..0000000000 --- a/Demo/tkinter/matt/window-creation-w-location.py +++ /dev/null @@ -1,40 +0,0 @@ -from Tkinter import * - -import sys -sys.path.append("/users/mjc4y/projects/python/tkinter/utils") -from TkinterUtils import * - -# this shows how to create a new window with a button in it that can create new windows - - -class Test(Frame): - def makeWindow(self, *args): - fred = Toplevel() - - fred.label = Canvas (fred, {"width" : "2i", - "height" : "2i"}) - - fred.label.create_line("0", "0", "2i", "2i") - fred.label.create_line("0", "2i", "2i", "0") - fred.label.pack() - - centerWindow(fred, self.master) - - def createWidgets(self): - self.QUIT = QuitButton(self) - self.QUIT.pack({'side': 'left', 'fill': 'both'}) - - - self.makeWindow = Button(self, {'text': 'Make a New Window', - 'width' : 50, - 'height' : 20, - 'command' : self.makeWindow}) - self.makeWindow.pack({'side': 'left'}) - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() -test.mainloop() diff --git a/Demo/tkinter/www/Para.py b/Demo/tkinter/www/Para.py deleted file mode 100755 index 6a7057ddbf..0000000000 --- a/Demo/tkinter/www/Para.py +++ /dev/null @@ -1,408 +0,0 @@ -# Text formatting abstractions - - -# Oft-used type object -Int = type(0) - - -# Represent a paragraph. This is a list of words with associated -# font and size information, plus indents and justification for the -# entire paragraph. -# Once the words have been added to a paragraph, it can be laid out -# for different line widths. Once laid out, it can be rendered at -# different screen locations. Once rendered, it can be queried -# for mouse hits, and parts of the text can be highlighted -class Para: - # - def __init__(self): - self.words = [] # The words - self.just = 'l' # Justification: 'l', 'r', 'lr' or 'c' - self.indent_left = self.indent_right = self.indent_hang = 0 - # Final lay-out parameters, may change - self.left = self.top = self.right = self.bottom = \ - self.width = self.height = self.lines = None - # - # Add a word, computing size information for it. - # Words may also be added manually by appending to self.words - # Each word should be a 7-tuple: - # (font, text, width, space, stretch, ascent, descent) - def addword(self, d, font, text, space, stretch): - if font <> None: - d.setfont(font) - width = d.textwidth(text) - ascent = d.baseline() - descent = d.lineheight() - ascent - spw = d.textwidth(' ') - space = space * spw - stretch = stretch * spw - tuple = (font, text, width, space, stretch, ascent, descent) - self.words.append(tuple) - # - # Hooks to begin and end anchors -- insert numbers in the word list! - def bgn_anchor(self, id): - self.words.append(id) - # - def end_anchor(self, id): - self.words.append(0) - # - # Return the total length (width) of the text added so far, in pixels - def getlength(self): - total = 0 - for word in self.words: - if type(word) <> Int: - total = total + word[2] + word[3] - return total - # - # Tab to a given position (relative to the current left indent): - # remove all stretch, add fixed space up to the new indent. - # If the current position is already beying the tab stop, - # don't add any new space (but still remove the stretch) - def tabto(self, tab): - total = 0 - as, de = 1, 0 - for i in range(len(self.words)): - word = self.words[i] - if type(word) == Int: continue - fo, te, wi, sp, st, as, de = word - self.words[i] = fo, te, wi, sp, 0, as, de - total = total + wi + sp - if total < tab: - self.words.append(None, '', 0, tab-total, 0, as, de) - # - # Make a hanging tag: tab to hang, increment indent_left by hang, - # and reset indent_hang to -hang - def makehangingtag(self, hang): - self.tabto(hang) - self.indent_left = self.indent_left + hang - self.indent_hang = -hang - # - # Decide where the line breaks will be given some screen width - def layout(self, linewidth): - self.width = linewidth - height = 0 - self.lines = lines = [] - avail1 = self.width - self.indent_left - self.indent_right - avail = avail1 - self.indent_hang - words = self.words - i = 0 - n = len(words) - lastfont = None - while i < n: - firstfont = lastfont - charcount = 0 - width = 0 - stretch = 0 - ascent = 0 - descent = 0 - lsp = 0 - j = i - while i < n: - word = words[i] - if type(word) == Int: - if word > 0 and width >= avail: - break - i = i+1 - continue - fo, te, wi, sp, st, as, de = word - if width + wi > avail and width > 0 and wi > 0: - break - if fo <> None: - lastfont = fo - if width == 0: - firstfont = fo - charcount = charcount + len(te) + (sp > 0) - width = width + wi + sp - lsp = sp - stretch = stretch + st - lst = st - ascent = max(ascent, as) - descent = max(descent, de) - i = i+1 - while i > j and type(words[i-1]) == Int and \ - words[i-1] > 0: i = i-1 - width = width - lsp - if i < n: - stretch = stretch - lst - else: - stretch = 0 - tuple = i-j, firstfont, charcount, width, stretch, \ - ascent, descent - lines.append(tuple) - height = height + ascent + descent - avail = avail1 - self.height = height - # - # Call a function for all words in a line - def visit(self, wordfunc, anchorfunc): - avail1 = self.width - self.indent_left - self.indent_right - avail = avail1 - self.indent_hang - v = self.top - i = 0 - for tuple in self.lines: - wordcount, firstfont, charcount, width, stretch, \ - ascent, descent = tuple - h = self.left + self.indent_left - if i == 0: h = h + self.indent_hang - extra = 0 - if self.just == 'r': h = h + avail - width - elif self.just == 'c': h = h + (avail - width) / 2 - elif self.just == 'lr' and stretch > 0: - extra = avail - width - v2 = v + ascent + descent - for j in range(i, i+wordcount): - word = self.words[j] - if type(word) == Int: - ok = anchorfunc(self, tuple, word, \ - h, v) - if ok <> None: return ok - continue - fo, te, wi, sp, st, as, de = word - if extra > 0 and stretch > 0: - ex = extra * st / stretch - extra = extra - ex - stretch = stretch - st - else: - ex = 0 - h2 = h + wi + sp + ex - ok = wordfunc(self, tuple, word, h, v, \ - h2, v2, (j==i), (j==i+wordcount-1)) - if ok <> None: return ok - h = h2 - v = v2 - i = i + wordcount - avail = avail1 - # - # Render a paragraph in "drawing object" d, using the rectangle - # given by (left, top, right) with an unspecified bottom. - # Return the computed bottom of the text. - def render(self, d, left, top, right): - if self.width <> right-left: - self.layout(right-left) - self.left = left - self.top = top - self.right = right - self.bottom = self.top + self.height - self.anchorid = 0 - try: - self.d = d - self.visit(self.__class__._renderword, \ - self.__class__._renderanchor) - finally: - self.d = None - return self.bottom - # - def _renderword(self, tuple, word, h, v, h2, v2, isfirst, islast): - if word[0] <> None: self.d.setfont(word[0]) - baseline = v + tuple[5] - self.d.text((h, baseline - word[5]), word[1]) - if self.anchorid > 0: - self.d.line((h, baseline+2), (h2, baseline+2)) - # - def _renderanchor(self, tuple, word, h, v): - self.anchorid = word - # - # Return which anchor(s) was hit by the mouse - def hitcheck(self, mouseh, mousev): - self.mouseh = mouseh - self.mousev = mousev - self.anchorid = 0 - self.hits = [] - self.visit(self.__class__._hitcheckword, \ - self.__class__._hitcheckanchor) - return self.hits - # - def _hitcheckword(self, tuple, word, h, v, h2, v2, isfirst, islast): - if self.anchorid > 0 and h <= self.mouseh <= h2 and \ - v <= self.mousev <= v2: - self.hits.append(self.anchorid) - # - def _hitcheckanchor(self, tuple, word, h, v): - self.anchorid = word - # - # Return whether the given anchor id is present - def hasanchor(self, id): - return id in self.words or -id in self.words - # - # Extract the raw text from the word list, substituting one space - # for non-empty inter-word space, and terminating with '\n' - def extract(self): - text = '' - for w in self.words: - if type(w) <> Int: - word = w[1] - if w[3]: word = word + ' ' - text = text + word - return text + '\n' - # - # Return which character position was hit by the mouse, as - # an offset in the entire text as returned by extract(). - # Return None if the mouse was not in this paragraph - def whereis(self, d, mouseh, mousev): - if mousev < self.top or mousev > self.bottom: - return None - self.mouseh = mouseh - self.mousev = mousev - self.lastfont = None - self.charcount = 0 - try: - self.d = d - return self.visit(self.__class__._whereisword, \ - self.__class__._whereisanchor) - finally: - self.d = None - # - def _whereisword(self, tuple, word, h1, v1, h2, v2, isfirst, islast): - fo, te, wi, sp, st, as, de = word - if fo <> None: self.lastfont = fo - h = h1 - if isfirst: h1 = 0 - if islast: h2 = 999999 - if not (v1 <= self.mousev <= v2 and h1 <= self.mouseh <= h2): - self.charcount = self.charcount + len(te) + (sp > 0) - return - if self.lastfont <> None: - self.d.setfont(self.lastfont) - cc = 0 - for c in te: - cw = self.d.textwidth(c) - if self.mouseh <= h + cw/2: - return self.charcount + cc - cc = cc+1 - h = h+cw - self.charcount = self.charcount + cc - if self.mouseh <= (h+h2) / 2: - return self.charcount - else: - return self.charcount + 1 - # - def _whereisanchor(self, tuple, word, h, v): - pass - # - # Return screen position corresponding to position in paragraph. - # Return tuple (h, vtop, vbaseline, vbottom). - # This is more or less the inverse of whereis() - def screenpos(self, d, pos): - if pos < 0: - ascent, descent = self.lines[0][5:7] - return self.left, self.top, self.top + ascent, \ - self.top + ascent + descent - self.pos = pos - self.lastfont = None - try: - self.d = d - ok = self.visit(self.__class__._screenposword, \ - self.__class__._screenposanchor) - finally: - self.d = None - if ok == None: - ascent, descent = self.lines[-1][5:7] - ok = self.right, self.bottom - ascent - descent, \ - self.bottom - descent, self.bottom - return ok - # - def _screenposword(self, tuple, word, h1, v1, h2, v2, isfirst, islast): - fo, te, wi, sp, st, as, de = word - if fo <> None: self.lastfont = fo - cc = len(te) + (sp > 0) - if self.pos > cc: - self.pos = self.pos - cc - return - if self.pos < cc: - self.d.setfont(self.lastfont) - h = h1 + self.d.textwidth(te[:self.pos]) - else: - h = h2 - ascent, descent = tuple[5:7] - return h, v1, v1+ascent, v2 - # - def _screenposanchor(self, tuple, word, h, v): - pass - # - # Invert the stretch of text between pos1 and pos2. - # If pos1 is None, the beginning is implied; - # if pos2 is None, the end is implied. - # Undoes its own effect when called again with the same arguments - def invert(self, d, pos1, pos2): - if pos1 == None: - pos1 = self.left, self.top, self.top, self.top - else: - pos1 = self.screenpos(d, pos1) - if pos2 == None: - pos2 = self.right, self.bottom,self.bottom,self.bottom - else: - pos2 = self.screenpos(d, pos2) - h1, top1, baseline1, bottom1 = pos1 - h2, top2, baseline2, bottom2 = pos2 - if bottom1 <= top2: - d.invert((h1, top1), (self.right, bottom1)) - h1 = self.left - if bottom1 < top2: - d.invert((h1, bottom1), (self.right, top2)) - top1, bottom1 = top2, bottom2 - d.invert((h1, top1), (h2, bottom2)) - - -# Test class Para -# XXX This was last used on the Mac, hence the weird fonts... -def test(): - import stdwin - from stdwinevents import * - words = 'The', 'quick', 'brown', 'fox', 'jumps', 'over', \ - 'the', 'lazy', 'dog.' - paralist = [] - for just in 'l', 'r', 'lr', 'c': - p = Para() - p.just = just - p.addword(stdwin, ('New York', 'p', 12), words[0], 1, 1) - for word in words[1:-1]: - p.addword(stdwin, None, word, 1, 1) - p.addword(stdwin, None, words[-1], 2, 4) - p.addword(stdwin, ('New York', 'b', 18), 'Bye!', 0, 0) - p.addword(stdwin, ('New York', 'p', 10), 'Bye!', 0, 0) - paralist.append(p) - window = stdwin.open('Para.test()') - start = stop = selpara = None - while 1: - etype, win, detail = stdwin.getevent() - if etype == WE_CLOSE: - break - if etype == WE_SIZE: - window.change((0, 0), (1000, 1000)) - if etype == WE_DRAW: - width, height = window.getwinsize() - d = None - try: - d = window.begindrawing() - d.cliprect(detail) - d.erase(detail) - v = 0 - for p in paralist: - v = p.render(d, 0, v, width) - if p == selpara and \ - start <> None and stop <> None: - p.invert(d, start, stop) - finally: - if d: d.close() - if etype == WE_MOUSE_DOWN: - if selpara and start <> None and stop <> None: - d = window.begindrawing() - selpara.invert(d, start, stop) - d.close() - start = stop = selpara = None - mouseh, mousev = detail[0] - for p in paralist: - start = p.whereis(stdwin, mouseh, mousev) - if start <> None: - selpara = p - break - if etype == WE_MOUSE_UP and start <> None and selpara: - mouseh, mousev = detail[0] - stop = selpara.whereis(stdwin, mouseh, mousev) - if stop == None: start = selpara = None - else: - if start > stop: - start, stop = stop, start - d = window.begindrawing() - selpara.invert(d, start, stop) - d.close() - window.close() diff --git a/Demo/tkinter/www/fmt.py b/Demo/tkinter/www/fmt.py deleted file mode 100755 index b5ca33c77f..0000000000 --- a/Demo/tkinter/www/fmt.py +++ /dev/null @@ -1,627 +0,0 @@ -# Text formatting abstractions - - -import string -import Para - - -# A formatter back-end object has one method that is called by the formatter: -# addpara(p), where p is a paragraph object. For example: - - -# Formatter back-end to do nothing at all with the paragraphs -class NullBackEnd: - # - def __init__(self): - pass - # - def addpara(self, p): - pass - # - def bgn_anchor(self, id): - pass - # - def end_anchor(self, id): - pass - - -# Formatter back-end to collect the paragraphs in a list -class SavingBackEnd(NullBackEnd): - # - def __init__(self): - self.paralist = [] - # - def addpara(self, p): - self.paralist.append(p) - # - def hitcheck(self, h, v): - hits = [] - for p in self.paralist: - if p.top <= v <= p.bottom: - for id in p.hitcheck(h, v): - if id not in hits: - hits.append(id) - return hits - # - def extract(self): - text = '' - for p in self.paralist: - text = text + (p.extract()) - return text - # - def extractpart(self, long1, long2): - if long1 > long2: long1, long2 = long2, long1 - para1, pos1 = long1 - para2, pos2 = long2 - text = '' - while para1 < para2: - ptext = self.paralist[para1].extract() - text = text + ptext[pos1:] - pos1 = 0 - para1 = para1 + 1 - ptext = self.paralist[para2].extract() - return text + ptext[pos1:pos2] - # - def whereis(self, d, h, v): - total = 0 - for i in range(len(self.paralist)): - p = self.paralist[i] - result = p.whereis(d, h, v) - if result <> None: - return i, result - return None - # - def roundtowords(self, long1, long2): - i, offset = long1 - text = self.paralist[i].extract() - while offset > 0 and text[offset-1] <> ' ': offset = offset-1 - long1 = i, offset - # - i, offset = long2 - text = self.paralist[i].extract() - n = len(text) - while offset < n-1 and text[offset] <> ' ': offset = offset+1 - long2 = i, offset - # - return long1, long2 - # - def roundtoparagraphs(self, long1, long2): - long1 = long1[0], 0 - long2 = long2[0], len(self.paralist[long2[0]].extract()) - return long1, long2 - - -# Formatter back-end to send the text directly to the drawing object -class WritingBackEnd(NullBackEnd): - # - def __init__(self, d, width): - self.d = d - self.width = width - self.lineno = 0 - # - def addpara(self, p): - self.lineno = p.render(self.d, 0, self.lineno, self.width) - - -# A formatter receives a stream of formatting instructions and assembles -# these into a stream of paragraphs on to a back-end. The assembly is -# parametrized by a text measurement object, which must match the output -# operations of the back-end. The back-end is responsible for splitting -# paragraphs up in lines of a given maximum width. (This is done because -# in a windowing environment, when the window size changes, there is no -# need to redo the assembly into paragraphs, but the splitting into lines -# must be done taking the new window size into account.) - - -# Formatter base class. Initialize it with a text measurement object, -# which is used for text measurements, and a back-end object, -# which receives the completed paragraphs. The formatting methods are: -# setfont(font) -# setleftindent(nspaces) -# setjust(type) where type is 'l', 'c', 'r', or 'lr' -# flush() -# vspace(nlines) -# needvspace(nlines) -# addword(word, nspaces) -class BaseFormatter: - # - def __init__(self, d, b): - # Drawing object used for text measurements - self.d = d - # - # BackEnd object receiving completed paragraphs - self.b = b - # - # Parameters of the formatting model - self.leftindent = 0 - self.just = 'l' - self.font = None - self.blanklines = 0 - # - # Parameters derived from the current font - self.space = d.textwidth(' ') - self.line = d.lineheight() - self.ascent = d.baseline() - self.descent = self.line - self.ascent - # - # Parameter derived from the default font - self.n_space = self.space - # - # Current paragraph being built - self.para = None - self.nospace = 1 - # - # Font to set on the next word - self.nextfont = None - # - def newpara(self): - return Para.Para() - # - def setfont(self, font): - if font == None: return - self.font = self.nextfont = font - d = self.d - d.setfont(font) - self.space = d.textwidth(' ') - self.line = d.lineheight() - self.ascent = d.baseline() - self.descent = self.line - self.ascent - # - def setleftindent(self, nspaces): - self.leftindent = int(self.n_space * nspaces) - if self.para: - hang = self.leftindent - self.para.indent_left - if hang > 0 and self.para.getlength() <= hang: - self.para.makehangingtag(hang) - self.nospace = 1 - else: - self.flush() - # - def setrightindent(self, nspaces): - self.rightindent = int(self.n_space * nspaces) - if self.para: - self.para.indent_right = self.rightindent - self.flush() - # - def setjust(self, just): - self.just = just - if self.para: - self.para.just = self.just - # - def flush(self): - if self.para: - self.b.addpara(self.para) - self.para = None - if self.font <> None: - self.d.setfont(self.font) - self.nospace = 1 - # - def vspace(self, nlines): - self.flush() - if nlines > 0: - self.para = self.newpara() - tuple = None, '', 0, 0, 0, int(nlines*self.line), 0 - self.para.words.append(tuple) - self.flush() - self.blanklines = self.blanklines + nlines - # - def needvspace(self, nlines): - self.flush() # Just to be sure - if nlines > self.blanklines: - self.vspace(nlines - self.blanklines) - # - def addword(self, text, space): - if self.nospace and not text: - return - self.nospace = 0 - self.blanklines = 0 - if not self.para: - self.para = self.newpara() - self.para.indent_left = self.leftindent - self.para.just = self.just - self.nextfont = self.font - space = int(space * self.space) - self.para.words.append(self.nextfont, text, \ - self.d.textwidth(text), space, space, \ - self.ascent, self.descent) - self.nextfont = None - # - def bgn_anchor(self, id): - if not self.para: - self.nospace = 0 - self.addword('', 0) - self.para.bgn_anchor(id) - # - def end_anchor(self, id): - if not self.para: - self.nospace = 0 - self.addword('', 0) - self.para.end_anchor(id) - # - def hrule(self): - # Typically need to override this for bit-mapped displays - self.flush() - self.addword('-'*60, 0) - self.flush() - - -# Measuring object for measuring text as viewed on a tty -class NullMeasurer: - # - def __init__(self): - pass - # - def setfont(self, font): - pass - # - def textwidth(self, text): - return len(text) - # - def lineheight(self): - return 1 - # - def baseline(self): - return 0 - - -# Drawing object for writing plain ASCII text to a file -class FileWriter: - # - def __init__(self, fp): - self.fp = fp - self.lineno, self.colno = 0, 0 - # - def setfont(self, font): - pass - # - def text(self, (h, v), str): - if not str: return - if '\n' in str: - raise ValueError, 'can\'t write \\n' - while self.lineno < v: - self.fp.write('\n') - self.colno, self.lineno = 0, self.lineno + 1 - while self.lineno > v: - # XXX This should never happen... - self.fp.write('\033[A') # ANSI up arrow - self.lineno = self.lineno - 1 - if self.colno < h: - self.fp.write(' ' * (h - self.colno)) - elif self.colno > h: - self.fp.write('\b' * (self.colno - h)) - self.colno = h - self.fp.write(str) - self.colno = h + len(str) - - -# Formatting class to do nothing at all with the data -class NullFormatter(BaseFormatter): - # - def __init__(self): - d = NullMeasurer() - b = NullBackEnd() - BaseFormatter.__init__(self, d, b) - - -# Formatting class to write directly to a file -class WritingFormatter(BaseFormatter): - # - def __init__(self, fp, width): - dm = NullMeasurer() - dw = FileWriter(fp) - b = WritingBackEnd(dw, width) - BaseFormatter.__init__(self, dm, b) - self.blanklines = 1 - # - # Suppress multiple blank lines - def needvspace(self, nlines): - BaseFormatter.needvspace(self, min(1, nlines)) - - -# A "FunnyFormatter" writes ASCII text with a twist: *bold words*, -# _italic text_ and _underlined words_, and `quoted text'. -# It assumes that the fonts are 'r', 'i', 'b', 'u', 'q': (roman, -# italic, bold, underline, quote). -# Moreover, if the font is in upper case, the text is converted to -# UPPER CASE. -class FunnyFormatter(WritingFormatter): - # - def flush(self): - if self.para: finalize(self.para) - WritingFormatter.flush(self) - - -# Surrounds *bold words* and _italic text_ in a paragraph with -# appropriate markers, fixing the size (assuming these characters' -# width is 1). -openchar = \ - {'b':'*', 'i':'_', 'u':'_', 'q':'`', 'B':'*', 'I':'_', 'U':'_', 'Q':'`'} -closechar = \ - {'b':'*', 'i':'_', 'u':'_', 'q':'\'', 'B':'*', 'I':'_', 'U':'_', 'Q':'\''} -def finalize(para): - oldfont = curfont = 'r' - para.words.append('r', '', 0, 0, 0, 0) # temporary, deleted at end - for i in range(len(para.words)): - fo, te, wi = para.words[i][:3] - if fo <> None: curfont = fo - if curfont <> oldfont: - if closechar.has_key(oldfont): - c = closechar[oldfont] - j = i-1 - while j > 0 and para.words[j][1] == '': j = j-1 - fo1, te1, wi1 = para.words[j][:3] - te1 = te1 + c - wi1 = wi1 + len(c) - para.words[j] = (fo1, te1, wi1) + \ - para.words[j][3:] - if openchar.has_key(curfont) and te: - c = openchar[curfont] - te = c + te - wi = len(c) + wi - para.words[i] = (fo, te, wi) + \ - para.words[i][3:] - if te: oldfont = curfont - else: oldfont = 'r' - if curfont in string.uppercase: - te = string.upper(te) - para.words[i] = (fo, te, wi) + para.words[i][3:] - del para.words[-1] - - -# Formatter back-end to draw the text in a window. -# This has an option to draw while the paragraphs are being added, -# to minimize the delay before the user sees anything. -# This manages the entire "document" of the window. -class StdwinBackEnd(SavingBackEnd): - # - def __init__(self, window, drawnow): - self.window = window - self.drawnow = drawnow - self.width = window.getwinsize()[0] - self.selection = None - self.height = 0 - window.setorigin(0, 0) - window.setdocsize(0, 0) - self.d = window.begindrawing() - SavingBackEnd.__init__(self) - # - def finish(self): - self.d.close() - self.d = None - self.window.setdocsize(0, self.height) - # - def addpara(self, p): - self.paralist.append(p) - if self.drawnow: - self.height = \ - p.render(self.d, 0, self.height, self.width) - else: - p.layout(self.width) - p.left = 0 - p.top = self.height - p.right = self.width - p.bottom = self.height + p.height - self.height = p.bottom - # - def resize(self): - self.window.change((0, 0), (self.width, self.height)) - self.width = self.window.getwinsize()[0] - self.height = 0 - for p in self.paralist: - p.layout(self.width) - p.left = 0 - p.top = self.height - p.right = self.width - p.bottom = self.height + p.height - self.height = p.bottom - self.window.change((0, 0), (self.width, self.height)) - self.window.setdocsize(0, self.height) - # - def redraw(self, area): - d = self.window.begindrawing() - (left, top), (right, bottom) = area - d.erase(area) - d.cliprect(area) - for p in self.paralist: - if top < p.bottom and p.top < bottom: - v = p.render(d, p.left, p.top, p.right) - if self.selection: - self.invert(d, self.selection) - d.close() - # - def setselection(self, new): - if new: - long1, long2 = new - pos1 = long1[:3] - pos2 = long2[:3] - new = pos1, pos2 - if new <> self.selection: - d = self.window.begindrawing() - if self.selection: - self.invert(d, self.selection) - if new: - self.invert(d, new) - d.close() - self.selection = new - # - def getselection(self): - return self.selection - # - def extractselection(self): - if self.selection: - a, b = self.selection - return self.extractpart(a, b) - else: - return None - # - def invert(self, d, region): - long1, long2 = region - if long1 > long2: long1, long2 = long2, long1 - para1, pos1 = long1 - para2, pos2 = long2 - while para1 < para2: - self.paralist[para1].invert(d, pos1, None) - pos1 = None - para1 = para1 + 1 - self.paralist[para2].invert(d, pos1, pos2) - # - def search(self, prog): - import regex, string - if type(prog) == type(''): - prog = regex.compile(string.lower(prog)) - if self.selection: - iold = self.selection[0][0] - else: - iold = -1 - hit = None - for i in range(len(self.paralist)): - if i == iold or i < iold and hit: - continue - p = self.paralist[i] - text = string.lower(p.extract()) - if prog.search(text) >= 0: - a, b = prog.regs[0] - long1 = i, a - long2 = i, b - hit = long1, long2 - if i > iold: - break - if hit: - self.setselection(hit) - i = hit[0][0] - p = self.paralist[i] - self.window.show((p.left, p.top), (p.right, p.bottom)) - return 1 - else: - return 0 - # - def showanchor(self, id): - for i in range(len(self.paralist)): - p = self.paralist[i] - if p.hasanchor(id): - long1 = i, 0 - long2 = i, len(p.extract()) - hit = long1, long2 - self.setselection(hit) - self.window.show( \ - (p.left, p.top), (p.right, p.bottom)) - break - - -# GL extensions - -class GLFontCache: - # - def __init__(self): - self.reset() - self.setfont('') - # - def reset(self): - self.fontkey = None - self.fonthandle = None - self.fontinfo = None - self.fontcache = {} - # - def close(self): - self.reset() - # - def setfont(self, fontkey): - if fontkey == '': - fontkey = 'Times-Roman 12' - elif ' ' not in fontkey: - fontkey = fontkey + ' 12' - if fontkey == self.fontkey: - return - if self.fontcache.has_key(fontkey): - handle = self.fontcache[fontkey] - else: - import string - i = string.index(fontkey, ' ') - name, sizestr = fontkey[:i], fontkey[i:] - size = eval(sizestr) - key1 = name + ' 1' - key = name + ' ' + `size` - # NB key may differ from fontkey! - if self.fontcache.has_key(key): - handle = self.fontcache[key] - else: - if self.fontcache.has_key(key1): - handle = self.fontcache[key1] - else: - import fm - handle = fm.findfont(name) - self.fontcache[key1] = handle - handle = handle.scalefont(size) - self.fontcache[fontkey] = \ - self.fontcache[key] = handle - self.fontkey = fontkey - if self.fonthandle <> handle: - self.fonthandle = handle - self.fontinfo = handle.getfontinfo() - handle.setfont() - - -class GLMeasurer(GLFontCache): - # - def textwidth(self, text): - return self.fonthandle.getstrwidth(text) - # - def baseline(self): - return self.fontinfo[6] - self.fontinfo[3] - # - def lineheight(self): - return self.fontinfo[6] - - -class GLWriter(GLFontCache): - # - # NOTES: - # (1) Use gl.ortho2 to use X pixel coordinates! - # - def text(self, (h, v), text): - import gl, fm - gl.cmov2i(h, v + self.fontinfo[6] - self.fontinfo[3]) - fm.prstr(text) - # - def setfont(self, fontkey): - oldhandle = self.fonthandle - GLFontCache.setfont(fontkey) - if self.fonthandle <> oldhandle: - handle.setfont() - - -class GLMeasurerWriter(GLMeasurer, GLWriter): - pass - - -class GLBackEnd(SavingBackEnd): - # - def __init__(self, wid): - import gl - gl.winset(wid) - self.wid = wid - self.width = gl.getsize()[1] - self.height = 0 - self.d = GLMeasurerWriter() - SavingBackEnd.__init__(self) - # - def finish(self): - pass - # - def addpara(self, p): - self.paralist.append(p) - self.height = p.render(self.d, 0, self.height, self.width) - # - def redraw(self): - import gl - gl.winset(self.wid) - width = gl.getsize()[1] - if width <> self.width: - setdocsize = 1 - self.width = width - for p in self.paralist: - p.top = p.bottom = None - d = self.d - v = 0 - for p in self.paralist: - v = p.render(d, 0, v, width) diff --git a/Demo/tkinter/www/htmllib.py b/Demo/tkinter/www/htmllib.py deleted file mode 100755 index f45657f645..0000000000 --- a/Demo/tkinter/www/htmllib.py +++ /dev/null @@ -1,639 +0,0 @@ -# A parser for HTML documents - - -# HTML: HyperText Markup Language; an SGML-like syntax used by WWW to -# describe hypertext documents -# -# SGML: Standard Generalized Markup Language -# -# WWW: World-Wide Web; a distributed hypertext system develped at CERN -# -# CERN: European Particle Physics Laboratory in Geneva, Switzerland - - -# This file is only concerned with parsing and formatting HTML -# documents, not with the other (hypertext and networking) aspects of -# the WWW project. (It does support highlighting of anchors.) - - -import os -import sys -import regex -import string -import sgmllib - - -class HTMLParser(sgmllib.SGMLParser): - - # Copy base class entities and add some - entitydefs = {} - for key in sgmllib.SGMLParser.entitydefs.keys(): - entitydefs[key] = sgmllib.SGMLParser.entitydefs[key] - entitydefs['bullet'] = '*' - - # Provided -- handlers for tags introducing literal text - - def start_listing(self, attrs): - self.setliteral('listing') - self.literal_bgn('listing', attrs) - - def end_listing(self): - self.literal_end('listing') - - def start_xmp(self, attrs): - self.setliteral('xmp') - self.literal_bgn('xmp', attrs) - - def end_xmp(self): - self.literal_end('xmp') - - def do_plaintext(self, attrs): - self.setnomoretags() - self.literal_bgn('plaintext', attrs) - - # To be overridden -- begin/end literal mode - def literal_bgn(self, tag, attrs): pass - def literal_end(self, tag): pass - - -# Next level of sophistication -- collect anchors, title, nextid and isindex -class CollectingParser(HTMLParser): - # - def __init__(self): - HTMLParser.__init__(self) - self.savetext = None - self.nextid = '' - self.isindex = 0 - self.title = '' - self.inanchor = 0 - self.anchors = [] - self.anchornames = [] - self.anchortypes = [] - # - def start_a(self, attrs): - self.inanchor = 0 - href = '' - name = '' - type = '' - for attrname, value in attrs: - if attrname == 'href': - href = value - if attrname == 'name=': - name = value - if attrname == 'type=': - type = string.lower(value) - if not (href or name): - return - self.anchors.append(href) - self.anchornames.append(name) - self.anchortypes.append(type) - self.inanchor = len(self.anchors) - if not href: - self.inanchor = -self.inanchor - # - def end_a(self): - if self.inanchor > 0: - # Don't show anchors pointing into the current document - if self.anchors[self.inanchor-1][:1] <> '#': - self.handle_data('[' + `self.inanchor` + ']') - self.inanchor = 0 - # - def start_header(self, attrs): pass - def end_header(self): pass - # - # (head is the same as header) - def start_head(self, attrs): pass - def end_head(self): pass - # - def start_body(self, attrs): pass - def end_body(self): pass - # - def do_nextid(self, attrs): - self.nextid = attrs - # - def do_isindex(self, attrs): - self.isindex = 1 - # - def start_title(self, attrs): - self.savetext = '' - # - def end_title(self): - if self.savetext <> None: - self.title = self.savetext - self.savetext = None - # - def handle_data(self, text): - if self.savetext is not None: - self.savetext = self.savetext + text - - -# Formatting parser -- takes a formatter and a style sheet as arguments - -# XXX The use of style sheets should change: for each tag and end tag -# there should be a style definition, and a style definition should -# encompass many more parameters: font, justification, indentation, -# vspace before, vspace after, hanging tag... - -wordprog = regex.compile('[^ \t\n]*') -spaceprog = regex.compile('[ \t\n]*') - -class FormattingParser(CollectingParser): - - def __init__(self, formatter, stylesheet): - CollectingParser.__init__(self) - self.fmt = formatter - self.stl = stylesheet - self.savetext = None - self.compact = 0 - self.nofill = 0 - self.resetfont() - self.setindent(self.stl.stdindent) - - def resetfont(self): - self.fontstack = [] - self.stylestack = [] - self.fontset = self.stl.stdfontset - self.style = ROMAN - self.passfont() - - def passfont(self): - font = self.fontset[self.style] - self.fmt.setfont(font) - - def pushstyle(self, style): - self.stylestack.append(self.style) - self.style = min(style, len(self.fontset)-1) - self.passfont() - - def popstyle(self): - self.style = self.stylestack[-1] - del self.stylestack[-1] - self.passfont() - - def pushfontset(self, fontset, style): - self.fontstack.append(self.fontset) - self.fontset = fontset - self.pushstyle(style) - - def popfontset(self): - self.fontset = self.fontstack[-1] - del self.fontstack[-1] - self.popstyle() - - def flush(self): - self.fmt.flush() - - def setindent(self, n): - self.fmt.setleftindent(n) - - def needvspace(self, n): - self.fmt.needvspace(n) - - def close(self): - HTMLParser.close(self) - self.fmt.flush() - - def handle_literal(self, text): - lines = string.splitfields(text, '\n') - for i in range(1, len(lines)): - lines[i] = string.expandtabs(lines[i], 8) - for line in lines[:-1]: - self.fmt.addword(line, 0) - self.fmt.flush() - self.fmt.nospace = 0 - for line in lines[-1:]: - self.fmt.addword(line, 0) - - def handle_data(self, text): - if self.savetext is not None: - self.savetext = self.savetext + text - return - if self.literal: - self.handle_literal(text) - return - i = 0 - n = len(text) - while i < n: - j = i + wordprog.match(text, i) - word = text[i:j] - i = j + spaceprog.match(text, j) - self.fmt.addword(word, i-j) - if self.nofill and '\n' in text[j:i]: - self.fmt.flush() - self.fmt.nospace = 0 - i = j+1 - while text[i-1] <> '\n': i = i+1 - - def literal_bgn(self, tag, attrs): - if tag == 'plaintext': - self.flush() - else: - self.needvspace(1) - self.pushfontset(self.stl.stdfontset, FIXED) - self.setindent(self.stl.literalindent) - - def literal_end(self, tag): - self.needvspace(1) - self.popfontset() - self.setindent(self.stl.stdindent) - - def start_title(self, attrs): - self.flush() - self.savetext = '' - # NB end_title is unchanged - - def do_p(self, attrs): - if self.compact: - self.flush() - else: - self.needvspace(1) - - def do_hr(self, attrs): - self.fmt.hrule() - - def start_h1(self, attrs): - self.needvspace(2) - self.setindent(self.stl.h1indent) - self.pushfontset(self.stl.h1fontset, BOLD) - self.fmt.setjust('c') - - def end_h1(self): - self.popfontset() - self.needvspace(2) - self.setindent(self.stl.stdindent) - self.fmt.setjust('l') - - def start_h2(self, attrs): - self.needvspace(1) - self.setindent(self.stl.h2indent) - self.pushfontset(self.stl.h2fontset, BOLD) - - def end_h2(self): - self.popfontset() - self.needvspace(1) - self.setindent(self.stl.stdindent) - - def start_h3(self, attrs): - self.needvspace(1) - self.setindent(self.stl.stdindent) - self.pushfontset(self.stl.h3fontset, BOLD) - - def end_h3(self): - self.popfontset() - self.needvspace(1) - self.setindent(self.stl.stdindent) - - def start_h4(self, attrs): - self.needvspace(1) - self.setindent(self.stl.stdindent) - self.pushfontset(self.stl.stdfontset, BOLD) - - def end_h4(self): - self.popfontset() - self.needvspace(1) - self.setindent(self.stl.stdindent) - - start_h5 = start_h4 - end_h5 = end_h4 - - start_h6 = start_h5 - end_h6 = end_h5 - - start_h7 = start_h6 - end_h7 = end_h6 - - def start_ul(self, attrs): - self.needvspace(1) - for attrname, value in attrs: - if attrname == 'compact': - self.compact = 1 - self.setindent(0) - break - else: - self.setindent(self.stl.ulindent) - - start_dir = start_menu = start_ol = start_ul - - do_li = do_p - - def end_ul(self): - self.compact = 0 - self.needvspace(1) - self.setindent(self.stl.stdindent) - - end_dir = end_menu = end_ol = end_ul - - def start_dl(self, attrs): - for attrname, value in attrs: - if attrname == 'compact': - self.compact = 1 - self.needvspace(1) - - def end_dl(self): - self.compact = 0 - self.needvspace(1) - self.setindent(self.stl.stdindent) - - def do_dt(self, attrs): - if self.compact: - self.flush() - else: - self.needvspace(1) - self.setindent(self.stl.stdindent) - - def do_dd(self, attrs): - self.fmt.addword('', 1) - self.setindent(self.stl.ddindent) - - def start_address(self, attrs): - self.compact = 1 - self.needvspace(1) - self.fmt.setjust('r') - - def end_address(self): - self.compact = 0 - self.needvspace(1) - self.setindent(self.stl.stdindent) - self.fmt.setjust('l') - - def start_pre(self, attrs): - self.needvspace(1) - self.nofill = self.nofill + 1 - self.pushstyle(FIXED) - - def end_pre(self): - self.popstyle() - self.nofill = self.nofill - 1 - self.needvspace(1) - - start_typewriter = start_pre - end_typewriter = end_pre - - def do_img(self, attrs): - self.fmt.addword('(image)', 0) - - # Physical styles - - def start_tt(self, attrs): self.pushstyle(FIXED) - def end_tt(self): self.popstyle() - - def start_b(self, attrs): self.pushstyle(BOLD) - def end_b(self): self.popstyle() - - def start_i(self, attrs): self.pushstyle(ITALIC) - def end_i(self): self.popstyle() - - def start_u(self, attrs): self.pushstyle(ITALIC) # Underline??? - def end_u(self): self.popstyle() - - def start_r(self, attrs): self.pushstyle(ROMAN) # Not official - def end_r(self): self.popstyle() - - # Logical styles - - start_em = start_i - end_em = end_i - - start_strong = start_b - end_strong = end_b - - start_code = start_tt - end_code = end_tt - - start_samp = start_tt - end_samp = end_tt - - start_kbd = start_tt - end_kbd = end_tt - - start_file = start_tt # unofficial - end_file = end_tt - - start_var = start_i - end_var = end_i - - start_dfn = start_i - end_dfn = end_i - - start_cite = start_i - end_cite = end_i - - start_hp1 = start_i - end_hp1 = start_i - - start_hp2 = start_b - end_hp2 = end_b - - def unknown_starttag(self, tag, attrs): - print '*** unknown <' + tag + '>' - - def unknown_endtag(self, tag): - print '*** unknown ' - - -# An extension of the formatting parser which formats anchors differently. -class AnchoringParser(FormattingParser): - - def start_a(self, attrs): - FormattingParser.start_a(self, attrs) - if self.inanchor: - self.fmt.bgn_anchor(self.inanchor) - - def end_a(self): - if self.inanchor: - self.fmt.end_anchor(self.inanchor) - self.inanchor = 0 - - -# Style sheet -- this is never instantiated, but the attributes -# of the class object itself are used to specify fonts to be used -# for various paragraph styles. -# A font set is a non-empty list of fonts, in the order: -# [roman, italic, bold, fixed]. -# When a style is not available the nearest lower style is used - -ROMAN = 0 -ITALIC = 1 -BOLD = 2 -FIXED = 3 - -class NullStylesheet: - # Fonts -- none - stdfontset = [None] - h1fontset = [None] - h2fontset = [None] - h3fontset = [None] - # Indents - stdindent = 2 - ddindent = 25 - ulindent = 4 - h1indent = 0 - h2indent = 0 - literalindent = 0 - - -class X11Stylesheet(NullStylesheet): - stdfontset = [ \ - '-*-helvetica-medium-r-normal-*-*-100-100-*-*-*-*-*', \ - '-*-helvetica-medium-o-normal-*-*-100-100-*-*-*-*-*', \ - '-*-helvetica-bold-r-normal-*-*-100-100-*-*-*-*-*', \ - '-*-courier-medium-r-normal-*-*-100-100-*-*-*-*-*', \ - ] - h1fontset = [ \ - '-*-helvetica-medium-r-normal-*-*-180-100-*-*-*-*-*', \ - '-*-helvetica-medium-o-normal-*-*-180-100-*-*-*-*-*', \ - '-*-helvetica-bold-r-normal-*-*-180-100-*-*-*-*-*', \ - ] - h2fontset = [ \ - '-*-helvetica-medium-r-normal-*-*-140-100-*-*-*-*-*', \ - '-*-helvetica-medium-o-normal-*-*-140-100-*-*-*-*-*', \ - '-*-helvetica-bold-r-normal-*-*-140-100-*-*-*-*-*', \ - ] - h3fontset = [ \ - '-*-helvetica-medium-r-normal-*-*-120-100-*-*-*-*-*', \ - '-*-helvetica-medium-o-normal-*-*-120-100-*-*-*-*-*', \ - '-*-helvetica-bold-r-normal-*-*-120-100-*-*-*-*-*', \ - ] - ddindent = 40 - - -class MacStylesheet(NullStylesheet): - stdfontset = [ \ - ('Geneva', 'p', 10), \ - ('Geneva', 'i', 10), \ - ('Geneva', 'b', 10), \ - ('Monaco', 'p', 10), \ - ] - h1fontset = [ \ - ('Geneva', 'p', 18), \ - ('Geneva', 'i', 18), \ - ('Geneva', 'b', 18), \ - ('Monaco', 'p', 18), \ - ] - h3fontset = [ \ - ('Geneva', 'p', 14), \ - ('Geneva', 'i', 14), \ - ('Geneva', 'b', 14), \ - ('Monaco', 'p', 14), \ - ] - h3fontset = [ \ - ('Geneva', 'p', 12), \ - ('Geneva', 'i', 12), \ - ('Geneva', 'b', 12), \ - ('Monaco', 'p', 12), \ - ] - - -if os.name == 'mac': - StdwinStylesheet = MacStylesheet -else: - StdwinStylesheet = X11Stylesheet - - -class GLStylesheet(NullStylesheet): - stdfontset = [ \ - 'Helvetica 10', \ - 'Helvetica-Italic 10', \ - 'Helvetica-Bold 10', \ - 'Courier 10', \ - ] - h1fontset = [ \ - 'Helvetica 18', \ - 'Helvetica-Italic 18', \ - 'Helvetica-Bold 18', \ - 'Courier 18', \ - ] - h2fontset = [ \ - 'Helvetica 14', \ - 'Helvetica-Italic 14', \ - 'Helvetica-Bold 14', \ - 'Courier 14', \ - ] - h3fontset = [ \ - 'Helvetica 12', \ - 'Helvetica-Italic 12', \ - 'Helvetica-Bold 12', \ - 'Courier 12', \ - ] - - -# Test program -- produces no output but times how long it takes -# to send a document to a null formatter, exclusive of I/O - -def test(): - import fmt - import time - import urllib - if sys.argv[1:]: file = sys.argv[1] - else: file = 'test.html' - data = urllib.urlopen(file).read() - t0 = time.time() - fmtr = fmt.WritingFormatter(sys.stdout, 79) - p = FormattingParser(fmtr, NullStylesheet) - p.feed(data) - p.close() - t1 = time.time() - print - print '*** Formatting time:', round(t1-t0, 3), 'seconds.' - - -# Test program using stdwin - -def testStdwin(): - import stdwin, fmt - from stdwinevents import * - if sys.argv[1:]: file = sys.argv[1] - else: file = 'test.html' - data = open(file, 'r').read() - window = stdwin.open('testStdwin') - b = None - while 1: - etype, ewin, edetail = stdwin.getevent() - if etype == WE_CLOSE: - break - if etype == WE_SIZE: - window.setdocsize(0, 0) - window.setorigin(0, 0) - window.change((0, 0), (10000, 30000)) # XXX - if etype == WE_DRAW: - if not b: - b = fmt.StdwinBackEnd(window, 1) - f = fmt.BaseFormatter(b.d, b) - p = FormattingParser(f, \ - MacStylesheet) - p.feed(data) - p.close() - b.finish() - else: - b.redraw(edetail) - window.close() - - -# Test program using GL - -def testGL(): - import gl, GL, fmt - if sys.argv[1:]: file = sys.argv[1] - else: file = 'test.html' - data = open(file, 'r').read() - W, H = 600, 600 - gl.foreground() - gl.prefsize(W, H) - wid = gl.winopen('testGL') - gl.ortho2(0, W, H, 0) - gl.color(GL.WHITE) - gl.clear() - gl.color(GL.BLACK) - b = fmt.GLBackEnd(wid) - f = fmt.BaseFormatter(b.d, b) - p = FormattingParser(f, GLStylesheet) - p.feed(data) - p.close() - b.finish() - # - import time - time.sleep(5) - - -if __name__ == '__main__': - test() diff --git a/Demo/tkinter/www/sgmllib.py b/Demo/tkinter/www/sgmllib.py deleted file mode 100755 index af75e0df26..0000000000 --- a/Demo/tkinter/www/sgmllib.py +++ /dev/null @@ -1,321 +0,0 @@ -# A parser for SGML, using the derived class as static DTD. - -# XXX This only supports those SGML features used by HTML. - -# XXX There should be a way to distinguish between PCDATA (parsed -# character data -- the normal case), RCDATA (replaceable character -# data -- only char and entity references and end tags are special) -# and CDATA (character data -- only end tags are special). - - -import regex -import string - - -# Regular expressions used for parsing - -incomplete = regex.compile( \ - '') -commentopen = regex.compile(' ') ---> Monty Python's Flying Circus ->>> s -"Monty Python's Flying Circus" ->>> -\end{verbatim}\ecode -\end{funcdesc} - -\begin{funcdesc}{reduce}{function\, list\optional{\, initializer}} -Apply the binary \var{function} to the items of \var{list} so as to -reduce the list to a single value. E.g., -\code{reduce(lambda x, y: x*y, \var{list}, 1)} returns the product of -the elements of \var{list}. The optional \var{initializer} can be -thought of as being prepended to \var{list} so as to allow reduction -of an empty \var{list}. The \var{list} arguments may be any kind of -sequence. -\end{funcdesc} - -\begin{funcdesc}{reload}{module} -Re-parse and re-initialize an already imported \var{module}. The -argument must be a module object, so it must have been successfully -imported before. This is useful if you have edited the module source -file using an external editor and want to try out the new version -without leaving the Python interpreter. The return value is the -module object (i.e.\ the same as the \var{module} argument). - -There are a number of caveats: - -If a module is syntactically correct but its initialization fails, the -first \code{import} statement for it does not bind its name locally, -but does store a (partially initialized) module object in -\code{sys.modules}. To reload the module you must first -\code{import} it again (this will bind the name to the partially -initialized module object) before you can \code{reload()} it. - -When a module is reloaded, its dictionary (containing the module's -global variables) is retained. Redefinitions of names will override -the old definitions, so this is generally not a problem. If the new -version of a module does not define a name that was defined by the old -version, the old definition remains. This feature can be used to the -module's advantage if it maintains a global table or cache of objects ---- with a \code{try} statement it can test for the table's presence -and skip its initialization if desired. - -It is legal though generally not very useful to reload built-in or -dynamically loaded modules, except for \code{sys}, \code{__main__} and -\code{__builtin__}. In certain cases, however, extension modules are -not designed to be initialized more than once, and may fail in -arbitrary ways when reloaded. - -If a module imports objects from another module using \code{from} -{\ldots} \code{import} {\ldots}, calling \code{reload()} for the other -module does not redefine the objects imported from it --- one way -around this is to re-execute the \code{from} statement, another is to -use \code{import} and qualified names (\var{module}.\var{name}) -instead. - -If a module instantiates instances of a class, reloading the module -that defines the class does not affect the method definitions of the -instances --- they continue to use the old class definition. The same -is true for derived classes. -\end{funcdesc} - -\begin{funcdesc}{repr}{object} -Return a string containing a printable representation of an object. -This is the same value yielded by conversions (reverse quotes). -It is sometimes useful to be able to access this operation as an -ordinary function. For many types, this function makes an attempt -to return a string that would yield an object with the same value -when passed to \code{eval()}. -\end{funcdesc} - -\begin{funcdesc}{round}{x\, n} - Return the floating point value \var{x} rounded to \var{n} digits - after the decimal point. If \var{n} is omitted, it defaults to zero. - The result is a floating point number. Values are rounded to the - closest multiple of 10 to the power minus \var{n}; if two multiples - are equally close, rounding is done away from 0 (so e.g. - \code{round(0.5)} is \code{1.0} and \code{round(-0.5)} is \code{-1.0}). -\end{funcdesc} - -\begin{funcdesc}{setattr}{object\, name\, value} - This is the counterpart of \code{getattr}. The arguments are an - object, a string and an arbitrary value. The string must be the name - of one of the object's attributes. The function assigns the value to - the attribute, provided the object allows it. For example, - \code{setattr(\var{x}, '\var{foobar}', 123)} is equivalent to - \code{\var{x}.\var{foobar} = 123}. -\end{funcdesc} - -\begin{funcdesc}{str}{object} -Return a string containing a nicely printable representation of an -object. For strings, this returns the string itself. The difference -with \code{repr(\var{object})} is that \code{str(\var{object})} does not -always attempt to return a string that is acceptable to \code{eval()}; -its goal is to return a printable string. -\end{funcdesc} - -\begin{funcdesc}{tuple}{sequence} -Return a tuple whose items are the same and in the same order as -\var{sequence}'s items. If \var{sequence} is alread a tuple, it -is returned unchanged. For instance, \code{tuple('abc')} returns -returns \code{('a', 'b', 'c')} and \code{tuple([1, 2, 3])} returns -\code{(1, 2, 3)}. -\end{funcdesc} - -\begin{funcdesc}{type}{object} -Return the type of an \var{object}. The return value is a type -object. The standard module \code{types} defines names for all -built-in types. -\stmodindex{types} -\obindex{type} -For instance: - -\bcode\begin{verbatim} ->>> import types ->>> if type(x) == types.StringType: print "It's a string" -\end{verbatim}\ecode -\end{funcdesc} - -\begin{funcdesc}{vars}{\optional{object}} -Without arguments, return a dictionary corresponding to the current -local symbol table. With a module, class or class instance object as -argument (or anything else that has a \code{__dict__} attribute), -returns a dictionary corresponding to the object's symbol table. -The returned dictionary should not be modified: the effects on the -corresponding symbol table are undefined.% -\footnote{In the current implementation, local variable bindings -cannot normally be affected this way, but variables retrieved from -other scopes (e.g. modules) can be. This may change.} -\end{funcdesc} - -\begin{funcdesc}{xrange}{\optional{start\,} end\optional{\, step}} -This function is very similar to \code{range()}, but returns an -``xrange object'' instead of a list. This is an opaque sequence type -which yields the same values as the corresponding list, without -actually storing them all simultaneously. The advantage of -\code{xrange()} over \code{range()} is minimal (since \code{xrange()} -still has to create the values when asked for them) except when a very -large range is used on a memory-starved machine (e.g. MS-DOS) or when all -of the range's elements are never used (e.g. when the loop is usually -terminated with \code{break}). -\end{funcdesc} diff --git a/Doc/lib/libgdbm.tex b/Doc/lib/libgdbm.tex deleted file mode 100644 index 96be1653e4..0000000000 --- a/Doc/lib/libgdbm.tex +++ /dev/null @@ -1,8 +0,0 @@ -\section{Built-in Module \sectcode{gdbm}} -\bimodindex{gdbm} - -This module is nearly identical to the \code{dbm} module, but uses -GDBM instead. Its interface is identical, and not repeated here. - -Warning: the file formats created by gdbm and dbm are incompatible. -\bimodindex{dbm} diff --git a/Doc/lib/libgetopt.tex b/Doc/lib/libgetopt.tex deleted file mode 100644 index 3f9592aa32..0000000000 --- a/Doc/lib/libgetopt.tex +++ /dev/null @@ -1,56 +0,0 @@ -\section{Standard Module \sectcode{getopt}} - -\stmodindex{getopt} -This module helps scripts to parse the command line arguments in -\code{sys.argv}. -It uses the same conventions as the \UNIX{} -\code{getopt()} -function (including the special meanings of arguments of the form -\samp{-} and \samp{--}). -It defines the function -\code{getopt.getopt(args, options)} -and the exception -\code{getopt.error}. - -The first argument to -\code{getopt()} -is the argument list passed to the script with its first element -chopped off (i.e., -\code{sys.argv[1:]}). -The second argument is the string of option letters that the -script wants to recognize, with options that require an argument -followed by a colon (i.e., the same format that \UNIX{} -\code{getopt()} -uses). -The return value consists of two elements: the first is a list of -option-and-value pairs; the second is the list of program arguments -left after the option list was stripped (this is a trailing slice of the -first argument). -Each option-and-value pair returned has the option as its first element, -prefixed with a hyphen (e.g., -\code{'-x'}), -and the option argument as its second element, or an empty string if the -option has no argument. -The options occur in the list in the same order in which they were -found, thus allowing multiple occurrences. -Example: - -\bcode\begin{verbatim} ->>> import getopt, string ->>> args = string.split('-a -b -cfoo -d bar a1 a2') ->>> args -['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] ->>> optlist, args = getopt.getopt(args, 'abc:d:') ->>> optlist -[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] ->>> args -['a1', 'a2'] ->>> -\end{verbatim}\ecode - -The exception -\code{getopt.error = 'getopt error'} -is raised when an unrecognized option is found in the argument list or -when an option requiring an argument is given none. -The argument to the exception is a string indicating the cause of the -error. diff --git a/Doc/lib/libgl.tex b/Doc/lib/libgl.tex deleted file mode 100644 index c32ea6f581..0000000000 --- a/Doc/lib/libgl.tex +++ /dev/null @@ -1,198 +0,0 @@ -\section{Built-in Module \sectcode{gl}} -\bimodindex{gl} - -This module provides access to the Silicon Graphics -{\em Graphics Library}. -It is available only on Silicon Graphics machines. - -\strong{Warning:} -Some illegal calls to the GL library cause the Python interpreter to dump -core. -In particular, the use of most GL calls is unsafe before the first -window is opened. - -The module is too large to document here in its entirety, but the -following should help you to get started. -The parameter conventions for the C functions are translated to Python as -follows: - -\begin{itemize} -\item -All (short, long, unsigned) int values are represented by Python -integers. -\item -All float and double values are represented by Python floating point -numbers. -In most cases, Python integers are also allowed. -\item -All arrays are represented by one-dimensional Python lists. -In most cases, tuples are also allowed. -\item -\begin{sloppypar} -All string and character arguments are represented by Python strings, -for instance, -\code{winopen('Hi There!')} -and -\code{rotate(900, 'z')}. -\end{sloppypar} -\item -All (short, long, unsigned) integer arguments or return values that are -only used to specify the length of an array argument are omitted. -For example, the C call - -\bcode\begin{verbatim} -lmdef(deftype, index, np, props) -\end{verbatim}\ecode - -is translated to Python as - -\bcode\begin{verbatim} -lmdef(deftype, index, props) -\end{verbatim}\ecode - -\item -Output arguments are omitted from the argument list; they are -transmitted as function return values instead. -If more than one value must be returned, the return value is a tuple. -If the C function has both a regular return value (that is not omitted -because of the previous rule) and an output argument, the return value -comes first in the tuple. -Examples: the C call - -\bcode\begin{verbatim} -getmcolor(i, &red, &green, &blue) -\end{verbatim}\ecode - -is translated to Python as - -\bcode\begin{verbatim} -red, green, blue = getmcolor(i) -\end{verbatim}\ecode - -\end{itemize} - -The following functions are non-standard or have special argument -conventions: - -\renewcommand{\indexsubitem}{(in module gl)} -\begin{funcdesc}{varray}{argument} -%JHXXX the argument-argument added -Equivalent to but faster than a number of -\code{v3d()} -calls. -The \var{argument} is a list (or tuple) of points. -Each point must be a tuple of coordinates -\code{(\var{x}, \var{y}, \var{z})} or \code{(\var{x}, \var{y})}. -The points may be 2- or 3-dimensional but must all have the -same dimension. -Float and int values may be mixed however. -The points are always converted to 3D double precision points -by assuming \code{\var{z} = 0.0} if necessary (as indicated in the man page), -and for each point -\code{v3d()} -is called. -\end{funcdesc} - -\begin{funcdesc}{nvarray}{} -Equivalent to but faster than a number of -\code{n3f} -and -\code{v3f} -calls. -The argument is an array (list or tuple) of pairs of normals and points. -Each pair is a tuple of a point and a normal for that point. -Each point or normal must be a tuple of coordinates -\code{(\var{x}, \var{y}, \var{z})}. -Three coordinates must be given. -Float and int values may be mixed. -For each pair, -\code{n3f()} -is called for the normal, and then -\code{v3f()} -is called for the point. -\end{funcdesc} - -\begin{funcdesc}{vnarray}{} -Similar to -\code{nvarray()} -but the pairs have the point first and the normal second. -\end{funcdesc} - -\begin{funcdesc}{nurbssurface}{s_k\, t_k\, ctl\, s_ord\, t_ord\, type} -% XXX s_k[], t_k[], ctl[][] -%\itembreak -Defines a nurbs surface. -The dimensions of -\code{\var{ctl}[][]} -are computed as follows: -\code{[len(\var{s_k}) - \var{s_ord}]}, -\code{[len(\var{t_k}) - \var{t_ord}]}. -\end{funcdesc} - -\begin{funcdesc}{nurbscurve}{knots\, ctlpoints\, order\, type} -Defines a nurbs curve. -The length of ctlpoints is -\code{len(\var{knots}) - \var{order}}. -\end{funcdesc} - -\begin{funcdesc}{pwlcurve}{points\, type} -Defines a piecewise-linear curve. -\var{points} -is a list of points. -\var{type} -must be -\code{N_ST}. -\end{funcdesc} - -\begin{funcdesc}{pick}{n} -\funcline{select}{n} -The only argument to these functions specifies the desired size of the -pick or select buffer. -\end{funcdesc} - -\begin{funcdesc}{endpick}{} -\funcline{endselect}{} -These functions have no arguments. -They return a list of integers representing the used part of the -pick/select buffer. -No method is provided to detect buffer overrun. -\end{funcdesc} - -Here is a tiny but complete example GL program in Python: - -\bcode\begin{verbatim} -import gl, GL, time - -def main(): - gl.foreground() - gl.prefposition(500, 900, 500, 900) - w = gl.winopen('CrissCross') - gl.ortho2(0.0, 400.0, 0.0, 400.0) - gl.color(GL.WHITE) - gl.clear() - gl.color(GL.RED) - gl.bgnline() - gl.v2f(0.0, 0.0) - gl.v2f(400.0, 400.0) - gl.endline() - gl.bgnline() - gl.v2f(400.0, 0.0) - gl.v2f(0.0, 400.0) - gl.endline() - time.sleep(5) - -main() -\end{verbatim}\ecode - -\section{Standard Modules \sectcode{GL} and \sectcode{DEVICE}} -\nodename{GL and DEVICE} -\stmodindex{GL} -\stmodindex{DEVICE} - -These modules define the constants used by the Silicon Graphics -{\em Graphics Library} -that C programmers find in the header files -\file{} -and -\file{}. -Read the module source files for details. diff --git a/Doc/lib/libgopherlib.tex b/Doc/lib/libgopherlib.tex deleted file mode 100644 index e94e1f9c6c..0000000000 --- a/Doc/lib/libgopherlib.tex +++ /dev/null @@ -1,30 +0,0 @@ -\section{Standard Module \sectcode{gopherlib}} -\stmodindex{gopherlib} - -\renewcommand{\indexsubitem}{(in module gopherlib)} - -This module provides a minimal implementation of client side of the -the Gopher protocol. It is used by the module \code{urllib} to handle -URLs that use the Gopher protocol. - -The module defines the following functions: - -\begin{funcdesc}{send_selector}{selector\, host\optional{\, port}} -Send a \var{selector} string to the gopher server at \var{host} and -\var{port} (default 70). Return an open file object from which the -returned document can be read. -\end{funcdesc} - -\begin{funcdesc}{send_query}{selector\, query\, host\optional{\, port}} -Send a \var{selector} string and a \var{query} string to a gopher -server at \var{host} and \var{port} (default 70). Return an open file -object from which the returned document can be read. -\end{funcdesc} - -Note that the data returned by the Gopher server can be of any type, -depending on the first character of the selector string. If the data -is text (first character of the selector is \samp{0}), lines are -terminated by CRLF, and the data is terminated by a line consisting of -a single \samp{.}, and a leading \samp{.} should be stripped from -lines that begin with \samp{..}. Directory listings (first charactger -of the selector is \samp{1}) are transferred using the same protocol. diff --git a/Doc/lib/libgrp.tex b/Doc/lib/libgrp.tex deleted file mode 100644 index 90a2ed3339..0000000000 --- a/Doc/lib/libgrp.tex +++ /dev/null @@ -1,32 +0,0 @@ -\section{Built-in Module \sectcode{grp}} - -\bimodindex{grp} -This module provides access to the \UNIX{} group database. -It is available on all \UNIX{} versions. - -Group database entries are reported as 4-tuples containing the -following items from the group database (see \file{}), in order: -\code{gr_name}, -\code{gr_passwd}, -\code{gr_gid}, -\code{gr_mem}. -The gid is an integer, name and password are strings, and the member -list is a list of strings. -(Note that most users are not explicitly listed as members of the -group they are in according to the password database.) -An exception is raised if the entry asked for cannot be found. - -It defines the following items: - -\renewcommand{\indexsubitem}{(in module grp)} -\begin{funcdesc}{getgrgid}{gid} -Return the group database entry for the given numeric group ID. -\end{funcdesc} - -\begin{funcdesc}{getgrnam}{name} -Return the group database entry for the given group name. -\end{funcdesc} - -\begin{funcdesc}{getgrall}{} -Return a list of all available group entries, in arbitrary order. -\end{funcdesc} diff --git a/Doc/lib/libhtmllib.tex b/Doc/lib/libhtmllib.tex deleted file mode 100644 index aeb4ce9c56..0000000000 --- a/Doc/lib/libhtmllib.tex +++ /dev/null @@ -1,274 +0,0 @@ -\section{Standard Module \sectcode{htmllib}} -\stmodindex{htmllib} -\index{HTML} -\index{hypertext} - -\renewcommand{\indexsubitem}{(in module htmllib)} - -This module defines a number of classes which can serve as a basis for -parsing text files formatted in HTML (HyperText Mark-up Language). -The classes are not directly concerned with I/O --- the have to be fed -their input in string form, and will make calls to methods of a -``formatter'' object in order to produce output. The classes are -designed to be used as base classes for other classes in order to add -functionality, and allow most of their methods to be extended or -overridden. In turn, the classes are derived from and extend the -class \code{SGMLParser} defined in module \code{sgmllib}. -\index{SGML} -\stmodindex{sgmllib} -\ttindex{SGMLParser} -\index{formatter} - -The following is a summary of the interface defined by -\code{sgmllib.SGMLParser}: - -\begin{itemize} - -\item -The interface to feed data to an instance is through the \code{feed()} -method, which takes a string argument. This can be called with as -little or as much text at a time as desired; -\code{p.feed(a); p.feed(b)} has the same effect as \code{p.feed(a+b)}. -When the data contains complete -HTML elements, these are processed immediately; incomplete elements -are saved in a buffer. To force processing of all unprocessed data, -call the \code{close()} method. - -Example: to parse the entire contents of a file, do\\ -\code{parser.feed(open(file).read()); parser.close()}. - -\item -The interface to define semantics for HTML tags is very simple: derive -a class and define methods called \code{start_\var{tag}()}, -\code{end_\var{tag}()}, or \code{do_\var{tag}()}. The parser will -call these at appropriate moments: \code{start_\var{tag}} or -\code{do_\var{tag}} is called when an opening tag of the form -\code{<\var{tag} ...>} is encountered; \code{end_\var{tag}} is called -when a closing tag of the form \code{<\var{tag}>} is encountered. If -an opening tag requires a corresponding closing tag, like \code{

      } -... \code{

      }, the class should define the \code{start_\var{tag}} -method; if a tag requires no closing tag, like \code{

      }, the class -should define the \code{do_\var{tag}} method. - -\end{itemize} - -The module defines the following classes: - -\begin{funcdesc}{HTMLParser}{} -This is the most basic HTML parser class. It defines one additional -entity name over the names defined by the \code{SGMLParser} base -class, \code{\•}. It also defines handlers for the following -tags: \code{

      ...}, \code{...}, and -\code{} (the latter is terminated only by end of file). -\end{funcdesc} - -\begin{funcdesc}{CollectingParser}{} -This class, derived from \code{HTMLParser}, collects various useful -bits of information from the HTML text. To this end it defines -additional handlers for the following tags: \code{<A>...</A>}, -\code{<HEAD>...</HEAD>}, \code{<BODY>...</BODY>}, -\code{<TITLE>...</TITLE>}, \code{<NEXTID>}, and \code{<ISINDEX>}. -\end{funcdesc} - -\begin{funcdesc}{FormattingParser}{formatter\, stylesheet} -This class, derived from \code{CollectingParser}, interprets a wide -selection of HTML tags so it can produce formatted output from the -parsed data. It is initialized with two objects, a \var{formatter} -which should define a number of methods to format text into -paragraphs, and a \var{stylesheet} which defines a number of static -parameters for the formatting process. Formatters and style sheets -are documented later in this section. -\index{formatter} -\index{style sheet} -\end{funcdesc} - -\begin{funcdesc}{AnchoringParser}{formatter\, stylesheet} -This class, derived from \code{FormattingParser}, extends the handling -of the \code{<A>...</A>} tag pair to call the formatter's -\code{bgn_anchor()} and \code{end_anchor()} methods. This allows the -formatter to display the anchor in a different font or color, etc. -\end{funcdesc} - -Instances of \code{CollectingParser} (and thus also instances of -\code{FormattingParser} and \code{AnchoringParser}) have the following -instance variables: - -\begin{datadesc}{anchornames} -A list of the values of the \code{NAME} attributes of the \code{<A>} -tags encountered. -\end{datadesc} - -\begin{datadesc}{anchors} -A list of the values of \code{HREF} attributes of the \code{<A>} tags -encountered. -\end{datadesc} - -\begin{datadesc}{anchortypes} -A list of the values of the \code{TYPE} attributes of the \code{<A>} -tags encountered. -\end{datadesc} - -\begin{datadesc}{inanchor} -Outside an \code{<A>...</A>} tag pair, this is zero. Inside such a -pair, it is a unique integer, which is positive if the anchor has a -\code{HREF} attribute, negative if it hasn't. Its absolute value is -one more than the index of the anchor in the \code{anchors}, -\code{anchornames} and \code{anchortypes} lists. -\end{datadesc} - -\begin{datadesc}{isindex} -True if the \code{<ISINDEX>} tag has been encountered. -\end{datadesc} - -\begin{datadesc}{nextid} -The attribute list of the last \code{<NEXTID>} tag encountered, or -an empty list if none. -\end{datadesc} - -\begin{datadesc}{title} -The text inside the last \code{<TITLE>...</TITLE>} tag pair, or -\code{''} if no title has been encountered yet. -\end{datadesc} - -The \code{anchors}, \code{anchornames} and \code{anchortypes} lists -are ``parallel arrays'': items in these lists with the same index -pertain to the same anchor. Missing attributes default to the empty -string. Anchors with neither a \code{HREF} nor a \code{NAME} -attribute are not entered in these lists at all. - -The module also defines a number of style sheet classes. These should -never be instantiated --- their class variables are the only behavior -required. Note that style sheets are specifically designed for a -particular formatter implementation. The currently defined style -sheets are: -\index{style sheet} - -\begin{datadesc}{NullStylesheet} -A style sheet for use on a dumb output device such as an \ASCII{} -terminal. -\end{datadesc} - -\begin{datadesc}{X11Stylesheet} -A style sheet for use with an X11 server. -\end{datadesc} - -\begin{datadesc}{MacStylesheet} -A style sheet for use on Apple Macintosh computers. -\end{datadesc} - -\begin{datadesc}{StdwinStylesheet} -A style sheet for use with the \code{stdwin} module; it is an alias -for either \code{X11Stylesheet} or \code{MacStylesheet}. -\bimodindex{stdwin} -\end{datadesc} - -\begin{datadesc}{GLStylesheet} -A style sheet for use with the SGI Graphics Library and its font -manager (the SGI-specific built-in modules \code{gl} and \code{fm}). -\bimodindex{gl} -\bimodindex{fm} -\end{datadesc} - -Style sheets have the following class variables: - -\begin{datadesc}{stdfontset} -A list of up to four font definititions, respectively for the roman, -italic, bold and constant-width variant of a font for normal text. If -the list contains less than four font definitions, the last item is -used as the default for missing items. The type of a font definition -depends on the formatter in use; its only use is as a parameter to the -formatter's \code{setfont()} method. -\end{datadesc} - -\begin{datadesc}{h1fontset} -\dataline{h2fontset} -\dataline{h3fontset} -The font set used for various headers (text inside \code{<H1>...</H1>} -tag pairs etc.). -\end{datadesc} - -\begin{datadesc}{stdindent} -The indentation of normal text. This is measured in the ``native'' -units of the formatter in use; for some formatters these are -characters, for others (especially those that actually support -variable-spacing fonts) in pixels or printer points. -\end{datadesc} - -\begin{datadesc}{ddindent} -The indentation used for the first level of \code{<DD>} tags. -\end{datadesc} - -\begin{datadesc}{ulindent} -The indentation used for the first level of \code{<UL>} tags. -\end{datadesc} - -\begin{datadesc}{h1indent} -The indentation used for level 1 headers. -\end{datadesc} - -\begin{datadesc}{h2indent} -The indentation used for level 2 headers. -\end{datadesc} - -\begin{datadesc}{literalindent} -The indentation used for literal text (text inside -\code{<PRE>...</PRE>} and similar tag pairs). -\end{datadesc} - -Although no documented implementation of a formatter exists, the -\code{FormattingParser} class assumes that formatters have a -certain interface. This interface requires the following methods: -\index{formatter} - -\begin{funcdesc}{setfont}{fontspec} -Set the font to be used subsequently. The \var{fontspec} argument is -an item in a style sheet's font set. -\end{funcdesc} - -\begin{funcdesc}{flush}{} -Finish the current line, if not empty, and begin a new one. -\end{funcdesc} - -\begin{funcdesc}{setleftindent}{n} -Set the left indentation of the following lines to \var{n} units. -\end{funcdesc} - -\begin{funcdesc}{needvspace}{n} -Require at least \var{n} blank lines before the next line. Implies -\code{flush()}. -\end{funcdesc} - -\begin{funcdesc}{addword}{word\, space} -Add a \var{word} to the current paragraph, followed by \var{space} -spaces. -\end{funcdesc} - -\begin{datadesc}{nospace} -If this instance variable is true, empty words should be ignored by -\code{addword}. It should be set to false after a non-empty word has -been added. -\end{datadesc} - -\begin{funcdesc}{setjust}{justification} -Set the justification of the current paragraph. The -\var{justification} can be \code{'c'} (center), \code{'l'} (left -justified), \code{'r'} (right justified) or \code{'lr'} (left and -right justified). -\end{funcdesc} - -\begin{funcdesc}{bgn_anchor}{id} -Begin an anchor. The \var{id} parameter is the value of the parser's -\code{inanchor} attribute. -\end{funcdesc} - -\begin{funcdesc}{end_anchor}{id} -End an anchor. The \var{id} parameter is the value of the parser's -\code{inanchor} attribute. -\end{funcdesc} - -A sample formatter implementation can be found in the module -\code{fmt}, which in turn uses the module \code{Para}. These modules are -not intended as standard library modules; they are available as an -example of how to write a formatter. -\ttindex{fmt} -\ttindex{Para} diff --git a/Doc/lib/libhttplib.tex b/Doc/lib/libhttplib.tex deleted file mode 100644 index d2e242092b..0000000000 --- a/Doc/lib/libhttplib.tex +++ /dev/null @@ -1,127 +0,0 @@ -\section{Standard Module \sectcode{httplib}} -\stmodindex{httplib} -\index{HTTP} - -\renewcommand{\indexsubitem}{(in module httplib)} - -This module defines a class which implements the client side of the -HTTP protocol. It is normally not used directly --- the module -\code{urllib} uses it to handle URLs that use HTTP. -\stmodindex{urllib} - -The module defines one class, \code{HTTP}. An \code{HTTP} instance -represents one transaction with an HTTP server. It should be -instantiated passing it a host and optional port number. If no port -number is passed, the port is extracted from the host string if it has -the form \code{host:port}, else the default HTTP port (80) is used. -If no host is passed, no connection is made, and the \code{connect} -method should be used to connect to a server. For example, the -following calls all create instances that connect to the server at the -same host and port: - -\begin{verbatim} ->>> h1 = httplib.HTTP('www.cwi.nl') ->>> h2 = httplib.HTTP('www.cwi.nl:80') ->>> h3 = httplib.HTTP('www.cwi.nl', 80) -\end{verbatim} - -Once an \code{HTTP} instance has been connected to an HTTP server, it -should be used as follows: - -\begin{enumerate} - -\item[1.] Make exactly one call to the \code{putrequest()} method. - -\item[2.] Make zero or more calls to the \code{putheader()} method. - -\item[3.] Call the \code{endheaders()} method (this can be omitted if -step 4 makes no calls). - -\item[4.] Optional calls to the \code{send()} method. - -\item[5.] Call the \code{getreply()} method. - -\item[6.] Call the \code{getfile()} method and read the data off the -file object that it returns. - -\end{enumerate} - -\subsection{HTTP Objects} - -\code{HTTP} instances have the following methods: - -\renewcommand{\indexsubitem}{(HTTP method)} - -\begin{funcdesc}{set_debuglevel}{level} -Set the debugging level (the amount of debugging output printed). -The default debug level is \code{0}, meaning no debugging output is -printed. -\end{funcdesc} - -\begin{funcdesc}{connect}{host\optional{\, port}} -Connect to the server given by \var{host} and \var{port}. See the -intro for the default port. This should be called directly only if -the instance was instantiated without passing a host. -\end{funcdesc} - -\begin{funcdesc}{send}{data} -Send data to the server. This should be used directly only after the -\code{endheaders()} method has been called and before -\code{getreply()} has been called. -\end{funcdesc} - -\begin{funcdesc}{putrequest}{request\, selector} -This should be the first call after the connection to the server has -been made. It sends a line to the server consisting of the -\var{request} string, the \var{selector} string, and the HTTP version -(\code{HTTP/1.0}). -\end{funcdesc} - -\begin{funcdesc}{putheader}{header\, argument\optional{\, ...}} -Send an RFC-822 style header to the server. It sends a line to the -server consisting of the header, a colon and a space, and the first -argument. If more arguments are given, continuation lines are sent, -each consisting of a tab and an argument. -\end{funcdesc} - -\begin{funcdesc}{endheaders}{} -Send a blank line to the server, signalling the end of the headers. -\end{funcdesc} - -\begin{funcdesc}{getreply}{} -Complete the request by shutting down the sending end of the socket, -read the reply from the server, and return a triple (\var{replycode}, -\var{message}, \var{headers}). Here \var{replycode} is the integer -reply code from the request (e.g.\ \code{200} if the request was -handled properly); \var{message} is the message string corresponding -to the reply code; and \var{header} is an instance of the class -\code{rfc822.Message} containing the headers received from the server. -See the description of the \code{rfc822} module. -\stmodindex{rfc822} -\end{funcdesc} - -\begin{funcdesc}{getfile}{} -Return a file object from which the data returned by the server can be -read, using the \code{read()}, \code{readline()} or \code{readlines()} -methods. -\end{funcdesc} - -\subsection{Example} -\nodename{HTTP Example} - -Here is an example session: - -\begin{verbatim} ->>> import httplib ->>> h = httplib.HTTP('www.cwi.nl') ->>> h.putrequest('GET', '/index.html') ->>> h.putheader('Accept', 'text/html') ->>> h.putheader('Accept', 'text/plain') ->>> h.endheaders() ->>> errcode, errmsg, headers = h.getreply() ->>> print errcode # Should be 200 ->>> f = h.getfile() ->>> data f.read() # Get the raw HTML ->>> f.close() ->>> -\end{verbatim} diff --git a/Doc/lib/libimageop.tex b/Doc/lib/libimageop.tex deleted file mode 100644 index 4e151170d0..0000000000 --- a/Doc/lib/libimageop.tex +++ /dev/null @@ -1,86 +0,0 @@ -\section{Built-in Module \sectcode{imageop}} -\bimodindex{imageop} - -The \code{imageop} module contains some useful operations on images. -It operates on images consisting of 8 or 32 bit pixels -stored in Python strings. This is the same format as used -by \code{gl.lrectwrite} and the \code{imgfile} module. - -The module defines the following variables and functions: - -\renewcommand{\indexsubitem}{(in module imageop)} - -\begin{excdesc}{error} -This exception is raised on all errors, such as unknown number of bits -per pixel, etc. -\end{excdesc} - - -\begin{funcdesc}{crop}{image\, psize\, width\, height\, x0\, y0\, x1\, y1} -Return the selected part of \var{image}, which should by -\var{width} by \var{height} in size and consist of pixels of -\var{psize} bytes. \var{x0}, \var{y0}, \var{x1} and \var{y1} are like -the \code{lrectread} parameters, i.e.\ the boundary is included in the -new image. The new boundaries need not be inside the picture. Pixels -that fall outside the old image will have their value set to zero. If -\var{x0} is bigger than \var{x1} the new image is mirrored. The same -holds for the y coordinates. -\end{funcdesc} - -\begin{funcdesc}{scale}{image\, psize\, width\, height\, newwidth\, newheight} -Return \var{image} scaled to size \var{newwidth} by \var{newheight}. -No interpolation is done, scaling is done by simple-minded pixel -duplication or removal. Therefore, computer-generated images or -dithered images will not look nice after scaling. -\end{funcdesc} - -\begin{funcdesc}{tovideo}{image\, psize\, width\, height} -Run a vertical low-pass filter over an image. It does so by computing -each destination pixel as the average of two vertically-aligned source -pixels. The main use of this routine is to forestall excessive -flicker if the image is displayed on a video device that uses -interlacing, hence the name. -\end{funcdesc} - -\begin{funcdesc}{grey2mono}{image\, width\, height\, threshold} -Convert a 8-bit deep greyscale image to a 1-bit deep image by -tresholding all the pixels. The resulting image is tightly packed and -is probably only useful as an argument to \code{mono2grey}. -\end{funcdesc} - -\begin{funcdesc}{dither2mono}{image\, width\, height} -Convert an 8-bit greyscale image to a 1-bit monochrome image using a -(simple-minded) dithering algorithm. -\end{funcdesc} - -\begin{funcdesc}{mono2grey}{image\, width\, height\, p0\, p1} -Convert a 1-bit monochrome image to an 8 bit greyscale or color image. -All pixels that are zero-valued on input get value \var{p0} on output -and all one-value input pixels get value \var{p1} on output. To -convert a monochrome black-and-white image to greyscale pass the -values \code{0} and \code{255} respectively. -\end{funcdesc} - -\begin{funcdesc}{grey2grey4}{image\, width\, height} -Convert an 8-bit greyscale image to a 4-bit greyscale image without -dithering. -\end{funcdesc} - -\begin{funcdesc}{grey2grey2}{image\, width\, height} -Convert an 8-bit greyscale image to a 2-bit greyscale image without -dithering. -\end{funcdesc} - -\begin{funcdesc}{dither2grey2}{image\, width\, height} -Convert an 8-bit greyscale image to a 2-bit greyscale image with -dithering. As for \code{dither2mono}, the dithering algorithm is -currently very simple. -\end{funcdesc} - -\begin{funcdesc}{grey42grey}{image\, width\, height} -Convert a 4-bit greyscale image to an 8-bit greyscale image. -\end{funcdesc} - -\begin{funcdesc}{grey22grey}{image\, width\, height} -Convert a 2-bit greyscale image to an 8-bit greyscale image. -\end{funcdesc} diff --git a/Doc/lib/libimgfile.tex b/Doc/lib/libimgfile.tex deleted file mode 100644 index 1e8b2aaa9b..0000000000 --- a/Doc/lib/libimgfile.tex +++ /dev/null @@ -1,63 +0,0 @@ -\section{Built-in Module \sectcode{imgfile}} -\bimodindex{imgfile} - -The imgfile module allows python programs to access SGI imglib image -files (also known as \file{.rgb} files). The module is far from -complete, but is provided anyway since the functionality that there is -is enough in some cases. Currently, colormap files are not supported. - -The module defines the following variables and functions: - -\renewcommand{\indexsubitem}{(in module imgfile)} -\begin{excdesc}{error} -This exception is raised on all errors, such as unsupported file type, etc. -\end{excdesc} - -\begin{funcdesc}{getsizes}{file} -This function returns a tuple \code{(\var{x}, \var{y}, \var{z})} where -\var{x} and \var{y} are the size of the image in pixels and -\var{z} is the number of -bytes per pixel. Only 3 byte RGB pixels and 1 byte greyscale pixels -are currently supported. -\end{funcdesc} - -\begin{funcdesc}{read}{file} -This function reads and decodes the image on the specified file, and -returns it as a python string. The string has either 1 byte greyscale -pixels or 4 byte RGBA pixels. The bottom left pixel is the first in -the string. This format is suitable to pass to \code{gl.lrectwrite}, -for instance. -\end{funcdesc} - -\begin{funcdesc}{readscaled}{file\, x\, y\, filter\optional{\, blur}} -This function is identical to read but it returns an image that is -scaled to the given \var{x} and \var{y} sizes. If the \var{filter} and -\var{blur} parameters are omitted scaling is done by -simply dropping or duplicating pixels, so the result will be less than -perfect, especially for computer-generated images. - -Alternatively, you can specify a filter to use to smoothen the image -after scaling. The filter forms supported are \code{'impulse'}, -\code{'box'}, \code{'triangle'}, \code{'quadratic'} and -\code{'gaussian'}. If a filter is specified \var{blur} is an optional -parameter specifying the blurriness of the filter. It defaults to \code{1.0}. - -\code{readscaled} makes no -attempt to keep the aspect ratio correct, so that is the users' -responsibility. -\end{funcdesc} - -\begin{funcdesc}{ttob}{flag} -This function sets a global flag which defines whether the scan lines -of the image are read or written from bottom to top (flag is zero, -compatible with SGI GL) or from top to bottom(flag is one, -compatible with X). The default is zero. -\end{funcdesc} - -\begin{funcdesc}{write}{file\, data\, x\, y\, z} -This function writes the RGB or greyscale data in \var{data} to image -file \var{file}. \var{x} and \var{y} give the size of the image, -\var{z} is 1 for 1 byte greyscale images or 3 for RGB images (which are -stored as 4 byte values of which only the lower three bytes are used). -These are the formats returned by \code{gl.lrectread}. -\end{funcdesc} diff --git a/Doc/lib/libimp.tex b/Doc/lib/libimp.tex deleted file mode 100644 index dbced97e31..0000000000 --- a/Doc/lib/libimp.tex +++ /dev/null @@ -1,174 +0,0 @@ -\section{Built-in Module \sectcode{imp}} -\bimodindex{imp} -\index{import} - -This module provides an interface to the mechanisms used to implement -the \code{import} statement. It defines the following constants and -functions: - -\renewcommand{\indexsubitem}{(in module imp)} - -\begin{funcdesc}{get_magic}{} -Return the magic string value used to recognize byte-compiled code -files (``\code{.pyc} files''). -\end{funcdesc} - -\begin{funcdesc}{get_suffixes}{} -Return a list of triples, each describing a particular type of file. -Each triple has the form \code{(\var{suffix}, \var{mode}, -\var{type})}, where \var{suffix} is a string to be appended to the -module name to form the filename to search for, \var{mode} is the mode -string to pass to the built-in \code{open} function to open the file -(this can be \code{'r'} for text files or \code{'rb'} for binary -files), and \var{type} is the file type, which has one of the values -\code{PY_SOURCE}, \code{PY_COMPILED} or \code{C_EXTENSION}, defined -below. (System-dependent values may also be returned.) -\end{funcdesc} - -\begin{funcdesc}{find_module}{name\, \optional{path}} -Try to find the module \var{name} on the search path \var{path}. The -default \var{path} is \code{sys.path}. The return value is a triple -\code{(\var{file}, \var{pathname}, \var{description})} where -\var{file} is an open file object positioned at the beginning, -\var{pathname} is the pathname of the -file found, and \var{description} is a triple as contained in the list -returned by \code{get_suffixes} describing the kind of file found. -\end{funcdesc} - -\begin{funcdesc}{init_builtin}{name} -Initialize the built-in module called \var{name} and return its module -object. If the module was already initialized, it will be initialized -{\em again}. A few modules cannot be initialized twice --- attempting -to initialize these again will raise an \code{ImportError} exception. -If there is no -built-in module called \var{name}, \code{None} is returned. -\end{funcdesc} - -\begin{funcdesc}{init_frozen}{name} -Initialize the frozen module called \var{name} and return its module -object. If the module was already initialized, it will be initialized -{\em again}. If there is no frozen module called \var{name}, -\code{None} is returned. (Frozen modules are modules written in -Python whose compiled byte-code object is incorporated into a -custom-built Python interpreter by Python's \code{freeze} utility. -See \code{Tools/freeze} for now.) -\end{funcdesc} - -\begin{funcdesc}{is_builtin}{name} -Return \code{1} if there is a built-in module called \var{name} which can be -initialized again. Return \code{-1} if there is a built-in module -called \var{name} which cannot be initialized again (see -\code{init_builtin}). Return \code{0} if there is no built-in module -called \var{name}. -\end{funcdesc} - -\begin{funcdesc}{is_frozen}{name} -Return \code{1} if there is a frozen module (see \code{init_frozen}) -called \var{name}, \code{0} if there is no such module. -\end{funcdesc} - -\begin{funcdesc}{load_compiled}{name\, pathname\, \optional{file}} -Load and initialize a module implemented as a byte-compiled code file -and return its module object. If the module was already initialized, -it will be initialized {\em again}. The \var{name} argument is used -to create or access a module object. The \var{pathname} argument -points to the byte-compiled code file. The optional \var{file} -argument is the byte-compiled code file, open for reading in binary -mode, from the beginning --- if not given, the function opens -\var{pathname}. It must currently be a real file object, not a -user-defined class emulating a file. -\end{funcdesc} - -\begin{funcdesc}{load_dynamic}{name\, pathname\, \optional{file}} -Load and initialize a module implemented as a dynamically loadable -shared library and return its module object. If the module was -already initialized, it will be initialized {\em again}. Some modules -don't like that and may raise an exception. The \var{pathname} -argument must point to the shared library. The \var{name} argument is -used to construct the name of the initialization function: an external -C function called \code{init\var{name}()} in the shared library is -called. The optional \var{file} argment is ignored. (Note: using -shared libraries is highly system dependent, and not all systems -support it.) -\end{funcdesc} - -\begin{funcdesc}{load_source}{name\, pathname\, \optional{file}} -Load and initialize a module implemented as a Python source file and -return its module object. If the module was already initialized, it -will be initialized {\em again}. The \var{name} argument is used to -create or access a module object. The \var{pathname} argument points -to the source file. The optional \var{file} argument is the source -file, open for reading as text, from the beginning --- if not given, -the function opens \var{pathname}. It must currently be a real file -object, not a user-defined class emulating a file. Note that if a -properly matching byte-compiled file (with suffix \code{.pyc}) exists, -it will be used instead of parsing the given source file. -\end{funcdesc} - -\begin{funcdesc}{new_module}{name} -Return a new empty module object called \var{name}. This object is -{\em not} inserted in \code{sys.modules}. -\end{funcdesc} - -The following constants with integer values, defined in the module, -are used to indicate the search result of \code{imp.find_module}. - -\begin{datadesc}{SEARCH_ERROR} -The module was not found. -\end{datadesc} - -\begin{datadesc}{PY_SOURCE} -The module was found as a source file. -\end{datadesc} - -\begin{datadesc}{PY_COMPILED} -The module was found as a compiled code object file. -\end{datadesc} - -\begin{datadesc}{C_EXTENSION} -The module was found as dynamically loadable shared library. -\end{datadesc} - -\subsection{Examples} -The following function emulates the default import statement: - -\begin{verbatim} -import imp -import sys - -def __import__(name, globals=None, locals=None, fromlist=None): - # Fast path: see if the module has already been imported. - if sys.modules.has_key(name): - return sys.modules[name] - - # If any of the following calls raises an exception, - # there's a problem we can't handle -- let the caller handle it. - - # See if it's a built-in module. - m = imp.init_builtin(name) - if m: - return m - - # See if it's a frozen module. - m = imp.init_frozen(name) - if m: - return m - - # Search the default path (i.e. sys.path). - fp, pathname, (suffix, mode, type) = imp.find_module(name) - - # See what we got. - try: - if type == imp.C_EXTENSION: - return imp.load_dynamic(name, pathname) - if type == imp.PY_SOURCE: - return imp.load_source(name, pathname, fp) - if type == imp.PY_COMPILED: - return imp.load_compiled(name, pathname, fp) - - # Shouldn't get here at all. - raise ImportError, '%s: unknown module type (%d)' % (name, type) - finally: - # Since we may exit via an exception, close fp explicitly. - fp.close() -\end{verbatim} diff --git a/Doc/lib/libintro.tex b/Doc/lib/libintro.tex deleted file mode 100644 index 70d7478c8d..0000000000 --- a/Doc/lib/libintro.tex +++ /dev/null @@ -1,47 +0,0 @@ -\chapter{Introduction} - -The ``Python library'' contains several different kinds of components. - -It contains data types that would normally be considered part of the -``core'' of a language, such as numbers and lists. For these types, -the Python language core defines the form of literals and places some -constraints on their semantics, but does not fully define the -semantics. (On the other hand, the language core does define -syntactic properties like the spelling and priorities of operators.) - -The library also contains built-in functions and exceptions --- -objects that can be used by all Python code without the need of an -\code{import} statement. Some of these are defined by the core -language, but many are not essential for the core semantics and are -only described here. - -The bulk of the library, however, consists of a collection of modules. -There are many ways to dissect this collection. Some modules are -written in C and built in to the Python interpreter; others are -written in Python and imported in source form. Some modules provide -interfaces that are highly specific to Python, like printing a stack -trace; some provide interfaces that are specific to particular -operating systems, like socket I/O; others provide interfaces that are -specific to a particular application domain, like the World-Wide Web. -Some modules are avaiable in all versions and ports of Python; others -are only available when the underlying system supports or requires -them; yet others are available only when a particular configuration -option was chosen at the time when Python was compiled and installed. - -This manual is organized ``from the inside out'': it first describes -the built-in data types, then the built-in functions and exceptions, -and finally the modules, grouped in chapters of related modules. The -ordering of the chapters as well as the ordering of the modules within -each chapter is roughly from most relevant to least important. - -This means that if you start reading this manual from the start, and -skip to the next chapter when you get bored, you will get a reasonable -overview of the available modules and application areas that are -supported by the Python library. Of course, you don't \emph{have} to -read it like a novel --- you can also browse the table of contents (in -front of the manual), or look for a specific function, module or term -in the index (in the back). And finally, if you enjoy learning about -random subjects, you choose a random page number (see module -\code{rand}) and read a section or two. - -Let the show begin! diff --git a/Doc/lib/libjpeg.tex b/Doc/lib/libjpeg.tex deleted file mode 100644 index 8215cada56..0000000000 --- a/Doc/lib/libjpeg.tex +++ /dev/null @@ -1,51 +0,0 @@ -\section{Built-in Module \sectcode{jpeg}} -\bimodindex{jpeg} - -The module \code{jpeg} provides access to the jpeg compressor and -decompressor written by the Independent JPEG Group. JPEG is a (draft?)\ -standard for compressing pictures. For details on jpeg or the -Independent JPEG Group software refer to the JPEG standard or the -documentation provided with the software. - -The \code{jpeg} module defines these functions: - -\renewcommand{\indexsubitem}{(in module jpeg)} -\begin{funcdesc}{compress}{data\, w\, h\, b} -Treat data as a pixmap of width \var{w} and height \var{h}, with \var{b} bytes per -pixel. The data is in SGI GL order, so the first pixel is in the -lower-left corner. This means that \code{lrectread} return data can -immediately be passed to compress. Currently only 1 byte and 4 byte -pixels are allowed, the former being treated as greyscale and the -latter as RGB color. Compress returns a string that contains the -compressed picture, in JFIF format. -\end{funcdesc} - -\begin{funcdesc}{decompress}{data} -Data is a string containing a picture in JFIF format. It returns a -tuple -\code{(\var{data}, \var{width}, \var{height}, \var{bytesperpixel})}. -Again, the data is suitable to pass to \code{lrectwrite}. -\end{funcdesc} - -\begin{funcdesc}{setoption}{name\, value} -Set various options. Subsequent compress and decompress calls -will use these options. The following options are available: -\begin{description} -\item[\code{'forcegray' }] -Force output to be grayscale, even if input is RGB. - -\item[\code{'quality' }] -Set the quality of the compressed image to a -value between \code{0} and \code{100} (default is \code{75}). Compress only. - -\item[\code{'optimize' }] -Perform Huffman table optimization. Takes longer, but results in -smaller compressed image. Compress only. - -\item[\code{'smooth' }] -Perform inter-block smoothing on uncompressed image. Only useful for -low-quality images. Decompress only. -\end{description} -\end{funcdesc} - -Compress and uncompress raise the error \code{jpeg.error} in case of errors. diff --git a/Doc/lib/libmain.tex b/Doc/lib/libmain.tex deleted file mode 100644 index c730a03a11..0000000000 --- a/Doc/lib/libmain.tex +++ /dev/null @@ -1,6 +0,0 @@ -\section{Built-in Module \sectcode{__main__}} - -\bimodindex{__main__} -This module represents the (otherwise anonymous) scope in which the -interpreter's main program executes --- commands read either from -standard input or from a script file. diff --git a/Doc/lib/libmarshal.tex b/Doc/lib/libmarshal.tex deleted file mode 100644 index 3abcc4291d..0000000000 --- a/Doc/lib/libmarshal.tex +++ /dev/null @@ -1,83 +0,0 @@ -\section{Built-in Module \sectcode{marshal}} - -\bimodindex{marshal} -This module contains functions that can read and write Python -values in a binary format. The format is specific to Python, but -independent of machine architecture issues (e.g., you can write a -Python value to a file on a PC, transport the file to a Sun, and read -it back there). Details of the format are undocumented on purpose; -it may change between Python versions (although it rarely does).% -\footnote{The name of this module stems from a bit of terminology used -by the designers of Modula-3 (amongst others), who use the term -``marshalling'' for shipping of data around in a self-contained form. -Strictly speaking, ``to marshal'' means to convert some data from -internal to external form (in an RPC buffer for instance) and -``unmarshalling'' for the reverse process.} - -This is not a general ``persistency'' module. For general persistency -and transfer of Python objects through RPC calls, see the modules -\code{pickle} and \code{shelve}. The \code{marshal} module exists -mainly to support reading and writing the ``pseudo-compiled'' code for -Python modules of \samp{.pyc} files. -\stmodindex{pickle} -\stmodindex{shelve} -\obindex{code} - -Not all Python object types are supported; in general, only objects -whose value is independent from a particular invocation of Python can -be written and read by this module. The following types are supported: -\code{None}, integers, long integers, floating point numbers, -strings, tuples, lists, dictionaries, and code objects, where it -should be understood that tuples, lists and dictionaries are only -supported as long as the values contained therein are themselves -supported; and recursive lists and dictionaries should not be written -(they will cause infinite loops). - -{\bf Caveat:} On machines where C's \code{long int} type has more than -32 bits (such as the DEC Alpha), it -is possible to create plain Python integers that are longer than 32 -bits. Since the current \code{marshal} module uses 32 bits to -transfer plain Python integers, such values are silently truncated. -This particularly affects the use of very long integer literals in -Python modules --- these will be accepted by the parser on such -machines, but will be silently be truncated when the module is read -from the \code{.pyc} instead.% -\footnote{A solution would be to refuse such literals in the parser, -since they are inherently non-portable. Another solution would be to -let the \code{marshal} module raise an exception when an integer value -would be truncated. At least one of these solutions will be -implemented in a future version.} - -There are functions that read/write files as well as functions -operating on strings. - -The module defines these functions: - -\renewcommand{\indexsubitem}{(in module marshal)} - -\begin{funcdesc}{dump}{value\, file} - Write the value on the open file. The value must be a supported - type. The file must be an open file object such as - \code{sys.stdout} or returned by \code{open()} or - \code{posix.popen()}. - - If the value has an unsupported type, garbage is written which cannot - be read back by \code{load()}. -\end{funcdesc} - -\begin{funcdesc}{load}{file} - Read one value from the open file and return it. If no valid value - is read, raise \code{EOFError}, \code{ValueError} or - \code{TypeError}. The file must be an open file object. -\end{funcdesc} - -\begin{funcdesc}{dumps}{value} - Return the string that would be written to a file by - \code{dump(value, file)}. The value must be a supported type. -\end{funcdesc} - -\begin{funcdesc}{loads}{string} - Convert the string to a value. If no valid value is found, raise - \code{EOFError}, \code{ValueError} or \code{TypeError}. Extra - characters in the string are ignored. -\end{funcdesc} diff --git a/Doc/lib/libmath.tex b/Doc/lib/libmath.tex deleted file mode 100644 index 765fcdf5c6..0000000000 --- a/Doc/lib/libmath.tex +++ /dev/null @@ -1,72 +0,0 @@ -\section{Built-in Module \sectcode{math}} - -\bimodindex{math} -\renewcommand{\indexsubitem}{(in module math)} -This module is always available. -It provides access to the mathematical functions defined by the C -standard. -They are: -\iftexi -\begin{funcdesc}{acos}{x} -\funcline{asin}{x} -\funcline{atan}{x} -\funcline{atan2}{x, y} -\funcline{ceil}{x} -\funcline{cos}{x} -\funcline{cosh}{x} -\funcline{exp}{x} -\funcline{fabs}{x} -\funcline{floor}{x} -\funcline{fmod}{x, y} -\funcline{frexp}{x} -\funcline{hypot}{x, y} -\funcline{ldexp}{x, y} -\funcline{log}{x} -\funcline{log10}{x} -\funcline{modf}{x} -\funcline{pow}{x, y} -\funcline{sin}{x} -\funcline{sinh}{x} -\funcline{sqrt}{x} -\funcline{tan}{x} -\funcline{tanh}{x} -\end{funcdesc} -\else -\code{acos(\varvars{x})}, -\code{asin(\varvars{x})}, -\code{atan(\varvars{x})}, -\code{atan2(\varvars{x\, y})}, -\code{ceil(\varvars{x})}, -\code{cos(\varvars{x})}, -\code{cosh(\varvars{x})}, -\code{exp(\varvars{x})}, -\code{fabs(\varvars{x})}, -\code{floor(\varvars{x})}, -\code{fmod(\varvars{x\, y})}, -\code{frexp(\varvars{x})}, -\code{hypot(\varvars{x\, y})}, -\code{ldexp(\varvars{x\, y})}, -\code{log(\varvars{x})}, -\code{log10(\varvars{x})}, -\code{modf(\varvars{x})}, -\code{pow(\varvars{x\, y})}, -\code{sin(\varvars{x})}, -\code{sinh(\varvars{x})}, -\code{sqrt(\varvars{x})}, -\code{tan(\varvars{x})}, -\code{tanh(\varvars{x})}. -\fi - -Note that \code{frexp} and \code{modf} have a different call/return -pattern than their C equivalents: they take a single argument and -return a pair of values, rather than returning their second return -value through an `output parameter' (there is no such thing in Python). - -The module also defines two mathematical constants: -\iftexi -\begin{datadesc}{pi} -\dataline{e} -\end{datadesc} -\else -\code{pi} and \code{e}. -\fi diff --git a/Doc/lib/libmd5.tex b/Doc/lib/libmd5.tex deleted file mode 100644 index bd26f02052..0000000000 --- a/Doc/lib/libmd5.tex +++ /dev/null @@ -1,64 +0,0 @@ -\section{Built-in Module \sectcode{md5}} -\bimodindex{md5} - -This module implements the interface to RSA's MD5 message digest -algorithm (see also Internet RFC 1321). Its use is quite -straightforward:\ use the \code{md5.new()} to create an md5 object. -You can now feed this object with arbitrary strings using the -\code{update()} method, and at any point you can ask it for the -\dfn{digest} (a strong kind of 128-bit checksum, -a.k.a. ``fingerprint'') of the contatenation of the strings fed to it -so far using the \code{digest()} method. - -For example, to obtain the digest of the string {\tt"Nobody inspects -the spammish repetition"}: - -\bcode\begin{verbatim} ->>> import md5 ->>> m = md5.new() ->>> m.update("Nobody inspects") ->>> m.update(" the spammish repetition") ->>> m.digest() -'\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351' -\end{verbatim}\ecode - -More condensed: - -\bcode\begin{verbatim} ->>> md5.new("Nobody inspects the spammish repetition").digest() -'\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351' -\end{verbatim}\ecode - -\renewcommand{\indexsubitem}{(in module md5)} - -\begin{funcdesc}{new}{\optional{arg}} -Return a new md5 object. If \var{arg} is present, the method call -\code{update(\var{arg})} is made. -\end{funcdesc} - -\begin{funcdesc}{md5}{\optional{arg}} -For backward compatibility reasons, this is an alternative name for the -\code{new()} function. -\end{funcdesc} - -An md5 object has the following methods: - -\renewcommand{\indexsubitem}{(md5 method)} -\begin{funcdesc}{update}{arg} -Update the md5 object with the string \var{arg}. Repeated calls are -equivalent to a single call with the concatenation of all the -arguments, i.e.\ \code{m.update(a); m.update(b)} is equivalent to -\code{m.update(a+b)}. -\end{funcdesc} - -\begin{funcdesc}{digest}{} -Return the digest of the strings passed to the \code{update()} -method so far. This is an 8-byte string which may contain -non-\ASCII{} characters, including null bytes. -\end{funcdesc} - -\begin{funcdesc}{copy}{} -Return a copy (``clone'') of the md5 object. This can be used to -efficiently compute the digests of strings that share a common initial -substring. -\end{funcdesc} diff --git a/Doc/lib/libmimetools.tex b/Doc/lib/libmimetools.tex deleted file mode 100644 index decb89021f..0000000000 --- a/Doc/lib/libmimetools.tex +++ /dev/null @@ -1,96 +0,0 @@ -\section{Standard Module \sectcode{mimetools}} -\stmodindex{mimetools} - -\renewcommand{\indexsubitem}{(in module mimetools)} - -This module defines a subclass of the class \code{rfc822.Message} and -a number of utility functions that are useful for the manipulation for -MIME style multipart or encoded message. - -It defines the following items: - -\begin{funcdesc}{Message}{fp} -Return a new instance of the \code{mimetools.Message} class. This is -a subclass of the \code{rfc822.Message} class, with some additional -methods (see below). -\end{funcdesc} - -\begin{funcdesc}{choose_boundary}{} -Return a unique string that has a high likelihood of being usable as a -part boundary. The string has the form -\code{"\var{hostipaddr}.\var{uid}.\var{pid}.\var{timestamp}.\var{random}"}. -\end{funcdesc} - -\begin{funcdesc}{decode}{input\, output\, encoding} -Read data encoded using the allowed MIME \var{encoding} from open file -object \var{input} and write the decoded data to open file object -\var{output}. Valid values for \var{encoding} include -\code{"base64"}, \code{"quoted-printable"} and \code{"uuencode"}. -\end{funcdesc} - -\begin{funcdesc}{encode}{input\, output\, encoding} -Read data from open file object \var{input} and write it encoded using -the allowed MIME \var{encoding} to open file object \var{output}. -Valid values for \var{encoding} are the same as for \code{decode()}. -\end{funcdesc} - -\begin{funcdesc}{copyliteral}{input\, output} -Read lines until EOF from open file \var{input} and write them to open -file \var{output}. -\end{funcdesc} - -\begin{funcdesc}{copybinary}{input\, output} -Read blocks until EOF from open file \var{input} and write them to open -file \var{output}. The block size is currently fixed at 8192. -\end{funcdesc} - - -\subsection{Additional Methods of Message objects} -\nodename{mimetools.Message Methods} - -The \code{mimetools.Message} class defines the following methods in -addition to the \code{rfc822.Message} class: - -\renewcommand{\indexsubitem}{(mimetool.Message method)} - -\begin{funcdesc}{getplist}{} -Return the parameter list of the \code{Content-type} header. This is -a list if strings. For parameters of the form -\samp{\var{key}=\var{value}}, \var{key} is converted to lower case but -\var{value} is not. For example, if the message contains the header -\samp{Content-type: text/html; spam=1; Spam=2; Spam} then -\code{getplist()} will return the Python list \code{['spam=1', -'spam=2', 'Spam']}. -\end{funcdesc} - -\begin{funcdesc}{getparam}{name} -Return the \var{value} of the first parameter (as returned by -\code{getplist()} of the form \samp{\var{name}=\var{value}} for the -given \var{name}. If \var{value} is surrounded by quotes of the form -\var{<...>} or \var{"..."}, these are removed. -\end{funcdesc} - -\begin{funcdesc}{getencoding}{} -Return the encoding specified in the \samp{Content-transfer-encoding} -message header. If no such header exists, return \code{"7bit"}. The -encoding is converted to lower case. -\end{funcdesc} - -\begin{funcdesc}{gettype}{} -Return the message type (of the form \samp{\var{type}/var{subtype}}) -as specified in the \samp{Content-type} header. If no such header -exists, return \code{"text/plain"}. The type is converted to lower -case. -\end{funcdesc} - -\begin{funcdesc}{getmaintype}{} -Return the main type as specified in the \samp{Content-type} header. -If no such header exists, return \code{"text"}. The main type is -converted to lower case. -\end{funcdesc} - -\begin{funcdesc}{getsubtype}{} -Return the subtype as specified in the \samp{Content-type} header. If -no such header exists, return \code{"plain"}. The subtype is -converted to lower case. -\end{funcdesc} diff --git a/Doc/lib/libmisc.tex b/Doc/lib/libmisc.tex deleted file mode 100644 index b7a726e72c..0000000000 --- a/Doc/lib/libmisc.tex +++ /dev/null @@ -1,20 +0,0 @@ -\chapter{Miscellaneous Services} - -The modules described in this chapter provide miscellaneous services -that are available in all Python versions. Here's an overview: - -\begin{description} - -\item[math] ---- Mathematical functions (\code{sin()} etc.). - -\item[rand] ---- Integer random number generator. - -\item[whrandom] ---- Floating point random number generator. - -\item[array] ---- Efficient arrays of uniformly typed numeric values. - -\end{description} diff --git a/Doc/lib/libmm.tex b/Doc/lib/libmm.tex deleted file mode 100644 index d5abc6f561..0000000000 --- a/Doc/lib/libmm.tex +++ /dev/null @@ -1,25 +0,0 @@ -\chapter{Multimedia Services} - -The modules described in this chapter implement various algorithms or -interfaces that are mainly useful for multimedia applications. They -are available at the discretion of the installation. Here's an overview: - -\begin{description} - -\item[audioop] ---- Manipulate raw audio data. - -\item[imageop] ---- Manipulate raw image data. - -\item[aifc] ---- Read and write audio files in AIFF or AIFC format. - -\item[jpeg] ---- Read and write image files in compressed JPEG format. - -\item[rgbimg] ---- Read and write image files in ``SGI RGB'' format (the module is -\emph{not} SGI specific though)! - -\end{description} diff --git a/Doc/lib/libmpz.tex b/Doc/lib/libmpz.tex deleted file mode 100644 index 46a2d474dc..0000000000 --- a/Doc/lib/libmpz.tex +++ /dev/null @@ -1,78 +0,0 @@ -\section{Built-in Module \sectcode{mpz}} -\bimodindex{mpz} - -This is an optional module. It is only available when Python is -configured to include it, which requires that the GNU MP software is -installed. - -This module implements the interface to part of the GNU MP library, -which defines arbitrary precision integer and rational number -arithmetic routines. Only the interfaces to the \emph{integer} -(\samp{mpz_{\rm \ldots}}) routines are provided. If not stated -otherwise, the description in the GNU MP documentation can be applied. - -In general, \dfn{mpz}-numbers can be used just like other standard -Python numbers, e.g.\ you can use the built-in operators like \code{+}, -\code{*}, etc., as well as the standard built-in functions like -\code{abs}, \code{int}, \ldots, \code{divmod}, \code{pow}. -\strong{Please note:} the {\it bitwise-xor} operation has been implemented as -a bunch of {\it and}s, {\it invert}s and {\it or}s, because the library -lacks an \code{mpz_xor} function, and I didn't need one. - -You create an mpz-number by calling the function called \code{mpz} (see -below for an exact description). An mpz-number is printed like this: -\code{mpz(\var{value})}. - -\renewcommand{\indexsubitem}{(in module mpz)} -\begin{funcdesc}{mpz}{value} - Create a new mpz-number. \var{value} can be an integer, a long, - another mpz-number, or even a string. If it is a string, it is - interpreted as an array of radix-256 digits, least significant digit - first, resulting in a positive number. See also the \code{binary} - method, described below. -\end{funcdesc} - -A number of {\em extra} functions are defined in this module. Non -mpz-arguments are converted to mpz-values first, and the functions -return mpz-numbers. - -\begin{funcdesc}{powm}{base\, exponent\, modulus} - Return \code{pow(\var{base}, \var{exponent}) \%{} \var{modulus}}. If - \code{\var{exponent} == 0}, return \code{mpz(1)}. In contrast to the - \C-library function, this version can handle negative exponents. -\end{funcdesc} - -\begin{funcdesc}{gcd}{op1\, op2} - Return the greatest common divisor of \var{op1} and \var{op2}. -\end{funcdesc} - -\begin{funcdesc}{gcdext}{a\, b} - Return a tuple \code{(\var{g}, \var{s}, \var{t})}, such that - \code{\var{a}*\var{s} + \var{b}*\var{t} == \var{g} == gcd(\var{a}, \var{b})}. -\end{funcdesc} - -\begin{funcdesc}{sqrt}{op} - Return the square root of \var{op}. The result is rounded towards zero. -\end{funcdesc} - -\begin{funcdesc}{sqrtrem}{op} - Return a tuple \code{(\var{root}, \var{remainder})}, such that - \code{\var{root}*\var{root} + \var{remainder} == \var{op}}. -\end{funcdesc} - -\begin{funcdesc}{divm}{numerator\, denominator\, modulus} - Returns a number \var{q}. such that - \code{\var{q} * \var{denominator} \%{} \var{modulus} == \var{numerator}}. - One could also implement this function in Python, using \code{gcdext}. -\end{funcdesc} - -An mpz-number has one method: - -\renewcommand{\indexsubitem}{(mpz method)} -\begin{funcdesc}{binary}{} - Convert this mpz-number to a binary string, where the number has been - stored as an array of radix-256 digits, least significant digit first. - - The mpz-number must have a value greater than or equal to zero, - otherwise a \code{ValueError}-exception will be raised. -\end{funcdesc} diff --git a/Doc/lib/libnntplib.tex b/Doc/lib/libnntplib.tex deleted file mode 100644 index e17ea8b488..0000000000 --- a/Doc/lib/libnntplib.tex +++ /dev/null @@ -1,212 +0,0 @@ -\section{Standard Module \sectcode{nntplib}} -\stmodindex{nntplib} - -\renewcommand{\indexsubitem}{(in module nntplib)} - -This module defines the class \code{NNTP} which implements the client -side of the NNTP protocol. It can be used to implement a news reader -or poster, or automated news processors. For more information on NNTP -(Network News Transfer Protocol), see Internet RFC 977. - -Here are two small examples of how it can be used. To list some -statistics about a newsgroup and print the subjects of the last 10 -articles: - -\small{ -\begin{verbatim} ->>> s = NNTP('news.cwi.nl') ->>> resp, count, first, last, name = s.group('comp.lang.python') ->>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last -Group comp.lang.python has 59 articles, range 3742 to 3803 ->>> resp, subs = s.xhdr('subject', first + '-' + last) ->>> for id, sub in subs[-10:]: print id, sub -... -3792 Re: Removing elements from a list while iterating... -3793 Re: Who likes Info files? -3794 Emacs and doc strings -3795 a few questions about the Mac implementation -3796 Re: executable python scripts -3797 Re: executable python scripts -3798 Re: a few questions about the Mac implementation -3799 Re: PROPOSAL: A Generic Python Object Interface for Python C Modules -3802 Re: executable python scripts -3803 Re: POSIX wait and SIGCHLD ->>> s.quit() -'205 news.cwi.nl closing connection. Goodbye.' ->>> -\end{verbatim} -} - -To post an article from a file (this assumes that the article has -valid headers): - -\begin{verbatim} ->>> s = NNTP('news.cwi.nl') ->>> f = open('/tmp/article') ->>> s.post(f) -'240 Article posted successfully.' ->>> s.quit() -'205 news.cwi.nl closing connection. Goodbye.' ->>> -\end{verbatim} - -The module itself defines the following items: - -\begin{funcdesc}{NNTP}{host\optional{\, port}} -Return a new instance of the \code{NNTP} class, representing a -connection to the NNTP server running on host \var{host}, listening at -port \var{port}. The default \var{port} is 119. -\end{funcdesc} - -\begin{excdesc}{error_reply} -Exception raised when an unexpected reply is received from the server. -\end{excdesc} - -\begin{excdesc}{error_temp} -Exception raised when an error code in the range 400--499 is received. -\end{excdesc} - -\begin{excdesc}{error_perm} -Exception raised when an error code in the range 500--599 is received. -\end{excdesc} - -\begin{excdesc}{error_proto} -Exception raised when a reply is received from the server that does -not begin with a digit in the range 1--5. -\end{excdesc} - -\subsection{NNTP Objects} - -NNTP instances have the following methods. The \var{response} that is -returned as the first item in the return tuple of almost all methods -is the server's response: a string beginning with a three-digit code. -If the server's response indicates an error, the method raises one of -the above exceptions. - -\renewcommand{\indexsubitem}{(NNTP object method)} - -\begin{funcdesc}{getwelcome}{} -Return the welcome message sent by the server in reply to the initial -connection. (This message sometimes contains disclaimers or help -information that may be relevant to the user.) -\end{funcdesc} - -\begin{funcdesc}{set_debuglevel}{level} -Set the instance's debugging level. This controls the amount of -debugging output printed. The default, 0, produces no debugging -output. A value of 1 produces a moderate amount of debugging output, -generally a single line per request or response. A value of 2 or -higher produces the maximum amount of debugging output, logging each -line sent and received on the connection (including message text). -\end{funcdesc} - -\begin{funcdesc}{newgroups}{date\, time} -Send a \samp{NEWGROUPS} command. The \var{date} argument should be a -string of the form \code{"\var{yy}\var{mm}\var{dd}"} indicating the -date, and \var{time} should be a string of the form -\code{"\var{hh}\var{mm}\var{ss}"} indicating the time. Return a pair -\code{(\var{response}, \var{groups})} where \var{groups} is a list of -group names that are new since the given date and time. -\end{funcdesc} - -\begin{funcdesc}{newnews}{group\, date\, time} -Send a \samp{NEWNEWS} command. Here, \var{group} is a group name or -\code{"*"}, and \var{date} and \var{time} have the same meaning as for -\code{newgroups()}. Return a pair \code{(\var{response}, -\var{articles})} where \var{articles} is a list of article ids. -\end{funcdesc} - -\begin{funcdesc}{list}{} -Send a \samp{LIST} command. Return a pair \code{(\var{response}, -\var{list})} where \var{list} is a list of tuples. Each tuple has the -form \code{(\var{group}, \var{last}, \var{first}, \var{flag})}, where -\var{group} is a group name, \var{last} and \var{first} are the last -and first article numbers (as strings), and \var{flag} is \code{'y'} -if posting is allowed, \code{'n'} if not, and \code{'m'} if the -newsgroup is moderated. (Note the ordering: \var{last}, \var{first}.) -\end{funcdesc} - -\begin{funcdesc}{group}{name} -Send a \samp{GROUP} command, where \var{name} is the group name. -Return a tuple \code{(\var{response}, \var{count}, \var{first}, -\var{last}, \var{name})} where \var{count} is the (estimated) number -of articles in the group, \var{first} is the first article number in -the group, \var{last} is the last article number in the group, and -\var{name} is the group name. The numbers are returned as strings. -\end{funcdesc} - -\begin{funcdesc}{help}{} -Send a \samp{HELP} command. Return a pair \code{(\var{response}, -\var{list})} where \var{list} is a list of help strings. -\end{funcdesc} - -\begin{funcdesc}{stat}{id} -Send a \samp{STAT} command, where \var{id} is the message id (enclosed -in \samp{<} and \samp{>}) or an article number (as a string). -Return a triple \code{(var{response}, \var{number}, \var{id})} where -\var{number} is the article number (as a string) and \var{id} is the -article id (enclosed in \samp{<} and \samp{>}). -\end{funcdesc} - -\begin{funcdesc}{next}{} -Send a \samp{NEXT} command. Return as for \code{stat()}. -\end{funcdesc} - -\begin{funcdesc}{last}{} -Send a \samp{LAST} command. Return as for \code{stat()}. -\end{funcdesc} - -\begin{funcdesc}{head}{id} -Send a \samp{HEAD} command, where \var{id} has the same meaning as for -\code{stat()}. Return a pair \code{(\var{response}, \var{list})} -where \var{list} is a list of the article's headers (an uninterpreted -list of lines, without trailing newlines). -\end{funcdesc} - -\begin{funcdesc}{body}{id} -Send a \samp{BODY} command, where \var{id} has the same meaning as for -\code{stat()}. Return a pair \code{(\var{response}, \var{list})} -where \var{list} is a list of the article's body text (an -uninterpreted list of lines, without trailing newlines). -\end{funcdesc} - -\begin{funcdesc}{article}{id} -Send a \samp{ARTICLE} command, where \var{id} has the same meaning as -for \code{stat()}. Return a pair \code{(\var{response}, \var{list})} -where \var{list} is a list of the article's header and body text (an -uninterpreted list of lines, without trailing newlines). -\end{funcdesc} - -\begin{funcdesc}{slave}{} -Send a \samp{SLAVE} command. Return the server's \var{response}. -\end{funcdesc} - -\begin{funcdesc}{xhdr}{header\, string} -Send an \samp{XHDR} command. This command is not defined in the RFC -but is a common extension. The \var{header} argument is a header -keyword, e.g. \code{"subject"}. The \var{string} argument should have -the form \code{"\var{first}-\var{last}"} where \var{first} and -\var{last} are the first and last article numbers to search. Return a -pair \code{(\var{response}, \var{list})}, where \var{list} is a list of -pairs \code{(\var{id}, \var{text})}, where \var{id} is an article id -(as a string) and \var{text} is the text of the requested header for -that article. -\end{funcdesc} - -\begin{funcdesc}{post}{file} -Post an article using the \samp{POST} command. The \var{file} -argument is an open file object which is read until EOF using its -\code{readline()} method. It should be a well-formed news article, -including the required headers. The \code{post()} method -automatically escapes lines beginning with \samp{.}. -\end{funcdesc} - -\begin{funcdesc}{ihave}{id\, file} -Send an \samp{IHAVE} command. If the response is not an error, treat -\var{file} exactly as for the \code{post()} method. -\end{funcdesc} - -\begin{funcdesc}{quit}{} -Send a \samp{QUIT} command and close the connection. Once this method -has been called, no other methods of the NNTP object should be called. -\end{funcdesc} diff --git a/Doc/lib/libobjs.tex b/Doc/lib/libobjs.tex deleted file mode 100644 index b4dd409c6d..0000000000 --- a/Doc/lib/libobjs.tex +++ /dev/null @@ -1,25 +0,0 @@ -\chapter{Built-in Types, Exceptions and Functions} - -\nodename{Built-in Objects} - -Names for built-in exceptions and functions are found in a separate -symbol table. This table is searched last when the interpreter looks -up the meaning of a name, so local and global -user-defined names can override built-in names. Built-in types are -described together here for easy reference.% -\footnote{Most descriptions sorely lack explanations of the exceptions - that may be raised --- this will be fixed in a future version of - this manual.} -\indexii{built-in}{types} -\indexii{built-in}{exceptions} -\indexii{built-in}{functions} -\index{symbol table} -\bifuncindex{type} - -The tables in this chapter document the priorities of operators by -listing them in order of ascending priority (within a table) and -grouping operators that have the same priority in the same box. -Binary operators of the same priority group from left to right. -(Unary operators group from right to left, but there you have no real -choice.) See Chapter 5 of the Python Reference Manual for the -complete picture on operator priorities. diff --git a/Doc/lib/libos.tex b/Doc/lib/libos.tex deleted file mode 100644 index 51442efcfc..0000000000 --- a/Doc/lib/libos.tex +++ /dev/null @@ -1,104 +0,0 @@ -\section{Standard Module \sectcode{os}} - -\stmodindex{os} -This module provides a more portable way of using operating system -(OS) dependent functionality than importing an OS dependent built-in -module like \code{posix}. - -When the optional built-in module \code{posix} is available, this -module exports the same functions and data as \code{posix}; otherwise, -it searches for an OS dependent built-in module like \code{mac} and -exports the same functions and data as found there. The design of all -Python's built-in OS dependent modules is such that as long as the same -functionality is available, it uses the same interface; e.g., the -function \code{os.stat(\var{file})} returns stat info about a \var{file} in a -format compatible with the POSIX interface. - -Extensions peculiar to a particular OS are also available through the -\code{os} module, but using them is of course a threat to portability! - -Note that after the first time \code{os} is imported, there is \emph{no} -performance penalty in using functions from \code{os} instead of -directly from the OS dependent built-in module, so there should be -\emph{no} reason not to use \code{os}! - -In addition to whatever the correct OS dependent module exports, the -following variables and functions are always exported by \code{os}: - -\renewcommand{\indexsubitem}{(in module os)} - -\begin{datadesc}{name} -The name of the OS dependent module imported. The following names -have currently been registered: \code{'posix'}, \code{'nt'}, -\code{'dos'}, \code{'mac'}. -\end{datadesc} - -\begin{datadesc}{path} -The corresponding OS dependent standard module for pathname -operations, e.g., \code{posixpath} or \code{macpath}. Thus, (given -the proper imports), \code{os.path.split(\var{file})} is equivalent to but -more portable than \code{posixpath.split(\var{file})}. -\end{datadesc} - -\begin{datadesc}{curdir} -The constant string used by the OS to refer to the current directory, -e.g. \code{'.'} for POSIX or \code{':'} for the Mac. -\end{datadesc} - -\begin{datadesc}{pardir} -The constant string used by the OS to refer to the parent directory, -e.g. \code{'..'} for POSIX or \code{'::'} for the Mac. -\end{datadesc} - -\begin{datadesc}{sep} -The character used by the OS to separate pathname components, e.g.\ -\code{'/'} for POSIX or \code{':'} for the Mac. Note that knowing this -is not sufficient to be able to parse or concatenate pathnames---better -use \code{os.path.split()} and \code{os.path.join()}---but it is -occasionally useful. -\end{datadesc} - -\begin{datadesc}{pathsep} -The character conventionally used by the OS to separate search patch -components (as in \code{\$PATH}), e.g.\ \code{':'} for POSIX or -\code{';'} for MS-DOS. -\end{datadesc} - -\begin{datadesc}{defpath} -The default search path used by \code{os.exec*p*()} if the environment -doesn't have a \code{'PATH'} key. -\end{datadesc} - -\begin{funcdesc}{execl}{path\, arg0\, arg1\, ...} -This is equivalent to -\code{os.execv(\var{path}, (\var{arg0}, \var{arg1}, ...))}. -\end{funcdesc} - -\begin{funcdesc}{execle}{path\, arg0\, arg1\, ...\, env} -This is equivalent to -\code{os.execve(\var{path}, (\var{arg0}, \var{arg1}, ...), \var{env})}. -\end{funcdesc} - -\begin{funcdesc}{execlp}{path\, arg0\, arg1\, ...} -This is equivalent to -\code{os.execvp(\var{path}, (\var{arg0}, \var{arg1}, ...))}. -\end{funcdesc} - -\begin{funcdesc}{execvp}{path\, args} -This is like \code{os.execv(\var{path}, \var{args})} but duplicates -the shell's actions in searching for an executable file in a list of -directories. The directory list is obtained from -\code{os.environ['PATH']}. -\end{funcdesc} - -\begin{funcdesc}{execvpe}{path\, args\, env} -This is a cross between \code{os.execve()} and \code{os.execvp()}. -The directory list is obtained from \code{\var{env}['PATH']}. -\end{funcdesc} - -(The functions \code{os.execv()} and \code{execve()} are not -documented here, since they are implemented by the OS dependent -module. If the OS dependent module doesn't define either of these, -the functions that rely on it will raise an exception. They are -documented in the section on module \code{posix}, together with all -other functions that \code{os} imports from the OS dependent module.) diff --git a/Doc/lib/libpanel.tex b/Doc/lib/libpanel.tex deleted file mode 100644 index b82bf98bfe..0000000000 --- a/Doc/lib/libpanel.tex +++ /dev/null @@ -1,66 +0,0 @@ -\section{Standard Module \sectcode{panel}} -\stmodindex{panel} - -\strong{Please note:} The FORMS library, to which the \code{fl} module described -above interfaces, is a simpler and more accessible user interface -library for use with GL than the Panel Module (besides also being by a -Dutch author). - -This module should be used instead of the built-in module -\code{pnl} -to interface with the -{\em Panel Library}. - -The module is too large to document here in its entirety. -One interesting function: - -\renewcommand{\indexsubitem}{(in module panel)} -\begin{funcdesc}{defpanellist}{filename} -Parses a panel description file containing S-expressions written by the -{\em Panel Editor} -that accompanies the Panel Library and creates the described panels. -It returns a list of panel objects. -\end{funcdesc} - -\strong{Warning:} -the Python interpreter will dump core if you don't create a GL window -before calling -\code{panel.mkpanel()} -or -\code{panel.defpanellist()}. - -\section{Standard Module \sectcode{panelparser}} -\stmodindex{panelparser} - -This module defines a self-contained parser for S-expressions as output -by the Panel Editor (which is written in Scheme so it can't help writing -S-expressions). -The relevant function is -\code{panelparser.parse_file(\var{file})} -which has a file object (not a filename!) as argument and returns a list -of parsed S-expressions. -Each S-expression is converted into a Python list, with atoms converted -to Python strings and sub-expressions (recursively) to Python lists. -For more details, read the module file. -% XXXXJH should be funcdesc, I think - -\section{Built-in Module \sectcode{pnl}} -\bimodindex{pnl} - -This module provides access to the -{\em Panel Library} -built by NASA Ames (to get it, send e-mail to -{\tt panel-request@nas.nasa.gov}). -All access to it should be done through the standard module -\code{panel}, -which transparantly exports most functions from -\code{pnl} -but redefines -\code{pnl.dopanel()}. - -\strong{Warning:} -the Python interpreter will dump core if you don't create a GL window -before calling -\code{pnl.mkpanel()}. - -The module is too large to document here in its entirety. diff --git a/Doc/lib/libparser.tex b/Doc/lib/libparser.tex deleted file mode 100644 index 1f5d4fda75..0000000000 --- a/Doc/lib/libparser.tex +++ /dev/null @@ -1,250 +0,0 @@ -% libparser.tex -% -% Introductory documentation for the new parser built-in module. -% -% Copyright 1995 Virginia Polytechnic Institute and State University -% and Fred L. Drake, Jr. This copyright notice must be distributed on -% all copies, but this document otherwise may be distributed as part -% of the Python distribution. No fee may be charged for this document -% in any representation, either on paper or electronically. This -% restriction does not affect other elements in a distributed package -% in any way. -% - -\section{Built-in Module \sectcode{parser}} -\bimodindex{parser} - - -% ==== 2. ==== -% Give a short overview of what the module does. -% If it is platform specific, mention this. -% Mention other important restrictions or general operating principles. - -The \code{parser} module provides an interface to Python's internal -parser and byte-code compiler. The primary purpose for this interface -is to allow Python code to edit the parse tree of a Python expression -and create executable code from this. This can be better than trying -to parse and modify an arbitrary Python code fragment as a string, and -ensures that parsing is performed in a manner identical to the code -forming the application. It's also faster. - -There are a few things to note about this module which are important -to making use of the data structures created. This is not a tutorial -on editing the parse trees for Python code. - -Most importantly, a good understanding of the Python grammar processed -by the internal parser is required. For full information on the -language syntax, refer to the Language Reference. The parser itself -is created from a grammar specification defined in the file -\code{Grammar/Grammar} in the standard Python distribution. The parse -trees stored in the ``AST objects'' created by this module are the -actual output from the internal parser when created by the -\code{expr()} or \code{suite()} functions, described below. The AST -objects created by \code{tuple2ast()} faithfully simulate those -structures. - -Each element of the tuples returned by \code{ast2tuple()} has a simple -form. Tuples representing non-terminal elements in the grammar always -have a length greater than one. The first element is an integer which -identifies a production in the grammar. These integers are given -symbolic names in the C header file \code{Include/graminit.h} and the -Python module \code{Lib/symbol.py}. Each additional element of the -tuple represents a component of the production as recognized in the -input string: these are always tuples which have the same form as the -parent. An important aspect of this structure which should be noted -is that keywords used to identify the parent node type, such as the -keyword \code{if} in an \emph{if\_stmt}, are included in the node tree -without any special treatment. For example, the \code{if} keyword is -represented by the tuple \code{(1, 'if')}, where \code{1} is the -numeric value associated with all \code{NAME} elements, including -variable and function names defined by the user. - -Terminal elements are represented in much the same way, but without -any child elements and the addition of the source text which was -identified. The example of the \code{if} keyword above is -representative. The various types of terminal symbols are defined in -the C header file \code{Include/token.h} and the Python module -\code{Lib/token.py}. - -The AST objects are not actually required to support the functionality -of this module, but are provided for three purposes: to allow an -application to amortize the cost of processing complex parse trees, to -provide a parse tree representation which conserves memory space when -compared to the Python tuple representation, and to ease the creation -of additional modules in C which manipulate parse trees. A simple -``wrapper'' module may be created in Python if desired to hide the use -of AST objects. - - -% ==== 3. ==== -% List the public functions defined by the module. Begin with a -% standard phrase. You may also list the exceptions and other data -% items defined in the module, insofar as they are important for the -% user. - -The \code{parser} module defines the following functions: - -% ---- 3.1. ---- -% Redefine the ``indexsubitem'' macro to point to this module -% (alternatively, you can put this at the top of the file): - -\renewcommand{\indexsubitem}{(in module parser)} - -% ---- 3.2. ---- -% For each function, use a ``funcdesc'' block. This has exactly two -% parameters (each parameters is contained in a set of curly braces): -% the first parameter is the function name (this automatically -% generates an index entry); the second parameter is the function's -% argument list. If there are no arguments, use an empty pair of -% curly braces. If there is more than one argument, separate the -% arguments with backslash-comma. Optional parts of the parameter -% list are contained in \optional{...} (this generates a set of square -% brackets around its parameter). Arguments are automatically set in -% italics in the parameter list. Each argument should be mentioned at -% least once in the description; each usage (even inside \code{...}) -% should be enclosed in \var{...}. - -\begin{funcdesc}{ast2tuple}{ast} -This function accepts an AST object from the caller in -\code{\var{ast}} and returns a Python tuple representing the -equivelent parse tree. The resulting tuple representation can be used -for inspection or the creation of a new parse tree in tuple form. -This function does not fail so long as memory is available to build -the tuple representation. -\end{funcdesc} - - -\begin{funcdesc}{compileast}{ast\optional{\, filename \code{= '<ast>'}}} -The Python byte compiler can be invoked on an AST object to produce -code objects which can be used as part of an \code{exec} statement or -a call to the built-in \code{eval()} function. This function provides -the interface to the compiler, passing the internal parse tree from -\code{\var{ast}} to the parser, using the source file name specified -by the \code{\var{filename}} parameter. The default value supplied -for \code{\var{filename}} indicates that the source was an AST object. -\end{funcdesc} - - -\begin{funcdesc}{expr}{string} -The \code{expr()} function parses the parameter \code{\var{string}} -as if it were an input to \code{compile(\var{string}, 'eval')}. If -the parse succeeds, an AST object is created to hold the internal -parse tree representation, otherwise an appropriate exception is -thrown. -\end{funcdesc} - - -\begin{funcdesc}{isexpr}{ast} -When \code{\var{ast}} represents an \code{'eval'} form, this function -returns a true value (\code{1}), otherwise it returns false -(\code{0}). This is useful, since code objects normally cannot be -queried for this information using existing built-in functions. Note -that the code objects created by \code{compileast()} cannot be queried -like this either, and are identical to those created by the built-in -\code{compile()} function. -\end{funcdesc} - - -\begin{funcdesc}{issuite}{ast} -This function mirrors \code{isexpr()} in that it reports whether an -AST object represents a suite of statements. It is not safe to assume -that this function is equivelent to \code{not isexpr(\var{ast})}, as -additional syntactic fragments may be supported in the future. -\end{funcdesc} - - -\begin{funcdesc}{suite}{string} -The \code{suite()} function parses the parameter \code{\var{string}} -as if it were an input to \code{compile(\var{string}, 'exec')}. If -the parse succeeds, an AST object is created to hold the internal -parse tree representation, otherwise an appropriate exception is -thrown. -\end{funcdesc} - - -\begin{funcdesc}{tuple2ast}{tuple} -This function accepts a parse tree represented as a tuple and builds -an internal representation if possible. If it can validate that the -tree conforms to the Python syntax and all nodes are valid node types -in the host version of Python, an AST object is created from the -internal representation and returned to the called. If there is a -problem creating the internal representation, or if the tree cannot be -validated, a \code{ParserError} exception is thrown. An AST object -created this way should not be assumed to compile correctly; normal -exceptions thrown by compilation may still be initiated when the AST -object is passed to \code{compileast()}. This will normally indicate -problems not related to syntax (such as a \code{MemoryError} -exception). -\end{funcdesc} - - -% --- 3.4. --- -% Exceptions are described using a ``excdesc'' block. This has only -% one parameter: the exception name. - -\subsection{Exceptions and Error Handling} - -The parser module defines a single exception, but may also pass other -built-in exceptions from other portions of the Python runtime -environment. See each function for information about the exceptions -it can raise. - -\begin{excdesc}{ParserError} -Exception raised when a failure occurs within the parser module. This -is generally produced for validation failures rather than the built in -\code{SyntaxError} thrown during normal parsing. -The exception argument is either a string describing the reason of the -failure or a tuple containing a tuple causing the failure from a parse -tree passed to \code{tuple2ast()} and an explanatory string. Calls to -\code{tuple2ast()} need to be able to handle either type of exception, -while calls to other functions in the module will only need to be -aware of the simple string values. -\end{excdesc} - -Note that the functions \code{compileast()}, \code{expr()}, and -\code{suite()} may throw exceptions which are normally thrown by the -parsing and compilation process. These include the built in -exceptions \code{MemoryError}, \code{OverflowError}, -\code{SyntaxError}, and \code{SystemError}. In these cases, these -exceptions carry all the meaning normally associated with them. Refer -to the descriptions of each function for detailed information. - -% ---- 3.5. ---- -% There is no standard block type for classes. I generally use -% ``funcdesc'' blocks, since class instantiation looks very much like -% a function call. - - -% ==== 4. ==== -% Now is probably a good time for a complete example. (Alternatively, -% an example giving the flavor of the module may be given before the -% detailed list of functions.) - -\subsection{Example} - -A simple example: - -\begin{verbatim} ->>> import parser ->>> ast = parser.expr('a + 5') ->>> code = parser.compileast(ast) ->>> a = 5 ->>> eval(code) -10 -\end{verbatim} - - -\subsection{AST Objects} - -AST objects (returned by \code{expr()}, \code{suite()}, and -\code{tuple2ast()}, described above) have no methods of their own. -Some of the functions defined which accept an AST object as their -first argument may change to object methods in the future. - -Ordered and equality comparisons are supported between AST objects. - -\renewcommand{\indexsubitem}{(ast method)} - -%\begin{funcdesc}{empty}{} -%Empty the can into the trash. -%\end{funcdesc} diff --git a/Doc/lib/libpdb.tex b/Doc/lib/libpdb.tex deleted file mode 100644 index a439363734..0000000000 --- a/Doc/lib/libpdb.tex +++ /dev/null @@ -1,303 +0,0 @@ -\chapter{The Python Debugger} -\stmodindex{pdb} -\index{debugging} - -\renewcommand{\indexsubitem}{(in module pdb)} - -The module \code{pdb} defines an interactive source code debugger for -Python programs. It supports setting breakpoints and single stepping -at the source line level, inspection of stack frames, source code -listing, and evaluation of arbitrary Python code in the context of any -stack frame. It also supports post-mortem debugging and can be called -under program control. - -The debugger is extensible --- it is actually defined as a class -\code{Pdb}. This is currently undocumented but easily understood by -reading the source. The extension interface uses the (also -undocumented) modules \code{bdb} and \code{cmd}. -\ttindex{Pdb} -\ttindex{bdb} -\ttindex{cmd} - -A primitive windowing version of the debugger also exists --- this is -module \code{wdb}, which requires STDWIN (see the chapter on STDWIN -specific modules). -\index{stdwin} -\ttindex{wdb} - -The debugger's prompt is ``\code{(Pdb) }''. -Typical usage to run a program under control of the debugger is: - -\begin{verbatim} ->>> import pdb ->>> import mymodule ->>> pdb.run('mymodule.test()') -> <string>(0)?() -(Pdb) continue -> <string>(1)?() -(Pdb) continue -NameError: 'spam' -> <string>(1)?() -(Pdb) -\end{verbatim} - -Typical usage to inspect a crashed program is: - -\begin{verbatim} ->>> import pdb ->>> import mymodule ->>> mymodule.test() -Traceback (innermost last): - File "<stdin>", line 1, in ? - File "./mymodule.py", line 4, in test - test2() - File "./mymodule.py", line 3, in test2 - print spam -NameError: spam ->>> pdb.pm() -> ./mymodule.py(3)test2() --> print spam -(Pdb) -\end{verbatim} - -The module defines the following functions; each enters the debugger -in a slightly different way: - -\begin{funcdesc}{run}{statement\optional{\, globals\optional{\, locals}}} -Execute the \var{statement} (given as a string) under debugger -control. The debugger prompt appears before any code is executed; you -can set breakpoints and type \code{continue}, or you can step through -the statement using \code{step} or \code{next} (all these commands are -explained below). The optional \var{globals} and \var{locals} -arguments specify the environment in which the code is executed; by -default the dictionary of the module \code{__main__} is used. (See -the explanation of the \code{exec} statement or the \code{eval()} -built-in function.) -\end{funcdesc} - -\begin{funcdesc}{runeval}{expression\optional{\, globals\optional{\, locals}}} -Evaluate the \var{expression} (given as a a string) under debugger -control. When \code{runeval()} returns, it returns the value of the -expression. Otherwise this function is similar to -\code{run()}. -\end{funcdesc} - -\begin{funcdesc}{runcall}{function\optional{\, argument\, ...}} -Call the \var{function} (a function or method object, not a string) -with the given arguments. When \code{runcall()} returns, it returns -whatever the function call returned. The debugger prompt appears as -soon as the function is entered. -\end{funcdesc} - -\begin{funcdesc}{set_trace}{} -Enter the debugger at the calling stack frame. This is useful to -hard-code a breakpoint at a given point in a program, even if the code -is not otherwise being debugged (e.g. when an assertion fails). -\end{funcdesc} - -\begin{funcdesc}{post_mortem}{traceback} -Enter post-mortem debugging of the given \var{traceback} object. -\end{funcdesc} - -\begin{funcdesc}{pm}{} -Enter post-mortem debugging of the traceback found in -\code{sys.last_traceback}. -\end{funcdesc} - -\section{Debugger Commands} - -The debugger recognizes the following commands. Most commands can be -abbreviated to one or two letters; e.g. ``\code{h(elp)}'' means that -either ``\code{h}'' or ``\code{help}'' can be used to enter the help -command (but not ``\code{he}'' or ``\code{hel}'', nor ``\code{H}'' or -``\code{Help} or ``\code{HELP}''). Arguments to commands must be -separated by whitespace (spaces or tabs). Optional arguments are -enclosed in square brackets (``\code{[]}'') in the command syntax; the -square brackets must not be typed. Alternatives in the command syntax -are separated by a vertical bar (``\code{|}''). - -Entering a blank line repeats the last command entered. Exception: if -the last command was a ``\code{list}'' command, the next 11 lines are -listed. - -Commands that the debugger doesn't recognize are assumed to be Python -statements and are executed in the context of the program being -debugged. Python statements can also be prefixed with an exclamation -point (``\code{!}''). This is a powerful way to inspect the program -being debugged; it is even possible to change a variable or call a -function. When an -exception occurs in such a statement, the exception name is printed -but the debugger's state is not changed. - -\begin{description} - -\item[h(elp) [\var{command}]] - -Without argument, print the list of available commands. -With a \var{command} as argument, print help about that command. -``\code{help pdb}'' displays the full documentation file; if the -environment variable \code{PAGER} is defined, the file is piped -through that command instead. Since the \var{command} argument must be -an identifier, ``\code{help exec}'' must be entered to get help on the -``\code{!}'' command. - -\item[w(here)] - -Print a stack trace, with the most recent frame at the bottom. -An arrow indicates the current frame, which determines the -context of most commands. - -\item[d(own)] - -Move the current frame one level down in the stack trace -(to an older frame). - -\item[u(p)] - -Move the current frame one level up in the stack trace -(to a newer frame). - -\item[b(reak) [\var{lineno}\code{|}\var{function}]] - -With a \var{lineno} argument, set a break there in the current -file. With a \var{function} argument, set a break at the entry of -that function. Without argument, list all breaks. - -\item[cl(ear) [\var{lineno}]] - -With a \var{lineno} argument, clear that break in the current file. -Without argument, clear all breaks (but first ask confirmation). - -\item[s(tep)] - -Execute the current line, stop at the first possible occasion -(either in a function that is called or on the next line in the -current function). - -\item[n(ext)] - -Continue execution until the next line in the current function -is reached or it returns. (The difference between \code{next} and -\code{step} is that \code{step} stops inside a called function, while -\code{next} executes called functions at (nearly) full speed, only -stopping at the next line in the current function.) - -\item[r(eturn)] - -Continue execution until the current function returns. - -\item[c(ont(inue))] - -Continue execution, only stop when a breakpoint is encountered. - -\item[l(ist) [\var{first} [, \var{last}]]] - -List source code for the current file. Without arguments, list 11 -lines around the current line or continue the previous listing. With -one argument, list 11 lines around at that line. With two arguments, -list the given range; if the second argument is less than the first, -it is interpreted as a count. - -\item[a(rgs)] - -Print the argument list of the current function. - -\item[p \var{expression}] - -Evaluate the \var{expression} in the current context and print its -value. (Note: \code{print} can also be used, but is not a debugger -command --- this executes the Python \code{print} statement.) - -\item[[!] \var{statement}] - -Execute the (one-line) \var{statement} in the context of -the current stack frame. -The exclamation point can be omitted unless the first word -of the statement resembles a debugger command. -To set a global variable, you can prefix the assignment -command with a ``\code{global}'' command on the same line, e.g.: -\begin{verbatim} -(Pdb) global list_options; list_options = ['-l'] -(Pdb) -\end{verbatim} - -\item[q(uit)] - -Quit from the debugger. -The program being executed is aborted. - -\end{description} - -\section{How It Works} - -Some changes were made to the interpreter: - -\begin{itemize} -\item sys.settrace(func) sets the global trace function -\item there can also a local trace function (see later) -\end{itemize} - -Trace functions have three arguments: (\var{frame}, \var{event}, \var{arg}) - -\begin{description} - -\item[\var{frame}] is the current stack frame - -\item[\var{event}] is a string: \code{'call'}, \code{'line'}, \code{'return'} -or \code{'exception'} - -\item[\var{arg}] is dependent on the event type - -\end{description} - -A trace function should return a new trace function or None. -Class methods are accepted (and most useful!) as trace methods. - -The events have the following meaning: - -\begin{description} - -\item[\code{'call'}] -A function is called (or some other code block entered). The global -trace function is called; arg is the argument list to the function; -the return value specifies the local trace function. - -\item[\code{'line'}] -The interpreter is about to execute a new line of code (sometimes -multiple line events on one line exist). The local trace function is -called; arg in None; the return value specifies the new local trace -function. - -\item[\code{'return'}] -A function (or other code block) is about to return. The local trace -function is called; arg is the value that will be returned. The trace -function's return value is ignored. - -\item[\code{'exception'}] -An exception has occurred. The local trace function is called; arg is -a triple (exception, value, traceback); the return value specifies the -new local trace function - -\end{description} - -Note that as an exception is propagated down the chain of callers, an -\code{'exception'} event is generated at each level. - -Stack frame objects have the following read-only attributes: - -\begin{description} -\item[f_code] the code object being executed -\item[f_lineno] the current line number (\code{-1} for \code{'call'} events) -\item[f_back] the stack frame of the caller, or None -\item[f_locals] dictionary containing local name bindings -\item[f_globals] dictionary containing global name bindings -\end{description} - -Code objects have the following read-only attributes: - -\begin{description} -\item[co_code] the code string -\item[co_names] the list of names used by the code -\item[co_consts] the list of (literal) constants used by the code -\item[co_filename] the filename from which the code was compiled -\end{description} diff --git a/Doc/lib/libpickle.tex b/Doc/lib/libpickle.tex deleted file mode 100644 index 579992f049..0000000000 --- a/Doc/lib/libpickle.tex +++ /dev/null @@ -1,229 +0,0 @@ -\section{Standard Module \sectcode{pickle}} -\stmodindex{pickle} -\index{persistency} -\indexii{persistent}{objects} -\indexii{serializing}{objects} -\indexii{marshalling}{objects} -\indexii{flattening}{objects} -\indexii{pickling}{objects} - -\renewcommand{\indexsubitem}{(in module pickle)} - -The \code{pickle} module implements a basic but powerful algorithm for -``pickling'' (a.k.a.\ serializing, marshalling or flattening) nearly -arbitrary Python objects. This is the act of converting objects to a -stream of bytes (and back: ``unpickling''). -This is a more primitive notion than -persistency --- although \code{pickle} reads and writes file objects, -it does not handle the issue of naming persistent objects, nor the -(even more complicated) area of concurrent access to persistent -objects. The \code{pickle} module can transform a complex object into -a byte stream and it can transform the byte stream into an object with -the same internal structure. The most obvious thing to do with these -byte streams is to write them onto a file, but it is also conceivable -to send them across a network or store them in a database. The module -\code{shelve} provides a simple interface to pickle and unpickle -objects on ``dbm''-style database files. -\stmodindex{shelve} - -Unlike the built-in module \code{marshal}, \code{pickle} handles the -following correctly: -\stmodindex{marshal} - -\begin{itemize} - -\item recursive objects (objects containing references to themselves) - -\item object sharing (references to the same object in different places) - -\item user-defined classes and their instances - -\end{itemize} - -The data format used by \code{pickle} is Python-specific. This has -the advantage that there are no restrictions imposed by external -standards such as CORBA (which probably can't represent pointer -sharing or recursive objects); however it means that non-Python -programs may not be able to reconstruct pickled Python objects. - -The \code{pickle} data format uses a printable \ASCII{} representation. -This is slightly more voluminous than a binary representation. -However, small integers actually take {\em less} space when -represented as minimal-size decimal strings than when represented as -32-bit binary numbers, and strings are only much longer if they -contain many control characters or 8-bit characters. The big -advantage of using printable \ASCII{} (and of some other characteristics -of \code{pickle}'s representation) is that for debugging or recovery -purposes it is possible for a human to read the pickled file with a -standard text editor. (I could have gone a step further and used a -notation like S-expressions, but the parser -(currently written in Python) would have been -considerably more complicated and slower, and the files would probably -have become much larger.) - -The \code{pickle} module doesn't handle code objects, which the -\code{marshal} module does. I suppose \code{pickle} could, and maybe -it should, but there's probably no great need for it right now (as -long as \code{marshal} continues to be used for reading and writing -code objects), and at least this avoids the possibility of smuggling -Trojan horses into a program. -\stmodindex{marshal} - -For the benefit of persistency modules written using \code{pickle}, it -supports the notion of a reference to an object outside the pickled -data stream. Such objects are referenced by a name, which is an -arbitrary string of printable \ASCII{} characters. The resolution of -such names is not defined by the \code{pickle} module --- the -persistent object module will have to implement a method -\code{persistent_load}. To write references to persistent objects, -the persistent module must define a method \code{persistent_id} which -returns either \code{None} or the persistent ID of the object. - -There are some restrictions on the pickling of class instances. - -First of all, the class must be defined at the top level in a module. - -\renewcommand{\indexsubitem}{(pickle protocol)} - -Next, it must normally be possible to create class instances by -calling the class without arguments. If this is undesirable, the -class can define a method \code{__getinitargs__()}, which should -return a {\em tuple} containing the arguments to be passed to the -class constructor (\code{__init__()}). -\ttindex{__getinitargs__} -\ttindex{__init__} - -Classes can further influence how their instances are pickled --- if the class -defines the method \code{__getstate__()}, it is called and the return -state is pickled as the contents for the instance, and if the class -defines the method \code{__setstate__()}, it is called with the -unpickled state. (Note that these methods can also be used to -implement copying class instances.) If there is no -\code{__getstate__()} method, the instance's \code{__dict__} is -pickled. If there is no \code{__setstate__()} method, the pickled -object must be a dictionary and its items are assigned to the new -instance's dictionary. (If a class defines both \code{__getstate__()} -and \code{__setstate__()}, the state object needn't be a dictionary ---- these methods can do what they want.) This protocol is also used -by the shallow and deep copying operations defined in the \code{copy} -module. -\ttindex{__getstate__} -\ttindex{__setstate__} -\ttindex{__dict__} - -Note that when class instances are pickled, their class's code and -data are not pickled along with them. Only the instance data are -pickled. This is done on purpose, so you can fix bugs in a class or -add methods and still load objects that were created with an earlier -version of the class. If you plan to have long-lived objects that -will see many versions of a class, it may be worthwhile to put a version -number in the objects so that suitable conversions can be made by the -class's \code{__setstate__()} method. - -When a class itself is pickled, only its name is pickled --- the class -definition is not pickled, but re-imported by the unpickling process. -Therefore, the restriction that the class must be defined at the top -level in a module applies to pickled classes as well. - -\renewcommand{\indexsubitem}{(in module pickle)} - -The interface can be summarized as follows. - -To pickle an object \code{x} onto a file \code{f}, open for writing: - -\begin{verbatim} -p = pickle.Pickler(f) -p.dump(x) -\end{verbatim} - -A shorthand for this is: - -\begin{verbatim} -pickle.dump(x, f) -\end{verbatim} - -To unpickle an object \code{x} from a file \code{f}, open for reading: - -\begin{verbatim} -u = pickle.Unpickler(f) -x = u.load() -\end{verbatim} - -A shorthand is: - -\begin{verbatim} -x = pickle.load(f) -\end{verbatim} - -The \code{Pickler} class only calls the method \code{f.write} with a -string argument. The \code{Unpickler} calls the methods \code{f.read} -(with an integer argument) and \code{f.readline} (without argument), -both returning a string. It is explicitly allowed to pass non-file -objects here, as long as they have the right methods. -\ttindex{Unpickler} -\ttindex{Pickler} - -The following types can be pickled: -\begin{itemize} - -\item \code{None} - -\item integers, long integers, floating point numbers - -\item strings - -\item tuples, lists and dictionaries containing only picklable objects - -\item classes that are defined at the top level in a module - -\item instances of such classes whose \code{__dict__} or -\code{__setstate__()} is picklable - -\end{itemize} - -Attempts to pickle unpicklable objects will raise the -\code{PicklingError} exception; when this happens, an unspecified -number of bytes may have been written to the file. - -It is possible to make multiple calls to the \code{dump()} method of -the same \code{Pickler} instance. These must then be matched to the -same number of calls to the \code{load()} instance of the -corresponding \code{Unpickler} instance. If the same object is -pickled by multiple \code{dump()} calls, the \code{load()} will all -yield references to the same object. {\em Warning}: this is intended -for pickling multiple objects without intervening modifications to the -objects or their parts. If you modify an object and then pickle it -again using the same \code{Pickler} instance, the object is not -pickled again --- a reference to it is pickled and the -\code{Unpickler} will return the old value, not the modified one. -(There are two problems here: (a) detecting changes, and (b) -marshalling a minimal set of changes. I have no answers. Garbage -Collection may also become a problem here.) - -Apart from the \code{Pickler} and \code{Unpickler} classes, the -module defines the following functions, and an exception: - -\begin{funcdesc}{dump}{object\, file} -Write a pickled representation of \var{obect} to the open file object -\var{file}. This is equivalent to \code{Pickler(file).dump(object)}. -\end{funcdesc} - -\begin{funcdesc}{load}{file} -Read a pickled object from the open file object \var{file}. This is -equivalent to \code{Unpickler(file).load()}. -\end{funcdesc} - -\begin{funcdesc}{dumps}{object} -Return the pickled representation of the object as a string, instead -of writing it to a file. -\end{funcdesc} - -\begin{funcdesc}{loads}{string} -Read a pickled object from a string instead of a file. Characters in -the string past the pickled object's representation are ignored. -\end{funcdesc} - -\begin{excdesc}{PicklingError} -This exception is raised when an unpicklable object is passed to -\code{Pickler.dump()}. -\end{excdesc} diff --git a/Doc/lib/libposix.tex b/Doc/lib/libposix.tex deleted file mode 100644 index 6696a28b73..0000000000 --- a/Doc/lib/libposix.tex +++ /dev/null @@ -1,371 +0,0 @@ -\section{Built-in Module \sectcode{posix}} -\bimodindex{posix} - -This module provides access to operating system functionality that is -standardized by the C Standard and the POSIX standard (a thinly disguised -\UNIX{} interface). - -\strong{Do not import this module directly.} Instead, import the -module \code{os}, which provides a \emph{portable} version of this -interface. On \UNIX{}, the \code{os} module provides a superset of -the \code{posix} interface. On non-\UNIX{} operating systems the -\code{posix} module is not available, but a subset is always available -through the \code{os} interface. Once \code{os} is imported, there is -\emph{no} performance penalty in using it instead of -\code{posix}. -\stmodindex{os} - -The descriptions below are very terse; refer to the -corresponding \UNIX{} manual entry for more information. Arguments -called \var{path} refer to a pathname given as a string. - -Errors are reported as exceptions; the usual exceptions are given -for type errors, while errors reported by the system calls raise -\code{posix.error}, described below. - -Module \code{posix} defines the following data items: - -\renewcommand{\indexsubitem}{(data in module posix)} -\begin{datadesc}{environ} -A dictionary representing the string environment at the time -the interpreter was started. -For example, -\code{posix.environ['HOME']} -is the pathname of your home directory, equivalent to -\code{getenv("HOME")} -in C. -Modifying this dictionary does not affect the string environment -passed on by \code{execv()}, \code{popen()} or \code{system()}; if you -need to change the environment, pass \code{environ} to \code{execve()} -or add variable assignments and export statements to the command -string for \code{system()} or \code{popen()}.% -\footnote{The problem with automatically passing on \code{environ} is -that there is no portable way of changing the environment.} -\end{datadesc} - -\renewcommand{\indexsubitem}{(exception in module posix)} -\begin{excdesc}{error} -This exception is raised when a POSIX function returns a -POSIX-related error (e.g., not for illegal argument types). Its -string value is \code{'posix.error'}. The accompanying value is a -pair containing the numeric error code from \code{errno} and the -corresponding string, as would be printed by the C function -\code{perror()}. -\end{excdesc} - -It defines the following functions and constants: - -\renewcommand{\indexsubitem}{(in module posix)} -\begin{funcdesc}{chdir}{path} -Change the current working directory to \var{path}. -\end{funcdesc} - -\begin{funcdesc}{chmod}{path\, mode} -Change the mode of \var{path} to the numeric \var{mode}. -\end{funcdesc} - -\begin{funcdesc}{chown}{path\, uid, gid} -Change the owner and group id of \var{path} to the numeric \var{uid} -and \var{gid}. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{close}{fd} -Close file descriptor \var{fd}. - -Note: this function is intended for low-level I/O and must be applied -to a file descriptor as returned by \code{posix.open()} or -\code{posix.pipe()}. To close a ``file object'' returned by the -built-in function \code{open} or by \code{posix.popen} or -\code{posix.fdopen}, use its \code{close()} method. -\end{funcdesc} - -\begin{funcdesc}{dup}{fd} -Return a duplicate of file descriptor \var{fd}. -\end{funcdesc} - -\begin{funcdesc}{dup2}{fd\, fd2} -Duplicate file descriptor \var{fd} to \var{fd2}, closing the latter -first if necessary. Return \code{None}. -\end{funcdesc} - -\begin{funcdesc}{execv}{path\, args} -Execute the executable \var{path} with argument list \var{args}, -replacing the current process (i.e., the Python interpreter). -The argument list may be a tuple or list of strings. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{execve}{path\, args\, env} -Execute the executable \var{path} with argument list \var{args}, -and environment \var{env}, -replacing the current process (i.e., the Python interpreter). -The argument list may be a tuple or list of strings. -The environment must be a dictionary mapping strings to strings. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{_exit}{n} -Exit to the system with status \var{n}, without calling cleanup -handlers, flushing stdio buffers, etc. -(Not on MS-DOS.) - -Note: the standard way to exit is \code{sys.exit(\var{n})}. -\code{posix._exit()} should normally only be used in the child process -after a \code{fork()}. -\end{funcdesc} - -\begin{funcdesc}{fdopen}{fd\optional{\, mode\optional{\, bufsize}}} -Return an open file object connected to the file descriptor \var{fd}. -The \var{mode} and \var{bufsize} arguments have the same meaning as -the corresponding arguments to the built-in \code{open()} function. -\end{funcdesc} - -\begin{funcdesc}{fork}{} -Fork a child process. Return 0 in the child, the child's process id -in the parent. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{fstat}{fd} -Return status for file descriptor \var{fd}, like \code{stat()}. -\end{funcdesc} - -\begin{funcdesc}{getcwd}{} -Return a string representing the current working directory. -\end{funcdesc} - -\begin{funcdesc}{getegid}{} -Return the current process's effective group id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{geteuid}{} -Return the current process's effective user id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{getgid}{} -Return the current process's group id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{getpid}{} -Return the current process id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{getppid}{} -Return the parent's process id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{getuid}{} -Return the current process's user id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{kill}{pid\, sig} -Kill the process \var{pid} with signal \var{sig}. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{link}{src\, dst} -Create a hard link pointing to \var{src} named \var{dst}. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{listdir}{path} -Return a list containing the names of the entries in the directory. -The list is in arbitrary order. It does not include the special -entries \code{'.'} and \code{'..'} even if they are present in the -directory. -\end{funcdesc} - -\begin{funcdesc}{lseek}{fd\, pos\, how} -Set the current position of file descriptor \var{fd} to position -\var{pos}, modified by \var{how}: 0 to set the position relative to -the beginning of the file; 1 to set it relative to the current -position; 2 to set it relative to the end of the file. -\end{funcdesc} - -\begin{funcdesc}{lstat}{path} -Like \code{stat()}, but do not follow symbolic links. (On systems -without symbolic links, this is identical to \code{posix.stat}.) -\end{funcdesc} - -\begin{funcdesc}{mkdir}{path\, mode} -Create a directory named \var{path} with numeric mode \var{mode}. -\end{funcdesc} - -\begin{funcdesc}{nice}{increment} -Add \var{incr} to the process' ``niceness''. Return the new niceness. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{open}{file\, flags\, mode} -Open the file \var{file} and set various flags according to -\var{flags} and possibly its mode according to \var{mode}. -Return the file descriptor for the newly opened file. - -Note: this function is intended for low-level I/O. For normal usage, -use the built-in function \code{open}, which returns a ``file object'' -with \code{read()} and \code{write()} methods (and many more). -\end{funcdesc} - -\begin{funcdesc}{pipe}{} -Create a pipe. Return a pair of file descriptors \code{(r, w)} -usable for reading and writing, respectively. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{popen}{command\optional{\, mode\optional{\, bufsize}}} -Open a pipe to or from \var{command}. The return value is an open -file object connected to the pipe, which can be read or written -depending on whether \var{mode} is \code{'r'} (default) or \code{'w'}. -The \var{bufsize} argument has the same meaning as the corresponding -argument to the built-in \code{open()} function. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{read}{fd\, n} -Read at most \var{n} bytes from file descriptor \var{fd}. -Return a string containing the bytes read. - -Note: this function is intended for low-level I/O and must be applied -to a file descriptor as returned by \code{posix.open()} or -\code{posix.pipe()}. To read a ``file object'' returned by the -built-in function \code{open} or by \code{posix.popen} or -\code{posix.fdopen}, or \code{sys.stdin}, use its -\code{read()} or \code{readline()} methods. -\end{funcdesc} - -\begin{funcdesc}{readlink}{path} -Return a string representing the path to which the symbolic link -points. (On systems without symbolic links, this always raises -\code{posix.error}.) -\end{funcdesc} - -\begin{funcdesc}{remove}{path} -Remove the file \var{path}. See \code{rmdir} below to remove a directory. -\end{funcdesc} - -\begin{funcdesc}{rename}{src\, dst} -Rename the file or directory \var{src} to \var{dst}. -\end{funcdesc} - -\begin{funcdesc}{rmdir}{path} -Remove the directory \var{path}. -\end{funcdesc} - -\begin{funcdesc}{setgid}{gid} -Set the current process's group id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{setuid}{uid} -Set the current process's user id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{stat}{path} -Perform a {\em stat} system call on the given path. The return value -is a tuple of at least 10 integers giving the most important (and -portable) members of the {\em stat} structure, in the order -\code{st_mode}, -\code{st_ino}, -\code{st_dev}, -\code{st_nlink}, -\code{st_uid}, -\code{st_gid}, -\code{st_size}, -\code{st_atime}, -\code{st_mtime}, -\code{st_ctime}. -More items may be added at the end by some implementations. -(On MS-DOS, some items are filled with dummy values.) - -Note: The standard module \code{stat} defines functions and constants -that are useful for extracting information from a stat structure. -\end{funcdesc} - -\begin{funcdesc}{symlink}{src\, dst} -Create a symbolic link pointing to \var{src} named \var{dst}. (On -systems without symbolic links, this always raises -\code{posix.error}.) -\end{funcdesc} - -\begin{funcdesc}{system}{command} -Execute the command (a string) in a subshell. This is implemented by -calling the Standard C function \code{system()}, and has the same -limitations. Changes to \code{posix.environ}, \code{sys.stdin} etc.\ are -not reflected in the environment of the executed command. The return -value is the exit status of the process as returned by Standard C -\code{system()}. -\end{funcdesc} - -\begin{funcdesc}{times}{} -Return a 5-tuple of floating point numbers indicating accumulated (CPU -or other) -times, in seconds. The items are: user time, system time, children's -user time, children's system time, and elapsed real time since a fixed -point in the past, in that order. See the \UNIX{} -manual page {\it times}(2). (Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{umask}{mask} -Set the current numeric umask and returns the previous umask. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{uname}{} -Return a 5-tuple containing information identifying the current -operating system. The tuple contains 5 strings: -\code{(\var{sysname}, \var{nodename}, \var{release}, \var{version}, \var{machine})}. -Some systems truncate the nodename to 8 -characters or to the leading component; a better way to get the -hostname is \code{socket.gethostname()}. (Not on MS-DOS, nor on older -\UNIX{} systems.) -\end{funcdesc} - -\begin{funcdesc}{unlink}{path} -Remove the file \var{path}. This is the same function as \code{remove}; -the \code{unlink} name is its traditional \UNIX{} name. -\end{funcdesc} - -\begin{funcdesc}{utime}{path\, \(atime\, mtime\)} -Set the access and modified time of the file to the given values. -(The second argument is a tuple of two items.) -\end{funcdesc} - -\begin{funcdesc}{wait}{} -Wait for completion of a child process, and return a tuple containing -its pid and exit status indication (encoded as by \UNIX{}). -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{waitpid}{pid\, options} -Wait for completion of a child process given by proces id, and return -a tuple containing its pid and exit status indication (encoded as by -\UNIX{}). The semantics of the call are affected by the value of -the integer options, which should be 0 for normal operation. (If the -system does not support \code{waitpid()}, this always raises -\code{posix.error}. Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{write}{fd\, str} -Write the string \var{str} to file descriptor \var{fd}. -Return the number of bytes actually written. - -Note: this function is intended for low-level I/O and must be applied -to a file descriptor as returned by \code{posix.open()} or -\code{posix.pipe()}. To write a ``file object'' returned by the -built-in function \code{open} or by \code{posix.popen} or -\code{posix.fdopen}, or \code{sys.stdout} or \code{sys.stderr}, use -its \code{write()} method. -\end{funcdesc} - -\begin{datadesc}{WNOHANG} -The option for \code{waitpid()} to avoid hanging if no child process -status is available immediately. -\end{datadesc} diff --git a/Doc/lib/libposixfile.tex b/Doc/lib/libposixfile.tex deleted file mode 100644 index 6679f12280..0000000000 --- a/Doc/lib/libposixfile.tex +++ /dev/null @@ -1,154 +0,0 @@ -% Manual text and implementation by Jaap Vermeulen -\section{Standard Module \sectcode{posixfile}} -\bimodindex{posixfile} -\indexii{posix}{file object} - -This module implements some additional functionality over the built-in -file objects. In particular, it implements file locking, control over -the file flags, and an easy interface to duplicate the file object. -The module defines a new file object, the posixfile object. It -has all the standard file object methods and adds the methods -described below. This module only works for certain flavors of -\UNIX{}, since it uses \code{fcntl()} for file locking. - -To instantiate a posixfile object, use the \code{open()} function in -the posixfile module. The resulting object looks and feels roughly -the same as a standard file object. - -The posixfile module defines the following constants: - -\renewcommand{\indexsubitem}{(in module posixfile)} -\begin{datadesc}{SEEK_SET} -offset is calculated from the start of the file -\end{datadesc} - -\begin{datadesc}{SEEK_CUR} -offset is calculated from the current position in the file -\end{datadesc} - -\begin{datadesc}{SEEK_END} -offset is calculated from the end of the file -\end{datadesc} - -The posixfile module defines the following functions: - -\renewcommand{\indexsubitem}{(in module posixfile)} - -\begin{funcdesc}{open}{filename\optional{\, mode\optional{\, bufsize}}} - Create a new posixfile object with the given filename and mode. The - \var{filename}, \var{mode} and \var{bufsize} arguments are - interpreted the same way as by the built-in \code{open()} function. -\end{funcdesc} - -\begin{funcdesc}{fileopen}{fileobject} - Create a new posixfile object with the given standard file object. - The resulting object has the same filename and mode as the original - file object. -\end{funcdesc} - -The posixfile object defines the following additional methods: - -\renewcommand{\indexsubitem}{(posixfile method)} -\begin{funcdesc}{lock}{fmt\, \optional{len\optional{\, start -\optional{\, whence}}}} - Lock the specified section of the file that the file object is - referring to. The format is explained - below in a table. The \var{len} argument specifies the length of the - section that should be locked. The default is \code{0}. \var{start} - specifies the starting offset of the section, where the default is - \code{0}. The \var{whence} argument specifies where the offset is - relative to. It accepts one of the constants \code{SEEK_SET}, - \code{SEEK_CUR} or \code{SEEK_END}. The default is \code{SEEK_SET}. - For more information about the arguments refer to the fcntl - manual page on your system. -\end{funcdesc} - -\begin{funcdesc}{flags}{\optional{flags}} - Set the specified flags for the file that the file object is referring - to. The new flags are ORed with the old flags, unless specified - otherwise. The format is explained below in a table. Without - the \var{flags} argument - a string indicating the current flags is returned (this is - the same as the '?' modifier). For more information about the flags - refer to the fcntl manual page on your system. -\end{funcdesc} - -\begin{funcdesc}{dup}{} - Duplicate the file object and the underlying file pointer and file - descriptor. The resulting object behaves as if it were newly - opened. -\end{funcdesc} - -\begin{funcdesc}{dup2}{fd} - Duplicate the file object and the underlying file pointer and file - descriptor. The new object will have the given file descriptor. - Otherwise the resulting object behaves as if it were newly opened. -\end{funcdesc} - -\begin{funcdesc}{file}{} - Return the standard file object that the posixfile object is based - on. This is sometimes necessary for functions that insist on a - standard file object. -\end{funcdesc} - -All methods return \code{IOError} when the request fails. - -Format characters for the \code{lock()} method have the following meaning: - -\begin{tableiii}{|c|l|c|}{samp}{Format}{Meaning}{} - \lineiii{u}{unlock the specified region}{} - \lineiii{r}{request a read lock for the specified section}{} - \lineiii{w}{request a write lock for the specified section}{} -\end{tableiii} - -In addition the following modifiers can be added to the format: - -\begin{tableiii}{|c|l|c|}{samp}{Modifier}{Meaning}{Notes} - \lineiii{|}{wait until the lock has been granted}{} - \lineiii{?}{return the first lock conflicting with the requested lock, or - \code{None} if there is no conflict.}{(1)} -\end{tableiii} - -Note: - -(1) The lock returned is in the format \code{(mode, len, start, -whence, pid)} where mode is a character representing the type of lock -('r' or 'w'). This modifier prevents a request from being granted; it -is for query purposes only. - -Format character for the \code{flags()} method have the following meaning: - -\begin{tableiii}{|c|l|c|}{samp}{Format}{Meaning}{} - \lineiii{a}{append only flag}{} - \lineiii{c}{close on exec flag}{} - \lineiii{n}{no delay flag (also called non-blocking flag)}{} - \lineiii{s}{synchronization flag}{} -\end{tableiii} - -In addition the following modifiers can be added to the format: - -\begin{tableiii}{|c|l|c|}{samp}{Modifier}{Meaning}{Notes} - \lineiii{!}{turn the specified flags 'off', instead of the default 'on'}{(1)} - \lineiii{=}{replace the flags, instead of the default 'OR' operation}{(1)} - \lineiii{?}{return a string in which the characters represent the flags that - are set.}{(2)} -\end{tableiii} - -Note: - -(1) The \code{!} and \code{=} modifiers are mutually exclusive. - -(2) This string represents the flags after they may have been altered -by the same call. - -Examples: - -\bcode\begin{verbatim} -from posixfile import * - -file = open('/tmp/test', 'w') -file.lock('w|') -... -file.lock('u') -file.close() -\end{verbatim}\ecode diff --git a/Doc/lib/libppath.tex b/Doc/lib/libppath.tex deleted file mode 100644 index 0d3bbe573d..0000000000 --- a/Doc/lib/libppath.tex +++ /dev/null @@ -1,144 +0,0 @@ -\section{Standard Module \sectcode{posixpath}} -\stmodindex{posixpath} - -This module implements some useful functions on POSIX pathnames. - -\strong{Do not import this module directly.} Instead, import the -module \code{os} and use \code{os.path}. -\stmodindex{os} - -\renewcommand{\indexsubitem}{(in module posixpath)} - -\begin{funcdesc}{basename}{p} -Return the base name of pathname -\var{p}. -This is the second half of the pair returned by -\code{posixpath.split(\var{p})}. -\end{funcdesc} - -\begin{funcdesc}{commonprefix}{list} -Return the longest string that is a prefix of all strings in -\var{list}. -If -\var{list} -is empty, return the empty string (\code{''}). -\end{funcdesc} - -\begin{funcdesc}{exists}{p} -Return true if -\var{p} -refers to an existing path. -\end{funcdesc} - -\begin{funcdesc}{expanduser}{p} -Return the argument with an initial component of \samp{\~} or -\samp{\~\var{user}} replaced by that \var{user}'s home directory. An -initial \samp{\~{}} is replaced by the environment variable \code{\${}HOME}; -an initial \samp{\~\var{user}} is looked up in the password directory through -the built-in module \code{pwd}. If the expansion fails, or if the -path does not begin with a tilde, the path is returned unchanged. -\end{funcdesc} - -\begin{funcdesc}{expandvars}{p} -Return the argument with environment variables expanded. Substrings -of the form \samp{\$\var{name}} or \samp{\$\{\var{name}\}} are -replaced by the value of environment variable \var{name}. Malformed -variable names and references to non-existing variables are left -unchanged. -\end{funcdesc} - -\begin{funcdesc}{isabs}{p} -Return true if \var{p} is an absolute pathname (begins with a slash). -\end{funcdesc} - -\begin{funcdesc}{isfile}{p} -Return true if \var{p} is an existing regular file. This follows -symbolic links, so both \code{islink()} and \code{isfile()} can be true for the same -path. -\end{funcdesc} - -\begin{funcdesc}{isdir}{p} -Return true if \var{p} is an existing directory. This follows -symbolic links, so both \code{islink()} and \code{isdir()} can be true for the same -path. -\end{funcdesc} - -\begin{funcdesc}{islink}{p} -Return true if -\var{p} -refers to a directory entry that is a symbolic link. -Always false if symbolic links are not supported. -\end{funcdesc} - -\begin{funcdesc}{ismount}{p} -Return true if pathname \var{p} is a \dfn{mount point}: a point in a -file system where a different file system has been mounted. The -function checks whether \var{p}'s parent, \file{\var{p}/..}, is on a -different device than \var{p}, or whether \file{\var{p}/..} and -\var{p} point to the same i-node on the same device --- this should -detect mount points for all \UNIX{} and POSIX variants. -\end{funcdesc} - -\begin{funcdesc}{join}{p\, q} -Join the paths -\var{p} -and -\var{q} intelligently: -If -\var{q} -is an absolute path, the return value is -\var{q}. -Otherwise, the concatenation of -\var{p} -and -\var{q} -is returned, with a slash (\code{'/'}) inserted unless -\var{p} -is empty or ends in a slash. -\end{funcdesc} - -\begin{funcdesc}{normcase}{p} -Normalize the case of a pathname. This returns the path unchanged; -however, a similar function in \code{macpath} converts upper case to -lower case. -\end{funcdesc} - -\begin{funcdesc}{samefile}{p\, q} -Return true if both pathname arguments refer to the same file or directory -(as indicated by device number and i-node number). -Raise an exception if a stat call on either pathname fails. -\end{funcdesc} - -\begin{funcdesc}{split}{p} -Split the pathname \var{p} in a pair \code{(\var{head}, \var{tail})}, where -\var{tail} is the last pathname component and \var{head} is -everything leading up to that. If \var{p} ends in a slash (except if -it is the root), the trailing slash is removed and the operation -applied to the result; otherwise, \code{join(\var{head}, \var{tail})} equals -\var{p}. The \var{tail} part never contains a slash. Some boundary -cases:\ if \var{p} is the root, \var{head} equals \var{p} and -\var{tail} is empty; if \var{p} is empty, both \var{head} and -\var{tail} are empty; if \var{p} contains no slash, \var{head} is -empty and \var{tail} equals \var{p}. -\end{funcdesc} - -\begin{funcdesc}{splitext}{p} -Split the pathname \var{p} in a pair \code{(\var{root}, \var{ext})} -such that \code{\var{root} + \var{ext} == \var{p}}, -the last component of \var{root} contains no periods, -and \var{ext} is empty or begins with a period. -\end{funcdesc} - -\begin{funcdesc}{walk}{p\, visit\, arg} -Calls the function \var{visit} with arguments -\code{(\var{arg}, \var{dirname}, \var{names})} for each directory in the -directory tree rooted at \var{p} (including \var{p} itself, if it is a -directory). The argument \var{dirname} specifies the visited directory, -the argument \var{names} lists the files in the directory (gotten from -\code{posix.listdir(\var{dirname})}, so including \samp{.} and -\samp{..}). The \var{visit} function may modify \var{names} to -influence the set of directories visited below \var{dirname}, e.g., to -avoid visiting certain parts of the tree. (The object referred to by -\var{names} must be modified in place, using \code{del} or slice -assignment.) -\end{funcdesc} diff --git a/Doc/lib/libprofile.tex b/Doc/lib/libprofile.tex deleted file mode 100644 index 4ba4cf979d..0000000000 --- a/Doc/lib/libprofile.tex +++ /dev/null @@ -1,760 +0,0 @@ -\chapter{The Python Profiler} -\stmodindex{profile} -\stmodindex{pstats} - -Copyright \copyright\ 1994, by InfoSeek Corporation, all rights reserved. - -Written by James Roskind% -\footnote{ -Updated and converted to \LaTeX\ by Guido van Rossum. The references to -the old profiler are left in the text, although it no longer exists. -} - -Permission to use, copy, modify, and distribute this Python software -and its associated documentation for any purpose (subject to the -restriction in the following sentence) without fee is hereby granted, -provided that the above copyright notice appears in all copies, and -that both that copyright notice and this permission notice appear in -supporting documentation, and that the name of InfoSeek not be used in -advertising or publicity pertaining to distribution of the software -without specific, written prior permission. This permission is -explicitly restricted to the copying and modification of the software -to remain in Python, compiled Python, or other languages (such as C) -wherein the modified or derived code is exclusively imported into a -Python module. - -INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS -SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION 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. - - -The profiler was written after only programming in Python for 3 weeks. -As a result, it is probably clumsy code, but I don't know for sure yet -'cause I'm a beginner :-). I did work hard to make the code run fast, -so that profiling would be a reasonable thing to do. I tried not to -repeat code fragments, but I'm sure I did some stuff in really awkward -ways at times. Please send suggestions for improvements to: -\code{jar@netscape.com}. I won't promise \emph{any} support. ...but -I'd appreciate the feedback. - - -\section{Introduction to the profiler} -\nodename{Profiler Introduction} - -A \dfn{profiler} is a program that describes the run time performance -of a program, providing a variety of statistics. This documentation -describes the profiler functionality provided in the modules -\code{profile} and \code{pstats.} This profiler provides -\dfn{deterministic profiling} of any Python programs. It also -provides a series of report generation tools to allow users to rapidly -examine the results of a profile operation. - - -\section{How Is This Profiler Different From The Old Profiler?} -\nodename{Profiler Changes} - -The big changes from old profiling module are that you get more -information, and you pay less CPU time. It's not a trade-off, it's a -trade-up. - -To be specific: - -\begin{description} - -\item[Bugs removed:] -Local stack frame is no longer molested, execution time is now charged -to correct functions. - -\item[Accuracy increased:] -Profiler execution time is no longer charged to user's code, -calibration for platform is supported, file reads are not done \emph{by} -profiler \emph{during} profiling (and charged to user's code!). - -\item[Speed increased:] -Overhead CPU cost was reduced by more than a factor of two (perhaps a -factor of five), lightweight profiler module is all that must be -loaded, and the report generating module (\code{pstats}) is not needed -during profiling. - -\item[Recursive functions support:] -Cumulative times in recursive functions are correctly calculated; -recursive entries are counted. - -\item[Large growth in report generating UI:] -Distinct profiles runs can be added together forming a comprehensive -report; functions that import statistics take arbitrary lists of -files; sorting criteria is now based on keywords (instead of 4 integer -options); reports shows what functions were profiled as well as what -profile file was referenced; output format has been improved. - -\end{description} - - -\section{Instant Users Manual} - -This section is provided for users that ``don't want to read the -manual.'' It provides a very brief overview, and allows a user to -rapidly perform profiling on an existing application. - -To profile an application with a main entry point of \samp{foo()}, you -would add the following to your module: - -\begin{verbatim} - import profile - profile.run("foo()") -\end{verbatim} - -The above action would cause \samp{foo()} to be run, and a series of -informative lines (the profile) to be printed. The above approach is -most useful when working with the interpreter. If you would like to -save the results of a profile into a file for later examination, you -can supply a file name as the second argument to the \code{run()} -function: - -\begin{verbatim} - import profile - profile.run("foo()", 'fooprof') -\end{verbatim} - -When you wish to review the profile, you should use the methods in the -\code{pstats} module. Typically you would load the statistics data as -follows: - -\begin{verbatim} - import pstats - p = pstats.Stats('fooprof') -\end{verbatim} - -The class \code{Stats} (the above code just created an instance of -this class) has a variety of methods for manipulating and printing the -data that was just read into \samp{p}. When you ran -\code{profile.run()} above, what was printed was the result of three -method calls: - -\begin{verbatim} - p.strip_dirs().sort_stats(-1).print_stats() -\end{verbatim} - -The first method removed the extraneous path from all the module -names. The second method sorted all the entries according to the -standard module/line/name string that is printed (this is to comply -with the semantics of the old profiler). The third method printed out -all the statistics. You might try the following sort calls: - -\begin{verbatim} - p.sort_stats('name') - p.print_stats() -\end{verbatim} - -The first call will actually sort the list by function name, and the -second call will print out the statistics. The following are some -interesting calls to experiment with: - -\begin{verbatim} - p.sort_stats('cumulative').print_stats(10) -\end{verbatim} - -This sorts the profile by cumulative time in a function, and then only -prints the ten most significant lines. If you want to understand what -algorithms are taking time, the above line is what you would use. - -If you were looking to see what functions were looping a lot, and -taking a lot of time, you would do: - -\begin{verbatim} - p.sort_stats('time').print_stats(10) -\end{verbatim} - -to sort according to time spent within each function, and then print -the statistics for the top ten functions. - -You might also try: - -\begin{verbatim} - p.sort_stats('file').print_stats('__init__') -\end{verbatim} - -This will sort all the statistics by file name, and then print out -statistics for only the class init methods ('cause they are spelled -with \code{__init__} in them). As one final example, you could try: - -\begin{verbatim} - p.sort_stats('time', 'cum').print_stats(.5, 'init') -\end{verbatim} - -This line sorts statistics with a primary key of time, and a secondary -key of cumulative time, and then prints out some of the statistics. -To be specific, the list is first culled down to 50\% (re: \samp{.5}) -of its original size, then only lines containing \code{init} are -maintained, and that sub-sub-list is printed. - -If you wondered what functions called the above functions, you could -now (\samp{p} is still sorted according to the last criteria) do: - -\begin{verbatim} - p.print_callers(.5, 'init') -\end{verbatim} - -and you would get a list of callers for each of the listed functions. - -If you want more functionality, you're going to have to read the -manual, or guess what the following functions do: - -\begin{verbatim} - p.print_callees() - p.add('fooprof') -\end{verbatim} - - -\section{What Is Deterministic Profiling?} -\nodename{Deterministic Profiling} - -\dfn{Deterministic profiling} is meant to reflect the fact that all -\dfn{function call}, \dfn{function return}, and \dfn{exception} events -are monitored, and precise timings are made for the intervals between -these events (during which time the user's code is executing). In -contrast, \dfn{statistical profiling} (which is not done by this -module) randomly samples the effective instruction pointer, and -deduces where time is being spent. The latter technique traditionally -involves less overhead (as the code does not need to be instrumented), -but provides only relative indications of where time is being spent. - -In Python, since there is an interpreter active during execution, the -presence of instrumented code is not required to do deterministic -profiling. Python automatically provides a \dfn{hook} (optional -callback) for each event. In addition, the interpreted nature of -Python tends to add so much overhead to execution, that deterministic -profiling tends to only add small processing overhead in typical -applications. The result is that deterministic profiling is not that -expensive, yet provides extensive run time statistics about the -execution of a Python program. - -Call count statistics can be used to identify bugs in code (surprising -counts), and to identify possible inline-expansion points (high call -counts). Internal time statistics can be used to identify ``hot -loops'' that should be carefully optimized. Cumulative time -statistics should be used to identify high level errors in the -selection of algorithms. Note that the unusual handling of cumulative -times in this profiler allows statistics for recursive implementations -of algorithms to be directly compared to iterative implementations. - - -\section{Reference Manual} - -\renewcommand{\indexsubitem}{(profiler function)} - -The primary entry point for the profiler is the global function -\code{profile.run()}. It is typically used to create any profile -information. The reports are formatted and printed using methods of -the class \code{pstats.Stats}. The following is a description of all -of these standard entry points and functions. For a more in-depth -view of some of the code, consider reading the later section on -Profiler Extensions, which includes discussion of how to derive -``better'' profilers from the classes presented, or reading the source -code for these modules. - -\begin{funcdesc}{profile.run}{string\optional{\, filename\optional{\, ...}}} - -This function takes a single argument that has can be passed to the -\code{exec} statement, and an optional file name. In all cases this -routine attempts to \code{exec} its first argument, and gather profiling -statistics from the execution. If no file name is present, then this -function automatically prints a simple profiling report, sorted by the -standard name string (file/line/function-name) that is presented in -each line. The following is a typical output from such a call: - -\small{ -\begin{verbatim} - main() - 2706 function calls (2004 primitive calls) in 4.504 CPU seconds - -Ordered by: standard name - -ncalls tottime percall cumtime percall filename:lineno(function) - 2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects) - 43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate) - ... -\end{verbatim} -} - -The first line indicates that this profile was generated by the call:\\ -\code{profile.run('main()')}, and hence the exec'ed string is -\code{'main()'}. The second line indicates that 2706 calls were -monitored. Of those calls, 2004 were \dfn{primitive}. We define -\dfn{primitive} to mean that the call was not induced via recursion. -The next line: \code{Ordered by:\ standard name}, indicates that -the text string in the far right column was used to sort the output. -The column headings include: - -\begin{description} - -\item[ncalls ] -for the number of calls, - -\item[tottime ] -for the total time spent in the given function (and excluding time -made in calls to sub-functions), - -\item[percall ] -is the quotient of \code{tottime} divided by \code{ncalls} - -\item[cumtime ] -is the total time spent in this and all subfunctions (i.e., from -invocation till exit). This figure is accurate \emph{even} for recursive -functions. - -\item[percall ] -is the quotient of \code{cumtime} divided by primitive calls - -\item[filename:lineno(function) ] -provides the respective data of each function - -\end{description} - -When there are two numbers in the first column (e.g.: \samp{43/3}), -then the latter is the number of primitive calls, and the former is -the actual number of calls. Note that when the function does not -recurse, these two values are the same, and only the single figure is -printed. - -\end{funcdesc} - -\begin{funcdesc}{pstats.Stats}{filename\optional{\, ...}} -This class constructor creates an instance of a ``statistics object'' -from a \var{filename} (or set of filenames). \code{Stats} objects are -manipulated by methods, in order to print useful reports. - -The file selected by the above constructor must have been created by -the corresponding version of \code{profile}. To be specific, there is -\emph{NO} file compatibility guaranteed with future versions of this -profiler, and there is no compatibility with files produced by other -profilers (e.g., the old system profiler). - -If several files are provided, all the statistics for identical -functions will be coalesced, so that an overall view of several -processes can be considered in a single report. If additional files -need to be combined with data in an existing \code{Stats} object, the -\code{add()} method can be used. -\end{funcdesc} - - -\subsection{The \sectcode{Stats} Class} - -\renewcommand{\indexsubitem}{(Stats method)} - -\begin{funcdesc}{strip_dirs}{} -This method for the \code{Stats} class removes all leading path information -from file names. It is very useful in reducing the size of the -printout to fit within (close to) 80 columns. This method modifies -the object, and the stripped information is lost. After performing a -strip operation, the object is considered to have its entries in a -``random'' order, as it was just after object initialization and -loading. If \code{strip_dirs()} causes two function names to be -indistinguishable (i.e., they are on the same line of the same -filename, and have the same function name), then the statistics for -these two entries are accumulated into a single entry. -\end{funcdesc} - - -\begin{funcdesc}{add}{filename\optional{\, ...}} -This method of the \code{Stats} class accumulates additional profiling -information into the current profiling object. Its arguments should -refer to filenames created by the corresponding version of -\code{profile.run()}. Statistics for identically named (re: file, -line, name) functions are automatically accumulated into single -function statistics. -\end{funcdesc} - -\begin{funcdesc}{sort_stats}{key\optional{\, ...}} -This method modifies the \code{Stats} object by sorting it according to the -supplied criteria. The argument is typically a string identifying the -basis of a sort (example: \code{"time"} or \code{"name"}). - -When more than one key is provided, then additional keys are used as -secondary criteria when the there is equality in all keys selected -before them. For example, sort_stats('name', 'file') will sort all -the entries according to their function name, and resolve all ties -(identical function names) by sorting by file name. - -Abbreviations can be used for any key names, as long as the -abbreviation is unambiguous. The following are the keys currently -defined: - -\begin{tableii}{|l|l|}{code}{Valid Arg}{Meaning} -\lineii{"calls"}{call count} -\lineii{"cumulative"}{cumulative time} -\lineii{"file"}{file name} -\lineii{"module"}{file name} -\lineii{"pcalls"}{primitive call count} -\lineii{"line"}{line number} -\lineii{"name"}{function name} -\lineii{"nfl"}{name/file/line} -\lineii{"stdname"}{standard name} -\lineii{"time"}{internal time} -\end{tableii} - -Note that all sorts on statistics are in descending order (placing -most time consuming items first), where as name, file, and line number -searches are in ascending order (i.e., alphabetical). The subtle -distinction between \code{"nfl"} and \code{"stdname"} is that the -standard name is a sort of the name as printed, which means that the -embedded line numbers get compared in an odd way. For example, lines -3, 20, and 40 would (if the file names were the same) appear in the -string order 20, 3 and 40. In contrast, \code{"nfl"} does a numeric -compare of the line numbers. In fact, \code{sort_stats("nfl")} is the -same as \code{sort_stats("name", "file", "line")}. - -For compatibility with the old profiler, the numeric arguments -\samp{-1}, \samp{0}, \samp{1}, and \samp{2} are permitted. They are -interpreted as \code{"stdname"}, \code{"calls"}, \code{"time"}, and -\code{"cumulative"} respectively. If this old style format (numeric) -is used, only one sort key (the numeric key) will be used, and -additional arguments will be silently ignored. -\end{funcdesc} - - -\begin{funcdesc}{reverse_order}{} -This method for the \code{Stats} class reverses the ordering of the basic -list within the object. This method is provided primarily for -compatibility with the old profiler. Its utility is questionable -now that ascending vs descending order is properly selected based on -the sort key of choice. -\end{funcdesc} - -\begin{funcdesc}{print_stats}{restriction\optional{\, ...}} -This method for the \code{Stats} class prints out a report as described -in the \code{profile.run()} definition. - -The order of the printing is based on the last \code{sort_stats()} -operation done on the object (subject to caveats in \code{add()} and -\code{strip_dirs())}. - -The arguments provided (if any) can be used to limit the list down to -the significant entries. Initially, the list is taken to be the -complete set of profiled functions. Each restriction is either an -integer (to select a count of lines), or a decimal fraction between -0.0 and 1.0 inclusive (to select a percentage of lines), or a regular -expression (to pattern match the standard name that is printed). If -several restrictions are provided, then they are applied sequentially. -For example: - -\begin{verbatim} - print_stats(.1, "foo:") -\end{verbatim} - -would first limit the printing to first 10\% of list, and then only -print functions that were part of filename \samp{.*foo:}. In -contrast, the command: - -\begin{verbatim} - print_stats("foo:", .1) -\end{verbatim} - -would limit the list to all functions having file names \samp{.*foo:}, -and then proceed to only print the first 10\% of them. -\end{funcdesc} - - -\begin{funcdesc}{print_callers}{restrictions\optional{\, ...}} -This method for the \code{Stats} class prints a list of all functions -that called each function in the profiled database. The ordering is -identical to that provided by \code{print_stats()}, and the definition -of the restricting argument is also identical. For convenience, a -number is shown in parentheses after each caller to show how many -times this specific call was made. A second non-parenthesized number -is the cumulative time spent in the function at the right. -\end{funcdesc} - -\begin{funcdesc}{print_callees}{restrictions\optional{\, ...}} -This method for the \code{Stats} class prints a list of all function -that were called by the indicated function. Aside from this reversal -of direction of calls (re: called vs was called by), the arguments and -ordering are identical to the \code{print_callers()} method. -\end{funcdesc} - -\begin{funcdesc}{ignore}{} -This method of the \code{Stats} class is used to dispose of the value -returned by earlier methods. All standard methods in this class -return the instance that is being processed, so that the commands can -be strung together. For example: - -\begin{verbatim} -pstats.Stats('foofile').strip_dirs().sort_stats('cum') \ - .print_stats().ignore() -\end{verbatim} - -would perform all the indicated functions, but it would not return -the final reference to the \code{Stats} instance.% -\footnote{ -This was once necessary, when Python would print any unused expression -result that was not \code{None}. The method is still defined for -backward compatibility. -} -\end{funcdesc} - - -\section{Limitations} - -There are two fundamental limitations on this profiler. The first is -that it relies on the Python interpreter to dispatch \dfn{call}, -\dfn{return}, and \dfn{exception} events. Compiled C code does not -get interpreted, and hence is ``invisible'' to the profiler. All time -spent in C code (including builtin functions) will be charged to the -Python function that invoked the C code. If the C code calls out -to some native Python code, then those calls will be profiled -properly. - -The second limitation has to do with accuracy of timing information. -There is a fundamental problem with deterministic profilers involving -accuracy. The most obvious restriction is that the underlying ``clock'' -is only ticking at a rate (typically) of about .001 seconds. Hence no -measurements will be more accurate that that underlying clock. If -enough measurements are taken, then the ``error'' will tend to average -out. Unfortunately, removing this first error induces a second source -of error... - -The second problem is that it ``takes a while'' from when an event is -dispatched until the profiler's call to get the time actually -\emph{gets} the state of the clock. Similarly, there is a certain lag -when exiting the profiler event handler from the time that the clock's -value was obtained (and then squirreled away), until the user's code -is once again executing. As a result, functions that are called many -times, or call many functions, will typically accumulate this error. -The error that accumulates in this fashion is typically less than the -accuracy of the clock (i.e., less than one clock tick), but it -\emph{can} accumulate and become very significant. This profiler -provides a means of calibrating itself for a given platform so that -this error can be probabilistically (i.e., on the average) removed. -After the profiler is calibrated, it will be more accurate (in a least -square sense), but it will sometimes produce negative numbers (when -call counts are exceptionally low, and the gods of probability work -against you :-). ) Do \emph{NOT} be alarmed by negative numbers in -the profile. They should \emph{only} appear if you have calibrated -your profiler, and the results are actually better than without -calibration. - - -\section{Calibration} - -The profiler class has a hard coded constant that is added to each -event handling time to compensate for the overhead of calling the time -function, and socking away the results. The following procedure can -be used to obtain this constant for a given platform (see discussion -in section Limitations above). - -\begin{verbatim} - import profile - pr = profile.Profile() - pr.calibrate(100) - pr.calibrate(100) - pr.calibrate(100) -\end{verbatim} - -The argument to calibrate() is the number of times to try to do the -sample calls to get the CPU times. If your computer is \emph{very} -fast, you might have to do: - -\begin{verbatim} - pr.calibrate(1000) -\end{verbatim} - -or even: - -\begin{verbatim} - pr.calibrate(10000) -\end{verbatim} - -The object of this exercise is to get a fairly consistent result. -When you have a consistent answer, you are ready to use that number in -the source code. For a Sun Sparcstation 1000 running Solaris 2.3, the -magical number is about .00053. If you have a choice, you are better -off with a smaller constant, and your results will ``less often'' show -up as negative in profile statistics. - -The following shows how the trace_dispatch() method in the Profile -class should be modified to install the calibration constant on a Sun -Sparcstation 1000: - -\begin{verbatim} - def trace_dispatch(self, frame, event, arg): - t = self.timer() - t = t[0] + t[1] - self.t - .00053 # Calibration constant - - if self.dispatch[event](frame,t): - t = self.timer() - self.t = t[0] + t[1] - else: - r = self.timer() - self.t = r[0] + r[1] - t # put back unrecorded delta - return -\end{verbatim} - -Note that if there is no calibration constant, then the line -containing the callibration constant should simply say: - -\begin{verbatim} - t = t[0] + t[1] - self.t # no calibration constant -\end{verbatim} - -You can also achieve the same results using a derived class (and the -profiler will actually run equally fast!!), but the above method is -the simplest to use. I could have made the profiler ``self -calibrating'', but it would have made the initialization of the -profiler class slower, and would have required some \emph{very} fancy -coding, or else the use of a variable where the constant \samp{.00053} -was placed in the code shown. This is a \strong{VERY} critical -performance section, and there is no reason to use a variable lookup -at this point, when a constant can be used. - - -\section{Extensions --- Deriving Better Profilers} -\nodename{Profiler Extensions} - -The \code{Profile} class of module \code{profile} was written so that -derived classes could be developed to extend the profiler. Rather -than describing all the details of such an effort, I'll just present -the following two examples of derived classes that can be used to do -profiling. If the reader is an avid Python programmer, then it should -be possible to use these as a model and create similar (and perchance -better) profile classes. - -If all you want to do is change how the timer is called, or which -timer function is used, then the basic class has an option for that in -the constructor for the class. Consider passing the name of a -function to call into the constructor: - -\begin{verbatim} - pr = profile.Profile(your_time_func) -\end{verbatim} - -The resulting profiler will call \code{your_time_func()} instead of -\code{os.times()}. The function should return either a single number -or a list of numbers (like what \code{os.times()} returns). If the -function returns a single time number, or the list of returned numbers -has length 2, then you will get an especially fast version of the -dispatch routine. - -Be warned that you \emph{should} calibrate the profiler class for the -timer function that you choose. For most machines, a timer that -returns a lone integer value will provide the best results in terms of -low overhead during profiling. (os.times is \emph{pretty} bad, 'cause -it returns a tuple of floating point values, so all arithmetic is -floating point in the profiler!). If you want to substitute a -better timer in the cleanest fashion, you should derive a class, and -simply put in the replacement dispatch method that better handles your -timer call, along with the appropriate calibration constant :-). - - -\subsection{OldProfile Class} - -The following derived profiler simulates the old style profiler, -providing errant results on recursive functions. The reason for the -usefulness of this profiler is that it runs faster (i.e., less -overhead) than the old profiler. It still creates all the caller -stats, and is quite useful when there is \emph{no} recursion in the -user's code. It is also a lot more accurate than the old profiler, as -it does not charge all its overhead time to the user's code. - -\begin{verbatim} -class OldProfile(Profile): - - def trace_dispatch_exception(self, frame, t): - rt, rtt, rct, rfn, rframe, rcur = self.cur - if rcur and not rframe is frame: - return self.trace_dispatch_return(rframe, t) - return 0 - - def trace_dispatch_call(self, frame, t): - fn = `frame.f_code` - - self.cur = (t, 0, 0, fn, frame, self.cur) - if self.timings.has_key(fn): - tt, ct, callers = self.timings[fn] - self.timings[fn] = tt, ct, callers - else: - self.timings[fn] = 0, 0, {} - return 1 - - def trace_dispatch_return(self, frame, t): - rt, rtt, rct, rfn, frame, rcur = self.cur - rtt = rtt + t - sft = rtt + rct - - pt, ptt, pct, pfn, pframe, pcur = rcur - self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur - - tt, ct, callers = self.timings[rfn] - if callers.has_key(pfn): - callers[pfn] = callers[pfn] + 1 - else: - callers[pfn] = 1 - self.timings[rfn] = tt+rtt, ct + sft, callers - - return 1 - - - def snapshot_stats(self): - self.stats = {} - for func in self.timings.keys(): - tt, ct, callers = self.timings[func] - nor_func = self.func_normalize(func) - nor_callers = {} - nc = 0 - for func_caller in callers.keys(): - nor_callers[self.func_normalize(func_caller)]=\ - callers[func_caller] - nc = nc + callers[func_caller] - self.stats[nor_func] = nc, nc, tt, ct, nor_callers -\end{verbatim} - - -\subsection{HotProfile Class} - -This profiler is the fastest derived profile example. It does not -calculate caller-callee relationships, and does not calculate -cumulative time under a function. It only calculates time spent in a -function, so it runs very quickly (re: very low overhead). In truth, -the basic profiler is so fast, that is probably not worth the savings -to give up the data, but this class still provides a nice example. - -\begin{verbatim} -class HotProfile(Profile): - - def trace_dispatch_exception(self, frame, t): - rt, rtt, rfn, rframe, rcur = self.cur - if rcur and not rframe is frame: - return self.trace_dispatch_return(rframe, t) - return 0 - - def trace_dispatch_call(self, frame, t): - self.cur = (t, 0, frame, self.cur) - return 1 - - def trace_dispatch_return(self, frame, t): - rt, rtt, frame, rcur = self.cur - - rfn = `frame.f_code` - - pt, ptt, pframe, pcur = rcur - self.cur = pt, ptt+rt, pframe, pcur - - if self.timings.has_key(rfn): - nc, tt = self.timings[rfn] - self.timings[rfn] = nc + 1, rt + rtt + tt - else: - self.timings[rfn] = 1, rt + rtt - - return 1 - - - def snapshot_stats(self): - self.stats = {} - for func in self.timings.keys(): - nc, tt = self.timings[func] - nor_func = self.func_normalize(func) - self.stats[nor_func] = nc, nc, tt, 0, {} -\end{verbatim} diff --git a/Doc/lib/libpwd.tex b/Doc/lib/libpwd.tex deleted file mode 100644 index 7bb30d80e2..0000000000 --- a/Doc/lib/libpwd.tex +++ /dev/null @@ -1,32 +0,0 @@ -\section{Built-in Module \sectcode{pwd}} - -\bimodindex{pwd} -This module provides access to the \UNIX{} password database. -It is available on all \UNIX{} versions. - -Password database entries are reported as 7-tuples containing the -following items from the password database (see \file{<pwd.h>}), in order: -\code{pw_name}, -\code{pw_passwd}, -\code{pw_uid}, -\code{pw_gid}, -\code{pw_gecos}, -\code{pw_dir}, -\code{pw_shell}. -The uid and gid items are integers, all others are strings. -An exception is raised if the entry asked for cannot be found. - -It defines the following items: - -\renewcommand{\indexsubitem}{(in module pwd)} -\begin{funcdesc}{getpwuid}{uid} -Return the password database entry for the given numeric user ID. -\end{funcdesc} - -\begin{funcdesc}{getpwnam}{name} -Return the password database entry for the given user name. -\end{funcdesc} - -\begin{funcdesc}{getpwall}{} -Return a list of all available password database entries, in arbitrary order. -\end{funcdesc} diff --git a/Doc/lib/libpython.tex b/Doc/lib/libpython.tex deleted file mode 100644 index ed253f5bad..0000000000 --- a/Doc/lib/libpython.tex +++ /dev/null @@ -1,40 +0,0 @@ -\chapter{Python Services} - -The modules described in this chapter provide a wide range of services -related to the Python interpreter and its interaction with its -environment. Here's an overview: - -\begin{description} - -\item[sys] ---- Access system specific parameters and functions. - -\item[types] ---- Names for all built-in types. - -\item[traceback] ---- Print or retrieve a stack traceback. - -\item[pickle] ---- Convert Python objects to streams of bytes and back. - -\item[shelve] ---- Python object persistency. - -\item[copy] ---- Shallow and deep copy operations. - -\item[marshal] ---- Convert Python objects to streams of bytes and back (with -different constraints). - -\item[imp] ---- Access the implementation of the \code{import} statement. - -\item[__builtin__] ---- The set of built-in functions. - -\item[__main__] ---- The environment where the top-level script is run. - -\end{description} diff --git a/Doc/lib/librand.tex b/Doc/lib/librand.tex deleted file mode 100644 index 4991e5986f..0000000000 --- a/Doc/lib/librand.tex +++ /dev/null @@ -1,21 +0,0 @@ -\section{Standard Module \sectcode{rand}} - -\stmodindex{rand} This module implements a pseudo-random number -generator with an interface similar to \code{rand()} in C\@. It defines -the following functions: - -\renewcommand{\indexsubitem}{(in module rand)} -\begin{funcdesc}{rand}{} -Returns an integer random number in the range [0 ... 32768). -\end{funcdesc} - -\begin{funcdesc}{choice}{s} -Returns a random element from the sequence (string, tuple or list) -\var{s}. -\end{funcdesc} - -\begin{funcdesc}{srand}{seed} -Initializes the random number generator with the given integral seed. -When the module is first imported, the random number is initialized with -the current time. -\end{funcdesc} diff --git a/Doc/lib/libregex.tex b/Doc/lib/libregex.tex deleted file mode 100644 index 4c98e59fc3..0000000000 --- a/Doc/lib/libregex.tex +++ /dev/null @@ -1,200 +0,0 @@ -\section{Built-in Module \sectcode{regex}} - -\bimodindex{regex} -This module provides regular expression matching operations similar to -those found in Emacs. It is always available. - -By default the patterns are Emacs-style regular expressions, -with one exception. There is -a way to change the syntax to match that of several well-known -\UNIX{} utilities. The exception is that Emacs' \samp{\e s} -pattern is not supported, since the original implementation references -the Emacs syntax tables. - -This module is 8-bit clean: both patterns and strings may contain null -bytes and characters whose high bit is set. - -\strong{Please note:} There is a little-known fact about Python string -literals which means that you don't usually have to worry about -doubling backslashes, even though they are used to escape special -characters in string literals as well as in regular expressions. This -is because Python doesn't remove backslashes from string literals if -they are followed by an unrecognized escape character. -\emph{However}, if you want to include a literal \dfn{backslash} in a -regular expression represented as a string literal, you have to -\emph{quadruple} it. E.g.\ to extract \LaTeX\ \samp{\e section\{{\rm -\ldots}\}} headers from a document, you can use this pattern: -\code{'\e \e \e\e section\{\e (.*\e )\}'}. - -The module defines these functions, and an exception: - -\renewcommand{\indexsubitem}{(in module regex)} - -\begin{funcdesc}{match}{pattern\, string} - Return how many characters at the beginning of \var{string} match - the regular expression \var{pattern}. Return \code{-1} if the - string does not match the pattern (this is different from a - zero-length match!). -\end{funcdesc} - -\begin{funcdesc}{search}{pattern\, string} - Return the first position in \var{string} that matches the regular - expression \var{pattern}. Return -1 if no position in the string - matches the pattern (this is different from a zero-length match - anywhere!). -\end{funcdesc} - -\begin{funcdesc}{compile}{pattern\optional{\, translate}} - Compile a regular expression pattern into a regular expression - object, which can be used for matching using its \code{match} and - \code{search} methods, described below. The optional argument - \var{translate}, if present, must be a 256-character string - indicating how characters (both of the pattern and of the strings to - be matched) are translated before comparing them; the \code{i}-th - element of the string gives the translation for the character with - \ASCII{} code \code{i}. This can be used to implement - case-insensitive matching; see the \code{casefold} data item below. - - The sequence - -\bcode\begin{verbatim} -prog = regex.compile(pat) -result = prog.match(str) -\end{verbatim}\ecode - -is equivalent to - -\bcode\begin{verbatim} -result = regex.match(pat, str) -\end{verbatim}\ecode - -but the version using \code{compile()} is more efficient when multiple -regular expressions are used concurrently in a single program. (The -compiled version of the last pattern passed to \code{regex.match()} or -\code{regex.search()} is cached, so programs that use only a single -regular expression at a time needn't worry about compiling regular -expressions.) -\end{funcdesc} - -\begin{funcdesc}{set_syntax}{flags} - Set the syntax to be used by future calls to \code{compile}, - \code{match} and \code{search}. (Already compiled expression objects - are not affected.) The argument is an integer which is the OR of - several flag bits. The return value is the previous value of - the syntax flags. Names for the flags are defined in the standard - module \code{regex_syntax}; read the file \file{regex_syntax.py} for - more information. -\end{funcdesc} - -\begin{funcdesc}{symcomp}{pattern\optional{\, translate}} -This is like \code{compile}, but supports symbolic group names: if a -parenthesis-enclosed group begins with a group name in angular -brackets, e.g. \code{'\e(<id>[a-z][a-z0-9]*\e)'}, the group can -be referenced by its name in arguments to the \code{group} method of -the resulting compiled regular expression object, like this: -\code{p.group('id')}. Group names may contain alphanumeric characters -and \code{'_'} only. -\end{funcdesc} - -\begin{excdesc}{error} - Exception raised when a string passed to one of the functions here - is not a valid regular expression (e.g., unmatched parentheses) or - when some other error occurs during compilation or matching. (It is - never an error if a string contains no match for a pattern.) -\end{excdesc} - -\begin{datadesc}{casefold} -A string suitable to pass as \var{translate} argument to -\code{compile} to map all upper case characters to their lowercase -equivalents. -\end{datadesc} - -\noindent -Compiled regular expression objects support these methods: - -\renewcommand{\indexsubitem}{(regex method)} -\begin{funcdesc}{match}{string\optional{\, pos}} - Return how many characters at the beginning of \var{string} match - the compiled regular expression. Return \code{-1} if the string - does not match the pattern (this is different from a zero-length - match!). - - The optional second parameter \var{pos} gives an index in the string - where the search is to start; it defaults to \code{0}. This is not - completely equivalent to slicing the string; the \code{'\^'} pattern - character matches at the real begin of the string and at positions - just after a newline, not necessarily at the index where the search - is to start. -\end{funcdesc} - -\begin{funcdesc}{search}{string\optional{\, pos}} - Return the first position in \var{string} that matches the regular - expression \code{pattern}. Return \code{-1} if no position in the - string matches the pattern (this is different from a zero-length - match anywhere!). - - The optional second parameter has the same meaning as for the - \code{match} method. -\end{funcdesc} - -\begin{funcdesc}{group}{index\, index\, ...} -This method is only valid when the last call to the \code{match} -or \code{search} method found a match. It returns one or more -groups of the match. If there is a single \var{index} argument, -the result is a single string; if there are multiple arguments, the -result is a tuple with one item per argument. If the \var{index} is -zero, the corresponding return value is the entire matching string; if -it is in the inclusive range [1..99], it is the string matching the -the corresponding parenthesized group (using the default syntax, -groups are parenthesized using \code{\\(} and \code{\\)}). If no -such group exists, the corresponding result is \code{None}. - -If the regular expression was compiled by \code{symcomp} instead of -\code{compile}, the \var{index} arguments may also be strings -identifying groups by their group name. -\end{funcdesc} - -\noindent -Compiled regular expressions support these data attributes: - -\renewcommand{\indexsubitem}{(regex attribute)} - -\begin{datadesc}{regs} -When the last call to the \code{match} or \code{search} method found a -match, this is a tuple of pairs of indices corresponding to the -beginning and end of all parenthesized groups in the pattern. Indices -are relative to the string argument passed to \code{match} or -\code{search}. The 0-th tuple gives the beginning and end or the -whole pattern. When the last match or search failed, this is -\code{None}. -\end{datadesc} - -\begin{datadesc}{last} -When the last call to the \code{match} or \code{search} method found a -match, this is the string argument passed to that method. When the -last match or search failed, this is \code{None}. -\end{datadesc} - -\begin{datadesc}{translate} -This is the value of the \var{translate} argument to -\code{regex.compile} that created this regular expression object. If -the \var{translate} argument was omitted in the \code{regex.compile} -call, this is \code{None}. -\end{datadesc} - -\begin{datadesc}{givenpat} -The regular expression pattern as passed to \code{compile} or -\code{symcomp}. -\end{datadesc} - -\begin{datadesc}{realpat} -The regular expression after stripping the group names for regular -expressions compiled with \code{symcomp}. Same as \code{givenpat} -otherwise. -\end{datadesc} - -\begin{datadesc}{groupindex} -A dictionary giving the mapping from symbolic group names to numerical -group indices for regular expressions compiled with \code{symcomp}. -\code{None} otherwise. -\end{datadesc} diff --git a/Doc/lib/libregsub.tex b/Doc/lib/libregsub.tex deleted file mode 100644 index 5747e4f99b..0000000000 --- a/Doc/lib/libregsub.tex +++ /dev/null @@ -1,30 +0,0 @@ -\section{Standard Module \sectcode{regsub}} - -\stmodindex{regsub} -This module defines a number of functions useful for working with -regular expressions (see built-in module \code{regex}). - -\renewcommand{\indexsubitem}{(in module regsub)} -\begin{funcdesc}{sub}{pat\, repl\, str} -Replace the first occurrence of pattern \var{pat} in string -\var{str} by replacement \var{repl}. If the pattern isn't found, -the string is returned unchanged. The pattern may be a string or an -already compiled pattern. The replacement may contain references -\samp{\e \var{digit}} to subpatterns and escaped backslashes. -\end{funcdesc} - -\begin{funcdesc}{gsub}{pat\, repl\, str} -Replace all (non-overlapping) occurrences of pattern \var{pat} in -string \var{str} by replacement \var{repl}. The same rules as for -\code{sub()} apply. Empty matches for the pattern are replaced only -when not adjacent to a previous match, so e.g. -\code{gsub('', '-', 'abc')} returns \code{'-a-b-c-'}. -\end{funcdesc} - -\begin{funcdesc}{split}{str\, pat} -Split the string \var{str} in fields separated by delimiters matching -the pattern \var{pat}, and return a list containing the fields. Only -non-empty matches for the pattern are considered, so e.g. -\code{split('a:b', ':*')} returns \code{['a', 'b']} and -\code{split('abc', '')} returns \code{['abc']}. -\end{funcdesc} diff --git a/Doc/lib/librfc822.tex b/Doc/lib/librfc822.tex deleted file mode 100644 index e2d182e89b..0000000000 --- a/Doc/lib/librfc822.tex +++ /dev/null @@ -1,112 +0,0 @@ -\section{Standard Module \sectcode{rfc822}} -\stmodindex{rfc822} - -\renewcommand{\indexsubitem}{(in module rfc822)} - -This module defines a class, \code{Message}, which represents a -collection of ``email headers'' as defined by the Internet standard -RFC 822. It is used in various contexts, usually to read such headers -from a file. - -A \code{Message} instance is instantiated with an open file object as -parameter. Instantiation reads headers from the file up to a blank -line and stores them in the instance; after instantiation, the file is -positioned directly after the blank line that terminates the headers. - -Input lines as read from the file may either be terminated by CR-LF or -by a single linefeed; a terminating CR-LF is replaced by a single -linefeed before the line is stored. - -All header matching is done independent of upper or lower case; -e.g. \code{m['From']}, \code{m['from']} and \code{m['FROM']} all yield -the same result. - -\subsection{Message Objects} - -A \code{Message} instance has the following methods: - -\begin{funcdesc}{rewindbody}{} -Seek to the start of the message body. This only works if the file -object is seekable. -\end{funcdesc} - -\begin{funcdesc}{getallmatchingheaders}{name} -Return a list of lines consisting of all headers matching -\var{name}, if any. Each physical line, whether it is a continuation -line or not, is a separate list item. Return the empty list if no -header matches \var{name}. -\end{funcdesc} - -\begin{funcdesc}{getfirstmatchingheader}{name} -Return a list of lines comprising the first header matching -\var{name}, and its continuation line(s), if any. Return \code{None} -if there is no header matching \var{name}. -\end{funcdesc} - -\begin{funcdesc}{getrawheader}{name} -Return a single string consisting of the text after the colon in the -first header matching \var{name}. This includes leading whitespace, -the trailing linefeed, and internal linefeeds and whitespace if there -any continuation line(s) were present. Return \code{None} if there is -no header matching \var{name}. -\end{funcdesc} - -\begin{funcdesc}{getheader}{name} -Like \code{getrawheader(\var{name})}, but strip leading and trailing -whitespace (but not internal whitespace). -\end{funcdesc} - -\begin{funcdesc}{getaddr}{name} -Return a pair (full name, email address) parsed from the string -returned by \code{getheader(\var{name})}. If no header matching -\var{name} exists, return \code{None, None}; otherwise both the full -name and the address are (possibly empty )strings. - -Example: If \code{m}'s first \code{From} header contains the string\\ -\code{'jack@cwi.nl (Jack Jansen)'}, then -\code{m.getaddr('From')} will yield the pair -\code{('Jack Jansen', 'jack@cwi.nl')}. -If the header contained -\code{'Jack Jansen <jack@cwi.nl>'} instead, it would yield the -exact same result. -\end{funcdesc} - -\begin{funcdesc}{getaddrlist}{name} -This is similar to \code{getaddr(\var{list})}, but parses a header -containing a list of email addresses (e.g. a \code{To} header) and -returns a list of (full name, email address) pairs (even if there was -only one address in the header). If there is no header matching -\var{name}, return an empty list. - -XXX The current version of this function is not really correct. It -yields bogus results if a full name contains a comma. -\end{funcdesc} - -\begin{funcdesc}{getdate}{name} -Retrieve a header using \code{getheader} and parse it into a 9-tuple -compatible with \code{time.mktime()}. If there is no header matching -\var{name}, or it is unparsable, return \code{None}. - -Date parsing appears to be a black art, and not all mailers adhere to -the standard. While it has been tested and found correct on a large -collection of email from many sources, it is still possible that this -function may occasionally yield an incorrect result. -\end{funcdesc} - -\code{Message} instances also support a read-only mapping interface. -In particular: \code{m[name]} is the same as \code{m.getheader(name)}; -and \code{len(m)}, \code{m.has_key(name)}, \code{m.keys()}, -\code{m.values()} and \code{m.items()} act as expected (and -consistently). - -Finally, \code{Message} instances have two public instance variables: - -\begin{datadesc}{headers} -A list containing the entire set of header lines, in the order in -which they were read. Each line contains a trailing newline. The -blank line terminating the headers is not contained in the list. -\end{datadesc} - -\begin{datadesc}{fp} -The file object passed at instantiation time. -\end{datadesc} diff --git a/Doc/lib/librgbimg.tex b/Doc/lib/librgbimg.tex deleted file mode 100644 index ace426fa98..0000000000 --- a/Doc/lib/librgbimg.tex +++ /dev/null @@ -1,45 +0,0 @@ -\section{Built-in Module \sectcode{rgbimg}} -\bimodindex{rgbimg} - -The rgbimg module allows python programs to access SGI imglib image -files (also known as \file{.rgb} files). The module is far from -complete, but is provided anyway since the functionality that there is -is enough in some cases. Currently, colormap files are not supported. - -The module defines the following variables and functions: - -\renewcommand{\indexsubitem}{(in module rgbimg)} -\begin{excdesc}{error} -This exception is raised on all errors, such as unsupported file type, etc. -\end{excdesc} - -\begin{funcdesc}{sizeofimage}{file} -This function returns a tuple \code{(\var{x}, \var{y})} where -\var{x} and \var{y} are the size of the image in pixels. -Only 4 byte RGBA pixels, 3 byte RGB pixels, and 1 byte greyscale pixels -are currently supported. -\end{funcdesc} - -\begin{funcdesc}{longimagedata}{file} -This function reads and decodes the image on the specified file, and -returns it as a Python string. The string has 4 byte RGBA pixels. -The bottom left pixel is the first in -the string. This format is suitable to pass to \code{gl.lrectwrite}, -for instance. -\end{funcdesc} - -\begin{funcdesc}{longstoimage}{data\, x\, y\, z\, file} -This function writes the RGBA data in \var{data} to image -file \var{file}. \var{x} and \var{y} give the size of the image. -\var{z} is 1 if the saved image should be 1 byte greyscale, 3 if the -saved image should be 3 byte RGB data, or 4 if the saved images should -be 4 byte RGBA data. The input data always contains 4 bytes per pixel. -These are the formats returned by \code{gl.lrectread}. -\end{funcdesc} - -\begin{funcdesc}{ttob}{flag} -This function sets a global flag which defines whether the scan lines -of the image are read or written from bottom to top (flag is zero, -compatible with SGI GL) or from top to bottom(flag is one, -compatible with X)\@. The default is zero. -\end{funcdesc} diff --git a/Doc/lib/librotor.tex b/Doc/lib/librotor.tex deleted file mode 100644 index 6befb05590..0000000000 --- a/Doc/lib/librotor.tex +++ /dev/null @@ -1,105 +0,0 @@ -\section{Built-in Module \sectcode{rotor}} -\bimodindex{rotor} - -This module implements a rotor-based encryption algorithm, contributed by -Lance Ellinghouse. The design is derived from the Enigma device, a machine -used during World War II to encipher messages. A rotor is simply a -permutation. For example, if the character `A' is the origin of the rotor, -then a given rotor might map `A' to `L', `B' to `Z', `C' to `G', and so on. -To encrypt, we choose several different rotors, and set the origins of the -rotors to known positions; their initial position is the ciphering key. To -encipher a character, we permute the original character by the first rotor, -and then apply the second rotor's permutation to the result. We continue -until we've applied all the rotors; the resulting character is our -ciphertext. We then change the origin of the final rotor by one position, -from `A' to `B'; if the final rotor has made a complete revolution, then we -rotate the next-to-last rotor by one position, and apply the same procedure -recursively. In other words, after enciphering one character, we advance -the rotors in the same fashion as a car's odometer. Decoding works in the -same way, except we reverse the permutations and apply them in the opposite -order. -\index{Ellinghouse, Lance} -\indexii{Enigma}{cipher} - -The available functions in this module are: - -\renewcommand{\indexsubitem}{(in module rotor)} -\begin{funcdesc}{newrotor}{key\optional{\, numrotors}} -Return a rotor object. \var{key} is a string containing the encryption key -for the object; it can contain arbitrary binary data. The key will be used -to randomly generate the rotor permutations and their initial positions. -\var{numrotors} is the number of rotor permutations in the returned object; -if it is omitted, a default value of 6 will be used. -\end{funcdesc} - -Rotor objects have the following methods: - -\renewcommand{\indexsubitem}{(rotor method)} -\begin{funcdesc}{setkey}{} -Reset the rotor to its initial state. -\end{funcdesc} - -\begin{funcdesc}{encrypt}{plaintext} -Reset the rotor object to its initial state and encrypt \var{plaintext}, -returning a string containing the ciphertext. The ciphertext is always the -same length as the original plaintext. -\end{funcdesc} - -\begin{funcdesc}{encryptmore}{plaintext} -Encrypt \var{plaintext} without resetting the rotor object, and return a -string containing the ciphertext. -\end{funcdesc} - -\begin{funcdesc}{decrypt}{ciphertext} -Reset the rotor object to its initial state and decrypt \var{ciphertext}, -returning a string containing the ciphertext. The plaintext string will -always be the same length as the ciphertext. -\end{funcdesc} - -\begin{funcdesc}{decryptmore}{ciphertext} -Decrypt \var{ciphertext} without resetting the rotor object, and return a -string containing the ciphertext. -\end{funcdesc} - -An example usage: -\bcode\begin{verbatim} ->>> import rotor ->>> rt = rotor.newrotor('key', 12) ->>> rt.encrypt('bar') -'\2534\363' ->>> rt.encryptmore('bar') -'\357\375$' ->>> rt.encrypt('bar') -'\2534\363' ->>> rt.decrypt('\2534\363') -'bar' ->>> rt.decryptmore('\357\375$') -'bar' ->>> rt.decrypt('\357\375$') -'l(\315' ->>> del rt -\end{verbatim}\ecode - -The module's code is not an exact simulation of the original Enigma device; -it implements the rotor encryption scheme differently from the original. The -most important difference is that in the original Enigma, there were only 5 -or 6 different rotors in existence, and they were applied twice to each -character; the cipher key was the order in which they were placed in the -machine. The Python rotor module uses the supplied key to initialize a -random number generator; the rotor permutations and their initial positions -are then randomly generated. The original device only enciphered the -letters of the alphabet, while this module can handle any 8-bit binary data; -it also produces binary output. This module can also operate with an -arbitrary number of rotors. - -The original Enigma cipher was broken in 1944. % XXX: Is this right? -The version implemented here is probably a good deal more difficult to crack -(especially if you use many rotors), but it won't be impossible for -a truly skilful and determined attacker to break the cipher. So if you want -to keep the NSA out of your files, this rotor cipher may well be unsafe, but -for discouraging casual snooping through your files, it will probably be -just fine, and may be somewhat safer than using the Unix \file{crypt} -command. -\index{National Security Agency}\index{crypt(1)} -% XXX How were Unix commands represented in the docs? - diff --git a/Doc/lib/libselect.tex b/Doc/lib/libselect.tex deleted file mode 100644 index 0b50101395..0000000000 --- a/Doc/lib/libselect.tex +++ /dev/null @@ -1,42 +0,0 @@ -\section{Built-in Module \sectcode{select}} -\bimodindex{select} - -This module provides access to the function \code{select} available in -most \UNIX{} versions. It defines the following: - -\renewcommand{\indexsubitem}{(in module select)} -\begin{excdesc}{error} -The exception raised when an error occurs. The accompanying value is -a pair containing the numeric error code from \code{errno} and the -corresponding string, as would be printed by the C function -\code{perror()}. -\end{excdesc} - -\begin{funcdesc}{select}{iwtd\, owtd\, ewtd\optional{\, timeout}} -This is a straightforward interface to the \UNIX{} \code{select()} -system call. The first three arguments are lists of `waitable -objects': either integers representing \UNIX{} file descriptors or -objects with a parameterless method named \code{fileno()} returning -such an integer. The three lists of waitable objects are for input, -output and `exceptional conditions', respectively. Empty lists are -allowed. The optional \var{timeout} argument specifies a time-out as a -floating point number in seconds. When the \var{timeout} argument -is omitted the function blocks until at least one file descriptor is -ready. A time-out value of zero specifies a poll and never blocks. - -The return value is a triple of lists of objects that are ready: -subsets of the first three arguments. When the time-out is reached -without a file descriptor becoming ready, three empty lists are -returned. - -Amongst the acceptable object types in the lists are Python file -objects (e.g. \code{sys.stdin}, or objects returned by \code{open()} -or \code{posix.popen()}), socket objects returned by -\code{socket.socket()}, and the module \code{stdwin} which happens to -define a function \code{fileno()} for just this purpose. You may -also define a \dfn{wrapper} class yourself, as long as it has an -appropriate \code{fileno()} method (that really returns a \UNIX{} file -descriptor, not just a random integer). -\end{funcdesc} -\ttindex{socket} -\ttindex{stdwin} diff --git a/Doc/lib/libsgi.tex b/Doc/lib/libsgi.tex deleted file mode 100644 index 8deede84a8..0000000000 --- a/Doc/lib/libsgi.tex +++ /dev/null @@ -1,4 +0,0 @@ -\chapter{SGI IRIX Specific Services} - -The modules described in this chapter provide interfaces to features -that are unique to SGI's IRIX operating system (versions 4 and 5). diff --git a/Doc/lib/libsgmllib.tex b/Doc/lib/libsgmllib.tex deleted file mode 100644 index 129bdd9adc..0000000000 --- a/Doc/lib/libsgmllib.tex +++ /dev/null @@ -1,148 +0,0 @@ -\section{Standard Module \sectcode{sgmllib}} -\stmodindex{sgmllib} -\index{SGML} - -\renewcommand{\indexsubitem}{(in module sgmllib)} - -This module defines a class \code{SGMLParser} which serves as the -basis for parsing text files formatted in SGML (Standard Generalized -Mark-up Language). In fact, it does not provide a full SGML parser ---- it only parses SGML insofar as it is used by HTML, and the module only -exists as a basis for the \code{htmllib} module. -\stmodindex{htmllib} - -In particular, the parser is hardcoded to recognize the following -elements: - -\begin{itemize} - -\item -Opening and closing tags of the form -``\code{<\var{tag} \var{attr}="\var{value}" ...>}'' and -``\code{</\var{tag}>}'', respectively. - -\item -Character references of the form ``\code{\&\#\var{name};}''. - -\item -Entity references of the form ``\code{\&\var{name};}''. - -\item -SGML comments of the form ``\code{<!--\var{text}>}''. - -\end{itemize} - -The \code{SGMLParser} class must be instantiated without arguments. -It has the following interface methods: - -\begin{funcdesc}{reset}{} -Reset the instance. Loses all unprocessed data. This is called -implicitly at instantiation time. -\end{funcdesc} - -\begin{funcdesc}{setnomoretags}{} -Stop processing tags. Treat all following input as literal input -(CDATA). (This is only provided so the HTML tag \code{<PLAINTEXT>} -can be implemented.) -\end{funcdesc} - -\begin{funcdesc}{setliteral}{} -Enter literal mode (CDATA mode). -\end{funcdesc} - -\begin{funcdesc}{feed}{data} -Feed some text to the parser. It is processed insofar as it consists -of complete elements; incomplete data is buffered until more data is -fed or \code{close()} is called. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Force processing of all buffered data as if it were followed by an -end-of-file mark. This method may be redefined by a derived class to -define additional processing at the end of the input, but the -redefined version should always call \code{SGMLParser.close()}. -\end{funcdesc} - -\begin{funcdesc}{handle_charref}{ref} -This method is called to process a character reference of the form -``\code{\&\#\var{ref};}'' where \var{ref} is a decimal number in the -range 0-255. It translates the character to \ASCII{} and calls the -method \code{handle_data()} with the character as argument. If -\var{ref} is invalid or out of range, the method -\code{unknown_charref(\var{ref})} is called instead. -\end{funcdesc} - -\begin{funcdesc}{handle_entityref}{ref} -This method is called to process an entity reference of the form -``\code{\&\var{ref};}'' where \var{ref} is an alphabetic entity -reference. It looks for \var{ref} in the instance (or class) -variable \code{entitydefs} which should give the entity's translation. -If a translation is found, it calls the method \code{handle_data()} -with the translation; otherwise, it calls the method -\code{unknown_entityref(\var{ref})}. -\end{funcdesc} - -\begin{funcdesc}{handle_data}{data} -This method is called to process arbitrary data. It is intended to be -overridden by a derived class; the base class implementation does -nothing. -\end{funcdesc} - -\begin{funcdesc}{unknown_starttag}{tag\, attributes} -This method is called to process an unknown start tag. It is intended -to be overridden by a derived class; the base class implementation -does nothing. The \var{attributes} argument is a list of -(\var{name}, \var{value}) pairs containing the attributes found inside -the tag's \code{<>} brackets. The \var{name} has been translated to -lower case and double quotes and backslashes in the \var{value} have -been interpreted. For instance, for the tag -\code{<A HREF="http://www.cwi.nl/">}, this method would be -called as \code{unknown_starttag('a', [('href', 'http://www.cwi.nl/')])}. -\end{funcdesc} - -\begin{funcdesc}{unknown_endtag}{tag} -This method is called to process an unknown end tag. It is intended -to be overridden by a derived class; the base class implementation -does nothing. -\end{funcdesc} - -\begin{funcdesc}{unknown_charref}{ref} -This method is called to process an unknown character reference. It -is intended to be overridden by a derived class; the base class -implementation does nothing. -\end{funcdesc} - -\begin{funcdesc}{unknown_entityref}{ref} -This method is called to process an unknown entity reference. It is -intended to be overridden by a derived class; the base class -implementation does nothing. -\end{funcdesc} - -Apart from overriding or extending the methods listed above, derived -classes may also define methods of the following form to define -processing of specific tags. Tag names in the input stream are case -independent; the \var{tag} occurring in method names must be in lower -case: - -\begin{funcdesc}{start_\var{tag}}{attributes} -This method is called to process an opening tag \var{tag}. It has -preference over \code{do_\var{tag}()}. The \var{attributes} argument -has the same meaning as described for \code{unknown_tag()} above. -\end{funcdesc} - -\begin{funcdesc}{do_\var{tag}}{attributes} -This method is called to process an opening tag \var{tag} that does -not come with a matching closing tag. The \var{attributes} argument -has the same meaning as described for \code{unknown_tag()} above. -\end{funcdesc} - -\begin{funcdesc}{end_\var{tag}}{} -This method is called to process a closing tag \var{tag}. -\end{funcdesc} - -Note that the parser maintains a stack of opening tags for which no -matching closing tag has been found yet. Only tags processed by -\code{start_\var{tag}()} are pushed on this stack. Definition of a -\code{end_\var{tag}()} method is optional for these tags. For tags -processed by \code{do_\var{tag}()} or by \code{unknown_tag()}, no -\code{end_\var{tag}()} method must be defined. diff --git a/Doc/lib/libshelve.tex b/Doc/lib/libshelve.tex deleted file mode 100644 index a232add09d..0000000000 --- a/Doc/lib/libshelve.tex +++ /dev/null @@ -1,59 +0,0 @@ -\section{Standard Module \sectcode{shelve}} -\stmodindex{shelve} -\stmodindex{pickle} -\bimodindex{dbm} -\bimodindex{gdbm} - -A ``shelf'' is a persistent, dictionary-like object. The difference -with ``dbm'' databases is that the values (not the keys!) in a shelf -can be essentially arbitrary Python objects --- anything that the -\code{pickle} module can handle. This includes most class instances, -recursive data types, and objects containing lots of shared -sub-objects. The keys are ordinary strings. - -To summarize the interface (\code{key} is a string, \code{data} is an -arbitrary object): - -\begin{verbatim} -import shelve - -d = shelve.open(filename) # open, with (g)dbm filename -- no suffix - -d[key] = data # store data at key (overwrites old data if - # using an existing key) -data = d[key] # retrieve data at key (raise KeyError if no - # such key) -del d[key] # delete data stored at key (raises KeyError - # if no such key) -flag = d.has_key(key) # true if the key exists -list = d.keys() # a list of all existing keys (slow!) - -d.close() # close it -\end{verbatim} - -Restrictions: - -\begin{itemize} - -\item -The choice of which database package will be used (e.g. dbm or gdbm) -depends on which interface is available. Therefore it isn't safe to -open the database directly using dbm. The database is also -(unfortunately) subject to the limitations of dbm, if it is used --- -this means that (the pickled representation of) the objects stored in -the database should be fairly small, and in rare cases key collisions -may cause the database to refuse updates. - -\item -Dependent on the implementation, closing a persistent dictionary may -or may not be necessary to flush changes to disk. - -\item -The \code{shelve} module does not support {\em concurrent} read/write -access to shelved objects. (Multiple simultaneous read accesses are -safe.) When a program has a shelf open for writing, no other program -should have it open for reading or writing. \UNIX{} file locking can -be used to solve this, but this differs across \UNIX{} versions and -requires knowledge about the database implementation used. - -\end{itemize} diff --git a/Doc/lib/libsignal.tex b/Doc/lib/libsignal.tex deleted file mode 100644 index 802c4d107f..0000000000 --- a/Doc/lib/libsignal.tex +++ /dev/null @@ -1,139 +0,0 @@ -\section{Built-in Module \sectcode{signal}} - -\bimodindex{signal} -This module provides mechanisms to use signal handlers in Python. -Some general rules for working with signals handlers: - -\begin{itemize} - -\item -A handler for a particular signal, once set, remains installed until -it is explicitly reset (i.e. Python emulates the BSD style interface -regardless of the underlying implementation), with the exception of -the handler for \code{SIGCHLD}, which follows the underlying -implementation. - -\item -There is no way to ``block'' signals temporarily from critical -sections (since this is not supported by all \UNIX{} flavors). - -\item -Although Python signal handlers are called asynchronously as far as -the Python user is concerned, they can only occur between the -``atomic'' instructions of the Python interpreter. This means that -signals arriving during long calculations implemented purely in C -(e.g.\ regular expression matches on large bodies of text) may be -delayed for an arbitrary amount of time. - -\item -When a signal arrives during an I/O operation, it is possible that the -I/O operation raises an exception after the signal handler returns. -This is dependent on the underlying \UNIX{} system's semantics regarding -interrupted system calls. - -\item -Because the C signal handler always returns, it makes little sense to -catch synchronous errors like \code{SIGFPE} or \code{SIGSEGV}. - -\item -Python installs a small number of signal handlers by default: -\code{SIGPIPE} is ignored (so write errors on pipes and sockets can be -reported as ordinary Python exceptions), \code{SIGINT} is translated -into a \code{KeyboardInterrupt} exception, and \code{SIGTERM} is -caught so that necessary cleanup (especially \code{sys.exitfunc}) can -be performed before actually terminating. All of these can be -overridden. - -\item -Some care must be taken if both signals and threads are used in the -same program. The fundamental thing to remember in using signals and -threads simultaneously is:\ always perform \code{signal()} operations -in the main thread of execution. Any thread can perform an -\code{alarm()}, \code{getsignal()}, or \code{pause()}; only the main -thread can set a new signal handler, and the main thread will be the -only one to receive signals (this is enforced by the Python signal -module, even if the underlying thread implementation supports sending -signals to individual threads). This means that signals can't be used -as a means of interthread communication. Use locks instead. - -\end{itemize} - -The variables defined in the signal module are: - -\renewcommand{\indexsubitem}{(in module signal)} -\begin{datadesc}{SIG_DFL} - This is one of two standard signal handling options; it will simply - perform the default function for the signal. For example, on most - systems the default action for SIGQUIT is to dump core and exit, - while the default action for SIGCLD is to simply ignore it. -\end{datadesc} - -\begin{datadesc}{SIG_IGN} - This is another standard signal handler, which will simply ignore - the given signal. -\end{datadesc} - -\begin{datadesc}{SIG*} - All the signal numbers are defined symbolically. For example, the - hangup signal is defined as \code{signal.SIGHUP}; the variable names - are identical to the names used in C programs, as found in - \file{signal.h}. - The \UNIX{} man page for \file{signal} lists the existing signals (on - some systems this is \file{signal(2)}, on others the list is in - \file{signal(7)}). - Note that not all systems define the same set of signal names; only - those names defined by the system are defined by this module. -\end{datadesc} - -\begin{datadesc}{NSIG} - One more than the number of the highest signal number. -\end{datadesc} - -The signal module defines the following functions: - -\begin{funcdesc}{alarm}{time} - If \var{time} is non-zero, this function requests that a - \code{SIGALRM} signal be sent to the process in \var{time} seconds. - Any previously scheduled alarm is canceled (i.e.\ only one alarm can - be scheduled at any time). The returned value is then the number of - seconds before any previously set alarm was to have been delivered. - If \var{time} is zero, no alarm id scheduled, and any scheduled - alarm is canceled. The return value is the number of seconds - remaining before a previously scheduled alarm. If the return value - is zero, no alarm is currently scheduled. (See the \UNIX{} man page - \code{alarm(2)}.) -\end{funcdesc} - -\begin{funcdesc}{getsignal}{signalnum} - Return the current signal handler for the signal \var{signalnum}. - The returned value may be a callable Python object, or one of the - special values \code{signal.SIG_IGN}, \code{signal.SIG_DFL} or - \code{None}. Here, \code{signal.SIG_IGN} means that the signal was - previously ignored, \code{signal.SIG_DFL} means that the default way - of handling the signal was previously in use, and \code{None} means - that the previous signal handler was not installed from Python. -\end{funcdesc} - -\begin{funcdesc}{pause}{} - Cause the process to sleep until a signal is received; the - appropriate handler will then be called. Returns nothing. (See the - \UNIX{} man page \code{signal(2)}.) -\end{funcdesc} - -\begin{funcdesc}{signal}{signalnum\, handler} - Set the handler for signal \var{signalnum} to the function - \var{handler}. \var{handler} can be any callable Python object, or - one of the special values \code{signal.SIG_IGN} or - \code{signal.SIG_DFL}. The previous signal handler will be returned - (see the description of \code{getsignal()} above). (See the \UNIX{} - man page \code{signal(2)}.) - - When threads are enabled, this function can only be called from the - main thread; attempting to call it from other threads will cause a - \code{ValueError} exception to be raised. - - The \var{handler} is called with two arguments: the signal number - and the current stack frame (\code{None} or a frame object; see the - reference manual for a description of frame objects). -\obindex{frame} -\end{funcdesc} diff --git a/Doc/lib/libsocket.tex b/Doc/lib/libsocket.tex deleted file mode 100644 index 9b3c2285c2..0000000000 --- a/Doc/lib/libsocket.tex +++ /dev/null @@ -1,317 +0,0 @@ -\section{Built-in Module \sectcode{socket}} - -\bimodindex{socket} -This module provides access to the BSD {\em socket} interface. -It is available on \UNIX{} systems that support this interface. - -For an introduction to socket programming (in C), see the following -papers: \emph{An Introductory 4.3BSD Interprocess Communication -Tutorial}, by Stuart Sechrest and \emph{An Advanced 4.3BSD Interprocess -Communication Tutorial}, by Samuel J. Leffler et al, both in the -\UNIX{} Programmer's Manual, Supplementary Documents 1 (sections PS1:7 -and PS1:8). The \UNIX{} manual pages for the various socket-related -system calls are also a valuable source of information on the details of -socket semantics. - -The Python interface is a straightforward transliteration of the -\UNIX{} system call and library interface for sockets to Python's -object-oriented style: the \code{socket()} function returns a -\dfn{socket object} whose methods implement the various socket system -calls. Parameter types are somewhat higer-level than in the C -interface: as with \code{read()} and \code{write()} operations on Python -files, buffer allocation on receive operations is automatic, and -buffer length is implicit on send operations. - -Socket addresses are represented as a single string for the -\code{AF_UNIX} address family and as a pair -\code{(\var{host}, \var{port})} for the \code{AF_INET} address family, -where \var{host} is a string representing -either a hostname in Internet domain notation like -\code{'daring.cwi.nl'} or an IP address like \code{'100.50.200.5'}, -and \var{port} is an integral port number. Other address families are -currently not supported. The address format required by a particular -socket object is automatically selected based on the address family -specified when the socket object was created. - -All errors raise exceptions. The normal exceptions for invalid -argument types and out-of-memory conditions can be raised; errors -related to socket or address semantics raise the error \code{socket.error}. - -Non-blocking mode is supported through the \code{setblocking()} -method. - -The module \code{socket} exports the following constants and functions: - -\renewcommand{\indexsubitem}{(in module socket)} -\begin{excdesc}{error} -This exception is raised for socket- or address-related errors. -The accompanying value is either a string telling what went wrong or a -pair \code{(\var{errno}, \var{string})} -representing an error returned by a system -call, similar to the value accompanying \code{posix.error}. -\end{excdesc} - -\begin{datadesc}{AF_UNIX} -\dataline{AF_INET} -These constants represent the address (and protocol) families, -used for the first argument to \code{socket()}. If the \code{AF_UNIX} -constant is not defined then this protocol is unsupported. -\end{datadesc} - -\begin{datadesc}{SOCK_STREAM} -\dataline{SOCK_DGRAM} -\dataline{SOCK_RAW} -\dataline{SOCK_RDM} -\dataline{SOCK_SEQPACKET} -These constants represent the socket types, -used for the second argument to \code{socket()}. -(Only \code{SOCK_STREAM} and -\code{SOCK_DGRAM} appear to be generally useful.) -\end{datadesc} - -\begin{datadesc}{SO_*} -\dataline{SOMAXCONN} -\dataline{MSG_*} -\dataline{SOL_*} -\dataline{IPPROTO_*} -\dataline{IPPORT_*} -\dataline{INADDR_*} -\dataline{IP_*} -Many constants of these forms, documented in the \UNIX{} documentation on -sockets and/or the IP protocol, are also defined in the socket module. -They are generally used in arguments to the \code{setsockopt} and -\code{getsockopt} methods of socket objects. In most cases, only -those symbols that are defined in the \UNIX{} header files are defined; -for a few symbols, default values are provided. -\end{datadesc} - -\begin{funcdesc}{gethostbyname}{hostname} -Translate a host name to IP address format. The IP address is -returned as a string, e.g., \code{'100.50.200.5'}. If the host name -is an IP address itself it is returned unchanged. -\end{funcdesc} - -\begin{funcdesc}{gethostname}{} -Return a string containing the hostname of the machine where -the Python interpreter is currently executing. If you want to know the -current machine's IP address, use -\code{socket.gethostbyname(socket.gethostname())}. -\end{funcdesc} - -\begin{funcdesc}{gethostbyaddr}{ip_address} -Return a triple \code{(hostname, aliaslist, ipaddrlist)} where -\code{hostname} is the primary host name responding to the given -\var{ip_address}, \code{aliaslist} is a (possibly empty) list of -alternative host names for the same address, and \code{ipaddrlist} is -a list of IP addresses for the same interface on the same -host (most likely containing only a single address). -\end{funcdesc} - -\begin{funcdesc}{getservbyname}{servicename\, protocolname} -Translate an Internet service name and protocol name to a port number -for that service. The protocol name should be \code{'tcp'} or -\code{'udp'}. -\end{funcdesc} - -\begin{funcdesc}{socket}{family\, type\optional{\, proto}} -Create a new socket using the given address family, socket type and -protocol number. The address family should be \code{AF_INET} or -\code{AF_UNIX}. The socket type should be \code{SOCK_STREAM}, -\code{SOCK_DGRAM} or perhaps one of the other \samp{SOCK_} constants. -The protocol number is usually zero and may be omitted in that case. -\end{funcdesc} - -\begin{funcdesc}{fromfd}{fd\, family\, type\optional{\, proto}} -Build a socket object from an existing file descriptor (an integer as -returned by a file object's \code{fileno} method). Address family, -socket type and protocol number are as for the \code{socket} function -above. The file descriptor should refer to a socket, but this is not -checked --- subsequent operations on the object may fail if the file -descriptor is invalid. This function is rarely needed, but can be -used to get or set socket options on a socket passed to a program as -standard input or output (e.g.\ a server started by the \UNIX{} inet -daemon). -\end{funcdesc} - -\subsection{Socket Objects} - -\noindent -Socket objects have the following methods. Except for -\code{makefile()} these correspond to \UNIX{} system calls applicable to -sockets. - -\renewcommand{\indexsubitem}{(socket method)} -\begin{funcdesc}{accept}{} -Accept a connection. -The socket must be bound to an address and listening for connections. -The return value is a pair \code{(\var{conn}, \var{address})} -where \var{conn} is a \emph{new} socket object usable to send and -receive data on the connection, and \var{address} is the address bound -to the socket on the other end of the connection. -\end{funcdesc} - -\begin{funcdesc}{bind}{address} -Bind the socket to \var{address}. The socket must not already be bound. -(The format of \var{address} depends on the address family --- see above.) -\end{funcdesc} - -\begin{funcdesc}{close}{} -Close the socket. All future operations on the socket object will fail. -The remote end will receive no more data (after queued data is flushed). -Sockets are automatically closed when they are garbage-collected. -\end{funcdesc} - -\begin{funcdesc}{connect}{address} -Connect to a remote socket at \var{address}. -(The format of \var{address} depends on the address family --- see above.) -\end{funcdesc} - -\begin{funcdesc}{fileno}{} -Return the socket's file descriptor (a small integer). This is useful -with \code{select}. -\end{funcdesc} - -\begin{funcdesc}{getpeername}{} -Return the remote address to which the socket is connected. This is -useful to find out the port number of a remote IP socket, for instance. -(The format of the address returned depends on the address family --- -see above.) On some systems this function is not supported. -\end{funcdesc} - -\begin{funcdesc}{getsockname}{} -Return the socket's own address. This is useful to find out the port -number of an IP socket, for instance. -(The format of the address returned depends on the address family --- -see above.) -\end{funcdesc} - -\begin{funcdesc}{getsockopt}{level\, optname\optional{\, buflen}} -Return the value of the given socket option (see the \UNIX{} man page -{\it getsockopt}(2)). The needed symbolic constants (\code{SO_*} etc.) -are defined in this module. If \var{buflen} -is absent, an integer option is assumed and its integer value -is returned by the function. If \var{buflen} is present, it specifies -the maximum length of the buffer used to receive the option in, and -this buffer is returned as a string. It is up to the caller to decode -the contents of the buffer (see the optional built-in module -\code{struct} for a way to decode C structures encoded as strings). -\end{funcdesc} - -\begin{funcdesc}{listen}{backlog} -Listen for connections made to the socket. The \var{backlog} argument -specifies the maximum number of queued connections and should be at -least 1; the maximum value is system-dependent (usually 5). -\end{funcdesc} - -\begin{funcdesc}{makefile}{\optional{mode\optional{\, bufsize}}} -Return a \dfn{file object} associated with the socket. (File objects -were described earlier under Built-in Types.) The file object -references a \code{dup()}ped version of the socket file descriptor, so -the file object and socket object may be closed or garbage-collected -independently. The optional \var{mode} and \var{bufsize} arguments -are interpreted the same way as by the built-in -\code{open()} function. -\end{funcdesc} - -\begin{funcdesc}{recv}{bufsize\optional{\, flags}} -Receive data from the socket. The return value is a string representing -the data received. The maximum amount of data to be received -at once is specified by \var{bufsize}. See the \UNIX{} manual page -for the meaning of the optional argument \var{flags}; it defaults to -zero. -\end{funcdesc} - -\begin{funcdesc}{recvfrom}{bufsize\optional{\, flags}} -Receive data from the socket. The return value is a pair -\code{(\var{string}, \var{address})} where \var{string} is a string -representing the data received and \var{address} is the address of the -socket sending the data. The optional \var{flags} argument has the -same meaning as for \code{recv()} above. -(The format of \var{address} depends on the address family --- see above.) -\end{funcdesc} - -\begin{funcdesc}{send}{string\optional{\, flags}} -Send data to the socket. The socket must be connected to a remote -socket. The optional \var{flags} argument has the same meaning as for -\code{recv()} above. Return the number of bytes sent. -\end{funcdesc} - -\begin{funcdesc}{sendto}{string\optional{\, flags}\, address} -Send data to the socket. The socket should not be connected to a -remote socket, since the destination socket is specified by -\code{address}. The optional \var{flags} argument has the same -meaning as for \code{recv()} above. Return the number of bytes sent. -(The format of \var{address} depends on the address family --- see above.) -\end{funcdesc} - -\begin{funcdesc}{setblocking}{flag} -Set blocking or non-blocking mode of the socket: if \var{flag} is 0, -the socket is set to non-blocking, else to blocking mode. Initially -all sockets are in blocking mode. In non-blocking mode, if a -\code{recv} call doesn't find any data, or if a \code{send} call can't -immediately dispose of the data, a \code{socket.error} exception is -raised; in blocking mode, the calls block until they can proceed. -\end{funcdesc} - -\begin{funcdesc}{setsockopt}{level\, optname\, value} -Set the value of the given socket option (see the \UNIX{} man page -{\it setsockopt}(2)). The needed symbolic constants are defined in -the \code{socket} module (\code{SO_*} etc.). The value can be an -integer or a string representing a buffer. In the latter case it is -up to the caller to ensure that the string contains the proper bits -(see the optional built-in module -\code{struct} for a way to encode C structures as strings). -\end{funcdesc} - -\begin{funcdesc}{shutdown}{how} -Shut down one or both halves of the connection. If \var{how} is \code{0}, -further receives are disallowed. If \var{how} is \code{1}, further sends are -disallowed. If \var{how} is \code{2}, further sends and receives are -disallowed. -\end{funcdesc} - -Note that there are no methods \code{read()} or \code{write()}; use -\code{recv()} and \code{send()} without \var{flags} argument instead. - -\subsection{Example} -\nodename{Socket Example} - -Here are two minimal example programs using the TCP/IP protocol:\ a -server that echoes all data that it receives back (servicing only one -client), and a client using it. Note that a server must perform the -sequence \code{socket}, \code{bind}, \code{listen}, \code{accept} -(possibly repeating the \code{accept} to service more than one client), -while a client only needs the sequence \code{socket}, \code{connect}. -Also note that the server does not \code{send}/\code{receive} on the -socket it is listening on but on the new socket returned by -\code{accept}. - -\bcode\begin{verbatim} -# Echo server program -from socket import * -HOST = '' # Symbolic name meaning the local host -PORT = 50007 # Arbitrary non-privileged server -s = socket(AF_INET, SOCK_STREAM) -s.bind(HOST, PORT) -s.listen(1) -conn, addr = s.accept() -print 'Connected by', addr -while 1: - data = conn.recv(1024) - if not data: break - conn.send(data) -conn.close() -\end{verbatim}\ecode - -\bcode\begin{verbatim} -# Echo client program -from socket import * -HOST = 'daring.cwi.nl' # The remote host -PORT = 50007 # The same port as used by the server -s = socket(AF_INET, SOCK_STREAM) -s.connect(HOST, PORT) -s.send('Hello, world') -data = s.recv(1024) -s.close() -print 'Received', `data` -\end{verbatim}\ecode diff --git a/Doc/lib/libsomeos.tex b/Doc/lib/libsomeos.tex deleted file mode 100644 index f9aedfe315..0000000000 --- a/Doc/lib/libsomeos.tex +++ /dev/null @@ -1,23 +0,0 @@ -\chapter{Optional Operating System Services} - -The modules described in this chapter provide interfaces to operating -system features that are available on selected operating systems only. -The interfaces are generally modelled after the \UNIX{} or C -interfaces but they are available on some other systems as well -(e.g. Windows or NT). Here's an overview: - -\begin{description} - -\item[signal] ---- Set handlers for asynchronous events. - -\item[socket] ---- Low-level networking interface. - -\item[select] ---- Wait for I/O completion on multiple streams. - -\item[thread] ---- Create multiple threads of control within one namespace. - -\end{description} diff --git a/Doc/lib/libstdwin.tex b/Doc/lib/libstdwin.tex deleted file mode 100644 index e009e3f0e0..0000000000 --- a/Doc/lib/libstdwin.tex +++ /dev/null @@ -1,910 +0,0 @@ -\chapter{Standard Windowing Interface} - -The modules in this chapter are available only on those systems where -the STDWIN library is available. STDWIN runs on \UNIX{} under X11 and -on the Macintosh. See CWI report CS-R8817. - -\strong{Warning:} Using STDWIN is not recommended for new -applications. It has never been ported to Microsoft Windows or -Windows NT, and for X11 or the Macintosh it lacks important -functionality --- in particular, it has no tools for the construction -of dialogs. For most platforms, alternative, native solutions exist -(though none are currently documented in this manual): Tkinter for -\UNIX{} under X11, native Xt with Motif or Athena widgets for \UNIX{} -under X11, Win32 for Windows and Windows NT, and a collection of -native toolkit interfaces for the Macintosh. - -\section{Built-in Module \sectcode{stdwin}} -\bimodindex{stdwin} - -This module defines several new object types and functions that -provide access to the functionality of STDWIN. - -On Unix running X11, it can only be used if the \code{DISPLAY} -environment variable is set or an explicit \samp{-display -\var{displayname}} argument is passed to the Python interpreter. - -Functions have names that usually resemble their C STDWIN counterparts -with the initial `w' dropped. -Points are represented by pairs of integers; rectangles -by pairs of points. -For a complete description of STDWIN please refer to the documentation -of STDWIN for C programmers (aforementioned CWI report). - -\subsection{Functions Defined in Module \sectcode{stdwin}} -\nodename{STDWIN Functions} - -The following functions are defined in the \code{stdwin} module: - -\renewcommand{\indexsubitem}{(in module stdwin)} -\begin{funcdesc}{open}{title} -Open a new window whose initial title is given by the string argument. -Return a window object; window object methods are described below.% -\footnote{The Python version of STDWIN does not support draw procedures; all - drawing requests are reported as draw events.} -\end{funcdesc} - -\begin{funcdesc}{getevent}{} -Wait for and return the next event. -An event is returned as a triple: the first element is the event -type, a small integer; the second element is the window object to which -the event applies, or -\code{None} -if it applies to no window in particular; -the third element is type-dependent. -Names for event types and command codes are defined in the standard -module -\code{stdwinevent}. -\end{funcdesc} - -\begin{funcdesc}{pollevent}{} -Return the next event, if one is immediately available. -If no event is available, return \code{()}. -\end{funcdesc} - -\begin{funcdesc}{getactive}{} -Return the window that is currently active, or \code{None} if no -window is currently active. (This can be emulated by monitoring -WE_ACTIVATE and WE_DEACTIVATE events.) -\end{funcdesc} - -\begin{funcdesc}{listfontnames}{pattern} -Return the list of font names in the system that match the pattern (a -string). The pattern should normally be \code{'*'}; returns all -available fonts. If the underlying window system is X11, other -patterns follow the standard X11 font selection syntax (as used e.g. -in resource definitions), i.e. the wildcard character \code{'*'} -matches any sequence of characters (including none) and \code{'?'} -matches any single character. -On the Macintosh this function currently returns an empty list. -\end{funcdesc} - -\begin{funcdesc}{setdefscrollbars}{hflag\, vflag} -Set the flags controlling whether subsequently opened windows will -have horizontal and/or vertical scroll bars. -\end{funcdesc} - -\begin{funcdesc}{setdefwinpos}{h\, v} -Set the default window position for windows opened subsequently. -\end{funcdesc} - -\begin{funcdesc}{setdefwinsize}{width\, height} -Set the default window size for windows opened subsequently. -\end{funcdesc} - -\begin{funcdesc}{getdefscrollbars}{} -Return the flags controlling whether subsequently opened windows will -have horizontal and/or vertical scroll bars. -\end{funcdesc} - -\begin{funcdesc}{getdefwinpos}{} -Return the default window position for windows opened subsequently. -\end{funcdesc} - -\begin{funcdesc}{getdefwinsize}{} -Return the default window size for windows opened subsequently. -\end{funcdesc} - -\begin{funcdesc}{getscrsize}{} -Return the screen size in pixels. -\end{funcdesc} - -\begin{funcdesc}{getscrmm}{} -Return the screen size in millimeters. -\end{funcdesc} - -\begin{funcdesc}{fetchcolor}{colorname} -Return the pixel value corresponding to the given color name. -Return the default foreground color for unknown color names. -Hint: the following code tests whether you are on a machine that -supports more than two colors: -\bcode\begin{verbatim} -if stdwin.fetchcolor('black') <> \ - stdwin.fetchcolor('red') <> \ - stdwin.fetchcolor('white'): - print 'color machine' -else: - print 'monochrome machine' -\end{verbatim}\ecode -\end{funcdesc} - -\begin{funcdesc}{setfgcolor}{pixel} -Set the default foreground color. -This will become the default foreground color of windows opened -subsequently, including dialogs. -\end{funcdesc} - -\begin{funcdesc}{setbgcolor}{pixel} -Set the default background color. -This will become the default background color of windows opened -subsequently, including dialogs. -\end{funcdesc} - -\begin{funcdesc}{getfgcolor}{} -Return the pixel value of the current default foreground color. -\end{funcdesc} - -\begin{funcdesc}{getbgcolor}{} -Return the pixel value of the current default background color. -\end{funcdesc} - -\begin{funcdesc}{setfont}{fontname} -Set the current default font. -This will become the default font for windows opened subsequently, -and is also used by the text measuring functions \code{textwidth}, -\code{textbreak}, \code{lineheight} and \code{baseline} below. -This accepts two more optional parameters, size and style: -Size is the font size (in `points'). -Style is a single character specifying the style, as follows: -\code{'b'} = bold, -\code{'i'} = italic, -\code{'o'} = bold + italic, -\code{'u'} = underline; -default style is roman. -Size and style are ignored under X11 but used on the Macintosh. -(Sorry for all this complexity --- a more uniform interface is being designed.) -\end{funcdesc} - -\begin{funcdesc}{menucreate}{title} -Create a menu object referring to a global menu (a menu that appears in -all windows). -Methods of menu objects are described below. -Note: normally, menus are created locally; see the window method -\code{menucreate} below. -\strong{Warning:} the menu only appears in a window as long as the object -returned by this call exists. -\end{funcdesc} - -\begin{funcdesc}{newbitmap}{width\, height} -Create a new bitmap object of the given dimensions. -Methods of bitmap objects are described below. -Not available on the Macintosh. -\end{funcdesc} - -\begin{funcdesc}{fleep}{} -Cause a beep or bell (or perhaps a `visual bell' or flash, hence the -name). -\end{funcdesc} - -\begin{funcdesc}{message}{string} -Display a dialog box containing the string. -The user must click OK before the function returns. -\end{funcdesc} - -\begin{funcdesc}{askync}{prompt\, default} -Display a dialog that prompts the user to answer a question with yes or -no. -Return 0 for no, 1 for yes. -If the user hits the Return key, the default (which must be 0 or 1) is -returned. -If the user cancels the dialog, the -\code{KeyboardInterrupt} -exception is raised. -\end{funcdesc} - -\begin{funcdesc}{askstr}{prompt\, default} -Display a dialog that prompts the user for a string. -If the user hits the Return key, the default string is returned. -If the user cancels the dialog, the -\code{KeyboardInterrupt} -exception is raised. -\end{funcdesc} - -\begin{funcdesc}{askfile}{prompt\, default\, new} -Ask the user to specify a filename. -If -\var{new} -is zero it must be an existing file; otherwise, it must be a new file. -If the user cancels the dialog, the -\code{KeyboardInterrupt} -exception is raised. -\end{funcdesc} - -\begin{funcdesc}{setcutbuffer}{i\, string} -Store the string in the system's cut buffer number -\var{i}, -where it can be found (for pasting) by other applications. -On X11, there are 8 cut buffers (numbered 0..7). -Cut buffer number 0 is the `clipboard' on the Macintosh. -\end{funcdesc} - -\begin{funcdesc}{getcutbuffer}{i} -Return the contents of the system's cut buffer number -\var{i}. -\end{funcdesc} - -\begin{funcdesc}{rotatecutbuffers}{n} -On X11, rotate the 8 cut buffers by -\var{n}. -Ignored on the Macintosh. -\end{funcdesc} - -\begin{funcdesc}{getselection}{i} -Return X11 selection number -\var{i.} -Selections are not cut buffers. -Selection numbers are defined in module -\code{stdwinevents}. -Selection \code{WS_PRIMARY} is the -\dfn{primary} -selection (used by -xterm, -for instance); -selection \code{WS_SECONDARY} is the -\dfn{secondary} -selection; selection \code{WS_CLIPBOARD} is the -\dfn{clipboard} -selection (used by -xclipboard). -On the Macintosh, this always returns an empty string. -\end{funcdesc} - -\begin{funcdesc}{resetselection}{i} -Reset selection number -\var{i}, -if this process owns it. -(See window method -\code{setselection()}). -\end{funcdesc} - -\begin{funcdesc}{baseline}{} -Return the baseline of the current font (defined by STDWIN as the -vertical distance between the baseline and the top of the -characters). -\end{funcdesc} - -\begin{funcdesc}{lineheight}{} -Return the total line height of the current font. -\end{funcdesc} - -\begin{funcdesc}{textbreak}{str\, width} -Return the number of characters of the string that fit into a space of -\var{width} -bits wide when drawn in the curent font. -\end{funcdesc} - -\begin{funcdesc}{textwidth}{str} -Return the width in bits of the string when drawn in the current font. -\end{funcdesc} - -\begin{funcdesc}{connectionnumber}{} -\funcline{fileno}{} -(X11 under \UNIX{} only) Return the ``connection number'' used by the -underlying X11 implementation. (This is normally the file number of -the socket.) Both functions return the same value; -\code{connectionnumber()} is named after the corresponding function in -X11 and STDWIN, while \code{fileno()} makes it possible to use the -\code{stdwin} module as a ``file'' object parameter to -\code{select.select()}. Note that if \code{select()} implies that -input is possible on \code{stdwin}, this does not guarantee that an -event is ready --- it may be some internal communication going on -between the X server and the client library. Thus, you should call -\code{stdwin.pollevent()} until it returns \code{None} to check for -events if you don't want your program to block. Because of internal -buffering in X11, it is also possible that \code{stdwin.pollevent()} -returns an event while \code{select()} does not find \code{stdwin} to -be ready, so you should read any pending events with -\code{stdwin.pollevent()} until it returns \code{None} before entering -a blocking \code{select()} call. -\ttindex{select} -\end{funcdesc} - -\subsection{Window Objects} - -Window objects are created by \code{stdwin.open()}. They are closed -by their \code{close()} method or when they are garbage-collected. -Window objects have the following methods: - -\renewcommand{\indexsubitem}{(window method)} - -\begin{funcdesc}{begindrawing}{} -Return a drawing object, whose methods (described below) allow drawing -in the window. -\end{funcdesc} - -\begin{funcdesc}{change}{rect} -Invalidate the given rectangle; this may cause a draw event. -\end{funcdesc} - -\begin{funcdesc}{gettitle}{} -Returns the window's title string. -\end{funcdesc} - -\begin{funcdesc}{getdocsize}{} -\begin{sloppypar} -Return a pair of integers giving the size of the document as set by -\code{setdocsize()}. -\end{sloppypar} -\end{funcdesc} - -\begin{funcdesc}{getorigin}{} -Return a pair of integers giving the origin of the window with respect -to the document. -\end{funcdesc} - -\begin{funcdesc}{gettitle}{} -Return the window's title string. -\end{funcdesc} - -\begin{funcdesc}{getwinsize}{} -Return a pair of integers giving the size of the window. -\end{funcdesc} - -\begin{funcdesc}{getwinpos}{} -Return a pair of integers giving the position of the window's upper -left corner (relative to the upper left corner of the screen). -\end{funcdesc} - -\begin{funcdesc}{menucreate}{title} -Create a menu object referring to a local menu (a menu that appears -only in this window). -Methods of menu objects are described below. -{\bf Warning:} the menu only appears as long as the object -returned by this call exists. -\end{funcdesc} - -\begin{funcdesc}{scroll}{rect\, point} -Scroll the given rectangle by the vector given by the point. -\end{funcdesc} - -\begin{funcdesc}{setdocsize}{point} -Set the size of the drawing document. -\end{funcdesc} - -\begin{funcdesc}{setorigin}{point} -Move the origin of the window (its upper left corner) -to the given point in the document. -\end{funcdesc} - -\begin{funcdesc}{setselection}{i\, str} -Attempt to set X11 selection number -\var{i} -to the string -\var{str}. -(See stdwin method -\code{getselection()} -for the meaning of -\var{i}.) -Return true if it succeeds. -If succeeds, the window ``owns'' the selection until -(a) another application takes ownership of the selection; or -(b) the window is deleted; or -(c) the application clears ownership by calling -\code{stdwin.resetselection(\var{i})}. -When another application takes ownership of the selection, a -\code{WE_LOST_SEL} -event is received for no particular window and with the selection number -as detail. -Ignored on the Macintosh. -\end{funcdesc} - -\begin{funcdesc}{settimer}{dsecs} -Schedule a timer event for the window in -\code{\var{dsecs}/10} -seconds. -\end{funcdesc} - -\begin{funcdesc}{settitle}{title} -Set the window's title string. -\end{funcdesc} - -\begin{funcdesc}{setwincursor}{name} -\begin{sloppypar} -Set the window cursor to a cursor of the given name. -It raises the -\code{RuntimeError} -exception if no cursor of the given name exists. -Suitable names include -\code{'ibeam'}, -\code{'arrow'}, -\code{'cross'}, -\code{'watch'} -and -\code{'plus'}. -On X11, there are many more (see -\file{<X11/cursorfont.h>}). -\end{sloppypar} -\end{funcdesc} - -\begin{funcdesc}{setwinpos}{h\, v} -Set the the position of the window's upper left corner (relative to -the upper left corner of the screen). -\end{funcdesc} - -\begin{funcdesc}{setwinsize}{width\, height} -Set the window's size. -\end{funcdesc} - -\begin{funcdesc}{show}{rect} -Try to ensure that the given rectangle of the document is visible in -the window. -\end{funcdesc} - -\begin{funcdesc}{textcreate}{rect} -Create a text-edit object in the document at the given rectangle. -Methods of text-edit objects are described below. -\end{funcdesc} - -\begin{funcdesc}{setactive}{} -Attempt to make this window the active window. If successful, this -will generate a WE_ACTIVATE event (and a WE_DEACTIVATE event in case -another window in this application became inactive). -\end{funcdesc} - -\begin{funcdesc}{close}{} -Discard the window object. It should not be used again. -\end{funcdesc} - -\subsection{Drawing Objects} - -Drawing objects are created exclusively by the window method -\code{begindrawing()}. -Only one drawing object can exist at any given time; the drawing object -must be deleted to finish drawing. -No drawing object may exist when -\code{stdwin.getevent()} -is called. -Drawing objects have the following methods: - -\renewcommand{\indexsubitem}{(drawing method)} - -\begin{funcdesc}{box}{rect} -Draw a box just inside a rectangle. -\end{funcdesc} - -\begin{funcdesc}{circle}{center\, radius} -Draw a circle with given center point and radius. -\end{funcdesc} - -\begin{funcdesc}{elarc}{center\, \(rh\, rv\)\, \(a1\, a2\)} -Draw an elliptical arc with given center point. -\code{(\var{rh}, \var{rv})} -gives the half sizes of the horizontal and vertical radii. -\code{(\var{a1}, \var{a2})} -gives the angles (in degrees) of the begin and end points. -0 degrees is at 3 o'clock, 90 degrees is at 12 o'clock. -\end{funcdesc} - -\begin{funcdesc}{erase}{rect} -Erase a rectangle. -\end{funcdesc} - -\begin{funcdesc}{fillcircle}{center\, radius} -Draw a filled circle with given center point and radius. -\end{funcdesc} - -\begin{funcdesc}{fillelarc}{center\, \(rh\, rv\)\, \(a1\, a2\)} -Draw a filled elliptical arc; arguments as for \code{elarc}. -\end{funcdesc} - -\begin{funcdesc}{fillpoly}{points} -Draw a filled polygon given by a list (or tuple) of points. -\end{funcdesc} - -\begin{funcdesc}{invert}{rect} -Invert a rectangle. -\end{funcdesc} - -\begin{funcdesc}{line}{p1\, p2} -Draw a line from point -\var{p1} -to -\var{p2}. -\end{funcdesc} - -\begin{funcdesc}{paint}{rect} -Fill a rectangle. -\end{funcdesc} - -\begin{funcdesc}{poly}{points} -Draw the lines connecting the given list (or tuple) of points. -\end{funcdesc} - -\begin{funcdesc}{shade}{rect\, percent} -Fill a rectangle with a shading pattern that is about -\var{percent} -percent filled. -\end{funcdesc} - -\begin{funcdesc}{text}{p\, str} -Draw a string starting at point p (the point specifies the -top left coordinate of the string). -\end{funcdesc} - -\begin{funcdesc}{xorcircle}{center\, radius} -\funcline{xorelarc}{center\, \(rh\, rv\)\, \(a1\, a2\)} -\funcline{xorline}{p1\, p2} -\funcline{xorpoly}{points} -Draw a circle, an elliptical arc, a line or a polygon, respectively, -in XOR mode. -\end{funcdesc} - -\begin{funcdesc}{setfgcolor}{} -\funcline{setbgcolor}{} -\funcline{getfgcolor}{} -\funcline{getbgcolor}{} -These functions are similar to the corresponding functions described -above for the -\code{stdwin} -module, but affect or return the colors currently used for drawing -instead of the global default colors. -When a drawing object is created, its colors are set to the window's -default colors, which are in turn initialized from the global default -colors when the window is created. -\end{funcdesc} - -\begin{funcdesc}{setfont}{} -\funcline{baseline}{} -\funcline{lineheight}{} -\funcline{textbreak}{} -\funcline{textwidth}{} -These functions are similar to the corresponding functions described -above for the -\code{stdwin} -module, but affect or use the current drawing font instead of -the global default font. -When a drawing object is created, its font is set to the window's -default font, which is in turn initialized from the global default -font when the window is created. -\end{funcdesc} - -\begin{funcdesc}{bitmap}{point\, bitmap\, mask} -Draw the \var{bitmap} with its top left corner at \var{point}. -If the optional \var{mask} argument is present, it should be either -the same object as \var{bitmap}, to draw only those bits that are set -in the bitmap, in the foreground color, or \code{None}, to draw all -bits (ones are drawn in the foreground color, zeros in the background -color). -Not available on the Macintosh. -\end{funcdesc} - -\begin{funcdesc}{cliprect}{rect} -Set the ``clipping region'' to a rectangle. -The clipping region limits the effect of all drawing operations, until -it is changed again or until the drawing object is closed. When a -drawing object is created the clipping region is set to the entire -window. When an object to be drawn falls partly outside the clipping -region, the set of pixels drawn is the intersection of the clipping -region and the set of pixels that would be drawn by the same operation -in the absence of a clipping region. -\end{funcdesc} - -\begin{funcdesc}{noclip}{} -Reset the clipping region to the entire window. -\end{funcdesc} - -\begin{funcdesc}{close}{} -\funcline{enddrawing}{} -Discard the drawing object. It should not be used again. -\end{funcdesc} - -\subsection{Menu Objects} - -A menu object represents a menu. -The menu is destroyed when the menu object is deleted. -The following methods are defined: - -\renewcommand{\indexsubitem}{(menu method)} - -\begin{funcdesc}{additem}{text\, shortcut} -Add a menu item with given text. -The shortcut must be a string of length 1, or omitted (to specify no -shortcut). -\end{funcdesc} - -\begin{funcdesc}{setitem}{i\, text} -Set the text of item number -\var{i}. -\end{funcdesc} - -\begin{funcdesc}{enable}{i\, flag} -Enable or disables item -\var{i}. -\end{funcdesc} - -\begin{funcdesc}{check}{i\, flag} -Set or clear the -\dfn{check mark} -for item -\var{i}. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Discard the menu object. It should not be used again. -\end{funcdesc} - -\subsection{Bitmap Objects} - -A bitmap represents a rectangular array of bits. -The top left bit has coordinate (0, 0). -A bitmap can be drawn with the \code{bitmap} method of a drawing object. -Bitmaps are currently not available on the Macintosh. - -The following methods are defined: - -\renewcommand{\indexsubitem}{(bitmap method)} - -\begin{funcdesc}{getsize}{} -Return a tuple representing the width and height of the bitmap. -(This returns the values that have been passed to the \code{newbitmap} -function.) -\end{funcdesc} - -\begin{funcdesc}{setbit}{point\, bit} -Set the value of the bit indicated by \var{point} to \var{bit}. -\end{funcdesc} - -\begin{funcdesc}{getbit}{point} -Return the value of the bit indicated by \var{point}. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Discard the bitmap object. It should not be used again. -\end{funcdesc} - -\subsection{Text-edit Objects} - -A text-edit object represents a text-edit block. -For semantics, see the STDWIN documentation for C programmers. -The following methods exist: - -\renewcommand{\indexsubitem}{(text-edit method)} - -\begin{funcdesc}{arrow}{code} -Pass an arrow event to the text-edit block. -The -\var{code} -must be one of -\code{WC_LEFT}, -\code{WC_RIGHT}, -\code{WC_UP} -or -\code{WC_DOWN} -(see module -\code{stdwinevents}). -\end{funcdesc} - -\begin{funcdesc}{draw}{rect} -Pass a draw event to the text-edit block. -The rectangle specifies the redraw area. -\end{funcdesc} - -\begin{funcdesc}{event}{type\, window\, detail} -Pass an event gotten from -\code{stdwin.getevent()} -to the text-edit block. -Return true if the event was handled. -\end{funcdesc} - -\begin{funcdesc}{getfocus}{} -Return 2 integers representing the start and end positions of the -focus, usable as slice indices on the string returned by -\code{gettext()}. -\end{funcdesc} - -\begin{funcdesc}{getfocustext}{} -Return the text in the focus. -\end{funcdesc} - -\begin{funcdesc}{getrect}{} -Return a rectangle giving the actual position of the text-edit block. -(The bottom coordinate may differ from the initial position because -the block automatically shrinks or grows to fit.) -\end{funcdesc} - -\begin{funcdesc}{gettext}{} -Return the entire text buffer. -\end{funcdesc} - -\begin{funcdesc}{move}{rect} -Specify a new position for the text-edit block in the document. -\end{funcdesc} - -\begin{funcdesc}{replace}{str} -Replace the text in the focus by the given string. -The new focus is an insert point at the end of the string. -\end{funcdesc} - -\begin{funcdesc}{setfocus}{i\, j} -Specify the new focus. -Out-of-bounds values are silently clipped. -\end{funcdesc} - -\begin{funcdesc}{settext}{str} -Replace the entire text buffer by the given string and set the focus -to \code{(0, 0)}. -\end{funcdesc} - -\begin{funcdesc}{setview}{rect} -Set the view rectangle to \var{rect}. If \var{rect} is \code{None}, -viewing mode is reset. In viewing mode, all output from the text-edit -object is clipped to the viewing rectangle. This may be useful to -implement your own scrolling text subwindow. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Discard the text-edit object. It should not be used again. -\end{funcdesc} - -\subsection{Example} -\nodename{STDWIN Example} - -Here is a minimal example of using STDWIN in Python. -It creates a window and draws the string ``Hello world'' in the top -left corner of the window. -The window will be correctly redrawn when covered and re-exposed. -The program quits when the close icon or menu item is requested. - -\bcode\begin{verbatim} -import stdwin -from stdwinevents import * - -def main(): - mywin = stdwin.open('Hello') - # - while 1: - (type, win, detail) = stdwin.getevent() - if type == WE_DRAW: - draw = win.begindrawing() - draw.text((0, 0), 'Hello, world') - del draw - elif type == WE_CLOSE: - break - -main() -\end{verbatim}\ecode - -\section{Standard Module \sectcode{stdwinevents}} -\stmodindex{stdwinevents} - -This module defines constants used by STDWIN for event types -(\code{WE_ACTIVATE} etc.), command codes (\code{WC_LEFT} etc.) -and selection types (\code{WS_PRIMARY} etc.). -Read the file for details. -Suggested usage is - -\bcode\begin{verbatim} ->>> from stdwinevents import * ->>> -\end{verbatim}\ecode - -\section{Standard Module \sectcode{rect}} -\stmodindex{rect} - -This module contains useful operations on rectangles. -A rectangle is defined as in module -\code{stdwin}: -a pair of points, where a point is a pair of integers. -For example, the rectangle - -\bcode\begin{verbatim} -(10, 20), (90, 80) -\end{verbatim}\ecode - -is a rectangle whose left, top, right and bottom edges are 10, 20, 90 -and 80, respectively. -Note that the positive vertical axis points down (as in -\code{stdwin}). - -The module defines the following objects: - -\renewcommand{\indexsubitem}{(in module rect)} -\begin{excdesc}{error} -The exception raised by functions in this module when they detect an -error. -The exception argument is a string describing the problem in more -detail. -\end{excdesc} - -\begin{datadesc}{empty} -The rectangle returned when some operations return an empty result. -This makes it possible to quickly check whether a result is empty: - -\bcode\begin{verbatim} ->>> import rect ->>> r1 = (10, 20), (90, 80) ->>> r2 = (0, 0), (10, 20) ->>> r3 = rect.intersect([r1, r2]) ->>> if r3 is rect.empty: print 'Empty intersection' -Empty intersection ->>> -\end{verbatim}\ecode -\end{datadesc} - -\begin{funcdesc}{is_empty}{r} -Returns true if the given rectangle is empty. -A rectangle -\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})} -is empty if -\iftexi -\code{\var{left} >= \var{right}} or \code{\var{top} => \var{bottom}}. -\else -$\var{left} \geq \var{right}$ or $\var{top} \geq \var{bottom}$. -%%JHXXX{\em left~$\geq$~right} or {\em top~$\leq$~bottom}. -\fi -\end{funcdesc} - -\begin{funcdesc}{intersect}{list} -Returns the intersection of all rectangles in the list argument. -It may also be called with a tuple argument. -Raises -\code{rect.error} -if the list is empty. -Returns -\code{rect.empty} -if the intersection of the rectangles is empty. -\end{funcdesc} - -\begin{funcdesc}{union}{list} -Returns the smallest rectangle that contains all non-empty rectangles in -the list argument. -It may also be called with a tuple argument or with two or more -rectangles as arguments. -Returns -\code{rect.empty} -if the list is empty or all its rectangles are empty. -\end{funcdesc} - -\begin{funcdesc}{pointinrect}{point\, rect} -Returns true if the point is inside the rectangle. -By definition, a point -\code{(\var{h}, \var{v})} -is inside a rectangle -\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})} if -\iftexi -\code{\var{left} <= \var{h} < \var{right}} and -\code{\var{top} <= \var{v} < \var{bottom}}. -\else -$\var{left} \leq \var{h} < \var{right}$ and -$\var{top} \leq \var{v} < \var{bottom}$. -\fi -\end{funcdesc} - -\begin{funcdesc}{inset}{rect\, \(dh\, dv\)} -Returns a rectangle that lies inside the -\code{rect} -argument by -\var{dh} -pixels horizontally -and -\var{dv} -pixels -vertically. -If -\var{dh} -or -\var{dv} -is negative, the result lies outside -\var{rect}. -\end{funcdesc} - -\begin{funcdesc}{rect2geom}{rect} -Converts a rectangle to geometry representation: -\code{(\var{left}, \var{top}), (\var{width}, \var{height})}. -\end{funcdesc} - -\begin{funcdesc}{geom2rect}{geom} -Converts a rectangle given in geometry representation back to the -standard rectangle representation -\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})}. -\end{funcdesc} diff --git a/Doc/lib/libstring.tex b/Doc/lib/libstring.tex deleted file mode 100644 index 2e79d43cb7..0000000000 --- a/Doc/lib/libstring.tex +++ /dev/null @@ -1,197 +0,0 @@ -\section{Standard Module \sectcode{string}} - -\stmodindex{string} - -This module defines some constants useful for checking character -classes and some useful string functions. See the modules -\code{regex} and \code{regsub} for string functions based on regular -expressions. - -The constants defined in this module are are: - -\renewcommand{\indexsubitem}{(data in module string)} -\begin{datadesc}{digits} - The string \code{'0123456789'}. -\end{datadesc} - -\begin{datadesc}{hexdigits} - The string \code{'0123456789abcdefABCDEF'}. -\end{datadesc} - -\begin{datadesc}{letters} - The concatenation of the strings \code{lowercase} and - \code{uppercase} described below. -\end{datadesc} - -\begin{datadesc}{lowercase} - A string containing all the characters that are considered lowercase - letters. On most systems this is the string - \code{'abcdefghijklmnopqrstuvwxyz'}. Do not change its definition --- - the effect on the routines \code{upper} and \code{swapcase} is - undefined. -\end{datadesc} - -\begin{datadesc}{octdigits} - The string \code{'01234567'}. -\end{datadesc} - -\begin{datadesc}{uppercase} - A string containing all the characters that are considered uppercase - letters. On most systems this is the string - \code{'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}. Do not change its definition --- - the effect on the routines \code{lower} and \code{swapcase} is - undefined. -\end{datadesc} - -\begin{datadesc}{whitespace} - A string containing all characters that are considered whitespace. - On most systems this includes the characters space, tab, linefeed, - return, formfeed, and vertical tab. Do not change its definition --- - the effect on the routines \code{strip} and \code{split} is - undefined. -\end{datadesc} - -The functions defined in this module are: - -\renewcommand{\indexsubitem}{(in module string)} - -\begin{funcdesc}{atof}{s} -Convert a string to a floating point number. The string must have -the standard syntax for a floating point literal in Python, optionally -preceded by a sign (\samp{+} or \samp{-}). -\end{funcdesc} - -\begin{funcdesc}{atoi}{s\optional{\, base}} -Convert string \var{s} to an integer in the given \var{base}. The -string must consist of one or more digits, optionally preceded by a -sign (\samp{+} or \samp{-}). The \var{base} defaults to 10. If it is -0, a default base is chosen depending on the leading characters of the -string (after stripping the sign): \samp{0x} or \samp{0X} means 16, -\samp{0} means 8, anything else means 10. If \var{base} is 16, a -leading \samp{0x} or \samp{0X} is always accepted. (Note: for a more -flexible interpretation of numeric literals, use the built-in function -\code{eval()}.) -\bifuncindex{eval} -\end{funcdesc} - -\begin{funcdesc}{atol}{s\optional{\, base}} -Convert string \var{s} to a long integer in the given \var{base}. The -string must consist of one or more digits, optionally preceded by a -sign (\samp{+} or \samp{-}). The \var{base} argument has the same -meaning as for \code{atoi()}. A trailing \samp{l} or \samp{L} is not -allowed, except if the base is 0. -\end{funcdesc} - -\begin{funcdesc}{expandtabs}{s\, tabsize} -Expand tabs in a string, i.e.\ replace them by one or more spaces, -depending on the current column and the given tab size. The column -number is reset to zero after each newline occurring in the string. -This doesn't understand other non-printing characters or escape -sequences. -\end{funcdesc} - -\begin{funcdesc}{find}{s\, sub\optional{\, start}} -Return the lowest index in \var{s} not smaller than \var{start} where the -substring \var{sub} is found. Return \code{-1} when \var{sub} -does not occur as a substring of \var{s} with index at least \var{start}. -If \var{start} is omitted, it defaults to \code{0}. If \var{start} is -negative, \code{len(\var{s})} is added. -\end{funcdesc} - -\begin{funcdesc}{rfind}{s\, sub\optional{\, start}} -Like \code{find} but find the highest index. -\end{funcdesc} - -\begin{funcdesc}{index}{s\, sub\optional{\, start}} -Like \code{find} but raise \code{ValueError} when the substring is -not found. -\end{funcdesc} - -\begin{funcdesc}{rindex}{s\, sub\optional{\, start}} -Like \code{rfind} but raise \code{ValueError} when the substring is -not found. -\end{funcdesc} - -\begin{funcdesc}{count}{s\, sub\optional{\, start}} -Return the number of (non-overlapping) occurrences of substring -\var{sub} in string \var{s} with index at least \var{start}. -If \var{start} is omitted, it defaults to \code{0}. If \var{start} is -negative, \code{len(\var{s})} is added. -\end{funcdesc} - -\begin{funcdesc}{lower}{s} -Convert letters to lower case. -\end{funcdesc} - -\begin{funcdesc}{split}{s} -Return a list of the whitespace-delimited words of the string -\var{s}. -\end{funcdesc} - -\begin{funcdesc}{splitfields}{s\, sep} - Return a list containing the fields of the string \var{s}, using - the string \var{sep} as a separator. The list will have one more - items than the number of non-overlapping occurrences of the - separator in the string. Thus, \code{string.splitfields(\var{s}, ' - ')} is not the same as \code{string.split(\var{s})}, as the latter - only returns non-empty words. As a special case, - \code{splitfields(\var{s}, '')} returns \code{[\var{s}]}, for any string - \var{s}. (See also \code{regsub.split()}.) -\end{funcdesc} - -\begin{funcdesc}{join}{words} -Concatenate a list or tuple of words with intervening spaces. -\end{funcdesc} - -\begin{funcdesc}{joinfields}{words\, sep} -Concatenate a list or tuple of words with intervening separators. -It is always true that -\code{string.joinfields(string.splitfields(\var{t}, \var{sep}), \var{sep})} -equals \var{t}. -\end{funcdesc} - -\begin{funcdesc}{strip}{s} -Remove leading and trailing whitespace from the string -\var{s}. -\end{funcdesc} - -\begin{funcdesc}{swapcase}{s} -Convert lower case letters to upper case and vice versa. -\end{funcdesc} - -\begin{funcdesc}{translate}{s, table} -Translate the characters from \var{s} using \var{table}, which must be -a 256-character string giving the translation for each character -value, indexed by its ordinal. -\end{funcdesc} - -\begin{funcdesc}{upper}{s} -Convert letters to upper case. -\end{funcdesc} - -\begin{funcdesc}{ljust}{s\, width} -\funcline{rjust}{s\, width} -\funcline{center}{s\, width} -These functions respectively left-justify, right-justify and center a -string in a field of given width. -They return a string that is at least -\var{width} -characters wide, created by padding the string -\var{s} -with spaces until the given width on the right, left or both sides. -The string is never truncated. -\end{funcdesc} - -\begin{funcdesc}{zfill}{s\, width} -Pad a numeric string on the left with zero digits until the given -width is reached. Strings starting with a sign are handled correctly. -\end{funcdesc} - -This module is implemented in Python. Much of its functionality has -been reimplemented in the built-in module \code{strop}. However, you -should \emph{never} import the latter module directly. When -\code{string} discovers that \code{strop} exists, it transparently -replaces parts of itself with the implementation from \code{strop}. -After initialization, there is \emph{no} overhead in using -\code{string} instead of \code{strop}. -\bimodindex{strop} diff --git a/Doc/lib/libstrings.tex b/Doc/lib/libstrings.tex deleted file mode 100644 index ea9a099966..0000000000 --- a/Doc/lib/libstrings.tex +++ /dev/null @@ -1,20 +0,0 @@ -\chapter{String Services} - -The modules described in this chapter provide a wide range of string -manipulation operations. Here's an overview: - -\begin{description} - -\item[string] ---- Common string operations. - -\item[regex] ---- Regular expression search and match operations. - -\item[regsub] ---- Substitution and splitting operations that use regular expressions. - -\item[struct] ---- Interpret strings as packed binary data. - -\end{description} diff --git a/Doc/lib/libstruct.tex b/Doc/lib/libstruct.tex deleted file mode 100644 index 4a08c78b87..0000000000 --- a/Doc/lib/libstruct.tex +++ /dev/null @@ -1,78 +0,0 @@ -\section{Built-in Module \sectcode{struct}} -\bimodindex{struct} -\indexii{C}{structures} - -This module performs conversions between Python values and C -structs represented as Python strings. It uses \dfn{format strings} -(explained below) as compact descriptions of the lay-out of the C -structs and the intended conversion to/from Python values. - -See also built-in module \code{array}. -\bimodindex{array} - -The module defines the following exception and functions: - -\renewcommand{\indexsubitem}{(in module struct)} -\begin{excdesc}{error} - Exception raised on various occasions; argument is a string - describing what is wrong. -\end{excdesc} - -\begin{funcdesc}{pack}{fmt\, v1\, v2\, {\rm \ldots}} - Return a string containing the values - \code{\var{v1}, \var{v2}, {\rm \ldots}} packed according to the given - format. The arguments must match the values required by the format - exactly. -\end{funcdesc} - -\begin{funcdesc}{unpack}{fmt\, string} - Unpack the string (presumably packed by \code{pack(\var{fmt}, {\rm \ldots})}) - according to the given format. The result is a tuple even if it - contains exactly one item. The string must contain exactly the - amount of data required by the format (i.e. \code{len(\var{string})} must - equal \code{calcsize(\var{fmt})}). -\end{funcdesc} - -\begin{funcdesc}{calcsize}{fmt} - Return the size of the struct (and hence of the string) - corresponding to the given format. -\end{funcdesc} - -Format characters have the following meaning; the conversion between C -and Python values should be obvious given their types: - -\begin{tableiii}{|c|l|l|}{samp}{Format}{C}{Python} - \lineiii{x}{pad byte}{no value} - \lineiii{c}{char}{string of length 1} - \lineiii{b}{signed char}{integer} - \lineiii{h}{short}{integer} - \lineiii{i}{int}{integer} - \lineiii{l}{long}{integer} - \lineiii{f}{float}{float} - \lineiii{d}{double}{float} -\end{tableiii} - -A format character may be preceded by an integral repeat count; e.g.\ -the format string \code{'4h'} means exactly the same as \code{'hhhh'}. - -C numbers are represented in the machine's native format and byte -order, and properly aligned by skipping pad bytes if necessary -(according to the rules used by the C compiler). - -Examples (all on a big-endian machine): - -\bcode\begin{verbatim} -pack('hhl', 1, 2, 3) == '\000\001\000\002\000\000\000\003' -unpack('hhl', '\000\001\000\002\000\000\000\003') == (1, 2, 3) -calcsize('hhl') == 8 -\end{verbatim}\ecode - -Hint: to align the end of a structure to the alignment requirement of -a particular type, end the format with the code for that type with a -repeat count of zero, e.g.\ the format \code{'llh0l'} specifies two -pad bytes at the end, assuming longs are aligned on 4-byte boundaries. - -(More format characters are planned, e.g.\ \code{'s'} for character -arrays, upper case for unsigned variants, and a way to specify the -byte order, which is useful for [de]constructing network packets and -reading/writing portable binary file formats like TIFF and AIFF.) diff --git a/Doc/lib/libsun.tex b/Doc/lib/libsun.tex deleted file mode 100644 index 909c14dc95..0000000000 --- a/Doc/lib/libsun.tex +++ /dev/null @@ -1,112 +0,0 @@ -\chapter{SunOS Specific Services} - -The modules described in this chapter provide interfaces to features -that are unique to the SunOS operating system (versions 4 and 5; the -latter is also known as Solaris version 2). - -\section{Built-in Module \sectcode{sunaudiodev}} -\bimodindex{sunaudiodev} - -This module allows you to access the sun audio interface. The sun -audio hardware is capable of recording and playing back audio data -in U-LAW format with a sample rate of 8K per second. A full -description can be gotten with \samp{man audio}. - -The module defines the following variables and functions: - -\renewcommand{\indexsubitem}{(in module sunaudiodev)} -\begin{excdesc}{error} -This exception is raised on all errors. The argument is a string -describing what went wrong. -\end{excdesc} - -\begin{funcdesc}{open}{mode} -This function opens the audio device and returns a sun audio device -object. This object can then be used to do I/O on. The \var{mode} parameter -is one of \code{'r'} for record-only access, \code{'w'} for play-only -access, \code{'rw'} for both and \code{'control'} for access to the -control device. Since only one process is allowed to have the recorder -or player open at the same time it is a good idea to open the device -only for the activity needed. See the audio manpage for details. -\end{funcdesc} - -\subsection{Audio Device Objects} - -The audio device objects are returned by \code{open} define the -following methods (except \code{control} objects which only provide -getinfo, setinfo and drain): - -\renewcommand{\indexsubitem}{(audio device method)} - -\begin{funcdesc}{close}{} -This method explicitly closes the device. It is useful in situations -where deleting the object does not immediately close it since there -are other references to it. A closed device should not be used again. -\end{funcdesc} - -\begin{funcdesc}{drain}{} -This method waits until all pending output is processed and then returns. -Calling this method is often not necessary: destroying the object will -automatically close the audio device and this will do an implicit drain. -\end{funcdesc} - -\begin{funcdesc}{flush}{} -This method discards all pending output. It can be used avoid the -slow response to a user's stop request (due to buffering of up to one -second of sound). -\end{funcdesc} - -\begin{funcdesc}{getinfo}{} -This method retrieves status information like input and output volume, -etc. and returns it in the form of -an audio status object. This object has no methods but it contains a -number of attributes describing the current device status. The names -and meanings of the attributes are described in -\file{/usr/include/sun/audioio.h} and in the audio man page. Member names -are slightly different from their C counterparts: a status object is -only a single structure. Members of the \code{play} substructure have -\samp{o_} prepended to their name and members of the \code{record} -structure have \samp{i_}. So, the C member \code{play.sample_rate} is -accessed as \code{o_sample_rate}, \code{record.gain} as \code{i_gain} -and \code{monitor_gain} plainly as \code{monitor_gain}. -\end{funcdesc} - -\begin{funcdesc}{ibufcount}{} -This method returns the number of samples that are buffered on the -recording side, i.e. -the program will not block on a \code{read} call of so many samples. -\end{funcdesc} - -\begin{funcdesc}{obufcount}{} -This method returns the number of samples buffered on the playback -side. Unfortunately, this number cannot be used to determine a number -of samples that can be written without blocking since the kernel -output queue length seems to be variable. -\end{funcdesc} - -\begin{funcdesc}{read}{size} -This method reads \var{size} samples from the audio input and returns -them as a python string. The function blocks until enough data is available. -\end{funcdesc} - -\begin{funcdesc}{setinfo}{status} -This method sets the audio device status parameters. The \var{status} -parameter is an device status object as returned by \code{getinfo} and -possibly modified by the program. -\end{funcdesc} - -\begin{funcdesc}{write}{samples} -Write is passed a python string containing audio samples to be played. -If there is enough buffer space free it will immediately return, -otherwise it will block. -\end{funcdesc} - -There is a companion module, \code{SUNAUDIODEV}, which defines useful -symbolic constants like \code{MIN_GAIN}, \code{MAX_GAIN}, -\code{SPEAKER}, etc. The names of -the constants are the same names as used in the C include file -\file{<sun/audioio.h>}, with the leading string \samp{AUDIO_} stripped. - -Useability of the control device is limited at the moment, since there -is no way to use the ``wait for something to happen'' feature the -device provides. diff --git a/Doc/lib/libsys.tex b/Doc/lib/libsys.tex deleted file mode 100644 index ff5d65e9f5..0000000000 --- a/Doc/lib/libsys.tex +++ /dev/null @@ -1,152 +0,0 @@ -\section{Built-in Module \sectcode{sys}} - -\bimodindex{sys} -This module provides access to some variables used or maintained by the -interpreter and to functions that interact strongly with the interpreter. -It is always available. - -\renewcommand{\indexsubitem}{(in module sys)} - -\begin{datadesc}{argv} - The list of command line arguments passed to a Python script. - \code{sys.argv[0]} is the script name (it is operating system - dependent whether this is a full pathname or not). - If the command was executed using the \samp{-c} command line option - to the interpreter, \code{sys.argv[0]} is set to the string - \code{"-c"}. - If no script name was passed to the Python interpreter, - \code{sys.argv} has zero length. -\end{datadesc} - -\begin{datadesc}{builtin_module_names} - A list of strings giving the names of all modules that are compiled - into this Python interpreter. (This information is not available in - any other way --- \code{sys.modules.keys()} only lists the imported - modules.) -\end{datadesc} - -\begin{datadesc}{exc_type} -\dataline{exc_value} -\dataline{exc_traceback} - These three variables are not always defined; they are set when an - exception handler (an \code{except} clause of a \code{try} statement) is - invoked. Their meaning is: \code{exc_type} gets the exception type of - the exception being handled; \code{exc_value} gets the exception - parameter (its \dfn{associated value} or the second argument to - \code{raise}); \code{exc_traceback} gets a traceback object (see the - Reference Manual) which - encapsulates the call stack at the point where the exception - originally occurred. -\obindex{traceback} -\end{datadesc} - -\begin{funcdesc}{exit}{n} - Exit from Python with numeric exit status \var{n}. This is - implemented by raising the \code{SystemExit} exception, so cleanup - actions specified by \code{finally} clauses of \code{try} statements - are honored, and it is possible to catch the exit attempt at an outer - level. -\end{funcdesc} - -\begin{datadesc}{exitfunc} - This value is not actually defined by the module, but can be set by - the user (or by a program) to specify a clean-up action at program - exit. When set, it should be a parameterless function. This function - will be called when the interpreter exits in any way (except when a - fatal error occurs: in that case the interpreter's internal state - cannot be trusted). -\end{datadesc} - -\begin{datadesc}{last_type} -\dataline{last_value} -\dataline{last_traceback} - These three variables are not always defined; they are set when an - exception is not handled and the interpreter prints an error message - and a stack traceback. Their intended use is to allow an interactive - user to import a debugger module and engage in post-mortem debugging - without having to re-execute the command that caused the error (which - may be hard to reproduce). The meaning of the variables is the same - as that of \code{exc_type}, \code{exc_value} and \code{exc_tracaback}, - respectively. -\end{datadesc} - -\begin{datadesc}{modules} - Gives the list of modules that have already been loaded. - This can be manipulated to force reloading of modules and other tricks. -\end{datadesc} - -\begin{datadesc}{path} - A list of strings that specifies the search path for modules. - Initialized from the environment variable \code{PYTHONPATH}, or an - installation-dependent default. -\end{datadesc} - -\begin{datadesc}{platform} -This string contains a platform identifier. This can be used to -append platform-specific components to \code{sys.path}, for instance. -\end{datadesc} - -\begin{datadesc}{ps1} -\dataline{ps2} - Strings specifying the primary and secondary prompt of the - interpreter. These are only defined if the interpreter is in - interactive mode. Their initial values in this case are - \code{'>>> '} and \code{'... '}. -\end{datadesc} - -\begin{funcdesc}{setcheckinterval}{interval} -Set the interpreter's ``check interval''. This integer value -determines how often the interpreter checks for periodic things such -as thread switches and signal handlers. The default is 10, meaning -the check is performed every 10 Python virtual instructions. Setting -it to a larger value may increase performance for programs using -threads. Setting it to a value $\leq 0$ checks every virtual instruction, -maximizing responsiveness as well as overhead. -\end{funcdesc} - -\begin{funcdesc}{settrace}{tracefunc} - Set the system's trace function, which allows you to implement a - Python source code debugger in Python. See section ``How It Works'' - in the chapter on the Python Debugger. -\end{funcdesc} -\index{trace function} -\index{debugger} - -\begin{funcdesc}{setprofile}{profilefunc} - Set the system's profile function, which allows you to implement a - Python source code profiler in Python. See the chapter on the - Python Profiler. The system's profile function - is called similarly to the system's trace function (see - \code{sys.settrace}), but it isn't called for each executed line of - code (only on call and return and when an exception occurs). Also, - its return value is not used, so it can just return \code{None}. -\end{funcdesc} -\index{profile function} -\index{profiler} - -\begin{datadesc}{stdin} -\dataline{stdout} -\dataline{stderr} - File objects corresponding to the interpreter's standard input, - output and error streams. \code{sys.stdin} is used for all - interpreter input except for scripts but including calls to - \code{input()} and \code{raw_input()}. \code{sys.stdout} is used - for the output of \code{print} and expression statements and for the - prompts of \code{input()} and \code{raw_input()}. The interpreter's - own prompts and (almost all of) its error messages go to - \code{sys.stderr}. \code{sys.stdout} and \code{sys.stderr} needn't - be built-in file objects: any object is acceptable as long as it has - a \code{write} method that takes a string argument. (Changing these - objects doesn't affect the standard I/O streams of processes - executed by \code{popen()}, \code{system()} or the \code{exec*()} - family of functions in the \code{os} module.) -\stmodindex{os} -\end{datadesc} - -\begin{datadesc}{tracebacklimit} -When this variable is set to an integer value, it determines the -maximum number of levels of traceback information printed when an -unhandled exception occurs. The default is 1000. When set to 0 or -less, all traceback information is suppressed and only the exception -type and value are printed. -\end{datadesc} diff --git a/Doc/lib/libsyslog.tex b/Doc/lib/libsyslog.tex deleted file mode 100644 index 5b4fdded4b..0000000000 --- a/Doc/lib/libsyslog.tex +++ /dev/null @@ -1,67 +0,0 @@ -\section{Built-in Module \sectcode{syslog}} -\bimodindex{syslog} - -This module provides an interface to the Unix \code{syslog} library -routines. Refer to the \UNIX{} manual pages for a detailed description -of the \code{syslog} facility. - -The module defines the following functions: - -\begin{funcdesc}{syslog}{\optional{priority\,} message} -Send the string \var{message} to the system logger. -A trailing newline is added if necessary. -Each message is tagged with a priority composed of a \var{facility} and -a \var{level}. -The optional \var{priority} argument, which defaults to -\code{(LOG_USER | LOG_INFO)}, determines the message priority. -\end{funcdesc} - -\begin{funcdesc}{openlog}{ident\, \optional{logopt\, \optional{facility}}} -Logging options other than the defaults can be set by explicitly opening -the log file with \code{openlog()} prior to calling \code{syslog()}. -The defaults are (usually) \var{ident} = \samp{syslog}, \var{logopt} = 0, -\var{facility} = \code{LOG_USER}. -The \var{ident} argument is a string which is prepended to every message. -The optional \var{logopt} argument is a bit field - see below for possible -values to combine. -The optional \var{facility} argument sets the default facility for messages -which do not have a facility explicitly encoded. -\end{funcdesc} - -\begin{funcdesc}{closelog}{} -Close the log file. -\end{funcdesc} - -\begin{funcdesc}{setlogmask}{maskpri} -This function set the priority mask to \var{maskpri} and returns the -previous mask value. -Calls to \code{syslog} with a priority level not set in \var{maskpri} -are ignored. -The default is to log all priorities. -The function \code{LOG_MASK(\var{pri})} calculates the mask for the -individual priority \var{pri}. -The function \code{LOG_UPTO(\var{pri})} calculates the mask for all priorities -up to and including \var{pri}. -\end{funcdesc} - -The module defines the following constants: - -\begin{description} - -\item[Priority levels (high to low):] - -\code{LOG_EMERG}, \code{LOG_ALERT}, \code{LOG_CRIT}, \code{LOG_ERR}, -\code{LOG_WARNING}, \code{LOG_NOTICE}, \code{LOG_INFO}, \code{LOG_DEBUG}. - -\item[Facilities:] - -\code{LOG_KERN}, \code{LOG_USER}, \code{LOG_MAIL}, \code{LOG_DAEMON}, -\code{LOG_AUTH}, \code{LOG_LPR}, \code{LOG_NEWS}, \code{LOG_UUCP}, -\code{LOG_CRON} and \code{LOG_LOCAL0} to \code{LOG_LOCAL7}. - -\item[Log options:] - -\code{LOG_PID}, \code{LOG_CONS}, \code{LOG_NDELAY}, \code{LOG_NOWAIT} -and \code{LOG_PERROR} if defined in \file{syslog.h}. - -\end{description} diff --git a/Doc/lib/libtempfile.tex b/Doc/lib/libtempfile.tex deleted file mode 100644 index 0a582e12dc..0000000000 --- a/Doc/lib/libtempfile.tex +++ /dev/null @@ -1,50 +0,0 @@ -\section{Standard Module \sectcode{tempfile}} -\stmodindex{tempfile} -\indexii{temporary}{file name} -\indexii{temporary}{file} - -\renewcommand{\indexsubitem}{(in module tempfile)} - -This module generates temporary file names. It is not \UNIX{} specific, -but it may require some help on non-\UNIX{} systems. - -Note: the modules does not create temporary files, nor does it -automatically remove them when the current process exits or dies. - -The module defines a single user-callable function: - -\begin{funcdesc}{mktemp}{} -Return a unique temporary filename. This is an absolute pathname of a -file that does not exist at the time the call is made. No two calls -will return the same filename. -\end{funcdesc} - -The module uses two global variables that tell it how to construct a -temporary name. The caller may assign values to them; by default they -are initialized at the first call to \code{mktemp()}. - -\begin{datadesc}{tempdir} -When set to a value other than \code{None}, this variable defines the -directory in which filenames returned by \code{mktemp()} reside. The -default is taken from the environment variable \code{TMPDIR}; if this -is not set, either \code{/usr/tmp} is used (on \UNIX{}), or the current -working directory (all other systems). No check is made to see -whether its value is valid. -\end{datadesc} -\ttindex{TMPDIR} - -\begin{datadesc}{template} -When set to a value other than \code{None}, this variable defines the -prefix of the final component of the filenames returned by -\code{mktemp()}. A string of decimal digits is added to generate -unique filenames. The default is either ``\code{@\var{pid}.}'' where -\var{pid} is the current process ID (on \UNIX{}), or ``\code{tmp}'' (all -other systems). -\end{datadesc} - -Warning: if a \UNIX{} process uses \code{mktemp()}, then calls -\code{fork()} and both parent and child continue to use -\code{mktemp()}, the processes will generate conflicting temporary -names. To resolve this, the child process should assign \code{None} -to \code{template}, to force recomputing the default on the next call -to \code{mktemp()}. diff --git a/Doc/lib/libtemplate.tex b/Doc/lib/libtemplate.tex deleted file mode 100644 index 4afb56b251..0000000000 --- a/Doc/lib/libtemplate.tex +++ /dev/null @@ -1,122 +0,0 @@ -% Template for a library manual section. -% PLEASE REMOVE THE COMMENTS AFTER USING THE TEMPLATE - - -% ==== 1. ==== -% Choose one of the following section headers and index entries; -% \section{} generates the section header, -% \bimodindex{} or \stmodundex{} generates an index entry for this module - -\section{Built-in Module \sectcode{spam}} % If implemented in C -\bimodindex{spam} - -\section{Standard module \sectcode{spam}} % If implemented in Python -\stmodindex{spam} - - -% ==== 2. ==== -% Give a short overview of what the module does. -% If it is platform specific, mention this. -% Mention other important restrictions or general operating principles. -% For example: - -The \code{spam} module defines operations for handling cans of Spam. -It knows the four generally available Spam varieties and understands -both can sizes. - -Because spamification requires UNIX process management, the module is -only available on genuine UNIX systems. - - -% ==== 3. ==== -% List the public functions defined by the module. Begin with a -% standard phrase. You may also list the exceptions and other data -% items defined in the module, insofar as they are important for the -% user. - -The \code{spam} module defines the following functions: - -% ---- 3.1. ---- -% Redefine the ``indexsubitem'' macro to point to this module -% (alternatively, you can put this at the top of the file): - -\renewcommand{\indexsubitem}{(in module spam)} - -% ---- 3.2. ---- -% For each function, use a ``funcdesc'' block. This has exactly two -% parameters (each parameters is contained in a set of curly braces): -% the first parameter is the function name (this automatically -% generates an index entry); the second parameter is the function's -% argument list. If there are no arguments, use an empty pair of -% curly braces. If there is more than one argument, separate the -% arguments with backslash-comma. Optional parts of the parameter -% list are contained in \optional{...} (this generates a set of square -% brackets around its parameter). Arguments are automatically set in -% italics in the parameter list. Each argument should be mentioned at -% least once in the description; each usage (even inside \code{...}) -% should be enclosed in \var{...}. - -\begin{funcdesc}{open}{filename\optional{\, mode\, buffersize}} -Open the file \var{filename} as a can of Spam. The optional -\var{mode} and \var{buffersize} arguments specify the read-write mode -(\code{'r'} (default) or \code{'w'}) and the buffer size (default: -system dependent). -\end{funcdesc} - -% ---- 3.3. ---- -% Data items are described using a ``datadesc'' block. This has only -% one parameter: the item's name. - -\begin{datadesc}{cansize} -The default can size, in ounces. Legal values are 7 and 12. The -default varies per supermarket. This variable should not be changed -once the \code{open()} function has been called. -\end{datadesc} - -% --- 3.4. --- -% Exceptions are described using a ``excdesc'' block. This has only -% one parameter: the exception name. - -\begin{excdesc}{error} -Exception raised when an operation fails for a Spam specific reason. -The exception argument is a string describing the reason of the -failure. -\end{excdesc} - -% ---- 3.5. ---- -% There is no standard block type for classes. I generally use -% ``funcdesc'' blocks, since class instantiation looks very much like -% a function call. - - -% ==== 4. ==== -% Now is probably a good time for a complete example. (Alternatively, -% an example giving the flavor of the module may be given before the -% detailed list of functions.) - -Example: - -\begin{verbatim} ->>> import spam ->>> can = spam.open('/etc/passwd') ->>> can.empty() ->>> can.close() -\end{verbatim} - -% ==== 5. ==== -% If your module defines new object types (for a built-in module) or -% classes (for a module written in Python), you should list the -% methods and instance variables (if any) of each type or class in a -% separate subsection. It is important to redefine ``indexsubitem'' -% for each subsection. - -\subsection{Spam Objects} - -Spam objects (returned by \code{open()} above) have the following -methods. - -\renewcommand{\indexsubitem}{(spam method)} - -\begin{funcdesc}{empty}{} -Empty the can into the trash. -\end{funcdesc} diff --git a/Doc/lib/libtermios.tex b/Doc/lib/libtermios.tex deleted file mode 100644 index e55aab4119..0000000000 --- a/Doc/lib/libtermios.tex +++ /dev/null @@ -1,108 +0,0 @@ -\section{Built-in Module \sectcode{termios}} -\bimodindex{termios} -\indexii{Posix}{I/O control} -\indexii{tty}{I/O control} - -\renewcommand{\indexsubitem}{(in module termios)} - -This module provides an interface to the Posix calls for tty I/O -control. For a complete description of these calls, see the Posix or -\UNIX{} manual pages. It is only available for those \UNIX{} versions -that support Posix \code{termios} style tty I/O control (and then -only if configured at installation time). - -All functions in this module take a file descriptor \var{fd} as their -first argument. This must be an integer file descriptor, such as -returned by \code{sys.stdin.fileno()}. - -This module should be used in conjunction with the \code{TERMIOS} -module, which defines the relevant symbolic constants (see the next -section). - -The module defines the following functions: - -\begin{funcdesc}{tcgetattr}{fd} -Return a list containing the tty attributes for file descriptor -\var{fd}, as follows: \code{[\var{iflag}, \var{oflag}, \var{cflag}, -\var{lflag}, \var{ispeed}, \var{ospeed}, \var{cc}]} where \var{cc} is -a list of the tty special characters (each a string of length 1, -except the items with indices \code{VMIN} and \code{VTIME}, which are -integers when these fields are defined). The interpretation of the -flags and the speeds as well as the indexing in the \var{cc} array -must be done using the symbolic constants defined in the -\code{TERMIOS} module. -\end{funcdesc} - -\begin{funcdesc}{tcsetattr}{fd\, when\, attributes} -Set the tty attributes for file descriptor \var{fd} from the -\var{attributes}, which is a list like the one returned by -\code{tcgetattr()}. The \var{when} argument determines when the -attributes are changed: \code{TERMIOS.TCSANOW} to change immediately, -\code{TERMIOS.TCSADRAIN} to change after transmitting all queued -output, or \code{TERMIOS.TCSAFLUSH} to change after transmitting all -queued output and discarding all queued input. -\end{funcdesc} - -\begin{funcdesc}{tcsendbreak}{fd\, duration} -Send a break on file descriptor \var{fd}. A zero \var{duration} sends -a break for 0.25--0.5 seconds; a nonzero \var{duration} has a system -dependent meaning. -\end{funcdesc} - -\begin{funcdesc}{tcdrain}{fd} -Wait until all output written to file descriptor \var{fd} has been -transmitted. -\end{funcdesc} - -\begin{funcdesc}{tcflush}{fd\, queue} -Discard queued data on file descriptor \var{fd}. The \var{queue} -selector specifies which queue: \code{TERMIOS.TCIFLUSH} for the input -queue, \code{TERMIOS.TCOFLUSH} for the output queue, or -\code{TERMIOS.TCIOFLUSH} for both queues. -\end{funcdesc} - -\begin{funcdesc}{tcflow}{fd\, action} -Suspend or resume input or output on file descriptor \var{fd}. The -\var{action} argument can be \code{TERMIOS.TCOOFF} to suspend output, -\code{TERMIOS.TCOON} to restart output, \code{TERMIOS.TCIOFF} to -suspend input, or \code{TERMIOS.TCION} to restart input. -\end{funcdesc} - -\subsection{Example} -\nodename{termios Example} - -Here's a function that prompts for a password with echoing turned off. -Note the technique using a separate \code{termios.tcgetattr()} call -and a \code{try {\ldots} finally} statement to ensure that the old tty -attributes are restored exactly no matter what happens: - -\begin{verbatim} -def getpass(prompt = "Password: "): - import termios, TERMIOS, sys - fd = sys.stdin.fileno() - old = termios.tcgetattr(fd) - new = termios.tcgetattr(fd) - new[3] = new[3] & ~TERMIOS.ECHO # lflags - try: - termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new) - passwd = raw_input(prompt) - finally: - termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old) - return passwd -\end{verbatim} - - -\section{Standard Module \sectcode{TERMIOS}} -\stmodindex{TERMIOS} -\indexii{Posix}{I/O control} -\indexii{tty}{I/O control} - -\renewcommand{\indexsubitem}{(in module TERMIOS)} - -This module defines the symbolic constants required to use the -\code{termios} module (see the previous section). See the Posix or -\UNIX{} manual pages (or the source) for a list of those constants. - -Note: this module resides in a system-dependent subdirectory of the -Python library directory. You may have to generate it for your -particular system using the script \file{Tools/scripts/h2py.py}. diff --git a/Doc/lib/libthread.tex b/Doc/lib/libthread.tex deleted file mode 100644 index f7453844db..0000000000 --- a/Doc/lib/libthread.tex +++ /dev/null @@ -1,101 +0,0 @@ -\section{Built-in Module \sectcode{thread}} -\bimodindex{thread} - -This module provides low-level primitives for working with multiple -threads (a.k.a.\ \dfn{light-weight processes} or \dfn{tasks}) --- multiple -threads of control sharing their global data space. For -synchronization, simple locks (a.k.a.\ \dfn{mutexes} or \dfn{binary -semaphores}) are provided. - -The module is optional and supported on SGI IRIX 4.x and 5.x and Sun -Solaris 2.x systems, as well as on systems that have a PTHREAD -implementation (e.g.\ KSR). - -It defines the following constant and functions: - -\renewcommand{\indexsubitem}{(in module thread)} -\begin{excdesc}{error} -Raised on thread-specific errors. -\end{excdesc} - -\begin{funcdesc}{start_new_thread}{func\, arg} -Start a new thread. The thread executes the function \var{func} -with the argument list \var{arg} (which must be a tuple). When the -function returns, the thread silently exits. When the function -terminates with an unhandled exception, a stack trace is printed and -then the thread exits (but other threads continue to run). -\end{funcdesc} - -\begin{funcdesc}{exit}{} -This is a shorthand for \code{thread.exit_thread()}. -\end{funcdesc} - -\begin{funcdesc}{exit_thread}{} -Raise the \code{SystemExit} exception. When not caught, this will -cause the thread to exit silently. -\end{funcdesc} - -%\begin{funcdesc}{exit_prog}{status} -%Exit all threads and report the value of the integer argument -%\var{status} as the exit status of the entire program. -%\strong{Caveat:} code in pending \code{finally} clauses, in this thread -%or in other threads, is not executed. -%\end{funcdesc} - -\begin{funcdesc}{allocate_lock}{} -Return a new lock object. Methods of locks are described below. The -lock is initially unlocked. -\end{funcdesc} - -\begin{funcdesc}{get_ident}{} -Return the `thread identifier' of the current thread. This is a -nonzero integer. Its value has no direct meaning; it is intended as a -magic cookie to be used e.g. to index a dictionary of thread-specific -data. Thread identifiers may be recycled when a thread exits and -another thread is created. -\end{funcdesc} - -Lock objects have the following methods: - -\renewcommand{\indexsubitem}{(lock method)} -\begin{funcdesc}{acquire}{\optional{waitflag}} -Without the optional argument, this method acquires the lock -unconditionally, if necessary waiting until it is released by another -thread (only one thread at a time can acquire a lock --- that's their -reason for existence), and returns \code{None}. If the integer -\var{waitflag} argument is present, the action depends on its value:\ -if it is zero, the lock is only acquired if it can be acquired -immediately without waiting, while if it is nonzero, the lock is -acquired unconditionally as before. If an argument is present, the -return value is 1 if the lock is acquired successfully, 0 if not. -\end{funcdesc} - -\begin{funcdesc}{release}{} -Releases the lock. The lock must have been acquired earlier, but not -necessarily by the same thread. -\end{funcdesc} - -\begin{funcdesc}{locked}{} -Return the status of the lock:\ 1 if it has been acquired by some -thread, 0 if not. -\end{funcdesc} - -{\bf Caveats:} - -\begin{itemize} -\item -Threads interact strangely with interrupts: the -\code{KeyboardInterrupt} exception will be received by an arbitrary -thread. (When the \code{signal} module is available, interrupts -always go to the main thread.) - -\item -Calling \code{sys.exit()} or raising the \code{SystemExit} is -equivalent to calling \code{thread.exit_thread()}. - -\item -Not all built-in functions that may block waiting for I/O allow other -threads to run. (The most popular ones (\code{sleep}, \code{read}, -\code{select}) work as expected.) - -\end{itemize} diff --git a/Doc/lib/libtime.tex b/Doc/lib/libtime.tex deleted file mode 100644 index f91a492a8a..0000000000 --- a/Doc/lib/libtime.tex +++ /dev/null @@ -1,122 +0,0 @@ -\section{Built-in Module \sectcode{time}} - -\bimodindex{time} -This module provides various time-related functions. -It is always available. - -An explanation of some terminology and conventions is in order. - -\begin{itemize} - -\item -The ``epoch'' is the point where the time starts. On January 1st of that -year, at 0 hours, the ``time since the epoch'' is zero. For UNIX, the -epoch is 1970. To find out what the epoch is, look at \code{gmtime(0)}. - -\item -UTC is Coordinated Universal Time (formerly known as Greenwich Mean -Time). The acronym UTC is not a mistake but a compromise between -English and French. - -\item -DST is Daylight Saving Time, an adjustment of the timezone by -(usually) one hour during part of the year. DST rules are magic -(determined by local law) and can change from year to year. The C -library has a table containing the local rules (often it is read from -a system file for flexibility) and is the only source of True Wisdom -in this respect. - -\item -The precision of the various real-time functions may be less than -suggested by the units in which their value or argument is expressed. -E.g.\ on most UNIX systems, the clock ``ticks'' only 50 or 100 times a -second, and on the Mac, times are only accurate to whole seconds. - -\end{itemize} - -The module defines the following functions and data items: - -\renewcommand{\indexsubitem}{(in module time)} - -\begin{datadesc}{altzone} -The offset of the local DST timezone, in seconds west of the 0th -meridian, if one is defined. Negative if the local DST timezone is -east of the 0th meridian (as in Western Europe, including the UK). -Only use this if \code{daylight} is nonzero. -\end{datadesc} - - -\begin{funcdesc}{asctime}{tuple} -Convert a tuple representing a time as returned by \code{gmtime()} or -\code{localtime()} to a 24-character string of the following form: -\code{'Sun Jun 20 23:21:05 1993'}. Note: unlike the C function of -the same name, there is no trailing newline. -\end{funcdesc} - - -\begin{funcdesc}{clock}{} -Return the current CPU time as a floating point number expressed in -seconds. The precision, and in fact the very definiton of the meaning -of ``CPU time'', depends on that of the C function of the same name. -\end{funcdesc} - - -\begin{funcdesc}{ctime}{secs} -Convert a time expressed in seconds since the epoch to a string -representing local time. \code{ctime(t)} is equivalent to -\code{asctime(localtime(t))}. -\end{funcdesc} - -\begin{datadesc}{daylight} -Nonzero if a DST timezone is defined. -\end{datadesc} - -\begin{funcdesc}{gmtime}{secs} -Convert a time expressed in seconds since the epoch to a tuple of 9 -integers, in UTC: year (e.g.\ 1993), month (1--12), day (1--31), hour -(0--23), minute (0--59), second (0--59), weekday (0--6, monday is 0), -Julian day (1--366), dst flag (always zero). Fractions of a second are -ignored. Note subtle differences with the C function of this name. -\end{funcdesc} - -\begin{funcdesc}{localtime}{secs} -Like \code{gmtime} but converts to local time. The dst flag is set -to 1 when DST applies to the given time. -\end{funcdesc} - -\begin{funcdesc}{mktime}{tuple} -This is the inverse function of \code{localtime}. Its argument is the -full 9-tuple (since the dst flag is needed). It returns an integer. If the -input value can't be represented as a non-negative integer, OverflowError is raised. -\end{funcdesc} - -\begin{funcdesc}{sleep}{secs} -Suspend execution for the given number of seconds. The argument may -be a floating point number to indicate a more precise sleep time. -\end{funcdesc} - -\begin{funcdesc}{strftime}{format, tuple} -Convert a tuple representing a time as returned by \code{gmtime()} or -\code{localtime()} to a string as specified by the format argument. -See the \code{strftime(3)} man page for details of the syntax of -format strings. -\end{funcdesc} - -\begin{funcdesc}{time}{} -Return the time as a floating point number expressed in seconds since -the epoch, in UTC. Note that even though the time is always returned -as a floating point number, not all systems provide time with a better -precision than 1 second. -\end{funcdesc} - -\begin{datadesc}{timezone} -The offset of the local (non-DST) timezone, in seconds west of the 0th -meridian (i.e. negative in most of Western Europe, positive in the US, -zero in the UK). -\end{datadesc} - -\begin{datadesc}{tzname} -A tuple of two strings: the first is the name of the local non-DST -timezone, the second is the name of the local DST timezone. If no DST -timezone is defined, the second string should not be used. -\end{datadesc} diff --git a/Doc/lib/libtraceback.tex b/Doc/lib/libtraceback.tex deleted file mode 100644 index ca9c374859..0000000000 --- a/Doc/lib/libtraceback.tex +++ /dev/null @@ -1,54 +0,0 @@ -\section{Standard Module \sectcode{traceback}} -\stmodindex{traceback} - -\renewcommand{\indexsubitem}{(in module traceback)} - -This module provides a standard interface to format and print stack -traces of Python programs. It exactly mimics the behavior of the -Python interpreter when it prints a stack trace. This is useful when -you want to print stack traces under program control, e.g. in a -``wrapper'' around the interpreter. - -The module uses traceback objects --- this is the object type -that is stored in the variables \code{sys.exc_traceback} and -\code{sys.last_traceback}. - -The module defines the following functions: - -\begin{funcdesc}{print_tb}{traceback\optional{\, limit}} -Print up to \var{limit} stack trace entries from \var{traceback}. If -\var{limit} is omitted or \code{None}, all entries are printed. -\end{funcdesc} - -\begin{funcdesc}{extract_tb}{traceback\optional{\, limit}} -Return a list of up to \var{limit} ``pre-processed'' stack trace -entries extracted from \var{traceback}. It is useful for alternate -formatting of stack traces. If \var{limit} is omitted or \code{None}, -all entries are extracted. A ``pre-processed'' stack trace entry is a -quadruple (\var{filename}, \var{line number}, \var{function name}, -\var{line text}) representing the information that is usually printed -for a stack trace. The \var{line text} is a string with leading and -trailing whitespace stripped; if the source is not available it is -\code{None}. -\end{funcdesc} - -\begin{funcdesc}{print_exception}{type\, value\, traceback\optional{\, limit}} -Print exception information and up to \var{limit} stack trace entries -from \var{traceback}. This differs from \code{print_tb} in the -following ways: (1) if \var{traceback} is not \code{None}, it prints a -header ``\code{Traceback (innermost last):}''; (2) it prints the -exception \var{type} and \var{value} after the stack trace; (3) if -\var{type} is \code{SyntaxError} and \var{value} has the appropriate -format, it prints the line where the syntax error occurred with a -caret indication the approximate position of the error. -\end{funcdesc} - -\begin{funcdesc}{print_exc}{\optional{limit}} -This is a shorthand for \code{print_exception(sys.exc_type,} -\code{sys.exc_value,} \code{sys.exc_traceback,} \code{limit)}. -\end{funcdesc} - -\begin{funcdesc}{print_last}{\optional{limit}} -This is a shorthand for \code{print_exception(sys.last_type,} -\code{sys.last_value,} \code{sys.last_traceback,} \code{limit)}. -\end{funcdesc} diff --git a/Doc/lib/libtypes.tex b/Doc/lib/libtypes.tex deleted file mode 100644 index 052bc9fe56..0000000000 --- a/Doc/lib/libtypes.tex +++ /dev/null @@ -1,761 +0,0 @@ -\section{Built-in Types} - -The following sections describe the standard types that are built into -the interpreter. These are the numeric types, sequence types, and -several others, including types themselves. There is no explicit -Boolean type; use integers instead. -\indexii{built-in}{types} -\indexii{Boolean}{type} - -Some operations are supported by several object types; in particular, -all objects can be compared, tested for truth value, and converted to -a string (with the \code{`{\rm \ldots}`} notation). The latter conversion is -implicitly used when an object is written by the \code{print} statement. -\stindex{print} - -\subsection{Truth Value Testing} - -Any object can be tested for truth value, for use in an \code{if} or -\code{while} condition or as operand of the Boolean operations below. -The following values are considered false: -\stindex{if} -\stindex{while} -\indexii{truth}{value} -\indexii{Boolean}{operations} -\index{false} - -\begin{itemize} -\renewcommand{\indexsubitem}{(Built-in object)} - -\item \code{None} - \ttindex{None} - -\item zero of any numeric type, e.g., \code{0}, \code{0L}, \code{0.0}. - -\item any empty sequence, e.g., \code{''}, \code{()}, \code{[]}. - -\item any empty mapping, e.g., \code{\{\}}. - -\item instances of user-defined classes, if the class defines a - \code{__nonzero__()} or \code{__len__()} method, when that - method returns zero. - -\end{itemize} - -All other values are considered true --- so objects of many types are -always true. -\index{true} - -Operations and built-in functions that have a Boolean result always -return \code{0} for false and \code{1} for true, unless otherwise -stated. (Important exception: the Boolean operations \samp{or} and -\samp{and} always return one of their operands.) - -\subsection{Boolean Operations} - -These are the Boolean operations, ordered by ascending priority: -\indexii{Boolean}{operations} - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes} - \lineiii{\var{x} or \var{y}}{if \var{x} is false, then \var{y}, else \var{x}}{(1)} - \hline - \lineiii{\var{x} and \var{y}}{if \var{x} is false, then \var{x}, else \var{y}}{(1)} - \hline - \lineiii{not \var{x}}{if \var{x} is false, then \code{1}, else \code{0}}{(2)} -\end{tableiii} -\opindex{and} -\opindex{or} -\opindex{not} - -\noindent -Notes: - -\begin{description} - -\item[(1)] -These only evaluate their second argument if needed for their outcome. - -\item[(2)] -\samp{not} has a lower priority than non-Boolean operators, so e.g. -\code{not a == b} is interpreted as \code{not(a == b)}, and -\code{a == not b} is a syntax error. - -\end{description} - -\subsection{Comparisons} - -Comparison operations are supported by all objects. They all have the -same priority (which is higher than that of the Boolean operations). -Comparisons can be chained arbitrarily, e.g. \code{x < y <= z} is -equivalent to \code{x < y and y <= z}, except that \code{y} is -evaluated only once (but in both cases \code{z} is not evaluated at -all when \code{x < y} is found to be false). -\indexii{chaining}{comparisons} - -This table summarizes the comparison operations: - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Meaning}{Notes} - \lineiii{<}{strictly less than}{} - \lineiii{<=}{less than or equal}{} - \lineiii{>}{strictly greater than}{} - \lineiii{>=}{greater than or equal}{} - \lineiii{==}{equal}{} - \lineiii{<>}{not equal}{(1)} - \lineiii{!=}{not equal}{(1)} - \lineiii{is}{object identity}{} - \lineiii{is not}{negated object identity}{} -\end{tableiii} -\indexii{operator}{comparison} -\opindex{==} % XXX *All* others have funny characters < ! > -\opindex{is} -\opindex{is not} - -\noindent -Notes: - -\begin{description} - -\item[(1)] -\code{<>} and \code{!=} are alternate spellings for the same operator. -(I couldn't choose between \ABC{} and \C{}! :-) -\indexii{\ABC{}}{language} -\indexii{\C{}}{language} - -\end{description} - -Objects of different types, except different numeric types, never -compare equal; such objects are ordered consistently but arbitrarily -(so that sorting a heterogeneous array yields a consistent result). -Furthermore, some types (e.g., windows) support only a degenerate -notion of comparison where any two objects of that type are unequal. -Again, such objects are ordered arbitrarily but consistently. -\indexii{types}{numeric} -\indexii{objects}{comparing} - -(Implementation note: objects of different types except numbers are -ordered by their type names; objects of the same types that don't -support proper comparison are ordered by their address.) - -Two more operations with the same syntactic priority, \code{in} and -\code{not in}, are supported only by sequence types (below). -\opindex{in} -\opindex{not in} - -\subsection{Numeric Types} - -There are three numeric types: \dfn{plain integers}, \dfn{long integers}, and -\dfn{floating point numbers}. Plain integers (also just called \dfn{integers}) -are implemented using \code{long} in \C{}, which gives them at least 32 -bits of precision. Long integers have unlimited precision. Floating -point numbers are implemented using \code{double} in \C{}. All bets on -their precision are off unless you happen to know the machine you are -working with. -\indexii{numeric}{types} -\indexii{integer}{types} -\indexii{integer}{type} -\indexiii{long}{integer}{type} -\indexii{floating point}{type} -\indexii{\C{}}{language} - -Numbers are created by numeric literals or as the result of built-in -functions and operators. Unadorned integer literals (including hex -and octal numbers) yield plain integers. Integer literals with an \samp{L} -or \samp{l} suffix yield long integers -(\samp{L} is preferred because \code{1l} looks too much like eleven!). -Numeric literals containing a decimal point or an exponent sign yield -floating point numbers. -\indexii{numeric}{literals} -\indexii{integer}{literals} -\indexiii{long}{integer}{literals} -\indexii{floating point}{literals} -\indexii{hexadecimal}{literals} -\indexii{octal}{literals} - -Python fully supports mixed arithmetic: when a binary arithmetic -operator has operands of different numeric types, the operand with the -``smaller'' type is converted to that of the other, where plain -integer is smaller than long integer is smaller than floating point. -Comparisons between numbers of mixed type use the same rule.% -\footnote{As a consequence, the list \code{[1, 2]} is considered equal - to \code{[1.0, 2.0]}, and similar for tuples.} -The functions \code{int()}, \code{long()} and \code{float()} can be used -to coerce numbers to a specific type. -\index{arithmetic} -\bifuncindex{int} -\bifuncindex{long} -\bifuncindex{float} - -All numeric types support the following operations, sorted by -ascending priority (operations in the same box have the same -priority; all numeric operations have a higher priority than -comparison operations): - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes} - \lineiii{\var{x} + \var{y}}{sum of \var{x} and \var{y}}{} - \lineiii{\var{x} - \var{y}}{difference of \var{x} and \var{y}}{} - \hline - \lineiii{\var{x} * \var{y}}{product of \var{x} and \var{y}}{} - \lineiii{\var{x} / \var{y}}{quotient of \var{x} and \var{y}}{(1)} - \lineiii{\var{x} \%{} \var{y}}{remainder of \code{\var{x} / \var{y}}}{} - \hline - \lineiii{-\var{x}}{\var{x} negated}{} - \lineiii{+\var{x}}{\var{x} unchanged}{} - \hline - \lineiii{abs(\var{x})}{absolute value of \var{x}}{} - \lineiii{int(\var{x})}{\var{x} converted to integer}{(2)} - \lineiii{long(\var{x})}{\var{x} converted to long integer}{(2)} - \lineiii{float(\var{x})}{\var{x} converted to floating point}{} - \lineiii{divmod(\var{x}, \var{y})}{the pair \code{(\var{x} / \var{y}, \var{x} \%{} \var{y})}}{(3)} - \lineiii{pow(\var{x}, \var{y})}{\var{x} to the power \var{y}}{} -\end{tableiii} -\indexiii{operations on}{numeric}{types} - -\noindent -Notes: -\begin{description} - -\item[(1)] -For (plain or long) integer division, the result is an integer. -The result is always rounded towards minus infinity: 1/2 is 0, -(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. -\indexii{integer}{division} -\indexiii{long}{integer}{division} - -\item[(2)] -Conversion from floating point to (long or plain) integer may round or -truncate as in \C{}; see functions \code{floor()} and \code{ceil()} in -module \code{math} for well-defined conversions. -\bifuncindex{floor} -\bifuncindex{ceil} -\indexii{numeric}{conversions} -\stmodindex{math} -\indexii{\C{}}{language} - -\item[(3)] -See the section on built-in functions for an exact definition. - -\end{description} -% XXXJH exceptions: overflow (when? what operations?) zerodivision - -\subsubsection{Bit-string Operations on Integer Types} -\nodename{Bit-string Operations} - -Plain and long integer types support additional operations that make -sense only for bit-strings. Negative numbers are treated as their 2's -complement value (for long integers, this assumes a sufficiently large -number of bits that no overflow occurs during the operation). - -The priorities of the binary bit-wise operations are all lower than -the numeric operations and higher than the comparisons; the unary -operation \samp{~} has the same priority as the other unary numeric -operations (\samp{+} and \samp{-}). - -This table lists the bit-string operations sorted in ascending -priority (operations in the same box have the same priority): - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes} - \lineiii{\var{x} | \var{y}}{bitwise \dfn{or} of \var{x} and \var{y}}{} - \hline - \lineiii{\var{x} \^{} \var{y}}{bitwise \dfn{exclusive or} of \var{x} and \var{y}}{} - \hline - \lineiii{\var{x} \&{} \var{y}}{bitwise \dfn{and} of \var{x} and \var{y}}{} - \hline - \lineiii{\var{x} << \var{n}}{\var{x} shifted left by \var{n} bits}{(1), (2)} - \lineiii{\var{x} >> \var{n}}{\var{x} shifted right by \var{n} bits}{(1), (3)} - \hline - \hline - \lineiii{\~\var{x}}{the bits of \var{x} inverted}{} -\end{tableiii} -\indexiii{operations on}{integer}{types} -\indexii{bit-string}{operations} -\indexii{shifting}{operations} -\indexii{masking}{operations} - -\noindent -Notes: -\begin{description} -\item[(1)] Negative shift counts are illegal. -\item[(2)] A left shift by \var{n} bits is equivalent to -multiplication by \code{pow(2, \var{n})} without overflow check. -\item[(3)] A right shift by \var{n} bits is equivalent to -division by \code{pow(2, \var{n})} without overflow check. -\end{description} - -\subsection{Sequence Types} - -There are three sequence types: strings, lists and tuples. - -Strings literals are written in single or double quotes: -\code{'xyzzy'}, \code{"frobozz"}. See Chapter 2 of the Python -Reference Manual for more about string literals. Lists are -constructed with square brackets, separating items with commas: -\code{[a, b, c]}. Tuples are constructed by the comma operator (not -within square brackets), with or without enclosing parentheses, but an -empty tuple must have the enclosing parentheses, e.g., -\code{a, b, c} or \code{()}. A single item tuple must have a trailing -comma, e.g., \code{(d,)}. -\indexii{sequence}{types} -\indexii{string}{type} -\indexii{tuple}{type} -\indexii{list}{type} - -Sequence types support the following operations. The \samp{in} and -\samp{not\,in} operations have the same priorities as the comparison -operations. The \samp{+} and \samp{*} operations have the same -priority as the corresponding numeric operations.\footnote{They must -have since the parser can't tell the type of the operands.} - -This table lists the sequence operations sorted in ascending priority -(operations in the same box have the same priority). In the table, -\var{s} and \var{t} are sequences of the same type; \var{n}, \var{i} -and \var{j} are integers: - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes} - \lineiii{\var{x} in \var{s}}{\code{1} if an item of \var{s} is equal to \var{x}, else \code{0}}{} - \lineiii{\var{x} not in \var{s}}{\code{0} if an item of \var{s} is -equal to \var{x}, else \code{1}}{} - \hline - \lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{} - \hline - \lineiii{\var{s} * \var{n}{\rm ,} \var{n} * \var{s}}{\var{n} copies of \var{s} concatenated}{} - \hline - \lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(1)} - \lineiii{\var{s}[\var{i}:\var{j}]}{slice of \var{s} from \var{i} to \var{j}}{(1), (2)} - \hline - \lineiii{len(\var{s})}{length of \var{s}}{} - \lineiii{min(\var{s})}{smallest item of \var{s}}{} - \lineiii{max(\var{s})}{largest item of \var{s}}{} -\end{tableiii} -\indexiii{operations on}{sequence}{types} -\bifuncindex{len} -\bifuncindex{min} -\bifuncindex{max} -\indexii{concatenation}{operation} -\indexii{repetition}{operation} -\indexii{subscript}{operation} -\indexii{slice}{operation} -\opindex{in} -\opindex{not in} - -\noindent -Notes: - -\begin{description} - -\item[(1)] If \var{i} or \var{j} is negative, the index is relative to - the end of the string, i.e., \code{len(\var{s}) + \var{i}} or - \code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is - still \code{0}. - -\item[(2)] The slice of \var{s} from \var{i} to \var{j} is defined as - the sequence of items with index \var{k} such that \code{\var{i} <= - \var{k} < \var{j}}. If \var{i} or \var{j} is greater than - \code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted, - use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If - \var{i} is greater than or equal to \var{j}, the slice is empty. - -\end{description} - -\subsubsection{More String Operations} - -String objects have one unique built-in operation: the \code{\%} -operator (modulo) with a string left argument interprets this string -as a C sprintf format string to be applied to the right argument, and -returns the string resulting from this formatting operation. - -The right argument should be a tuple with one item for each argument -required by the format string; if the string requires a single -argument, the right argument may also be a single non-tuple object.% -\footnote{A tuple object in this case should be a singleton.} -The following format characters are understood: -\%, c, s, i, d, u, o, x, X, e, E, f, g, G. -Width and precision may be a * to specify that an integer argument -specifies the actual width or precision. The flag characters -, +, -blank, \# and 0 are understood. The size specifiers h, l or L may be -present but are ignored. The \code{\%s} conversion takes any Python -object and converts it to a string using \code{str()} before -formatting it. The ANSI features \code{\%p} and \code{\%n} -are not supported. Since Python strings have an explicit length, -\code{\%s} conversions don't assume that \code{'\e0'} is the end of -the string. - -For safety reasons, floating point precisions are clipped to 50; -\code{\%f} conversions for numbers whose absolute value is over 1e25 -are replaced by \code{\%g} conversions.% -\footnote{These numbers are fairly arbitrary. They are intended to -avoid printing endless strings of meaningless digits without hampering -correct use and without having to know the exact precision of floating -point values on a particular machine.} -All other errors raise exceptions. - -If the right argument is a dictionary (or any kind of mapping), then -the formats in the string must have a parenthesized key into that -dictionary inserted immediately after the \code{\%} character, and -each format formats the corresponding entry from the mapping. E.g. -\begin{verbatim} - >>> count = 2 - >>> language = 'Python' - >>> print '%(language)s has %(count)03d quote types.' % vars() - Python has 002 quote types. - >>> -\end{verbatim} -In this case no * specifiers may occur in a format (since they a -require sequential parameter list). - -Additional string operations are defined in standard module -\code{string} and in built-in module \code{regex}. -\index{string} -\index{regex} - -\subsubsection{Mutable Sequence Types} - -List objects support additional operations that allow in-place -modification of the object. -These operations would be supported by other mutable sequence types -(when added to the language) as well. -Strings and tuples are immutable sequence types and such objects cannot -be modified once created. -The following operations are defined on mutable sequence types (where -\var{x} is an arbitrary object): -\indexiii{mutable}{sequence}{types} -\indexii{list}{type} - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes} - \lineiii{\var{s}[\var{i}] = \var{x}} - {item \var{i} of \var{s} is replaced by \var{x}}{} - \lineiii{\var{s}[\var{i}:\var{j}] = \var{t}} - {slice of \var{s} from \var{i} to \var{j} is replaced by \var{t}}{} - \lineiii{del \var{s}[\var{i}:\var{j}]} - {same as \code{\var{s}[\var{i}:\var{j}] = []}}{} - \lineiii{\var{s}.append(\var{x})} - {same as \code{\var{s}[len(\var{s}):len(\var{s})] = [\var{x}]}}{} - \lineiii{\var{s}.count(\var{x})} - {return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{} - \lineiii{\var{s}.index(\var{x})} - {return smallest \var{i} such that \code{\var{s}[\var{i}] == \var{x}}}{(1)} - \lineiii{\var{s}.insert(\var{i}, \var{x})} - {same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]} - if \code{\var{i} >= 0}}{} - \lineiii{\var{s}.remove(\var{x})} - {same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(1)} - \lineiii{\var{s}.reverse()} - {reverses the items of \var{s} in place}{} - \lineiii{\var{s}.sort()} - {permutes the items of \var{s} to satisfy - \code{\var{s}[\var{i}] <= \var{s}[\var{j}]}, - for \code{\var{i} < \var{j}}}{(2)} -\end{tableiii} -\indexiv{operations on}{mutable}{sequence}{types} -\indexiii{operations on}{sequence}{types} -\indexiii{operations on}{list}{type} -\indexii{subscript}{assignment} -\indexii{slice}{assignment} -\stindex{del} -\renewcommand{\indexsubitem}{(list method)} -\ttindex{append} -\ttindex{count} -\ttindex{index} -\ttindex{insert} -\ttindex{remove} -\ttindex{reverse} -\ttindex{sort} - -\noindent -Notes: -\begin{description} -\item[(1)] Raises an exception when \var{x} is not found in \var{s}. - -\item[(2)] The \code{sort()} method takes an optional argument - specifying a comparison function of two arguments (list items) which - should return \code{-1}, \code{0} or \code{1} depending on whether the - first argument is considered smaller than, equal to, or larger than the - second argument. Note that this slows the sorting process down - considerably; e.g. to sort a list in reverse order it is much faster - to use calls to \code{sort()} and \code{reverse()} than to use - \code{sort()} with a comparison function that reverses the ordering of - the elements. -\end{description} - -\subsection{Mapping Types} - -A \dfn{mapping} object maps values of one type (the key type) to -arbitrary objects. Mappings are mutable objects. There is currently -only one standard mapping type, the \dfn{dictionary}. A dictionary's keys are -almost arbitrary values. The only types of values not acceptable as -keys are values containing lists or dictionaries or other mutable -types that are compared by value rather than by object identity. -Numeric types used for keys obey the normal rules for numeric -comparison: if two numbers compare equal (e.g. 1 and 1.0) then they -can be used interchangeably to index the same dictionary entry. - -\indexii{mapping}{types} -\indexii{dictionary}{type} - -Dictionaries are created by placing a comma-separated list of -\code{\var{key}:\,var{value}} pairs within braces, for example: -\code{\{'jack':\,4098, 'sjoerd':\,4127\}} or -\code{\{4098:\,'jack', 4127:\,'sjoerd'\}}. - -The following operations are defined on mappings (where \var{a} is a -mapping, \var{k} is a key and \var{x} is an arbitrary object): - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes} - \lineiii{len(\var{a})}{the number of items in \var{a}}{} - \lineiii{\var{a}[\var{k}]}{the item of \var{a} with key \var{k}}{(1)} - \lineiii{\var{a}[\var{k}] = \var{x}}{set \code{\var{a}[\var{k}]} to \var{x}}{} - \lineiii{del \var{a}[\var{k}]}{remove \code{\var{a}[\var{k}]} from \var{a}}{(1)} - \lineiii{\var{a}.items()}{a copy of \var{a}'s list of (key, item) pairs}{(2)} - \lineiii{\var{a}.keys()}{a copy of \var{a}'s list of keys}{(2)} - \lineiii{\var{a}.values()}{a copy of \var{a}'s list of values}{(2)} - \lineiii{\var{a}.has_key(\var{k})}{\code{1} if \var{a} has a key \var{k}, else \code{0}}{} -\end{tableiii} -\indexiii{operations on}{mapping}{types} -\indexiii{operations on}{dictionary}{type} -\stindex{del} -\bifuncindex{len} -\renewcommand{\indexsubitem}{(dictionary method)} -\ttindex{keys} -\ttindex{has_key} - -\noindent -Notes: -\begin{description} -\item[(1)] Raises an exception if \var{k} is not in the map. - -\item[(2)] Keys and values are listed in random order. -\end{description} - -\subsection{Other Built-in Types} - -The interpreter supports several other kinds of objects. -Most of these support only one or two operations. - -\subsubsection{Modules} - -The only special operation on a module is attribute access: -\code{\var{m}.\var{name}}, where \var{m} is a module and \var{name} accesses -a name defined in \var{m}'s symbol table. Module attributes can be -assigned to. (Note that the \code{import} statement is not, strictly -spoken, an operation on a module object; \code{import \var{foo}} does not -require a module object named \var{foo} to exist, rather it requires -an (external) \emph{definition} for a module named \var{foo} -somewhere.) - -A special member of every module is \code{__dict__}. -This is the dictionary containing the module's symbol table. -Modifying this dictionary will actually change the module's symbol -table, but direct assignment to the \code{__dict__} attribute is not -possible (i.e., you can write \code{\var{m}.__dict__['a'] = 1}, which -defines \code{\var{m}.a} to be \code{1}, but you can't write \code{\var{m}.__dict__ = \{\}}. - -Modules are written like this: \code{<module 'sys'>}. - -\subsubsection{Classes and Class Instances} -\nodename{Classes and Instances} - -(See Chapters 3 and 7 of the Python Reference Manual for these.) - -\subsubsection{Functions} - -Function objects are created by function definitions. The only -operation on a function object is to call it: -\code{\var{func}(\var{argument-list})}. - -There are really two flavors of function objects: built-in functions -and user-defined functions. Both support the same operation (to call -the function), but the implementation is different, hence the -different object types. - -The implementation adds two special read-only attributes: -\code{\var{f}.func_code} is a function's \dfn{code object} (see below) and -\code{\var{f}.func_globals} is the dictionary used as the function's -global name space (this is the same as \code{\var{m}.__dict__} where -\var{m} is the module in which the function \var{f} was defined). - -\subsubsection{Methods} -\obindex{method} - -Methods are functions that are called using the attribute notation. -There are two flavors: built-in methods (such as \code{append()} on -lists) and class instance methods. Built-in methods are described -with the types that support them. - -The implementation adds two special read-only attributes to class -instance methods: \code{\var{m}.im_self} is the object whose method this -is, and \code{\var{m}.im_func} is the function implementing the method. -Calling \code{\var{m}(\var{arg-1}, \var{arg-2}, {\rm \ldots}, -\var{arg-n})} is completely equivalent to calling -\code{\var{m}.im_func(\var{m}.im_self, \var{arg-1}, \var{arg-2}, {\rm -\ldots}, \var{arg-n})}. - -(See the Python Reference Manual for more info.) - -\subsubsection{Code Objects} -\obindex{code} - -Code objects are used by the implementation to represent -``pseudo-compiled'' executable Python code such as a function body. -They differ from function objects because they don't contain a -reference to their global execution environment. Code objects are -returned by the built-in \code{compile()} function and can be -extracted from function objects through their \code{func_code} -attribute. -\bifuncindex{compile} -\ttindex{func_code} - -A code object can be executed or evaluated by passing it (instead of a -source string) to the \code{exec} statement or the built-in -\code{eval()} function. -\stindex{exec} -\bifuncindex{eval} - -(See the Python Reference Manual for more info.) - -\subsubsection{Type Objects} - -Type objects represent the various object types. An object's type is -accessed by the built-in function \code{type()}. There are no special -operations on types. The standard module \code{types} defines names -for all standard built-in types. -\bifuncindex{type} -\stmodindex{types} - -Types are written like this: \code{<type 'int'>}. - -\subsubsection{The Null Object} - -This object is returned by functions that don't explicitly return a -value. It supports no special operations. There is exactly one null -object, named \code{None} (a built-in name). - -It is written as \code{None}. - -\subsubsection{File Objects} - -File objects are implemented using \C{}'s \code{stdio} package and can be -created with the built-in function \code{open()} described under -Built-in Functions below. They are also returned by some other -built-in functions and methods, e.g.\ \code{posix.popen()} and -\code{posix.fdopen()} and the \code{makefile()} method of socket -objects. -\bifuncindex{open} - -When a file operation fails for an I/O-related reason, the exception -\code{IOError} is raised. This includes situations where the -operation is not defined for some reason, like \code{seek()} on a tty -device or writing a file opened for reading. - -Files have the following methods: - - -\renewcommand{\indexsubitem}{(file method)} - -\begin{funcdesc}{close}{} - Close the file. A closed file cannot be read or written anymore. -\end{funcdesc} - -\begin{funcdesc}{flush}{} - Flush the internal buffer, like \code{stdio}'s \code{fflush()}. -\end{funcdesc} - -\begin{funcdesc}{isatty}{} - Return \code{1} if the file is connected to a tty(-like) device, else - \code{0}. -\end{funcdesc} - -\begin{funcdesc}{read}{\optional{size}} - Read at most \var{size} bytes from the file (less if the read hits - \EOF{} or no more data is immediately available on a pipe, tty or - similar device). If the \var{size} argument is negative or omitted, - read all data until \EOF{} is reached. The bytes are returned as a string - object. An empty string is returned when \EOF{} is encountered - immediately. (For certain files, like ttys, it makes sense to - continue reading after an \EOF{} is hit.) -\end{funcdesc} - -\begin{funcdesc}{readline}{\optional{size}} - Read one entire line from the file. A trailing newline character is - kept in the string% -\footnote{The advantage of leaving the newline on is that an empty string - can be returned to mean \EOF{} without being ambiguous. Another - advantage is that (in cases where it might matter, e.g. if you - want to make an exact copy of a file while scanning its lines) - you can tell whether the last line of a file ended in a newline - or not (yes this happens!).} - (but may be absent when a file ends with an - incomplete line). If thevar{size} argument is present and - non-negative, it is a maximum byte count (including the trailing - newline) and an incomplete line may be returned. - An empty string is returned when \EOF{} is hit - immediately. Note: unlike \code{stdio}'s \code{fgets()}, the returned - string contains null characters (\code{'\e 0'}) if they occurred in the - input. -\end{funcdesc} - -\begin{funcdesc}{readlines}{} - Read until \EOF{} using \code{readline()} and return a list containing - the lines thus read. -\end{funcdesc} - -\begin{funcdesc}{seek}{offset\, whence} - Set the file's current position, like \code{stdio}'s \code{fseek()}. - The \var{whence} argument is optional and defaults to \code{0} - (absolute file positioning); other values are \code{1} (seek - relative to the current position) and \code{2} (seek relative to the - file's end). There is no return value. -\end{funcdesc} - -\begin{funcdesc}{tell}{} - Return the file's current position, like \code{stdio}'s \code{ftell()}. -\end{funcdesc} - -\begin{funcdesc}{truncate}{\optional{size}} -Truncate the file's size. If the optional size argument present, the -file is truncated to (at most) that size. The size defaults to the -current position. Availability of this function depends on the -operating system version (e.g., not all {\UNIX} versions support this -operation). -\end{funcdesc} - -\begin{funcdesc}{write}{str} -Write a string to the file. There is no return value. Note: due to -buffering, the string may not actually show up in the file until -the \code{flush()} or \code{close()} method is called. -\end{funcdesc} - -\begin{funcdesc}{writelines}{list} -Write a list of strings to the file. There is no return value. -(The name is intended to match \code{readlines}; \code{writelines} -does not add line separators.) -\end{funcdesc} - -\subsubsection{Internal Objects} - -(See the Python Reference Manual for these.) - -\subsection{Special Attributes} - -The implementation adds a few special read-only attributes to several -object types, where they are relevant: - -\begin{itemize} - -\item -\code{\var{x}.__dict__} is a dictionary of some sort used to store an -object's (writable) attributes; - -\item -\code{\var{x}.__methods__} lists the methods of many built-in object types, -e.g., \code{[].__methods__} yields -\code{['append', 'count', 'index', 'insert', 'remove', 'reverse', 'sort']}; - -\item -\code{\var{x}.__members__} lists data attributes; - -\item -\code{\var{x}.__class__} is the class to which a class instance belongs; - -\item -\code{\var{x}.__bases__} is the tuple of base classes of a class object. - -\end{itemize} diff --git a/Doc/lib/libtypes2.tex b/Doc/lib/libtypes2.tex deleted file mode 100644 index d0f20c9db7..0000000000 --- a/Doc/lib/libtypes2.tex +++ /dev/null @@ -1,122 +0,0 @@ -\section{Standard Module \sectcode{types}} -\stmodindex{types} - -\renewcommand{\indexsubitem}{(in module types)} - -This module defines names for all object types that are used by the -standard Python interpreter (but not for the types defined by various -extension modules). It is safe to use ``\code{from types import *}'' --- -the module does not export any other names besides the ones listed -here. New names exported by future versions of this module will -all end in \code{Type}. - -Typical use is for functions that do different things depending on -their argument types, like the following: - -\begin{verbatim} -from types import * -def delete(list, item): - if type(item) is IntType: - del list[item] - else: - list.remove(item) -\end{verbatim} - -The module defines the following names: - -\begin{datadesc}{NoneType} -The type of \code{None}. -\end{datadesc} - -\begin{datadesc}{TypeType} -The type of type objects (such as returned by \code{type()}). -\end{datadesc} - -\begin{datadesc}{IntType} -The type of integers (e.g. \code{1}). -\end{datadesc} - -\begin{datadesc}{LongType} -The type of long integers (e.g. \code{1L}). -\end{datadesc} - -\begin{datadesc}{FloatType} -The type of floating point numbers (e.g. \code{1.0}). -\end{datadesc} - -\begin{datadesc}{StringType} -The type of character strings (e.g. \code{'Spam'}). -\end{datadesc} - -\begin{datadesc}{TupleType} -The type of tuples (e.g. \code{(1, 2, 3, 'Spam')}). -\end{datadesc} - -\begin{datadesc}{ListType} -The type of lists (e.g. \code{[0, 1, 2, 3]}). -\end{datadesc} - -\begin{datadesc}{DictType} -The type of dictionaries (e.g. \code{\{'Bacon': 1, 'Ham': 0\}}). -\end{datadesc} - -\begin{datadesc}{DictionaryType} -An alternative name for \code{DictType}. -\end{datadesc} - -\begin{datadesc}{FunctionType} -The type of user-defined functions and lambdas. -\end{datadesc} - -\begin{datadesc}{LambdaType} - An alternative name for \code{FunctionType}. -\end{datadesc} - -\begin{datadesc}{CodeType} -The type for code objects such as returned by \code{compile()}. -\end{datadesc} - -\begin{datadesc}{ClassType} -The type of user-defined classes. -\end{datadesc} - -\begin{datadesc}{InstanceType} -The type of instances of user-defined classes. -\end{datadesc} - -\begin{datadesc}{MethodType} -The type of methods of user-defined class instances. -\end{datadesc} - -\begin{datadesc}{UnboundMethodType} -An alternative name for \code{MethodType}. -\end{datadesc} - -\begin{datadesc}{BuiltinFunctionType} -The type of built-in functions like \code{len} or \code{sys.exit}. -\end{datadesc} - -\begin{datadesc}{BuiltinMethodType} -An alternative name for \code{BuiltinFunction}. -\end{datadesc} - -\begin{datadesc}{ModuleType} -The type of modules. -\end{datadesc} - -\begin{datadesc}{FileType} -The type of open file objects such as \code{sys.stdout}. -\end{datadesc} - -\begin{datadesc}{XRangeType} -The type of range objects returned by \code{xrange()}. -\end{datadesc} - -\begin{datadesc}{TracebackType} -The type of traceback objects such as found in \code{sys.exc_traceback}. -\end{datadesc} - -\begin{datadesc}{FrameType} -The type of frame objects such as found in \code{tb.tb_frame} if -\code{tb} is a traceback object. -\end{datadesc} diff --git a/Doc/lib/libunix.tex b/Doc/lib/libunix.tex deleted file mode 100644 index 895c6e5745..0000000000 --- a/Doc/lib/libunix.tex +++ /dev/null @@ -1,39 +0,0 @@ -\chapter{UNIX Specific Services} - -The modules described in this chapter provide interfaces to features -that are unique to the \UNIX{} operating system, or in some cases to -some or many variants of it. Here's an overview: - -\begin{description} - -\item[posix] ---- The most common Posix system calls (normally used via module \code{os}). - -\item[posixpath] ---- Common Posix pathname manipulations (normally used via \code{os.path}). - -\item[pwd] ---- The password database (\code{getpwnam()} and friends). - -\item[grp] ---- The group database (\code{getgrnam()} and friends). - -\item[crypt] ---- The (\code{crypt()} function used to check Unix passwords). - -\item[dbm] ---- The standard ``database'' interface, based on \code{ndbm}. - -\item[gdbm] ---- GNU's reinterpretation of dbm. - -\item[termios] ---- Posix style tty control. - -\item[fcntl] ---- The \code{fcntl()} and \code{ioctl()} system calls. - -\item[posixfile] ---- A file-like object with support for locking. - -\end{description} diff --git a/Doc/lib/liburllib.tex b/Doc/lib/liburllib.tex deleted file mode 100644 index b26228f12e..0000000000 --- a/Doc/lib/liburllib.tex +++ /dev/null @@ -1,121 +0,0 @@ -\section{Standard Module \sectcode{urllib}} -\stmodindex{urllib} -\index{WWW} -\index{World-Wide Web} -\index{URL} - -\renewcommand{\indexsubitem}{(in module urllib)} - -This module provides a high-level interface for fetching data across -the World-Wide Web. In particular, the \code{urlopen} function is -similar to the built-in function \code{open}, but accepts URLs -(Universal Resource Locators) instead of filenames. Some restrictions -apply --- it can only open URLs for reading, and no seek operations -are available. - -it defines the following public functions: - -\begin{funcdesc}{urlopen}{url} -Open a network object denoted by a URL for reading. If the URL does -not have a scheme identifier, or if it has \samp{file:} as its scheme -identifier, this opens a local file; otherwise it opens a socket to a -server somewhere on the network. If the connection cannot be made, or -if the server returns an error code, the \code{IOError} exception is -raised. If all went well, a file-like object is returned. This -supports the following methods: \code{read()}, \code{readline()}, -\code{readlines()}, \code{fileno()}, \code{close()} and \code{info()}. -Except for the last one, these methods have the same interface as for -file objects --- see the section on File Objects earlier in this -manual. (It's not a built-in file object, however, so it can't be -used at those few places where a true built-in file object is -required.) - -The \code{info()} method returns an instance of the class -\code{rfc822.Message} containing the headers received from the server, -if the protocol uses such headers (currently the only supported -protocol that uses this is HTTP). See the description of the -\code{rfc822} module. -\end{funcdesc} - -\begin{funcdesc}{urlretrieve}{url} -Copy a network object denoted by a URL to a local file, if necessary. -If the URL points to a local file, or a valid cached copy of the -object exists, the object is not copied. Return a tuple (\var{filename}, -\var{headers}) where \var{filename} is the local file name under which -the object can be found, and \var{headers} is either \code{None} (for -a local object) or whatever the \code{info()} method of the object -returned by \code{urlopen()} returned (for a remote object, possibly -cached). Exceptions are the same as for \code{urlopen()}. -\end{funcdesc} - -\begin{funcdesc}{urlcleanup}{} -Clear the cache that may have been built up by previous calls to -\code{urlretrieve()}. -\end{funcdesc} - -\begin{funcdesc}{quote}{string\optional{\, addsafe}} -Replace special characters in \var{string} using the \code{\%xx} escape. -Letters, digits, and the characters ``\code{_,.-}'' are never quoted. -The optional \var{addsafe} parameter specifies additional characters -that should not be quoted --- its default value is \code{'/'}. - -Example: \code{quote('/\~conolly/')} yields \code{'/\%7econnolly/'}. -\end{funcdesc} - -\begin{funcdesc}{unquote}{string} -Replace \samp{\%xx} escapes by their single-character equivalent. - -Example: \code{unquote('/\%7Econnolly/')} yields \code{'/\~connolly/'}. -\end{funcdesc} - -Restrictions: - -\begin{itemize} - -\item -Currently, only the following protocols are supported: HTTP, (versions -0.9 and 1.0), Gopher (but not Gopher-+), FTP, and local files. -\index{HTTP} -\index{Gopher} -\index{FTP} - -\item -The caching feature of \code{urlretrieve()} has been disabled until I -find the time to hack proper processing of Expiration time headers. - -\item -There should be a function to query whether a particular URL is in -the cache. - -\item -For backward compatibility, if a URL appears to point to a local file -but the file can't be opened, the URL is re-interpreted using the FTP -protocol. This can sometimes cause confusing error messages. - -\item -The \code{urlopen()} and \code{urlretrieve()} functions can cause -arbitrarily long delays while waiting for a network connection to be -set up. This means that it is difficult to build an interactive -web client using these functions without using threads. - -\item -The data returned by \code{urlopen()} or \code{urlretrieve()} is the -raw data returned by the server. This may be binary data (e.g. an -image), plain text or (for example) HTML. The HTTP protocol provides -type information in the reply header, which can be inspected by -looking at the \code{Content-type} header. For the Gopher protocol, -type information is encoded in the URL; there is currently no easy way -to extract it. If the returned data is HTML, you can use the module -\code{htmllib} to parse it. -\index{HTML} -\index{HTTP} -\index{Gopher} -\stmodindex{htmllib} - -\item -Although the \code{urllib} module contains (undocumented) routines to -parse and unparse URL strings, the recommended interface for URL -manipulation is in module \code{urlparse}. -\stmodindex{urlparse} - -\end{itemize} diff --git a/Doc/lib/liburlparse.tex b/Doc/lib/liburlparse.tex deleted file mode 100644 index 36ca949ba6..0000000000 --- a/Doc/lib/liburlparse.tex +++ /dev/null @@ -1,84 +0,0 @@ -\section{Standard Module \sectcode{urlparse}} -\stmodindex{urlparse} -\index{WWW} -\index{World-Wide Web} -\index{URL} -\indexii{URL}{parsing} -\indexii{relative}{URL} - -\renewcommand{\indexsubitem}{(in module urlparse)} - -This module defines a standard interface to break URL strings up in -components (addessing scheme, network location, path etc.), to combine -the components back into a URL string, and to convert a ``relative -URL'' to an absolute URL given a ``base URL''. - -The module has been designed to match the current Internet draft on -Relative Uniform Resource Locators (and discovered a bug in an earlier -draft!). - -It defines the following functions: - -\begin{funcdesc}{urlparse}{urlstring\optional{\, -default_scheme\optional{\, allow_fragments}}} -Parse a URL into 6 components, returning a 6-tuple: (addressing -scheme, network location, path, parameters, query, fragment -identifier). This corresponds to the general structure of a URL: -\code{\var{scheme}://\var{netloc}/\var{path};\var{parameters}?\var{query}\#\var{fragment}}. -Each tuple item is a string, possibly empty. -The components are not broken up in smaller parts (e.g. the network -location is a single string), and \% escapes are not expanded. -The delimiters as shown above are not part of the tuple items, -except for a leading slash in the \var{path} component, which is -retained if present. - -Example: - -\begin{verbatim} -urlparse('http://www.cwi.nl:80/%7Eguido/Python.html') -\end{verbatim} - -yields the tuple - -\begin{verbatim} -('http', 'www.cwi.nl:80', '/%7Eguido/Python.html', '', '', '') -\end{verbatim} - -If the \var{default_scheme} argument is specified, it gives the -default addressing scheme, to be used only if the URL string does not -specify one. The default value for this argument is the empty string. - -If the \var{allow_fragments} argument is zero, fragment identifiers -are not allowed, even if the URL's addressing scheme normally does -support them. The default value for this argument is \code{1}. -\end{funcdesc} - -\begin{funcdesc}{urlunparse}{tuple} -Construct a URL string from a tuple as returned by \code{urlparse}. -This may result in a slightly different, but equivalent URL, if the -URL that was parsed originally had redundant delimiters, e.g. a ? with -an empty query (the draft states that these are equivalent). -\end{funcdesc} - -\begin{funcdesc}{urljoin}{base\, url\optional{\, allow_fragments}} -Construct a full (``absolute'') URL by combining a ``base URL'' -(\var{base}) with a ``relative URL'' (\var{url}). Informally, this -uses components of the base URL, in particular the addressing scheme, -the network location and (part of) the path, to provide missing -components in the relative URL. - -Example: - -\begin{verbatim} -urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html') -\end{verbatim} - -yields the string - -\begin{verbatim} -'http://www.cwi.nl/%7Eguido/FAQ.html' -\end{verbatim} - -The \var{allow_fragments} argument has the same meaning as for -\code{urlparse}. -\end{funcdesc} diff --git a/Doc/lib/libwhrandom.tex b/Doc/lib/libwhrandom.tex deleted file mode 100644 index 8ad2339a34..0000000000 --- a/Doc/lib/libwhrandom.tex +++ /dev/null @@ -1,20 +0,0 @@ -\section{Standard Module \sectcode{whrandom}} - -\stmodindex{whrandom} -This module implements a Wichmann-Hill pseudo-random number generator. -It defines the following functions: - -\renewcommand{\indexsubitem}{(in module whrandom)} -\begin{funcdesc}{random}{} -Returns the next random floating point number in the range [0.0 ... 1.0). -\end{funcdesc} - -\begin{funcdesc}{seed}{x\, y\, z} -Initializes the random number generator from the integers -\var{x}, -\var{y} -and -\var{z}. -When the module is first imported, the random number is initialized -using values derived from the current time. -\end{funcdesc} diff --git a/Doc/lib/libwww.tex b/Doc/lib/libwww.tex deleted file mode 100644 index 009c79bc71..0000000000 --- a/Doc/lib/libwww.tex +++ /dev/null @@ -1,51 +0,0 @@ -\chapter{Internet and WWW Services} -\nodename{Internet and WWW} -\index{WWW} -\index{Internet} -\index{World-Wide Web} - -The modules described in this chapter provide various services to -World-Wide Web (WWW) clients and/or services, and a few modules -related to news and email. They are all implemented in Python. Some -of these modules require the presence of the system-dependent module -\code{sockets}, which is currently only fully supported on Unix and -Windows NT. Here is an overview: - -\begin{description} - -\item[cgi] ---- Common Gateway Interface, used to interpret forms in server-side -scripts. - -\item[urllib] ---- Open an arbitrary object given by URL (requires sockets). - -\item[httplib] ---- HTTP protocol client (requires sockets). - -\item[ftplib] ---- FTP protocol client (requires sockets). - -\item[gopherlib] ---- Gopher protocol client (requires sockets). - -\item[nntplib] ---- NNTP protocol client (requires sockets). - -\item[urlparse] ---- Parse a URL string into a tuple (addressing scheme identifier, network -location, path, parameters, query string, fragment identifier). - -\item[htmllib] ---- A (slow) parser for HTML files. - -\item[sgmllib] ---- Only as much of an SGML parser as needed to parse HTML. - -\item[rfc822] ---- Parse RFC-822 style mail headers. - -\item[mimetools] ---- Tools for parsing MIME style message bodies. - -\end{description} diff --git a/Doc/libaifc.tex b/Doc/libaifc.tex deleted file mode 100644 index 04ed2e421a..0000000000 --- a/Doc/libaifc.tex +++ /dev/null @@ -1,189 +0,0 @@ -\section{Standard Module \sectcode{aifc}} -\stmodindex{aifc} - -This module provides support for reading and writing AIFF and AIFF-C -files. AIFF is Audio Interchange File Format, a format for storing -digital audio samples in a file. AIFF-C is a newer version of the -format that includes the ability to compress the audio data. - -Audio files have a number of parameters that describe the audio data. -The sampling rate or frame rate is the number of times per second the -sound is sampled. The number of channels indicate if the audio is -mono, stereo, or quadro. Each frame consists of one sample per -channel. The sample size is the size in bytes of each sample. Thus a -frame consists of \var{nchannels}*\var{samplesize} bytes, and a -second's worth of audio consists of -\var{nchannels}*\var{samplesize}*\var{framerate} bytes. - -For example, CD quality audio has a sample size of two bytes (16 -bits), uses two channels (stereo) and has a frame rate of 44,100 -frames/second. This gives a frame size of 4 bytes (2*2), and a -second's worth occupies 2*2*44100 bytes, i.e.\ 176,400 bytes. - -Module \code{aifc} defines the following function: - -\renewcommand{\indexsubitem}{(in module aifc)} -\begin{funcdesc}{open}{file\, mode} -Open an AIFF or AIFF-C file and return an object instance with -methods that are described below. The argument file is either a -string naming a file or a file object. The mode is either the string -\code{'r'} when the file must be opened for reading, or \code{'w'} -when the file must be opened for writing. When used for writing, the -file object should be seekable, unless you know ahead of time how many -samples you are going to write in total and use -\code{writeframesraw()} and \code{setnframes()}. -\end{funcdesc} - -Objects returned by \code{aifc.open()} when a file is opened for -reading have the following methods: - -\renewcommand{\indexsubitem}{(aifc object method)} -\begin{funcdesc}{getnchannels}{} -Return the number of audio channels (1 for mono, 2 for stereo). -\end{funcdesc} - -\begin{funcdesc}{getsampwidth}{} -Return the size in bytes of individual samples. -\end{funcdesc} - -\begin{funcdesc}{getframerate}{} -Return the sampling rate (number of audio frames per second). -\end{funcdesc} - -\begin{funcdesc}{getnframes}{} -Return the number of audio frames in the file. -\end{funcdesc} - -\begin{funcdesc}{getcomptype}{} -Return a four-character string describing the type of compression used -in the audio file. For AIFF files, the returned value is -\code{'NONE'}. -\end{funcdesc} - -\begin{funcdesc}{getcompname}{} -Return a human-readable description of the type of compression used in -the audio file. For AIFF files, the returned value is \code{'not -compressed'}. -\end{funcdesc} - -\begin{funcdesc}{getparams}{} -Return a tuple consisting of all of the above values in the above -order. -\end{funcdesc} - -\begin{funcdesc}{getmarkers}{} -Return a list of markers in the audio file. A marker consists of a -tuple of three elements. The first is the mark ID (an integer), the -second is the mark position in frames from the beginning of the data -(an integer), the third is the name of the mark (a string). -\end{funcdesc} - -\begin{funcdesc}{getmark}{id} -Return the tuple as described in \code{getmarkers} for the mark with -the given id. -\end{funcdesc} - -\begin{funcdesc}{readframes}{nframes} -Read and return the next \var{nframes} frames from the audio file. The -returned data is a string containing for each frame the uncompressed -samples of all channels. -\end{funcdesc} - -\begin{funcdesc}{rewind}{} -Rewind the read pointer. The next \code{readframes} will start from -the beginning. -\end{funcdesc} - -\begin{funcdesc}{setpos}{pos} -Seek to the specified frame number. -\end{funcdesc} - -\begin{funcdesc}{tell}{} -Return the current frame number. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Close the AIFF file. After calling this method, the object can no -longer be used. -\end{funcdesc} - -Objects returned by \code{aifc.open()} when a file is opened for -writing have all the above methods, except for \code{readframes} and -\code{setpos}. In addition the following methods exist. The -\code{get} methods can only be called after the corresponding -\code{set} methods have been called. Before the first -\code{writeframes} or \code{writeframesraw}, all parameters except for -the number of frames must be filled in. - -\begin{funcdesc}{aiff}{} -Create an AIFF file. The default is that an AIFF-C file is created, -unless the name of the file ends in '.aiff' in which case the default -is an AIFF file. -\end{funcdesc} - -\begin{funcdesc}{aifc}{} -Create an AIFF-C file. The default is that an AIFF-C file is created, -unless the name of the file ends in '.aiff' in which case the default -is an AIFF file. -\end{funcdesc} - -\begin{funcdesc}{setnchannels}{nchannels} -Specify the number of channels in the audio file. -\end{funcdesc} - -\begin{funcdesc}{setsampwidth}{width} -Specify the size in bytes of audio samples. -\end{funcdesc} - -\begin{funcdesc}{setframerate}{rate} -Specify the sampling frequency in frames per second. -\end{funcdesc} - -\begin{funcdesc}{setnframes}{nframes} -Specify the number of frames that are to be written to the audio file. -If this parameter is not set, or not set correctly, the file needs to -support seeking. -\end{funcdesc} - -\begin{funcdesc}{setcomptype}{type\, name} -Specify the compression type. If not specified, the audio data will -not be compressed. In AIFF files, compression is not possible. The -name parameter should be a human-readable description of the -compression type, the type parameter should be a four-character -string. Currently the following compression types are supported: -NONE, ULAW, ALAW, G722. -\end{funcdesc} - -\begin{funcdesc}{setparams}{nchannels\, sampwidth\, framerate\, comptype\, compname} -Set all the above parameters at once. The argument is a tuple -consisting of the various parameters. This means that it is possible -to use the result of a \code{getparams} call as argument to -\code{setparams}. -\end{funcdesc} - -\begin{funcdesc}{setmark}{id\, pos\, name} -Add a mark with the given id (larger than 0), and the given name at -the given position. This method can be called at any time before -\code{close}. -\end{funcdesc} - -\begin{funcdesc}{tell}{} -Return the current write position in the output file. Useful in -combination with \code{setmark}. -\end{funcdesc} - -\begin{funcdesc}{writeframes}{data} -Write data to the output file. This method can only be called after -the audio file parameters have been set. -\end{funcdesc} - -\begin{funcdesc}{writeframesraw}{data} -Like \code{writeframes}, except that the header of the audio file is -not updated. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Close the AIFF file. The header of the file is updated to reflect the -actual size of the audio data. After calling this method, the object -can no longer be used. -\end{funcdesc} diff --git a/Doc/libal.tex b/Doc/libal.tex deleted file mode 100644 index 6a812ddab0..0000000000 --- a/Doc/libal.tex +++ /dev/null @@ -1,172 +0,0 @@ -\section{Built-in Module \sectcode{al}} -\bimodindex{al} - -This module provides access to the audio facilities of the SGI Indy -and Indigo workstations. See section 3A of the IRIX man pages for -details. You'll need to read those man pages to understand what these -functions do! Some of the functions are not available in IRIX -releases before 4.0.5. Again, see the manual to check whether a -specific function is available on your platform. - -All functions and methods defined in this module are equivalent to -the C functions with \samp{AL} prefixed to their name. - -Symbolic constants from the C header file \file{<audio.h>} are defined -in the standard module \code{AL}, see below. - -\strong{Warning:} the current version of the audio library may dump core -when bad argument values are passed rather than returning an error -status. Unfortunately, since the precise circumstances under which -this may happen are undocumented and hard to check, the Python -interface can provide no protection against this kind of problems. -(One example is specifying an excessive queue size --- there is no -documented upper limit.) - -The module defines the following functions: - -\renewcommand{\indexsubitem}{(in module al)} - -\begin{funcdesc}{openport}{name\, direction\optional{\, config}} -The name and direction arguments are strings. The optional config -argument is a configuration object as returned by -\code{al.newconfig()}. The return value is an \dfn{port object}; -methods of port objects are described below. -\end{funcdesc} - -\begin{funcdesc}{newconfig}{} -The return value is a new \dfn{configuration object}; methods of -configuration objects are described below. -\end{funcdesc} - -\begin{funcdesc}{queryparams}{device} -The device argument is an integer. The return value is a list of -integers containing the data returned by ALqueryparams(). -\end{funcdesc} - -\begin{funcdesc}{getparams}{device\, list} -The device argument is an integer. The list argument is a list such -as returned by \code{queryparams}; it is modified in place (!). -\end{funcdesc} - -\begin{funcdesc}{setparams}{device\, list} -The device argument is an integer. The list argument is a list such -as returned by \code{al.queryparams}. -\end{funcdesc} - -\subsection{Configuration Objects} - -Configuration objects (returned by \code{al.newconfig()} have the -following methods: - -\renewcommand{\indexsubitem}{(audio configuration object method)} - -\begin{funcdesc}{getqueuesize}{} -Return the queue size. -\end{funcdesc} - -\begin{funcdesc}{setqueuesize}{size} -Set the queue size. -\end{funcdesc} - -\begin{funcdesc}{getwidth}{} -Get the sample width. -\end{funcdesc} - -\begin{funcdesc}{setwidth}{width} -Set the sample width. -\end{funcdesc} - -\begin{funcdesc}{getchannels}{} -Get the channel count. -\end{funcdesc} - -\begin{funcdesc}{setchannels}{nchannels} -Set the channel count. -\end{funcdesc} - -\begin{funcdesc}{getsampfmt}{} -Get the sample format. -\end{funcdesc} - -\begin{funcdesc}{setsampfmt}{sampfmt} -Set the sample format. -\end{funcdesc} - -\begin{funcdesc}{getfloatmax}{} -Get the maximum value for floating sample formats. -\end{funcdesc} - -\begin{funcdesc}{setfloatmax}{floatmax} -Set the maximum value for floating sample formats. -\end{funcdesc} - -\subsection{Port Objects} - -Port objects (returned by \code{al.openport()} have the following -methods: - -\renewcommand{\indexsubitem}{(audio port object method)} - -\begin{funcdesc}{closeport}{} -Close the port. -\end{funcdesc} - -\begin{funcdesc}{getfd}{} -Return the file descriptor as an int. -\end{funcdesc} - -\begin{funcdesc}{getfilled}{} -Return the number of filled samples. -\end{funcdesc} - -\begin{funcdesc}{getfillable}{} -Return the number of fillable samples. -\end{funcdesc} - -\begin{funcdesc}{readsamps}{nsamples} -Read a number of samples from the queue, blocking if necessary. -Return the data as a string containing the raw data, (e.g., 2 bytes per -sample in big-endian byte order (high byte, low byte) if you have set -the sample width to 2 bytes). -\end{funcdesc} - -\begin{funcdesc}{writesamps}{samples} -Write samples into the queue, blocking if necessary. The samples are -encoded as described for the \code{readsamps} return value. -\end{funcdesc} - -\begin{funcdesc}{getfillpoint}{} -Return the `fill point'. -\end{funcdesc} - -\begin{funcdesc}{setfillpoint}{fillpoint} -Set the `fill point'. -\end{funcdesc} - -\begin{funcdesc}{getconfig}{} -Return a configuration object containing the current configuration of -the port. -\end{funcdesc} - -\begin{funcdesc}{setconfig}{config} -Set the configuration from the argument, a configuration object. -\end{funcdesc} - -\begin{funcdesc}{getstatus}{list} -Get status information on last error. -\end{funcdesc} - -\section{Standard Module \sectcode{AL}} -\nodename{AL (uppercase)} -\stmodindex{AL} - -This module defines symbolic constants needed to use the built-in -module \code{al} (see above); they are equivalent to those defined in -the C header file \file{<audio.h>} except that the name prefix -\samp{AL_} is omitted. Read the module source for a complete list of -the defined names. Suggested use: - -\bcode\begin{verbatim} -import al -from AL import * -\end{verbatim}\ecode diff --git a/Doc/liballos.tex b/Doc/liballos.tex deleted file mode 100644 index b5a207e2b8..0000000000 --- a/Doc/liballos.tex +++ /dev/null @@ -1,23 +0,0 @@ -\chapter{Generic Operating System Services} - -The modules described in this chapter provide interfaces to operating -system features that are available on (almost) all operating systems, -such as files and a clock. The interfaces are generally modelled -after the \UNIX{} or C interfaces but they are available on most other -systems as well. Here's an overview: - -\begin{description} - -\item[os] ---- Miscellaneous OS interfaces. - -\item[time] ---- Time access and conversions. - -\item[getopt] ---- Parser for command line options. - -\item[tempfile] ---- Generate temporary file names. - -\end{description} diff --git a/Doc/libamoeba.tex b/Doc/libamoeba.tex deleted file mode 100644 index 54a9dfbd53..0000000000 --- a/Doc/libamoeba.tex +++ /dev/null @@ -1,128 +0,0 @@ -\chapter{Amoeba Specific Services} - -\section{Built-in Module \sectcode{amoeba}} - -\bimodindex{amoeba} -This module provides some object types and operations useful for -Amoeba applications. It is only available on systems that support -Amoeba operations. RPC errors and other Amoeba errors are reported as -the exception \code{amoeba.error = 'amoeba.error'}. - -The module \code{amoeba} defines the following items: - -\renewcommand{\indexsubitem}{(in module amoeba)} -\begin{funcdesc}{name_append}{path\, cap} -Stores a capability in the Amoeba directory tree. -Arguments are the pathname (a string) and the capability (a capability -object as returned by -\code{name_lookup()}). -\end{funcdesc} - -\begin{funcdesc}{name_delete}{path} -Deletes a capability from the Amoeba directory tree. -Argument is the pathname. -\end{funcdesc} - -\begin{funcdesc}{name_lookup}{path} -Looks up a capability. -Argument is the pathname. -Returns a -\dfn{capability} -object, to which various interesting operations apply, described below. -\end{funcdesc} - -\begin{funcdesc}{name_replace}{path\, cap} -Replaces a capability in the Amoeba directory tree. -Arguments are the pathname and the new capability. -(This differs from -\code{name_append()} -in the behavior when the pathname already exists: -\code{name_append()} -finds this an error while -\code{name_replace()} -allows it, as its name suggests.) -\end{funcdesc} - -\begin{datadesc}{capv} -A table representing the capability environment at the time the -interpreter was started. -(Alas, modifying this table does not affect the capability environment -of the interpreter.) -For example, -\code{amoeba.capv['ROOT']} -is the capability of your root directory, similar to -\code{getcap("ROOT")} -in C. -\end{datadesc} - -\begin{excdesc}{error} -The exception raised when an Amoeba function returns an error. -The value accompanying this exception is a pair containing the numeric -error code and the corresponding string, as returned by the C function -\code{err_why()}. -\end{excdesc} - -\begin{funcdesc}{timeout}{msecs} -Sets the transaction timeout, in milliseconds. -Returns the previous timeout. -Initially, the timeout is set to 2 seconds by the Python interpreter. -\end{funcdesc} - -\subsection{Capability Operations} - -Capabilities are written in a convenient \ASCII{} format, also used by the -Amoeba utilities -{\it c2a}(U) -and -{\it a2c}(U). -For example: - -\bcode\begin{verbatim} ->>> amoeba.name_lookup('/profile/cap') -aa:1c:95:52:6a:fa/14(ff)/8e:ba:5b:8:11:1a ->>> -\end{verbatim}\ecode - -The following methods are defined for capability objects. - -\renewcommand{\indexsubitem}{(capability method)} -\begin{funcdesc}{dir_list}{} -Returns a list of the names of the entries in an Amoeba directory. -\end{funcdesc} - -\begin{funcdesc}{b_read}{offset\, maxsize} -Reads (at most) -\var{maxsize} -bytes from a bullet file at offset -\var{offset.} -The data is returned as a string. -EOF is reported as an empty string. -\end{funcdesc} - -\begin{funcdesc}{b_size}{} -Returns the size of a bullet file. -\end{funcdesc} - -\begin{funcdesc}{dir_append}{} -\funcline{dir_delete}{}\ -\funcline{dir_lookup}{}\ -\funcline{dir_replace}{} -Like the corresponding -\samp{name_}* -functions, but with a path relative to the capability. -(For paths beginning with a slash the capability is ignored, since this -is the defined semantics for Amoeba.) -\end{funcdesc} - -\begin{funcdesc}{std_info}{} -Returns the standard info string of the object. -\end{funcdesc} - -\begin{funcdesc}{tod_gettime}{} -Returns the time (in seconds since the Epoch, in UCT, as for POSIX) from -a time server. -\end{funcdesc} - -\begin{funcdesc}{tod_settime}{t} -Sets the time kept by a time server. -\end{funcdesc} diff --git a/Doc/libarray.tex b/Doc/libarray.tex deleted file mode 100644 index 8122f4965b..0000000000 --- a/Doc/libarray.tex +++ /dev/null @@ -1,114 +0,0 @@ -\section{Built-in Module \sectcode{array}} -\bimodindex{array} -\index{arrays} - -This module defines a new object type which can efficiently represent -an array of basic values: characters, integers, floating point -numbers. Arrays are sequence types and behave very much like lists, -except that the type of objects stored in them is constrained. The -type is specified at object creation time by using a \dfn{type code}, -which is a single character. The following type codes are defined: - -\begin{tableiii}{|c|c|c|}{code}{Typecode}{Type}{Minimal size in bytes} -\lineiii{'c'}{character}{1} -\lineiii{'b'}{signed integer}{1} -\lineiii{'h'}{signed integer}{2} -\lineiii{'i'}{signed integer}{2} -\lineiii{'l'}{signed integer}{4} -\lineiii{'f'}{floating point}{4} -\lineiii{'d'}{floating point}{8} -\end{tableiii} - -The actual representation of values is determined by the machine -architecture (strictly speaking, by the C implementation). The actual -size can be accessed through the \var{itemsize} attribute. - -See also built-in module \code{struct}. -\bimodindex{struct} - -The module defines the following function: - -\renewcommand{\indexsubitem}{(in module array)} - -\begin{funcdesc}{array}{typecode\optional{\, initializer}} -Return a new array whose items are restricted by \var{typecode}, and -initialized from the optional \var{initializer} value, which must be a -list or a string. The list or string is passed to the new array's -\code{fromlist()} or \code{fromstring()} method (see below) to add -initial items to the array. -\end{funcdesc} - -Array objects support the following data items and methods: - -\begin{datadesc}{typecode} -The typecode character used to create the array. -\end{datadesc} - -\begin{datadesc}{itemsize} -The length in bytes of one array item in the internal representation. -\end{datadesc} - -\begin{funcdesc}{append}{x} -Append a new item with value \var{x} to the end of the array. -\end{funcdesc} - -\begin{funcdesc}{byteswap}{x} -``Byteswap'' all items of the array. This is only supported for -integer values. It is useful when reading data from a file written -on a machine with a different byte order. -\end{funcdesc} - -\begin{funcdesc}{fromfile}{f\, n} -Read \var{n} items (as machine values) from the file object \var{f} -and append them to the end of the array. If less than \var{n} items -are available, \code{EOFError} is raised, but the items that were -available are still inserted into the array. \var{f} must be a real -built-in file object; something else with a \code{read()} method won't -do. -\end{funcdesc} - -\begin{funcdesc}{fromlist}{list} -Append items from the list. This is equivalent to -\code{for x in \var{list}:\ a.append(x)} -except that if there is a type error, the array is unchanged. -\end{funcdesc} - -\begin{funcdesc}{fromstring}{s} -Appends items from the string, interpreting the string as an -array of machine values (i.e. as if it had been read from a -file using the \code{fromfile()} method). -\end{funcdesc} - -\begin{funcdesc}{insert}{i\, x} -Insert a new item with value \var{x} in the array before position -\var{i}. -\end{funcdesc} - -\begin{funcdesc}{tofile}{f} -Write all items (as machine values) to the file object \var{f}. -\end{funcdesc} - -\begin{funcdesc}{tolist}{} -Convert the array to an ordinary list with the same items. -\end{funcdesc} - -\begin{funcdesc}{tostring}{} -Convert the array to an array of machine values and return the -string representation (the same sequence of bytes that would -be written to a file by the \code{tofile()} method.) -\end{funcdesc} - -When an array object is printed or converted to a string, it is -represented as \code{array(\var{typecode}, \var{initializer})}. The -\var{initializer} is omitted if the array is empty, otherwise it is a -string if the \var{typecode} is \code{'c'}, otherwise it is a list of -numbers. The string is guaranteed to be able to be converted back to -an array with the same type and value using reverse quotes -(\code{``}). Examples: - -\bcode\begin{verbatim} -array('l') -array('c', 'hello world') -array('l', [1, 2, 3, 4, 5]) -array('d', [1.0, 2.0, 3.14]) -\end{verbatim}\ecode diff --git a/Doc/libaudio.tex b/Doc/libaudio.tex deleted file mode 100644 index 47c0b643c7..0000000000 --- a/Doc/libaudio.tex +++ /dev/null @@ -1,120 +0,0 @@ -\section{Built-in Module \sectcode{audio}} -\bimodindex{audio} - -\strong{Note:} This module is obsolete, since the hardware to which it -interfaces is obsolete. For audio on the Indigo or 4D/35, see -built-in module \code{al} above. - -This module provides rudimentary access to the audio I/O device -\file{/dev/audio} on the Silicon Graphics Personal IRIS 4D/25; -see {\it audio}(7). It supports the following operations: - -\renewcommand{\indexsubitem}{(in module audio)} -\begin{funcdesc}{setoutgain}{n} -Sets the output gain. -\iftexi -\code{0 <= \var{n} < 256}. -\else -$0 \leq \var{n} < 256$. -%%JHXXX Sets the output gain (0-255). -\fi -\end{funcdesc} - -\begin{funcdesc}{getoutgain}{} -Returns the output gain. -\end{funcdesc} - -\begin{funcdesc}{setrate}{n} -Sets the sampling rate: \code{1} = 32K/sec, \code{2} = 16K/sec, -\code{3} = 8K/sec. -\end{funcdesc} - -\begin{funcdesc}{setduration}{n} -Sets the `sound duration' in units of 1/100 seconds. -\end{funcdesc} - -\begin{funcdesc}{read}{n} -Reads a chunk of -\var{n} -sampled bytes from the audio input (line in or microphone). -The chunk is returned as a string of length n. -Each byte encodes one sample as a signed 8-bit quantity using linear -encoding. -This string can be converted to numbers using \code{chr2num()} described -below. -\end{funcdesc} - -\begin{funcdesc}{write}{buf} -Writes a chunk of samples to the audio output (speaker). -\end{funcdesc} - -These operations support asynchronous audio I/O: - -\renewcommand{\indexsubitem}{(in module audio)} -\begin{funcdesc}{start_recording}{n} -Starts a second thread (a process with shared memory) that begins reading -\var{n} -bytes from the audio device. -The main thread immediately continues. -\end{funcdesc} - -\begin{funcdesc}{wait_recording}{} -Waits for the second thread to finish and returns the data read. -\end{funcdesc} - -\begin{funcdesc}{stop_recording}{} -Makes the second thread stop reading as soon as possible. -Returns the data read so far. -\end{funcdesc} - -\begin{funcdesc}{poll_recording}{} -Returns true if the second thread has finished reading (so -\code{wait_recording()} would return the data without delay). -\end{funcdesc} - -\begin{funcdesc}{start_playing}{} -\funcline{wait_playing}{} -\funcline{stop_playing}{} -\funcline{poll_playing}{} -\begin{sloppypar} -Similar but for output. -\code{stop_playing()} -returns a lower bound for the number of bytes actually played (not very -accurate). -\end{sloppypar} -\end{funcdesc} - -The following operations do not affect the audio device but are -implemented in C for efficiency: - -\renewcommand{\indexsubitem}{(in module audio)} -\begin{funcdesc}{amplify}{buf\, f1\, f2} -Amplifies a chunk of samples by a variable factor changing from -\code{\var{f1}/256} to \code{\var{f2}/256.} -Negative factors are allowed. -Resulting values that are to large to fit in a byte are clipped. -\end{funcdesc} - -\begin{funcdesc}{reverse}{buf} -Returns a chunk of samples backwards. -\end{funcdesc} - -\begin{funcdesc}{add}{buf1\, buf2} -Bytewise adds two chunks of samples. -Bytes that exceed the range are clipped. -If one buffer is shorter, it is assumed to be padded with zeros. -\end{funcdesc} - -\begin{funcdesc}{chr2num}{buf} -Converts a string of sampled bytes as returned by \code{read()} into -a list containing the numeric values of the samples. -\end{funcdesc} - -\begin{funcdesc}{num2chr}{list} -\begin{sloppypar} -Converts a list as returned by -\code{chr2num()} -back to a buffer acceptable by -\code{write()}. -\end{sloppypar} -\end{funcdesc} diff --git a/Doc/libaudioop.tex b/Doc/libaudioop.tex deleted file mode 100644 index 6a74a0beb7..0000000000 --- a/Doc/libaudioop.tex +++ /dev/null @@ -1,235 +0,0 @@ -\section{Built-in Module \sectcode{audioop}} -\bimodindex{audioop} - -The \code{audioop} module contains some useful operations on sound fragments. -It operates on sound fragments consisting of signed integer samples -8, 16 or 32 bits wide, stored in Python strings. This is the same -format as used by the \code{al} and \code{sunaudiodev} modules. All -scalar items are integers, unless specified otherwise. - -A few of the more complicated operations only take 16-bit samples, -otherwise the sample size (in bytes) is always a parameter of the operation. - -The module defines the following variables and functions: - -\renewcommand{\indexsubitem}{(in module audioop)} -\begin{excdesc}{error} -This exception is raised on all errors, such as unknown number of bytes -per sample, etc. -\end{excdesc} - -\begin{funcdesc}{add}{fragment1\, fragment2\, width} -Return a fragment which is the addition of the two samples passed as -parameters. \var{width} is the sample width in bytes, either -\code{1}, \code{2} or \code{4}. Both fragments should have the same -length. -\end{funcdesc} - -\begin{funcdesc}{adpcm2lin}{adpcmfragment\, width\, state} -Decode an Intel/DVI ADPCM coded fragment to a linear fragment. See -the description of \code{lin2adpcm} for details on ADPCM coding. -Return a tuple \code{(\var{sample}, \var{newstate})} where the sample -has the width specified in \var{width}. -\end{funcdesc} - -\begin{funcdesc}{adpcm32lin}{adpcmfragment\, width\, state} -Decode an alternative 3-bit ADPCM code. See \code{lin2adpcm3} for -details. -\end{funcdesc} - -\begin{funcdesc}{avg}{fragment\, width} -Return the average over all samples in the fragment. -\end{funcdesc} - -\begin{funcdesc}{avgpp}{fragment\, width} -Return the average peak-peak value over all samples in the fragment. -No filtering is done, so the usefulness of this routine is -questionable. -\end{funcdesc} - -\begin{funcdesc}{bias}{fragment\, width\, bias} -Return a fragment that is the original fragment with a bias added to -each sample. -\end{funcdesc} - -\begin{funcdesc}{cross}{fragment\, width} -Return the number of zero crossings in the fragment passed as an -argument. -\end{funcdesc} - -\begin{funcdesc}{findfactor}{fragment\, reference} -Return a factor \var{F} such that -\code{rms(add(fragment, mul(reference, -F)))} is minimal, i.e., -return the factor with which you should multiply \var{reference} to -make it match as well as possible to \var{fragment}. The fragments -should both contain 2-byte samples. - -The time taken by this routine is proportional to \code{len(fragment)}. -\end{funcdesc} - -\begin{funcdesc}{findfit}{fragment\, reference} -This routine (which only accepts 2-byte sample fragments) - -Try to match \var{reference} as well as possible to a portion of -\var{fragment} (which should be the longer fragment). This is -(conceptually) done by taking slices out of \var{fragment}, using -\code{findfactor} to compute the best match, and minimizing the -result. The fragments should both contain 2-byte samples. Return a -tuple \code{(\var{offset}, \var{factor})} where \var{offset} is the -(integer) offset into \var{fragment} where the optimal match started -and \var{factor} is the (floating-point) factor as per -\code{findfactor}. -\end{funcdesc} - -\begin{funcdesc}{findmax}{fragment\, length} -Search \var{fragment} for a slice of length \var{length} samples (not -bytes!)\ with maximum energy, i.e., return \var{i} for which -\code{rms(fragment[i*2:(i+length)*2])} is maximal. The fragments -should both contain 2-byte samples. - -The routine takes time proportional to \code{len(fragment)}. -\end{funcdesc} - -\begin{funcdesc}{getsample}{fragment\, width\, index} -Return the value of sample \var{index} from the fragment. -\end{funcdesc} - -\begin{funcdesc}{lin2lin}{fragment\, width\, newwidth} -Convert samples between 1-, 2- and 4-byte formats. -\end{funcdesc} - -\begin{funcdesc}{lin2adpcm}{fragment\, width\, state} -Convert samples to 4 bit Intel/DVI ADPCM encoding. ADPCM coding is an -adaptive coding scheme, whereby each 4 bit number is the difference -between one sample and the next, divided by a (varying) step. The -Intel/DVI ADPCM algorithm has been selected for use by the IMA, so it -may well become a standard. - -\code{State} is a tuple containing the state of the coder. The coder -returns a tuple \code{(\var{adpcmfrag}, \var{newstate})}, and the -\var{newstate} should be passed to the next call of lin2adpcm. In the -initial call \code{None} can be passed as the state. \var{adpcmfrag} -is the ADPCM coded fragment packed 2 4-bit values per byte. -\end{funcdesc} - -\begin{funcdesc}{lin2adpcm3}{fragment\, width\, state} -This is an alternative ADPCM coder that uses only 3 bits per sample. -It is not compatible with the Intel/DVI ADPCM coder and its output is -not packed (due to laziness on the side of the author). Its use is -discouraged. -\end{funcdesc} - -\begin{funcdesc}{lin2ulaw}{fragment\, width} -Convert samples in the audio fragment to U-LAW encoding and return -this as a Python string. U-LAW is an audio encoding format whereby -you get a dynamic range of about 14 bits using only 8 bit samples. It -is used by the Sun audio hardware, among others. -\end{funcdesc} - -\begin{funcdesc}{minmax}{fragment\, width} -Return a tuple consisting of the minimum and maximum values of all -samples in the sound fragment. -\end{funcdesc} - -\begin{funcdesc}{max}{fragment\, width} -Return the maximum of the {\em absolute value} of all samples in a -fragment. -\end{funcdesc} - -\begin{funcdesc}{maxpp}{fragment\, width} -Return the maximum peak-peak value in the sound fragment. -\end{funcdesc} - -\begin{funcdesc}{mul}{fragment\, width\, factor} -Return a fragment that has all samples in the original framgent -multiplied by the floating-point value \var{factor}. Overflow is -silently ignored. -\end{funcdesc} - -\begin{funcdesc}{reverse}{fragment\, width} -Reverse the samples in a fragment and returns the modified fragment. -\end{funcdesc} - -\begin{funcdesc}{rms}{fragment\, width} -Return the root-mean-square of the fragment, i.e. -\iftexi -the square root of the quotient of the sum of all squared sample value, -divided by the sumber of samples. -\else -% in eqn: sqrt { sum S sub i sup 2 over n } -\begin{displaymath} -\catcode`_=8 -\sqrt{\frac{\sum{{S_{i}}^{2}}}{n}} -\end{displaymath} -\fi -This is a measure of the power in an audio signal. -\end{funcdesc} - -\begin{funcdesc}{tomono}{fragment\, width\, lfactor\, rfactor} -Convert a stereo fragment to a mono fragment. The left channel is -multiplied by \var{lfactor} and the right channel by \var{rfactor} -before adding the two channels to give a mono signal. -\end{funcdesc} - -\begin{funcdesc}{tostereo}{fragment\, width\, lfactor\, rfactor} -Generate a stereo fragment from a mono fragment. Each pair of samples -in the stereo fragment are computed from the mono sample, whereby left -channel samples are multiplied by \var{lfactor} and right channel -samples by \var{rfactor}. -\end{funcdesc} - -\begin{funcdesc}{ulaw2lin}{fragment\, width} -Convert sound fragments in ULAW encoding to linearly encoded sound -fragments. ULAW encoding always uses 8 bits samples, so \var{width} -refers only to the sample width of the output fragment here. -\end{funcdesc} - -Note that operations such as \code{mul} or \code{max} make no -distinction between mono and stereo fragments, i.e.\ all samples are -treated equal. If this is a problem the stereo fragment should be split -into two mono fragments first and recombined later. Here is an example -of how to do that: -\bcode\begin{verbatim} -def mul_stereo(sample, width, lfactor, rfactor): - lsample = audioop.tomono(sample, width, 1, 0) - rsample = audioop.tomono(sample, width, 0, 1) - lsample = audioop.mul(sample, width, lfactor) - rsample = audioop.mul(sample, width, rfactor) - lsample = audioop.tostereo(lsample, width, 1, 0) - rsample = audioop.tostereo(rsample, width, 0, 1) - return audioop.add(lsample, rsample, width) -\end{verbatim}\ecode - -If you use the ADPCM coder to build network packets and you want your -protocol to be stateless (i.e.\ to be able to tolerate packet loss) -you should not only transmit the data but also the state. Note that -you should send the \var{initial} state (the one you passed to -\code{lin2adpcm}) along to the decoder, not the final state (as returned by -the coder). If you want to use \code{struct} to store the state in -binary you can code the first element (the predicted value) in 16 bits -and the second (the delta index) in 8. - -The ADPCM coders have never been tried against other ADPCM coders, -only against themselves. It could well be that I misinterpreted the -standards in which case they will not be interoperable with the -respective standards. - -The \code{find...} routines might look a bit funny at first sight. -They are primarily meant to do echo cancellation. A reasonably -fast way to do this is to pick the most energetic piece of the output -sample, locate that in the input sample and subtract the whole output -sample from the input sample: -\bcode\begin{verbatim} -def echocancel(outputdata, inputdata): - pos = audioop.findmax(outputdata, 800) # one tenth second - out_test = outputdata[pos*2:] - in_test = inputdata[pos*2:] - ipos, factor = audioop.findfit(in_test, out_test) - # Optional (for better cancellation): - # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)], - # out_test) - prefill = '\0'*(pos+ipos)*2 - postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata)) - outputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill - return audioop.add(inputdata, outputdata, 2) -\end{verbatim}\ecode diff --git a/Doc/libbinascii.tex b/Doc/libbinascii.tex deleted file mode 100644 index 6938eeb54c..0000000000 --- a/Doc/libbinascii.tex +++ /dev/null @@ -1,150 +0,0 @@ -\section{Standard module \sectcode{binhex}} -\stmodindex{binhex} - -This module encodes and decodes files in binhex4 format, a format -allowing representation of Macintosh files in ASCII. On the macintosh, -both forks of a file and the finder information are encoded (or -decoded), on other platforms only the data fork is handled. - -The \code{binhex} module defines the following functions: - -\renewcommand{\indexsubitem}{(in module binhex)} - -\begin{funcdesc}{binhex}{input\, output} -Convert a binary file with filename \var{input} to binhex file -\var{output}. The \var{output} parameter can either be a filename or a -file-like object (any object supporting a \var{write} and \var{close} -method). -\end{funcdesc} - -\begin{funcdesc}{hexbin}{input\optional{\, output}} -Decode a binhex file \var{input}. \var{Input} may be a filename or a -file-like object supporting \var{read} and \var{close} methods. -The resulting file is written to a file named \var{output}, unless the -argument is empty in which case the output filename is read from the -binhex file. -\end{funcdesc} - -\subsection{notes} -There is an alternative, more powerful interface to the coder and -decoder, see the source for details. - -If you code or decode textfiles on non-Macintosh platforms they will -still use the macintosh newline convention (carriage-return as end of -line). - -As of this writing, \var{hexbin} appears to not work in all cases. - -\section{Standard module \sectcode{uu}} -\stmodindex{uu} - -This module encodes and decodes files in uuencode format, allowing -arbitrary binary data to be transferred over ascii-only connections. -Whereever a file argument is expected, the methods accept either a -pathname (\code{'-'} for stdin/stdout) or a file-like object. - -Normally you would pass filenames, but there is one case where you -have to open the file yourself: if you are on a non-unix platform and -your binary file is actually a textfile that you want encoded -unix-compatible you will have to open the file yourself as a textfile, -so newline conversion is performed. - -This code was contributed by Lance Ellinghouse, and modified by Jack -Jansen. - -The \code{uu} module defines the following functions: - -\renewcommand{\indexsubitem}{(in module uu)} - -\begin{funcdesc}{encode}{in_file\, out_file\optional{\, name\, mode}} -Uuencode file \var{in_file} into file \var{out_file}. The uuencoded -file will have the header specifying \var{name} and \var{mode} as the -defaults for the results of decoding the file. The default defaults -are taken from \var{in_file}, or \code{'-'} and \code{0666} -respectively. -\end{funcdesc} - -\begin{funcdesc}{decode}{in_file\optional{\, out_file\, mode}} -This call decodes uuencoded file \var{in_file} placing the result on -file \var{out_file}. If \var{out_file} is a pathname the \var{mode} is -also set. Defaults for \var{out_file} and \var{mode} are taken from -the uuencode header. -\end{funcdesc} - -\section{Built-in Module \sectcode{binascii}} % If implemented in C -\bimodindex{binascii} - -The binascii module contains a number of methods to convert between -binary and various ascii-encoded binary representations. Normally, you -will not use these modules directly but use wrapper modules like -\var{uu} or \var{hexbin} in stead, this module solely exists because -bit-manipuation of large amounts of data is slow in python. - -The \code{binascii} module defines the following functions: - -\renewcommand{\indexsubitem}{(in module binascii)} - -\begin{funcdesc}{a2b_uu}{string} -Convert a single line of uuencoded data back to binary and return the -binary data. Lines normally contain 45 (binary) bytes, except for the -last line. Line data may be followed by whitespace. -\end{funcdesc} - -\begin{funcdesc}{b2a_uu}{data} -Convert binary data to a line of ascii characters, the return value is -the converted line, including a newline char. The length of \var{data} -should be at most 45. -\end{funcdesc} - -\begin{funcdesc}{a2b_base64}{string} -Convert a block of base64 data back to binary and return the -binary data. More than one line may be passed at a time. -\end{funcdesc} - -\begin{funcdesc}{b2a_base64}{data} -Convert binary data to a line of ascii characters in base64 coding. -The return value is the converted line, including a newline char. -The length of \var{data} should be at most 57 to adhere to the base64 -standard. -\end{funcdesc} - -\begin{funcdesc}{a2b_hqx}{string} -Convert binhex4 formatted ascii data to binary, without doing -rle-decompression. The string should contain a complete number of -binary bytes, or (in case of the last portion of the binhex4 data) -have the remaining bits zero. -\end{funcdesc} - -\begin{funcdesc}{rledecode_hqx}{data} -Perform RLE-decompression on the data, as per the binhex4 -standard. The algorithm uses \code{0x90} after a byte as a repeat -indicator, followed by a count. A count of \code{0} specifies a byte -value of \code{0x90}. The routine returns the decompressed data, -unless data input data ends in an orphaned repeat indicator, in which -case the \var{Incomplete} exception is raised. -\end{funcdesc} - -\begin{funcdesc}{rlecode_hqx}{data} -Perform binhex4 style RLE-compression on \var{data} and return the -result. -\end{funcdesc} - -\begin{funcdesc}{b2a_hqx}{data} -Perform hexbin4 binary-to-ascii translation and return the resulting -string. The argument should already be rle-coded, and have a length -divisible by 3 (except possibly the last fragment). -\end{funcdesc} - -\begin{funcdesc}{crc_hqx}{data, crc} -Compute the binhex4 crc value of \var{data}, starting with an initial -\var{crc} and returning the result. -\end{funcdesc} - -\begin{excdesc}{Error} -Exception raised on errors. These are usually programming errors. -\end{excdesc} - -\begin{excdesc}{Incomplete} -Exception raised on incomplete data. These are usually not programming -errors, but handled by reading a little more data and trying again. -\end{excdesc} diff --git a/Doc/libbltin.tex b/Doc/libbltin.tex deleted file mode 100644 index 63b7c6394a..0000000000 --- a/Doc/libbltin.tex +++ /dev/null @@ -1,7 +0,0 @@ -\section{Built-in Module \sectcode{__builtin__}} -\bimodindex{__builtin__} - -This module provides direct access to all `built-in' identifiers of -Python; e.g. \code{__builtin__.open} is the full name for the built-in -function \code{open}. See the section on Built-in Functions in the -previous chapter. diff --git a/Doc/libcd.tex b/Doc/libcd.tex deleted file mode 100644 index 98ed560261..0000000000 --- a/Doc/libcd.tex +++ /dev/null @@ -1,300 +0,0 @@ -\section{Built-in Module \sectcode{cd}} -\bimodindex{cd} - -This module provides an interface to the Silicon Graphics CD library. -It is available only on Silicon Graphics systems. - -The way the library works is as follows. A program opens the CD-ROM -device with \code{cd.open()} and creates a parser to parse the data -from the CD with \code{cd.createparser()}. The object returned by -\code{cd.open()} can be used to read data from the CD, but also to get -status information for the CD-ROM device, and to get information about -the CD, such as the table of contents. Data from the CD is passed to -the parser, which parses the frames, and calls any callback -functions that have previously been added. - -An audio CD is divided into \dfn{tracks} or \dfn{programs} (the terms -are used interchangeably). Tracks can be subdivided into -\dfn{indices}. An audio CD contains a \dfn{table of contents} which -gives the starts of the tracks on the CD. Index 0 is usually the -pause before the start of a track. The start of the track as given by -the table of contents is normally the start of index 1. - -Positions on a CD can be represented in two ways. Either a frame -number or a tuple of three values, minutes, seconds and frames. Most -functions use the latter representation. Positions can be both -relative to the beginning of the CD, and to the beginning of the -track. - -Module \code{cd} defines the following functions and constants: - -\renewcommand{\indexsubitem}{(in module cd)} - -\begin{funcdesc}{createparser}{} -Create and return an opaque parser object. The methods of the parser -object are described below. -\end{funcdesc} - -\begin{funcdesc}{msftoframe}{min\, sec\, frame} -Converts a \code{(minutes, seconds, frames)} triple representing time -in absolute time code into the corresponding CD frame number. -\end{funcdesc} - -\begin{funcdesc}{open}{\optional{device\optional{\, mode}}} -Open the CD-ROM device. The return value is an opaque player object; -methods of the player object are described below. The device is the -name of the SCSI device file, e.g. /dev/scsi/sc0d4l0, or \code{None}. -If omited or \code{None}, the hardware inventory is consulted to -locate a CD-ROM drive. The \code{mode}, if not omited, should be the -string 'r'. -\end{funcdesc} - -The module defines the following variables: - -\begin{datadesc}{error} -Exception raised on various errors. -\end{datadesc} - -\begin{datadesc}{DATASIZE} -The size of one frame's worth of audio data. This is the size of the -audio data as passed to the callback of type \code{audio}. -\end{datadesc} - -\begin{datadesc}{BLOCKSIZE} -The size of one uninterpreted frame of audio data. -\end{datadesc} - -The following variables are states as returned by \code{getstatus}: - -\begin{datadesc}{READY} -The drive is ready for operation loaded with an audio CD. -\end{datadesc} - -\begin{datadesc}{NODISC} -The drive does not have a CD loaded. -\end{datadesc} - -\begin{datadesc}{CDROM} -The drive is loaded with a CD-ROM. Subsequent play or read operations -will return I/O errors. -\end{datadesc} - -\begin{datadesc}{ERROR} -An error aoocurred while trying to read the disc or its table of -contents. -\end{datadesc} - -\begin{datadesc}{PLAYING} -The drive is in CD player mode playing an audio CD through its audio -jacks. -\end{datadesc} - -\begin{datadesc}{PAUSED} -The drive is in CD layer mode with play paused. -\end{datadesc} - -\begin{datadesc}{STILL} -The equivalent of \code{PAUSED} on older (non 3301) model Toshiba -CD-ROM drives. Such drives have never been shipped by SGI. -\end{datadesc} - -\begin{datadesc}{audio} -\dataline{pnum} -\dataline{index} -\dataline{ptime} -\dataline{atime} -\dataline{catalog} -\dataline{ident} -\dataline{control} -Integer constants describing the various types of parser callbacks -that can be set by the \code{addcallback()} method of CD parser -objects (see below). -\end{datadesc} - -Player objects (returned by \code{cd.open()}) have the following -methods: - -\renewcommand{\indexsubitem}{(CD player object method)} - -\begin{funcdesc}{allowremoval}{} -Unlocks the eject button on the CD-ROM drive permitting the user to -eject the caddy if desired. -\end{funcdesc} - -\begin{funcdesc}{bestreadsize}{} -Returns the best value to use for the \code{num_frames} parameter of -the \code{readda} method. Best is defined as the value that permits a -continuous flow of data from the CD-ROM drive. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Frees the resources associated with the player object. After calling -\code{close}, the methods of the object should no longer be used. -\end{funcdesc} - -\begin{funcdesc}{eject}{} -Ejects the caddy from the CD-ROM drive. -\end{funcdesc} - -\begin{funcdesc}{getstatus}{} -Returns information pertaining to the current state of the CD-ROM -drive. The returned information is a tuple with the following values: -\code{state}, \code{track}, \code{rtime}, \code{atime}, \code{ttime}, -\code{first}, \code{last}, \code{scsi_audio}, \code{cur_block}. -\code{rtime} is the time relative to the start of the current track; -\code{atime} is the time relative to the beginning of the disc; -\code{ttime} is the total time on the disc. For more information on -the meaning of the values, see the manual for CDgetstatus. -The value of \code{state} is one of the following: \code{cd.ERROR}, -\code{cd.NODISC}, \code{cd.READY}, \code{cd.PLAYING}, -\code{cd.PAUSED}, \code{cd.STILL}, or \code{cd.CDROM}. -\end{funcdesc} - -\begin{funcdesc}{gettrackinfo}{track} -Returns information about the specified track. The returned -information is a tuple consisting of two elements, the start time of -the track and the duration of the track. -\end{funcdesc} - -\begin{funcdesc}{msftoblock}{min\, sec\, frame} -Converts a minutes, seconds, frames triple representing a time in -absolute time code into the corresponding logical block number for the -given CD-ROM drive. You should use \code{cd.msftoframe()} rather than -\code{msftoblock()} for comparing times. The logical block number -differs from the frame number by an offset required by certain CD-ROM -drives. -\end{funcdesc} - -\begin{funcdesc}{play}{start\, play} -Starts playback of an audio CD in the CD-ROM drive at the specified -track. The audio output appears on the CD-ROM drive's headphone and -audio jacks (if fitted). Play stops at the end of the disc. -\code{start} is the number of the track at which to start playing the -CD; if \code{play} is 0, the CD will be set to an initial paused -state. The method \code{togglepause()} can then be used to commence -play. -\end{funcdesc} - -\begin{funcdesc}{playabs}{min\, sec\, frame\, play} -Like \code{play()}, except that the start is given in minutes, -seconds, frames instead of a track number. -\end{funcdesc} - -\begin{funcdesc}{playtrack}{start\, play} -Like \code{play()}, except that playing stops at the end of the track. -\end{funcdesc} - -\begin{funcdesc}{playtrackabs}{track\, min\, sec\, frame\, play} -Like \code{play()}, except that playing begins at the spcified -absolute time and ends at the end of the specified track. -\end{funcdesc} - -\begin{funcdesc}{preventremoval}{} -Locks the eject button on the CD-ROM drive thus preventing the user -from arbitrarily ejecting the caddy. -\end{funcdesc} - -\begin{funcdesc}{readda}{num_frames} -Reads the specified number of frames from an audio CD mounted in the -CD-ROM drive. The return value is a string representing the audio -frames. This string can be passed unaltered to the \code{parseframe} -method of the parser object. -\end{funcdesc} - -\begin{funcdesc}{seek}{min\, sec\, frame} -Sets the pointer that indicates the starting point of the next read of -digital audio data from a CD-ROM. The pointer is set to an absolute -time code location specified in minutes, seconds, and frames. The -return value is the logical block number to which the pointer has been -set. -\end{funcdesc} - -\begin{funcdesc}{seekblock}{block} -Sets the pointer that indicates the starting point of the next read of -digital audio data from a CD-ROM. The pointer is set to the specified -logical block number. The return value is the logical block number to -which the pointer has been set. -\end{funcdesc} - -\begin{funcdesc}{seektrack}{track} -Sets the pointer that indicates the starting point of the next read of -digital audio data from a CD-ROM. The pointer is set to the specified -track. The return value is the logical block number to which the -pointer has been set. -\end{funcdesc} - -\begin{funcdesc}{stop}{} -Stops the current playing operation. -\end{funcdesc} - -\begin{funcdesc}{togglepause}{} -Pauses the CD if it is playing, and makes it play if it is paused. -\end{funcdesc} - -Parser objects (returned by \code{cd.createparser()}) have the -following methods: - -\renewcommand{\indexsubitem}{(CD parser object method)} - -\begin{funcdesc}{addcallback}{type\, func\, arg} -Adds a callback for the parser. The parser has callbacks for eight -different types of data in the digital audio data stream. Constants -for these types are defined at the \code{cd} module level (see above). -The callback is called as follows: \code{func(arg, type, data)}, where -\code{arg} is the user supplied argument, \code{type} is the -particular type of callback, and \code{data} is the data returned for -this \code{type} of callback. The type of the data depends on the -\code{type} of callback as follows: -\begin{description} -\item[\code{cd.audio}: ] -The argument is a string which can be passed unmodified to -\code{al.writesamps()}. -\item[\code{cd.pnum}: ] -The argument is an integer giving the program (track) number. -\item[\code{cd.index}: ] -The argument is an integer giving the index number. -\item[\code{cd.ptime}: ] -The argument is a tuple consisting of the program time in minutes, -seconds, and frames. -\item[\code{cd.atime}: ] -The argument is a tuple consisting of the absolute time in minutes, -seconds, and frames. -\item[\code{cd.catalog}: ] -The argument is a string of 13 characters, giving the catalog number -of the CD. -\item[\code{cd.ident}: ] -The argument is a string of 12 characters, giving the ISRC -identification number of the recording. The string consists of two -characters country code, three characters owner code, two characters -giving the year, and five characters giving a serial number. -\item[\code{cd.control}: ] -The argument is an integer giving the control bits from the CD subcode -data. -\end{description} -\end{funcdesc} - -\begin{funcdesc}{deleteparser}{} -Deletes the parser and frees the memory it was using. The object -should not be used after this call. This call is done automatically -when the last reference to the object is removed. -\end{funcdesc} - -\begin{funcdesc}{parseframe}{frame} -Parses one or more frames of digital audio data from a CD such as -returned by \code{readda}. It determines which subcodes are present -in the data. If these subcodes have changed since the last frame, -then \code{parseframe} executes a callback of the appropriate type -passing to it the subcode data found in the frame. -Unlike the C function, more than one frame of digital audio data can -be passed to this method. -\end{funcdesc} - -\begin{funcdesc}{removecallback}{type} -Removes the callback for the given \code{type}. -\end{funcdesc} - -\begin{funcdesc}{resetparser}{} -Resets the fields of the parser used for tracking subcodes to an -initial state. \code{resetparser} should be called after the disc has -been changed. -\end{funcdesc} diff --git a/Doc/libcgi.tex b/Doc/libcgi.tex deleted file mode 100644 index 1262dc0077..0000000000 --- a/Doc/libcgi.tex +++ /dev/null @@ -1,219 +0,0 @@ -\section{Standard Module \sectcode{cgi}} -\stmodindex{cgi} -\indexii{WWW}{server} -\indexii{CGI}{protocol} -\indexii{HTTP}{protocol} -\indexii{MIME}{headers} -\index{URL} - -\renewcommand{\indexsubitem}{(in module cgi)} - -This module makes it easy to write Python scripts that run in a WWW -server using the Common Gateway Interface. It was written by Michael -McLay and subsequently modified by Steve Majewski and Guido van -Rossum. - -When a WWW server finds that a URL contains a reference to a file in a -particular subdirectory (usually \code{/cgibin}), it runs the file as -a subprocess. Information about the request such as the full URL, the -originating host etc., is passed to the subprocess in the shell -environment; additional input from the client may be read from -standard input. Standard output from the subprocess is sent back -across the network to the client as the response from the request. -The CGI protocol describes what the environment variables passed to -the subprocess mean and how the output should be formatted. The -official reference documentation for the CGI protocol can be found on -the World-Wide Web at -\code{<URL:http://hoohoo.ncsa.uiuc.edu/cgi/overview.html>}. The -\code{cgi} module was based on version 1.1 of the protocol and should -also work with version 1.0. - -The \code{cgi} module defines several classes that make it easy to -access the information passed to the subprocess from a Python script; -in particular, it knows how to parse the input sent by an HTML -``form'' using either a POST or a GET request (these are alternatives -for submitting forms in the HTTP protocol). - -The formatting of the output is so trivial that no additional support -is needed. All you need to do is print a minimal set of MIME headers -describing the output format, followed by a blank line and your actual -output. E.g. if you want to generate HTML, your script could start as -follows: - -\begin{verbatim} -# Header -- one or more lines: -print "Content-type: text/html" -# Blank line separating header from body: -print -# Body, in HTML format: -print "<TITLE>The Amazing SPAM Homepage!</TITLE>" -# etc... -\end{verbatim} - -The server will add some header lines of its own, but it won't touch -the output following the header. - -The \code{cgi} module defines the following functions: - -\begin{funcdesc}{parse}{} -Read and parse the form submitted to the script and return a -dictionary containing the form's fields. This should be called at -most once per script invocation, as it may consume standard input (if -the form was submitted through a POST request). The keys in the -resulting dictionary are the field names used in the submission; the -values are {\em lists} of the field values (since field name may be -used multiple times in a single form). \samp{\%} escapes in the -values are translated to their single-character equivalent using -\code{urllib.unquote()}. As a side effect, this function sets -\code{environ['QUERY_STRING']} to the raw query string, if it isn't -already set. -\end{funcdesc} - -\begin{funcdesc}{print_environ_usage}{} -Print a piece of HTML listing the environment variables that may be -set by the CGI protocol. -This is mainly useful when learning about writing CGI scripts. -\end{funcdesc} - -\begin{funcdesc}{print_environ}{} -Print a piece of HTML text showing the entire contents of the shell -environment. This is mainly useful when debugging a CGI script. -\end{funcdesc} - -\begin{funcdesc}{print_form}{form} -Print a piece of HTML text showing the contents of the \var{form} (a -dictionary, an instance of the \code{FormContentDict} class defined -below, or a subclass thereof). -This is mainly useful when debugging a CGI script. -\end{funcdesc} - -\begin{funcdesc}{escape}{string} -Convert special characters in \var{string} to HTML escapes. In -particular, ``\code{\&}'' is replaced with ``\code{\&amp;}'', -``\code{<}'' is replaced with ``\code{\&lt;}'', and ``\code{>}'' is -replaced with ``\code{\&gt;}''. This is useful when printing (almost) -arbitrary text in an HTML context. Note that for inclusion in quoted -tag attributes (e.g. \code{<A HREF="...">}), some additional -characters would have to be converted --- in particular the string -quote. There is currently no function that does this. -\end{funcdesc} - -The module defines the following classes. Since the base class -initializes itself by calling \code{parse()}, at most one instance of -at most one of these classes should be created per script invocation: - -\begin{funcdesc}{FormContentDict}{} -This class behaves like a (read-only) dictionary and has the same keys -and values as the dictionary returned by \code{parse()} (i.e. each -field name maps to a list of values). Additionally, it initializes -its data member \code{query_string} to the raw query sent from the -server. -\end{funcdesc} - -\begin{funcdesc}{SvFormContentDict}{} -This class, derived from \code{FormContentDict}, is a little more -user-friendly when you are expecting that each field name is only used -once in the form. When you access for a particular field (using -\code{form[fieldname]}), it will return the string value of that item -if it is unique, or raise \code{IndexError} if the field was specified -more than once in the form. (If the field wasn't specified at all, -\code{KeyError} is raised.) To access fields that are specified -multiple times, use \code{form.getlist(fieldname)}. The -\code{values()} and \code{items()} methods return mixed lists --- -containing strings for singly-defined fields, and lists of strings for -multiply-defined fields. -\end{funcdesc} - -(It currently defines some more classes, but these are experimental -and/or obsolescent, and are thus not documented --- see the source for -more informations.) - -The module defines the following variable: - -\begin{datadesc}{environ} -The shell environment, exactly as received from the http server. See -the CGI documentation for a description of the various fields. -\end{datadesc} - -\subsection{Example} -\nodename{CGI Example} - -This example assumes that you have a WWW server up and running, -e.g.\ NCSA's \code{httpd}. - -Place the following file in a convenient spot in the WWW server's -directory tree. E.g., if you place it in the subdirectory \file{test} -of the root directory and call it \file{test.html}, its URL will be -\file{http://\var{yourservername}/test/test.html}. - -\begin{verbatim} -<TITLE>Test Form Input</TITLE> -<H1>Test Form Input</H1> -<FORM METHOD="POST" ACTION="/cgi-bin/test.py"> -<INPUT NAME=Name> (Name)<br> -<INPUT NAME=Address> (Address)<br> -<INPUT TYPE=SUBMIT> -</FORM> -\end{verbatim} - -Selecting this file's URL from a forms-capable browser such as Mosaic -or Netscape will bring up a simple form with two text input fields and -a ``submit'' button. - -But wait. Before pressing ``submit'', a script that responds to the -form must also be installed. The test file as shown assumes that the -script is called \file{test.py} and lives in the server's -\code{cgi-bin} directory. Here's the test script: - -\begin{verbatim} -#!/usr/local/bin/python - -import cgi - -print "Content-type: text/html" -print # End of headers! -print "<TITLE>Test Form Output</TITLE>" -print "<H1>Test Form Output</H1>" - -form = cgi.SvFormContentDict() # Load the form - -name = addr = None # Default: no name and address - -# Extract name and address from the form, if given - -if form.has_key('Name'): - name = form['Name'] -if form.has_key('Address'): - addr = form['Address'] - -# Print an unnumbered list of the name and address, if present - -print "<UL>" -if name is not None: - print "<LI>Name:", cgi.escape(name) -if addr is not None: - print "<LI>Address:", cgi.escape(addr) -print "</UL>" -\end{verbatim} - -The script should be made executable (\samp{chmod +x \var{script}}). -If the Python interpreter is not located at -\file{/usr/local/bin/python} but somewhere else, the first line of the -script should be modified accordingly. - -Now that everything is installed correctly, we can try out the form. -Bring up the test form in your WWW browser, fill in a name and address -in the form, and press the ``submit'' button. The script should now -run and its output is sent back to your browser. This should roughly -look as follows: - -\strong{Test Form Output} - -\begin{itemize} -\item Name: \var{the name you entered} -\item Address: \var{the address you entered} -\end{itemize} - -If you didn't enter a name or address, the corresponding line will be -missing (since the browser doesn't send empty form fields to the -server). diff --git a/Doc/libcopy.tex b/Doc/libcopy.tex deleted file mode 100644 index 4c0ce72bbd..0000000000 --- a/Doc/libcopy.tex +++ /dev/null @@ -1,81 +0,0 @@ -\section{Standard Module \sectcode{copy}} -\stmodindex{copy} -\renewcommand{\indexsubitem}{(copy function)} -\ttindex{copy} -\ttindex{deepcopy} - -This module provides generic (shallow and deep) copying operations. - -Interface summary: - -\begin{verbatim} -import copy - -x = copy.copy(y) # make a shallow copy of y -x = copy.deepcopy(y) # make a deep copy of y -\end{verbatim} - -For module specific errors, \code{copy.error} is raised. - -The difference between shallow and deep copying is only relevant for -compound objects (objects that contain other objects, like lists or -class instances): - -\begin{itemize} - -\item -A {\em shallow copy} constructs a new compound object and then (to the -extent possible) inserts {\em references} into it to the objects found -in the original. - -\item -A {\em deep copy} constructs a new compound object and then, -recursively, inserts {\em copies} into it of the objects found in the -original. - -\end{itemize} - -Two problems often exist with deep copy operations that don't exist -with shallow copy operations: - -\begin{itemize} - -\item -Recursive objects (compound objects that, directly or indirectly, -contain a reference to themselves) may cause a recursive loop. - -\item -Because deep copy copies {\em everything} it may copy too much, e.g.\ -administrative data structures that should be shared even between -copies. - -\end{itemize} - -Python's \code{deepcopy()} operation avoids these problems by: - -\begin{itemize} - -\item -keeping a table of objects already copied during the current -copying pass; and - -\item -letting user-defined classes override the copying operation or the -set of components copied. - -\end{itemize} - -This version does not copy types like module, class, function, method, -nor stack trace, stack frame, nor file, socket, window, nor array, nor -any similar types. - -Classes can use the same interfaces to control copying that they use -to control pickling: they can define methods called -\code{__getinitargs__()}, \code{__getstate__()} and -\code{__setstate__()}. See the description of module \code{pickle} -for information on these methods. -\stmodindex{pickle} -\renewcommand{\indexsubitem}{(copy protocol)} -\ttindex{__getinitargs__} -\ttindex{__getstate__} -\ttindex{__setstate__} diff --git a/Doc/libcrypt.tex b/Doc/libcrypt.tex deleted file mode 100644 index e44f7b2be9..0000000000 --- a/Doc/libcrypt.tex +++ /dev/null @@ -1,21 +0,0 @@ -\section{Built-in module {\tt crypt}} -\bimodindex{crypt} - -This module implements an interface to the crypt({\bf 3}) routine, -which is a one-way hash function based upon a modified DES algorithm; -see the Unix man page for further details. Possible uses include -allowing Python scripts to accept typed passwords from the user, or -attempting to crack Unix passwords with a dictionary. -\index{crypt(3)} - -\begin{funcdesc}{crypt}{word\, salt} -\var{word} will usually be a user's password. \var{salt} is a -2-character string which will be used to select one of 4096 variations -of DES. The characters in \var{salt} must be either \code{.}, -\code{/}, or an alphanumeric character. Returns the hashed password -as a string, which will be composed of characters from the same -alphabet as the salt. -\end{funcdesc} - -The module and documentation were written by Steve Majewski. -\index{Majewski, Steve} diff --git a/Doc/libcrypto.tex b/Doc/libcrypto.tex deleted file mode 100644 index cc38e5b181..0000000000 --- a/Doc/libcrypto.tex +++ /dev/null @@ -1,30 +0,0 @@ -\chapter{Cryptographic Services} -\index{cryptography} - -The modules described in this chapter implement various algorithms of -a cryptographic nature. They are available at the discretion of the -installation. Here's an overview: - -\begin{description} - -\item[md5] ---- RSA's MD5 message digest algorithm. - -\item[mpz] ---- Interface to the GNU MP library for arbitrary precision arithmetic. - -\item[rotor] ---- Enigma-like encryption and decryption. - -\end{description} - -Hardcore cypherpunks will probably find the Python Cryptography Kit of -further interest; the package adds built-in modules for DES and IDEA -encryption, and provides a Python module for reading and decrypting -PGP files. The Python Cryptography Kit is not distributed with Python -but available separately. See the URL -\file{http://www.cs.mcgill.ca/\%7Efnord/crypt.html} for more information. -\index{PGP} -\indexii{DES}{cipher} -\indexii{IDEA}{cipher} -\index{Python Cryptography Kit} diff --git a/Doc/libctb.tex b/Doc/libctb.tex deleted file mode 100644 index a5aab71421..0000000000 --- a/Doc/libctb.tex +++ /dev/null @@ -1,149 +0,0 @@ -\section{Built-in Module \sectcode{ctb}} -\bimodindex{ctb} -\renewcommand{\indexsubitem}{(in module ctb)} - -This module provides a partial interface to the Macintosh -Communications Toolbox. Currently, only Connection Manager tools are -supported. It may not be available in all Mac Python versions. - -\begin{datadesc}{error} -The exception raised on errors. -\end{datadesc} - -\begin{datadesc}{cmData} -\dataline{cmCntl} -\dataline{cmAttn} -Flags for the \var{channel} argument of the \var{Read} and \var{Write} -methods. -\end{datadesc} - -\begin{datadesc}{cmFlagsEOM} -End-of-message flag for \var{Read} and \var{Write}. -\end{datadesc} - -\begin{datadesc}{choose*} -Values returned by \var{Choose}. -\end{datadesc} - -\begin{datadesc}{cmStatus*} -Bits in the status as returned by \var{Status}. -\end{datadesc} - -\begin{funcdesc}{available}{} -Return 1 if the communication toolbox is available, zero otherwise. -\end{funcdesc} - -\begin{funcdesc}{CMNew}{name\, sizes} -Create a connection object using the connection tool named -\var{name}. \var{sizes} is a 6-tuple given buffer sizes for data in, -data out, control in, control out, attention in and attention out. -Alternatively, passing \code{None} will result in default buffer sizes. -\end{funcdesc} - -\subsection{connection object} -For all connection methods that take a \var{timeout} argument, a value -of \code{-1} is indefinite, meaning that the command runs to completion. - -\renewcommand{\indexsubitem}{(connection object attribute)} - -\begin{datadesc}{callback} -If this member is set to a value other than \code{None} it should point -to a function accepting a single argument (the connection -object). This will make all connection object methods work -asynchronously, with the callback routine being called upon -completion. - -{\em Note:} for reasons beyond my understanding the callback routine -is currently never called. You are advised against using asynchronous -calls for the time being. -\end{datadesc} - - -\renewcommand{\indexsubitem}{(connection object method)} - -\begin{funcdesc}{Open}{timeout} -Open an outgoing connection, waiting at most \var{timeout} seconds for -the connection to be established. -\end{funcdesc} - -\begin{funcdesc}{Listen}{timeout} -Wait for an incoming connection. Stop waiting after \var{timeout} -seconds. This call is only meaningful to some tools. -\end{funcdesc} - -\begin{funcdesc}{accept}{yesno} -Accept (when \var{yesno} is non-zero) or reject an incoming call after -\var{Listen} returned. -\end{funcdesc} - -\begin{funcdesc}{Close}{timeout\, now} -Close a connection. When \var{now} is zero, the close is orderly -(i.e.\ outstanding output is flushed, etc.)\ with a timeout of -\var{timeout} seconds. When \var{now} is non-zero the close is -immediate, discarding output. -\end{funcdesc} - -\begin{funcdesc}{Read}{len\, chan\, timeout} -Read \var{len} bytes, or until \var{timeout} seconds have passed, from -the channel \var{chan} (which is one of \var{cmData}, \var{cmCntl} or -\var{cmAttn}). Return a 2-tuple:\ the data read and the end-of-message -flag. -\end{funcdesc} - -\begin{funcdesc}{Write}{buf\, chan\, timeout\, eom} -Write \var{buf} to channel \var{chan}, aborting after \var{timeout} -seconds. When \var{eom} has the value \var{cmFlagsEOM} an -end-of-message indicator will be written after the data (if this -concept has a meaning for this communication tool). The method returns -the number of bytes written. -\end{funcdesc} - -\begin{funcdesc}{Status}{} -Return connection status as the 2-tuple \code{(\var{sizes}, -\var{flags})}. \var{sizes} is a 6-tuple giving the actual buffer sizes used -(see \var{CMNew}), \var{flags} is a set of bits describing the state -of the connection. -\end{funcdesc} - -\begin{funcdesc}{GetConfig}{} -Return the configuration string of the communication tool. These -configuration strings are tool-dependent, but usually easily parsed -and modified. -\end{funcdesc} - -\begin{funcdesc}{SetConfig}{str} -Set the configuration string for the tool. The strings are parsed -left-to-right, with later values taking precedence. This means -individual configuration parameters can be modified by simply appending -something like \code{'baud 4800'} to the end of the string returned by -\var{GetConfig} and passing that to this method. The method returns -the number of characters actually parsed by the tool before it -encountered an error (or completed successfully). -\end{funcdesc} - -\begin{funcdesc}{Choose}{} -Present the user with a dialog to choose a communication tool and -configure it. If there is an outstanding connection some choices (like -selecting a different tool) may cause the connection to be -aborted. The return value (one of the \var{choose*} constants) will -indicate this. -\end{funcdesc} - -\begin{funcdesc}{Idle}{} -Give the tool a chance to use the processor. You should call this -method regularly. -\end{funcdesc} - -\begin{funcdesc}{Abort}{} -Abort an outstanding asynchronous \var{Open} or \var{Listen}. -\end{funcdesc} - -\begin{funcdesc}{Reset}{} -Reset a connection. Exact meaning depends on the tool. -\end{funcdesc} - -\begin{funcdesc}{Break}{length} -Send a break. Whether this means anything, what it means and -interpretation of the \var{length} parameter depend on the tool in -use. -\end{funcdesc} diff --git a/Doc/libdbm.tex b/Doc/libdbm.tex deleted file mode 100644 index ee2d39f15a..0000000000 --- a/Doc/libdbm.tex +++ /dev/null @@ -1,36 +0,0 @@ -\section{Built-in Module \sectcode{dbm}} -\bimodindex{dbm} - -The \code{dbm} module provides an interface to the {\UNIX} -\code{(n)dbm} library. Dbm objects behave like mappings -(dictionaries), except that keys and values are always strings. -Printing a dbm object doesn't print the keys and values, and the -\code{items()} and \code{values()} methods are not supported. - -See also the \code{gdbm} module, which provides a similar interface -using the GNU GDBM library. -\bimodindex{gdbm} - -The module defines the following constant and functions: - -\renewcommand{\indexsubitem}{(in module dbm)} -\begin{excdesc}{error} -Raised on dbm-specific errors, such as I/O errors. \code{KeyError} is -raised for general mapping errors like specifying an incorrect key. -\end{excdesc} - -\begin{funcdesc}{open}{filename\, \optional{flag\, \optional{mode}}} -Open a dbm database and return a dbm object. The \var{filename} -argument is the name of the database file (without the \file{.dir} or -\file{.pag} extensions). - -The optional \var{flag} argument can be -\code{'r'} (to open an existing database for reading only --- default), -\code{'w'} (to open an existing database for reading and writing), -\code{'c'} (which creates the database if it doesn't exist), or -\code{'n'} (which always creates a new empty database). - -The optional \var{mode} argument is the \UNIX{} mode of the file, used -only when the database has to be created. It defaults to octal -\code{0666}. -\end{funcdesc} diff --git a/Doc/libexcs.tex b/Doc/libexcs.tex deleted file mode 100644 index 7cc919559a..0000000000 --- a/Doc/libexcs.tex +++ /dev/null @@ -1,172 +0,0 @@ -\section{Built-in Exceptions} - -Exceptions are string objects. Two distinct string objects with the -same value are different exceptions. This is done to force programmers -to use exception names rather than their string value when specifying -exception handlers. The string value of all built-in exceptions is -their name, but this is not a requirement for user-defined exceptions -or exceptions defined by library modules. - -The following exceptions can be generated by the interpreter or -built-in functions. Except where mentioned, they have an `associated -value' indicating the detailed cause of the error. This may be a -string or a tuple containing several items of information (e.g., an -error code and a string explaining the code). - -User code can raise built-in exceptions. This can be used to test an -exception handler or to report an error condition `just like' the -situation in which the interpreter raises the same exception; but -beware that there is nothing to prevent user code from raising an -inappropriate error. - -\renewcommand{\indexsubitem}{(built-in exception)} - -\begin{excdesc}{AttributeError} -% xref to attribute reference? - Raised when an attribute reference or assignment fails. (When an - object does not support attribute references or attribute assignments - at all, \code{TypeError} is raised.) -\end{excdesc} - -\begin{excdesc}{EOFError} -% XXXJH xrefs here - Raised when one of the built-in functions (\code{input()} or - \code{raw_input()}) hits an end-of-file condition (\EOF{}) without - reading any data. -% XXXJH xrefs here - (N.B.: the \code{read()} and \code{readline()} methods of file - objects return an empty string when they hit \EOF{}.) No associated value. -\end{excdesc} - -\begin{excdesc}{IOError} -% XXXJH xrefs here - Raised when an I/O operation (such as a \code{print} statement, the - built-in \code{open()} function or a method of a file object) fails - for an I/O-related reason, e.g., `file not found', `disk full'. -\end{excdesc} - -\begin{excdesc}{ImportError} -% XXXJH xref to import statement? - Raised when an \code{import} statement fails to find the module - definition or when a \code{from {\rm \ldots} import} fails to find a - name that is to be imported. -\end{excdesc} - -\begin{excdesc}{IndexError} -% XXXJH xref to sequences - Raised when a sequence subscript is out of range. (Slice indices are - silently truncated to fall in the allowed range; if an index is not a - plain integer, \code{TypeError} is raised.) -\end{excdesc} - -\begin{excdesc}{KeyError} -% XXXJH xref to mapping objects? - Raised when a mapping (dictionary) key is not found in the set of - existing keys. -\end{excdesc} - -\begin{excdesc}{KeyboardInterrupt} - Raised when the user hits the interrupt key (normally - \kbd{Control-C} or -\key{DEL}). During execution, a check for interrupts is made regularly. -% XXXJH xrefs here - Interrupts typed when a built-in function \code{input()} or - \code{raw_input()}) is waiting for input also raise this exception. No - associated value. -\end{excdesc} - -\begin{excdesc}{MemoryError} - Raised when an operation runs out of memory but the situation may - still be rescued (by deleting some objects). The associated value is - a string indicating what kind of (internal) operation ran out of memory. - Note that because of the underlying memory management architecture - (\C{}'s \code{malloc()} function), the interpreter may not always be able - to completely recover from this situation; it nevertheless raises an - exception so that a stack traceback can be printed, in case a run-away - program was the cause. -\end{excdesc} - -\begin{excdesc}{NameError} - Raised when a local or global name is not found. This applies only - to unqualified names. The associated value is the name that could - not be found. -\end{excdesc} - -\begin{excdesc}{OverflowError} -% XXXJH reference to long's and/or int's? - Raised when the result of an arithmetic operation is too large to be - represented. This cannot occur for long integers (which would rather - raise \code{MemoryError} than give up). Because of the lack of - standardization of floating point exception handling in \C{}, most - floating point operations also aren't checked. For plain integers, - all operations that can overflow are checked except left shift, where - typical applications prefer to drop bits than raise an exception. -\end{excdesc} - -\begin{excdesc}{RuntimeError} - Raised when an error is detected that doesn't fall in any of the - other categories. The associated value is a string indicating what - precisely went wrong. (This exception is a relic from a previous - version of the interpreter; it is not used any more except by some - extension modules that haven't been converted to define their own - exceptions yet.) -\end{excdesc} - -\begin{excdesc}{SyntaxError} -% XXXJH xref to these functions? - Raised when the parser encounters a syntax error. This may occur in - an \code{import} statement, in an \code{exec} statement, in a call - to the built-in function \code{eval()} or \code{input()}, or - when reading the initial script or standard input (also - interactively). -\end{excdesc} - -\begin{excdesc}{SystemError} - Raised when the interpreter finds an internal error, but the - situation does not look so serious to cause it to abandon all hope. - The associated value is a string indicating what went wrong (in - low-level terms). - - You should report this to the author or maintainer of your Python - interpreter. Be sure to report the version string of the Python - interpreter (\code{sys.version}; it is also printed at the start of an - interactive Python session), the exact error message (the exception's - associated value) and if possible the source of the program that - triggered the error. -\end{excdesc} - -\begin{excdesc}{SystemExit} -% XXXJH xref to module sys? - This exception is raised by the \code{sys.exit()} function. When it - is not handled, the Python interpreter exits; no stack traceback is - printed. If the associated value is a plain integer, it specifies the - system exit status (passed to \C{}'s \code{exit()} function); if it is - \code{None}, the exit status is zero; if it has another type (such as - a string), the object's value is printed and the exit status is one. - - A call to \code{sys.exit} is translated into an exception so that - clean-up handlers (\code{finally} clauses of \code{try} statements) - can be executed, and so that a debugger can execute a script without - running the risk of losing control. The \code{posix._exit()} function - can be used if it is absolutely positively necessary to exit - immediately (e.g., after a \code{fork()} in the child process). -\end{excdesc} - -\begin{excdesc}{TypeError} - Raised when a built-in operation or function is applied to an object - of inappropriate type. The associated value is a string giving - details about the type mismatch. -\end{excdesc} - -\begin{excdesc}{ValueError} - Raised when a built-in operation or function receives an argument - that has the right type but an inappropriate value, and the - situation is not described by a more precise exception such as - \code{IndexError}. -\end{excdesc} - -\begin{excdesc}{ZeroDivisionError} - Raised when the second argument of a division or modulo operation is - zero. The associated value is a string indicating the type of the - operands and the operation. -\end{excdesc} diff --git a/Doc/libfcntl.tex b/Doc/libfcntl.tex deleted file mode 100644 index 8539e2aa43..0000000000 --- a/Doc/libfcntl.tex +++ /dev/null @@ -1,60 +0,0 @@ -% Manual text by Jaap Vermeulen -\section{Built-in Module \sectcode{fcntl}} -\bimodindex{fcntl} -\indexii{\UNIX{}}{file control} -\indexii{\UNIX{}}{I/O control} - -This module performs file control and I/O control on file descriptors. -It is an interface to the \dfn{fcntl()} and \dfn{ioctl()} \UNIX{} routines. -File descriptors can be obtained with the \dfn{fileno()} method of a -file or socket object. - -The module defines the following functions: - -\renewcommand{\indexsubitem}{(in module struct)} - -\begin{funcdesc}{fcntl}{fd\, op\optional{\, arg}} - Perform the requested operation on file descriptor \code{\var{fd}}. - The operation is defined by \code{\var{op}} and is operating system - dependent. Typically these codes can be retrieved from the library - module \code{FCNTL}. The argument \code{\var{arg}} is optional, and - defaults to the integer value \code{0}. When - it is present, it can either be an integer value, or a string. With - the argument missing or an integer value, the return value of this - function is the integer return value of the real \code{fcntl()} - call. When the argument is a string it represents a binary - structure, e.g.\ created by \code{struct.pack()}. The binary data is - copied to a buffer whose address is passed to the real \code{fcntl()} - call. The return value after a successful call is the contents of - the buffer, converted to a string object. In case the - \code{fcntl()} fails, an \code{IOError} will be raised. -\end{funcdesc} - -\begin{funcdesc}{ioctl}{fd\, op\, arg} - This function is identical to the \code{fcntl()} function, except - that the operations are typically defined in the library module - \code{IOCTL}. -\end{funcdesc} - -If the library modules \code{FCNTL} or \code{IOCTL} are missing, you -can find the opcodes in the C include files \code{sys/fcntl} and -\code{sys/ioctl}. You can create the modules yourself with the h2py -script, found in the \code{Tools/scripts} directory. -\stmodindex{FCNTL} -\stmodindex{IOCTL} - -Examples (all on a SVR4 compliant system): - -\bcode\begin{verbatim} -import struct, FCNTL - -file = open(...) -rv = fcntl(file.fileno(), FCNTL.O_NDELAY, 1) - -lockdata = struct.pack('hhllhh', FCNTL.F_WRLCK, 0, 0, 0, 0, 0) -rv = fcntl(file.fileno(), FCNTL.F_SETLKW, lockdata) -\end{verbatim}\ecode - -Note that in the first example the return value variable \code{rv} will -hold an integer value; in the second example it will hold a string -value. diff --git a/Doc/libfl.tex b/Doc/libfl.tex deleted file mode 100644 index d5332a0602..0000000000 --- a/Doc/libfl.tex +++ /dev/null @@ -1,485 +0,0 @@ -\section{Built-in Module \sectcode{fl}} -\bimodindex{fl} - -This module provides an interface to the FORMS Library by Mark -Overmars. The source for the library can be retrieved by anonymous -ftp from host \samp{ftp.cs.ruu.nl}, directory \file{SGI/FORMS}. It -was last tested with version 2.0b. - -Most functions are literal translations of their C equivalents, -dropping the initial \samp{fl_} from their name. Constants used by -the library are defined in module \code{FL} described below. - -The creation of objects is a little different in Python than in C: -instead of the `current form' maintained by the library to which new -FORMS objects are added, all functions that add a FORMS object to a -form are methods of the Python object representing the form. -Consequently, there are no Python equivalents for the C functions -\code{fl_addto_form} and \code{fl_end_form}, and the equivalent of -\code{fl_bgn_form} is called \code{fl.make_form}. - -Watch out for the somewhat confusing terminology: FORMS uses the word -\dfn{object} for the buttons, sliders etc. that you can place in a form. -In Python, `object' means any value. The Python interface to FORMS -introduces two new Python object types: form objects (representing an -entire form) and FORMS objects (representing one button, slider etc.). -Hopefully this isn't too confusing... - -There are no `free objects' in the Python interface to FORMS, nor is -there an easy way to add object classes written in Python. The FORMS -interface to GL event handling is available, though, so you can mix -FORMS with pure GL windows. - -\strong{Please note:} importing \code{fl} implies a call to the GL function -\code{foreground()} and to the FORMS routine \code{fl_init()}. - -\subsection{Functions Defined in Module \sectcode{fl}} -\nodename{FL Functions} - -Module \code{fl} defines the following functions. For more information -about what they do, see the description of the equivalent C function -in the FORMS documentation: - -\renewcommand{\indexsubitem}{(in module fl)} -\begin{funcdesc}{make_form}{type\, width\, height} -Create a form with given type, width and height. This returns a -\dfn{form} object, whose methods are described below. -\end{funcdesc} - -\begin{funcdesc}{do_forms}{} -The standard FORMS main loop. Returns a Python object representing -the FORMS object needing interaction, or the special value -\code{FL.EVENT}. -\end{funcdesc} - -\begin{funcdesc}{check_forms}{} -Check for FORMS events. Returns what \code{do_forms} above returns, -or \code{None} if there is no event that immediately needs -interaction. -\end{funcdesc} - -\begin{funcdesc}{set_event_call_back}{function} -Set the event callback function. -\end{funcdesc} - -\begin{funcdesc}{set_graphics_mode}{rgbmode\, doublebuffering} -Set the graphics modes. -\end{funcdesc} - -\begin{funcdesc}{get_rgbmode}{} -Return the current rgb mode. This is the value of the C global -variable \code{fl_rgbmode}. -\end{funcdesc} - -\begin{funcdesc}{show_message}{str1\, str2\, str3} -Show a dialog box with a three-line message and an OK button. -\end{funcdesc} - -\begin{funcdesc}{show_question}{str1\, str2\, str3} -Show a dialog box with a three-line message and YES and NO buttons. -It returns \code{1} if the user pressed YES, \code{0} if NO. -\end{funcdesc} - -\begin{funcdesc}{show_choice}{str1\, str2\, str3\, but1\optional{\, but2\, -but3}} -Show a dialog box with a three-line message and up to three buttons. -It returns the number of the button clicked by the user -(\code{1}, \code{2} or \code{3}). -\end{funcdesc} - -\begin{funcdesc}{show_input}{prompt\, default} -Show a dialog box with a one-line prompt message and text field in -which the user can enter a string. The second argument is the default -input string. It returns the string value as edited by the user. -\end{funcdesc} - -\begin{funcdesc}{show_file_selector}{message\, directory\, pattern\, default} -Show a dialog box in which the user can select a file. It returns -the absolute filename selected by the user, or \code{None} if the user -presses Cancel. -\end{funcdesc} - -\begin{funcdesc}{get_directory}{} -\funcline{get_pattern}{} -\funcline{get_filename}{} -These functions return the directory, pattern and filename (the tail -part only) selected by the user in the last \code{show_file_selector} -call. -\end{funcdesc} - -\begin{funcdesc}{qdevice}{dev} -\funcline{unqdevice}{dev} -\funcline{isqueued}{dev} -\funcline{qtest}{} -\funcline{qread}{} -%\funcline{blkqread}{?} -\funcline{qreset}{} -\funcline{qenter}{dev\, val} -\funcline{get_mouse}{} -\funcline{tie}{button\, valuator1\, valuator2} -These functions are the FORMS interfaces to the corresponding GL -functions. Use these if you want to handle some GL events yourself -when using \code{fl.do_events}. When a GL event is detected that -FORMS cannot handle, \code{fl.do_forms()} returns the special value -\code{FL.EVENT} and you should call \code{fl.qread()} to read the -event from the queue. Don't use the equivalent GL functions! -\end{funcdesc} - -\begin{funcdesc}{color}{} -\funcline{mapcolor}{} -\funcline{getmcolor}{} -See the description in the FORMS documentation of \code{fl_color}, -\code{fl_mapcolor} and \code{fl_getmcolor}. -\end{funcdesc} - -\subsection{Form Objects} - -Form objects (returned by \code{fl.make_form()} above) have the -following methods. Each method corresponds to a C function whose name -is prefixed with \samp{fl_}; and whose first argument is a form -pointer; please refer to the official FORMS documentation for -descriptions. - -All the \samp{add_{\rm \ldots}} functions return a Python object representing -the FORMS object. Methods of FORMS objects are described below. Most -kinds of FORMS object also have some methods specific to that kind; -these methods are listed here. - -\begin{flushleft} -\renewcommand{\indexsubitem}{(form object method)} -\begin{funcdesc}{show_form}{placement\, bordertype\, name} - Show the form. -\end{funcdesc} - -\begin{funcdesc}{hide_form}{} - Hide the form. -\end{funcdesc} - -\begin{funcdesc}{redraw_form}{} - Redraw the form. -\end{funcdesc} - -\begin{funcdesc}{set_form_position}{x\, y} -Set the form's position. -\end{funcdesc} - -\begin{funcdesc}{freeze_form}{} -Freeze the form. -\end{funcdesc} - -\begin{funcdesc}{unfreeze_form}{} - Unfreeze the form. -\end{funcdesc} - -\begin{funcdesc}{activate_form}{} - Activate the form. -\end{funcdesc} - -\begin{funcdesc}{deactivate_form}{} - Deactivate the form. -\end{funcdesc} - -\begin{funcdesc}{bgn_group}{} - Begin a new group of objects; return a group object. -\end{funcdesc} - -\begin{funcdesc}{end_group}{} - End the current group of objects. -\end{funcdesc} - -\begin{funcdesc}{find_first}{} - Find the first object in the form. -\end{funcdesc} - -\begin{funcdesc}{find_last}{} - Find the last object in the form. -\end{funcdesc} - -%--- - -\begin{funcdesc}{add_box}{type\, x\, y\, w\, h\, name} -Add a box object to the form. -No extra methods. -\end{funcdesc} - -\begin{funcdesc}{add_text}{type\, x\, y\, w\, h\, name} -Add a text object to the form. -No extra methods. -\end{funcdesc} - -%\begin{funcdesc}{add_bitmap}{type\, x\, y\, w\, h\, name} -%Add a bitmap object to the form. -%\end{funcdesc} - -\begin{funcdesc}{add_clock}{type\, x\, y\, w\, h\, name} -Add a clock object to the form. \\ -Method: -\code{get_clock}. -\end{funcdesc} - -%--- - -\begin{funcdesc}{add_button}{type\, x\, y\, w\, h\, name} -Add a button object to the form. \\ -Methods: -\code{get_button}, -\code{set_button}. -\end{funcdesc} - -\begin{funcdesc}{add_lightbutton}{type\, x\, y\, w\, h\, name} -Add a lightbutton object to the form. \\ -Methods: -\code{get_button}, -\code{set_button}. -\end{funcdesc} - -\begin{funcdesc}{add_roundbutton}{type\, x\, y\, w\, h\, name} -Add a roundbutton object to the form. \\ -Methods: -\code{get_button}, -\code{set_button}. -\end{funcdesc} - -%--- - -\begin{funcdesc}{add_slider}{type\, x\, y\, w\, h\, name} -Add a slider object to the form. \\ -Methods: -\code{set_slider_value}, -\code{get_slider_value}, -\code{set_slider_bounds}, -\code{get_slider_bounds}, -\code{set_slider_return}, -\code{set_slider_size}, -\code{set_slider_precision}, -\code{set_slider_step}. -\end{funcdesc} - -\begin{funcdesc}{add_valslider}{type\, x\, y\, w\, h\, name} -Add a valslider object to the form. \\ -Methods: -\code{set_slider_value}, -\code{get_slider_value}, -\code{set_slider_bounds}, -\code{get_slider_bounds}, -\code{set_slider_return}, -\code{set_slider_size}, -\code{set_slider_precision}, -\code{set_slider_step}. -\end{funcdesc} - -\begin{funcdesc}{add_dial}{type\, x\, y\, w\, h\, name} -Add a dial object to the form. \\ -Methods: -\code{set_dial_value}, -\code{get_dial_value}, -\code{set_dial_bounds}, -\code{get_dial_bounds}. -\end{funcdesc} - -\begin{funcdesc}{add_positioner}{type\, x\, y\, w\, h\, name} -Add a positioner object to the form. \\ -Methods: -\code{set_positioner_xvalue}, -\code{set_positioner_yvalue}, -\code{set_positioner_xbounds}, -\code{set_positioner_ybounds}, -\code{get_positioner_xvalue}, -\code{get_positioner_yvalue}, -\code{get_positioner_xbounds}, -\code{get_positioner_ybounds}. -\end{funcdesc} - -\begin{funcdesc}{add_counter}{type\, x\, y\, w\, h\, name} -Add a counter object to the form. \\ -Methods: -\code{set_counter_value}, -\code{get_counter_value}, -\code{set_counter_bounds}, -\code{set_counter_step}, -\code{set_counter_precision}, -\code{set_counter_return}. -\end{funcdesc} - -%--- - -\begin{funcdesc}{add_input}{type\, x\, y\, w\, h\, name} -Add a input object to the form. \\ -Methods: -\code{set_input}, -\code{get_input}, -\code{set_input_color}, -\code{set_input_return}. -\end{funcdesc} - -%--- - -\begin{funcdesc}{add_menu}{type\, x\, y\, w\, h\, name} -Add a menu object to the form. \\ -Methods: -\code{set_menu}, -\code{get_menu}, -\code{addto_menu}. -\end{funcdesc} - -\begin{funcdesc}{add_choice}{type\, x\, y\, w\, h\, name} -Add a choice object to the form. \\ -Methods: -\code{set_choice}, -\code{get_choice}, -\code{clear_choice}, -\code{addto_choice}, -\code{replace_choice}, -\code{delete_choice}, -\code{get_choice_text}, -\code{set_choice_fontsize}, -\code{set_choice_fontstyle}. -\end{funcdesc} - -\begin{funcdesc}{add_browser}{type\, x\, y\, w\, h\, name} -Add a browser object to the form. \\ -Methods: -\code{set_browser_topline}, -\code{clear_browser}, -\code{add_browser_line}, -\code{addto_browser}, -\code{insert_browser_line}, -\code{delete_browser_line}, -\code{replace_browser_line}, -\code{get_browser_line}, -\code{load_browser}, -\code{get_browser_maxline}, -\code{select_browser_line}, -\code{deselect_browser_line}, -\code{deselect_browser}, -\code{isselected_browser_line}, -\code{get_browser}, -\code{set_browser_fontsize}, -\code{set_browser_fontstyle}, -\code{set_browser_specialkey}. -\end{funcdesc} - -%--- - -\begin{funcdesc}{add_timer}{type\, x\, y\, w\, h\, name} -Add a timer object to the form. \\ -Methods: -\code{set_timer}, -\code{get_timer}. -\end{funcdesc} -\end{flushleft} - -Form objects have the following data attributes; see the FORMS -documentation: - -\begin{tableiii}{|l|c|l|}{code}{Name}{Type}{Meaning} - \lineiii{window}{int (read-only)}{GL window id} - \lineiii{w}{float}{form width} - \lineiii{h}{float}{form height} - \lineiii{x}{float}{form x origin} - \lineiii{y}{float}{form y origin} - \lineiii{deactivated}{int}{nonzero if form is deactivated} - \lineiii{visible}{int}{nonzero if form is visible} - \lineiii{frozen}{int}{nonzero if form is frozen} - \lineiii{doublebuf}{int}{nonzero if double buffering on} -\end{tableiii} - -\subsection{FORMS Objects} - -Besides methods specific to particular kinds of FORMS objects, all -FORMS objects also have the following methods: - -\renewcommand{\indexsubitem}{(FORMS object method)} -\begin{funcdesc}{set_call_back}{function\, argument} -Set the object's callback function and argument. When the object -needs interaction, the callback function will be called with two -arguments: the object, and the callback argument. (FORMS objects -without a callback function are returned by \code{fl.do_forms()} or -\code{fl.check_forms()} when they need interaction.) Call this method -without arguments to remove the callback function. -\end{funcdesc} - -\begin{funcdesc}{delete_object}{} - Delete the object. -\end{funcdesc} - -\begin{funcdesc}{show_object}{} - Show the object. -\end{funcdesc} - -\begin{funcdesc}{hide_object}{} - Hide the object. -\end{funcdesc} - -\begin{funcdesc}{redraw_object}{} - Redraw the object. -\end{funcdesc} - -\begin{funcdesc}{freeze_object}{} - Freeze the object. -\end{funcdesc} - -\begin{funcdesc}{unfreeze_object}{} - Unfreeze the object. -\end{funcdesc} - -%\begin{funcdesc}{handle_object}{} XXX -%\end{funcdesc} - -%\begin{funcdesc}{handle_object_direct}{} XXX -%\end{funcdesc} - -FORMS objects have these data attributes; see the FORMS documentation: - -\begin{tableiii}{|l|c|l|}{code}{Name}{Type}{Meaning} - \lineiii{objclass}{int (read-only)}{object class} - \lineiii{type}{int (read-only)}{object type} - \lineiii{boxtype}{int}{box type} - \lineiii{x}{float}{x origin} - \lineiii{y}{float}{y origin} - \lineiii{w}{float}{width} - \lineiii{h}{float}{height} - \lineiii{col1}{int}{primary color} - \lineiii{col2}{int}{secondary color} - \lineiii{align}{int}{alignment} - \lineiii{lcol}{int}{label color} - \lineiii{lsize}{float}{label font size} - \lineiii{label}{string}{label string} - \lineiii{lstyle}{int}{label style} - \lineiii{pushed}{int (read-only)}{(see FORMS docs)} - \lineiii{focus}{int (read-only)}{(see FORMS docs)} - \lineiii{belowmouse}{int (read-only)}{(see FORMS docs)} - \lineiii{frozen}{int (read-only)}{(see FORMS docs)} - \lineiii{active}{int (read-only)}{(see FORMS docs)} - \lineiii{input}{int (read-only)}{(see FORMS docs)} - \lineiii{visible}{int (read-only)}{(see FORMS docs)} - \lineiii{radio}{int (read-only)}{(see FORMS docs)} - \lineiii{automatic}{int (read-only)}{(see FORMS docs)} -\end{tableiii} - -\section{Standard Module \sectcode{FL}} -\nodename{FL (uppercase)} -\stmodindex{FL} - -This module defines symbolic constants needed to use the built-in -module \code{fl} (see above); they are equivalent to those defined in -the C header file \file{<forms.h>} except that the name prefix -\samp{FL_} is omitted. Read the module source for a complete list of -the defined names. Suggested use: - -\bcode\begin{verbatim} -import fl -from FL import * -\end{verbatim}\ecode - -\section{Standard Module \sectcode{flp}} -\stmodindex{flp} - -This module defines functions that can read form definitions created -by the `form designer' (\code{fdesign}) program that comes with the -FORMS library (see module \code{fl} above). - -For now, see the file \file{flp.doc} in the Python library source -directory for a description. - -XXX A complete description should be inserted here! diff --git a/Doc/libfm.tex b/Doc/libfm.tex deleted file mode 100644 index 45d820c0b0..0000000000 --- a/Doc/libfm.tex +++ /dev/null @@ -1,87 +0,0 @@ -\section{Built-in Module \sectcode{fm}} -\bimodindex{fm} - -This module provides access to the IRIS {\em Font Manager} library. -It is available only on Silicon Graphics machines. -See also: 4Sight User's Guide, Section 1, Chapter 5: Using the IRIS -Font Manager. - -This is not yet a full interface to the IRIS Font Manager. -Among the unsupported features are: matrix operations; cache -operations; character operations (use string operations instead); some -details of font info; individual glyph metrics; and printer matching. - -It supports the following operations: - -\renewcommand{\indexsubitem}{(in module fm)} -\begin{funcdesc}{init}{} -Initialization function. -Calls \code{fminit()}. -It is normally not necessary to call this function, since it is called -automatically the first time the \code{fm} module is imported. -\end{funcdesc} - -\begin{funcdesc}{findfont}{fontname} -Return a font handle object. -Calls \code{fmfindfont(\var{fontname})}. -\end{funcdesc} - -\begin{funcdesc}{enumerate}{} -Returns a list of available font names. -This is an interface to \code{fmenumerate()}. -\end{funcdesc} - -\begin{funcdesc}{prstr}{string} -Render a string using the current font (see the \code{setfont()} font -handle method below). -Calls \code{fmprstr(\var{string})}. -\end{funcdesc} - -\begin{funcdesc}{setpath}{string} -Sets the font search path. -Calls \code{fmsetpath(string)}. -(XXX Does not work!?!) -\end{funcdesc} - -\begin{funcdesc}{fontpath}{} -Returns the current font search path. -\end{funcdesc} - -Font handle objects support the following operations: - -\renewcommand{\indexsubitem}{(font handle method)} -\begin{funcdesc}{scalefont}{factor} -Returns a handle for a scaled version of this font. -Calls \code{fmscalefont(\var{fh}, \var{factor})}. -\end{funcdesc} - -\begin{funcdesc}{setfont}{} -Makes this font the current font. -Note: the effect is undone silently when the font handle object is -deleted. -Calls \code{fmsetfont(\var{fh})}. -\end{funcdesc} - -\begin{funcdesc}{getfontname}{} -Returns this font's name. -Calls \code{fmgetfontname(\var{fh})}. -\end{funcdesc} - -\begin{funcdesc}{getcomment}{} -Returns the comment string associated with this font. -Raises an exception if there is none. -Calls \code{fmgetcomment(\var{fh})}. -\end{funcdesc} - -\begin{funcdesc}{getfontinfo}{} -Returns a tuple giving some pertinent data about this font. -This is an interface to \code{fmgetfontinfo()}. -The returned tuple contains the following numbers: -{\tt(\var{printermatched}, \var{fixed_width}, \var{xorig}, \var{yorig}, -\var{xsize}, \var{ysize}, \var{height}, \var{nglyphs})}. -\end{funcdesc} - -\begin{funcdesc}{getstrwidth}{string} -Returns the width, in pixels, of the string when drawn in this font. -Calls \code{fmgetstrwidth(\var{fh}, \var{string})}. -\end{funcdesc} diff --git a/Doc/libftplib.tex b/Doc/libftplib.tex deleted file mode 100644 index 3fda77ac44..0000000000 --- a/Doc/libftplib.tex +++ /dev/null @@ -1,204 +0,0 @@ -\section{Standard Module \sectcode{ftplib}} -\stmodindex{ftplib} - -\renewcommand{\indexsubitem}{(in module ftplib)} - -This module defines the class \code{FTP} and a few related items. The -\code{FTP} class implements the client side of the FTP protocol. You -can use this to write Python programs that perform a variety of -automated FTP jobs, such as mirroring other ftp servers. It is also -used by the module \code{urllib} to handle URLs that use FTP. For -more information on FTP (File Transfer Protocol), see Internet RFC -959. - -Here's a sample session using the \code{ftplib} module: - -\begin{verbatim} ->>> from ftplib import FTP ->>> ftp = FTP('ftp.cwi.nl') # connect to host, default port ->>> ftp.login() # user anonymous, passwd user@hostname ->>> ftp.retrlines('LIST') # list directory contents -total 24418 -drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 . -dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 .. --rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX - . - . - . ->>> ftp.quit() -\end{verbatim} - -The module defines the following items: - -\begin{funcdesc}{FTP}{\optional{host\optional{\, user\, passwd\, acct}}} -Return a new instance of the \code{FTP} class. When -\var{host} is given, the method call \code{connect(\var{host})} is -made. When \var{user} is given, additionally the method call -\code{login(\var{user}, \var{passwd}, \var{acct})} is made (where -\var{passwd} and \var{acct} default to the empty string when not given). -\end{funcdesc} - -\begin{datadesc}{all_errors} -The set of all exceptions (as a tuple) that methods of \code{FTP} -instances may raise as a result of problems with the FTP connection -(as opposed to programming errors made by the caller). This set -includes the four exceptions listed below as well as -\code{socket.error} and \code{IOError}. -\end{datadesc} - -\begin{excdesc}{error_reply} -Exception raised when an unexpected reply is received from the server. -\end{excdesc} - -\begin{excdesc}{error_temp} -Exception raised when an error code in the range 400--499 is received. -\end{excdesc} - -\begin{excdesc}{error_perm} -Exception raised when an error code in the range 500--599 is received. -\end{excdesc} - -\begin{excdesc}{error_proto} -Exception raised when a reply is received from the server that does -not begin with a digit in the range 1--5. -\end{excdesc} - -\subsection{FTP Objects} - -FTP instances have the following methods: - -\renewcommand{\indexsubitem}{(FTP object method)} - -\begin{funcdesc}{set_debuglevel}{level} -Set the instance's debugging level. This controls the amount of -debugging output printed. The default, 0, produces no debugging -output. A value of 1 produces a moderate amount of debugging output, -generally a single line per request. A value of 2 or higher produces -the maximum amount of debugging output, logging each line sent and -received on the control connection. -\end{funcdesc} - -\begin{funcdesc}{connect}{host\optional{\, port}} -Connect to the given host and port. The default port number is 21, as -specified by the FTP protocol specification. It is rarely needed to -specify a different port number. This function should be called only -once for each instance; it should not be called at all if a host was -given when the instance was created. All other methods can only be -used after a connection has been made. -\end{funcdesc} - -\begin{funcdesc}{getwelcome}{} -Return the welcome message sent by the server in reply to the initial -connection. (This message sometimes contains disclaimers or help -information that may be relevant to the user.) -\end{funcdesc} - -\begin{funcdesc}{login}{\optional{user\optional{\, passwd\optional{\, acct}}}} -Log in as the given \var{user}. The \var{passwd} and \var{acct} -parameters are optional and default to the empty string. If no -\var{user} is specified, it defaults to \samp{anonymous}. If -\var{user} is \code{anonymous}, the default \var{passwd} is -\samp{\var{realuser}@\var{host}} where \var{realuser} is the real user -name (glanced from the \samp{LOGNAME} or \samp{USER} environment -variable) and \var{host} is the hostname as returned by -\code{socket.gethostname()}. This function should be called only -once for each instance, after a connection has been established; it -should not be called at all if a host and user were given when the -instance was created. Most FTP commands are only allowed after the -client has logged in. -\end{funcdesc} - -\begin{funcdesc}{abort}{} -Abort a file transfer that is in progress. Using this does not always -work, but it's worth a try. -\end{funcdesc} - -\begin{funcdesc}{sendcmd}{command} -Send a simple command string to the server and return the response -string. -\end{funcdesc} - -\begin{funcdesc}{voidcmd}{command} -Send a simple command string to the server and handle the response. -Return nothing if a response code in the range 200--299 is received. -Raise an exception otherwise. -\end{funcdesc} - -\begin{funcdesc}{retrbinary}{command\, callback\, maxblocksize} -Retrieve a file in binary transfer mode. \var{command} should be an -appropriate \samp{RETR} command, i.e.\ \code{"RETR \var{filename}"}. -The \var{callback} function is called for each block of data received, -with a single string argument giving the data block. -The \var{maxblocksize} argument specifies the maximum block size -(which may not be the actual size of the data blocks passed to -\var{callback}). -\end{funcdesc} - -\begin{funcdesc}{retrlines}{command\optional{\, callback}} -Retrieve a file or directory listing in \ASCII{} transfer mode. -var{command} should be an appropriate \samp{RETR} command (see -\code{retrbinary()} or a \samp{LIST} command (usually just the string -\code{"LIST"}). The \var{callback} function is called for each line, -with the trailing CRLF stripped. The default \var{callback} prints -the line to \code{sys.stdout}. -\end{funcdesc} - -\begin{funcdesc}{storbinary}{command\, file\, blocksize} -Store a file in binary transfer mode. \var{command} should be an -appropriate \samp{STOR} command, i.e.\ \code{"STOR \var{filename}"}. -\var{file} is an open file object which is read until EOF using its -\code{read()} method in blocks of size \var{blocksize} to provide the -data to be stored. -\end{funcdesc} - -\begin{funcdesc}{storlines}{command\, file} -Store a file in \ASCII{} transfer mode. \var{command} should be an -appropriate \samp{STOR} command (see \code{storbinary()}). Lines are -read until EOF from the open file object \var{file} using its -\code{readline()} method to privide the data to be stored. -\end{funcdesc} - -\begin{funcdesc}{nlst}{argument\optional{\, \ldots}} -Return a list of files as returned by the \samp{NLST} command. The -optional var{argument} is a directory to list (default is the current -server directory). Multiple arguments can be used to pass -non-standard options to the \samp{NLST} command. -\end{funcdesc} - -\begin{funcdesc}{dir}{argument\optional{\, \ldots}} -Return a directory listing as returned by the \samp{LIST} command, as -a list of lines. The optional var{argument} is a directory to list -(default is the current server directory). Multiple arguments can be -used to pass non-standard options to the \samp{LIST} command. If the -last argument is a function, it is used as a \var{callback} function -as for \code{retrlines()}. -\end{funcdesc} - -\begin{funcdesc}{rename}{fromname\, toname} -Rename file \var{fromname} on the server to \var{toname}. -\end{funcdesc} - -\begin{funcdesc}{cwd}{pathname} -Set the current directory on the server. -\end{funcdesc} - -\begin{funcdesc}{mkd}{pathname} -Create a new directory on the server. -\end{funcdesc} - -\begin{funcdesc}{pwd}{} -Return the pathname of the current directory on the server. -\end{funcdesc} - -\begin{funcdesc}{quit}{} -Send a \samp{QUIT} command to the server and close the connection. -This is the ``polite'' way to close a connection, but it may raise an -exception of the server reponds with an error to the \code{QUIT} -command. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Close the connection unilaterally. This should not be applied to an -already closed connection (e.g.\ after a successful call to -\code{quit()}. -\end{funcdesc} diff --git a/Doc/libfuncs.tex b/Doc/libfuncs.tex deleted file mode 100644 index 088f969e79..0000000000 --- a/Doc/libfuncs.tex +++ /dev/null @@ -1,491 +0,0 @@ -\section{Built-in Functions} - -The Python interpreter has a number of functions built into it that -are always available. They are listed here in alphabetical order. - - -\renewcommand{\indexsubitem}{(built-in function)} -\begin{funcdesc}{abs}{x} - Return the absolute value of a number. The argument may be a plain - or long integer or a floating point number. -\end{funcdesc} - -\begin{funcdesc}{apply}{function\, args\optional{, keywords}} -The \var{function} argument must be a callable object (a user-defined or -built-in function or method, or a class object) and the \var{args} -argument must be a tuple. The \var{function} is called with -\var{args} as argument list; the number of arguments is the the length -of the tuple. (This is different from just calling -\code{\var{func}(\var{args})}, since in that case there is always -exactly one argument.) -If the optional \var{keywords} argument is present, it must be a -dictionary whose keys are strings. It specifies keyword arguments to -be added to the end of the the argument list. -\end{funcdesc} - -\begin{funcdesc}{chr}{i} - Return a string of one character whose \ASCII{} code is the integer - \var{i}, e.g., \code{chr(97)} returns the string \code{'a'}. This is the - inverse of \code{ord()}. The argument must be in the range [0..255], - inclusive. -\end{funcdesc} - -\begin{funcdesc}{cmp}{x\, y} - Compare the two objects \var{x} and \var{y} and return an integer - according to the outcome. The return value is negative if \code{\var{x} - < \var{y}}, zero if \code{\var{x} == \var{y}} and strictly positive if - \code{\var{x} > \var{y}}. -\end{funcdesc} - -\begin{funcdesc}{coerce}{x\, y} - Return a tuple consisting of the two numeric arguments converted to - a common type, using the same rules as used by arithmetic - operations. -\end{funcdesc} - -\begin{funcdesc}{compile}{string\, filename\, kind} - Compile the \var{string} into a code object. Code objects can be - executed by an \code{exec} statement or evaluated by a call to - \code{eval()}. The \var{filename} argument should - give the file from which the code was read; pass e.g. \code{'<string>'} - if it wasn't read from a file. The \var{kind} argument specifies - what kind of code must be compiled; it can be \code{'exec'} if - \var{string} consists of a sequence of statements, \code{'eval'} - if it consists of a single expression, or \code{'single'} if - it consists of a single interactive statement (in the latter case, - expression statements that evaluate to something else than - \code{None} will printed). -\end{funcdesc} - -\begin{funcdesc}{delattr}{object\, name} - This is a relative of \code{setattr}. The arguments are an - object and a string. The string must be the name - of one of the object's attributes. The function deletes - the named attribute, provided the object allows it. For example, - \code{delattr(\var{x}, '\var{foobar}')} is equivalent to - \code{del \var{x}.\var{foobar}}. -\end{funcdesc} - -\begin{funcdesc}{dir}{} - Without arguments, return the list of names in the current local - symbol table. With a module, class or class instance object as - argument (or anything else that has a \code{__dict__} attribute), - returns the list of names in that object's attribute dictionary. - The resulting list is sorted. For example: - -\bcode\begin{verbatim} ->>> import sys ->>> dir() -['sys'] ->>> dir(sys) -['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout'] ->>> -\end{verbatim}\ecode -\end{funcdesc} - -\begin{funcdesc}{divmod}{a\, b} - Take two numbers as arguments and return a pair of integers - consisting of their integer quotient and remainder. With mixed - operand types, the rules for binary arithmetic operators apply. For - plain and long integers, the result is the same as - \code{(\var{a} / \var{b}, \var{a} \%{} \var{b})}. - For floating point numbers the result is the same as - \code{(math.floor(\var{a} / \var{b}), \var{a} \%{} \var{b})}. -\end{funcdesc} - -\begin{funcdesc}{eval}{expression\optional{\, globals\optional{\, locals}}} - The arguments are a string and two optional dictionaries. The - \var{expression} argument is parsed and evaluated as a Python - expression (technically speaking, a condition list) using the - \var{globals} and \var{locals} dictionaries as global and local name - space. If the \var{locals} dictionary is omitted it defaults to - the \var{globals} dictionary. If both dictionaries are omitted, the - expression is executed in the environment where \code{eval} is - called. The return value is the result of the evaluated expression. - Syntax errors are reported as exceptions. Example: - -\bcode\begin{verbatim} ->>> x = 1 ->>> print eval('x+1') -2 ->>> -\end{verbatim}\ecode - - This function can also be used to execute arbitrary code objects - (e.g.\ created by \code{compile()}). In this case pass a code - object instead of a string. The code object must have been compiled - passing \code{'eval'} to the \var{kind} argument. - - Hints: dynamic execution of statements is supported by the - \code{exec} statement. Execution of statements from a file is - supported by the \code{execfile()} function. The \code{globals()} - and \code{locals()} functions returns the current global and local - dictionary, respectively, which may be useful - to pass around for use by \code{eval()} or \code{execfile()}. - -\end{funcdesc} - -\begin{funcdesc}{execfile}{file\optional{\, globals\optional{\, locals}}} - This function is similar to the - \code{exec} statement, but parses a file instead of a string. It is - different from the \code{import} statement in that it does not use - the module administration --- it reads the file unconditionally and - does not create a new module.\footnote{It is used relatively rarely - so does not warrant being made into a statement.} - - The arguments are a file name and two optional dictionaries. The - file is parsed and evaluated as a sequence of Python statements - (similarly to a module) using the \var{globals} and \var{locals} - dictionaries as global and local name space. If the \var{locals} - dictionary is omitted it defaults to the \var{globals} dictionary. - If both dictionaries are omitted, the expression is executed in the - environment where \code{execfile()} is called. The return value is - \code{None}. -\end{funcdesc} - -\begin{funcdesc}{filter}{function\, list} -Construct a list from those elements of \var{list} for which -\var{function} returns true. If \var{list} is a string or a tuple, -the result also has that type; otherwise it is always a list. If -\var{function} is \code{None}, the identity function is assumed, -i.e.\ all elements of \var{list} that are false (zero or empty) are -removed. -\end{funcdesc} - -\begin{funcdesc}{float}{x} - Convert a number to floating point. The argument may be a plain or - long integer or a floating point number. -\end{funcdesc} - -\begin{funcdesc}{getattr}{object\, name} - The arguments are an object and a string. The string must be the - name - of one of the object's attributes. The result is the value of that - attribute. For example, \code{getattr(\var{x}, '\var{foobar}')} is equivalent to - \code{\var{x}.\var{foobar}}. -\end{funcdesc} - -\begin{funcdesc}{globals}{} -Return a dictionary representing the current global symbol table. -This is always the dictionary of the current module (inside a -function or method, this is the module where it is defined, not the -module from which it is called). -\end{funcdesc} - -\begin{funcdesc}{hasattr}{object\, name} - The arguments are an object and a string. The result is 1 if the - string is the name of one of the object's attributes, 0 if not. - (This is implemented by calling \code{getattr(object, name)} and - seeing whether it raises an exception or not.) -\end{funcdesc} - -\begin{funcdesc}{hash}{object} - Return the hash value of the object (if it has one). Hash values - are 32-bit integers. They are used to quickly compare dictionary - keys during a dictionary lookup. Numeric values that compare equal - have the same hash value (even if they are of different types, e.g. - 1 and 1.0). -\end{funcdesc} - -\begin{funcdesc}{hex}{x} - Convert an integer number (of any size) to a hexadecimal string. - The result is a valid Python expression. -\end{funcdesc} - -\begin{funcdesc}{id}{object} - Return the `identity' of an object. This is an integer which is - guaranteed to be unique and constant for this object during its - lifetime. (Two objects whose lifetimes are disjunct may have the - same id() value.) (Implementation note: this is the address of the - object.) -\end{funcdesc} - -\begin{funcdesc}{input}{\optional{prompt}} - Almost equivalent to \code{eval(raw_input(\var{prompt}))}. Like - \code{raw_input()}, the \var{prompt} argument is optional. The difference - is that a long input expression may be broken over multiple lines using - the backslash convention. -\end{funcdesc} - -\begin{funcdesc}{int}{x} - Convert a number to a plain integer. The argument may be a plain or - long integer or a floating point number. Conversion of floating - point numbers to integers is defined by the C semantics; normally - the conversion truncates towards zero.\footnote{This is ugly --- the - language definition should require truncation towards zero.} -\end{funcdesc} - -\begin{funcdesc}{len}{s} - Return the length (the number of items) of an object. The argument - may be a sequence (string, tuple or list) or a mapping (dictionary). -\end{funcdesc} - -\begin{funcdesc}{locals}{} -Return a dictionary representing the current local symbol table. -Inside a function, modifying this dictionary does not always have the -desired effect. -\end{funcdesc} - -\begin{funcdesc}{long}{x} - Convert a number to a long integer. The argument may be a plain or - long integer or a floating point number. -\end{funcdesc} - -\begin{funcdesc}{map}{function\, list\, ...} -Apply \var{function} to every item of \var{list} and return a list -of the results. If additional \var{list} arguments are passed, -\var{function} must take that many arguments and is applied to -the items of all lists in parallel; if a list is shorter than another -it is assumed to be extended with \code{None} items. If -\var{function} is \code{None}, the identity function is assumed; if -there are multiple list arguments, \code{map} returns a list -consisting of tuples containing the corresponding items from all lists -(i.e. a kind of transpose operation). The \var{list} arguments may be -any kind of sequence; the result is always a list. -\end{funcdesc} - -\begin{funcdesc}{max}{s} - Return the largest item of a non-empty sequence (string, tuple or - list). -\end{funcdesc} - -\begin{funcdesc}{min}{s} - Return the smallest item of a non-empty sequence (string, tuple or - list). -\end{funcdesc} - -\begin{funcdesc}{oct}{x} - Convert an integer number (of any size) to an octal string. The - result is a valid Python expression. -\end{funcdesc} - -\begin{funcdesc}{open}{filename\optional{\, mode\optional{\, bufsize}}} - Return a new file object (described earlier under Built-in Types). - The first two arguments are the same as for \code{stdio}'s - \code{fopen()}: \var{filename} is the file name to be opened, - \var{mode} indicates how the file is to be opened: \code{'r'} for - reading, \code{'w'} for writing (truncating an existing file), and - \code{'a'} opens it for appending (which on {\em some} {\UNIX} - systems means that {\em all} writes append to the end of the file, - regardless of the current seek position). - Modes \code{'r+'}, \code{'w+'} and - \code{'a+'} open the file for updating, provided the underlying - \code{stdio} library understands this. On systems that differentiate - between binary and text files, \code{'b'} appended to the mode opens - the file in binary mode. If the file cannot be opened, \code{IOError} - is raised. -If \var{mode} is omitted, it defaults to \code{'r'}. -The optional \var{bufsize} argument specifies the file's desired -buffer size: 0 means unbuffered, 1 means line buffered, any other -positive value means use a buffer of (approximately) that size. A -negative \var{bufsize} means to use the system default, which is -usually line buffered for for tty devices and fully buffered for other -files.% -\footnote{Specifying a buffer size currently has no effect on systems -that don't have \code{setvbuf()}. The interface to specify the buffer -size is not done using a method that calls \code{setvbuf()}, because -that may dump core when called after any I/O has been performed, and -there's no reliable way to determine whether this is the case.} -\end{funcdesc} - -\begin{funcdesc}{ord}{c} - Return the \ASCII{} value of a string of one character. E.g., - \code{ord('a')} returns the integer \code{97}. This is the inverse of - \code{chr()}. -\end{funcdesc} - -\begin{funcdesc}{pow}{x\, y\optional{\, z}} - Return \var{x} to the power \var{y}; if \var{z} is present, return - \var{x} to the power \var{y}, modulo \var{z} (computed more - efficiently than \code{pow(\var{x}, \var{y}) \% \var{z}}). - The arguments must have - numeric types. With mixed operand types, the rules for binary - arithmetic operators apply. The effective operand type is also the - type of the result; if the result is not expressible in this type, the - function raises an exception; e.g., \code{pow(2, -1)} or \code{pow(2, - 35000)} is not allowed. -\end{funcdesc} - -\begin{funcdesc}{range}{\optional{start\,} end\optional{\, step}} - This is a versatile function to create lists containing arithmetic - progressions. It is most often used in \code{for} loops. The - arguments must be plain integers. If the \var{step} argument is - omitted, it defaults to \code{1}. If the \var{start} argument is - omitted, it defaults to \code{0}. The full form returns a list of - plain integers \code{[\var{start}, \var{start} + \var{step}, - \var{start} + 2 * \var{step}, \ldots]}. If \var{step} is positive, - the last element is the largest \code{\var{start} + \var{i} * - \var{step}} less than \var{end}; if \var{step} is negative, the last - element is the largest \code{\var{start} + \var{i} * \var{step}} - greater than \var{end}. \var{step} must not be zero (or else an - exception is raised). Example: - -\bcode\begin{verbatim} ->>> range(10) -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ->>> range(1, 11) -[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ->>> range(0, 30, 5) -[0, 5, 10, 15, 20, 25] ->>> range(0, 10, 3) -[0, 3, 6, 9] ->>> range(0, -10, -1) -[0, -1, -2, -3, -4, -5, -6, -7, -8, -9] ->>> range(0) -[] ->>> range(1, 0) -[] ->>> -\end{verbatim}\ecode -\end{funcdesc} - -\begin{funcdesc}{raw_input}{\optional{prompt}} - If the \var{prompt} argument is present, it is written to standard output - without a trailing newline. The function then reads a line from input, - converts it to a string (stripping a trailing newline), and returns that. - When \EOF{} is read, \code{EOFError} is raised. Example: - -\bcode\begin{verbatim} ->>> s = raw_input('--> ') ---> Monty Python's Flying Circus ->>> s -"Monty Python's Flying Circus" ->>> -\end{verbatim}\ecode -\end{funcdesc} - -\begin{funcdesc}{reduce}{function\, list\optional{\, initializer}} -Apply the binary \var{function} to the items of \var{list} so as to -reduce the list to a single value. E.g., -\code{reduce(lambda x, y: x*y, \var{list}, 1)} returns the product of -the elements of \var{list}. The optional \var{initializer} can be -thought of as being prepended to \var{list} so as to allow reduction -of an empty \var{list}. The \var{list} arguments may be any kind of -sequence. -\end{funcdesc} - -\begin{funcdesc}{reload}{module} -Re-parse and re-initialize an already imported \var{module}. The -argument must be a module object, so it must have been successfully -imported before. This is useful if you have edited the module source -file using an external editor and want to try out the new version -without leaving the Python interpreter. The return value is the -module object (i.e.\ the same as the \var{module} argument). - -There are a number of caveats: - -If a module is syntactically correct but its initialization fails, the -first \code{import} statement for it does not bind its name locally, -but does store a (partially initialized) module object in -\code{sys.modules}. To reload the module you must first -\code{import} it again (this will bind the name to the partially -initialized module object) before you can \code{reload()} it. - -When a module is reloaded, its dictionary (containing the module's -global variables) is retained. Redefinitions of names will override -the old definitions, so this is generally not a problem. If the new -version of a module does not define a name that was defined by the old -version, the old definition remains. This feature can be used to the -module's advantage if it maintains a global table or cache of objects ---- with a \code{try} statement it can test for the table's presence -and skip its initialization if desired. - -It is legal though generally not very useful to reload built-in or -dynamically loaded modules, except for \code{sys}, \code{__main__} and -\code{__builtin__}. In certain cases, however, extension modules are -not designed to be initialized more than once, and may fail in -arbitrary ways when reloaded. - -If a module imports objects from another module using \code{from} -{\ldots} \code{import} {\ldots}, calling \code{reload()} for the other -module does not redefine the objects imported from it --- one way -around this is to re-execute the \code{from} statement, another is to -use \code{import} and qualified names (\var{module}.\var{name}) -instead. - -If a module instantiates instances of a class, reloading the module -that defines the class does not affect the method definitions of the -instances --- they continue to use the old class definition. The same -is true for derived classes. -\end{funcdesc} - -\begin{funcdesc}{repr}{object} -Return a string containing a printable representation of an object. -This is the same value yielded by conversions (reverse quotes). -It is sometimes useful to be able to access this operation as an -ordinary function. For many types, this function makes an attempt -to return a string that would yield an object with the same value -when passed to \code{eval()}. -\end{funcdesc} - -\begin{funcdesc}{round}{x\, n} - Return the floating point value \var{x} rounded to \var{n} digits - after the decimal point. If \var{n} is omitted, it defaults to zero. - The result is a floating point number. Values are rounded to the - closest multiple of 10 to the power minus \var{n}; if two multiples - are equally close, rounding is done away from 0 (so e.g. - \code{round(0.5)} is \code{1.0} and \code{round(-0.5)} is \code{-1.0}). -\end{funcdesc} - -\begin{funcdesc}{setattr}{object\, name\, value} - This is the counterpart of \code{getattr}. The arguments are an - object, a string and an arbitrary value. The string must be the name - of one of the object's attributes. The function assigns the value to - the attribute, provided the object allows it. For example, - \code{setattr(\var{x}, '\var{foobar}', 123)} is equivalent to - \code{\var{x}.\var{foobar} = 123}. -\end{funcdesc} - -\begin{funcdesc}{str}{object} -Return a string containing a nicely printable representation of an -object. For strings, this returns the string itself. The difference -with \code{repr(\var{object})} is that \code{str(\var{object})} does not -always attempt to return a string that is acceptable to \code{eval()}; -its goal is to return a printable string. -\end{funcdesc} - -\begin{funcdesc}{tuple}{sequence} -Return a tuple whose items are the same and in the same order as -\var{sequence}'s items. If \var{sequence} is alread a tuple, it -is returned unchanged. For instance, \code{tuple('abc')} returns -returns \code{('a', 'b', 'c')} and \code{tuple([1, 2, 3])} returns -\code{(1, 2, 3)}. -\end{funcdesc} - -\begin{funcdesc}{type}{object} -Return the type of an \var{object}. The return value is a type -object. The standard module \code{types} defines names for all -built-in types. -\stmodindex{types} -\obindex{type} -For instance: - -\bcode\begin{verbatim} ->>> import types ->>> if type(x) == types.StringType: print "It's a string" -\end{verbatim}\ecode -\end{funcdesc} - -\begin{funcdesc}{vars}{\optional{object}} -Without arguments, return a dictionary corresponding to the current -local symbol table. With a module, class or class instance object as -argument (or anything else that has a \code{__dict__} attribute), -returns a dictionary corresponding to the object's symbol table. -The returned dictionary should not be modified: the effects on the -corresponding symbol table are undefined.% -\footnote{In the current implementation, local variable bindings -cannot normally be affected this way, but variables retrieved from -other scopes (e.g. modules) can be. This may change.} -\end{funcdesc} - -\begin{funcdesc}{xrange}{\optional{start\,} end\optional{\, step}} -This function is very similar to \code{range()}, but returns an -``xrange object'' instead of a list. This is an opaque sequence type -which yields the same values as the corresponding list, without -actually storing them all simultaneously. The advantage of -\code{xrange()} over \code{range()} is minimal (since \code{xrange()} -still has to create the values when asked for them) except when a very -large range is used on a memory-starved machine (e.g. MS-DOS) or when all -of the range's elements are never used (e.g. when the loop is usually -terminated with \code{break}). -\end{funcdesc} diff --git a/Doc/libgdbm.tex b/Doc/libgdbm.tex deleted file mode 100644 index 96be1653e4..0000000000 --- a/Doc/libgdbm.tex +++ /dev/null @@ -1,8 +0,0 @@ -\section{Built-in Module \sectcode{gdbm}} -\bimodindex{gdbm} - -This module is nearly identical to the \code{dbm} module, but uses -GDBM instead. Its interface is identical, and not repeated here. - -Warning: the file formats created by gdbm and dbm are incompatible. -\bimodindex{dbm} diff --git a/Doc/libgetopt.tex b/Doc/libgetopt.tex deleted file mode 100644 index 3f9592aa32..0000000000 --- a/Doc/libgetopt.tex +++ /dev/null @@ -1,56 +0,0 @@ -\section{Standard Module \sectcode{getopt}} - -\stmodindex{getopt} -This module helps scripts to parse the command line arguments in -\code{sys.argv}. -It uses the same conventions as the \UNIX{} -\code{getopt()} -function (including the special meanings of arguments of the form -\samp{-} and \samp{--}). -It defines the function -\code{getopt.getopt(args, options)} -and the exception -\code{getopt.error}. - -The first argument to -\code{getopt()} -is the argument list passed to the script with its first element -chopped off (i.e., -\code{sys.argv[1:]}). -The second argument is the string of option letters that the -script wants to recognize, with options that require an argument -followed by a colon (i.e., the same format that \UNIX{} -\code{getopt()} -uses). -The return value consists of two elements: the first is a list of -option-and-value pairs; the second is the list of program arguments -left after the option list was stripped (this is a trailing slice of the -first argument). -Each option-and-value pair returned has the option as its first element, -prefixed with a hyphen (e.g., -\code{'-x'}), -and the option argument as its second element, or an empty string if the -option has no argument. -The options occur in the list in the same order in which they were -found, thus allowing multiple occurrences. -Example: - -\bcode\begin{verbatim} ->>> import getopt, string ->>> args = string.split('-a -b -cfoo -d bar a1 a2') ->>> args -['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] ->>> optlist, args = getopt.getopt(args, 'abc:d:') ->>> optlist -[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] ->>> args -['a1', 'a2'] ->>> -\end{verbatim}\ecode - -The exception -\code{getopt.error = 'getopt error'} -is raised when an unrecognized option is found in the argument list or -when an option requiring an argument is given none. -The argument to the exception is a string indicating the cause of the -error. diff --git a/Doc/libgl.tex b/Doc/libgl.tex deleted file mode 100644 index c32ea6f581..0000000000 --- a/Doc/libgl.tex +++ /dev/null @@ -1,198 +0,0 @@ -\section{Built-in Module \sectcode{gl}} -\bimodindex{gl} - -This module provides access to the Silicon Graphics -{\em Graphics Library}. -It is available only on Silicon Graphics machines. - -\strong{Warning:} -Some illegal calls to the GL library cause the Python interpreter to dump -core. -In particular, the use of most GL calls is unsafe before the first -window is opened. - -The module is too large to document here in its entirety, but the -following should help you to get started. -The parameter conventions for the C functions are translated to Python as -follows: - -\begin{itemize} -\item -All (short, long, unsigned) int values are represented by Python -integers. -\item -All float and double values are represented by Python floating point -numbers. -In most cases, Python integers are also allowed. -\item -All arrays are represented by one-dimensional Python lists. -In most cases, tuples are also allowed. -\item -\begin{sloppypar} -All string and character arguments are represented by Python strings, -for instance, -\code{winopen('Hi There!')} -and -\code{rotate(900, 'z')}. -\end{sloppypar} -\item -All (short, long, unsigned) integer arguments or return values that are -only used to specify the length of an array argument are omitted. -For example, the C call - -\bcode\begin{verbatim} -lmdef(deftype, index, np, props) -\end{verbatim}\ecode - -is translated to Python as - -\bcode\begin{verbatim} -lmdef(deftype, index, props) -\end{verbatim}\ecode - -\item -Output arguments are omitted from the argument list; they are -transmitted as function return values instead. -If more than one value must be returned, the return value is a tuple. -If the C function has both a regular return value (that is not omitted -because of the previous rule) and an output argument, the return value -comes first in the tuple. -Examples: the C call - -\bcode\begin{verbatim} -getmcolor(i, &red, &green, &blue) -\end{verbatim}\ecode - -is translated to Python as - -\bcode\begin{verbatim} -red, green, blue = getmcolor(i) -\end{verbatim}\ecode - -\end{itemize} - -The following functions are non-standard or have special argument -conventions: - -\renewcommand{\indexsubitem}{(in module gl)} -\begin{funcdesc}{varray}{argument} -%JHXXX the argument-argument added -Equivalent to but faster than a number of -\code{v3d()} -calls. -The \var{argument} is a list (or tuple) of points. -Each point must be a tuple of coordinates -\code{(\var{x}, \var{y}, \var{z})} or \code{(\var{x}, \var{y})}. -The points may be 2- or 3-dimensional but must all have the -same dimension. -Float and int values may be mixed however. -The points are always converted to 3D double precision points -by assuming \code{\var{z} = 0.0} if necessary (as indicated in the man page), -and for each point -\code{v3d()} -is called. -\end{funcdesc} - -\begin{funcdesc}{nvarray}{} -Equivalent to but faster than a number of -\code{n3f} -and -\code{v3f} -calls. -The argument is an array (list or tuple) of pairs of normals and points. -Each pair is a tuple of a point and a normal for that point. -Each point or normal must be a tuple of coordinates -\code{(\var{x}, \var{y}, \var{z})}. -Three coordinates must be given. -Float and int values may be mixed. -For each pair, -\code{n3f()} -is called for the normal, and then -\code{v3f()} -is called for the point. -\end{funcdesc} - -\begin{funcdesc}{vnarray}{} -Similar to -\code{nvarray()} -but the pairs have the point first and the normal second. -\end{funcdesc} - -\begin{funcdesc}{nurbssurface}{s_k\, t_k\, ctl\, s_ord\, t_ord\, type} -% XXX s_k[], t_k[], ctl[][] -%\itembreak -Defines a nurbs surface. -The dimensions of -\code{\var{ctl}[][]} -are computed as follows: -\code{[len(\var{s_k}) - \var{s_ord}]}, -\code{[len(\var{t_k}) - \var{t_ord}]}. -\end{funcdesc} - -\begin{funcdesc}{nurbscurve}{knots\, ctlpoints\, order\, type} -Defines a nurbs curve. -The length of ctlpoints is -\code{len(\var{knots}) - \var{order}}. -\end{funcdesc} - -\begin{funcdesc}{pwlcurve}{points\, type} -Defines a piecewise-linear curve. -\var{points} -is a list of points. -\var{type} -must be -\code{N_ST}. -\end{funcdesc} - -\begin{funcdesc}{pick}{n} -\funcline{select}{n} -The only argument to these functions specifies the desired size of the -pick or select buffer. -\end{funcdesc} - -\begin{funcdesc}{endpick}{} -\funcline{endselect}{} -These functions have no arguments. -They return a list of integers representing the used part of the -pick/select buffer. -No method is provided to detect buffer overrun. -\end{funcdesc} - -Here is a tiny but complete example GL program in Python: - -\bcode\begin{verbatim} -import gl, GL, time - -def main(): - gl.foreground() - gl.prefposition(500, 900, 500, 900) - w = gl.winopen('CrissCross') - gl.ortho2(0.0, 400.0, 0.0, 400.0) - gl.color(GL.WHITE) - gl.clear() - gl.color(GL.RED) - gl.bgnline() - gl.v2f(0.0, 0.0) - gl.v2f(400.0, 400.0) - gl.endline() - gl.bgnline() - gl.v2f(400.0, 0.0) - gl.v2f(0.0, 400.0) - gl.endline() - time.sleep(5) - -main() -\end{verbatim}\ecode - -\section{Standard Modules \sectcode{GL} and \sectcode{DEVICE}} -\nodename{GL and DEVICE} -\stmodindex{GL} -\stmodindex{DEVICE} - -These modules define the constants used by the Silicon Graphics -{\em Graphics Library} -that C programmers find in the header files -\file{<gl/gl.h>} -and -\file{<gl/device.h>}. -Read the module source files for details. diff --git a/Doc/libgopherlib.tex b/Doc/libgopherlib.tex deleted file mode 100644 index e94e1f9c6c..0000000000 --- a/Doc/libgopherlib.tex +++ /dev/null @@ -1,30 +0,0 @@ -\section{Standard Module \sectcode{gopherlib}} -\stmodindex{gopherlib} - -\renewcommand{\indexsubitem}{(in module gopherlib)} - -This module provides a minimal implementation of client side of the -the Gopher protocol. It is used by the module \code{urllib} to handle -URLs that use the Gopher protocol. - -The module defines the following functions: - -\begin{funcdesc}{send_selector}{selector\, host\optional{\, port}} -Send a \var{selector} string to the gopher server at \var{host} and -\var{port} (default 70). Return an open file object from which the -returned document can be read. -\end{funcdesc} - -\begin{funcdesc}{send_query}{selector\, query\, host\optional{\, port}} -Send a \var{selector} string and a \var{query} string to a gopher -server at \var{host} and \var{port} (default 70). Return an open file -object from which the returned document can be read. -\end{funcdesc} - -Note that the data returned by the Gopher server can be of any type, -depending on the first character of the selector string. If the data -is text (first character of the selector is \samp{0}), lines are -terminated by CRLF, and the data is terminated by a line consisting of -a single \samp{.}, and a leading \samp{.} should be stripped from -lines that begin with \samp{..}. Directory listings (first charactger -of the selector is \samp{1}) are transferred using the same protocol. diff --git a/Doc/libgrp.tex b/Doc/libgrp.tex deleted file mode 100644 index 90a2ed3339..0000000000 --- a/Doc/libgrp.tex +++ /dev/null @@ -1,32 +0,0 @@ -\section{Built-in Module \sectcode{grp}} - -\bimodindex{grp} -This module provides access to the \UNIX{} group database. -It is available on all \UNIX{} versions. - -Group database entries are reported as 4-tuples containing the -following items from the group database (see \file{<grp.h>}), in order: -\code{gr_name}, -\code{gr_passwd}, -\code{gr_gid}, -\code{gr_mem}. -The gid is an integer, name and password are strings, and the member -list is a list of strings. -(Note that most users are not explicitly listed as members of the -group they are in according to the password database.) -An exception is raised if the entry asked for cannot be found. - -It defines the following items: - -\renewcommand{\indexsubitem}{(in module grp)} -\begin{funcdesc}{getgrgid}{gid} -Return the group database entry for the given numeric group ID. -\end{funcdesc} - -\begin{funcdesc}{getgrnam}{name} -Return the group database entry for the given group name. -\end{funcdesc} - -\begin{funcdesc}{getgrall}{} -Return a list of all available group entries, in arbitrary order. -\end{funcdesc} diff --git a/Doc/libhtmllib.tex b/Doc/libhtmllib.tex deleted file mode 100644 index aeb4ce9c56..0000000000 --- a/Doc/libhtmllib.tex +++ /dev/null @@ -1,274 +0,0 @@ -\section{Standard Module \sectcode{htmllib}} -\stmodindex{htmllib} -\index{HTML} -\index{hypertext} - -\renewcommand{\indexsubitem}{(in module htmllib)} - -This module defines a number of classes which can serve as a basis for -parsing text files formatted in HTML (HyperText Mark-up Language). -The classes are not directly concerned with I/O --- the have to be fed -their input in string form, and will make calls to methods of a -``formatter'' object in order to produce output. The classes are -designed to be used as base classes for other classes in order to add -functionality, and allow most of their methods to be extended or -overridden. In turn, the classes are derived from and extend the -class \code{SGMLParser} defined in module \code{sgmllib}. -\index{SGML} -\stmodindex{sgmllib} -\ttindex{SGMLParser} -\index{formatter} - -The following is a summary of the interface defined by -\code{sgmllib.SGMLParser}: - -\begin{itemize} - -\item -The interface to feed data to an instance is through the \code{feed()} -method, which takes a string argument. This can be called with as -little or as much text at a time as desired; -\code{p.feed(a); p.feed(b)} has the same effect as \code{p.feed(a+b)}. -When the data contains complete -HTML elements, these are processed immediately; incomplete elements -are saved in a buffer. To force processing of all unprocessed data, -call the \code{close()} method. - -Example: to parse the entire contents of a file, do\\ -\code{parser.feed(open(file).read()); parser.close()}. - -\item -The interface to define semantics for HTML tags is very simple: derive -a class and define methods called \code{start_\var{tag}()}, -\code{end_\var{tag}()}, or \code{do_\var{tag}()}. The parser will -call these at appropriate moments: \code{start_\var{tag}} or -\code{do_\var{tag}} is called when an opening tag of the form -\code{<\var{tag} ...>} is encountered; \code{end_\var{tag}} is called -when a closing tag of the form \code{<\var{tag}>} is encountered. If -an opening tag requires a corresponding closing tag, like \code{<H1>} -... \code{</H1>}, the class should define the \code{start_\var{tag}} -method; if a tag requires no closing tag, like \code{<P>}, the class -should define the \code{do_\var{tag}} method. - -\end{itemize} - -The module defines the following classes: - -\begin{funcdesc}{HTMLParser}{} -This is the most basic HTML parser class. It defines one additional -entity name over the names defined by the \code{SGMLParser} base -class, \code{\&bullet;}. It also defines handlers for the following -tags: \code{<LISTING>...</LISTING>}, \code{<XMP>...</XMP>}, and -\code{<PLAINTEXT>} (the latter is terminated only by end of file). -\end{funcdesc} - -\begin{funcdesc}{CollectingParser}{} -This class, derived from \code{HTMLParser}, collects various useful -bits of information from the HTML text. To this end it defines -additional handlers for the following tags: \code{<A>...</A>}, -\code{<HEAD>...</HEAD>}, \code{<BODY>...</BODY>}, -\code{<TITLE>...</TITLE>}, \code{<NEXTID>}, and \code{<ISINDEX>}. -\end{funcdesc} - -\begin{funcdesc}{FormattingParser}{formatter\, stylesheet} -This class, derived from \code{CollectingParser}, interprets a wide -selection of HTML tags so it can produce formatted output from the -parsed data. It is initialized with two objects, a \var{formatter} -which should define a number of methods to format text into -paragraphs, and a \var{stylesheet} which defines a number of static -parameters for the formatting process. Formatters and style sheets -are documented later in this section. -\index{formatter} -\index{style sheet} -\end{funcdesc} - -\begin{funcdesc}{AnchoringParser}{formatter\, stylesheet} -This class, derived from \code{FormattingParser}, extends the handling -of the \code{<A>...</A>} tag pair to call the formatter's -\code{bgn_anchor()} and \code{end_anchor()} methods. This allows the -formatter to display the anchor in a different font or color, etc. -\end{funcdesc} - -Instances of \code{CollectingParser} (and thus also instances of -\code{FormattingParser} and \code{AnchoringParser}) have the following -instance variables: - -\begin{datadesc}{anchornames} -A list of the values of the \code{NAME} attributes of the \code{<A>} -tags encountered. -\end{datadesc} - -\begin{datadesc}{anchors} -A list of the values of \code{HREF} attributes of the \code{<A>} tags -encountered. -\end{datadesc} - -\begin{datadesc}{anchortypes} -A list of the values of the \code{TYPE} attributes of the \code{<A>} -tags encountered. -\end{datadesc} - -\begin{datadesc}{inanchor} -Outside an \code{<A>...</A>} tag pair, this is zero. Inside such a -pair, it is a unique integer, which is positive if the anchor has a -\code{HREF} attribute, negative if it hasn't. Its absolute value is -one more than the index of the anchor in the \code{anchors}, -\code{anchornames} and \code{anchortypes} lists. -\end{datadesc} - -\begin{datadesc}{isindex} -True if the \code{<ISINDEX>} tag has been encountered. -\end{datadesc} - -\begin{datadesc}{nextid} -The attribute list of the last \code{<NEXTID>} tag encountered, or -an empty list if none. -\end{datadesc} - -\begin{datadesc}{title} -The text inside the last \code{<TITLE>...</TITLE>} tag pair, or -\code{''} if no title has been encountered yet. -\end{datadesc} - -The \code{anchors}, \code{anchornames} and \code{anchortypes} lists -are ``parallel arrays'': items in these lists with the same index -pertain to the same anchor. Missing attributes default to the empty -string. Anchors with neither a \code{HREF} nor a \code{NAME} -attribute are not entered in these lists at all. - -The module also defines a number of style sheet classes. These should -never be instantiated --- their class variables are the only behavior -required. Note that style sheets are specifically designed for a -particular formatter implementation. The currently defined style -sheets are: -\index{style sheet} - -\begin{datadesc}{NullStylesheet} -A style sheet for use on a dumb output device such as an \ASCII{} -terminal. -\end{datadesc} - -\begin{datadesc}{X11Stylesheet} -A style sheet for use with an X11 server. -\end{datadesc} - -\begin{datadesc}{MacStylesheet} -A style sheet for use on Apple Macintosh computers. -\end{datadesc} - -\begin{datadesc}{StdwinStylesheet} -A style sheet for use with the \code{stdwin} module; it is an alias -for either \code{X11Stylesheet} or \code{MacStylesheet}. -\bimodindex{stdwin} -\end{datadesc} - -\begin{datadesc}{GLStylesheet} -A style sheet for use with the SGI Graphics Library and its font -manager (the SGI-specific built-in modules \code{gl} and \code{fm}). -\bimodindex{gl} -\bimodindex{fm} -\end{datadesc} - -Style sheets have the following class variables: - -\begin{datadesc}{stdfontset} -A list of up to four font definititions, respectively for the roman, -italic, bold and constant-width variant of a font for normal text. If -the list contains less than four font definitions, the last item is -used as the default for missing items. The type of a font definition -depends on the formatter in use; its only use is as a parameter to the -formatter's \code{setfont()} method. -\end{datadesc} - -\begin{datadesc}{h1fontset} -\dataline{h2fontset} -\dataline{h3fontset} -The font set used for various headers (text inside \code{<H1>...</H1>} -tag pairs etc.). -\end{datadesc} - -\begin{datadesc}{stdindent} -The indentation of normal text. This is measured in the ``native'' -units of the formatter in use; for some formatters these are -characters, for others (especially those that actually support -variable-spacing fonts) in pixels or printer points. -\end{datadesc} - -\begin{datadesc}{ddindent} -The indentation used for the first level of \code{<DD>} tags. -\end{datadesc} - -\begin{datadesc}{ulindent} -The indentation used for the first level of \code{<UL>} tags. -\end{datadesc} - -\begin{datadesc}{h1indent} -The indentation used for level 1 headers. -\end{datadesc} - -\begin{datadesc}{h2indent} -The indentation used for level 2 headers. -\end{datadesc} - -\begin{datadesc}{literalindent} -The indentation used for literal text (text inside -\code{<PRE>...</PRE>} and similar tag pairs). -\end{datadesc} - -Although no documented implementation of a formatter exists, the -\code{FormattingParser} class assumes that formatters have a -certain interface. This interface requires the following methods: -\index{formatter} - -\begin{funcdesc}{setfont}{fontspec} -Set the font to be used subsequently. The \var{fontspec} argument is -an item in a style sheet's font set. -\end{funcdesc} - -\begin{funcdesc}{flush}{} -Finish the current line, if not empty, and begin a new one. -\end{funcdesc} - -\begin{funcdesc}{setleftindent}{n} -Set the left indentation of the following lines to \var{n} units. -\end{funcdesc} - -\begin{funcdesc}{needvspace}{n} -Require at least \var{n} blank lines before the next line. Implies -\code{flush()}. -\end{funcdesc} - -\begin{funcdesc}{addword}{word\, space} -Add a \var{word} to the current paragraph, followed by \var{space} -spaces. -\end{funcdesc} - -\begin{datadesc}{nospace} -If this instance variable is true, empty words should be ignored by -\code{addword}. It should be set to false after a non-empty word has -been added. -\end{datadesc} - -\begin{funcdesc}{setjust}{justification} -Set the justification of the current paragraph. The -\var{justification} can be \code{'c'} (center), \code{'l'} (left -justified), \code{'r'} (right justified) or \code{'lr'} (left and -right justified). -\end{funcdesc} - -\begin{funcdesc}{bgn_anchor}{id} -Begin an anchor. The \var{id} parameter is the value of the parser's -\code{inanchor} attribute. -\end{funcdesc} - -\begin{funcdesc}{end_anchor}{id} -End an anchor. The \var{id} parameter is the value of the parser's -\code{inanchor} attribute. -\end{funcdesc} - -A sample formatter implementation can be found in the module -\code{fmt}, which in turn uses the module \code{Para}. These modules are -not intended as standard library modules; they are available as an -example of how to write a formatter. -\ttindex{fmt} -\ttindex{Para} diff --git a/Doc/libhttplib.tex b/Doc/libhttplib.tex deleted file mode 100644 index d2e242092b..0000000000 --- a/Doc/libhttplib.tex +++ /dev/null @@ -1,127 +0,0 @@ -\section{Standard Module \sectcode{httplib}} -\stmodindex{httplib} -\index{HTTP} - -\renewcommand{\indexsubitem}{(in module httplib)} - -This module defines a class which implements the client side of the -HTTP protocol. It is normally not used directly --- the module -\code{urllib} uses it to handle URLs that use HTTP. -\stmodindex{urllib} - -The module defines one class, \code{HTTP}. An \code{HTTP} instance -represents one transaction with an HTTP server. It should be -instantiated passing it a host and optional port number. If no port -number is passed, the port is extracted from the host string if it has -the form \code{host:port}, else the default HTTP port (80) is used. -If no host is passed, no connection is made, and the \code{connect} -method should be used to connect to a server. For example, the -following calls all create instances that connect to the server at the -same host and port: - -\begin{verbatim} ->>> h1 = httplib.HTTP('www.cwi.nl') ->>> h2 = httplib.HTTP('www.cwi.nl:80') ->>> h3 = httplib.HTTP('www.cwi.nl', 80) -\end{verbatim} - -Once an \code{HTTP} instance has been connected to an HTTP server, it -should be used as follows: - -\begin{enumerate} - -\item[1.] Make exactly one call to the \code{putrequest()} method. - -\item[2.] Make zero or more calls to the \code{putheader()} method. - -\item[3.] Call the \code{endheaders()} method (this can be omitted if -step 4 makes no calls). - -\item[4.] Optional calls to the \code{send()} method. - -\item[5.] Call the \code{getreply()} method. - -\item[6.] Call the \code{getfile()} method and read the data off the -file object that it returns. - -\end{enumerate} - -\subsection{HTTP Objects} - -\code{HTTP} instances have the following methods: - -\renewcommand{\indexsubitem}{(HTTP method)} - -\begin{funcdesc}{set_debuglevel}{level} -Set the debugging level (the amount of debugging output printed). -The default debug level is \code{0}, meaning no debugging output is -printed. -\end{funcdesc} - -\begin{funcdesc}{connect}{host\optional{\, port}} -Connect to the server given by \var{host} and \var{port}. See the -intro for the default port. This should be called directly only if -the instance was instantiated without passing a host. -\end{funcdesc} - -\begin{funcdesc}{send}{data} -Send data to the server. This should be used directly only after the -\code{endheaders()} method has been called and before -\code{getreply()} has been called. -\end{funcdesc} - -\begin{funcdesc}{putrequest}{request\, selector} -This should be the first call after the connection to the server has -been made. It sends a line to the server consisting of the -\var{request} string, the \var{selector} string, and the HTTP version -(\code{HTTP/1.0}). -\end{funcdesc} - -\begin{funcdesc}{putheader}{header\, argument\optional{\, ...}} -Send an RFC-822 style header to the server. It sends a line to the -server consisting of the header, a colon and a space, and the first -argument. If more arguments are given, continuation lines are sent, -each consisting of a tab and an argument. -\end{funcdesc} - -\begin{funcdesc}{endheaders}{} -Send a blank line to the server, signalling the end of the headers. -\end{funcdesc} - -\begin{funcdesc}{getreply}{} -Complete the request by shutting down the sending end of the socket, -read the reply from the server, and return a triple (\var{replycode}, -\var{message}, \var{headers}). Here \var{replycode} is the integer -reply code from the request (e.g.\ \code{200} if the request was -handled properly); \var{message} is the message string corresponding -to the reply code; and \var{header} is an instance of the class -\code{rfc822.Message} containing the headers received from the server. -See the description of the \code{rfc822} module. -\stmodindex{rfc822} -\end{funcdesc} - -\begin{funcdesc}{getfile}{} -Return a file object from which the data returned by the server can be -read, using the \code{read()}, \code{readline()} or \code{readlines()} -methods. -\end{funcdesc} - -\subsection{Example} -\nodename{HTTP Example} - -Here is an example session: - -\begin{verbatim} ->>> import httplib ->>> h = httplib.HTTP('www.cwi.nl') ->>> h.putrequest('GET', '/index.html') ->>> h.putheader('Accept', 'text/html') ->>> h.putheader('Accept', 'text/plain') ->>> h.endheaders() ->>> errcode, errmsg, headers = h.getreply() ->>> print errcode # Should be 200 ->>> f = h.getfile() ->>> data f.read() # Get the raw HTML ->>> f.close() ->>> -\end{verbatim} diff --git a/Doc/libimageop.tex b/Doc/libimageop.tex deleted file mode 100644 index 4e151170d0..0000000000 --- a/Doc/libimageop.tex +++ /dev/null @@ -1,86 +0,0 @@ -\section{Built-in Module \sectcode{imageop}} -\bimodindex{imageop} - -The \code{imageop} module contains some useful operations on images. -It operates on images consisting of 8 or 32 bit pixels -stored in Python strings. This is the same format as used -by \code{gl.lrectwrite} and the \code{imgfile} module. - -The module defines the following variables and functions: - -\renewcommand{\indexsubitem}{(in module imageop)} - -\begin{excdesc}{error} -This exception is raised on all errors, such as unknown number of bits -per pixel, etc. -\end{excdesc} - - -\begin{funcdesc}{crop}{image\, psize\, width\, height\, x0\, y0\, x1\, y1} -Return the selected part of \var{image}, which should by -\var{width} by \var{height} in size and consist of pixels of -\var{psize} bytes. \var{x0}, \var{y0}, \var{x1} and \var{y1} are like -the \code{lrectread} parameters, i.e.\ the boundary is included in the -new image. The new boundaries need not be inside the picture. Pixels -that fall outside the old image will have their value set to zero. If -\var{x0} is bigger than \var{x1} the new image is mirrored. The same -holds for the y coordinates. -\end{funcdesc} - -\begin{funcdesc}{scale}{image\, psize\, width\, height\, newwidth\, newheight} -Return \var{image} scaled to size \var{newwidth} by \var{newheight}. -No interpolation is done, scaling is done by simple-minded pixel -duplication or removal. Therefore, computer-generated images or -dithered images will not look nice after scaling. -\end{funcdesc} - -\begin{funcdesc}{tovideo}{image\, psize\, width\, height} -Run a vertical low-pass filter over an image. It does so by computing -each destination pixel as the average of two vertically-aligned source -pixels. The main use of this routine is to forestall excessive -flicker if the image is displayed on a video device that uses -interlacing, hence the name. -\end{funcdesc} - -\begin{funcdesc}{grey2mono}{image\, width\, height\, threshold} -Convert a 8-bit deep greyscale image to a 1-bit deep image by -tresholding all the pixels. The resulting image is tightly packed and -is probably only useful as an argument to \code{mono2grey}. -\end{funcdesc} - -\begin{funcdesc}{dither2mono}{image\, width\, height} -Convert an 8-bit greyscale image to a 1-bit monochrome image using a -(simple-minded) dithering algorithm. -\end{funcdesc} - -\begin{funcdesc}{mono2grey}{image\, width\, height\, p0\, p1} -Convert a 1-bit monochrome image to an 8 bit greyscale or color image. -All pixels that are zero-valued on input get value \var{p0} on output -and all one-value input pixels get value \var{p1} on output. To -convert a monochrome black-and-white image to greyscale pass the -values \code{0} and \code{255} respectively. -\end{funcdesc} - -\begin{funcdesc}{grey2grey4}{image\, width\, height} -Convert an 8-bit greyscale image to a 4-bit greyscale image without -dithering. -\end{funcdesc} - -\begin{funcdesc}{grey2grey2}{image\, width\, height} -Convert an 8-bit greyscale image to a 2-bit greyscale image without -dithering. -\end{funcdesc} - -\begin{funcdesc}{dither2grey2}{image\, width\, height} -Convert an 8-bit greyscale image to a 2-bit greyscale image with -dithering. As for \code{dither2mono}, the dithering algorithm is -currently very simple. -\end{funcdesc} - -\begin{funcdesc}{grey42grey}{image\, width\, height} -Convert a 4-bit greyscale image to an 8-bit greyscale image. -\end{funcdesc} - -\begin{funcdesc}{grey22grey}{image\, width\, height} -Convert a 2-bit greyscale image to an 8-bit greyscale image. -\end{funcdesc} diff --git a/Doc/libimgfile.tex b/Doc/libimgfile.tex deleted file mode 100644 index 1e8b2aaa9b..0000000000 --- a/Doc/libimgfile.tex +++ /dev/null @@ -1,63 +0,0 @@ -\section{Built-in Module \sectcode{imgfile}} -\bimodindex{imgfile} - -The imgfile module allows python programs to access SGI imglib image -files (also known as \file{.rgb} files). The module is far from -complete, but is provided anyway since the functionality that there is -is enough in some cases. Currently, colormap files are not supported. - -The module defines the following variables and functions: - -\renewcommand{\indexsubitem}{(in module imgfile)} -\begin{excdesc}{error} -This exception is raised on all errors, such as unsupported file type, etc. -\end{excdesc} - -\begin{funcdesc}{getsizes}{file} -This function returns a tuple \code{(\var{x}, \var{y}, \var{z})} where -\var{x} and \var{y} are the size of the image in pixels and -\var{z} is the number of -bytes per pixel. Only 3 byte RGB pixels and 1 byte greyscale pixels -are currently supported. -\end{funcdesc} - -\begin{funcdesc}{read}{file} -This function reads and decodes the image on the specified file, and -returns it as a python string. The string has either 1 byte greyscale -pixels or 4 byte RGBA pixels. The bottom left pixel is the first in -the string. This format is suitable to pass to \code{gl.lrectwrite}, -for instance. -\end{funcdesc} - -\begin{funcdesc}{readscaled}{file\, x\, y\, filter\optional{\, blur}} -This function is identical to read but it returns an image that is -scaled to the given \var{x} and \var{y} sizes. If the \var{filter} and -\var{blur} parameters are omitted scaling is done by -simply dropping or duplicating pixels, so the result will be less than -perfect, especially for computer-generated images. - -Alternatively, you can specify a filter to use to smoothen the image -after scaling. The filter forms supported are \code{'impulse'}, -\code{'box'}, \code{'triangle'}, \code{'quadratic'} and -\code{'gaussian'}. If a filter is specified \var{blur} is an optional -parameter specifying the blurriness of the filter. It defaults to \code{1.0}. - -\code{readscaled} makes no -attempt to keep the aspect ratio correct, so that is the users' -responsibility. -\end{funcdesc} - -\begin{funcdesc}{ttob}{flag} -This function sets a global flag which defines whether the scan lines -of the image are read or written from bottom to top (flag is zero, -compatible with SGI GL) or from top to bottom(flag is one, -compatible with X). The default is zero. -\end{funcdesc} - -\begin{funcdesc}{write}{file\, data\, x\, y\, z} -This function writes the RGB or greyscale data in \var{data} to image -file \var{file}. \var{x} and \var{y} give the size of the image, -\var{z} is 1 for 1 byte greyscale images or 3 for RGB images (which are -stored as 4 byte values of which only the lower three bytes are used). -These are the formats returned by \code{gl.lrectread}. -\end{funcdesc} diff --git a/Doc/libimp.tex b/Doc/libimp.tex deleted file mode 100644 index dbced97e31..0000000000 --- a/Doc/libimp.tex +++ /dev/null @@ -1,174 +0,0 @@ -\section{Built-in Module \sectcode{imp}} -\bimodindex{imp} -\index{import} - -This module provides an interface to the mechanisms used to implement -the \code{import} statement. It defines the following constants and -functions: - -\renewcommand{\indexsubitem}{(in module imp)} - -\begin{funcdesc}{get_magic}{} -Return the magic string value used to recognize byte-compiled code -files (``\code{.pyc} files''). -\end{funcdesc} - -\begin{funcdesc}{get_suffixes}{} -Return a list of triples, each describing a particular type of file. -Each triple has the form \code{(\var{suffix}, \var{mode}, -\var{type})}, where \var{suffix} is a string to be appended to the -module name to form the filename to search for, \var{mode} is the mode -string to pass to the built-in \code{open} function to open the file -(this can be \code{'r'} for text files or \code{'rb'} for binary -files), and \var{type} is the file type, which has one of the values -\code{PY_SOURCE}, \code{PY_COMPILED} or \code{C_EXTENSION}, defined -below. (System-dependent values may also be returned.) -\end{funcdesc} - -\begin{funcdesc}{find_module}{name\, \optional{path}} -Try to find the module \var{name} on the search path \var{path}. The -default \var{path} is \code{sys.path}. The return value is a triple -\code{(\var{file}, \var{pathname}, \var{description})} where -\var{file} is an open file object positioned at the beginning, -\var{pathname} is the pathname of the -file found, and \var{description} is a triple as contained in the list -returned by \code{get_suffixes} describing the kind of file found. -\end{funcdesc} - -\begin{funcdesc}{init_builtin}{name} -Initialize the built-in module called \var{name} and return its module -object. If the module was already initialized, it will be initialized -{\em again}. A few modules cannot be initialized twice --- attempting -to initialize these again will raise an \code{ImportError} exception. -If there is no -built-in module called \var{name}, \code{None} is returned. -\end{funcdesc} - -\begin{funcdesc}{init_frozen}{name} -Initialize the frozen module called \var{name} and return its module -object. If the module was already initialized, it will be initialized -{\em again}. If there is no frozen module called \var{name}, -\code{None} is returned. (Frozen modules are modules written in -Python whose compiled byte-code object is incorporated into a -custom-built Python interpreter by Python's \code{freeze} utility. -See \code{Tools/freeze} for now.) -\end{funcdesc} - -\begin{funcdesc}{is_builtin}{name} -Return \code{1} if there is a built-in module called \var{name} which can be -initialized again. Return \code{-1} if there is a built-in module -called \var{name} which cannot be initialized again (see -\code{init_builtin}). Return \code{0} if there is no built-in module -called \var{name}. -\end{funcdesc} - -\begin{funcdesc}{is_frozen}{name} -Return \code{1} if there is a frozen module (see \code{init_frozen}) -called \var{name}, \code{0} if there is no such module. -\end{funcdesc} - -\begin{funcdesc}{load_compiled}{name\, pathname\, \optional{file}} -Load and initialize a module implemented as a byte-compiled code file -and return its module object. If the module was already initialized, -it will be initialized {\em again}. The \var{name} argument is used -to create or access a module object. The \var{pathname} argument -points to the byte-compiled code file. The optional \var{file} -argument is the byte-compiled code file, open for reading in binary -mode, from the beginning --- if not given, the function opens -\var{pathname}. It must currently be a real file object, not a -user-defined class emulating a file. -\end{funcdesc} - -\begin{funcdesc}{load_dynamic}{name\, pathname\, \optional{file}} -Load and initialize a module implemented as a dynamically loadable -shared library and return its module object. If the module was -already initialized, it will be initialized {\em again}. Some modules -don't like that and may raise an exception. The \var{pathname} -argument must point to the shared library. The \var{name} argument is -used to construct the name of the initialization function: an external -C function called \code{init\var{name}()} in the shared library is -called. The optional \var{file} argment is ignored. (Note: using -shared libraries is highly system dependent, and not all systems -support it.) -\end{funcdesc} - -\begin{funcdesc}{load_source}{name\, pathname\, \optional{file}} -Load and initialize a module implemented as a Python source file and -return its module object. If the module was already initialized, it -will be initialized {\em again}. The \var{name} argument is used to -create or access a module object. The \var{pathname} argument points -to the source file. The optional \var{file} argument is the source -file, open for reading as text, from the beginning --- if not given, -the function opens \var{pathname}. It must currently be a real file -object, not a user-defined class emulating a file. Note that if a -properly matching byte-compiled file (with suffix \code{.pyc}) exists, -it will be used instead of parsing the given source file. -\end{funcdesc} - -\begin{funcdesc}{new_module}{name} -Return a new empty module object called \var{name}. This object is -{\em not} inserted in \code{sys.modules}. -\end{funcdesc} - -The following constants with integer values, defined in the module, -are used to indicate the search result of \code{imp.find_module}. - -\begin{datadesc}{SEARCH_ERROR} -The module was not found. -\end{datadesc} - -\begin{datadesc}{PY_SOURCE} -The module was found as a source file. -\end{datadesc} - -\begin{datadesc}{PY_COMPILED} -The module was found as a compiled code object file. -\end{datadesc} - -\begin{datadesc}{C_EXTENSION} -The module was found as dynamically loadable shared library. -\end{datadesc} - -\subsection{Examples} -The following function emulates the default import statement: - -\begin{verbatim} -import imp -import sys - -def __import__(name, globals=None, locals=None, fromlist=None): - # Fast path: see if the module has already been imported. - if sys.modules.has_key(name): - return sys.modules[name] - - # If any of the following calls raises an exception, - # there's a problem we can't handle -- let the caller handle it. - - # See if it's a built-in module. - m = imp.init_builtin(name) - if m: - return m - - # See if it's a frozen module. - m = imp.init_frozen(name) - if m: - return m - - # Search the default path (i.e. sys.path). - fp, pathname, (suffix, mode, type) = imp.find_module(name) - - # See what we got. - try: - if type == imp.C_EXTENSION: - return imp.load_dynamic(name, pathname) - if type == imp.PY_SOURCE: - return imp.load_source(name, pathname, fp) - if type == imp.PY_COMPILED: - return imp.load_compiled(name, pathname, fp) - - # Shouldn't get here at all. - raise ImportError, '%s: unknown module type (%d)' % (name, type) - finally: - # Since we may exit via an exception, close fp explicitly. - fp.close() -\end{verbatim} diff --git a/Doc/libintro.tex b/Doc/libintro.tex deleted file mode 100644 index 70d7478c8d..0000000000 --- a/Doc/libintro.tex +++ /dev/null @@ -1,47 +0,0 @@ -\chapter{Introduction} - -The ``Python library'' contains several different kinds of components. - -It contains data types that would normally be considered part of the -``core'' of a language, such as numbers and lists. For these types, -the Python language core defines the form of literals and places some -constraints on their semantics, but does not fully define the -semantics. (On the other hand, the language core does define -syntactic properties like the spelling and priorities of operators.) - -The library also contains built-in functions and exceptions --- -objects that can be used by all Python code without the need of an -\code{import} statement. Some of these are defined by the core -language, but many are not essential for the core semantics and are -only described here. - -The bulk of the library, however, consists of a collection of modules. -There are many ways to dissect this collection. Some modules are -written in C and built in to the Python interpreter; others are -written in Python and imported in source form. Some modules provide -interfaces that are highly specific to Python, like printing a stack -trace; some provide interfaces that are specific to particular -operating systems, like socket I/O; others provide interfaces that are -specific to a particular application domain, like the World-Wide Web. -Some modules are avaiable in all versions and ports of Python; others -are only available when the underlying system supports or requires -them; yet others are available only when a particular configuration -option was chosen at the time when Python was compiled and installed. - -This manual is organized ``from the inside out'': it first describes -the built-in data types, then the built-in functions and exceptions, -and finally the modules, grouped in chapters of related modules. The -ordering of the chapters as well as the ordering of the modules within -each chapter is roughly from most relevant to least important. - -This means that if you start reading this manual from the start, and -skip to the next chapter when you get bored, you will get a reasonable -overview of the available modules and application areas that are -supported by the Python library. Of course, you don't \emph{have} to -read it like a novel --- you can also browse the table of contents (in -front of the manual), or look for a specific function, module or term -in the index (in the back). And finally, if you enjoy learning about -random subjects, you choose a random page number (see module -\code{rand}) and read a section or two. - -Let the show begin! diff --git a/Doc/libjpeg.tex b/Doc/libjpeg.tex deleted file mode 100644 index 8215cada56..0000000000 --- a/Doc/libjpeg.tex +++ /dev/null @@ -1,51 +0,0 @@ -\section{Built-in Module \sectcode{jpeg}} -\bimodindex{jpeg} - -The module \code{jpeg} provides access to the jpeg compressor and -decompressor written by the Independent JPEG Group. JPEG is a (draft?)\ -standard for compressing pictures. For details on jpeg or the -Independent JPEG Group software refer to the JPEG standard or the -documentation provided with the software. - -The \code{jpeg} module defines these functions: - -\renewcommand{\indexsubitem}{(in module jpeg)} -\begin{funcdesc}{compress}{data\, w\, h\, b} -Treat data as a pixmap of width \var{w} and height \var{h}, with \var{b} bytes per -pixel. The data is in SGI GL order, so the first pixel is in the -lower-left corner. This means that \code{lrectread} return data can -immediately be passed to compress. Currently only 1 byte and 4 byte -pixels are allowed, the former being treated as greyscale and the -latter as RGB color. Compress returns a string that contains the -compressed picture, in JFIF format. -\end{funcdesc} - -\begin{funcdesc}{decompress}{data} -Data is a string containing a picture in JFIF format. It returns a -tuple -\code{(\var{data}, \var{width}, \var{height}, \var{bytesperpixel})}. -Again, the data is suitable to pass to \code{lrectwrite}. -\end{funcdesc} - -\begin{funcdesc}{setoption}{name\, value} -Set various options. Subsequent compress and decompress calls -will use these options. The following options are available: -\begin{description} -\item[\code{'forcegray' }] -Force output to be grayscale, even if input is RGB. - -\item[\code{'quality' }] -Set the quality of the compressed image to a -value between \code{0} and \code{100} (default is \code{75}). Compress only. - -\item[\code{'optimize' }] -Perform Huffman table optimization. Takes longer, but results in -smaller compressed image. Compress only. - -\item[\code{'smooth' }] -Perform inter-block smoothing on uncompressed image. Only useful for -low-quality images. Decompress only. -\end{description} -\end{funcdesc} - -Compress and uncompress raise the error \code{jpeg.error} in case of errors. diff --git a/Doc/libmac.tex b/Doc/libmac.tex deleted file mode 100644 index af07142023..0000000000 --- a/Doc/libmac.tex +++ /dev/null @@ -1,40 +0,0 @@ -\chapter{Macintosh Specific Services} - -The modules in this chapter are available on the Apple Macintosh only. - -\section{Built-in Module \sectcode{mac}} - -\bimodindex{mac} -This module provides a subset of the operating system dependent -functionality provided by the optional built-in module \code{posix}. -It is best accessed through the more portable standard module -\code{os}. - -The following functions are available in this module: -\code{chdir}, -\code{getcwd}, -\code{listdir}, -\code{mkdir}, -\code{rename}, -\code{rmdir}, -\code{stat}, -\code{sync}, -\code{unlink}, -as well as the exception \code{error}. - -\section{Standard Module \sectcode{macpath}} - -\stmodindex{macpath} -This module provides a subset of the pathname manipulation functions -available from the optional standard module \code{posixpath}. It is -best accessed through the more portable standard module \code{os}, as -\code{os.path}. - -The following functions are available in this module: -\code{normcase}, -\code{isabs}, -\code{join}, -\code{split}, -\code{isdir}, -\code{isfile}, -\code{exists}. diff --git a/Doc/libmacconsole.tex b/Doc/libmacconsole.tex deleted file mode 100644 index 42d4e51a06..0000000000 --- a/Doc/libmacconsole.tex +++ /dev/null @@ -1,111 +0,0 @@ -\section{Built-in Module \sectcode{macconsole}} -\bimodindex{macconsole} - -\renewcommand{\indexsubitem}{(in module macconsole)} - -This module is available on the Macintosh, provided Python has been -built using the Think C compiler. It provides an interface to the -Think console package, with which basic text windows can be created. - -\begin{datadesc}{options} -An object allowing you to set various options when creating windows, -see below. -\end{datadesc} - -\begin{datadesc}{C_ECHO} -\dataline{C_NOECHO} -\dataline{C_CBREAK} -\dataline{C_RAW} -Options for the \code{setmode} method. \var{C_ECHO} and \var{C_CBREAK} -enable character echo, the other two disable it, \var{C_ECHO} and -\var{C_NOECHO} enable line-oriented input (erase/kill processing, -etc). -\end{datadesc} - -\begin{funcdesc}{copen}{} -Open a new console window. Return a console window object. -\end{funcdesc} - -\begin{funcdesc}{fopen}{fp} -Return the console window object corresponding with the given file -object. \var{fp} should be one of \code{sys.stdin}, \code{sys.stdout} or -\code{sys.stderr}. -\end{funcdesc} - -\subsection{macconsole options object} -These options are examined when a window is created: - -\renewcommand{\indexsubitem}{(macconsole option)} -\begin{datadesc}{top} -\dataline{left} -The origin of the window. -\end{datadesc} - -\begin{datadesc}{nrows} -\dataline{ncols} -The size of the window. -\end{datadesc} - -\begin{datadesc}{txFont} -\dataline{txSize} -\dataline{txStyle} -The font, fontsize and fontstyle to be used in the window. -\end{datadesc} - -\begin{datadesc}{title} -The title of the window. -\end{datadesc} - -\begin{datadesc}{pause_atexit} -If set non-zero, the window will wait for user action before closing. -\end{datadesc} - -\subsection{console window object} - -\renewcommand{\indexsubitem}{(console window attribute)} - -\begin{datadesc}{file} -The file object corresponding to this console window. If the file is -buffered, you should call \code{file.flush()} between \code{write()} -and \code{read()} calls. -\end{datadesc} - -\renewcommand{\indexsubitem}{(console window method)} - -\begin{funcdesc}{setmode}{mode} -Set the input mode of the console to \var{C_ECHO}, etc. -\end{funcdesc} - -\begin{funcdesc}{settabs}{n} -Set the tabsize to \var{n} spaces. -\end{funcdesc} - -\begin{funcdesc}{cleos}{} -Clear to end-of-screen. -\end{funcdesc} - -\begin{funcdesc}{cleol}{} -Clear to end-of-line. -\end{funcdesc} - -\begin{funcdesc}{inverse}{onoff} -Enable inverse-video mode:\ characters with the high bit set are -displayed in inverse video (this disables the upper half of a -non-\ASCII{} character set). -\end{funcdesc} - -\begin{funcdesc}{gotoxy}{x\, y} -Set the cursor to position \code{(\var{x}, \var{y})}. -\end{funcdesc} - -\begin{funcdesc}{hide}{} -Hide the window, remembering the contents. -\end{funcdesc} - -\begin{funcdesc}{show}{} -Show the window again. -\end{funcdesc} - -\begin{funcdesc}{echo2printer}{} -Copy everything written to the window to the printer as well. -\end{funcdesc} diff --git a/Doc/libmacdnr.tex b/Doc/libmacdnr.tex deleted file mode 100644 index ab45788210..0000000000 --- a/Doc/libmacdnr.tex +++ /dev/null @@ -1,119 +0,0 @@ - -\section{Built-in Module \sectcode{macdnr}} -\bimodindex{macdnr} - -This module provides an interface to the Macintosh Domain Name -Resolver. It is usually used in conjunction with the \var{mactcp} -module, to map hostnames to IP-addresses. It may not be available in -all Mac Python versions. - -The \code{macdnr} module defines the following functions: - -\renewcommand{\indexsubitem}{(in module macdnr)} - -\begin{funcdesc}{Open}{\optional{filename}} -Open the domain name resolver extension. If \var{filename} is given it -should be the pathname of the extension, otherwise a default is -used. Normally, this call is not needed since the other calls will -open the extension automatically. -\end{funcdesc} - -\begin{funcdesc}{Close}{} -Close the resolver extension. Again, not needed for normal use. -\end{funcdesc} - -\begin{funcdesc}{StrToAddr}{hostname} -Look up the IP address for \var{hostname}. This call returns a dnr -result object of the ``address'' variation. -\end{funcdesc} - -\begin{funcdesc}{AddrToName}{addr} -Do a reverse lookup on the 32-bit integer IP-address -\var{addr}. Returns a dnr result object of the ``address'' variation. -\end{funcdesc} - -\begin{funcdesc}{AddrToStr}{addr} -Convert the 32-bit integer IP-address \var{addr} to a dotted-decimal -string. Returns the string. -\end{funcdesc} - -\begin{funcdesc}{HInfo}{hostname} -Query the nameservers for a \code{HInfo} record for host -\var{hostname}. These records contain hardware and software -information about the machine in question (if they are available in -the first place). Returns a dnr result object of the ``hinfo'' -variety. -\end{funcdesc} - -\begin{funcdesc}{MXInfo}{domain} -Query the nameservers for a mail exchanger for \var{domain}. This is -the hostname of a host willing to accept SMTP mail for the given -domain. Returns a dnr result object of the ``mx'' variety. -\end{funcdesc} - -\subsection{dnr result object} - -Since the DNR calls all execute asynchronously you do not get the -results back immediately. Instead, you get a dnr result object. You -can check this object to see whether the query is complete, and access -its attributes to obtain the information when it is. - -Alternatively, you can also reference the result attributes directly, -this will result in an implicit wait for the query to complete. - -The \var{rtnCode} and \var{cname} attributes are always available, the -others depend on the type of query (address, hinfo or mx). - -\renewcommand{\indexsubitem}{(dnr result object method)} - -% Add args, as in {arg1\, arg2 \optional{\, arg3}} -\begin{funcdesc}{wait}{} -Wait for the query to complete. -\end{funcdesc} - -% Add args, as in {arg1\, arg2 \optional{\, arg3}} -\begin{funcdesc}{isdone}{} -Return 1 if the query is complete. -\end{funcdesc} - -\renewcommand{\indexsubitem}{(dnr result object attribute)} - -\begin{datadesc}{rtnCode} -The error code returned by the query. -\end{datadesc} - -\begin{datadesc}{cname} -The canonical name of the host that was queried. -\end{datadesc} - -\begin{datadesc}{ip0} -\dataline{ip1} -\dataline{ip2} -\dataline{ip3} -At most four integer IP addresses for this host. Unused entries are -zero. Valid only for address queries. -\end{datadesc} - -\begin{datadesc}{cpuType} -\dataline{osType} -Textual strings giving the machine type an OS name. Valid for hinfo -queries. -\end{datadesc} - -\begin{datadesc}{exchange} -The name of a mail-exchanger host. Valid for mx queries. -\end{datadesc} - -\begin{datadesc}{preference} -The preference of this mx record. Not too useful, since the Macintosh -will only return a single mx record. Mx queries only. -\end{datadesc} - -The simplest way to use the module to convert names to dotted-decimal -strings, without worrying about idle time, etc: -\begin{verbatim} ->>> def gethostname(name): -... import macdnr -... dnrr = macdnr.StrToAddr(name) -... return macdnr.AddrToStr(dnrr.ip0) -\end{verbatim} diff --git a/Doc/libmacfs.tex b/Doc/libmacfs.tex deleted file mode 100644 index 254ed253ac..0000000000 --- a/Doc/libmacfs.tex +++ /dev/null @@ -1,182 +0,0 @@ -\section{Built-in Module \sectcode{macfs}} -\bimodindex{macfs} - -\renewcommand{\indexsubitem}{(in module macfs)} - -This module provides access to macintosh FSSpec handling, the Alias -Manager, finder aliases and the Standard File package. - -Whenever a function or method expects a \var{file} argument, this -argument can be one of three things:\ (1) a full or partial Macintosh -pathname, (2) an FSSpec object or (3) a 3-tuple \code{(wdRefNum, -parID, name)} as described in Inside Mac VI\@. A description of aliases -and the standard file package can also be found there. - -\begin{funcdesc}{FSSpec}{file} -Create an FSSpec object for the specified file. -\end{funcdesc} - -\begin{funcdesc}{RawFSSpec}{data} -Create an FSSpec object given the raw data for the C structure for the -FSSpec as a string. This is mainly useful if you have obtained an -FSSpec structure over a network. -\end{funcdesc} - -\begin{funcdesc}{RawAlias}{data} -Create an Alias object given the raw data for the C structure for the -alias as a string. This is mainly useful if you have obtained an -FSSpec structure over a network. -\end{funcdesc} - -\begin{funcdesc}{FInfo}{} -Create a zero-filled FInfo object. -\end{funcdesc} - -\begin{funcdesc}{ResolveAliasFile}{file} -Resolve an alias file. Returns a 3-tuple \code{(\var{fsspec}, \var{isfolder}, -\var{aliased})} where \var{fsspec} is the resulting FSSpec object, -\var{isfolder} is true if \var{fsspec} points to a folder and -\var{aliased} is true if the file was an alias in the first place -(otherwise the FSSpec object for the file itself is returned). -\end{funcdesc} - -\begin{funcdesc}{StandardGetFile}{\optional{type\, ...}} -Present the user with a standard ``open input file'' -dialog. Optionally, you can pass up to four 4-char file types to limit -the files the user can choose from. The function returns an FSSpec -object and a flag indicating that the user completed the dialog -without cancelling. -\end{funcdesc} - -\begin{funcdesc}{PromptGetFile}{prompt\optional{\, type\, ...}} -Similar to \var{StandardGetFile} but allows you to specify a prompt. -\end{funcdesc} - -\begin{funcdesc}{StandardPutFile}{prompt\, \optional{default}} -Present the user with a standard ``open output file'' -dialog. \var{prompt} is the prompt string, and the optional -\var{default} argument initializes the output file name. The function -returns an FSSpec object and a flag indicating that the user completed -the dialog without cancelling. -\end{funcdesc} - -\begin{funcdesc}{GetDirectory}{\optional{prompt}} -Present the user with a non-standard ``select a directory'' -dialog. \var{prompt} is the prompt string, and the optional. -Return an FSSpec object and a success-indicator. -\end{funcdesc} - -\begin{funcdesc}{FindFolder}{where\, which\, create} -Locates one of the ``special'' folders that MacOS knows about, such as -the trash or the Preferences folder. \var{Where} is the disk to -search, \var{which} is the 4-char string specifying which folder to -locate. Setting \var{create} causes the folder to be created if it -does not exist. Returns a \code{(vrefnum, dirid)} tuple. - -The constants for \var{where} and \var{which} can be obtained from the -standard module \var{MACFS}. -\end{funcdesc} - -\subsection{FSSpec objects} - -\renewcommand{\indexsubitem}{(FSSpec object attribute)} -\begin{datadesc}{data} -The raw data from the FSSpec object, suitable for passing -to other applications, for instance. -\end{datadesc} - -\renewcommand{\indexsubitem}{(FSSpec object method)} -\begin{funcdesc}{as_pathname}{} -Return the full pathname of the file described by the FSSpec object. -\end{funcdesc} - -\begin{funcdesc}{as_tuple}{} -Return the \code{(\var{wdRefNum}, \var{parID}, \var{name})} tuple of the file described -by the FSSpec object. -\end{funcdesc} - -\begin{funcdesc}{NewAlias}{\optional{file}} -Create an Alias object pointing to the file described by this -FSSpec. If the optional \var{file} parameter is present the alias -will be relative to that file, otherwise it will be absolute. -\end{funcdesc} - -\begin{funcdesc}{NewAliasMinimal}{} -Create a minimal alias pointing to this file. -\end{funcdesc} - -\begin{funcdesc}{GetCreatorType}{} -Return the 4-char creator and type of the file. -\end{funcdesc} - -\begin{funcdesc}{SetCreatorType}{creator\, type} -Set the 4-char creator and type of the file. -\end{funcdesc} - -\begin{funcdesc}{GetFInfo}{} -Return a FInfo object describing the finder info for the file. -\end{funcdesc} - -\begin{funcdesc}{SetFInfo}{finfo} -Set the finder info for the file to the values specified in the -\var{finfo} object. -\end{funcdesc} - -\subsection{alias objects} - -\renewcommand{\indexsubitem}{(alias object attribute)} -\begin{datadesc}{data} -The raw data for the Alias record, suitable for storing in a resource -or transmitting to other programs. -\end{datadesc} - -\renewcommand{\indexsubitem}{(alias object method)} -\begin{funcdesc}{Resolve}{\optional{file}} -Resolve the alias. If the alias was created as a relative alias you -should pass the file relative to which it is. Return the FSSpec for -the file pointed to and a flag indicating whether the alias object -itself was modified during the search process. -\end{funcdesc} - -\begin{funcdesc}{GetInfo}{num} -An interface to the C routine \code{GetAliasInfo()}. -\end{funcdesc} - -\begin{funcdesc}{Update}{file\, \optional{file2}} -Update the alias to point to the \var{file} given. If \var{file2} is -present a relative alias will be created. -\end{funcdesc} - -Note that it is currently not possible to directly manipulate a resource -as an alias object. Hence, after calling \var{Update} or after -\var{Resolve} indicates that the alias has changed the Python program -is responsible for getting the \var{data} from the alias object and -modifying the resource. - - -\subsection{FInfo objects} - -See Inside Mac for a complete description of what the various fields -mean. - -\renewcommand{\indexsubitem}{(FInfo object attribute)} -\begin{datadesc}{Creator} -The 4-char creator code of the file. -\end{datadesc} - -\begin{datadesc}{Type} -The 4-char type code of the file. -\end{datadesc} - -\begin{datadesc}{Flags} -The finder flags for the file as 16-bit integer. The bit values in -\var{Flags} are defined in standard module \var{MACFS}. -\end{datadesc} - -\begin{datadesc}{Location} -A Point giving the position of the file's icon in its folder. -\end{datadesc} - -\begin{datadesc}{Fldr} -The folder the file is in (as an integer). -\end{datadesc} diff --git a/Doc/libmacos.tex b/Doc/libmacos.tex deleted file mode 100644 index 66187545ef..0000000000 --- a/Doc/libmacos.tex +++ /dev/null @@ -1,74 +0,0 @@ -\section{Built-in Module \sectcode{MacOS}} -\bimodindex{MacOS} - -\renewcommand{\indexsubitem}{(in module MacOS)} - -This module provides access to MacOS specific functionality in the -python interpreter, such as how the interpreter eventloop functions -and the like. Use with care. - -Note the capitalisation of the module name, this is a historical -artefact. - -\begin{excdesc}{Error} -This exception is raised on MacOS generated errors, either from -functions in this module or from other mac-specific modules like the -toolbox interfaces. The arguments are the integer error code (the -\var{OSErr} value) and a textual description of the error code. -\end{excdesc} - -\begin{funcdesc}{SetHighLevelEventHandler}{handler} -Pass a python function that will be called upon reception of a -high-level event. The previous handler is returned. The handler -function is called with the event as argument. - -Note that your event handler is currently only called dependably if -your main event loop is in \var{stdwin}. -\end{funcdesc} - -\begin{funcdesc}{AcceptHighLevelEvent}{} -Read a high-level event. The return value is a tuple \code{(sender, -refcon, data)}. -\end{funcdesc} - -\begin{funcdesc}{SetScheduleTimes}{fgi\, fgy \optional{\, bgi\, bgy}} -Controls how often the interpreter checks the event queue and how -long it will yield the processor to other processes. \var{fgi} -specifies after how many clicks (one click is one 60th of a second) -the interpreter should check the event queue, and \var{fgy} specifies -for how many clicks the CPU should be yielded when in the -foreground. The optional \var{bgi} and \var{bgy} allow you to specify -different values to use when python runs in the background, otherwise -the background values will be set the the same as the foreground -values. The function returns nothing. - -The default values, which are based on nothing at all, are 12, 6, 1 -and 12 respectively. -\end{funcdesc} - -\begin{funcdesc}{EnableAppswitch}{onoff} -Enable or disable the python event loop, based on the value of -\var{onoff}. The old value is returned. If the event loop is disabled -no time is granted to other applications, checking for command-period -is not performed and it is impossible to switch applications. This -should only be used by programs providing their own complete event -loop. - -Note that based on the compiler used to build python it is still -possible to loose events even with the python event loop disabled. If -you have a \code{sys.stdout} window its handler will often also look -in the event queue. Making sure nothing is ever printed works around -this. -\end{funcdesc} - -\begin{funcdesc}{HandleEvent}{ev} -Pass the event record \code{ev} back to the python event loop, or -possibly to the handler for the \code{sys.stdout} window (based on the -compiler used to build python). This allows python programs that do -their own event handling to still have some command-period and -window-switching capability. -\end{funcdesc} - -\begin{funcdesc}{GetErrorString}{errno} -Return the textual description of MacOS error code \var{errno}. -\end{funcdesc} diff --git a/Doc/libmacostools.tex b/Doc/libmacostools.tex deleted file mode 100644 index 1e60983b1c..0000000000 --- a/Doc/libmacostools.tex +++ /dev/null @@ -1,39 +0,0 @@ - -\section{Standard module \sectcode{macostools}} -\stmodindex{macostools} - -This module contains some convenience routines for file-manipulation -on the Macintosh. - -The \code{macostools} module defines the following functions: - -\renewcommand{\indexsubitem}{(in module macostools)} - -\begin{funcdesc}{copy}{src\, dst\optional{\, createpath}} -Copy file \var{src} to \var{dst}. The files can be specified as -pathnames or \code{FSSpec} objects. If \var{createpath} is non-zero -\var{dst} must be a pathname and the folders leading to the -destination are created if necessary. -The method copies data and resource fork and some finder information -(creator, type and flags). Custom icons, comments and icon position -are not copied. -\end{funcdesc} - -\begin{funcdesc}{copytree}{src\, dst} -Recursively copy a file tree from \var{src} to \var{dst}, creating -folders as needed. \var{Src} and \var{dst} should be specified as -pathnames. -\end{funcdesc} - -\begin{funcdesc}{mkalias}{src\, dst} -Create a finder alias \var{dst} pointing to \var{src}. Both may be -specified as pathnames or \var{FSSpec} objects. -\end{funcdesc} - -\begin{datadesc}{BUFSIZ} -The buffer size for \code{copy}, default 1 megabyte. -\end{datadesc} - -Note that the process of creating finder aliases is not specified in -the Apple documentation. Hence, aliases created with \code{mkalias} -could conceivably have incompatible behaviour in some cases. diff --git a/Doc/libmacspeech.tex b/Doc/libmacspeech.tex deleted file mode 100644 index fc35520b64..0000000000 --- a/Doc/libmacspeech.tex +++ /dev/null @@ -1,86 +0,0 @@ -\section{Built-in Module \sectcode{macspeech}} -\bimodindex{macspeech} - -\renewcommand{\indexsubitem}{(in module macspeech)} - -This module provides an interface to the Macintosh Speech Manager, -allowing you to let the Macintosh utter phrases. You need a version of -the speech manager extension (version 1 and 2 have been tested) in -your \code{Extensions} folder for this to work. The module does not -provide full access to all features of the Speech Manager yet. It may -not be available in all Mac Python versions. - -\begin{funcdesc}{Available}{} -Test availability of the Speech Manager extension (and, on the -PowerPC, the Speech Manager shared library). Return 0 or 1. -\end{funcdesc} - -\begin{funcdesc}{Version}{} -Return the (integer) version number of the Speech Manager. -\end{funcdesc} - -\begin{funcdesc}{SpeakString}{str} -Utter the string \var{str} using the default voice, -asynchronously. This aborts any speech that may still be active from -prior \code{SpeakString} invocations. -\end{funcdesc} - -\begin{funcdesc}{Busy}{} -Return the number of speech channels busy, system-wide. -\end{funcdesc} - -\begin{funcdesc}{CountVoices}{} -Return the number of different voices available. -\end{funcdesc} - -\begin{funcdesc}{GetIndVoice}{num} -Return a voice object for voice number \var{num}. -\end{funcdesc} - -\subsection{voice objects} -Voice objects contain the description of a voice. It is currently not -yet possible to access the parameters of a voice. - -\renewcommand{\indexsubitem}{(voice object method)} - -\begin{funcdesc}{GetGender}{} -Return the gender of the voice:\ 0 for male, 1 for female and $-1$ for neuter. -\end{funcdesc} - -\begin{funcdesc}{NewChannel}{} -Return a new speech channel object using this voice. -\end{funcdesc} - -\subsection{speech channel objects} -A speech channel object allows you to speak strings with slightly more -control than \code{SpeakString()}, and allows you to use multiple -speakers at the same time. Please note that channel pitch and rate are -interrelated in some way, so that to make your Macintosh sing you will -have to adjust both. - -\renewcommand{\indexsubitem}{(speech channel object method)} -\begin{funcdesc}{SpeakText}{str} -Start uttering the given string. -\end{funcdesc} - -\begin{funcdesc}{Stop}{} -Stop babbling. -\end{funcdesc} - -\begin{funcdesc}{GetPitch}{} -Return the current pitch of the channel, as a floating-point number. -\end{funcdesc} - -\begin{funcdesc}{SetPitch}{pitch} -Set the pitch of the channel. -\end{funcdesc} - -\begin{funcdesc}{GetRate}{} -Get the speech rate (utterances per minute) of the channel as a -floating point number. -\end{funcdesc} - -\begin{funcdesc}{SetRate}{rate} -Set the speech rate of the channel. -\end{funcdesc} - diff --git a/Doc/libmactcp.tex b/Doc/libmactcp.tex deleted file mode 100644 index 6c5a78bf60..0000000000 --- a/Doc/libmactcp.tex +++ /dev/null @@ -1,173 +0,0 @@ -\section{Built-in Module \sectcode{mactcp}} -\bimodindex{mactcp} - -\renewcommand{\indexsubitem}{(in module mactcp)} - -This module provides an interface to the Macintosh TCP/IP driver -MacTCP\@. There is an accompanying module \code{macdnr} which provides an -interface to the name-server (allowing you to translate hostnames to -ip-addresses), a module \code{MACTCP} which has symbolic names for -constants constants used by MacTCP and a wrapper module \code{socket} -which mimics the \UNIX{} socket interface (as far as possible). It may -not be available in all Mac Python versions. - -A complete description of the MacTCP interface can be found in the -Apple MacTCP API documentation. - -\begin{funcdesc}{MTU}{} -Return the Maximum Transmit Unit (the packet size) of the network -interface. -\end{funcdesc} - -\begin{funcdesc}{IPAddr}{} -Return the 32-bit integer IP address of the network interface. -\end{funcdesc} - -\begin{funcdesc}{NetMask}{} -Return the 32-bit integer network mask of the interface. -\end{funcdesc} - -\begin{funcdesc}{TCPCreate}{size} -Create a TCP Stream object. \var{size} is the size of the receive -buffer, \code{4096} is suggested by various sources. -\end{funcdesc} - -\begin{funcdesc}{UDPCreate}{size, port} -Create a UDP stream object. \var{size} is the size of the receive -buffer (and, hence, the size of the biggest datagram you can receive -on this port). \var{port} is the UDP port number you want to receive -datagrams on, a value of zero will make MacTCP select a free port. -\end{funcdesc} - -\subsection{TCP Stream Objects} - -\renewcommand{\indexsubitem}{(TCP stream attribute)} - -\begin{datadesc}{asr} -When set to a value different than \code{None} this should point to a -function with two integer parameters:\ an event code and a detail. This -function will be called upon network-generated events such as urgent -data arrival. In addition, it is called with eventcode -\code{MACTCP.PassiveOpenDone} when a \code{PassiveOpen} completes. This -is a Python addition to the MacTCP semantics. -It is safe to do further calls from the \code{asr}. -\end{datadesc} - -\renewcommand{\indexsubitem}{(TCP stream method)} - -\begin{funcdesc}{PassiveOpen}{port} -Wait for an incoming connection on TCP port \var{port} (zero makes the -system pick a free port). The call returns immediately, and you should -use \var{wait} to wait for completion. You should not issue any method -calls other than -\code{wait}, \code{isdone} or \code{GetSockName} before the call -completes. -\end{funcdesc} - -\begin{funcdesc}{wait}{} -Wait for \code{PassiveOpen} to complete. -\end{funcdesc} - -\begin{funcdesc}{isdone}{} -Return 1 if a \code{PassiveOpen} has completed. -\end{funcdesc} - -\begin{funcdesc}{GetSockName}{} -Return the TCP address of this side of a connection as a 2-tuple -\code{(host, port)}, both integers. -\end{funcdesc} - -\begin{funcdesc}{ActiveOpen}{lport\, host\, rport} -Open an outgoing connection to TCP address \code{(\var{host}, \var{rport})}. Use -local port \var{lport} (zero makes the system pick a free port). This -call blocks until the connection has been established. -\end{funcdesc} - -\begin{funcdesc}{Send}{buf\, push\, urgent} -Send data \var{buf} over the connection. \var{Push} and \var{urgent} -are flags as specified by the TCP standard. -\end{funcdesc} - -\begin{funcdesc}{Rcv}{timeout} -Receive data. The call returns when \var{timeout} seconds have passed -or when (according to the MacTCP documentation) ``a reasonable amount -of data has been received''. The return value is a 3-tuple -\code{(\var{data}, \var{urgent}, \var{mark})}. If urgent data is outstanding \code{Rcv} -will always return that before looking at any normal data. The first -call returning urgent data will have the \var{urgent} flag set, the -last will have the \var{mark} flag set. -\end{funcdesc} - -\begin{funcdesc}{Close}{} -Tell MacTCP that no more data will be transmitted on this -connection. The call returns when all data has been acknowledged by -the receiving side. -\end{funcdesc} - -\begin{funcdesc}{Abort}{} -Forcibly close both sides of a connection, ignoring outstanding data. -\end{funcdesc} - -\begin{funcdesc}{Status}{} -Return a TCP status object for this stream giving the current status -(see below). -\end{funcdesc} - -\subsection{TCP Status Objects} -This object has no methods, only some members holding information on -the connection. A complete description of all fields in this objects -can be found in the Apple documentation. The most interesting ones are: - -\renewcommand{\indexsubitem}{(TCP status attribute)} - -\begin{datadesc}{localHost} -\dataline{localPort} -\dataline{remoteHost} -\dataline{remotePort} -The integer IP-addresses and port numbers of both endpoints of the -connection. -\end{datadesc} - -\begin{datadesc}{sendWindow} -The current window size. -\end{datadesc} - -\begin{datadesc}{amtUnackedData} -The number of bytes sent but not yet acknowledged. \code{sendWindow - -amtUnackedData} is what you can pass to \code{Send} without blocking. -\end{datadesc} - -\begin{datadesc}{amtUnreadData} -The number of bytes received but not yet read (what you can \code{Recv} -without blocking). -\end{datadesc} - - - -\subsection{UDP Stream Objects} -Note that, unlike the name suggests, there is nothing stream-like -about UDP. - -\renewcommand{\indexsubitem}{(UDP stream attribute)} - -\begin{datadesc}{asr} -The asynchronous service routine to be called on events such as -datagram arrival without outstanding \code{Read} call. The \code{asr} has a -single argument, the event code. -\end{datadesc} - -\begin{datadesc}{port} -A read-only member giving the port number of this UDP stream. -\end{datadesc} - -\renewcommand{\indexsubitem}{(UDP stream method)} - -\begin{funcdesc}{Read}{timeout} -Read a datagram, waiting at most \var{timeout} seconds ($-1$ is -infinite). Return the data. -\end{funcdesc} - -\begin{funcdesc}{Write}{host\, port\, buf} -Send \var{buf} as a datagram to IP-address \var{host}, port -\var{port}. -\end{funcdesc} diff --git a/Doc/libmacui.tex b/Doc/libmacui.tex deleted file mode 100644 index f785679e80..0000000000 --- a/Doc/libmacui.tex +++ /dev/null @@ -1,221 +0,0 @@ -\section{Standard module \sectcode{EasyDialogs}} -\stmodindex{EasyDialogs} - -The \code{EasyDialogs} module contains some simple dialogs for -the Macintosh, modelled after the \code{stdwin} dialogs with similar -names. - -The \code{EasyDialogs} module defines the following functions: - -\renewcommand{\indexsubitem}{(in module EasyDialogs)} - -\begin{funcdesc}{Message}{str} -A modal dialog with the message text \var{str}, which should be at -most 255 characters long, is displayed. Control is returned when the -user clicks ``OK''. -\end{funcdesc} - -\begin{funcdesc}{AskString}{prompt\optional{\, default}} -Ask the user to input a string value, in a modal dialog. \var{Prompt} -is the promt message, the optional \var{default} arg is the initial -value for the string. All strings can be at most 255 bytes -long. \var{AskString} returns the string entered or \code{None} in -case the user cancelled. -\end{funcdesc} - -\begin{funcdesc}{AskYesNoCancel}{question\optional{\, default}} -Present a dialog with text \var{question} and three buttons labelled -``yes'', ``no'' and ``cancel''. Return \code{1} for yes, \code{0} for -no and \code{-1} for cancel. The default return value chosen by -hitting return is \code{0}. This can be changed with the optional -\var{default} argument. -\end{funcdesc} - -\begin{funcdesc}{ProgressBar}{\optional{label\, maxval}} -Display a modeless progress dialog with a thermometer bar. \var{Label} -is the textstring displayed (default ``Working...''), \var{maxval} is -the value at which progress is complete (default 100). The returned -object has one method, \code{set(value)}, which sets the value of the -progress bar. The bar remains visible until the object returned is -discarded. - -The progress bar has a ``cancel'' button, but it is currently -non-functional. -\end{funcdesc} - -Note that \code{EasyDialogs} does not currently use the notification -manager. This means that displaying dialogs while the program is in -the background will lead to unexpected results and possibly -crashes. Also, all dialogs are modeless and hence expect to be at the -top of the stacking order. This is true when the dialogs are created, -but windows that pop-up later (like a console window) may also result -in crashes. - - -\section{Standard module \sectcode{FrameWork}} -\stmodindex{FrameWork} - -The \code{FrameWork} module contains classes that together provide a -framework for an interactive Macintosh application. The programmer -builds an application by creating subclasses that override various -methods of the bases classes, thereby implementing the functionality -wanted. Overriding functionality can often be done on various -different levels, i.e. to handle clicks in a single dialog window in a -non-standard way it is not necessary to override the complete event -handling. - -The \code{FrameWork} is still very much work-in-progress, and the -documentation describes only the most important functionality, and not -in the most logical manner at that. Examine the source for more -esoteric needs. - -The \code{EasyDialogs} module defines the following functions: - -\renewcommand{\indexsubitem}{(in module FrameWork)} - -\begin{funcdesc}{Application}{} -An object representing the complete application. See below for a -description of the methods. The default \code{__init__} routine -creates an empty window dictionary and a menu bar with an apple menu. -\end{funcdesc} - -\begin{funcdesc}{MenuBar}{} -An object representing the menubar. This object is usually not created -by the user. -\end{funcdesc} - -\begin{funcdesc}{Menu}{bar\, title\optional{\, after}} -An object representing a menu. Upon creation you pass the -\code{MenuBar} the menu appears in, the \var{title} string and a -position (1-based) \var{after} where the menu should appear (default: -at the end). -\end{funcdesc} - -\begin{funcdesc}{MenuItem}{menu\, title\optional{\, shortcut\, callback}} -Create a menu item object. The arguments are the menu to crate the -item it, the item title string and optionally the keyboard shortcut -and a callback routine. The callback is called with the arguments -menu-id, item number within menu (1-based), current front window and -the event record. -\end{funcdesc} - -\begin{funcdesc}{Separator}{menu} -Add a separator to the end of a menu. -\end{funcdesc} - -\begin{funcdesc}{SubMenu}{menu\, label} -Create a submenu named \var{label} under menu \var{menu}. The menu -object is returned. -\end{funcdesc} - -\begin{funcdesc}{Window}{parent} -Creates a (modeless) window. \var{Parent} is the application object to -which the window belongs. The window is not displayed until later. -\end{funcdesc} - -\begin{funcdesc}{DialogWindow}{parent} -Creates a modeless dialog window. -\end{funcdesc} - - -\subsection{Application objects} -Application objects have the following methods, among others: - -\renewcommand{\indexsubitem}{(Application method)} - -\begin{funcdesc}{makeusermenus}{} -Override this method if you need menus in your application. Append the -menus to \code{self.menubar}. -\end{funcdesc} - -\begin{funcdesc}{getabouttext}{} -Override this method to return a text string describing your -application. Alternatively, override the \code{do_about} method for -more elaborate about messages. -\end{funcdesc} - -\begin{funcdesc}{mainloop}{\optional{mask\, wait}} -This routine is the main event loop, call it to set your application -rolling. \var{Mask} is the mask of events you want to handle, -\var{wait} is the number of ticks you want to leave to other -concurrent application (default 0, which is probably not a good -idea). This method does not return until \code{self} is raised. - -The event loop is split into many small parts, each of which can be -overridden. The default methods take care of dispatching events to -windows and dialogs, handling drags and resizes, Apple Events, events -for non-FrameWork windows, etc. -\end{funcdesc} - -\begin{funcdesc}{do_char}{c\, event} -The user typed character \var{c}. The complete details of the event -can be found in the \var{event} structure. This method can also be -provided in a \code{Window} object, which overrides the -application-wide handler if the window is frontmost. -\end{funcdesc} - -\begin{funcdesc}{do_dialogevent}{event} -Called early in the event loop to handle modeless dialog events. The -default method simply dispatches the event to the relevant dialog (not -through the the \code{DialogWindow} object involved). Override if you -need special handling of dialog events (keyboard shortcuts, etc). -\end{funcdesc} - -\begin{funcdesc}{idle}{} -Called by the main event loop when no events are available. -\end{funcdesc} - -\subsection{Window Objects} - -Window objects have the following methods, among others: - -\renewcommand{\indexsubitem}{(Window method)} - -\begin{funcdesc}{open}{} -Override this method to open a window. Store the MacOS window-id in -\code{self.wid} and call \code{self.do_postopen} to register the -window with the parent application. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Override this method to do any special processing on window -close. Call \code{self.do_postclose} to cleanup the parent state. -\end{funcdesc} - -\begin{funcdesc}{do_postresize}{width\, height\, macoswindowid} -Called after the window is resized. Override if more needs to be done -than calling \code{InvalRect}. -\end{funcdesc} - -\begin{funcdesc}{do_contentclick}{local\, modifiers\, event} -The user clicked in the content part of a window. The arguments are -the coordinates (window-relative), the key modifiers and the raw -event. -\end{funcdesc} - -\begin{funcdesc}{do_update}{macoswindowid\, event} -An update event for the window was received. Redraw the window. -\end{funcdesc} - -\begin{funcdesc}{do_activate}{activate\, event} -The window was activated (\code{activate==1}) or deactivated -(\code{activate==0}). Handle things like focus highlighting, etc. -\end{funcdesc} - -\subsection{DialogWindow Objects} - -DialogWindow objects have the following methods besides those of -\code{Window} objects: - -\renewcommand{\indexsubitem}{(DialogWindow method)} - -\begin{funcdesc}{open}{resid} -Create the dialog window, from the DLOG resource with id -\var{resid}. The dialog object is stored in \code{self.wid}. -\end{funcdesc} - -\begin{funcdesc}{do_itemhit}{item\, event} -Item number \var{item} was hit. You are responsible for redrawing -toggle buttons, etc. -\end{funcdesc} - diff --git a/Doc/libmain.tex b/Doc/libmain.tex deleted file mode 100644 index c730a03a11..0000000000 --- a/Doc/libmain.tex +++ /dev/null @@ -1,6 +0,0 @@ -\section{Built-in Module \sectcode{__main__}} - -\bimodindex{__main__} -This module represents the (otherwise anonymous) scope in which the -interpreter's main program executes --- commands read either from -standard input or from a script file. diff --git a/Doc/libmarshal.tex b/Doc/libmarshal.tex deleted file mode 100644 index 3abcc4291d..0000000000 --- a/Doc/libmarshal.tex +++ /dev/null @@ -1,83 +0,0 @@ -\section{Built-in Module \sectcode{marshal}} - -\bimodindex{marshal} -This module contains functions that can read and write Python -values in a binary format. The format is specific to Python, but -independent of machine architecture issues (e.g., you can write a -Python value to a file on a PC, transport the file to a Sun, and read -it back there). Details of the format are undocumented on purpose; -it may change between Python versions (although it rarely does).% -\footnote{The name of this module stems from a bit of terminology used -by the designers of Modula-3 (amongst others), who use the term -``marshalling'' for shipping of data around in a self-contained form. -Strictly speaking, ``to marshal'' means to convert some data from -internal to external form (in an RPC buffer for instance) and -``unmarshalling'' for the reverse process.} - -This is not a general ``persistency'' module. For general persistency -and transfer of Python objects through RPC calls, see the modules -\code{pickle} and \code{shelve}. The \code{marshal} module exists -mainly to support reading and writing the ``pseudo-compiled'' code for -Python modules of \samp{.pyc} files. -\stmodindex{pickle} -\stmodindex{shelve} -\obindex{code} - -Not all Python object types are supported; in general, only objects -whose value is independent from a particular invocation of Python can -be written and read by this module. The following types are supported: -\code{None}, integers, long integers, floating point numbers, -strings, tuples, lists, dictionaries, and code objects, where it -should be understood that tuples, lists and dictionaries are only -supported as long as the values contained therein are themselves -supported; and recursive lists and dictionaries should not be written -(they will cause infinite loops). - -{\bf Caveat:} On machines where C's \code{long int} type has more than -32 bits (such as the DEC Alpha), it -is possible to create plain Python integers that are longer than 32 -bits. Since the current \code{marshal} module uses 32 bits to -transfer plain Python integers, such values are silently truncated. -This particularly affects the use of very long integer literals in -Python modules --- these will be accepted by the parser on such -machines, but will be silently be truncated when the module is read -from the \code{.pyc} instead.% -\footnote{A solution would be to refuse such literals in the parser, -since they are inherently non-portable. Another solution would be to -let the \code{marshal} module raise an exception when an integer value -would be truncated. At least one of these solutions will be -implemented in a future version.} - -There are functions that read/write files as well as functions -operating on strings. - -The module defines these functions: - -\renewcommand{\indexsubitem}{(in module marshal)} - -\begin{funcdesc}{dump}{value\, file} - Write the value on the open file. The value must be a supported - type. The file must be an open file object such as - \code{sys.stdout} or returned by \code{open()} or - \code{posix.popen()}. - - If the value has an unsupported type, garbage is written which cannot - be read back by \code{load()}. -\end{funcdesc} - -\begin{funcdesc}{load}{file} - Read one value from the open file and return it. If no valid value - is read, raise \code{EOFError}, \code{ValueError} or - \code{TypeError}. The file must be an open file object. -\end{funcdesc} - -\begin{funcdesc}{dumps}{value} - Return the string that would be written to a file by - \code{dump(value, file)}. The value must be a supported type. -\end{funcdesc} - -\begin{funcdesc}{loads}{string} - Convert the string to a value. If no valid value is found, raise - \code{EOFError}, \code{ValueError} or \code{TypeError}. Extra - characters in the string are ignored. -\end{funcdesc} diff --git a/Doc/libmath.tex b/Doc/libmath.tex deleted file mode 100644 index 765fcdf5c6..0000000000 --- a/Doc/libmath.tex +++ /dev/null @@ -1,72 +0,0 @@ -\section{Built-in Module \sectcode{math}} - -\bimodindex{math} -\renewcommand{\indexsubitem}{(in module math)} -This module is always available. -It provides access to the mathematical functions defined by the C -standard. -They are: -\iftexi -\begin{funcdesc}{acos}{x} -\funcline{asin}{x} -\funcline{atan}{x} -\funcline{atan2}{x, y} -\funcline{ceil}{x} -\funcline{cos}{x} -\funcline{cosh}{x} -\funcline{exp}{x} -\funcline{fabs}{x} -\funcline{floor}{x} -\funcline{fmod}{x, y} -\funcline{frexp}{x} -\funcline{hypot}{x, y} -\funcline{ldexp}{x, y} -\funcline{log}{x} -\funcline{log10}{x} -\funcline{modf}{x} -\funcline{pow}{x, y} -\funcline{sin}{x} -\funcline{sinh}{x} -\funcline{sqrt}{x} -\funcline{tan}{x} -\funcline{tanh}{x} -\end{funcdesc} -\else -\code{acos(\varvars{x})}, -\code{asin(\varvars{x})}, -\code{atan(\varvars{x})}, -\code{atan2(\varvars{x\, y})}, -\code{ceil(\varvars{x})}, -\code{cos(\varvars{x})}, -\code{cosh(\varvars{x})}, -\code{exp(\varvars{x})}, -\code{fabs(\varvars{x})}, -\code{floor(\varvars{x})}, -\code{fmod(\varvars{x\, y})}, -\code{frexp(\varvars{x})}, -\code{hypot(\varvars{x\, y})}, -\code{ldexp(\varvars{x\, y})}, -\code{log(\varvars{x})}, -\code{log10(\varvars{x})}, -\code{modf(\varvars{x})}, -\code{pow(\varvars{x\, y})}, -\code{sin(\varvars{x})}, -\code{sinh(\varvars{x})}, -\code{sqrt(\varvars{x})}, -\code{tan(\varvars{x})}, -\code{tanh(\varvars{x})}. -\fi - -Note that \code{frexp} and \code{modf} have a different call/return -pattern than their C equivalents: they take a single argument and -return a pair of values, rather than returning their second return -value through an `output parameter' (there is no such thing in Python). - -The module also defines two mathematical constants: -\iftexi -\begin{datadesc}{pi} -\dataline{e} -\end{datadesc} -\else -\code{pi} and \code{e}. -\fi diff --git a/Doc/libmd5.tex b/Doc/libmd5.tex deleted file mode 100644 index bd26f02052..0000000000 --- a/Doc/libmd5.tex +++ /dev/null @@ -1,64 +0,0 @@ -\section{Built-in Module \sectcode{md5}} -\bimodindex{md5} - -This module implements the interface to RSA's MD5 message digest -algorithm (see also Internet RFC 1321). Its use is quite -straightforward:\ use the \code{md5.new()} to create an md5 object. -You can now feed this object with arbitrary strings using the -\code{update()} method, and at any point you can ask it for the -\dfn{digest} (a strong kind of 128-bit checksum, -a.k.a. ``fingerprint'') of the contatenation of the strings fed to it -so far using the \code{digest()} method. - -For example, to obtain the digest of the string {\tt"Nobody inspects -the spammish repetition"}: - -\bcode\begin{verbatim} ->>> import md5 ->>> m = md5.new() ->>> m.update("Nobody inspects") ->>> m.update(" the spammish repetition") ->>> m.digest() -'\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351' -\end{verbatim}\ecode - -More condensed: - -\bcode\begin{verbatim} ->>> md5.new("Nobody inspects the spammish repetition").digest() -'\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351' -\end{verbatim}\ecode - -\renewcommand{\indexsubitem}{(in module md5)} - -\begin{funcdesc}{new}{\optional{arg}} -Return a new md5 object. If \var{arg} is present, the method call -\code{update(\var{arg})} is made. -\end{funcdesc} - -\begin{funcdesc}{md5}{\optional{arg}} -For backward compatibility reasons, this is an alternative name for the -\code{new()} function. -\end{funcdesc} - -An md5 object has the following methods: - -\renewcommand{\indexsubitem}{(md5 method)} -\begin{funcdesc}{update}{arg} -Update the md5 object with the string \var{arg}. Repeated calls are -equivalent to a single call with the concatenation of all the -arguments, i.e.\ \code{m.update(a); m.update(b)} is equivalent to -\code{m.update(a+b)}. -\end{funcdesc} - -\begin{funcdesc}{digest}{} -Return the digest of the strings passed to the \code{update()} -method so far. This is an 8-byte string which may contain -non-\ASCII{} characters, including null bytes. -\end{funcdesc} - -\begin{funcdesc}{copy}{} -Return a copy (``clone'') of the md5 object. This can be used to -efficiently compute the digests of strings that share a common initial -substring. -\end{funcdesc} diff --git a/Doc/libmimetools.tex b/Doc/libmimetools.tex deleted file mode 100644 index decb89021f..0000000000 --- a/Doc/libmimetools.tex +++ /dev/null @@ -1,96 +0,0 @@ -\section{Standard Module \sectcode{mimetools}} -\stmodindex{mimetools} - -\renewcommand{\indexsubitem}{(in module mimetools)} - -This module defines a subclass of the class \code{rfc822.Message} and -a number of utility functions that are useful for the manipulation for -MIME style multipart or encoded message. - -It defines the following items: - -\begin{funcdesc}{Message}{fp} -Return a new instance of the \code{mimetools.Message} class. This is -a subclass of the \code{rfc822.Message} class, with some additional -methods (see below). -\end{funcdesc} - -\begin{funcdesc}{choose_boundary}{} -Return a unique string that has a high likelihood of being usable as a -part boundary. The string has the form -\code{"\var{hostipaddr}.\var{uid}.\var{pid}.\var{timestamp}.\var{random}"}. -\end{funcdesc} - -\begin{funcdesc}{decode}{input\, output\, encoding} -Read data encoded using the allowed MIME \var{encoding} from open file -object \var{input} and write the decoded data to open file object -\var{output}. Valid values for \var{encoding} include -\code{"base64"}, \code{"quoted-printable"} and \code{"uuencode"}. -\end{funcdesc} - -\begin{funcdesc}{encode}{input\, output\, encoding} -Read data from open file object \var{input} and write it encoded using -the allowed MIME \var{encoding} to open file object \var{output}. -Valid values for \var{encoding} are the same as for \code{decode()}. -\end{funcdesc} - -\begin{funcdesc}{copyliteral}{input\, output} -Read lines until EOF from open file \var{input} and write them to open -file \var{output}. -\end{funcdesc} - -\begin{funcdesc}{copybinary}{input\, output} -Read blocks until EOF from open file \var{input} and write them to open -file \var{output}. The block size is currently fixed at 8192. -\end{funcdesc} - - -\subsection{Additional Methods of Message objects} -\nodename{mimetools.Message Methods} - -The \code{mimetools.Message} class defines the following methods in -addition to the \code{rfc822.Message} class: - -\renewcommand{\indexsubitem}{(mimetool.Message method)} - -\begin{funcdesc}{getplist}{} -Return the parameter list of the \code{Content-type} header. This is -a list if strings. For parameters of the form -\samp{\var{key}=\var{value}}, \var{key} is converted to lower case but -\var{value} is not. For example, if the message contains the header -\samp{Content-type: text/html; spam=1; Spam=2; Spam} then -\code{getplist()} will return the Python list \code{['spam=1', -'spam=2', 'Spam']}. -\end{funcdesc} - -\begin{funcdesc}{getparam}{name} -Return the \var{value} of the first parameter (as returned by -\code{getplist()} of the form \samp{\var{name}=\var{value}} for the -given \var{name}. If \var{value} is surrounded by quotes of the form -\var{<...>} or \var{"..."}, these are removed. -\end{funcdesc} - -\begin{funcdesc}{getencoding}{} -Return the encoding specified in the \samp{Content-transfer-encoding} -message header. If no such header exists, return \code{"7bit"}. The -encoding is converted to lower case. -\end{funcdesc} - -\begin{funcdesc}{gettype}{} -Return the message type (of the form \samp{\var{type}/var{subtype}}) -as specified in the \samp{Content-type} header. If no such header -exists, return \code{"text/plain"}. The type is converted to lower -case. -\end{funcdesc} - -\begin{funcdesc}{getmaintype}{} -Return the main type as specified in the \samp{Content-type} header. -If no such header exists, return \code{"text"}. The main type is -converted to lower case. -\end{funcdesc} - -\begin{funcdesc}{getsubtype}{} -Return the subtype as specified in the \samp{Content-type} header. If -no such header exists, return \code{"plain"}. The subtype is -converted to lower case. -\end{funcdesc} diff --git a/Doc/libmisc.tex b/Doc/libmisc.tex deleted file mode 100644 index b7a726e72c..0000000000 --- a/Doc/libmisc.tex +++ /dev/null @@ -1,20 +0,0 @@ -\chapter{Miscellaneous Services} - -The modules described in this chapter provide miscellaneous services -that are available in all Python versions. Here's an overview: - -\begin{description} - -\item[math] ---- Mathematical functions (\code{sin()} etc.). - -\item[rand] ---- Integer random number generator. - -\item[whrandom] ---- Floating point random number generator. - -\item[array] ---- Efficient arrays of uniformly typed numeric values. - -\end{description} diff --git a/Doc/libmm.tex b/Doc/libmm.tex deleted file mode 100644 index d5abc6f561..0000000000 --- a/Doc/libmm.tex +++ /dev/null @@ -1,25 +0,0 @@ -\chapter{Multimedia Services} - -The modules described in this chapter implement various algorithms or -interfaces that are mainly useful for multimedia applications. They -are available at the discretion of the installation. Here's an overview: - -\begin{description} - -\item[audioop] ---- Manipulate raw audio data. - -\item[imageop] ---- Manipulate raw image data. - -\item[aifc] ---- Read and write audio files in AIFF or AIFC format. - -\item[jpeg] ---- Read and write image files in compressed JPEG format. - -\item[rgbimg] ---- Read and write image files in ``SGI RGB'' format (the module is -\emph{not} SGI specific though)! - -\end{description} diff --git a/Doc/libmods.tex b/Doc/libmods.tex deleted file mode 100755 index 5bc6ee21e3..0000000000 --- a/Doc/libmods.tex +++ /dev/null @@ -1,7 +0,0 @@ -\chapter{Built-in Modules} - -The modules described in this chapter are built into the interpreter -and considered part of Python's standard environment: they are always -available.\footnote{at least in theory --- it is possible to specify -at build time that one or more of these modules should be excluded, -but it would be antisocial to do so.} diff --git a/Doc/libmpz.tex b/Doc/libmpz.tex deleted file mode 100644 index 46a2d474dc..0000000000 --- a/Doc/libmpz.tex +++ /dev/null @@ -1,78 +0,0 @@ -\section{Built-in Module \sectcode{mpz}} -\bimodindex{mpz} - -This is an optional module. It is only available when Python is -configured to include it, which requires that the GNU MP software is -installed. - -This module implements the interface to part of the GNU MP library, -which defines arbitrary precision integer and rational number -arithmetic routines. Only the interfaces to the \emph{integer} -(\samp{mpz_{\rm \ldots}}) routines are provided. If not stated -otherwise, the description in the GNU MP documentation can be applied. - -In general, \dfn{mpz}-numbers can be used just like other standard -Python numbers, e.g.\ you can use the built-in operators like \code{+}, -\code{*}, etc., as well as the standard built-in functions like -\code{abs}, \code{int}, \ldots, \code{divmod}, \code{pow}. -\strong{Please note:} the {\it bitwise-xor} operation has been implemented as -a bunch of {\it and}s, {\it invert}s and {\it or}s, because the library -lacks an \code{mpz_xor} function, and I didn't need one. - -You create an mpz-number by calling the function called \code{mpz} (see -below for an exact description). An mpz-number is printed like this: -\code{mpz(\var{value})}. - -\renewcommand{\indexsubitem}{(in module mpz)} -\begin{funcdesc}{mpz}{value} - Create a new mpz-number. \var{value} can be an integer, a long, - another mpz-number, or even a string. If it is a string, it is - interpreted as an array of radix-256 digits, least significant digit - first, resulting in a positive number. See also the \code{binary} - method, described below. -\end{funcdesc} - -A number of {\em extra} functions are defined in this module. Non -mpz-arguments are converted to mpz-values first, and the functions -return mpz-numbers. - -\begin{funcdesc}{powm}{base\, exponent\, modulus} - Return \code{pow(\var{base}, \var{exponent}) \%{} \var{modulus}}. If - \code{\var{exponent} == 0}, return \code{mpz(1)}. In contrast to the - \C-library function, this version can handle negative exponents. -\end{funcdesc} - -\begin{funcdesc}{gcd}{op1\, op2} - Return the greatest common divisor of \var{op1} and \var{op2}. -\end{funcdesc} - -\begin{funcdesc}{gcdext}{a\, b} - Return a tuple \code{(\var{g}, \var{s}, \var{t})}, such that - \code{\var{a}*\var{s} + \var{b}*\var{t} == \var{g} == gcd(\var{a}, \var{b})}. -\end{funcdesc} - -\begin{funcdesc}{sqrt}{op} - Return the square root of \var{op}. The result is rounded towards zero. -\end{funcdesc} - -\begin{funcdesc}{sqrtrem}{op} - Return a tuple \code{(\var{root}, \var{remainder})}, such that - \code{\var{root}*\var{root} + \var{remainder} == \var{op}}. -\end{funcdesc} - -\begin{funcdesc}{divm}{numerator\, denominator\, modulus} - Returns a number \var{q}. such that - \code{\var{q} * \var{denominator} \%{} \var{modulus} == \var{numerator}}. - One could also implement this function in Python, using \code{gcdext}. -\end{funcdesc} - -An mpz-number has one method: - -\renewcommand{\indexsubitem}{(mpz method)} -\begin{funcdesc}{binary}{} - Convert this mpz-number to a binary string, where the number has been - stored as an array of radix-256 digits, least significant digit first. - - The mpz-number must have a value greater than or equal to zero, - otherwise a \code{ValueError}-exception will be raised. -\end{funcdesc} diff --git a/Doc/libnntplib.tex b/Doc/libnntplib.tex deleted file mode 100644 index e17ea8b488..0000000000 --- a/Doc/libnntplib.tex +++ /dev/null @@ -1,212 +0,0 @@ -\section{Standard Module \sectcode{nntplib}} -\stmodindex{nntplib} - -\renewcommand{\indexsubitem}{(in module nntplib)} - -This module defines the class \code{NNTP} which implements the client -side of the NNTP protocol. It can be used to implement a news reader -or poster, or automated news processors. For more information on NNTP -(Network News Transfer Protocol), see Internet RFC 977. - -Here are two small examples of how it can be used. To list some -statistics about a newsgroup and print the subjects of the last 10 -articles: - -\small{ -\begin{verbatim} ->>> s = NNTP('news.cwi.nl') ->>> resp, count, first, last, name = s.group('comp.lang.python') ->>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last -Group comp.lang.python has 59 articles, range 3742 to 3803 ->>> resp, subs = s.xhdr('subject', first + '-' + last) ->>> for id, sub in subs[-10:]: print id, sub -... -3792 Re: Removing elements from a list while iterating... -3793 Re: Who likes Info files? -3794 Emacs and doc strings -3795 a few questions about the Mac implementation -3796 Re: executable python scripts -3797 Re: executable python scripts -3798 Re: a few questions about the Mac implementation -3799 Re: PROPOSAL: A Generic Python Object Interface for Python C Modules -3802 Re: executable python scripts -3803 Re: POSIX wait and SIGCHLD ->>> s.quit() -'205 news.cwi.nl closing connection. Goodbye.' ->>> -\end{verbatim} -} - -To post an article from a file (this assumes that the article has -valid headers): - -\begin{verbatim} ->>> s = NNTP('news.cwi.nl') ->>> f = open('/tmp/article') ->>> s.post(f) -'240 Article posted successfully.' ->>> s.quit() -'205 news.cwi.nl closing connection. Goodbye.' ->>> -\end{verbatim} - -The module itself defines the following items: - -\begin{funcdesc}{NNTP}{host\optional{\, port}} -Return a new instance of the \code{NNTP} class, representing a -connection to the NNTP server running on host \var{host}, listening at -port \var{port}. The default \var{port} is 119. -\end{funcdesc} - -\begin{excdesc}{error_reply} -Exception raised when an unexpected reply is received from the server. -\end{excdesc} - -\begin{excdesc}{error_temp} -Exception raised when an error code in the range 400--499 is received. -\end{excdesc} - -\begin{excdesc}{error_perm} -Exception raised when an error code in the range 500--599 is received. -\end{excdesc} - -\begin{excdesc}{error_proto} -Exception raised when a reply is received from the server that does -not begin with a digit in the range 1--5. -\end{excdesc} - -\subsection{NNTP Objects} - -NNTP instances have the following methods. The \var{response} that is -returned as the first item in the return tuple of almost all methods -is the server's response: a string beginning with a three-digit code. -If the server's response indicates an error, the method raises one of -the above exceptions. - -\renewcommand{\indexsubitem}{(NNTP object method)} - -\begin{funcdesc}{getwelcome}{} -Return the welcome message sent by the server in reply to the initial -connection. (This message sometimes contains disclaimers or help -information that may be relevant to the user.) -\end{funcdesc} - -\begin{funcdesc}{set_debuglevel}{level} -Set the instance's debugging level. This controls the amount of -debugging output printed. The default, 0, produces no debugging -output. A value of 1 produces a moderate amount of debugging output, -generally a single line per request or response. A value of 2 or -higher produces the maximum amount of debugging output, logging each -line sent and received on the connection (including message text). -\end{funcdesc} - -\begin{funcdesc}{newgroups}{date\, time} -Send a \samp{NEWGROUPS} command. The \var{date} argument should be a -string of the form \code{"\var{yy}\var{mm}\var{dd}"} indicating the -date, and \var{time} should be a string of the form -\code{"\var{hh}\var{mm}\var{ss}"} indicating the time. Return a pair -\code{(\var{response}, \var{groups})} where \var{groups} is a list of -group names that are new since the given date and time. -\end{funcdesc} - -\begin{funcdesc}{newnews}{group\, date\, time} -Send a \samp{NEWNEWS} command. Here, \var{group} is a group name or -\code{"*"}, and \var{date} and \var{time} have the same meaning as for -\code{newgroups()}. Return a pair \code{(\var{response}, -\var{articles})} where \var{articles} is a list of article ids. -\end{funcdesc} - -\begin{funcdesc}{list}{} -Send a \samp{LIST} command. Return a pair \code{(\var{response}, -\var{list})} where \var{list} is a list of tuples. Each tuple has the -form \code{(\var{group}, \var{last}, \var{first}, \var{flag})}, where -\var{group} is a group name, \var{last} and \var{first} are the last -and first article numbers (as strings), and \var{flag} is \code{'y'} -if posting is allowed, \code{'n'} if not, and \code{'m'} if the -newsgroup is moderated. (Note the ordering: \var{last}, \var{first}.) -\end{funcdesc} - -\begin{funcdesc}{group}{name} -Send a \samp{GROUP} command, where \var{name} is the group name. -Return a tuple \code{(\var{response}, \var{count}, \var{first}, -\var{last}, \var{name})} where \var{count} is the (estimated) number -of articles in the group, \var{first} is the first article number in -the group, \var{last} is the last article number in the group, and -\var{name} is the group name. The numbers are returned as strings. -\end{funcdesc} - -\begin{funcdesc}{help}{} -Send a \samp{HELP} command. Return a pair \code{(\var{response}, -\var{list})} where \var{list} is a list of help strings. -\end{funcdesc} - -\begin{funcdesc}{stat}{id} -Send a \samp{STAT} command, where \var{id} is the message id (enclosed -in \samp{<} and \samp{>}) or an article number (as a string). -Return a triple \code{(var{response}, \var{number}, \var{id})} where -\var{number} is the article number (as a string) and \var{id} is the -article id (enclosed in \samp{<} and \samp{>}). -\end{funcdesc} - -\begin{funcdesc}{next}{} -Send a \samp{NEXT} command. Return as for \code{stat()}. -\end{funcdesc} - -\begin{funcdesc}{last}{} -Send a \samp{LAST} command. Return as for \code{stat()}. -\end{funcdesc} - -\begin{funcdesc}{head}{id} -Send a \samp{HEAD} command, where \var{id} has the same meaning as for -\code{stat()}. Return a pair \code{(\var{response}, \var{list})} -where \var{list} is a list of the article's headers (an uninterpreted -list of lines, without trailing newlines). -\end{funcdesc} - -\begin{funcdesc}{body}{id} -Send a \samp{BODY} command, where \var{id} has the same meaning as for -\code{stat()}. Return a pair \code{(\var{response}, \var{list})} -where \var{list} is a list of the article's body text (an -uninterpreted list of lines, without trailing newlines). -\end{funcdesc} - -\begin{funcdesc}{article}{id} -Send a \samp{ARTICLE} command, where \var{id} has the same meaning as -for \code{stat()}. Return a pair \code{(\var{response}, \var{list})} -where \var{list} is a list of the article's header and body text (an -uninterpreted list of lines, without trailing newlines). -\end{funcdesc} - -\begin{funcdesc}{slave}{} -Send a \samp{SLAVE} command. Return the server's \var{response}. -\end{funcdesc} - -\begin{funcdesc}{xhdr}{header\, string} -Send an \samp{XHDR} command. This command is not defined in the RFC -but is a common extension. The \var{header} argument is a header -keyword, e.g. \code{"subject"}. The \var{string} argument should have -the form \code{"\var{first}-\var{last}"} where \var{first} and -\var{last} are the first and last article numbers to search. Return a -pair \code{(\var{response}, \var{list})}, where \var{list} is a list of -pairs \code{(\var{id}, \var{text})}, where \var{id} is an article id -(as a string) and \var{text} is the text of the requested header for -that article. -\end{funcdesc} - -\begin{funcdesc}{post}{file} -Post an article using the \samp{POST} command. The \var{file} -argument is an open file object which is read until EOF using its -\code{readline()} method. It should be a well-formed news article, -including the required headers. The \code{post()} method -automatically escapes lines beginning with \samp{.}. -\end{funcdesc} - -\begin{funcdesc}{ihave}{id\, file} -Send an \samp{IHAVE} command. If the response is not an error, treat -\var{file} exactly as for the \code{post()} method. -\end{funcdesc} - -\begin{funcdesc}{quit}{} -Send a \samp{QUIT} command and close the connection. Once this method -has been called, no other methods of the NNTP object should be called. -\end{funcdesc} diff --git a/Doc/libobjs.tex b/Doc/libobjs.tex deleted file mode 100644 index b4dd409c6d..0000000000 --- a/Doc/libobjs.tex +++ /dev/null @@ -1,25 +0,0 @@ -\chapter{Built-in Types, Exceptions and Functions} - -\nodename{Built-in Objects} - -Names for built-in exceptions and functions are found in a separate -symbol table. This table is searched last when the interpreter looks -up the meaning of a name, so local and global -user-defined names can override built-in names. Built-in types are -described together here for easy reference.% -\footnote{Most descriptions sorely lack explanations of the exceptions - that may be raised --- this will be fixed in a future version of - this manual.} -\indexii{built-in}{types} -\indexii{built-in}{exceptions} -\indexii{built-in}{functions} -\index{symbol table} -\bifuncindex{type} - -The tables in this chapter document the priorities of operators by -listing them in order of ascending priority (within a table) and -grouping operators that have the same priority in the same box. -Binary operators of the same priority group from left to right. -(Unary operators group from right to left, but there you have no real -choice.) See Chapter 5 of the Python Reference Manual for the -complete picture on operator priorities. diff --git a/Doc/libos.tex b/Doc/libos.tex deleted file mode 100644 index 51442efcfc..0000000000 --- a/Doc/libos.tex +++ /dev/null @@ -1,104 +0,0 @@ -\section{Standard Module \sectcode{os}} - -\stmodindex{os} -This module provides a more portable way of using operating system -(OS) dependent functionality than importing an OS dependent built-in -module like \code{posix}. - -When the optional built-in module \code{posix} is available, this -module exports the same functions and data as \code{posix}; otherwise, -it searches for an OS dependent built-in module like \code{mac} and -exports the same functions and data as found there. The design of all -Python's built-in OS dependent modules is such that as long as the same -functionality is available, it uses the same interface; e.g., the -function \code{os.stat(\var{file})} returns stat info about a \var{file} in a -format compatible with the POSIX interface. - -Extensions peculiar to a particular OS are also available through the -\code{os} module, but using them is of course a threat to portability! - -Note that after the first time \code{os} is imported, there is \emph{no} -performance penalty in using functions from \code{os} instead of -directly from the OS dependent built-in module, so there should be -\emph{no} reason not to use \code{os}! - -In addition to whatever the correct OS dependent module exports, the -following variables and functions are always exported by \code{os}: - -\renewcommand{\indexsubitem}{(in module os)} - -\begin{datadesc}{name} -The name of the OS dependent module imported. The following names -have currently been registered: \code{'posix'}, \code{'nt'}, -\code{'dos'}, \code{'mac'}. -\end{datadesc} - -\begin{datadesc}{path} -The corresponding OS dependent standard module for pathname -operations, e.g., \code{posixpath} or \code{macpath}. Thus, (given -the proper imports), \code{os.path.split(\var{file})} is equivalent to but -more portable than \code{posixpath.split(\var{file})}. -\end{datadesc} - -\begin{datadesc}{curdir} -The constant string used by the OS to refer to the current directory, -e.g. \code{'.'} for POSIX or \code{':'} for the Mac. -\end{datadesc} - -\begin{datadesc}{pardir} -The constant string used by the OS to refer to the parent directory, -e.g. \code{'..'} for POSIX or \code{'::'} for the Mac. -\end{datadesc} - -\begin{datadesc}{sep} -The character used by the OS to separate pathname components, e.g.\ -\code{'/'} for POSIX or \code{':'} for the Mac. Note that knowing this -is not sufficient to be able to parse or concatenate pathnames---better -use \code{os.path.split()} and \code{os.path.join()}---but it is -occasionally useful. -\end{datadesc} - -\begin{datadesc}{pathsep} -The character conventionally used by the OS to separate search patch -components (as in \code{\$PATH}), e.g.\ \code{':'} for POSIX or -\code{';'} for MS-DOS. -\end{datadesc} - -\begin{datadesc}{defpath} -The default search path used by \code{os.exec*p*()} if the environment -doesn't have a \code{'PATH'} key. -\end{datadesc} - -\begin{funcdesc}{execl}{path\, arg0\, arg1\, ...} -This is equivalent to -\code{os.execv(\var{path}, (\var{arg0}, \var{arg1}, ...))}. -\end{funcdesc} - -\begin{funcdesc}{execle}{path\, arg0\, arg1\, ...\, env} -This is equivalent to -\code{os.execve(\var{path}, (\var{arg0}, \var{arg1}, ...), \var{env})}. -\end{funcdesc} - -\begin{funcdesc}{execlp}{path\, arg0\, arg1\, ...} -This is equivalent to -\code{os.execvp(\var{path}, (\var{arg0}, \var{arg1}, ...))}. -\end{funcdesc} - -\begin{funcdesc}{execvp}{path\, args} -This is like \code{os.execv(\var{path}, \var{args})} but duplicates -the shell's actions in searching for an executable file in a list of -directories. The directory list is obtained from -\code{os.environ['PATH']}. -\end{funcdesc} - -\begin{funcdesc}{execvpe}{path\, args\, env} -This is a cross between \code{os.execve()} and \code{os.execvp()}. -The directory list is obtained from \code{\var{env}['PATH']}. -\end{funcdesc} - -(The functions \code{os.execv()} and \code{execve()} are not -documented here, since they are implemented by the OS dependent -module. If the OS dependent module doesn't define either of these, -the functions that rely on it will raise an exception. They are -documented in the section on module \code{posix}, together with all -other functions that \code{os} imports from the OS dependent module.) diff --git a/Doc/libpanel.tex b/Doc/libpanel.tex deleted file mode 100644 index b82bf98bfe..0000000000 --- a/Doc/libpanel.tex +++ /dev/null @@ -1,66 +0,0 @@ -\section{Standard Module \sectcode{panel}} -\stmodindex{panel} - -\strong{Please note:} The FORMS library, to which the \code{fl} module described -above interfaces, is a simpler and more accessible user interface -library for use with GL than the Panel Module (besides also being by a -Dutch author). - -This module should be used instead of the built-in module -\code{pnl} -to interface with the -{\em Panel Library}. - -The module is too large to document here in its entirety. -One interesting function: - -\renewcommand{\indexsubitem}{(in module panel)} -\begin{funcdesc}{defpanellist}{filename} -Parses a panel description file containing S-expressions written by the -{\em Panel Editor} -that accompanies the Panel Library and creates the described panels. -It returns a list of panel objects. -\end{funcdesc} - -\strong{Warning:} -the Python interpreter will dump core if you don't create a GL window -before calling -\code{panel.mkpanel()} -or -\code{panel.defpanellist()}. - -\section{Standard Module \sectcode{panelparser}} -\stmodindex{panelparser} - -This module defines a self-contained parser for S-expressions as output -by the Panel Editor (which is written in Scheme so it can't help writing -S-expressions). -The relevant function is -\code{panelparser.parse_file(\var{file})} -which has a file object (not a filename!) as argument and returns a list -of parsed S-expressions. -Each S-expression is converted into a Python list, with atoms converted -to Python strings and sub-expressions (recursively) to Python lists. -For more details, read the module file. -% XXXXJH should be funcdesc, I think - -\section{Built-in Module \sectcode{pnl}} -\bimodindex{pnl} - -This module provides access to the -{\em Panel Library} -built by NASA Ames (to get it, send e-mail to -{\tt panel-request@nas.nasa.gov}). -All access to it should be done through the standard module -\code{panel}, -which transparantly exports most functions from -\code{pnl} -but redefines -\code{pnl.dopanel()}. - -\strong{Warning:} -the Python interpreter will dump core if you don't create a GL window -before calling -\code{pnl.mkpanel()}. - -The module is too large to document here in its entirety. diff --git a/Doc/libparser.tex b/Doc/libparser.tex deleted file mode 100644 index 1f5d4fda75..0000000000 --- a/Doc/libparser.tex +++ /dev/null @@ -1,250 +0,0 @@ -% libparser.tex -% -% Introductory documentation for the new parser built-in module. -% -% Copyright 1995 Virginia Polytechnic Institute and State University -% and Fred L. Drake, Jr. This copyright notice must be distributed on -% all copies, but this document otherwise may be distributed as part -% of the Python distribution. No fee may be charged for this document -% in any representation, either on paper or electronically. This -% restriction does not affect other elements in a distributed package -% in any way. -% - -\section{Built-in Module \sectcode{parser}} -\bimodindex{parser} - - -% ==== 2. ==== -% Give a short overview of what the module does. -% If it is platform specific, mention this. -% Mention other important restrictions or general operating principles. - -The \code{parser} module provides an interface to Python's internal -parser and byte-code compiler. The primary purpose for this interface -is to allow Python code to edit the parse tree of a Python expression -and create executable code from this. This can be better than trying -to parse and modify an arbitrary Python code fragment as a string, and -ensures that parsing is performed in a manner identical to the code -forming the application. It's also faster. - -There are a few things to note about this module which are important -to making use of the data structures created. This is not a tutorial -on editing the parse trees for Python code. - -Most importantly, a good understanding of the Python grammar processed -by the internal parser is required. For full information on the -language syntax, refer to the Language Reference. The parser itself -is created from a grammar specification defined in the file -\code{Grammar/Grammar} in the standard Python distribution. The parse -trees stored in the ``AST objects'' created by this module are the -actual output from the internal parser when created by the -\code{expr()} or \code{suite()} functions, described below. The AST -objects created by \code{tuple2ast()} faithfully simulate those -structures. - -Each element of the tuples returned by \code{ast2tuple()} has a simple -form. Tuples representing non-terminal elements in the grammar always -have a length greater than one. The first element is an integer which -identifies a production in the grammar. These integers are given -symbolic names in the C header file \code{Include/graminit.h} and the -Python module \code{Lib/symbol.py}. Each additional element of the -tuple represents a component of the production as recognized in the -input string: these are always tuples which have the same form as the -parent. An important aspect of this structure which should be noted -is that keywords used to identify the parent node type, such as the -keyword \code{if} in an \emph{if\_stmt}, are included in the node tree -without any special treatment. For example, the \code{if} keyword is -represented by the tuple \code{(1, 'if')}, where \code{1} is the -numeric value associated with all \code{NAME} elements, including -variable and function names defined by the user. - -Terminal elements are represented in much the same way, but without -any child elements and the addition of the source text which was -identified. The example of the \code{if} keyword above is -representative. The various types of terminal symbols are defined in -the C header file \code{Include/token.h} and the Python module -\code{Lib/token.py}. - -The AST objects are not actually required to support the functionality -of this module, but are provided for three purposes: to allow an -application to amortize the cost of processing complex parse trees, to -provide a parse tree representation which conserves memory space when -compared to the Python tuple representation, and to ease the creation -of additional modules in C which manipulate parse trees. A simple -``wrapper'' module may be created in Python if desired to hide the use -of AST objects. - - -% ==== 3. ==== -% List the public functions defined by the module. Begin with a -% standard phrase. You may also list the exceptions and other data -% items defined in the module, insofar as they are important for the -% user. - -The \code{parser} module defines the following functions: - -% ---- 3.1. ---- -% Redefine the ``indexsubitem'' macro to point to this module -% (alternatively, you can put this at the top of the file): - -\renewcommand{\indexsubitem}{(in module parser)} - -% ---- 3.2. ---- -% For each function, use a ``funcdesc'' block. This has exactly two -% parameters (each parameters is contained in a set of curly braces): -% the first parameter is the function name (this automatically -% generates an index entry); the second parameter is the function's -% argument list. If there are no arguments, use an empty pair of -% curly braces. If there is more than one argument, separate the -% arguments with backslash-comma. Optional parts of the parameter -% list are contained in \optional{...} (this generates a set of square -% brackets around its parameter). Arguments are automatically set in -% italics in the parameter list. Each argument should be mentioned at -% least once in the description; each usage (even inside \code{...}) -% should be enclosed in \var{...}. - -\begin{funcdesc}{ast2tuple}{ast} -This function accepts an AST object from the caller in -\code{\var{ast}} and returns a Python tuple representing the -equivelent parse tree. The resulting tuple representation can be used -for inspection or the creation of a new parse tree in tuple form. -This function does not fail so long as memory is available to build -the tuple representation. -\end{funcdesc} - - -\begin{funcdesc}{compileast}{ast\optional{\, filename \code{= '<ast>'}}} -The Python byte compiler can be invoked on an AST object to produce -code objects which can be used as part of an \code{exec} statement or -a call to the built-in \code{eval()} function. This function provides -the interface to the compiler, passing the internal parse tree from -\code{\var{ast}} to the parser, using the source file name specified -by the \code{\var{filename}} parameter. The default value supplied -for \code{\var{filename}} indicates that the source was an AST object. -\end{funcdesc} - - -\begin{funcdesc}{expr}{string} -The \code{expr()} function parses the parameter \code{\var{string}} -as if it were an input to \code{compile(\var{string}, 'eval')}. If -the parse succeeds, an AST object is created to hold the internal -parse tree representation, otherwise an appropriate exception is -thrown. -\end{funcdesc} - - -\begin{funcdesc}{isexpr}{ast} -When \code{\var{ast}} represents an \code{'eval'} form, this function -returns a true value (\code{1}), otherwise it returns false -(\code{0}). This is useful, since code objects normally cannot be -queried for this information using existing built-in functions. Note -that the code objects created by \code{compileast()} cannot be queried -like this either, and are identical to those created by the built-in -\code{compile()} function. -\end{funcdesc} - - -\begin{funcdesc}{issuite}{ast} -This function mirrors \code{isexpr()} in that it reports whether an -AST object represents a suite of statements. It is not safe to assume -that this function is equivelent to \code{not isexpr(\var{ast})}, as -additional syntactic fragments may be supported in the future. -\end{funcdesc} - - -\begin{funcdesc}{suite}{string} -The \code{suite()} function parses the parameter \code{\var{string}} -as if it were an input to \code{compile(\var{string}, 'exec')}. If -the parse succeeds, an AST object is created to hold the internal -parse tree representation, otherwise an appropriate exception is -thrown. -\end{funcdesc} - - -\begin{funcdesc}{tuple2ast}{tuple} -This function accepts a parse tree represented as a tuple and builds -an internal representation if possible. If it can validate that the -tree conforms to the Python syntax and all nodes are valid node types -in the host version of Python, an AST object is created from the -internal representation and returned to the called. If there is a -problem creating the internal representation, or if the tree cannot be -validated, a \code{ParserError} exception is thrown. An AST object -created this way should not be assumed to compile correctly; normal -exceptions thrown by compilation may still be initiated when the AST -object is passed to \code{compileast()}. This will normally indicate -problems not related to syntax (such as a \code{MemoryError} -exception). -\end{funcdesc} - - -% --- 3.4. --- -% Exceptions are described using a ``excdesc'' block. This has only -% one parameter: the exception name. - -\subsection{Exceptions and Error Handling} - -The parser module defines a single exception, but may also pass other -built-in exceptions from other portions of the Python runtime -environment. See each function for information about the exceptions -it can raise. - -\begin{excdesc}{ParserError} -Exception raised when a failure occurs within the parser module. This -is generally produced for validation failures rather than the built in -\code{SyntaxError} thrown during normal parsing. -The exception argument is either a string describing the reason of the -failure or a tuple containing a tuple causing the failure from a parse -tree passed to \code{tuple2ast()} and an explanatory string. Calls to -\code{tuple2ast()} need to be able to handle either type of exception, -while calls to other functions in the module will only need to be -aware of the simple string values. -\end{excdesc} - -Note that the functions \code{compileast()}, \code{expr()}, and -\code{suite()} may throw exceptions which are normally thrown by the -parsing and compilation process. These include the built in -exceptions \code{MemoryError}, \code{OverflowError}, -\code{SyntaxError}, and \code{SystemError}. In these cases, these -exceptions carry all the meaning normally associated with them. Refer -to the descriptions of each function for detailed information. - -% ---- 3.5. ---- -% There is no standard block type for classes. I generally use -% ``funcdesc'' blocks, since class instantiation looks very much like -% a function call. - - -% ==== 4. ==== -% Now is probably a good time for a complete example. (Alternatively, -% an example giving the flavor of the module may be given before the -% detailed list of functions.) - -\subsection{Example} - -A simple example: - -\begin{verbatim} ->>> import parser ->>> ast = parser.expr('a + 5') ->>> code = parser.compileast(ast) ->>> a = 5 ->>> eval(code) -10 -\end{verbatim} - - -\subsection{AST Objects} - -AST objects (returned by \code{expr()}, \code{suite()}, and -\code{tuple2ast()}, described above) have no methods of their own. -Some of the functions defined which accept an AST object as their -first argument may change to object methods in the future. - -Ordered and equality comparisons are supported between AST objects. - -\renewcommand{\indexsubitem}{(ast method)} - -%\begin{funcdesc}{empty}{} -%Empty the can into the trash. -%\end{funcdesc} diff --git a/Doc/libpdb.tex b/Doc/libpdb.tex deleted file mode 100644 index a439363734..0000000000 --- a/Doc/libpdb.tex +++ /dev/null @@ -1,303 +0,0 @@ -\chapter{The Python Debugger} -\stmodindex{pdb} -\index{debugging} - -\renewcommand{\indexsubitem}{(in module pdb)} - -The module \code{pdb} defines an interactive source code debugger for -Python programs. It supports setting breakpoints and single stepping -at the source line level, inspection of stack frames, source code -listing, and evaluation of arbitrary Python code in the context of any -stack frame. It also supports post-mortem debugging and can be called -under program control. - -The debugger is extensible --- it is actually defined as a class -\code{Pdb}. This is currently undocumented but easily understood by -reading the source. The extension interface uses the (also -undocumented) modules \code{bdb} and \code{cmd}. -\ttindex{Pdb} -\ttindex{bdb} -\ttindex{cmd} - -A primitive windowing version of the debugger also exists --- this is -module \code{wdb}, which requires STDWIN (see the chapter on STDWIN -specific modules). -\index{stdwin} -\ttindex{wdb} - -The debugger's prompt is ``\code{(Pdb) }''. -Typical usage to run a program under control of the debugger is: - -\begin{verbatim} ->>> import pdb ->>> import mymodule ->>> pdb.run('mymodule.test()') -> <string>(0)?() -(Pdb) continue -> <string>(1)?() -(Pdb) continue -NameError: 'spam' -> <string>(1)?() -(Pdb) -\end{verbatim} - -Typical usage to inspect a crashed program is: - -\begin{verbatim} ->>> import pdb ->>> import mymodule ->>> mymodule.test() -Traceback (innermost last): - File "<stdin>", line 1, in ? - File "./mymodule.py", line 4, in test - test2() - File "./mymodule.py", line 3, in test2 - print spam -NameError: spam ->>> pdb.pm() -> ./mymodule.py(3)test2() --> print spam -(Pdb) -\end{verbatim} - -The module defines the following functions; each enters the debugger -in a slightly different way: - -\begin{funcdesc}{run}{statement\optional{\, globals\optional{\, locals}}} -Execute the \var{statement} (given as a string) under debugger -control. The debugger prompt appears before any code is executed; you -can set breakpoints and type \code{continue}, or you can step through -the statement using \code{step} or \code{next} (all these commands are -explained below). The optional \var{globals} and \var{locals} -arguments specify the environment in which the code is executed; by -default the dictionary of the module \code{__main__} is used. (See -the explanation of the \code{exec} statement or the \code{eval()} -built-in function.) -\end{funcdesc} - -\begin{funcdesc}{runeval}{expression\optional{\, globals\optional{\, locals}}} -Evaluate the \var{expression} (given as a a string) under debugger -control. When \code{runeval()} returns, it returns the value of the -expression. Otherwise this function is similar to -\code{run()}. -\end{funcdesc} - -\begin{funcdesc}{runcall}{function\optional{\, argument\, ...}} -Call the \var{function} (a function or method object, not a string) -with the given arguments. When \code{runcall()} returns, it returns -whatever the function call returned. The debugger prompt appears as -soon as the function is entered. -\end{funcdesc} - -\begin{funcdesc}{set_trace}{} -Enter the debugger at the calling stack frame. This is useful to -hard-code a breakpoint at a given point in a program, even if the code -is not otherwise being debugged (e.g. when an assertion fails). -\end{funcdesc} - -\begin{funcdesc}{post_mortem}{traceback} -Enter post-mortem debugging of the given \var{traceback} object. -\end{funcdesc} - -\begin{funcdesc}{pm}{} -Enter post-mortem debugging of the traceback found in -\code{sys.last_traceback}. -\end{funcdesc} - -\section{Debugger Commands} - -The debugger recognizes the following commands. Most commands can be -abbreviated to one or two letters; e.g. ``\code{h(elp)}'' means that -either ``\code{h}'' or ``\code{help}'' can be used to enter the help -command (but not ``\code{he}'' or ``\code{hel}'', nor ``\code{H}'' or -``\code{Help} or ``\code{HELP}''). Arguments to commands must be -separated by whitespace (spaces or tabs). Optional arguments are -enclosed in square brackets (``\code{[]}'') in the command syntax; the -square brackets must not be typed. Alternatives in the command syntax -are separated by a vertical bar (``\code{|}''). - -Entering a blank line repeats the last command entered. Exception: if -the last command was a ``\code{list}'' command, the next 11 lines are -listed. - -Commands that the debugger doesn't recognize are assumed to be Python -statements and are executed in the context of the program being -debugged. Python statements can also be prefixed with an exclamation -point (``\code{!}''). This is a powerful way to inspect the program -being debugged; it is even possible to change a variable or call a -function. When an -exception occurs in such a statement, the exception name is printed -but the debugger's state is not changed. - -\begin{description} - -\item[h(elp) [\var{command}]] - -Without argument, print the list of available commands. -With a \var{command} as argument, print help about that command. -``\code{help pdb}'' displays the full documentation file; if the -environment variable \code{PAGER} is defined, the file is piped -through that command instead. Since the \var{command} argument must be -an identifier, ``\code{help exec}'' must be entered to get help on the -``\code{!}'' command. - -\item[w(here)] - -Print a stack trace, with the most recent frame at the bottom. -An arrow indicates the current frame, which determines the -context of most commands. - -\item[d(own)] - -Move the current frame one level down in the stack trace -(to an older frame). - -\item[u(p)] - -Move the current frame one level up in the stack trace -(to a newer frame). - -\item[b(reak) [\var{lineno}\code{|}\var{function}]] - -With a \var{lineno} argument, set a break there in the current -file. With a \var{function} argument, set a break at the entry of -that function. Without argument, list all breaks. - -\item[cl(ear) [\var{lineno}]] - -With a \var{lineno} argument, clear that break in the current file. -Without argument, clear all breaks (but first ask confirmation). - -\item[s(tep)] - -Execute the current line, stop at the first possible occasion -(either in a function that is called or on the next line in the -current function). - -\item[n(ext)] - -Continue execution until the next line in the current function -is reached or it returns. (The difference between \code{next} and -\code{step} is that \code{step} stops inside a called function, while -\code{next} executes called functions at (nearly) full speed, only -stopping at the next line in the current function.) - -\item[r(eturn)] - -Continue execution until the current function returns. - -\item[c(ont(inue))] - -Continue execution, only stop when a breakpoint is encountered. - -\item[l(ist) [\var{first} [, \var{last}]]] - -List source code for the current file. Without arguments, list 11 -lines around the current line or continue the previous listing. With -one argument, list 11 lines around at that line. With two arguments, -list the given range; if the second argument is less than the first, -it is interpreted as a count. - -\item[a(rgs)] - -Print the argument list of the current function. - -\item[p \var{expression}] - -Evaluate the \var{expression} in the current context and print its -value. (Note: \code{print} can also be used, but is not a debugger -command --- this executes the Python \code{print} statement.) - -\item[[!] \var{statement}] - -Execute the (one-line) \var{statement} in the context of -the current stack frame. -The exclamation point can be omitted unless the first word -of the statement resembles a debugger command. -To set a global variable, you can prefix the assignment -command with a ``\code{global}'' command on the same line, e.g.: -\begin{verbatim} -(Pdb) global list_options; list_options = ['-l'] -(Pdb) -\end{verbatim} - -\item[q(uit)] - -Quit from the debugger. -The program being executed is aborted. - -\end{description} - -\section{How It Works} - -Some changes were made to the interpreter: - -\begin{itemize} -\item sys.settrace(func) sets the global trace function -\item there can also a local trace function (see later) -\end{itemize} - -Trace functions have three arguments: (\var{frame}, \var{event}, \var{arg}) - -\begin{description} - -\item[\var{frame}] is the current stack frame - -\item[\var{event}] is a string: \code{'call'}, \code{'line'}, \code{'return'} -or \code{'exception'} - -\item[\var{arg}] is dependent on the event type - -\end{description} - -A trace function should return a new trace function or None. -Class methods are accepted (and most useful!) as trace methods. - -The events have the following meaning: - -\begin{description} - -\item[\code{'call'}] -A function is called (or some other code block entered). The global -trace function is called; arg is the argument list to the function; -the return value specifies the local trace function. - -\item[\code{'line'}] -The interpreter is about to execute a new line of code (sometimes -multiple line events on one line exist). The local trace function is -called; arg in None; the return value specifies the new local trace -function. - -\item[\code{'return'}] -A function (or other code block) is about to return. The local trace -function is called; arg is the value that will be returned. The trace -function's return value is ignored. - -\item[\code{'exception'}] -An exception has occurred. The local trace function is called; arg is -a triple (exception, value, traceback); the return value specifies the -new local trace function - -\end{description} - -Note that as an exception is propagated down the chain of callers, an -\code{'exception'} event is generated at each level. - -Stack frame objects have the following read-only attributes: - -\begin{description} -\item[f_code] the code object being executed -\item[f_lineno] the current line number (\code{-1} for \code{'call'} events) -\item[f_back] the stack frame of the caller, or None -\item[f_locals] dictionary containing local name bindings -\item[f_globals] dictionary containing global name bindings -\end{description} - -Code objects have the following read-only attributes: - -\begin{description} -\item[co_code] the code string -\item[co_names] the list of names used by the code -\item[co_consts] the list of (literal) constants used by the code -\item[co_filename] the filename from which the code was compiled -\end{description} diff --git a/Doc/libpickle.tex b/Doc/libpickle.tex deleted file mode 100644 index 579992f049..0000000000 --- a/Doc/libpickle.tex +++ /dev/null @@ -1,229 +0,0 @@ -\section{Standard Module \sectcode{pickle}} -\stmodindex{pickle} -\index{persistency} -\indexii{persistent}{objects} -\indexii{serializing}{objects} -\indexii{marshalling}{objects} -\indexii{flattening}{objects} -\indexii{pickling}{objects} - -\renewcommand{\indexsubitem}{(in module pickle)} - -The \code{pickle} module implements a basic but powerful algorithm for -``pickling'' (a.k.a.\ serializing, marshalling or flattening) nearly -arbitrary Python objects. This is the act of converting objects to a -stream of bytes (and back: ``unpickling''). -This is a more primitive notion than -persistency --- although \code{pickle} reads and writes file objects, -it does not handle the issue of naming persistent objects, nor the -(even more complicated) area of concurrent access to persistent -objects. The \code{pickle} module can transform a complex object into -a byte stream and it can transform the byte stream into an object with -the same internal structure. The most obvious thing to do with these -byte streams is to write them onto a file, but it is also conceivable -to send them across a network or store them in a database. The module -\code{shelve} provides a simple interface to pickle and unpickle -objects on ``dbm''-style database files. -\stmodindex{shelve} - -Unlike the built-in module \code{marshal}, \code{pickle} handles the -following correctly: -\stmodindex{marshal} - -\begin{itemize} - -\item recursive objects (objects containing references to themselves) - -\item object sharing (references to the same object in different places) - -\item user-defined classes and their instances - -\end{itemize} - -The data format used by \code{pickle} is Python-specific. This has -the advantage that there are no restrictions imposed by external -standards such as CORBA (which probably can't represent pointer -sharing or recursive objects); however it means that non-Python -programs may not be able to reconstruct pickled Python objects. - -The \code{pickle} data format uses a printable \ASCII{} representation. -This is slightly more voluminous than a binary representation. -However, small integers actually take {\em less} space when -represented as minimal-size decimal strings than when represented as -32-bit binary numbers, and strings are only much longer if they -contain many control characters or 8-bit characters. The big -advantage of using printable \ASCII{} (and of some other characteristics -of \code{pickle}'s representation) is that for debugging or recovery -purposes it is possible for a human to read the pickled file with a -standard text editor. (I could have gone a step further and used a -notation like S-expressions, but the parser -(currently written in Python) would have been -considerably more complicated and slower, and the files would probably -have become much larger.) - -The \code{pickle} module doesn't handle code objects, which the -\code{marshal} module does. I suppose \code{pickle} could, and maybe -it should, but there's probably no great need for it right now (as -long as \code{marshal} continues to be used for reading and writing -code objects), and at least this avoids the possibility of smuggling -Trojan horses into a program. -\stmodindex{marshal} - -For the benefit of persistency modules written using \code{pickle}, it -supports the notion of a reference to an object outside the pickled -data stream. Such objects are referenced by a name, which is an -arbitrary string of printable \ASCII{} characters. The resolution of -such names is not defined by the \code{pickle} module --- the -persistent object module will have to implement a method -\code{persistent_load}. To write references to persistent objects, -the persistent module must define a method \code{persistent_id} which -returns either \code{None} or the persistent ID of the object. - -There are some restrictions on the pickling of class instances. - -First of all, the class must be defined at the top level in a module. - -\renewcommand{\indexsubitem}{(pickle protocol)} - -Next, it must normally be possible to create class instances by -calling the class without arguments. If this is undesirable, the -class can define a method \code{__getinitargs__()}, which should -return a {\em tuple} containing the arguments to be passed to the -class constructor (\code{__init__()}). -\ttindex{__getinitargs__} -\ttindex{__init__} - -Classes can further influence how their instances are pickled --- if the class -defines the method \code{__getstate__()}, it is called and the return -state is pickled as the contents for the instance, and if the class -defines the method \code{__setstate__()}, it is called with the -unpickled state. (Note that these methods can also be used to -implement copying class instances.) If there is no -\code{__getstate__()} method, the instance's \code{__dict__} is -pickled. If there is no \code{__setstate__()} method, the pickled -object must be a dictionary and its items are assigned to the new -instance's dictionary. (If a class defines both \code{__getstate__()} -and \code{__setstate__()}, the state object needn't be a dictionary ---- these methods can do what they want.) This protocol is also used -by the shallow and deep copying operations defined in the \code{copy} -module. -\ttindex{__getstate__} -\ttindex{__setstate__} -\ttindex{__dict__} - -Note that when class instances are pickled, their class's code and -data are not pickled along with them. Only the instance data are -pickled. This is done on purpose, so you can fix bugs in a class or -add methods and still load objects that were created with an earlier -version of the class. If you plan to have long-lived objects that -will see many versions of a class, it may be worthwhile to put a version -number in the objects so that suitable conversions can be made by the -class's \code{__setstate__()} method. - -When a class itself is pickled, only its name is pickled --- the class -definition is not pickled, but re-imported by the unpickling process. -Therefore, the restriction that the class must be defined at the top -level in a module applies to pickled classes as well. - -\renewcommand{\indexsubitem}{(in module pickle)} - -The interface can be summarized as follows. - -To pickle an object \code{x} onto a file \code{f}, open for writing: - -\begin{verbatim} -p = pickle.Pickler(f) -p.dump(x) -\end{verbatim} - -A shorthand for this is: - -\begin{verbatim} -pickle.dump(x, f) -\end{verbatim} - -To unpickle an object \code{x} from a file \code{f}, open for reading: - -\begin{verbatim} -u = pickle.Unpickler(f) -x = u.load() -\end{verbatim} - -A shorthand is: - -\begin{verbatim} -x = pickle.load(f) -\end{verbatim} - -The \code{Pickler} class only calls the method \code{f.write} with a -string argument. The \code{Unpickler} calls the methods \code{f.read} -(with an integer argument) and \code{f.readline} (without argument), -both returning a string. It is explicitly allowed to pass non-file -objects here, as long as they have the right methods. -\ttindex{Unpickler} -\ttindex{Pickler} - -The following types can be pickled: -\begin{itemize} - -\item \code{None} - -\item integers, long integers, floating point numbers - -\item strings - -\item tuples, lists and dictionaries containing only picklable objects - -\item classes that are defined at the top level in a module - -\item instances of such classes whose \code{__dict__} or -\code{__setstate__()} is picklable - -\end{itemize} - -Attempts to pickle unpicklable objects will raise the -\code{PicklingError} exception; when this happens, an unspecified -number of bytes may have been written to the file. - -It is possible to make multiple calls to the \code{dump()} method of -the same \code{Pickler} instance. These must then be matched to the -same number of calls to the \code{load()} instance of the -corresponding \code{Unpickler} instance. If the same object is -pickled by multiple \code{dump()} calls, the \code{load()} will all -yield references to the same object. {\em Warning}: this is intended -for pickling multiple objects without intervening modifications to the -objects or their parts. If you modify an object and then pickle it -again using the same \code{Pickler} instance, the object is not -pickled again --- a reference to it is pickled and the -\code{Unpickler} will return the old value, not the modified one. -(There are two problems here: (a) detecting changes, and (b) -marshalling a minimal set of changes. I have no answers. Garbage -Collection may also become a problem here.) - -Apart from the \code{Pickler} and \code{Unpickler} classes, the -module defines the following functions, and an exception: - -\begin{funcdesc}{dump}{object\, file} -Write a pickled representation of \var{obect} to the open file object -\var{file}. This is equivalent to \code{Pickler(file).dump(object)}. -\end{funcdesc} - -\begin{funcdesc}{load}{file} -Read a pickled object from the open file object \var{file}. This is -equivalent to \code{Unpickler(file).load()}. -\end{funcdesc} - -\begin{funcdesc}{dumps}{object} -Return the pickled representation of the object as a string, instead -of writing it to a file. -\end{funcdesc} - -\begin{funcdesc}{loads}{string} -Read a pickled object from a string instead of a file. Characters in -the string past the pickled object's representation are ignored. -\end{funcdesc} - -\begin{excdesc}{PicklingError} -This exception is raised when an unpicklable object is passed to -\code{Pickler.dump()}. -\end{excdesc} diff --git a/Doc/libposix.tex b/Doc/libposix.tex deleted file mode 100644 index 6696a28b73..0000000000 --- a/Doc/libposix.tex +++ /dev/null @@ -1,371 +0,0 @@ -\section{Built-in Module \sectcode{posix}} -\bimodindex{posix} - -This module provides access to operating system functionality that is -standardized by the C Standard and the POSIX standard (a thinly disguised -\UNIX{} interface). - -\strong{Do not import this module directly.} Instead, import the -module \code{os}, which provides a \emph{portable} version of this -interface. On \UNIX{}, the \code{os} module provides a superset of -the \code{posix} interface. On non-\UNIX{} operating systems the -\code{posix} module is not available, but a subset is always available -through the \code{os} interface. Once \code{os} is imported, there is -\emph{no} performance penalty in using it instead of -\code{posix}. -\stmodindex{os} - -The descriptions below are very terse; refer to the -corresponding \UNIX{} manual entry for more information. Arguments -called \var{path} refer to a pathname given as a string. - -Errors are reported as exceptions; the usual exceptions are given -for type errors, while errors reported by the system calls raise -\code{posix.error}, described below. - -Module \code{posix} defines the following data items: - -\renewcommand{\indexsubitem}{(data in module posix)} -\begin{datadesc}{environ} -A dictionary representing the string environment at the time -the interpreter was started. -For example, -\code{posix.environ['HOME']} -is the pathname of your home directory, equivalent to -\code{getenv("HOME")} -in C. -Modifying this dictionary does not affect the string environment -passed on by \code{execv()}, \code{popen()} or \code{system()}; if you -need to change the environment, pass \code{environ} to \code{execve()} -or add variable assignments and export statements to the command -string for \code{system()} or \code{popen()}.% -\footnote{The problem with automatically passing on \code{environ} is -that there is no portable way of changing the environment.} -\end{datadesc} - -\renewcommand{\indexsubitem}{(exception in module posix)} -\begin{excdesc}{error} -This exception is raised when a POSIX function returns a -POSIX-related error (e.g., not for illegal argument types). Its -string value is \code{'posix.error'}. The accompanying value is a -pair containing the numeric error code from \code{errno} and the -corresponding string, as would be printed by the C function -\code{perror()}. -\end{excdesc} - -It defines the following functions and constants: - -\renewcommand{\indexsubitem}{(in module posix)} -\begin{funcdesc}{chdir}{path} -Change the current working directory to \var{path}. -\end{funcdesc} - -\begin{funcdesc}{chmod}{path\, mode} -Change the mode of \var{path} to the numeric \var{mode}. -\end{funcdesc} - -\begin{funcdesc}{chown}{path\, uid, gid} -Change the owner and group id of \var{path} to the numeric \var{uid} -and \var{gid}. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{close}{fd} -Close file descriptor \var{fd}. - -Note: this function is intended for low-level I/O and must be applied -to a file descriptor as returned by \code{posix.open()} or -\code{posix.pipe()}. To close a ``file object'' returned by the -built-in function \code{open} or by \code{posix.popen} or -\code{posix.fdopen}, use its \code{close()} method. -\end{funcdesc} - -\begin{funcdesc}{dup}{fd} -Return a duplicate of file descriptor \var{fd}. -\end{funcdesc} - -\begin{funcdesc}{dup2}{fd\, fd2} -Duplicate file descriptor \var{fd} to \var{fd2}, closing the latter -first if necessary. Return \code{None}. -\end{funcdesc} - -\begin{funcdesc}{execv}{path\, args} -Execute the executable \var{path} with argument list \var{args}, -replacing the current process (i.e., the Python interpreter). -The argument list may be a tuple or list of strings. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{execve}{path\, args\, env} -Execute the executable \var{path} with argument list \var{args}, -and environment \var{env}, -replacing the current process (i.e., the Python interpreter). -The argument list may be a tuple or list of strings. -The environment must be a dictionary mapping strings to strings. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{_exit}{n} -Exit to the system with status \var{n}, without calling cleanup -handlers, flushing stdio buffers, etc. -(Not on MS-DOS.) - -Note: the standard way to exit is \code{sys.exit(\var{n})}. -\code{posix._exit()} should normally only be used in the child process -after a \code{fork()}. -\end{funcdesc} - -\begin{funcdesc}{fdopen}{fd\optional{\, mode\optional{\, bufsize}}} -Return an open file object connected to the file descriptor \var{fd}. -The \var{mode} and \var{bufsize} arguments have the same meaning as -the corresponding arguments to the built-in \code{open()} function. -\end{funcdesc} - -\begin{funcdesc}{fork}{} -Fork a child process. Return 0 in the child, the child's process id -in the parent. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{fstat}{fd} -Return status for file descriptor \var{fd}, like \code{stat()}. -\end{funcdesc} - -\begin{funcdesc}{getcwd}{} -Return a string representing the current working directory. -\end{funcdesc} - -\begin{funcdesc}{getegid}{} -Return the current process's effective group id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{geteuid}{} -Return the current process's effective user id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{getgid}{} -Return the current process's group id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{getpid}{} -Return the current process id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{getppid}{} -Return the parent's process id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{getuid}{} -Return the current process's user id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{kill}{pid\, sig} -Kill the process \var{pid} with signal \var{sig}. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{link}{src\, dst} -Create a hard link pointing to \var{src} named \var{dst}. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{listdir}{path} -Return a list containing the names of the entries in the directory. -The list is in arbitrary order. It does not include the special -entries \code{'.'} and \code{'..'} even if they are present in the -directory. -\end{funcdesc} - -\begin{funcdesc}{lseek}{fd\, pos\, how} -Set the current position of file descriptor \var{fd} to position -\var{pos}, modified by \var{how}: 0 to set the position relative to -the beginning of the file; 1 to set it relative to the current -position; 2 to set it relative to the end of the file. -\end{funcdesc} - -\begin{funcdesc}{lstat}{path} -Like \code{stat()}, but do not follow symbolic links. (On systems -without symbolic links, this is identical to \code{posix.stat}.) -\end{funcdesc} - -\begin{funcdesc}{mkdir}{path\, mode} -Create a directory named \var{path} with numeric mode \var{mode}. -\end{funcdesc} - -\begin{funcdesc}{nice}{increment} -Add \var{incr} to the process' ``niceness''. Return the new niceness. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{open}{file\, flags\, mode} -Open the file \var{file} and set various flags according to -\var{flags} and possibly its mode according to \var{mode}. -Return the file descriptor for the newly opened file. - -Note: this function is intended for low-level I/O. For normal usage, -use the built-in function \code{open}, which returns a ``file object'' -with \code{read()} and \code{write()} methods (and many more). -\end{funcdesc} - -\begin{funcdesc}{pipe}{} -Create a pipe. Return a pair of file descriptors \code{(r, w)} -usable for reading and writing, respectively. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{popen}{command\optional{\, mode\optional{\, bufsize}}} -Open a pipe to or from \var{command}. The return value is an open -file object connected to the pipe, which can be read or written -depending on whether \var{mode} is \code{'r'} (default) or \code{'w'}. -The \var{bufsize} argument has the same meaning as the corresponding -argument to the built-in \code{open()} function. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{read}{fd\, n} -Read at most \var{n} bytes from file descriptor \var{fd}. -Return a string containing the bytes read. - -Note: this function is intended for low-level I/O and must be applied -to a file descriptor as returned by \code{posix.open()} or -\code{posix.pipe()}. To read a ``file object'' returned by the -built-in function \code{open} or by \code{posix.popen} or -\code{posix.fdopen}, or \code{sys.stdin}, use its -\code{read()} or \code{readline()} methods. -\end{funcdesc} - -\begin{funcdesc}{readlink}{path} -Return a string representing the path to which the symbolic link -points. (On systems without symbolic links, this always raises -\code{posix.error}.) -\end{funcdesc} - -\begin{funcdesc}{remove}{path} -Remove the file \var{path}. See \code{rmdir} below to remove a directory. -\end{funcdesc} - -\begin{funcdesc}{rename}{src\, dst} -Rename the file or directory \var{src} to \var{dst}. -\end{funcdesc} - -\begin{funcdesc}{rmdir}{path} -Remove the directory \var{path}. -\end{funcdesc} - -\begin{funcdesc}{setgid}{gid} -Set the current process's group id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{setuid}{uid} -Set the current process's user id. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{stat}{path} -Perform a {\em stat} system call on the given path. The return value -is a tuple of at least 10 integers giving the most important (and -portable) members of the {\em stat} structure, in the order -\code{st_mode}, -\code{st_ino}, -\code{st_dev}, -\code{st_nlink}, -\code{st_uid}, -\code{st_gid}, -\code{st_size}, -\code{st_atime}, -\code{st_mtime}, -\code{st_ctime}. -More items may be added at the end by some implementations. -(On MS-DOS, some items are filled with dummy values.) - -Note: The standard module \code{stat} defines functions and constants -that are useful for extracting information from a stat structure. -\end{funcdesc} - -\begin{funcdesc}{symlink}{src\, dst} -Create a symbolic link pointing to \var{src} named \var{dst}. (On -systems without symbolic links, this always raises -\code{posix.error}.) -\end{funcdesc} - -\begin{funcdesc}{system}{command} -Execute the command (a string) in a subshell. This is implemented by -calling the Standard C function \code{system()}, and has the same -limitations. Changes to \code{posix.environ}, \code{sys.stdin} etc.\ are -not reflected in the environment of the executed command. The return -value is the exit status of the process as returned by Standard C -\code{system()}. -\end{funcdesc} - -\begin{funcdesc}{times}{} -Return a 5-tuple of floating point numbers indicating accumulated (CPU -or other) -times, in seconds. The items are: user time, system time, children's -user time, children's system time, and elapsed real time since a fixed -point in the past, in that order. See the \UNIX{} -manual page {\it times}(2). (Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{umask}{mask} -Set the current numeric umask and returns the previous umask. -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{uname}{} -Return a 5-tuple containing information identifying the current -operating system. The tuple contains 5 strings: -\code{(\var{sysname}, \var{nodename}, \var{release}, \var{version}, \var{machine})}. -Some systems truncate the nodename to 8 -characters or to the leading component; a better way to get the -hostname is \code{socket.gethostname()}. (Not on MS-DOS, nor on older -\UNIX{} systems.) -\end{funcdesc} - -\begin{funcdesc}{unlink}{path} -Remove the file \var{path}. This is the same function as \code{remove}; -the \code{unlink} name is its traditional \UNIX{} name. -\end{funcdesc} - -\begin{funcdesc}{utime}{path\, \(atime\, mtime\)} -Set the access and modified time of the file to the given values. -(The second argument is a tuple of two items.) -\end{funcdesc} - -\begin{funcdesc}{wait}{} -Wait for completion of a child process, and return a tuple containing -its pid and exit status indication (encoded as by \UNIX{}). -(Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{waitpid}{pid\, options} -Wait for completion of a child process given by proces id, and return -a tuple containing its pid and exit status indication (encoded as by -\UNIX{}). The semantics of the call are affected by the value of -the integer options, which should be 0 for normal operation. (If the -system does not support \code{waitpid()}, this always raises -\code{posix.error}. Not on MS-DOS.) -\end{funcdesc} - -\begin{funcdesc}{write}{fd\, str} -Write the string \var{str} to file descriptor \var{fd}. -Return the number of bytes actually written. - -Note: this function is intended for low-level I/O and must be applied -to a file descriptor as returned by \code{posix.open()} or -\code{posix.pipe()}. To write a ``file object'' returned by the -built-in function \code{open} or by \code{posix.popen} or -\code{posix.fdopen}, or \code{sys.stdout} or \code{sys.stderr}, use -its \code{write()} method. -\end{funcdesc} - -\begin{datadesc}{WNOHANG} -The option for \code{waitpid()} to avoid hanging if no child process -status is available immediately. -\end{datadesc} diff --git a/Doc/libposixfile.tex b/Doc/libposixfile.tex deleted file mode 100644 index 6679f12280..0000000000 --- a/Doc/libposixfile.tex +++ /dev/null @@ -1,154 +0,0 @@ -% Manual text and implementation by Jaap Vermeulen -\section{Standard Module \sectcode{posixfile}} -\bimodindex{posixfile} -\indexii{posix}{file object} - -This module implements some additional functionality over the built-in -file objects. In particular, it implements file locking, control over -the file flags, and an easy interface to duplicate the file object. -The module defines a new file object, the posixfile object. It -has all the standard file object methods and adds the methods -described below. This module only works for certain flavors of -\UNIX{}, since it uses \code{fcntl()} for file locking. - -To instantiate a posixfile object, use the \code{open()} function in -the posixfile module. The resulting object looks and feels roughly -the same as a standard file object. - -The posixfile module defines the following constants: - -\renewcommand{\indexsubitem}{(in module posixfile)} -\begin{datadesc}{SEEK_SET} -offset is calculated from the start of the file -\end{datadesc} - -\begin{datadesc}{SEEK_CUR} -offset is calculated from the current position in the file -\end{datadesc} - -\begin{datadesc}{SEEK_END} -offset is calculated from the end of the file -\end{datadesc} - -The posixfile module defines the following functions: - -\renewcommand{\indexsubitem}{(in module posixfile)} - -\begin{funcdesc}{open}{filename\optional{\, mode\optional{\, bufsize}}} - Create a new posixfile object with the given filename and mode. The - \var{filename}, \var{mode} and \var{bufsize} arguments are - interpreted the same way as by the built-in \code{open()} function. -\end{funcdesc} - -\begin{funcdesc}{fileopen}{fileobject} - Create a new posixfile object with the given standard file object. - The resulting object has the same filename and mode as the original - file object. -\end{funcdesc} - -The posixfile object defines the following additional methods: - -\renewcommand{\indexsubitem}{(posixfile method)} -\begin{funcdesc}{lock}{fmt\, \optional{len\optional{\, start -\optional{\, whence}}}} - Lock the specified section of the file that the file object is - referring to. The format is explained - below in a table. The \var{len} argument specifies the length of the - section that should be locked. The default is \code{0}. \var{start} - specifies the starting offset of the section, where the default is - \code{0}. The \var{whence} argument specifies where the offset is - relative to. It accepts one of the constants \code{SEEK_SET}, - \code{SEEK_CUR} or \code{SEEK_END}. The default is \code{SEEK_SET}. - For more information about the arguments refer to the fcntl - manual page on your system. -\end{funcdesc} - -\begin{funcdesc}{flags}{\optional{flags}} - Set the specified flags for the file that the file object is referring - to. The new flags are ORed with the old flags, unless specified - otherwise. The format is explained below in a table. Without - the \var{flags} argument - a string indicating the current flags is returned (this is - the same as the '?' modifier). For more information about the flags - refer to the fcntl manual page on your system. -\end{funcdesc} - -\begin{funcdesc}{dup}{} - Duplicate the file object and the underlying file pointer and file - descriptor. The resulting object behaves as if it were newly - opened. -\end{funcdesc} - -\begin{funcdesc}{dup2}{fd} - Duplicate the file object and the underlying file pointer and file - descriptor. The new object will have the given file descriptor. - Otherwise the resulting object behaves as if it were newly opened. -\end{funcdesc} - -\begin{funcdesc}{file}{} - Return the standard file object that the posixfile object is based - on. This is sometimes necessary for functions that insist on a - standard file object. -\end{funcdesc} - -All methods return \code{IOError} when the request fails. - -Format characters for the \code{lock()} method have the following meaning: - -\begin{tableiii}{|c|l|c|}{samp}{Format}{Meaning}{} - \lineiii{u}{unlock the specified region}{} - \lineiii{r}{request a read lock for the specified section}{} - \lineiii{w}{request a write lock for the specified section}{} -\end{tableiii} - -In addition the following modifiers can be added to the format: - -\begin{tableiii}{|c|l|c|}{samp}{Modifier}{Meaning}{Notes} - \lineiii{|}{wait until the lock has been granted}{} - \lineiii{?}{return the first lock conflicting with the requested lock, or - \code{None} if there is no conflict.}{(1)} -\end{tableiii} - -Note: - -(1) The lock returned is in the format \code{(mode, len, start, -whence, pid)} where mode is a character representing the type of lock -('r' or 'w'). This modifier prevents a request from being granted; it -is for query purposes only. - -Format character for the \code{flags()} method have the following meaning: - -\begin{tableiii}{|c|l|c|}{samp}{Format}{Meaning}{} - \lineiii{a}{append only flag}{} - \lineiii{c}{close on exec flag}{} - \lineiii{n}{no delay flag (also called non-blocking flag)}{} - \lineiii{s}{synchronization flag}{} -\end{tableiii} - -In addition the following modifiers can be added to the format: - -\begin{tableiii}{|c|l|c|}{samp}{Modifier}{Meaning}{Notes} - \lineiii{!}{turn the specified flags 'off', instead of the default 'on'}{(1)} - \lineiii{=}{replace the flags, instead of the default 'OR' operation}{(1)} - \lineiii{?}{return a string in which the characters represent the flags that - are set.}{(2)} -\end{tableiii} - -Note: - -(1) The \code{!} and \code{=} modifiers are mutually exclusive. - -(2) This string represents the flags after they may have been altered -by the same call. - -Examples: - -\bcode\begin{verbatim} -from posixfile import * - -file = open('/tmp/test', 'w') -file.lock('w|') -... -file.lock('u') -file.close() -\end{verbatim}\ecode diff --git a/Doc/libppath.tex b/Doc/libppath.tex deleted file mode 100644 index 0d3bbe573d..0000000000 --- a/Doc/libppath.tex +++ /dev/null @@ -1,144 +0,0 @@ -\section{Standard Module \sectcode{posixpath}} -\stmodindex{posixpath} - -This module implements some useful functions on POSIX pathnames. - -\strong{Do not import this module directly.} Instead, import the -module \code{os} and use \code{os.path}. -\stmodindex{os} - -\renewcommand{\indexsubitem}{(in module posixpath)} - -\begin{funcdesc}{basename}{p} -Return the base name of pathname -\var{p}. -This is the second half of the pair returned by -\code{posixpath.split(\var{p})}. -\end{funcdesc} - -\begin{funcdesc}{commonprefix}{list} -Return the longest string that is a prefix of all strings in -\var{list}. -If -\var{list} -is empty, return the empty string (\code{''}). -\end{funcdesc} - -\begin{funcdesc}{exists}{p} -Return true if -\var{p} -refers to an existing path. -\end{funcdesc} - -\begin{funcdesc}{expanduser}{p} -Return the argument with an initial component of \samp{\~} or -\samp{\~\var{user}} replaced by that \var{user}'s home directory. An -initial \samp{\~{}} is replaced by the environment variable \code{\${}HOME}; -an initial \samp{\~\var{user}} is looked up in the password directory through -the built-in module \code{pwd}. If the expansion fails, or if the -path does not begin with a tilde, the path is returned unchanged. -\end{funcdesc} - -\begin{funcdesc}{expandvars}{p} -Return the argument with environment variables expanded. Substrings -of the form \samp{\$\var{name}} or \samp{\$\{\var{name}\}} are -replaced by the value of environment variable \var{name}. Malformed -variable names and references to non-existing variables are left -unchanged. -\end{funcdesc} - -\begin{funcdesc}{isabs}{p} -Return true if \var{p} is an absolute pathname (begins with a slash). -\end{funcdesc} - -\begin{funcdesc}{isfile}{p} -Return true if \var{p} is an existing regular file. This follows -symbolic links, so both \code{islink()} and \code{isfile()} can be true for the same -path. -\end{funcdesc} - -\begin{funcdesc}{isdir}{p} -Return true if \var{p} is an existing directory. This follows -symbolic links, so both \code{islink()} and \code{isdir()} can be true for the same -path. -\end{funcdesc} - -\begin{funcdesc}{islink}{p} -Return true if -\var{p} -refers to a directory entry that is a symbolic link. -Always false if symbolic links are not supported. -\end{funcdesc} - -\begin{funcdesc}{ismount}{p} -Return true if pathname \var{p} is a \dfn{mount point}: a point in a -file system where a different file system has been mounted. The -function checks whether \var{p}'s parent, \file{\var{p}/..}, is on a -different device than \var{p}, or whether \file{\var{p}/..} and -\var{p} point to the same i-node on the same device --- this should -detect mount points for all \UNIX{} and POSIX variants. -\end{funcdesc} - -\begin{funcdesc}{join}{p\, q} -Join the paths -\var{p} -and -\var{q} intelligently: -If -\var{q} -is an absolute path, the return value is -\var{q}. -Otherwise, the concatenation of -\var{p} -and -\var{q} -is returned, with a slash (\code{'/'}) inserted unless -\var{p} -is empty or ends in a slash. -\end{funcdesc} - -\begin{funcdesc}{normcase}{p} -Normalize the case of a pathname. This returns the path unchanged; -however, a similar function in \code{macpath} converts upper case to -lower case. -\end{funcdesc} - -\begin{funcdesc}{samefile}{p\, q} -Return true if both pathname arguments refer to the same file or directory -(as indicated by device number and i-node number). -Raise an exception if a stat call on either pathname fails. -\end{funcdesc} - -\begin{funcdesc}{split}{p} -Split the pathname \var{p} in a pair \code{(\var{head}, \var{tail})}, where -\var{tail} is the last pathname component and \var{head} is -everything leading up to that. If \var{p} ends in a slash (except if -it is the root), the trailing slash is removed and the operation -applied to the result; otherwise, \code{join(\var{head}, \var{tail})} equals -\var{p}. The \var{tail} part never contains a slash. Some boundary -cases:\ if \var{p} is the root, \var{head} equals \var{p} and -\var{tail} is empty; if \var{p} is empty, both \var{head} and -\var{tail} are empty; if \var{p} contains no slash, \var{head} is -empty and \var{tail} equals \var{p}. -\end{funcdesc} - -\begin{funcdesc}{splitext}{p} -Split the pathname \var{p} in a pair \code{(\var{root}, \var{ext})} -such that \code{\var{root} + \var{ext} == \var{p}}, -the last component of \var{root} contains no periods, -and \var{ext} is empty or begins with a period. -\end{funcdesc} - -\begin{funcdesc}{walk}{p\, visit\, arg} -Calls the function \var{visit} with arguments -\code{(\var{arg}, \var{dirname}, \var{names})} for each directory in the -directory tree rooted at \var{p} (including \var{p} itself, if it is a -directory). The argument \var{dirname} specifies the visited directory, -the argument \var{names} lists the files in the directory (gotten from -\code{posix.listdir(\var{dirname})}, so including \samp{.} and -\samp{..}). The \var{visit} function may modify \var{names} to -influence the set of directories visited below \var{dirname}, e.g., to -avoid visiting certain parts of the tree. (The object referred to by -\var{names} must be modified in place, using \code{del} or slice -assignment.) -\end{funcdesc} diff --git a/Doc/libprofile.tex b/Doc/libprofile.tex deleted file mode 100644 index 4ba4cf979d..0000000000 --- a/Doc/libprofile.tex +++ /dev/null @@ -1,760 +0,0 @@ -\chapter{The Python Profiler} -\stmodindex{profile} -\stmodindex{pstats} - -Copyright \copyright\ 1994, by InfoSeek Corporation, all rights reserved. - -Written by James Roskind% -\footnote{ -Updated and converted to \LaTeX\ by Guido van Rossum. The references to -the old profiler are left in the text, although it no longer exists. -} - -Permission to use, copy, modify, and distribute this Python software -and its associated documentation for any purpose (subject to the -restriction in the following sentence) without fee is hereby granted, -provided that the above copyright notice appears in all copies, and -that both that copyright notice and this permission notice appear in -supporting documentation, and that the name of InfoSeek not be used in -advertising or publicity pertaining to distribution of the software -without specific, written prior permission. This permission is -explicitly restricted to the copying and modification of the software -to remain in Python, compiled Python, or other languages (such as C) -wherein the modified or derived code is exclusively imported into a -Python module. - -INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS -SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION 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. - - -The profiler was written after only programming in Python for 3 weeks. -As a result, it is probably clumsy code, but I don't know for sure yet -'cause I'm a beginner :-). I did work hard to make the code run fast, -so that profiling would be a reasonable thing to do. I tried not to -repeat code fragments, but I'm sure I did some stuff in really awkward -ways at times. Please send suggestions for improvements to: -\code{jar@netscape.com}. I won't promise \emph{any} support. ...but -I'd appreciate the feedback. - - -\section{Introduction to the profiler} -\nodename{Profiler Introduction} - -A \dfn{profiler} is a program that describes the run time performance -of a program, providing a variety of statistics. This documentation -describes the profiler functionality provided in the modules -\code{profile} and \code{pstats.} This profiler provides -\dfn{deterministic profiling} of any Python programs. It also -provides a series of report generation tools to allow users to rapidly -examine the results of a profile operation. - - -\section{How Is This Profiler Different From The Old Profiler?} -\nodename{Profiler Changes} - -The big changes from old profiling module are that you get more -information, and you pay less CPU time. It's not a trade-off, it's a -trade-up. - -To be specific: - -\begin{description} - -\item[Bugs removed:] -Local stack frame is no longer molested, execution time is now charged -to correct functions. - -\item[Accuracy increased:] -Profiler execution time is no longer charged to user's code, -calibration for platform is supported, file reads are not done \emph{by} -profiler \emph{during} profiling (and charged to user's code!). - -\item[Speed increased:] -Overhead CPU cost was reduced by more than a factor of two (perhaps a -factor of five), lightweight profiler module is all that must be -loaded, and the report generating module (\code{pstats}) is not needed -during profiling. - -\item[Recursive functions support:] -Cumulative times in recursive functions are correctly calculated; -recursive entries are counted. - -\item[Large growth in report generating UI:] -Distinct profiles runs can be added together forming a comprehensive -report; functions that import statistics take arbitrary lists of -files; sorting criteria is now based on keywords (instead of 4 integer -options); reports shows what functions were profiled as well as what -profile file was referenced; output format has been improved. - -\end{description} - - -\section{Instant Users Manual} - -This section is provided for users that ``don't want to read the -manual.'' It provides a very brief overview, and allows a user to -rapidly perform profiling on an existing application. - -To profile an application with a main entry point of \samp{foo()}, you -would add the following to your module: - -\begin{verbatim} - import profile - profile.run("foo()") -\end{verbatim} - -The above action would cause \samp{foo()} to be run, and a series of -informative lines (the profile) to be printed. The above approach is -most useful when working with the interpreter. If you would like to -save the results of a profile into a file for later examination, you -can supply a file name as the second argument to the \code{run()} -function: - -\begin{verbatim} - import profile - profile.run("foo()", 'fooprof') -\end{verbatim} - -When you wish to review the profile, you should use the methods in the -\code{pstats} module. Typically you would load the statistics data as -follows: - -\begin{verbatim} - import pstats - p = pstats.Stats('fooprof') -\end{verbatim} - -The class \code{Stats} (the above code just created an instance of -this class) has a variety of methods for manipulating and printing the -data that was just read into \samp{p}. When you ran -\code{profile.run()} above, what was printed was the result of three -method calls: - -\begin{verbatim} - p.strip_dirs().sort_stats(-1).print_stats() -\end{verbatim} - -The first method removed the extraneous path from all the module -names. The second method sorted all the entries according to the -standard module/line/name string that is printed (this is to comply -with the semantics of the old profiler). The third method printed out -all the statistics. You might try the following sort calls: - -\begin{verbatim} - p.sort_stats('name') - p.print_stats() -\end{verbatim} - -The first call will actually sort the list by function name, and the -second call will print out the statistics. The following are some -interesting calls to experiment with: - -\begin{verbatim} - p.sort_stats('cumulative').print_stats(10) -\end{verbatim} - -This sorts the profile by cumulative time in a function, and then only -prints the ten most significant lines. If you want to understand what -algorithms are taking time, the above line is what you would use. - -If you were looking to see what functions were looping a lot, and -taking a lot of time, you would do: - -\begin{verbatim} - p.sort_stats('time').print_stats(10) -\end{verbatim} - -to sort according to time spent within each function, and then print -the statistics for the top ten functions. - -You might also try: - -\begin{verbatim} - p.sort_stats('file').print_stats('__init__') -\end{verbatim} - -This will sort all the statistics by file name, and then print out -statistics for only the class init methods ('cause they are spelled -with \code{__init__} in them). As one final example, you could try: - -\begin{verbatim} - p.sort_stats('time', 'cum').print_stats(.5, 'init') -\end{verbatim} - -This line sorts statistics with a primary key of time, and a secondary -key of cumulative time, and then prints out some of the statistics. -To be specific, the list is first culled down to 50\% (re: \samp{.5}) -of its original size, then only lines containing \code{init} are -maintained, and that sub-sub-list is printed. - -If you wondered what functions called the above functions, you could -now (\samp{p} is still sorted according to the last criteria) do: - -\begin{verbatim} - p.print_callers(.5, 'init') -\end{verbatim} - -and you would get a list of callers for each of the listed functions. - -If you want more functionality, you're going to have to read the -manual, or guess what the following functions do: - -\begin{verbatim} - p.print_callees() - p.add('fooprof') -\end{verbatim} - - -\section{What Is Deterministic Profiling?} -\nodename{Deterministic Profiling} - -\dfn{Deterministic profiling} is meant to reflect the fact that all -\dfn{function call}, \dfn{function return}, and \dfn{exception} events -are monitored, and precise timings are made for the intervals between -these events (during which time the user's code is executing). In -contrast, \dfn{statistical profiling} (which is not done by this -module) randomly samples the effective instruction pointer, and -deduces where time is being spent. The latter technique traditionally -involves less overhead (as the code does not need to be instrumented), -but provides only relative indications of where time is being spent. - -In Python, since there is an interpreter active during execution, the -presence of instrumented code is not required to do deterministic -profiling. Python automatically provides a \dfn{hook} (optional -callback) for each event. In addition, the interpreted nature of -Python tends to add so much overhead to execution, that deterministic -profiling tends to only add small processing overhead in typical -applications. The result is that deterministic profiling is not that -expensive, yet provides extensive run time statistics about the -execution of a Python program. - -Call count statistics can be used to identify bugs in code (surprising -counts), and to identify possible inline-expansion points (high call -counts). Internal time statistics can be used to identify ``hot -loops'' that should be carefully optimized. Cumulative time -statistics should be used to identify high level errors in the -selection of algorithms. Note that the unusual handling of cumulative -times in this profiler allows statistics for recursive implementations -of algorithms to be directly compared to iterative implementations. - - -\section{Reference Manual} - -\renewcommand{\indexsubitem}{(profiler function)} - -The primary entry point for the profiler is the global function -\code{profile.run()}. It is typically used to create any profile -information. The reports are formatted and printed using methods of -the class \code{pstats.Stats}. The following is a description of all -of these standard entry points and functions. For a more in-depth -view of some of the code, consider reading the later section on -Profiler Extensions, which includes discussion of how to derive -``better'' profilers from the classes presented, or reading the source -code for these modules. - -\begin{funcdesc}{profile.run}{string\optional{\, filename\optional{\, ...}}} - -This function takes a single argument that has can be passed to the -\code{exec} statement, and an optional file name. In all cases this -routine attempts to \code{exec} its first argument, and gather profiling -statistics from the execution. If no file name is present, then this -function automatically prints a simple profiling report, sorted by the -standard name string (file/line/function-name) that is presented in -each line. The following is a typical output from such a call: - -\small{ -\begin{verbatim} - main() - 2706 function calls (2004 primitive calls) in 4.504 CPU seconds - -Ordered by: standard name - -ncalls tottime percall cumtime percall filename:lineno(function) - 2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects) - 43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate) - ... -\end{verbatim} -} - -The first line indicates that this profile was generated by the call:\\ -\code{profile.run('main()')}, and hence the exec'ed string is -\code{'main()'}. The second line indicates that 2706 calls were -monitored. Of those calls, 2004 were \dfn{primitive}. We define -\dfn{primitive} to mean that the call was not induced via recursion. -The next line: \code{Ordered by:\ standard name}, indicates that -the text string in the far right column was used to sort the output. -The column headings include: - -\begin{description} - -\item[ncalls ] -for the number of calls, - -\item[tottime ] -for the total time spent in the given function (and excluding time -made in calls to sub-functions), - -\item[percall ] -is the quotient of \code{tottime} divided by \code{ncalls} - -\item[cumtime ] -is the total time spent in this and all subfunctions (i.e., from -invocation till exit). This figure is accurate \emph{even} for recursive -functions. - -\item[percall ] -is the quotient of \code{cumtime} divided by primitive calls - -\item[filename:lineno(function) ] -provides the respective data of each function - -\end{description} - -When there are two numbers in the first column (e.g.: \samp{43/3}), -then the latter is the number of primitive calls, and the former is -the actual number of calls. Note that when the function does not -recurse, these two values are the same, and only the single figure is -printed. - -\end{funcdesc} - -\begin{funcdesc}{pstats.Stats}{filename\optional{\, ...}} -This class constructor creates an instance of a ``statistics object'' -from a \var{filename} (or set of filenames). \code{Stats} objects are -manipulated by methods, in order to print useful reports. - -The file selected by the above constructor must have been created by -the corresponding version of \code{profile}. To be specific, there is -\emph{NO} file compatibility guaranteed with future versions of this -profiler, and there is no compatibility with files produced by other -profilers (e.g., the old system profiler). - -If several files are provided, all the statistics for identical -functions will be coalesced, so that an overall view of several -processes can be considered in a single report. If additional files -need to be combined with data in an existing \code{Stats} object, the -\code{add()} method can be used. -\end{funcdesc} - - -\subsection{The \sectcode{Stats} Class} - -\renewcommand{\indexsubitem}{(Stats method)} - -\begin{funcdesc}{strip_dirs}{} -This method for the \code{Stats} class removes all leading path information -from file names. It is very useful in reducing the size of the -printout to fit within (close to) 80 columns. This method modifies -the object, and the stripped information is lost. After performing a -strip operation, the object is considered to have its entries in a -``random'' order, as it was just after object initialization and -loading. If \code{strip_dirs()} causes two function names to be -indistinguishable (i.e., they are on the same line of the same -filename, and have the same function name), then the statistics for -these two entries are accumulated into a single entry. -\end{funcdesc} - - -\begin{funcdesc}{add}{filename\optional{\, ...}} -This method of the \code{Stats} class accumulates additional profiling -information into the current profiling object. Its arguments should -refer to filenames created by the corresponding version of -\code{profile.run()}. Statistics for identically named (re: file, -line, name) functions are automatically accumulated into single -function statistics. -\end{funcdesc} - -\begin{funcdesc}{sort_stats}{key\optional{\, ...}} -This method modifies the \code{Stats} object by sorting it according to the -supplied criteria. The argument is typically a string identifying the -basis of a sort (example: \code{"time"} or \code{"name"}). - -When more than one key is provided, then additional keys are used as -secondary criteria when the there is equality in all keys selected -before them. For example, sort_stats('name', 'file') will sort all -the entries according to their function name, and resolve all ties -(identical function names) by sorting by file name. - -Abbreviations can be used for any key names, as long as the -abbreviation is unambiguous. The following are the keys currently -defined: - -\begin{tableii}{|l|l|}{code}{Valid Arg}{Meaning} -\lineii{"calls"}{call count} -\lineii{"cumulative"}{cumulative time} -\lineii{"file"}{file name} -\lineii{"module"}{file name} -\lineii{"pcalls"}{primitive call count} -\lineii{"line"}{line number} -\lineii{"name"}{function name} -\lineii{"nfl"}{name/file/line} -\lineii{"stdname"}{standard name} -\lineii{"time"}{internal time} -\end{tableii} - -Note that all sorts on statistics are in descending order (placing -most time consuming items first), where as name, file, and line number -searches are in ascending order (i.e., alphabetical). The subtle -distinction between \code{"nfl"} and \code{"stdname"} is that the -standard name is a sort of the name as printed, which means that the -embedded line numbers get compared in an odd way. For example, lines -3, 20, and 40 would (if the file names were the same) appear in the -string order 20, 3 and 40. In contrast, \code{"nfl"} does a numeric -compare of the line numbers. In fact, \code{sort_stats("nfl")} is the -same as \code{sort_stats("name", "file", "line")}. - -For compatibility with the old profiler, the numeric arguments -\samp{-1}, \samp{0}, \samp{1}, and \samp{2} are permitted. They are -interpreted as \code{"stdname"}, \code{"calls"}, \code{"time"}, and -\code{"cumulative"} respectively. If this old style format (numeric) -is used, only one sort key (the numeric key) will be used, and -additional arguments will be silently ignored. -\end{funcdesc} - - -\begin{funcdesc}{reverse_order}{} -This method for the \code{Stats} class reverses the ordering of the basic -list within the object. This method is provided primarily for -compatibility with the old profiler. Its utility is questionable -now that ascending vs descending order is properly selected based on -the sort key of choice. -\end{funcdesc} - -\begin{funcdesc}{print_stats}{restriction\optional{\, ...}} -This method for the \code{Stats} class prints out a report as described -in the \code{profile.run()} definition. - -The order of the printing is based on the last \code{sort_stats()} -operation done on the object (subject to caveats in \code{add()} and -\code{strip_dirs())}. - -The arguments provided (if any) can be used to limit the list down to -the significant entries. Initially, the list is taken to be the -complete set of profiled functions. Each restriction is either an -integer (to select a count of lines), or a decimal fraction between -0.0 and 1.0 inclusive (to select a percentage of lines), or a regular -expression (to pattern match the standard name that is printed). If -several restrictions are provided, then they are applied sequentially. -For example: - -\begin{verbatim} - print_stats(.1, "foo:") -\end{verbatim} - -would first limit the printing to first 10\% of list, and then only -print functions that were part of filename \samp{.*foo:}. In -contrast, the command: - -\begin{verbatim} - print_stats("foo:", .1) -\end{verbatim} - -would limit the list to all functions having file names \samp{.*foo:}, -and then proceed to only print the first 10\% of them. -\end{funcdesc} - - -\begin{funcdesc}{print_callers}{restrictions\optional{\, ...}} -This method for the \code{Stats} class prints a list of all functions -that called each function in the profiled database. The ordering is -identical to that provided by \code{print_stats()}, and the definition -of the restricting argument is also identical. For convenience, a -number is shown in parentheses after each caller to show how many -times this specific call was made. A second non-parenthesized number -is the cumulative time spent in the function at the right. -\end{funcdesc} - -\begin{funcdesc}{print_callees}{restrictions\optional{\, ...}} -This method for the \code{Stats} class prints a list of all function -that were called by the indicated function. Aside from this reversal -of direction of calls (re: called vs was called by), the arguments and -ordering are identical to the \code{print_callers()} method. -\end{funcdesc} - -\begin{funcdesc}{ignore}{} -This method of the \code{Stats} class is used to dispose of the value -returned by earlier methods. All standard methods in this class -return the instance that is being processed, so that the commands can -be strung together. For example: - -\begin{verbatim} -pstats.Stats('foofile').strip_dirs().sort_stats('cum') \ - .print_stats().ignore() -\end{verbatim} - -would perform all the indicated functions, but it would not return -the final reference to the \code{Stats} instance.% -\footnote{ -This was once necessary, when Python would print any unused expression -result that was not \code{None}. The method is still defined for -backward compatibility. -} -\end{funcdesc} - - -\section{Limitations} - -There are two fundamental limitations on this profiler. The first is -that it relies on the Python interpreter to dispatch \dfn{call}, -\dfn{return}, and \dfn{exception} events. Compiled C code does not -get interpreted, and hence is ``invisible'' to the profiler. All time -spent in C code (including builtin functions) will be charged to the -Python function that invoked the C code. If the C code calls out -to some native Python code, then those calls will be profiled -properly. - -The second limitation has to do with accuracy of timing information. -There is a fundamental problem with deterministic profilers involving -accuracy. The most obvious restriction is that the underlying ``clock'' -is only ticking at a rate (typically) of about .001 seconds. Hence no -measurements will be more accurate that that underlying clock. If -enough measurements are taken, then the ``error'' will tend to average -out. Unfortunately, removing this first error induces a second source -of error... - -The second problem is that it ``takes a while'' from when an event is -dispatched until the profiler's call to get the time actually -\emph{gets} the state of the clock. Similarly, there is a certain lag -when exiting the profiler event handler from the time that the clock's -value was obtained (and then squirreled away), until the user's code -is once again executing. As a result, functions that are called many -times, or call many functions, will typically accumulate this error. -The error that accumulates in this fashion is typically less than the -accuracy of the clock (i.e., less than one clock tick), but it -\emph{can} accumulate and become very significant. This profiler -provides a means of calibrating itself for a given platform so that -this error can be probabilistically (i.e., on the average) removed. -After the profiler is calibrated, it will be more accurate (in a least -square sense), but it will sometimes produce negative numbers (when -call counts are exceptionally low, and the gods of probability work -against you :-). ) Do \emph{NOT} be alarmed by negative numbers in -the profile. They should \emph{only} appear if you have calibrated -your profiler, and the results are actually better than without -calibration. - - -\section{Calibration} - -The profiler class has a hard coded constant that is added to each -event handling time to compensate for the overhead of calling the time -function, and socking away the results. The following procedure can -be used to obtain this constant for a given platform (see discussion -in section Limitations above). - -\begin{verbatim} - import profile - pr = profile.Profile() - pr.calibrate(100) - pr.calibrate(100) - pr.calibrate(100) -\end{verbatim} - -The argument to calibrate() is the number of times to try to do the -sample calls to get the CPU times. If your computer is \emph{very} -fast, you might have to do: - -\begin{verbatim} - pr.calibrate(1000) -\end{verbatim} - -or even: - -\begin{verbatim} - pr.calibrate(10000) -\end{verbatim} - -The object of this exercise is to get a fairly consistent result. -When you have a consistent answer, you are ready to use that number in -the source code. For a Sun Sparcstation 1000 running Solaris 2.3, the -magical number is about .00053. If you have a choice, you are better -off with a smaller constant, and your results will ``less often'' show -up as negative in profile statistics. - -The following shows how the trace_dispatch() method in the Profile -class should be modified to install the calibration constant on a Sun -Sparcstation 1000: - -\begin{verbatim} - def trace_dispatch(self, frame, event, arg): - t = self.timer() - t = t[0] + t[1] - self.t - .00053 # Calibration constant - - if self.dispatch[event](frame,t): - t = self.timer() - self.t = t[0] + t[1] - else: - r = self.timer() - self.t = r[0] + r[1] - t # put back unrecorded delta - return -\end{verbatim} - -Note that if there is no calibration constant, then the line -containing the callibration constant should simply say: - -\begin{verbatim} - t = t[0] + t[1] - self.t # no calibration constant -\end{verbatim} - -You can also achieve the same results using a derived class (and the -profiler will actually run equally fast!!), but the above method is -the simplest to use. I could have made the profiler ``self -calibrating'', but it would have made the initialization of the -profiler class slower, and would have required some \emph{very} fancy -coding, or else the use of a variable where the constant \samp{.00053} -was placed in the code shown. This is a \strong{VERY} critical -performance section, and there is no reason to use a variable lookup -at this point, when a constant can be used. - - -\section{Extensions --- Deriving Better Profilers} -\nodename{Profiler Extensions} - -The \code{Profile} class of module \code{profile} was written so that -derived classes could be developed to extend the profiler. Rather -than describing all the details of such an effort, I'll just present -the following two examples of derived classes that can be used to do -profiling. If the reader is an avid Python programmer, then it should -be possible to use these as a model and create similar (and perchance -better) profile classes. - -If all you want to do is change how the timer is called, or which -timer function is used, then the basic class has an option for that in -the constructor for the class. Consider passing the name of a -function to call into the constructor: - -\begin{verbatim} - pr = profile.Profile(your_time_func) -\end{verbatim} - -The resulting profiler will call \code{your_time_func()} instead of -\code{os.times()}. The function should return either a single number -or a list of numbers (like what \code{os.times()} returns). If the -function returns a single time number, or the list of returned numbers -has length 2, then you will get an especially fast version of the -dispatch routine. - -Be warned that you \emph{should} calibrate the profiler class for the -timer function that you choose. For most machines, a timer that -returns a lone integer value will provide the best results in terms of -low overhead during profiling. (os.times is \emph{pretty} bad, 'cause -it returns a tuple of floating point values, so all arithmetic is -floating point in the profiler!). If you want to substitute a -better timer in the cleanest fashion, you should derive a class, and -simply put in the replacement dispatch method that better handles your -timer call, along with the appropriate calibration constant :-). - - -\subsection{OldProfile Class} - -The following derived profiler simulates the old style profiler, -providing errant results on recursive functions. The reason for the -usefulness of this profiler is that it runs faster (i.e., less -overhead) than the old profiler. It still creates all the caller -stats, and is quite useful when there is \emph{no} recursion in the -user's code. It is also a lot more accurate than the old profiler, as -it does not charge all its overhead time to the user's code. - -\begin{verbatim} -class OldProfile(Profile): - - def trace_dispatch_exception(self, frame, t): - rt, rtt, rct, rfn, rframe, rcur = self.cur - if rcur and not rframe is frame: - return self.trace_dispatch_return(rframe, t) - return 0 - - def trace_dispatch_call(self, frame, t): - fn = `frame.f_code` - - self.cur = (t, 0, 0, fn, frame, self.cur) - if self.timings.has_key(fn): - tt, ct, callers = self.timings[fn] - self.timings[fn] = tt, ct, callers - else: - self.timings[fn] = 0, 0, {} - return 1 - - def trace_dispatch_return(self, frame, t): - rt, rtt, rct, rfn, frame, rcur = self.cur - rtt = rtt + t - sft = rtt + rct - - pt, ptt, pct, pfn, pframe, pcur = rcur - self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur - - tt, ct, callers = self.timings[rfn] - if callers.has_key(pfn): - callers[pfn] = callers[pfn] + 1 - else: - callers[pfn] = 1 - self.timings[rfn] = tt+rtt, ct + sft, callers - - return 1 - - - def snapshot_stats(self): - self.stats = {} - for func in self.timings.keys(): - tt, ct, callers = self.timings[func] - nor_func = self.func_normalize(func) - nor_callers = {} - nc = 0 - for func_caller in callers.keys(): - nor_callers[self.func_normalize(func_caller)]=\ - callers[func_caller] - nc = nc + callers[func_caller] - self.stats[nor_func] = nc, nc, tt, ct, nor_callers -\end{verbatim} - - -\subsection{HotProfile Class} - -This profiler is the fastest derived profile example. It does not -calculate caller-callee relationships, and does not calculate -cumulative time under a function. It only calculates time spent in a -function, so it runs very quickly (re: very low overhead). In truth, -the basic profiler is so fast, that is probably not worth the savings -to give up the data, but this class still provides a nice example. - -\begin{verbatim} -class HotProfile(Profile): - - def trace_dispatch_exception(self, frame, t): - rt, rtt, rfn, rframe, rcur = self.cur - if rcur and not rframe is frame: - return self.trace_dispatch_return(rframe, t) - return 0 - - def trace_dispatch_call(self, frame, t): - self.cur = (t, 0, frame, self.cur) - return 1 - - def trace_dispatch_return(self, frame, t): - rt, rtt, frame, rcur = self.cur - - rfn = `frame.f_code` - - pt, ptt, pframe, pcur = rcur - self.cur = pt, ptt+rt, pframe, pcur - - if self.timings.has_key(rfn): - nc, tt = self.timings[rfn] - self.timings[rfn] = nc + 1, rt + rtt + tt - else: - self.timings[rfn] = 1, rt + rtt - - return 1 - - - def snapshot_stats(self): - self.stats = {} - for func in self.timings.keys(): - nc, tt = self.timings[func] - nor_func = self.func_normalize(func) - self.stats[nor_func] = nc, nc, tt, 0, {} -\end{verbatim} diff --git a/Doc/libpwd.tex b/Doc/libpwd.tex deleted file mode 100644 index 7bb30d80e2..0000000000 --- a/Doc/libpwd.tex +++ /dev/null @@ -1,32 +0,0 @@ -\section{Built-in Module \sectcode{pwd}} - -\bimodindex{pwd} -This module provides access to the \UNIX{} password database. -It is available on all \UNIX{} versions. - -Password database entries are reported as 7-tuples containing the -following items from the password database (see \file{<pwd.h>}), in order: -\code{pw_name}, -\code{pw_passwd}, -\code{pw_uid}, -\code{pw_gid}, -\code{pw_gecos}, -\code{pw_dir}, -\code{pw_shell}. -The uid and gid items are integers, all others are strings. -An exception is raised if the entry asked for cannot be found. - -It defines the following items: - -\renewcommand{\indexsubitem}{(in module pwd)} -\begin{funcdesc}{getpwuid}{uid} -Return the password database entry for the given numeric user ID. -\end{funcdesc} - -\begin{funcdesc}{getpwnam}{name} -Return the password database entry for the given user name. -\end{funcdesc} - -\begin{funcdesc}{getpwall}{} -Return a list of all available password database entries, in arbitrary order. -\end{funcdesc} diff --git a/Doc/libpython.tex b/Doc/libpython.tex deleted file mode 100644 index ed253f5bad..0000000000 --- a/Doc/libpython.tex +++ /dev/null @@ -1,40 +0,0 @@ -\chapter{Python Services} - -The modules described in this chapter provide a wide range of services -related to the Python interpreter and its interaction with its -environment. Here's an overview: - -\begin{description} - -\item[sys] ---- Access system specific parameters and functions. - -\item[types] ---- Names for all built-in types. - -\item[traceback] ---- Print or retrieve a stack traceback. - -\item[pickle] ---- Convert Python objects to streams of bytes and back. - -\item[shelve] ---- Python object persistency. - -\item[copy] ---- Shallow and deep copy operations. - -\item[marshal] ---- Convert Python objects to streams of bytes and back (with -different constraints). - -\item[imp] ---- Access the implementation of the \code{import} statement. - -\item[__builtin__] ---- The set of built-in functions. - -\item[__main__] ---- The environment where the top-level script is run. - -\end{description} diff --git a/Doc/librand.tex b/Doc/librand.tex deleted file mode 100644 index 4991e5986f..0000000000 --- a/Doc/librand.tex +++ /dev/null @@ -1,21 +0,0 @@ -\section{Standard Module \sectcode{rand}} - -\stmodindex{rand} This module implements a pseudo-random number -generator with an interface similar to \code{rand()} in C\@. It defines -the following functions: - -\renewcommand{\indexsubitem}{(in module rand)} -\begin{funcdesc}{rand}{} -Returns an integer random number in the range [0 ... 32768). -\end{funcdesc} - -\begin{funcdesc}{choice}{s} -Returns a random element from the sequence (string, tuple or list) -\var{s}. -\end{funcdesc} - -\begin{funcdesc}{srand}{seed} -Initializes the random number generator with the given integral seed. -When the module is first imported, the random number is initialized with -the current time. -\end{funcdesc} diff --git a/Doc/libregex.tex b/Doc/libregex.tex deleted file mode 100644 index 4c98e59fc3..0000000000 --- a/Doc/libregex.tex +++ /dev/null @@ -1,200 +0,0 @@ -\section{Built-in Module \sectcode{regex}} - -\bimodindex{regex} -This module provides regular expression matching operations similar to -those found in Emacs. It is always available. - -By default the patterns are Emacs-style regular expressions, -with one exception. There is -a way to change the syntax to match that of several well-known -\UNIX{} utilities. The exception is that Emacs' \samp{\e s} -pattern is not supported, since the original implementation references -the Emacs syntax tables. - -This module is 8-bit clean: both patterns and strings may contain null -bytes and characters whose high bit is set. - -\strong{Please note:} There is a little-known fact about Python string -literals which means that you don't usually have to worry about -doubling backslashes, even though they are used to escape special -characters in string literals as well as in regular expressions. This -is because Python doesn't remove backslashes from string literals if -they are followed by an unrecognized escape character. -\emph{However}, if you want to include a literal \dfn{backslash} in a -regular expression represented as a string literal, you have to -\emph{quadruple} it. E.g.\ to extract \LaTeX\ \samp{\e section\{{\rm -\ldots}\}} headers from a document, you can use this pattern: -\code{'\e \e \e\e section\{\e (.*\e )\}'}. - -The module defines these functions, and an exception: - -\renewcommand{\indexsubitem}{(in module regex)} - -\begin{funcdesc}{match}{pattern\, string} - Return how many characters at the beginning of \var{string} match - the regular expression \var{pattern}. Return \code{-1} if the - string does not match the pattern (this is different from a - zero-length match!). -\end{funcdesc} - -\begin{funcdesc}{search}{pattern\, string} - Return the first position in \var{string} that matches the regular - expression \var{pattern}. Return -1 if no position in the string - matches the pattern (this is different from a zero-length match - anywhere!). -\end{funcdesc} - -\begin{funcdesc}{compile}{pattern\optional{\, translate}} - Compile a regular expression pattern into a regular expression - object, which can be used for matching using its \code{match} and - \code{search} methods, described below. The optional argument - \var{translate}, if present, must be a 256-character string - indicating how characters (both of the pattern and of the strings to - be matched) are translated before comparing them; the \code{i}-th - element of the string gives the translation for the character with - \ASCII{} code \code{i}. This can be used to implement - case-insensitive matching; see the \code{casefold} data item below. - - The sequence - -\bcode\begin{verbatim} -prog = regex.compile(pat) -result = prog.match(str) -\end{verbatim}\ecode - -is equivalent to - -\bcode\begin{verbatim} -result = regex.match(pat, str) -\end{verbatim}\ecode - -but the version using \code{compile()} is more efficient when multiple -regular expressions are used concurrently in a single program. (The -compiled version of the last pattern passed to \code{regex.match()} or -\code{regex.search()} is cached, so programs that use only a single -regular expression at a time needn't worry about compiling regular -expressions.) -\end{funcdesc} - -\begin{funcdesc}{set_syntax}{flags} - Set the syntax to be used by future calls to \code{compile}, - \code{match} and \code{search}. (Already compiled expression objects - are not affected.) The argument is an integer which is the OR of - several flag bits. The return value is the previous value of - the syntax flags. Names for the flags are defined in the standard - module \code{regex_syntax}; read the file \file{regex_syntax.py} for - more information. -\end{funcdesc} - -\begin{funcdesc}{symcomp}{pattern\optional{\, translate}} -This is like \code{compile}, but supports symbolic group names: if a -parenthesis-enclosed group begins with a group name in angular -brackets, e.g. \code{'\e(<id>[a-z][a-z0-9]*\e)'}, the group can -be referenced by its name in arguments to the \code{group} method of -the resulting compiled regular expression object, like this: -\code{p.group('id')}. Group names may contain alphanumeric characters -and \code{'_'} only. -\end{funcdesc} - -\begin{excdesc}{error} - Exception raised when a string passed to one of the functions here - is not a valid regular expression (e.g., unmatched parentheses) or - when some other error occurs during compilation or matching. (It is - never an error if a string contains no match for a pattern.) -\end{excdesc} - -\begin{datadesc}{casefold} -A string suitable to pass as \var{translate} argument to -\code{compile} to map all upper case characters to their lowercase -equivalents. -\end{datadesc} - -\noindent -Compiled regular expression objects support these methods: - -\renewcommand{\indexsubitem}{(regex method)} -\begin{funcdesc}{match}{string\optional{\, pos}} - Return how many characters at the beginning of \var{string} match - the compiled regular expression. Return \code{-1} if the string - does not match the pattern (this is different from a zero-length - match!). - - The optional second parameter \var{pos} gives an index in the string - where the search is to start; it defaults to \code{0}. This is not - completely equivalent to slicing the string; the \code{'\^'} pattern - character matches at the real begin of the string and at positions - just after a newline, not necessarily at the index where the search - is to start. -\end{funcdesc} - -\begin{funcdesc}{search}{string\optional{\, pos}} - Return the first position in \var{string} that matches the regular - expression \code{pattern}. Return \code{-1} if no position in the - string matches the pattern (this is different from a zero-length - match anywhere!). - - The optional second parameter has the same meaning as for the - \code{match} method. -\end{funcdesc} - -\begin{funcdesc}{group}{index\, index\, ...} -This method is only valid when the last call to the \code{match} -or \code{search} method found a match. It returns one or more -groups of the match. If there is a single \var{index} argument, -the result is a single string; if there are multiple arguments, the -result is a tuple with one item per argument. If the \var{index} is -zero, the corresponding return value is the entire matching string; if -it is in the inclusive range [1..99], it is the string matching the -the corresponding parenthesized group (using the default syntax, -groups are parenthesized using \code{\\(} and \code{\\)}). If no -such group exists, the corresponding result is \code{None}. - -If the regular expression was compiled by \code{symcomp} instead of -\code{compile}, the \var{index} arguments may also be strings -identifying groups by their group name. -\end{funcdesc} - -\noindent -Compiled regular expressions support these data attributes: - -\renewcommand{\indexsubitem}{(regex attribute)} - -\begin{datadesc}{regs} -When the last call to the \code{match} or \code{search} method found a -match, this is a tuple of pairs of indices corresponding to the -beginning and end of all parenthesized groups in the pattern. Indices -are relative to the string argument passed to \code{match} or -\code{search}. The 0-th tuple gives the beginning and end or the -whole pattern. When the last match or search failed, this is -\code{None}. -\end{datadesc} - -\begin{datadesc}{last} -When the last call to the \code{match} or \code{search} method found a -match, this is the string argument passed to that method. When the -last match or search failed, this is \code{None}. -\end{datadesc} - -\begin{datadesc}{translate} -This is the value of the \var{translate} argument to -\code{regex.compile} that created this regular expression object. If -the \var{translate} argument was omitted in the \code{regex.compile} -call, this is \code{None}. -\end{datadesc} - -\begin{datadesc}{givenpat} -The regular expression pattern as passed to \code{compile} or -\code{symcomp}. -\end{datadesc} - -\begin{datadesc}{realpat} -The regular expression after stripping the group names for regular -expressions compiled with \code{symcomp}. Same as \code{givenpat} -otherwise. -\end{datadesc} - -\begin{datadesc}{groupindex} -A dictionary giving the mapping from symbolic group names to numerical -group indices for regular expressions compiled with \code{symcomp}. -\code{None} otherwise. -\end{datadesc} diff --git a/Doc/libregsub.tex b/Doc/libregsub.tex deleted file mode 100644 index 5747e4f99b..0000000000 --- a/Doc/libregsub.tex +++ /dev/null @@ -1,30 +0,0 @@ -\section{Standard Module \sectcode{regsub}} - -\stmodindex{regsub} -This module defines a number of functions useful for working with -regular expressions (see built-in module \code{regex}). - -\renewcommand{\indexsubitem}{(in module regsub)} -\begin{funcdesc}{sub}{pat\, repl\, str} -Replace the first occurrence of pattern \var{pat} in string -\var{str} by replacement \var{repl}. If the pattern isn't found, -the string is returned unchanged. The pattern may be a string or an -already compiled pattern. The replacement may contain references -\samp{\e \var{digit}} to subpatterns and escaped backslashes. -\end{funcdesc} - -\begin{funcdesc}{gsub}{pat\, repl\, str} -Replace all (non-overlapping) occurrences of pattern \var{pat} in -string \var{str} by replacement \var{repl}. The same rules as for -\code{sub()} apply. Empty matches for the pattern are replaced only -when not adjacent to a previous match, so e.g. -\code{gsub('', '-', 'abc')} returns \code{'-a-b-c-'}. -\end{funcdesc} - -\begin{funcdesc}{split}{str\, pat} -Split the string \var{str} in fields separated by delimiters matching -the pattern \var{pat}, and return a list containing the fields. Only -non-empty matches for the pattern are considered, so e.g. -\code{split('a:b', ':*')} returns \code{['a', 'b']} and -\code{split('abc', '')} returns \code{['abc']}. -\end{funcdesc} diff --git a/Doc/librfc822.tex b/Doc/librfc822.tex deleted file mode 100644 index e2d182e89b..0000000000 --- a/Doc/librfc822.tex +++ /dev/null @@ -1,112 +0,0 @@ -\section{Standard Module \sectcode{rfc822}} -\stmodindex{rfc822} - -\renewcommand{\indexsubitem}{(in module rfc822)} - -This module defines a class, \code{Message}, which represents a -collection of ``email headers'' as defined by the Internet standard -RFC 822. It is used in various contexts, usually to read such headers -from a file. - -A \code{Message} instance is instantiated with an open file object as -parameter. Instantiation reads headers from the file up to a blank -line and stores them in the instance; after instantiation, the file is -positioned directly after the blank line that terminates the headers. - -Input lines as read from the file may either be terminated by CR-LF or -by a single linefeed; a terminating CR-LF is replaced by a single -linefeed before the line is stored. - -All header matching is done independent of upper or lower case; -e.g. \code{m['From']}, \code{m['from']} and \code{m['FROM']} all yield -the same result. - -\subsection{Message Objects} - -A \code{Message} instance has the following methods: - -\begin{funcdesc}{rewindbody}{} -Seek to the start of the message body. This only works if the file -object is seekable. -\end{funcdesc} - -\begin{funcdesc}{getallmatchingheaders}{name} -Return a list of lines consisting of all headers matching -\var{name}, if any. Each physical line, whether it is a continuation -line or not, is a separate list item. Return the empty list if no -header matches \var{name}. -\end{funcdesc} - -\begin{funcdesc}{getfirstmatchingheader}{name} -Return a list of lines comprising the first header matching -\var{name}, and its continuation line(s), if any. Return \code{None} -if there is no header matching \var{name}. -\end{funcdesc} - -\begin{funcdesc}{getrawheader}{name} -Return a single string consisting of the text after the colon in the -first header matching \var{name}. This includes leading whitespace, -the trailing linefeed, and internal linefeeds and whitespace if there -any continuation line(s) were present. Return \code{None} if there is -no header matching \var{name}. -\end{funcdesc} - -\begin{funcdesc}{getheader}{name} -Like \code{getrawheader(\var{name})}, but strip leading and trailing -whitespace (but not internal whitespace). -\end{funcdesc} - -\begin{funcdesc}{getaddr}{name} -Return a pair (full name, email address) parsed from the string -returned by \code{getheader(\var{name})}. If no header matching -\var{name} exists, return \code{None, None}; otherwise both the full -name and the address are (possibly empty )strings. - -Example: If \code{m}'s first \code{From} header contains the string\\ -\code{'jack@cwi.nl (Jack Jansen)'}, then -\code{m.getaddr('From')} will yield the pair -\code{('Jack Jansen', 'jack@cwi.nl')}. -If the header contained -\code{'Jack Jansen <jack@cwi.nl>'} instead, it would yield the -exact same result. -\end{funcdesc} - -\begin{funcdesc}{getaddrlist}{name} -This is similar to \code{getaddr(\var{list})}, but parses a header -containing a list of email addresses (e.g. a \code{To} header) and -returns a list of (full name, email address) pairs (even if there was -only one address in the header). If there is no header matching -\var{name}, return an empty list. - -XXX The current version of this function is not really correct. It -yields bogus results if a full name contains a comma. -\end{funcdesc} - -\begin{funcdesc}{getdate}{name} -Retrieve a header using \code{getheader} and parse it into a 9-tuple -compatible with \code{time.mktime()}. If there is no header matching -\var{name}, or it is unparsable, return \code{None}. - -Date parsing appears to be a black art, and not all mailers adhere to -the standard. While it has been tested and found correct on a large -collection of email from many sources, it is still possible that this -function may occasionally yield an incorrect result. -\end{funcdesc} - -\code{Message} instances also support a read-only mapping interface. -In particular: \code{m[name]} is the same as \code{m.getheader(name)}; -and \code{len(m)}, \code{m.has_key(name)}, \code{m.keys()}, -\code{m.values()} and \code{m.items()} act as expected (and -consistently). - -Finally, \code{Message} instances have two public instance variables: - -\begin{datadesc}{headers} -A list containing the entire set of header lines, in the order in -which they were read. Each line contains a trailing newline. The -blank line terminating the headers is not contained in the list. -\end{datadesc} - -\begin{datadesc}{fp} -The file object passed at instantiation time. -\end{datadesc} diff --git a/Doc/librgbimg.tex b/Doc/librgbimg.tex deleted file mode 100644 index ace426fa98..0000000000 --- a/Doc/librgbimg.tex +++ /dev/null @@ -1,45 +0,0 @@ -\section{Built-in Module \sectcode{rgbimg}} -\bimodindex{rgbimg} - -The rgbimg module allows python programs to access SGI imglib image -files (also known as \file{.rgb} files). The module is far from -complete, but is provided anyway since the functionality that there is -is enough in some cases. Currently, colormap files are not supported. - -The module defines the following variables and functions: - -\renewcommand{\indexsubitem}{(in module rgbimg)} -\begin{excdesc}{error} -This exception is raised on all errors, such as unsupported file type, etc. -\end{excdesc} - -\begin{funcdesc}{sizeofimage}{file} -This function returns a tuple \code{(\var{x}, \var{y})} where -\var{x} and \var{y} are the size of the image in pixels. -Only 4 byte RGBA pixels, 3 byte RGB pixels, and 1 byte greyscale pixels -are currently supported. -\end{funcdesc} - -\begin{funcdesc}{longimagedata}{file} -This function reads and decodes the image on the specified file, and -returns it as a Python string. The string has 4 byte RGBA pixels. -The bottom left pixel is the first in -the string. This format is suitable to pass to \code{gl.lrectwrite}, -for instance. -\end{funcdesc} - -\begin{funcdesc}{longstoimage}{data\, x\, y\, z\, file} -This function writes the RGBA data in \var{data} to image -file \var{file}. \var{x} and \var{y} give the size of the image. -\var{z} is 1 if the saved image should be 1 byte greyscale, 3 if the -saved image should be 3 byte RGB data, or 4 if the saved images should -be 4 byte RGBA data. The input data always contains 4 bytes per pixel. -These are the formats returned by \code{gl.lrectread}. -\end{funcdesc} - -\begin{funcdesc}{ttob}{flag} -This function sets a global flag which defines whether the scan lines -of the image are read or written from bottom to top (flag is zero, -compatible with SGI GL) or from top to bottom(flag is one, -compatible with X)\@. The default is zero. -\end{funcdesc} diff --git a/Doc/librotor.tex b/Doc/librotor.tex deleted file mode 100644 index 6befb05590..0000000000 --- a/Doc/librotor.tex +++ /dev/null @@ -1,105 +0,0 @@ -\section{Built-in Module \sectcode{rotor}} -\bimodindex{rotor} - -This module implements a rotor-based encryption algorithm, contributed by -Lance Ellinghouse. The design is derived from the Enigma device, a machine -used during World War II to encipher messages. A rotor is simply a -permutation. For example, if the character `A' is the origin of the rotor, -then a given rotor might map `A' to `L', `B' to `Z', `C' to `G', and so on. -To encrypt, we choose several different rotors, and set the origins of the -rotors to known positions; their initial position is the ciphering key. To -encipher a character, we permute the original character by the first rotor, -and then apply the second rotor's permutation to the result. We continue -until we've applied all the rotors; the resulting character is our -ciphertext. We then change the origin of the final rotor by one position, -from `A' to `B'; if the final rotor has made a complete revolution, then we -rotate the next-to-last rotor by one position, and apply the same procedure -recursively. In other words, after enciphering one character, we advance -the rotors in the same fashion as a car's odometer. Decoding works in the -same way, except we reverse the permutations and apply them in the opposite -order. -\index{Ellinghouse, Lance} -\indexii{Enigma}{cipher} - -The available functions in this module are: - -\renewcommand{\indexsubitem}{(in module rotor)} -\begin{funcdesc}{newrotor}{key\optional{\, numrotors}} -Return a rotor object. \var{key} is a string containing the encryption key -for the object; it can contain arbitrary binary data. The key will be used -to randomly generate the rotor permutations and their initial positions. -\var{numrotors} is the number of rotor permutations in the returned object; -if it is omitted, a default value of 6 will be used. -\end{funcdesc} - -Rotor objects have the following methods: - -\renewcommand{\indexsubitem}{(rotor method)} -\begin{funcdesc}{setkey}{} -Reset the rotor to its initial state. -\end{funcdesc} - -\begin{funcdesc}{encrypt}{plaintext} -Reset the rotor object to its initial state and encrypt \var{plaintext}, -returning a string containing the ciphertext. The ciphertext is always the -same length as the original plaintext. -\end{funcdesc} - -\begin{funcdesc}{encryptmore}{plaintext} -Encrypt \var{plaintext} without resetting the rotor object, and return a -string containing the ciphertext. -\end{funcdesc} - -\begin{funcdesc}{decrypt}{ciphertext} -Reset the rotor object to its initial state and decrypt \var{ciphertext}, -returning a string containing the ciphertext. The plaintext string will -always be the same length as the ciphertext. -\end{funcdesc} - -\begin{funcdesc}{decryptmore}{ciphertext} -Decrypt \var{ciphertext} without resetting the rotor object, and return a -string containing the ciphertext. -\end{funcdesc} - -An example usage: -\bcode\begin{verbatim} ->>> import rotor ->>> rt = rotor.newrotor('key', 12) ->>> rt.encrypt('bar') -'\2534\363' ->>> rt.encryptmore('bar') -'\357\375$' ->>> rt.encrypt('bar') -'\2534\363' ->>> rt.decrypt('\2534\363') -'bar' ->>> rt.decryptmore('\357\375$') -'bar' ->>> rt.decrypt('\357\375$') -'l(\315' ->>> del rt -\end{verbatim}\ecode - -The module's code is not an exact simulation of the original Enigma device; -it implements the rotor encryption scheme differently from the original. The -most important difference is that in the original Enigma, there were only 5 -or 6 different rotors in existence, and they were applied twice to each -character; the cipher key was the order in which they were placed in the -machine. The Python rotor module uses the supplied key to initialize a -random number generator; the rotor permutations and their initial positions -are then randomly generated. The original device only enciphered the -letters of the alphabet, while this module can handle any 8-bit binary data; -it also produces binary output. This module can also operate with an -arbitrary number of rotors. - -The original Enigma cipher was broken in 1944. % XXX: Is this right? -The version implemented here is probably a good deal more difficult to crack -(especially if you use many rotors), but it won't be impossible for -a truly skilful and determined attacker to break the cipher. So if you want -to keep the NSA out of your files, this rotor cipher may well be unsafe, but -for discouraging casual snooping through your files, it will probably be -just fine, and may be somewhat safer than using the Unix \file{crypt} -command. -\index{National Security Agency}\index{crypt(1)} -% XXX How were Unix commands represented in the docs? - diff --git a/Doc/libselect.tex b/Doc/libselect.tex deleted file mode 100644 index 0b50101395..0000000000 --- a/Doc/libselect.tex +++ /dev/null @@ -1,42 +0,0 @@ -\section{Built-in Module \sectcode{select}} -\bimodindex{select} - -This module provides access to the function \code{select} available in -most \UNIX{} versions. It defines the following: - -\renewcommand{\indexsubitem}{(in module select)} -\begin{excdesc}{error} -The exception raised when an error occurs. The accompanying value is -a pair containing the numeric error code from \code{errno} and the -corresponding string, as would be printed by the C function -\code{perror()}. -\end{excdesc} - -\begin{funcdesc}{select}{iwtd\, owtd\, ewtd\optional{\, timeout}} -This is a straightforward interface to the \UNIX{} \code{select()} -system call. The first three arguments are lists of `waitable -objects': either integers representing \UNIX{} file descriptors or -objects with a parameterless method named \code{fileno()} returning -such an integer. The three lists of waitable objects are for input, -output and `exceptional conditions', respectively. Empty lists are -allowed. The optional \var{timeout} argument specifies a time-out as a -floating point number in seconds. When the \var{timeout} argument -is omitted the function blocks until at least one file descriptor is -ready. A time-out value of zero specifies a poll and never blocks. - -The return value is a triple of lists of objects that are ready: -subsets of the first three arguments. When the time-out is reached -without a file descriptor becoming ready, three empty lists are -returned. - -Amongst the acceptable object types in the lists are Python file -objects (e.g. \code{sys.stdin}, or objects returned by \code{open()} -or \code{posix.popen()}), socket objects returned by -\code{socket.socket()}, and the module \code{stdwin} which happens to -define a function \code{fileno()} for just this purpose. You may -also define a \dfn{wrapper} class yourself, as long as it has an -appropriate \code{fileno()} method (that really returns a \UNIX{} file -descriptor, not just a random integer). -\end{funcdesc} -\ttindex{socket} -\ttindex{stdwin} diff --git a/Doc/libsgi.tex b/Doc/libsgi.tex deleted file mode 100644 index 8deede84a8..0000000000 --- a/Doc/libsgi.tex +++ /dev/null @@ -1,4 +0,0 @@ -\chapter{SGI IRIX Specific Services} - -The modules described in this chapter provide interfaces to features -that are unique to SGI's IRIX operating system (versions 4 and 5). diff --git a/Doc/libsgmllib.tex b/Doc/libsgmllib.tex deleted file mode 100644 index 129bdd9adc..0000000000 --- a/Doc/libsgmllib.tex +++ /dev/null @@ -1,148 +0,0 @@ -\section{Standard Module \sectcode{sgmllib}} -\stmodindex{sgmllib} -\index{SGML} - -\renewcommand{\indexsubitem}{(in module sgmllib)} - -This module defines a class \code{SGMLParser} which serves as the -basis for parsing text files formatted in SGML (Standard Generalized -Mark-up Language). In fact, it does not provide a full SGML parser ---- it only parses SGML insofar as it is used by HTML, and the module only -exists as a basis for the \code{htmllib} module. -\stmodindex{htmllib} - -In particular, the parser is hardcoded to recognize the following -elements: - -\begin{itemize} - -\item -Opening and closing tags of the form -``\code{<\var{tag} \var{attr}="\var{value}" ...>}'' and -``\code{</\var{tag}>}'', respectively. - -\item -Character references of the form ``\code{\&\#\var{name};}''. - -\item -Entity references of the form ``\code{\&\var{name};}''. - -\item -SGML comments of the form ``\code{<!--\var{text}>}''. - -\end{itemize} - -The \code{SGMLParser} class must be instantiated without arguments. -It has the following interface methods: - -\begin{funcdesc}{reset}{} -Reset the instance. Loses all unprocessed data. This is called -implicitly at instantiation time. -\end{funcdesc} - -\begin{funcdesc}{setnomoretags}{} -Stop processing tags. Treat all following input as literal input -(CDATA). (This is only provided so the HTML tag \code{<PLAINTEXT>} -can be implemented.) -\end{funcdesc} - -\begin{funcdesc}{setliteral}{} -Enter literal mode (CDATA mode). -\end{funcdesc} - -\begin{funcdesc}{feed}{data} -Feed some text to the parser. It is processed insofar as it consists -of complete elements; incomplete data is buffered until more data is -fed or \code{close()} is called. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Force processing of all buffered data as if it were followed by an -end-of-file mark. This method may be redefined by a derived class to -define additional processing at the end of the input, but the -redefined version should always call \code{SGMLParser.close()}. -\end{funcdesc} - -\begin{funcdesc}{handle_charref}{ref} -This method is called to process a character reference of the form -``\code{\&\#\var{ref};}'' where \var{ref} is a decimal number in the -range 0-255. It translates the character to \ASCII{} and calls the -method \code{handle_data()} with the character as argument. If -\var{ref} is invalid or out of range, the method -\code{unknown_charref(\var{ref})} is called instead. -\end{funcdesc} - -\begin{funcdesc}{handle_entityref}{ref} -This method is called to process an entity reference of the form -``\code{\&\var{ref};}'' where \var{ref} is an alphabetic entity -reference. It looks for \var{ref} in the instance (or class) -variable \code{entitydefs} which should give the entity's translation. -If a translation is found, it calls the method \code{handle_data()} -with the translation; otherwise, it calls the method -\code{unknown_entityref(\var{ref})}. -\end{funcdesc} - -\begin{funcdesc}{handle_data}{data} -This method is called to process arbitrary data. It is intended to be -overridden by a derived class; the base class implementation does -nothing. -\end{funcdesc} - -\begin{funcdesc}{unknown_starttag}{tag\, attributes} -This method is called to process an unknown start tag. It is intended -to be overridden by a derived class; the base class implementation -does nothing. The \var{attributes} argument is a list of -(\var{name}, \var{value}) pairs containing the attributes found inside -the tag's \code{<>} brackets. The \var{name} has been translated to -lower case and double quotes and backslashes in the \var{value} have -been interpreted. For instance, for the tag -\code{<A HREF="http://www.cwi.nl/">}, this method would be -called as \code{unknown_starttag('a', [('href', 'http://www.cwi.nl/')])}. -\end{funcdesc} - -\begin{funcdesc}{unknown_endtag}{tag} -This method is called to process an unknown end tag. It is intended -to be overridden by a derived class; the base class implementation -does nothing. -\end{funcdesc} - -\begin{funcdesc}{unknown_charref}{ref} -This method is called to process an unknown character reference. It -is intended to be overridden by a derived class; the base class -implementation does nothing. -\end{funcdesc} - -\begin{funcdesc}{unknown_entityref}{ref} -This method is called to process an unknown entity reference. It is -intended to be overridden by a derived class; the base class -implementation does nothing. -\end{funcdesc} - -Apart from overriding or extending the methods listed above, derived -classes may also define methods of the following form to define -processing of specific tags. Tag names in the input stream are case -independent; the \var{tag} occurring in method names must be in lower -case: - -\begin{funcdesc}{start_\var{tag}}{attributes} -This method is called to process an opening tag \var{tag}. It has -preference over \code{do_\var{tag}()}. The \var{attributes} argument -has the same meaning as described for \code{unknown_tag()} above. -\end{funcdesc} - -\begin{funcdesc}{do_\var{tag}}{attributes} -This method is called to process an opening tag \var{tag} that does -not come with a matching closing tag. The \var{attributes} argument -has the same meaning as described for \code{unknown_tag()} above. -\end{funcdesc} - -\begin{funcdesc}{end_\var{tag}}{} -This method is called to process a closing tag \var{tag}. -\end{funcdesc} - -Note that the parser maintains a stack of opening tags for which no -matching closing tag has been found yet. Only tags processed by -\code{start_\var{tag}()} are pushed on this stack. Definition of a -\code{end_\var{tag}()} method is optional for these tags. For tags -processed by \code{do_\var{tag}()} or by \code{unknown_tag()}, no -\code{end_\var{tag}()} method must be defined. diff --git a/Doc/libshelve.tex b/Doc/libshelve.tex deleted file mode 100644 index a232add09d..0000000000 --- a/Doc/libshelve.tex +++ /dev/null @@ -1,59 +0,0 @@ -\section{Standard Module \sectcode{shelve}} -\stmodindex{shelve} -\stmodindex{pickle} -\bimodindex{dbm} -\bimodindex{gdbm} - -A ``shelf'' is a persistent, dictionary-like object. The difference -with ``dbm'' databases is that the values (not the keys!) in a shelf -can be essentially arbitrary Python objects --- anything that the -\code{pickle} module can handle. This includes most class instances, -recursive data types, and objects containing lots of shared -sub-objects. The keys are ordinary strings. - -To summarize the interface (\code{key} is a string, \code{data} is an -arbitrary object): - -\begin{verbatim} -import shelve - -d = shelve.open(filename) # open, with (g)dbm filename -- no suffix - -d[key] = data # store data at key (overwrites old data if - # using an existing key) -data = d[key] # retrieve data at key (raise KeyError if no - # such key) -del d[key] # delete data stored at key (raises KeyError - # if no such key) -flag = d.has_key(key) # true if the key exists -list = d.keys() # a list of all existing keys (slow!) - -d.close() # close it -\end{verbatim} - -Restrictions: - -\begin{itemize} - -\item -The choice of which database package will be used (e.g. dbm or gdbm) -depends on which interface is available. Therefore it isn't safe to -open the database directly using dbm. The database is also -(unfortunately) subject to the limitations of dbm, if it is used --- -this means that (the pickled representation of) the objects stored in -the database should be fairly small, and in rare cases key collisions -may cause the database to refuse updates. - -\item -Dependent on the implementation, closing a persistent dictionary may -or may not be necessary to flush changes to disk. - -\item -The \code{shelve} module does not support {\em concurrent} read/write -access to shelved objects. (Multiple simultaneous read accesses are -safe.) When a program has a shelf open for writing, no other program -should have it open for reading or writing. \UNIX{} file locking can -be used to solve this, but this differs across \UNIX{} versions and -requires knowledge about the database implementation used. - -\end{itemize} diff --git a/Doc/libsignal.tex b/Doc/libsignal.tex deleted file mode 100644 index 802c4d107f..0000000000 --- a/Doc/libsignal.tex +++ /dev/null @@ -1,139 +0,0 @@ -\section{Built-in Module \sectcode{signal}} - -\bimodindex{signal} -This module provides mechanisms to use signal handlers in Python. -Some general rules for working with signals handlers: - -\begin{itemize} - -\item -A handler for a particular signal, once set, remains installed until -it is explicitly reset (i.e. Python emulates the BSD style interface -regardless of the underlying implementation), with the exception of -the handler for \code{SIGCHLD}, which follows the underlying -implementation. - -\item -There is no way to ``block'' signals temporarily from critical -sections (since this is not supported by all \UNIX{} flavors). - -\item -Although Python signal handlers are called asynchronously as far as -the Python user is concerned, they can only occur between the -``atomic'' instructions of the Python interpreter. This means that -signals arriving during long calculations implemented purely in C -(e.g.\ regular expression matches on large bodies of text) may be -delayed for an arbitrary amount of time. - -\item -When a signal arrives during an I/O operation, it is possible that the -I/O operation raises an exception after the signal handler returns. -This is dependent on the underlying \UNIX{} system's semantics regarding -interrupted system calls. - -\item -Because the C signal handler always returns, it makes little sense to -catch synchronous errors like \code{SIGFPE} or \code{SIGSEGV}. - -\item -Python installs a small number of signal handlers by default: -\code{SIGPIPE} is ignored (so write errors on pipes and sockets can be -reported as ordinary Python exceptions), \code{SIGINT} is translated -into a \code{KeyboardInterrupt} exception, and \code{SIGTERM} is -caught so that necessary cleanup (especially \code{sys.exitfunc}) can -be performed before actually terminating. All of these can be -overridden. - -\item -Some care must be taken if both signals and threads are used in the -same program. The fundamental thing to remember in using signals and -threads simultaneously is:\ always perform \code{signal()} operations -in the main thread of execution. Any thread can perform an -\code{alarm()}, \code{getsignal()}, or \code{pause()}; only the main -thread can set a new signal handler, and the main thread will be the -only one to receive signals (this is enforced by the Python signal -module, even if the underlying thread implementation supports sending -signals to individual threads). This means that signals can't be used -as a means of interthread communication. Use locks instead. - -\end{itemize} - -The variables defined in the signal module are: - -\renewcommand{\indexsubitem}{(in module signal)} -\begin{datadesc}{SIG_DFL} - This is one of two standard signal handling options; it will simply - perform the default function for the signal. For example, on most - systems the default action for SIGQUIT is to dump core and exit, - while the default action for SIGCLD is to simply ignore it. -\end{datadesc} - -\begin{datadesc}{SIG_IGN} - This is another standard signal handler, which will simply ignore - the given signal. -\end{datadesc} - -\begin{datadesc}{SIG*} - All the signal numbers are defined symbolically. For example, the - hangup signal is defined as \code{signal.SIGHUP}; the variable names - are identical to the names used in C programs, as found in - \file{signal.h}. - The \UNIX{} man page for \file{signal} lists the existing signals (on - some systems this is \file{signal(2)}, on others the list is in - \file{signal(7)}). - Note that not all systems define the same set of signal names; only - those names defined by the system are defined by this module. -\end{datadesc} - -\begin{datadesc}{NSIG} - One more than the number of the highest signal number. -\end{datadesc} - -The signal module defines the following functions: - -\begin{funcdesc}{alarm}{time} - If \var{time} is non-zero, this function requests that a - \code{SIGALRM} signal be sent to the process in \var{time} seconds. - Any previously scheduled alarm is canceled (i.e.\ only one alarm can - be scheduled at any time). The returned value is then the number of - seconds before any previously set alarm was to have been delivered. - If \var{time} is zero, no alarm id scheduled, and any scheduled - alarm is canceled. The return value is the number of seconds - remaining before a previously scheduled alarm. If the return value - is zero, no alarm is currently scheduled. (See the \UNIX{} man page - \code{alarm(2)}.) -\end{funcdesc} - -\begin{funcdesc}{getsignal}{signalnum} - Return the current signal handler for the signal \var{signalnum}. - The returned value may be a callable Python object, or one of the - special values \code{signal.SIG_IGN}, \code{signal.SIG_DFL} or - \code{None}. Here, \code{signal.SIG_IGN} means that the signal was - previously ignored, \code{signal.SIG_DFL} means that the default way - of handling the signal was previously in use, and \code{None} means - that the previous signal handler was not installed from Python. -\end{funcdesc} - -\begin{funcdesc}{pause}{} - Cause the process to sleep until a signal is received; the - appropriate handler will then be called. Returns nothing. (See the - \UNIX{} man page \code{signal(2)}.) -\end{funcdesc} - -\begin{funcdesc}{signal}{signalnum\, handler} - Set the handler for signal \var{signalnum} to the function - \var{handler}. \var{handler} can be any callable Python object, or - one of the special values \code{signal.SIG_IGN} or - \code{signal.SIG_DFL}. The previous signal handler will be returned - (see the description of \code{getsignal()} above). (See the \UNIX{} - man page \code{signal(2)}.) - - When threads are enabled, this function can only be called from the - main thread; attempting to call it from other threads will cause a - \code{ValueError} exception to be raised. - - The \var{handler} is called with two arguments: the signal number - and the current stack frame (\code{None} or a frame object; see the - reference manual for a description of frame objects). -\obindex{frame} -\end{funcdesc} diff --git a/Doc/libsocket.tex b/Doc/libsocket.tex deleted file mode 100644 index 9b3c2285c2..0000000000 --- a/Doc/libsocket.tex +++ /dev/null @@ -1,317 +0,0 @@ -\section{Built-in Module \sectcode{socket}} - -\bimodindex{socket} -This module provides access to the BSD {\em socket} interface. -It is available on \UNIX{} systems that support this interface. - -For an introduction to socket programming (in C), see the following -papers: \emph{An Introductory 4.3BSD Interprocess Communication -Tutorial}, by Stuart Sechrest and \emph{An Advanced 4.3BSD Interprocess -Communication Tutorial}, by Samuel J. Leffler et al, both in the -\UNIX{} Programmer's Manual, Supplementary Documents 1 (sections PS1:7 -and PS1:8). The \UNIX{} manual pages for the various socket-related -system calls are also a valuable source of information on the details of -socket semantics. - -The Python interface is a straightforward transliteration of the -\UNIX{} system call and library interface for sockets to Python's -object-oriented style: the \code{socket()} function returns a -\dfn{socket object} whose methods implement the various socket system -calls. Parameter types are somewhat higer-level than in the C -interface: as with \code{read()} and \code{write()} operations on Python -files, buffer allocation on receive operations is automatic, and -buffer length is implicit on send operations. - -Socket addresses are represented as a single string for the -\code{AF_UNIX} address family and as a pair -\code{(\var{host}, \var{port})} for the \code{AF_INET} address family, -where \var{host} is a string representing -either a hostname in Internet domain notation like -\code{'daring.cwi.nl'} or an IP address like \code{'100.50.200.5'}, -and \var{port} is an integral port number. Other address families are -currently not supported. The address format required by a particular -socket object is automatically selected based on the address family -specified when the socket object was created. - -All errors raise exceptions. The normal exceptions for invalid -argument types and out-of-memory conditions can be raised; errors -related to socket or address semantics raise the error \code{socket.error}. - -Non-blocking mode is supported through the \code{setblocking()} -method. - -The module \code{socket} exports the following constants and functions: - -\renewcommand{\indexsubitem}{(in module socket)} -\begin{excdesc}{error} -This exception is raised for socket- or address-related errors. -The accompanying value is either a string telling what went wrong or a -pair \code{(\var{errno}, \var{string})} -representing an error returned by a system -call, similar to the value accompanying \code{posix.error}. -\end{excdesc} - -\begin{datadesc}{AF_UNIX} -\dataline{AF_INET} -These constants represent the address (and protocol) families, -used for the first argument to \code{socket()}. If the \code{AF_UNIX} -constant is not defined then this protocol is unsupported. -\end{datadesc} - -\begin{datadesc}{SOCK_STREAM} -\dataline{SOCK_DGRAM} -\dataline{SOCK_RAW} -\dataline{SOCK_RDM} -\dataline{SOCK_SEQPACKET} -These constants represent the socket types, -used for the second argument to \code{socket()}. -(Only \code{SOCK_STREAM} and -\code{SOCK_DGRAM} appear to be generally useful.) -\end{datadesc} - -\begin{datadesc}{SO_*} -\dataline{SOMAXCONN} -\dataline{MSG_*} -\dataline{SOL_*} -\dataline{IPPROTO_*} -\dataline{IPPORT_*} -\dataline{INADDR_*} -\dataline{IP_*} -Many constants of these forms, documented in the \UNIX{} documentation on -sockets and/or the IP protocol, are also defined in the socket module. -They are generally used in arguments to the \code{setsockopt} and -\code{getsockopt} methods of socket objects. In most cases, only -those symbols that are defined in the \UNIX{} header files are defined; -for a few symbols, default values are provided. -\end{datadesc} - -\begin{funcdesc}{gethostbyname}{hostname} -Translate a host name to IP address format. The IP address is -returned as a string, e.g., \code{'100.50.200.5'}. If the host name -is an IP address itself it is returned unchanged. -\end{funcdesc} - -\begin{funcdesc}{gethostname}{} -Return a string containing the hostname of the machine where -the Python interpreter is currently executing. If you want to know the -current machine's IP address, use -\code{socket.gethostbyname(socket.gethostname())}. -\end{funcdesc} - -\begin{funcdesc}{gethostbyaddr}{ip_address} -Return a triple \code{(hostname, aliaslist, ipaddrlist)} where -\code{hostname} is the primary host name responding to the given -\var{ip_address}, \code{aliaslist} is a (possibly empty) list of -alternative host names for the same address, and \code{ipaddrlist} is -a list of IP addresses for the same interface on the same -host (most likely containing only a single address). -\end{funcdesc} - -\begin{funcdesc}{getservbyname}{servicename\, protocolname} -Translate an Internet service name and protocol name to a port number -for that service. The protocol name should be \code{'tcp'} or -\code{'udp'}. -\end{funcdesc} - -\begin{funcdesc}{socket}{family\, type\optional{\, proto}} -Create a new socket using the given address family, socket type and -protocol number. The address family should be \code{AF_INET} or -\code{AF_UNIX}. The socket type should be \code{SOCK_STREAM}, -\code{SOCK_DGRAM} or perhaps one of the other \samp{SOCK_} constants. -The protocol number is usually zero and may be omitted in that case. -\end{funcdesc} - -\begin{funcdesc}{fromfd}{fd\, family\, type\optional{\, proto}} -Build a socket object from an existing file descriptor (an integer as -returned by a file object's \code{fileno} method). Address family, -socket type and protocol number are as for the \code{socket} function -above. The file descriptor should refer to a socket, but this is not -checked --- subsequent operations on the object may fail if the file -descriptor is invalid. This function is rarely needed, but can be -used to get or set socket options on a socket passed to a program as -standard input or output (e.g.\ a server started by the \UNIX{} inet -daemon). -\end{funcdesc} - -\subsection{Socket Objects} - -\noindent -Socket objects have the following methods. Except for -\code{makefile()} these correspond to \UNIX{} system calls applicable to -sockets. - -\renewcommand{\indexsubitem}{(socket method)} -\begin{funcdesc}{accept}{} -Accept a connection. -The socket must be bound to an address and listening for connections. -The return value is a pair \code{(\var{conn}, \var{address})} -where \var{conn} is a \emph{new} socket object usable to send and -receive data on the connection, and \var{address} is the address bound -to the socket on the other end of the connection. -\end{funcdesc} - -\begin{funcdesc}{bind}{address} -Bind the socket to \var{address}. The socket must not already be bound. -(The format of \var{address} depends on the address family --- see above.) -\end{funcdesc} - -\begin{funcdesc}{close}{} -Close the socket. All future operations on the socket object will fail. -The remote end will receive no more data (after queued data is flushed). -Sockets are automatically closed when they are garbage-collected. -\end{funcdesc} - -\begin{funcdesc}{connect}{address} -Connect to a remote socket at \var{address}. -(The format of \var{address} depends on the address family --- see above.) -\end{funcdesc} - -\begin{funcdesc}{fileno}{} -Return the socket's file descriptor (a small integer). This is useful -with \code{select}. -\end{funcdesc} - -\begin{funcdesc}{getpeername}{} -Return the remote address to which the socket is connected. This is -useful to find out the port number of a remote IP socket, for instance. -(The format of the address returned depends on the address family --- -see above.) On some systems this function is not supported. -\end{funcdesc} - -\begin{funcdesc}{getsockname}{} -Return the socket's own address. This is useful to find out the port -number of an IP socket, for instance. -(The format of the address returned depends on the address family --- -see above.) -\end{funcdesc} - -\begin{funcdesc}{getsockopt}{level\, optname\optional{\, buflen}} -Return the value of the given socket option (see the \UNIX{} man page -{\it getsockopt}(2)). The needed symbolic constants (\code{SO_*} etc.) -are defined in this module. If \var{buflen} -is absent, an integer option is assumed and its integer value -is returned by the function. If \var{buflen} is present, it specifies -the maximum length of the buffer used to receive the option in, and -this buffer is returned as a string. It is up to the caller to decode -the contents of the buffer (see the optional built-in module -\code{struct} for a way to decode C structures encoded as strings). -\end{funcdesc} - -\begin{funcdesc}{listen}{backlog} -Listen for connections made to the socket. The \var{backlog} argument -specifies the maximum number of queued connections and should be at -least 1; the maximum value is system-dependent (usually 5). -\end{funcdesc} - -\begin{funcdesc}{makefile}{\optional{mode\optional{\, bufsize}}} -Return a \dfn{file object} associated with the socket. (File objects -were described earlier under Built-in Types.) The file object -references a \code{dup()}ped version of the socket file descriptor, so -the file object and socket object may be closed or garbage-collected -independently. The optional \var{mode} and \var{bufsize} arguments -are interpreted the same way as by the built-in -\code{open()} function. -\end{funcdesc} - -\begin{funcdesc}{recv}{bufsize\optional{\, flags}} -Receive data from the socket. The return value is a string representing -the data received. The maximum amount of data to be received -at once is specified by \var{bufsize}. See the \UNIX{} manual page -for the meaning of the optional argument \var{flags}; it defaults to -zero. -\end{funcdesc} - -\begin{funcdesc}{recvfrom}{bufsize\optional{\, flags}} -Receive data from the socket. The return value is a pair -\code{(\var{string}, \var{address})} where \var{string} is a string -representing the data received and \var{address} is the address of the -socket sending the data. The optional \var{flags} argument has the -same meaning as for \code{recv()} above. -(The format of \var{address} depends on the address family --- see above.) -\end{funcdesc} - -\begin{funcdesc}{send}{string\optional{\, flags}} -Send data to the socket. The socket must be connected to a remote -socket. The optional \var{flags} argument has the same meaning as for -\code{recv()} above. Return the number of bytes sent. -\end{funcdesc} - -\begin{funcdesc}{sendto}{string\optional{\, flags}\, address} -Send data to the socket. The socket should not be connected to a -remote socket, since the destination socket is specified by -\code{address}. The optional \var{flags} argument has the same -meaning as for \code{recv()} above. Return the number of bytes sent. -(The format of \var{address} depends on the address family --- see above.) -\end{funcdesc} - -\begin{funcdesc}{setblocking}{flag} -Set blocking or non-blocking mode of the socket: if \var{flag} is 0, -the socket is set to non-blocking, else to blocking mode. Initially -all sockets are in blocking mode. In non-blocking mode, if a -\code{recv} call doesn't find any data, or if a \code{send} call can't -immediately dispose of the data, a \code{socket.error} exception is -raised; in blocking mode, the calls block until they can proceed. -\end{funcdesc} - -\begin{funcdesc}{setsockopt}{level\, optname\, value} -Set the value of the given socket option (see the \UNIX{} man page -{\it setsockopt}(2)). The needed symbolic constants are defined in -the \code{socket} module (\code{SO_*} etc.). The value can be an -integer or a string representing a buffer. In the latter case it is -up to the caller to ensure that the string contains the proper bits -(see the optional built-in module -\code{struct} for a way to encode C structures as strings). -\end{funcdesc} - -\begin{funcdesc}{shutdown}{how} -Shut down one or both halves of the connection. If \var{how} is \code{0}, -further receives are disallowed. If \var{how} is \code{1}, further sends are -disallowed. If \var{how} is \code{2}, further sends and receives are -disallowed. -\end{funcdesc} - -Note that there are no methods \code{read()} or \code{write()}; use -\code{recv()} and \code{send()} without \var{flags} argument instead. - -\subsection{Example} -\nodename{Socket Example} - -Here are two minimal example programs using the TCP/IP protocol:\ a -server that echoes all data that it receives back (servicing only one -client), and a client using it. Note that a server must perform the -sequence \code{socket}, \code{bind}, \code{listen}, \code{accept} -(possibly repeating the \code{accept} to service more than one client), -while a client only needs the sequence \code{socket}, \code{connect}. -Also note that the server does not \code{send}/\code{receive} on the -socket it is listening on but on the new socket returned by -\code{accept}. - -\bcode\begin{verbatim} -# Echo server program -from socket import * -HOST = '' # Symbolic name meaning the local host -PORT = 50007 # Arbitrary non-privileged server -s = socket(AF_INET, SOCK_STREAM) -s.bind(HOST, PORT) -s.listen(1) -conn, addr = s.accept() -print 'Connected by', addr -while 1: - data = conn.recv(1024) - if not data: break - conn.send(data) -conn.close() -\end{verbatim}\ecode - -\bcode\begin{verbatim} -# Echo client program -from socket import * -HOST = 'daring.cwi.nl' # The remote host -PORT = 50007 # The same port as used by the server -s = socket(AF_INET, SOCK_STREAM) -s.connect(HOST, PORT) -s.send('Hello, world') -data = s.recv(1024) -s.close() -print 'Received', `data` -\end{verbatim}\ecode diff --git a/Doc/libsomeos.tex b/Doc/libsomeos.tex deleted file mode 100644 index f9aedfe315..0000000000 --- a/Doc/libsomeos.tex +++ /dev/null @@ -1,23 +0,0 @@ -\chapter{Optional Operating System Services} - -The modules described in this chapter provide interfaces to operating -system features that are available on selected operating systems only. -The interfaces are generally modelled after the \UNIX{} or C -interfaces but they are available on some other systems as well -(e.g. Windows or NT). Here's an overview: - -\begin{description} - -\item[signal] ---- Set handlers for asynchronous events. - -\item[socket] ---- Low-level networking interface. - -\item[select] ---- Wait for I/O completion on multiple streams. - -\item[thread] ---- Create multiple threads of control within one namespace. - -\end{description} diff --git a/Doc/libstd.tex b/Doc/libstd.tex deleted file mode 100755 index e642a8d60b..0000000000 --- a/Doc/libstd.tex +++ /dev/null @@ -1,7 +0,0 @@ -\chapter{Standard Modules} - -The modules described in this chapter are implemented in Python, but -are considered to be a part of Python's standard environment: they are -always available.\footnote{at least in theory --- it is possible to -botch the library installation or to sabotage the module search path -so that these modules cannot be found.} diff --git a/Doc/libstdwin.tex b/Doc/libstdwin.tex deleted file mode 100644 index e009e3f0e0..0000000000 --- a/Doc/libstdwin.tex +++ /dev/null @@ -1,910 +0,0 @@ -\chapter{Standard Windowing Interface} - -The modules in this chapter are available only on those systems where -the STDWIN library is available. STDWIN runs on \UNIX{} under X11 and -on the Macintosh. See CWI report CS-R8817. - -\strong{Warning:} Using STDWIN is not recommended for new -applications. It has never been ported to Microsoft Windows or -Windows NT, and for X11 or the Macintosh it lacks important -functionality --- in particular, it has no tools for the construction -of dialogs. For most platforms, alternative, native solutions exist -(though none are currently documented in this manual): Tkinter for -\UNIX{} under X11, native Xt with Motif or Athena widgets for \UNIX{} -under X11, Win32 for Windows and Windows NT, and a collection of -native toolkit interfaces for the Macintosh. - -\section{Built-in Module \sectcode{stdwin}} -\bimodindex{stdwin} - -This module defines several new object types and functions that -provide access to the functionality of STDWIN. - -On Unix running X11, it can only be used if the \code{DISPLAY} -environment variable is set or an explicit \samp{-display -\var{displayname}} argument is passed to the Python interpreter. - -Functions have names that usually resemble their C STDWIN counterparts -with the initial `w' dropped. -Points are represented by pairs of integers; rectangles -by pairs of points. -For a complete description of STDWIN please refer to the documentation -of STDWIN for C programmers (aforementioned CWI report). - -\subsection{Functions Defined in Module \sectcode{stdwin}} -\nodename{STDWIN Functions} - -The following functions are defined in the \code{stdwin} module: - -\renewcommand{\indexsubitem}{(in module stdwin)} -\begin{funcdesc}{open}{title} -Open a new window whose initial title is given by the string argument. -Return a window object; window object methods are described below.% -\footnote{The Python version of STDWIN does not support draw procedures; all - drawing requests are reported as draw events.} -\end{funcdesc} - -\begin{funcdesc}{getevent}{} -Wait for and return the next event. -An event is returned as a triple: the first element is the event -type, a small integer; the second element is the window object to which -the event applies, or -\code{None} -if it applies to no window in particular; -the third element is type-dependent. -Names for event types and command codes are defined in the standard -module -\code{stdwinevent}. -\end{funcdesc} - -\begin{funcdesc}{pollevent}{} -Return the next event, if one is immediately available. -If no event is available, return \code{()}. -\end{funcdesc} - -\begin{funcdesc}{getactive}{} -Return the window that is currently active, or \code{None} if no -window is currently active. (This can be emulated by monitoring -WE_ACTIVATE and WE_DEACTIVATE events.) -\end{funcdesc} - -\begin{funcdesc}{listfontnames}{pattern} -Return the list of font names in the system that match the pattern (a -string). The pattern should normally be \code{'*'}; returns all -available fonts. If the underlying window system is X11, other -patterns follow the standard X11 font selection syntax (as used e.g. -in resource definitions), i.e. the wildcard character \code{'*'} -matches any sequence of characters (including none) and \code{'?'} -matches any single character. -On the Macintosh this function currently returns an empty list. -\end{funcdesc} - -\begin{funcdesc}{setdefscrollbars}{hflag\, vflag} -Set the flags controlling whether subsequently opened windows will -have horizontal and/or vertical scroll bars. -\end{funcdesc} - -\begin{funcdesc}{setdefwinpos}{h\, v} -Set the default window position for windows opened subsequently. -\end{funcdesc} - -\begin{funcdesc}{setdefwinsize}{width\, height} -Set the default window size for windows opened subsequently. -\end{funcdesc} - -\begin{funcdesc}{getdefscrollbars}{} -Return the flags controlling whether subsequently opened windows will -have horizontal and/or vertical scroll bars. -\end{funcdesc} - -\begin{funcdesc}{getdefwinpos}{} -Return the default window position for windows opened subsequently. -\end{funcdesc} - -\begin{funcdesc}{getdefwinsize}{} -Return the default window size for windows opened subsequently. -\end{funcdesc} - -\begin{funcdesc}{getscrsize}{} -Return the screen size in pixels. -\end{funcdesc} - -\begin{funcdesc}{getscrmm}{} -Return the screen size in millimeters. -\end{funcdesc} - -\begin{funcdesc}{fetchcolor}{colorname} -Return the pixel value corresponding to the given color name. -Return the default foreground color for unknown color names. -Hint: the following code tests whether you are on a machine that -supports more than two colors: -\bcode\begin{verbatim} -if stdwin.fetchcolor('black') <> \ - stdwin.fetchcolor('red') <> \ - stdwin.fetchcolor('white'): - print 'color machine' -else: - print 'monochrome machine' -\end{verbatim}\ecode -\end{funcdesc} - -\begin{funcdesc}{setfgcolor}{pixel} -Set the default foreground color. -This will become the default foreground color of windows opened -subsequently, including dialogs. -\end{funcdesc} - -\begin{funcdesc}{setbgcolor}{pixel} -Set the default background color. -This will become the default background color of windows opened -subsequently, including dialogs. -\end{funcdesc} - -\begin{funcdesc}{getfgcolor}{} -Return the pixel value of the current default foreground color. -\end{funcdesc} - -\begin{funcdesc}{getbgcolor}{} -Return the pixel value of the current default background color. -\end{funcdesc} - -\begin{funcdesc}{setfont}{fontname} -Set the current default font. -This will become the default font for windows opened subsequently, -and is also used by the text measuring functions \code{textwidth}, -\code{textbreak}, \code{lineheight} and \code{baseline} below. -This accepts two more optional parameters, size and style: -Size is the font size (in `points'). -Style is a single character specifying the style, as follows: -\code{'b'} = bold, -\code{'i'} = italic, -\code{'o'} = bold + italic, -\code{'u'} = underline; -default style is roman. -Size and style are ignored under X11 but used on the Macintosh. -(Sorry for all this complexity --- a more uniform interface is being designed.) -\end{funcdesc} - -\begin{funcdesc}{menucreate}{title} -Create a menu object referring to a global menu (a menu that appears in -all windows). -Methods of menu objects are described below. -Note: normally, menus are created locally; see the window method -\code{menucreate} below. -\strong{Warning:} the menu only appears in a window as long as the object -returned by this call exists. -\end{funcdesc} - -\begin{funcdesc}{newbitmap}{width\, height} -Create a new bitmap object of the given dimensions. -Methods of bitmap objects are described below. -Not available on the Macintosh. -\end{funcdesc} - -\begin{funcdesc}{fleep}{} -Cause a beep or bell (or perhaps a `visual bell' or flash, hence the -name). -\end{funcdesc} - -\begin{funcdesc}{message}{string} -Display a dialog box containing the string. -The user must click OK before the function returns. -\end{funcdesc} - -\begin{funcdesc}{askync}{prompt\, default} -Display a dialog that prompts the user to answer a question with yes or -no. -Return 0 for no, 1 for yes. -If the user hits the Return key, the default (which must be 0 or 1) is -returned. -If the user cancels the dialog, the -\code{KeyboardInterrupt} -exception is raised. -\end{funcdesc} - -\begin{funcdesc}{askstr}{prompt\, default} -Display a dialog that prompts the user for a string. -If the user hits the Return key, the default string is returned. -If the user cancels the dialog, the -\code{KeyboardInterrupt} -exception is raised. -\end{funcdesc} - -\begin{funcdesc}{askfile}{prompt\, default\, new} -Ask the user to specify a filename. -If -\var{new} -is zero it must be an existing file; otherwise, it must be a new file. -If the user cancels the dialog, the -\code{KeyboardInterrupt} -exception is raised. -\end{funcdesc} - -\begin{funcdesc}{setcutbuffer}{i\, string} -Store the string in the system's cut buffer number -\var{i}, -where it can be found (for pasting) by other applications. -On X11, there are 8 cut buffers (numbered 0..7). -Cut buffer number 0 is the `clipboard' on the Macintosh. -\end{funcdesc} - -\begin{funcdesc}{getcutbuffer}{i} -Return the contents of the system's cut buffer number -\var{i}. -\end{funcdesc} - -\begin{funcdesc}{rotatecutbuffers}{n} -On X11, rotate the 8 cut buffers by -\var{n}. -Ignored on the Macintosh. -\end{funcdesc} - -\begin{funcdesc}{getselection}{i} -Return X11 selection number -\var{i.} -Selections are not cut buffers. -Selection numbers are defined in module -\code{stdwinevents}. -Selection \code{WS_PRIMARY} is the -\dfn{primary} -selection (used by -xterm, -for instance); -selection \code{WS_SECONDARY} is the -\dfn{secondary} -selection; selection \code{WS_CLIPBOARD} is the -\dfn{clipboard} -selection (used by -xclipboard). -On the Macintosh, this always returns an empty string. -\end{funcdesc} - -\begin{funcdesc}{resetselection}{i} -Reset selection number -\var{i}, -if this process owns it. -(See window method -\code{setselection()}). -\end{funcdesc} - -\begin{funcdesc}{baseline}{} -Return the baseline of the current font (defined by STDWIN as the -vertical distance between the baseline and the top of the -characters). -\end{funcdesc} - -\begin{funcdesc}{lineheight}{} -Return the total line height of the current font. -\end{funcdesc} - -\begin{funcdesc}{textbreak}{str\, width} -Return the number of characters of the string that fit into a space of -\var{width} -bits wide when drawn in the curent font. -\end{funcdesc} - -\begin{funcdesc}{textwidth}{str} -Return the width in bits of the string when drawn in the current font. -\end{funcdesc} - -\begin{funcdesc}{connectionnumber}{} -\funcline{fileno}{} -(X11 under \UNIX{} only) Return the ``connection number'' used by the -underlying X11 implementation. (This is normally the file number of -the socket.) Both functions return the same value; -\code{connectionnumber()} is named after the corresponding function in -X11 and STDWIN, while \code{fileno()} makes it possible to use the -\code{stdwin} module as a ``file'' object parameter to -\code{select.select()}. Note that if \code{select()} implies that -input is possible on \code{stdwin}, this does not guarantee that an -event is ready --- it may be some internal communication going on -between the X server and the client library. Thus, you should call -\code{stdwin.pollevent()} until it returns \code{None} to check for -events if you don't want your program to block. Because of internal -buffering in X11, it is also possible that \code{stdwin.pollevent()} -returns an event while \code{select()} does not find \code{stdwin} to -be ready, so you should read any pending events with -\code{stdwin.pollevent()} until it returns \code{None} before entering -a blocking \code{select()} call. -\ttindex{select} -\end{funcdesc} - -\subsection{Window Objects} - -Window objects are created by \code{stdwin.open()}. They are closed -by their \code{close()} method or when they are garbage-collected. -Window objects have the following methods: - -\renewcommand{\indexsubitem}{(window method)} - -\begin{funcdesc}{begindrawing}{} -Return a drawing object, whose methods (described below) allow drawing -in the window. -\end{funcdesc} - -\begin{funcdesc}{change}{rect} -Invalidate the given rectangle; this may cause a draw event. -\end{funcdesc} - -\begin{funcdesc}{gettitle}{} -Returns the window's title string. -\end{funcdesc} - -\begin{funcdesc}{getdocsize}{} -\begin{sloppypar} -Return a pair of integers giving the size of the document as set by -\code{setdocsize()}. -\end{sloppypar} -\end{funcdesc} - -\begin{funcdesc}{getorigin}{} -Return a pair of integers giving the origin of the window with respect -to the document. -\end{funcdesc} - -\begin{funcdesc}{gettitle}{} -Return the window's title string. -\end{funcdesc} - -\begin{funcdesc}{getwinsize}{} -Return a pair of integers giving the size of the window. -\end{funcdesc} - -\begin{funcdesc}{getwinpos}{} -Return a pair of integers giving the position of the window's upper -left corner (relative to the upper left corner of the screen). -\end{funcdesc} - -\begin{funcdesc}{menucreate}{title} -Create a menu object referring to a local menu (a menu that appears -only in this window). -Methods of menu objects are described below. -{\bf Warning:} the menu only appears as long as the object -returned by this call exists. -\end{funcdesc} - -\begin{funcdesc}{scroll}{rect\, point} -Scroll the given rectangle by the vector given by the point. -\end{funcdesc} - -\begin{funcdesc}{setdocsize}{point} -Set the size of the drawing document. -\end{funcdesc} - -\begin{funcdesc}{setorigin}{point} -Move the origin of the window (its upper left corner) -to the given point in the document. -\end{funcdesc} - -\begin{funcdesc}{setselection}{i\, str} -Attempt to set X11 selection number -\var{i} -to the string -\var{str}. -(See stdwin method -\code{getselection()} -for the meaning of -\var{i}.) -Return true if it succeeds. -If succeeds, the window ``owns'' the selection until -(a) another application takes ownership of the selection; or -(b) the window is deleted; or -(c) the application clears ownership by calling -\code{stdwin.resetselection(\var{i})}. -When another application takes ownership of the selection, a -\code{WE_LOST_SEL} -event is received for no particular window and with the selection number -as detail. -Ignored on the Macintosh. -\end{funcdesc} - -\begin{funcdesc}{settimer}{dsecs} -Schedule a timer event for the window in -\code{\var{dsecs}/10} -seconds. -\end{funcdesc} - -\begin{funcdesc}{settitle}{title} -Set the window's title string. -\end{funcdesc} - -\begin{funcdesc}{setwincursor}{name} -\begin{sloppypar} -Set the window cursor to a cursor of the given name. -It raises the -\code{RuntimeError} -exception if no cursor of the given name exists. -Suitable names include -\code{'ibeam'}, -\code{'arrow'}, -\code{'cross'}, -\code{'watch'} -and -\code{'plus'}. -On X11, there are many more (see -\file{<X11/cursorfont.h>}). -\end{sloppypar} -\end{funcdesc} - -\begin{funcdesc}{setwinpos}{h\, v} -Set the the position of the window's upper left corner (relative to -the upper left corner of the screen). -\end{funcdesc} - -\begin{funcdesc}{setwinsize}{width\, height} -Set the window's size. -\end{funcdesc} - -\begin{funcdesc}{show}{rect} -Try to ensure that the given rectangle of the document is visible in -the window. -\end{funcdesc} - -\begin{funcdesc}{textcreate}{rect} -Create a text-edit object in the document at the given rectangle. -Methods of text-edit objects are described below. -\end{funcdesc} - -\begin{funcdesc}{setactive}{} -Attempt to make this window the active window. If successful, this -will generate a WE_ACTIVATE event (and a WE_DEACTIVATE event in case -another window in this application became inactive). -\end{funcdesc} - -\begin{funcdesc}{close}{} -Discard the window object. It should not be used again. -\end{funcdesc} - -\subsection{Drawing Objects} - -Drawing objects are created exclusively by the window method -\code{begindrawing()}. -Only one drawing object can exist at any given time; the drawing object -must be deleted to finish drawing. -No drawing object may exist when -\code{stdwin.getevent()} -is called. -Drawing objects have the following methods: - -\renewcommand{\indexsubitem}{(drawing method)} - -\begin{funcdesc}{box}{rect} -Draw a box just inside a rectangle. -\end{funcdesc} - -\begin{funcdesc}{circle}{center\, radius} -Draw a circle with given center point and radius. -\end{funcdesc} - -\begin{funcdesc}{elarc}{center\, \(rh\, rv\)\, \(a1\, a2\)} -Draw an elliptical arc with given center point. -\code{(\var{rh}, \var{rv})} -gives the half sizes of the horizontal and vertical radii. -\code{(\var{a1}, \var{a2})} -gives the angles (in degrees) of the begin and end points. -0 degrees is at 3 o'clock, 90 degrees is at 12 o'clock. -\end{funcdesc} - -\begin{funcdesc}{erase}{rect} -Erase a rectangle. -\end{funcdesc} - -\begin{funcdesc}{fillcircle}{center\, radius} -Draw a filled circle with given center point and radius. -\end{funcdesc} - -\begin{funcdesc}{fillelarc}{center\, \(rh\, rv\)\, \(a1\, a2\)} -Draw a filled elliptical arc; arguments as for \code{elarc}. -\end{funcdesc} - -\begin{funcdesc}{fillpoly}{points} -Draw a filled polygon given by a list (or tuple) of points. -\end{funcdesc} - -\begin{funcdesc}{invert}{rect} -Invert a rectangle. -\end{funcdesc} - -\begin{funcdesc}{line}{p1\, p2} -Draw a line from point -\var{p1} -to -\var{p2}. -\end{funcdesc} - -\begin{funcdesc}{paint}{rect} -Fill a rectangle. -\end{funcdesc} - -\begin{funcdesc}{poly}{points} -Draw the lines connecting the given list (or tuple) of points. -\end{funcdesc} - -\begin{funcdesc}{shade}{rect\, percent} -Fill a rectangle with a shading pattern that is about -\var{percent} -percent filled. -\end{funcdesc} - -\begin{funcdesc}{text}{p\, str} -Draw a string starting at point p (the point specifies the -top left coordinate of the string). -\end{funcdesc} - -\begin{funcdesc}{xorcircle}{center\, radius} -\funcline{xorelarc}{center\, \(rh\, rv\)\, \(a1\, a2\)} -\funcline{xorline}{p1\, p2} -\funcline{xorpoly}{points} -Draw a circle, an elliptical arc, a line or a polygon, respectively, -in XOR mode. -\end{funcdesc} - -\begin{funcdesc}{setfgcolor}{} -\funcline{setbgcolor}{} -\funcline{getfgcolor}{} -\funcline{getbgcolor}{} -These functions are similar to the corresponding functions described -above for the -\code{stdwin} -module, but affect or return the colors currently used for drawing -instead of the global default colors. -When a drawing object is created, its colors are set to the window's -default colors, which are in turn initialized from the global default -colors when the window is created. -\end{funcdesc} - -\begin{funcdesc}{setfont}{} -\funcline{baseline}{} -\funcline{lineheight}{} -\funcline{textbreak}{} -\funcline{textwidth}{} -These functions are similar to the corresponding functions described -above for the -\code{stdwin} -module, but affect or use the current drawing font instead of -the global default font. -When a drawing object is created, its font is set to the window's -default font, which is in turn initialized from the global default -font when the window is created. -\end{funcdesc} - -\begin{funcdesc}{bitmap}{point\, bitmap\, mask} -Draw the \var{bitmap} with its top left corner at \var{point}. -If the optional \var{mask} argument is present, it should be either -the same object as \var{bitmap}, to draw only those bits that are set -in the bitmap, in the foreground color, or \code{None}, to draw all -bits (ones are drawn in the foreground color, zeros in the background -color). -Not available on the Macintosh. -\end{funcdesc} - -\begin{funcdesc}{cliprect}{rect} -Set the ``clipping region'' to a rectangle. -The clipping region limits the effect of all drawing operations, until -it is changed again or until the drawing object is closed. When a -drawing object is created the clipping region is set to the entire -window. When an object to be drawn falls partly outside the clipping -region, the set of pixels drawn is the intersection of the clipping -region and the set of pixels that would be drawn by the same operation -in the absence of a clipping region. -\end{funcdesc} - -\begin{funcdesc}{noclip}{} -Reset the clipping region to the entire window. -\end{funcdesc} - -\begin{funcdesc}{close}{} -\funcline{enddrawing}{} -Discard the drawing object. It should not be used again. -\end{funcdesc} - -\subsection{Menu Objects} - -A menu object represents a menu. -The menu is destroyed when the menu object is deleted. -The following methods are defined: - -\renewcommand{\indexsubitem}{(menu method)} - -\begin{funcdesc}{additem}{text\, shortcut} -Add a menu item with given text. -The shortcut must be a string of length 1, or omitted (to specify no -shortcut). -\end{funcdesc} - -\begin{funcdesc}{setitem}{i\, text} -Set the text of item number -\var{i}. -\end{funcdesc} - -\begin{funcdesc}{enable}{i\, flag} -Enable or disables item -\var{i}. -\end{funcdesc} - -\begin{funcdesc}{check}{i\, flag} -Set or clear the -\dfn{check mark} -for item -\var{i}. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Discard the menu object. It should not be used again. -\end{funcdesc} - -\subsection{Bitmap Objects} - -A bitmap represents a rectangular array of bits. -The top left bit has coordinate (0, 0). -A bitmap can be drawn with the \code{bitmap} method of a drawing object. -Bitmaps are currently not available on the Macintosh. - -The following methods are defined: - -\renewcommand{\indexsubitem}{(bitmap method)} - -\begin{funcdesc}{getsize}{} -Return a tuple representing the width and height of the bitmap. -(This returns the values that have been passed to the \code{newbitmap} -function.) -\end{funcdesc} - -\begin{funcdesc}{setbit}{point\, bit} -Set the value of the bit indicated by \var{point} to \var{bit}. -\end{funcdesc} - -\begin{funcdesc}{getbit}{point} -Return the value of the bit indicated by \var{point}. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Discard the bitmap object. It should not be used again. -\end{funcdesc} - -\subsection{Text-edit Objects} - -A text-edit object represents a text-edit block. -For semantics, see the STDWIN documentation for C programmers. -The following methods exist: - -\renewcommand{\indexsubitem}{(text-edit method)} - -\begin{funcdesc}{arrow}{code} -Pass an arrow event to the text-edit block. -The -\var{code} -must be one of -\code{WC_LEFT}, -\code{WC_RIGHT}, -\code{WC_UP} -or -\code{WC_DOWN} -(see module -\code{stdwinevents}). -\end{funcdesc} - -\begin{funcdesc}{draw}{rect} -Pass a draw event to the text-edit block. -The rectangle specifies the redraw area. -\end{funcdesc} - -\begin{funcdesc}{event}{type\, window\, detail} -Pass an event gotten from -\code{stdwin.getevent()} -to the text-edit block. -Return true if the event was handled. -\end{funcdesc} - -\begin{funcdesc}{getfocus}{} -Return 2 integers representing the start and end positions of the -focus, usable as slice indices on the string returned by -\code{gettext()}. -\end{funcdesc} - -\begin{funcdesc}{getfocustext}{} -Return the text in the focus. -\end{funcdesc} - -\begin{funcdesc}{getrect}{} -Return a rectangle giving the actual position of the text-edit block. -(The bottom coordinate may differ from the initial position because -the block automatically shrinks or grows to fit.) -\end{funcdesc} - -\begin{funcdesc}{gettext}{} -Return the entire text buffer. -\end{funcdesc} - -\begin{funcdesc}{move}{rect} -Specify a new position for the text-edit block in the document. -\end{funcdesc} - -\begin{funcdesc}{replace}{str} -Replace the text in the focus by the given string. -The new focus is an insert point at the end of the string. -\end{funcdesc} - -\begin{funcdesc}{setfocus}{i\, j} -Specify the new focus. -Out-of-bounds values are silently clipped. -\end{funcdesc} - -\begin{funcdesc}{settext}{str} -Replace the entire text buffer by the given string and set the focus -to \code{(0, 0)}. -\end{funcdesc} - -\begin{funcdesc}{setview}{rect} -Set the view rectangle to \var{rect}. If \var{rect} is \code{None}, -viewing mode is reset. In viewing mode, all output from the text-edit -object is clipped to the viewing rectangle. This may be useful to -implement your own scrolling text subwindow. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Discard the text-edit object. It should not be used again. -\end{funcdesc} - -\subsection{Example} -\nodename{STDWIN Example} - -Here is a minimal example of using STDWIN in Python. -It creates a window and draws the string ``Hello world'' in the top -left corner of the window. -The window will be correctly redrawn when covered and re-exposed. -The program quits when the close icon or menu item is requested. - -\bcode\begin{verbatim} -import stdwin -from stdwinevents import * - -def main(): - mywin = stdwin.open('Hello') - # - while 1: - (type, win, detail) = stdwin.getevent() - if type == WE_DRAW: - draw = win.begindrawing() - draw.text((0, 0), 'Hello, world') - del draw - elif type == WE_CLOSE: - break - -main() -\end{verbatim}\ecode - -\section{Standard Module \sectcode{stdwinevents}} -\stmodindex{stdwinevents} - -This module defines constants used by STDWIN for event types -(\code{WE_ACTIVATE} etc.), command codes (\code{WC_LEFT} etc.) -and selection types (\code{WS_PRIMARY} etc.). -Read the file for details. -Suggested usage is - -\bcode\begin{verbatim} ->>> from stdwinevents import * ->>> -\end{verbatim}\ecode - -\section{Standard Module \sectcode{rect}} -\stmodindex{rect} - -This module contains useful operations on rectangles. -A rectangle is defined as in module -\code{stdwin}: -a pair of points, where a point is a pair of integers. -For example, the rectangle - -\bcode\begin{verbatim} -(10, 20), (90, 80) -\end{verbatim}\ecode - -is a rectangle whose left, top, right and bottom edges are 10, 20, 90 -and 80, respectively. -Note that the positive vertical axis points down (as in -\code{stdwin}). - -The module defines the following objects: - -\renewcommand{\indexsubitem}{(in module rect)} -\begin{excdesc}{error} -The exception raised by functions in this module when they detect an -error. -The exception argument is a string describing the problem in more -detail. -\end{excdesc} - -\begin{datadesc}{empty} -The rectangle returned when some operations return an empty result. -This makes it possible to quickly check whether a result is empty: - -\bcode\begin{verbatim} ->>> import rect ->>> r1 = (10, 20), (90, 80) ->>> r2 = (0, 0), (10, 20) ->>> r3 = rect.intersect([r1, r2]) ->>> if r3 is rect.empty: print 'Empty intersection' -Empty intersection ->>> -\end{verbatim}\ecode -\end{datadesc} - -\begin{funcdesc}{is_empty}{r} -Returns true if the given rectangle is empty. -A rectangle -\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})} -is empty if -\iftexi -\code{\var{left} >= \var{right}} or \code{\var{top} => \var{bottom}}. -\else -$\var{left} \geq \var{right}$ or $\var{top} \geq \var{bottom}$. -%%JHXXX{\em left~$\geq$~right} or {\em top~$\leq$~bottom}. -\fi -\end{funcdesc} - -\begin{funcdesc}{intersect}{list} -Returns the intersection of all rectangles in the list argument. -It may also be called with a tuple argument. -Raises -\code{rect.error} -if the list is empty. -Returns -\code{rect.empty} -if the intersection of the rectangles is empty. -\end{funcdesc} - -\begin{funcdesc}{union}{list} -Returns the smallest rectangle that contains all non-empty rectangles in -the list argument. -It may also be called with a tuple argument or with two or more -rectangles as arguments. -Returns -\code{rect.empty} -if the list is empty or all its rectangles are empty. -\end{funcdesc} - -\begin{funcdesc}{pointinrect}{point\, rect} -Returns true if the point is inside the rectangle. -By definition, a point -\code{(\var{h}, \var{v})} -is inside a rectangle -\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})} if -\iftexi -\code{\var{left} <= \var{h} < \var{right}} and -\code{\var{top} <= \var{v} < \var{bottom}}. -\else -$\var{left} \leq \var{h} < \var{right}$ and -$\var{top} \leq \var{v} < \var{bottom}$. -\fi -\end{funcdesc} - -\begin{funcdesc}{inset}{rect\, \(dh\, dv\)} -Returns a rectangle that lies inside the -\code{rect} -argument by -\var{dh} -pixels horizontally -and -\var{dv} -pixels -vertically. -If -\var{dh} -or -\var{dv} -is negative, the result lies outside -\var{rect}. -\end{funcdesc} - -\begin{funcdesc}{rect2geom}{rect} -Converts a rectangle to geometry representation: -\code{(\var{left}, \var{top}), (\var{width}, \var{height})}. -\end{funcdesc} - -\begin{funcdesc}{geom2rect}{geom} -Converts a rectangle given in geometry representation back to the -standard rectangle representation -\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})}. -\end{funcdesc} diff --git a/Doc/libstring.tex b/Doc/libstring.tex deleted file mode 100644 index 2e79d43cb7..0000000000 --- a/Doc/libstring.tex +++ /dev/null @@ -1,197 +0,0 @@ -\section{Standard Module \sectcode{string}} - -\stmodindex{string} - -This module defines some constants useful for checking character -classes and some useful string functions. See the modules -\code{regex} and \code{regsub} for string functions based on regular -expressions. - -The constants defined in this module are are: - -\renewcommand{\indexsubitem}{(data in module string)} -\begin{datadesc}{digits} - The string \code{'0123456789'}. -\end{datadesc} - -\begin{datadesc}{hexdigits} - The string \code{'0123456789abcdefABCDEF'}. -\end{datadesc} - -\begin{datadesc}{letters} - The concatenation of the strings \code{lowercase} and - \code{uppercase} described below. -\end{datadesc} - -\begin{datadesc}{lowercase} - A string containing all the characters that are considered lowercase - letters. On most systems this is the string - \code{'abcdefghijklmnopqrstuvwxyz'}. Do not change its definition --- - the effect on the routines \code{upper} and \code{swapcase} is - undefined. -\end{datadesc} - -\begin{datadesc}{octdigits} - The string \code{'01234567'}. -\end{datadesc} - -\begin{datadesc}{uppercase} - A string containing all the characters that are considered uppercase - letters. On most systems this is the string - \code{'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}. Do not change its definition --- - the effect on the routines \code{lower} and \code{swapcase} is - undefined. -\end{datadesc} - -\begin{datadesc}{whitespace} - A string containing all characters that are considered whitespace. - On most systems this includes the characters space, tab, linefeed, - return, formfeed, and vertical tab. Do not change its definition --- - the effect on the routines \code{strip} and \code{split} is - undefined. -\end{datadesc} - -The functions defined in this module are: - -\renewcommand{\indexsubitem}{(in module string)} - -\begin{funcdesc}{atof}{s} -Convert a string to a floating point number. The string must have -the standard syntax for a floating point literal in Python, optionally -preceded by a sign (\samp{+} or \samp{-}). -\end{funcdesc} - -\begin{funcdesc}{atoi}{s\optional{\, base}} -Convert string \var{s} to an integer in the given \var{base}. The -string must consist of one or more digits, optionally preceded by a -sign (\samp{+} or \samp{-}). The \var{base} defaults to 10. If it is -0, a default base is chosen depending on the leading characters of the -string (after stripping the sign): \samp{0x} or \samp{0X} means 16, -\samp{0} means 8, anything else means 10. If \var{base} is 16, a -leading \samp{0x} or \samp{0X} is always accepted. (Note: for a more -flexible interpretation of numeric literals, use the built-in function -\code{eval()}.) -\bifuncindex{eval} -\end{funcdesc} - -\begin{funcdesc}{atol}{s\optional{\, base}} -Convert string \var{s} to a long integer in the given \var{base}. The -string must consist of one or more digits, optionally preceded by a -sign (\samp{+} or \samp{-}). The \var{base} argument has the same -meaning as for \code{atoi()}. A trailing \samp{l} or \samp{L} is not -allowed, except if the base is 0. -\end{funcdesc} - -\begin{funcdesc}{expandtabs}{s\, tabsize} -Expand tabs in a string, i.e.\ replace them by one or more spaces, -depending on the current column and the given tab size. The column -number is reset to zero after each newline occurring in the string. -This doesn't understand other non-printing characters or escape -sequences. -\end{funcdesc} - -\begin{funcdesc}{find}{s\, sub\optional{\, start}} -Return the lowest index in \var{s} not smaller than \var{start} where the -substring \var{sub} is found. Return \code{-1} when \var{sub} -does not occur as a substring of \var{s} with index at least \var{start}. -If \var{start} is omitted, it defaults to \code{0}. If \var{start} is -negative, \code{len(\var{s})} is added. -\end{funcdesc} - -\begin{funcdesc}{rfind}{s\, sub\optional{\, start}} -Like \code{find} but find the highest index. -\end{funcdesc} - -\begin{funcdesc}{index}{s\, sub\optional{\, start}} -Like \code{find} but raise \code{ValueError} when the substring is -not found. -\end{funcdesc} - -\begin{funcdesc}{rindex}{s\, sub\optional{\, start}} -Like \code{rfind} but raise \code{ValueError} when the substring is -not found. -\end{funcdesc} - -\begin{funcdesc}{count}{s\, sub\optional{\, start}} -Return the number of (non-overlapping) occurrences of substring -\var{sub} in string \var{s} with index at least \var{start}. -If \var{start} is omitted, it defaults to \code{0}. If \var{start} is -negative, \code{len(\var{s})} is added. -\end{funcdesc} - -\begin{funcdesc}{lower}{s} -Convert letters to lower case. -\end{funcdesc} - -\begin{funcdesc}{split}{s} -Return a list of the whitespace-delimited words of the string -\var{s}. -\end{funcdesc} - -\begin{funcdesc}{splitfields}{s\, sep} - Return a list containing the fields of the string \var{s}, using - the string \var{sep} as a separator. The list will have one more - items than the number of non-overlapping occurrences of the - separator in the string. Thus, \code{string.splitfields(\var{s}, ' - ')} is not the same as \code{string.split(\var{s})}, as the latter - only returns non-empty words. As a special case, - \code{splitfields(\var{s}, '')} returns \code{[\var{s}]}, for any string - \var{s}. (See also \code{regsub.split()}.) -\end{funcdesc} - -\begin{funcdesc}{join}{words} -Concatenate a list or tuple of words with intervening spaces. -\end{funcdesc} - -\begin{funcdesc}{joinfields}{words\, sep} -Concatenate a list or tuple of words with intervening separators. -It is always true that -\code{string.joinfields(string.splitfields(\var{t}, \var{sep}), \var{sep})} -equals \var{t}. -\end{funcdesc} - -\begin{funcdesc}{strip}{s} -Remove leading and trailing whitespace from the string -\var{s}. -\end{funcdesc} - -\begin{funcdesc}{swapcase}{s} -Convert lower case letters to upper case and vice versa. -\end{funcdesc} - -\begin{funcdesc}{translate}{s, table} -Translate the characters from \var{s} using \var{table}, which must be -a 256-character string giving the translation for each character -value, indexed by its ordinal. -\end{funcdesc} - -\begin{funcdesc}{upper}{s} -Convert letters to upper case. -\end{funcdesc} - -\begin{funcdesc}{ljust}{s\, width} -\funcline{rjust}{s\, width} -\funcline{center}{s\, width} -These functions respectively left-justify, right-justify and center a -string in a field of given width. -They return a string that is at least -\var{width} -characters wide, created by padding the string -\var{s} -with spaces until the given width on the right, left or both sides. -The string is never truncated. -\end{funcdesc} - -\begin{funcdesc}{zfill}{s\, width} -Pad a numeric string on the left with zero digits until the given -width is reached. Strings starting with a sign are handled correctly. -\end{funcdesc} - -This module is implemented in Python. Much of its functionality has -been reimplemented in the built-in module \code{strop}. However, you -should \emph{never} import the latter module directly. When -\code{string} discovers that \code{strop} exists, it transparently -replaces parts of itself with the implementation from \code{strop}. -After initialization, there is \emph{no} overhead in using -\code{string} instead of \code{strop}. -\bimodindex{strop} diff --git a/Doc/libstrings.tex b/Doc/libstrings.tex deleted file mode 100644 index ea9a099966..0000000000 --- a/Doc/libstrings.tex +++ /dev/null @@ -1,20 +0,0 @@ -\chapter{String Services} - -The modules described in this chapter provide a wide range of string -manipulation operations. Here's an overview: - -\begin{description} - -\item[string] ---- Common string operations. - -\item[regex] ---- Regular expression search and match operations. - -\item[regsub] ---- Substitution and splitting operations that use regular expressions. - -\item[struct] ---- Interpret strings as packed binary data. - -\end{description} diff --git a/Doc/libstruct.tex b/Doc/libstruct.tex deleted file mode 100644 index 4a08c78b87..0000000000 --- a/Doc/libstruct.tex +++ /dev/null @@ -1,78 +0,0 @@ -\section{Built-in Module \sectcode{struct}} -\bimodindex{struct} -\indexii{C}{structures} - -This module performs conversions between Python values and C -structs represented as Python strings. It uses \dfn{format strings} -(explained below) as compact descriptions of the lay-out of the C -structs and the intended conversion to/from Python values. - -See also built-in module \code{array}. -\bimodindex{array} - -The module defines the following exception and functions: - -\renewcommand{\indexsubitem}{(in module struct)} -\begin{excdesc}{error} - Exception raised on various occasions; argument is a string - describing what is wrong. -\end{excdesc} - -\begin{funcdesc}{pack}{fmt\, v1\, v2\, {\rm \ldots}} - Return a string containing the values - \code{\var{v1}, \var{v2}, {\rm \ldots}} packed according to the given - format. The arguments must match the values required by the format - exactly. -\end{funcdesc} - -\begin{funcdesc}{unpack}{fmt\, string} - Unpack the string (presumably packed by \code{pack(\var{fmt}, {\rm \ldots})}) - according to the given format. The result is a tuple even if it - contains exactly one item. The string must contain exactly the - amount of data required by the format (i.e. \code{len(\var{string})} must - equal \code{calcsize(\var{fmt})}). -\end{funcdesc} - -\begin{funcdesc}{calcsize}{fmt} - Return the size of the struct (and hence of the string) - corresponding to the given format. -\end{funcdesc} - -Format characters have the following meaning; the conversion between C -and Python values should be obvious given their types: - -\begin{tableiii}{|c|l|l|}{samp}{Format}{C}{Python} - \lineiii{x}{pad byte}{no value} - \lineiii{c}{char}{string of length 1} - \lineiii{b}{signed char}{integer} - \lineiii{h}{short}{integer} - \lineiii{i}{int}{integer} - \lineiii{l}{long}{integer} - \lineiii{f}{float}{float} - \lineiii{d}{double}{float} -\end{tableiii} - -A format character may be preceded by an integral repeat count; e.g.\ -the format string \code{'4h'} means exactly the same as \code{'hhhh'}. - -C numbers are represented in the machine's native format and byte -order, and properly aligned by skipping pad bytes if necessary -(according to the rules used by the C compiler). - -Examples (all on a big-endian machine): - -\bcode\begin{verbatim} -pack('hhl', 1, 2, 3) == '\000\001\000\002\000\000\000\003' -unpack('hhl', '\000\001\000\002\000\000\000\003') == (1, 2, 3) -calcsize('hhl') == 8 -\end{verbatim}\ecode - -Hint: to align the end of a structure to the alignment requirement of -a particular type, end the format with the code for that type with a -repeat count of zero, e.g.\ the format \code{'llh0l'} specifies two -pad bytes at the end, assuming longs are aligned on 4-byte boundaries. - -(More format characters are planned, e.g.\ \code{'s'} for character -arrays, upper case for unsigned variants, and a way to specify the -byte order, which is useful for [de]constructing network packets and -reading/writing portable binary file formats like TIFF and AIFF.) diff --git a/Doc/libsun.tex b/Doc/libsun.tex deleted file mode 100644 index 909c14dc95..0000000000 --- a/Doc/libsun.tex +++ /dev/null @@ -1,112 +0,0 @@ -\chapter{SunOS Specific Services} - -The modules described in this chapter provide interfaces to features -that are unique to the SunOS operating system (versions 4 and 5; the -latter is also known as Solaris version 2). - -\section{Built-in Module \sectcode{sunaudiodev}} -\bimodindex{sunaudiodev} - -This module allows you to access the sun audio interface. The sun -audio hardware is capable of recording and playing back audio data -in U-LAW format with a sample rate of 8K per second. A full -description can be gotten with \samp{man audio}. - -The module defines the following variables and functions: - -\renewcommand{\indexsubitem}{(in module sunaudiodev)} -\begin{excdesc}{error} -This exception is raised on all errors. The argument is a string -describing what went wrong. -\end{excdesc} - -\begin{funcdesc}{open}{mode} -This function opens the audio device and returns a sun audio device -object. This object can then be used to do I/O on. The \var{mode} parameter -is one of \code{'r'} for record-only access, \code{'w'} for play-only -access, \code{'rw'} for both and \code{'control'} for access to the -control device. Since only one process is allowed to have the recorder -or player open at the same time it is a good idea to open the device -only for the activity needed. See the audio manpage for details. -\end{funcdesc} - -\subsection{Audio Device Objects} - -The audio device objects are returned by \code{open} define the -following methods (except \code{control} objects which only provide -getinfo, setinfo and drain): - -\renewcommand{\indexsubitem}{(audio device method)} - -\begin{funcdesc}{close}{} -This method explicitly closes the device. It is useful in situations -where deleting the object does not immediately close it since there -are other references to it. A closed device should not be used again. -\end{funcdesc} - -\begin{funcdesc}{drain}{} -This method waits until all pending output is processed and then returns. -Calling this method is often not necessary: destroying the object will -automatically close the audio device and this will do an implicit drain. -\end{funcdesc} - -\begin{funcdesc}{flush}{} -This method discards all pending output. It can be used avoid the -slow response to a user's stop request (due to buffering of up to one -second of sound). -\end{funcdesc} - -\begin{funcdesc}{getinfo}{} -This method retrieves status information like input and output volume, -etc. and returns it in the form of -an audio status object. This object has no methods but it contains a -number of attributes describing the current device status. The names -and meanings of the attributes are described in -\file{/usr/include/sun/audioio.h} and in the audio man page. Member names -are slightly different from their C counterparts: a status object is -only a single structure. Members of the \code{play} substructure have -\samp{o_} prepended to their name and members of the \code{record} -structure have \samp{i_}. So, the C member \code{play.sample_rate} is -accessed as \code{o_sample_rate}, \code{record.gain} as \code{i_gain} -and \code{monitor_gain} plainly as \code{monitor_gain}. -\end{funcdesc} - -\begin{funcdesc}{ibufcount}{} -This method returns the number of samples that are buffered on the -recording side, i.e. -the program will not block on a \code{read} call of so many samples. -\end{funcdesc} - -\begin{funcdesc}{obufcount}{} -This method returns the number of samples buffered on the playback -side. Unfortunately, this number cannot be used to determine a number -of samples that can be written without blocking since the kernel -output queue length seems to be variable. -\end{funcdesc} - -\begin{funcdesc}{read}{size} -This method reads \var{size} samples from the audio input and returns -them as a python string. The function blocks until enough data is available. -\end{funcdesc} - -\begin{funcdesc}{setinfo}{status} -This method sets the audio device status parameters. The \var{status} -parameter is an device status object as returned by \code{getinfo} and -possibly modified by the program. -\end{funcdesc} - -\begin{funcdesc}{write}{samples} -Write is passed a python string containing audio samples to be played. -If there is enough buffer space free it will immediately return, -otherwise it will block. -\end{funcdesc} - -There is a companion module, \code{SUNAUDIODEV}, which defines useful -symbolic constants like \code{MIN_GAIN}, \code{MAX_GAIN}, -\code{SPEAKER}, etc. The names of -the constants are the same names as used in the C include file -\file{<sun/audioio.h>}, with the leading string \samp{AUDIO_} stripped. - -Useability of the control device is limited at the moment, since there -is no way to use the ``wait for something to happen'' feature the -device provides. diff --git a/Doc/libsys.tex b/Doc/libsys.tex deleted file mode 100644 index ff5d65e9f5..0000000000 --- a/Doc/libsys.tex +++ /dev/null @@ -1,152 +0,0 @@ -\section{Built-in Module \sectcode{sys}} - -\bimodindex{sys} -This module provides access to some variables used or maintained by the -interpreter and to functions that interact strongly with the interpreter. -It is always available. - -\renewcommand{\indexsubitem}{(in module sys)} - -\begin{datadesc}{argv} - The list of command line arguments passed to a Python script. - \code{sys.argv[0]} is the script name (it is operating system - dependent whether this is a full pathname or not). - If the command was executed using the \samp{-c} command line option - to the interpreter, \code{sys.argv[0]} is set to the string - \code{"-c"}. - If no script name was passed to the Python interpreter, - \code{sys.argv} has zero length. -\end{datadesc} - -\begin{datadesc}{builtin_module_names} - A list of strings giving the names of all modules that are compiled - into this Python interpreter. (This information is not available in - any other way --- \code{sys.modules.keys()} only lists the imported - modules.) -\end{datadesc} - -\begin{datadesc}{exc_type} -\dataline{exc_value} -\dataline{exc_traceback} - These three variables are not always defined; they are set when an - exception handler (an \code{except} clause of a \code{try} statement) is - invoked. Their meaning is: \code{exc_type} gets the exception type of - the exception being handled; \code{exc_value} gets the exception - parameter (its \dfn{associated value} or the second argument to - \code{raise}); \code{exc_traceback} gets a traceback object (see the - Reference Manual) which - encapsulates the call stack at the point where the exception - originally occurred. -\obindex{traceback} -\end{datadesc} - -\begin{funcdesc}{exit}{n} - Exit from Python with numeric exit status \var{n}. This is - implemented by raising the \code{SystemExit} exception, so cleanup - actions specified by \code{finally} clauses of \code{try} statements - are honored, and it is possible to catch the exit attempt at an outer - level. -\end{funcdesc} - -\begin{datadesc}{exitfunc} - This value is not actually defined by the module, but can be set by - the user (or by a program) to specify a clean-up action at program - exit. When set, it should be a parameterless function. This function - will be called when the interpreter exits in any way (except when a - fatal error occurs: in that case the interpreter's internal state - cannot be trusted). -\end{datadesc} - -\begin{datadesc}{last_type} -\dataline{last_value} -\dataline{last_traceback} - These three variables are not always defined; they are set when an - exception is not handled and the interpreter prints an error message - and a stack traceback. Their intended use is to allow an interactive - user to import a debugger module and engage in post-mortem debugging - without having to re-execute the command that caused the error (which - may be hard to reproduce). The meaning of the variables is the same - as that of \code{exc_type}, \code{exc_value} and \code{exc_tracaback}, - respectively. -\end{datadesc} - -\begin{datadesc}{modules} - Gives the list of modules that have already been loaded. - This can be manipulated to force reloading of modules and other tricks. -\end{datadesc} - -\begin{datadesc}{path} - A list of strings that specifies the search path for modules. - Initialized from the environment variable \code{PYTHONPATH}, or an - installation-dependent default. -\end{datadesc} - -\begin{datadesc}{platform} -This string contains a platform identifier. This can be used to -append platform-specific components to \code{sys.path}, for instance. -\end{datadesc} - -\begin{datadesc}{ps1} -\dataline{ps2} - Strings specifying the primary and secondary prompt of the - interpreter. These are only defined if the interpreter is in - interactive mode. Their initial values in this case are - \code{'>>> '} and \code{'... '}. -\end{datadesc} - -\begin{funcdesc}{setcheckinterval}{interval} -Set the interpreter's ``check interval''. This integer value -determines how often the interpreter checks for periodic things such -as thread switches and signal handlers. The default is 10, meaning -the check is performed every 10 Python virtual instructions. Setting -it to a larger value may increase performance for programs using -threads. Setting it to a value $\leq 0$ checks every virtual instruction, -maximizing responsiveness as well as overhead. -\end{funcdesc} - -\begin{funcdesc}{settrace}{tracefunc} - Set the system's trace function, which allows you to implement a - Python source code debugger in Python. See section ``How It Works'' - in the chapter on the Python Debugger. -\end{funcdesc} -\index{trace function} -\index{debugger} - -\begin{funcdesc}{setprofile}{profilefunc} - Set the system's profile function, which allows you to implement a - Python source code profiler in Python. See the chapter on the - Python Profiler. The system's profile function - is called similarly to the system's trace function (see - \code{sys.settrace}), but it isn't called for each executed line of - code (only on call and return and when an exception occurs). Also, - its return value is not used, so it can just return \code{None}. -\end{funcdesc} -\index{profile function} -\index{profiler} - -\begin{datadesc}{stdin} -\dataline{stdout} -\dataline{stderr} - File objects corresponding to the interpreter's standard input, - output and error streams. \code{sys.stdin} is used for all - interpreter input except for scripts but including calls to - \code{input()} and \code{raw_input()}. \code{sys.stdout} is used - for the output of \code{print} and expression statements and for the - prompts of \code{input()} and \code{raw_input()}. The interpreter's - own prompts and (almost all of) its error messages go to - \code{sys.stderr}. \code{sys.stdout} and \code{sys.stderr} needn't - be built-in file objects: any object is acceptable as long as it has - a \code{write} method that takes a string argument. (Changing these - objects doesn't affect the standard I/O streams of processes - executed by \code{popen()}, \code{system()} or the \code{exec*()} - family of functions in the \code{os} module.) -\stmodindex{os} -\end{datadesc} - -\begin{datadesc}{tracebacklimit} -When this variable is set to an integer value, it determines the -maximum number of levels of traceback information printed when an -unhandled exception occurs. The default is 1000. When set to 0 or -less, all traceback information is suppressed and only the exception -type and value are printed. -\end{datadesc} diff --git a/Doc/libsyslog.tex b/Doc/libsyslog.tex deleted file mode 100644 index 5b4fdded4b..0000000000 --- a/Doc/libsyslog.tex +++ /dev/null @@ -1,67 +0,0 @@ -\section{Built-in Module \sectcode{syslog}} -\bimodindex{syslog} - -This module provides an interface to the Unix \code{syslog} library -routines. Refer to the \UNIX{} manual pages for a detailed description -of the \code{syslog} facility. - -The module defines the following functions: - -\begin{funcdesc}{syslog}{\optional{priority\,} message} -Send the string \var{message} to the system logger. -A trailing newline is added if necessary. -Each message is tagged with a priority composed of a \var{facility} and -a \var{level}. -The optional \var{priority} argument, which defaults to -\code{(LOG_USER | LOG_INFO)}, determines the message priority. -\end{funcdesc} - -\begin{funcdesc}{openlog}{ident\, \optional{logopt\, \optional{facility}}} -Logging options other than the defaults can be set by explicitly opening -the log file with \code{openlog()} prior to calling \code{syslog()}. -The defaults are (usually) \var{ident} = \samp{syslog}, \var{logopt} = 0, -\var{facility} = \code{LOG_USER}. -The \var{ident} argument is a string which is prepended to every message. -The optional \var{logopt} argument is a bit field - see below for possible -values to combine. -The optional \var{facility} argument sets the default facility for messages -which do not have a facility explicitly encoded. -\end{funcdesc} - -\begin{funcdesc}{closelog}{} -Close the log file. -\end{funcdesc} - -\begin{funcdesc}{setlogmask}{maskpri} -This function set the priority mask to \var{maskpri} and returns the -previous mask value. -Calls to \code{syslog} with a priority level not set in \var{maskpri} -are ignored. -The default is to log all priorities. -The function \code{LOG_MASK(\var{pri})} calculates the mask for the -individual priority \var{pri}. -The function \code{LOG_UPTO(\var{pri})} calculates the mask for all priorities -up to and including \var{pri}. -\end{funcdesc} - -The module defines the following constants: - -\begin{description} - -\item[Priority levels (high to low):] - -\code{LOG_EMERG}, \code{LOG_ALERT}, \code{LOG_CRIT}, \code{LOG_ERR}, -\code{LOG_WARNING}, \code{LOG_NOTICE}, \code{LOG_INFO}, \code{LOG_DEBUG}. - -\item[Facilities:] - -\code{LOG_KERN}, \code{LOG_USER}, \code{LOG_MAIL}, \code{LOG_DAEMON}, -\code{LOG_AUTH}, \code{LOG_LPR}, \code{LOG_NEWS}, \code{LOG_UUCP}, -\code{LOG_CRON} and \code{LOG_LOCAL0} to \code{LOG_LOCAL7}. - -\item[Log options:] - -\code{LOG_PID}, \code{LOG_CONS}, \code{LOG_NDELAY}, \code{LOG_NOWAIT} -and \code{LOG_PERROR} if defined in \file{syslog.h}. - -\end{description} diff --git a/Doc/libtempfile.tex b/Doc/libtempfile.tex deleted file mode 100644 index 0a582e12dc..0000000000 --- a/Doc/libtempfile.tex +++ /dev/null @@ -1,50 +0,0 @@ -\section{Standard Module \sectcode{tempfile}} -\stmodindex{tempfile} -\indexii{temporary}{file name} -\indexii{temporary}{file} - -\renewcommand{\indexsubitem}{(in module tempfile)} - -This module generates temporary file names. It is not \UNIX{} specific, -but it may require some help on non-\UNIX{} systems. - -Note: the modules does not create temporary files, nor does it -automatically remove them when the current process exits or dies. - -The module defines a single user-callable function: - -\begin{funcdesc}{mktemp}{} -Return a unique temporary filename. This is an absolute pathname of a -file that does not exist at the time the call is made. No two calls -will return the same filename. -\end{funcdesc} - -The module uses two global variables that tell it how to construct a -temporary name. The caller may assign values to them; by default they -are initialized at the first call to \code{mktemp()}. - -\begin{datadesc}{tempdir} -When set to a value other than \code{None}, this variable defines the -directory in which filenames returned by \code{mktemp()} reside. The -default is taken from the environment variable \code{TMPDIR}; if this -is not set, either \code{/usr/tmp} is used (on \UNIX{}), or the current -working directory (all other systems). No check is made to see -whether its value is valid. -\end{datadesc} -\ttindex{TMPDIR} - -\begin{datadesc}{template} -When set to a value other than \code{None}, this variable defines the -prefix of the final component of the filenames returned by -\code{mktemp()}. A string of decimal digits is added to generate -unique filenames. The default is either ``\code{@\var{pid}.}'' where -\var{pid} is the current process ID (on \UNIX{}), or ``\code{tmp}'' (all -other systems). -\end{datadesc} - -Warning: if a \UNIX{} process uses \code{mktemp()}, then calls -\code{fork()} and both parent and child continue to use -\code{mktemp()}, the processes will generate conflicting temporary -names. To resolve this, the child process should assign \code{None} -to \code{template}, to force recomputing the default on the next call -to \code{mktemp()}. diff --git a/Doc/libtemplate.tex b/Doc/libtemplate.tex deleted file mode 100644 index 4afb56b251..0000000000 --- a/Doc/libtemplate.tex +++ /dev/null @@ -1,122 +0,0 @@ -% Template for a library manual section. -% PLEASE REMOVE THE COMMENTS AFTER USING THE TEMPLATE - - -% ==== 1. ==== -% Choose one of the following section headers and index entries; -% \section{} generates the section header, -% \bimodindex{} or \stmodundex{} generates an index entry for this module - -\section{Built-in Module \sectcode{spam}} % If implemented in C -\bimodindex{spam} - -\section{Standard module \sectcode{spam}} % If implemented in Python -\stmodindex{spam} - - -% ==== 2. ==== -% Give a short overview of what the module does. -% If it is platform specific, mention this. -% Mention other important restrictions or general operating principles. -% For example: - -The \code{spam} module defines operations for handling cans of Spam. -It knows the four generally available Spam varieties and understands -both can sizes. - -Because spamification requires UNIX process management, the module is -only available on genuine UNIX systems. - - -% ==== 3. ==== -% List the public functions defined by the module. Begin with a -% standard phrase. You may also list the exceptions and other data -% items defined in the module, insofar as they are important for the -% user. - -The \code{spam} module defines the following functions: - -% ---- 3.1. ---- -% Redefine the ``indexsubitem'' macro to point to this module -% (alternatively, you can put this at the top of the file): - -\renewcommand{\indexsubitem}{(in module spam)} - -% ---- 3.2. ---- -% For each function, use a ``funcdesc'' block. This has exactly two -% parameters (each parameters is contained in a set of curly braces): -% the first parameter is the function name (this automatically -% generates an index entry); the second parameter is the function's -% argument list. If there are no arguments, use an empty pair of -% curly braces. If there is more than one argument, separate the -% arguments with backslash-comma. Optional parts of the parameter -% list are contained in \optional{...} (this generates a set of square -% brackets around its parameter). Arguments are automatically set in -% italics in the parameter list. Each argument should be mentioned at -% least once in the description; each usage (even inside \code{...}) -% should be enclosed in \var{...}. - -\begin{funcdesc}{open}{filename\optional{\, mode\, buffersize}} -Open the file \var{filename} as a can of Spam. The optional -\var{mode} and \var{buffersize} arguments specify the read-write mode -(\code{'r'} (default) or \code{'w'}) and the buffer size (default: -system dependent). -\end{funcdesc} - -% ---- 3.3. ---- -% Data items are described using a ``datadesc'' block. This has only -% one parameter: the item's name. - -\begin{datadesc}{cansize} -The default can size, in ounces. Legal values are 7 and 12. The -default varies per supermarket. This variable should not be changed -once the \code{open()} function has been called. -\end{datadesc} - -% --- 3.4. --- -% Exceptions are described using a ``excdesc'' block. This has only -% one parameter: the exception name. - -\begin{excdesc}{error} -Exception raised when an operation fails for a Spam specific reason. -The exception argument is a string describing the reason of the -failure. -\end{excdesc} - -% ---- 3.5. ---- -% There is no standard block type for classes. I generally use -% ``funcdesc'' blocks, since class instantiation looks very much like -% a function call. - - -% ==== 4. ==== -% Now is probably a good time for a complete example. (Alternatively, -% an example giving the flavor of the module may be given before the -% detailed list of functions.) - -Example: - -\begin{verbatim} ->>> import spam ->>> can = spam.open('/etc/passwd') ->>> can.empty() ->>> can.close() -\end{verbatim} - -% ==== 5. ==== -% If your module defines new object types (for a built-in module) or -% classes (for a module written in Python), you should list the -% methods and instance variables (if any) of each type or class in a -% separate subsection. It is important to redefine ``indexsubitem'' -% for each subsection. - -\subsection{Spam Objects} - -Spam objects (returned by \code{open()} above) have the following -methods. - -\renewcommand{\indexsubitem}{(spam method)} - -\begin{funcdesc}{empty}{} -Empty the can into the trash. -\end{funcdesc} diff --git a/Doc/libtermios.tex b/Doc/libtermios.tex deleted file mode 100644 index e55aab4119..0000000000 --- a/Doc/libtermios.tex +++ /dev/null @@ -1,108 +0,0 @@ -\section{Built-in Module \sectcode{termios}} -\bimodindex{termios} -\indexii{Posix}{I/O control} -\indexii{tty}{I/O control} - -\renewcommand{\indexsubitem}{(in module termios)} - -This module provides an interface to the Posix calls for tty I/O -control. For a complete description of these calls, see the Posix or -\UNIX{} manual pages. It is only available for those \UNIX{} versions -that support Posix \code{termios} style tty I/O control (and then -only if configured at installation time). - -All functions in this module take a file descriptor \var{fd} as their -first argument. This must be an integer file descriptor, such as -returned by \code{sys.stdin.fileno()}. - -This module should be used in conjunction with the \code{TERMIOS} -module, which defines the relevant symbolic constants (see the next -section). - -The module defines the following functions: - -\begin{funcdesc}{tcgetattr}{fd} -Return a list containing the tty attributes for file descriptor -\var{fd}, as follows: \code{[\var{iflag}, \var{oflag}, \var{cflag}, -\var{lflag}, \var{ispeed}, \var{ospeed}, \var{cc}]} where \var{cc} is -a list of the tty special characters (each a string of length 1, -except the items with indices \code{VMIN} and \code{VTIME}, which are -integers when these fields are defined). The interpretation of the -flags and the speeds as well as the indexing in the \var{cc} array -must be done using the symbolic constants defined in the -\code{TERMIOS} module. -\end{funcdesc} - -\begin{funcdesc}{tcsetattr}{fd\, when\, attributes} -Set the tty attributes for file descriptor \var{fd} from the -\var{attributes}, which is a list like the one returned by -\code{tcgetattr()}. The \var{when} argument determines when the -attributes are changed: \code{TERMIOS.TCSANOW} to change immediately, -\code{TERMIOS.TCSADRAIN} to change after transmitting all queued -output, or \code{TERMIOS.TCSAFLUSH} to change after transmitting all -queued output and discarding all queued input. -\end{funcdesc} - -\begin{funcdesc}{tcsendbreak}{fd\, duration} -Send a break on file descriptor \var{fd}. A zero \var{duration} sends -a break for 0.25--0.5 seconds; a nonzero \var{duration} has a system -dependent meaning. -\end{funcdesc} - -\begin{funcdesc}{tcdrain}{fd} -Wait until all output written to file descriptor \var{fd} has been -transmitted. -\end{funcdesc} - -\begin{funcdesc}{tcflush}{fd\, queue} -Discard queued data on file descriptor \var{fd}. The \var{queue} -selector specifies which queue: \code{TERMIOS.TCIFLUSH} for the input -queue, \code{TERMIOS.TCOFLUSH} for the output queue, or -\code{TERMIOS.TCIOFLUSH} for both queues. -\end{funcdesc} - -\begin{funcdesc}{tcflow}{fd\, action} -Suspend or resume input or output on file descriptor \var{fd}. The -\var{action} argument can be \code{TERMIOS.TCOOFF} to suspend output, -\code{TERMIOS.TCOON} to restart output, \code{TERMIOS.TCIOFF} to -suspend input, or \code{TERMIOS.TCION} to restart input. -\end{funcdesc} - -\subsection{Example} -\nodename{termios Example} - -Here's a function that prompts for a password with echoing turned off. -Note the technique using a separate \code{termios.tcgetattr()} call -and a \code{try {\ldots} finally} statement to ensure that the old tty -attributes are restored exactly no matter what happens: - -\begin{verbatim} -def getpass(prompt = "Password: "): - import termios, TERMIOS, sys - fd = sys.stdin.fileno() - old = termios.tcgetattr(fd) - new = termios.tcgetattr(fd) - new[3] = new[3] & ~TERMIOS.ECHO # lflags - try: - termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new) - passwd = raw_input(prompt) - finally: - termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old) - return passwd -\end{verbatim} - - -\section{Standard Module \sectcode{TERMIOS}} -\stmodindex{TERMIOS} -\indexii{Posix}{I/O control} -\indexii{tty}{I/O control} - -\renewcommand{\indexsubitem}{(in module TERMIOS)} - -This module defines the symbolic constants required to use the -\code{termios} module (see the previous section). See the Posix or -\UNIX{} manual pages (or the source) for a list of those constants. - -Note: this module resides in a system-dependent subdirectory of the -Python library directory. You may have to generate it for your -particular system using the script \file{Tools/scripts/h2py.py}. diff --git a/Doc/libthread.tex b/Doc/libthread.tex deleted file mode 100644 index f7453844db..0000000000 --- a/Doc/libthread.tex +++ /dev/null @@ -1,101 +0,0 @@ -\section{Built-in Module \sectcode{thread}} -\bimodindex{thread} - -This module provides low-level primitives for working with multiple -threads (a.k.a.\ \dfn{light-weight processes} or \dfn{tasks}) --- multiple -threads of control sharing their global data space. For -synchronization, simple locks (a.k.a.\ \dfn{mutexes} or \dfn{binary -semaphores}) are provided. - -The module is optional and supported on SGI IRIX 4.x and 5.x and Sun -Solaris 2.x systems, as well as on systems that have a PTHREAD -implementation (e.g.\ KSR). - -It defines the following constant and functions: - -\renewcommand{\indexsubitem}{(in module thread)} -\begin{excdesc}{error} -Raised on thread-specific errors. -\end{excdesc} - -\begin{funcdesc}{start_new_thread}{func\, arg} -Start a new thread. The thread executes the function \var{func} -with the argument list \var{arg} (which must be a tuple). When the -function returns, the thread silently exits. When the function -terminates with an unhandled exception, a stack trace is printed and -then the thread exits (but other threads continue to run). -\end{funcdesc} - -\begin{funcdesc}{exit}{} -This is a shorthand for \code{thread.exit_thread()}. -\end{funcdesc} - -\begin{funcdesc}{exit_thread}{} -Raise the \code{SystemExit} exception. When not caught, this will -cause the thread to exit silently. -\end{funcdesc} - -%\begin{funcdesc}{exit_prog}{status} -%Exit all threads and report the value of the integer argument -%\var{status} as the exit status of the entire program. -%\strong{Caveat:} code in pending \code{finally} clauses, in this thread -%or in other threads, is not executed. -%\end{funcdesc} - -\begin{funcdesc}{allocate_lock}{} -Return a new lock object. Methods of locks are described below. The -lock is initially unlocked. -\end{funcdesc} - -\begin{funcdesc}{get_ident}{} -Return the `thread identifier' of the current thread. This is a -nonzero integer. Its value has no direct meaning; it is intended as a -magic cookie to be used e.g. to index a dictionary of thread-specific -data. Thread identifiers may be recycled when a thread exits and -another thread is created. -\end{funcdesc} - -Lock objects have the following methods: - -\renewcommand{\indexsubitem}{(lock method)} -\begin{funcdesc}{acquire}{\optional{waitflag}} -Without the optional argument, this method acquires the lock -unconditionally, if necessary waiting until it is released by another -thread (only one thread at a time can acquire a lock --- that's their -reason for existence), and returns \code{None}. If the integer -\var{waitflag} argument is present, the action depends on its value:\ -if it is zero, the lock is only acquired if it can be acquired -immediately without waiting, while if it is nonzero, the lock is -acquired unconditionally as before. If an argument is present, the -return value is 1 if the lock is acquired successfully, 0 if not. -\end{funcdesc} - -\begin{funcdesc}{release}{} -Releases the lock. The lock must have been acquired earlier, but not -necessarily by the same thread. -\end{funcdesc} - -\begin{funcdesc}{locked}{} -Return the status of the lock:\ 1 if it has been acquired by some -thread, 0 if not. -\end{funcdesc} - -{\bf Caveats:} - -\begin{itemize} -\item -Threads interact strangely with interrupts: the -\code{KeyboardInterrupt} exception will be received by an arbitrary -thread. (When the \code{signal} module is available, interrupts -always go to the main thread.) - -\item -Calling \code{sys.exit()} or raising the \code{SystemExit} is -equivalent to calling \code{thread.exit_thread()}. - -\item -Not all built-in functions that may block waiting for I/O allow other -threads to run. (The most popular ones (\code{sleep}, \code{read}, -\code{select}) work as expected.) - -\end{itemize} diff --git a/Doc/libtime.tex b/Doc/libtime.tex deleted file mode 100644 index f91a492a8a..0000000000 --- a/Doc/libtime.tex +++ /dev/null @@ -1,122 +0,0 @@ -\section{Built-in Module \sectcode{time}} - -\bimodindex{time} -This module provides various time-related functions. -It is always available. - -An explanation of some terminology and conventions is in order. - -\begin{itemize} - -\item -The ``epoch'' is the point where the time starts. On January 1st of that -year, at 0 hours, the ``time since the epoch'' is zero. For UNIX, the -epoch is 1970. To find out what the epoch is, look at \code{gmtime(0)}. - -\item -UTC is Coordinated Universal Time (formerly known as Greenwich Mean -Time). The acronym UTC is not a mistake but a compromise between -English and French. - -\item -DST is Daylight Saving Time, an adjustment of the timezone by -(usually) one hour during part of the year. DST rules are magic -(determined by local law) and can change from year to year. The C -library has a table containing the local rules (often it is read from -a system file for flexibility) and is the only source of True Wisdom -in this respect. - -\item -The precision of the various real-time functions may be less than -suggested by the units in which their value or argument is expressed. -E.g.\ on most UNIX systems, the clock ``ticks'' only 50 or 100 times a -second, and on the Mac, times are only accurate to whole seconds. - -\end{itemize} - -The module defines the following functions and data items: - -\renewcommand{\indexsubitem}{(in module time)} - -\begin{datadesc}{altzone} -The offset of the local DST timezone, in seconds west of the 0th -meridian, if one is defined. Negative if the local DST timezone is -east of the 0th meridian (as in Western Europe, including the UK). -Only use this if \code{daylight} is nonzero. -\end{datadesc} - - -\begin{funcdesc}{asctime}{tuple} -Convert a tuple representing a time as returned by \code{gmtime()} or -\code{localtime()} to a 24-character string of the following form: -\code{'Sun Jun 20 23:21:05 1993'}. Note: unlike the C function of -the same name, there is no trailing newline. -\end{funcdesc} - - -\begin{funcdesc}{clock}{} -Return the current CPU time as a floating point number expressed in -seconds. The precision, and in fact the very definiton of the meaning -of ``CPU time'', depends on that of the C function of the same name. -\end{funcdesc} - - -\begin{funcdesc}{ctime}{secs} -Convert a time expressed in seconds since the epoch to a string -representing local time. \code{ctime(t)} is equivalent to -\code{asctime(localtime(t))}. -\end{funcdesc} - -\begin{datadesc}{daylight} -Nonzero if a DST timezone is defined. -\end{datadesc} - -\begin{funcdesc}{gmtime}{secs} -Convert a time expressed in seconds since the epoch to a tuple of 9 -integers, in UTC: year (e.g.\ 1993), month (1--12), day (1--31), hour -(0--23), minute (0--59), second (0--59), weekday (0--6, monday is 0), -Julian day (1--366), dst flag (always zero). Fractions of a second are -ignored. Note subtle differences with the C function of this name. -\end{funcdesc} - -\begin{funcdesc}{localtime}{secs} -Like \code{gmtime} but converts to local time. The dst flag is set -to 1 when DST applies to the given time. -\end{funcdesc} - -\begin{funcdesc}{mktime}{tuple} -This is the inverse function of \code{localtime}. Its argument is the -full 9-tuple (since the dst flag is needed). It returns an integer. If the -input value can't be represented as a non-negative integer, OverflowError is raised. -\end{funcdesc} - -\begin{funcdesc}{sleep}{secs} -Suspend execution for the given number of seconds. The argument may -be a floating point number to indicate a more precise sleep time. -\end{funcdesc} - -\begin{funcdesc}{strftime}{format, tuple} -Convert a tuple representing a time as returned by \code{gmtime()} or -\code{localtime()} to a string as specified by the format argument. -See the \code{strftime(3)} man page for details of the syntax of -format strings. -\end{funcdesc} - -\begin{funcdesc}{time}{} -Return the time as a floating point number expressed in seconds since -the epoch, in UTC. Note that even though the time is always returned -as a floating point number, not all systems provide time with a better -precision than 1 second. -\end{funcdesc} - -\begin{datadesc}{timezone} -The offset of the local (non-DST) timezone, in seconds west of the 0th -meridian (i.e. negative in most of Western Europe, positive in the US, -zero in the UK). -\end{datadesc} - -\begin{datadesc}{tzname} -A tuple of two strings: the first is the name of the local non-DST -timezone, the second is the name of the local DST timezone. If no DST -timezone is defined, the second string should not be used. -\end{datadesc} diff --git a/Doc/libtraceback.tex b/Doc/libtraceback.tex deleted file mode 100644 index ca9c374859..0000000000 --- a/Doc/libtraceback.tex +++ /dev/null @@ -1,54 +0,0 @@ -\section{Standard Module \sectcode{traceback}} -\stmodindex{traceback} - -\renewcommand{\indexsubitem}{(in module traceback)} - -This module provides a standard interface to format and print stack -traces of Python programs. It exactly mimics the behavior of the -Python interpreter when it prints a stack trace. This is useful when -you want to print stack traces under program control, e.g. in a -``wrapper'' around the interpreter. - -The module uses traceback objects --- this is the object type -that is stored in the variables \code{sys.exc_traceback} and -\code{sys.last_traceback}. - -The module defines the following functions: - -\begin{funcdesc}{print_tb}{traceback\optional{\, limit}} -Print up to \var{limit} stack trace entries from \var{traceback}. If -\var{limit} is omitted or \code{None}, all entries are printed. -\end{funcdesc} - -\begin{funcdesc}{extract_tb}{traceback\optional{\, limit}} -Return a list of up to \var{limit} ``pre-processed'' stack trace -entries extracted from \var{traceback}. It is useful for alternate -formatting of stack traces. If \var{limit} is omitted or \code{None}, -all entries are extracted. A ``pre-processed'' stack trace entry is a -quadruple (\var{filename}, \var{line number}, \var{function name}, -\var{line text}) representing the information that is usually printed -for a stack trace. The \var{line text} is a string with leading and -trailing whitespace stripped; if the source is not available it is -\code{None}. -\end{funcdesc} - -\begin{funcdesc}{print_exception}{type\, value\, traceback\optional{\, limit}} -Print exception information and up to \var{limit} stack trace entries -from \var{traceback}. This differs from \code{print_tb} in the -following ways: (1) if \var{traceback} is not \code{None}, it prints a -header ``\code{Traceback (innermost last):}''; (2) it prints the -exception \var{type} and \var{value} after the stack trace; (3) if -\var{type} is \code{SyntaxError} and \var{value} has the appropriate -format, it prints the line where the syntax error occurred with a -caret indication the approximate position of the error. -\end{funcdesc} - -\begin{funcdesc}{print_exc}{\optional{limit}} -This is a shorthand for \code{print_exception(sys.exc_type,} -\code{sys.exc_value,} \code{sys.exc_traceback,} \code{limit)}. -\end{funcdesc} - -\begin{funcdesc}{print_last}{\optional{limit}} -This is a shorthand for \code{print_exception(sys.last_type,} -\code{sys.last_value,} \code{sys.last_traceback,} \code{limit)}. -\end{funcdesc} diff --git a/Doc/libtypes.tex b/Doc/libtypes.tex deleted file mode 100644 index 052bc9fe56..0000000000 --- a/Doc/libtypes.tex +++ /dev/null @@ -1,761 +0,0 @@ -\section{Built-in Types} - -The following sections describe the standard types that are built into -the interpreter. These are the numeric types, sequence types, and -several others, including types themselves. There is no explicit -Boolean type; use integers instead. -\indexii{built-in}{types} -\indexii{Boolean}{type} - -Some operations are supported by several object types; in particular, -all objects can be compared, tested for truth value, and converted to -a string (with the \code{`{\rm \ldots}`} notation). The latter conversion is -implicitly used when an object is written by the \code{print} statement. -\stindex{print} - -\subsection{Truth Value Testing} - -Any object can be tested for truth value, for use in an \code{if} or -\code{while} condition or as operand of the Boolean operations below. -The following values are considered false: -\stindex{if} -\stindex{while} -\indexii{truth}{value} -\indexii{Boolean}{operations} -\index{false} - -\begin{itemize} -\renewcommand{\indexsubitem}{(Built-in object)} - -\item \code{None} - \ttindex{None} - -\item zero of any numeric type, e.g., \code{0}, \code{0L}, \code{0.0}. - -\item any empty sequence, e.g., \code{''}, \code{()}, \code{[]}. - -\item any empty mapping, e.g., \code{\{\}}. - -\item instances of user-defined classes, if the class defines a - \code{__nonzero__()} or \code{__len__()} method, when that - method returns zero. - -\end{itemize} - -All other values are considered true --- so objects of many types are -always true. -\index{true} - -Operations and built-in functions that have a Boolean result always -return \code{0} for false and \code{1} for true, unless otherwise -stated. (Important exception: the Boolean operations \samp{or} and -\samp{and} always return one of their operands.) - -\subsection{Boolean Operations} - -These are the Boolean operations, ordered by ascending priority: -\indexii{Boolean}{operations} - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes} - \lineiii{\var{x} or \var{y}}{if \var{x} is false, then \var{y}, else \var{x}}{(1)} - \hline - \lineiii{\var{x} and \var{y}}{if \var{x} is false, then \var{x}, else \var{y}}{(1)} - \hline - \lineiii{not \var{x}}{if \var{x} is false, then \code{1}, else \code{0}}{(2)} -\end{tableiii} -\opindex{and} -\opindex{or} -\opindex{not} - -\noindent -Notes: - -\begin{description} - -\item[(1)] -These only evaluate their second argument if needed for their outcome. - -\item[(2)] -\samp{not} has a lower priority than non-Boolean operators, so e.g. -\code{not a == b} is interpreted as \code{not(a == b)}, and -\code{a == not b} is a syntax error. - -\end{description} - -\subsection{Comparisons} - -Comparison operations are supported by all objects. They all have the -same priority (which is higher than that of the Boolean operations). -Comparisons can be chained arbitrarily, e.g. \code{x < y <= z} is -equivalent to \code{x < y and y <= z}, except that \code{y} is -evaluated only once (but in both cases \code{z} is not evaluated at -all when \code{x < y} is found to be false). -\indexii{chaining}{comparisons} - -This table summarizes the comparison operations: - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Meaning}{Notes} - \lineiii{<}{strictly less than}{} - \lineiii{<=}{less than or equal}{} - \lineiii{>}{strictly greater than}{} - \lineiii{>=}{greater than or equal}{} - \lineiii{==}{equal}{} - \lineiii{<>}{not equal}{(1)} - \lineiii{!=}{not equal}{(1)} - \lineiii{is}{object identity}{} - \lineiii{is not}{negated object identity}{} -\end{tableiii} -\indexii{operator}{comparison} -\opindex{==} % XXX *All* others have funny characters < ! > -\opindex{is} -\opindex{is not} - -\noindent -Notes: - -\begin{description} - -\item[(1)] -\code{<>} and \code{!=} are alternate spellings for the same operator. -(I couldn't choose between \ABC{} and \C{}! :-) -\indexii{\ABC{}}{language} -\indexii{\C{}}{language} - -\end{description} - -Objects of different types, except different numeric types, never -compare equal; such objects are ordered consistently but arbitrarily -(so that sorting a heterogeneous array yields a consistent result). -Furthermore, some types (e.g., windows) support only a degenerate -notion of comparison where any two objects of that type are unequal. -Again, such objects are ordered arbitrarily but consistently. -\indexii{types}{numeric} -\indexii{objects}{comparing} - -(Implementation note: objects of different types except numbers are -ordered by their type names; objects of the same types that don't -support proper comparison are ordered by their address.) - -Two more operations with the same syntactic priority, \code{in} and -\code{not in}, are supported only by sequence types (below). -\opindex{in} -\opindex{not in} - -\subsection{Numeric Types} - -There are three numeric types: \dfn{plain integers}, \dfn{long integers}, and -\dfn{floating point numbers}. Plain integers (also just called \dfn{integers}) -are implemented using \code{long} in \C{}, which gives them at least 32 -bits of precision. Long integers have unlimited precision. Floating -point numbers are implemented using \code{double} in \C{}. All bets on -their precision are off unless you happen to know the machine you are -working with. -\indexii{numeric}{types} -\indexii{integer}{types} -\indexii{integer}{type} -\indexiii{long}{integer}{type} -\indexii{floating point}{type} -\indexii{\C{}}{language} - -Numbers are created by numeric literals or as the result of built-in -functions and operators. Unadorned integer literals (including hex -and octal numbers) yield plain integers. Integer literals with an \samp{L} -or \samp{l} suffix yield long integers -(\samp{L} is preferred because \code{1l} looks too much like eleven!). -Numeric literals containing a decimal point or an exponent sign yield -floating point numbers. -\indexii{numeric}{literals} -\indexii{integer}{literals} -\indexiii{long}{integer}{literals} -\indexii{floating point}{literals} -\indexii{hexadecimal}{literals} -\indexii{octal}{literals} - -Python fully supports mixed arithmetic: when a binary arithmetic -operator has operands of different numeric types, the operand with the -``smaller'' type is converted to that of the other, where plain -integer is smaller than long integer is smaller than floating point. -Comparisons between numbers of mixed type use the same rule.% -\footnote{As a consequence, the list \code{[1, 2]} is considered equal - to \code{[1.0, 2.0]}, and similar for tuples.} -The functions \code{int()}, \code{long()} and \code{float()} can be used -to coerce numbers to a specific type. -\index{arithmetic} -\bifuncindex{int} -\bifuncindex{long} -\bifuncindex{float} - -All numeric types support the following operations, sorted by -ascending priority (operations in the same box have the same -priority; all numeric operations have a higher priority than -comparison operations): - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes} - \lineiii{\var{x} + \var{y}}{sum of \var{x} and \var{y}}{} - \lineiii{\var{x} - \var{y}}{difference of \var{x} and \var{y}}{} - \hline - \lineiii{\var{x} * \var{y}}{product of \var{x} and \var{y}}{} - \lineiii{\var{x} / \var{y}}{quotient of \var{x} and \var{y}}{(1)} - \lineiii{\var{x} \%{} \var{y}}{remainder of \code{\var{x} / \var{y}}}{} - \hline - \lineiii{-\var{x}}{\var{x} negated}{} - \lineiii{+\var{x}}{\var{x} unchanged}{} - \hline - \lineiii{abs(\var{x})}{absolute value of \var{x}}{} - \lineiii{int(\var{x})}{\var{x} converted to integer}{(2)} - \lineiii{long(\var{x})}{\var{x} converted to long integer}{(2)} - \lineiii{float(\var{x})}{\var{x} converted to floating point}{} - \lineiii{divmod(\var{x}, \var{y})}{the pair \code{(\var{x} / \var{y}, \var{x} \%{} \var{y})}}{(3)} - \lineiii{pow(\var{x}, \var{y})}{\var{x} to the power \var{y}}{} -\end{tableiii} -\indexiii{operations on}{numeric}{types} - -\noindent -Notes: -\begin{description} - -\item[(1)] -For (plain or long) integer division, the result is an integer. -The result is always rounded towards minus infinity: 1/2 is 0, -(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. -\indexii{integer}{division} -\indexiii{long}{integer}{division} - -\item[(2)] -Conversion from floating point to (long or plain) integer may round or -truncate as in \C{}; see functions \code{floor()} and \code{ceil()} in -module \code{math} for well-defined conversions. -\bifuncindex{floor} -\bifuncindex{ceil} -\indexii{numeric}{conversions} -\stmodindex{math} -\indexii{\C{}}{language} - -\item[(3)] -See the section on built-in functions for an exact definition. - -\end{description} -% XXXJH exceptions: overflow (when? what operations?) zerodivision - -\subsubsection{Bit-string Operations on Integer Types} -\nodename{Bit-string Operations} - -Plain and long integer types support additional operations that make -sense only for bit-strings. Negative numbers are treated as their 2's -complement value (for long integers, this assumes a sufficiently large -number of bits that no overflow occurs during the operation). - -The priorities of the binary bit-wise operations are all lower than -the numeric operations and higher than the comparisons; the unary -operation \samp{~} has the same priority as the other unary numeric -operations (\samp{+} and \samp{-}). - -This table lists the bit-string operations sorted in ascending -priority (operations in the same box have the same priority): - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes} - \lineiii{\var{x} | \var{y}}{bitwise \dfn{or} of \var{x} and \var{y}}{} - \hline - \lineiii{\var{x} \^{} \var{y}}{bitwise \dfn{exclusive or} of \var{x} and \var{y}}{} - \hline - \lineiii{\var{x} \&{} \var{y}}{bitwise \dfn{and} of \var{x} and \var{y}}{} - \hline - \lineiii{\var{x} << \var{n}}{\var{x} shifted left by \var{n} bits}{(1), (2)} - \lineiii{\var{x} >> \var{n}}{\var{x} shifted right by \var{n} bits}{(1), (3)} - \hline - \hline - \lineiii{\~\var{x}}{the bits of \var{x} inverted}{} -\end{tableiii} -\indexiii{operations on}{integer}{types} -\indexii{bit-string}{operations} -\indexii{shifting}{operations} -\indexii{masking}{operations} - -\noindent -Notes: -\begin{description} -\item[(1)] Negative shift counts are illegal. -\item[(2)] A left shift by \var{n} bits is equivalent to -multiplication by \code{pow(2, \var{n})} without overflow check. -\item[(3)] A right shift by \var{n} bits is equivalent to -division by \code{pow(2, \var{n})} without overflow check. -\end{description} - -\subsection{Sequence Types} - -There are three sequence types: strings, lists and tuples. - -Strings literals are written in single or double quotes: -\code{'xyzzy'}, \code{"frobozz"}. See Chapter 2 of the Python -Reference Manual for more about string literals. Lists are -constructed with square brackets, separating items with commas: -\code{[a, b, c]}. Tuples are constructed by the comma operator (not -within square brackets), with or without enclosing parentheses, but an -empty tuple must have the enclosing parentheses, e.g., -\code{a, b, c} or \code{()}. A single item tuple must have a trailing -comma, e.g., \code{(d,)}. -\indexii{sequence}{types} -\indexii{string}{type} -\indexii{tuple}{type} -\indexii{list}{type} - -Sequence types support the following operations. The \samp{in} and -\samp{not\,in} operations have the same priorities as the comparison -operations. The \samp{+} and \samp{*} operations have the same -priority as the corresponding numeric operations.\footnote{They must -have since the parser can't tell the type of the operands.} - -This table lists the sequence operations sorted in ascending priority -(operations in the same box have the same priority). In the table, -\var{s} and \var{t} are sequences of the same type; \var{n}, \var{i} -and \var{j} are integers: - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes} - \lineiii{\var{x} in \var{s}}{\code{1} if an item of \var{s} is equal to \var{x}, else \code{0}}{} - \lineiii{\var{x} not in \var{s}}{\code{0} if an item of \var{s} is -equal to \var{x}, else \code{1}}{} - \hline - \lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{} - \hline - \lineiii{\var{s} * \var{n}{\rm ,} \var{n} * \var{s}}{\var{n} copies of \var{s} concatenated}{} - \hline - \lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(1)} - \lineiii{\var{s}[\var{i}:\var{j}]}{slice of \var{s} from \var{i} to \var{j}}{(1), (2)} - \hline - \lineiii{len(\var{s})}{length of \var{s}}{} - \lineiii{min(\var{s})}{smallest item of \var{s}}{} - \lineiii{max(\var{s})}{largest item of \var{s}}{} -\end{tableiii} -\indexiii{operations on}{sequence}{types} -\bifuncindex{len} -\bifuncindex{min} -\bifuncindex{max} -\indexii{concatenation}{operation} -\indexii{repetition}{operation} -\indexii{subscript}{operation} -\indexii{slice}{operation} -\opindex{in} -\opindex{not in} - -\noindent -Notes: - -\begin{description} - -\item[(1)] If \var{i} or \var{j} is negative, the index is relative to - the end of the string, i.e., \code{len(\var{s}) + \var{i}} or - \code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is - still \code{0}. - -\item[(2)] The slice of \var{s} from \var{i} to \var{j} is defined as - the sequence of items with index \var{k} such that \code{\var{i} <= - \var{k} < \var{j}}. If \var{i} or \var{j} is greater than - \code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted, - use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If - \var{i} is greater than or equal to \var{j}, the slice is empty. - -\end{description} - -\subsubsection{More String Operations} - -String objects have one unique built-in operation: the \code{\%} -operator (modulo) with a string left argument interprets this string -as a C sprintf format string to be applied to the right argument, and -returns the string resulting from this formatting operation. - -The right argument should be a tuple with one item for each argument -required by the format string; if the string requires a single -argument, the right argument may also be a single non-tuple object.% -\footnote{A tuple object in this case should be a singleton.} -The following format characters are understood: -\%, c, s, i, d, u, o, x, X, e, E, f, g, G. -Width and precision may be a * to specify that an integer argument -specifies the actual width or precision. The flag characters -, +, -blank, \# and 0 are understood. The size specifiers h, l or L may be -present but are ignored. The \code{\%s} conversion takes any Python -object and converts it to a string using \code{str()} before -formatting it. The ANSI features \code{\%p} and \code{\%n} -are not supported. Since Python strings have an explicit length, -\code{\%s} conversions don't assume that \code{'\e0'} is the end of -the string. - -For safety reasons, floating point precisions are clipped to 50; -\code{\%f} conversions for numbers whose absolute value is over 1e25 -are replaced by \code{\%g} conversions.% -\footnote{These numbers are fairly arbitrary. They are intended to -avoid printing endless strings of meaningless digits without hampering -correct use and without having to know the exact precision of floating -point values on a particular machine.} -All other errors raise exceptions. - -If the right argument is a dictionary (or any kind of mapping), then -the formats in the string must have a parenthesized key into that -dictionary inserted immediately after the \code{\%} character, and -each format formats the corresponding entry from the mapping. E.g. -\begin{verbatim} - >>> count = 2 - >>> language = 'Python' - >>> print '%(language)s has %(count)03d quote types.' % vars() - Python has 002 quote types. - >>> -\end{verbatim} -In this case no * specifiers may occur in a format (since they a -require sequential parameter list). - -Additional string operations are defined in standard module -\code{string} and in built-in module \code{regex}. -\index{string} -\index{regex} - -\subsubsection{Mutable Sequence Types} - -List objects support additional operations that allow in-place -modification of the object. -These operations would be supported by other mutable sequence types -(when added to the language) as well. -Strings and tuples are immutable sequence types and such objects cannot -be modified once created. -The following operations are defined on mutable sequence types (where -\var{x} is an arbitrary object): -\indexiii{mutable}{sequence}{types} -\indexii{list}{type} - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes} - \lineiii{\var{s}[\var{i}] = \var{x}} - {item \var{i} of \var{s} is replaced by \var{x}}{} - \lineiii{\var{s}[\var{i}:\var{j}] = \var{t}} - {slice of \var{s} from \var{i} to \var{j} is replaced by \var{t}}{} - \lineiii{del \var{s}[\var{i}:\var{j}]} - {same as \code{\var{s}[\var{i}:\var{j}] = []}}{} - \lineiii{\var{s}.append(\var{x})} - {same as \code{\var{s}[len(\var{s}):len(\var{s})] = [\var{x}]}}{} - \lineiii{\var{s}.count(\var{x})} - {return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{} - \lineiii{\var{s}.index(\var{x})} - {return smallest \var{i} such that \code{\var{s}[\var{i}] == \var{x}}}{(1)} - \lineiii{\var{s}.insert(\var{i}, \var{x})} - {same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]} - if \code{\var{i} >= 0}}{} - \lineiii{\var{s}.remove(\var{x})} - {same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(1)} - \lineiii{\var{s}.reverse()} - {reverses the items of \var{s} in place}{} - \lineiii{\var{s}.sort()} - {permutes the items of \var{s} to satisfy - \code{\var{s}[\var{i}] <= \var{s}[\var{j}]}, - for \code{\var{i} < \var{j}}}{(2)} -\end{tableiii} -\indexiv{operations on}{mutable}{sequence}{types} -\indexiii{operations on}{sequence}{types} -\indexiii{operations on}{list}{type} -\indexii{subscript}{assignment} -\indexii{slice}{assignment} -\stindex{del} -\renewcommand{\indexsubitem}{(list method)} -\ttindex{append} -\ttindex{count} -\ttindex{index} -\ttindex{insert} -\ttindex{remove} -\ttindex{reverse} -\ttindex{sort} - -\noindent -Notes: -\begin{description} -\item[(1)] Raises an exception when \var{x} is not found in \var{s}. - -\item[(2)] The \code{sort()} method takes an optional argument - specifying a comparison function of two arguments (list items) which - should return \code{-1}, \code{0} or \code{1} depending on whether the - first argument is considered smaller than, equal to, or larger than the - second argument. Note that this slows the sorting process down - considerably; e.g. to sort a list in reverse order it is much faster - to use calls to \code{sort()} and \code{reverse()} than to use - \code{sort()} with a comparison function that reverses the ordering of - the elements. -\end{description} - -\subsection{Mapping Types} - -A \dfn{mapping} object maps values of one type (the key type) to -arbitrary objects. Mappings are mutable objects. There is currently -only one standard mapping type, the \dfn{dictionary}. A dictionary's keys are -almost arbitrary values. The only types of values not acceptable as -keys are values containing lists or dictionaries or other mutable -types that are compared by value rather than by object identity. -Numeric types used for keys obey the normal rules for numeric -comparison: if two numbers compare equal (e.g. 1 and 1.0) then they -can be used interchangeably to index the same dictionary entry. - -\indexii{mapping}{types} -\indexii{dictionary}{type} - -Dictionaries are created by placing a comma-separated list of -\code{\var{key}:\,var{value}} pairs within braces, for example: -\code{\{'jack':\,4098, 'sjoerd':\,4127\}} or -\code{\{4098:\,'jack', 4127:\,'sjoerd'\}}. - -The following operations are defined on mappings (where \var{a} is a -mapping, \var{k} is a key and \var{x} is an arbitrary object): - -\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes} - \lineiii{len(\var{a})}{the number of items in \var{a}}{} - \lineiii{\var{a}[\var{k}]}{the item of \var{a} with key \var{k}}{(1)} - \lineiii{\var{a}[\var{k}] = \var{x}}{set \code{\var{a}[\var{k}]} to \var{x}}{} - \lineiii{del \var{a}[\var{k}]}{remove \code{\var{a}[\var{k}]} from \var{a}}{(1)} - \lineiii{\var{a}.items()}{a copy of \var{a}'s list of (key, item) pairs}{(2)} - \lineiii{\var{a}.keys()}{a copy of \var{a}'s list of keys}{(2)} - \lineiii{\var{a}.values()}{a copy of \var{a}'s list of values}{(2)} - \lineiii{\var{a}.has_key(\var{k})}{\code{1} if \var{a} has a key \var{k}, else \code{0}}{} -\end{tableiii} -\indexiii{operations on}{mapping}{types} -\indexiii{operations on}{dictionary}{type} -\stindex{del} -\bifuncindex{len} -\renewcommand{\indexsubitem}{(dictionary method)} -\ttindex{keys} -\ttindex{has_key} - -\noindent -Notes: -\begin{description} -\item[(1)] Raises an exception if \var{k} is not in the map. - -\item[(2)] Keys and values are listed in random order. -\end{description} - -\subsection{Other Built-in Types} - -The interpreter supports several other kinds of objects. -Most of these support only one or two operations. - -\subsubsection{Modules} - -The only special operation on a module is attribute access: -\code{\var{m}.\var{name}}, where \var{m} is a module and \var{name} accesses -a name defined in \var{m}'s symbol table. Module attributes can be -assigned to. (Note that the \code{import} statement is not, strictly -spoken, an operation on a module object; \code{import \var{foo}} does not -require a module object named \var{foo} to exist, rather it requires -an (external) \emph{definition} for a module named \var{foo} -somewhere.) - -A special member of every module is \code{__dict__}. -This is the dictionary containing the module's symbol table. -Modifying this dictionary will actually change the module's symbol -table, but direct assignment to the \code{__dict__} attribute is not -possible (i.e., you can write \code{\var{m}.__dict__['a'] = 1}, which -defines \code{\var{m}.a} to be \code{1}, but you can't write \code{\var{m}.__dict__ = \{\}}. - -Modules are written like this: \code{<module 'sys'>}. - -\subsubsection{Classes and Class Instances} -\nodename{Classes and Instances} - -(See Chapters 3 and 7 of the Python Reference Manual for these.) - -\subsubsection{Functions} - -Function objects are created by function definitions. The only -operation on a function object is to call it: -\code{\var{func}(\var{argument-list})}. - -There are really two flavors of function objects: built-in functions -and user-defined functions. Both support the same operation (to call -the function), but the implementation is different, hence the -different object types. - -The implementation adds two special read-only attributes: -\code{\var{f}.func_code} is a function's \dfn{code object} (see below) and -\code{\var{f}.func_globals} is the dictionary used as the function's -global name space (this is the same as \code{\var{m}.__dict__} where -\var{m} is the module in which the function \var{f} was defined). - -\subsubsection{Methods} -\obindex{method} - -Methods are functions that are called using the attribute notation. -There are two flavors: built-in methods (such as \code{append()} on -lists) and class instance methods. Built-in methods are described -with the types that support them. - -The implementation adds two special read-only attributes to class -instance methods: \code{\var{m}.im_self} is the object whose method this -is, and \code{\var{m}.im_func} is the function implementing the method. -Calling \code{\var{m}(\var{arg-1}, \var{arg-2}, {\rm \ldots}, -\var{arg-n})} is completely equivalent to calling -\code{\var{m}.im_func(\var{m}.im_self, \var{arg-1}, \var{arg-2}, {\rm -\ldots}, \var{arg-n})}. - -(See the Python Reference Manual for more info.) - -\subsubsection{Code Objects} -\obindex{code} - -Code objects are used by the implementation to represent -``pseudo-compiled'' executable Python code such as a function body. -They differ from function objects because they don't contain a -reference to their global execution environment. Code objects are -returned by the built-in \code{compile()} function and can be -extracted from function objects through their \code{func_code} -attribute. -\bifuncindex{compile} -\ttindex{func_code} - -A code object can be executed or evaluated by passing it (instead of a -source string) to the \code{exec} statement or the built-in -\code{eval()} function. -\stindex{exec} -\bifuncindex{eval} - -(See the Python Reference Manual for more info.) - -\subsubsection{Type Objects} - -Type objects represent the various object types. An object's type is -accessed by the built-in function \code{type()}. There are no special -operations on types. The standard module \code{types} defines names -for all standard built-in types. -\bifuncindex{type} -\stmodindex{types} - -Types are written like this: \code{<type 'int'>}. - -\subsubsection{The Null Object} - -This object is returned by functions that don't explicitly return a -value. It supports no special operations. There is exactly one null -object, named \code{None} (a built-in name). - -It is written as \code{None}. - -\subsubsection{File Objects} - -File objects are implemented using \C{}'s \code{stdio} package and can be -created with the built-in function \code{open()} described under -Built-in Functions below. They are also returned by some other -built-in functions and methods, e.g.\ \code{posix.popen()} and -\code{posix.fdopen()} and the \code{makefile()} method of socket -objects. -\bifuncindex{open} - -When a file operation fails for an I/O-related reason, the exception -\code{IOError} is raised. This includes situations where the -operation is not defined for some reason, like \code{seek()} on a tty -device or writing a file opened for reading. - -Files have the following methods: - - -\renewcommand{\indexsubitem}{(file method)} - -\begin{funcdesc}{close}{} - Close the file. A closed file cannot be read or written anymore. -\end{funcdesc} - -\begin{funcdesc}{flush}{} - Flush the internal buffer, like \code{stdio}'s \code{fflush()}. -\end{funcdesc} - -\begin{funcdesc}{isatty}{} - Return \code{1} if the file is connected to a tty(-like) device, else - \code{0}. -\end{funcdesc} - -\begin{funcdesc}{read}{\optional{size}} - Read at most \var{size} bytes from the file (less if the read hits - \EOF{} or no more data is immediately available on a pipe, tty or - similar device). If the \var{size} argument is negative or omitted, - read all data until \EOF{} is reached. The bytes are returned as a string - object. An empty string is returned when \EOF{} is encountered - immediately. (For certain files, like ttys, it makes sense to - continue reading after an \EOF{} is hit.) -\end{funcdesc} - -\begin{funcdesc}{readline}{\optional{size}} - Read one entire line from the file. A trailing newline character is - kept in the string% -\footnote{The advantage of leaving the newline on is that an empty string - can be returned to mean \EOF{} without being ambiguous. Another - advantage is that (in cases where it might matter, e.g. if you - want to make an exact copy of a file while scanning its lines) - you can tell whether the last line of a file ended in a newline - or not (yes this happens!).} - (but may be absent when a file ends with an - incomplete line). If thevar{size} argument is present and - non-negative, it is a maximum byte count (including the trailing - newline) and an incomplete line may be returned. - An empty string is returned when \EOF{} is hit - immediately. Note: unlike \code{stdio}'s \code{fgets()}, the returned - string contains null characters (\code{'\e 0'}) if they occurred in the - input. -\end{funcdesc} - -\begin{funcdesc}{readlines}{} - Read until \EOF{} using \code{readline()} and return a list containing - the lines thus read. -\end{funcdesc} - -\begin{funcdesc}{seek}{offset\, whence} - Set the file's current position, like \code{stdio}'s \code{fseek()}. - The \var{whence} argument is optional and defaults to \code{0} - (absolute file positioning); other values are \code{1} (seek - relative to the current position) and \code{2} (seek relative to the - file's end). There is no return value. -\end{funcdesc} - -\begin{funcdesc}{tell}{} - Return the file's current position, like \code{stdio}'s \code{ftell()}. -\end{funcdesc} - -\begin{funcdesc}{truncate}{\optional{size}} -Truncate the file's size. If the optional size argument present, the -file is truncated to (at most) that size. The size defaults to the -current position. Availability of this function depends on the -operating system version (e.g., not all {\UNIX} versions support this -operation). -\end{funcdesc} - -\begin{funcdesc}{write}{str} -Write a string to the file. There is no return value. Note: due to -buffering, the string may not actually show up in the file until -the \code{flush()} or \code{close()} method is called. -\end{funcdesc} - -\begin{funcdesc}{writelines}{list} -Write a list of strings to the file. There is no return value. -(The name is intended to match \code{readlines}; \code{writelines} -does not add line separators.) -\end{funcdesc} - -\subsubsection{Internal Objects} - -(See the Python Reference Manual for these.) - -\subsection{Special Attributes} - -The implementation adds a few special read-only attributes to several -object types, where they are relevant: - -\begin{itemize} - -\item -\code{\var{x}.__dict__} is a dictionary of some sort used to store an -object's (writable) attributes; - -\item -\code{\var{x}.__methods__} lists the methods of many built-in object types, -e.g., \code{[].__methods__} yields -\code{['append', 'count', 'index', 'insert', 'remove', 'reverse', 'sort']}; - -\item -\code{\var{x}.__members__} lists data attributes; - -\item -\code{\var{x}.__class__} is the class to which a class instance belongs; - -\item -\code{\var{x}.__bases__} is the tuple of base classes of a class object. - -\end{itemize} diff --git a/Doc/libtypes2.tex b/Doc/libtypes2.tex deleted file mode 100644 index d0f20c9db7..0000000000 --- a/Doc/libtypes2.tex +++ /dev/null @@ -1,122 +0,0 @@ -\section{Standard Module \sectcode{types}} -\stmodindex{types} - -\renewcommand{\indexsubitem}{(in module types)} - -This module defines names for all object types that are used by the -standard Python interpreter (but not for the types defined by various -extension modules). It is safe to use ``\code{from types import *}'' --- -the module does not export any other names besides the ones listed -here. New names exported by future versions of this module will -all end in \code{Type}. - -Typical use is for functions that do different things depending on -their argument types, like the following: - -\begin{verbatim} -from types import * -def delete(list, item): - if type(item) is IntType: - del list[item] - else: - list.remove(item) -\end{verbatim} - -The module defines the following names: - -\begin{datadesc}{NoneType} -The type of \code{None}. -\end{datadesc} - -\begin{datadesc}{TypeType} -The type of type objects (such as returned by \code{type()}). -\end{datadesc} - -\begin{datadesc}{IntType} -The type of integers (e.g. \code{1}). -\end{datadesc} - -\begin{datadesc}{LongType} -The type of long integers (e.g. \code{1L}). -\end{datadesc} - -\begin{datadesc}{FloatType} -The type of floating point numbers (e.g. \code{1.0}). -\end{datadesc} - -\begin{datadesc}{StringType} -The type of character strings (e.g. \code{'Spam'}). -\end{datadesc} - -\begin{datadesc}{TupleType} -The type of tuples (e.g. \code{(1, 2, 3, 'Spam')}). -\end{datadesc} - -\begin{datadesc}{ListType} -The type of lists (e.g. \code{[0, 1, 2, 3]}). -\end{datadesc} - -\begin{datadesc}{DictType} -The type of dictionaries (e.g. \code{\{'Bacon': 1, 'Ham': 0\}}). -\end{datadesc} - -\begin{datadesc}{DictionaryType} -An alternative name for \code{DictType}. -\end{datadesc} - -\begin{datadesc}{FunctionType} -The type of user-defined functions and lambdas. -\end{datadesc} - -\begin{datadesc}{LambdaType} - An alternative name for \code{FunctionType}. -\end{datadesc} - -\begin{datadesc}{CodeType} -The type for code objects such as returned by \code{compile()}. -\end{datadesc} - -\begin{datadesc}{ClassType} -The type of user-defined classes. -\end{datadesc} - -\begin{datadesc}{InstanceType} -The type of instances of user-defined classes. -\end{datadesc} - -\begin{datadesc}{MethodType} -The type of methods of user-defined class instances. -\end{datadesc} - -\begin{datadesc}{UnboundMethodType} -An alternative name for \code{MethodType}. -\end{datadesc} - -\begin{datadesc}{BuiltinFunctionType} -The type of built-in functions like \code{len} or \code{sys.exit}. -\end{datadesc} - -\begin{datadesc}{BuiltinMethodType} -An alternative name for \code{BuiltinFunction}. -\end{datadesc} - -\begin{datadesc}{ModuleType} -The type of modules. -\end{datadesc} - -\begin{datadesc}{FileType} -The type of open file objects such as \code{sys.stdout}. -\end{datadesc} - -\begin{datadesc}{XRangeType} -The type of range objects returned by \code{xrange()}. -\end{datadesc} - -\begin{datadesc}{TracebackType} -The type of traceback objects such as found in \code{sys.exc_traceback}. -\end{datadesc} - -\begin{datadesc}{FrameType} -The type of frame objects such as found in \code{tb.tb_frame} if -\code{tb} is a traceback object. -\end{datadesc} diff --git a/Doc/libunix.tex b/Doc/libunix.tex deleted file mode 100644 index 895c6e5745..0000000000 --- a/Doc/libunix.tex +++ /dev/null @@ -1,39 +0,0 @@ -\chapter{UNIX Specific Services} - -The modules described in this chapter provide interfaces to features -that are unique to the \UNIX{} operating system, or in some cases to -some or many variants of it. Here's an overview: - -\begin{description} - -\item[posix] ---- The most common Posix system calls (normally used via module \code{os}). - -\item[posixpath] ---- Common Posix pathname manipulations (normally used via \code{os.path}). - -\item[pwd] ---- The password database (\code{getpwnam()} and friends). - -\item[grp] ---- The group database (\code{getgrnam()} and friends). - -\item[crypt] ---- The (\code{crypt()} function used to check Unix passwords). - -\item[dbm] ---- The standard ``database'' interface, based on \code{ndbm}. - -\item[gdbm] ---- GNU's reinterpretation of dbm. - -\item[termios] ---- Posix style tty control. - -\item[fcntl] ---- The \code{fcntl()} and \code{ioctl()} system calls. - -\item[posixfile] ---- A file-like object with support for locking. - -\end{description} diff --git a/Doc/liburllib.tex b/Doc/liburllib.tex deleted file mode 100644 index b26228f12e..0000000000 --- a/Doc/liburllib.tex +++ /dev/null @@ -1,121 +0,0 @@ -\section{Standard Module \sectcode{urllib}} -\stmodindex{urllib} -\index{WWW} -\index{World-Wide Web} -\index{URL} - -\renewcommand{\indexsubitem}{(in module urllib)} - -This module provides a high-level interface for fetching data across -the World-Wide Web. In particular, the \code{urlopen} function is -similar to the built-in function \code{open}, but accepts URLs -(Universal Resource Locators) instead of filenames. Some restrictions -apply --- it can only open URLs for reading, and no seek operations -are available. - -it defines the following public functions: - -\begin{funcdesc}{urlopen}{url} -Open a network object denoted by a URL for reading. If the URL does -not have a scheme identifier, or if it has \samp{file:} as its scheme -identifier, this opens a local file; otherwise it opens a socket to a -server somewhere on the network. If the connection cannot be made, or -if the server returns an error code, the \code{IOError} exception is -raised. If all went well, a file-like object is returned. This -supports the following methods: \code{read()}, \code{readline()}, -\code{readlines()}, \code{fileno()}, \code{close()} and \code{info()}. -Except for the last one, these methods have the same interface as for -file objects --- see the section on File Objects earlier in this -manual. (It's not a built-in file object, however, so it can't be -used at those few places where a true built-in file object is -required.) - -The \code{info()} method returns an instance of the class -\code{rfc822.Message} containing the headers received from the server, -if the protocol uses such headers (currently the only supported -protocol that uses this is HTTP). See the description of the -\code{rfc822} module. -\end{funcdesc} - -\begin{funcdesc}{urlretrieve}{url} -Copy a network object denoted by a URL to a local file, if necessary. -If the URL points to a local file, or a valid cached copy of the -object exists, the object is not copied. Return a tuple (\var{filename}, -\var{headers}) where \var{filename} is the local file name under which -the object can be found, and \var{headers} is either \code{None} (for -a local object) or whatever the \code{info()} method of the object -returned by \code{urlopen()} returned (for a remote object, possibly -cached). Exceptions are the same as for \code{urlopen()}. -\end{funcdesc} - -\begin{funcdesc}{urlcleanup}{} -Clear the cache that may have been built up by previous calls to -\code{urlretrieve()}. -\end{funcdesc} - -\begin{funcdesc}{quote}{string\optional{\, addsafe}} -Replace special characters in \var{string} using the \code{\%xx} escape. -Letters, digits, and the characters ``\code{_,.-}'' are never quoted. -The optional \var{addsafe} parameter specifies additional characters -that should not be quoted --- its default value is \code{'/'}. - -Example: \code{quote('/\~conolly/')} yields \code{'/\%7econnolly/'}. -\end{funcdesc} - -\begin{funcdesc}{unquote}{string} -Replace \samp{\%xx} escapes by their single-character equivalent. - -Example: \code{unquote('/\%7Econnolly/')} yields \code{'/\~connolly/'}. -\end{funcdesc} - -Restrictions: - -\begin{itemize} - -\item -Currently, only the following protocols are supported: HTTP, (versions -0.9 and 1.0), Gopher (but not Gopher-+), FTP, and local files. -\index{HTTP} -\index{Gopher} -\index{FTP} - -\item -The caching feature of \code{urlretrieve()} has been disabled until I -find the time to hack proper processing of Expiration time headers. - -\item -There should be a function to query whether a particular URL is in -the cache. - -\item -For backward compatibility, if a URL appears to point to a local file -but the file can't be opened, the URL is re-interpreted using the FTP -protocol. This can sometimes cause confusing error messages. - -\item -The \code{urlopen()} and \code{urlretrieve()} functions can cause -arbitrarily long delays while waiting for a network connection to be -set up. This means that it is difficult to build an interactive -web client using these functions without using threads. - -\item -The data returned by \code{urlopen()} or \code{urlretrieve()} is the -raw data returned by the server. This may be binary data (e.g. an -image), plain text or (for example) HTML. The HTTP protocol provides -type information in the reply header, which can be inspected by -looking at the \code{Content-type} header. For the Gopher protocol, -type information is encoded in the URL; there is currently no easy way -to extract it. If the returned data is HTML, you can use the module -\code{htmllib} to parse it. -\index{HTML} -\index{HTTP} -\index{Gopher} -\stmodindex{htmllib} - -\item -Although the \code{urllib} module contains (undocumented) routines to -parse and unparse URL strings, the recommended interface for URL -manipulation is in module \code{urlparse}. -\stmodindex{urlparse} - -\end{itemize} diff --git a/Doc/liburlparse.tex b/Doc/liburlparse.tex deleted file mode 100644 index 36ca949ba6..0000000000 --- a/Doc/liburlparse.tex +++ /dev/null @@ -1,84 +0,0 @@ -\section{Standard Module \sectcode{urlparse}} -\stmodindex{urlparse} -\index{WWW} -\index{World-Wide Web} -\index{URL} -\indexii{URL}{parsing} -\indexii{relative}{URL} - -\renewcommand{\indexsubitem}{(in module urlparse)} - -This module defines a standard interface to break URL strings up in -components (addessing scheme, network location, path etc.), to combine -the components back into a URL string, and to convert a ``relative -URL'' to an absolute URL given a ``base URL''. - -The module has been designed to match the current Internet draft on -Relative Uniform Resource Locators (and discovered a bug in an earlier -draft!). - -It defines the following functions: - -\begin{funcdesc}{urlparse}{urlstring\optional{\, -default_scheme\optional{\, allow_fragments}}} -Parse a URL into 6 components, returning a 6-tuple: (addressing -scheme, network location, path, parameters, query, fragment -identifier). This corresponds to the general structure of a URL: -\code{\var{scheme}://\var{netloc}/\var{path};\var{parameters}?\var{query}\#\var{fragment}}. -Each tuple item is a string, possibly empty. -The components are not broken up in smaller parts (e.g. the network -location is a single string), and \% escapes are not expanded. -The delimiters as shown above are not part of the tuple items, -except for a leading slash in the \var{path} component, which is -retained if present. - -Example: - -\begin{verbatim} -urlparse('http://www.cwi.nl:80/%7Eguido/Python.html') -\end{verbatim} - -yields the tuple - -\begin{verbatim} -('http', 'www.cwi.nl:80', '/%7Eguido/Python.html', '', '', '') -\end{verbatim} - -If the \var{default_scheme} argument is specified, it gives the -default addressing scheme, to be used only if the URL string does not -specify one. The default value for this argument is the empty string. - -If the \var{allow_fragments} argument is zero, fragment identifiers -are not allowed, even if the URL's addressing scheme normally does -support them. The default value for this argument is \code{1}. -\end{funcdesc} - -\begin{funcdesc}{urlunparse}{tuple} -Construct a URL string from a tuple as returned by \code{urlparse}. -This may result in a slightly different, but equivalent URL, if the -URL that was parsed originally had redundant delimiters, e.g. a ? with -an empty query (the draft states that these are equivalent). -\end{funcdesc} - -\begin{funcdesc}{urljoin}{base\, url\optional{\, allow_fragments}} -Construct a full (``absolute'') URL by combining a ``base URL'' -(\var{base}) with a ``relative URL'' (\var{url}). Informally, this -uses components of the base URL, in particular the addressing scheme, -the network location and (part of) the path, to provide missing -components in the relative URL. - -Example: - -\begin{verbatim} -urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html') -\end{verbatim} - -yields the string - -\begin{verbatim} -'http://www.cwi.nl/%7Eguido/FAQ.html' -\end{verbatim} - -The \var{allow_fragments} argument has the same meaning as for -\code{urlparse}. -\end{funcdesc} diff --git a/Doc/libwhrandom.tex b/Doc/libwhrandom.tex deleted file mode 100644 index 8ad2339a34..0000000000 --- a/Doc/libwhrandom.tex +++ /dev/null @@ -1,20 +0,0 @@ -\section{Standard Module \sectcode{whrandom}} - -\stmodindex{whrandom} -This module implements a Wichmann-Hill pseudo-random number generator. -It defines the following functions: - -\renewcommand{\indexsubitem}{(in module whrandom)} -\begin{funcdesc}{random}{} -Returns the next random floating point number in the range [0.0 ... 1.0). -\end{funcdesc} - -\begin{funcdesc}{seed}{x\, y\, z} -Initializes the random number generator from the integers -\var{x}, -\var{y} -and -\var{z}. -When the module is first imported, the random number is initialized -using values derived from the current time. -\end{funcdesc} diff --git a/Doc/libwww.tex b/Doc/libwww.tex deleted file mode 100644 index 009c79bc71..0000000000 --- a/Doc/libwww.tex +++ /dev/null @@ -1,51 +0,0 @@ -\chapter{Internet and WWW Services} -\nodename{Internet and WWW} -\index{WWW} -\index{Internet} -\index{World-Wide Web} - -The modules described in this chapter provide various services to -World-Wide Web (WWW) clients and/or services, and a few modules -related to news and email. They are all implemented in Python. Some -of these modules require the presence of the system-dependent module -\code{sockets}, which is currently only fully supported on Unix and -Windows NT. Here is an overview: - -\begin{description} - -\item[cgi] ---- Common Gateway Interface, used to interpret forms in server-side -scripts. - -\item[urllib] ---- Open an arbitrary object given by URL (requires sockets). - -\item[httplib] ---- HTTP protocol client (requires sockets). - -\item[ftplib] ---- FTP protocol client (requires sockets). - -\item[gopherlib] ---- Gopher protocol client (requires sockets). - -\item[nntplib] ---- NNTP protocol client (requires sockets). - -\item[urlparse] ---- Parse a URL string into a tuple (addressing scheme identifier, network -location, path, parameters, query string, fragment identifier). - -\item[htmllib] ---- A (slow) parser for HTML files. - -\item[sgmllib] ---- Only as much of an SGML parser as needed to parse HTML. - -\item[rfc822] ---- Parse RFC-822 style mail headers. - -\item[mimetools] ---- Tools for parsing MIME style message bodies. - -\end{description} diff --git a/Doc/mac/libctb.tex b/Doc/mac/libctb.tex deleted file mode 100644 index a5aab71421..0000000000 --- a/Doc/mac/libctb.tex +++ /dev/null @@ -1,149 +0,0 @@ -\section{Built-in Module \sectcode{ctb}} -\bimodindex{ctb} -\renewcommand{\indexsubitem}{(in module ctb)} - -This module provides a partial interface to the Macintosh -Communications Toolbox. Currently, only Connection Manager tools are -supported. It may not be available in all Mac Python versions. - -\begin{datadesc}{error} -The exception raised on errors. -\end{datadesc} - -\begin{datadesc}{cmData} -\dataline{cmCntl} -\dataline{cmAttn} -Flags for the \var{channel} argument of the \var{Read} and \var{Write} -methods. -\end{datadesc} - -\begin{datadesc}{cmFlagsEOM} -End-of-message flag for \var{Read} and \var{Write}. -\end{datadesc} - -\begin{datadesc}{choose*} -Values returned by \var{Choose}. -\end{datadesc} - -\begin{datadesc}{cmStatus*} -Bits in the status as returned by \var{Status}. -\end{datadesc} - -\begin{funcdesc}{available}{} -Return 1 if the communication toolbox is available, zero otherwise. -\end{funcdesc} - -\begin{funcdesc}{CMNew}{name\, sizes} -Create a connection object using the connection tool named -\var{name}. \var{sizes} is a 6-tuple given buffer sizes for data in, -data out, control in, control out, attention in and attention out. -Alternatively, passing \code{None} will result in default buffer sizes. -\end{funcdesc} - -\subsection{connection object} -For all connection methods that take a \var{timeout} argument, a value -of \code{-1} is indefinite, meaning that the command runs to completion. - -\renewcommand{\indexsubitem}{(connection object attribute)} - -\begin{datadesc}{callback} -If this member is set to a value other than \code{None} it should point -to a function accepting a single argument (the connection -object). This will make all connection object methods work -asynchronously, with the callback routine being called upon -completion. - -{\em Note:} for reasons beyond my understanding the callback routine -is currently never called. You are advised against using asynchronous -calls for the time being. -\end{datadesc} - - -\renewcommand{\indexsubitem}{(connection object method)} - -\begin{funcdesc}{Open}{timeout} -Open an outgoing connection, waiting at most \var{timeout} seconds for -the connection to be established. -\end{funcdesc} - -\begin{funcdesc}{Listen}{timeout} -Wait for an incoming connection. Stop waiting after \var{timeout} -seconds. This call is only meaningful to some tools. -\end{funcdesc} - -\begin{funcdesc}{accept}{yesno} -Accept (when \var{yesno} is non-zero) or reject an incoming call after -\var{Listen} returned. -\end{funcdesc} - -\begin{funcdesc}{Close}{timeout\, now} -Close a connection. When \var{now} is zero, the close is orderly -(i.e.\ outstanding output is flushed, etc.)\ with a timeout of -\var{timeout} seconds. When \var{now} is non-zero the close is -immediate, discarding output. -\end{funcdesc} - -\begin{funcdesc}{Read}{len\, chan\, timeout} -Read \var{len} bytes, or until \var{timeout} seconds have passed, from -the channel \var{chan} (which is one of \var{cmData}, \var{cmCntl} or -\var{cmAttn}). Return a 2-tuple:\ the data read and the end-of-message -flag. -\end{funcdesc} - -\begin{funcdesc}{Write}{buf\, chan\, timeout\, eom} -Write \var{buf} to channel \var{chan}, aborting after \var{timeout} -seconds. When \var{eom} has the value \var{cmFlagsEOM} an -end-of-message indicator will be written after the data (if this -concept has a meaning for this communication tool). The method returns -the number of bytes written. -\end{funcdesc} - -\begin{funcdesc}{Status}{} -Return connection status as the 2-tuple \code{(\var{sizes}, -\var{flags})}. \var{sizes} is a 6-tuple giving the actual buffer sizes used -(see \var{CMNew}), \var{flags} is a set of bits describing the state -of the connection. -\end{funcdesc} - -\begin{funcdesc}{GetConfig}{} -Return the configuration string of the communication tool. These -configuration strings are tool-dependent, but usually easily parsed -and modified. -\end{funcdesc} - -\begin{funcdesc}{SetConfig}{str} -Set the configuration string for the tool. The strings are parsed -left-to-right, with later values taking precedence. This means -individual configuration parameters can be modified by simply appending -something like \code{'baud 4800'} to the end of the string returned by -\var{GetConfig} and passing that to this method. The method returns -the number of characters actually parsed by the tool before it -encountered an error (or completed successfully). -\end{funcdesc} - -\begin{funcdesc}{Choose}{} -Present the user with a dialog to choose a communication tool and -configure it. If there is an outstanding connection some choices (like -selecting a different tool) may cause the connection to be -aborted. The return value (one of the \var{choose*} constants) will -indicate this. -\end{funcdesc} - -\begin{funcdesc}{Idle}{} -Give the tool a chance to use the processor. You should call this -method regularly. -\end{funcdesc} - -\begin{funcdesc}{Abort}{} -Abort an outstanding asynchronous \var{Open} or \var{Listen}. -\end{funcdesc} - -\begin{funcdesc}{Reset}{} -Reset a connection. Exact meaning depends on the tool. -\end{funcdesc} - -\begin{funcdesc}{Break}{length} -Send a break. Whether this means anything, what it means and -interpretation of the \var{length} parameter depend on the tool in -use. -\end{funcdesc} diff --git a/Doc/mac/libmac.tex b/Doc/mac/libmac.tex deleted file mode 100644 index af07142023..0000000000 --- a/Doc/mac/libmac.tex +++ /dev/null @@ -1,40 +0,0 @@ -\chapter{Macintosh Specific Services} - -The modules in this chapter are available on the Apple Macintosh only. - -\section{Built-in Module \sectcode{mac}} - -\bimodindex{mac} -This module provides a subset of the operating system dependent -functionality provided by the optional built-in module \code{posix}. -It is best accessed through the more portable standard module -\code{os}. - -The following functions are available in this module: -\code{chdir}, -\code{getcwd}, -\code{listdir}, -\code{mkdir}, -\code{rename}, -\code{rmdir}, -\code{stat}, -\code{sync}, -\code{unlink}, -as well as the exception \code{error}. - -\section{Standard Module \sectcode{macpath}} - -\stmodindex{macpath} -This module provides a subset of the pathname manipulation functions -available from the optional standard module \code{posixpath}. It is -best accessed through the more portable standard module \code{os}, as -\code{os.path}. - -The following functions are available in this module: -\code{normcase}, -\code{isabs}, -\code{join}, -\code{split}, -\code{isdir}, -\code{isfile}, -\code{exists}. diff --git a/Doc/mac/libmacconsole.tex b/Doc/mac/libmacconsole.tex deleted file mode 100644 index 42d4e51a06..0000000000 --- a/Doc/mac/libmacconsole.tex +++ /dev/null @@ -1,111 +0,0 @@ -\section{Built-in Module \sectcode{macconsole}} -\bimodindex{macconsole} - -\renewcommand{\indexsubitem}{(in module macconsole)} - -This module is available on the Macintosh, provided Python has been -built using the Think C compiler. It provides an interface to the -Think console package, with which basic text windows can be created. - -\begin{datadesc}{options} -An object allowing you to set various options when creating windows, -see below. -\end{datadesc} - -\begin{datadesc}{C_ECHO} -\dataline{C_NOECHO} -\dataline{C_CBREAK} -\dataline{C_RAW} -Options for the \code{setmode} method. \var{C_ECHO} and \var{C_CBREAK} -enable character echo, the other two disable it, \var{C_ECHO} and -\var{C_NOECHO} enable line-oriented input (erase/kill processing, -etc). -\end{datadesc} - -\begin{funcdesc}{copen}{} -Open a new console window. Return a console window object. -\end{funcdesc} - -\begin{funcdesc}{fopen}{fp} -Return the console window object corresponding with the given file -object. \var{fp} should be one of \code{sys.stdin}, \code{sys.stdout} or -\code{sys.stderr}. -\end{funcdesc} - -\subsection{macconsole options object} -These options are examined when a window is created: - -\renewcommand{\indexsubitem}{(macconsole option)} -\begin{datadesc}{top} -\dataline{left} -The origin of the window. -\end{datadesc} - -\begin{datadesc}{nrows} -\dataline{ncols} -The size of the window. -\end{datadesc} - -\begin{datadesc}{txFont} -\dataline{txSize} -\dataline{txStyle} -The font, fontsize and fontstyle to be used in the window. -\end{datadesc} - -\begin{datadesc}{title} -The title of the window. -\end{datadesc} - -\begin{datadesc}{pause_atexit} -If set non-zero, the window will wait for user action before closing. -\end{datadesc} - -\subsection{console window object} - -\renewcommand{\indexsubitem}{(console window attribute)} - -\begin{datadesc}{file} -The file object corresponding to this console window. If the file is -buffered, you should call \code{file.flush()} between \code{write()} -and \code{read()} calls. -\end{datadesc} - -\renewcommand{\indexsubitem}{(console window method)} - -\begin{funcdesc}{setmode}{mode} -Set the input mode of the console to \var{C_ECHO}, etc. -\end{funcdesc} - -\begin{funcdesc}{settabs}{n} -Set the tabsize to \var{n} spaces. -\end{funcdesc} - -\begin{funcdesc}{cleos}{} -Clear to end-of-screen. -\end{funcdesc} - -\begin{funcdesc}{cleol}{} -Clear to end-of-line. -\end{funcdesc} - -\begin{funcdesc}{inverse}{onoff} -Enable inverse-video mode:\ characters with the high bit set are -displayed in inverse video (this disables the upper half of a -non-\ASCII{} character set). -\end{funcdesc} - -\begin{funcdesc}{gotoxy}{x\, y} -Set the cursor to position \code{(\var{x}, \var{y})}. -\end{funcdesc} - -\begin{funcdesc}{hide}{} -Hide the window, remembering the contents. -\end{funcdesc} - -\begin{funcdesc}{show}{} -Show the window again. -\end{funcdesc} - -\begin{funcdesc}{echo2printer}{} -Copy everything written to the window to the printer as well. -\end{funcdesc} diff --git a/Doc/mac/libmacdnr.tex b/Doc/mac/libmacdnr.tex deleted file mode 100644 index ab45788210..0000000000 --- a/Doc/mac/libmacdnr.tex +++ /dev/null @@ -1,119 +0,0 @@ - -\section{Built-in Module \sectcode{macdnr}} -\bimodindex{macdnr} - -This module provides an interface to the Macintosh Domain Name -Resolver. It is usually used in conjunction with the \var{mactcp} -module, to map hostnames to IP-addresses. It may not be available in -all Mac Python versions. - -The \code{macdnr} module defines the following functions: - -\renewcommand{\indexsubitem}{(in module macdnr)} - -\begin{funcdesc}{Open}{\optional{filename}} -Open the domain name resolver extension. If \var{filename} is given it -should be the pathname of the extension, otherwise a default is -used. Normally, this call is not needed since the other calls will -open the extension automatically. -\end{funcdesc} - -\begin{funcdesc}{Close}{} -Close the resolver extension. Again, not needed for normal use. -\end{funcdesc} - -\begin{funcdesc}{StrToAddr}{hostname} -Look up the IP address for \var{hostname}. This call returns a dnr -result object of the ``address'' variation. -\end{funcdesc} - -\begin{funcdesc}{AddrToName}{addr} -Do a reverse lookup on the 32-bit integer IP-address -\var{addr}. Returns a dnr result object of the ``address'' variation. -\end{funcdesc} - -\begin{funcdesc}{AddrToStr}{addr} -Convert the 32-bit integer IP-address \var{addr} to a dotted-decimal -string. Returns the string. -\end{funcdesc} - -\begin{funcdesc}{HInfo}{hostname} -Query the nameservers for a \code{HInfo} record for host -\var{hostname}. These records contain hardware and software -information about the machine in question (if they are available in -the first place). Returns a dnr result object of the ``hinfo'' -variety. -\end{funcdesc} - -\begin{funcdesc}{MXInfo}{domain} -Query the nameservers for a mail exchanger for \var{domain}. This is -the hostname of a host willing to accept SMTP mail for the given -domain. Returns a dnr result object of the ``mx'' variety. -\end{funcdesc} - -\subsection{dnr result object} - -Since the DNR calls all execute asynchronously you do not get the -results back immediately. Instead, you get a dnr result object. You -can check this object to see whether the query is complete, and access -its attributes to obtain the information when it is. - -Alternatively, you can also reference the result attributes directly, -this will result in an implicit wait for the query to complete. - -The \var{rtnCode} and \var{cname} attributes are always available, the -others depend on the type of query (address, hinfo or mx). - -\renewcommand{\indexsubitem}{(dnr result object method)} - -% Add args, as in {arg1\, arg2 \optional{\, arg3}} -\begin{funcdesc}{wait}{} -Wait for the query to complete. -\end{funcdesc} - -% Add args, as in {arg1\, arg2 \optional{\, arg3}} -\begin{funcdesc}{isdone}{} -Return 1 if the query is complete. -\end{funcdesc} - -\renewcommand{\indexsubitem}{(dnr result object attribute)} - -\begin{datadesc}{rtnCode} -The error code returned by the query. -\end{datadesc} - -\begin{datadesc}{cname} -The canonical name of the host that was queried. -\end{datadesc} - -\begin{datadesc}{ip0} -\dataline{ip1} -\dataline{ip2} -\dataline{ip3} -At most four integer IP addresses for this host. Unused entries are -zero. Valid only for address queries. -\end{datadesc} - -\begin{datadesc}{cpuType} -\dataline{osType} -Textual strings giving the machine type an OS name. Valid for hinfo -queries. -\end{datadesc} - -\begin{datadesc}{exchange} -The name of a mail-exchanger host. Valid for mx queries. -\end{datadesc} - -\begin{datadesc}{preference} -The preference of this mx record. Not too useful, since the Macintosh -will only return a single mx record. Mx queries only. -\end{datadesc} - -The simplest way to use the module to convert names to dotted-decimal -strings, without worrying about idle time, etc: -\begin{verbatim} ->>> def gethostname(name): -... import macdnr -... dnrr = macdnr.StrToAddr(name) -... return macdnr.AddrToStr(dnrr.ip0) -\end{verbatim} diff --git a/Doc/mac/libmacfs.tex b/Doc/mac/libmacfs.tex deleted file mode 100644 index 254ed253ac..0000000000 --- a/Doc/mac/libmacfs.tex +++ /dev/null @@ -1,182 +0,0 @@ -\section{Built-in Module \sectcode{macfs}} -\bimodindex{macfs} - -\renewcommand{\indexsubitem}{(in module macfs)} - -This module provides access to macintosh FSSpec handling, the Alias -Manager, finder aliases and the Standard File package. - -Whenever a function or method expects a \var{file} argument, this -argument can be one of three things:\ (1) a full or partial Macintosh -pathname, (2) an FSSpec object or (3) a 3-tuple \code{(wdRefNum, -parID, name)} as described in Inside Mac VI\@. A description of aliases -and the standard file package can also be found there. - -\begin{funcdesc}{FSSpec}{file} -Create an FSSpec object for the specified file. -\end{funcdesc} - -\begin{funcdesc}{RawFSSpec}{data} -Create an FSSpec object given the raw data for the C structure for the -FSSpec as a string. This is mainly useful if you have obtained an -FSSpec structure over a network. -\end{funcdesc} - -\begin{funcdesc}{RawAlias}{data} -Create an Alias object given the raw data for the C structure for the -alias as a string. This is mainly useful if you have obtained an -FSSpec structure over a network. -\end{funcdesc} - -\begin{funcdesc}{FInfo}{} -Create a zero-filled FInfo object. -\end{funcdesc} - -\begin{funcdesc}{ResolveAliasFile}{file} -Resolve an alias file. Returns a 3-tuple \code{(\var{fsspec}, \var{isfolder}, -\var{aliased})} where \var{fsspec} is the resulting FSSpec object, -\var{isfolder} is true if \var{fsspec} points to a folder and -\var{aliased} is true if the file was an alias in the first place -(otherwise the FSSpec object for the file itself is returned). -\end{funcdesc} - -\begin{funcdesc}{StandardGetFile}{\optional{type\, ...}} -Present the user with a standard ``open input file'' -dialog. Optionally, you can pass up to four 4-char file types to limit -the files the user can choose from. The function returns an FSSpec -object and a flag indicating that the user completed the dialog -without cancelling. -\end{funcdesc} - -\begin{funcdesc}{PromptGetFile}{prompt\optional{\, type\, ...}} -Similar to \var{StandardGetFile} but allows you to specify a prompt. -\end{funcdesc} - -\begin{funcdesc}{StandardPutFile}{prompt\, \optional{default}} -Present the user with a standard ``open output file'' -dialog. \var{prompt} is the prompt string, and the optional -\var{default} argument initializes the output file name. The function -returns an FSSpec object and a flag indicating that the user completed -the dialog without cancelling. -\end{funcdesc} - -\begin{funcdesc}{GetDirectory}{\optional{prompt}} -Present the user with a non-standard ``select a directory'' -dialog. \var{prompt} is the prompt string, and the optional. -Return an FSSpec object and a success-indicator. -\end{funcdesc} - -\begin{funcdesc}{FindFolder}{where\, which\, create} -Locates one of the ``special'' folders that MacOS knows about, such as -the trash or the Preferences folder. \var{Where} is the disk to -search, \var{which} is the 4-char string specifying which folder to -locate. Setting \var{create} causes the folder to be created if it -does not exist. Returns a \code{(vrefnum, dirid)} tuple. - -The constants for \var{where} and \var{which} can be obtained from the -standard module \var{MACFS}. -\end{funcdesc} - -\subsection{FSSpec objects} - -\renewcommand{\indexsubitem}{(FSSpec object attribute)} -\begin{datadesc}{data} -The raw data from the FSSpec object, suitable for passing -to other applications, for instance. -\end{datadesc} - -\renewcommand{\indexsubitem}{(FSSpec object method)} -\begin{funcdesc}{as_pathname}{} -Return the full pathname of the file described by the FSSpec object. -\end{funcdesc} - -\begin{funcdesc}{as_tuple}{} -Return the \code{(\var{wdRefNum}, \var{parID}, \var{name})} tuple of the file described -by the FSSpec object. -\end{funcdesc} - -\begin{funcdesc}{NewAlias}{\optional{file}} -Create an Alias object pointing to the file described by this -FSSpec. If the optional \var{file} parameter is present the alias -will be relative to that file, otherwise it will be absolute. -\end{funcdesc} - -\begin{funcdesc}{NewAliasMinimal}{} -Create a minimal alias pointing to this file. -\end{funcdesc} - -\begin{funcdesc}{GetCreatorType}{} -Return the 4-char creator and type of the file. -\end{funcdesc} - -\begin{funcdesc}{SetCreatorType}{creator\, type} -Set the 4-char creator and type of the file. -\end{funcdesc} - -\begin{funcdesc}{GetFInfo}{} -Return a FInfo object describing the finder info for the file. -\end{funcdesc} - -\begin{funcdesc}{SetFInfo}{finfo} -Set the finder info for the file to the values specified in the -\var{finfo} object. -\end{funcdesc} - -\subsection{alias objects} - -\renewcommand{\indexsubitem}{(alias object attribute)} -\begin{datadesc}{data} -The raw data for the Alias record, suitable for storing in a resource -or transmitting to other programs. -\end{datadesc} - -\renewcommand{\indexsubitem}{(alias object method)} -\begin{funcdesc}{Resolve}{\optional{file}} -Resolve the alias. If the alias was created as a relative alias you -should pass the file relative to which it is. Return the FSSpec for -the file pointed to and a flag indicating whether the alias object -itself was modified during the search process. -\end{funcdesc} - -\begin{funcdesc}{GetInfo}{num} -An interface to the C routine \code{GetAliasInfo()}. -\end{funcdesc} - -\begin{funcdesc}{Update}{file\, \optional{file2}} -Update the alias to point to the \var{file} given. If \var{file2} is -present a relative alias will be created. -\end{funcdesc} - -Note that it is currently not possible to directly manipulate a resource -as an alias object. Hence, after calling \var{Update} or after -\var{Resolve} indicates that the alias has changed the Python program -is responsible for getting the \var{data} from the alias object and -modifying the resource. - - -\subsection{FInfo objects} - -See Inside Mac for a complete description of what the various fields -mean. - -\renewcommand{\indexsubitem}{(FInfo object attribute)} -\begin{datadesc}{Creator} -The 4-char creator code of the file. -\end{datadesc} - -\begin{datadesc}{Type} -The 4-char type code of the file. -\end{datadesc} - -\begin{datadesc}{Flags} -The finder flags for the file as 16-bit integer. The bit values in -\var{Flags} are defined in standard module \var{MACFS}. -\end{datadesc} - -\begin{datadesc}{Location} -A Point giving the position of the file's icon in its folder. -\end{datadesc} - -\begin{datadesc}{Fldr} -The folder the file is in (as an integer). -\end{datadesc} diff --git a/Doc/mac/libmacos.tex b/Doc/mac/libmacos.tex deleted file mode 100644 index 66187545ef..0000000000 --- a/Doc/mac/libmacos.tex +++ /dev/null @@ -1,74 +0,0 @@ -\section{Built-in Module \sectcode{MacOS}} -\bimodindex{MacOS} - -\renewcommand{\indexsubitem}{(in module MacOS)} - -This module provides access to MacOS specific functionality in the -python interpreter, such as how the interpreter eventloop functions -and the like. Use with care. - -Note the capitalisation of the module name, this is a historical -artefact. - -\begin{excdesc}{Error} -This exception is raised on MacOS generated errors, either from -functions in this module or from other mac-specific modules like the -toolbox interfaces. The arguments are the integer error code (the -\var{OSErr} value) and a textual description of the error code. -\end{excdesc} - -\begin{funcdesc}{SetHighLevelEventHandler}{handler} -Pass a python function that will be called upon reception of a -high-level event. The previous handler is returned. The handler -function is called with the event as argument. - -Note that your event handler is currently only called dependably if -your main event loop is in \var{stdwin}. -\end{funcdesc} - -\begin{funcdesc}{AcceptHighLevelEvent}{} -Read a high-level event. The return value is a tuple \code{(sender, -refcon, data)}. -\end{funcdesc} - -\begin{funcdesc}{SetScheduleTimes}{fgi\, fgy \optional{\, bgi\, bgy}} -Controls how often the interpreter checks the event queue and how -long it will yield the processor to other processes. \var{fgi} -specifies after how many clicks (one click is one 60th of a second) -the interpreter should check the event queue, and \var{fgy} specifies -for how many clicks the CPU should be yielded when in the -foreground. The optional \var{bgi} and \var{bgy} allow you to specify -different values to use when python runs in the background, otherwise -the background values will be set the the same as the foreground -values. The function returns nothing. - -The default values, which are based on nothing at all, are 12, 6, 1 -and 12 respectively. -\end{funcdesc} - -\begin{funcdesc}{EnableAppswitch}{onoff} -Enable or disable the python event loop, based on the value of -\var{onoff}. The old value is returned. If the event loop is disabled -no time is granted to other applications, checking for command-period -is not performed and it is impossible to switch applications. This -should only be used by programs providing their own complete event -loop. - -Note that based on the compiler used to build python it is still -possible to loose events even with the python event loop disabled. If -you have a \code{sys.stdout} window its handler will often also look -in the event queue. Making sure nothing is ever printed works around -this. -\end{funcdesc} - -\begin{funcdesc}{HandleEvent}{ev} -Pass the event record \code{ev} back to the python event loop, or -possibly to the handler for the \code{sys.stdout} window (based on the -compiler used to build python). This allows python programs that do -their own event handling to still have some command-period and -window-switching capability. -\end{funcdesc} - -\begin{funcdesc}{GetErrorString}{errno} -Return the textual description of MacOS error code \var{errno}. -\end{funcdesc} diff --git a/Doc/mac/libmacostools.tex b/Doc/mac/libmacostools.tex deleted file mode 100644 index 1e60983b1c..0000000000 --- a/Doc/mac/libmacostools.tex +++ /dev/null @@ -1,39 +0,0 @@ - -\section{Standard module \sectcode{macostools}} -\stmodindex{macostools} - -This module contains some convenience routines for file-manipulation -on the Macintosh. - -The \code{macostools} module defines the following functions: - -\renewcommand{\indexsubitem}{(in module macostools)} - -\begin{funcdesc}{copy}{src\, dst\optional{\, createpath}} -Copy file \var{src} to \var{dst}. The files can be specified as -pathnames or \code{FSSpec} objects. If \var{createpath} is non-zero -\var{dst} must be a pathname and the folders leading to the -destination are created if necessary. -The method copies data and resource fork and some finder information -(creator, type and flags). Custom icons, comments and icon position -are not copied. -\end{funcdesc} - -\begin{funcdesc}{copytree}{src\, dst} -Recursively copy a file tree from \var{src} to \var{dst}, creating -folders as needed. \var{Src} and \var{dst} should be specified as -pathnames. -\end{funcdesc} - -\begin{funcdesc}{mkalias}{src\, dst} -Create a finder alias \var{dst} pointing to \var{src}. Both may be -specified as pathnames or \var{FSSpec} objects. -\end{funcdesc} - -\begin{datadesc}{BUFSIZ} -The buffer size for \code{copy}, default 1 megabyte. -\end{datadesc} - -Note that the process of creating finder aliases is not specified in -the Apple documentation. Hence, aliases created with \code{mkalias} -could conceivably have incompatible behaviour in some cases. diff --git a/Doc/mac/libmacspeech.tex b/Doc/mac/libmacspeech.tex deleted file mode 100644 index fc35520b64..0000000000 --- a/Doc/mac/libmacspeech.tex +++ /dev/null @@ -1,86 +0,0 @@ -\section{Built-in Module \sectcode{macspeech}} -\bimodindex{macspeech} - -\renewcommand{\indexsubitem}{(in module macspeech)} - -This module provides an interface to the Macintosh Speech Manager, -allowing you to let the Macintosh utter phrases. You need a version of -the speech manager extension (version 1 and 2 have been tested) in -your \code{Extensions} folder for this to work. The module does not -provide full access to all features of the Speech Manager yet. It may -not be available in all Mac Python versions. - -\begin{funcdesc}{Available}{} -Test availability of the Speech Manager extension (and, on the -PowerPC, the Speech Manager shared library). Return 0 or 1. -\end{funcdesc} - -\begin{funcdesc}{Version}{} -Return the (integer) version number of the Speech Manager. -\end{funcdesc} - -\begin{funcdesc}{SpeakString}{str} -Utter the string \var{str} using the default voice, -asynchronously. This aborts any speech that may still be active from -prior \code{SpeakString} invocations. -\end{funcdesc} - -\begin{funcdesc}{Busy}{} -Return the number of speech channels busy, system-wide. -\end{funcdesc} - -\begin{funcdesc}{CountVoices}{} -Return the number of different voices available. -\end{funcdesc} - -\begin{funcdesc}{GetIndVoice}{num} -Return a voice object for voice number \var{num}. -\end{funcdesc} - -\subsection{voice objects} -Voice objects contain the description of a voice. It is currently not -yet possible to access the parameters of a voice. - -\renewcommand{\indexsubitem}{(voice object method)} - -\begin{funcdesc}{GetGender}{} -Return the gender of the voice:\ 0 for male, 1 for female and $-1$ for neuter. -\end{funcdesc} - -\begin{funcdesc}{NewChannel}{} -Return a new speech channel object using this voice. -\end{funcdesc} - -\subsection{speech channel objects} -A speech channel object allows you to speak strings with slightly more -control than \code{SpeakString()}, and allows you to use multiple -speakers at the same time. Please note that channel pitch and rate are -interrelated in some way, so that to make your Macintosh sing you will -have to adjust both. - -\renewcommand{\indexsubitem}{(speech channel object method)} -\begin{funcdesc}{SpeakText}{str} -Start uttering the given string. -\end{funcdesc} - -\begin{funcdesc}{Stop}{} -Stop babbling. -\end{funcdesc} - -\begin{funcdesc}{GetPitch}{} -Return the current pitch of the channel, as a floating-point number. -\end{funcdesc} - -\begin{funcdesc}{SetPitch}{pitch} -Set the pitch of the channel. -\end{funcdesc} - -\begin{funcdesc}{GetRate}{} -Get the speech rate (utterances per minute) of the channel as a -floating point number. -\end{funcdesc} - -\begin{funcdesc}{SetRate}{rate} -Set the speech rate of the channel. -\end{funcdesc} - diff --git a/Doc/mac/libmactcp.tex b/Doc/mac/libmactcp.tex deleted file mode 100644 index 6c5a78bf60..0000000000 --- a/Doc/mac/libmactcp.tex +++ /dev/null @@ -1,173 +0,0 @@ -\section{Built-in Module \sectcode{mactcp}} -\bimodindex{mactcp} - -\renewcommand{\indexsubitem}{(in module mactcp)} - -This module provides an interface to the Macintosh TCP/IP driver -MacTCP\@. There is an accompanying module \code{macdnr} which provides an -interface to the name-server (allowing you to translate hostnames to -ip-addresses), a module \code{MACTCP} which has symbolic names for -constants constants used by MacTCP and a wrapper module \code{socket} -which mimics the \UNIX{} socket interface (as far as possible). It may -not be available in all Mac Python versions. - -A complete description of the MacTCP interface can be found in the -Apple MacTCP API documentation. - -\begin{funcdesc}{MTU}{} -Return the Maximum Transmit Unit (the packet size) of the network -interface. -\end{funcdesc} - -\begin{funcdesc}{IPAddr}{} -Return the 32-bit integer IP address of the network interface. -\end{funcdesc} - -\begin{funcdesc}{NetMask}{} -Return the 32-bit integer network mask of the interface. -\end{funcdesc} - -\begin{funcdesc}{TCPCreate}{size} -Create a TCP Stream object. \var{size} is the size of the receive -buffer, \code{4096} is suggested by various sources. -\end{funcdesc} - -\begin{funcdesc}{UDPCreate}{size, port} -Create a UDP stream object. \var{size} is the size of the receive -buffer (and, hence, the size of the biggest datagram you can receive -on this port). \var{port} is the UDP port number you want to receive -datagrams on, a value of zero will make MacTCP select a free port. -\end{funcdesc} - -\subsection{TCP Stream Objects} - -\renewcommand{\indexsubitem}{(TCP stream attribute)} - -\begin{datadesc}{asr} -When set to a value different than \code{None} this should point to a -function with two integer parameters:\ an event code and a detail. This -function will be called upon network-generated events such as urgent -data arrival. In addition, it is called with eventcode -\code{MACTCP.PassiveOpenDone} when a \code{PassiveOpen} completes. This -is a Python addition to the MacTCP semantics. -It is safe to do further calls from the \code{asr}. -\end{datadesc} - -\renewcommand{\indexsubitem}{(TCP stream method)} - -\begin{funcdesc}{PassiveOpen}{port} -Wait for an incoming connection on TCP port \var{port} (zero makes the -system pick a free port). The call returns immediately, and you should -use \var{wait} to wait for completion. You should not issue any method -calls other than -\code{wait}, \code{isdone} or \code{GetSockName} before the call -completes. -\end{funcdesc} - -\begin{funcdesc}{wait}{} -Wait for \code{PassiveOpen} to complete. -\end{funcdesc} - -\begin{funcdesc}{isdone}{} -Return 1 if a \code{PassiveOpen} has completed. -\end{funcdesc} - -\begin{funcdesc}{GetSockName}{} -Return the TCP address of this side of a connection as a 2-tuple -\code{(host, port)}, both integers. -\end{funcdesc} - -\begin{funcdesc}{ActiveOpen}{lport\, host\, rport} -Open an outgoing connection to TCP address \code{(\var{host}, \var{rport})}. Use -local port \var{lport} (zero makes the system pick a free port). This -call blocks until the connection has been established. -\end{funcdesc} - -\begin{funcdesc}{Send}{buf\, push\, urgent} -Send data \var{buf} over the connection. \var{Push} and \var{urgent} -are flags as specified by the TCP standard. -\end{funcdesc} - -\begin{funcdesc}{Rcv}{timeout} -Receive data. The call returns when \var{timeout} seconds have passed -or when (according to the MacTCP documentation) ``a reasonable amount -of data has been received''. The return value is a 3-tuple -\code{(\var{data}, \var{urgent}, \var{mark})}. If urgent data is outstanding \code{Rcv} -will always return that before looking at any normal data. The first -call returning urgent data will have the \var{urgent} flag set, the -last will have the \var{mark} flag set. -\end{funcdesc} - -\begin{funcdesc}{Close}{} -Tell MacTCP that no more data will be transmitted on this -connection. The call returns when all data has been acknowledged by -the receiving side. -\end{funcdesc} - -\begin{funcdesc}{Abort}{} -Forcibly close both sides of a connection, ignoring outstanding data. -\end{funcdesc} - -\begin{funcdesc}{Status}{} -Return a TCP status object for this stream giving the current status -(see below). -\end{funcdesc} - -\subsection{TCP Status Objects} -This object has no methods, only some members holding information on -the connection. A complete description of all fields in this objects -can be found in the Apple documentation. The most interesting ones are: - -\renewcommand{\indexsubitem}{(TCP status attribute)} - -\begin{datadesc}{localHost} -\dataline{localPort} -\dataline{remoteHost} -\dataline{remotePort} -The integer IP-addresses and port numbers of both endpoints of the -connection. -\end{datadesc} - -\begin{datadesc}{sendWindow} -The current window size. -\end{datadesc} - -\begin{datadesc}{amtUnackedData} -The number of bytes sent but not yet acknowledged. \code{sendWindow - -amtUnackedData} is what you can pass to \code{Send} without blocking. -\end{datadesc} - -\begin{datadesc}{amtUnreadData} -The number of bytes received but not yet read (what you can \code{Recv} -without blocking). -\end{datadesc} - - - -\subsection{UDP Stream Objects} -Note that, unlike the name suggests, there is nothing stream-like -about UDP. - -\renewcommand{\indexsubitem}{(UDP stream attribute)} - -\begin{datadesc}{asr} -The asynchronous service routine to be called on events such as -datagram arrival without outstanding \code{Read} call. The \code{asr} has a -single argument, the event code. -\end{datadesc} - -\begin{datadesc}{port} -A read-only member giving the port number of this UDP stream. -\end{datadesc} - -\renewcommand{\indexsubitem}{(UDP stream method)} - -\begin{funcdesc}{Read}{timeout} -Read a datagram, waiting at most \var{timeout} seconds ($-1$ is -infinite). Return the data. -\end{funcdesc} - -\begin{funcdesc}{Write}{host\, port\, buf} -Send \var{buf} as a datagram to IP-address \var{host}, port -\var{port}. -\end{funcdesc} diff --git a/Doc/mac/libmacui.tex b/Doc/mac/libmacui.tex deleted file mode 100644 index f785679e80..0000000000 --- a/Doc/mac/libmacui.tex +++ /dev/null @@ -1,221 +0,0 @@ -\section{Standard module \sectcode{EasyDialogs}} -\stmodindex{EasyDialogs} - -The \code{EasyDialogs} module contains some simple dialogs for -the Macintosh, modelled after the \code{stdwin} dialogs with similar -names. - -The \code{EasyDialogs} module defines the following functions: - -\renewcommand{\indexsubitem}{(in module EasyDialogs)} - -\begin{funcdesc}{Message}{str} -A modal dialog with the message text \var{str}, which should be at -most 255 characters long, is displayed. Control is returned when the -user clicks ``OK''. -\end{funcdesc} - -\begin{funcdesc}{AskString}{prompt\optional{\, default}} -Ask the user to input a string value, in a modal dialog. \var{Prompt} -is the promt message, the optional \var{default} arg is the initial -value for the string. All strings can be at most 255 bytes -long. \var{AskString} returns the string entered or \code{None} in -case the user cancelled. -\end{funcdesc} - -\begin{funcdesc}{AskYesNoCancel}{question\optional{\, default}} -Present a dialog with text \var{question} and three buttons labelled -``yes'', ``no'' and ``cancel''. Return \code{1} for yes, \code{0} for -no and \code{-1} for cancel. The default return value chosen by -hitting return is \code{0}. This can be changed with the optional -\var{default} argument. -\end{funcdesc} - -\begin{funcdesc}{ProgressBar}{\optional{label\, maxval}} -Display a modeless progress dialog with a thermometer bar. \var{Label} -is the textstring displayed (default ``Working...''), \var{maxval} is -the value at which progress is complete (default 100). The returned -object has one method, \code{set(value)}, which sets the value of the -progress bar. The bar remains visible until the object returned is -discarded. - -The progress bar has a ``cancel'' button, but it is currently -non-functional. -\end{funcdesc} - -Note that \code{EasyDialogs} does not currently use the notification -manager. This means that displaying dialogs while the program is in -the background will lead to unexpected results and possibly -crashes. Also, all dialogs are modeless and hence expect to be at the -top of the stacking order. This is true when the dialogs are created, -but windows that pop-up later (like a console window) may also result -in crashes. - - -\section{Standard module \sectcode{FrameWork}} -\stmodindex{FrameWork} - -The \code{FrameWork} module contains classes that together provide a -framework for an interactive Macintosh application. The programmer -builds an application by creating subclasses that override various -methods of the bases classes, thereby implementing the functionality -wanted. Overriding functionality can often be done on various -different levels, i.e. to handle clicks in a single dialog window in a -non-standard way it is not necessary to override the complete event -handling. - -The \code{FrameWork} is still very much work-in-progress, and the -documentation describes only the most important functionality, and not -in the most logical manner at that. Examine the source for more -esoteric needs. - -The \code{EasyDialogs} module defines the following functions: - -\renewcommand{\indexsubitem}{(in module FrameWork)} - -\begin{funcdesc}{Application}{} -An object representing the complete application. See below for a -description of the methods. The default \code{__init__} routine -creates an empty window dictionary and a menu bar with an apple menu. -\end{funcdesc} - -\begin{funcdesc}{MenuBar}{} -An object representing the menubar. This object is usually not created -by the user. -\end{funcdesc} - -\begin{funcdesc}{Menu}{bar\, title\optional{\, after}} -An object representing a menu. Upon creation you pass the -\code{MenuBar} the menu appears in, the \var{title} string and a -position (1-based) \var{after} where the menu should appear (default: -at the end). -\end{funcdesc} - -\begin{funcdesc}{MenuItem}{menu\, title\optional{\, shortcut\, callback}} -Create a menu item object. The arguments are the menu to crate the -item it, the item title string and optionally the keyboard shortcut -and a callback routine. The callback is called with the arguments -menu-id, item number within menu (1-based), current front window and -the event record. -\end{funcdesc} - -\begin{funcdesc}{Separator}{menu} -Add a separator to the end of a menu. -\end{funcdesc} - -\begin{funcdesc}{SubMenu}{menu\, label} -Create a submenu named \var{label} under menu \var{menu}. The menu -object is returned. -\end{funcdesc} - -\begin{funcdesc}{Window}{parent} -Creates a (modeless) window. \var{Parent} is the application object to -which the window belongs. The window is not displayed until later. -\end{funcdesc} - -\begin{funcdesc}{DialogWindow}{parent} -Creates a modeless dialog window. -\end{funcdesc} - - -\subsection{Application objects} -Application objects have the following methods, among others: - -\renewcommand{\indexsubitem}{(Application method)} - -\begin{funcdesc}{makeusermenus}{} -Override this method if you need menus in your application. Append the -menus to \code{self.menubar}. -\end{funcdesc} - -\begin{funcdesc}{getabouttext}{} -Override this method to return a text string describing your -application. Alternatively, override the \code{do_about} method for -more elaborate about messages. -\end{funcdesc} - -\begin{funcdesc}{mainloop}{\optional{mask\, wait}} -This routine is the main event loop, call it to set your application -rolling. \var{Mask} is the mask of events you want to handle, -\var{wait} is the number of ticks you want to leave to other -concurrent application (default 0, which is probably not a good -idea). This method does not return until \code{self} is raised. - -The event loop is split into many small parts, each of which can be -overridden. The default methods take care of dispatching events to -windows and dialogs, handling drags and resizes, Apple Events, events -for non-FrameWork windows, etc. -\end{funcdesc} - -\begin{funcdesc}{do_char}{c\, event} -The user typed character \var{c}. The complete details of the event -can be found in the \var{event} structure. This method can also be -provided in a \code{Window} object, which overrides the -application-wide handler if the window is frontmost. -\end{funcdesc} - -\begin{funcdesc}{do_dialogevent}{event} -Called early in the event loop to handle modeless dialog events. The -default method simply dispatches the event to the relevant dialog (not -through the the \code{DialogWindow} object involved). Override if you -need special handling of dialog events (keyboard shortcuts, etc). -\end{funcdesc} - -\begin{funcdesc}{idle}{} -Called by the main event loop when no events are available. -\end{funcdesc} - -\subsection{Window Objects} - -Window objects have the following methods, among others: - -\renewcommand{\indexsubitem}{(Window method)} - -\begin{funcdesc}{open}{} -Override this method to open a window. Store the MacOS window-id in -\code{self.wid} and call \code{self.do_postopen} to register the -window with the parent application. -\end{funcdesc} - -\begin{funcdesc}{close}{} -Override this method to do any special processing on window -close. Call \code{self.do_postclose} to cleanup the parent state. -\end{funcdesc} - -\begin{funcdesc}{do_postresize}{width\, height\, macoswindowid} -Called after the window is resized. Override if more needs to be done -than calling \code{InvalRect}. -\end{funcdesc} - -\begin{funcdesc}{do_contentclick}{local\, modifiers\, event} -The user clicked in the content part of a window. The arguments are -the coordinates (window-relative), the key modifiers and the raw -event. -\end{funcdesc} - -\begin{funcdesc}{do_update}{macoswindowid\, event} -An update event for the window was received. Redraw the window. -\end{funcdesc} - -\begin{funcdesc}{do_activate}{activate\, event} -The window was activated (\code{activate==1}) or deactivated -(\code{activate==0}). Handle things like focus highlighting, etc. -\end{funcdesc} - -\subsection{DialogWindow Objects} - -DialogWindow objects have the following methods besides those of -\code{Window} objects: - -\renewcommand{\indexsubitem}{(DialogWindow method)} - -\begin{funcdesc}{open}{resid} -Create the dialog window, from the DLOG resource with id -\var{resid}. The dialog object is stored in \code{self.wid}. -\end{funcdesc} - -\begin{funcdesc}{do_itemhit}{item\, event} -Item number \var{item} was hit. You are responsible for redrawing -toggle buttons, etc. -\end{funcdesc} - diff --git a/Doc/myformat.perl b/Doc/myformat.perl deleted file mode 100644 index bfb482144f..0000000000 --- a/Doc/myformat.perl +++ /dev/null @@ -1,153 +0,0 @@ -# myformat.perl by Guido van Rossum <guido@cwi.nl> 25 Jan 1994 -# -# Extension to LaTeX2HTML for documents using myformat.sty. -# Subroutines of the form do_cmd_<name> here define translations -# for LaTeX commands \<name> defined in the corresponding .sty file. -# -# XXX Not complete: \indexii etc.; \funcitem etc. - -package main; - -# \bcode and \ecode brackets around verbatim - -sub do_cmd_bcode{ @_[0]; } -sub do_cmd_ecode{ @_[0]; } - -# words typeset in a special way (not in HTML though) - -sub do_cmd_ABC{ join('', 'ABC', @_[0]); } -sub do_cmd_UNIX{ join('', 'Unix', @_[0]); } -sub do_cmd_ASCII{ join('', 'ASCII', @_[0]); } -sub do_cmd_C{ join('', 'C', @_[0]); } -sub do_cmd_Cpp{ join('', 'C++', @_[0]); } -sub do_cmd_EOF{ join('', 'EOF', @_[0]); } - -# texinfo-like formatting commands: \code{...} etc. - -sub do_cmd_code{ - local($_) = @_; - s/(<#[0-9]+#>)(.*)(\1)/<CODE>\2<\/CODE>/; - $_; -} - -sub do_cmd_kbd{ - local($_) = @_; - s/(<#[0-9]+#>)(.*)(\1)/<KBD>\2<\/KBD>/; - $_; -} - -sub do_cmd_key{ - local($_) = @_; - s/(<#[0-9]+#>)(.*)(\1)/<TT>\2<\/TT>/; - $_; -} - -sub do_cmd_samp{ - local($_) = @_; - s/(<#[0-9]+#>)(.*)(\1)/`<SAMP>\2<\/SAMP>'/; - $_; -} - -sub do_cmd_var{ - local($_) = @_; - s/(<#[0-9]+#>)(.*)(\1)/<VAR>\2<\/VAR>/; - $_; -} - -sub do_cmd_file{ - local($_) = @_; - s/(<#[0-9]+#>)(.*)(\1)/`<CODE>\2<\/CODE>'/; - $_; -} - -sub do_cmd_dfn{ - local($_) = @_; - s/(<#[0-9]+#>)(.*)(\1)/<I><DFN>\2<\/DFN><\/I>/; - $_; -} - -sub do_cmd_emph{ - local($_) = @_; - s/(<#[0-9]+#>)(.*)(\1)/<EM>\2<\/EM>/; - $_; -} - -sub do_cmd_strong{ - local($_) = @_; - s/(<#[0-9]+#>)(.*)(\1)/<STRONG>\2<\/STRONG>/; - $_; -} - -# index commands - -sub do_cmd_indexii{ - local($_) = @_; - s/$next_pair_pr_rx//o; - local($br_id1, $str1) = ($1, $2); - s/$next_pair_pr_rx//o; - local($br_id2, $str2) = ($1, $2); - join('', &make_index_entry($br_id1, "$str1 $str2"), - &make_index_entry($br_id2, "$str2, $str1"), $_); -} - -sub do_cmd_indexiii{ - local($_) = @_; - s/$next_pair_pr_rx//o; - local($br_id1, $str1) = ($1, $2); - s/$next_pair_pr_rx//o; - local($br_id2, $str2) = ($1, $2); - s/$next_pair_pr_rx//o; - local($br_id3, $str3) = ($1, $2); - join('', &make_index_entry($br_id1, "$str1 $str2 $str3"), - &make_index_entry($br_id2, "$str2 $str3, $str1"), - &make_index_entry($br_id3, "$str3, $str1 $str2"), - $_); -} - -sub do_cmd_indexiv{ - local($_) = @_; - s/$next_pair_pr_rx//o; - local($br_id1, $str1) = ($1, $2); - s/$next_pair_pr_rx//o; - local($br_id2, $str2) = ($1, $2); - s/$next_pair_pr_rx//o; - local($br_id3, $str3) = ($1, $2); - s/$next_pair_pr_rx//o; - local($br_id4, $str4) = ($1, $2); - join('', &make_index_entry($br_id1, "$str1 $str2 $str3 $str4"), - &make_index_entry($br_id2, "$str2 $str3 $str4, $str1"), - &make_index_entry($br_id3, "$str3 $str4, $str1 $str2"), - &make_index_entry($br_id4, "$str4, $str1 $str2 $str3"), - $_); -} - -sub do_cmd_ttindex{ - &do_cmd_index(@_); -} - -sub my_typed_index_helper{ - local($word, $_) = @_; - s/$next_pair_pr_rx//o; - local($br_id, $str) = ($1, $2); - join('', &make_index_entry($br_id, "$str $word"), - &make_index_entry($br_id, "$word, $str"), $_); -} - -sub do_cmd_stindex{ &my_typed_index_helper('statement', @_); } -sub do_cmd_kwindex{ &my_typed_index_helper('keyword', @_); } -sub do_cmd_opindex{ &my_typed_index_helper('operator', @_); } -sub do_cmd_exindex{ &my_typed_index_helper('exception', @_); } -sub do_cmd_obindex{ &my_typed_index_helper('object', @_); } - -sub my_parword_index_helper{ - local($word, $_) = @_; - s/$next_pair_pr_rx//o; - local($br_id, $str) = ($1, $2); - join('', &make_index_entry($br_id, "$str ($word)"), $_); -} - -sub do_cmd_bifuncindex{ &my_parword_index_helper('built-in function', @_); } -sub do_cmd_bimodindex{ &my_parword_index_helper('built-in module', @_); } -sub do_cmd_bifuncindex{ &my_parword_index_helper('standard module', @_); } - -1; # This must be the last line diff --git a/Doc/myformat.sty b/Doc/myformat.sty deleted file mode 100644 index f1779cb445..0000000000 --- a/Doc/myformat.sty +++ /dev/null @@ -1,196 +0,0 @@ -% Style parameters and macros used by most documents here - -\input{a4wide.sty} % Take this out if it doesn't exist or doesn't work -\input{times.sty} % And this (at CWI, this uses PostScript fonts) - -% This has to be tuned each time the repair person takes the printer apart: -%\addtolength{\oddsidemargin}{-2.5mm} -%\addtolength{\evensidemargin}{-2.5mm} - -% Style parameters -\raggedbottom -\sloppy -\parindent = 0mm -\parskip = 2mm - -% Variable used by begin code command -\newlength{\codewidth} - -% Command to start a code block (follow this by \begin{verbatim}) -\newcommand{\bcode}{ - % Calculate the text width for the minipage: - \setlength{\codewidth}{\linewidth} - \addtolength{\codewidth}{-\parindent} - % - \par - \vspace{3mm} - \indent - \begin{minipage}[t]{\codewidth} -} - -% Command to end a code block (precede this by \end{verbatim}) -\newcommand{\ecode}{ - \end{minipage} - \vspace{3mm} - \par - \noindent -} - -% Underscores are not magic throughout the Python documentation. -% This still only gives the right effect in the tt font!!! -\def\_{\ifnum\fam=\ttfam \char'137\else{\tt\char'137}\fi} -\catcode`\_=12 -\catcode`\_=\active\def_{\ifnum\fam=\ttfam \char'137 \else{\tt\char'137}\fi} - -% Define \itembreak: force the text after an item to start on a new line -\newcommand{\itembreak}{ -\mbox{} -\\*[0mm] -} - -% Command to generate two index entries (using subentries) -\newcommand{\indexii}[2]{\index{#1!#2}\index{#2!#1}} - -% And three entries (using only one level of subentries) -\newcommand{\indexiii}[3]{\index{#1!#2 #3}\index{#2!#3, #1}\index{#3!#1 #2}} - -% And four (again, using only one level of subentries) -\newcommand{\indexiv}[4]{ -\index{#1!#2 #3 #4} -\index{#2!#3 #4, #1} -\index{#3!#4, #1 #2} -\index{#4!#1 #2 #3} -} - -% Command to generate a reference to a function, statement, keyword, operator -\newcommand{\stindex}[1]{\indexii{statement}{#1@{\tt#1}}} -\newcommand{\kwindex}[1]{\indexii{keyword}{#1@{\tt#1}}} -\newcommand{\opindex}[1]{\indexii{operator}{#1@{\tt#1}}} -\newcommand{\exindex}[1]{\indexii{exception}{#1@{\tt#1}}} -\newcommand{\obindex}[1]{\indexii{object}{#1}} -\newcommand{\bifuncindex}[1]{\index{#1@{\tt#1} (built-in function)}} - -% Add an index entry for a module -\newcommand{\modindex}[2]{\index{#1@{\tt#1} (#2module)}} -\newcommand{\bimodindex}[1]{\modindex{#1}{built-in }} -\newcommand{\stmodindex}[1]{\modindex{#1}{standard }} - -% Additional string for an index entry -\newcommand{\indexsubitem}{} -\newcommand{\ttindex}[1]{\index{#1@{\tt#1} \indexsubitem}} - -% Define \itemjoin: some negative vspace to join two items together -\newcommand{\itemjoin}{ -\mbox{} -\vspace{-\itemsep} -\vspace{-\parsep} -} - -% Define \funcitem{func}{args}: define a function item -\newcommand{\funcitem}[2]{% -\ttindex{#1}% -%\item[{\tt #1(#2)}] -\item[\code{#1(\varvars{#2})}] -\ -} - - -% from user-level, fulllineitems should be called as an environment -\def\fulllineitems{\list{}{\labelwidth \leftmargin \labelsep 0pt -\rightmargin 0pt \topsep -\parskip \partopsep \parskip -\itemsep -\parsep -\let\makelabel\itemnewline}} -\let\endfulllineitems\endlist - - -% funcdesc should be called as an \begin{funcdesc} ... \end{funcdesc} -\newcommand{\funcline}[2]{\item[\code{#1(\varvars{#2})}]\ttindex{#1}} -\newcommand{\funcdesc}[2]{\fulllineitems\funcline{#1}{#2}} -\let\endfuncdesc\endfulllineitems -\newcommand{\optional}[1]{{\ \Large[}{#1}\hspace{0.5mm}{\Large]}\ } - - -% same for excdesc -\newcommand{\excline}[1]{\item[\code{#1}]\ttindex{#1}} -\newcommand{\excdesc}[1]{\fulllineitems\excline{#1}} -\let\endexcdesc\endfulllineitems - -% same for datadesc -\newcommand{\dataline}[1]{\item[\code{#1}]\ttindex{#1}} -\newcommand{\datadesc}[1]{\fulllineitems\dataline{#1}} -\let\enddatadesc\endfulllineitems - - -% Define \dataitem{name}: define a data item -\newcommand{\dataitem}[1]{% -\ttindex{#1}% -\item[{\tt #1}] -\ -} - -% Define \excitem{name}: define an exception item -\newcommand{\excitem}[1]{% -\ttindex{#1}% -\item[{\tt #1}] -\itembreak -} - -\let\nodename=\label - -\newcommand{\ABC}{{\sc abc}} -\newcommand{\UNIX}{{\sc Unix}} -\newcommand{\ASCII}{{\sc ascii}} -%\newcommand{\C}{{\bf C}} -\newcommand{\Cpp}{C\protect\raisebox{.18ex}{++}} -\newcommand{\C}{C} -\newcommand{\EOF}{{\sc eof}} - -% code is the most difficult one... -%\frenchspacing removed, because \section, etc., can't handle it -\newcommand{\code}[1]{{\@vobeyspaces\@noligs\def\{{\char`\{}\def\}{\char`\}}\def\~{\char`\~}\def\^{\char`\^}\def\e{\char`\\}\def\${\char`\$}\def\#{\char`\#}\def\&{\char`\&}\def\%{\char`\%}% -\mbox{\tt #1}}} -%This one does not work -%%%% myspecials, same as dospecials, but without {, } and \ -%%%\def\myspecials{\do\ \do\$\do\&% -%%% \do\#\do\^\do\^^K\do\_\do\^^A\do\%\do\~} -%%%\newcommand{\code}[1]{\begingroup \catcode``=13 \@noligs -%%%\tt \let\do\@makeother \myspecials -%%%#1\endgroup} -\newcommand{\kbd}[1]{\mbox{\tt #1}} -\newcommand{\key}[1]{\mbox{\tt #1}} -\newcommand{\samp}[1]{\mbox{`\code{#1}'}} -\newcommand{\var}[1]{\mbox{\it#1\/}} -\let\file=\samp -\newcommand{\dfn}[1]{{\em #1\/}} -\newcommand{\emph}[1]{{\em #1\/}} -\newcommand{\strong}[1]{{\bf #1}} - -%\newcommand{\varvars}[1]{{\catcode`\,=\active\def,{\tt\char`\,\/tt}\var{#1}}} -%\newcommand{\varvars}[1]{{\def\,{\/{\tt\char`\,}}\var{#1}}} -\newcommand{\varvars}[1]{{\def\,{\/{\tt\char`\,}}\def\({\/{\tt\char`\(}}\def\){\/{\tt\char`\)}}\var{#1}}} - -\newif\iftexi\texifalse -%not supported yet%\newif\iflatex\latextrue - -\newenvironment{tableii}[4]{\begin{center}\def\lineii##1##2{\csname#2\endcsname{##1}&##2\\}\begin{tabular}{#1}\hline#3&#4\\ -\hline}{\hline\end{tabular}\end{center}} - -\newenvironment{tableiii}[5]{\begin{center}\def\lineiii##1##2##3{\csname#2\endcsname{##1}&##2&##3\\}\begin{tabular}{#1}\hline#3&#4&#5\\ -\hline}{\hline\end{tabular}\end{center}} - -\newcommand{\itemnewline}[1]{\@tempdima\linewidth -\advance\@tempdima \leftmargin\makebox[\@tempdima][l]{#1}} - -\newcommand{\sectcode}[1]{{\tt #1}} -%%% -%%%\let\orgchapter\chapter -%%%\def\chapter#1{{\let\code\sectcode\orgchapter{#1}}} -%%%\let\orgsection\section -%%%\def\section#1{{\let\code\sectcode\orgsection{#1}}} -%%%\let\orgsubsection\subsection -%%%\def\subsection#1{{\let\code\sectcode\orgsubsection{#1}}} -%%%\let\orgsubsubsection\subsubsection -%%%\def\subsubsection#1{{\let\code\sectcode\orgsubsubsection{#1}}} -%%%\let\orgsubsubsubsection\subsubsubsection -%%%\def\subsubsubsection#1{{\let\code\sectcode\orgsubsubsubsection{#1}}} - diff --git a/Doc/partparse.py b/Doc/partparse.py deleted file mode 100644 index 6128bbfaf9..0000000000 --- a/Doc/partparse.py +++ /dev/null @@ -1,2165 +0,0 @@ -# -# partparse.py: parse a by-Guido-written-and-by-Jan-Hein-edited LaTeX file, -# and generate texinfo source. -# -# This is *not* a good example of good programming practices. In fact, this -# file could use a complete rewrite, in order to become faster, more -# easy extensible and maintainable. -# -# However, I added some comments on a few places for the pityful person who -# would ever need to take a look into this file. -# -# Have I been clear enough?? -# -# -jh - - -import sys, string, regex, getopt, os - -# Different parse modes for phase 1 -MODE_REGULAR = 0 -MODE_VERBATIM = 1 -MODE_CS_SCAN = 2 -MODE_COMMENT = 3 -MODE_MATH = 4 -MODE_DMATH = 5 -MODE_GOBBLEWHITE = 6 - -the_modes = MODE_REGULAR, MODE_VERBATIM, MODE_CS_SCAN, MODE_COMMENT, \ - MODE_MATH, MODE_DMATH, MODE_GOBBLEWHITE - -# Show the neighbourhood of the scanned buffer -def epsilon(buf, where): - wmt, wpt = where - 10, where + 10 - if wmt < 0: - wmt = 0 - if wpt > len(buf): - wpt = len(buf) - return ' Context ' + `buf[wmt:where]` + '.' + `buf[where:wpt]` + '.' - -# Should return the line number. never worked -def lin(): - global lineno - return ' Line ' + `lineno` + '.' - -# Displays the recursion level. -def lv(lvl): - return ' Level ' + `lvl` + '.' - -# Combine the three previous functions. Used often. -def lle(lvl, buf, where): - return lv(lvl) + lin() + epsilon(buf, where) - - -# This class is only needed for _symbolic_ representation of the parse mode. -class Mode: - def init(self, arg): - if arg not in the_modes: - raise ValueError, 'mode not in the_modes' - self.mode = arg - return self - - def __cmp__(self, other): - if type(self) != type(other): - other = mode(other) - return cmp(self.mode, other.mode) - - def __repr__(self): - if self.mode == MODE_REGULAR: - return 'MODE_REGULAR' - elif self.mode == MODE_VERBATIM: - return 'MODE_VERBATIM' - elif self.mode == MODE_CS_SCAN: - return 'MODE_CS_SCAN' - elif self.mode == MODE_COMMENT: - return 'MODE_COMMENT' - elif self.mode == MODE_MATH: - return 'MODE_MATH' - elif self.mode == MODE_DMATH: - return 'MODE_DMATH' - elif self.mode == MODE_GOBBLEWHITE: - return 'MODE_GOBBLEWHITE' - else: - raise ValueError, 'mode not in the_modes' - -# just a wrapper around a class initialisation -def mode(arg): - return Mode().init(arg) - - -# After phase 1, the text consists of chunks, with a certain type -# this type will be assigned to the chtype member of the chunk -# the where-field contains the file position where this is found -# and the data field contains (1): a tuple describing start- end end -# positions of the substring (can be used as slice for the buf-variable), -# (2) just a string, mostly generated by the changeit routine, -# or (3) a list, describing a (recursive) subgroup of chunks -PLAIN = 0 # ASSUME PLAINTEXT, data = the text -GROUP = 1 # GROUP ({}), data = [chunk, chunk,..] -CSNAME = 2 # CONTROL SEQ TOKEN, data = the command -COMMENT = 3 # data is the actual comment -DMATH = 4 # DISPLAYMATH, data = [chunk, chunk,..] -MATH = 5 # MATH, see DISPLAYMATH -OTHER = 6 # CHAR WITH CATCODE OTHER, data = char -ACTIVE = 7 # ACTIVE CHAR -GOBBLEDWHITE = 8 # Gobbled LWSP, after CSNAME -ENDLINE = 9 # END-OF-LINE, data = '\n' -DENDLINE = 10 # DOUBLE EOL, data='\n', indicates \par -ENV = 11 # LaTeX-environment - # data =(envname,[ch,ch,ch,.]) -CSLINE = 12 # for texi: next chunk will be one group - # of args. Will be set all on 1 line -IGNORE = 13 # IGNORE this data -ENDENV = 14 # TEMP END OF GROUP INDICATOR -IF = 15 # IF-directive - # data = (flag,negate,[ch, ch, ch,...]) -the_types = PLAIN, GROUP, CSNAME, COMMENT, DMATH, MATH, OTHER, ACTIVE, \ - GOBBLEDWHITE, ENDLINE, DENDLINE, ENV, CSLINE, IGNORE, ENDENV, IF - -# class, just to display symbolic name -class ChunkType: - def init(self, chunk_type): - if chunk_type not in the_types: - raise 'ValueError', 'chunk_type not in the_types' - self.chunk_type = chunk_type - return self - - def __cmp__(self, other): - if type(self) != type(other): - other = chunk_type(other) - return cmp(self.chunk_type, other.chunk_type) - - def __repr__(self): - if self.chunk_type == PLAIN: - return 'PLAIN' - elif self.chunk_type == GROUP: - return 'GROUP' - elif self.chunk_type == CSNAME: - return 'CSNAME' - elif self.chunk_type == COMMENT: - return 'COMMENT' - elif self.chunk_type == DMATH: - return 'DMATH' - elif self.chunk_type == MATH: - return 'MATH' - elif self.chunk_type == OTHER: - return 'OTHER' - elif self.chunk_type == ACTIVE: - return 'ACTIVE' - elif self.chunk_type == GOBBLEDWHITE: - return 'GOBBLEDWHITE' - elif self.chunk_type == DENDLINE: - return 'DENDLINE' - elif self.chunk_type == ENDLINE: - return 'ENDLINE' - elif self.chunk_type == ENV: - return 'ENV' - elif self.chunk_type == CSLINE: - return 'CSLINE' - elif self.chunk_type == IGNORE: - return 'IGNORE' - elif self.chunk_type == ENDENV: - return 'ENDENV' - elif self.chunk_type == IF: - return 'IF' - else: - raise ValueError, 'chunk_type not in the_types' - -# ...and the wrapper -def chunk_type(type): - return ChunkType().init(type) - -# store a type object of the ChunkType-class-instance... -chunk_type_type = type(chunk_type(0)) - -# this class contains a part of the parsed buffer -class Chunk: - def init(self, chtype, where, data): - if type(chtype) != chunk_type_type: - chtype = chunk_type(chtype) - self.chtype = chtype - if type(where) != type(0): - raise TypeError, '\'where\' is not a number' - self.where = where - self.data = data - ##print 'CHUNK', self - return self - - def __repr__(self): - return 'chunk' + `self.chtype, self.where, self.data` - -# and the wrapper -def chunk(chtype, where, data): - return Chunk().init(chtype, where, data) - - - -error = 'partparse.error' - -# -# TeX's catcodes... -# -CC_ESCAPE = 0 -CC_LBRACE = 1 -CC_RBRACE = 2 -CC_MATHSHIFT = 3 -CC_ALIGNMENT = 4 -CC_ENDLINE = 5 -CC_PARAMETER = 6 -CC_SUPERSCRIPT = 7 -CC_SUBSCRIPT = 8 -CC_IGNORE = 9 -CC_WHITE = 10 -CC_LETTER = 11 -CC_OTHER = 12 -CC_ACTIVE = 13 -CC_COMMENT = 14 -CC_INVALID = 15 - -# and the names -cc_names = [\ - 'CC_ESCAPE', \ - 'CC_LBRACE', \ - 'CC_RBRACE', \ - 'CC_MATHSHIFT', \ - 'CC_ALIGNMENT', \ - 'CC_ENDLINE', \ - 'CC_PARAMETER', \ - 'CC_SUPERSCRIPT', \ - 'CC_SUBSCRIPT', \ - 'CC_IGNORE', \ - 'CC_WHITE', \ - 'CC_LETTER', \ - 'CC_OTHER', \ - 'CC_ACTIVE', \ - 'CC_COMMENT', \ - 'CC_INVALID', \ - ] - -# Show a list of catcode-name-symbols -def pcl(codelist): - result = '' - for i in codelist: - result = result + cc_names[i] + ', ' - return '[' + result[:-2] + ']' - -# the name of the catcode (ACTIVE, OTHER, etc.) -def pc(code): - return cc_names[code] - - -# Which catcodes make the parser stop parsing regular plaintext -regular_stopcodes = [CC_ESCAPE, CC_LBRACE, CC_RBRACE, CC_MATHSHIFT, \ - CC_ALIGNMENT, CC_PARAMETER, CC_SUPERSCRIPT, CC_SUBSCRIPT, \ - CC_IGNORE, CC_ACTIVE, CC_COMMENT, CC_INVALID, CC_ENDLINE] - -# same for scanning a control sequence name -csname_scancodes = [CC_LETTER] - -# same for gobbling LWSP -white_scancodes = [CC_WHITE] -##white_scancodes = [CC_WHITE, CC_ENDLINE] - -# make a list of all catcode id's, except for catcode ``other'' -all_but_other_codes = range(16) -del all_but_other_codes[CC_OTHER] -##print all_but_other_codes - -# when does a comment end -comment_stopcodes = [CC_ENDLINE] - -# gather all characters together, specified by a list of catcodes -def code2string(cc, codelist): - ##print 'code2string: codelist = ' + pcl(codelist), - result = '' - for category in codelist: - if cc[category]: - result = result + cc[category] - ##print 'result = ' + `result` - return result - -# automatically generate all characters of catcode other, being the -# complement set in the ASCII range (128 characters) -def make_other_codes(cc): - otherchars = range(256) # could be made 256, no problem - for category in all_but_other_codes: - if cc[category]: - for c in cc[category]: - otherchars[ord(c)] = None - result = '' - for i in otherchars: - if i != None: - result = result + chr(i) - return result - -# catcode dump (which characters have which catcodes). -def dump_cc(name, cc): - ##print '\t' + name - ##print '=' * (8+len(name)) - if len(cc) != 16: - raise TypeError, 'cc not good cat class' -## for i in range(16): -## print pc(i) + '\t' + `cc[i]` - - -# In the beginning,.... -epoch_cc = [None] * 16 -##dump_cc('epoch_cc', epoch_cc) - - -# INITEX -initex_cc = epoch_cc[:] -initex_cc[CC_ESCAPE] = '\\' -initex_cc[CC_ENDLINE], initex_cc[CC_IGNORE], initex_cc[CC_WHITE] = \ - '\n', '\0', ' ' -initex_cc[CC_LETTER] = string.uppercase + string.lowercase -initex_cc[CC_COMMENT], initex_cc[CC_INVALID] = '%', '\x7F' -#initex_cc[CC_OTHER] = make_other_codes(initex_cc) I don't need them, anyway -##dump_cc('initex_cc', initex_cc) - - -# LPLAIN: LaTeX catcode setting (see lplain.tex) -lplain_cc = initex_cc[:] -lplain_cc[CC_LBRACE], lplain_cc[CC_RBRACE] = '{', '}' -lplain_cc[CC_MATHSHIFT] = '$' -lplain_cc[CC_ALIGNMENT] = '&' -lplain_cc[CC_PARAMETER] = '#' -lplain_cc[CC_SUPERSCRIPT] = '^\x0B' # '^' and C-k -lplain_cc[CC_SUBSCRIPT] = '_\x01' # '_' and C-a -lplain_cc[CC_WHITE] = lplain_cc[CC_WHITE] + '\t' -lplain_cc[CC_ACTIVE] = '~\x0C' # '~' and C-l -lplain_cc[CC_OTHER] = make_other_codes(lplain_cc) -##dump_cc('lplain_cc', lplain_cc) - - -# Guido's LaTeX environment catcoded '_' as ``other'' -# my own purpose catlist -my_cc = lplain_cc[:] -my_cc[CC_SUBSCRIPT] = my_cc[CC_SUBSCRIPT][1:] # remove '_' here -my_cc[CC_OTHER] = my_cc[CC_OTHER] + '_' # add it to OTHER list -dump_cc('my_cc', my_cc) - - - -# needed for un_re, my equivalent for regexp-quote in Emacs -re_meaning = '\\[]^$' - -def un_re(str): - result = '' - for i in str: - if i in re_meaning: - result = result + '\\' - result = result + i - return result - -# NOTE the negate ('^') operator in *some* of the regexps below -def make_rc_regular(cc): - # problems here if '[]' are included!! - return regex.compile('[' + code2string(cc, regular_stopcodes) + ']') - -def make_rc_cs_scan(cc): - return regex.compile('[^' + code2string(cc, csname_scancodes) + ']') - -def make_rc_comment(cc): - return regex.compile('[' + code2string(cc, comment_stopcodes) + ']') - -def make_rc_endwhite(cc): - return regex.compile('[^' + code2string(cc, white_scancodes) + ']') - - - -# regular: normal mode: -rc_regular = make_rc_regular(my_cc) - -# scan: scan a command sequence e.g. `newlength' or `mbox' or `;', `,' or `$' -rc_cs_scan = make_rc_cs_scan(my_cc) -rc_comment = make_rc_comment(my_cc) -rc_endwhite = make_rc_endwhite(my_cc) - - -# parseit (BUF, PARSEMODE=mode(MODE_REGULAR), START=0, RECURSION-LEVEL=0) -# RECURSION-LEVEL will is incremented on entry. -# result contains the list of chunks returned -# together with this list, the buffer position is returned - -# RECURSION-LEVEL will be set to zero *again*, when recursively a -# {,D}MATH-mode scan has been enetered. -# This has been done in order to better check for environment-mismatches - -def parseit(buf, *rest): - global lineno - - if len(rest) == 3: - parsemode, start, lvl = rest - elif len(rest) == 2: - parsemode, start, lvl = rest + (0, ) - elif len(rest) == 1: - parsemode, start, lvl = rest + (0, 0) - elif len(rest) == 0: - parsemode, start, lvl = mode(MODE_REGULAR), 0, 0 - else: - raise TypeError, 'usage: parseit(buf[, parsemode[, start[, level]]])' - result = [] - end = len(buf) - if lvl == 0 and parsemode == mode(MODE_REGULAR): - lineno = 1 - lvl = lvl + 1 - - ##print 'parseit(' + epsilon(buf, start) + ', ' + `parsemode` + ', ' + `start` + ', ' + `lvl` + ')' - - # - # some of the more regular modes... - # - - if parsemode in (mode(MODE_REGULAR), mode(MODE_DMATH), mode(MODE_MATH)): - cstate = [] - newpos = start - curpmode = parsemode - while 1: - where = newpos - #print '\tnew round: ' + epsilon(buf, where) - if where == end: - if lvl > 1 or curpmode != mode(MODE_REGULAR): - # not the way we started... - raise EOFError, 'premature end of file.' + lle(lvl, buf, where) - # the real ending of lvl-1 parse - return end, result - - pos = rc_regular.search(buf, where) - - if pos < 0: - pos = end - - if pos != where: - newpos, c = pos, chunk(PLAIN, where, (where, pos)) - result.append(c) - continue - - - # - # ok, pos == where and pos != end - # - foundchar = buf[where] - if foundchar in my_cc[CC_LBRACE]: - # recursive subgroup parse... - newpos, data = parseit(buf, curpmode, where+1, lvl) - result.append(chunk(GROUP, where, data)) - - elif foundchar in my_cc[CC_RBRACE]: - if lvl <= 1: - raise error, 'ENDGROUP while in base level.' + lle(lvl, buf, where) - if lvl == 1 and mode != mode(MODE_REGULAR): - raise error, 'endgroup while in math mode. +lin() + epsilon(buf, where)' - return where + 1, result - - elif foundchar in my_cc[CC_ESCAPE]: - # - # call the routine that actually deals with - # this problem. If do_ret is None, than - # return the value of do_ret - # - # Note that handle_cs might call this routine - # recursively again... - # - do_ret, newpos = handlecs(buf, where, \ - curpmode, lvl, result, end) - if do_ret != None: - return do_ret - - elif foundchar in my_cc[CC_COMMENT]: - newpos, data = parseit(buf, \ - mode(MODE_COMMENT), where+1, lvl) - result.append(chunk(COMMENT, where, data)) - - elif foundchar in my_cc[CC_MATHSHIFT]: - # note that recursive calls to math-mode - # scanning are called with recursion-level 0 - # again, in order to check for bad mathend - # - if where + 1 != end and \ - buf[where + 1] in \ - my_cc[CC_MATHSHIFT]: - # - # double mathshift, e.g. '$$' - # - if curpmode == mode(MODE_REGULAR): - newpos, data = parseit(buf, \ - mode(MODE_DMATH), \ - where+2, 0) - result.append(chunk(DMATH, \ - where, data)) - elif curpmode == mode(MODE_MATH): - raise error, 'wrong math delimiiter' + lin() + epsilon(buf, where) - elif lvl != 1: - raise error, 'bad mathend.' + \ - lle(lvl, buf, where) - else: - return where + 2, result - else: - # - # single math shift, e.g. '$' - # - if curpmode == mode(MODE_REGULAR): - newpos, data = parseit(buf, \ - mode(MODE_MATH), \ - where+1, 0) - result.append(chunk(MATH, \ - where, data)) - elif curpmode == mode(MODE_DMATH): - raise error, 'wrong math delimiiter' + lin() + epsilon(buf, where) - elif lvl != 1: - raise error, 'bad mathend.' + \ - lv(lvl, buf, where) - else: - return where + 1, result - - elif foundchar in my_cc[CC_IGNORE]: - print 'warning: ignored char', `foundchar` - newpos = where + 1 - - elif foundchar in my_cc[CC_ACTIVE]: - result.append(chunk(ACTIVE, where, foundchar)) - newpos = where + 1 - - elif foundchar in my_cc[CC_INVALID]: - raise error, 'invalid char ' + `foundchar` - newpos = where + 1 - - elif foundchar in my_cc[CC_ENDLINE]: - # - # after an end of line, eat the rest of - # whitespace on the beginning of the next line - # this is what LaTeX more or less does - # - # also, try to indicate double newlines (\par) - # - lineno = lineno + 1 - savedwhere = where - newpos, dummy = parseit(buf, mode(MODE_GOBBLEWHITE), where + 1, lvl) - if newpos != end and buf[newpos] in \ - my_cc[CC_ENDLINE]: - result.append(chunk(DENDLINE, \ - savedwhere, foundchar)) - else: - result.append(chunk(ENDLINE, \ - savedwhere, foundchar)) - else: - result.append(chunk(OTHER, where, foundchar)) - newpos = where + 1 - - elif parsemode == mode(MODE_CS_SCAN): - # - # scan for a control sequence token. `\ape', `\nut' or `\%' - # - if start == end: - raise EOFError, 'can\'t find end of csname' - pos = rc_cs_scan.search(buf, start) - if pos < 0: - pos = end - if pos == start: - # first non-letter right where we started the search - # ---> the control sequence name consists of one single - # character. Also: don't eat white space... - if buf[pos] in my_cc[CC_ENDLINE]: - lineno = lineno + 1 - pos = pos + 1 - return pos, (start, pos) - else: - spos = pos - if buf[pos] == '\n': - lineno = lineno + 1 - spos = pos + 1 - pos2, dummy = parseit(buf, \ - mode(MODE_GOBBLEWHITE), spos, lvl) - return pos2, (start, pos) - - elif parsemode == mode(MODE_GOBBLEWHITE): - if start == end: - return start, '' - pos = rc_endwhite.search(buf, start) - if pos < 0: - pos = start - return pos, (start, pos) - - elif parsemode == mode(MODE_COMMENT): - pos = rc_comment.search(buf, start) - lineno = lineno + 1 - if pos < 0: - print 'no newline perhaps?' - raise EOFError, 'can\'t find end of comment' - pos = pos + 1 - pos2, dummy = parseit(buf, mode(MODE_GOBBLEWHITE), pos, lvl) - return pos2, (start, pos) - - - else: - raise error, 'Unknown mode (' + `parsemode` + ')' - - -#moreresult = cswitch(buf[x1:x2], buf, newpos, parsemode, lvl) - -#boxcommands = 'mbox', 'fbox' -#defcommands = 'def', 'newcommand' - -endverbstr = '\\end{verbatim}' - -re_endverb = regex.compile(un_re(endverbstr)) - -# -# handlecs: helper function for parseit, for the special thing we might -# wanna do after certain command control sequences -# returns: None or return_data, newpos -# -# in the latter case, the calling function is instructed to immediately -# return with the data in return_data -# -def handlecs(buf, where, curpmode, lvl, result, end): - global lineno - - # get the control sequence name... - newpos, data = parseit(buf, mode(MODE_CS_SCAN), where+1, lvl) - saveddata = data - - if s(buf, data) in ('begin', 'end'): - # skip the expected '{' and get the LaTeX-envname '}' - newpos, data = parseit(buf, mode(MODE_REGULAR), newpos+1, lvl) - if len(data) != 1: - raise error, 'expected 1 chunk of data.' + \ - lle(lvl, buf, where) - - # yucky, we've got an environment - envname = s(buf, data[0].data) - ##print 'FOUND ' + s(buf, saveddata) + '. Name ' + `envname` + '.' + lv(lvl) - if s(buf, saveddata) == 'begin' and envname == 'verbatim': - # verbatim deserves special treatment - pos = re_endverb.search(buf, newpos) - if pos < 0: - raise error, `endverbstr` + ' not found.' + lle(lvl, buf, where) - result.append(chunk(ENV, where, (envname, [chunk(PLAIN, newpos, (newpos, pos))]))) - newpos = pos + len(endverbstr) - - elif s(buf, saveddata) == 'begin': - # start parsing recursively... If that parse returns - # from an '\end{...}', then should the last item of - # the returned data be a string containing the ended - # environment - newpos, data = parseit(buf, curpmode, newpos, lvl) - if not data or type(data[-1]) != type(''): - raise error, 'missing \'end\'' + lle(lvl, buf, where) + epsilon(buf, newpos) - retenv = data[-1] - del data[-1] - if retenv != envname: - #[`retenv`, `envname`] - raise error, 'environments do not match.' + \ - lle(lvl, buf, where) + \ - epsilon(buf, newpos) - result.append(chunk(ENV, where, (retenv, data))) - else: - # 'end'... append the environment name, as just - # pointed out, and order parsit to return... - result.append(envname) - ##print 'POINT of return: ' + epsilon(buf, newpos) - # the tuple will be returned by parseit - return (newpos, result), newpos - - # end of \begin ... \end handling - - elif s(buf, data)[0:2] == 'if': - # another scary monster: the 'if' directive - flag = s(buf, data)[2:] - - # recursively call parseit, just like environment above.. - # the last item of data should contain the if-termination - # e.g., 'else' of 'fi' - newpos, data = parseit(buf, curpmode, newpos, lvl) - if not data or data[-1] not in ('else', 'fi'): - raise error, 'wrong if... termination' + \ - lle(lvl, buf, where) + epsilon(buf, newpos) - - ifterm = data[-1] - del data[-1] - # 0 means dont_negate flag - result.append(chunk(IF, where, (flag, 0, data))) - if ifterm == 'else': - # do the whole thing again, there is only one way - # to end this one, by 'fi' - newpos, data = parseit(buf, curpmode, newpos, lvl) - if not data or data[-1] not in ('fi', ): - raise error, 'wrong if...else... termination' \ - + lle(lvl, buf, where) \ - + epsilon(buf, newpos) - - ifterm = data[-1] - del data[-1] - result.append(chunk(IF, where, (flag, 1, data))) - #done implicitely: return None, newpos - - elif s(buf, data) in ('else', 'fi'): - result.append(s(buf, data)) - # order calling party to return tuple - return (newpos, result), newpos - - # end of \if, \else, ... \fi handling - - elif s(buf, saveddata) == 'verb': - x2 = saveddata[1] - result.append(chunk(CSNAME, where, data)) - if x2 == end: - raise error, 'premature end of command.' + lle(lvl, buf, where) - delimchar = buf[x2] - ##print 'VERB: delimchar ' + `delimchar` - pos = regex.compile(un_re(delimchar)).search(buf, x2 + 1) - if pos < 0: - raise error, 'end of \'verb\' argument (' + \ - `delimchar` + ') not found.' + \ - lle(lvl, buf, where) - result.append(chunk(GROUP, x2, [chunk(PLAIN, x2+1, (x2+1, pos))])) - newpos = pos + 1 - else: - result.append(chunk(CSNAME, where, data)) - return None, newpos - -# this is just a function to get the string value if the possible data-tuple -def s(buf, data): - if type(data) == type(''): - return data - if len(data) != 2 or not (type(data[0]) == type(data[1]) == type(0)): - raise TypeError, 'expected tuple of 2 integers' - x1, x2 = data - return buf[x1:x2] - - -##length, data1, i = getnextarg(length, buf, pp, i + 1) - -# make a deep-copy of some chunks -def crcopy(r): - result = [] - for x in r: - result.append(chunkcopy(x)) - return result - - - -# copy a chunk, would better be a method of class Chunk... -def chunkcopy(ch): - if ch.chtype == chunk_type(GROUP): - listc = ch.data[:] - for i in range(len(listc)): - listc[i] = chunkcopy(listc[i]) - return chunk(GROUP, ch.where, listc) - else: - return chunk(ch.chtype, ch.where, ch.data) - - -# get next argument for TeX-macro, flatten a group (insert between) -# or return Command Sequence token, or give back one character -def getnextarg(length, buf, pp, item): - - ##wobj = Wobj().init() - ##dumpit(buf, wobj.write, pp[item:min(length, item + 5)]) - ##print 'GETNEXTARG, (len, item) =', `length, item` + ' ---> ' + wobj.data + ' <---' - - while item < length and pp[item].chtype == chunk_type(ENDLINE): - del pp[item] - length = length - 1 - if item >= length: - raise error, 'no next arg.' + epsilon(buf, pp[-1].where) - if pp[item].chtype == chunk_type(GROUP): - newpp = pp[item].data - del pp[item] - length = length - 1 - changeit(buf, newpp) - length = length + len(newpp) - pp[item:item] = newpp - item = item + len(newpp) - if len(newpp) < 10: - wobj = Wobj().init() - dumpit(buf, wobj.write, newpp) - ##print 'GETNEXTARG: inserted ' + `wobj.data` - return length, item - elif pp[item].chtype == chunk_type(PLAIN): - #grab one char - print 'WARNING: grabbing one char' - if len(s(buf, pp[item].data)) > 1: - pp.insert(item, chunk(PLAIN, pp[item].where, s(buf, pp[item].data)[:1])) - item, length = item+1, length+1 - pp[item].data = s(buf, pp[item].data)[1:] - else: - item = item+1 - return length, item - else: - ch = pp[item] - try: - str = `s(buf, ch.data)` - except TypeError: - str = `ch.data` - if len(str) > 400: - str = str[:400] + '...' - print 'GETNEXTARG:', ch.chtype, 'not handled, data ' + str - return length, item - - -# this one is needed to find the end of LaTeX's optional argument, like -# item[...] -re_endopt = regex.compile(']') - -# get a LaTeX-optional argument, you know, the square braces '[' and ']' -def getoptarg(length, buf, pp, item): - - wobj = Wobj().init() - dumpit(buf, wobj.write, pp[item:min(length, item + 5)]) - ##print 'GETOPTARG, (len, item) =', `length, item` + ' ---> ' + wobj.data + ' <---' - - if item >= length or \ - pp[item].chtype != chunk_type(PLAIN) or \ - s(buf, pp[item].data)[0] != '[': - return length, item - - pp[item].data = s(buf, pp[item].data)[1:] - if len(pp[item].data) == 0: - del pp[item] - length = length-1 - - while 1: - if item == length: - raise error, 'No end of optional arg found' - if pp[item].chtype == chunk_type(PLAIN): - text = s(buf, pp[item].data) - pos = re_endopt.search(text) - if pos >= 0: - pp[item].data = text[:pos] - if pos == 0: - del pp[item] - length = length-1 - else: - item=item+1 - text = text[pos+1:] - - while text and text[0] in ' \t': - text = text[1:] - - if text: - pp.insert(item, chunk(PLAIN, 0, text)) - length = length + 1 - return length, item - - item = item+1 - - -# Wobj just add write-requests to the ``data'' attribute -class Wobj: - def init(self): - self.data = '' - return self - def write(self, data): - self.data = self.data + data - -# ignore these commands -ignoredcommands = ('bcode', 'ecode') -# map commands like these to themselves as plaintext -wordsselves = ('UNIX', 'ABC', 'C', 'ASCII', 'EOF', 'LaTeX') -# \{ --> {, \} --> }, etc -themselves = ('{', '}', '.', '@', ' ', '\n') + wordsselves -# these ones also themselves (see argargs macro in myformat.sty) -inargsselves = (',', '[', ']', '(', ')') -# this is how *I* would show the difference between emph and strong -# code 1 means: fold to uppercase -markcmds = {'code': ('', ''), 'var': 1, 'emph': ('_', '_'), \ - 'strong': ('*', '*')} - -# recognise patter {\FONTCHANGE-CMD TEXT} to \MAPPED-FC-CMD{TEXT} -fontchanges = {'rm': 'r', 'it': 'i', 'em': 'emph', 'bf': 'b', 'tt': 't'} - -# transparent for these commands -for_texi = ('emph', 'var', 'strong', 'code', 'kbd', 'key', 'dfn', 'samp', - 'file', 'r', 'i', 't') - - -# try to remove macros and return flat text -def flattext(buf, pp): - pp = crcopy(pp) - ##print '---> FLATTEXT ' + `pp` - wobj = Wobj().init() - - i, length = 0, len(pp) - while 1: - if len(pp) != length: - raise 'FATAL', 'inconsistent length' - if i >= length: - break - ch = pp[i] - i = i+1 - if ch.chtype == chunk_type(PLAIN): - pass - elif ch.chtype == chunk_type(CSNAME): - if s(buf, ch.data) in themselves or hist.inargs and s(buf, ch.data) in inargsselves: - ch.chtype = chunk_type(PLAIN) - elif s(buf, ch.data) == 'e': - ch.chtype = chunk_type(PLAIN) - ch.data = '\\' - elif len(s(buf, ch.data)) == 1 \ - and s(buf, ch.data) in onlylatexspecial: - ch.chtype = chunk_type(PLAIN) - # if it is followed by an empty group, - # remove that group, it was needed for - # a true space - if i < length \ - and pp[i].chtype==chunk_type(GROUP) \ - and len(pp[i].data) == 0: - del pp[i] - length = length-1 - - elif s(buf, ch.data) in markcmds.keys(): - length, newi = getnextarg(length, buf, pp, i) - str = flattext(buf, pp[i:newi]) - del pp[i:newi] - length = length - (newi - i) - ch.chtype = chunk_type(PLAIN) - markcmd = s(buf, ch.data) - x = markcmds[markcmd] - if type(x) == type(()): - pre, after = x - str = pre+str+after - elif x == 1: - str = string.upper(str) - else: - raise 'FATAL', 'corrupt markcmds' - ch.data = str - else: - if s(buf, ch.data) not in ignoredcommands: - print 'WARNING: deleting command ' + `s(buf, ch.data)` - print 'PP' + `pp[i-1]` - del pp[i-1] - i, length = i-1, length-1 - elif ch.chtype == chunk_type(GROUP): - length, newi = getnextarg(length, buf, pp, i-1) - i = i-1 -## str = flattext(buf, crcopy(pp[i-1:newi])) -## del pp[i:newi] -## length = length - (newi - i) -## ch.chtype = chunk_type(PLAIN) -## ch.data = str - else: - pass - - dumpit(buf, wobj.write, pp) - ##print 'FLATTEXT: RETURNING ' + `wobj.data` - return wobj.data - -# try to generate node names (a bit shorter than the chapter title) -# note that the \nodename command (see elsewhere) overules these efforts -def invent_node_names(text): - words = string.split(text) - - ##print 'WORDS ' + `words` - - if len(words) == 2 \ - and string.lower(words[0]) == 'built-in' \ - and string.lower(words[1]) not in ('modules', 'functions'): - return words[1] - if len(words) == 3 and string.lower(words[1]) == 'module': - return words[2] - if len(words) == 3 and string.lower(words[1]) == 'object': - return string.join(words[0:2]) - if len(words) > 4 and string.lower(string.join(words[-4:])) == \ - 'methods and data attributes': - return string.join(words[:2]) - return text - -re_commas_etc = regex.compile('[,`\'@{}]') - -re_whitespace = regex.compile('[ \t]*') - - -##nodenamecmd = next_command_p(length, buf, pp, newi, 'nodename') - -# look if the next non-white stuff is also a command, resulting in skipping -# double endlines (DENDLINE) too, and thus omitting \par's -# Sometimes this is too much, maybe consider DENDLINE's as stop -def next_command_p(length, buf, pp, i, cmdname): - - while 1: - if i >= len(pp): - break - ch = pp[i] - i = i+1 - if ch.chtype == chunk_type(ENDLINE): - continue - if ch.chtype == chunk_type(DENDLINE): - continue - if ch.chtype == chunk_type(PLAIN): - if re_whitespace.search(s(buf, ch.data)) == 0 and \ - re_whitespace.match(s(buf, ch.data)) == len(s(buf, ch.data)): - continue - return -1 - if ch.chtype == chunk_type(CSNAME): - if s(buf, ch.data) == cmdname: - return i # _after_ the command - return -1 - return -1 - - -# things that are special to LaTeX, but not to texi.. -onlylatexspecial = '_~^$#&%' - -class Struct: pass - -hist = Struct() -out = Struct() - -def startchange(): - global hist, out - - hist.inenv = [] - hist.nodenames = [] - hist.cindex = [] - hist.inargs = 0 - hist.enumeratenesting, hist.itemizenesting = 0, 0 - - out.doublenodes = [] - out.doublecindeces = [] - - -spacech = [chunk(PLAIN, 0, ' ')] -commach = [chunk(PLAIN, 0, ', ')] -cindexch = [chunk(CSLINE, 0, 'cindex')] - -# the standard variation in symbols for itemize -itemizesymbols = ['bullet', 'minus', 'dots'] - -# same for enumerate -enumeratesymbols = ['1', 'A', 'a'] - -## -## \begin{ {func,data,exc}desc }{name}... -## the resulting texi-code is dependent on the contents of indexsubitem -## - -# indexsubitem: `['XXX', 'function'] -# funcdesc: -# deffn {`idxsi`} NAME (FUNCARGS) - -# indexsubitem: `['XXX', 'method']` -# funcdesc: -# defmethod {`idxsi[0]`} NAME (FUNCARGS) - -# indexsubitem: `['in', 'module', 'MODNAME']' -# datadesc: -# defcv data {`idxsi[1:]`} NAME -# excdesc: -# defcv exception {`idxsi[1:]`} NAME -# funcdesc: -# deffn {function of `idxsi[1:]`} NAME (FUNCARGS) - -# indexsubitem: `['OBJECT', 'attribute']' -# datadesc -# defcv attribute {`OBJECT`} NAME - - -## this routine will be called on \begin{funcdesc}{NAME}{ARGS} -## or \funcline{NAME}{ARGS} -## -def do_funcdesc(length, buf, pp, i): - startpoint = i-1 - ch = pp[startpoint] - wh = ch.where - length, newi = getnextarg(length, buf, pp, i) - funcname = chunk(GROUP, wh, pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - save = hist.inargs - hist.inargs = 1 - length, newi = getnextarg(length, buf, pp, i) - hist.inargs = save - del save - the_args = [chunk(PLAIN, wh, '()'[0])] + \ - pp[i:newi] + \ - [chunk(PLAIN, wh, '()'[1])] - del pp[i:newi] - length = length - (newi-i) - - idxsi = hist.indexsubitem # words - command = '' - cat_class = '' - if idxsi and idxsi[-1] in ('method', 'protocol'): - command = 'defmethod' - cat_class = string.join(idxsi[:-1]) - elif len(idxsi) == 2 and idxsi[1] == 'function': - command = 'deffn' - cat_class = string.join(idxsi) - elif len(idxsi) == 3 and idxsi[:2] == ['in', 'module']: - command = 'deffn' - cat_class = 'function of ' + string.join(idxsi[1:]) - - if not command: - raise error, 'don\'t know what to do with indexsubitem ' + `idxsi` - - ch.chtype = chunk_type(CSLINE) - ch.data = command - - cslinearg = [chunk(GROUP, wh, [chunk(PLAIN, wh, cat_class)])] - cslinearg.append(chunk(PLAIN, wh, ' ')) - cslinearg.append(funcname) - cslinearg.append(chunk(PLAIN, wh, ' ')) - l = len(cslinearg) - cslinearg[l:l] = the_args - - pp.insert(i, chunk(GROUP, wh, cslinearg)) - i, length = i+1, length+1 - hist.command = command - return length, i - - -## this routine will be called on \begin{excdesc}{NAME} -## or \excline{NAME} -## -def do_excdesc(length, buf, pp, i): - startpoint = i-1 - ch = pp[startpoint] - wh = ch.where - length, newi = getnextarg(length, buf, pp, i) - excname = chunk(GROUP, wh, pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - - idxsi = hist.indexsubitem # words - command = '' - cat_class = '' - class_class = '' - if len(idxsi) == 2 and idxsi[1] == 'exception': - command = 'defvr' - cat_class = string.join(idxsi) - elif len(idxsi) == 3 and idxsi[:2] == ['in', 'module']: - command = 'defcv' - cat_class = 'exception' - class_class = string.join(idxsi[1:]) - elif len(idxsi) == 4 and idxsi[:3] == ['exception', 'in', 'module']: - command = 'defcv' - cat_class = 'exception' - class_class = string.join(idxsi[2:]) - - - if not command: - raise error, 'don\'t know what to do with indexsubitem ' + `idxsi` - - ch.chtype = chunk_type(CSLINE) - ch.data = command - - cslinearg = [chunk(GROUP, wh, [chunk(PLAIN, wh, cat_class)])] - cslinearg.append(chunk(PLAIN, wh, ' ')) - if class_class: - cslinearg.append(chunk(GROUP, wh, [chunk(PLAIN, wh, class_class)])) - cslinearg.append(chunk(PLAIN, wh, ' ')) - cslinearg.append(excname) - - pp.insert(i, chunk(GROUP, wh, cslinearg)) - i, length = i+1, length+1 - hist.command = command - return length, i - -## same for datadesc or dataline... -def do_datadesc(length, buf, pp, i): - startpoint = i-1 - ch = pp[startpoint] - wh = ch.where - length, newi = getnextarg(length, buf, pp, i) - dataname = chunk(GROUP, wh, pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - - idxsi = hist.indexsubitem # words - command = '' - cat_class = '' - class_class = '' - if idxsi[-1] in ('attribute', 'option'): - command = 'defcv' - cat_class = idxsi[-1] - class_class = string.join(idxsi[:-1]) - elif len(idxsi) == 3 and idxsi[:2] == ['in', 'module']: - command = 'defcv' - cat_class = 'data' - class_class = string.join(idxsi[1:]) - elif len(idxsi) == 4 and idxsi[:3] == ['data', 'in', 'module']: - command = 'defcv' - cat_class = 'data' - class_class = string.join(idxsi[2:]) - - - if not command: - raise error, 'don\'t know what to do with indexsubitem ' + `idxsi` - - ch.chtype = chunk_type(CSLINE) - ch.data = command - - cslinearg = [chunk(GROUP, wh, [chunk(PLAIN, wh, cat_class)])] - cslinearg.append(chunk(PLAIN, wh, ' ')) - if class_class: - cslinearg.append(chunk(GROUP, wh, [chunk(PLAIN, wh, class_class)])) - cslinearg.append(chunk(PLAIN, wh, ' ')) - cslinearg.append(dataname) - - pp.insert(i, chunk(GROUP, wh, cslinearg)) - i, length = i+1, length+1 - hist.command = command - return length, i - - -# regular indices: those that are not set in tt font by default.... -regindices = ('cindex', ) - -# remove illegal characters from node names -def rm_commas_etc(text): - result = '' - changed = 0 - while 1: - pos = re_commas_etc.search(text) - if pos >= 0: - changed = 1 - result = result + text[:pos] - text = text[pos+1:] - else: - result = result + text - break - if changed: - print 'Warning: nodename changhed to ' + `result` - - return result - -# boolean flags -flags = {'texi': 1} - - -## -## changeit: the actual routine, that changes the contents of the parsed -## chunks -## - -def changeit(buf, pp): - global onlylatexspecial, hist, out - - i, length = 0, len(pp) - while 1: - # sanity check: length should always equal len(pp) - if len(pp) != length: - raise 'FATAL', 'inconsistent length. thought ' + `length` + ', but should really be ' + `len(pp)` - if i >= length: - break - ch = pp[i] - i = i + 1 - - if type(ch) == type(''): - #normally, only chunks are present in pp, - # but in some cases, some extra info - # has been inserted, e.g., the \end{...} clauses - raise 'FATAL', 'got string, probably too many ' + `end` - - if ch.chtype == chunk_type(GROUP): - # check for {\em ...} constructs - if ch.data and \ - ch.data[0].chtype == chunk_type(CSNAME) and \ - s(buf, ch.data[0].data) in fontchanges.keys(): - k = s(buf, ch.data[0].data) - del ch.data[0] - pp.insert(i-1, chunk(CSNAME, ch.where, fontchanges[k])) - length, i = length+1, i+1 - - # recursively parse the contents of the group - changeit(buf, ch.data) - - elif ch.chtype == chunk_type(IF): - # \if... - flag, negate, data = ch.data - ##print 'IF: flag, negate = ' + `flag, negate` - if flag not in flags.keys(): - raise error, 'unknown flag ' + `flag` - - value = flags[flag] - if negate: - value = (not value) - del pp[i-1] - length, i = length-1, i-1 - if value: - pp[i:i] = data - length = length + len(data) - - - elif ch.chtype == chunk_type(ENV): - # \begin{...} .... - envname, data = ch.data - - #push this environment name on stack - hist.inenv.insert(0, envname) - - #append an endenv chunk after grouped data - data.append(chunk(ENDENV, ch.where, envname)) - ##[`data`] - - #delete this object - del pp[i-1] - i, length = i-1, length-1 - - #insert found data - pp[i:i] = data - length = length + len(data) - - if envname == 'verbatim': - pp[i:i] = [chunk(CSLINE, ch.where, 'example'), \ - chunk(GROUP, ch.where, [])] - length, i = length+2, i+2 - - elif envname == 'itemize': - if hist.itemizenesting > len(itemizesymbols): - raise error, 'too deep itemize nesting' - ingroupch = [chunk(CSNAME, ch.where,\ - itemizesymbols[hist.itemizenesting])] - hist.itemizenesting = hist.itemizenesting + 1 - pp[i:i] = [chunk(CSLINE, ch.where, 'itemize'),\ - chunk(GROUP, ch.where, ingroupch)] - length, i = length+2, i+2 - - elif envname == 'enumerate': - if hist.enumeratenesting > len(enumeratesymbols): - raise error, 'too deep enumerate nesting' - ingroupch = [chunk(PLAIN, ch.where,\ - enumeratesymbols[hist.enumeratenesting])] - hist.enumeratenesting = hist.enumeratenesting + 1 - pp[i:i] = [chunk(CSLINE, ch.where, 'enumerate'),\ - chunk(GROUP, ch.where, ingroupch)] - length, i = length+2, i+2 - - elif envname == 'description': - ingroupch = [chunk(CSNAME, ch.where, 'b')] - pp[i:i] = [chunk(CSLINE, ch.where, 'table'), \ - chunk(GROUP, ch.where, ingroupch)] - length, i = length+2, i+2 - - elif (envname == 'tableiii') or \ - (envname == 'tableii'): - if (envname == 'tableii'): - ltable = 2 - else: - ltable = 3 - wh = ch.where - newcode = [] - - #delete tabular format description - # e.g., {|l|c|l|} - length, newi = getnextarg(length, buf, pp, i) - del pp[i:newi] - length = length - (newi-i) - - newcode.append(chunk(CSLINE, wh, 'table')) - ingroupch = [chunk(CSNAME, wh, 'asis')] - newcode.append(chunk(GROUP, wh, ingroupch)) - newcode.append(chunk(CSLINE, wh, 'item')) - - #get the name of macro for @item - # e.g., {code} - length, newi = getnextarg(length, buf, pp, i) - - if newi-i != 1: - raise error, 'Sorry, expected 1 chunk argument' - if pp[i].chtype != chunk_type(PLAIN): - raise error, 'Sorry, expected plain text argument' - hist.itemargmacro = s(buf, pp[i].data) - del pp[i:newi] - length = length - (newi-i) - - itembody = [] - for count in range(ltable): - length, newi = getnextarg(length, buf, pp, i) - emphgroup = [\ - chunk(CSNAME, wh, 'emph'), \ - chunk(GROUP, 0, pp[i:newi])] - del pp[i:newi] - length = length - (newi-i) - if count == 0: - itemarg = emphgroup - elif count == ltable-1: - itembody = itembody + \ - [chunk(PLAIN, wh, ' --- ')] + \ - emphgroup - else: - itembody = emphgroup - newcode.append(chunk(GROUP, wh, itemarg)) - newcode = newcode + itembody + [chunk(DENDLINE, wh, '\n')] - pp[i:i] = newcode - l = len(newcode) - length, i = length+l, i+l - del newcode, l - - if length != len(pp): - raise 'STILL, SOMETHING wrong', `i` - - - elif envname == 'funcdesc': - pp.insert(i, chunk(PLAIN, ch.where, '')) - i, length = i+1, length+1 - length, i = do_funcdesc(length, buf, pp, i) - - elif envname == 'excdesc': - pp.insert(i, chunk(PLAIN, ch.where, '')) - i, length = i+1, length+1 - length, i = do_excdesc(length, buf, pp, i) - - elif envname == 'datadesc': - pp.insert(i, chunk(PLAIN, ch.where, '')) - i, length = i+1, length+1 - length, i = do_datadesc(length, buf, pp, i) - - else: - print 'WARNING: don\'t know what to do with env ' + `envname` - - elif ch.chtype == chunk_type(ENDENV): - envname = ch.data - if envname != hist.inenv[0]: - raise error, '\'end\' does not match. Name ' + `envname` + ', expected ' + `hist.inenv[0]` - del hist.inenv[0] - del pp[i-1] - i, length = i-1, length-1 - - if envname == 'verbatim': - pp[i:i] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, 'example')])] - i, length = i+2, length+2 - elif envname == 'itemize': - hist.itemizenesting = hist.itemizenesting - 1 - pp[i:i] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, 'itemize')])] - i, length = i+2, length+2 - elif envname == 'enumerate': - hist.enumeratenesting = hist.enumeratenesting-1 - pp[i:i] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, 'enumerate')])] - i, length = i+2, length+2 - elif envname == 'description': - pp[i:i] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, 'table')])] - i, length = i+2, length+2 - elif (envname == 'tableiii') or (envname == 'tableii'): - pp[i:i] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, 'table')])] - i, length = i+2, length + 2 - pp.insert(i, chunk(DENDLINE, ch.where, '\n')) - i, length = i+1, length+1 - - elif envname in ('funcdesc', 'excdesc', 'datadesc'): - pp[i:i] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, hist.command)])] - i, length = i+2, length+2 - else: - print 'WARNING: ending env ' + `envname` + 'has no actions' - - elif ch.chtype == chunk_type(CSNAME): - # control name transformations - if s(buf, ch.data) == 'optional': - pp[i-1].chtype = chunk_type (PLAIN) - pp[i-1].data = '[' - if (i < length) and \ - (pp[i].chtype == chunk_type(GROUP)): - cp=pp[i].data - pp[i:i+1]=cp + [\ - chunk(PLAIN, ch.where, ']')] - length = length+len(cp) - elif s(buf, ch.data) in ignoredcommands: - del pp[i-1] - i, length = i-1, length-1 - elif s(buf, ch.data) == '@' and \ - i != length and \ - pp[i].chtype == chunk_type(PLAIN) and \ - s(buf, pp[i].data)[0] == '.': - # \@. --> \. --> @. - ch.data = '.' - del pp[i] - length = length-1 - elif s(buf, ch.data) == '\\': - # \\ --> \* --> @* - ch.data = '*' - elif len(s(buf, ch.data)) == 1 and \ - s(buf, ch.data) in onlylatexspecial: - ch.chtype = chunk_type(PLAIN) - # check if such a command is followed by - # an empty group: e.g., `\%{}'. If so, remove - # this empty group too - if i < length and \ - pp[i].chtype == chunk_type(GROUP) \ - and len(pp[i].data) == 0: - del pp[i] - length = length-1 - - elif hist.inargs and s(buf, ch.data) in inargsselves: - # This is the special processing of the - # arguments of the \begin{funcdesc}... or - # \funcline... arguments - # \, --> , \[ --> [, \] --> ] - ch.chtype = chunk_type(PLAIN) - - elif s(buf, ch.data) == 'renewcommand': - # \renewcommand{\indexsubitem}.... - i, length = i-1, length-1 - del pp[i] - length, newi = getnextarg(length, buf, pp, i) - if newi-i == 1 \ - and i < length \ - and pp[i].chtype == chunk_type(CSNAME) \ - and s(buf, pp[i].data) == 'indexsubitem': - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - text = flattext(buf, pp[i:newi]) - if text[:1] != '(' or text[-1:] != ')': - raise error, 'expected indexsubitme enclosed in braces' - words = string.split(text[1:-1]) - hist.indexsubitem = words - del text, words - else: - print 'WARNING: renewcommand with unsupported arg removed' - del pp[i:newi] - length = length - (newi-i) - - elif s(buf, ch.data) == 'item': - ch.chtype = chunk_type(CSLINE) - length, newi = getoptarg(length, buf, pp, i) - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - i, length = i+1, length+1 - - elif s(buf, ch.data) == 'ttindex': - idxsi = hist.indexsubitem - - cat_class = '' - if len(idxsi) >= 2 and idxsi[1] in \ - ('method', 'function', 'protocol'): - command = 'findex' - elif len(idxsi) >= 2 and idxsi[1] in \ - ('exception', 'object'): - command = 'vindex' - else: - print 'WARNING: can\'t categorize ' + `idxsi` + ' for \'ttindex\' command' - command = 'cindex' - - if not cat_class: - cat_class = '('+string.join(idxsi)+')' - - ch.chtype = chunk_type(CSLINE) - ch.data = command - - length, newi = getnextarg(length, buf, pp, i) - arg = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - - cat_arg = [chunk(PLAIN, ch.where, cat_class)] - - # determine what should be set in roman, and - # what in tt-font - if command in regindices: - - arg = [chunk(CSNAME, ch.where, 't'), \ - chunk(GROUP, ch.where, arg)] - else: - cat_arg = [chunk(CSNAME, ch.where, 'r'), \ - chunk(GROUP, ch.where, cat_arg)] - - ingroupch = arg + \ - [chunk(PLAIN, ch.where, ' ')] + \ - cat_arg - - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - - elif s(buf, ch.data) == 'ldots': - # \ldots --> \dots{} --> @dots{} - ch.data = 'dots' - if i == length \ - or pp[i].chtype != chunk_type(GROUP) \ - or pp[i].data != []: - pp.insert(i, chunk(GROUP, ch.where, [])) - i, length = i+1, length+1 - elif s(buf, ch.data) in wordsselves: - # \UNIX --> UNIX - ch.chtype = chunk_type(PLAIN) - if i != length \ - and pp[i].chtype == chunk_type(GROUP) \ - and pp[i].data == []: - del pp[i] - length = length-1 - elif s(buf, ch.data) in for_texi: - pass - - elif s(buf, ch.data) == 'e': - # \e --> \ - ch.data = '\\' - ch.chtype = chunk_type(PLAIN) - elif (s(buf, ch.data) == 'lineiii') or\ - (s(buf, ch.data) == 'lineii'): - # This is the most tricky one - # \lineiii{a1}{a2}[{a3}] --> - # @item @<cts. of itemargmacro>{a1} - # a2 [ -- a3] - # - ##print 'LINEIIIIII!!!!!!!' -## wobj = Wobj().init() -## dumpit(buf, wobj.write, pp[i-1:i+5]) -## print '--->' + wobj.data + '<----' - if not hist.inenv: - raise error, \ - 'no environment for lineiii' - if (hist.inenv[0] != 'tableiii') and\ - (hist.inenv[0] != 'tableii'): - raise error, \ - 'wrong command (' + \ - s(buf, ch.data)+ \ - ') in wrong environment (' \ - + `hist.inenv[0]` + ')' - ch.chtype = chunk_type(CSLINE) - ch.data = 'item' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = [chunk(CSNAME, 0, \ - hist.itemargmacro), \ - chunk(GROUP, 0, pp[i:newi])] - del pp[i:newi] - length = length - (newi-i) -## print 'ITEM ARG: --->', -## wobj = Wobj().init() -## dumpit(buf, wobj.write, ingroupch) -## print wobj.data, '<---' - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - grouppos = i - i, length = i+1, length+1 - length, i = getnextarg(length, buf, pp, i) - length, newi = getnextarg(length, buf, pp, i) - if newi > i: - # we have a 3rd arg - pp.insert(i, chunk(PLAIN, ch.where, ' --- ')) - i = newi + 1 - length = length + 1 -## pp[grouppos].data = pp[grouppos].data \ -## + [chunk(PLAIN, ch.where, ' ')] \ -## + pp[i:newi] -## del pp[i:newi] -## length = length - (newi-i) - if length != len(pp): - raise 'IN LINEIII IS THE ERR', `i` - - elif s(buf, ch.data) in ('chapter', 'section', 'subsection', 'subsubsection'): - #\xxxsection{A} ----> - # @node A, , , - # @xxxsection A - ## also: remove commas and quotes - ch.chtype = chunk_type(CSLINE) - length, newi = getnextarg(length, buf, pp, i) - afternodenamecmd = next_command_p(length, buf, pp, newi, 'nodename') - if afternodenamecmd < 0: - cp1 = crcopy(pp[i:newi]) - pp[i:newi] = [\ - chunk(GROUP, ch.where, \ - pp[i:newi])] - length, newi = length - (newi-i) + 1, \ - i+1 - text = flattext(buf, cp1) - text = invent_node_names(text) - else: - length, endarg = getnextarg(length, buf, pp, afternodenamecmd) - cp1 = crcopy(pp[afternodenamecmd:endarg]) - del pp[newi:endarg] - length = length - (endarg-newi) - - pp[i:newi] = [\ - chunk(GROUP, ch.where, \ - pp[i:newi])] - length, newi = length - (newi-i) + 1, \ - i + 1 - text = flattext(buf, cp1) - if text[-1] == '.': - text = text[:-1] -## print 'FLATTEXT:', `text` - if text in hist.nodenames: - print 'WARNING: node name ' + `text` + ' already used' - out.doublenodes.append(text) - else: - hist.nodenames.append(text) - text = rm_commas_etc(text) - pp[i-1:i-1] = [\ - chunk(CSLINE, ch.where, 'node'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, text+', , ,')\ - ])] - i, length = newi+2, length+2 - - elif s(buf,ch.data) == 'funcline': - # fold it to a very short environment - pp[i-1:i-1] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, hist.command)])] - i, length = i+2, length+2 - length, i = do_funcdesc(length, buf, pp, i) - - elif s(buf,ch.data) == 'dataline': - pp[i-1:i-1] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, hist.command)])] - i, length = i+2, length+2 - length, i = do_datadesc(length, buf, pp, i) - - elif s(buf,ch.data) == 'excline': - pp[i-1:i-1] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, hist.command)])] - i, length = i+2, length+2 - length, i = do_excdesc(length, buf, pp, i) - - - elif s(buf, ch.data) == 'index': - #\index{A} ---> - # @cindex A - ch.chtype = chunk_type(CSLINE) - ch.data = 'cindex' - length, newi = getnextarg(length, buf, pp, i) - - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - elif s(buf, ch.data) == 'bifuncindex': - ch.chtype = chunk_type(CSLINE) - ch.data = 'findex' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - - ingroupch.append(chunk(PLAIN, ch.where, ' ')) - ingroupch.append(chunk(CSNAME, ch.where, 'r')) - ingroupch.append(chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, \ - '(built-in function)')])) - - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - - elif s(buf, ch.data) == 'obindex': - ch.chtype = chunk_type(CSLINE) - ch.data = 'findex' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - - ingroupch.append(chunk(PLAIN, ch.where, ' ')) - ingroupch.append(chunk(CSNAME, ch.where, 'r')) - ingroupch.append(chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, \ - '(object)')])) - - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - - elif s(buf, ch.data) == 'opindex': - ch.chtype = chunk_type(CSLINE) - ch.data = 'findex' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - - ingroupch.append(chunk(PLAIN, ch.where, ' ')) - ingroupch.append(chunk(CSNAME, ch.where, 'r')) - ingroupch.append(chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, \ - '(operator)')])) - - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - - elif s(buf, ch.data) == 'bimodindex': - ch.chtype = chunk_type(CSLINE) - ch.data = 'pindex' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - - ingroupch.append(chunk(PLAIN, ch.where, ' ')) - ingroupch.append(chunk(CSNAME, ch.where, 'r')) - ingroupch.append(chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, \ - '(built-in)')])) - - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - elif s(buf, ch.data) == 'sectcode': - ch.data = 'code' - - - elif s(buf, ch.data) == 'stmodindex': - ch.chtype = chunk_type(CSLINE) - # use the program index as module index - ch.data = 'pindex' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - - ingroupch.append(chunk(PLAIN, ch.where, ' ')) - ingroupch.append(chunk(CSNAME, ch.where, 'r')) - ingroupch.append(chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, \ - '(standard)')])) - - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - - elif s(buf, ch.data) == 'stindex': - # XXX must actually go to newindex st - wh = ch.where - ch.chtype = chunk_type(CSLINE) - ch.data = 'cindex' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = [chunk(CSNAME, wh, 'code'), \ - chunk(GROUP, wh, pp[i:newi])] - - del pp[i:newi] - length = length - (newi-i) - - t = ingroupch[:] - t.append(chunk(PLAIN, wh, ' statement')) - - pp.insert(i, chunk(GROUP, wh, t)) - i, length = i+1, length+1 - - pp.insert(i, chunk(CSLINE, wh, 'cindex')) - i, length = i+1, length+1 - - t = ingroupch[:] - t.insert(0, chunk(PLAIN, wh, 'statement, ')) - - pp.insert(i, chunk(GROUP, wh, t)) - i, length = i+1, length+1 - - - elif s(buf, ch.data) == 'indexii': - #\indexii{A}{B} ---> - # @cindex A B - # @cindex B, A - length, newi = getnextarg(length, buf, pp, i) - cp11 = pp[i:newi] - cp21 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - cp12 = pp[i:newi] - cp22 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - - ch.chtype = chunk_type(CSLINE) - ch.data = 'cindex' - pp.insert(i, chunk(GROUP, ch.where, cp11 + [\ - chunk(PLAIN, ch.where, ' ')] + cp12)) - i, length = i+1, length+1 - pp[i:i] = [chunk(CSLINE, ch.where, 'cindex'), \ - chunk(GROUP, ch.where, cp22 + [\ - chunk(PLAIN, ch.where, ', ')]+ cp21)] - i, length = i+2, length+2 - - elif s(buf, ch.data) == 'indexiii': - length, newi = getnextarg(length, buf, pp, i) - cp11 = pp[i:newi] - cp21 = crcopy(pp[i:newi]) - cp31 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - cp12 = pp[i:newi] - cp22 = crcopy(pp[i:newi]) - cp32 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - cp13 = pp[i:newi] - cp23 = crcopy(pp[i:newi]) - cp33 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - - ch.chtype = chunk_type(CSLINE) - ch.data = 'cindex' - pp.insert(i, chunk(GROUP, ch.where, cp11 + [\ - chunk(PLAIN, ch.where, ' ')] + cp12 \ - + [chunk(PLAIN, ch.where, ' ')] \ - + cp13)) - i, length = i+1, length+1 - pp[i:i] = [chunk(CSLINE, ch.where, 'cindex'), \ - chunk(GROUP, ch.where, cp22 + [\ - chunk(PLAIN, ch.where, ' ')]+ cp23\ - + [chunk(PLAIN, ch.where, ', ')] +\ - cp21)] - i, length = i+2, length+2 - pp[i:i] = [chunk(CSLINE, ch.where, 'cindex'), \ - chunk(GROUP, ch.where, cp33 + [\ - chunk(PLAIN, ch.where, ', ')]+ cp31\ - + [chunk(PLAIN, ch.where, ' ')] +\ - cp32)] - i, length = i+2, length+2 - - - elif s(buf, ch.data) == 'indexiv': - length, newi = getnextarg(length, buf, pp, i) - cp11 = pp[i:newi] - cp21 = crcopy(pp[i:newi]) - cp31 = crcopy(pp[i:newi]) - cp41 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - cp12 = pp[i:newi] - cp22 = crcopy(pp[i:newi]) - cp32 = crcopy(pp[i:newi]) - cp42 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - cp13 = pp[i:newi] - cp23 = crcopy(pp[i:newi]) - cp33 = crcopy(pp[i:newi]) - cp43 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - cp14 = pp[i:newi] - cp24 = crcopy(pp[i:newi]) - cp34 = crcopy(pp[i:newi]) - cp44 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - - ch.chtype = chunk_type(CSLINE) - ch.data = 'cindex' - ingroupch = cp11 + \ - spacech + cp12 + \ - spacech + cp13 + \ - spacech + cp14 - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - i, length = i+1, length+1 - ingroupch = cp22 + \ - spacech + cp23 + \ - spacech + cp24 + \ - commach + cp21 - pp[i:i] = cindexch + [\ - chunk(GROUP, ch.where, ingroupch)] - i, length = i+2, length+2 - ingroupch = cp33 + \ - spacech + cp34 + \ - commach + cp31 + \ - spacech + cp32 - pp[i:i] = cindexch + [\ - chunk(GROUP, ch.where, ingroupch)] - i, length = i+2, length+2 - ingroupch = cp44 + \ - commach + cp41 + \ - spacech + cp42 + \ - spacech + cp43 - pp[i:i] = cindexch + [\ - chunk(GROUP, ch.where, ingroupch)] - i, length = i+2, length+2 - - - - else: - print 'don\'t know what to do with keyword ' + `s(buf, ch.data)` - - - -re_atsign = regex.compile('[@{}]') -re_newline = regex.compile('\n') - -def dumpit(buf, wm, pp): - - global out - - i, length = 0, len(pp) - - addspace = 0 - - while 1: - if len(pp) != length: - raise 'FATAL', 'inconsistent length' - if i == length: - break - ch = pp[i] - i = i + 1 - - if addspace: - dospace = 1 - addspace = 0 - else: - dospace = 0 - - if ch.chtype == chunk_type(CSNAME): - wm('@' + s(buf, ch.data)) - if s(buf, ch.data) == 'node' and \ - pp[i].chtype == chunk_type(PLAIN) and \ - s(buf, pp[i].data) in out.doublenodes: - ##XXX doesnt work yet?? - wm(' ZZZ-' + zfill(`i`, 4)) - if s(buf, ch.data)[0] in string.letters: - addspace = 1 - elif ch.chtype == chunk_type(PLAIN): - if dospace and s(buf, ch.data) not in (' ', '\t'): - wm(' ') - text = s(buf, ch.data) - while 1: - pos = re_atsign.search(text) - if pos < 0: - break - wm(text[:pos] + '@' + text[pos]) - text = text[pos+1:] - wm(text) - elif ch.chtype == chunk_type(GROUP): - wm('{') - dumpit(buf, wm, ch.data) - wm('}') - elif ch.chtype == chunk_type(DENDLINE): - wm('\n\n') - while i != length and pp[i].chtype in \ - (chunk_type(DENDLINE), chunk_type(ENDLINE)): - i = i + 1 - elif ch.chtype == chunk_type(OTHER): - wm(s(buf, ch.data)) - elif ch.chtype == chunk_type(ACTIVE): - wm(s(buf, ch.data)) - elif ch.chtype == chunk_type(ENDLINE): - wm('\n') - elif ch.chtype == chunk_type(CSLINE): - if i >= 2 and pp[i-2].chtype not in \ - (chunk_type(ENDLINE), chunk_type(DENDLINE)) \ - and (pp[i-2].chtype != chunk_type(PLAIN) \ - or s(buf, pp[i-2].data)[-1] != '\n'): - - wm('\n') - wm('@' + s(buf, ch.data)) - if i == length: - raise error, 'CSLINE expected another chunk' - if pp[i].chtype != chunk_type(GROUP): - raise error, 'CSLINE expected GROUP' - if type(pp[i].data) != type([]): - raise error, 'GROUP chould contain []-data' - - wobj = Wobj().init() - dumpit(buf, wobj.write, pp[i].data) - i = i + 1 - text = wobj.data - del wobj - if text: - wm(' ') - while 1: - pos = re_newline.search(text) - if pos < 0: - break - print 'WARNING: found newline in csline arg' - wm(text[:pos] + ' ') - text = text[pos+1:] - wm(text) - if i >= length or \ - pp[i].chtype not in (chunk_type(CSLINE), \ - chunk_type(ENDLINE), chunk_type(DENDLINE)) \ - and (pp[i].chtype != chunk_type(PLAIN) \ - or s(buf, pp[i].data)[0] != '\n'): - wm('\n') - - elif ch.chtype == chunk_type(COMMENT): -## print 'COMMENT: previous chunk =', pp[i-2] -## if pp[i-2].chtype == chunk_type(PLAIN): -## print 'PLAINTEXT =', `s(buf, pp[i-2].data)` - if s(buf, ch.data) and \ - regex.match('^[ \t]*$', s(buf, ch.data)) < 0: - if i >= 2 and pp[i-2].chtype not in \ - (chunk_type(ENDLINE), chunk_type(DENDLINE)) \ - and not (pp[i-2].chtype == chunk_type(PLAIN) \ - and regex.match('\\(.\\|\n\\)*[ \t]*\n$', s(buf, pp[i-2].data)) >= 0): - print 'ADDING NEWLINE' - wm('\n') - wm('@c ' + s(buf, ch.data)) - elif ch.chtype == chunk_type(IGNORE): - pass - else: - try: - str = `s(buf, ch.data)` - except TypeError: - str = `ch.data` - if len(str) > 400: - str = str[:400] + '...' - print 'warning:', ch.chtype, 'not handled, data ' + str - - - -def main(): - outfile = None - headerfile = 'texipre.dat' - trailerfile = 'texipost.dat' - - try: - opts, args = getopt.getopt(sys.argv[1:], 'o:h:t:') - except getopt.error: - args = [] - - if not args: - print 'usage: partparse [-o outfile] [-h headerfile]', - print '[-t trailerfile] file ...' - sys.exit(2) - - for opt, arg in opts: - if opt == '-o': outfile = arg - if opt == '-h': headerfile = arg - if opt == '-t': trailerfile = arg - - if not outfile: - root, ext = os.path.splitext(args[0]) - outfile = root + '.texi' - - if outfile in args: - print 'will not overwrite input file', outfile - sys.exit(2) - - outf = open(outfile, 'w') - outf.write(open(headerfile, 'r').read()) - - for file in args: - if len(args) > 1: print '='*20, file, '='*20 - buf = open(file, 'r').read() - w, pp = parseit(buf) - startchange() - changeit(buf, pp) - dumpit(buf, outf.write, pp) - - outf.write(open(trailerfile, 'r').read()) - - outf.close() - -main() diff --git a/Doc/qua.tex b/Doc/qua.tex deleted file mode 100644 index 88f5778fa5..0000000000 --- a/Doc/qua.tex +++ /dev/null @@ -1,1236 +0,0 @@ -\documentstyle[11pt]{article} -\newcommand{\Cpp}{C\protect\raisebox{.18ex}{++}} - -\title{ -Interactively Testing Remote Servers Using the Python Programming Language -} - -\author{ - Guido van Rossum \\ - Dept. AA, CWI, P.O. Box 94079 \\ - 1090 GB Amsterdam, The Netherlands \\ - E-mail: {\tt guido@cwi.nl} -\and - Jelke de Boer \\ - HIO Enschede; P.O.Box 1326 \\ - 7500 BH Enschede, The Netherlands -} - -\begin{document} - -\maketitle - -\begin{abstract} -This paper describes how two tools that were developed quite -independently gained in power by a well-designed connection between -them. The tools are Python, an interpreted prototyping language, and -AIL, a Remote Procedure Call stub generator. The context is Amoeba, a -well-known distributed operating system developed jointly by the Free -University and CWI in Amsterdam. - -As a consequence of their integration, both tools have profited: -Python gained usability when used with Amoeba --- for which it was not -specifically developed --- and AIL users now have a powerful -interactive tool to test servers and to experiment with new -client/server interfaces.% -\footnote{ -An earlier version of this paper was presented at the Spring 1991 -EurOpen Conference in Troms{\o} under the title ``Linking a Stub -Generator (AIL) to a Prototyping Language (Python).'' -} -\end{abstract} - -\section{Introduction} - -Remote Procedure Call (RPC) interfaces, used in distributed systems -like Amoeba -\cite{Amoeba:IEEE,Amoeba:CACM}, -have a much more concrete character than local procedure call -interfaces in traditional systems. Because clients and servers may -run on different machines, with possibly different word size, byte -order, etc., much care is needed to describe interfaces exactly and to -implement them in such a way that they continue to work when a client -or server is moved to a different machine. Since machines may fail -independently, error handling must also be treated more carefully. - -A common approach to such problems is to use a {\em stub generator}. -This is a program that takes an interface description and transforms -it into functions that must be compiled and linked with client and -server applications. These functions are called by the application -code to take care of details of interfacing to the system's RPC layer, -to implement transformations between data representations of different -machines, to check for errors, etc. They are called `stubs' because -they don't actually perform the action that they are called for but -only relay the parameters to the server -\cite{RPC}. - -Amoeba's stub generator is called AIL, which stands for Amoeba -Interface Language -\cite{AIL}. -The first version of AIL generated only C functions, but an explicit -goal of AIL's design was {\em retargetability}: it should be possible -to add back-ends that generate stubs for different languages from the -same interface descriptions. Moreover, the stubs generated by -different back-ends must be {\em interoperable}: a client written in -Modula-3, say, should be able to use a server written in C, and vice -versa. - -This interoperability is the key to the success of the marriage -between AIL and Python. Python is a versatile interpreted language -developed by the first author. Originally intended as an alternative -for the kind of odd jobs that are traditionally solved by a mixture of -shell scripts, manually given shell commands, and an occasional ad hoc -C program, Python has evolved into a general interactive prototyping -language. It has been applied to a wide range of problems, from -replacements for large shell scripts to fancy graphics demos and -multimedia applications. - -One of Python's strengths is the ability for the user to type in some -code and immediately run it: no compilation or linking is necessary. -Interactive performance is further enhanced by Python's concise, clear -syntax, its very-high-level data types, and its lack of declarations -(which is compensated by run-time type checking). All this makes -programming in Python feel like a leisure trip compared to the hard -work involved in writing and debugging even a smallish C program. - -It should be clear by now that Python will be the ideal tool to test -servers and their interfaces. Especially during the development of a -complex server, one often needs to generate test requests on an ad hoc -basis, to answer questions like ``what happens if request X arrives -when the server is in state Y,'' to test the behavior of the server -with requests that touch its limitations, to check server responses to -all sorts of wrong requests, etc. Python's ability to immediately -execute `improvised' code makes it a much better tool for this -situation than C. - -The link to AIL extends Python with the necessary functionality to -connect to arbitrary servers, making the server testbed sketched above -a reality. Python's high-level data types, general programming -features, and system interface ensure that it has all the power and -flexibility needed for the job. - -One could go even further than this. Current distributed operating -systems, based on client-server interaction, all lack a good command -language or `shell' to give adequate access to available services. -Python has considerable potential for becoming such a shell. - -\subsection{Overview of this Paper} - -The rest of this paper contains three major sections and a conclusion. -First an overview of the Python programming language is given. Next -comes a short description of AIL, together with some relevant details -about Amoeba. Finally, the design and construction of the link -between Python and AIL is described in much detail. The conclusion -looks back at the work and points out weaknesses and strengths of -Python and AIL that were discovered in the process. - -\section{An Overview of Python} - -Python% -\footnote{ -Named after the funny TV show, not the nasty reptile. -} -owes much to ABC -\cite{ABC}, -a language developed at CWI as a programming language for non-expert -computer users. Python borrows freely from ABC's syntax and data -types, but adds modules, exceptions and classes, extensibility, and -the ability to call system functions. The concepts of modules, -exceptions and (to some extent) classes are influenced strongly by -their occurrence in Modula-3 -\cite{Modula-3}. - -Although Python resembles ABC in many ways, there is a a clear -difference in application domain. ABC is intended to be the only -programming language for those who use a computer as a tool, but -occasionally need to write a program. For this reason, ABC is not -just a programming language but also a programming environment, which -comes with an integrated syntax-directed editor and some source -manipulation commands. Python, on the other hand, aims to be a tool -for professional (system) programmers, for whom having a choice of -languages with different feature sets makes it possible to choose `the -right tool for the job.' The features added to Python make it more -useful than ABC in an environment where access to system functions -(such as file and directory manipulations) are common. They also -support the building of larger systems and libraries. The Python -implementation offers little in the way of a programming environment, -but is designed to integrate seamlessly with existing programming -environments (e.g. UNIX and Emacs). - -Perhaps the best introduction to Python is a short example. The -following is a complete Python program to list the contents of a UNIX -directory. -\begin{verbatim} -import sys, posix - -def ls(dirname): # Print sorted directory contents - names = posix.listdir(dirname) - names.sort() - for name in names: - if name[0] != '.': print name - -ls(sys.argv[1]) -\end{verbatim} -The largest part of this program, in the middle starting with {\tt -def}, is a function definition. It defines a function named {\tt ls} -with a single parameter called {\tt dirname}. (Comments in Python -start with `\#' and extend to the end of the line.) The function body -is indented: Python uses indentation for statement grouping instead of -braces or begin/end keywords. This is shorter to type and avoids -frustrating mismatches between the perception of grouping by the user -and the parser. Python accepts one statement per line; long -statements may be broken in pieces using the standard backslash -convention. If the body of a compound statement is a single, simple -statement, it may be placed on the same line as the head. - -The first statement of the function body calls the function {\tt -listdir} defined in the module {\tt posix}. This function returns a -list of strings representing the contents of the directory name passed -as a string argument, here the argument {\tt dirname}. If {\tt -dirname} were not a valid directory name, or perhaps not even a -string, {\tt listdir} would raise an exception and the next statement -would never be reached. (Exceptions can be caught in Python; see -later.) Assuming {\tt listdir} returns normally, its result is -assigned to the local variable {\tt names}. - -The second statement calls the method {\tt sort} of the variable {\tt -names}. This method is defined for all lists in Python and does the -obvious thing: the elements of the list are reordered according to -their natural ordering relationship. Since in our example the list -contains strings, they are sorted in ascending \ASCII{} order. - -The last two lines of the function contain a loop that prints all -elements of the list whose first character isn't a period. In each -iteration, the {\tt for} statement assigns an element of the list to -the local variable {\tt name}. The {\tt print} statement is intended -for simple-minded output; more elaborate formatting is possible with -Python's string handling functions. - -The other two parts of the program are easily explained. The first -line is an {\tt import} statement that tells the interpreter to import -the modules {\tt sys} and {\tt posix}. As it happens these are both -built into the interpreter. Importing a module (built-in or -otherwise) only makes the module name available in the current scope; -functions and data defined in the module are accessed through the dot -notation as in {\tt posix.listdir}. The scope rules of Python are -such that the imported module name {\tt posix} is also available in -the function {\tt ls} (this will be discussed in more detail later). - -Finally, the last line of the program calls the {\tt ls} function with -a definite argument. It must be last since Python objects must be -defined before they can be used; in particular, the function {\tt ls} -must be defined before it can be called. The argument to {\tt ls} is -{\tt sys.argv[1]}, which happens to be the Python equivalent of {\tt -\$1} in a shell script or {\tt argv[1]} in a C program's {\tt main} -function. - -\subsection{Python Data Types} - -(This and the following subsections describe Python in quite a lot of -detail. If you are more interested in AIL, Amoeba and how they are -linked with Python, you can skip to section 3 now.) - -Python's syntax may not have big surprises (which is exactly as it -should be), but its data types are quite different from what is found -in languages like C, Ada or Modula-3. All data types in Python, even -integers, are `objects'. All objects participate in a common garbage -collection scheme (currently implemented using reference counting). -Assignment is cheap, independent of object size and type: only a -pointer to the assigned object is stored in the assigned-to variable. -No type checking is performed on assignment; only specific operations -like addition test for particular operand types. - -The basic object types in Python are numbers, strings, tuples, lists -and dictionaries. Some other object types are open files, functions, -modules, classes, and class instances; even types themselves are -represented as objects. Extension modules written in C can define -additional object types; examples are objects representing windows and -Amoeba capabilities. Finally, the implementation itself makes heavy -use of objects, and defines some private object types that aren't -normally visible to the user. There is no explicit pointer type in -Python. - -{\em Numbers}, both integers and floating point, are pretty -straightforward. The notation for numeric literals is the same as in -C, including octal and hexadecimal integers; precision is the same as -{\tt long} or {\tt double} in C\@. A third numeric type, `long -integer', written with an `L' suffix, can be used for arbitrary -precision calculations. All arithmetic, shifting and masking -operations from C are supported. - -{\em Strings} are `primitive' objects just like numbers. String -literals are written between single quotes, using similar escape -sequences as in C\@. Operations are built into the language to -concatenate and to replicate strings, to extract substrings, etc. -There is no limit to the length of the strings created by a program. -There is no separate character data type; strings of length one do -nicely. - -{\em Tuples} are a way to `pack' small amounts of heterogeneous data -together and carry them around as a unit. Unlike structure members in -C, tuple items are nameless. Packing and unpacking assignments allow -access to the items, for example: -\begin{verbatim} -x = 'Hi', (1, 2), 'World' # x is a 3-item tuple, - # its middle item is (1, 2) -p, q, r = x # unpack x into p, q and r -a, b = q # unpack q into a and b -\end{verbatim} -A combination of packing and unpacking assignment can be used as -parallel assignment, and is idiom for permutations, e.g.: -\begin{verbatim} -p, q = q, p # swap without temporary -a, b, c = b, c, a # cyclic permutation -\end{verbatim} -Tuples are also used for function argument lists if there is more than -one argument. A tuple object, once created, cannot be modified; but -it is easy enough to unpack it and create a new, modified tuple from -the unpacked items and assign this to the variable that held the -original tuple object (which will then be garbage-collected). - -{\em Lists} are array-like objects. List items may be arbitrary -objects and can be accessed and changed using standard subscription -notation. Lists support item insertion and deletion, and can -therefore be used as queues, stacks etc.; there is no limit to their -size. - -Strings, tuples and lists together are {\em sequence} types. These -share a common notation for generic operations on sequences such as -subscription, concatenation, slicing (taking subsequences) and -membership tests. As in C, subscripts start at 0. - -{\em Dictionaries} are `mappings' from one domain to another. The -basic operations on dictionaries are item insertion, extraction and -deletion, using subscript notation with the key as subscript. (The -current implementation allows only strings in the key domain, but a -future version of the language may remove this restriction.) - -\subsection{Statements} - -Python has various kinds of simple statements, such as assignments -and {\tt print} statements, and several kinds of compound statements, -like {\tt if} and {\tt for} statements. Formally, function -definitions and {\tt import} statements are also statements, and there -are no restrictions on the ordering of statements or their nesting: -{\tt import} may be used inside a function, functions may be defined -conditionally using an {\tt if} statement, etc. The effect of a -declaration-like statement takes place only when it is executed. - -All statements except assignments and expression statements begin with -a keyword: this makes the language easy to parse. An overview of the -most common statement forms in Python follows. - -An {\em assignment} has the general form -\vspace{\itemsep} - -\noindent -{\em variable $=$ variable $= ... =$ variable $=$ expression} -\vspace{\itemsep} - -It assigns the value of the expression to all listed variables. (As -shown in the section on tuples, variables and expressions can in fact -be comma-separated lists.) The assignment operator is not an -expression operator; there are no horrible things in Python like -\begin{verbatim} -while (p = p->next) { ... } -\end{verbatim} -Expression syntax is mostly straightforward and will not be explained -in detail here. - -An {\em expression statement} is just an expression on a line by -itself. This writes the value of the expression to standard output, -in a suitably unambiguous way, unless it is a `procedure call' (a -function call that returns no value). Writing the value is useful -when Python is used in `calculator mode', and reminds the programmer -not to ignore function results. - -The {\tt if} statement allows conditional execution. It has optional -{\tt elif} and {\tt else} parts; a construct like {\tt -if...elif...elif...elif...else} can be used to compensate for the -absence of a {\em switch} or {\em case} statement. - -Looping is done with {\tt while} and {\tt for} statements. The latter -(demonstrated in the `ls' example earlier) iterates over the elements -of a `sequence' (see the discussion of data types below). It is -possible to terminate a loop with a {\tt break} statement or to start -the next iteration with {\tt continue}. Both looping statements have -an optional {\tt else} clause which is executed after the loop is -terminated normally, but skipped when it is terminated by {\tt break}. -This can be handy for searches, to handle the case that the item is -not found. - -Python's {\em exception} mechanism is modelled after that of Modula-3. -Exceptions are raised by the interpreter when an illegal operation is -tried. It is also possible to explicitly raise an exception with the -{\tt raise} statement: -\vspace{\itemsep} - -\noindent -{\tt raise {\em expression}, {\em expression}} -\vspace{\itemsep} - -The first expression identifies which exception should be raised; -there are several built-in exceptions and the user may define -additional ones. The second, optional expression is passed to the -handler, e.g. as a detailed error message. - -Exceptions may be handled (caught) with the {\tt try} statement, which -has the following general form: -\vspace{\itemsep} - -\noindent -{\tt -\begin{tabular}{l} -try: {\em block} \\ -except {\em expression}, {\em variable}: {\em block} \\ -except {\em expression}, {\em variable}: {\em block} \\ -... \\ -except: {\em block} -\end{tabular} -} -\vspace{\itemsep} - -When an exception is raised during execution of the first block, a -search for an exception handler starts. The first {\tt except} clause -whose {\em expression} matches the exception is executed. The -expression may specify a list of exceptions to match against. A -handler without an expression serves as a `catch-all'. If there is no -match, the search for a handler continues with outer {\tt try} -statements; if no match is found on the entire invocation stack, an -error message and stack trace are printed, and the program is -terminated (interactively, the interpreter returns to its main loop). - -Note that the form of the {\tt except} clauses encourages a style of -programming whereby only selected exceptions are caught, passing -unanticipated exceptions on to the caller and ultimately to the user. -This is preferable over a simpler `catch-all' error handling -mechanism, where a simplistic handler intended to catch a single type -of error like `file not found' can easily mask genuine programming -errors --- especially in a language like Python which relies strongly -on run-time checking and allows the catching of almost any type of -error. - -Other common statement forms, which we have already encountered, are -function definitions, {\tt import} statements and {\tt print} -statements. There is also a {\tt del} statement to delete one or more -variables, a {\tt return} statement to return from a function, and a -{\tt global} statement to allow assignments to global variables. -Finally, the {\tt pass} statement is a no-op. - -\subsection{Execution Model} - -A Python program is executed by a stack-based interpreter. - -When a function is called, a new `execution environment' for it is -pushed onto the stack. An execution environment contains (among other -data) pointers to two `symbol tables' that are used to hold variables: -the local and the global symbol table. The local symbol table -contains local variables of the current function invocation (including -the function arguments); the global symbol table contains variables -defined in the module containing the current function. - -The `global' symbol table is thus only global with respect to the -current function. There are no system-wide global variables; using -the {\tt import} statement it is easy enough to reference variables -that are defined in other modules. A system-wide read-only symbol -table is used for built-in functions and constants though. - -On assignment to a variable, by default an entry for it is made in the -local symbol table of the current execution environment. The {\tt -global} command can override this (it is not enough that a global -variable by the same name already exists). When a variable's value is -needed, it is searched first in the local symbol table, then in the -global one, and finally in the symbol table containing built-in -functions and constants. - -The term `variable' in this context refers to any name: functions and -imported modules are searched in exactly the same way. - -Names defined in a module's symbol table survive until the end of the -program. This approximates the semantics of file-static global -variables in C or module variables in Modula-3. A module is -initialized the first time it is imported, by executing the text of -the module as a parameterless function whose local and global symbol -tables are the same, so names are defined in module's symbol table. -(Modules implemented in C have another way to define symbols.) - -A Python main program is read from standard input or from a script -file passed as an argument to the interpreter. It is executed as if -an anonymous module was imported. Since {\tt import} statements are -executed like all other statements, the initialization order of the -modules used in a program is defined by the flow of control through -the program. - -The `attribute' notation {\em m.name}, where {\em m} is a module, -accesses the symbol {\em name} in that module's symbol table. It can -be assigned to as well. This is in fact a special case of the -construct {\em x.name} where {\em x} denotes an arbitrary object; the -type of {\em x} determines how this is to be interpreted, and what -assignment to it means. - -For instance, when {\tt a} is a list object, {\tt a.append} yields a -built-in `method' object which, when called, appends an item to {\tt a}. -(If {\tt a} and {\tt b} are distinct list objects, {\tt a.append} and -{\tt b.append} are distinguishable method objects.) Normally, in -statements like {\tt a.append(x)}, the method object {\tt a.append} is -called and then discarded, but this is a matter of convention. - -List attributes are read-only --- the user cannot define new list -methods. Some objects, like numbers and strings, have no attributes -at all. Like all type checking in Python, the meaning of an attribute -is determined at run-time --- when the parser sees {\em x.name}, it -has no idea of the type of {\em x}. Note that {\em x} here does not -have to be a variable --- it can be an arbitrary (perhaps -parenthesized) expression. - -Given the flexibility of the attribute notation, one is tempted to use -methods to replace all standard operations. Yet, Python has kept a -small repertoire of built-in functions like {\tt len()} and {\tt -abs()}. The reason is that in some cases the function notation is -more familiar than the method notation; just like programs would -become less readable if all infix operators were replaced by function -calls, they would become less readable if all function calls had to be -replaced by method calls (and vice versa!). - -The choice whether to make something a built-in function or a method -is a matter of taste. For arithmetic and string operations, function -notation is preferred, since frequently the argument to such an -operation is an expression using infix notation, as in {\tt abs(a+b)}; -this definitely looks better than {\tt (a+b).abs()}. The choice -between make something a built-in function or a function defined in a -built-in method (requiring {\tt import}) is similarly guided by -intuition; all in all, only functions needed by `general' programming -techniques are built-in functions. - -\subsection{Classes} - -Python has a class mechanism distinct from the object-orientation -already explained. A class in Python is not much more than a -collection of methods and a way to create class instances. Class -methods are ordinary functions whose first parameter is the class -instance; they are called using the method notation. - -For instance, a class can be defined as follows: -\begin{verbatim} -class Foo: - def meth1(self, arg): ... - def meth2(self): ... -\end{verbatim} -A class instance is created by -{\tt x = Foo()} -and its methods can be called thus: -\begin{verbatim} -x.meth1('Hi There!') -x.meth2() -\end{verbatim} -The functions used as methods are also available as attributes of the -class object, and the above method calls could also have been written -as follows: -\begin{verbatim} -Foo.meth1(x, 'Hi There!') -Foo.meth2(x) -\end{verbatim} -Class methods can store instance data by assigning to instance data -attributes, e.g.: -\begin{verbatim} -self.size = 100 -self.title = 'Dear John' -\end{verbatim} -Data attributes do not have to be declared; as with local variables, -they spring into existence when assigned to. It is a matter of -discretion to avoid name conflicts with method names. This facility -is also available to class users; instances of a method-less class can -be used as records with named fields. - -There is no built-in mechanism for instance initialization. Classes -by convention provide an {\tt init()} method which initializes the -instance and then returns it, so the user can write -\begin{verbatim} -x = Foo().init('Dr. Strangelove') -\end{verbatim} - -Any user-defined class can be used as a base class to derive other -classes. However, built-in types like lists cannot be used as base -classes. (Incidentally, the same is true in \Cpp{} and Modula-3.) A -class may override any method of its base classes. Instance methods -are first searched in the method list of their class, and then, -recursively, in the method lists of their base class. Initialization -methods of derived classes should explicitly call the initialization -methods of their base class. - -A simple form of multiple inheritance is also supported: a class can -have multiple base classes, but the language rules for resolving name -conflicts are somewhat simplistic, and consequently the feature has so -far found little usage. - -\subsection{The Python Library} - -Python comes with an extensive library, structured as a collection of -modules. A few modules are built into the interpreter: these -generally provide access to system libraries implemented in C such as -mathematical functions or operating system calls. Two built-in -modules provide access to internals of the interpreter and its -environment. Even abusing these internals will at most cause an -exception in the Python program; the interpreter will not dump core -because of errors in Python code. - -Most modules however are written in Python and distributed with the -interpreter; they provide general programming tools like string -operations and random number generators, provide more convenient -interfaces to some built-in modules, or provide specialized services -like a {\em getopt}-style command line option processor for -stand-alone scripts. - -There are also some modules written in Python that dig deep in the -internals of the interpreter; there is a module to browse the stack -backtrace when an unhandled exception has occurred, one to disassemble -the internal representation of Python code, and even an interactive -source code debugger which can trace Python code, set breakpoints, -etc. - -\subsection{Extensibility} - -It is easy to add new built-in modules written in C to the Python -interpreter. Extensions appear to the Python user as built-in -modules. Using a built-in module is no different from using a module -written in Python, but obviously the author of a built-in module can -do things that cannot be implemented purely in Python. - -In particular, built-in modules can contain Python-callable functions -that call functions from particular system libraries (`wrapper -functions'), and they can define new object types. In general, if a -built-in module defines a new object type, it should also provide at -least one function that creates such objects. Attributes of such -object types are also implemented in C; they can return data -associated with the object or methods, implemented as C functions. - -For instance, an extension was created for Amoeba: it provides wrapper -functions for the basic Amoeba name server functions, and defines a -`capability' object type, whose methods are file server operations. -Another extension is a built-in module called {\tt posix}; it provides -wrappers around post UNIX system calls. Extension modules also -provide access to two different windowing/graphics interfaces: STDWIN -\cite{STDWIN} -(which connects to X11 on UNIX and to the Mac Toolbox on the -Macintosh), and the Graphics Library (GL) for Silicon Graphics -machines. - -Any function in an extension module is supposed to type-check its -arguments; the interpreter contains a convenience function to -facilitate extracting C values from arguments and type-checking them -at the same time. Returning values is also painless, using standard -functions to create Python objects from C values. - -On some systems extension modules may be dynamically loaded, thus -avoiding the need to maintain a private copy of the Python interpreter -in order to use a private extension. - -\section{A Short Description of AIL and Amoeba} - -An RPC stub generator takes an interface description as input. The -designer of a stub generator has at least two choices for the input -language: use a suitably restricted version of the target language, or -design a new language. The first solution was chosen, for instance, -by the designers of Flume, the stub generator for the Topaz -distributed operating system built at DEC SRC -\cite{Flume,Evolving}. - -Flume's one and only target language is Modula-2+ (the predecessor of -Modula-3). Modula-2+, like Modula-N for any N, has an interface -syntax that is well suited as a stub generator input language: an -interface module declares the functions that are `exported' by a -module implementation, with their parameter and return types, plus the -types and constants used for the parameters. Therefore, the input to -Flume is simply a Modula-2+ interface module. But even in this ideal -situation, an RPC stub generator needs to know things about functions -that are not stated explicitly in the interface module: for instance, -the transfer direction of VAR parameters (IN, OUT or both) is not -given. Flume solves this and other problems by a mixture of -directives hidden in comments and a convention for the names of -objects. Thus, one could say that the designers of Flume really -created a new language, even though it looks remarkably like their -target language. - -\subsection{The AIL Input Language} - -Amoeba uses C as its primary programming language. C function -declarations (at least in `Classic' C) don't specify the types of -the parameters, let alone their transfer direction. Using this as -input for a stub generator would require almost all information for -the stub generator to be hidden inside comments, which would require a -rather contorted scanner. Therefore we decided to design the input -syntax for Amoeba's stub generator `from scratch'. This gave us the -liberty to invent proper syntax not only for the transfer direction of -parameters, but also for variable-length arrays. - -On the other hand we decided not to abuse our freedom, and borrowed as -much from C as we could. For instance, AIL runs its input through the -C preprocessor, so we get macros, include files and conditional -compilation for free. AIL's type declaration syntax is a superset of -C's, so the user can include C header files to use the types declared -there as function parameter types --- which are declared using -function prototypes as in \Cpp{} or Standard C\@. It should be clear by -now that AIL's lexical conventions are also identical to C's. The -same is true for its expression syntax. - -Where does AIL differ from C, then? Function declarations in AIL are -grouped in {\em classes}. Classes in AIL are mostly intended as a -grouping mechanism: all functions implemented by a server are grouped -together in a class. Inheritance is used to form new groups by adding -elements to existing groups; multiple inheritance is supported to join -groups together. Classes can also contain constant and type -definitions, and one form of output that AIL can generate is a header -file for use by C programmers who wish to use functions from a -particular AIL class. - -Let's have a look at some (unrealistically simple) class definitions: -\begin{verbatim} -#include <amoeba.h> /* Defines `capability', etc. */ - -class standard_ops [1000 .. 1999] { - /* Operations supported by most interfaces */ - std_info(*, out char buf[size:100], out int size); - std_destroy(*); -}; -\end{verbatim} -This defines a class called `standard\_ops' whose request codes are -chosen by AIL from the range 1000-1999. Request codes are small -integers used to identify remote operations. The author of the class -must specify a range from which AIL chooses, and class authors must -make sure they avoid conflicts, e.g. by using an `assigned number -administration office'. In the example, `std\_info' will be assigned -request code 1000 and `std\_destroy' will get code 1001. There is -also an option to explicitly assign request codes, for compatibility -with servers with manually written interfaces. - -The class `standard\_ops' defines two operations, `std\_info' and -`std\_destroy'. The first parameter of each operation is a star -(`*'); this is a placeholder for a capability that must be passed when -the operation is called. The description of Amoeba below explains the -meaning and usage of capabilities; for now, it is sufficient to know -that a capability is a small structure that uniquely identifies an -object and a server or service. - -The standard operation `std\_info' has two output parameters: a -variable-size character buffer (which will be filled with a short -descriptive string of the object to which the operation is applied) -and an integer giving the length of this string. The standard -operation `std\_destroy' has no further parameters --- it just -destroys the object, if the caller has the right to do so. - -The next class is called `tty': -\begin{verbatim} -class tty [2000 .. 2099] { - inherit standard_ops; - const TTY_MAXBUF = 1000; - tty_write(*, char buf[size:TTY_MAXBUF], int size); - tty_read(*, out char buf[size:TTY_MAXBUF], out int size); -}; -\end{verbatim} -The request codes for operations defined in this class lie in the -range 2000-2099; inherited operations use the request codes already -assigned to them. The operations defined by this class are -`tty\_read' and `tty\_write', which pass variable-sized data buffers -between client and server. Class `tty' inherits class -`standard\_ops', so tty objects also support the operations -`std\_info' and `std\_destroy'. - -Only the {\em interface} for `std\_info' and `std\_destroy' is shared -between tty objects and other objects whose interface inherits -`standard\_ops'; the implementation may differ. Even multiple -implementations of the `tty' interface may exist, e.g. a driver for a -console terminal and a terminal emulator in a window. To expand on -the latter example, consider: -\begin{verbatim} -class window [2100 .. 2199] { - inherit standard_ops; - win_create(*, int x, int y, int width, int height, - out capability win_cap); - win_reconfigure(*, int x, int y, int width, int height); -}; - -class tty_emulator [2200 .. 2299] { - inherit tty, window; -}; -\end{verbatim} -Here two new interface classes are defined. -Class `window' could be used for creating and manipulating windows. -Note that `win\_create' returns a capability for the new window. -This request should probably should be sent to a generic window -server capability, or it might create a subwindow when applied to a -window object. - -Class `tty\_emulator' demonstrates the essence of multiple inheritance. -It is presumably the interface to a window-based terminal emulator. -Inheritance is transitive, so `tty\_emulator' also implicitly inherits -`standard\_ops'. -In fact, it inherits it twice: once via `tty' and once via `window'. -Since AIL class inheritance only means interface sharing, not -implementation sharing, inheriting the same class multiple times is -never a problem and has the same effect as inheriting it once. - -Note that the power of AIL classes doesn't go as far as \Cpp{}. -AIL classes cannot have data members, and there is -no mechanism for a server that implements a derived class -to inherit the implementation of the base -class --- other than copying the source code. -The syntax for class definitions and inheritance is also different. - -\subsection{Amoeba} - -The smell of `object-orientedness' that the use of classes in AIL -creates matches nicely with Amoeba's object-oriented approach to -RPC\@. In Amoeba, almost all operating system entities (files, -directories, processes, devices etc.) are implemented as {\em -objects}. Objects are managed by {\em services} and represented by -{\em capabilities}. A capability gives its holder access to the -object it represents. Capabilities are protected cryptographically -against forgery and can thus be kept in user space. A capability is a -128-bit binary string, subdivided as follows: - -% XXX Need a better version of this picture! -\begin{verbatim} - 48 24 8 48 Bits -+----------------+------------+--------+---------------+ -| Service | Object | Perm. | Check | -| port | number | bits | word | -+----------------+------------+--------+---------------+ -\end{verbatim} - -The service port is used by the RPC implementation in the Amoeba -kernel to locate a server implementing the service that manages the -object. In many cases there is a one-to-one correspondence between -servers and services (each service is implemented by exactly one -server process), but some services are replicated. For instance, -Amoeba's directory service, which is crucial for gaining access to most -other services, is implemented by two servers that listen on the same -port and know about exactly the same objects. - -The object number in the capability is used by the server receiving -the request for identifying the object to which the operation applies. -The permission bits specify which operations the holder of the capability -may apply. The last part of a capability is a 48-bit long `check -word', which is used to prevent forgery. The check word is computed -by the server based upon the permission bits and a random key per object -that it keeps secret. If you change the permission bits you must compute -the proper check word or else the server will refuse the capability. -Due to the size of the check word and the nature of the cryptographic -`one-way function' used to compute it, inverting this function is -impractical, so forging capabilities is impossible.% -\footnote{ -As computers become faster, inverting the one-way function becomes -less impractical. -Therefore, a next version of Amoeba will have 64-bit check words. -} - -A working Amoeba system is a collection of diverse servers, managing -files, directories, processes, devices etc. While most servers have -their own interface, there are some requests that make sense for some -or all object types. For instance, the {\em std\_info()} request, -which returns a short descriptive string, applies to all object types. -Likewise, {\em std\_destroy()} applies to files, directories and -processes, but not to devices. - -Similarly, different file server implementations may want to offer the -same interface for operations like {\em read()} and {\em write()} to -their clients. AIL's grouping of requests into classes is ideally -suited to describe this kind of interface sharing, and a class -hierarchy results which clearly shows the similarities between server -interfaces (not necessarily their implementations!). - -The base class of all classes defines the {\em std\_info()} request. -Most server interfaces actually inherit a derived class that also -defines {\em std\_destroy().} File servers inherit a class that -defines the common operations on files, etc. - -\subsection{How AIL Works} - -The AIL stub generator functions in three phases: -\begin{itemize} -\item -parsing, -\item -strategy determination, -\item -code generation. -\end{itemize} - -{\bf Phase one} parses the input and builds a symbol table containing -everything it knows about the classes and other definitions found in -the input. - -{\bf Phase two} determines the strategy to use for each function -declaration in turn and decides upon the request and reply message -formats. This is not a simple matter, because of various optimization -attempts. Amoeba's kernel interface for RPC requests takes a -fixed-size header and one arbitrary-size buffer. A large part of the -header holds the capability of the object to which the request is -directed, but there is some space left for a few integer parameters -whose interpretation is left up to the server. AIL tries to use these -slots for simple integer parameters, for two reasons. - -First, unlike the buffer, header fields are byte-swapped by the RPC -layer in the kernel if necessary, so it saves a few byte swapping -instructions in the user code. Second, and more important, a common -form of request transfers a few integers and one large buffer to or -from a server. The {\em read()} and {\em write()} requests of most -file servers have this form, for instance. If it is possible to place -all integer parameters in the header, the address of the buffer -parameter can be passed directly to the kernel RPC layer. While AIL -is perfectly capable of handling requests that do not fit this format, -the resulting code involves allocating a new buffer and copying all -parameters into it. It is a top priority to avoid this copying -(`marshalling') if at all possible, in order to maintain Amoeba's -famous RPC performance. - -When AIL resorts to copying parameters into a buffer, it reorders them -so that integers indicating the lengths of variable-size arrays are -placed in the buffer before the arrays they describe, since otherwise -decoding the request would be impossible. It also adds occasional -padding bytes to ensure integers are aligned properly in the buffer --- -this can speed up (un)marshalling. - -{\bf Phase three} is the code generator, or back-end. There are in -fact many different back-ends that may be called in a single run to -generate different types of output. The most important output types -are header files (for inclusion by the clients of an interface), -client stubs, and `server main loop' code. The latter decodes -incoming requests in the server. The generated code depends on the -programming language requested, and there are separate back-ends for -each supported language. - -It is important that the strategy chosen by phase two is independent -of the language requested for phase three --- otherwise the -interoperability of servers and clients written in different languages -would be compromised. - -\section{Linking AIL to Python} - -From the previous section it can be concluded that linking AIL to -Python is a matter of writing a back-end for Python. This is indeed -what we did. - -Considerable time went into the design of the back-end in order to -make the resulting RPC interface for Python fit as smoothly as -possible in Python's programming style. For instance, the issues of -parameter transfer, variable-size arrays, error handling, and call -syntax were all solved in a manner that favors ease of use in Python -rather than strict correspondence with the stubs generated for C, -without compromising network-level compatibility. - -\subsection{Mapping AIL Entities to Python} - -For each programming language that AIL is to support, a mapping must -be designed between the data types in AIL and those in that language. -Other aspects of the programming languages, such as differences in -function call semantics, must also be taken care of. - -While the mapping for C is mostly straightforward, the mapping for -Python requires a little thinking to get the best results for Python -programmers. - -\subsubsection{Parameter Transfer Direction} - -Perhaps the simplest issue is that of parameter transfer direction. -Parameters of functions declared in AIL are categorized as being of -type {\tt in}, {\tt out} or {\tt in} {\tt out} (the same distinction -as made in Ada). Python only has call-by-value parameter semantics; -functions can return multiple values as a tuple. This means that, -unlike the C back-end, the Python back-end cannot always generate -Python functions with exactly the same parameter list as the AIL -functions. - -Instead, the Python parameter list consists of all {\tt in} and {\tt -in} {\tt out} parameters, in the order in which they occur in the AIL -parameter list; similarly, the Python function returns a tuple -containing all {\tt in} {\tt out} and {\tt out} parameters. In fact -Python packs function parameters into a tuple as well, stressing the -symmetry between parameters and return value. For example, a stub -with this AIL parameter list: -\begin{verbatim} -(*, in int p1, in out int p2, in int p3, out int p4) -\end{verbatim} -will have the following parameter list and return values in Python: -\begin{verbatim} -(p1, p2, p3) -> (p2, p4) -\end{verbatim} - -\subsubsection{Variable-size Entities} - -The support for variable-size objects in AIL is strongly guided by the -limitations of C in this matter. Basically, AIL allows what is -feasible in C: functions may have variable-size arrays as parameters -(both input or output), provided their length is passed separately. -In practice this is narrowed to the following rule: for each -variable-size array parameter, there must be an integer parameter -giving its length. (An exception for null-terminated strings is -planned but not yet realized.) - -Variable-size arrays in AIL or C correspond to {\em sequences} in -Python: lists, tuples or strings. These are much easier to use than -their C counterparts. Given a sequence object in Python, it is always -possible to determine its size: the built-in function {\tt len()} -returns it. It would be annoying to require the caller of an RPC stub -with a variable-size parameter to also pass a parameter that -explicitly gives its size. Therefore we eliminate all parameters from -the Python parameter list whose value is used as the size of a -variable-size array. Such parameters are easily found: the array -bound expression contains the name of the parameter giving its size. -This requires the stub code to work harder (it has to recover the -value for size parameters from the corresponding sequence parameter), -but at least part of this work would otherwise be needed as well, to -check that the given and actual sizes match. - -Because of the symmetry in Python between the parameter list and the -return value of a function, the same elimination is performed on -return values containing variable-size arrays: integers returned -solely to tell the client the size of a returned array are not -returned explicitly to the caller in Python. - -\subsubsection{Error Handling} - -Another point where Python is really better than C is the issue of -error handling. It is a fact of life that everything involving RPC -may fail, for a variety of reasons outside the user's control: the -network may be disconnected, the server may be down, etc. Clients -must be prepared to handle such failures and recover from them, or at -least print an error message and die. In C this means that every -function returns an error status that must be checked by the caller, -causing programs to be cluttered with error checks --- or worse, -programs that ignore errors and carry on working with garbage data. - -In Python, errors are generally indicated by exceptions, which can be -handled out of line from the main flow of control if necessary, and -cause immediate program termination (with a stack trace) if ignored. -To profit from this feature, all RPC errors that may be encountered by -AIL-generated stubs in Python are turned into exceptions. An extra -value passed together with the exception is used to relay the error -code returned by the server to the handler. Since in general RPC -failures are rare, Python test programs can usually ignore exceptions ---- making the program simpler --- without the risk of occasional -errors going undetected. (I still remember the embarrassment of a -hundredfold speed improvement reported, long, long, ago, about a new -version of a certain program, which later had to be attributed to a -benchmark that silently dumped core...) - -\subsubsection{Function Call Syntax} - -Amoeba RPC operations always need a capability parameter (this is what -the `*' in the AIL function templates stands for); the service is -identified by the port field of the capability. In C, the capability -must always be the first parameter of the stub function, but in Python -we can do better. - -A Python capability is an opaque object type in its own right, which -is used, for instance, as parameter to and return value from Amoeba's -name server functions. Python objects can have methods, so it is -convenient to make all AIL-generated stubs methods of capabilities -instead of just functions. Therefore, instead of writing -\begin{verbatim} -some_stub(cap, other_parameters) -\end{verbatim} -as in C, Python programmers can write -\begin{verbatim} -cap.some_stub(other_parameters) -\end{verbatim} -This is better because it reduces name conflicts: in Python, no -confusion is possible between a stub and a local or global variable or -user-defined function with the same name. - -\subsubsection{Example} - -All the preceding principles can be seen at work in the following -example. Suppose a function is declared in AIL as follows: -\begin{verbatim} -some_stub(*, in char buf[size:1000], in int size, - out int n_done, out int status); -\end{verbatim} -In C it might be called by the following code (including declarations, -for clarity, but not initializations): -\begin{verbatim} -int err, n_done, status; -capability cap; -char buf[500]; -... -err = some_stub(&cap, buf, sizeof buf, &n_done, &status); -if (err != 0) return err; -printf("%d done; status = %d\n", n_done, status); -\end{verbatim} -Equivalent code in Python might be the following: -\begin{verbatim} -cap = ... -buf = ... -n_done, status = cap.some_stub(buf) -print n_done, 'done;', 'status =', status -\end{verbatim} -No explicit error check is required in Python: if the RPC fails, an -exception is raised so the {\tt print} statement is never reached. - -\subsection{The Implementation} - -More or less orthogonal to the issue of how to map AIL operations to -the Python language is the question of how they should be implemented. - -In principle it would be possible to use the same strategy that is -used for C: add an interface to Amoeba's low-level RPC primitives to -Python and generate Python code to marshal parameters into and out of -a buffer. However, Python's high-level data types are not well suited -for marshalling: byte-level operations are clumsy and expensive, with -the result that marshalling a single byte of data can take several -Python statements. This would mean that a large amount of code would -be needed to implement a stub, which would cost a lot of time to parse -and take up a lot of space in `compiled' form (as parse tree or pseudo -code). Execution of the marshalling code would be sluggish as well. - -We therefore chose an alternate approach, writing the marshalling in -C, which is efficient at such byte-level operations. While it is easy -enough to generate C code that can be linked with the Python -interpreter, it would obviously not stimulate the use of Python for -server testing if each change to an interface required relinking the -interpreter (dynamic loading of C code is not yet available on -Amoeba). This is circumvented by the following solution: the -marshalling is handled by a simple {\em virtual machine}, and AIL -generates instructions for this machine. An interpreter for the -machine is linked into the Python interpreter and reads its -instructions from a file written by AIL. - -The machine language for our virtual machine is dubbed {\em Stubcode}. -Stubcode is a super-specialized language. There are two sets of of -about a dozen instructions each: one set marshals Python objects -representing parameters into a buffer, the other set (similar but not -quite symmetric) unmarshals results from a buffer into Python objects. -The Stubcode interpreter uses a stack to hold Python intermediate -results. Other state elements are an Amoeba header and buffer, a -pointer indicating the current position in the buffer, and of course a -program counter. Besides (un)marshalling, the virtual machine must -also implement type checking, and raise a Python exception when a -parameter does not have the expected type. - -The Stubcode interpreter marshals Python data types very efficiently, -since each instruction can marshal a large amount of data. For -instance, a whole Python string is marshalled by a single Stubcode -instruction, which (after some checking) executes the most efficient -byte-copying loop possible --- it calls {\tt memcpy()}. - - -Construction details of the Stubcode interpreter are straightforward. -Most complications are caused by the peculiarities of AIL's strategy -module and Python's type system. By far the most complex single -instruction is the `loop' instruction, which is used to marshal -arrays. - -As an example, here is the complete Stubcode program (with spaces and -comments added for clarity) generated for the function {\tt -some\_stub()} of the example above. The stack contains pointers to -Python objects, and its initial contents is the parameter to the -function, the string {\tt buf}. The final stack contents will be the -function return value, the tuple {\tt (n\_done, status)}. The name -{\tt header} refers to the fixed size Amoeba RPC header structure. -\vspace{1em} - -{\tt -\begin{tabular}{l l l} -BufSize & 1000 & {\em Allocate RPC buffer of 1000 bytes} \\ -Dup & 1 & {\em Duplicate stack top} \\ -StringS & & {\em Replace stack top by its string size} \\ -PutI & h\_extra int32 & {\em Store top element in }header.h\_extra \\ -TStringSlt & 1000 & {\em Assert string size less than 1000} \\ -PutVS & & {\em Marshal variable-size string} \\ - & & \\ -Trans & 1234 & {\em Execute the RPC (request code 1234)} \\ - & & \\ -GetI & h\_extra int32 & {\em Push integer from} header.h\_extra \\ -GetI & h\_size int32 & {\em Push integer from} header.h\_size \\ -Pack & 2 & {\em Pack top 2 elements into a tuple} \\ -\end{tabular} -} -\vspace{1em} - -As much work as possible is done by the Python back-end in AIL, rather -than in the Stubcode interpreter, to make the latter both simple and -fast. For instance, the decision to eliminate an array size parameter -from the Python parameter list is taken by AIL, and Stubcode -instructions are generated to recover the size from the actual -parameter and to marshal it properly. Similarly, there is a special -alignment instruction (not used in the example) to meet alignment -requirements. - -Communication between AIL and the Stubcode generator is via the file -system. For each stub function, AIL creates a file in its output -directory, named after the stub with a specific suffix. This file -contains a machine-readable version of the Stubcode program for the -stub. The Python user can specify a search path containing -directories which the interpreter searches for a Stubcode file the -first time the definition for a particular stub is needed. - -The transformations on the parameter list and data types needed to map -AIL data types to Python data types make it necessary to help the -Python programmer a bit in figuring out the parameters to a call. -Although in most cases the rules are simple enough, it is sometimes -hard to figure out exactly what the parameter and return values of a -particular stub are. There are two sources of help in this case: -first, the exception contains enough information so that the user can -figure what type was expected; second, AIL's Python back-end -optionally generates a human-readable `interface specification' file. - -\section{Conclusion} - -We have succeeded in creating a useful extension to Python that -enables Amoeba server writers to test and experiment with their server -in a much more interactive manner. We hope that this facility will -add to the popularity of AIL amongst Amoeba programmers. - -Python's extensibility was proven convincingly by the exercise -(performed by the second author) of adding the Stubcode interpreter to -Python. Standard data abstraction techniques are used to insulate -extension modules from details of the rest of the Python interpreter. -In the case of the Stubcode interpreter this worked well enough that -it survived a major overhaul of the main Python interpreter virtually -unchanged. - -On the other hand, adding a new back-end to AIL turned out to be quite -a bit of work. One problem, specific to Python, was to be expected: -Python's variable-size data types differ considerably from the -C-derived data model that AIL favors. Two additional problems we -encountered were the complexity of the interface between AIL's second -and third phases, and a number of remaining bugs in the second phase -that surfaced when the implementation of the Python back-end was -tested. The bugs have been tracked down and fixed, but nothing -has been done about the complexity of the interface. - -\subsection{Future Plans} - -AIL's C back-end generates server main loop code as well as client -stubs. The Python back-end currently only generates client stubs, so -it is not yet possible to write servers in Python. While it is -clearly more important to be able to use Python as a client than as a -server, the ability to write server prototypes in Python would be a -valuable addition: it allows server designers to experiment with -interfaces in a much earlier stage of the design, with a much smaller -programming effort. This makes it possible to concentrate on concepts -first, before worrying about efficient implementation. - -The unmarshalling done in the server is almost symmetric with the -marshalling in the client, and vice versa, so relative small -extensions to the Stubcode virtual machine will allow its use in a -server main loop. We hope to find the time to add this feature to a -future version of Python. - -\section{Availability} - -The Python source distribution is available to Internet users by -anonymous ftp to site {\tt ftp.cwi.nl} [IP address 192.16.184.180] -from directory {\tt /pub}, file name {\tt python*.tar.Z} (where the -{\tt *} stands for a version number). This is a compressed UNIX tar -file containing the C source and \LaTeX documentation for the Python -interpreter. It includes the Python library modules and the {\em -Stubcode} interpreter, as well as many example Python programs. Total -disk space occupied by the distribution is about 3 Mb; compilation -requires 1-3 Mb depending on the configuration built, the compile -options, etc. - -\bibliographystyle{plain} - -\bibliography{quabib} - -\end{document} diff --git a/Doc/quabib.bib b/Doc/quabib.bib deleted file mode 100644 index 97b93f6d55..0000000000 --- a/Doc/quabib.bib +++ /dev/null @@ -1,139 +0,0 @@ -@inproceedings{bult:usenix91, - title = "A Structure for Transportable, Dynamic Multimedia Documents", - author = "Dick C.A. Bulterman - and Guido van Rossum - and Robert van Liere", - booktitle = "Proceedings of the 1991 Summer USENIX Conference", - publisher = "The USENIX Association", - year = "1991", -} - -@techreport{bult:gogh90, - title = "The {CWI} van {G}ogh Multimedia Research Project: Goals - and Objectives", - author = "Dick C.A. Bulterman", - institution = "CWI", - year = "1990", - number = "CST-90.1004", -} - -@article{Amoeba:IEEE, - title = "{A}moeba: A Distributed Operating System for the 1990s", - author = "S.J. Mullender - and G. van Rossum - and A.S. Tanenbaum - and R. van Renesse - and J.M. van Staveren", - journal = "IEEE Computer Magazine", - volume = "23", - number = "5", - month = "May", - year = "1990", - pages = "44-53", -} - -@article{Amoeba:CACM, - title = "Experiences with the {A}moeba Distributed Operating System", - author = "A.S. Tanenbaum -and R. van Renesse -and J.M. van Staveren -and G.J. Sharp -and S.J. Mullender -and A.J. Jansen -and G. van Rossum", -journal = "Communications of the ACM", -volume = "33", -number = "12", -month = "December", -year ="1990", -pages = "46-63", -} - -@inproceedings{AIL, -title = "{AIL} --- A Class-Oriented Stub Generator for {A}moeba", -author = "G. van Rossum", -editor = {E W. Schr\"{o}der-Preikschat -and E. W. Zimmer}, -booktitle = "Workshop on Progress in Distributed Operating Systems and Distributed Systems Management", -publisher = "Springer Verlag", -series = "Lecture Notes in Computer Science", -volume = "433", -year = "1990", -pages = "13-21", -} - -@techreport{STDWIN, -title = "{STDWIN} --- A Standard Window System Interface", -author = "G. van Rossum", -number = "CS-R8817", -institution = "CWI", -address = "Amsterdam", -month = "April", -year = "1988", -} - -@book{ABC, -title = "{ABC} Programmer's Handbook", -author = "Leo Geurts -and Lambert Meertens -and Steven Pemberton", -publisher = "Prentice-Hall", -address = "London", -year = "1990", -note = "ISBN 0-13-000027-2", -} - -@manual{Flume, -title = "{F}lume --- Remote Procedure Call Stub Generator for {M}odula-2+", -author = "A.D. Birrell -and E.D. Lazowska -and E. Wobber", -organization = "DEC SRC", -address = "Palo Alto, CA", -year = "1987", -note = "(Topaz manual page)", -} - -@techreport{Evolving, -title = "Evolving the {UNIX} System Interface to Support Multithreaded Programs", -author = "P.R. McJones -and G.F. Swart", -number = "21", -institution = "DEC SRC", -address = "Palo Alto, CA", -month = "September", -year = "1987", -} - -@inproceedings{Tcl, -title = "{T}cl: an Embeddable Command Language", -author = "John K. Ousterhout", -booktitle = "Proceedings of the Winter 1990 USENIX Conference", -publisher = "USENIX Association", -address = "Washington, DC", -month = "January", -year = "1990", -pages = "133-146", -} - -@article{RPC, -title = "Implementing Remote Procedure Calls", -author = "A. D. Birrell -and B. J. Nelson", -journal = "ACM Transactions on Computer Systems", -volume = "2", -number = "1", -month = "February", -year = "1984", -pages = "39-59", -} - -@techreport{Modula-3, -title = "{M}odula-3 Report (revised)", -author = "Luca Cardelli et al.", -number = "52", -institution = "DEC SRC", -address = "Palo Alto, CA", -month = "November", -year = "1989", -} diff --git a/Doc/ref.tex b/Doc/ref.tex deleted file mode 100644 index e63fa7c3d6..0000000000 --- a/Doc/ref.tex +++ /dev/null @@ -1,68 +0,0 @@ -\documentstyle[twoside,11pt,myformat]{report} - -\title{Python Reference Manual} - -\input{boilerplate} - -% Tell \index to actually write the .idx file -\makeindex - -\begin{document} - -\pagenumbering{roman} - -\maketitle - -\input{copyright} - -\begin{abstract} - -\noindent -Python is a simple, yet powerful, interpreted programming language -that bridges the gap between C and shell programming, and is thus -ideally suited for ``throw-away programming'' and rapid prototyping. -Its syntax is put together from constructs borrowed from a variety of -other languages; most prominent are influences from ABC, C, Modula-3 -and Icon. - -The Python interpreter is easily extended with new functions and data -types implemented in C. Python is also suitable as an extension -language for highly customizable C applications such as editors or -window managers. - -Python is available for various operating systems, amongst which -several flavors of {\UNIX} (including Linux), the Apple Macintosh O.S., -MS-DOS, MS-Windows 3.1, Windows NT, and OS/2. - -This reference manual describes the syntax and ``core semantics'' of -the language. It is terse, but attempts to be exact and complete. -The semantics of non-essential built-in object types and of the -built-in functions and modules are described in the {\em Python -Library Reference}. For an informal introduction to the language, see -the {\em Python Tutorial}. - -\end{abstract} - -\pagebreak - -{ -\parskip = 0mm -\tableofcontents -} - -\pagebreak - -\pagenumbering{arabic} - -\include{ref1} % Introduction -\include{ref2} % Lexical analysis -\include{ref3} % Data model -\include{ref4} % Execution model -\include{ref5} % Expressions and conditions -\include{ref6} % Simple statements -\include{ref7} % Compound statements -\include{ref8} % Top-level components - -\input{ref.ind} - -\end{document} diff --git a/Doc/ref/ref.tex b/Doc/ref/ref.tex deleted file mode 100644 index e63fa7c3d6..0000000000 --- a/Doc/ref/ref.tex +++ /dev/null @@ -1,68 +0,0 @@ -\documentstyle[twoside,11pt,myformat]{report} - -\title{Python Reference Manual} - -\input{boilerplate} - -% Tell \index to actually write the .idx file -\makeindex - -\begin{document} - -\pagenumbering{roman} - -\maketitle - -\input{copyright} - -\begin{abstract} - -\noindent -Python is a simple, yet powerful, interpreted programming language -that bridges the gap between C and shell programming, and is thus -ideally suited for ``throw-away programming'' and rapid prototyping. -Its syntax is put together from constructs borrowed from a variety of -other languages; most prominent are influences from ABC, C, Modula-3 -and Icon. - -The Python interpreter is easily extended with new functions and data -types implemented in C. Python is also suitable as an extension -language for highly customizable C applications such as editors or -window managers. - -Python is available for various operating systems, amongst which -several flavors of {\UNIX} (including Linux), the Apple Macintosh O.S., -MS-DOS, MS-Windows 3.1, Windows NT, and OS/2. - -This reference manual describes the syntax and ``core semantics'' of -the language. It is terse, but attempts to be exact and complete. -The semantics of non-essential built-in object types and of the -built-in functions and modules are described in the {\em Python -Library Reference}. For an informal introduction to the language, see -the {\em Python Tutorial}. - -\end{abstract} - -\pagebreak - -{ -\parskip = 0mm -\tableofcontents -} - -\pagebreak - -\pagenumbering{arabic} - -\include{ref1} % Introduction -\include{ref2} % Lexical analysis -\include{ref3} % Data model -\include{ref4} % Execution model -\include{ref5} % Expressions and conditions -\include{ref6} % Simple statements -\include{ref7} % Compound statements -\include{ref8} % Top-level components - -\input{ref.ind} - -\end{document} diff --git a/Doc/ref/ref1.tex b/Doc/ref/ref1.tex deleted file mode 100644 index 30bfcce022..0000000000 --- a/Doc/ref/ref1.tex +++ /dev/null @@ -1,81 +0,0 @@ -\chapter{Introduction} - -This reference manual describes the Python programming language. -It is not intended as a tutorial. - -While I am trying to be as precise as possible, I chose to use English -rather than formal specifications for everything except syntax and -lexical analysis. This should make the document more understandable -to the average reader, but will leave room for ambiguities. -Consequently, if you were coming from Mars and tried to re-implement -Python from this document alone, you might have to guess things and in -fact you would probably end up implementing quite a different language. -On the other hand, if you are using -Python and wonder what the precise rules about a particular area of -the language are, you should definitely be able to find them here. - -It is dangerous to add too many implementation details to a language -reference document --- the implementation may change, and other -implementations of the same language may work differently. On the -other hand, there is currently only one Python implementation, and -its particular quirks are sometimes worth being mentioned, especially -where the implementation imposes additional limitations. Therefore, -you'll find short ``implementation notes'' sprinkled throughout the -text. - -Every Python implementation comes with a number of built-in and -standard modules. These are not documented here, but in the separate -{\em Python Library Reference} document. A few built-in modules are -mentioned when they interact in a significant way with the language -definition. - -\section{Notation} - -The descriptions of lexical analysis and syntax use a modified BNF -grammar notation. This uses the following style of definition: -\index{BNF} -\index{grammar} -\index{syntax} -\index{notation} - -\begin{verbatim} -name: lc_letter (lc_letter | "_")* -lc_letter: "a"..."z" -\end{verbatim} - -The first line says that a \verb@name@ is an \verb@lc_letter@ followed by -a sequence of zero or more \verb@lc_letter@s and underscores. An -\verb@lc_letter@ in turn is any of the single characters `a' through `z'. -(This rule is actually adhered to for the names defined in lexical and -grammar rules in this document.) - -Each rule begins with a name (which is the name defined by the rule) -and a colon. A vertical bar (\verb@|@) is used to separate -alternatives; it is the least binding operator in this notation. A -star (\verb@*@) means zero or more repetitions of the preceding item; -likewise, a plus (\verb@+@) means one or more repetitions, and a -phrase enclosed in square brackets (\verb@[ ]@) means zero or one -occurrences (in other words, the enclosed phrase is optional). The -\verb@*@ and \verb@+@ operators bind as tightly as possible; -parentheses are used for grouping. Literal strings are enclosed in -quotes. White space is only meaningful to separate tokens. -Rules are normally contained on a single line; rules with many -alternatives may be formatted alternatively with each line after the -first beginning with a vertical bar. - -In lexical definitions (as the example above), two more conventions -are used: Two literal characters separated by three dots mean a choice -of any single character in the given (inclusive) range of \ASCII{} -characters. A phrase between angular brackets (\verb@<...>@) gives an -informal description of the symbol defined; e.g. this could be used -to describe the notion of `control character' if needed. -\index{lexical definitions} -\index{ASCII} - -Even though the notation used is almost the same, there is a big -difference between the meaning of lexical and syntactic definitions: -a lexical definition operates on the individual characters of the -input source, while a syntax definition operates on the stream of -tokens generated by the lexical analysis. All uses of BNF in the next -chapter (``Lexical Analysis'') are lexical definitions; uses in -subsequent chapters are syntactic definitions. diff --git a/Doc/ref/ref2.tex b/Doc/ref/ref2.tex deleted file mode 100644 index 9ccfee6ce1..0000000000 --- a/Doc/ref/ref2.tex +++ /dev/null @@ -1,372 +0,0 @@ -\chapter{Lexical analysis} - -A Python program is read by a {\em parser}. Input to the parser is a -stream of {\em tokens}, generated by the {\em lexical analyzer}. This -chapter describes how the lexical analyzer breaks a file into tokens. -\index{lexical analysis} -\index{parser} -\index{token} - -\section{Line structure} - -A Python program is divided in a number of logical lines. The end of -a logical line is represented by the token NEWLINE. Statements cannot -cross logical line boundaries except where NEWLINE is allowed by the -syntax (e.g. between statements in compound statements). -\index{line structure} -\index{logical line} -\index{NEWLINE token} - -\subsection{Comments} - -A comment starts with a hash character (\verb@#@) that is not part of -a string literal, and ends at the end of the physical line. A comment -always signifies the end of the logical line. Comments are ignored by -the syntax. -\index{comment} -\index{logical line} -\index{physical line} -\index{hash character} - -\subsection{Explicit line joining} - -Two or more physical lines may be joined into logical lines using -backslash characters (\verb/\/), as follows: when a physical line ends -in a backslash that is not part of a string literal or comment, it is -joined with the following forming a single logical line, deleting the -backslash and the following end-of-line character. For example: -\index{physical line} -\index{line joining} -\index{line continuation} -\index{backslash character} -% -\begin{verbatim} -if 1900 < year < 2100 and 1 <= month <= 12 \ - and 1 <= day <= 31 and 0 <= hour < 24 \ - and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date - return 1 -\end{verbatim} - -A line ending in a backslash cannot carry a comment; a backslash does -not continue a comment (but it does continue a string literal, see -below). - -\subsection{Implicit line joining} - -Expressions in parentheses, square brackets or curly braces can be -split over more than one physical line without using backslashes. -For example: - -\begin{verbatim} -month_names = ['Januari', 'Februari', 'Maart', # These are the - 'April', 'Mei', 'Juni', # Dutch names - 'Juli', 'Augustus', 'September', # for the months - 'Oktober', 'November', 'December'] # of the year -\end{verbatim} - -Implicitly continued lines can carry comments. The indentation of the -continuation lines is not important. Blank continuation lines are -allowed. - -\subsection{Blank lines} - -A logical line that contains only spaces, tabs, and possibly a -comment, is ignored (i.e., no NEWLINE token is generated), except that -during interactive input of statements, an entirely blank logical line -terminates a multi-line statement. -\index{blank line} - -\subsection{Indentation} - -Leading whitespace (spaces and tabs) at the beginning of a logical -line is used to compute the indentation level of the line, which in -turn is used to determine the grouping of statements. -\index{indentation} -\index{whitespace} -\index{leading whitespace} -\index{space} -\index{tab} -\index{grouping} -\index{statement grouping} - -First, tabs are replaced (from left to right) by one to eight spaces -such that the total number of characters up to there is a multiple of -eight (this is intended to be the same rule as used by {\UNIX}). The -total number of spaces preceding the first non-blank character then -determines the line's indentation. Indentation cannot be split over -multiple physical lines using backslashes. - -The indentation levels of consecutive lines are used to generate -INDENT and DEDENT tokens, using a stack, as follows. -\index{INDENT token} -\index{DEDENT token} - -Before the first line of the file is read, a single zero is pushed on -the stack; this will never be popped off again. The numbers pushed on -the stack will always be strictly increasing from bottom to top. At -the beginning of each logical line, the line's indentation level is -compared to the top of the stack. If it is equal, nothing happens. -If it is larger, it is pushed on the stack, and one INDENT token is -generated. If it is smaller, it {\em must} be one of the numbers -occurring on the stack; all numbers on the stack that are larger are -popped off, and for each number popped off a DEDENT token is -generated. At the end of the file, a DEDENT token is generated for -each number remaining on the stack that is larger than zero. - -Here is an example of a correctly (though confusingly) indented piece -of Python code: - -\begin{verbatim} -def perm(l): - # Compute the list of all permutations of l - - if len(l) <= 1: - return [l] - r = [] - for i in range(len(l)): - s = l[:i] + l[i+1:] - p = perm(s) - for x in p: - r.append(l[i:i+1] + x) - return r -\end{verbatim} - -The following example shows various indentation errors: - -\begin{verbatim} - def perm(l): # error: first line indented - for i in range(len(l)): # error: not indented - s = l[:i] + l[i+1:] - p = perm(l[:i] + l[i+1:]) # error: unexpected indent - for x in p: - r.append(l[i:i+1] + x) - return r # error: inconsistent dedent -\end{verbatim} - -(Actually, the first three errors are detected by the parser; only the -last error is found by the lexical analyzer --- the indentation of -\verb@return r@ does not match a level popped off the stack.) - -\section{Other tokens} - -Besides NEWLINE, INDENT and DEDENT, the following categories of tokens -exist: identifiers, keywords, literals, operators, and delimiters. -Spaces and tabs are not tokens, but serve to delimit tokens. Where -ambiguity exists, a token comprises the longest possible string that -forms a legal token, when read from left to right. - -\section{Identifiers} - -Identifiers (also referred to as names) are described by the following -lexical definitions: -\index{identifier} -\index{name} - -\begin{verbatim} -identifier: (letter|"_") (letter|digit|"_")* -letter: lowercase | uppercase -lowercase: "a"..."z" -uppercase: "A"..."Z" -digit: "0"..."9" -\end{verbatim} - -Identifiers are unlimited in length. Case is significant. - -\subsection{Keywords} - -The following identifiers are used as reserved words, or {\em -keywords} of the language, and cannot be used as ordinary -identifiers. They must be spelled exactly as written here: -\index{keyword} -\index{reserved word} - -\begin{verbatim} -access del from lambda return -and elif global not try -break else if or while -class except import pass -continue finally in print -def for is raise -\end{verbatim} - -% When adding keywords, pipe it through keywords.py for reformatting - -\section{Literals} \label{literals} - -Literals are notations for constant values of some built-in types. -\index{literal} -\index{constant} - -\subsection{String literals} - -String literals are described by the following lexical definitions: -\index{string literal} - -\begin{verbatim} -stringliteral: shortstring | longstring -shortstring: "'" shortstringitem* "'" | '"' shortstringitem* '"' -longstring: "'''" longstringitem* "'''" | '"""' longstringitem* '"""' -shortstringitem: shortstringchar | escapeseq -longstringitem: longstringchar | escapeseq -shortstringchar: <any ASCII character except "\" or newline or the quote> -longstringchar: <any ASCII character except "\"> -escapeseq: "\" <any ASCII character> -\end{verbatim} -\index{ASCII} - -In ``long strings'' (strings surrounded by sets of three quotes), -unescaped newlines and quotes are allowed (and are retained), except -that three unescaped quotes in a row terminate the string. (A -``quote'' is the character used to open the string, i.e. either -\verb/'/ or \verb/"/.) - -Escape sequences in strings are interpreted according to rules similar -to those used by Standard C. The recognized escape sequences are: -\index{physical line} -\index{escape sequence} -\index{Standard C} -\index{C} - -\begin{center} -\begin{tabular}{|l|l|} -\hline -\verb/\/{\em newline} & Ignored \\ -\verb/\\/ & Backslash (\verb/\/) \\ -\verb/\'/ & Single quote (\verb/'/) \\ -\verb/\"/ & Double quote (\verb/"/) \\ -\verb/\a/ & \ASCII{} Bell (BEL) \\ -\verb/\b/ & \ASCII{} Backspace (BS) \\ -%\verb/\E/ & \ASCII{} Escape (ESC) \\ -\verb/\f/ & \ASCII{} Formfeed (FF) \\ -\verb/\n/ & \ASCII{} Linefeed (LF) \\ -\verb/\r/ & \ASCII{} Carriage Return (CR) \\ -\verb/\t/ & \ASCII{} Horizontal Tab (TAB) \\ -\verb/\v/ & \ASCII{} Vertical Tab (VT) \\ -\verb/\/{\em ooo} & \ASCII{} character with octal value {\em ooo} \\ -\verb/\x/{\em xx...} & \ASCII{} character with hex value {\em xx...} \\ -\hline -\end{tabular} -\end{center} -\index{ASCII} - -In strict compatibility with Standard C, up to three octal digits are -accepted, but an unlimited number of hex digits is taken to be part of -the hex escape (and then the lower 8 bits of the resulting hex number -are used in all current implementations...). - -All unrecognized escape sequences are left in the string unchanged, -i.e., {\em the backslash is left in the string.} (This behavior is -useful when debugging: if an escape sequence is mistyped, the -resulting output is more easily recognized as broken. It also helps a -great deal for string literals used as regular expressions or -otherwise passed to other modules that do their own escape handling.) -\index{unrecognized escape sequence} - -\subsection{Numeric literals} - -There are three types of numeric literals: plain integers, long -integers, and floating point numbers. -\index{number} -\index{numeric literal} -\index{integer literal} -\index{plain integer literal} -\index{long integer literal} -\index{floating point literal} -\index{hexadecimal literal} -\index{octal literal} -\index{decimal literal} - -Integer and long integer literals are described by the following -lexical definitions: - -\begin{verbatim} -longinteger: integer ("l"|"L") -integer: decimalinteger | octinteger | hexinteger -decimalinteger: nonzerodigit digit* | "0" -octinteger: "0" octdigit+ -hexinteger: "0" ("x"|"X") hexdigit+ - -nonzerodigit: "1"..."9" -octdigit: "0"..."7" -hexdigit: digit|"a"..."f"|"A"..."F" -\end{verbatim} - -Although both lower case `l' and upper case `L' are allowed as suffix -for long integers, it is strongly recommended to always use `L', since -the letter `l' looks too much like the digit `1'. - -Plain integer decimal literals must be at most 2147483647 (i.e., the -largest positive integer, using 32-bit arithmetic). Plain octal and -hexadecimal literals may be as large as 4294967295, but values larger -than 2147483647 are converted to a negative value by subtracting -4294967296. There is no limit for long integer literals apart from -what can be stored in available memory. - -Some examples of plain and long integer literals: - -\begin{verbatim} -7 2147483647 0177 0x80000000 -3L 79228162514264337593543950336L 0377L 0x100000000L -\end{verbatim} - -Floating point literals are described by the following lexical -definitions: - -\begin{verbatim} -floatnumber: pointfloat | exponentfloat -pointfloat: [intpart] fraction | intpart "." -exponentfloat: (intpart | pointfloat) exponent -intpart: digit+ -fraction: "." digit+ -exponent: ("e"|"E") ["+"|"-"] digit+ -\end{verbatim} - -The allowed range of floating point literals is -implementation-dependent. - -Some examples of floating point literals: - -\begin{verbatim} -3.14 10. .001 1e100 3.14e-10 -\end{verbatim} - -Note that numeric literals do not include a sign; a phrase like -\verb@-1@ is actually an expression composed of the operator -\verb@-@ and the literal \verb@1@. - -\section{Operators} - -The following tokens are operators: -\index{operators} - -\begin{verbatim} -+ - * / % -<< >> & | ^ ~ -< == > <= <> != >= -\end{verbatim} - -The comparison operators \verb@<>@ and \verb@!=@ are alternate -spellings of the same operator. - -\section{Delimiters} - -The following tokens serve as delimiters or otherwise have a special -meaning: -\index{delimiters} - -\begin{verbatim} -( ) [ ] { } -, : . " ` ' -= ; -\end{verbatim} - -The following printing \ASCII{} characters are not used in Python. Their -occurrence outside string literals and comments is an unconditional -error: -\index{ASCII} - -\begin{verbatim} -@ $ ? -\end{verbatim} - -They may be used by future versions of the language though! diff --git a/Doc/ref/ref3.tex b/Doc/ref/ref3.tex deleted file mode 100644 index 60af2dc94a..0000000000 --- a/Doc/ref/ref3.tex +++ /dev/null @@ -1,876 +0,0 @@ -\chapter{Data model} - -\section{Objects, values and types} - -{\em Objects} are Python's abstraction for data. All data in a Python -program is represented by objects or by relations between objects. -(In a sense, and in conformance to Von Neumann's model of a -``stored program computer'', code is also represented by objects.) -\index{object} -\index{data} - -Every object has an identity, a type and a value. An object's {\em -identity} never changes once it has been created; you may think of it -as the object's address in memory. An object's {\em type} is also -unchangeable. It determines the operations that an object supports -(e.g. ``does it have a length?'') and also defines the possible -values for objects of that type. The {\em value} of some objects can -change. Objects whose value can change are said to be {\em mutable}; -objects whose value is unchangeable once they are created are called -{\em immutable}. The type determines an object's (im)mutability. -\index{identity of an object} -\index{value of an object} -\index{type of an object} -\index{mutable object} -\index{immutable object} - -Objects are never explicitly destroyed; however, when they become -unreachable they may be garbage-collected. An implementation is -allowed to delay garbage collection or omit it altogether --- it is a -matter of implementation quality how garbage collection is -implemented, as long as no objects are collected that are still -reachable. (Implementation note: the current implementation uses a -reference-counting scheme which collects most objects as soon as they -become unreachable, but never collects garbage containing circular -references.) -\index{garbage collection} -\index{reference counting} -\index{unreachable object} - -Note that the use of the implementation's tracing or debugging -facilities may keep objects alive that would normally be collectable. - -Some objects contain references to ``external'' resources such as open -files or windows. It is understood that these resources are freed -when the object is garbage-collected, but since garbage collection is -not guaranteed to happen, such objects also provide an explicit way to -release the external resource, usually a \verb@close@ method. -Programs are strongly recommended to always explicitly close such -objects. - -Some objects contain references to other objects; these are called -{\em containers}. Examples of containers are tuples, lists and -dictionaries. The references are part of a container's value. In -most cases, when we talk about the value of a container, we imply the -values, not the identities of the contained objects; however, when we -talk about the (im)mutability of a container, only the identities of -the immediately contained objects are implied. (So, if an immutable -container contains a reference to a mutable object, its value changes -if that mutable object is changed.) -\index{container} - -Types affect almost all aspects of objects' lives. Even the meaning -of object identity is affected in some sense: for immutable types, -operations that compute new values may actually return a reference to -any existing object with the same type and value, while for mutable -objects this is not allowed. E.g. after - -\begin{verbatim} -a = 1; b = 1; c = []; d = [] -\end{verbatim} - -\verb@a@ and \verb@b@ may or may not refer to the same object with the -value one, depending on the implementation, but \verb@c@ and \verb@d@ -are guaranteed to refer to two different, unique, newly created empty -lists. - -\section{The standard type hierarchy} \label{types} - -Below is a list of the types that are built into Python. Extension -modules written in C can define additional types. Future versions of -Python may add types to the type hierarchy (e.g. rational or complex -numbers, efficiently stored arrays of integers, etc.). -\index{type} -\indexii{data}{type} -\indexii{type}{hierarchy} -\indexii{extension}{module} -\index{C} - -Some of the type descriptions below contain a paragraph listing -`special attributes'. These are attributes that provide access to the -implementation and are not intended for general use. Their definition -may change in the future. There are also some `generic' special -attributes, not listed with the individual objects: \verb@__methods__@ -is a list of the method names of a built-in object, if it has any; -\verb@__members__@ is a list of the data attribute names of a built-in -object, if it has any. -\index{attribute} -\indexii{special}{attribute} -\indexiii{generic}{special}{attribute} -\ttindex{__methods__} -\ttindex{__members__} - -\begin{description} - -\item[None] -This type has a single value. There is a single object with this value. -This object is accessed through the built-in name \verb@None@. -It is returned from functions that don't explicitly return an object. -\ttindex{None} -\obindex{None@{\tt None}} - -\item[Numbers] -These are created by numeric literals and returned as results by -arithmetic operators and arithmetic built-in functions. Numeric -objects are immutable; once created their value never changes. Python -numbers are of course strongly related to mathematical numbers, but -subject to the limitations of numerical representation in computers. -\obindex{number} -\obindex{numeric} - -Python distinguishes between integers and floating point numbers: - -\begin{description} -\item[Integers] -These represent elements from the mathematical set of whole numbers. -\obindex{integer} - -There are two types of integers: - -\begin{description} - -\item[Plain integers] -These represent numbers in the range -2147483648 through 2147483647. -(The range may be larger on machines with a larger natural word -size, but not smaller.) -When the result of an operation falls outside this range, the -exception \verb@OverflowError@ is raised. -For the purpose of shift and mask operations, integers are assumed to -have a binary, 2's complement notation using 32 or more bits, and -hiding no bits from the user (i.e., all 4294967296 different bit -patterns correspond to different values). -\obindex{plain integer} - -\item[Long integers] -These represent numbers in an unlimited range, subject to available -(virtual) memory only. For the purpose of shift and mask operations, -a binary representation is assumed, and negative numbers are -represented in a variant of 2's complement which gives the illusion of -an infinite string of sign bits extending to the left. -\obindex{long integer} - -\end{description} % Integers - -The rules for integer representation are intended to give the most -meaningful interpretation of shift and mask operations involving -negative integers and the least surprises when switching between the -plain and long integer domains. For any operation except left shift, -if it yields a result in the plain integer domain without causing -overflow, it will yield the same result in the long integer domain or -when using mixed operands. -\indexii{integer}{representation} - -\item[Floating point numbers] -These represent machine-level double precision floating point numbers. -You are at the mercy of the underlying machine architecture and -C implementation for the accepted range and handling of overflow. -\obindex{floating point} -\indexii{floating point}{number} -\index{C} - -\end{description} % Numbers - -\item[Sequences] -These represent finite ordered sets indexed by natural numbers. -The built-in function \verb@len()@ returns the number of elements -of a sequence. When this number is \var{n}, the index set contains -the numbers 0, 1, \ldots, \var{n}-1. Element \var{i} of sequence -\var{a} is selected by \code{\var{a}[\var{i}]}. -\obindex{seqence} -\bifuncindex{len} -\index{index operation} -\index{item selection} -\index{subscription} - -Sequences also support slicing: \verb@a[i:j]@ selects all elements -with index \var{k} such that \var{i} \code{<=} \var{k} \code{<} -\var{j}. When used as an expression, a slice is a sequence of the -same type --- this implies that the index set is renumbered so that it -starts at 0 again. -\index{slicing} - -Sequences are distinguished according to their mutability: - -\begin{description} -% -\item[Immutable sequences] -An object of an immutable sequence type cannot change once it is -created. (If the object contains references to other objects, -these other objects may be mutable and may be changed; however -the collection of objects directly referenced by an immutable object -cannot change.) -\obindex{immutable sequence} -\obindex{immutable} - -The following types are immutable sequences: - -\begin{description} - -\item[Strings] -The elements of a string are characters. There is no separate -character type; a character is represented by a string of one element. -Characters represent (at least) 8-bit bytes. The built-in -functions \verb@chr()@ and \verb@ord()@ convert between characters -and nonnegative integers representing the byte values. -Bytes with the values 0-127 represent the corresponding \ASCII{} values. -The string data type is also used to represent arrays of bytes, e.g. -to hold data read from a file. -\obindex{string} -\index{character} -\index{byte} -\index{ASCII} -\bifuncindex{chr} -\bifuncindex{ord} - -(On systems whose native character set is not \ASCII{}, strings may use -EBCDIC in their internal representation, provided the functions -\verb@chr()@ and \verb@ord()@ implement a mapping between \ASCII{} and -EBCDIC, and string comparison preserves the \ASCII{} order. -Or perhaps someone can propose a better rule?) -\index{ASCII} -\index{EBCDIC} -\index{character set} -\indexii{string}{comparison} -\bifuncindex{chr} -\bifuncindex{ord} - -\item[Tuples] -The elements of a tuple are arbitrary Python objects. -Tuples of two or more elements are formed by comma-separated lists -of expressions. A tuple of one element (a `singleton') can be formed -by affixing a comma to an expression (an expression by itself does -not create a tuple, since parentheses must be usable for grouping of -expressions). An empty tuple can be formed by enclosing `nothing' in -parentheses. -\obindex{tuple} -\indexii{singleton}{tuple} -\indexii{empty}{tuple} - -\end{description} % Immutable sequences - -\item[Mutable sequences] -Mutable sequences can be changed after they are created. The -subscription and slicing notations can be used as the target of -assignment and \verb@del@ (delete) statements. -\obindex{mutable sequece} -\obindex{mutable} -\indexii{assignment}{statement} -\index{delete} -\stindex{del} -\index{subscription} -\index{slicing} - -There is currently a single mutable sequence type: - -\begin{description} - -\item[Lists] -The elements of a list are arbitrary Python objects. Lists are formed -by placing a comma-separated list of expressions in square brackets. -(Note that there are no special cases needed to form lists of length 0 -or 1.) -\obindex{list} - -\end{description} % Mutable sequences - -\end{description} % Sequences - -\item[Mapping types] -These represent finite sets of objects indexed by arbitrary index sets. -The subscript notation \verb@a[k]@ selects the element indexed -by \verb@k@ from the mapping \verb@a@; this can be used in -expressions and as the target of assignments or \verb@del@ statements. -The built-in function \verb@len()@ returns the number of elements -in a mapping. -\bifuncindex{len} -\index{subscription} -\obindex{mapping} - -There is currently a single mapping type: - -\begin{description} - -\item[Dictionaries] -These represent finite sets of objects indexed by almost arbitrary -values. The only types of values not acceptable as keys are values -containing lists or dictionaries or other mutable types that are -compared by value rather than by object identity --- the reason being -that the implementation requires that a key's hash value be constant. -Numeric types used for keys obey the normal rules for numeric -comparison: if two numbers compare equal (e.g. 1 and 1.0) then they -can be used interchangeably to index the same dictionary entry. - -Dictionaries are mutable; they are created by the \verb@{...}@ -notation (see section \ref{dict}). -\obindex{dictionary} -\obindex{mutable} - -\end{description} % Mapping types - -\item[Callable types] -These are the types to which the function call (invocation) operation, -written as \verb@function(argument, argument, ...)@, can be applied: -\indexii{function}{call} -\index{invocation} -\indexii{function}{argument} -\obindex{callable} - -\begin{description} - -\item[User-defined functions] -A user-defined function object is created by a function definition -(see section \ref{function}). It should be called with an argument -list containing the same number of items as the function's formal -parameter list. -\indexii{user-defined}{function} -\obindex{function} -\obindex{user-defined function} - -Special read-only attributes: \verb@func_code@ is the code object -representing the compiled function body, and \verb@func_globals@ is (a -reference to) the dictionary that holds the function's global -variables --- it implements the global name space of the module in -which the function was defined. -\ttindex{func_code} -\ttindex{func_globals} -\indexii{global}{name space} - -\item[User-defined methods] -A user-defined method (a.k.a. {\em object closure}) is a pair of a -class instance object and a user-defined function. It should be -called with an argument list containing one item less than the number -of items in the function's formal parameter list. When called, the -class instance becomes the first argument, and the call arguments are -shifted one to the right. -\obindex{method} -\obindex{user-defined method} -\indexii{user-defined}{method} -\index{object closure} - -Special read-only attributes: \verb@im_self@ is the class instance -object, \verb@im_func@ is the function object. -\ttindex{im_func} -\ttindex{im_self} - -\item[Built-in functions] -A built-in function object is a wrapper around a C function. Examples -of built-in functions are \verb@len@ and \verb@math.sin@. There -are no special attributes. The number and type of the arguments are -determined by the C function. -\obindex{built-in function} -\obindex{function} -\index{C} - -\item[Built-in methods] -This is really a different disguise of a built-in function, this time -containing an object passed to the C function as an implicit extra -argument. An example of a built-in method is \verb@list.append@ if -\verb@list@ is a list object. -\obindex{built-in method} -\obindex{method} -\indexii{built-in}{method} - -\item[Classes] -Class objects are described below. When a class object is called as a -function, a new class instance (also described below) is created and -returned. This implies a call to the class's \verb@__init__@ method -if it has one. Any arguments are passed on to the \verb@__init__@ -method --- if there is no \verb@__init__@ method, the class must be called -without arguments. -\ttindex{__init__} -\obindex{class} -\obindex{class instance} -\obindex{instance} -\indexii{class object}{call} - -\end{description} - -\item[Modules] -Modules are imported by the \verb@import@ statement (see section -\ref{import}). A module object is a container for a module's name -space, which is a dictionary (the same dictionary as referenced by the -\verb@func_globals@ attribute of functions defined in the module). -Module attribute references are translated to lookups in this -dictionary. A module object does not contain the code object used to -initialize the module (since it isn't needed once the initialization -is done). -\stindex{import} -\obindex{module} - -Attribute assignment update the module's name space dictionary. - -Special read-only attributes: \verb@__dict__@ yields the module's name -space as a dictionary object; \verb@__name__@ yields the module's name -as a string object. -\ttindex{__dict__} -\ttindex{__name__} -\indexii{module}{name space} - -\item[Classes] -Class objects are created by class definitions (see section -\ref{class}). A class is a container for a dictionary containing the -class's name space. Class attribute references are translated to -lookups in this dictionary. When an attribute name is not found -there, the attribute search continues in the base classes. The search -is depth-first, left-to-right in the order of their occurrence in the -base class list. -\obindex{class} -\obindex{class instance} -\obindex{instance} -\indexii{class object}{call} -\index{container} -\obindex{dictionary} -\indexii{class}{attribute} - -Class attribute assignments update the class's dictionary, never the -dictionary of a base class. -\indexiii{class}{attribute}{assignment} - -A class can be called as a function to yield a class instance (see -above). -\indexii{class object}{call} - -Special read-only attributes: \verb@__dict__@ yields the dictionary -containing the class's name space; \verb@__bases__@ yields a tuple -(possibly empty or a singleton) containing the base classes, in the -order of their occurrence in the base class list. -\ttindex{__dict__} -\ttindex{__bases__} - -\item[Class instances] -A class instance is created by calling a class object as a -function. A class instance has a dictionary in which -attribute references are searched. When an attribute is not found -there, and the instance's class has an attribute by that name, and -that class attribute is a user-defined function (and in no other -cases), the instance attribute reference yields a user-defined method -object (see above) constructed from the instance and the function. -\obindex{class instance} -\obindex{instance} -\indexii{class}{instance} -\indexii{class instance}{attribute} - -Attribute assignments update the instance's dictionary. -\indexiii{class instance}{attribute}{assignment} - -Class instances can pretend to be numbers, sequences, or mappings if -they have methods with certain special names. These are described in -section \ref{specialnames}. -\obindex{number} -\obindex{sequence} -\obindex{mapping} - -Special read-only attributes: \verb@__dict__@ yields the attribute -dictionary; \verb@__class__@ yields the instance's class. -\ttindex{__dict__} -\ttindex{__class__} - -\item[Files] -A file object represents an open file. (It is a wrapper around a C -{\tt stdio} file pointer.) File objects are created by the -\verb@open()@ built-in function, and also by \verb@posix.popen()@ and -the \verb@makefile@ method of socket objects. \verb@sys.stdin@, -\verb@sys.stdout@ and \verb@sys.stderr@ are file objects corresponding -to the interpreter's standard input, output and error streams. -See the Python Library Reference for methods of file objects and other -details. -\obindex{file} -\index{C} -\index{stdio} -\bifuncindex{open} -\bifuncindex{popen} -\bifuncindex{makefile} -\ttindex{stdin} -\ttindex{stdout} -\ttindex{stderr} -\ttindex{sys.stdin} -\ttindex{sys.stdout} -\ttindex{sys.stderr} - -\item[Internal types] -A few types used internally by the interpreter are exposed to the user. -Their definition may change with future versions of the interpreter, -but they are mentioned here for completeness. -\index{internal type} - -\begin{description} - -\item[Code objects] -Code objects represent ``pseudo-compiled'' executable Python code. -The difference between a code -object and a function object is that the function object contains an -explicit reference to the function's context (the module in which it -was defined) while a code object contains no context. -\obindex{code} - -Special read-only attributes: \verb@co_code@ is a string representing -the sequence of instructions; \verb@co_consts@ is a list of literals -used by the code; \verb@co_names@ is a list of names (strings) used by -the code; \verb@co_filename@ is the filename from which the code was -compiled. (To find out the line numbers, you would have to decode the -instructions; the standard library module \verb@dis@ contains an -example of how to do this.) -\ttindex{co_code} -\ttindex{co_consts} -\ttindex{co_names} -\ttindex{co_filename} - -\item[Frame objects] -Frame objects represent execution frames. They may occur in traceback -objects (see below). -\obindex{frame} - -Special read-only attributes: \verb@f_back@ is to the previous -stack frame (towards the caller), or \verb@None@ if this is the bottom -stack frame; \verb@f_code@ is the code object being executed in this -frame; \verb@f_globals@ is the dictionary used to look up global -variables; \verb@f_locals@ is used for local variables; -\verb@f_lineno@ gives the line number and \verb@f_lasti@ gives the -precise instruction (this is an index into the instruction string of -the code object). -\ttindex{f_back} -\ttindex{f_code} -\ttindex{f_globals} -\ttindex{f_locals} -\ttindex{f_lineno} -\ttindex{f_lasti} - -\item[Traceback objects] \label{traceback} -Traceback objects represent a stack trace of an exception. A -traceback object is created when an exception occurs. When the search -for an exception handler unwinds the execution stack, at each unwound -level a traceback object is inserted in front of the current -traceback. When an exception handler is entered -(see also section \ref{try}), the stack trace is -made available to the program as \verb@sys.exc_traceback@. When the -program contains no suitable handler, the stack trace is written -(nicely formatted) to the standard error stream; if the interpreter is -interactive, it is also made available to the user as -\verb@sys.last_traceback@. -\obindex{traceback} -\indexii{stack}{trace} -\indexii{exception}{handler} -\indexii{execution}{stack} -\ttindex{exc_traceback} -\ttindex{last_traceback} -\ttindex{sys.exc_traceback} -\ttindex{sys.last_traceback} - -Special read-only attributes: \verb@tb_next@ is the next level in the -stack trace (towards the frame where the exception occurred), or -\verb@None@ if there is no next level; \verb@tb_frame@ points to the -execution frame of the current level; \verb@tb_lineno@ gives the line -number where the exception occurred; \verb@tb_lasti@ indicates the -precise instruction. The line number and last instruction in the -traceback may differ from the line number of its frame object if the -exception occurred in a \verb@try@ statement with no matching -\verb@except@ clause or with a \verb@finally@ clause. -\ttindex{tb_next} -\ttindex{tb_frame} -\ttindex{tb_lineno} -\ttindex{tb_lasti} -\stindex{try} - -\end{description} % Internal types - -\end{description} % Types - - -\section{Special method names} \label{specialnames} - -A class can implement certain operations that are invoked by special -syntax (such as subscription or arithmetic operations) by defining -methods with special names. For instance, if a class defines a -method named \verb@__getitem__@, and \verb@x@ is an instance of this -class, then \verb@x[i]@ is equivalent to \verb@x.__getitem__(i)@. -(The reverse is not true --- if \verb@x@ is a list object, -\verb@x.__getitem__(i)@ is not equivalent to \verb@x[i]@.) -\ttindex{__getitem__} - -Except for \verb@__repr__@, \verb@__str__@ and \verb@__cmp__@, -attempts to execute an -operation raise an exception when no appropriate method is defined. -For \verb@__repr__@, the default is to return a string describing the -object's class and address. -For \verb@__cmp__@, the default is to compare instances based on their -address. -For \verb@__str__@, the default is to use \verb@__repr__@. -\ttindex{__repr__} -\ttindex{__str__} -\ttindex{__cmp__} - - -\subsection{Special methods for any type} - -\begin{description} - -\item[{\tt __init__(self, args...)}] -Called when the instance is created. The arguments are those passed -to the class constructor expression. If a base class has an -\code{__init__} method the derived class's \code{__init__} method must -explicitly call it to ensure proper initialization of the base class -part of the instance. -\ttindex{__init__} -\indexii{class}{constructor} - - -\item[{\tt __del__(self)}] -Called when the instance is about to be destroyed. If a base class -has an \code{__del__} method the derived class's \code{__del__} method -must explicitly call it to ensure proper deletion of the base class -part of the instance. Note that it is possible for the \code{__del__} -method to postpone destruction of the instance by creating a new -reference to it. It may then be called at a later time when this new -reference is deleted. It is not guaranteed that -\code{__del__} methods are called for objects that still exist when -the interpreter exits. -\ttindex{__del__} -\stindex{del} - -Note that \code{del x} doesn't directly call \code{x.__del__} --- the -former decrements the reference count for \code{x} by one, but -\code{x.__del__} is only called when its reference count reaches zero. - -\item[{\tt __repr__(self)}] -Called by the \verb@repr()@ built-in function and by string conversions -(reverse or backward quotes) to compute the string representation of an object. -\ttindex{__repr__} -\bifuncindex{repr} -\indexii{string}{conversion} -\indexii{reverse}{quotes} -\indexii{backward}{quotes} -\index{back-quotes} - -\item[{\tt __str__(self)}] -Called by the \verb@str()@ built-in function and by the \verb@print@ -statement compute the string representation of an object. -\ttindex{__str__} -\bifuncindex{str} -\stindex{print} - -\item[{\tt __cmp__(self, other)}] -Called by all comparison operations. Should return -1 if -\verb@self < other@, 0 if \verb@self == other@, +1 if -\verb@self > other@. If no \code{__cmp__} operation is defined, class -instances are compared by object identity (``address''). -(Implementation note: due to limitations in the interpreter, -exceptions raised by comparisons are ignored, and the objects will be -considered equal in this case.) -\ttindex{__cmp__} -\bifuncindex{cmp} -\index{comparisons} - -\item[{\tt __hash__(self)}] -Called for the key object for dictionary operations, -and by the built-in function -\code{hash()}. Should return a 32-bit integer usable as a hash value -for dictionary operations. The only required property is that objects -which compare equal have the same hash value; it is advised to somehow -mix together (e.g. using exclusive or) the hash values for the -components of the object that also play a part in comparison of -objects. If a class does not define a \code{__cmp__} method it should -not define a \code{__hash__} operation either; if it defines -\code{__cmp__} but not \code{__hash__} its instances will not be -usable as dictionary keys. If a class defines mutable objects and -implements a \code{__cmp__} method it should not implement -\code{__hash__}, since the dictionary implementation assumes that a -key's hash value is a constant. -\obindex{dictionary} -\ttindex{__cmp__} -\ttindex{__hash__} -\bifuncindex{hash} - -\item[{\tt __call__(self, *args)}] -Called when the instance is ``called'' as a function. -\ttindex{__call__} -\indexii{call}{instance} - -\end{description} - - -\subsection{Special methods for attribute access} - -The following methods can be used to change the meaning of attribute -access for class instances. - -\begin{description} - -\item[{\tt __getattr__(self, name)}] -Called when an attribute lookup has not found the attribute in the -usual places (i.e. it is not an instance attribute nor is it found in -the class tree for \code{self}). \code{name} is the attribute name. -\ttindex{__getattr__} - -Note that if the attribute is found through the normal mechanism, -\code{__getattr__} is not called. (This is an asymmetry between -\code{__getattr__} and \code{__setattr__}.) -This is done both for efficiency reasons and because otherwise -\code{__getattr__} would have no way to access other attributes of the -instance. -Note that at least for instance variables, \code{__getattr__} can fake -total control by simply not inserting any values in the instance -attribute dictionary. -\ttindex{__setattr__} - -\item[{\tt __setattr__(self, name, value)}] -Called when an attribute assignment is attempted. This is called -instead of the normal mechanism (i.e. store the value as an instance -attribute). \code{name} is the attribute name, \code{value} is the -value to be assigned to it. -\ttindex{__setattr__} - -If \code{__setattr__} wants to assign to an instance attribute, it -should not simply execute \code{self.\var{name} = value} --- this would -cause a recursive call. Instead, it should insert the value in the -dictionary of instance attributes, e.g. \code{self.__dict__[name] = -value}. -\ttindex{__dict__} - -\item[{\tt __delattr__(self, name)}] -Like \code{__setattr__} but for attribute deletion instead of -assignment. -\ttindex{__delattr__} - -\end{description} - - -\subsection{Special methods for sequence and mapping types} - -\begin{description} - -\item[{\tt __len__(self)}] -Called to implement the built-in function \verb@len()@. Should return -the length of the object, an integer \verb@>=@ 0. Also, an object -whose \verb@__len__()@ method returns 0 is considered to be false in a -Boolean context. -\ttindex{__len__} - -\item[{\tt __getitem__(self, key)}] -Called to implement evaluation of \verb@self[key]@. Note that the -special interpretation of negative keys (if the class wishes to -emulate a sequence type) is up to the \verb@__getitem__@ method. -\ttindex{__getitem__} - -\item[{\tt __setitem__(self, key, value)}] -Called to implement assignment to \verb@self[key]@. Same note as for -\verb@__getitem__@. -\ttindex{__setitem__} - -\item[{\tt __delitem__(self, key)}] -Called to implement deletion of \verb@self[key]@. Same note as for -\verb@__getitem__@. -\ttindex{__delitem__} - -\end{description} - - -\subsection{Special methods for sequence types} - -\begin{description} - -\item[{\tt __getslice__(self, i, j)}] -Called to implement evaluation of \verb@self[i:j]@. Note that missing -\verb@i@ or \verb@j@ are replaced by 0 or \verb@len(self)@, -respectively, and \verb@len(self)@ has been added (once) to originally -negative \verb@i@ or \verb@j@ by the time this function is called -(unlike for \verb@__getitem__@). -\ttindex{__getslice__} - -\item[{\tt __setslice__(self, i, j, sequence)}] -Called to implement assignment to \verb@self[i:j]@. Same notes as for -\verb@__getslice__@. -\ttindex{__setslice__} - -\item[{\tt __delslice__(self, i, j)}] -Called to implement deletion of \verb@self[i:j]@. Same notes as for -\verb@__getslice__@. -\ttindex{__delslice__} - -\end{description} - - -\subsection{Special methods for numeric types} - -\begin{description} - -\item[{\tt __add__(self, other)}]\itemjoin -\item[{\tt __sub__(self, other)}]\itemjoin -\item[{\tt __mul__(self, other)}]\itemjoin -\item[{\tt __div__(self, other)}]\itemjoin -\item[{\tt __mod__(self, other)}]\itemjoin -\item[{\tt __divmod__(self, other)}]\itemjoin -\item[{\tt __pow__(self, other)}]\itemjoin -\item[{\tt __lshift__(self, other)}]\itemjoin -\item[{\tt __rshift__(self, other)}]\itemjoin -\item[{\tt __and__(self, other)}]\itemjoin -\item[{\tt __xor__(self, other)}]\itemjoin -\item[{\tt __or__(self, other)}]\itembreak -Called to implement the binary arithmetic operations (\verb@+@, -\verb@-@, \verb@*@, \verb@/@, \verb@%@, \verb@divmod()@, \verb@pow()@, -\verb@<<@, \verb@>>@, \verb@&@, \verb@^@, \verb@|@). -\ttindex{__or__} -\ttindex{__xor__} -\ttindex{__and__} -\ttindex{__rshift__} -\ttindex{__lshift__} -\ttindex{__pow__} -\ttindex{__divmod__} -\ttindex{__mod__} -\ttindex{__div__} -\ttindex{__mul__} -\ttindex{__sub__} -\ttindex{__add__} - -\item[{\tt __neg__(self)}]\itemjoin -\item[{\tt __pos__(self)}]\itemjoin -\item[{\tt __abs__(self)}]\itemjoin -\item[{\tt __invert__(self)}]\itembreak -Called to implement the unary arithmetic operations (\verb@-@, \verb@+@, -\verb@abs()@ and \verb@~@). -\ttindex{__invert__} -\ttindex{__abs__} -\ttindex{__pos__} -\ttindex{__neg__} - -\item[{\tt __nonzero__(self)}] -Called to implement boolean testing; should return 0 or 1. An -alternative name for this method is \verb@__len__@. -\ttindex{__nonzero__} - -\item[{\tt __coerce__(self, other)}] -Called to implement ``mixed-mode'' numeric arithmetic. Should either -return a tuple containing self and other converted to a common numeric -type, or None if no way of conversion is known. When the common type -would be the type of other, it is sufficient to return None, since the -interpreter will also ask the other object to attempt a coercion (but -sometimes, if the implementation of the other type cannot be changed, -it is useful to do the conversion to the other type here). -\ttindex{__coerce__} - -Note that this method is not called to coerce the arguments to \verb@+@ -and \verb@*@, because these are also used to implement sequence -concatenation and repetition, respectively. Also note that, for the -same reason, in \verb@n*x@, where \verb@n@ is a built-in number and -\verb@x@ is an instance, a call to \verb@x.__mul__(n)@ is made.% -\footnote{The interpreter should really distinguish between -user-defined classes implementing sequences, mappings or numbers, but -currently it doesn't --- hence this strange exception.} -\ttindex{__mul__} - -\item[{\tt __int__(self)}]\itemjoin -\item[{\tt __long__(self)}]\itemjoin -\item[{\tt __float__(self)}]\itembreak -Called to implement the built-in functions \verb@int()@, \verb@long()@ -and \verb@float()@. Should return a value of the appropriate type. -\ttindex{__float__} -\ttindex{__long__} -\ttindex{__int__} - -\item[{\tt __oct__(self)}]\itemjoin -\item[{\tt __hex__(self)}]\itembreak -Called to implement the built-in functions \verb@oct()@ and -\verb@hex()@. Should return a string value. -\ttindex{__hex__} -\ttindex{__oct__} - -\end{description} diff --git a/Doc/ref/ref4.tex b/Doc/ref/ref4.tex deleted file mode 100644 index 429302a907..0000000000 --- a/Doc/ref/ref4.tex +++ /dev/null @@ -1,176 +0,0 @@ -\chapter{Execution model} -\index{execution model} - -\section{Code blocks, execution frames, and name spaces} \label{execframes} -\index{code block} -\indexii{execution}{frame} -\index{name space} - -A {\em code block} is a piece of Python program text that can be -executed as a unit, such as a module, a class definition or a function -body. Some code blocks (like modules) are executed only once, others -(like function bodies) may be executed many times. Code blocks may -textually contain other code blocks. Code blocks may invoke other -code blocks (that may or may not be textually contained in them) as -part of their execution, e.g. by invoking (calling) a function. -\index{code block} -\indexii{code}{block} - -The following are code blocks: A module is a code block. A function -body is a code block. A class definition is a code block. Each -command typed interactively is a separate code block; a script file is -a code block. The string argument passed to the built-in function -\verb@eval@ and to the \verb@exec@ statement are code blocks. -And finally, the -expression read and evaluated by the built-in function \verb@input@ is -a code block. - -A code block is executed in an execution frame. An {\em execution -frame} contains some administrative information (used for debugging), -determines where and how execution continues after the code block's -execution has completed, and (perhaps most importantly) defines two -name spaces, the local and the global name space, that affect -execution of the code block. -\indexii{execution}{frame} - -A {\em name space} is a mapping from names (identifiers) to objects. -A particular name space may be referenced by more than one execution -frame, and from other places as well. Adding a name to a name space -is called {\em binding} a name (to an object); changing the mapping of -a name is called {\em rebinding}; removing a name is {\em unbinding}. -Name spaces are functionally equivalent to dictionaries. -\index{name space} -\indexii{binding}{name} -\indexii{rebinding}{name} -\indexii{unbinding}{name} - -The {\em local name space} of an execution frame determines the default -place where names are defined and searched. The {\em global name -space} determines the place where names listed in \verb@global@ -statements are defined and searched, and where names that are not -explicitly bound in the current code block are searched. -\indexii{local}{name space} -\indexii{global}{name space} -\stindex{global} - -Whether a name is local or global in a code block is determined by -static inspection of the source text for the code block: in the -absence of \verb@global@ statements, a name that is bound anywhere in -the code block is local in the entire code block; all other names are -considered global. The \verb@global@ statement forces global -interpretation of selected names throughout the code block. The -following constructs bind names: formal parameters, \verb@import@ -statements, class and function definitions (these bind the class or -function name), and targets that are identifiers if occurring in an -assignment, \verb@for@ loop header, or \verb@except@ clause header. - -A target occurring in a \verb@del@ statement is also considered bound -for this purpose (though the actual semantics are to ``unbind'' the -name). - -When a global name is not found in the global name space, it is -searched in the list of ``built-in'' names (which is actually the -global name space of the module \verb@__builtin__@). When a name is not -found at all, the \verb@NameError@ exception is raised.% -\footnote{If the code block contains {\tt exec} statements or the -construct {\tt from \ldots import *}, the semantics of names not -explicitly mentioned in a {\tt global} statement change subtly: name -lookup first searches the local name space, then the global one, then -the built-in one.} -\bimodindex{__builtin__} -\stindex{from} -\stindex{exec} -\stindex{global} -\ttindex{NameError} - -The following table lists the meaning of the local and global name -space for various types of code blocks. The name space for a -particular module is automatically created when the module is first -referenced. Note that in almost all cases, the global name space is -the name space of the containing module --- scopes in Python do not -nest! - -\begin{center} -\begin{tabular}{|l|l|l|l|} -\hline -Code block type & Global name space & Local name space & Notes \\ -\hline -Module & n.s. for this module & same as global & \\ -Script & n.s. for \verb@__main__@ & same as global & \\ -Interactive command & n.s. for \verb@__main__@ & same as global & \\ -Class definition & global n.s. of containing block & new n.s. & \\ -Function body & global n.s. of containing block & new n.s. & \\ -String passed to \verb@exec@ statement - & global n.s. of cobtaining block - & local n.s. of containing block & (1) \\ -String passed to \verb@eval()@ - & global n.s. of caller & local n.s. of caller & (1) \\ -File read by \verb@execfile()@ - & global n.s. of caller & local n.s. of caller & (1) \\ -Expression read by \verb@input@ - & global n.s. of caller & local n.s. of caller & \\ -\hline -\end{tabular} -\end{center} -\bimodindex{__main__} - -Notes: - -\begin{description} - -\item[n.s.] means {\em name space} - -\item[(1)] The global and local name space for these can be -overridden with optional extra arguments. - -\end{description} - -The built-in functions \verb@globals()@ and \verb@locals()@ returns a -dictionary representing the current global and local name space, -respectively. The effect of modifications to this dictionary on the -name space are undefined.% -\footnote{The current implementations return the dictionary actually -used to implement the name space, {\em except} for functions, where -the optimizer may cause the local name space to be implemented -differently, and \verb@locals()@ returns a read-only dictionary.} - -\section{Exceptions} - -Exceptions are a means of breaking out of the normal flow of control -of a code block in order to handle errors or other exceptional -conditions. An exception is {\em raised} at the point where the error -is detected; it may be {\em handled} by the surrounding code block or -by any code block that directly or indirectly invoked the code block -where the error occurred. -\index{exception} -\index{raise an exception} -\index{handle an exception} -\index{exception handler} -\index{errors} -\index{error handling} - -The Python interpreter raises an exception when it detects an run-time -error (such as division by zero). A Python program can also -explicitly raise an exception with the \verb@raise@ statement. -Exception handlers are specified with the \verb@try...except@ -statement. - -Python uses the ``termination'' model of error handling: an exception -handler can find out what happened and continue execution at an outer -level, but it cannot repair the cause of the error and retry the -failing operation (except by re-entering the the offending piece of -code from the top). - -When an exception is not handled at all, the interpreter terminates -execution of the program, or returns to its interactive main loop. - -Exceptions are identified by string objects. Two different string -objects with the same value identify different exceptions. - -When an exception is raised, an object (maybe \verb@None@) is passed -as the exception's ``parameter''; this object does not affect the -selection of an exception handler, but is passed to the selected -exception handler as additional information. - -See also the description of the \verb@try@ and \verb@raise@ -statements. diff --git a/Doc/ref/ref5.tex b/Doc/ref/ref5.tex deleted file mode 100644 index 62cd9a7e52..0000000000 --- a/Doc/ref/ref5.tex +++ /dev/null @@ -1,759 +0,0 @@ -\chapter{Expressions and conditions} -\index{expression} -\index{condition} - -{\bf Note:} In this and the following chapters, extended BNF notation -will be used to describe syntax, not lexical analysis. -\index{BNF} - -This chapter explains the meaning of the elements of expressions and -conditions. Conditions are a superset of expressions, and a condition -may be used wherever an expression is required by enclosing it in -parentheses. The only places where expressions are used in the syntax -instead of conditions is in expression statements and on the -right-hand side of assignment statements; this catches some nasty bugs -like accidentally writing \verb@x == 1@ instead of \verb@x = 1@. -\indexii{assignment}{statement} - -The comma plays several roles in Python's syntax. It is usually an -operator with a lower precedence than all others, but occasionally -serves other purposes as well; e.g. it separates function arguments, -is used in list and dictionary constructors, and has special semantics -in \verb@print@ statements. -\index{comma} - -When (one alternative of) a syntax rule has the form - -\begin{verbatim} -name: othername -\end{verbatim} - -and no semantics are given, the semantics of this form of \verb@name@ -are the same as for \verb@othername@. -\index{syntax} - -\section{Arithmetic conversions} -\indexii{arithmetic}{conversion} - -When a description of an arithmetic operator below uses the phrase -``the numeric arguments are converted to a common type'', -this both means that if either argument is not a number, a -\verb@TypeError@ exception is raised, and that otherwise -the following conversions are applied: -\exindex{TypeError} -\indexii{floating point}{number} -\indexii{long}{integer} -\indexii{plain}{integer} - -\begin{itemize} -\item first, if either argument is a floating point number, - the other is converted to floating point; -\item else, if either argument is a long integer, - the other is converted to long integer; -\item otherwise, both must be plain integers and no conversion - is necessary. -\end{itemize} - -\section{Atoms} -\index{atom} - -Atoms are the most basic elements of expressions. Forms enclosed in -reverse quotes or in parentheses, brackets or braces are also -categorized syntactically as atoms. The syntax for atoms is: - -\begin{verbatim} -atom: identifier | literal | enclosure -enclosure: parenth_form|list_display|dict_display|string_conversion -\end{verbatim} - -\subsection{Identifiers (Names)} -\index{name} -\index{identifier} - -An identifier occurring as an atom is a reference to a local, global -or built-in name binding. If a name is assigned to anywhere in a code -block (even in unreachable code), and is not mentioned in a -\verb@global@ statement in that code block, then it refers to a local -name throughout that code block. When it is not assigned to anywhere -in the block, or when it is assigned to but also explicitly listed in -a \verb@global@ statement, it refers to a global name if one exists, -else to a built-in name (and this binding may dynamically change). -\indexii{name}{binding} -\index{code block} -\stindex{global} -\indexii{built-in}{name} -\indexii{global}{name} - -When the name is bound to an object, evaluation of the atom yields -that object. When a name is not bound, an attempt to evaluate it -raises a \verb@NameError@ exception. -\exindex{NameError} - -\subsection{Literals} -\index{literal} - -Python knows string and numeric literals: - -\begin{verbatim} -literal: stringliteral | integer | longinteger | floatnumber -\end{verbatim} - -Evaluation of a literal yields an object of the given type (string, -integer, long integer, floating point number) with the given value. -The value may be approximated in the case of floating point literals. -See section \ref{literals} for details. - -All literals correspond to immutable data types, and hence the -object's identity is less important than its value. Multiple -evaluations of literals with the same value (either the same -occurrence in the program text or a different occurrence) may obtain -the same object or a different object with the same value. -\indexiii{immutable}{data}{type} - -(In the original implementation, all literals in the same code block -with the same type and value yield the same object.) - -\subsection{Parenthesized forms} -\index{parenthesized form} - -A parenthesized form is an optional condition list enclosed in -parentheses: - -\begin{verbatim} -parenth_form: "(" [condition_list] ")" -\end{verbatim} - -A parenthesized condition list yields whatever that condition list -yields. - -An empty pair of parentheses yields an empty tuple object. Since -tuples are immutable, the rules for literals apply here. -\indexii{empty}{tuple} - -(Note that tuples are not formed by the parentheses, but rather by use -of the comma operator. The exception is the empty tuple, for which -parentheses {\em are} required --- allowing unparenthesized ``nothing'' -in expressions would cause ambiguities and allow common typos to -pass uncaught.) -\index{comma} -\indexii{tuple}{display} - -\subsection{List displays} -\indexii{list}{display} - -A list display is a possibly empty series of conditions enclosed in -square brackets: - -\begin{verbatim} -list_display: "[" [condition_list] "]" -\end{verbatim} - -A list display yields a new list object. -\obindex{list} - -If it has no condition list, the list object has no items. Otherwise, -the elements of the condition list are evaluated from left to right -and inserted in the list object in that order. -\indexii{empty}{list} - -\subsection{Dictionary displays} \label{dict} -\indexii{dictionary}{display} - -A dictionary display is a possibly empty series of key/datum pairs -enclosed in curly braces: -\index{key} -\index{datum} -\index{key/datum pair} - -\begin{verbatim} -dict_display: "{" [key_datum_list] "}" -key_datum_list: key_datum ("," key_datum)* [","] -key_datum: condition ":" condition -\end{verbatim} - -A dictionary display yields a new dictionary object. -\obindex{dictionary} - -The key/datum pairs are evaluated from left to right to define the -entries of the dictionary: each key object is used as a key into the -dictionary to store the corresponding datum. - -Restrictions on the types of the key values are listed earlier in -section \ref{types}. -Clashes between duplicate keys are not detected; the last -datum (textually rightmost in the display) stored for a given key -value prevails. -\exindex{TypeError} - -\subsection{String conversions} -\indexii{string}{conversion} -\indexii{reverse}{quotes} -\indexii{backward}{quotes} -\index{back-quotes} - -A string conversion is a condition list enclosed in reverse (or -backward) quotes: - -\begin{verbatim} -string_conversion: "`" condition_list "`" -\end{verbatim} - -A string conversion evaluates the contained condition list and -converts the resulting object into a string according to rules -specific to its type. - -If the object is a string, a number, \verb@None@, or a tuple, list or -dictionary containing only objects whose type is one of these, the -resulting string is a valid Python expression which can be passed to -the built-in function \verb@eval()@ to yield an expression with the -same value (or an approximation, if floating point numbers are -involved). - -(In particular, converting a string adds quotes around it and converts -``funny'' characters to escape sequences that are safe to print.) - -It is illegal to attempt to convert recursive objects (e.g. lists or -dictionaries that contain a reference to themselves, directly or -indirectly.) -\obindex{recursive} - -The built-in function \verb@repr()@ performs exactly the same -conversion in its argument as enclosing it it reverse quotes does. -The built-in function \verb@str()@ performs a similar but more -user-friendly conversion. -\bifuncindex{repr} -\bifuncindex{str} - -\section{Primaries} \label{primaries} -\index{primary} - -Primaries represent the most tightly bound operations of the language. -Their syntax is: - -\begin{verbatim} -primary: atom | attributeref | subscription | slicing | call -\end{verbatim} - -\subsection{Attribute references} -\indexii{attribute}{reference} - -An attribute reference is a primary followed by a period and a name: - -\begin{verbatim} -attributeref: primary "." identifier -\end{verbatim} - -The primary must evaluate to an object of a type that supports -attribute references, e.g. a module or a list. This object is then -asked to produce the attribute whose name is the identifier. If this -attribute is not available, the exception \verb@AttributeError@ is -raised. Otherwise, the type and value of the object produced is -determined by the object. Multiple evaluations of the same attribute -reference may yield different objects. -\obindex{module} -\obindex{list} - -\subsection{Subscriptions} -\index{subscription} - -A subscription selects an item of a sequence (string, tuple or list) -or mapping (dictionary) object: -\obindex{sequence} -\obindex{mapping} -\obindex{string} -\obindex{tuple} -\obindex{list} -\obindex{dictionary} -\indexii{sequence}{item} - -\begin{verbatim} -subscription: primary "[" condition "]" -\end{verbatim} - -The primary must evaluate to an object of a sequence or mapping type. - -If it is a mapping, the condition must evaluate to an object whose -value is one of the keys of the mapping, and the subscription selects -the value in the mapping that corresponds to that key. - -If it is a sequence, the condition must evaluate to a plain integer. -If this value is negative, the length of the sequence is added to it -(so that, e.g. \verb@x[-1]@ selects the last item of \verb@x@.) -The resulting value must be a nonnegative integer smaller than the -number of items in the sequence, and the subscription selects the item -whose index is that value (counting from zero). - -A string's items are characters. A character is not a separate data -type but a string of exactly one character. -\index{character} -\indexii{string}{item} - -\subsection{Slicings} -\index{slicing} -\index{slice} - -A slicing (or slice) selects a range of items in a sequence (string, -tuple or list) object: -\obindex{sequence} -\obindex{string} -\obindex{tuple} -\obindex{list} - -\begin{verbatim} -slicing: primary "[" [condition] ":" [condition] "]" -\end{verbatim} - -The primary must evaluate to a sequence object. The lower and upper -bound expressions, if present, must evaluate to plain integers; -defaults are zero and the sequence's length, respectively. If either -bound is negative, the sequence's length is added to it. The slicing -now selects all items with index \var{k} such that -\code{\var{i} <= \var{k} < \var{j}} where \var{i} -and \var{j} are the specified lower and upper bounds. This may be an -empty sequence. It is not an error if \var{i} or \var{j} lie outside the -range of valid indexes (such items don't exist so they aren't -selected). - -\subsection{Calls} \label{calls} -\index{call} - -A call calls a callable object (e.g. a function) with a possibly empty -series of arguments:\footnote{The new syntax for keyword arguments is -not yet documented in this manual. See chapter 12 of the Tutorial.} -\obindex{callable} - -\begin{verbatim} -call: primary "(" [condition_list] ")" -\end{verbatim} - -The primary must evaluate to a callable object (user-defined -functions, built-in functions, methods of built-in objects, class -objects, and methods of class instances are callable). If it is a -class, the argument list must be empty; otherwise, the arguments are -evaluated. - -A call always returns some value, possibly \verb@None@, unless it -raises an exception. How this value is computed depends on the type -of the callable object. If it is: - -\begin{description} - -\item[a user-defined function:] the code block for the function is -executed, passing it the argument list. The first thing the code -block will do is bind the formal parameters to the arguments; this is -described in section \ref{function}. When the code block executes a -\verb@return@ statement, this specifies the return value of the -function call. -\indexii{function}{call} -\indexiii{user-defined}{function}{call} -\obindex{user-defined function} -\obindex{function} - -\item[a built-in function or method:] the result is up to the -interpreter; see the library reference manual for the descriptions of -built-in functions and methods. -\indexii{function}{call} -\indexii{built-in function}{call} -\indexii{method}{call} -\indexii{built-in method}{call} -\obindex{built-in method} -\obindex{built-in function} -\obindex{method} -\obindex{function} - -\item[a class object:] a new instance of that class is returned. -\obindex{class} -\indexii{class object}{call} - -\item[a class instance method:] the corresponding user-defined -function is called, with an argument list that is one longer than the -argument list of the call: the instance becomes the first argument. -\obindex{class instance} -\obindex{instance} -\indexii{instance}{call} -\indexii{class instance}{call} - -\end{description} - -\section{Unary arithmetic operations} -\indexiii{unary}{arithmetic}{operation} -\indexiii{unary}{bit-wise}{operation} - -All unary arithmetic (and bit-wise) operations have the same priority: - -\begin{verbatim} -u_expr: primary | "-" u_expr | "+" u_expr | "~" u_expr -\end{verbatim} - -The unary \verb@"-"@ (minus) operator yields the negation of its -numeric argument. -\index{negation} -\index{minus} - -The unary \verb@"+"@ (plus) operator yields its numeric argument -unchanged. -\index{plus} - -The unary \verb@"~"@ (invert) operator yields the bit-wise inversion -of its plain or long integer argument. The bit-wise inversion of -\verb@x@ is defined as \verb@-(x+1)@. -\index{inversion} - -In all three cases, if the argument does not have the proper type, -a \verb@TypeError@ exception is raised. -\exindex{TypeError} - -\section{Binary arithmetic operations} -\indexiii{binary}{arithmetic}{operation} - -The binary arithmetic operations have the conventional priority -levels. Note that some of these operations also apply to certain -non-numeric types. There is no ``power'' operator, so there are only -two levels, one for multiplicative operators and one for additive -operators: - -\begin{verbatim} -m_expr: u_expr | m_expr "*" u_expr - | m_expr "/" u_expr | m_expr "%" u_expr -a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr -\end{verbatim} - -The \verb@"*"@ (multiplication) operator yields the product of its -arguments. The arguments must either both be numbers, or one argument -must be a plain integer and the other must be a sequence. In the -former case, the numbers are converted to a common type and then -multiplied together. In the latter case, sequence repetition is -performed; a negative repetition factor yields an empty sequence. -\index{multiplication} - -The \verb@"/"@ (division) operator yields the quotient of its -arguments. The numeric arguments are first converted to a common -type. Plain or long integer division yields an integer of the same -type; the result is that of mathematical division with the `floor' -function applied to the result. Division by zero raises the -\verb@ZeroDivisionError@ exception. -\exindex{ZeroDivisionError} -\index{division} - -The \verb@"%"@ (modulo) operator yields the remainder from the -division of the first argument by the second. The numeric arguments -are first converted to a common type. A zero right argument raises -the \verb@ZeroDivisionError@ exception. The arguments may be floating -point numbers, e.g. \verb@3.14 % 0.7@ equals \verb@0.34@. The modulo -operator always yields a result with the same sign as its second -operand (or zero); the absolute value of the result is strictly -smaller than the second operand. -\index{modulo} - -The integer division and modulo operators are connected by the -following identity: \verb@x == (x/y)*y + (x%y)@. Integer division and -modulo are also connected with the built-in function \verb@divmod()@: -\verb@divmod(x, y) == (x/y, x%y)@. These identities don't hold for -floating point numbers; there a similar identity holds where -\verb@x/y@ is replaced by \verb@floor(x/y)@). - -The \verb@"+"@ (addition) operator yields the sum of its arguments. -The arguments must either both be numbers, or both sequences of the -same type. In the former case, the numbers are converted to a common -type and then added together. In the latter case, the sequences are -concatenated. -\index{addition} - -The \verb@"-"@ (subtraction) operator yields the difference of its -arguments. The numeric arguments are first converted to a common -type. -\index{subtraction} - -\section{Shifting operations} -\indexii{shifting}{operation} - -The shifting operations have lower priority than the arithmetic -operations: - -\begin{verbatim} -shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr -\end{verbatim} - -These operators accept plain or long integers as arguments. The -arguments are converted to a common type. They shift the first -argument to the left or right by the number of bits given by the -second argument. - -A right shift by \var{n} bits is defined as division by -\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as -multiplication with \code{pow(2,\var{n})}; for plain integers there is -no overflow check so this drops bits and flips the sign if the result -is not less than \code{pow(2,31)} in absolute value. - -Negative shift counts raise a \verb@ValueError@ exception. -\exindex{ValueError} - -\section{Binary bit-wise operations} -\indexiii{binary}{bit-wise}{operation} - -Each of the three bitwise operations has a different priority level: - -\begin{verbatim} -and_expr: shift_expr | and_expr "&" shift_expr -xor_expr: and_expr | xor_expr "^" and_expr -or_expr: xor_expr | or_expr "|" xor_expr -\end{verbatim} - -The \verb@"&"@ operator yields the bitwise AND of its arguments, which -must be plain or long integers. The arguments are converted to a -common type. -\indexii{bit-wise}{and} - -The \verb@"^"@ operator yields the bitwise XOR (exclusive OR) of its -arguments, which must be plain or long integers. The arguments are -converted to a common type. -\indexii{bit-wise}{xor} -\indexii{exclusive}{or} - -The \verb@"|"@ operator yields the bitwise (inclusive) OR of its -arguments, which must be plain or long integers. The arguments are -converted to a common type. -\indexii{bit-wise}{or} -\indexii{inclusive}{or} - -\section{Comparisons} -\index{comparison} - -Contrary to C, all comparison operations in Python have the same -priority, which is lower than that of any arithmetic, shifting or -bitwise operation. Also contrary to C, expressions like -\verb@a < b < c@ have the interpretation that is conventional in -mathematics: -\index{C} - -\begin{verbatim} -comparison: or_expr (comp_operator or_expr)* -comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in" -\end{verbatim} - -Comparisons yield integer values: 1 for true, 0 for false. - -Comparisons can be chained arbitrarily, e.g. \code{x < y <= z} is -equivalent to \code{x < y and y <= z}, except that \code{y} is -evaluated only once (but in both cases \code{z} is not evaluated at all -when \code{x < y} is found to be false). -\indexii{chaining}{comparisons} - -Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are -expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison -operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent -to \var{a opa b} \code{and} \var{b opb c} \code{and} \ldots \code{and} -\var{y opy z}, except that each expression is evaluated at most once. - -Note that \var{a opa b opb c} doesn't imply any kind of comparison -between \var{a} and \var{c}, so that e.g.\ \code{x < y > z} is -perfectly legal (though perhaps not pretty). - -The forms \verb@<>@ and \verb@!=@ are equivalent; for consistency with -C, \verb@!=@ is preferred; where \verb@!=@ is mentioned below -\verb@<>@ is also implied. - -The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare -the values of two objects. The objects needn't have the same type. -If both are numbers, they are coverted to a common type. Otherwise, -objects of different types {\em always} compare unequal, and are -ordered consistently but arbitrarily. - -(This unusual definition of comparison is done to simplify the -definition of operations like sorting and the \verb@in@ and -\verb@not@ \verb@in@ operators.) - -Comparison of objects of the same type depends on the type: - -\begin{itemize} - -\item -Numbers are compared arithmetically. - -\item -Strings are compared lexicographically using the numeric equivalents -(the result of the built-in function \verb@ord@) of their characters. - -\item -Tuples and lists are compared lexicographically using comparison of -corresponding items. - -\item -Mappings (dictionaries) are compared through lexicographic -comparison of their sorted (key, value) lists.% -\footnote{This is expensive since it requires sorting the keys first, -but about the only sensible definition. An earlier version of Python -compared dictionaries by identity only, but this caused surprises -because people expected to be able to test a dictionary for emptiness -by comparing it to {\tt \{\}}.} - -\item -Most other types compare unequal unless they are the same object; -the choice whether one object is considered smaller or larger than -another one is made arbitrarily but consistently within one -execution of a program. - -\end{itemize} - -The operators \verb@in@ and \verb@not in@ test for sequence -membership: if \var{y} is a sequence, \code{\var{x} in \var{y}} is -true if and only if there exists an index \var{i} such that -\code{\var{x} = \var{y}[\var{i}]}. -\code{\var{x} not in \var{y}} yields the inverse truth value. The -exception \verb@TypeError@ is raised when \var{y} is not a sequence, -or when \var{y} is a string and \var{x} is not a string of length one.% -\footnote{The latter restriction is sometimes a nuisance.} -\opindex{in} -\opindex{not in} -\indexii{membership}{test} -\obindex{sequence} - -The operators \verb@is@ and \verb@is not@ test for object identity: -\var{x} \code{is} \var{y} is true if and only if \var{x} and \var{y} -are the same object. \var{x} \code{is not} \var{y} yields the inverse -truth value. -\opindex{is} -\opindex{is not} -\indexii{identity}{test} - -\section{Boolean operations} \label{Booleans} -\indexii{Boolean}{operation} - -Boolean operations have the lowest priority of all Python operations: - -\begin{verbatim} -condition: or_test | lambda_form -or_test: and_test | or_test "or" and_test -and_test: not_test | and_test "and" not_test -not_test: comparison | "not" not_test -lambda_form: "lambda" [parameter_list]: condition -\end{verbatim} - -In the context of Boolean operations, and also when conditions are -used by control flow statements, the following values are interpreted -as false: \verb@None@, numeric zero of all types, empty sequences -(strings, tuples and lists), and empty mappings (dictionaries). All -other values are interpreted as true. - -The operator \verb@not@ yields 1 if its argument is false, 0 otherwise. -\opindex{not} - -The condition \var{x} \verb@and@ \var{y} first evaluates \var{x}; if -\var{x} is false, its value is returned; otherwise, \var{y} is -evaluated and the resulting value is returned. -\opindex{and} - -The condition \var{x} \verb@or@ \var{y} first evaluates \var{x}; if -\var{x} is true, its value is returned; otherwise, \var{y} is -evaluated and the resulting value is returned. -\opindex{or} - -(Note that \verb@and@ and \verb@or@ do not restrict the value and type -they return to 0 and 1, but rather return the last evaluated argument. -This is sometimes useful, e.g. if \verb@s@ is a string that should be -replaced by a default value if it is empty, the expression -\verb@s or 'foo'@ yields the desired value. Because \verb@not@ has to -invent a value anyway, it does not bother to return a value of the -same type as its argument, so e.g. \verb@not 'foo'@ yields \verb@0@, -not \verb@''@.) - -Lambda forms (lambda expressions) have the same syntactic position as -conditions. They are a shorthand to create anonymous functions; the -expression {\em {\tt lambda} arguments{\tt :} condition} -yields a function object that behaves virtually identical to one -defined with -{\em {\tt def} name {\tt (}arguments{\tt ): return} condition}. -See section \ref{function} for the syntax of -parameter lists. Note that functions created with lambda forms cannot -contain statements. -\label{lambda} -\indexii{lambda}{expression} -\indexii{lambda}{form} -\indexii{anonmymous}{function} - -\section{Expression lists and condition lists} -\indexii{expression}{list} -\indexii{condition}{list} - -\begin{verbatim} -expr_list: or_expr ("," or_expr)* [","] -cond_list: condition ("," condition)* [","] -\end{verbatim} - -The only difference between expression lists and condition lists is -the lowest priority of operators that can be used in them without -being enclosed in parentheses; condition lists allow all operators, -while expression lists don't allow comparisons and Boolean operators -(they do allow bitwise and shift operators though). - -Expression lists are used in expression statements and assignments; -condition lists are used everywhere else where a list of -comma-separated values is required. - -An expression (condition) list containing at least one comma yields a -tuple. The length of the tuple is the number of expressions -(conditions) in the list. The expressions (conditions) are evaluated -from left to right. (Condition lists are used syntactically is a few -places where no tuple is constructed but a list of values is needed -nevertheless.) -\obindex{tuple} - -The trailing comma is required only to create a single tuple (a.k.a. a -{\em singleton}); it is optional in all other cases. A single -expression (condition) without a trailing comma doesn't create a -tuple, but rather yields the value of that expression (condition). -\indexii{trailing}{comma} - -(To create an empty tuple, use an empty pair of parentheses: -\verb@()@.) - -\section{Summary} - -The following table summarizes the operator precedences in Python, -from lowest precedence (least binding) to highest precedence (most -binding). Operators in the same box have the same precedence. Unless -the syntax is explicitly given, operators are binary. Operators in -the same box group left to right (except for comparisons, which -chain from left to right --- see above). - -\begin{center} -\begin{tabular}{|c|c|} -\hline -\code{or} & Boolean OR \\ -\hline -\code{and} & Boolean AND \\ -\hline -\code{not} \var{x} & Boolean NOT \\ -\hline -\code{in}, \code{not} \code{in} & Membership tests \\ -\code{is}, \code{is} \code{not} & Identity tests \\ -\code{<}, \code{<=}, \code{>}, \code{>=}, \code{<>}, \code{!=}, \code{=} & - Comparisons \\ -\hline -\code{|} & Bitwise OR \\ -\hline -\code{\^} & Bitwise XOR \\ -\hline -\code{\&} & Bitwise AND \\ -\hline -\code{<<}, \code{>>} & Shifts \\ -\hline -\code{+}, \code{-} & Addition and subtraction \\ -\hline -\code{*}, \code{/}, \code{\%} & Multiplication, division, remainder \\ -\hline -\code{+\var{x}}, \code{-\var{x}} & Positive, negative \\ -\code{\~\var{x}} & Bitwise not \\ -\hline -\code{\var{x}.\var{attribute}} & Attribute reference \\ -\code{\var{x}[\var{index}]} & Subscription \\ -\code{\var{x}[\var{index}:\var{index}]} & Slicing \\ -\code{\var{f}(\var{arguments}...)} & Function call \\ -\hline -\code{(\var{expressions}\ldots)} & Binding or tuple display \\ -\code{[\var{expressions}\ldots]} & List display \\ -\code{\{\var{key}:\var{datum}\ldots\}} & Dictionary display \\ -\code{`\var{expression}\ldots`} & String conversion \\ -\hline -\end{tabular} -\end{center} diff --git a/Doc/ref/ref6.tex b/Doc/ref/ref6.tex deleted file mode 100644 index 22575c2039..0000000000 --- a/Doc/ref/ref6.tex +++ /dev/null @@ -1,536 +0,0 @@ -\chapter{Simple statements} -\indexii{simple}{statement} - -Simple statements are comprised within a single logical line. -Several simple statements may occur on a single line separated -by semicolons. The syntax for simple statements is: - -\begin{verbatim} -simple_stmt: expression_stmt - | assignment_stmt - | pass_stmt - | del_stmt - | print_stmt - | return_stmt - | raise_stmt - | break_stmt - | continue_stmt - | import_stmt - | global_stmt - | access_stmt - | exec_stmt -\end{verbatim} - -\section{Expression statements} -\indexii{expression}{statement} - -Expression statements are used (mostly interactively) to compute and -write a value, or (usually) to call a procedure (a function that -returns no meaningful result; in Python, procedures return the value -\verb@None@): - -\begin{verbatim} -expression_stmt: condition_list -\end{verbatim} - -An expression statement evaluates the condition list (which may be a -single condition). -\indexii{expression}{list} - -In interactive mode, if the value is not \verb@None@, it is converted -to a string using the rules for string conversions (expressions in -reverse quotes), and the resulting string is written to standard -output (see section \ref{print}) on a line by itself. -(The exception for \verb@None@ is made so that procedure calls, which -are syntactically equivalent to expressions, do not cause any output.) -\ttindex{None} -\indexii{string}{conversion} -\index{output} -\indexii{standard}{output} -\indexii{writing}{values} -\indexii{procedure}{call} - -\section{Assignment statements} -\indexii{assignment}{statement} - -Assignment statements are used to (re)bind names to values and to -modify attributes or items of mutable objects: -\indexii{binding}{name} -\indexii{rebinding}{name} -\obindex{mutable} -\indexii{attribute}{assignment} - -\begin{verbatim} -assignment_stmt: (target_list "=")+ expression_list -target_list: target ("," target)* [","] -target: identifier | "(" target_list ")" | "[" target_list "]" - | attributeref | subscription | slicing -\end{verbatim} - -(See section \ref{primaries} for the syntax definitions for the last -three symbols.) - -An assignment statement evaluates the expression list (remember that -this can be a single expression or a comma-separated list, the latter -yielding a tuple) and assigns the single resulting object to each of -the target lists, from left to right. -\indexii{expression}{list} - -Assignment is defined recursively depending on the form of the target -(list). When a target is part of a mutable object (an attribute -reference, subscription or slicing), the mutable object must -ultimately perform the assignment and decide about its validity, and -may raise an exception if the assignment is unacceptable. The rules -observed by various types and the exceptions raised are given with the -definition of the object types (see section \ref{types}). -\index{target} -\indexii{target}{list} - -Assignment of an object to a target list is recursively defined as -follows. -\indexiii{target}{list}{assignment} - -\begin{itemize} -\item -If the target list is a single target: the object is assigned to that -target. - -\item -If the target list is a comma-separated list of targets: the object -must be a tuple with the same number of items as the list contains -targets, and the items are assigned, from left to right, to the -corresponding targets. - -\end{itemize} - -Assignment of an object to a single target is recursively defined as -follows. - -\begin{itemize} % nested - -\item -If the target is an identifier (name): - -\begin{itemize} - -\item -If the name does not occur in a \verb@global@ statement in the current -code block: the name is bound to the object in the current local name -space. -\stindex{global} - -\item -Otherwise: the name is bound to the object in the current global name -space. - -\end{itemize} % nested - -The name is rebound if it was already bound. - -\item -If the target is a target list enclosed in parentheses: the object is -assigned to that target list as described above. - -\item -If the target is a target list enclosed in square brackets: the object -must be a list with the same number of items as the target list -contains targets, and its items are assigned, from left to right, to -the corresponding targets. - -\item -If the target is an attribute reference: The primary expression in the -reference is evaluated. It should yield an object with assignable -attributes; if this is not the case, \verb@TypeError@ is raised. That -object is then asked to assign the assigned object to the given -attribute; if it cannot perform the assignment, it raises an exception -(usually but not necessarily \verb@AttributeError@). -\indexii{attribute}{assignment} - -\item -If the target is a subscription: The primary expression in the -reference is evaluated. It should yield either a mutable sequence -(list) object or a mapping (dictionary) object. Next, the subscript -expression is evaluated. -\indexii{subscription}{assignment} -\obindex{mutable} - -If the primary is a mutable sequence object (a list), the subscript -must yield a plain integer. If it is negative, the sequence's length -is added to it. The resulting value must be a nonnegative integer -less than the sequence's length, and the sequence is asked to assign -the assigned object to its item with that index. If the index is out -of range, \verb@IndexError@ is raised (assignment to a subscripted -sequence cannot add new items to a list). -\obindex{sequence} -\obindex{list} - -If the primary is a mapping (dictionary) object, the subscript must -have a type compatible with the mapping's key type, and the mapping is -then asked to create a key/datum pair which maps the subscript to -the assigned object. This can either replace an existing key/value -pair with the same key value, or insert a new key/value pair (if no -key with the same value existed). -\obindex{mapping} -\obindex{dictionary} - -\item -If the target is a slicing: The primary expression in the reference is -evaluated. It should yield a mutable sequence object (e.g. a list). The -assigned object should be a sequence object of the same type. Next, -the lower and upper bound expressions are evaluated, insofar they are -present; defaults are zero and the sequence's length. The bounds -should evaluate to (small) integers. If either bound is negative, the -sequence's length is added to it. The resulting bounds are clipped to -lie between zero and the sequence's length, inclusive. Finally, the -sequence object is asked to replace the slice with the items of the -assigned sequence. The length of the slice may be different from the -length of the assigned sequence, thus changing the length of the -target sequence, if the object allows it. -\indexii{slicing}{assignment} - -\end{itemize} - -(In the current implementation, the syntax for targets is taken -to be the same as for expressions, and invalid syntax is rejected -during the code generation phase, causing less detailed error -messages.) - -WARNING: Although the definition of assignment implies that overlaps -between the left-hand side and the right-hand side are `safe' (e.g. -\verb@a, b = b, a@ swaps two variables), overlaps within the -collection of assigned-to variables are not safe! For instance, the -following program prints \code@[0, 2]@: - -\begin{verbatim} -x = [0, 1] -i = 0 -i, x[i] = 1, 2 -print x -\end{verbatim} - - -\section{The {\tt pass} statement} -\stindex{pass} - -\begin{verbatim} -pass_stmt: "pass" -\end{verbatim} - -\verb@pass@ is a null operation --- when it is executed, nothing -happens. It is useful as a placeholder when a statement is -required syntactically, but no code needs to be executed, for example: -\indexii{null}{operation} - -\begin{verbatim} -def f(arg): pass # a function that does nothing (yet) - -class C: pass # a class with no methods (yet) -\end{verbatim} - -\section{The {\tt del} statement} -\stindex{del} - -\begin{verbatim} -del_stmt: "del" target_list -\end{verbatim} - -Deletion is recursively defined very similar to the way assignment is -defined. Rather that spelling it out in full details, here are some -hints. -\indexii{deletion}{target} -\indexiii{deletion}{target}{list} - -Deletion of a target list recursively deletes each target, from left -to right. - -Deletion of a name removes the binding of that name (which must exist) -from the local or global name space, depending on whether the name -occurs in a \verb@global@ statement in the same code block. -\stindex{global} -\indexii{unbinding}{name} - -Deletion of attribute references, subscriptions and slicings -is passed to the primary object involved; deletion of a slicing -is in general equivalent to assignment of an empty slice of the -right type (but even this is determined by the sliced object). -\indexii{attribute}{deletion} - -\section{The {\tt print} statement} \label{print} -\stindex{print} - -\begin{verbatim} -print_stmt: "print" [ condition ("," condition)* [","] ] -\end{verbatim} - -\verb@print@ evaluates each condition in turn and writes the resulting -object to standard output (see below). If an object is not a string, -it is first converted to a string using the rules for string -conversions. The (resulting or original) string is then written. A -space is written before each object is (converted and) written, unless -the output system believes it is positioned at the beginning of a -line. This is the case: (1) when no characters have yet been written -to standard output; or (2) when the last character written to standard -output is \verb/\n/; or (3) when the last write operation on standard -output was not a \verb@print@ statement. (In some cases it may be -functional to write an empty string to standard output for this -reason.) -\index{output} -\indexii{writing}{values} - -A \verb/"\n"/ character is written at the end, unless the \verb@print@ -statement ends with a comma. This is the only action if the statement -contains just the keyword \verb@print@. -\indexii{trailing}{comma} -\indexii{newline}{suppression} - -Standard output is defined as the file object named \verb@stdout@ -in the built-in module \verb@sys@. If no such object exists, -or if it is not a writable file, a \verb@RuntimeError@ exception is raised. -(The original implementation attempts to write to the system's original -standard output instead, but this is not safe, and should be fixed.) -\indexii{standard}{output} -\bimodindex{sys} -\ttindex{stdout} -\exindex{RuntimeError} - -\section{The {\tt return} statement} -\stindex{return} - -\begin{verbatim} -return_stmt: "return" [condition_list] -\end{verbatim} - -\verb@return@ may only occur syntactically nested in a function -definition, not within a nested class definition. -\indexii{function}{definition} -\indexii{class}{definition} - -If a condition list is present, it is evaluated, else \verb@None@ -is substituted. - -\verb@return@ leaves the current function call with the condition -list (or \verb@None@) as return value. - -When \verb@return@ passes control out of a \verb@try@ statement -with a \verb@finally@ clause, that finally clause is executed -before really leaving the function. -\kwindex{finally} - -\section{The {\tt raise} statement} -\stindex{raise} - -\begin{verbatim} -raise_stmt: "raise" condition ["," condition ["," condition]] -\end{verbatim} - -\verb@raise@ evaluates its first condition, which must yield -a string, class, or instance object. If there is a second condition, -this is evaluated, else \verb@None@ is substituted. If the first -condition is a class object, then the second condition must be an -instance of that class or one of its derivatives. If the first -condition is an instance object, the second condition must be -\verb@None@. -\index{exception} -\indexii{raising}{exception} - -If the first object is a class or string, it then raises the exception -identified by the first object, with the second one (or \verb@None@) -as its parameter. If the first object is an instance, it raises the -exception identified by the class of the object, with the instance as -its parameter (and there should be no second object, or the second -object should be \verb@None@). - -If a third object is present, and it it not \verb@None@, it should be -a traceback object (see section \ref{traceback}), and it is -substituted instead of the current location as the place where the -exception occurred. This is useful to re-raise an exception -transparently in an except clause. -\obindex{traceback} - -\section{The {\tt break} statement} -\stindex{break} - -\begin{verbatim} -break_stmt: "break" -\end{verbatim} - -\verb@break@ may only occur syntactically nested in a \verb@for@ -or \verb@while@ loop, but not nested in a function or class definition -within that loop. -\stindex{for} -\stindex{while} -\indexii{loop}{statement} - -It terminates the nearest enclosing loop, skipping the optional -\verb@else@ clause if the loop has one. -\kwindex{else} - -If a \verb@for@ loop is terminated by \verb@break@, the loop control -target keeps its current value. -\indexii{loop control}{target} - -When \verb@break@ passes control out of a \verb@try@ statement -with a \verb@finally@ clause, that finally clause is executed -before really leaving the loop. -\kwindex{finally} - -\section{The {\tt continue} statement} -\stindex{continue} - -\begin{verbatim} -continue_stmt: "continue" -\end{verbatim} - -\verb@continue@ may only occur syntactically nested in a \verb@for@ or -\verb@while@ loop, but not nested in a function or class definition or -\verb@try@ statement within that loop.\footnote{Except that it may -currently occur within an {\tt except} clause.} -\stindex{for} -\stindex{while} -\indexii{loop}{statement} -\kwindex{finally} - -It continues with the next cycle of the nearest enclosing loop. - -\section{The {\tt import} statement} \label{import} -\stindex{import} - -\begin{verbatim} -import_stmt: "import" identifier ("," identifier)* - | "from" identifier "import" identifier ("," identifier)* - | "from" identifier "import" "*" -\end{verbatim} - -Import statements are executed in two steps: (1) find a module, and -initialize it if necessary; (2) define a name or names in the local -name space (of the scope where the \verb@import@ statement occurs). -The first form (without \verb@from@) repeats these steps for each -identifier in the list, the \verb@from@ form performs them once, with -the first identifier specifying the module name. -\indexii{importing}{module} -\indexii{name}{binding} -\kwindex{from} - -The system maintains a table of modules that have been initialized, -indexed by module name. (The current implementation makes this table -accessible as \verb@sys.modules@.) When a module name is found in -this table, step (1) is finished. If not, a search for a module -definition is started. This first looks for a built-in module -definition, and if no built-in module if the given name is found, it -searches a user-specified list of directories for a file whose name is -the module name with extension \verb@".py"@. (The current -implementation uses the list of strings \verb@sys.path@ as the search -path; it is initialized from the shell environment variable -\verb@$PYTHONPATH@, with an installation-dependent default.) -\ttindex{modules} -\ttindex{sys.modules} -\indexii{module}{name} -\indexii{built-in}{module} -\indexii{user-defined}{module} -\bimodindex{sys} -\ttindex{path} -\ttindex{sys.path} -\indexii{filename}{extension} - -If a built-in module is found, its built-in initialization code is -executed and step (1) is finished. If no matching file is found, -\verb@ImportError@ is raised. If a file is found, it is parsed, -yielding an executable code block. If a syntax error occurs, -\verb@SyntaxError@ is raised. Otherwise, an empty module of the given -name is created and inserted in the module table, and then the code -block is executed in the context of this module. Exceptions during -this execution terminate step (1). -\indexii{module}{initialization} -\exindex{SyntaxError} -\exindex{ImportError} -\index{code block} - -When step (1) finishes without raising an exception, step (2) can -begin. - -The first form of \verb@import@ statement binds the module name in the -local name space to the module object, and then goes on to import the -next identifier, if any. The \verb@from@ from does not bind the -module name: it goes through the list of identifiers, looks each one -of them up in the module found in step (1), and binds the name in the -local name space to the object thus found. If a name is not found, -\verb@ImportError@ is raised. If the list of identifiers is replaced -by a star (\verb@*@), all names defined in the module are bound, -except those beginning with an underscore(\verb@_@). -\indexii{name}{binding} -\exindex{ImportError} - -Names bound by import statements may not occur in \verb@global@ -statements in the same scope. -\stindex{global} - -The \verb@from@ form with \verb@*@ may only occur in a module scope. -\kwindex{from} -\ttindex{from ... import *} - -(The current implementation does not enforce the latter two -restrictions, but programs should not abuse this freedom, as future -implementations may enforce them or silently change the meaning of the -program.) - -\section{The {\tt global} statement} \label{global} -\stindex{global} - -\begin{verbatim} -global_stmt: "global" identifier ("," identifier)* -\end{verbatim} - -The \verb@global@ statement is a declaration which holds for the -entire current scope. It means that the listed identifiers are to be -interpreted as globals. While {\em using} global names is automatic -if they are not defined in the local scope, {\em assigning} to global -names would be impossible without \verb@global@. -\indexiii{global}{name}{binding} - -Names listed in a \verb@global@ statement must not be used in the same -scope before that \verb@global@ statement is executed. - -Names listed in a \verb@global@ statement must not be defined as formal -parameters or in a \verb@for@ loop control target, \verb@class@ -definition, function definition, or \verb@import@ statement. - -(The current implementation does not enforce the latter two -restrictions, but programs should not abuse this freedom, as future -implementations may enforce them or silently change the meaning of the -program.) - -\section{The {\tt access} statement} \label{access} -\stindex{access} - -\begin{verbatim} -access_stmt: "access" ... -\end{verbatim} - -This statement is obsolete. It no longer generates any code; in the -future, \verb@access@ will no longer be a reserved word. - -\section{The {\tt exec} statement} \label{exec} -\stindex{exec} - -\begin{verbatim} -exec_stmt: "exec" expression ["in" expression ["," expression]] -\end{verbatim} - -This statement supports dynamic execution of Python code. The first -expression should evaluate to either a string, an open file object, or -a code object. If it is a string, the string is parsed as a suite of -Python statements which is then executed (unless a syntax error -occurs). If it is an open file, the file is parsed until EOF and -executed. If it is a code object, it is simply executed. - -In all cases, if the optional parts are omitted, the code is executed -in the current scope. If only the first expression after \verb@in@ is -specified, it should be a dictionary, which will be used for both the -global and the local variables. If two expressions are given, both -must be dictionaries and they are used for the global and local -variables, respectively. - -Hints: dynamic evaluation of expressions is supported by the built-in -function \verb@eval()@. The built-in functions \verb@globals()@ and -\verb@locals()@ return the current global and local dictionary, -respectively, which may be useful to pass around for use by \verb@exec@. diff --git a/Doc/ref/ref7.tex b/Doc/ref/ref7.tex deleted file mode 100644 index 89fa6ed1f7..0000000000 --- a/Doc/ref/ref7.tex +++ /dev/null @@ -1,389 +0,0 @@ -\chapter{Compound statements} -\indexii{compound}{statement} - -Compound statements contain (groups of) other statements; they affect -or control the execution of those other statements in some way. In -general, compound statements span multiple lines, although in simple -incarnations a whole compound statement may be contained in one line. - -The \verb@if@, \verb@while@ and \verb@for@ statements implement -traditional control flow constructs. \verb@try@ specifies exception -handlers and/or cleanup code for a group of statements. Function and -class definitions are also syntactically compound statements. - -Compound statements consist of one or more `clauses'. A clause -consists of a header and a `suite'. The clause headers of a -particular compound statement are all at the same indentation level. -Each clause header begins with a uniquely identifying keyword and ends -with a colon. A suite is a group of statements controlled by a -clause. A suite can be one or more semicolon-separated simple -statements on the same line as the header, following the header's -colon, or it can be one or more indented statements on subsequent -lines. Only the latter form of suite can contain nested compound -statements; the following is illegal, mostly because it wouldn't be -clear to which \verb@if@ clause a following \verb@else@ clause would -belong: -\index{clause} -\index{suite} - -\begin{verbatim} -if test1: if test2: print x -\end{verbatim} - -Also note that the semicolon binds tighter than the colon in this -context, so that in the following example, either all or none of the -\verb@print@ statements are executed: - -\begin{verbatim} -if x < y < z: print x; print y; print z -\end{verbatim} - -Summarizing: - -\begin{verbatim} -compound_stmt: if_stmt | while_stmt | for_stmt - | try_stmt | funcdef | classdef -suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT -statement: stmt_list NEWLINE | compound_stmt -stmt_list: simple_stmt (";" simple_stmt)* [";"] -\end{verbatim} - -Note that statements always end in a \verb@NEWLINE@ possibly followed -by a \verb@DEDENT@. -\index{NEWLINE token} -\index{DEDENT token} - -Also note that optional continuation clauses always begin with a -keyword that cannot start a statement, thus there are no ambiguities -(the `dangling \verb@else@' problem is solved in Python by requiring -nested \verb@if@ statements to be indented). -\indexii{dangling}{else} - -The formatting of the grammar rules in the following sections places -each clause on a separate line for clarity. - -\section{The {\tt if} statement} -\stindex{if} - -The \verb@if@ statement is used for conditional execution: - -\begin{verbatim} -if_stmt: "if" condition ":" suite - ("elif" condition ":" suite)* - ["else" ":" suite] -\end{verbatim} - -It selects exactly one of the suites by evaluating the conditions one -by one until one is found to be true (see section \ref{Booleans} for -the definition of true and false); then that suite is executed (and no -other part of the \verb@if@ statement is executed or evaluated). If -all conditions are false, the suite of the \verb@else@ clause, if -present, is executed. -\kwindex{elif} -\kwindex{else} - -\section{The {\tt while} statement} -\stindex{while} -\indexii{loop}{statement} - -The \verb@while@ statement is used for repeated execution as long as a -condition is true: - -\begin{verbatim} -while_stmt: "while" condition ":" suite - ["else" ":" suite] -\end{verbatim} - -This repeatedly tests the condition and, if it is true, executes the -first suite; if the condition is false (which may be the first time it -is tested) the suite of the \verb@else@ clause, if present, is -executed and the loop terminates. -\kwindex{else} - -A \verb@break@ statement executed in the first suite terminates the -loop without executing the \verb@else@ clause's suite. A -\verb@continue@ statement executed in the first suite skips the rest -of the suite and goes back to testing the condition. -\stindex{break} -\stindex{continue} - -\section{The {\tt for} statement} -\stindex{for} -\indexii{loop}{statement} - -The \verb@for@ statement is used to iterate over the elements of a -sequence (string, tuple or list): -\obindex{sequence} - -\begin{verbatim} -for_stmt: "for" target_list "in" condition_list ":" suite - ["else" ":" suite] -\end{verbatim} - -The condition list is evaluated once; it should yield a sequence. The -suite is then executed once for each item in the sequence, in the -order of ascending indices. Each item in turn is assigned to the -target list using the standard rules for assignments, and then the -suite is executed. When the items are exhausted (which is immediately -when the sequence is empty), the suite in the \verb@else@ clause, if -present, is executed, and the loop terminates. -\kwindex{in} -\kwindex{else} -\indexii{target}{list} - -A \verb@break@ statement executed in the first suite terminates the -loop without executing the \verb@else@ clause's suite. A -\verb@continue@ statement executed in the first suite skips the rest -of the suite and continues with the next item, or with the \verb@else@ -clause if there was no next item. -\stindex{break} -\stindex{continue} - -The suite may assign to the variable(s) in the target list; this does -not affect the next item assigned to it. - -The target list is not deleted when the loop is finished, but if the -sequence is empty, it will not have been assigned to at all by the -loop. - -Hint: the built-in function \verb@range()@ returns a sequence of -integers suitable to emulate the effect of Pascal's -\verb@for i := a to b do@; -e.g. \verb@range(3)@ returns the list \verb@[0, 1, 2]@. -\bifuncindex{range} -\index{Pascal} - -{\bf Warning:} There is a subtlety when the sequence is being modified -by the loop (this can only occur for mutable sequences, i.e. lists). -An internal counter is used to keep track of which item is used next, -and this is incremented on each iteration. When this counter has -reached the length of the sequence the loop terminates. This means that -if the suite deletes the current (or a previous) item from the -sequence, the next item will be skipped (since it gets the index of -the current item which has already been treated). Likewise, if the -suite inserts an item in the sequence before the current item, the -current item will be treated again the next time through the loop. -This can lead to nasty bugs that can be avoided by making a temporary -copy using a slice of the whole sequence, e.g. -\index{loop!over mutable sequence} -\index{mutable sequence!loop over} - -\begin{verbatim} -for x in a[:]: - if x < 0: a.remove(x) -\end{verbatim} - -\section{The {\tt try} statement} \label{try} -\stindex{try} - -The \verb@try@ statement specifies exception handlers and/or cleanup -code for a group of statements: - -\begin{verbatim} -try_stmt: try_exc_stmt | try_fin_stmt -try_exc_stmt: "try" ":" suite - ("except" [condition ["," target]] ":" suite)+ - ["else" ":" suite] -try_fin_stmt: "try" ":" suite - "finally" ":" suite -\end{verbatim} - -There are two forms of \verb@try@ statement: \verb@try...except@ and -\verb@try...finally@. These forms cannot be mixed. - -The \verb@try...except@ form specifies one or more exception handlers -(the \verb@except@ clauses). When no exception occurs in the -\verb@try@ clause, no exception handler is executed. When an -exception occurs in the \verb@try@ suite, a search for an exception -handler is started. This inspects the except clauses in turn until -one is found that matches the exception. A condition-less except -clause, if present, must be last; it matches any exception. For an -except clause with a condition, that condition is evaluated, and the -clause matches the exception if the resulting object is ``compatible'' -with the exception. An object is compatible with an exception if it -is either the object that identifies the exception, or (for exceptions -that are classes) it is a base class of the exception, or it is a -tuple containing an item that is compatible with the exception. Note -that the object identities must match, i.e. it must be the same -object, not just an object with the same value. -\kwindex{except} - -If no except clause matches the exception, the search for an exception -handler continues in the surrounding code and on the invocation stack. - -If the evaluation of a condition in the header of an except clause -raises an exception, the original search for a handler is cancelled -and a search starts for the new exception in the surrounding code and -on the call stack (it is treated as if the entire \verb@try@ statement -raised the exception). - -When a matching except clause is found, the exception's parameter is -assigned to the target specified in that except clause, if present, -and the except clause's suite is executed. When the end of this suite -is reached, execution continues normally after the entire try -statement. (This means that if two nested handlers exist for the same -exception, and the exception occurs in the try clause of the inner -handler, the outer handler will not handle the exception.) - -Before an except clause's suite is executed, details about the -exception are assigned to three variables in the \verb@sys@ module: -\verb@sys.exc_type@ receives the object identifying the exception; -\verb@sys.exc_value@ receives the exception's parameter; -\verb@sys.exc_traceback@ receives a traceback object (see section -\ref{traceback}) identifying the point in the program where the -exception occurred. -\bimodindex{sys} -\ttindex{exc_type} -\ttindex{exc_value} -\ttindex{exc_traceback} -\obindex{traceback} - -The optional \verb@else@ clause is executed when no exception occurs -in the \verb@try@ clause. Exceptions in the \verb@else@ clause are -not handled by the preceding \verb@except@ clauses. -\kwindex{else} - -The \verb@try...finally@ form specifies a `cleanup' handler. The -\verb@try@ clause is executed. When no exception occurs, the -\verb@finally@ clause is executed. When an exception occurs in the -\verb@try@ clause, the exception is temporarily saved, the -\verb@finally@ clause is executed, and then the saved exception is -re-raised. If the \verb@finally@ clause raises another exception or -executes a \verb@return@, \verb@break@ or \verb@continue@ statement, -the saved exception is lost. -\kwindex{finally} - -When a \verb@return@ or \verb@break@ statement is executed in the -\verb@try@ suite of a \verb@try...finally@ statement, the -\verb@finally@ clause is also executed `on the way out'. A -\verb@continue@ statement is illegal in the \verb@try@ clause. (The -reason is a problem with the current implementation --- this -restriction may be lifted in the future). -\stindex{return} -\stindex{break} -\stindex{continue} - -\section{Function definitions} \label{function} -\indexii{function}{definition} - -A function definition defines a user-defined function object (see -section \ref{types}):\footnote{The new syntax to receive arbitrary -keyword arguments is not yet documented in this manual. See chapter -12 of the Tutorial.} -\obindex{user-defined function} -\obindex{function} - -\begin{verbatim} -funcdef: "def" funcname "(" [parameter_list] ")" ":" suite -parameter_list: (defparameter ",")* ("*" identifier | defparameter [","]) -defparameter: parameter ["=" condition] -sublist: parameter ("," parameter)* [","] -parameter: identifier | "(" sublist ")" -funcname: identifier -\end{verbatim} - -A function definition is an executable statement. Its execution binds -the function name in the current local name space to a function object -(a wrapper around the executable code for the function). This -function object contains a reference to the current global name space -as the global name space to be used when the function is called. -\indexii{function}{name} -\indexii{name}{binding} - -The function definition does not execute the function body; this gets -executed only when the function is called. - -When one or more top-level parameters have the form {\em parameter = -condition}, the function is said to have ``default parameter values''. -Default parameter values are evaluated when the function definition is -executed. For a parameter with a default value, the correponding -argument may be omitted from a call, in which case the parameter's -default value is substituted. If a parameter has a default value, all -following parameters must also have a default value --- this is a -syntactic restriction that is not expressed by the grammar.% -\footnote{Currently this is not checked; instead, -{\tt def f(a=1,b)} is interpreted as {\tt def f(a=1,b=None)}.} -\indexiii{default}{parameter}{value} - -Function call semantics are described in section \ref{calls}. When a -user-defined function is called, first missing arguments for which a -default value exists are supplied; then the arguments (a.k.a. actual -parameters) are bound to the (formal) parameters, as follows: -\indexii{function}{call} -\indexiii{user-defined}{function}{call} -\index{parameter} -\index{argument} -\indexii{parameter}{formal} -\indexii{parameter}{actual} - -\begin{itemize} - -\item -If there are no formal parameters, there must be no arguments. - -\item -If the formal parameter list does not end in a star followed by an -identifier, there must be exactly as many arguments as there are -parameters in the formal parameter list (at the top level); the -arguments are assigned to the formal parameters one by one. Note that -the presence or absence of a trailing comma at the top level in either -the formal or the actual parameter list makes no difference. The -assignment to a formal parameter is performed as if the parameter -occurs on the left hand side of an assignment statement whose right -hand side's value is that of the argument. - -\item -If the formal parameter list ends in a star followed by an identifier, -preceded by zero or more comma-followed parameters, there must be at -least as many arguments as there are parameters preceding the star. -Call this number {\em N}. The first {\em N} arguments are assigned to -the corresponding formal parameters in the way descibed above. A -tuple containing the remaining arguments, if any, is then assigned to -the identifier following the star. This variable will always be a -tuple: if there are no extra arguments, its value is \verb@()@, if -there is just one extra argument, it is a singleton tuple. -\indexii{variable length}{parameter list} - -\end{itemize} - -Note that the `variable length parameter list' feature only works at -the top level of the parameter list; individual parameters use a model -corresponding more closely to that of ordinary assignment. While the -latter model is generally preferable, because of the greater type -safety it offers (wrong-sized tuples aren't silently mistreated), -variable length parameter lists are a sufficiently accepted practice -in most programming languages that a compromise has been worked out. -(And anyway, assignment has no equivalent for empty argument lists.) - -It is also possible to create anonymous functions (functions not bound -to a name), for immediate use in expressions. This uses lambda forms, -described in section \ref{lambda}. -\indexii{lambda}{form} - -\section{Class definitions} \label{class} -\indexii{class}{definition} - -A class definition defines a class object (see section \ref{types}): -\obindex{class} - -\begin{verbatim} -classdef: "class" classname [inheritance] ":" suite -inheritance: "(" [condition_list] ")" -classname: identifier -\end{verbatim} - -A class definition is an executable statement. It first evaluates the -inheritance list, if present. Each item in the inheritance list -should evaluate to a class object. The class's suite is then executed -in a new execution frame (see section \ref{execframes}), using a newly -created local name space and the original global name space. -(Usually, the suite contains only function definitions.) When the -class's suite finishes execution, its execution frame is discarded but -its local name space is saved. A class object is then created using -the inheritance list for the base classes and the saved local name -space for the attribute dictionary. The class name is bound to this -class object in the original local name space. -\index{inheritance} -\indexii{class}{name} -\indexii{name}{binding} -\indexii{execution}{frame} diff --git a/Doc/ref/ref8.tex b/Doc/ref/ref8.tex deleted file mode 100644 index a9e688a840..0000000000 --- a/Doc/ref/ref8.tex +++ /dev/null @@ -1,105 +0,0 @@ -\chapter{Top-level components} - -The Python interpreter can get its input from a number of sources: -from a script passed to it as standard input or as program argument, -typed in interactively, from a module source file, etc. This chapter -gives the syntax used in these cases. -\index{interpreter} - -\section{Complete Python programs} -\index{program} - -While a language specification need not prescribe how the language -interpreter is invoked, it is useful to have a notion of a complete -Python program. A complete Python program is executed in a minimally -initialized environment: all built-in and standard modules are -available, but none have been initialized, except for \verb@sys@ -(various system services), \verb@__builtin__@ (built-in functions, -exceptions and \verb@None@) and \verb@__main__@. The latter is used -to provide the local and global name space for execution of the -complete program. -\bimodindex{sys} -\bimodindex{__main__} -\bimodindex{__builtin__} - -The syntax for a complete Python program is that for file input, -described in the next section. - -The interpreter may also be invoked in interactive mode; in this case, -it does not read and execute a complete program but reads and executes -one statement (possibly compound) at a time. The initial environment -is identical to that of a complete program; each statement is executed -in the name space of \verb@__main__@. -\index{interactive mode} -\bimodindex{__main__} - -Under {\UNIX}, a complete program can be passed to the interpreter in -three forms: with the {\bf -c} {\it string} command line option, as a -file passed as the first command line argument, or as standard input. -If the file or standard input is a tty device, the interpreter enters -interactive mode; otherwise, it executes the file as a complete -program. -\index{UNIX} -\index{command line} -\index{standard input} - -\section{File input} - -All input read from non-interactive files has the same form: - -\begin{verbatim} -file_input: (NEWLINE | statement)* -\end{verbatim} - -This syntax is used in the following situations: - -\begin{itemize} - -\item when parsing a complete Python program (from a file or from a string); - -\item when parsing a module; - -\item when parsing a string passed to the \verb@exec@ statement; - -\end{itemize} - -\section{Interactive input} - -Input in interactive mode is parsed using the following grammar: - -\begin{verbatim} -interactive_input: [stmt_list] NEWLINE | compound_stmt NEWLINE -\end{verbatim} - -Note that a (top-level) compound statement must be followed by a blank -line in interactive mode; this is needed to help the parser detect the -end of the input. - -\section{Expression input} -\index{input} - -There are two forms of expression input. Both ignore leading -whitespace. - -The string argument to \verb@eval()@ must have the following form: -\bifuncindex{eval} - -\begin{verbatim} -eval_input: condition_list NEWLINE* -\end{verbatim} - -The input line read by \verb@input()@ must have the following form: -\bifuncindex{input} - -\begin{verbatim} -input_input: condition_list NEWLINE -\end{verbatim} - -Note: to read `raw' input line without interpretation, you can use the -built-in function \verb@raw_input()@ or the \verb@readline()@ method -of file objects. -\obindex{file} -\index{input!raw} -\index{raw input} -\bifuncindex{raw_index} -\ttindex{readline} diff --git a/Doc/ref1.tex b/Doc/ref1.tex deleted file mode 100644 index 30bfcce022..0000000000 --- a/Doc/ref1.tex +++ /dev/null @@ -1,81 +0,0 @@ -\chapter{Introduction} - -This reference manual describes the Python programming language. -It is not intended as a tutorial. - -While I am trying to be as precise as possible, I chose to use English -rather than formal specifications for everything except syntax and -lexical analysis. This should make the document more understandable -to the average reader, but will leave room for ambiguities. -Consequently, if you were coming from Mars and tried to re-implement -Python from this document alone, you might have to guess things and in -fact you would probably end up implementing quite a different language. -On the other hand, if you are using -Python and wonder what the precise rules about a particular area of -the language are, you should definitely be able to find them here. - -It is dangerous to add too many implementation details to a language -reference document --- the implementation may change, and other -implementations of the same language may work differently. On the -other hand, there is currently only one Python implementation, and -its particular quirks are sometimes worth being mentioned, especially -where the implementation imposes additional limitations. Therefore, -you'll find short ``implementation notes'' sprinkled throughout the -text. - -Every Python implementation comes with a number of built-in and -standard modules. These are not documented here, but in the separate -{\em Python Library Reference} document. A few built-in modules are -mentioned when they interact in a significant way with the language -definition. - -\section{Notation} - -The descriptions of lexical analysis and syntax use a modified BNF -grammar notation. This uses the following style of definition: -\index{BNF} -\index{grammar} -\index{syntax} -\index{notation} - -\begin{verbatim} -name: lc_letter (lc_letter | "_")* -lc_letter: "a"..."z" -\end{verbatim} - -The first line says that a \verb@name@ is an \verb@lc_letter@ followed by -a sequence of zero or more \verb@lc_letter@s and underscores. An -\verb@lc_letter@ in turn is any of the single characters `a' through `z'. -(This rule is actually adhered to for the names defined in lexical and -grammar rules in this document.) - -Each rule begins with a name (which is the name defined by the rule) -and a colon. A vertical bar (\verb@|@) is used to separate -alternatives; it is the least binding operator in this notation. A -star (\verb@*@) means zero or more repetitions of the preceding item; -likewise, a plus (\verb@+@) means one or more repetitions, and a -phrase enclosed in square brackets (\verb@[ ]@) means zero or one -occurrences (in other words, the enclosed phrase is optional). The -\verb@*@ and \verb@+@ operators bind as tightly as possible; -parentheses are used for grouping. Literal strings are enclosed in -quotes. White space is only meaningful to separate tokens. -Rules are normally contained on a single line; rules with many -alternatives may be formatted alternatively with each line after the -first beginning with a vertical bar. - -In lexical definitions (as the example above), two more conventions -are used: Two literal characters separated by three dots mean a choice -of any single character in the given (inclusive) range of \ASCII{} -characters. A phrase between angular brackets (\verb@<...>@) gives an -informal description of the symbol defined; e.g. this could be used -to describe the notion of `control character' if needed. -\index{lexical definitions} -\index{ASCII} - -Even though the notation used is almost the same, there is a big -difference between the meaning of lexical and syntactic definitions: -a lexical definition operates on the individual characters of the -input source, while a syntax definition operates on the stream of -tokens generated by the lexical analysis. All uses of BNF in the next -chapter (``Lexical Analysis'') are lexical definitions; uses in -subsequent chapters are syntactic definitions. diff --git a/Doc/ref2.tex b/Doc/ref2.tex deleted file mode 100644 index 9ccfee6ce1..0000000000 --- a/Doc/ref2.tex +++ /dev/null @@ -1,372 +0,0 @@ -\chapter{Lexical analysis} - -A Python program is read by a {\em parser}. Input to the parser is a -stream of {\em tokens}, generated by the {\em lexical analyzer}. This -chapter describes how the lexical analyzer breaks a file into tokens. -\index{lexical analysis} -\index{parser} -\index{token} - -\section{Line structure} - -A Python program is divided in a number of logical lines. The end of -a logical line is represented by the token NEWLINE. Statements cannot -cross logical line boundaries except where NEWLINE is allowed by the -syntax (e.g. between statements in compound statements). -\index{line structure} -\index{logical line} -\index{NEWLINE token} - -\subsection{Comments} - -A comment starts with a hash character (\verb@#@) that is not part of -a string literal, and ends at the end of the physical line. A comment -always signifies the end of the logical line. Comments are ignored by -the syntax. -\index{comment} -\index{logical line} -\index{physical line} -\index{hash character} - -\subsection{Explicit line joining} - -Two or more physical lines may be joined into logical lines using -backslash characters (\verb/\/), as follows: when a physical line ends -in a backslash that is not part of a string literal or comment, it is -joined with the following forming a single logical line, deleting the -backslash and the following end-of-line character. For example: -\index{physical line} -\index{line joining} -\index{line continuation} -\index{backslash character} -% -\begin{verbatim} -if 1900 < year < 2100 and 1 <= month <= 12 \ - and 1 <= day <= 31 and 0 <= hour < 24 \ - and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date - return 1 -\end{verbatim} - -A line ending in a backslash cannot carry a comment; a backslash does -not continue a comment (but it does continue a string literal, see -below). - -\subsection{Implicit line joining} - -Expressions in parentheses, square brackets or curly braces can be -split over more than one physical line without using backslashes. -For example: - -\begin{verbatim} -month_names = ['Januari', 'Februari', 'Maart', # These are the - 'April', 'Mei', 'Juni', # Dutch names - 'Juli', 'Augustus', 'September', # for the months - 'Oktober', 'November', 'December'] # of the year -\end{verbatim} - -Implicitly continued lines can carry comments. The indentation of the -continuation lines is not important. Blank continuation lines are -allowed. - -\subsection{Blank lines} - -A logical line that contains only spaces, tabs, and possibly a -comment, is ignored (i.e., no NEWLINE token is generated), except that -during interactive input of statements, an entirely blank logical line -terminates a multi-line statement. -\index{blank line} - -\subsection{Indentation} - -Leading whitespace (spaces and tabs) at the beginning of a logical -line is used to compute the indentation level of the line, which in -turn is used to determine the grouping of statements. -\index{indentation} -\index{whitespace} -\index{leading whitespace} -\index{space} -\index{tab} -\index{grouping} -\index{statement grouping} - -First, tabs are replaced (from left to right) by one to eight spaces -such that the total number of characters up to there is a multiple of -eight (this is intended to be the same rule as used by {\UNIX}). The -total number of spaces preceding the first non-blank character then -determines the line's indentation. Indentation cannot be split over -multiple physical lines using backslashes. - -The indentation levels of consecutive lines are used to generate -INDENT and DEDENT tokens, using a stack, as follows. -\index{INDENT token} -\index{DEDENT token} - -Before the first line of the file is read, a single zero is pushed on -the stack; this will never be popped off again. The numbers pushed on -the stack will always be strictly increasing from bottom to top. At -the beginning of each logical line, the line's indentation level is -compared to the top of the stack. If it is equal, nothing happens. -If it is larger, it is pushed on the stack, and one INDENT token is -generated. If it is smaller, it {\em must} be one of the numbers -occurring on the stack; all numbers on the stack that are larger are -popped off, and for each number popped off a DEDENT token is -generated. At the end of the file, a DEDENT token is generated for -each number remaining on the stack that is larger than zero. - -Here is an example of a correctly (though confusingly) indented piece -of Python code: - -\begin{verbatim} -def perm(l): - # Compute the list of all permutations of l - - if len(l) <= 1: - return [l] - r = [] - for i in range(len(l)): - s = l[:i] + l[i+1:] - p = perm(s) - for x in p: - r.append(l[i:i+1] + x) - return r -\end{verbatim} - -The following example shows various indentation errors: - -\begin{verbatim} - def perm(l): # error: first line indented - for i in range(len(l)): # error: not indented - s = l[:i] + l[i+1:] - p = perm(l[:i] + l[i+1:]) # error: unexpected indent - for x in p: - r.append(l[i:i+1] + x) - return r # error: inconsistent dedent -\end{verbatim} - -(Actually, the first three errors are detected by the parser; only the -last error is found by the lexical analyzer --- the indentation of -\verb@return r@ does not match a level popped off the stack.) - -\section{Other tokens} - -Besides NEWLINE, INDENT and DEDENT, the following categories of tokens -exist: identifiers, keywords, literals, operators, and delimiters. -Spaces and tabs are not tokens, but serve to delimit tokens. Where -ambiguity exists, a token comprises the longest possible string that -forms a legal token, when read from left to right. - -\section{Identifiers} - -Identifiers (also referred to as names) are described by the following -lexical definitions: -\index{identifier} -\index{name} - -\begin{verbatim} -identifier: (letter|"_") (letter|digit|"_")* -letter: lowercase | uppercase -lowercase: "a"..."z" -uppercase: "A"..."Z" -digit: "0"..."9" -\end{verbatim} - -Identifiers are unlimited in length. Case is significant. - -\subsection{Keywords} - -The following identifiers are used as reserved words, or {\em -keywords} of the language, and cannot be used as ordinary -identifiers. They must be spelled exactly as written here: -\index{keyword} -\index{reserved word} - -\begin{verbatim} -access del from lambda return -and elif global not try -break else if or while -class except import pass -continue finally in print -def for is raise -\end{verbatim} - -% When adding keywords, pipe it through keywords.py for reformatting - -\section{Literals} \label{literals} - -Literals are notations for constant values of some built-in types. -\index{literal} -\index{constant} - -\subsection{String literals} - -String literals are described by the following lexical definitions: -\index{string literal} - -\begin{verbatim} -stringliteral: shortstring | longstring -shortstring: "'" shortstringitem* "'" | '"' shortstringitem* '"' -longstring: "'''" longstringitem* "'''" | '"""' longstringitem* '"""' -shortstringitem: shortstringchar | escapeseq -longstringitem: longstringchar | escapeseq -shortstringchar: <any ASCII character except "\" or newline or the quote> -longstringchar: <any ASCII character except "\"> -escapeseq: "\" <any ASCII character> -\end{verbatim} -\index{ASCII} - -In ``long strings'' (strings surrounded by sets of three quotes), -unescaped newlines and quotes are allowed (and are retained), except -that three unescaped quotes in a row terminate the string. (A -``quote'' is the character used to open the string, i.e. either -\verb/'/ or \verb/"/.) - -Escape sequences in strings are interpreted according to rules similar -to those used by Standard C. The recognized escape sequences are: -\index{physical line} -\index{escape sequence} -\index{Standard C} -\index{C} - -\begin{center} -\begin{tabular}{|l|l|} -\hline -\verb/\/{\em newline} & Ignored \\ -\verb/\\/ & Backslash (\verb/\/) \\ -\verb/\'/ & Single quote (\verb/'/) \\ -\verb/\"/ & Double quote (\verb/"/) \\ -\verb/\a/ & \ASCII{} Bell (BEL) \\ -\verb/\b/ & \ASCII{} Backspace (BS) \\ -%\verb/\E/ & \ASCII{} Escape (ESC) \\ -\verb/\f/ & \ASCII{} Formfeed (FF) \\ -\verb/\n/ & \ASCII{} Linefeed (LF) \\ -\verb/\r/ & \ASCII{} Carriage Return (CR) \\ -\verb/\t/ & \ASCII{} Horizontal Tab (TAB) \\ -\verb/\v/ & \ASCII{} Vertical Tab (VT) \\ -\verb/\/{\em ooo} & \ASCII{} character with octal value {\em ooo} \\ -\verb/\x/{\em xx...} & \ASCII{} character with hex value {\em xx...} \\ -\hline -\end{tabular} -\end{center} -\index{ASCII} - -In strict compatibility with Standard C, up to three octal digits are -accepted, but an unlimited number of hex digits is taken to be part of -the hex escape (and then the lower 8 bits of the resulting hex number -are used in all current implementations...). - -All unrecognized escape sequences are left in the string unchanged, -i.e., {\em the backslash is left in the string.} (This behavior is -useful when debugging: if an escape sequence is mistyped, the -resulting output is more easily recognized as broken. It also helps a -great deal for string literals used as regular expressions or -otherwise passed to other modules that do their own escape handling.) -\index{unrecognized escape sequence} - -\subsection{Numeric literals} - -There are three types of numeric literals: plain integers, long -integers, and floating point numbers. -\index{number} -\index{numeric literal} -\index{integer literal} -\index{plain integer literal} -\index{long integer literal} -\index{floating point literal} -\index{hexadecimal literal} -\index{octal literal} -\index{decimal literal} - -Integer and long integer literals are described by the following -lexical definitions: - -\begin{verbatim} -longinteger: integer ("l"|"L") -integer: decimalinteger | octinteger | hexinteger -decimalinteger: nonzerodigit digit* | "0" -octinteger: "0" octdigit+ -hexinteger: "0" ("x"|"X") hexdigit+ - -nonzerodigit: "1"..."9" -octdigit: "0"..."7" -hexdigit: digit|"a"..."f"|"A"..."F" -\end{verbatim} - -Although both lower case `l' and upper case `L' are allowed as suffix -for long integers, it is strongly recommended to always use `L', since -the letter `l' looks too much like the digit `1'. - -Plain integer decimal literals must be at most 2147483647 (i.e., the -largest positive integer, using 32-bit arithmetic). Plain octal and -hexadecimal literals may be as large as 4294967295, but values larger -than 2147483647 are converted to a negative value by subtracting -4294967296. There is no limit for long integer literals apart from -what can be stored in available memory. - -Some examples of plain and long integer literals: - -\begin{verbatim} -7 2147483647 0177 0x80000000 -3L 79228162514264337593543950336L 0377L 0x100000000L -\end{verbatim} - -Floating point literals are described by the following lexical -definitions: - -\begin{verbatim} -floatnumber: pointfloat | exponentfloat -pointfloat: [intpart] fraction | intpart "." -exponentfloat: (intpart | pointfloat) exponent -intpart: digit+ -fraction: "." digit+ -exponent: ("e"|"E") ["+"|"-"] digit+ -\end{verbatim} - -The allowed range of floating point literals is -implementation-dependent. - -Some examples of floating point literals: - -\begin{verbatim} -3.14 10. .001 1e100 3.14e-10 -\end{verbatim} - -Note that numeric literals do not include a sign; a phrase like -\verb@-1@ is actually an expression composed of the operator -\verb@-@ and the literal \verb@1@. - -\section{Operators} - -The following tokens are operators: -\index{operators} - -\begin{verbatim} -+ - * / % -<< >> & | ^ ~ -< == > <= <> != >= -\end{verbatim} - -The comparison operators \verb@<>@ and \verb@!=@ are alternate -spellings of the same operator. - -\section{Delimiters} - -The following tokens serve as delimiters or otherwise have a special -meaning: -\index{delimiters} - -\begin{verbatim} -( ) [ ] { } -, : . " ` ' -= ; -\end{verbatim} - -The following printing \ASCII{} characters are not used in Python. Their -occurrence outside string literals and comments is an unconditional -error: -\index{ASCII} - -\begin{verbatim} -@ $ ? -\end{verbatim} - -They may be used by future versions of the language though! diff --git a/Doc/ref3.tex b/Doc/ref3.tex deleted file mode 100644 index 60af2dc94a..0000000000 --- a/Doc/ref3.tex +++ /dev/null @@ -1,876 +0,0 @@ -\chapter{Data model} - -\section{Objects, values and types} - -{\em Objects} are Python's abstraction for data. All data in a Python -program is represented by objects or by relations between objects. -(In a sense, and in conformance to Von Neumann's model of a -``stored program computer'', code is also represented by objects.) -\index{object} -\index{data} - -Every object has an identity, a type and a value. An object's {\em -identity} never changes once it has been created; you may think of it -as the object's address in memory. An object's {\em type} is also -unchangeable. It determines the operations that an object supports -(e.g. ``does it have a length?'') and also defines the possible -values for objects of that type. The {\em value} of some objects can -change. Objects whose value can change are said to be {\em mutable}; -objects whose value is unchangeable once they are created are called -{\em immutable}. The type determines an object's (im)mutability. -\index{identity of an object} -\index{value of an object} -\index{type of an object} -\index{mutable object} -\index{immutable object} - -Objects are never explicitly destroyed; however, when they become -unreachable they may be garbage-collected. An implementation is -allowed to delay garbage collection or omit it altogether --- it is a -matter of implementation quality how garbage collection is -implemented, as long as no objects are collected that are still -reachable. (Implementation note: the current implementation uses a -reference-counting scheme which collects most objects as soon as they -become unreachable, but never collects garbage containing circular -references.) -\index{garbage collection} -\index{reference counting} -\index{unreachable object} - -Note that the use of the implementation's tracing or debugging -facilities may keep objects alive that would normally be collectable. - -Some objects contain references to ``external'' resources such as open -files or windows. It is understood that these resources are freed -when the object is garbage-collected, but since garbage collection is -not guaranteed to happen, such objects also provide an explicit way to -release the external resource, usually a \verb@close@ method. -Programs are strongly recommended to always explicitly close such -objects. - -Some objects contain references to other objects; these are called -{\em containers}. Examples of containers are tuples, lists and -dictionaries. The references are part of a container's value. In -most cases, when we talk about the value of a container, we imply the -values, not the identities of the contained objects; however, when we -talk about the (im)mutability of a container, only the identities of -the immediately contained objects are implied. (So, if an immutable -container contains a reference to a mutable object, its value changes -if that mutable object is changed.) -\index{container} - -Types affect almost all aspects of objects' lives. Even the meaning -of object identity is affected in some sense: for immutable types, -operations that compute new values may actually return a reference to -any existing object with the same type and value, while for mutable -objects this is not allowed. E.g. after - -\begin{verbatim} -a = 1; b = 1; c = []; d = [] -\end{verbatim} - -\verb@a@ and \verb@b@ may or may not refer to the same object with the -value one, depending on the implementation, but \verb@c@ and \verb@d@ -are guaranteed to refer to two different, unique, newly created empty -lists. - -\section{The standard type hierarchy} \label{types} - -Below is a list of the types that are built into Python. Extension -modules written in C can define additional types. Future versions of -Python may add types to the type hierarchy (e.g. rational or complex -numbers, efficiently stored arrays of integers, etc.). -\index{type} -\indexii{data}{type} -\indexii{type}{hierarchy} -\indexii{extension}{module} -\index{C} - -Some of the type descriptions below contain a paragraph listing -`special attributes'. These are attributes that provide access to the -implementation and are not intended for general use. Their definition -may change in the future. There are also some `generic' special -attributes, not listed with the individual objects: \verb@__methods__@ -is a list of the method names of a built-in object, if it has any; -\verb@__members__@ is a list of the data attribute names of a built-in -object, if it has any. -\index{attribute} -\indexii{special}{attribute} -\indexiii{generic}{special}{attribute} -\ttindex{__methods__} -\ttindex{__members__} - -\begin{description} - -\item[None] -This type has a single value. There is a single object with this value. -This object is accessed through the built-in name \verb@None@. -It is returned from functions that don't explicitly return an object. -\ttindex{None} -\obindex{None@{\tt None}} - -\item[Numbers] -These are created by numeric literals and returned as results by -arithmetic operators and arithmetic built-in functions. Numeric -objects are immutable; once created their value never changes. Python -numbers are of course strongly related to mathematical numbers, but -subject to the limitations of numerical representation in computers. -\obindex{number} -\obindex{numeric} - -Python distinguishes between integers and floating point numbers: - -\begin{description} -\item[Integers] -These represent elements from the mathematical set of whole numbers. -\obindex{integer} - -There are two types of integers: - -\begin{description} - -\item[Plain integers] -These represent numbers in the range -2147483648 through 2147483647. -(The range may be larger on machines with a larger natural word -size, but not smaller.) -When the result of an operation falls outside this range, the -exception \verb@OverflowError@ is raised. -For the purpose of shift and mask operations, integers are assumed to -have a binary, 2's complement notation using 32 or more bits, and -hiding no bits from the user (i.e., all 4294967296 different bit -patterns correspond to different values). -\obindex{plain integer} - -\item[Long integers] -These represent numbers in an unlimited range, subject to available -(virtual) memory only. For the purpose of shift and mask operations, -a binary representation is assumed, and negative numbers are -represented in a variant of 2's complement which gives the illusion of -an infinite string of sign bits extending to the left. -\obindex{long integer} - -\end{description} % Integers - -The rules for integer representation are intended to give the most -meaningful interpretation of shift and mask operations involving -negative integers and the least surprises when switching between the -plain and long integer domains. For any operation except left shift, -if it yields a result in the plain integer domain without causing -overflow, it will yield the same result in the long integer domain or -when using mixed operands. -\indexii{integer}{representation} - -\item[Floating point numbers] -These represent machine-level double precision floating point numbers. -You are at the mercy of the underlying machine architecture and -C implementation for the accepted range and handling of overflow. -\obindex{floating point} -\indexii{floating point}{number} -\index{C} - -\end{description} % Numbers - -\item[Sequences] -These represent finite ordered sets indexed by natural numbers. -The built-in function \verb@len()@ returns the number of elements -of a sequence. When this number is \var{n}, the index set contains -the numbers 0, 1, \ldots, \var{n}-1. Element \var{i} of sequence -\var{a} is selected by \code{\var{a}[\var{i}]}. -\obindex{seqence} -\bifuncindex{len} -\index{index operation} -\index{item selection} -\index{subscription} - -Sequences also support slicing: \verb@a[i:j]@ selects all elements -with index \var{k} such that \var{i} \code{<=} \var{k} \code{<} -\var{j}. When used as an expression, a slice is a sequence of the -same type --- this implies that the index set is renumbered so that it -starts at 0 again. -\index{slicing} - -Sequences are distinguished according to their mutability: - -\begin{description} -% -\item[Immutable sequences] -An object of an immutable sequence type cannot change once it is -created. (If the object contains references to other objects, -these other objects may be mutable and may be changed; however -the collection of objects directly referenced by an immutable object -cannot change.) -\obindex{immutable sequence} -\obindex{immutable} - -The following types are immutable sequences: - -\begin{description} - -\item[Strings] -The elements of a string are characters. There is no separate -character type; a character is represented by a string of one element. -Characters represent (at least) 8-bit bytes. The built-in -functions \verb@chr()@ and \verb@ord()@ convert between characters -and nonnegative integers representing the byte values. -Bytes with the values 0-127 represent the corresponding \ASCII{} values. -The string data type is also used to represent arrays of bytes, e.g. -to hold data read from a file. -\obindex{string} -\index{character} -\index{byte} -\index{ASCII} -\bifuncindex{chr} -\bifuncindex{ord} - -(On systems whose native character set is not \ASCII{}, strings may use -EBCDIC in their internal representation, provided the functions -\verb@chr()@ and \verb@ord()@ implement a mapping between \ASCII{} and -EBCDIC, and string comparison preserves the \ASCII{} order. -Or perhaps someone can propose a better rule?) -\index{ASCII} -\index{EBCDIC} -\index{character set} -\indexii{string}{comparison} -\bifuncindex{chr} -\bifuncindex{ord} - -\item[Tuples] -The elements of a tuple are arbitrary Python objects. -Tuples of two or more elements are formed by comma-separated lists -of expressions. A tuple of one element (a `singleton') can be formed -by affixing a comma to an expression (an expression by itself does -not create a tuple, since parentheses must be usable for grouping of -expressions). An empty tuple can be formed by enclosing `nothing' in -parentheses. -\obindex{tuple} -\indexii{singleton}{tuple} -\indexii{empty}{tuple} - -\end{description} % Immutable sequences - -\item[Mutable sequences] -Mutable sequences can be changed after they are created. The -subscription and slicing notations can be used as the target of -assignment and \verb@del@ (delete) statements. -\obindex{mutable sequece} -\obindex{mutable} -\indexii{assignment}{statement} -\index{delete} -\stindex{del} -\index{subscription} -\index{slicing} - -There is currently a single mutable sequence type: - -\begin{description} - -\item[Lists] -The elements of a list are arbitrary Python objects. Lists are formed -by placing a comma-separated list of expressions in square brackets. -(Note that there are no special cases needed to form lists of length 0 -or 1.) -\obindex{list} - -\end{description} % Mutable sequences - -\end{description} % Sequences - -\item[Mapping types] -These represent finite sets of objects indexed by arbitrary index sets. -The subscript notation \verb@a[k]@ selects the element indexed -by \verb@k@ from the mapping \verb@a@; this can be used in -expressions and as the target of assignments or \verb@del@ statements. -The built-in function \verb@len()@ returns the number of elements -in a mapping. -\bifuncindex{len} -\index{subscription} -\obindex{mapping} - -There is currently a single mapping type: - -\begin{description} - -\item[Dictionaries] -These represent finite sets of objects indexed by almost arbitrary -values. The only types of values not acceptable as keys are values -containing lists or dictionaries or other mutable types that are -compared by value rather than by object identity --- the reason being -that the implementation requires that a key's hash value be constant. -Numeric types used for keys obey the normal rules for numeric -comparison: if two numbers compare equal (e.g. 1 and 1.0) then they -can be used interchangeably to index the same dictionary entry. - -Dictionaries are mutable; they are created by the \verb@{...}@ -notation (see section \ref{dict}). -\obindex{dictionary} -\obindex{mutable} - -\end{description} % Mapping types - -\item[Callable types] -These are the types to which the function call (invocation) operation, -written as \verb@function(argument, argument, ...)@, can be applied: -\indexii{function}{call} -\index{invocation} -\indexii{function}{argument} -\obindex{callable} - -\begin{description} - -\item[User-defined functions] -A user-defined function object is created by a function definition -(see section \ref{function}). It should be called with an argument -list containing the same number of items as the function's formal -parameter list. -\indexii{user-defined}{function} -\obindex{function} -\obindex{user-defined function} - -Special read-only attributes: \verb@func_code@ is the code object -representing the compiled function body, and \verb@func_globals@ is (a -reference to) the dictionary that holds the function's global -variables --- it implements the global name space of the module in -which the function was defined. -\ttindex{func_code} -\ttindex{func_globals} -\indexii{global}{name space} - -\item[User-defined methods] -A user-defined method (a.k.a. {\em object closure}) is a pair of a -class instance object and a user-defined function. It should be -called with an argument list containing one item less than the number -of items in the function's formal parameter list. When called, the -class instance becomes the first argument, and the call arguments are -shifted one to the right. -\obindex{method} -\obindex{user-defined method} -\indexii{user-defined}{method} -\index{object closure} - -Special read-only attributes: \verb@im_self@ is the class instance -object, \verb@im_func@ is the function object. -\ttindex{im_func} -\ttindex{im_self} - -\item[Built-in functions] -A built-in function object is a wrapper around a C function. Examples -of built-in functions are \verb@len@ and \verb@math.sin@. There -are no special attributes. The number and type of the arguments are -determined by the C function. -\obindex{built-in function} -\obindex{function} -\index{C} - -\item[Built-in methods] -This is really a different disguise of a built-in function, this time -containing an object passed to the C function as an implicit extra -argument. An example of a built-in method is \verb@list.append@ if -\verb@list@ is a list object. -\obindex{built-in method} -\obindex{method} -\indexii{built-in}{method} - -\item[Classes] -Class objects are described below. When a class object is called as a -function, a new class instance (also described below) is created and -returned. This implies a call to the class's \verb@__init__@ method -if it has one. Any arguments are passed on to the \verb@__init__@ -method --- if there is no \verb@__init__@ method, the class must be called -without arguments. -\ttindex{__init__} -\obindex{class} -\obindex{class instance} -\obindex{instance} -\indexii{class object}{call} - -\end{description} - -\item[Modules] -Modules are imported by the \verb@import@ statement (see section -\ref{import}). A module object is a container for a module's name -space, which is a dictionary (the same dictionary as referenced by the -\verb@func_globals@ attribute of functions defined in the module). -Module attribute references are translated to lookups in this -dictionary. A module object does not contain the code object used to -initialize the module (since it isn't needed once the initialization -is done). -\stindex{import} -\obindex{module} - -Attribute assignment update the module's name space dictionary. - -Special read-only attributes: \verb@__dict__@ yields the module's name -space as a dictionary object; \verb@__name__@ yields the module's name -as a string object. -\ttindex{__dict__} -\ttindex{__name__} -\indexii{module}{name space} - -\item[Classes] -Class objects are created by class definitions (see section -\ref{class}). A class is a container for a dictionary containing the -class's name space. Class attribute references are translated to -lookups in this dictionary. When an attribute name is not found -there, the attribute search continues in the base classes. The search -is depth-first, left-to-right in the order of their occurrence in the -base class list. -\obindex{class} -\obindex{class instance} -\obindex{instance} -\indexii{class object}{call} -\index{container} -\obindex{dictionary} -\indexii{class}{attribute} - -Class attribute assignments update the class's dictionary, never the -dictionary of a base class. -\indexiii{class}{attribute}{assignment} - -A class can be called as a function to yield a class instance (see -above). -\indexii{class object}{call} - -Special read-only attributes: \verb@__dict__@ yields the dictionary -containing the class's name space; \verb@__bases__@ yields a tuple -(possibly empty or a singleton) containing the base classes, in the -order of their occurrence in the base class list. -\ttindex{__dict__} -\ttindex{__bases__} - -\item[Class instances] -A class instance is created by calling a class object as a -function. A class instance has a dictionary in which -attribute references are searched. When an attribute is not found -there, and the instance's class has an attribute by that name, and -that class attribute is a user-defined function (and in no other -cases), the instance attribute reference yields a user-defined method -object (see above) constructed from the instance and the function. -\obindex{class instance} -\obindex{instance} -\indexii{class}{instance} -\indexii{class instance}{attribute} - -Attribute assignments update the instance's dictionary. -\indexiii{class instance}{attribute}{assignment} - -Class instances can pretend to be numbers, sequences, or mappings if -they have methods with certain special names. These are described in -section \ref{specialnames}. -\obindex{number} -\obindex{sequence} -\obindex{mapping} - -Special read-only attributes: \verb@__dict__@ yields the attribute -dictionary; \verb@__class__@ yields the instance's class. -\ttindex{__dict__} -\ttindex{__class__} - -\item[Files] -A file object represents an open file. (It is a wrapper around a C -{\tt stdio} file pointer.) File objects are created by the -\verb@open()@ built-in function, and also by \verb@posix.popen()@ and -the \verb@makefile@ method of socket objects. \verb@sys.stdin@, -\verb@sys.stdout@ and \verb@sys.stderr@ are file objects corresponding -to the interpreter's standard input, output and error streams. -See the Python Library Reference for methods of file objects and other -details. -\obindex{file} -\index{C} -\index{stdio} -\bifuncindex{open} -\bifuncindex{popen} -\bifuncindex{makefile} -\ttindex{stdin} -\ttindex{stdout} -\ttindex{stderr} -\ttindex{sys.stdin} -\ttindex{sys.stdout} -\ttindex{sys.stderr} - -\item[Internal types] -A few types used internally by the interpreter are exposed to the user. -Their definition may change with future versions of the interpreter, -but they are mentioned here for completeness. -\index{internal type} - -\begin{description} - -\item[Code objects] -Code objects represent ``pseudo-compiled'' executable Python code. -The difference between a code -object and a function object is that the function object contains an -explicit reference to the function's context (the module in which it -was defined) while a code object contains no context. -\obindex{code} - -Special read-only attributes: \verb@co_code@ is a string representing -the sequence of instructions; \verb@co_consts@ is a list of literals -used by the code; \verb@co_names@ is a list of names (strings) used by -the code; \verb@co_filename@ is the filename from which the code was -compiled. (To find out the line numbers, you would have to decode the -instructions; the standard library module \verb@dis@ contains an -example of how to do this.) -\ttindex{co_code} -\ttindex{co_consts} -\ttindex{co_names} -\ttindex{co_filename} - -\item[Frame objects] -Frame objects represent execution frames. They may occur in traceback -objects (see below). -\obindex{frame} - -Special read-only attributes: \verb@f_back@ is to the previous -stack frame (towards the caller), or \verb@None@ if this is the bottom -stack frame; \verb@f_code@ is the code object being executed in this -frame; \verb@f_globals@ is the dictionary used to look up global -variables; \verb@f_locals@ is used for local variables; -\verb@f_lineno@ gives the line number and \verb@f_lasti@ gives the -precise instruction (this is an index into the instruction string of -the code object). -\ttindex{f_back} -\ttindex{f_code} -\ttindex{f_globals} -\ttindex{f_locals} -\ttindex{f_lineno} -\ttindex{f_lasti} - -\item[Traceback objects] \label{traceback} -Traceback objects represent a stack trace of an exception. A -traceback object is created when an exception occurs. When the search -for an exception handler unwinds the execution stack, at each unwound -level a traceback object is inserted in front of the current -traceback. When an exception handler is entered -(see also section \ref{try}), the stack trace is -made available to the program as \verb@sys.exc_traceback@. When the -program contains no suitable handler, the stack trace is written -(nicely formatted) to the standard error stream; if the interpreter is -interactive, it is also made available to the user as -\verb@sys.last_traceback@. -\obindex{traceback} -\indexii{stack}{trace} -\indexii{exception}{handler} -\indexii{execution}{stack} -\ttindex{exc_traceback} -\ttindex{last_traceback} -\ttindex{sys.exc_traceback} -\ttindex{sys.last_traceback} - -Special read-only attributes: \verb@tb_next@ is the next level in the -stack trace (towards the frame where the exception occurred), or -\verb@None@ if there is no next level; \verb@tb_frame@ points to the -execution frame of the current level; \verb@tb_lineno@ gives the line -number where the exception occurred; \verb@tb_lasti@ indicates the -precise instruction. The line number and last instruction in the -traceback may differ from the line number of its frame object if the -exception occurred in a \verb@try@ statement with no matching -\verb@except@ clause or with a \verb@finally@ clause. -\ttindex{tb_next} -\ttindex{tb_frame} -\ttindex{tb_lineno} -\ttindex{tb_lasti} -\stindex{try} - -\end{description} % Internal types - -\end{description} % Types - - -\section{Special method names} \label{specialnames} - -A class can implement certain operations that are invoked by special -syntax (such as subscription or arithmetic operations) by defining -methods with special names. For instance, if a class defines a -method named \verb@__getitem__@, and \verb@x@ is an instance of this -class, then \verb@x[i]@ is equivalent to \verb@x.__getitem__(i)@. -(The reverse is not true --- if \verb@x@ is a list object, -\verb@x.__getitem__(i)@ is not equivalent to \verb@x[i]@.) -\ttindex{__getitem__} - -Except for \verb@__repr__@, \verb@__str__@ and \verb@__cmp__@, -attempts to execute an -operation raise an exception when no appropriate method is defined. -For \verb@__repr__@, the default is to return a string describing the -object's class and address. -For \verb@__cmp__@, the default is to compare instances based on their -address. -For \verb@__str__@, the default is to use \verb@__repr__@. -\ttindex{__repr__} -\ttindex{__str__} -\ttindex{__cmp__} - - -\subsection{Special methods for any type} - -\begin{description} - -\item[{\tt __init__(self, args...)}] -Called when the instance is created. The arguments are those passed -to the class constructor expression. If a base class has an -\code{__init__} method the derived class's \code{__init__} method must -explicitly call it to ensure proper initialization of the base class -part of the instance. -\ttindex{__init__} -\indexii{class}{constructor} - - -\item[{\tt __del__(self)}] -Called when the instance is about to be destroyed. If a base class -has an \code{__del__} method the derived class's \code{__del__} method -must explicitly call it to ensure proper deletion of the base class -part of the instance. Note that it is possible for the \code{__del__} -method to postpone destruction of the instance by creating a new -reference to it. It may then be called at a later time when this new -reference is deleted. It is not guaranteed that -\code{__del__} methods are called for objects that still exist when -the interpreter exits. -\ttindex{__del__} -\stindex{del} - -Note that \code{del x} doesn't directly call \code{x.__del__} --- the -former decrements the reference count for \code{x} by one, but -\code{x.__del__} is only called when its reference count reaches zero. - -\item[{\tt __repr__(self)}] -Called by the \verb@repr()@ built-in function and by string conversions -(reverse or backward quotes) to compute the string representation of an object. -\ttindex{__repr__} -\bifuncindex{repr} -\indexii{string}{conversion} -\indexii{reverse}{quotes} -\indexii{backward}{quotes} -\index{back-quotes} - -\item[{\tt __str__(self)}] -Called by the \verb@str()@ built-in function and by the \verb@print@ -statement compute the string representation of an object. -\ttindex{__str__} -\bifuncindex{str} -\stindex{print} - -\item[{\tt __cmp__(self, other)}] -Called by all comparison operations. Should return -1 if -\verb@self < other@, 0 if \verb@self == other@, +1 if -\verb@self > other@. If no \code{__cmp__} operation is defined, class -instances are compared by object identity (``address''). -(Implementation note: due to limitations in the interpreter, -exceptions raised by comparisons are ignored, and the objects will be -considered equal in this case.) -\ttindex{__cmp__} -\bifuncindex{cmp} -\index{comparisons} - -\item[{\tt __hash__(self)}] -Called for the key object for dictionary operations, -and by the built-in function -\code{hash()}. Should return a 32-bit integer usable as a hash value -for dictionary operations. The only required property is that objects -which compare equal have the same hash value; it is advised to somehow -mix together (e.g. using exclusive or) the hash values for the -components of the object that also play a part in comparison of -objects. If a class does not define a \code{__cmp__} method it should -not define a \code{__hash__} operation either; if it defines -\code{__cmp__} but not \code{__hash__} its instances will not be -usable as dictionary keys. If a class defines mutable objects and -implements a \code{__cmp__} method it should not implement -\code{__hash__}, since the dictionary implementation assumes that a -key's hash value is a constant. -\obindex{dictionary} -\ttindex{__cmp__} -\ttindex{__hash__} -\bifuncindex{hash} - -\item[{\tt __call__(self, *args)}] -Called when the instance is ``called'' as a function. -\ttindex{__call__} -\indexii{call}{instance} - -\end{description} - - -\subsection{Special methods for attribute access} - -The following methods can be used to change the meaning of attribute -access for class instances. - -\begin{description} - -\item[{\tt __getattr__(self, name)}] -Called when an attribute lookup has not found the attribute in the -usual places (i.e. it is not an instance attribute nor is it found in -the class tree for \code{self}). \code{name} is the attribute name. -\ttindex{__getattr__} - -Note that if the attribute is found through the normal mechanism, -\code{__getattr__} is not called. (This is an asymmetry between -\code{__getattr__} and \code{__setattr__}.) -This is done both for efficiency reasons and because otherwise -\code{__getattr__} would have no way to access other attributes of the -instance. -Note that at least for instance variables, \code{__getattr__} can fake -total control by simply not inserting any values in the instance -attribute dictionary. -\ttindex{__setattr__} - -\item[{\tt __setattr__(self, name, value)}] -Called when an attribute assignment is attempted. This is called -instead of the normal mechanism (i.e. store the value as an instance -attribute). \code{name} is the attribute name, \code{value} is the -value to be assigned to it. -\ttindex{__setattr__} - -If \code{__setattr__} wants to assign to an instance attribute, it -should not simply execute \code{self.\var{name} = value} --- this would -cause a recursive call. Instead, it should insert the value in the -dictionary of instance attributes, e.g. \code{self.__dict__[name] = -value}. -\ttindex{__dict__} - -\item[{\tt __delattr__(self, name)}] -Like \code{__setattr__} but for attribute deletion instead of -assignment. -\ttindex{__delattr__} - -\end{description} - - -\subsection{Special methods for sequence and mapping types} - -\begin{description} - -\item[{\tt __len__(self)}] -Called to implement the built-in function \verb@len()@. Should return -the length of the object, an integer \verb@>=@ 0. Also, an object -whose \verb@__len__()@ method returns 0 is considered to be false in a -Boolean context. -\ttindex{__len__} - -\item[{\tt __getitem__(self, key)}] -Called to implement evaluation of \verb@self[key]@. Note that the -special interpretation of negative keys (if the class wishes to -emulate a sequence type) is up to the \verb@__getitem__@ method. -\ttindex{__getitem__} - -\item[{\tt __setitem__(self, key, value)}] -Called to implement assignment to \verb@self[key]@. Same note as for -\verb@__getitem__@. -\ttindex{__setitem__} - -\item[{\tt __delitem__(self, key)}] -Called to implement deletion of \verb@self[key]@. Same note as for -\verb@__getitem__@. -\ttindex{__delitem__} - -\end{description} - - -\subsection{Special methods for sequence types} - -\begin{description} - -\item[{\tt __getslice__(self, i, j)}] -Called to implement evaluation of \verb@self[i:j]@. Note that missing -\verb@i@ or \verb@j@ are replaced by 0 or \verb@len(self)@, -respectively, and \verb@len(self)@ has been added (once) to originally -negative \verb@i@ or \verb@j@ by the time this function is called -(unlike for \verb@__getitem__@). -\ttindex{__getslice__} - -\item[{\tt __setslice__(self, i, j, sequence)}] -Called to implement assignment to \verb@self[i:j]@. Same notes as for -\verb@__getslice__@. -\ttindex{__setslice__} - -\item[{\tt __delslice__(self, i, j)}] -Called to implement deletion of \verb@self[i:j]@. Same notes as for -\verb@__getslice__@. -\ttindex{__delslice__} - -\end{description} - - -\subsection{Special methods for numeric types} - -\begin{description} - -\item[{\tt __add__(self, other)}]\itemjoin -\item[{\tt __sub__(self, other)}]\itemjoin -\item[{\tt __mul__(self, other)}]\itemjoin -\item[{\tt __div__(self, other)}]\itemjoin -\item[{\tt __mod__(self, other)}]\itemjoin -\item[{\tt __divmod__(self, other)}]\itemjoin -\item[{\tt __pow__(self, other)}]\itemjoin -\item[{\tt __lshift__(self, other)}]\itemjoin -\item[{\tt __rshift__(self, other)}]\itemjoin -\item[{\tt __and__(self, other)}]\itemjoin -\item[{\tt __xor__(self, other)}]\itemjoin -\item[{\tt __or__(self, other)}]\itembreak -Called to implement the binary arithmetic operations (\verb@+@, -\verb@-@, \verb@*@, \verb@/@, \verb@%@, \verb@divmod()@, \verb@pow()@, -\verb@<<@, \verb@>>@, \verb@&@, \verb@^@, \verb@|@). -\ttindex{__or__} -\ttindex{__xor__} -\ttindex{__and__} -\ttindex{__rshift__} -\ttindex{__lshift__} -\ttindex{__pow__} -\ttindex{__divmod__} -\ttindex{__mod__} -\ttindex{__div__} -\ttindex{__mul__} -\ttindex{__sub__} -\ttindex{__add__} - -\item[{\tt __neg__(self)}]\itemjoin -\item[{\tt __pos__(self)}]\itemjoin -\item[{\tt __abs__(self)}]\itemjoin -\item[{\tt __invert__(self)}]\itembreak -Called to implement the unary arithmetic operations (\verb@-@, \verb@+@, -\verb@abs()@ and \verb@~@). -\ttindex{__invert__} -\ttindex{__abs__} -\ttindex{__pos__} -\ttindex{__neg__} - -\item[{\tt __nonzero__(self)}] -Called to implement boolean testing; should return 0 or 1. An -alternative name for this method is \verb@__len__@. -\ttindex{__nonzero__} - -\item[{\tt __coerce__(self, other)}] -Called to implement ``mixed-mode'' numeric arithmetic. Should either -return a tuple containing self and other converted to a common numeric -type, or None if no way of conversion is known. When the common type -would be the type of other, it is sufficient to return None, since the -interpreter will also ask the other object to attempt a coercion (but -sometimes, if the implementation of the other type cannot be changed, -it is useful to do the conversion to the other type here). -\ttindex{__coerce__} - -Note that this method is not called to coerce the arguments to \verb@+@ -and \verb@*@, because these are also used to implement sequence -concatenation and repetition, respectively. Also note that, for the -same reason, in \verb@n*x@, where \verb@n@ is a built-in number and -\verb@x@ is an instance, a call to \verb@x.__mul__(n)@ is made.% -\footnote{The interpreter should really distinguish between -user-defined classes implementing sequences, mappings or numbers, but -currently it doesn't --- hence this strange exception.} -\ttindex{__mul__} - -\item[{\tt __int__(self)}]\itemjoin -\item[{\tt __long__(self)}]\itemjoin -\item[{\tt __float__(self)}]\itembreak -Called to implement the built-in functions \verb@int()@, \verb@long()@ -and \verb@float()@. Should return a value of the appropriate type. -\ttindex{__float__} -\ttindex{__long__} -\ttindex{__int__} - -\item[{\tt __oct__(self)}]\itemjoin -\item[{\tt __hex__(self)}]\itembreak -Called to implement the built-in functions \verb@oct()@ and -\verb@hex()@. Should return a string value. -\ttindex{__hex__} -\ttindex{__oct__} - -\end{description} diff --git a/Doc/ref4.tex b/Doc/ref4.tex deleted file mode 100644 index 429302a907..0000000000 --- a/Doc/ref4.tex +++ /dev/null @@ -1,176 +0,0 @@ -\chapter{Execution model} -\index{execution model} - -\section{Code blocks, execution frames, and name spaces} \label{execframes} -\index{code block} -\indexii{execution}{frame} -\index{name space} - -A {\em code block} is a piece of Python program text that can be -executed as a unit, such as a module, a class definition or a function -body. Some code blocks (like modules) are executed only once, others -(like function bodies) may be executed many times. Code blocks may -textually contain other code blocks. Code blocks may invoke other -code blocks (that may or may not be textually contained in them) as -part of their execution, e.g. by invoking (calling) a function. -\index{code block} -\indexii{code}{block} - -The following are code blocks: A module is a code block. A function -body is a code block. A class definition is a code block. Each -command typed interactively is a separate code block; a script file is -a code block. The string argument passed to the built-in function -\verb@eval@ and to the \verb@exec@ statement are code blocks. -And finally, the -expression read and evaluated by the built-in function \verb@input@ is -a code block. - -A code block is executed in an execution frame. An {\em execution -frame} contains some administrative information (used for debugging), -determines where and how execution continues after the code block's -execution has completed, and (perhaps most importantly) defines two -name spaces, the local and the global name space, that affect -execution of the code block. -\indexii{execution}{frame} - -A {\em name space} is a mapping from names (identifiers) to objects. -A particular name space may be referenced by more than one execution -frame, and from other places as well. Adding a name to a name space -is called {\em binding} a name (to an object); changing the mapping of -a name is called {\em rebinding}; removing a name is {\em unbinding}. -Name spaces are functionally equivalent to dictionaries. -\index{name space} -\indexii{binding}{name} -\indexii{rebinding}{name} -\indexii{unbinding}{name} - -The {\em local name space} of an execution frame determines the default -place where names are defined and searched. The {\em global name -space} determines the place where names listed in \verb@global@ -statements are defined and searched, and where names that are not -explicitly bound in the current code block are searched. -\indexii{local}{name space} -\indexii{global}{name space} -\stindex{global} - -Whether a name is local or global in a code block is determined by -static inspection of the source text for the code block: in the -absence of \verb@global@ statements, a name that is bound anywhere in -the code block is local in the entire code block; all other names are -considered global. The \verb@global@ statement forces global -interpretation of selected names throughout the code block. The -following constructs bind names: formal parameters, \verb@import@ -statements, class and function definitions (these bind the class or -function name), and targets that are identifiers if occurring in an -assignment, \verb@for@ loop header, or \verb@except@ clause header. - -A target occurring in a \verb@del@ statement is also considered bound -for this purpose (though the actual semantics are to ``unbind'' the -name). - -When a global name is not found in the global name space, it is -searched in the list of ``built-in'' names (which is actually the -global name space of the module \verb@__builtin__@). When a name is not -found at all, the \verb@NameError@ exception is raised.% -\footnote{If the code block contains {\tt exec} statements or the -construct {\tt from \ldots import *}, the semantics of names not -explicitly mentioned in a {\tt global} statement change subtly: name -lookup first searches the local name space, then the global one, then -the built-in one.} -\bimodindex{__builtin__} -\stindex{from} -\stindex{exec} -\stindex{global} -\ttindex{NameError} - -The following table lists the meaning of the local and global name -space for various types of code blocks. The name space for a -particular module is automatically created when the module is first -referenced. Note that in almost all cases, the global name space is -the name space of the containing module --- scopes in Python do not -nest! - -\begin{center} -\begin{tabular}{|l|l|l|l|} -\hline -Code block type & Global name space & Local name space & Notes \\ -\hline -Module & n.s. for this module & same as global & \\ -Script & n.s. for \verb@__main__@ & same as global & \\ -Interactive command & n.s. for \verb@__main__@ & same as global & \\ -Class definition & global n.s. of containing block & new n.s. & \\ -Function body & global n.s. of containing block & new n.s. & \\ -String passed to \verb@exec@ statement - & global n.s. of cobtaining block - & local n.s. of containing block & (1) \\ -String passed to \verb@eval()@ - & global n.s. of caller & local n.s. of caller & (1) \\ -File read by \verb@execfile()@ - & global n.s. of caller & local n.s. of caller & (1) \\ -Expression read by \verb@input@ - & global n.s. of caller & local n.s. of caller & \\ -\hline -\end{tabular} -\end{center} -\bimodindex{__main__} - -Notes: - -\begin{description} - -\item[n.s.] means {\em name space} - -\item[(1)] The global and local name space for these can be -overridden with optional extra arguments. - -\end{description} - -The built-in functions \verb@globals()@ and \verb@locals()@ returns a -dictionary representing the current global and local name space, -respectively. The effect of modifications to this dictionary on the -name space are undefined.% -\footnote{The current implementations return the dictionary actually -used to implement the name space, {\em except} for functions, where -the optimizer may cause the local name space to be implemented -differently, and \verb@locals()@ returns a read-only dictionary.} - -\section{Exceptions} - -Exceptions are a means of breaking out of the normal flow of control -of a code block in order to handle errors or other exceptional -conditions. An exception is {\em raised} at the point where the error -is detected; it may be {\em handled} by the surrounding code block or -by any code block that directly or indirectly invoked the code block -where the error occurred. -\index{exception} -\index{raise an exception} -\index{handle an exception} -\index{exception handler} -\index{errors} -\index{error handling} - -The Python interpreter raises an exception when it detects an run-time -error (such as division by zero). A Python program can also -explicitly raise an exception with the \verb@raise@ statement. -Exception handlers are specified with the \verb@try...except@ -statement. - -Python uses the ``termination'' model of error handling: an exception -handler can find out what happened and continue execution at an outer -level, but it cannot repair the cause of the error and retry the -failing operation (except by re-entering the the offending piece of -code from the top). - -When an exception is not handled at all, the interpreter terminates -execution of the program, or returns to its interactive main loop. - -Exceptions are identified by string objects. Two different string -objects with the same value identify different exceptions. - -When an exception is raised, an object (maybe \verb@None@) is passed -as the exception's ``parameter''; this object does not affect the -selection of an exception handler, but is passed to the selected -exception handler as additional information. - -See also the description of the \verb@try@ and \verb@raise@ -statements. diff --git a/Doc/ref5.tex b/Doc/ref5.tex deleted file mode 100644 index 62cd9a7e52..0000000000 --- a/Doc/ref5.tex +++ /dev/null @@ -1,759 +0,0 @@ -\chapter{Expressions and conditions} -\index{expression} -\index{condition} - -{\bf Note:} In this and the following chapters, extended BNF notation -will be used to describe syntax, not lexical analysis. -\index{BNF} - -This chapter explains the meaning of the elements of expressions and -conditions. Conditions are a superset of expressions, and a condition -may be used wherever an expression is required by enclosing it in -parentheses. The only places where expressions are used in the syntax -instead of conditions is in expression statements and on the -right-hand side of assignment statements; this catches some nasty bugs -like accidentally writing \verb@x == 1@ instead of \verb@x = 1@. -\indexii{assignment}{statement} - -The comma plays several roles in Python's syntax. It is usually an -operator with a lower precedence than all others, but occasionally -serves other purposes as well; e.g. it separates function arguments, -is used in list and dictionary constructors, and has special semantics -in \verb@print@ statements. -\index{comma} - -When (one alternative of) a syntax rule has the form - -\begin{verbatim} -name: othername -\end{verbatim} - -and no semantics are given, the semantics of this form of \verb@name@ -are the same as for \verb@othername@. -\index{syntax} - -\section{Arithmetic conversions} -\indexii{arithmetic}{conversion} - -When a description of an arithmetic operator below uses the phrase -``the numeric arguments are converted to a common type'', -this both means that if either argument is not a number, a -\verb@TypeError@ exception is raised, and that otherwise -the following conversions are applied: -\exindex{TypeError} -\indexii{floating point}{number} -\indexii{long}{integer} -\indexii{plain}{integer} - -\begin{itemize} -\item first, if either argument is a floating point number, - the other is converted to floating point; -\item else, if either argument is a long integer, - the other is converted to long integer; -\item otherwise, both must be plain integers and no conversion - is necessary. -\end{itemize} - -\section{Atoms} -\index{atom} - -Atoms are the most basic elements of expressions. Forms enclosed in -reverse quotes or in parentheses, brackets or braces are also -categorized syntactically as atoms. The syntax for atoms is: - -\begin{verbatim} -atom: identifier | literal | enclosure -enclosure: parenth_form|list_display|dict_display|string_conversion -\end{verbatim} - -\subsection{Identifiers (Names)} -\index{name} -\index{identifier} - -An identifier occurring as an atom is a reference to a local, global -or built-in name binding. If a name is assigned to anywhere in a code -block (even in unreachable code), and is not mentioned in a -\verb@global@ statement in that code block, then it refers to a local -name throughout that code block. When it is not assigned to anywhere -in the block, or when it is assigned to but also explicitly listed in -a \verb@global@ statement, it refers to a global name if one exists, -else to a built-in name (and this binding may dynamically change). -\indexii{name}{binding} -\index{code block} -\stindex{global} -\indexii{built-in}{name} -\indexii{global}{name} - -When the name is bound to an object, evaluation of the atom yields -that object. When a name is not bound, an attempt to evaluate it -raises a \verb@NameError@ exception. -\exindex{NameError} - -\subsection{Literals} -\index{literal} - -Python knows string and numeric literals: - -\begin{verbatim} -literal: stringliteral | integer | longinteger | floatnumber -\end{verbatim} - -Evaluation of a literal yields an object of the given type (string, -integer, long integer, floating point number) with the given value. -The value may be approximated in the case of floating point literals. -See section \ref{literals} for details. - -All literals correspond to immutable data types, and hence the -object's identity is less important than its value. Multiple -evaluations of literals with the same value (either the same -occurrence in the program text or a different occurrence) may obtain -the same object or a different object with the same value. -\indexiii{immutable}{data}{type} - -(In the original implementation, all literals in the same code block -with the same type and value yield the same object.) - -\subsection{Parenthesized forms} -\index{parenthesized form} - -A parenthesized form is an optional condition list enclosed in -parentheses: - -\begin{verbatim} -parenth_form: "(" [condition_list] ")" -\end{verbatim} - -A parenthesized condition list yields whatever that condition list -yields. - -An empty pair of parentheses yields an empty tuple object. Since -tuples are immutable, the rules for literals apply here. -\indexii{empty}{tuple} - -(Note that tuples are not formed by the parentheses, but rather by use -of the comma operator. The exception is the empty tuple, for which -parentheses {\em are} required --- allowing unparenthesized ``nothing'' -in expressions would cause ambiguities and allow common typos to -pass uncaught.) -\index{comma} -\indexii{tuple}{display} - -\subsection{List displays} -\indexii{list}{display} - -A list display is a possibly empty series of conditions enclosed in -square brackets: - -\begin{verbatim} -list_display: "[" [condition_list] "]" -\end{verbatim} - -A list display yields a new list object. -\obindex{list} - -If it has no condition list, the list object has no items. Otherwise, -the elements of the condition list are evaluated from left to right -and inserted in the list object in that order. -\indexii{empty}{list} - -\subsection{Dictionary displays} \label{dict} -\indexii{dictionary}{display} - -A dictionary display is a possibly empty series of key/datum pairs -enclosed in curly braces: -\index{key} -\index{datum} -\index{key/datum pair} - -\begin{verbatim} -dict_display: "{" [key_datum_list] "}" -key_datum_list: key_datum ("," key_datum)* [","] -key_datum: condition ":" condition -\end{verbatim} - -A dictionary display yields a new dictionary object. -\obindex{dictionary} - -The key/datum pairs are evaluated from left to right to define the -entries of the dictionary: each key object is used as a key into the -dictionary to store the corresponding datum. - -Restrictions on the types of the key values are listed earlier in -section \ref{types}. -Clashes between duplicate keys are not detected; the last -datum (textually rightmost in the display) stored for a given key -value prevails. -\exindex{TypeError} - -\subsection{String conversions} -\indexii{string}{conversion} -\indexii{reverse}{quotes} -\indexii{backward}{quotes} -\index{back-quotes} - -A string conversion is a condition list enclosed in reverse (or -backward) quotes: - -\begin{verbatim} -string_conversion: "`" condition_list "`" -\end{verbatim} - -A string conversion evaluates the contained condition list and -converts the resulting object into a string according to rules -specific to its type. - -If the object is a string, a number, \verb@None@, or a tuple, list or -dictionary containing only objects whose type is one of these, the -resulting string is a valid Python expression which can be passed to -the built-in function \verb@eval()@ to yield an expression with the -same value (or an approximation, if floating point numbers are -involved). - -(In particular, converting a string adds quotes around it and converts -``funny'' characters to escape sequences that are safe to print.) - -It is illegal to attempt to convert recursive objects (e.g. lists or -dictionaries that contain a reference to themselves, directly or -indirectly.) -\obindex{recursive} - -The built-in function \verb@repr()@ performs exactly the same -conversion in its argument as enclosing it it reverse quotes does. -The built-in function \verb@str()@ performs a similar but more -user-friendly conversion. -\bifuncindex{repr} -\bifuncindex{str} - -\section{Primaries} \label{primaries} -\index{primary} - -Primaries represent the most tightly bound operations of the language. -Their syntax is: - -\begin{verbatim} -primary: atom | attributeref | subscription | slicing | call -\end{verbatim} - -\subsection{Attribute references} -\indexii{attribute}{reference} - -An attribute reference is a primary followed by a period and a name: - -\begin{verbatim} -attributeref: primary "." identifier -\end{verbatim} - -The primary must evaluate to an object of a type that supports -attribute references, e.g. a module or a list. This object is then -asked to produce the attribute whose name is the identifier. If this -attribute is not available, the exception \verb@AttributeError@ is -raised. Otherwise, the type and value of the object produced is -determined by the object. Multiple evaluations of the same attribute -reference may yield different objects. -\obindex{module} -\obindex{list} - -\subsection{Subscriptions} -\index{subscription} - -A subscription selects an item of a sequence (string, tuple or list) -or mapping (dictionary) object: -\obindex{sequence} -\obindex{mapping} -\obindex{string} -\obindex{tuple} -\obindex{list} -\obindex{dictionary} -\indexii{sequence}{item} - -\begin{verbatim} -subscription: primary "[" condition "]" -\end{verbatim} - -The primary must evaluate to an object of a sequence or mapping type. - -If it is a mapping, the condition must evaluate to an object whose -value is one of the keys of the mapping, and the subscription selects -the value in the mapping that corresponds to that key. - -If it is a sequence, the condition must evaluate to a plain integer. -If this value is negative, the length of the sequence is added to it -(so that, e.g. \verb@x[-1]@ selects the last item of \verb@x@.) -The resulting value must be a nonnegative integer smaller than the -number of items in the sequence, and the subscription selects the item -whose index is that value (counting from zero). - -A string's items are characters. A character is not a separate data -type but a string of exactly one character. -\index{character} -\indexii{string}{item} - -\subsection{Slicings} -\index{slicing} -\index{slice} - -A slicing (or slice) selects a range of items in a sequence (string, -tuple or list) object: -\obindex{sequence} -\obindex{string} -\obindex{tuple} -\obindex{list} - -\begin{verbatim} -slicing: primary "[" [condition] ":" [condition] "]" -\end{verbatim} - -The primary must evaluate to a sequence object. The lower and upper -bound expressions, if present, must evaluate to plain integers; -defaults are zero and the sequence's length, respectively. If either -bound is negative, the sequence's length is added to it. The slicing -now selects all items with index \var{k} such that -\code{\var{i} <= \var{k} < \var{j}} where \var{i} -and \var{j} are the specified lower and upper bounds. This may be an -empty sequence. It is not an error if \var{i} or \var{j} lie outside the -range of valid indexes (such items don't exist so they aren't -selected). - -\subsection{Calls} \label{calls} -\index{call} - -A call calls a callable object (e.g. a function) with a possibly empty -series of arguments:\footnote{The new syntax for keyword arguments is -not yet documented in this manual. See chapter 12 of the Tutorial.} -\obindex{callable} - -\begin{verbatim} -call: primary "(" [condition_list] ")" -\end{verbatim} - -The primary must evaluate to a callable object (user-defined -functions, built-in functions, methods of built-in objects, class -objects, and methods of class instances are callable). If it is a -class, the argument list must be empty; otherwise, the arguments are -evaluated. - -A call always returns some value, possibly \verb@None@, unless it -raises an exception. How this value is computed depends on the type -of the callable object. If it is: - -\begin{description} - -\item[a user-defined function:] the code block for the function is -executed, passing it the argument list. The first thing the code -block will do is bind the formal parameters to the arguments; this is -described in section \ref{function}. When the code block executes a -\verb@return@ statement, this specifies the return value of the -function call. -\indexii{function}{call} -\indexiii{user-defined}{function}{call} -\obindex{user-defined function} -\obindex{function} - -\item[a built-in function or method:] the result is up to the -interpreter; see the library reference manual for the descriptions of -built-in functions and methods. -\indexii{function}{call} -\indexii{built-in function}{call} -\indexii{method}{call} -\indexii{built-in method}{call} -\obindex{built-in method} -\obindex{built-in function} -\obindex{method} -\obindex{function} - -\item[a class object:] a new instance of that class is returned. -\obindex{class} -\indexii{class object}{call} - -\item[a class instance method:] the corresponding user-defined -function is called, with an argument list that is one longer than the -argument list of the call: the instance becomes the first argument. -\obindex{class instance} -\obindex{instance} -\indexii{instance}{call} -\indexii{class instance}{call} - -\end{description} - -\section{Unary arithmetic operations} -\indexiii{unary}{arithmetic}{operation} -\indexiii{unary}{bit-wise}{operation} - -All unary arithmetic (and bit-wise) operations have the same priority: - -\begin{verbatim} -u_expr: primary | "-" u_expr | "+" u_expr | "~" u_expr -\end{verbatim} - -The unary \verb@"-"@ (minus) operator yields the negation of its -numeric argument. -\index{negation} -\index{minus} - -The unary \verb@"+"@ (plus) operator yields its numeric argument -unchanged. -\index{plus} - -The unary \verb@"~"@ (invert) operator yields the bit-wise inversion -of its plain or long integer argument. The bit-wise inversion of -\verb@x@ is defined as \verb@-(x+1)@. -\index{inversion} - -In all three cases, if the argument does not have the proper type, -a \verb@TypeError@ exception is raised. -\exindex{TypeError} - -\section{Binary arithmetic operations} -\indexiii{binary}{arithmetic}{operation} - -The binary arithmetic operations have the conventional priority -levels. Note that some of these operations also apply to certain -non-numeric types. There is no ``power'' operator, so there are only -two levels, one for multiplicative operators and one for additive -operators: - -\begin{verbatim} -m_expr: u_expr | m_expr "*" u_expr - | m_expr "/" u_expr | m_expr "%" u_expr -a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr -\end{verbatim} - -The \verb@"*"@ (multiplication) operator yields the product of its -arguments. The arguments must either both be numbers, or one argument -must be a plain integer and the other must be a sequence. In the -former case, the numbers are converted to a common type and then -multiplied together. In the latter case, sequence repetition is -performed; a negative repetition factor yields an empty sequence. -\index{multiplication} - -The \verb@"/"@ (division) operator yields the quotient of its -arguments. The numeric arguments are first converted to a common -type. Plain or long integer division yields an integer of the same -type; the result is that of mathematical division with the `floor' -function applied to the result. Division by zero raises the -\verb@ZeroDivisionError@ exception. -\exindex{ZeroDivisionError} -\index{division} - -The \verb@"%"@ (modulo) operator yields the remainder from the -division of the first argument by the second. The numeric arguments -are first converted to a common type. A zero right argument raises -the \verb@ZeroDivisionError@ exception. The arguments may be floating -point numbers, e.g. \verb@3.14 % 0.7@ equals \verb@0.34@. The modulo -operator always yields a result with the same sign as its second -operand (or zero); the absolute value of the result is strictly -smaller than the second operand. -\index{modulo} - -The integer division and modulo operators are connected by the -following identity: \verb@x == (x/y)*y + (x%y)@. Integer division and -modulo are also connected with the built-in function \verb@divmod()@: -\verb@divmod(x, y) == (x/y, x%y)@. These identities don't hold for -floating point numbers; there a similar identity holds where -\verb@x/y@ is replaced by \verb@floor(x/y)@). - -The \verb@"+"@ (addition) operator yields the sum of its arguments. -The arguments must either both be numbers, or both sequences of the -same type. In the former case, the numbers are converted to a common -type and then added together. In the latter case, the sequences are -concatenated. -\index{addition} - -The \verb@"-"@ (subtraction) operator yields the difference of its -arguments. The numeric arguments are first converted to a common -type. -\index{subtraction} - -\section{Shifting operations} -\indexii{shifting}{operation} - -The shifting operations have lower priority than the arithmetic -operations: - -\begin{verbatim} -shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr -\end{verbatim} - -These operators accept plain or long integers as arguments. The -arguments are converted to a common type. They shift the first -argument to the left or right by the number of bits given by the -second argument. - -A right shift by \var{n} bits is defined as division by -\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as -multiplication with \code{pow(2,\var{n})}; for plain integers there is -no overflow check so this drops bits and flips the sign if the result -is not less than \code{pow(2,31)} in absolute value. - -Negative shift counts raise a \verb@ValueError@ exception. -\exindex{ValueError} - -\section{Binary bit-wise operations} -\indexiii{binary}{bit-wise}{operation} - -Each of the three bitwise operations has a different priority level: - -\begin{verbatim} -and_expr: shift_expr | and_expr "&" shift_expr -xor_expr: and_expr | xor_expr "^" and_expr -or_expr: xor_expr | or_expr "|" xor_expr -\end{verbatim} - -The \verb@"&"@ operator yields the bitwise AND of its arguments, which -must be plain or long integers. The arguments are converted to a -common type. -\indexii{bit-wise}{and} - -The \verb@"^"@ operator yields the bitwise XOR (exclusive OR) of its -arguments, which must be plain or long integers. The arguments are -converted to a common type. -\indexii{bit-wise}{xor} -\indexii{exclusive}{or} - -The \verb@"|"@ operator yields the bitwise (inclusive) OR of its -arguments, which must be plain or long integers. The arguments are -converted to a common type. -\indexii{bit-wise}{or} -\indexii{inclusive}{or} - -\section{Comparisons} -\index{comparison} - -Contrary to C, all comparison operations in Python have the same -priority, which is lower than that of any arithmetic, shifting or -bitwise operation. Also contrary to C, expressions like -\verb@a < b < c@ have the interpretation that is conventional in -mathematics: -\index{C} - -\begin{verbatim} -comparison: or_expr (comp_operator or_expr)* -comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in" -\end{verbatim} - -Comparisons yield integer values: 1 for true, 0 for false. - -Comparisons can be chained arbitrarily, e.g. \code{x < y <= z} is -equivalent to \code{x < y and y <= z}, except that \code{y} is -evaluated only once (but in both cases \code{z} is not evaluated at all -when \code{x < y} is found to be false). -\indexii{chaining}{comparisons} - -Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are -expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison -operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent -to \var{a opa b} \code{and} \var{b opb c} \code{and} \ldots \code{and} -\var{y opy z}, except that each expression is evaluated at most once. - -Note that \var{a opa b opb c} doesn't imply any kind of comparison -between \var{a} and \var{c}, so that e.g.\ \code{x < y > z} is -perfectly legal (though perhaps not pretty). - -The forms \verb@<>@ and \verb@!=@ are equivalent; for consistency with -C, \verb@!=@ is preferred; where \verb@!=@ is mentioned below -\verb@<>@ is also implied. - -The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare -the values of two objects. The objects needn't have the same type. -If both are numbers, they are coverted to a common type. Otherwise, -objects of different types {\em always} compare unequal, and are -ordered consistently but arbitrarily. - -(This unusual definition of comparison is done to simplify the -definition of operations like sorting and the \verb@in@ and -\verb@not@ \verb@in@ operators.) - -Comparison of objects of the same type depends on the type: - -\begin{itemize} - -\item -Numbers are compared arithmetically. - -\item -Strings are compared lexicographically using the numeric equivalents -(the result of the built-in function \verb@ord@) of their characters. - -\item -Tuples and lists are compared lexicographically using comparison of -corresponding items. - -\item -Mappings (dictionaries) are compared through lexicographic -comparison of their sorted (key, value) lists.% -\footnote{This is expensive since it requires sorting the keys first, -but about the only sensible definition. An earlier version of Python -compared dictionaries by identity only, but this caused surprises -because people expected to be able to test a dictionary for emptiness -by comparing it to {\tt \{\}}.} - -\item -Most other types compare unequal unless they are the same object; -the choice whether one object is considered smaller or larger than -another one is made arbitrarily but consistently within one -execution of a program. - -\end{itemize} - -The operators \verb@in@ and \verb@not in@ test for sequence -membership: if \var{y} is a sequence, \code{\var{x} in \var{y}} is -true if and only if there exists an index \var{i} such that -\code{\var{x} = \var{y}[\var{i}]}. -\code{\var{x} not in \var{y}} yields the inverse truth value. The -exception \verb@TypeError@ is raised when \var{y} is not a sequence, -or when \var{y} is a string and \var{x} is not a string of length one.% -\footnote{The latter restriction is sometimes a nuisance.} -\opindex{in} -\opindex{not in} -\indexii{membership}{test} -\obindex{sequence} - -The operators \verb@is@ and \verb@is not@ test for object identity: -\var{x} \code{is} \var{y} is true if and only if \var{x} and \var{y} -are the same object. \var{x} \code{is not} \var{y} yields the inverse -truth value. -\opindex{is} -\opindex{is not} -\indexii{identity}{test} - -\section{Boolean operations} \label{Booleans} -\indexii{Boolean}{operation} - -Boolean operations have the lowest priority of all Python operations: - -\begin{verbatim} -condition: or_test | lambda_form -or_test: and_test | or_test "or" and_test -and_test: not_test | and_test "and" not_test -not_test: comparison | "not" not_test -lambda_form: "lambda" [parameter_list]: condition -\end{verbatim} - -In the context of Boolean operations, and also when conditions are -used by control flow statements, the following values are interpreted -as false: \verb@None@, numeric zero of all types, empty sequences -(strings, tuples and lists), and empty mappings (dictionaries). All -other values are interpreted as true. - -The operator \verb@not@ yields 1 if its argument is false, 0 otherwise. -\opindex{not} - -The condition \var{x} \verb@and@ \var{y} first evaluates \var{x}; if -\var{x} is false, its value is returned; otherwise, \var{y} is -evaluated and the resulting value is returned. -\opindex{and} - -The condition \var{x} \verb@or@ \var{y} first evaluates \var{x}; if -\var{x} is true, its value is returned; otherwise, \var{y} is -evaluated and the resulting value is returned. -\opindex{or} - -(Note that \verb@and@ and \verb@or@ do not restrict the value and type -they return to 0 and 1, but rather return the last evaluated argument. -This is sometimes useful, e.g. if \verb@s@ is a string that should be -replaced by a default value if it is empty, the expression -\verb@s or 'foo'@ yields the desired value. Because \verb@not@ has to -invent a value anyway, it does not bother to return a value of the -same type as its argument, so e.g. \verb@not 'foo'@ yields \verb@0@, -not \verb@''@.) - -Lambda forms (lambda expressions) have the same syntactic position as -conditions. They are a shorthand to create anonymous functions; the -expression {\em {\tt lambda} arguments{\tt :} condition} -yields a function object that behaves virtually identical to one -defined with -{\em {\tt def} name {\tt (}arguments{\tt ): return} condition}. -See section \ref{function} for the syntax of -parameter lists. Note that functions created with lambda forms cannot -contain statements. -\label{lambda} -\indexii{lambda}{expression} -\indexii{lambda}{form} -\indexii{anonmymous}{function} - -\section{Expression lists and condition lists} -\indexii{expression}{list} -\indexii{condition}{list} - -\begin{verbatim} -expr_list: or_expr ("," or_expr)* [","] -cond_list: condition ("," condition)* [","] -\end{verbatim} - -The only difference between expression lists and condition lists is -the lowest priority of operators that can be used in them without -being enclosed in parentheses; condition lists allow all operators, -while expression lists don't allow comparisons and Boolean operators -(they do allow bitwise and shift operators though). - -Expression lists are used in expression statements and assignments; -condition lists are used everywhere else where a list of -comma-separated values is required. - -An expression (condition) list containing at least one comma yields a -tuple. The length of the tuple is the number of expressions -(conditions) in the list. The expressions (conditions) are evaluated -from left to right. (Condition lists are used syntactically is a few -places where no tuple is constructed but a list of values is needed -nevertheless.) -\obindex{tuple} - -The trailing comma is required only to create a single tuple (a.k.a. a -{\em singleton}); it is optional in all other cases. A single -expression (condition) without a trailing comma doesn't create a -tuple, but rather yields the value of that expression (condition). -\indexii{trailing}{comma} - -(To create an empty tuple, use an empty pair of parentheses: -\verb@()@.) - -\section{Summary} - -The following table summarizes the operator precedences in Python, -from lowest precedence (least binding) to highest precedence (most -binding). Operators in the same box have the same precedence. Unless -the syntax is explicitly given, operators are binary. Operators in -the same box group left to right (except for comparisons, which -chain from left to right --- see above). - -\begin{center} -\begin{tabular}{|c|c|} -\hline -\code{or} & Boolean OR \\ -\hline -\code{and} & Boolean AND \\ -\hline -\code{not} \var{x} & Boolean NOT \\ -\hline -\code{in}, \code{not} \code{in} & Membership tests \\ -\code{is}, \code{is} \code{not} & Identity tests \\ -\code{<}, \code{<=}, \code{>}, \code{>=}, \code{<>}, \code{!=}, \code{=} & - Comparisons \\ -\hline -\code{|} & Bitwise OR \\ -\hline -\code{\^} & Bitwise XOR \\ -\hline -\code{\&} & Bitwise AND \\ -\hline -\code{<<}, \code{>>} & Shifts \\ -\hline -\code{+}, \code{-} & Addition and subtraction \\ -\hline -\code{*}, \code{/}, \code{\%} & Multiplication, division, remainder \\ -\hline -\code{+\var{x}}, \code{-\var{x}} & Positive, negative \\ -\code{\~\var{x}} & Bitwise not \\ -\hline -\code{\var{x}.\var{attribute}} & Attribute reference \\ -\code{\var{x}[\var{index}]} & Subscription \\ -\code{\var{x}[\var{index}:\var{index}]} & Slicing \\ -\code{\var{f}(\var{arguments}...)} & Function call \\ -\hline -\code{(\var{expressions}\ldots)} & Binding or tuple display \\ -\code{[\var{expressions}\ldots]} & List display \\ -\code{\{\var{key}:\var{datum}\ldots\}} & Dictionary display \\ -\code{`\var{expression}\ldots`} & String conversion \\ -\hline -\end{tabular} -\end{center} diff --git a/Doc/ref6.tex b/Doc/ref6.tex deleted file mode 100644 index 22575c2039..0000000000 --- a/Doc/ref6.tex +++ /dev/null @@ -1,536 +0,0 @@ -\chapter{Simple statements} -\indexii{simple}{statement} - -Simple statements are comprised within a single logical line. -Several simple statements may occur on a single line separated -by semicolons. The syntax for simple statements is: - -\begin{verbatim} -simple_stmt: expression_stmt - | assignment_stmt - | pass_stmt - | del_stmt - | print_stmt - | return_stmt - | raise_stmt - | break_stmt - | continue_stmt - | import_stmt - | global_stmt - | access_stmt - | exec_stmt -\end{verbatim} - -\section{Expression statements} -\indexii{expression}{statement} - -Expression statements are used (mostly interactively) to compute and -write a value, or (usually) to call a procedure (a function that -returns no meaningful result; in Python, procedures return the value -\verb@None@): - -\begin{verbatim} -expression_stmt: condition_list -\end{verbatim} - -An expression statement evaluates the condition list (which may be a -single condition). -\indexii{expression}{list} - -In interactive mode, if the value is not \verb@None@, it is converted -to a string using the rules for string conversions (expressions in -reverse quotes), and the resulting string is written to standard -output (see section \ref{print}) on a line by itself. -(The exception for \verb@None@ is made so that procedure calls, which -are syntactically equivalent to expressions, do not cause any output.) -\ttindex{None} -\indexii{string}{conversion} -\index{output} -\indexii{standard}{output} -\indexii{writing}{values} -\indexii{procedure}{call} - -\section{Assignment statements} -\indexii{assignment}{statement} - -Assignment statements are used to (re)bind names to values and to -modify attributes or items of mutable objects: -\indexii{binding}{name} -\indexii{rebinding}{name} -\obindex{mutable} -\indexii{attribute}{assignment} - -\begin{verbatim} -assignment_stmt: (target_list "=")+ expression_list -target_list: target ("," target)* [","] -target: identifier | "(" target_list ")" | "[" target_list "]" - | attributeref | subscription | slicing -\end{verbatim} - -(See section \ref{primaries} for the syntax definitions for the last -three symbols.) - -An assignment statement evaluates the expression list (remember that -this can be a single expression or a comma-separated list, the latter -yielding a tuple) and assigns the single resulting object to each of -the target lists, from left to right. -\indexii{expression}{list} - -Assignment is defined recursively depending on the form of the target -(list). When a target is part of a mutable object (an attribute -reference, subscription or slicing), the mutable object must -ultimately perform the assignment and decide about its validity, and -may raise an exception if the assignment is unacceptable. The rules -observed by various types and the exceptions raised are given with the -definition of the object types (see section \ref{types}). -\index{target} -\indexii{target}{list} - -Assignment of an object to a target list is recursively defined as -follows. -\indexiii{target}{list}{assignment} - -\begin{itemize} -\item -If the target list is a single target: the object is assigned to that -target. - -\item -If the target list is a comma-separated list of targets: the object -must be a tuple with the same number of items as the list contains -targets, and the items are assigned, from left to right, to the -corresponding targets. - -\end{itemize} - -Assignment of an object to a single target is recursively defined as -follows. - -\begin{itemize} % nested - -\item -If the target is an identifier (name): - -\begin{itemize} - -\item -If the name does not occur in a \verb@global@ statement in the current -code block: the name is bound to the object in the current local name -space. -\stindex{global} - -\item -Otherwise: the name is bound to the object in the current global name -space. - -\end{itemize} % nested - -The name is rebound if it was already bound. - -\item -If the target is a target list enclosed in parentheses: the object is -assigned to that target list as described above. - -\item -If the target is a target list enclosed in square brackets: the object -must be a list with the same number of items as the target list -contains targets, and its items are assigned, from left to right, to -the corresponding targets. - -\item -If the target is an attribute reference: The primary expression in the -reference is evaluated. It should yield an object with assignable -attributes; if this is not the case, \verb@TypeError@ is raised. That -object is then asked to assign the assigned object to the given -attribute; if it cannot perform the assignment, it raises an exception -(usually but not necessarily \verb@AttributeError@). -\indexii{attribute}{assignment} - -\item -If the target is a subscription: The primary expression in the -reference is evaluated. It should yield either a mutable sequence -(list) object or a mapping (dictionary) object. Next, the subscript -expression is evaluated. -\indexii{subscription}{assignment} -\obindex{mutable} - -If the primary is a mutable sequence object (a list), the subscript -must yield a plain integer. If it is negative, the sequence's length -is added to it. The resulting value must be a nonnegative integer -less than the sequence's length, and the sequence is asked to assign -the assigned object to its item with that index. If the index is out -of range, \verb@IndexError@ is raised (assignment to a subscripted -sequence cannot add new items to a list). -\obindex{sequence} -\obindex{list} - -If the primary is a mapping (dictionary) object, the subscript must -have a type compatible with the mapping's key type, and the mapping is -then asked to create a key/datum pair which maps the subscript to -the assigned object. This can either replace an existing key/value -pair with the same key value, or insert a new key/value pair (if no -key with the same value existed). -\obindex{mapping} -\obindex{dictionary} - -\item -If the target is a slicing: The primary expression in the reference is -evaluated. It should yield a mutable sequence object (e.g. a list). The -assigned object should be a sequence object of the same type. Next, -the lower and upper bound expressions are evaluated, insofar they are -present; defaults are zero and the sequence's length. The bounds -should evaluate to (small) integers. If either bound is negative, the -sequence's length is added to it. The resulting bounds are clipped to -lie between zero and the sequence's length, inclusive. Finally, the -sequence object is asked to replace the slice with the items of the -assigned sequence. The length of the slice may be different from the -length of the assigned sequence, thus changing the length of the -target sequence, if the object allows it. -\indexii{slicing}{assignment} - -\end{itemize} - -(In the current implementation, the syntax for targets is taken -to be the same as for expressions, and invalid syntax is rejected -during the code generation phase, causing less detailed error -messages.) - -WARNING: Although the definition of assignment implies that overlaps -between the left-hand side and the right-hand side are `safe' (e.g. -\verb@a, b = b, a@ swaps two variables), overlaps within the -collection of assigned-to variables are not safe! For instance, the -following program prints \code@[0, 2]@: - -\begin{verbatim} -x = [0, 1] -i = 0 -i, x[i] = 1, 2 -print x -\end{verbatim} - - -\section{The {\tt pass} statement} -\stindex{pass} - -\begin{verbatim} -pass_stmt: "pass" -\end{verbatim} - -\verb@pass@ is a null operation --- when it is executed, nothing -happens. It is useful as a placeholder when a statement is -required syntactically, but no code needs to be executed, for example: -\indexii{null}{operation} - -\begin{verbatim} -def f(arg): pass # a function that does nothing (yet) - -class C: pass # a class with no methods (yet) -\end{verbatim} - -\section{The {\tt del} statement} -\stindex{del} - -\begin{verbatim} -del_stmt: "del" target_list -\end{verbatim} - -Deletion is recursively defined very similar to the way assignment is -defined. Rather that spelling it out in full details, here are some -hints. -\indexii{deletion}{target} -\indexiii{deletion}{target}{list} - -Deletion of a target list recursively deletes each target, from left -to right. - -Deletion of a name removes the binding of that name (which must exist) -from the local or global name space, depending on whether the name -occurs in a \verb@global@ statement in the same code block. -\stindex{global} -\indexii{unbinding}{name} - -Deletion of attribute references, subscriptions and slicings -is passed to the primary object involved; deletion of a slicing -is in general equivalent to assignment of an empty slice of the -right type (but even this is determined by the sliced object). -\indexii{attribute}{deletion} - -\section{The {\tt print} statement} \label{print} -\stindex{print} - -\begin{verbatim} -print_stmt: "print" [ condition ("," condition)* [","] ] -\end{verbatim} - -\verb@print@ evaluates each condition in turn and writes the resulting -object to standard output (see below). If an object is not a string, -it is first converted to a string using the rules for string -conversions. The (resulting or original) string is then written. A -space is written before each object is (converted and) written, unless -the output system believes it is positioned at the beginning of a -line. This is the case: (1) when no characters have yet been written -to standard output; or (2) when the last character written to standard -output is \verb/\n/; or (3) when the last write operation on standard -output was not a \verb@print@ statement. (In some cases it may be -functional to write an empty string to standard output for this -reason.) -\index{output} -\indexii{writing}{values} - -A \verb/"\n"/ character is written at the end, unless the \verb@print@ -statement ends with a comma. This is the only action if the statement -contains just the keyword \verb@print@. -\indexii{trailing}{comma} -\indexii{newline}{suppression} - -Standard output is defined as the file object named \verb@stdout@ -in the built-in module \verb@sys@. If no such object exists, -or if it is not a writable file, a \verb@RuntimeError@ exception is raised. -(The original implementation attempts to write to the system's original -standard output instead, but this is not safe, and should be fixed.) -\indexii{standard}{output} -\bimodindex{sys} -\ttindex{stdout} -\exindex{RuntimeError} - -\section{The {\tt return} statement} -\stindex{return} - -\begin{verbatim} -return_stmt: "return" [condition_list] -\end{verbatim} - -\verb@return@ may only occur syntactically nested in a function -definition, not within a nested class definition. -\indexii{function}{definition} -\indexii{class}{definition} - -If a condition list is present, it is evaluated, else \verb@None@ -is substituted. - -\verb@return@ leaves the current function call with the condition -list (or \verb@None@) as return value. - -When \verb@return@ passes control out of a \verb@try@ statement -with a \verb@finally@ clause, that finally clause is executed -before really leaving the function. -\kwindex{finally} - -\section{The {\tt raise} statement} -\stindex{raise} - -\begin{verbatim} -raise_stmt: "raise" condition ["," condition ["," condition]] -\end{verbatim} - -\verb@raise@ evaluates its first condition, which must yield -a string, class, or instance object. If there is a second condition, -this is evaluated, else \verb@None@ is substituted. If the first -condition is a class object, then the second condition must be an -instance of that class or one of its derivatives. If the first -condition is an instance object, the second condition must be -\verb@None@. -\index{exception} -\indexii{raising}{exception} - -If the first object is a class or string, it then raises the exception -identified by the first object, with the second one (or \verb@None@) -as its parameter. If the first object is an instance, it raises the -exception identified by the class of the object, with the instance as -its parameter (and there should be no second object, or the second -object should be \verb@None@). - -If a third object is present, and it it not \verb@None@, it should be -a traceback object (see section \ref{traceback}), and it is -substituted instead of the current location as the place where the -exception occurred. This is useful to re-raise an exception -transparently in an except clause. -\obindex{traceback} - -\section{The {\tt break} statement} -\stindex{break} - -\begin{verbatim} -break_stmt: "break" -\end{verbatim} - -\verb@break@ may only occur syntactically nested in a \verb@for@ -or \verb@while@ loop, but not nested in a function or class definition -within that loop. -\stindex{for} -\stindex{while} -\indexii{loop}{statement} - -It terminates the nearest enclosing loop, skipping the optional -\verb@else@ clause if the loop has one. -\kwindex{else} - -If a \verb@for@ loop is terminated by \verb@break@, the loop control -target keeps its current value. -\indexii{loop control}{target} - -When \verb@break@ passes control out of a \verb@try@ statement -with a \verb@finally@ clause, that finally clause is executed -before really leaving the loop. -\kwindex{finally} - -\section{The {\tt continue} statement} -\stindex{continue} - -\begin{verbatim} -continue_stmt: "continue" -\end{verbatim} - -\verb@continue@ may only occur syntactically nested in a \verb@for@ or -\verb@while@ loop, but not nested in a function or class definition or -\verb@try@ statement within that loop.\footnote{Except that it may -currently occur within an {\tt except} clause.} -\stindex{for} -\stindex{while} -\indexii{loop}{statement} -\kwindex{finally} - -It continues with the next cycle of the nearest enclosing loop. - -\section{The {\tt import} statement} \label{import} -\stindex{import} - -\begin{verbatim} -import_stmt: "import" identifier ("," identifier)* - | "from" identifier "import" identifier ("," identifier)* - | "from" identifier "import" "*" -\end{verbatim} - -Import statements are executed in two steps: (1) find a module, and -initialize it if necessary; (2) define a name or names in the local -name space (of the scope where the \verb@import@ statement occurs). -The first form (without \verb@from@) repeats these steps for each -identifier in the list, the \verb@from@ form performs them once, with -the first identifier specifying the module name. -\indexii{importing}{module} -\indexii{name}{binding} -\kwindex{from} - -The system maintains a table of modules that have been initialized, -indexed by module name. (The current implementation makes this table -accessible as \verb@sys.modules@.) When a module name is found in -this table, step (1) is finished. If not, a search for a module -definition is started. This first looks for a built-in module -definition, and if no built-in module if the given name is found, it -searches a user-specified list of directories for a file whose name is -the module name with extension \verb@".py"@. (The current -implementation uses the list of strings \verb@sys.path@ as the search -path; it is initialized from the shell environment variable -\verb@$PYTHONPATH@, with an installation-dependent default.) -\ttindex{modules} -\ttindex{sys.modules} -\indexii{module}{name} -\indexii{built-in}{module} -\indexii{user-defined}{module} -\bimodindex{sys} -\ttindex{path} -\ttindex{sys.path} -\indexii{filename}{extension} - -If a built-in module is found, its built-in initialization code is -executed and step (1) is finished. If no matching file is found, -\verb@ImportError@ is raised. If a file is found, it is parsed, -yielding an executable code block. If a syntax error occurs, -\verb@SyntaxError@ is raised. Otherwise, an empty module of the given -name is created and inserted in the module table, and then the code -block is executed in the context of this module. Exceptions during -this execution terminate step (1). -\indexii{module}{initialization} -\exindex{SyntaxError} -\exindex{ImportError} -\index{code block} - -When step (1) finishes without raising an exception, step (2) can -begin. - -The first form of \verb@import@ statement binds the module name in the -local name space to the module object, and then goes on to import the -next identifier, if any. The \verb@from@ from does not bind the -module name: it goes through the list of identifiers, looks each one -of them up in the module found in step (1), and binds the name in the -local name space to the object thus found. If a name is not found, -\verb@ImportError@ is raised. If the list of identifiers is replaced -by a star (\verb@*@), all names defined in the module are bound, -except those beginning with an underscore(\verb@_@). -\indexii{name}{binding} -\exindex{ImportError} - -Names bound by import statements may not occur in \verb@global@ -statements in the same scope. -\stindex{global} - -The \verb@from@ form with \verb@*@ may only occur in a module scope. -\kwindex{from} -\ttindex{from ... import *} - -(The current implementation does not enforce the latter two -restrictions, but programs should not abuse this freedom, as future -implementations may enforce them or silently change the meaning of the -program.) - -\section{The {\tt global} statement} \label{global} -\stindex{global} - -\begin{verbatim} -global_stmt: "global" identifier ("," identifier)* -\end{verbatim} - -The \verb@global@ statement is a declaration which holds for the -entire current scope. It means that the listed identifiers are to be -interpreted as globals. While {\em using} global names is automatic -if they are not defined in the local scope, {\em assigning} to global -names would be impossible without \verb@global@. -\indexiii{global}{name}{binding} - -Names listed in a \verb@global@ statement must not be used in the same -scope before that \verb@global@ statement is executed. - -Names listed in a \verb@global@ statement must not be defined as formal -parameters or in a \verb@for@ loop control target, \verb@class@ -definition, function definition, or \verb@import@ statement. - -(The current implementation does not enforce the latter two -restrictions, but programs should not abuse this freedom, as future -implementations may enforce them or silently change the meaning of the -program.) - -\section{The {\tt access} statement} \label{access} -\stindex{access} - -\begin{verbatim} -access_stmt: "access" ... -\end{verbatim} - -This statement is obsolete. It no longer generates any code; in the -future, \verb@access@ will no longer be a reserved word. - -\section{The {\tt exec} statement} \label{exec} -\stindex{exec} - -\begin{verbatim} -exec_stmt: "exec" expression ["in" expression ["," expression]] -\end{verbatim} - -This statement supports dynamic execution of Python code. The first -expression should evaluate to either a string, an open file object, or -a code object. If it is a string, the string is parsed as a suite of -Python statements which is then executed (unless a syntax error -occurs). If it is an open file, the file is parsed until EOF and -executed. If it is a code object, it is simply executed. - -In all cases, if the optional parts are omitted, the code is executed -in the current scope. If only the first expression after \verb@in@ is -specified, it should be a dictionary, which will be used for both the -global and the local variables. If two expressions are given, both -must be dictionaries and they are used for the global and local -variables, respectively. - -Hints: dynamic evaluation of expressions is supported by the built-in -function \verb@eval()@. The built-in functions \verb@globals()@ and -\verb@locals()@ return the current global and local dictionary, -respectively, which may be useful to pass around for use by \verb@exec@. diff --git a/Doc/ref7.tex b/Doc/ref7.tex deleted file mode 100644 index 89fa6ed1f7..0000000000 --- a/Doc/ref7.tex +++ /dev/null @@ -1,389 +0,0 @@ -\chapter{Compound statements} -\indexii{compound}{statement} - -Compound statements contain (groups of) other statements; they affect -or control the execution of those other statements in some way. In -general, compound statements span multiple lines, although in simple -incarnations a whole compound statement may be contained in one line. - -The \verb@if@, \verb@while@ and \verb@for@ statements implement -traditional control flow constructs. \verb@try@ specifies exception -handlers and/or cleanup code for a group of statements. Function and -class definitions are also syntactically compound statements. - -Compound statements consist of one or more `clauses'. A clause -consists of a header and a `suite'. The clause headers of a -particular compound statement are all at the same indentation level. -Each clause header begins with a uniquely identifying keyword and ends -with a colon. A suite is a group of statements controlled by a -clause. A suite can be one or more semicolon-separated simple -statements on the same line as the header, following the header's -colon, or it can be one or more indented statements on subsequent -lines. Only the latter form of suite can contain nested compound -statements; the following is illegal, mostly because it wouldn't be -clear to which \verb@if@ clause a following \verb@else@ clause would -belong: -\index{clause} -\index{suite} - -\begin{verbatim} -if test1: if test2: print x -\end{verbatim} - -Also note that the semicolon binds tighter than the colon in this -context, so that in the following example, either all or none of the -\verb@print@ statements are executed: - -\begin{verbatim} -if x < y < z: print x; print y; print z -\end{verbatim} - -Summarizing: - -\begin{verbatim} -compound_stmt: if_stmt | while_stmt | for_stmt - | try_stmt | funcdef | classdef -suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT -statement: stmt_list NEWLINE | compound_stmt -stmt_list: simple_stmt (";" simple_stmt)* [";"] -\end{verbatim} - -Note that statements always end in a \verb@NEWLINE@ possibly followed -by a \verb@DEDENT@. -\index{NEWLINE token} -\index{DEDENT token} - -Also note that optional continuation clauses always begin with a -keyword that cannot start a statement, thus there are no ambiguities -(the `dangling \verb@else@' problem is solved in Python by requiring -nested \verb@if@ statements to be indented). -\indexii{dangling}{else} - -The formatting of the grammar rules in the following sections places -each clause on a separate line for clarity. - -\section{The {\tt if} statement} -\stindex{if} - -The \verb@if@ statement is used for conditional execution: - -\begin{verbatim} -if_stmt: "if" condition ":" suite - ("elif" condition ":" suite)* - ["else" ":" suite] -\end{verbatim} - -It selects exactly one of the suites by evaluating the conditions one -by one until one is found to be true (see section \ref{Booleans} for -the definition of true and false); then that suite is executed (and no -other part of the \verb@if@ statement is executed or evaluated). If -all conditions are false, the suite of the \verb@else@ clause, if -present, is executed. -\kwindex{elif} -\kwindex{else} - -\section{The {\tt while} statement} -\stindex{while} -\indexii{loop}{statement} - -The \verb@while@ statement is used for repeated execution as long as a -condition is true: - -\begin{verbatim} -while_stmt: "while" condition ":" suite - ["else" ":" suite] -\end{verbatim} - -This repeatedly tests the condition and, if it is true, executes the -first suite; if the condition is false (which may be the first time it -is tested) the suite of the \verb@else@ clause, if present, is -executed and the loop terminates. -\kwindex{else} - -A \verb@break@ statement executed in the first suite terminates the -loop without executing the \verb@else@ clause's suite. A -\verb@continue@ statement executed in the first suite skips the rest -of the suite and goes back to testing the condition. -\stindex{break} -\stindex{continue} - -\section{The {\tt for} statement} -\stindex{for} -\indexii{loop}{statement} - -The \verb@for@ statement is used to iterate over the elements of a -sequence (string, tuple or list): -\obindex{sequence} - -\begin{verbatim} -for_stmt: "for" target_list "in" condition_list ":" suite - ["else" ":" suite] -\end{verbatim} - -The condition list is evaluated once; it should yield a sequence. The -suite is then executed once for each item in the sequence, in the -order of ascending indices. Each item in turn is assigned to the -target list using the standard rules for assignments, and then the -suite is executed. When the items are exhausted (which is immediately -when the sequence is empty), the suite in the \verb@else@ clause, if -present, is executed, and the loop terminates. -\kwindex{in} -\kwindex{else} -\indexii{target}{list} - -A \verb@break@ statement executed in the first suite terminates the -loop without executing the \verb@else@ clause's suite. A -\verb@continue@ statement executed in the first suite skips the rest -of the suite and continues with the next item, or with the \verb@else@ -clause if there was no next item. -\stindex{break} -\stindex{continue} - -The suite may assign to the variable(s) in the target list; this does -not affect the next item assigned to it. - -The target list is not deleted when the loop is finished, but if the -sequence is empty, it will not have been assigned to at all by the -loop. - -Hint: the built-in function \verb@range()@ returns a sequence of -integers suitable to emulate the effect of Pascal's -\verb@for i := a to b do@; -e.g. \verb@range(3)@ returns the list \verb@[0, 1, 2]@. -\bifuncindex{range} -\index{Pascal} - -{\bf Warning:} There is a subtlety when the sequence is being modified -by the loop (this can only occur for mutable sequences, i.e. lists). -An internal counter is used to keep track of which item is used next, -and this is incremented on each iteration. When this counter has -reached the length of the sequence the loop terminates. This means that -if the suite deletes the current (or a previous) item from the -sequence, the next item will be skipped (since it gets the index of -the current item which has already been treated). Likewise, if the -suite inserts an item in the sequence before the current item, the -current item will be treated again the next time through the loop. -This can lead to nasty bugs that can be avoided by making a temporary -copy using a slice of the whole sequence, e.g. -\index{loop!over mutable sequence} -\index{mutable sequence!loop over} - -\begin{verbatim} -for x in a[:]: - if x < 0: a.remove(x) -\end{verbatim} - -\section{The {\tt try} statement} \label{try} -\stindex{try} - -The \verb@try@ statement specifies exception handlers and/or cleanup -code for a group of statements: - -\begin{verbatim} -try_stmt: try_exc_stmt | try_fin_stmt -try_exc_stmt: "try" ":" suite - ("except" [condition ["," target]] ":" suite)+ - ["else" ":" suite] -try_fin_stmt: "try" ":" suite - "finally" ":" suite -\end{verbatim} - -There are two forms of \verb@try@ statement: \verb@try...except@ and -\verb@try...finally@. These forms cannot be mixed. - -The \verb@try...except@ form specifies one or more exception handlers -(the \verb@except@ clauses). When no exception occurs in the -\verb@try@ clause, no exception handler is executed. When an -exception occurs in the \verb@try@ suite, a search for an exception -handler is started. This inspects the except clauses in turn until -one is found that matches the exception. A condition-less except -clause, if present, must be last; it matches any exception. For an -except clause with a condition, that condition is evaluated, and the -clause matches the exception if the resulting object is ``compatible'' -with the exception. An object is compatible with an exception if it -is either the object that identifies the exception, or (for exceptions -that are classes) it is a base class of the exception, or it is a -tuple containing an item that is compatible with the exception. Note -that the object identities must match, i.e. it must be the same -object, not just an object with the same value. -\kwindex{except} - -If no except clause matches the exception, the search for an exception -handler continues in the surrounding code and on the invocation stack. - -If the evaluation of a condition in the header of an except clause -raises an exception, the original search for a handler is cancelled -and a search starts for the new exception in the surrounding code and -on the call stack (it is treated as if the entire \verb@try@ statement -raised the exception). - -When a matching except clause is found, the exception's parameter is -assigned to the target specified in that except clause, if present, -and the except clause's suite is executed. When the end of this suite -is reached, execution continues normally after the entire try -statement. (This means that if two nested handlers exist for the same -exception, and the exception occurs in the try clause of the inner -handler, the outer handler will not handle the exception.) - -Before an except clause's suite is executed, details about the -exception are assigned to three variables in the \verb@sys@ module: -\verb@sys.exc_type@ receives the object identifying the exception; -\verb@sys.exc_value@ receives the exception's parameter; -\verb@sys.exc_traceback@ receives a traceback object (see section -\ref{traceback}) identifying the point in the program where the -exception occurred. -\bimodindex{sys} -\ttindex{exc_type} -\ttindex{exc_value} -\ttindex{exc_traceback} -\obindex{traceback} - -The optional \verb@else@ clause is executed when no exception occurs -in the \verb@try@ clause. Exceptions in the \verb@else@ clause are -not handled by the preceding \verb@except@ clauses. -\kwindex{else} - -The \verb@try...finally@ form specifies a `cleanup' handler. The -\verb@try@ clause is executed. When no exception occurs, the -\verb@finally@ clause is executed. When an exception occurs in the -\verb@try@ clause, the exception is temporarily saved, the -\verb@finally@ clause is executed, and then the saved exception is -re-raised. If the \verb@finally@ clause raises another exception or -executes a \verb@return@, \verb@break@ or \verb@continue@ statement, -the saved exception is lost. -\kwindex{finally} - -When a \verb@return@ or \verb@break@ statement is executed in the -\verb@try@ suite of a \verb@try...finally@ statement, the -\verb@finally@ clause is also executed `on the way out'. A -\verb@continue@ statement is illegal in the \verb@try@ clause. (The -reason is a problem with the current implementation --- this -restriction may be lifted in the future). -\stindex{return} -\stindex{break} -\stindex{continue} - -\section{Function definitions} \label{function} -\indexii{function}{definition} - -A function definition defines a user-defined function object (see -section \ref{types}):\footnote{The new syntax to receive arbitrary -keyword arguments is not yet documented in this manual. See chapter -12 of the Tutorial.} -\obindex{user-defined function} -\obindex{function} - -\begin{verbatim} -funcdef: "def" funcname "(" [parameter_list] ")" ":" suite -parameter_list: (defparameter ",")* ("*" identifier | defparameter [","]) -defparameter: parameter ["=" condition] -sublist: parameter ("," parameter)* [","] -parameter: identifier | "(" sublist ")" -funcname: identifier -\end{verbatim} - -A function definition is an executable statement. Its execution binds -the function name in the current local name space to a function object -(a wrapper around the executable code for the function). This -function object contains a reference to the current global name space -as the global name space to be used when the function is called. -\indexii{function}{name} -\indexii{name}{binding} - -The function definition does not execute the function body; this gets -executed only when the function is called. - -When one or more top-level parameters have the form {\em parameter = -condition}, the function is said to have ``default parameter values''. -Default parameter values are evaluated when the function definition is -executed. For a parameter with a default value, the correponding -argument may be omitted from a call, in which case the parameter's -default value is substituted. If a parameter has a default value, all -following parameters must also have a default value --- this is a -syntactic restriction that is not expressed by the grammar.% -\footnote{Currently this is not checked; instead, -{\tt def f(a=1,b)} is interpreted as {\tt def f(a=1,b=None)}.} -\indexiii{default}{parameter}{value} - -Function call semantics are described in section \ref{calls}. When a -user-defined function is called, first missing arguments for which a -default value exists are supplied; then the arguments (a.k.a. actual -parameters) are bound to the (formal) parameters, as follows: -\indexii{function}{call} -\indexiii{user-defined}{function}{call} -\index{parameter} -\index{argument} -\indexii{parameter}{formal} -\indexii{parameter}{actual} - -\begin{itemize} - -\item -If there are no formal parameters, there must be no arguments. - -\item -If the formal parameter list does not end in a star followed by an -identifier, there must be exactly as many arguments as there are -parameters in the formal parameter list (at the top level); the -arguments are assigned to the formal parameters one by one. Note that -the presence or absence of a trailing comma at the top level in either -the formal or the actual parameter list makes no difference. The -assignment to a formal parameter is performed as if the parameter -occurs on the left hand side of an assignment statement whose right -hand side's value is that of the argument. - -\item -If the formal parameter list ends in a star followed by an identifier, -preceded by zero or more comma-followed parameters, there must be at -least as many arguments as there are parameters preceding the star. -Call this number {\em N}. The first {\em N} arguments are assigned to -the corresponding formal parameters in the way descibed above. A -tuple containing the remaining arguments, if any, is then assigned to -the identifier following the star. This variable will always be a -tuple: if there are no extra arguments, its value is \verb@()@, if -there is just one extra argument, it is a singleton tuple. -\indexii{variable length}{parameter list} - -\end{itemize} - -Note that the `variable length parameter list' feature only works at -the top level of the parameter list; individual parameters use a model -corresponding more closely to that of ordinary assignment. While the -latter model is generally preferable, because of the greater type -safety it offers (wrong-sized tuples aren't silently mistreated), -variable length parameter lists are a sufficiently accepted practice -in most programming languages that a compromise has been worked out. -(And anyway, assignment has no equivalent for empty argument lists.) - -It is also possible to create anonymous functions (functions not bound -to a name), for immediate use in expressions. This uses lambda forms, -described in section \ref{lambda}. -\indexii{lambda}{form} - -\section{Class definitions} \label{class} -\indexii{class}{definition} - -A class definition defines a class object (see section \ref{types}): -\obindex{class} - -\begin{verbatim} -classdef: "class" classname [inheritance] ":" suite -inheritance: "(" [condition_list] ")" -classname: identifier -\end{verbatim} - -A class definition is an executable statement. It first evaluates the -inheritance list, if present. Each item in the inheritance list -should evaluate to a class object. The class's suite is then executed -in a new execution frame (see section \ref{execframes}), using a newly -created local name space and the original global name space. -(Usually, the suite contains only function definitions.) When the -class's suite finishes execution, its execution frame is discarded but -its local name space is saved. A class object is then created using -the inheritance list for the base classes and the saved local name -space for the attribute dictionary. The class name is bound to this -class object in the original local name space. -\index{inheritance} -\indexii{class}{name} -\indexii{name}{binding} -\indexii{execution}{frame} diff --git a/Doc/ref8.tex b/Doc/ref8.tex deleted file mode 100644 index a9e688a840..0000000000 --- a/Doc/ref8.tex +++ /dev/null @@ -1,105 +0,0 @@ -\chapter{Top-level components} - -The Python interpreter can get its input from a number of sources: -from a script passed to it as standard input or as program argument, -typed in interactively, from a module source file, etc. This chapter -gives the syntax used in these cases. -\index{interpreter} - -\section{Complete Python programs} -\index{program} - -While a language specification need not prescribe how the language -interpreter is invoked, it is useful to have a notion of a complete -Python program. A complete Python program is executed in a minimally -initialized environment: all built-in and standard modules are -available, but none have been initialized, except for \verb@sys@ -(various system services), \verb@__builtin__@ (built-in functions, -exceptions and \verb@None@) and \verb@__main__@. The latter is used -to provide the local and global name space for execution of the -complete program. -\bimodindex{sys} -\bimodindex{__main__} -\bimodindex{__builtin__} - -The syntax for a complete Python program is that for file input, -described in the next section. - -The interpreter may also be invoked in interactive mode; in this case, -it does not read and execute a complete program but reads and executes -one statement (possibly compound) at a time. The initial environment -is identical to that of a complete program; each statement is executed -in the name space of \verb@__main__@. -\index{interactive mode} -\bimodindex{__main__} - -Under {\UNIX}, a complete program can be passed to the interpreter in -three forms: with the {\bf -c} {\it string} command line option, as a -file passed as the first command line argument, or as standard input. -If the file or standard input is a tty device, the interpreter enters -interactive mode; otherwise, it executes the file as a complete -program. -\index{UNIX} -\index{command line} -\index{standard input} - -\section{File input} - -All input read from non-interactive files has the same form: - -\begin{verbatim} -file_input: (NEWLINE | statement)* -\end{verbatim} - -This syntax is used in the following situations: - -\begin{itemize} - -\item when parsing a complete Python program (from a file or from a string); - -\item when parsing a module; - -\item when parsing a string passed to the \verb@exec@ statement; - -\end{itemize} - -\section{Interactive input} - -Input in interactive mode is parsed using the following grammar: - -\begin{verbatim} -interactive_input: [stmt_list] NEWLINE | compound_stmt NEWLINE -\end{verbatim} - -Note that a (top-level) compound statement must be followed by a blank -line in interactive mode; this is needed to help the parser detect the -end of the input. - -\section{Expression input} -\index{input} - -There are two forms of expression input. Both ignore leading -whitespace. - -The string argument to \verb@eval()@ must have the following form: -\bifuncindex{eval} - -\begin{verbatim} -eval_input: condition_list NEWLINE* -\end{verbatim} - -The input line read by \verb@input()@ must have the following form: -\bifuncindex{input} - -\begin{verbatim} -input_input: condition_list NEWLINE -\end{verbatim} - -Note: to read `raw' input line without interpretation, you can use the -built-in function \verb@raw_input()@ or the \verb@readline()@ method -of file objects. -\obindex{file} -\index{input!raw} -\index{raw input} -\bifuncindex{raw_index} -\ttindex{readline} diff --git a/Doc/templates/module.tex b/Doc/templates/module.tex deleted file mode 100644 index 4afb56b251..0000000000 --- a/Doc/templates/module.tex +++ /dev/null @@ -1,122 +0,0 @@ -% Template for a library manual section. -% PLEASE REMOVE THE COMMENTS AFTER USING THE TEMPLATE - - -% ==== 1. ==== -% Choose one of the following section headers and index entries; -% \section{} generates the section header, -% \bimodindex{} or \stmodundex{} generates an index entry for this module - -\section{Built-in Module \sectcode{spam}} % If implemented in C -\bimodindex{spam} - -\section{Standard module \sectcode{spam}} % If implemented in Python -\stmodindex{spam} - - -% ==== 2. ==== -% Give a short overview of what the module does. -% If it is platform specific, mention this. -% Mention other important restrictions or general operating principles. -% For example: - -The \code{spam} module defines operations for handling cans of Spam. -It knows the four generally available Spam varieties and understands -both can sizes. - -Because spamification requires UNIX process management, the module is -only available on genuine UNIX systems. - - -% ==== 3. ==== -% List the public functions defined by the module. Begin with a -% standard phrase. You may also list the exceptions and other data -% items defined in the module, insofar as they are important for the -% user. - -The \code{spam} module defines the following functions: - -% ---- 3.1. ---- -% Redefine the ``indexsubitem'' macro to point to this module -% (alternatively, you can put this at the top of the file): - -\renewcommand{\indexsubitem}{(in module spam)} - -% ---- 3.2. ---- -% For each function, use a ``funcdesc'' block. This has exactly two -% parameters (each parameters is contained in a set of curly braces): -% the first parameter is the function name (this automatically -% generates an index entry); the second parameter is the function's -% argument list. If there are no arguments, use an empty pair of -% curly braces. If there is more than one argument, separate the -% arguments with backslash-comma. Optional parts of the parameter -% list are contained in \optional{...} (this generates a set of square -% brackets around its parameter). Arguments are automatically set in -% italics in the parameter list. Each argument should be mentioned at -% least once in the description; each usage (even inside \code{...}) -% should be enclosed in \var{...}. - -\begin{funcdesc}{open}{filename\optional{\, mode\, buffersize}} -Open the file \var{filename} as a can of Spam. The optional -\var{mode} and \var{buffersize} arguments specify the read-write mode -(\code{'r'} (default) or \code{'w'}) and the buffer size (default: -system dependent). -\end{funcdesc} - -% ---- 3.3. ---- -% Data items are described using a ``datadesc'' block. This has only -% one parameter: the item's name. - -\begin{datadesc}{cansize} -The default can size, in ounces. Legal values are 7 and 12. The -default varies per supermarket. This variable should not be changed -once the \code{open()} function has been called. -\end{datadesc} - -% --- 3.4. --- -% Exceptions are described using a ``excdesc'' block. This has only -% one parameter: the exception name. - -\begin{excdesc}{error} -Exception raised when an operation fails for a Spam specific reason. -The exception argument is a string describing the reason of the -failure. -\end{excdesc} - -% ---- 3.5. ---- -% There is no standard block type for classes. I generally use -% ``funcdesc'' blocks, since class instantiation looks very much like -% a function call. - - -% ==== 4. ==== -% Now is probably a good time for a complete example. (Alternatively, -% an example giving the flavor of the module may be given before the -% detailed list of functions.) - -Example: - -\begin{verbatim} ->>> import spam ->>> can = spam.open('/etc/passwd') ->>> can.empty() ->>> can.close() -\end{verbatim} - -% ==== 5. ==== -% If your module defines new object types (for a built-in module) or -% classes (for a module written in Python), you should list the -% methods and instance variables (if any) of each type or class in a -% separate subsection. It is important to redefine ``indexsubitem'' -% for each subsection. - -\subsection{Spam Objects} - -Spam objects (returned by \code{open()} above) have the following -methods. - -\renewcommand{\indexsubitem}{(spam method)} - -\begin{funcdesc}{empty}{} -Empty the can into the trash. -\end{funcdesc} diff --git a/Doc/texi2html.py b/Doc/texi2html.py deleted file mode 100644 index a1c0ebd44a..0000000000 --- a/Doc/texi2html.py +++ /dev/null @@ -1,1500 +0,0 @@ -#! /usr/local/bin/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 fexible error handling -# How about icons ? - -import os -import regex -import regsub -import string - -MAGIC = '\\input texinfo' - -cmprog = regex.compile('^@\([a-z]+\)\([ \t]\|$\)') # Command (line-oriented) -blprog = regex.compile('^[ \t]*$') # Blank line -kwprog = regex.compile('@[a-z]+') # Keyword (embedded, usually with {} args) -spprog = regex.compile('[\n@{}&<>]') # Special characters in running text -miprog = regex.compile( \ - '^\* \([^:]*\):\(:\|[ \t]*\([^\t,\n.]+\)\([^ \t\n]*\)\)[ \t\n]*') - # menu item (Yuck!) - - -class Node: - __doc__ = """ - 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. """ - - 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 = [] - self.type = 0 - self.cont = '' - - def write (self, *lines): - for line in lines: - self.lines.append (line) - - 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): - if nodename: - if string.lower(nodename) == '(dir)': - addr = '../dir.html' - else: - addr = makefile(nodename) - self.write(label, ': <A HREF="', addr, '" TYPE="', \ - label, '">', nodename, '</A> \n') - - - def finalize(self): - length = len (self.lines) - self.text = string.joinfields (self.lines, '') - self.lines = [] - self.write ('<BR> <HR>\n') - if self.cont != self.next: - self.link('Cont', self.cont) - self.link('Next', self.next) - self.link('Prev', self.prev) - self.link('Up', self.up) - if self.name <> self.topname: - self.link('Top', self.topname) - self.write ('<BR> <HR> <P>\n') - links = string.joinfields (self.lines, '') - self.lines = [] - - self.prologue = \ - '<!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN">\n' + \ - '<!- Converted with texi2html and Python>\n' + \ - '<P>\n<HEAD>\n' + \ - '<TITLE>' + self.title + '</TITLE>\n' + \ - '</HEAD>\n<BODY>\n<P>\n' + \ - links - - if length > 20: - self.epilogue = links + '</BODY>\n' - else: - self.epilogue = '</BODY>\n' - - -class TexinfoParser: - - # 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.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.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 (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) >= 0): - line = fp.readline() - lineno = lineno + 1 - if line[:len(MAGIC)] <> MAGIC: - raise SyntaxError, 'file does not begin with '+`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 - if cmprog.match(line) >= 0: - a, b = cmprog.regs[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) - elif blprog.match(line) >= 0 and \ - 'format' not in self.stack and \ - 'example' not in self.stack: - if accu: - if not self.skip: - self.process(accu) - 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 = string.joinfields(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.skip, self.stack, - if accu: print accu[0][:30], - if accu[0][30:] or accu[1:]: print '...', - print - if self.stack and self.stack[-1] == 'menu': - # XXX should be done differently - for line in accu: - if miprog.match(line) < 0: - line = string.strip(line) + '\n' - self.expand(line) - continue - (bgn, end), (a, b), (c, d), (e, f), (g, h) = \ - miprog.regs[:5] - label = line[a:b] - nodename = line[c:d] - if nodename[0] == ':': nodename = label - else: nodename = line[e:f] - punct = line[g:h] - self.write('<DT><A HREF="', \ - makefile(nodename), \ - '" TYPE=Menu>', nodename, \ - '</A>', punct, '\n<DD>') - self.expand(line[end:]) - else: - text = string.joinfields(accu, '') - self.expand(text) - - # Write a string, expanding embedded @-commands - def expand(self, text): - stack = [] - i = 0 - n = len(text) - while i < n: - start = i - i = spprog.search(text, i) - if i < 0: - self.write(text[start:]) - break - self.write(text[start:i]) - c = text[i] - i = i+1 - if c == '\n': - if self.nofill > 0: - self.write('<P>\n') - else: - 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 '+`c` - start = i - while i < n and text[i] in string.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', `file` - return - if self.debugging: - print '--> file', `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 - if self.debugging: - print '<-- file', `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('(C)') - def open_copyright(self): self.write('(C)') - def close_copyright(self): pass - - def open_minus(self): self.write('-') - def close_minus(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 = string.splitfields(text, ',') - n = len(args) - for i in range(n): - args[i] = string.strip(args[i]) - while len(args) < 3: args.append('') - node = args[0] - file = args[2] - self.write('`', file, '\', node `', node, '\'') - - def makeref(self): - text = self.collectsavings() - args = string.splitfields(text, ',') - n = len(args) - for i in range(n): - args[i] = string.strip(args[i]) - 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>') - - # --- 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>') - - open_t = open_code - close_t = close_code - - def open_dfn(self): self.write('<DFN>') - def close_dfn(self): self.write('</DFN>') - - def open_emph(self): self.write('<I>') - def close_emph(self): self.write('</I>') - - open_i = open_emph - close_i = close_emph - - def open_footnote(self): - # if self.savetext <> None: - # print '*** Recursive footnote -- expect weirdness' - id = len(self.footnotes) + 1 - self.write('<A NAME="footnoteref', `id`, \ - '" HREF="#footnotetext', `id`, '">(', `id`, ')</A>') - # self.savetext = '' - self.startsaving () - - def close_footnote(self): - id = len(self.footnotes) + 1 - # self.footnotes.append(`id`, self.savetext) - self.footnotes.append(`id`, self.collectsavings()) - # self.savetext = None - - def writefootnotes(self): - self.write('<H2>---------- Footnotes ----------</H2>\n') - for id, text in self.footnotes: - self.write('<A NAME="footnotetext', id, \ - '" HREF="#footnoteref', id, '">(', \ - id, ')</A>\n', text, '<P>\n') - self.footnotes = [] - - def open_file(self): self.write('<FILE>') - def close_file(self): self.write('</FILE>') - - 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('<B>') - def close_strong(self): self.write('</B>') - - open_b = open_strong - close_b = close_strong - - 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>') - - open_titlefont = open_ - close_titlefont = close_ - - def open_small(self): pass - def close_small(self): pass - - def command(self, line): - a, b = cmprog.regs[1] - cmd = line[a:b] - args = string.strip(line[b:]) - if self.debugging > 1: - print 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 = string.split(args) - 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 = string.splitfields (args, ' ') - key = fields[0] - if len(fields) == 1: - value = 1 - else: - value = string.joinfields (fields[1:], ' ') - self.values[key]=value - print self.values - - 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): - print self.stack - print self.stackinfo - if self.stackinfo[len(self.stack) + 1]: - self.skip = self.skip - 1 - del self.stackinfo[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 - - end_ifclear = end_ifset - - 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): - print args - self.startsaving() - self.expand (args) - self.title = self.collectsavings () - print self.title - 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 = string.splitfields(args, ',') - while len(parts) < 4: parts.append('') - for i in range(4): parts[i] = string.strip(parts[i]) - 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 '--- 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 - # No idea what this means, but this is what latex2html writes - # self.write('<!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN">\n') - # self.write('<!- Converted with texi2html and Python>\n') - # self.write ('<P>\n<HEAD>\n') - # self.write('<TITLE>', title, '</TITLE>\n') - # self.write ('</HEAD>\n<BODY>\n<P>\n<BR> <HR>\n') - # self.link('Next', next) - # self.link('Prev', prev) - # self.link('Up', up) - # if self.nodename <> self.topname: - # self.link('Top', self.topname) - # self.write ('<BR> <HR> <P>\n') - self.node = Node (self.dirname, self.nodename, self.topname, \ - title, next, prev, up) - - def link(self, label, nodename): - if nodename: - if string.lower(nodename) == '(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 + `i` + '.' - args = x + ' ' + args - self.contents.append(level, args, self.nodename) - self.write('<', type, '>') - self.expand(args) - self.write('</', type, '>\n') - if self.debugging: - 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>\n') - for level, title, node in self.contents: - if level <= maxlevel: - self.write('<LI>', '. '*level, '<A HREF="', \ - makefile(node), '">') - self.expand(title) - self.write('</A> ', node, '\n') - self.write('</UL>\n') - - # --- 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): - # Insert <args> blank lines - if args: - try: - n = string.atoi(args) - except string.atoi_error: - n = 1 - else: - n = 1 - self.write('<P>\n'*max(n, 0)) - - 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{' + name + '}') - for word in rest: self.expand(' ' + makevar(word)) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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{' + name + '}') - # If there are too many arguments, show them - for word in rest: self.expand(' ' + word) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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{' + datatype + '} @b{' + name + '}') - for word in rest: self.expand(' ' + makevar(word)) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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{' + datatype + '} @b{' + name + '}') - # If there are too many arguments, show them - for word in rest: self.expand(' ' + word) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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{' + name + '}') - # If there are too many arguments, show them - for word in rest: self.expand(' ' + word) - self.expand(' -- ' + category + ' of ' + classname) - self.write('<DD>\n') - self.index('vr', name + ' @r{of ' + 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{' + name + '}') - for word in rest: self.expand(' ' + makevar(word)) - self.expand(' -- ' + category + ' on ' + classname) - self.write('<DD>\n') - self.index('fn', name + ' @r{on ' + 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{' + name + '}') - for word in rest: self.expand(' ' + word) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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 do_item(self, args): - if self.itemindex: self.index(self.itemindex, args) - if self.itemarg: - if self.itemarg[0] == '@' and self.itemarg[1:2] and \ - self.itemarg[1] in string.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('<DD>') - else: - self.write('<LI>') - self.expand(args) - self.write(' ') - do_itemx = do_item # XXX Should suppress leading blank line - - # --- Enumerations, displays, quotations --- - # XXX Most of these should increase the indentation somehow - - def bgn_quotation(self, args): self.write('<P>') - def end_quotation(self): self.write('<P>\n') - - def bgn_example(self, args): - self.nofill = self.nofill + 1 - self.write('<PRE><CODE>') - def end_example(self): - self.write('</CODE></PRE>') - 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 - - def bgn_display(self, args): - self.nofill = self.nofill + 1 - self.write('<PRE>\n') - def end_display(self): - self.write('</PRE>\n') - self.nofill = self.nofill - 1 - - def bgn_format(self, args): - self.nofill = self.nofill + 1 - self.write('<PRE><CODE>\n') - def end_format(self): - self.write('</CODE></PRE>\n') - self.nofill = self.nofill - 1 - - 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('<H2>Menu</H2><DL COMPACT>\n') - def end_menu(self): self.write('</DL>\n') - - 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', `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) - - def do_synindex(self, args): - words = string.split(args) - 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 = string.split(args) - for name in words: - if self.whichindex.has_key(name): - self.prindex(name) - else: - print '*** No index named', `name` - - def prindex(self, name): - iscodeindex = (name not in self.noncodeindices) - index = self.whichindex[name] - if not index: return - if self.debugging: - print '--- Generating', self.indextitle[name], 'index' - # The node already provides a title - index1 = [] - junkprog = regex.compile('^\(@[a-z]+\)?{') - for key, node in index: - sortkey = string.lower(key) - # Remove leading `@cmd{' from sort key - # -- don't bother about the matching `}' - oldsortkey = sortkey - while 1: - i = junkprog.match(sortkey) - if i < 0: break - sortkey = sortkey[i:] - index1.append(sortkey, key, node) - del index[:] - index1.sort() - self.write('<DL COMPACT>\n') - for sortkey, key, node in index1: - if self.debugging > 1: print key, ':', node - self.write('<DT>') - if iscodeindex: key = '@code{' + key + '}' - self.expand(key) - self.write('<DD><A HREF="', makefile(node), \ - '">', node, '</A>\n') - 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 string.ljust(cmd, 20), self.unknown[cmd] - - -# 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 = regex.compile('[@{} ]') -def findwordend(str, i, n): - level = 0 - while i < n: - i = fwprog.search(str, i) - if i < 0: break - 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): - return fixfunnychars(nodename) + '.html' - - -# Characters that are perfectly safe in filenames and hyperlinks -goodchars = string.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 = string.index(sequence, 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 - parser = TexinfoParser() - while sys.argv[1:2] == ['-d']: - parser.debugging = parser.debugging + 1 - del sys.argv[1:2] - if sys.argv[1] == '-c': - parser.cont = 1 - del sys.argv[1] - if len(sys.argv) <> 3: - print 'usage: texi2html [-d] [-d] [-c] inputfile outputdirectory' - sys.exit(2) - file = sys.argv[1] - parser.setdirname(sys.argv[2]) - if file == '-': - fp = sys.stdin - else: - parser.setincludedir(os.path.dirname(file)) - try: - fp = open(file, 'r') - except IOError, msg: - print file, ':', msg - sys.exit(1) - parser.parse(fp) - fp.close() - parser.report() - - -test() - -# Emacs local variables -# -# Local Variables: -# py-indent-offset: 8 -# End: diff --git a/Doc/texinputs/boilerplate.tex b/Doc/texinputs/boilerplate.tex deleted file mode 100644 index 7cc2c983e4..0000000000 --- a/Doc/texinputs/boilerplate.tex +++ /dev/null @@ -1,8 +0,0 @@ -\author{ - Guido van Rossum \\ - Dept. AA, CWI, P.O. Box 94079 \\ - 1090 GB Amsterdam, The Netherlands \\ - E-mail: {\tt guido@cwi.nl} -} - -\date{13 October 1995 \\ Release 1.3} % XXX update before release! diff --git a/Doc/texinputs/copyright.tex b/Doc/texinputs/copyright.tex deleted file mode 100644 index 4669ff462b..0000000000 --- a/Doc/texinputs/copyright.tex +++ /dev/null @@ -1,22 +0,0 @@ -Copyright \copyright{} 1991-1995 by Stichting Mathematisch Centrum, -Amsterdam, The Netherlands. - -\begin{center} -All Rights Reserved -\end{center} - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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/Doc/texipost.dat b/Doc/texipost.dat deleted file mode 100644 index 7897e44b09..0000000000 --- a/Doc/texipost.dat +++ /dev/null @@ -1,23 +0,0 @@ -@node Function Index, , , -@unnumbered Function Index - -@printindex fn - -@node Variable Index, , , -@unnumbered Variable Index - -@printindex vr - -@node Module Index, , , -@unnumbered Module Index - -@printindex pg - -@node Concept Index, , , -@unnumbered Concept Index - -@printindex cp - -@summarycontents -@contents -@bye diff --git a/Doc/texipre.dat b/Doc/texipre.dat deleted file mode 100644 index a0a9d4dae2..0000000000 --- a/Doc/texipre.dat +++ /dev/null @@ -1,86 +0,0 @@ -\input texinfo @c -*-texinfo-*- -@c %**start of header -@setfilename python-lib.info -@settitle Python library reference -@setchapternewpage odd -@footnotestyle end -@c %**end of header - -@ifinfo -This file describes the built-in types, exceptions and functions and the -standard modules that come with the Python system. It assumes basic -knowledge about the Python language. For an informal introduction to -the language, see the Python Tutorial. The Python Reference Manual -gives a more formal definition of the language. (These manuals are not -yet available in INFO or Texinfo format.) - -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. -@end ifinfo - -@titlepage -@title Python library reference -@author Guido van Rossum - -@c The following two commands start the copyright page. -@page -@vskip 0pt plus 1filll -Copyright @copyright{} 1991-1995 by Stichting Mathematisch Centrum, -Amsterdam, The Netherlands. - -@center All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. -@end titlepage - - -@node Top, Overview, (dir), (dir) -@top The Python library - -@ifinfo -This file describes the built-in types, exceptions and functions and the -standard modules that come with the Python system. It assumes basic -knowledge about the Python language. For an informal introduction to -the language, see the @cite{Python Tutorial}. The @cite{Python -Reference Manual} gives a more formal definition of the language. -(These manuals are not yet available in INFO or Texinfo format.) - -This version corresponds to Python version 1.3 (13 Oct 1995). - -@end ifinfo - -@c placeholder for the master menu -- patched by texinfo-all-menus-update -@menu -@end menu diff --git a/Doc/text2latex.py b/Doc/text2latex.py deleted file mode 100644 index 93d0587d30..0000000000 --- a/Doc/text2latex.py +++ /dev/null @@ -1,55 +0,0 @@ -import os -import sys -import regex -import regsub -import string -import getopt - -def main(): - process(sys.stdin, sys.stdout) - -dashes = regex.compile('^-+[ \t]*$') -equals = regex.compile('^=+[ \t]*$') -stars = regex.compile('^\*+[ \t]*$') -blank = regex.compile('^[ \t]*$') -indented = regex.compile('^\( *\t\| \)[ \t]*[^ \t]') - -def process(fi, fo): - inverbatim = 0 - line = '\n' - nextline = fi.readline() - while nextline: - prevline = line - line = nextline - nextline = fi.readline() - fmt = None - if dashes.match(nextline) >= 0: - fmt = '\\subsection{%s}\n' - elif equals.match(nextline) >= 0: - fmt = '\\section{%s}\n' - elif stars.match(nextline) >= 0: - fmt = '\\chapter{%s}\n' - if fmt: - nextline = '\n' - line = fmt % string.strip(line) - if '(' in line: - line = regsub.gsub('[a-zA-Z0-9_]+()', - '{\\\\tt \\0}', line) - elif inverbatim: - if blank.match(line) >= 0 and \ - indented.match(nextline) < 0: - inverbatim = 0 - fo.write('\\end{verbatim}\n') - else: - if indented.match(line) >= 0 and \ - blank.match(prevline) >= 0: - inverbatim = 1 - fo.write('\\begin{verbatim}\n') - if inverbatim: - line = string.expandtabs(line, 4) - elif not fmt and '(' in line: - line = regsub.gsub('[a-zA-Z0-9_]+()', - '\\\\code{\\0}', line) - fo.write(line) - -main() diff --git a/Doc/tools/fix.el b/Doc/tools/fix.el deleted file mode 100644 index f36d6f0dee..0000000000 --- a/Doc/tools/fix.el +++ /dev/null @@ -1,5 +0,0 @@ -; load the new texinfo package (2.xx) if not installed by default -; (setq load-path (cons "/ufs/guido/lib/emacs/texinfo-2.14" load-path)) -(find-file "@lib.texi") -(texinfo-all-menus-update t) -(texinfo-all-menus-update t) diff --git a/Doc/tools/fix_hack b/Doc/tools/fix_hack deleted file mode 100755 index 8dad11101a..0000000000 --- a/Doc/tools/fix_hack +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -sed -e 's/{\\ptt[ ]*\\char[ ]*'"'"'137}/_/g' <"$1" > "@$1" && mv "@$1" $1 diff --git a/Doc/tools/keywords.py b/Doc/tools/keywords.py deleted file mode 100644 index 52b4d6825c..0000000000 --- a/Doc/tools/keywords.py +++ /dev/null @@ -1,20 +0,0 @@ -#! /usr/local/bin/python - -# This Python program sorts and reformats the table of keywords in ref2.tex - -import string -l = [] -try: - while 1: - l = l + string.split(raw_input()) -except EOFError: - pass -l.sort() -for x in l[:]: - while l.count(x) > 1: l.remove(x) -ncols = 5 -nrows = (len(l)+ncols-1)/ncols -for i in range(nrows): - for j in range(i, len(l), nrows): - print string.ljust(l[j], 10), - print diff --git a/Doc/tools/partparse.py b/Doc/tools/partparse.py deleted file mode 100644 index 6128bbfaf9..0000000000 --- a/Doc/tools/partparse.py +++ /dev/null @@ -1,2165 +0,0 @@ -# -# partparse.py: parse a by-Guido-written-and-by-Jan-Hein-edited LaTeX file, -# and generate texinfo source. -# -# This is *not* a good example of good programming practices. In fact, this -# file could use a complete rewrite, in order to become faster, more -# easy extensible and maintainable. -# -# However, I added some comments on a few places for the pityful person who -# would ever need to take a look into this file. -# -# Have I been clear enough?? -# -# -jh - - -import sys, string, regex, getopt, os - -# Different parse modes for phase 1 -MODE_REGULAR = 0 -MODE_VERBATIM = 1 -MODE_CS_SCAN = 2 -MODE_COMMENT = 3 -MODE_MATH = 4 -MODE_DMATH = 5 -MODE_GOBBLEWHITE = 6 - -the_modes = MODE_REGULAR, MODE_VERBATIM, MODE_CS_SCAN, MODE_COMMENT, \ - MODE_MATH, MODE_DMATH, MODE_GOBBLEWHITE - -# Show the neighbourhood of the scanned buffer -def epsilon(buf, where): - wmt, wpt = where - 10, where + 10 - if wmt < 0: - wmt = 0 - if wpt > len(buf): - wpt = len(buf) - return ' Context ' + `buf[wmt:where]` + '.' + `buf[where:wpt]` + '.' - -# Should return the line number. never worked -def lin(): - global lineno - return ' Line ' + `lineno` + '.' - -# Displays the recursion level. -def lv(lvl): - return ' Level ' + `lvl` + '.' - -# Combine the three previous functions. Used often. -def lle(lvl, buf, where): - return lv(lvl) + lin() + epsilon(buf, where) - - -# This class is only needed for _symbolic_ representation of the parse mode. -class Mode: - def init(self, arg): - if arg not in the_modes: - raise ValueError, 'mode not in the_modes' - self.mode = arg - return self - - def __cmp__(self, other): - if type(self) != type(other): - other = mode(other) - return cmp(self.mode, other.mode) - - def __repr__(self): - if self.mode == MODE_REGULAR: - return 'MODE_REGULAR' - elif self.mode == MODE_VERBATIM: - return 'MODE_VERBATIM' - elif self.mode == MODE_CS_SCAN: - return 'MODE_CS_SCAN' - elif self.mode == MODE_COMMENT: - return 'MODE_COMMENT' - elif self.mode == MODE_MATH: - return 'MODE_MATH' - elif self.mode == MODE_DMATH: - return 'MODE_DMATH' - elif self.mode == MODE_GOBBLEWHITE: - return 'MODE_GOBBLEWHITE' - else: - raise ValueError, 'mode not in the_modes' - -# just a wrapper around a class initialisation -def mode(arg): - return Mode().init(arg) - - -# After phase 1, the text consists of chunks, with a certain type -# this type will be assigned to the chtype member of the chunk -# the where-field contains the file position where this is found -# and the data field contains (1): a tuple describing start- end end -# positions of the substring (can be used as slice for the buf-variable), -# (2) just a string, mostly generated by the changeit routine, -# or (3) a list, describing a (recursive) subgroup of chunks -PLAIN = 0 # ASSUME PLAINTEXT, data = the text -GROUP = 1 # GROUP ({}), data = [chunk, chunk,..] -CSNAME = 2 # CONTROL SEQ TOKEN, data = the command -COMMENT = 3 # data is the actual comment -DMATH = 4 # DISPLAYMATH, data = [chunk, chunk,..] -MATH = 5 # MATH, see DISPLAYMATH -OTHER = 6 # CHAR WITH CATCODE OTHER, data = char -ACTIVE = 7 # ACTIVE CHAR -GOBBLEDWHITE = 8 # Gobbled LWSP, after CSNAME -ENDLINE = 9 # END-OF-LINE, data = '\n' -DENDLINE = 10 # DOUBLE EOL, data='\n', indicates \par -ENV = 11 # LaTeX-environment - # data =(envname,[ch,ch,ch,.]) -CSLINE = 12 # for texi: next chunk will be one group - # of args. Will be set all on 1 line -IGNORE = 13 # IGNORE this data -ENDENV = 14 # TEMP END OF GROUP INDICATOR -IF = 15 # IF-directive - # data = (flag,negate,[ch, ch, ch,...]) -the_types = PLAIN, GROUP, CSNAME, COMMENT, DMATH, MATH, OTHER, ACTIVE, \ - GOBBLEDWHITE, ENDLINE, DENDLINE, ENV, CSLINE, IGNORE, ENDENV, IF - -# class, just to display symbolic name -class ChunkType: - def init(self, chunk_type): - if chunk_type not in the_types: - raise 'ValueError', 'chunk_type not in the_types' - self.chunk_type = chunk_type - return self - - def __cmp__(self, other): - if type(self) != type(other): - other = chunk_type(other) - return cmp(self.chunk_type, other.chunk_type) - - def __repr__(self): - if self.chunk_type == PLAIN: - return 'PLAIN' - elif self.chunk_type == GROUP: - return 'GROUP' - elif self.chunk_type == CSNAME: - return 'CSNAME' - elif self.chunk_type == COMMENT: - return 'COMMENT' - elif self.chunk_type == DMATH: - return 'DMATH' - elif self.chunk_type == MATH: - return 'MATH' - elif self.chunk_type == OTHER: - return 'OTHER' - elif self.chunk_type == ACTIVE: - return 'ACTIVE' - elif self.chunk_type == GOBBLEDWHITE: - return 'GOBBLEDWHITE' - elif self.chunk_type == DENDLINE: - return 'DENDLINE' - elif self.chunk_type == ENDLINE: - return 'ENDLINE' - elif self.chunk_type == ENV: - return 'ENV' - elif self.chunk_type == CSLINE: - return 'CSLINE' - elif self.chunk_type == IGNORE: - return 'IGNORE' - elif self.chunk_type == ENDENV: - return 'ENDENV' - elif self.chunk_type == IF: - return 'IF' - else: - raise ValueError, 'chunk_type not in the_types' - -# ...and the wrapper -def chunk_type(type): - return ChunkType().init(type) - -# store a type object of the ChunkType-class-instance... -chunk_type_type = type(chunk_type(0)) - -# this class contains a part of the parsed buffer -class Chunk: - def init(self, chtype, where, data): - if type(chtype) != chunk_type_type: - chtype = chunk_type(chtype) - self.chtype = chtype - if type(where) != type(0): - raise TypeError, '\'where\' is not a number' - self.where = where - self.data = data - ##print 'CHUNK', self - return self - - def __repr__(self): - return 'chunk' + `self.chtype, self.where, self.data` - -# and the wrapper -def chunk(chtype, where, data): - return Chunk().init(chtype, where, data) - - - -error = 'partparse.error' - -# -# TeX's catcodes... -# -CC_ESCAPE = 0 -CC_LBRACE = 1 -CC_RBRACE = 2 -CC_MATHSHIFT = 3 -CC_ALIGNMENT = 4 -CC_ENDLINE = 5 -CC_PARAMETER = 6 -CC_SUPERSCRIPT = 7 -CC_SUBSCRIPT = 8 -CC_IGNORE = 9 -CC_WHITE = 10 -CC_LETTER = 11 -CC_OTHER = 12 -CC_ACTIVE = 13 -CC_COMMENT = 14 -CC_INVALID = 15 - -# and the names -cc_names = [\ - 'CC_ESCAPE', \ - 'CC_LBRACE', \ - 'CC_RBRACE', \ - 'CC_MATHSHIFT', \ - 'CC_ALIGNMENT', \ - 'CC_ENDLINE', \ - 'CC_PARAMETER', \ - 'CC_SUPERSCRIPT', \ - 'CC_SUBSCRIPT', \ - 'CC_IGNORE', \ - 'CC_WHITE', \ - 'CC_LETTER', \ - 'CC_OTHER', \ - 'CC_ACTIVE', \ - 'CC_COMMENT', \ - 'CC_INVALID', \ - ] - -# Show a list of catcode-name-symbols -def pcl(codelist): - result = '' - for i in codelist: - result = result + cc_names[i] + ', ' - return '[' + result[:-2] + ']' - -# the name of the catcode (ACTIVE, OTHER, etc.) -def pc(code): - return cc_names[code] - - -# Which catcodes make the parser stop parsing regular plaintext -regular_stopcodes = [CC_ESCAPE, CC_LBRACE, CC_RBRACE, CC_MATHSHIFT, \ - CC_ALIGNMENT, CC_PARAMETER, CC_SUPERSCRIPT, CC_SUBSCRIPT, \ - CC_IGNORE, CC_ACTIVE, CC_COMMENT, CC_INVALID, CC_ENDLINE] - -# same for scanning a control sequence name -csname_scancodes = [CC_LETTER] - -# same for gobbling LWSP -white_scancodes = [CC_WHITE] -##white_scancodes = [CC_WHITE, CC_ENDLINE] - -# make a list of all catcode id's, except for catcode ``other'' -all_but_other_codes = range(16) -del all_but_other_codes[CC_OTHER] -##print all_but_other_codes - -# when does a comment end -comment_stopcodes = [CC_ENDLINE] - -# gather all characters together, specified by a list of catcodes -def code2string(cc, codelist): - ##print 'code2string: codelist = ' + pcl(codelist), - result = '' - for category in codelist: - if cc[category]: - result = result + cc[category] - ##print 'result = ' + `result` - return result - -# automatically generate all characters of catcode other, being the -# complement set in the ASCII range (128 characters) -def make_other_codes(cc): - otherchars = range(256) # could be made 256, no problem - for category in all_but_other_codes: - if cc[category]: - for c in cc[category]: - otherchars[ord(c)] = None - result = '' - for i in otherchars: - if i != None: - result = result + chr(i) - return result - -# catcode dump (which characters have which catcodes). -def dump_cc(name, cc): - ##print '\t' + name - ##print '=' * (8+len(name)) - if len(cc) != 16: - raise TypeError, 'cc not good cat class' -## for i in range(16): -## print pc(i) + '\t' + `cc[i]` - - -# In the beginning,.... -epoch_cc = [None] * 16 -##dump_cc('epoch_cc', epoch_cc) - - -# INITEX -initex_cc = epoch_cc[:] -initex_cc[CC_ESCAPE] = '\\' -initex_cc[CC_ENDLINE], initex_cc[CC_IGNORE], initex_cc[CC_WHITE] = \ - '\n', '\0', ' ' -initex_cc[CC_LETTER] = string.uppercase + string.lowercase -initex_cc[CC_COMMENT], initex_cc[CC_INVALID] = '%', '\x7F' -#initex_cc[CC_OTHER] = make_other_codes(initex_cc) I don't need them, anyway -##dump_cc('initex_cc', initex_cc) - - -# LPLAIN: LaTeX catcode setting (see lplain.tex) -lplain_cc = initex_cc[:] -lplain_cc[CC_LBRACE], lplain_cc[CC_RBRACE] = '{', '}' -lplain_cc[CC_MATHSHIFT] = '$' -lplain_cc[CC_ALIGNMENT] = '&' -lplain_cc[CC_PARAMETER] = '#' -lplain_cc[CC_SUPERSCRIPT] = '^\x0B' # '^' and C-k -lplain_cc[CC_SUBSCRIPT] = '_\x01' # '_' and C-a -lplain_cc[CC_WHITE] = lplain_cc[CC_WHITE] + '\t' -lplain_cc[CC_ACTIVE] = '~\x0C' # '~' and C-l -lplain_cc[CC_OTHER] = make_other_codes(lplain_cc) -##dump_cc('lplain_cc', lplain_cc) - - -# Guido's LaTeX environment catcoded '_' as ``other'' -# my own purpose catlist -my_cc = lplain_cc[:] -my_cc[CC_SUBSCRIPT] = my_cc[CC_SUBSCRIPT][1:] # remove '_' here -my_cc[CC_OTHER] = my_cc[CC_OTHER] + '_' # add it to OTHER list -dump_cc('my_cc', my_cc) - - - -# needed for un_re, my equivalent for regexp-quote in Emacs -re_meaning = '\\[]^$' - -def un_re(str): - result = '' - for i in str: - if i in re_meaning: - result = result + '\\' - result = result + i - return result - -# NOTE the negate ('^') operator in *some* of the regexps below -def make_rc_regular(cc): - # problems here if '[]' are included!! - return regex.compile('[' + code2string(cc, regular_stopcodes) + ']') - -def make_rc_cs_scan(cc): - return regex.compile('[^' + code2string(cc, csname_scancodes) + ']') - -def make_rc_comment(cc): - return regex.compile('[' + code2string(cc, comment_stopcodes) + ']') - -def make_rc_endwhite(cc): - return regex.compile('[^' + code2string(cc, white_scancodes) + ']') - - - -# regular: normal mode: -rc_regular = make_rc_regular(my_cc) - -# scan: scan a command sequence e.g. `newlength' or `mbox' or `;', `,' or `$' -rc_cs_scan = make_rc_cs_scan(my_cc) -rc_comment = make_rc_comment(my_cc) -rc_endwhite = make_rc_endwhite(my_cc) - - -# parseit (BUF, PARSEMODE=mode(MODE_REGULAR), START=0, RECURSION-LEVEL=0) -# RECURSION-LEVEL will is incremented on entry. -# result contains the list of chunks returned -# together with this list, the buffer position is returned - -# RECURSION-LEVEL will be set to zero *again*, when recursively a -# {,D}MATH-mode scan has been enetered. -# This has been done in order to better check for environment-mismatches - -def parseit(buf, *rest): - global lineno - - if len(rest) == 3: - parsemode, start, lvl = rest - elif len(rest) == 2: - parsemode, start, lvl = rest + (0, ) - elif len(rest) == 1: - parsemode, start, lvl = rest + (0, 0) - elif len(rest) == 0: - parsemode, start, lvl = mode(MODE_REGULAR), 0, 0 - else: - raise TypeError, 'usage: parseit(buf[, parsemode[, start[, level]]])' - result = [] - end = len(buf) - if lvl == 0 and parsemode == mode(MODE_REGULAR): - lineno = 1 - lvl = lvl + 1 - - ##print 'parseit(' + epsilon(buf, start) + ', ' + `parsemode` + ', ' + `start` + ', ' + `lvl` + ')' - - # - # some of the more regular modes... - # - - if parsemode in (mode(MODE_REGULAR), mode(MODE_DMATH), mode(MODE_MATH)): - cstate = [] - newpos = start - curpmode = parsemode - while 1: - where = newpos - #print '\tnew round: ' + epsilon(buf, where) - if where == end: - if lvl > 1 or curpmode != mode(MODE_REGULAR): - # not the way we started... - raise EOFError, 'premature end of file.' + lle(lvl, buf, where) - # the real ending of lvl-1 parse - return end, result - - pos = rc_regular.search(buf, where) - - if pos < 0: - pos = end - - if pos != where: - newpos, c = pos, chunk(PLAIN, where, (where, pos)) - result.append(c) - continue - - - # - # ok, pos == where and pos != end - # - foundchar = buf[where] - if foundchar in my_cc[CC_LBRACE]: - # recursive subgroup parse... - newpos, data = parseit(buf, curpmode, where+1, lvl) - result.append(chunk(GROUP, where, data)) - - elif foundchar in my_cc[CC_RBRACE]: - if lvl <= 1: - raise error, 'ENDGROUP while in base level.' + lle(lvl, buf, where) - if lvl == 1 and mode != mode(MODE_REGULAR): - raise error, 'endgroup while in math mode. +lin() + epsilon(buf, where)' - return where + 1, result - - elif foundchar in my_cc[CC_ESCAPE]: - # - # call the routine that actually deals with - # this problem. If do_ret is None, than - # return the value of do_ret - # - # Note that handle_cs might call this routine - # recursively again... - # - do_ret, newpos = handlecs(buf, where, \ - curpmode, lvl, result, end) - if do_ret != None: - return do_ret - - elif foundchar in my_cc[CC_COMMENT]: - newpos, data = parseit(buf, \ - mode(MODE_COMMENT), where+1, lvl) - result.append(chunk(COMMENT, where, data)) - - elif foundchar in my_cc[CC_MATHSHIFT]: - # note that recursive calls to math-mode - # scanning are called with recursion-level 0 - # again, in order to check for bad mathend - # - if where + 1 != end and \ - buf[where + 1] in \ - my_cc[CC_MATHSHIFT]: - # - # double mathshift, e.g. '$$' - # - if curpmode == mode(MODE_REGULAR): - newpos, data = parseit(buf, \ - mode(MODE_DMATH), \ - where+2, 0) - result.append(chunk(DMATH, \ - where, data)) - elif curpmode == mode(MODE_MATH): - raise error, 'wrong math delimiiter' + lin() + epsilon(buf, where) - elif lvl != 1: - raise error, 'bad mathend.' + \ - lle(lvl, buf, where) - else: - return where + 2, result - else: - # - # single math shift, e.g. '$' - # - if curpmode == mode(MODE_REGULAR): - newpos, data = parseit(buf, \ - mode(MODE_MATH), \ - where+1, 0) - result.append(chunk(MATH, \ - where, data)) - elif curpmode == mode(MODE_DMATH): - raise error, 'wrong math delimiiter' + lin() + epsilon(buf, where) - elif lvl != 1: - raise error, 'bad mathend.' + \ - lv(lvl, buf, where) - else: - return where + 1, result - - elif foundchar in my_cc[CC_IGNORE]: - print 'warning: ignored char', `foundchar` - newpos = where + 1 - - elif foundchar in my_cc[CC_ACTIVE]: - result.append(chunk(ACTIVE, where, foundchar)) - newpos = where + 1 - - elif foundchar in my_cc[CC_INVALID]: - raise error, 'invalid char ' + `foundchar` - newpos = where + 1 - - elif foundchar in my_cc[CC_ENDLINE]: - # - # after an end of line, eat the rest of - # whitespace on the beginning of the next line - # this is what LaTeX more or less does - # - # also, try to indicate double newlines (\par) - # - lineno = lineno + 1 - savedwhere = where - newpos, dummy = parseit(buf, mode(MODE_GOBBLEWHITE), where + 1, lvl) - if newpos != end and buf[newpos] in \ - my_cc[CC_ENDLINE]: - result.append(chunk(DENDLINE, \ - savedwhere, foundchar)) - else: - result.append(chunk(ENDLINE, \ - savedwhere, foundchar)) - else: - result.append(chunk(OTHER, where, foundchar)) - newpos = where + 1 - - elif parsemode == mode(MODE_CS_SCAN): - # - # scan for a control sequence token. `\ape', `\nut' or `\%' - # - if start == end: - raise EOFError, 'can\'t find end of csname' - pos = rc_cs_scan.search(buf, start) - if pos < 0: - pos = end - if pos == start: - # first non-letter right where we started the search - # ---> the control sequence name consists of one single - # character. Also: don't eat white space... - if buf[pos] in my_cc[CC_ENDLINE]: - lineno = lineno + 1 - pos = pos + 1 - return pos, (start, pos) - else: - spos = pos - if buf[pos] == '\n': - lineno = lineno + 1 - spos = pos + 1 - pos2, dummy = parseit(buf, \ - mode(MODE_GOBBLEWHITE), spos, lvl) - return pos2, (start, pos) - - elif parsemode == mode(MODE_GOBBLEWHITE): - if start == end: - return start, '' - pos = rc_endwhite.search(buf, start) - if pos < 0: - pos = start - return pos, (start, pos) - - elif parsemode == mode(MODE_COMMENT): - pos = rc_comment.search(buf, start) - lineno = lineno + 1 - if pos < 0: - print 'no newline perhaps?' - raise EOFError, 'can\'t find end of comment' - pos = pos + 1 - pos2, dummy = parseit(buf, mode(MODE_GOBBLEWHITE), pos, lvl) - return pos2, (start, pos) - - - else: - raise error, 'Unknown mode (' + `parsemode` + ')' - - -#moreresult = cswitch(buf[x1:x2], buf, newpos, parsemode, lvl) - -#boxcommands = 'mbox', 'fbox' -#defcommands = 'def', 'newcommand' - -endverbstr = '\\end{verbatim}' - -re_endverb = regex.compile(un_re(endverbstr)) - -# -# handlecs: helper function for parseit, for the special thing we might -# wanna do after certain command control sequences -# returns: None or return_data, newpos -# -# in the latter case, the calling function is instructed to immediately -# return with the data in return_data -# -def handlecs(buf, where, curpmode, lvl, result, end): - global lineno - - # get the control sequence name... - newpos, data = parseit(buf, mode(MODE_CS_SCAN), where+1, lvl) - saveddata = data - - if s(buf, data) in ('begin', 'end'): - # skip the expected '{' and get the LaTeX-envname '}' - newpos, data = parseit(buf, mode(MODE_REGULAR), newpos+1, lvl) - if len(data) != 1: - raise error, 'expected 1 chunk of data.' + \ - lle(lvl, buf, where) - - # yucky, we've got an environment - envname = s(buf, data[0].data) - ##print 'FOUND ' + s(buf, saveddata) + '. Name ' + `envname` + '.' + lv(lvl) - if s(buf, saveddata) == 'begin' and envname == 'verbatim': - # verbatim deserves special treatment - pos = re_endverb.search(buf, newpos) - if pos < 0: - raise error, `endverbstr` + ' not found.' + lle(lvl, buf, where) - result.append(chunk(ENV, where, (envname, [chunk(PLAIN, newpos, (newpos, pos))]))) - newpos = pos + len(endverbstr) - - elif s(buf, saveddata) == 'begin': - # start parsing recursively... If that parse returns - # from an '\end{...}', then should the last item of - # the returned data be a string containing the ended - # environment - newpos, data = parseit(buf, curpmode, newpos, lvl) - if not data or type(data[-1]) != type(''): - raise error, 'missing \'end\'' + lle(lvl, buf, where) + epsilon(buf, newpos) - retenv = data[-1] - del data[-1] - if retenv != envname: - #[`retenv`, `envname`] - raise error, 'environments do not match.' + \ - lle(lvl, buf, where) + \ - epsilon(buf, newpos) - result.append(chunk(ENV, where, (retenv, data))) - else: - # 'end'... append the environment name, as just - # pointed out, and order parsit to return... - result.append(envname) - ##print 'POINT of return: ' + epsilon(buf, newpos) - # the tuple will be returned by parseit - return (newpos, result), newpos - - # end of \begin ... \end handling - - elif s(buf, data)[0:2] == 'if': - # another scary monster: the 'if' directive - flag = s(buf, data)[2:] - - # recursively call parseit, just like environment above.. - # the last item of data should contain the if-termination - # e.g., 'else' of 'fi' - newpos, data = parseit(buf, curpmode, newpos, lvl) - if not data or data[-1] not in ('else', 'fi'): - raise error, 'wrong if... termination' + \ - lle(lvl, buf, where) + epsilon(buf, newpos) - - ifterm = data[-1] - del data[-1] - # 0 means dont_negate flag - result.append(chunk(IF, where, (flag, 0, data))) - if ifterm == 'else': - # do the whole thing again, there is only one way - # to end this one, by 'fi' - newpos, data = parseit(buf, curpmode, newpos, lvl) - if not data or data[-1] not in ('fi', ): - raise error, 'wrong if...else... termination' \ - + lle(lvl, buf, where) \ - + epsilon(buf, newpos) - - ifterm = data[-1] - del data[-1] - result.append(chunk(IF, where, (flag, 1, data))) - #done implicitely: return None, newpos - - elif s(buf, data) in ('else', 'fi'): - result.append(s(buf, data)) - # order calling party to return tuple - return (newpos, result), newpos - - # end of \if, \else, ... \fi handling - - elif s(buf, saveddata) == 'verb': - x2 = saveddata[1] - result.append(chunk(CSNAME, where, data)) - if x2 == end: - raise error, 'premature end of command.' + lle(lvl, buf, where) - delimchar = buf[x2] - ##print 'VERB: delimchar ' + `delimchar` - pos = regex.compile(un_re(delimchar)).search(buf, x2 + 1) - if pos < 0: - raise error, 'end of \'verb\' argument (' + \ - `delimchar` + ') not found.' + \ - lle(lvl, buf, where) - result.append(chunk(GROUP, x2, [chunk(PLAIN, x2+1, (x2+1, pos))])) - newpos = pos + 1 - else: - result.append(chunk(CSNAME, where, data)) - return None, newpos - -# this is just a function to get the string value if the possible data-tuple -def s(buf, data): - if type(data) == type(''): - return data - if len(data) != 2 or not (type(data[0]) == type(data[1]) == type(0)): - raise TypeError, 'expected tuple of 2 integers' - x1, x2 = data - return buf[x1:x2] - - -##length, data1, i = getnextarg(length, buf, pp, i + 1) - -# make a deep-copy of some chunks -def crcopy(r): - result = [] - for x in r: - result.append(chunkcopy(x)) - return result - - - -# copy a chunk, would better be a method of class Chunk... -def chunkcopy(ch): - if ch.chtype == chunk_type(GROUP): - listc = ch.data[:] - for i in range(len(listc)): - listc[i] = chunkcopy(listc[i]) - return chunk(GROUP, ch.where, listc) - else: - return chunk(ch.chtype, ch.where, ch.data) - - -# get next argument for TeX-macro, flatten a group (insert between) -# or return Command Sequence token, or give back one character -def getnextarg(length, buf, pp, item): - - ##wobj = Wobj().init() - ##dumpit(buf, wobj.write, pp[item:min(length, item + 5)]) - ##print 'GETNEXTARG, (len, item) =', `length, item` + ' ---> ' + wobj.data + ' <---' - - while item < length and pp[item].chtype == chunk_type(ENDLINE): - del pp[item] - length = length - 1 - if item >= length: - raise error, 'no next arg.' + epsilon(buf, pp[-1].where) - if pp[item].chtype == chunk_type(GROUP): - newpp = pp[item].data - del pp[item] - length = length - 1 - changeit(buf, newpp) - length = length + len(newpp) - pp[item:item] = newpp - item = item + len(newpp) - if len(newpp) < 10: - wobj = Wobj().init() - dumpit(buf, wobj.write, newpp) - ##print 'GETNEXTARG: inserted ' + `wobj.data` - return length, item - elif pp[item].chtype == chunk_type(PLAIN): - #grab one char - print 'WARNING: grabbing one char' - if len(s(buf, pp[item].data)) > 1: - pp.insert(item, chunk(PLAIN, pp[item].where, s(buf, pp[item].data)[:1])) - item, length = item+1, length+1 - pp[item].data = s(buf, pp[item].data)[1:] - else: - item = item+1 - return length, item - else: - ch = pp[item] - try: - str = `s(buf, ch.data)` - except TypeError: - str = `ch.data` - if len(str) > 400: - str = str[:400] + '...' - print 'GETNEXTARG:', ch.chtype, 'not handled, data ' + str - return length, item - - -# this one is needed to find the end of LaTeX's optional argument, like -# item[...] -re_endopt = regex.compile(']') - -# get a LaTeX-optional argument, you know, the square braces '[' and ']' -def getoptarg(length, buf, pp, item): - - wobj = Wobj().init() - dumpit(buf, wobj.write, pp[item:min(length, item + 5)]) - ##print 'GETOPTARG, (len, item) =', `length, item` + ' ---> ' + wobj.data + ' <---' - - if item >= length or \ - pp[item].chtype != chunk_type(PLAIN) or \ - s(buf, pp[item].data)[0] != '[': - return length, item - - pp[item].data = s(buf, pp[item].data)[1:] - if len(pp[item].data) == 0: - del pp[item] - length = length-1 - - while 1: - if item == length: - raise error, 'No end of optional arg found' - if pp[item].chtype == chunk_type(PLAIN): - text = s(buf, pp[item].data) - pos = re_endopt.search(text) - if pos >= 0: - pp[item].data = text[:pos] - if pos == 0: - del pp[item] - length = length-1 - else: - item=item+1 - text = text[pos+1:] - - while text and text[0] in ' \t': - text = text[1:] - - if text: - pp.insert(item, chunk(PLAIN, 0, text)) - length = length + 1 - return length, item - - item = item+1 - - -# Wobj just add write-requests to the ``data'' attribute -class Wobj: - def init(self): - self.data = '' - return self - def write(self, data): - self.data = self.data + data - -# ignore these commands -ignoredcommands = ('bcode', 'ecode') -# map commands like these to themselves as plaintext -wordsselves = ('UNIX', 'ABC', 'C', 'ASCII', 'EOF', 'LaTeX') -# \{ --> {, \} --> }, etc -themselves = ('{', '}', '.', '@', ' ', '\n') + wordsselves -# these ones also themselves (see argargs macro in myformat.sty) -inargsselves = (',', '[', ']', '(', ')') -# this is how *I* would show the difference between emph and strong -# code 1 means: fold to uppercase -markcmds = {'code': ('', ''), 'var': 1, 'emph': ('_', '_'), \ - 'strong': ('*', '*')} - -# recognise patter {\FONTCHANGE-CMD TEXT} to \MAPPED-FC-CMD{TEXT} -fontchanges = {'rm': 'r', 'it': 'i', 'em': 'emph', 'bf': 'b', 'tt': 't'} - -# transparent for these commands -for_texi = ('emph', 'var', 'strong', 'code', 'kbd', 'key', 'dfn', 'samp', - 'file', 'r', 'i', 't') - - -# try to remove macros and return flat text -def flattext(buf, pp): - pp = crcopy(pp) - ##print '---> FLATTEXT ' + `pp` - wobj = Wobj().init() - - i, length = 0, len(pp) - while 1: - if len(pp) != length: - raise 'FATAL', 'inconsistent length' - if i >= length: - break - ch = pp[i] - i = i+1 - if ch.chtype == chunk_type(PLAIN): - pass - elif ch.chtype == chunk_type(CSNAME): - if s(buf, ch.data) in themselves or hist.inargs and s(buf, ch.data) in inargsselves: - ch.chtype = chunk_type(PLAIN) - elif s(buf, ch.data) == 'e': - ch.chtype = chunk_type(PLAIN) - ch.data = '\\' - elif len(s(buf, ch.data)) == 1 \ - and s(buf, ch.data) in onlylatexspecial: - ch.chtype = chunk_type(PLAIN) - # if it is followed by an empty group, - # remove that group, it was needed for - # a true space - if i < length \ - and pp[i].chtype==chunk_type(GROUP) \ - and len(pp[i].data) == 0: - del pp[i] - length = length-1 - - elif s(buf, ch.data) in markcmds.keys(): - length, newi = getnextarg(length, buf, pp, i) - str = flattext(buf, pp[i:newi]) - del pp[i:newi] - length = length - (newi - i) - ch.chtype = chunk_type(PLAIN) - markcmd = s(buf, ch.data) - x = markcmds[markcmd] - if type(x) == type(()): - pre, after = x - str = pre+str+after - elif x == 1: - str = string.upper(str) - else: - raise 'FATAL', 'corrupt markcmds' - ch.data = str - else: - if s(buf, ch.data) not in ignoredcommands: - print 'WARNING: deleting command ' + `s(buf, ch.data)` - print 'PP' + `pp[i-1]` - del pp[i-1] - i, length = i-1, length-1 - elif ch.chtype == chunk_type(GROUP): - length, newi = getnextarg(length, buf, pp, i-1) - i = i-1 -## str = flattext(buf, crcopy(pp[i-1:newi])) -## del pp[i:newi] -## length = length - (newi - i) -## ch.chtype = chunk_type(PLAIN) -## ch.data = str - else: - pass - - dumpit(buf, wobj.write, pp) - ##print 'FLATTEXT: RETURNING ' + `wobj.data` - return wobj.data - -# try to generate node names (a bit shorter than the chapter title) -# note that the \nodename command (see elsewhere) overules these efforts -def invent_node_names(text): - words = string.split(text) - - ##print 'WORDS ' + `words` - - if len(words) == 2 \ - and string.lower(words[0]) == 'built-in' \ - and string.lower(words[1]) not in ('modules', 'functions'): - return words[1] - if len(words) == 3 and string.lower(words[1]) == 'module': - return words[2] - if len(words) == 3 and string.lower(words[1]) == 'object': - return string.join(words[0:2]) - if len(words) > 4 and string.lower(string.join(words[-4:])) == \ - 'methods and data attributes': - return string.join(words[:2]) - return text - -re_commas_etc = regex.compile('[,`\'@{}]') - -re_whitespace = regex.compile('[ \t]*') - - -##nodenamecmd = next_command_p(length, buf, pp, newi, 'nodename') - -# look if the next non-white stuff is also a command, resulting in skipping -# double endlines (DENDLINE) too, and thus omitting \par's -# Sometimes this is too much, maybe consider DENDLINE's as stop -def next_command_p(length, buf, pp, i, cmdname): - - while 1: - if i >= len(pp): - break - ch = pp[i] - i = i+1 - if ch.chtype == chunk_type(ENDLINE): - continue - if ch.chtype == chunk_type(DENDLINE): - continue - if ch.chtype == chunk_type(PLAIN): - if re_whitespace.search(s(buf, ch.data)) == 0 and \ - re_whitespace.match(s(buf, ch.data)) == len(s(buf, ch.data)): - continue - return -1 - if ch.chtype == chunk_type(CSNAME): - if s(buf, ch.data) == cmdname: - return i # _after_ the command - return -1 - return -1 - - -# things that are special to LaTeX, but not to texi.. -onlylatexspecial = '_~^$#&%' - -class Struct: pass - -hist = Struct() -out = Struct() - -def startchange(): - global hist, out - - hist.inenv = [] - hist.nodenames = [] - hist.cindex = [] - hist.inargs = 0 - hist.enumeratenesting, hist.itemizenesting = 0, 0 - - out.doublenodes = [] - out.doublecindeces = [] - - -spacech = [chunk(PLAIN, 0, ' ')] -commach = [chunk(PLAIN, 0, ', ')] -cindexch = [chunk(CSLINE, 0, 'cindex')] - -# the standard variation in symbols for itemize -itemizesymbols = ['bullet', 'minus', 'dots'] - -# same for enumerate -enumeratesymbols = ['1', 'A', 'a'] - -## -## \begin{ {func,data,exc}desc }{name}... -## the resulting texi-code is dependent on the contents of indexsubitem -## - -# indexsubitem: `['XXX', 'function'] -# funcdesc: -# deffn {`idxsi`} NAME (FUNCARGS) - -# indexsubitem: `['XXX', 'method']` -# funcdesc: -# defmethod {`idxsi[0]`} NAME (FUNCARGS) - -# indexsubitem: `['in', 'module', 'MODNAME']' -# datadesc: -# defcv data {`idxsi[1:]`} NAME -# excdesc: -# defcv exception {`idxsi[1:]`} NAME -# funcdesc: -# deffn {function of `idxsi[1:]`} NAME (FUNCARGS) - -# indexsubitem: `['OBJECT', 'attribute']' -# datadesc -# defcv attribute {`OBJECT`} NAME - - -## this routine will be called on \begin{funcdesc}{NAME}{ARGS} -## or \funcline{NAME}{ARGS} -## -def do_funcdesc(length, buf, pp, i): - startpoint = i-1 - ch = pp[startpoint] - wh = ch.where - length, newi = getnextarg(length, buf, pp, i) - funcname = chunk(GROUP, wh, pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - save = hist.inargs - hist.inargs = 1 - length, newi = getnextarg(length, buf, pp, i) - hist.inargs = save - del save - the_args = [chunk(PLAIN, wh, '()'[0])] + \ - pp[i:newi] + \ - [chunk(PLAIN, wh, '()'[1])] - del pp[i:newi] - length = length - (newi-i) - - idxsi = hist.indexsubitem # words - command = '' - cat_class = '' - if idxsi and idxsi[-1] in ('method', 'protocol'): - command = 'defmethod' - cat_class = string.join(idxsi[:-1]) - elif len(idxsi) == 2 and idxsi[1] == 'function': - command = 'deffn' - cat_class = string.join(idxsi) - elif len(idxsi) == 3 and idxsi[:2] == ['in', 'module']: - command = 'deffn' - cat_class = 'function of ' + string.join(idxsi[1:]) - - if not command: - raise error, 'don\'t know what to do with indexsubitem ' + `idxsi` - - ch.chtype = chunk_type(CSLINE) - ch.data = command - - cslinearg = [chunk(GROUP, wh, [chunk(PLAIN, wh, cat_class)])] - cslinearg.append(chunk(PLAIN, wh, ' ')) - cslinearg.append(funcname) - cslinearg.append(chunk(PLAIN, wh, ' ')) - l = len(cslinearg) - cslinearg[l:l] = the_args - - pp.insert(i, chunk(GROUP, wh, cslinearg)) - i, length = i+1, length+1 - hist.command = command - return length, i - - -## this routine will be called on \begin{excdesc}{NAME} -## or \excline{NAME} -## -def do_excdesc(length, buf, pp, i): - startpoint = i-1 - ch = pp[startpoint] - wh = ch.where - length, newi = getnextarg(length, buf, pp, i) - excname = chunk(GROUP, wh, pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - - idxsi = hist.indexsubitem # words - command = '' - cat_class = '' - class_class = '' - if len(idxsi) == 2 and idxsi[1] == 'exception': - command = 'defvr' - cat_class = string.join(idxsi) - elif len(idxsi) == 3 and idxsi[:2] == ['in', 'module']: - command = 'defcv' - cat_class = 'exception' - class_class = string.join(idxsi[1:]) - elif len(idxsi) == 4 and idxsi[:3] == ['exception', 'in', 'module']: - command = 'defcv' - cat_class = 'exception' - class_class = string.join(idxsi[2:]) - - - if not command: - raise error, 'don\'t know what to do with indexsubitem ' + `idxsi` - - ch.chtype = chunk_type(CSLINE) - ch.data = command - - cslinearg = [chunk(GROUP, wh, [chunk(PLAIN, wh, cat_class)])] - cslinearg.append(chunk(PLAIN, wh, ' ')) - if class_class: - cslinearg.append(chunk(GROUP, wh, [chunk(PLAIN, wh, class_class)])) - cslinearg.append(chunk(PLAIN, wh, ' ')) - cslinearg.append(excname) - - pp.insert(i, chunk(GROUP, wh, cslinearg)) - i, length = i+1, length+1 - hist.command = command - return length, i - -## same for datadesc or dataline... -def do_datadesc(length, buf, pp, i): - startpoint = i-1 - ch = pp[startpoint] - wh = ch.where - length, newi = getnextarg(length, buf, pp, i) - dataname = chunk(GROUP, wh, pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - - idxsi = hist.indexsubitem # words - command = '' - cat_class = '' - class_class = '' - if idxsi[-1] in ('attribute', 'option'): - command = 'defcv' - cat_class = idxsi[-1] - class_class = string.join(idxsi[:-1]) - elif len(idxsi) == 3 and idxsi[:2] == ['in', 'module']: - command = 'defcv' - cat_class = 'data' - class_class = string.join(idxsi[1:]) - elif len(idxsi) == 4 and idxsi[:3] == ['data', 'in', 'module']: - command = 'defcv' - cat_class = 'data' - class_class = string.join(idxsi[2:]) - - - if not command: - raise error, 'don\'t know what to do with indexsubitem ' + `idxsi` - - ch.chtype = chunk_type(CSLINE) - ch.data = command - - cslinearg = [chunk(GROUP, wh, [chunk(PLAIN, wh, cat_class)])] - cslinearg.append(chunk(PLAIN, wh, ' ')) - if class_class: - cslinearg.append(chunk(GROUP, wh, [chunk(PLAIN, wh, class_class)])) - cslinearg.append(chunk(PLAIN, wh, ' ')) - cslinearg.append(dataname) - - pp.insert(i, chunk(GROUP, wh, cslinearg)) - i, length = i+1, length+1 - hist.command = command - return length, i - - -# regular indices: those that are not set in tt font by default.... -regindices = ('cindex', ) - -# remove illegal characters from node names -def rm_commas_etc(text): - result = '' - changed = 0 - while 1: - pos = re_commas_etc.search(text) - if pos >= 0: - changed = 1 - result = result + text[:pos] - text = text[pos+1:] - else: - result = result + text - break - if changed: - print 'Warning: nodename changhed to ' + `result` - - return result - -# boolean flags -flags = {'texi': 1} - - -## -## changeit: the actual routine, that changes the contents of the parsed -## chunks -## - -def changeit(buf, pp): - global onlylatexspecial, hist, out - - i, length = 0, len(pp) - while 1: - # sanity check: length should always equal len(pp) - if len(pp) != length: - raise 'FATAL', 'inconsistent length. thought ' + `length` + ', but should really be ' + `len(pp)` - if i >= length: - break - ch = pp[i] - i = i + 1 - - if type(ch) == type(''): - #normally, only chunks are present in pp, - # but in some cases, some extra info - # has been inserted, e.g., the \end{...} clauses - raise 'FATAL', 'got string, probably too many ' + `end` - - if ch.chtype == chunk_type(GROUP): - # check for {\em ...} constructs - if ch.data and \ - ch.data[0].chtype == chunk_type(CSNAME) and \ - s(buf, ch.data[0].data) in fontchanges.keys(): - k = s(buf, ch.data[0].data) - del ch.data[0] - pp.insert(i-1, chunk(CSNAME, ch.where, fontchanges[k])) - length, i = length+1, i+1 - - # recursively parse the contents of the group - changeit(buf, ch.data) - - elif ch.chtype == chunk_type(IF): - # \if... - flag, negate, data = ch.data - ##print 'IF: flag, negate = ' + `flag, negate` - if flag not in flags.keys(): - raise error, 'unknown flag ' + `flag` - - value = flags[flag] - if negate: - value = (not value) - del pp[i-1] - length, i = length-1, i-1 - if value: - pp[i:i] = data - length = length + len(data) - - - elif ch.chtype == chunk_type(ENV): - # \begin{...} .... - envname, data = ch.data - - #push this environment name on stack - hist.inenv.insert(0, envname) - - #append an endenv chunk after grouped data - data.append(chunk(ENDENV, ch.where, envname)) - ##[`data`] - - #delete this object - del pp[i-1] - i, length = i-1, length-1 - - #insert found data - pp[i:i] = data - length = length + len(data) - - if envname == 'verbatim': - pp[i:i] = [chunk(CSLINE, ch.where, 'example'), \ - chunk(GROUP, ch.where, [])] - length, i = length+2, i+2 - - elif envname == 'itemize': - if hist.itemizenesting > len(itemizesymbols): - raise error, 'too deep itemize nesting' - ingroupch = [chunk(CSNAME, ch.where,\ - itemizesymbols[hist.itemizenesting])] - hist.itemizenesting = hist.itemizenesting + 1 - pp[i:i] = [chunk(CSLINE, ch.where, 'itemize'),\ - chunk(GROUP, ch.where, ingroupch)] - length, i = length+2, i+2 - - elif envname == 'enumerate': - if hist.enumeratenesting > len(enumeratesymbols): - raise error, 'too deep enumerate nesting' - ingroupch = [chunk(PLAIN, ch.where,\ - enumeratesymbols[hist.enumeratenesting])] - hist.enumeratenesting = hist.enumeratenesting + 1 - pp[i:i] = [chunk(CSLINE, ch.where, 'enumerate'),\ - chunk(GROUP, ch.where, ingroupch)] - length, i = length+2, i+2 - - elif envname == 'description': - ingroupch = [chunk(CSNAME, ch.where, 'b')] - pp[i:i] = [chunk(CSLINE, ch.where, 'table'), \ - chunk(GROUP, ch.where, ingroupch)] - length, i = length+2, i+2 - - elif (envname == 'tableiii') or \ - (envname == 'tableii'): - if (envname == 'tableii'): - ltable = 2 - else: - ltable = 3 - wh = ch.where - newcode = [] - - #delete tabular format description - # e.g., {|l|c|l|} - length, newi = getnextarg(length, buf, pp, i) - del pp[i:newi] - length = length - (newi-i) - - newcode.append(chunk(CSLINE, wh, 'table')) - ingroupch = [chunk(CSNAME, wh, 'asis')] - newcode.append(chunk(GROUP, wh, ingroupch)) - newcode.append(chunk(CSLINE, wh, 'item')) - - #get the name of macro for @item - # e.g., {code} - length, newi = getnextarg(length, buf, pp, i) - - if newi-i != 1: - raise error, 'Sorry, expected 1 chunk argument' - if pp[i].chtype != chunk_type(PLAIN): - raise error, 'Sorry, expected plain text argument' - hist.itemargmacro = s(buf, pp[i].data) - del pp[i:newi] - length = length - (newi-i) - - itembody = [] - for count in range(ltable): - length, newi = getnextarg(length, buf, pp, i) - emphgroup = [\ - chunk(CSNAME, wh, 'emph'), \ - chunk(GROUP, 0, pp[i:newi])] - del pp[i:newi] - length = length - (newi-i) - if count == 0: - itemarg = emphgroup - elif count == ltable-1: - itembody = itembody + \ - [chunk(PLAIN, wh, ' --- ')] + \ - emphgroup - else: - itembody = emphgroup - newcode.append(chunk(GROUP, wh, itemarg)) - newcode = newcode + itembody + [chunk(DENDLINE, wh, '\n')] - pp[i:i] = newcode - l = len(newcode) - length, i = length+l, i+l - del newcode, l - - if length != len(pp): - raise 'STILL, SOMETHING wrong', `i` - - - elif envname == 'funcdesc': - pp.insert(i, chunk(PLAIN, ch.where, '')) - i, length = i+1, length+1 - length, i = do_funcdesc(length, buf, pp, i) - - elif envname == 'excdesc': - pp.insert(i, chunk(PLAIN, ch.where, '')) - i, length = i+1, length+1 - length, i = do_excdesc(length, buf, pp, i) - - elif envname == 'datadesc': - pp.insert(i, chunk(PLAIN, ch.where, '')) - i, length = i+1, length+1 - length, i = do_datadesc(length, buf, pp, i) - - else: - print 'WARNING: don\'t know what to do with env ' + `envname` - - elif ch.chtype == chunk_type(ENDENV): - envname = ch.data - if envname != hist.inenv[0]: - raise error, '\'end\' does not match. Name ' + `envname` + ', expected ' + `hist.inenv[0]` - del hist.inenv[0] - del pp[i-1] - i, length = i-1, length-1 - - if envname == 'verbatim': - pp[i:i] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, 'example')])] - i, length = i+2, length+2 - elif envname == 'itemize': - hist.itemizenesting = hist.itemizenesting - 1 - pp[i:i] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, 'itemize')])] - i, length = i+2, length+2 - elif envname == 'enumerate': - hist.enumeratenesting = hist.enumeratenesting-1 - pp[i:i] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, 'enumerate')])] - i, length = i+2, length+2 - elif envname == 'description': - pp[i:i] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, 'table')])] - i, length = i+2, length+2 - elif (envname == 'tableiii') or (envname == 'tableii'): - pp[i:i] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, 'table')])] - i, length = i+2, length + 2 - pp.insert(i, chunk(DENDLINE, ch.where, '\n')) - i, length = i+1, length+1 - - elif envname in ('funcdesc', 'excdesc', 'datadesc'): - pp[i:i] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, hist.command)])] - i, length = i+2, length+2 - else: - print 'WARNING: ending env ' + `envname` + 'has no actions' - - elif ch.chtype == chunk_type(CSNAME): - # control name transformations - if s(buf, ch.data) == 'optional': - pp[i-1].chtype = chunk_type (PLAIN) - pp[i-1].data = '[' - if (i < length) and \ - (pp[i].chtype == chunk_type(GROUP)): - cp=pp[i].data - pp[i:i+1]=cp + [\ - chunk(PLAIN, ch.where, ']')] - length = length+len(cp) - elif s(buf, ch.data) in ignoredcommands: - del pp[i-1] - i, length = i-1, length-1 - elif s(buf, ch.data) == '@' and \ - i != length and \ - pp[i].chtype == chunk_type(PLAIN) and \ - s(buf, pp[i].data)[0] == '.': - # \@. --> \. --> @. - ch.data = '.' - del pp[i] - length = length-1 - elif s(buf, ch.data) == '\\': - # \\ --> \* --> @* - ch.data = '*' - elif len(s(buf, ch.data)) == 1 and \ - s(buf, ch.data) in onlylatexspecial: - ch.chtype = chunk_type(PLAIN) - # check if such a command is followed by - # an empty group: e.g., `\%{}'. If so, remove - # this empty group too - if i < length and \ - pp[i].chtype == chunk_type(GROUP) \ - and len(pp[i].data) == 0: - del pp[i] - length = length-1 - - elif hist.inargs and s(buf, ch.data) in inargsselves: - # This is the special processing of the - # arguments of the \begin{funcdesc}... or - # \funcline... arguments - # \, --> , \[ --> [, \] --> ] - ch.chtype = chunk_type(PLAIN) - - elif s(buf, ch.data) == 'renewcommand': - # \renewcommand{\indexsubitem}.... - i, length = i-1, length-1 - del pp[i] - length, newi = getnextarg(length, buf, pp, i) - if newi-i == 1 \ - and i < length \ - and pp[i].chtype == chunk_type(CSNAME) \ - and s(buf, pp[i].data) == 'indexsubitem': - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - text = flattext(buf, pp[i:newi]) - if text[:1] != '(' or text[-1:] != ')': - raise error, 'expected indexsubitme enclosed in braces' - words = string.split(text[1:-1]) - hist.indexsubitem = words - del text, words - else: - print 'WARNING: renewcommand with unsupported arg removed' - del pp[i:newi] - length = length - (newi-i) - - elif s(buf, ch.data) == 'item': - ch.chtype = chunk_type(CSLINE) - length, newi = getoptarg(length, buf, pp, i) - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - i, length = i+1, length+1 - - elif s(buf, ch.data) == 'ttindex': - idxsi = hist.indexsubitem - - cat_class = '' - if len(idxsi) >= 2 and idxsi[1] in \ - ('method', 'function', 'protocol'): - command = 'findex' - elif len(idxsi) >= 2 and idxsi[1] in \ - ('exception', 'object'): - command = 'vindex' - else: - print 'WARNING: can\'t categorize ' + `idxsi` + ' for \'ttindex\' command' - command = 'cindex' - - if not cat_class: - cat_class = '('+string.join(idxsi)+')' - - ch.chtype = chunk_type(CSLINE) - ch.data = command - - length, newi = getnextarg(length, buf, pp, i) - arg = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - - cat_arg = [chunk(PLAIN, ch.where, cat_class)] - - # determine what should be set in roman, and - # what in tt-font - if command in regindices: - - arg = [chunk(CSNAME, ch.where, 't'), \ - chunk(GROUP, ch.where, arg)] - else: - cat_arg = [chunk(CSNAME, ch.where, 'r'), \ - chunk(GROUP, ch.where, cat_arg)] - - ingroupch = arg + \ - [chunk(PLAIN, ch.where, ' ')] + \ - cat_arg - - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - - elif s(buf, ch.data) == 'ldots': - # \ldots --> \dots{} --> @dots{} - ch.data = 'dots' - if i == length \ - or pp[i].chtype != chunk_type(GROUP) \ - or pp[i].data != []: - pp.insert(i, chunk(GROUP, ch.where, [])) - i, length = i+1, length+1 - elif s(buf, ch.data) in wordsselves: - # \UNIX --> UNIX - ch.chtype = chunk_type(PLAIN) - if i != length \ - and pp[i].chtype == chunk_type(GROUP) \ - and pp[i].data == []: - del pp[i] - length = length-1 - elif s(buf, ch.data) in for_texi: - pass - - elif s(buf, ch.data) == 'e': - # \e --> \ - ch.data = '\\' - ch.chtype = chunk_type(PLAIN) - elif (s(buf, ch.data) == 'lineiii') or\ - (s(buf, ch.data) == 'lineii'): - # This is the most tricky one - # \lineiii{a1}{a2}[{a3}] --> - # @item @<cts. of itemargmacro>{a1} - # a2 [ -- a3] - # - ##print 'LINEIIIIII!!!!!!!' -## wobj = Wobj().init() -## dumpit(buf, wobj.write, pp[i-1:i+5]) -## print '--->' + wobj.data + '<----' - if not hist.inenv: - raise error, \ - 'no environment for lineiii' - if (hist.inenv[0] != 'tableiii') and\ - (hist.inenv[0] != 'tableii'): - raise error, \ - 'wrong command (' + \ - s(buf, ch.data)+ \ - ') in wrong environment (' \ - + `hist.inenv[0]` + ')' - ch.chtype = chunk_type(CSLINE) - ch.data = 'item' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = [chunk(CSNAME, 0, \ - hist.itemargmacro), \ - chunk(GROUP, 0, pp[i:newi])] - del pp[i:newi] - length = length - (newi-i) -## print 'ITEM ARG: --->', -## wobj = Wobj().init() -## dumpit(buf, wobj.write, ingroupch) -## print wobj.data, '<---' - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - grouppos = i - i, length = i+1, length+1 - length, i = getnextarg(length, buf, pp, i) - length, newi = getnextarg(length, buf, pp, i) - if newi > i: - # we have a 3rd arg - pp.insert(i, chunk(PLAIN, ch.where, ' --- ')) - i = newi + 1 - length = length + 1 -## pp[grouppos].data = pp[grouppos].data \ -## + [chunk(PLAIN, ch.where, ' ')] \ -## + pp[i:newi] -## del pp[i:newi] -## length = length - (newi-i) - if length != len(pp): - raise 'IN LINEIII IS THE ERR', `i` - - elif s(buf, ch.data) in ('chapter', 'section', 'subsection', 'subsubsection'): - #\xxxsection{A} ----> - # @node A, , , - # @xxxsection A - ## also: remove commas and quotes - ch.chtype = chunk_type(CSLINE) - length, newi = getnextarg(length, buf, pp, i) - afternodenamecmd = next_command_p(length, buf, pp, newi, 'nodename') - if afternodenamecmd < 0: - cp1 = crcopy(pp[i:newi]) - pp[i:newi] = [\ - chunk(GROUP, ch.where, \ - pp[i:newi])] - length, newi = length - (newi-i) + 1, \ - i+1 - text = flattext(buf, cp1) - text = invent_node_names(text) - else: - length, endarg = getnextarg(length, buf, pp, afternodenamecmd) - cp1 = crcopy(pp[afternodenamecmd:endarg]) - del pp[newi:endarg] - length = length - (endarg-newi) - - pp[i:newi] = [\ - chunk(GROUP, ch.where, \ - pp[i:newi])] - length, newi = length - (newi-i) + 1, \ - i + 1 - text = flattext(buf, cp1) - if text[-1] == '.': - text = text[:-1] -## print 'FLATTEXT:', `text` - if text in hist.nodenames: - print 'WARNING: node name ' + `text` + ' already used' - out.doublenodes.append(text) - else: - hist.nodenames.append(text) - text = rm_commas_etc(text) - pp[i-1:i-1] = [\ - chunk(CSLINE, ch.where, 'node'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, text+', , ,')\ - ])] - i, length = newi+2, length+2 - - elif s(buf,ch.data) == 'funcline': - # fold it to a very short environment - pp[i-1:i-1] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, hist.command)])] - i, length = i+2, length+2 - length, i = do_funcdesc(length, buf, pp, i) - - elif s(buf,ch.data) == 'dataline': - pp[i-1:i-1] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, hist.command)])] - i, length = i+2, length+2 - length, i = do_datadesc(length, buf, pp, i) - - elif s(buf,ch.data) == 'excline': - pp[i-1:i-1] = [\ - chunk(CSLINE, ch.where, 'end'), \ - chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, hist.command)])] - i, length = i+2, length+2 - length, i = do_excdesc(length, buf, pp, i) - - - elif s(buf, ch.data) == 'index': - #\index{A} ---> - # @cindex A - ch.chtype = chunk_type(CSLINE) - ch.data = 'cindex' - length, newi = getnextarg(length, buf, pp, i) - - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - elif s(buf, ch.data) == 'bifuncindex': - ch.chtype = chunk_type(CSLINE) - ch.data = 'findex' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - - ingroupch.append(chunk(PLAIN, ch.where, ' ')) - ingroupch.append(chunk(CSNAME, ch.where, 'r')) - ingroupch.append(chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, \ - '(built-in function)')])) - - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - - elif s(buf, ch.data) == 'obindex': - ch.chtype = chunk_type(CSLINE) - ch.data = 'findex' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - - ingroupch.append(chunk(PLAIN, ch.where, ' ')) - ingroupch.append(chunk(CSNAME, ch.where, 'r')) - ingroupch.append(chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, \ - '(object)')])) - - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - - elif s(buf, ch.data) == 'opindex': - ch.chtype = chunk_type(CSLINE) - ch.data = 'findex' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - - ingroupch.append(chunk(PLAIN, ch.where, ' ')) - ingroupch.append(chunk(CSNAME, ch.where, 'r')) - ingroupch.append(chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, \ - '(operator)')])) - - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - - elif s(buf, ch.data) == 'bimodindex': - ch.chtype = chunk_type(CSLINE) - ch.data = 'pindex' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - - ingroupch.append(chunk(PLAIN, ch.where, ' ')) - ingroupch.append(chunk(CSNAME, ch.where, 'r')) - ingroupch.append(chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, \ - '(built-in)')])) - - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - elif s(buf, ch.data) == 'sectcode': - ch.data = 'code' - - - elif s(buf, ch.data) == 'stmodindex': - ch.chtype = chunk_type(CSLINE) - # use the program index as module index - ch.data = 'pindex' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = pp[i:newi] - del pp[i:newi] - length = length - (newi-i) - - ingroupch.append(chunk(PLAIN, ch.where, ' ')) - ingroupch.append(chunk(CSNAME, ch.where, 'r')) - ingroupch.append(chunk(GROUP, ch.where, [\ - chunk(PLAIN, ch.where, \ - '(standard)')])) - - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - length, i = length+1, i+1 - - - elif s(buf, ch.data) == 'stindex': - # XXX must actually go to newindex st - wh = ch.where - ch.chtype = chunk_type(CSLINE) - ch.data = 'cindex' - length, newi = getnextarg(length, buf, pp, i) - ingroupch = [chunk(CSNAME, wh, 'code'), \ - chunk(GROUP, wh, pp[i:newi])] - - del pp[i:newi] - length = length - (newi-i) - - t = ingroupch[:] - t.append(chunk(PLAIN, wh, ' statement')) - - pp.insert(i, chunk(GROUP, wh, t)) - i, length = i+1, length+1 - - pp.insert(i, chunk(CSLINE, wh, 'cindex')) - i, length = i+1, length+1 - - t = ingroupch[:] - t.insert(0, chunk(PLAIN, wh, 'statement, ')) - - pp.insert(i, chunk(GROUP, wh, t)) - i, length = i+1, length+1 - - - elif s(buf, ch.data) == 'indexii': - #\indexii{A}{B} ---> - # @cindex A B - # @cindex B, A - length, newi = getnextarg(length, buf, pp, i) - cp11 = pp[i:newi] - cp21 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - cp12 = pp[i:newi] - cp22 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - - ch.chtype = chunk_type(CSLINE) - ch.data = 'cindex' - pp.insert(i, chunk(GROUP, ch.where, cp11 + [\ - chunk(PLAIN, ch.where, ' ')] + cp12)) - i, length = i+1, length+1 - pp[i:i] = [chunk(CSLINE, ch.where, 'cindex'), \ - chunk(GROUP, ch.where, cp22 + [\ - chunk(PLAIN, ch.where, ', ')]+ cp21)] - i, length = i+2, length+2 - - elif s(buf, ch.data) == 'indexiii': - length, newi = getnextarg(length, buf, pp, i) - cp11 = pp[i:newi] - cp21 = crcopy(pp[i:newi]) - cp31 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - cp12 = pp[i:newi] - cp22 = crcopy(pp[i:newi]) - cp32 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - cp13 = pp[i:newi] - cp23 = crcopy(pp[i:newi]) - cp33 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - - ch.chtype = chunk_type(CSLINE) - ch.data = 'cindex' - pp.insert(i, chunk(GROUP, ch.where, cp11 + [\ - chunk(PLAIN, ch.where, ' ')] + cp12 \ - + [chunk(PLAIN, ch.where, ' ')] \ - + cp13)) - i, length = i+1, length+1 - pp[i:i] = [chunk(CSLINE, ch.where, 'cindex'), \ - chunk(GROUP, ch.where, cp22 + [\ - chunk(PLAIN, ch.where, ' ')]+ cp23\ - + [chunk(PLAIN, ch.where, ', ')] +\ - cp21)] - i, length = i+2, length+2 - pp[i:i] = [chunk(CSLINE, ch.where, 'cindex'), \ - chunk(GROUP, ch.where, cp33 + [\ - chunk(PLAIN, ch.where, ', ')]+ cp31\ - + [chunk(PLAIN, ch.where, ' ')] +\ - cp32)] - i, length = i+2, length+2 - - - elif s(buf, ch.data) == 'indexiv': - length, newi = getnextarg(length, buf, pp, i) - cp11 = pp[i:newi] - cp21 = crcopy(pp[i:newi]) - cp31 = crcopy(pp[i:newi]) - cp41 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - cp12 = pp[i:newi] - cp22 = crcopy(pp[i:newi]) - cp32 = crcopy(pp[i:newi]) - cp42 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - cp13 = pp[i:newi] - cp23 = crcopy(pp[i:newi]) - cp33 = crcopy(pp[i:newi]) - cp43 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - length, newi = getnextarg(length, buf, pp, i) - cp14 = pp[i:newi] - cp24 = crcopy(pp[i:newi]) - cp34 = crcopy(pp[i:newi]) - cp44 = crcopy(pp[i:newi]) - del pp[i:newi] - length = length - (newi-i) - - ch.chtype = chunk_type(CSLINE) - ch.data = 'cindex' - ingroupch = cp11 + \ - spacech + cp12 + \ - spacech + cp13 + \ - spacech + cp14 - pp.insert(i, chunk(GROUP, ch.where, ingroupch)) - i, length = i+1, length+1 - ingroupch = cp22 + \ - spacech + cp23 + \ - spacech + cp24 + \ - commach + cp21 - pp[i:i] = cindexch + [\ - chunk(GROUP, ch.where, ingroupch)] - i, length = i+2, length+2 - ingroupch = cp33 + \ - spacech + cp34 + \ - commach + cp31 + \ - spacech + cp32 - pp[i:i] = cindexch + [\ - chunk(GROUP, ch.where, ingroupch)] - i, length = i+2, length+2 - ingroupch = cp44 + \ - commach + cp41 + \ - spacech + cp42 + \ - spacech + cp43 - pp[i:i] = cindexch + [\ - chunk(GROUP, ch.where, ingroupch)] - i, length = i+2, length+2 - - - - else: - print 'don\'t know what to do with keyword ' + `s(buf, ch.data)` - - - -re_atsign = regex.compile('[@{}]') -re_newline = regex.compile('\n') - -def dumpit(buf, wm, pp): - - global out - - i, length = 0, len(pp) - - addspace = 0 - - while 1: - if len(pp) != length: - raise 'FATAL', 'inconsistent length' - if i == length: - break - ch = pp[i] - i = i + 1 - - if addspace: - dospace = 1 - addspace = 0 - else: - dospace = 0 - - if ch.chtype == chunk_type(CSNAME): - wm('@' + s(buf, ch.data)) - if s(buf, ch.data) == 'node' and \ - pp[i].chtype == chunk_type(PLAIN) and \ - s(buf, pp[i].data) in out.doublenodes: - ##XXX doesnt work yet?? - wm(' ZZZ-' + zfill(`i`, 4)) - if s(buf, ch.data)[0] in string.letters: - addspace = 1 - elif ch.chtype == chunk_type(PLAIN): - if dospace and s(buf, ch.data) not in (' ', '\t'): - wm(' ') - text = s(buf, ch.data) - while 1: - pos = re_atsign.search(text) - if pos < 0: - break - wm(text[:pos] + '@' + text[pos]) - text = text[pos+1:] - wm(text) - elif ch.chtype == chunk_type(GROUP): - wm('{') - dumpit(buf, wm, ch.data) - wm('}') - elif ch.chtype == chunk_type(DENDLINE): - wm('\n\n') - while i != length and pp[i].chtype in \ - (chunk_type(DENDLINE), chunk_type(ENDLINE)): - i = i + 1 - elif ch.chtype == chunk_type(OTHER): - wm(s(buf, ch.data)) - elif ch.chtype == chunk_type(ACTIVE): - wm(s(buf, ch.data)) - elif ch.chtype == chunk_type(ENDLINE): - wm('\n') - elif ch.chtype == chunk_type(CSLINE): - if i >= 2 and pp[i-2].chtype not in \ - (chunk_type(ENDLINE), chunk_type(DENDLINE)) \ - and (pp[i-2].chtype != chunk_type(PLAIN) \ - or s(buf, pp[i-2].data)[-1] != '\n'): - - wm('\n') - wm('@' + s(buf, ch.data)) - if i == length: - raise error, 'CSLINE expected another chunk' - if pp[i].chtype != chunk_type(GROUP): - raise error, 'CSLINE expected GROUP' - if type(pp[i].data) != type([]): - raise error, 'GROUP chould contain []-data' - - wobj = Wobj().init() - dumpit(buf, wobj.write, pp[i].data) - i = i + 1 - text = wobj.data - del wobj - if text: - wm(' ') - while 1: - pos = re_newline.search(text) - if pos < 0: - break - print 'WARNING: found newline in csline arg' - wm(text[:pos] + ' ') - text = text[pos+1:] - wm(text) - if i >= length or \ - pp[i].chtype not in (chunk_type(CSLINE), \ - chunk_type(ENDLINE), chunk_type(DENDLINE)) \ - and (pp[i].chtype != chunk_type(PLAIN) \ - or s(buf, pp[i].data)[0] != '\n'): - wm('\n') - - elif ch.chtype == chunk_type(COMMENT): -## print 'COMMENT: previous chunk =', pp[i-2] -## if pp[i-2].chtype == chunk_type(PLAIN): -## print 'PLAINTEXT =', `s(buf, pp[i-2].data)` - if s(buf, ch.data) and \ - regex.match('^[ \t]*$', s(buf, ch.data)) < 0: - if i >= 2 and pp[i-2].chtype not in \ - (chunk_type(ENDLINE), chunk_type(DENDLINE)) \ - and not (pp[i-2].chtype == chunk_type(PLAIN) \ - and regex.match('\\(.\\|\n\\)*[ \t]*\n$', s(buf, pp[i-2].data)) >= 0): - print 'ADDING NEWLINE' - wm('\n') - wm('@c ' + s(buf, ch.data)) - elif ch.chtype == chunk_type(IGNORE): - pass - else: - try: - str = `s(buf, ch.data)` - except TypeError: - str = `ch.data` - if len(str) > 400: - str = str[:400] + '...' - print 'warning:', ch.chtype, 'not handled, data ' + str - - - -def main(): - outfile = None - headerfile = 'texipre.dat' - trailerfile = 'texipost.dat' - - try: - opts, args = getopt.getopt(sys.argv[1:], 'o:h:t:') - except getopt.error: - args = [] - - if not args: - print 'usage: partparse [-o outfile] [-h headerfile]', - print '[-t trailerfile] file ...' - sys.exit(2) - - for opt, arg in opts: - if opt == '-o': outfile = arg - if opt == '-h': headerfile = arg - if opt == '-t': trailerfile = arg - - if not outfile: - root, ext = os.path.splitext(args[0]) - outfile = root + '.texi' - - if outfile in args: - print 'will not overwrite input file', outfile - sys.exit(2) - - outf = open(outfile, 'w') - outf.write(open(headerfile, 'r').read()) - - for file in args: - if len(args) > 1: print '='*20, file, '='*20 - buf = open(file, 'r').read() - w, pp = parseit(buf) - startchange() - changeit(buf, pp) - dumpit(buf, outf.write, pp) - - outf.write(open(trailerfile, 'r').read()) - - outf.close() - -main() diff --git a/Doc/tools/texi2html.py b/Doc/tools/texi2html.py deleted file mode 100644 index a1c0ebd44a..0000000000 --- a/Doc/tools/texi2html.py +++ /dev/null @@ -1,1500 +0,0 @@ -#! /usr/local/bin/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 fexible error handling -# How about icons ? - -import os -import regex -import regsub -import string - -MAGIC = '\\input texinfo' - -cmprog = regex.compile('^@\([a-z]+\)\([ \t]\|$\)') # Command (line-oriented) -blprog = regex.compile('^[ \t]*$') # Blank line -kwprog = regex.compile('@[a-z]+') # Keyword (embedded, usually with {} args) -spprog = regex.compile('[\n@{}&<>]') # Special characters in running text -miprog = regex.compile( \ - '^\* \([^:]*\):\(:\|[ \t]*\([^\t,\n.]+\)\([^ \t\n]*\)\)[ \t\n]*') - # menu item (Yuck!) - - -class Node: - __doc__ = """ - 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. """ - - 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 = [] - self.type = 0 - self.cont = '' - - def write (self, *lines): - for line in lines: - self.lines.append (line) - - 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): - if nodename: - if string.lower(nodename) == '(dir)': - addr = '../dir.html' - else: - addr = makefile(nodename) - self.write(label, ': <A HREF="', addr, '" TYPE="', \ - label, '">', nodename, '</A> \n') - - - def finalize(self): - length = len (self.lines) - self.text = string.joinfields (self.lines, '') - self.lines = [] - self.write ('<BR> <HR>\n') - if self.cont != self.next: - self.link('Cont', self.cont) - self.link('Next', self.next) - self.link('Prev', self.prev) - self.link('Up', self.up) - if self.name <> self.topname: - self.link('Top', self.topname) - self.write ('<BR> <HR> <P>\n') - links = string.joinfields (self.lines, '') - self.lines = [] - - self.prologue = \ - '<!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN">\n' + \ - '<!- Converted with texi2html and Python>\n' + \ - '<P>\n<HEAD>\n' + \ - '<TITLE>' + self.title + '</TITLE>\n' + \ - '</HEAD>\n<BODY>\n<P>\n' + \ - links - - if length > 20: - self.epilogue = links + '</BODY>\n' - else: - self.epilogue = '</BODY>\n' - - -class TexinfoParser: - - # 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.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.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 (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) >= 0): - line = fp.readline() - lineno = lineno + 1 - if line[:len(MAGIC)] <> MAGIC: - raise SyntaxError, 'file does not begin with '+`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 - if cmprog.match(line) >= 0: - a, b = cmprog.regs[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) - elif blprog.match(line) >= 0 and \ - 'format' not in self.stack and \ - 'example' not in self.stack: - if accu: - if not self.skip: - self.process(accu) - 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 = string.joinfields(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.skip, self.stack, - if accu: print accu[0][:30], - if accu[0][30:] or accu[1:]: print '...', - print - if self.stack and self.stack[-1] == 'menu': - # XXX should be done differently - for line in accu: - if miprog.match(line) < 0: - line = string.strip(line) + '\n' - self.expand(line) - continue - (bgn, end), (a, b), (c, d), (e, f), (g, h) = \ - miprog.regs[:5] - label = line[a:b] - nodename = line[c:d] - if nodename[0] == ':': nodename = label - else: nodename = line[e:f] - punct = line[g:h] - self.write('<DT><A HREF="', \ - makefile(nodename), \ - '" TYPE=Menu>', nodename, \ - '</A>', punct, '\n<DD>') - self.expand(line[end:]) - else: - text = string.joinfields(accu, '') - self.expand(text) - - # Write a string, expanding embedded @-commands - def expand(self, text): - stack = [] - i = 0 - n = len(text) - while i < n: - start = i - i = spprog.search(text, i) - if i < 0: - self.write(text[start:]) - break - self.write(text[start:i]) - c = text[i] - i = i+1 - if c == '\n': - if self.nofill > 0: - self.write('<P>\n') - else: - 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 '+`c` - start = i - while i < n and text[i] in string.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', `file` - return - if self.debugging: - print '--> file', `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 - if self.debugging: - print '<-- file', `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('(C)') - def open_copyright(self): self.write('(C)') - def close_copyright(self): pass - - def open_minus(self): self.write('-') - def close_minus(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 = string.splitfields(text, ',') - n = len(args) - for i in range(n): - args[i] = string.strip(args[i]) - while len(args) < 3: args.append('') - node = args[0] - file = args[2] - self.write('`', file, '\', node `', node, '\'') - - def makeref(self): - text = self.collectsavings() - args = string.splitfields(text, ',') - n = len(args) - for i in range(n): - args[i] = string.strip(args[i]) - 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>') - - # --- 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>') - - open_t = open_code - close_t = close_code - - def open_dfn(self): self.write('<DFN>') - def close_dfn(self): self.write('</DFN>') - - def open_emph(self): self.write('<I>') - def close_emph(self): self.write('</I>') - - open_i = open_emph - close_i = close_emph - - def open_footnote(self): - # if self.savetext <> None: - # print '*** Recursive footnote -- expect weirdness' - id = len(self.footnotes) + 1 - self.write('<A NAME="footnoteref', `id`, \ - '" HREF="#footnotetext', `id`, '">(', `id`, ')</A>') - # self.savetext = '' - self.startsaving () - - def close_footnote(self): - id = len(self.footnotes) + 1 - # self.footnotes.append(`id`, self.savetext) - self.footnotes.append(`id`, self.collectsavings()) - # self.savetext = None - - def writefootnotes(self): - self.write('<H2>---------- Footnotes ----------</H2>\n') - for id, text in self.footnotes: - self.write('<A NAME="footnotetext', id, \ - '" HREF="#footnoteref', id, '">(', \ - id, ')</A>\n', text, '<P>\n') - self.footnotes = [] - - def open_file(self): self.write('<FILE>') - def close_file(self): self.write('</FILE>') - - 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('<B>') - def close_strong(self): self.write('</B>') - - open_b = open_strong - close_b = close_strong - - 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>') - - open_titlefont = open_ - close_titlefont = close_ - - def open_small(self): pass - def close_small(self): pass - - def command(self, line): - a, b = cmprog.regs[1] - cmd = line[a:b] - args = string.strip(line[b:]) - if self.debugging > 1: - print 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 = string.split(args) - 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 = string.splitfields (args, ' ') - key = fields[0] - if len(fields) == 1: - value = 1 - else: - value = string.joinfields (fields[1:], ' ') - self.values[key]=value - print self.values - - 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): - print self.stack - print self.stackinfo - if self.stackinfo[len(self.stack) + 1]: - self.skip = self.skip - 1 - del self.stackinfo[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 - - end_ifclear = end_ifset - - 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): - print args - self.startsaving() - self.expand (args) - self.title = self.collectsavings () - print self.title - 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 = string.splitfields(args, ',') - while len(parts) < 4: parts.append('') - for i in range(4): parts[i] = string.strip(parts[i]) - 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 '--- 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 - # No idea what this means, but this is what latex2html writes - # self.write('<!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN">\n') - # self.write('<!- Converted with texi2html and Python>\n') - # self.write ('<P>\n<HEAD>\n') - # self.write('<TITLE>', title, '</TITLE>\n') - # self.write ('</HEAD>\n<BODY>\n<P>\n<BR> <HR>\n') - # self.link('Next', next) - # self.link('Prev', prev) - # self.link('Up', up) - # if self.nodename <> self.topname: - # self.link('Top', self.topname) - # self.write ('<BR> <HR> <P>\n') - self.node = Node (self.dirname, self.nodename, self.topname, \ - title, next, prev, up) - - def link(self, label, nodename): - if nodename: - if string.lower(nodename) == '(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 + `i` + '.' - args = x + ' ' + args - self.contents.append(level, args, self.nodename) - self.write('<', type, '>') - self.expand(args) - self.write('</', type, '>\n') - if self.debugging: - 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>\n') - for level, title, node in self.contents: - if level <= maxlevel: - self.write('<LI>', '. '*level, '<A HREF="', \ - makefile(node), '">') - self.expand(title) - self.write('</A> ', node, '\n') - self.write('</UL>\n') - - # --- 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): - # Insert <args> blank lines - if args: - try: - n = string.atoi(args) - except string.atoi_error: - n = 1 - else: - n = 1 - self.write('<P>\n'*max(n, 0)) - - 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{' + name + '}') - for word in rest: self.expand(' ' + makevar(word)) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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{' + name + '}') - # If there are too many arguments, show them - for word in rest: self.expand(' ' + word) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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{' + datatype + '} @b{' + name + '}') - for word in rest: self.expand(' ' + makevar(word)) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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{' + datatype + '} @b{' + name + '}') - # If there are too many arguments, show them - for word in rest: self.expand(' ' + word) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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{' + name + '}') - # If there are too many arguments, show them - for word in rest: self.expand(' ' + word) - self.expand(' -- ' + category + ' of ' + classname) - self.write('<DD>\n') - self.index('vr', name + ' @r{of ' + 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{' + name + '}') - for word in rest: self.expand(' ' + makevar(word)) - self.expand(' -- ' + category + ' on ' + classname) - self.write('<DD>\n') - self.index('fn', name + ' @r{on ' + 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{' + name + '}') - for word in rest: self.expand(' ' + word) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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 do_item(self, args): - if self.itemindex: self.index(self.itemindex, args) - if self.itemarg: - if self.itemarg[0] == '@' and self.itemarg[1:2] and \ - self.itemarg[1] in string.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('<DD>') - else: - self.write('<LI>') - self.expand(args) - self.write(' ') - do_itemx = do_item # XXX Should suppress leading blank line - - # --- Enumerations, displays, quotations --- - # XXX Most of these should increase the indentation somehow - - def bgn_quotation(self, args): self.write('<P>') - def end_quotation(self): self.write('<P>\n') - - def bgn_example(self, args): - self.nofill = self.nofill + 1 - self.write('<PRE><CODE>') - def end_example(self): - self.write('</CODE></PRE>') - 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 - - def bgn_display(self, args): - self.nofill = self.nofill + 1 - self.write('<PRE>\n') - def end_display(self): - self.write('</PRE>\n') - self.nofill = self.nofill - 1 - - def bgn_format(self, args): - self.nofill = self.nofill + 1 - self.write('<PRE><CODE>\n') - def end_format(self): - self.write('</CODE></PRE>\n') - self.nofill = self.nofill - 1 - - 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('<H2>Menu</H2><DL COMPACT>\n') - def end_menu(self): self.write('</DL>\n') - - 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', `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) - - def do_synindex(self, args): - words = string.split(args) - 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 = string.split(args) - for name in words: - if self.whichindex.has_key(name): - self.prindex(name) - else: - print '*** No index named', `name` - - def prindex(self, name): - iscodeindex = (name not in self.noncodeindices) - index = self.whichindex[name] - if not index: return - if self.debugging: - print '--- Generating', self.indextitle[name], 'index' - # The node already provides a title - index1 = [] - junkprog = regex.compile('^\(@[a-z]+\)?{') - for key, node in index: - sortkey = string.lower(key) - # Remove leading `@cmd{' from sort key - # -- don't bother about the matching `}' - oldsortkey = sortkey - while 1: - i = junkprog.match(sortkey) - if i < 0: break - sortkey = sortkey[i:] - index1.append(sortkey, key, node) - del index[:] - index1.sort() - self.write('<DL COMPACT>\n') - for sortkey, key, node in index1: - if self.debugging > 1: print key, ':', node - self.write('<DT>') - if iscodeindex: key = '@code{' + key + '}' - self.expand(key) - self.write('<DD><A HREF="', makefile(node), \ - '">', node, '</A>\n') - 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 string.ljust(cmd, 20), self.unknown[cmd] - - -# 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 = regex.compile('[@{} ]') -def findwordend(str, i, n): - level = 0 - while i < n: - i = fwprog.search(str, i) - if i < 0: break - 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): - return fixfunnychars(nodename) + '.html' - - -# Characters that are perfectly safe in filenames and hyperlinks -goodchars = string.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 = string.index(sequence, 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 - parser = TexinfoParser() - while sys.argv[1:2] == ['-d']: - parser.debugging = parser.debugging + 1 - del sys.argv[1:2] - if sys.argv[1] == '-c': - parser.cont = 1 - del sys.argv[1] - if len(sys.argv) <> 3: - print 'usage: texi2html [-d] [-d] [-c] inputfile outputdirectory' - sys.exit(2) - file = sys.argv[1] - parser.setdirname(sys.argv[2]) - if file == '-': - fp = sys.stdin - else: - parser.setincludedir(os.path.dirname(file)) - try: - fp = open(file, 'r') - except IOError, msg: - print file, ':', msg - sys.exit(1) - parser.parse(fp) - fp.close() - parser.report() - - -test() - -# Emacs local variables -# -# Local Variables: -# py-indent-offset: 8 -# End: diff --git a/Doc/tools/text2latex.py b/Doc/tools/text2latex.py deleted file mode 100644 index 93d0587d30..0000000000 --- a/Doc/tools/text2latex.py +++ /dev/null @@ -1,55 +0,0 @@ -import os -import sys -import regex -import regsub -import string -import getopt - -def main(): - process(sys.stdin, sys.stdout) - -dashes = regex.compile('^-+[ \t]*$') -equals = regex.compile('^=+[ \t]*$') -stars = regex.compile('^\*+[ \t]*$') -blank = regex.compile('^[ \t]*$') -indented = regex.compile('^\( *\t\| \)[ \t]*[^ \t]') - -def process(fi, fo): - inverbatim = 0 - line = '\n' - nextline = fi.readline() - while nextline: - prevline = line - line = nextline - nextline = fi.readline() - fmt = None - if dashes.match(nextline) >= 0: - fmt = '\\subsection{%s}\n' - elif equals.match(nextline) >= 0: - fmt = '\\section{%s}\n' - elif stars.match(nextline) >= 0: - fmt = '\\chapter{%s}\n' - if fmt: - nextline = '\n' - line = fmt % string.strip(line) - if '(' in line: - line = regsub.gsub('[a-zA-Z0-9_]+()', - '{\\\\tt \\0}', line) - elif inverbatim: - if blank.match(line) >= 0 and \ - indented.match(nextline) < 0: - inverbatim = 0 - fo.write('\\end{verbatim}\n') - else: - if indented.match(line) >= 0 and \ - blank.match(prevline) >= 0: - inverbatim = 1 - fo.write('\\begin{verbatim}\n') - if inverbatim: - line = string.expandtabs(line, 4) - elif not fmt and '(' in line: - line = regsub.gsub('[a-zA-Z0-9_]+()', - '\\\\code{\\0}', line) - fo.write(line) - -main() diff --git a/Doc/tools/whichlibs b/Doc/tools/whichlibs deleted file mode 100755 index 56287cbee3..0000000000 --- a/Doc/tools/whichlibs +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -sed -n 's/^\\input{\(lib[a-zA-Z0-9_]*\)}.*/\1.tex/p' lib.tex diff --git a/Doc/tut.tex b/Doc/tut.tex deleted file mode 100644 index 97ebeb77da..0000000000 --- a/Doc/tut.tex +++ /dev/null @@ -1,3863 +0,0 @@ -\documentstyle[twoside,11pt,myformat]{report} - -\title{Python Tutorial} - -\input{boilerplate} - -\begin{document} - -\pagenumbering{roman} - -\maketitle - -\input{copyright} - -\begin{abstract} - -\noindent -Python is a simple, yet powerful programming language that bridges the -gap between C and shell programming, and is thus ideally suited for -``throw-away programming'' -and rapid prototyping. Its syntax is put -together from constructs borrowed from a variety of other languages; -most prominent are influences from ABC, C, Modula-3 and Icon. - -The Python interpreter is easily extended with new functions and data -types implemented in C. Python is also suitable as an extension -language for highly customizable C applications such as editors or -window managers. - -Python is available for various operating systems, amongst which -several flavors of {\UNIX}, Amoeba, the Apple Macintosh O.S., -and MS-DOS. - -This tutorial introduces the reader informally to the basic concepts -and features of the Python language and system. It helps to have a -Python interpreter handy for hands-on experience, but as the examples -are self-contained, the tutorial can be read off-line as well. - -For a description of standard objects and modules, see the {\em Python -Library Reference} document. The {\em Python Reference Manual} gives -a more formal definition of the language. - -\end{abstract} - -\pagebreak -{ -\parskip = 0mm -\tableofcontents -} - -\pagebreak - -\pagenumbering{arabic} - - -\chapter{Whetting Your Appetite} - -If you ever wrote a large shell script, you probably know this -feeling: you'd love to add yet another feature, but it's already so -slow, and so big, and so complicated; or the feature involves a system -call or other function that is only accessible from C \ldots Usually -the problem at hand isn't serious enough to warrant rewriting the -script in C; perhaps because the problem requires variable-length -strings or other data types (like sorted lists of file names) that are -easy in the shell but lots of work to implement in C; or perhaps just -because you're not sufficiently familiar with C. - -In such cases, Python may be just the language for you. Python is -simple to use, but it is a real programming language, offering much -more structure and support for large programs than the shell has. On -the other hand, it also offers much more error checking than C, and, -being a {\em very-high-level language}, it has high-level data types -built in, such as flexible arrays and dictionaries that would cost you -days to implement efficiently in C. Because of its more general data -types Python is applicable to a much larger problem domain than {\em -Awk} or even {\em Perl}, yet many things are at least as easy in -Python as in those languages. - -Python allows you to split up your program in modules that can be -reused in other Python programs. It comes with a large collection of -standard modules that you can use as the basis of your programs --- or -as examples to start learning to program in Python. There are also -built-in modules that provide things like file I/O, system calls, -sockets, and even a generic interface to window systems (STDWIN). - -Python is an interpreted language, which can save you considerable time -during program development because no compilation and linking is -necessary. The interpreter can be used interactively, which makes it -easy to experiment with features of the language, to write throw-away -programs, or to test functions during bottom-up program development. -It is also a handy desk calculator. - -Python allows writing very compact and readable programs. Programs -written in Python are typically much shorter than equivalent C -programs, for several reasons: -\begin{itemize} -\item -the high-level data types allow you to express complex operations in a -single statement; -\item -statement grouping is done by indentation instead of begin/end -brackets; -\item -no variable or argument declarations are necessary. -\end{itemize} - -Python is {\em extensible}: if you know how to program in C it is easy -to add a new built-in -function or -module to the interpreter, either to -perform critical operations at maximum speed, or to link Python -programs to libraries that may only be available in binary form (such -as a vendor-specific graphics library). Once you are really hooked, -you can link the Python interpreter into an application written in C -and use it as an extension or command language for that application. - -By the way, the language is named after the BBC show ``Monty -Python's Flying Circus'' and has nothing to do with nasty reptiles... - -\section{Where From Here} - -Now that you are all excited about Python, you'll want to examine it -in some more detail. Since the best way to learn a language is -using it, you are invited here to do so. - -In the next chapter, the mechanics of using the interpreter are -explained. This is rather mundane information, but essential for -trying out the examples shown later. - -The rest of the tutorial introduces various features of the Python -language and system though examples, beginning with simple -expressions, statements and data types, through functions and modules, -and finally touching upon advanced concepts like exceptions -and user-defined classes. - -When you're through with the tutorial (or just getting bored), you -should read the Library Reference, which gives complete (though terse) -reference material about built-in and standard types, functions and -modules that can save you a lot of time when writing Python programs. - - -\chapter{Using the Python Interpreter} - -\section{Invoking the Interpreter} - -The Python interpreter is usually installed as {\tt /usr/local/bin/python} -on those machines where it is available; putting {\tt /usr/local/bin} in -your {\UNIX} shell's search path makes it possible to start it by -typing the command - -\bcode\begin{verbatim} -python -\end{verbatim}\ecode -% -to the shell. Since the choice of the directory where the interpreter -lives is an installation option, other places are possible; check with -your local Python guru or system administrator. (E.g., {\tt -/usr/local/python} is a popular alternative location.) - -The interpreter operates somewhat like the {\UNIX} shell: when called -with standard input connected to a tty device, it reads and executes -commands interactively; when called with a file name argument or with -a file as standard input, it reads and executes a {\em script} from -that file. - -A third way of starting the interpreter is -``{\tt python -c command [arg] ...}'', which -executes the statement(s) in {\tt command}, analogous to the shell's -{\tt -c} option. Since Python statements often contain spaces or other -characters that are special to the shell, it is best to quote {\tt -command} in its entirety with double quotes. - -Note that there is a difference between ``{\tt python file}'' and -``{\tt python $<$file}''. In the latter case, input requests from the -program, such as calls to {\tt input()} and {\tt raw_input()}, are -satisfied from {\em file}. Since this file has already been read -until the end by the parser before the program starts executing, the -program will encounter EOF immediately. In the former case (which is -usually what you want) they are satisfied from whatever file or device -is connected to standard input of the Python interpreter. - -When a script file is used, it is sometimes useful to be able to run -the script and enter interactive mode afterwards. This can be done by -passing {\tt -i} before the script. (This does not work if the script -is read from standard input, for the same reason as explained in the -previous paragraph.) - -\subsection{Argument Passing} - -When known to the interpreter, the script name and additional -arguments thereafter are passed to the script in the variable {\tt -sys.argv}, which is a list of strings. Its length is at least one; -when no script and no arguments are given, {\tt sys.argv[0]} is an -empty string. When the script name is given as {\tt '-'} (meaning -standard input), {\tt sys.argv[0]} is set to {\tt '-'}. When {\tt -c -command} is used, {\tt sys.argv[0]} is set to {\tt '-c'}. Options -found after {\tt -c command} are not consumed by the Python -interpreter's option processing but left in {\tt sys.argv} for the -command to handle. - -\subsection{Interactive Mode} - -When commands are read from a tty, the interpreter is said to be in -{\em interactive\ mode}. In this mode it prompts for the next command -with the {\em primary\ prompt}, usually three greater-than signs ({\tt ->>>}); for continuation lines it prompts with the -{\em secondary\ prompt}, -by default three dots ({\tt ...}). Typing an EOF (Control-D) -at the primary prompt causes the interpreter to exit with a zero exit -status. - -The interpreter prints a welcome message stating its version number -and a copyright notice before printing the first prompt, e.g.: - -\bcode\begin{verbatim} -python -Python 1.3 (Oct 13 1995) -Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam ->>> -\end{verbatim}\ecode - -\section{The Interpreter and its Environment} - -\subsection{Error Handling} - -When an error occurs, the interpreter prints an error -message and a stack trace. In interactive mode, it then returns to -the primary prompt; when input came from a file, it exits with a -nonzero exit status after printing -the stack trace. (Exceptions handled by an {\tt except} clause in a -{\tt try} statement are not errors in this context.) Some errors are -unconditionally fatal and cause an exit with a nonzero exit; this -applies to internal inconsistencies and some cases of running out of -memory. All error messages are written to the standard error stream; -normal output from the executed commands is written to standard -output. - -Typing the interrupt character (usually Control-C or DEL) to the -primary or secondary prompt cancels the input and returns to the -primary prompt.% -\footnote{ - A problem with the GNU Readline package may prevent this. -} -Typing an interrupt while a command is executing raises the {\tt -KeyboardInterrupt} exception, which may be handled by a {\tt try} -statement. - -\subsection{The Module Search Path} - -When a module named {\tt spam} is imported, the interpreter searches -for a file named {\tt spam.py} in the list of directories specified by -the environment variable {\tt PYTHONPATH}. It has the same syntax as -the {\UNIX} shell variable {\tt PATH}, i.e., a list of colon-separated -directory names. When {\tt PYTHONPATH} is not set, or when the file -is not found there, the search continues in an installation-dependent -default path, usually {\tt .:/usr/local/lib/python}. - -Actually, modules are searched in the list of directories given by the -variable {\tt sys.path} which is initialized from {\tt PYTHONPATH} and -the installation-dependent default. This allows Python programs that -know what they're doing to modify or replace the module search path. -See the section on Standard Modules later. - -\subsection{``Compiled'' Python files} - -As an important speed-up of the start-up time for short programs that -use a lot of standard modules, if a file called {\tt spam.pyc} exists -in the directory where {\tt spam.py} is found, this is assumed to -contain an already-``compiled'' version of the module {\tt spam}. The -modification time of the version of {\tt spam.py} used to create {\tt -spam.pyc} is recorded in {\tt spam.pyc}, and the file is ignored if -these don't match. - -Whenever {\tt spam.py} is successfully compiled, an attempt is made to -write the compiled version to {\tt spam.pyc}. It is not an error if -this attempt fails; if for any reason the file is not written -completely, the resulting {\tt spam.pyc} file will be recognized as -invalid and thus ignored later. - -\subsection{Executable Python scripts} - -On BSD'ish {\UNIX} systems, Python scripts can be made directly -executable, like shell scripts, by putting the line - -\bcode\begin{verbatim} -#! /usr/local/bin/python -\end{verbatim}\ecode -% -(assuming that's the name of the interpreter) at the beginning of the -script and giving the file an executable mode. The {\tt \#!} must be -the first two characters of the file. - -\subsection{The Interactive Startup File} - -When you use Python interactively, it is frequently handy to have some -standard commands executed every time the interpreter is started. You -can do this by setting an environment variable named {\tt -PYTHONSTARTUP} to the name of a file containing your start-up -commands. This is similar to the {\tt .profile} feature of the UNIX -shells. - -This file is only read in interactive sessions, not when Python reads -commands from a script, and not when {\tt /dev/tty} is given as the -explicit source of commands (which otherwise behaves like an -interactive session). It is executed in the same name space where -interactive commands are executed, so that objects that it defines or -imports can be used without qualification in the interactive session. -You can also change the prompts {\tt sys.ps1} and {\tt sys.ps2} in -this file. - -If you want to read an additional start-up file from the current -directory, you can program this in the global start-up file, e.g. -\verb\execfile('.pythonrc')\. If you want to use the startup file -in a script, you must write this explicitly in the script, e.g. -\verb\import os;\ \verb\execfile(os.environ['PYTHONSTARTUP'])\. - -\section{Interactive Input Editing and History Substitution} - -Some versions of the Python interpreter support editing of the current -input line and history substitution, similar to facilities found in -the Korn shell and the GNU Bash shell. This is implemented using the -{\em GNU\ Readline} library, which supports Emacs-style and vi-style -editing. This library has its own documentation which I won't -duplicate here; however, the basics are easily explained. - -Perhaps the quickest check to see whether command line editing is -supported is typing Control-P to the first Python prompt you get. If -it beeps, you have command line editing. If nothing appears to -happen, or if \verb/^P/ is echoed, you can skip the rest of this -section. - -\subsection{Line Editing} - -If supported, input line editing is active whenever the interpreter -prints a primary or secondary prompt. The current line can be edited -using the conventional Emacs control characters. The most important -of these are: C-A (Control-A) moves the cursor to the beginning of the -line, C-E to the end, C-B moves it one position to the left, C-F to -the right. Backspace erases the character to the left of the cursor, -C-D the character to its right. C-K kills (erases) the rest of the -line to the right of the cursor, C-Y yanks back the last killed -string. C-underscore undoes the last change you made; it can be -repeated for cumulative effect. - -\subsection{History Substitution} - -History substitution works as follows. All non-empty input lines -issued are saved in a history buffer, and when a new prompt is given -you are positioned on a new line at the bottom of this buffer. C-P -moves one line up (back) in the history buffer, C-N moves one down. -Any line in the history buffer can be edited; an asterisk appears in -front of the prompt to mark a line as modified. Pressing the Return -key passes the current line to the interpreter. C-R starts an -incremental reverse search; C-S starts a forward search. - -\subsection{Key Bindings} - -The key bindings and some other parameters of the Readline library can -be customized by placing commands in an initialization file called -{\tt \$HOME/.inputrc}. Key bindings have the form - -\bcode\begin{verbatim} -key-name: function-name -\end{verbatim}\ecode -% -or - -\bcode\begin{verbatim} -"string": function-name -\end{verbatim}\ecode -% -and options can be set with - -\bcode\begin{verbatim} -set option-name value -\end{verbatim}\ecode -% -For example: - -\bcode\begin{verbatim} -# I prefer vi-style editing: -set editing-mode vi -# Edit using a single line: -set horizontal-scroll-mode On -# Rebind some keys: -Meta-h: backward-kill-word -"\C-u": universal-argument -"\C-x\C-r": re-read-init-file -\end{verbatim}\ecode -% -Note that the default binding for TAB in Python is to insert a TAB -instead of Readline's default filename completion function. If you -insist, you can override this by putting - -\bcode\begin{verbatim} -TAB: complete -\end{verbatim}\ecode -% -in your {\tt \$HOME/.inputrc}. (Of course, this makes it hard to type -indented continuation lines...) - -\subsection{Commentary} - -This facility is an enormous step forward compared to previous -versions of the interpreter; however, some wishes are left: It would -be nice if the proper indentation were suggested on continuation lines -(the parser knows if an indent token is required next). The -completion mechanism might use the interpreter's symbol table. A -command to check (or even suggest) matching parentheses, quotes etc. -would also be useful. - - -\chapter{An Informal Introduction to Python} - -In the following examples, input and output are distinguished by the -presence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat -the example, you must type everything after the prompt, when the -prompt appears; lines that do not begin with a prompt are output from -the interpreter.% -\footnote{ - I'd prefer to use different fonts to distinguish input - from output, but the amount of LaTeX hacking that would require - is currently beyond my ability. -} -Note that a secondary prompt on a line by itself in an example means -you must type a blank line; this is used to end a multi-line command. - -\section{Using Python as a Calculator} - -Let's try some simple Python commands. Start the interpreter and wait -for the primary prompt, {\tt >>>}. (It shouldn't take long.) - -\subsection{Numbers} - -The interpreter acts as a simple calculator: you can type an -expression at it and it will write the value. Expression syntax is -straightforward: the operators {\tt +}, {\tt -}, {\tt *} and {\tt /} -work just like in most other languages (e.g., Pascal or C); parentheses -can be used for grouping. For example: - -\bcode\begin{verbatim} ->>> 2+2 -4 ->>> # This is a comment -... 2+2 -4 ->>> 2+2 # and a comment on the same line as code -4 ->>> (50-5*6)/4 -5 ->>> # Integer division returns the floor: -... 7/3 -2 ->>> 7/-3 --3 ->>> -\end{verbatim}\ecode -% -Like in C, the equal sign ({\tt =}) is used to assign a value to a -variable. The value of an assignment is not written: - -\bcode\begin{verbatim} ->>> width = 20 ->>> height = 5*9 ->>> width * height -900 ->>> -\end{verbatim}\ecode -% -A value can be assigned to several variables simultaneously: - -\bcode\begin{verbatim} ->>> x = y = z = 0 # Zero x, y and z ->>> x -0 ->>> y -0 ->>> z -0 ->>> -\end{verbatim}\ecode -% -There is full support for floating point; operators with mixed type -operands convert the integer operand to floating point: - -\bcode\begin{verbatim} ->>> 4 * 2.5 / 3.3 -3.0303030303 ->>> 7.0 / 2 -3.5 ->>> -\end{verbatim}\ecode - -\subsection{Strings} - -Besides numbers, Python can also manipulate strings, enclosed in -single quotes or double quotes: - -\bcode\begin{verbatim} ->>> 'spam eggs' -'spam eggs' ->>> 'doesn\'t' -"doesn't" ->>> "doesn't" -"doesn't" ->>> '"Yes," he said.' -'"Yes," he said.' ->>> "\"Yes,\" he said." -'"Yes," he said.' ->>> '"Isn\'t," she said.' -'"Isn\'t," she said.' ->>> -\end{verbatim}\ecode -% -Strings are written the same way as they are typed for input: inside -quotes and with quotes and other funny characters escaped by backslashes, -to show the precise value. The string is enclosed in double quotes if -the string contains a single quote and no double quotes, else it's -enclosed in single quotes. (The {\tt print} statement, described later, -can be used to write strings without quotes or escapes.) - -Strings can be concatenated (glued together) with the {\tt +} -operator, and repeated with {\tt *}: - -\bcode\begin{verbatim} ->>> word = 'Help' + 'A' ->>> word -'HelpA' ->>> '<' + word*5 + '>' -'<HelpAHelpAHelpAHelpAHelpA>' ->>> -\end{verbatim}\ecode -% -Strings can be subscripted (indexed); like in C, the first character of -a string has subscript (index) 0. - -There is no separate character type; a character is simply a string of -size one. Like in Icon, substrings can be specified with the {\em -slice} notation: two indices separated by a colon. - -\bcode\begin{verbatim} ->>> word[4] -'A' ->>> word[0:2] -'He' ->>> word[2:4] -'lp' ->>> -\end{verbatim}\ecode -% -Slice indices have useful defaults; an omitted first index defaults to -zero, an omitted second index defaults to the size of the string being -sliced. - -\bcode\begin{verbatim} ->>> word[:2] # The first two characters -'He' ->>> word[2:] # All but the first two characters -'lpA' ->>> -\end{verbatim}\ecode -% -Here's a useful invariant of slice operations: \verb\s[:i] + s[i:]\ -equals \verb\s\. - -\bcode\begin{verbatim} ->>> word[:2] + word[2:] -'HelpA' ->>> word[:3] + word[3:] -'HelpA' ->>> -\end{verbatim}\ecode -% -Degenerate slice indices are handled gracefully: an index that is too -large is replaced by the string size, an upper bound smaller than the -lower bound returns an empty string. - -\bcode\begin{verbatim} ->>> word[1:100] -'elpA' ->>> word[10:] -'' ->>> word[2:1] -'' ->>> -\end{verbatim}\ecode -% -Indices may be negative numbers, to start counting from the right. -For example: - -\bcode\begin{verbatim} ->>> word[-1] # The last character -'A' ->>> word[-2] # The last-but-one character -'p' ->>> word[-2:] # The last two characters -'pA' ->>> word[:-2] # All but the last two characters -'Hel' ->>> -\end{verbatim}\ecode -% -But note that -0 is really the same as 0, so it does not count from -the right! - -\bcode\begin{verbatim} ->>> word[-0] # (since -0 equals 0) -'H' ->>> -\end{verbatim}\ecode -% -Out-of-range negative slice indices are truncated, but don't try this -for single-element (non-slice) indices: - -\bcode\begin{verbatim} ->>> word[-100:] -'HelpA' ->>> word[-10] # error -Traceback (innermost last): - File "<stdin>", line 1 -IndexError: string index out of range ->>> -\end{verbatim}\ecode -% -The best way to remember how slices work is to think of the indices as -pointing {\em between} characters, with the left edge of the first -character numbered 0. Then the right edge of the last character of a -string of {\tt n} characters has index {\tt n}, for example: - -\bcode\begin{verbatim} - +---+---+---+---+---+ - | H | e | l | p | A | - +---+---+---+---+---+ - 0 1 2 3 4 5 --5 -4 -3 -2 -1 -\end{verbatim}\ecode -% -The first row of numbers gives the position of the indices 0...5 in -the string; the second row gives the corresponding negative indices. -The slice from \verb\i\ to \verb\j\ consists of all characters between -the edges labeled \verb\i\ and \verb\j\, respectively. - -For nonnegative indices, the length of a slice is the difference of -the indices, if both are within bounds, e.g., the length of -\verb\word[1:3]\ is 2. - -The built-in function {\tt len()} returns the length of a string: - -\bcode\begin{verbatim} ->>> s = 'supercalifragilisticexpialidocious' ->>> len(s) -34 ->>> -\end{verbatim}\ecode - -\subsection{Lists} - -Python knows a number of {\em compound} data types, used to group -together other values. The most versatile is the {\em list}, which -can be written as a list of comma-separated values (items) between -square brackets. List items need not all have the same type. - -\bcode\begin{verbatim} ->>> a = ['spam', 'eggs', 100, 1234] ->>> a -['spam', 'eggs', 100, 1234] ->>> -\end{verbatim}\ecode -% -Like string indices, list indices start at 0, and lists can be sliced, -concatenated and so on: - -\bcode\begin{verbatim} ->>> a[0] -'spam' ->>> a[3] -1234 ->>> a[-2] -100 ->>> a[1:-1] -['eggs', 100] ->>> a[:2] + ['bacon', 2*2] -['spam', 'eggs', 'bacon', 4] ->>> 3*a[:3] + ['Boe!'] -['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!'] ->>> -\end{verbatim}\ecode -% -Unlike strings, which are {\em immutable}, it is possible to change -individual elements of a list: - -\bcode\begin{verbatim} ->>> a -['spam', 'eggs', 100, 1234] ->>> a[2] = a[2] + 23 ->>> a -['spam', 'eggs', 123, 1234] ->>> -\end{verbatim}\ecode -% -Assignment to slices is also possible, and this can even change the size -of the list: - -\bcode\begin{verbatim} ->>> # Replace some items: -... a[0:2] = [1, 12] ->>> a -[1, 12, 123, 1234] ->>> # Remove some: -... a[0:2] = [] ->>> a -[123, 1234] ->>> # Insert some: -... a[1:1] = ['bletch', 'xyzzy'] ->>> a -[123, 'bletch', 'xyzzy', 1234] ->>> a[:0] = a # Insert (a copy of) itself at the beginning ->>> a -[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] ->>> -\end{verbatim}\ecode -% -The built-in function {\tt len()} also applies to lists: - -\bcode\begin{verbatim} ->>> len(a) -8 ->>> -\end{verbatim}\ecode -% -It is possible to nest lists (create lists containing other lists), -for example: - -\bcode\begin{verbatim} ->>> q = [2, 3] ->>> p = [1, q, 4] ->>> len(p) -3 ->>> p[1] -[2, 3] ->>> p[1][0] -2 ->>> p[1].append('xtra') # See section 5.1 ->>> p -[1, [2, 3, 'xtra'], 4] ->>> q -[2, 3, 'xtra'] ->>> -\end{verbatim}\ecode -% -Note that in the last example, {\tt p[1]} and {\tt q} really refer to -the same object! We'll come back to {\em object semantics} later. - -\section{First Steps Towards Programming} - -Of course, we can use Python for more complicated tasks than adding -two and two together. For instance, we can write an initial -subsequence of the {\em Fibonacci} series as follows: - -\bcode\begin{verbatim} ->>> # Fibonacci series: -... # the sum of two elements defines the next -... a, b = 0, 1 ->>> while b < 10: -... print b -... a, b = b, a+b -... -1 -1 -2 -3 -5 -8 ->>> -\end{verbatim}\ecode -% -This example introduces several new features. - -\begin{itemize} - -\item -The first line contains a {\em multiple assignment}: the variables -{\tt a} and {\tt b} simultaneously get the new values 0 and 1. On the -last line this is used again, demonstrating that the expressions on -the right-hand side are all evaluated first before any of the -assignments take place. - -\item -The {\tt while} loop executes as long as the condition (here: {\tt b < -10}) remains true. In Python, like in C, any non-zero integer value is -true; zero is false. The condition may also be a string or list value, -in fact any sequence; anything with a non-zero length is true, empty -sequences are false. The test used in the example is a simple -comparison. The standard comparison operators are written the same as -in C: {\tt <}, {\tt >}, {\tt ==}, {\tt <=}, {\tt >=} and {\tt !=}. - -\item -The {\em body} of the loop is {\em indented}: indentation is Python's -way of grouping statements. Python does not (yet!) provide an -intelligent input line editing facility, so you have to type a tab or -space(s) for each indented line. In practice you will prepare more -complicated input for Python with a text editor; most text editors have -an auto-indent facility. When a compound statement is entered -interactively, it must be followed by a blank line to indicate -completion (since the parser cannot guess when you have typed the last -line). - -\item -The {\tt print} statement writes the value of the expression(s) it is -given. It differs from just writing the expression you want to write -(as we did earlier in the calculator examples) in the way it handles -multiple expressions and strings. Strings are printed without quotes, -and a space is inserted between items, so you can format things nicely, -like this: - -\bcode\begin{verbatim} ->>> i = 256*256 ->>> print 'The value of i is', i -The value of i is 65536 ->>> -\end{verbatim}\ecode -% -A trailing comma avoids the newline after the output: - -\bcode\begin{verbatim} ->>> a, b = 0, 1 ->>> while b < 1000: -... print b, -... a, b = b, a+b -... -1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ->>> -\end{verbatim}\ecode -% -Note that the interpreter inserts a newline before it prints the next -prompt if the last line was not completed. - -\end{itemize} - - -\chapter{More Control Flow Tools} - -Besides the {\tt while} statement just introduced, Python knows the -usual control flow statements known from other languages, with some -twists. - -\section{If Statements} - -Perhaps the most well-known statement type is the {\tt if} statement. -For example: - -\bcode\begin{verbatim} ->>> if x < 0: -... x = 0 -... print 'Negative changed to zero' -... elif x == 0: -... print 'Zero' -... elif x == 1: -... print 'Single' -... else: -... print 'More' -... -\end{verbatim}\ecode -% -There can be zero or more {\tt elif} parts, and the {\tt else} part is -optional. The keyword `{\tt elif}' is short for `{\tt else if}', and is -useful to avoid excessive indentation. An {\tt if...elif...elif...} -sequence is a substitute for the {\em switch} or {\em case} statements -found in other languages. - -\section{For Statements} - -The {\tt for} statement in Python differs a bit from what you may be -used to in C or Pascal. Rather than always iterating over an -arithmetic progression of numbers (like in Pascal), or leaving the user -completely free in the iteration test and step (as C), Python's {\tt -for} statement iterates over the items of any sequence (e.g., a list -or a string), in the order that they appear in the sequence. For -example (no pun intended): - -\bcode\begin{verbatim} ->>> # Measure some strings: -... a = ['cat', 'window', 'defenestrate'] ->>> for x in a: -... print x, len(x) -... -cat 3 -window 6 -defenestrate 12 ->>> -\end{verbatim}\ecode -% -It is not safe to modify the sequence being iterated over in the loop -(this can only happen for mutable sequence types, i.e., lists). If -you need to modify the list you are iterating over, e.g., duplicate -selected items, you must iterate over a copy. The slice notation -makes this particularly convenient: - -\bcode\begin{verbatim} ->>> for x in a[:]: # make a slice copy of the entire list -... if len(x) > 6: a.insert(0, x) -... ->>> a -['defenestrate', 'cat', 'window', 'defenestrate'] ->>> -\end{verbatim}\ecode - -\section{The {\tt range()} Function} - -If you do need to iterate over a sequence of numbers, the built-in -function {\tt range()} comes in handy. It generates lists containing -arithmetic progressions, e.g.: - -\bcode\begin{verbatim} ->>> range(10) -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ->>> -\end{verbatim}\ecode -% -The given end point is never part of the generated list; {\tt range(10)} -generates a list of 10 values, exactly the legal indices for items of a -sequence of length 10. It is possible to let the range start at another -number, or to specify a different increment (even negative): - -\bcode\begin{verbatim} ->>> range(5, 10) -[5, 6, 7, 8, 9] ->>> range(0, 10, 3) -[0, 3, 6, 9] ->>> range(-10, -100, -30) -[-10, -40, -70] ->>> -\end{verbatim}\ecode -% -To iterate over the indices of a sequence, combine {\tt range()} and -{\tt len()} as follows: - -\bcode\begin{verbatim} ->>> a = ['Mary', 'had', 'a', 'little', 'lamb'] ->>> for i in range(len(a)): -... print i, a[i] -... -0 Mary -1 had -2 a -3 little -4 lamb ->>> -\end{verbatim}\ecode - -\section{Break and Continue Statements, and Else Clauses on Loops} - -The {\tt break} statement, like in C, breaks out of the smallest -enclosing {\tt for} or {\tt while} loop. - -The {\tt continue} statement, also borrowed from C, continues with the -next iteration of the loop. - -Loop statements may have an {\tt else} clause; it is executed when the -loop terminates through exhaustion of the list (with {\tt for}) or when -the condition becomes false (with {\tt while}), but not when the loop is -terminated by a {\tt break} statement. This is exemplified by the -following loop, which searches for prime numbers: - -\bcode\begin{verbatim} ->>> for n in range(2, 10): -... for x in range(2, n): -... if n % x == 0: -... print n, 'equals', x, '*', n/x -... break -... else: -... print n, 'is a prime number' -... -2 is a prime number -3 is a prime number -4 equals 2 * 2 -5 is a prime number -6 equals 2 * 3 -7 is a prime number -8 equals 2 * 4 -9 equals 3 * 3 ->>> -\end{verbatim}\ecode - -\section{Pass Statements} - -The {\tt pass} statement does nothing. -It can be used when a statement is required syntactically but the -program requires no action. -For example: - -\bcode\begin{verbatim} ->>> while 1: -... pass # Busy-wait for keyboard interrupt -... -\end{verbatim}\ecode - -\section{Defining Functions} - -We can create a function that writes the Fibonacci series to an -arbitrary boundary: - -\bcode\begin{verbatim} ->>> def fib(n): # write Fibonacci series up to n -... a, b = 0, 1 -... while b < n: -... print b, -... a, b = b, a+b -... ->>> # Now call the function we just defined: -... fib(2000) -1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 ->>> -\end{verbatim}\ecode -% -The keyword {\tt def} introduces a function {\em definition}. It must -be followed by the function name and the parenthesized list of formal -parameters. The statements that form the body of the function starts at -the next line, indented by a tab stop. - -The {\em execution} of a function introduces a new symbol table used -for the local variables of the function. More precisely, all variable -assignments in a function store the value in the local symbol table; -whereas -variable references first look in the local symbol table, then -in the global symbol table, and then in the table of built-in names. -Thus, -global variables cannot be directly assigned a value within a -function (unless named in a {\tt global} statement), although -they may be referenced. - -The actual parameters (arguments) to a function call are introduced in -the local symbol table of the called function when it is called; thus, -arguments are passed using {\em call\ by\ value}.% -\footnote{ - Actually, {\em call by object reference} would be a better - description, since if a mutable object is passed, the caller - will see any changes the callee makes to it (e.g., items - inserted into a list). -} -When a function calls another function, a new local symbol table is -created for that call. - -A function definition introduces the function name in the -current -symbol table. The value -of the function name -has a type that is recognized by the interpreter as a user-defined -function. This value can be assigned to another name which can then -also be used as a function. This serves as a general renaming -mechanism: - -\bcode\begin{verbatim} ->>> fib -<function object at 10042ed0> ->>> f = fib ->>> f(100) -1 1 2 3 5 8 13 21 34 55 89 ->>> -\end{verbatim}\ecode -% -You might object that {\tt fib} is not a function but a procedure. In -Python, like in C, procedures are just functions that don't return a -value. In fact, technically speaking, procedures do return a value, -albeit a rather boring one. This value is called {\tt None} (it's a -built-in name). Writing the value {\tt None} is normally suppressed by -the interpreter if it would be the only value written. You can see it -if you really want to: - -\bcode\begin{verbatim} ->>> print fib(0) -None ->>> -\end{verbatim}\ecode -% -It is simple to write a function that returns a list of the numbers of -the Fibonacci series, instead of printing it: - -\bcode\begin{verbatim} ->>> def fib2(n): # return Fibonacci series up to n -... result = [] -... a, b = 0, 1 -... while b < n: -... result.append(b) # see below -... a, b = b, a+b -... return result -... ->>> f100 = fib2(100) # call it ->>> f100 # write the result -[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] ->>> -\end{verbatim}\ecode -% -This example, as usual, demonstrates some new Python features: - -\begin{itemize} - -\item -The {\tt return} statement returns with a value from a function. {\tt -return} without an expression argument is used to return from the middle -of a procedure (falling off the end also returns from a procedure), in -which case the {\tt None} value is returned. - -\item -The statement {\tt result.append(b)} calls a {\em method} of the list -object {\tt result}. A method is a function that `belongs' to an -object and is named {\tt obj.methodname}, where {\tt obj} is some -object (this may be an expression), and {\tt methodname} is the name -of a method that is defined by the object's type. Different types -define different methods. Methods of different types may have the -same name without causing ambiguity. (It is possible to define your -own object types and methods, using {\em classes}, as discussed later -in this tutorial.) -The method {\tt append} shown in the example, is defined for -list objects; it adds a new element at the end of the list. In this -example -it is equivalent to {\tt result = result + [b]}, but more efficient. - -\end{itemize} - - -\chapter{Odds and Ends} - -This chapter describes some things you've learned about already in -more detail, and adds some new things as well. - -\section{More on Lists} - -The list data type has some more methods. Here are all of the methods -of lists objects: - -\begin{description} - -\item[{\tt insert(i, x)}] -Insert an item at a given position. The first argument is the index of -the element before which to insert, so {\tt a.insert(0, x)} inserts at -the front of the list, and {\tt a.insert(len(a), x)} is equivalent to -{\tt a.append(x)}. - -\item[{\tt append(x)}] -Equivalent to {\tt a.insert(len(a), x)}. - -\item[{\tt index(x)}] -Return the index in the list of the first item whose value is {\tt x}. -It is an error if there is no such item. - -\item[{\tt remove(x)}] -Remove the first item from the list whose value is {\tt x}. -It is an error if there is no such item. - -\item[{\tt sort()}] -Sort the items of the list, in place. - -\item[{\tt reverse()}] -Reverse the elements of the list, in place. - -\item[{\tt count(x)}] -Return the number of times {\tt x} appears in the list. - -\end{description} - -An example that uses all list methods: - -\bcode\begin{verbatim} ->>> a = [66.6, 333, 333, 1, 1234.5] ->>> print a.count(333), a.count(66.6), a.count('x') -2 1 0 ->>> a.insert(2, -1) ->>> a.append(333) ->>> a -[66.6, 333, -1, 333, 1, 1234.5, 333] ->>> a.index(333) -1 ->>> a.remove(333) ->>> a -[66.6, -1, 333, 1, 1234.5, 333] ->>> a.reverse() ->>> a -[333, 1234.5, 1, 333, -1, 66.6] ->>> a.sort() ->>> a -[-1, 1, 66.6, 333, 333, 1234.5] ->>> -\end{verbatim}\ecode - -\section{The {\tt del} statement} - -There is a way to remove an item from a list given its index instead -of its value: the {\tt del} statement. This can also be used to -remove slices from a list (which we did earlier by assignment of an -empty list to the slice). For example: - -\bcode\begin{verbatim} ->>> a -[-1, 1, 66.6, 333, 333, 1234.5] ->>> del a[0] ->>> a -[1, 66.6, 333, 333, 1234.5] ->>> del a[2:4] ->>> a -[1, 66.6, 1234.5] ->>> -\end{verbatim}\ecode -% -{\tt del} can also be used to delete entire variables: - -\bcode\begin{verbatim} ->>> del a ->>> -\end{verbatim}\ecode -% -Referencing the name {\tt a} hereafter is an error (at least until -another value is assigned to it). We'll find other uses for {\tt del} -later. - -\section{Tuples and Sequences} - -We saw that lists and strings have many common properties, e.g., -indexing and slicing operations. They are two examples of {\em -sequence} data types. Since Python is an evolving language, other -sequence data types may be added. There is also another standard -sequence data type: the {\em tuple}. - -A tuple consists of a number of values separated by commas, for -instance: - -\bcode\begin{verbatim} ->>> t = 12345, 54321, 'hello!' ->>> t[0] -12345 ->>> t -(12345, 54321, 'hello!') ->>> # Tuples may be nested: -... u = t, (1, 2, 3, 4, 5) ->>> u -((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) ->>> -\end{verbatim}\ecode -% -As you see, on output tuples are alway enclosed in parentheses, so -that nested tuples are interpreted correctly; they may be input with -or without surrounding parentheses, although often parentheses are -necessary anyway (if the tuple is part of a larger expression). - -Tuples have many uses, e.g., (x, y) coordinate pairs, employee records -from a database, etc. Tuples, like strings, are immutable: it is not -possible to assign to the individual items of a tuple (you can -simulate much of the same effect with slicing and concatenation, -though). - -A special problem is the construction of tuples containing 0 or 1 -items: the syntax has some extra quirks to accommodate these. Empty -tuples are constructed by an empty pair of parentheses; a tuple with -one item is constructed by following a value with a comma -(it is not sufficient to enclose a single value in parentheses). -Ugly, but effective. For example: - -\bcode\begin{verbatim} ->>> empty = () ->>> singleton = 'hello', # <-- note trailing comma ->>> len(empty) -0 ->>> len(singleton) -1 ->>> singleton -('hello',) ->>> -\end{verbatim}\ecode -% -The statement {\tt t = 12345, 54321, 'hello!'} is an example of {\em -tuple packing}: the values {\tt 12345}, {\tt 54321} and {\tt 'hello!'} -are packed together in a tuple. The reverse operation is also -possible, e.g.: - -\bcode\begin{verbatim} ->>> x, y, z = t ->>> -\end{verbatim}\ecode -% -This is called, appropriately enough, {\em tuple unpacking}. Tuple -unpacking requires that the list of variables on the left has the same -number of elements as the length of the tuple. Note that multiple -assignment is really just a combination of tuple packing and tuple -unpacking! - -Occasionally, the corresponding operation on lists is useful: {\em list -unpacking}. This is supported by enclosing the list of variables in -square brackets: - -\bcode\begin{verbatim} ->>> a = ['spam', 'eggs', 100, 1234] ->>> [a1, a2, a3, a4] = a ->>> -\end{verbatim}\ecode - -\section{Dictionaries} - -Another useful data type built into Python is the {\em dictionary}. -Dictionaries are sometimes found in other languages as ``associative -memories'' or ``associative arrays''. Unlike sequences, which are -indexed by a range of numbers, dictionaries are indexed by {\em keys}, -which are strings (the use of non-string values as keys -is supported, but beyond the scope of this tutorial). -It is best to think of a dictionary as an unordered set of -{\em key:value} pairs, with the requirement that the keys are unique -(within one dictionary). -A pair of braces creates an empty dictionary: \verb/{}/. -Placing a comma-separated list of key:value pairs within the -braces adds initial key:value pairs to the dictionary; this is also the -way dictionaries are written on output. - -The main operations on a dictionary are storing a value with some key -and extracting the value given the key. It is also possible to delete -a key:value pair -with {\tt del}. -If you store using a key that is already in use, the old value -associated with that key is forgotten. It is an error to extract a -value using a non-existent key. - -The {\tt keys()} method of a dictionary object returns a list of all the -keys used in the dictionary, in random order (if you want it sorted, -just apply the {\tt sort()} method to the list of keys). To check -whether a single key is in the dictionary, use the \verb/has_key()/ -method of the dictionary. - -Here is a small example using a dictionary: - -\bcode\begin{verbatim} ->>> tel = {'jack': 4098, 'sape': 4139} ->>> tel['guido'] = 4127 ->>> tel -{'sape': 4139, 'guido': 4127, 'jack': 4098} ->>> tel['jack'] -4098 ->>> del tel['sape'] ->>> tel['irv'] = 4127 ->>> tel -{'guido': 4127, 'irv': 4127, 'jack': 4098} ->>> tel.keys() -['guido', 'irv', 'jack'] ->>> tel.has_key('guido') -1 ->>> -\end{verbatim}\ecode - -\section{More on Conditions} - -The conditions used in {\tt while} and {\tt if} statements above can -contain other operators besides comparisons. - -The comparison operators {\tt in} and {\tt not in} check whether a value -occurs (does not occur) in a sequence. The operators {\tt is} and {\tt -is not} compare whether two objects are really the same object; this -only matters for mutable objects like lists. All comparison operators -have the same priority, which is lower than that of all numerical -operators. - -Comparisons can be chained: e.g., {\tt a < b == c} tests whether {\tt a} -is less than {\tt b} and moreover {\tt b} equals {\tt c}. - -Comparisons may be combined by the Boolean operators {\tt and} and {\tt -or}, and the outcome of a comparison (or of any other Boolean -expression) may be negated with {\tt not}. These all have lower -priorities than comparison operators again; between them, {\tt not} has -the highest priority, and {\tt or} the lowest, so that -{\tt A and not B or C} is equivalent to {\tt (A and (not B)) or C}. Of -course, parentheses can be used to express the desired composition. - -The Boolean operators {\tt and} and {\tt or} are so-called {\em -shortcut} operators: their arguments are evaluated from left to right, -and evaluation stops as soon as the outcome is determined. E.g., if -{\tt A} and {\tt C} are true but {\tt B} is false, {\tt A and B and C} -does not evaluate the expression C. In general, the return value of a -shortcut operator, when used as a general value and not as a Boolean, is -the last evaluated argument. - -It is possible to assign the result of a comparison or other Boolean -expression to a variable. For example, - -\bcode\begin{verbatim} ->>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' ->>> non_null = string1 or string2 or string3 ->>> non_null -'Trondheim' ->>> -\end{verbatim}\ecode -% -Note that in Python, unlike C, assignment cannot occur inside expressions. - -\section{Comparing Sequences and Other Types} - -Sequence objects may be compared to other objects with the same -sequence type. The comparison uses {\em lexicographical} ordering: -first the first two items are compared, and if they differ this -determines the outcome of the comparison; if they are equal, the next -two items are compared, and so on, until either sequence is exhausted. -If two items to be compared are themselves sequences of the same type, -the lexicographical comparison is carried out recursively. If all -items of two sequences compare equal, the sequences are considered -equal. If one sequence is an initial subsequence of the other, the -shorted sequence is the smaller one. Lexicographical ordering for -strings uses the \ASCII{} ordering for individual characters. Some -examples of comparisons between sequences with the same types: - -\bcode\begin{verbatim} -(1, 2, 3) < (1, 2, 4) -[1, 2, 3] < [1, 2, 4] -'ABC' < 'C' < 'Pascal' < 'Python' -(1, 2, 3, 4) < (1, 2, 4) -(1, 2) < (1, 2, -1) -(1, 2, 3) = (1.0, 2.0, 3.0) -(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) -\end{verbatim}\ecode -% -Note that comparing objects of different types is legal. The outcome -is deterministic but arbitrary: the types are ordered by their name. -Thus, a list is always smaller than a string, a string is always -smaller than a tuple, etc. Mixed numeric types are compared according -to their numeric value, so 0 equals 0.0, etc.% -\footnote{ - The rules for comparing objects of different types should - not be relied upon; they may change in a future version of - the language. -} - - -\chapter{Modules} - -If you quit from the Python interpreter and enter it again, the -definitions you have made (functions and variables) are lost. -Therefore, if you want to write a somewhat longer program, you are -better off using a text editor to prepare the input for the interpreter -and running it with that file as input instead. This is known as creating a -{\em script}. As your program gets longer, you may want to split it -into several files for easier maintenance. You may also want to use a -handy function that you've written in several programs without copying -its definition into each program. - -To support this, Python has a way to put definitions in a file and use -them in a script or in an interactive instance of the interpreter. -Such a file is called a {\em module}; definitions from a module can be -{\em imported} into other modules or into the {\em main} module (the -collection of variables that you have access to in a script -executed at the top level -and in calculator mode). - -A module is a file containing Python definitions and statements. The -file name is the module name with the suffix {\tt .py} appended. Within -a module, the module's name (as a string) is available as the value of -the global variable {\tt __name__}. For instance, use your favorite text -editor to create a file called {\tt fibo.py} in the current directory -with the following contents: - -\bcode\begin{verbatim} -# Fibonacci numbers module - -def fib(n): # write Fibonacci series up to n - a, b = 0, 1 - while b < n: - print b, - a, b = b, a+b - -def fib2(n): # return Fibonacci series up to n - result = [] - a, b = 0, 1 - while b < n: - result.append(b) - a, b = b, a+b - return result -\end{verbatim}\ecode -% -Now enter the Python interpreter and import this module with the -following command: - -\bcode\begin{verbatim} ->>> import fibo ->>> -\end{verbatim}\ecode -% -This does not enter the names of the functions defined in -{\tt fibo} -directly in the current symbol table; it only enters the module name -{\tt fibo} -there. -Using the module name you can access the functions: - -\bcode\begin{verbatim} ->>> fibo.fib(1000) -1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ->>> fibo.fib2(100) -[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] ->>> fibo.__name__ -'fibo' ->>> -\end{verbatim}\ecode -% -If you intend to use a function often you can assign it to a local name: - -\bcode\begin{verbatim} ->>> fib = fibo.fib ->>> fib(500) -1 1 2 3 5 8 13 21 34 55 89 144 233 377 ->>> -\end{verbatim}\ecode - -\section{More on Modules} - -A module can contain executable statements as well as function -definitions. -These statements are intended to initialize the module. -They are executed only the -{\em first} -time the module is imported somewhere.% -\footnote{ - In fact function definitions are also `statements' that are - `executed'; the execution enters the function name in the - module's global symbol table. -} - -Each module has its own private symbol table, which is used as the -global symbol table by all functions defined in the module. -Thus, the author of a module can use global variables in the module -without worrying about accidental clashes with a user's global -variables. -On the other hand, if you know what you are doing you can touch a -module's global variables with the same notation used to refer to its -functions, -{\tt modname.itemname}. - -Modules can import other modules. -It is customary but not required to place all -{\tt import} -statements at the beginning of a module (or script, for that matter). -The imported module names are placed in the importing module's global -symbol table. - -There is a variant of the -{\tt import} -statement that imports names from a module directly into the importing -module's symbol table. -For example: - -\bcode\begin{verbatim} ->>> from fibo import fib, fib2 ->>> fib(500) -1 1 2 3 5 8 13 21 34 55 89 144 233 377 ->>> -\end{verbatim}\ecode -% -This does not introduce the module name from which the imports are taken -in the local symbol table (so in the example, {\tt fibo} is not -defined). - -There is even a variant to import all names that a module defines: - -\bcode\begin{verbatim} ->>> from fibo import * ->>> fib(500) -1 1 2 3 5 8 13 21 34 55 89 144 233 377 ->>> -\end{verbatim}\ecode -% -This imports all names except those beginning with an underscore -({\tt _}). - -\section{Standard Modules} - -Python comes with a library of standard modules, described in a separate -document (Python Library Reference). Some modules are built into the -interpreter; these provide access to operations that are not part of the -core of the language but are nevertheless built in, either for -efficiency or to provide access to operating system primitives such as -system calls. The set of such modules is a configuration option; e.g., -the {\tt amoeba} module is only provided on systems that somehow support -Amoeba primitives. One particular module deserves some attention: {\tt -sys}, which is built into every Python interpreter. The variables {\tt -sys.ps1} and {\tt sys.ps2} define the strings used as primary and -secondary prompts: - -\bcode\begin{verbatim} ->>> import sys ->>> sys.ps1 -'>>> ' ->>> sys.ps2 -'... ' ->>> sys.ps1 = 'C> ' -C> print 'Yuck!' -Yuck! -C> -\end{verbatim}\ecode -% -These two variables are only defined if the interpreter is in -interactive mode. - -The variable -{\tt sys.path} -is a list of strings that determine the interpreter's search path for -modules. -It is initialized to a default path taken from the environment variable -{\tt PYTHONPATH}, -or from a built-in default if -{\tt PYTHONPATH} -is not set. -You can modify it using standard list operations, e.g.: - -\bcode\begin{verbatim} ->>> import sys ->>> sys.path.append('/ufs/guido/lib/python') ->>> -\end{verbatim}\ecode - -\section{The {\tt dir()} function} - -The built-in function {\tt dir} is used to find out which names a module -defines. It returns a sorted list of strings: - -\bcode\begin{verbatim} ->>> import fibo, sys ->>> dir(fibo) -['__name__', 'fib', 'fib2'] ->>> dir(sys) -['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit', -'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace', -'stderr', 'stdin', 'stdout', 'version'] ->>> -\end{verbatim}\ecode -% -Without arguments, {\tt dir()} lists the names you have defined currently: - -\bcode\begin{verbatim} ->>> a = [1, 2, 3, 4, 5] ->>> import fibo, sys ->>> fib = fibo.fib ->>> dir() -['__name__', 'a', 'fib', 'fibo', 'sys'] ->>> -\end{verbatim}\ecode -% -Note that it lists all types of names: variables, modules, functions, etc. - -{\tt dir()} does not list the names of built-in functions and variables. -If you want a list of those, they are defined in the standard module -{\tt __builtin__}: - -\bcode\begin{verbatim} ->>> import __builtin__ ->>> dir(__builtin__) -['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError', -'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt', -'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError', -'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError', -'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce', -'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float', -'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long', -'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input', -'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange'] ->>> -\end{verbatim}\ecode - - -\chapter{Output Formatting} - -So far we've encountered two ways of writing values: {\em expression -statements} and the {\tt print} statement. (A third way is using the -{\tt write} method of file objects; the standard output file can be -referenced as {\tt sys.stdout}. See the Library Reference for more -information on this.) - -Often you'll want more control over the formatting of your output than -simply printing space-separated values. The key to nice formatting in -Python is to do all the string handling yourself; using string slicing -and concatenation operations you can create any lay-out you can imagine. -The standard module {\tt string} contains some useful operations for -padding strings to a given column width; these will be discussed shortly. -Finally, the \code{\%} operator (modulo) with a string left argument -interprets this string as a C sprintf format string to be applied to the -right argument, and returns the string resulting from this formatting -operation. - -One question remains, of course: how do you convert values to strings? -Luckily, Python has a way to convert any value to a string: just write -the value between reverse quotes (\verb/``/). Some examples: - -\bcode\begin{verbatim} ->>> x = 10 * 3.14 ->>> y = 200*200 ->>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...' ->>> print s -The value of x is 31.4, and y is 40000... ->>> # Reverse quotes work on other types besides numbers: -... p = [x, y] ->>> ps = `p` ->>> ps -'[31.4, 40000]' ->>> # Converting a string adds string quotes and backslashes: -... hello = 'hello, world\n' ->>> hellos = `hello` ->>> print hellos -'hello, world\012' ->>> # The argument of reverse quotes may be a tuple: -... `x, y, ('spam', 'eggs')` -"(31.4, 40000, ('spam', 'eggs'))" ->>> -\end{verbatim}\ecode -% -Here are two ways to write a table of squares and cubes: - -\bcode\begin{verbatim} ->>> import string ->>> for x in range(1, 11): -... print string.rjust(`x`, 2), string.rjust(`x*x`, 3), -... # Note trailing comma on previous line -... print string.rjust(`x*x*x`, 4) -... - 1 1 1 - 2 4 8 - 3 9 27 - 4 16 64 - 5 25 125 - 6 36 216 - 7 49 343 - 8 64 512 - 9 81 729 -10 100 1000 ->>> for x in range(1,11): -... print '%2d %3d %4d' % (x, x*x, x*x*x) -... - 1 1 1 - 2 4 8 - 3 9 27 - 4 16 64 - 5 25 125 - 6 36 216 - 7 49 343 - 8 64 512 - 9 81 729 -10 100 1000 ->>> -\end{verbatim}\ecode -% -(Note that one space between each column was added by the way {\tt print} -works: it always adds spaces between its arguments.) - -This example demonstrates the function {\tt string.rjust()}, which -right-justifies a string in a field of a given width by padding it with -spaces on the left. There are similar functions {\tt string.ljust()} -and {\tt string.center()}. These functions do not write anything, they -just return a new string. If the input string is too long, they don't -truncate it, but return it unchanged; this will mess up your column -lay-out but that's usually better than the alternative, which would be -lying about a value. (If you really want truncation you can always add -a slice operation, as in {\tt string.ljust(x,~n)[0:n]}.) - -There is another function, {\tt string.zfill}, which pads a numeric -string on the left with zeros. It understands about plus and minus -signs: - -\bcode\begin{verbatim} ->>> string.zfill('12', 5) -'00012' ->>> string.zfill('-3.14', 7) -'-003.14' ->>> string.zfill('3.14159265359', 5) -'3.14159265359' ->>> -\end{verbatim}\ecode - - -\chapter{Errors and Exceptions} - -Until now error messages haven't been more than mentioned, but if you -have tried out the examples you have probably seen some. There are -(at least) two distinguishable kinds of errors: {\em syntax\ errors} -and {\em exceptions}. - -\section{Syntax Errors} - -Syntax errors, also known as parsing errors, are perhaps the most common -kind of complaint you get while you are still learning Python: - -\bcode\begin{verbatim} ->>> while 1 print 'Hello world' - File "<stdin>", line 1 - while 1 print 'Hello world' - ^ -SyntaxError: invalid syntax ->>> -\end{verbatim}\ecode -% -The parser repeats the offending line and displays a little `arrow' -pointing at the earliest point in the line where the error was detected. -The error is caused by (or at least detected at) the token -{\em preceding} -the arrow: in the example, the error is detected at the keyword -{\tt print}, since a colon ({\tt :}) is missing before it. -File name and line number are printed so you know where to look in case -the input came from a script. - -\section{Exceptions} - -Even if a statement or expression is syntactically correct, it may -cause an error when an attempt is made to execute it. -Errors detected during execution are called {\em exceptions} and are -not unconditionally fatal: you will soon learn how to handle them in -Python programs. Most exceptions are not handled by programs, -however, and result in error messages as shown here: - -\bcode\small\begin{verbatim} ->>> 10 * (1/0) -Traceback (innermost last): - File "<stdin>", line 1 -ZeroDivisionError: integer division or modulo ->>> 4 + spam*3 -Traceback (innermost last): - File "<stdin>", line 1 -NameError: spam ->>> '2' + 2 -Traceback (innermost last): - File "<stdin>", line 1 -TypeError: illegal argument type for built-in operation ->>> -\end{verbatim}\ecode -% -The last line of the error message indicates what happened. -Exceptions come in different types, and the type is printed as part of -the message: the types in the example are -{\tt ZeroDivisionError}, -{\tt NameError} -and -{\tt TypeError}. -The string printed as the exception type is the name of the built-in -name for the exception that occurred. This is true for all built-in -exceptions, but need not be true for user-defined exceptions (although -it is a useful convention). -Standard exception names are built-in identifiers (not reserved -keywords). - -The rest of the line is a detail whose interpretation depends on the -exception type; its meaning is dependent on the exception type. - -The preceding part of the error message shows the context where the -exception happened, in the form of a stack backtrace. -In general it contains a stack backtrace listing source lines; however, -it will not display lines read from standard input. - -The Python library reference manual lists the built-in exceptions and -their meanings. - -\section{Handling Exceptions} - -It is possible to write programs that handle selected exceptions. -Look at the following example, which prints a table of inverses of -some floating point numbers: - -\bcode\begin{verbatim} ->>> numbers = [0.3333, 2.5, 0, 10] ->>> for x in numbers: -... print x, -... try: -... print 1.0 / x -... except ZeroDivisionError: -... print '*** has no inverse ***' -... -0.3333 3.00030003 -2.5 0.4 -0 *** has no inverse *** -10 0.1 ->>> -\end{verbatim}\ecode -% -The {\tt try} statement works as follows. -\begin{itemize} -\item -First, the -{\em try\ clause} -(the statement(s) between the {\tt try} and {\tt except} keywords) is -executed. -\item -If no exception occurs, the -{\em except\ clause} -is skipped and execution of the {\tt try} statement is finished. -\item -If an exception occurs during execution of the try clause, -the rest of the clause is skipped. Then if -its type matches the exception named after the {\tt except} keyword, -the rest of the try clause is skipped, the except clause is executed, -and then execution continues after the {\tt try} statement. -\item -If an exception occurs which does not match the exception named in the -except clause, it is passed on to outer try statements; if no handler is -found, it is an -{\em unhandled\ exception} -and execution stops with a message as shown above. -\end{itemize} -A {\tt try} statement may have more than one except clause, to specify -handlers for different exceptions. -At most one handler will be executed. -Handlers only handle exceptions that occur in the corresponding try -clause, not in other handlers of the same {\tt try} statement. -An except clause may name multiple exceptions as a parenthesized list, -e.g.: - -\bcode\begin{verbatim} -... except (RuntimeError, TypeError, NameError): -... pass -\end{verbatim}\ecode -% -The last except clause may omit the exception name(s), to serve as a -wildcard. -Use this with extreme caution, since it is easy to mask a real -programming error in this way! - -When an exception occurs, it may have an associated value, also known as -the exceptions's -{\em argument}. -The presence and type of the argument depend on the exception type. -For exception types which have an argument, the except clause may -specify a variable after the exception name (or list) to receive the -argument's value, as follows: - -\bcode\begin{verbatim} ->>> try: -... spam() -... except NameError, x: -... print 'name', x, 'undefined' -... -name spam undefined ->>> -\end{verbatim}\ecode -% -If an exception has an argument, it is printed as the last part -(`detail') of the message for unhandled exceptions. - -Exception handlers don't just handle exceptions if they occur -immediately in the try clause, but also if they occur inside functions -that are called (even indirectly) in the try clause. -For example: - -\bcode\begin{verbatim} ->>> def this_fails(): -... x = 1/0 -... ->>> try: -... this_fails() -... except ZeroDivisionError, detail: -... print 'Handling run-time error:', detail -... -Handling run-time error: integer division or modulo ->>> -\end{verbatim}\ecode - -\section{Raising Exceptions} - -The {\tt raise} statement allows the programmer to force a specified -exception to occur. -For example: - -\bcode\begin{verbatim} ->>> raise NameError, 'HiThere' -Traceback (innermost last): - File "<stdin>", line 1 -NameError: HiThere ->>> -\end{verbatim}\ecode -% -The first argument to {\tt raise} names the exception to be raised. -The optional second argument specifies the exception's argument. - -\section{User-defined Exceptions} - -Programs may name their own exceptions by assigning a string to a -variable. -For example: - -\bcode\begin{verbatim} ->>> my_exc = 'my_exc' ->>> try: -... raise my_exc, 2*2 -... except my_exc, val: -... print 'My exception occurred, value:', val -... -My exception occurred, value: 4 ->>> raise my_exc, 1 -Traceback (innermost last): - File "<stdin>", line 1 -my_exc: 1 ->>> -\end{verbatim}\ecode -% -Many standard modules use this to report errors that may occur in -functions they define. - -\section{Defining Clean-up Actions} - -The {\tt try} statement has another optional clause which is intended to -define clean-up actions that must be executed under all circumstances. -For example: - -\bcode\begin{verbatim} ->>> try: -... raise KeyboardInterrupt -... finally: -... print 'Goodbye, world!' -... -Goodbye, world! -Traceback (innermost last): - File "<stdin>", line 2 -KeyboardInterrupt ->>> -\end{verbatim}\ecode -% -A {\tt finally} clause is executed whether or not an exception has -occurred in the {\tt try} clause. When an exception has occurred, it -is re-raised after the {\tt finally} clause is executed. The -{\tt finally} clause is also executed ``on the way out'' when the -{\tt try} statement is left via a {\tt break} or {\tt return} -statement. - -A {\tt try} statement must either have one or more {\tt except} -clauses or one {\tt finally} clause, but not both. - - -\chapter{Classes} - -Python's class mechanism adds classes to the language with a minimum -of new syntax and semantics. It is a mixture of the class mechanisms -found in \Cpp{} and Modula-3. As is true for modules, classes in Python -do not put an absolute barrier between definition and user, but rather -rely on the politeness of the user not to ``break into the -definition.'' The most important features of classes are retained -with full power, however: the class inheritance mechanism allows -multiple base classes, a derived class can override any methods of its -base class(es), a method can call the method of a base class with the -same name. Objects can contain an arbitrary amount of private data. - -In \Cpp{} terminology, all class members (including the data members) are -{\em public}, and all member functions are {\em virtual}. There are -no special constructors or destructors. As in Modula-3, there are no -shorthands for referencing the object's members from its methods: the -method function is declared with an explicit first argument -representing the object, which is provided implicitly by the call. As -in Smalltalk, classes themselves are objects, albeit in the wider -sense of the word: in Python, all data types are objects. This -provides semantics for importing and renaming. But, just like in \Cpp{} -or Modula-3, built-in types cannot be used as base classes for -extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most -built-in operators with special syntax (arithmetic operators, -subscripting etc.) can be redefined for class members. - - -\section{A word about terminology} - -Lacking universally accepted terminology to talk about classes, I'll -make occasional use of Smalltalk and \Cpp{} terms. (I'd use Modula-3 -terms, since its object-oriented semantics are closer to those of -Python than \Cpp{}, but I expect that few readers have heard of it...) - -I also have to warn you that there's a terminological pitfall for -object-oriented readers: the word ``object'' in Python does not -necessarily mean a class instance. Like \Cpp{} and Modula-3, and unlike -Smalltalk, not all types in Python are classes: the basic built-in -types like integers and lists aren't, and even somewhat more exotic -types like files aren't. However, {\em all} Python types share a little -bit of common semantics that is best described by using the word -object. - -Objects have individuality, and multiple names (in multiple scopes) -can be bound to the same object. This is known as aliasing in other -languages. This is usually not appreciated on a first glance at -Python, and can be safely ignored when dealing with immutable basic -types (numbers, strings, tuples). However, aliasing has an -(intended!) effect on the semantics of Python code involving mutable -objects such as lists, dictionaries, and most types representing -entities outside the program (files, windows, etc.). This is usually -used to the benefit of the program, since aliases behave like pointers -in some respects. For example, passing an object is cheap since only -a pointer is passed by the implementation; and if a function modifies -an object passed as an argument, the caller will see the change --- this -obviates the need for two different argument passing mechanisms as in -Pascal. - - -\section{Python scopes and name spaces} - -Before introducing classes, I first have to tell you something about -Python's scope rules. Class definitions play some neat tricks with -name spaces, and you need to know how scopes and name spaces work to -fully understand what's going on. Incidentally, knowledge about this -subject is useful for any advanced Python programmer. - -Let's begin with some definitions. - -A {\em name space} is a mapping from names to objects. Most name -spaces are currently implemented as Python dictionaries, but that's -normally not noticeable in any way (except for performance), and it -may change in the future. Examples of name spaces are: the set of -built-in names (functions such as \verb\abs()\, and built-in exception -names); the global names in a module; and the local names in a -function invocation. In a sense the set of attributes of an object -also form a name space. The important thing to know about name -spaces is that there is absolutely no relation between names in -different name spaces; for instance, two different modules may both -define a function ``maximize'' without confusion --- users of the -modules must prefix it with the module name. - -By the way, I use the word {\em attribute} for any name following a -dot --- for example, in the expression \verb\z.real\, \verb\real\ is -an attribute of the object \verb\z\. Strictly speaking, references to -names in modules are attribute references: in the expression -\verb\modname.funcname\, \verb\modname\ is a module object and -\verb\funcname\ is an attribute of it. In this case there happens to -be a straightforward mapping between the module's attributes and the -global names defined in the module: they share the same name space!% -\footnote{ - Except for one thing. Module objects have a secret read-only - attribute called {\tt __dict__} which returns the dictionary - used to implement the module's name space; the name - {\tt __dict__} is an attribute but not a global name. - Obviously, using this violates the abstraction of name space - implementation, and should be restricted to things like - post-mortem debuggers... -} - -Attributes may be read-only or writable. In the latter case, -assignment to attributes is possible. Module attributes are writable: -you can write \verb\modname.the_answer = 42\. Writable attributes may -also be deleted with the del statement, e.g. -\verb\del modname.the_answer\. - -Name spaces are created at different moments and have different -lifetimes. The name space containing the built-in names is created -when the Python interpreter starts up, and is never deleted. The -global name space for a module is created when the module definition -is read in; normally, module name spaces also last until the -interpreter quits. The statements executed by the top-level -invocation of the interpreter, either read from a script file or -interactively, are considered part of a module called \verb\__main__\, -so they have their own global name space. (The built-in names -actually also live in a module; this is called \verb\__builtin__\.) - -The local name space for a function is created when the function is -called, and deleted when the function returns or raises an exception -that is not handled within the function. (Actually, forgetting would -be a better way to describe what actually happens.) Of course, -recursive invocations each have their own local name space. - -A {\em scope} is a textual region of a Python program where a name space -is directly accessible. ``Directly accessible'' here means that an -unqualified reference to a name attempts to find the name in the name -space. - -Although scopes are determined statically, they are used dynamically. -At any time during execution, exactly three nested scopes are in use -(i.e., exactly three name spaces are directly accessible): the -innermost scope, which is searched first, contains the local names, -the middle scope, searched next, contains the current module's global -names, and the outermost scope (searched last) is the name space -containing built-in names. - -Usually, the local scope references the local names of the (textually) -current function. Outside of functions, the local scope references -the same name space as the global scope: the module's name space. -Class definitions place yet another name space in the local scope. - -It is important to realize that scopes are determined textually: the -global scope of a function defined in a module is that module's name -space, no matter from where or by what alias the function is called. -On the other hand, the actual search for names is done dynamically, at -run time --- however, the language definition is evolving towards -static name resolution, at ``compile'' time, so don't rely on dynamic -name resolution! (In fact, local variables are already determined -statically.) - -A special quirk of Python is that assignments always go into the -innermost scope. Assignments do not copy data --- they just -bind names to objects. The same is true for deletions: the statement -\verb\del x\ removes the binding of x from the name space referenced by the -local scope. In fact, all operations that introduce new names use the -local scope: in particular, import statements and function definitions -bind the module or function name in the local scope. (The -\verb\global\ statement can be used to indicate that particular -variables live in the global scope.) - - -\section{A first look at classes} - -Classes introduce a little bit of new syntax, three new object types, -and some new semantics. - - -\subsection{Class definition syntax} - -The simplest form of class definition looks like this: - -\begin{verbatim} - class ClassName: - <statement-1> - . - . - . - <statement-N> -\end{verbatim} - -Class definitions, like function definitions (\verb\def\ statements) -must be executed before they have any effect. (You could conceivably -place a class definition in a branch of an \verb\if\ statement, or -inside a function.) - -In practice, the statements inside a class definition will usually be -function definitions, but other statements are allowed, and sometimes -useful --- we'll come back to this later. The function definitions -inside a class normally have a peculiar form of argument list, -dictated by the calling conventions for methods --- again, this is -explained later. - -When a class definition is entered, a new name space is created, and -used as the local scope --- thus, all assignments to local variables -go into this new name space. In particular, function definitions bind -the name of the new function here. - -When a class definition is left normally (via the end), a {\em class -object} is created. This is basically a wrapper around the contents -of the name space created by the class definition; we'll learn more -about class objects in the next section. The original local scope -(the one in effect just before the class definitions was entered) is -reinstated, and the class object is bound here to class name given in -the class definition header (ClassName in the example). - - -\subsection{Class objects} - -Class objects support two kinds of operations: attribute references -and instantiation. - -{\em Attribute references} use the standard syntax used for all -attribute references in Python: \verb\obj.name\. Valid attribute -names are all the names that were in the class's name space when the -class object was created. So, if the class definition looked like -this: - -\begin{verbatim} - class MyClass: - i = 12345 - def f(x): - return 'hello world' -\end{verbatim} - -then \verb\MyClass.i\ and \verb\MyClass.f\ are valid attribute -references, returning an integer and a function object, respectively. -Class attributes can also be assigned to, so you can change the -value of \verb\MyClass.i\ by assignment. - -Class {\em instantiation} uses function notation. Just pretend that -the class object is a parameterless function that returns a new -instance of the class. For example, (assuming the above class): - -\begin{verbatim} - x = MyClass() -\end{verbatim} - -creates a new {\em instance} of the class and assigns this object to -the local variable \verb\x\. - - -\subsection{Instance objects} - -Now what can we do with instance objects? The only operations -understood by instance objects are attribute references. There are -two kinds of valid attribute names. - -The first I'll call {\em data attributes}. These correspond to -``instance variables'' in Smalltalk, and to ``data members'' in \Cpp{}. -Data attributes need not be declared; like local variables, they -spring into existence when they are first assigned to. For example, -if \verb\x\ in the instance of \verb\MyClass\ created above, the -following piece of code will print the value 16, without leaving a -trace: - -\begin{verbatim} - x.counter = 1 - while x.counter < 10: - x.counter = x.counter * 2 - print x.counter - del x.counter -\end{verbatim} - -The second kind of attribute references understood by instance objects -are {\em methods}. A method is a function that ``belongs to'' an -object. (In Python, the term method is not unique to class instances: -other object types can have methods as well, e.g., list objects have -methods called append, insert, remove, sort, and so on. However, -below, we'll use the term method exclusively to mean methods of class -instance objects, unless explicitly stated otherwise.) - -Valid method names of an instance object depend on its class. By -definition, all attributes of a class that are (user-defined) function -objects define corresponding methods of its instances. So in our -example, \verb\x.f\ is a valid method reference, since -\verb\MyClass.f\ is a function, but \verb\x.i\ is not, since -\verb\MyClass.i\ is not. But \verb\x.f\ is not the -same thing as \verb\MyClass.f\ --- it is a {\em method object}, not a -function object. - - -\subsection{Method objects} - -Usually, a method is called immediately, e.g.: - -\begin{verbatim} - x.f() -\end{verbatim} - -In our example, this will return the string \verb\'hello world'\. -However, it is not necessary to call a method right away: \verb\x.f\ -is a method object, and can be stored away and called at a later -moment, for example: - -\begin{verbatim} - xf = x.f - while 1: - print xf() -\end{verbatim} - -will continue to print \verb\hello world\ until the end of time. - -What exactly happens when a method is called? You may have noticed -that \verb\x.f()\ was called without an argument above, even though -the function definition for \verb\f\ specified an argument. What -happened to the argument? Surely Python raises an exception when a -function that requires an argument is called without any --- even if -the argument isn't actually used... - -Actually, you may have guessed the answer: the special thing about -methods is that the object is passed as the first argument of the -function. In our example, the call \verb\x.f()\ is exactly equivalent -to \verb\MyClass.f(x)\. In general, calling a method with a list of -{\em n} arguments is equivalent to calling the corresponding function -with an argument list that is created by inserting the method's object -before the first argument. - -If you still don't understand how methods work, a look at the -implementation can perhaps clarify matters. When an instance -attribute is referenced that isn't a data attribute, its class is -searched. If the name denotes a valid class attribute that is a -function object, a method object is created by packing (pointers to) -the instance object and the function object just found together in an -abstract object: this is the method object. When the method object is -called with an argument list, it is unpacked again, a new argument -list is constructed from the instance object and the original argument -list, and the function object is called with this new argument list. - - -\section{Random remarks} - - -[These should perhaps be placed more carefully...] - - -Data attributes override method attributes with the same name; to -avoid accidental name conflicts, which may cause hard-to-find bugs in -large programs, it is wise to use some kind of convention that -minimizes the chance of conflicts, e.g., capitalize method names, -prefix data attribute names with a small unique string (perhaps just -an underscore), or use verbs for methods and nouns for data attributes. - - -Data attributes may be referenced by methods as well as by ordinary -users (``clients'') of an object. In other words, classes are not -usable to implement pure abstract data types. In fact, nothing in -Python makes it possible to enforce data hiding --- it is all based -upon convention. (On the other hand, the Python implementation, -written in C, can completely hide implementation details and control -access to an object if necessary; this can be used by extensions to -Python written in C.) - - -Clients should use data attributes with care --- clients may mess up -invariants maintained by the methods by stamping on their data -attributes. Note that clients may add data attributes of their own to -an instance object without affecting the validity of the methods, as -long as name conflicts are avoided --- again, a naming convention can -save a lot of headaches here. - - -There is no shorthand for referencing data attributes (or other -methods!) from within methods. I find that this actually increases -the readability of methods: there is no chance of confusing local -variables and instance variables when glancing through a method. - - -Conventionally, the first argument of methods is often called -\verb\self\. This is nothing more than a convention: the name -\verb\self\ has absolutely no special meaning to Python. (Note, -however, that by not following the convention your code may be less -readable by other Python programmers, and it is also conceivable that -a {\em class browser} program be written which relies upon such a -convention.) - - -Any function object that is a class attribute defines a method for -instances of that class. It is not necessary that the function -definition is textually enclosed in the class definition: assigning a -function object to a local variable in the class is also ok. For -example: - -\begin{verbatim} - # Function defined outside the class - def f1(self, x, y): - return min(x, x+y) - - class C: - f = f1 - def g(self): - return 'hello world' - h = g -\end{verbatim} - -Now \verb\f\, \verb\g\ and \verb\h\ are all attributes of class -\verb\C\ that refer to function objects, and consequently they are all -methods of instances of \verb\C\ --- \verb\h\ being exactly equivalent -to \verb\g\. Note that this practice usually only serves to confuse -the reader of a program. - - -Methods may call other methods by using method attributes of the -\verb\self\ argument, e.g.: - -\begin{verbatim} - class Bag: - def empty(self): - self.data = [] - def add(self, x): - self.data.append(x) - def addtwice(self, x): - self.add(x) - self.add(x) -\end{verbatim} - - -The instantiation operation (``calling'' a class object) creates an -empty object. Many classes like to create objects in a known initial -state. Therefore a class may define a special method named -\verb\__init__\, like this: - -\begin{verbatim} - def __init__(self): - self.empty() -\end{verbatim} - -When a class defines an \verb\__init__\ method, class instantiation -automatically invokes \verb\__init__\ for the newly-created class -instance. So in the \verb\Bag\ example, a new and initialized instance -can be obtained by: - -\begin{verbatim} - x = Bag() -\end{verbatim} - -Of course, the \verb\__init__\ method may have arguments for greater -flexibility. In that case, arguments given to the class instantiation -operator are passed on to \verb\__init__\. For example, - -\bcode\begin{verbatim} ->>> class Complex: -... def __init__(self, realpart, imagpart): -... self.r = realpart -... self.i = imagpart -... ->>> x = Complex(3.0,-4.5) ->>> x.r, x.i -(3.0, -4.5) ->>> -\end{verbatim}\ecode -% -Methods may reference global names in the same way as ordinary -functions. The global scope associated with a method is the module -containing the class definition. (The class itself is never used as a -global scope!) While one rarely encounters a good reason for using -global data in a method, there are many legitimate uses of the global -scope: for one thing, functions and modules imported into the global -scope can be used by methods, as well as functions and classes defined -in it. Usually, the class containing the method is itself defined in -this global scope, and in the next section we'll find some good -reasons why a method would want to reference its own class! - - -\section{Inheritance} - -Of course, a language feature would not be worthy of the name ``class'' -without supporting inheritance. The syntax for a derived class -definition looks as follows: - -\begin{verbatim} - class DerivedClassName(BaseClassName): - <statement-1> - . - . - . - <statement-N> -\end{verbatim} - -The name \verb\BaseClassName\ must be defined in a scope containing -the derived class definition. Instead of a base class name, an -expression is also allowed. This is useful when the base class is -defined in another module, e.g., - -\begin{verbatim} - class DerivedClassName(modname.BaseClassName): -\end{verbatim} - -Execution of a derived class definition proceeds the same as for a -base class. When the class object is constructed, the base class is -remembered. This is used for resolving attribute references: if a -requested attribute is not found in the class, it is searched in the -base class. This rule is applied recursively if the base class itself -is derived from some other class. - -There's nothing special about instantiation of derived classes: -\verb\DerivedClassName()\ creates a new instance of the class. Method -references are resolved as follows: the corresponding class attribute -is searched, descending down the chain of base classes if necessary, -and the method reference is valid if this yields a function object. - -Derived classes may override methods of their base classes. Because -methods have no special privileges when calling other methods of the -same object, a method of a base class that calls another method -defined in the same base class, may in fact end up calling a method of -a derived class that overrides it. (For \Cpp{} programmers: all methods -in Python are ``virtual functions''.) - -An overriding method in a derived class may in fact want to extend -rather than simply replace the base class method of the same name. -There is a simple way to call the base class method directly: just -call \verb\BaseClassName.methodname(self, arguments)\. This is -occasionally useful to clients as well. (Note that this only works if -the base class is defined or imported directly in the global scope.) - - -\subsection{Multiple inheritance} - -Python supports a limited form of multiple inheritance as well. A -class definition with multiple base classes looks as follows: - -\begin{verbatim} - class DerivedClassName(Base1, Base2, Base3): - <statement-1> - . - . - . - <statement-N> -\end{verbatim} - -The only rule necessary to explain the semantics is the resolution -rule used for class attribute references. This is depth-first, -left-to-right. Thus, if an attribute is not found in -\verb\DerivedClassName\, it is searched in \verb\Base1\, then -(recursively) in the base classes of \verb\Base1\, and only if it is -not found there, it is searched in \verb\Base2\, and so on. - -(To some people breadth first---searching \verb\Base2\ and -\verb\Base3\ before the base classes of \verb\Base1\---looks more -natural. However, this would require you to know whether a particular -attribute of \verb\Base1\ is actually defined in \verb\Base1\ or in -one of its base classes before you can figure out the consequences of -a name conflict with an attribute of \verb\Base2\. The depth-first -rule makes no differences between direct and inherited attributes of -\verb\Base1\.) - -It is clear that indiscriminate use of multiple inheritance is a -maintenance nightmare, given the reliance in Python on conventions to -avoid accidental name conflicts. A well-known problem with multiple -inheritance is a class derived from two classes that happen to have a -common base class. While it is easy enough to figure out what happens -in this case (the instance will have a single copy of ``instance -variables'' or data attributes used by the common base class), it is -not clear that these semantics are in any way useful. - - -\section{Odds and ends} - -Sometimes it is useful to have a data type similar to the Pascal -``record'' or C ``struct'', bundling together a couple of named data -items. An empty class definition will do nicely, e.g.: - -\begin{verbatim} - class Employee: - pass - - john = Employee() # Create an empty employee record - - # Fill the fields of the record - john.name = 'John Doe' - john.dept = 'computer lab' - john.salary = 1000 -\end{verbatim} - - -A piece of Python code that expects a particular abstract data type -can often be passed a class that emulates the methods of that data -type instead. For instance, if you have a function that formats some -data from a file object, you can define a class with methods -\verb\read()\ and \verb\readline()\ that gets the data from a string -buffer instead, and pass it as an argument. (Unfortunately, this -technique has its limitations: a class can't define operations that -are accessed by special syntax such as sequence subscripting or -arithmetic operators, and assigning such a ``pseudo-file'' to -\verb\sys.stdin\ will not cause the interpreter to read further input -from it.) - - -Instance method objects have attributes, too: \verb\m.im_self\ is the -object of which the method is an instance, and \verb\m.im_func\ is the -function object corresponding to the method. - - -\chapter{Recent Additions} - -Python is an evolving language. Since this tutorial was last -thoroughly revised, several new features have been added to the -language. While ideally I should revise the tutorial to incorporate -them in the mainline of the text, lack of time currently requires me -to take a more modest approach. In this chapter I will briefly list the -most important improvements to the language and how you can use them -to your benefit. - -\section{The Last Printed Expression} - -In interactive mode, the last printed expression is assigned to the -variable \code{_}. This means that when you are using Python as a -desk calculator, it is somewhat easier to continue calculations, for -example: - -\begin{verbatim} - >>> tax = 17.5 / 100 - >>> price = 3.50 - >>> price * tax - 0.6125 - >>> price + _ - 4.1125 - >>> round(_, 2) - 4.11 - >>> -\end{verbatim} - -For reasons too embarrassing to explain, this variable is implemented -as a built-in (living in the module \code{__builtin__}), so it should -be treated as read-only by the user. I.e. don't explicitly assign a -value to it --- you would create an independent local variable with -the same name masking the built-in variable with its magic behavior. - -\section{String Literals} - -\subsection{Double Quotes} - -Python can now also use double quotes to surround string literals, -e.g. \verb\"this doesn't hurt a bit"\. There is no semantic -difference between strings surrounded by single or double quotes. - -\subsection{Continuation Of String Literals} - -String literals can span multiple lines by escaping newlines with -backslashes, e.g. - -\begin{verbatim} - hello = "This is a rather long string containing\n\ - several lines of text just as you would do in C.\n\ - Note that whitespace at the beginning of the line is\ - significant.\n" - print hello -\end{verbatim} - -which would print the following: -\begin{verbatim} - This is a rather long string containing - several lines of text just as you would do in C. - Note that whitespace at the beginning of the line is significant. -\end{verbatim} - -\subsection{Triple-quoted strings} - -In some cases, when you need to include really long strings (e.g. -containing several paragraphs of informational text), it is annoying -that you have to terminate each line with \verb@\n\@, especially if -you would like to reformat the text occasionally with a powerful text -editor like Emacs. For such situations, ``triple-quoted'' strings can -be used, e.g. - -\begin{verbatim} - hello = """ - - This string is bounded by triple double quotes (3 times "). - Unescaped newlines in the string are retained, though \ - it is still possible\nto use all normal escape sequences. - - Whitespace at the beginning of a line is - significant. If you need to include three opening quotes - you have to escape at least one of them, e.g. \""". - - This string ends in a newline. - """ -\end{verbatim} - -Triple-quoted strings can be surrounded by three single quotes as -well, again without semantic difference. - -\subsection{String Literal Juxtaposition} - -One final twist: you can juxtapose multiple string literals. Two or -more adjacent string literals (but not arbitrary expressions!) -separated only by whitespace will be concatenated (without intervening -whitespace) into a single string object at compile time. This makes -it possible to continue a long string on the next line without -sacrificing indentation or performance, unlike the use of the string -concatenation operator \verb\+\ or the continuation of the literal -itself on the next line (since leading whitespace is significant -inside all types of string literals). Note that this feature, like -all string features except triple-quoted strings, is borrowed from -Standard C. - -\section{The Formatting Operator} - -\subsection{Basic Usage} - -The chapter on output formatting is really out of date: there is now -an almost complete interface to C-style printf formats. This is done -by overloading the modulo operator (\verb\%\) for a left operand -which is a string, e.g. - -\begin{verbatim} - >>> import math - >>> print 'The value of PI is approximately %5.3f.' % math.pi - The value of PI is approximately 3.142. - >>> -\end{verbatim} - -If there is more than one format in the string you pass a tuple as -right operand, e.g. - -\begin{verbatim} - >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} - >>> for name, phone in table.items(): - ... print '%-10s ==> %10d' % (name, phone) - ... - Jack ==> 4098 - Dcab ==> 8637678 - Sjoerd ==> 4127 - >>> -\end{verbatim} - -Most formats work exactly as in C and require that you pass the proper -type (however, if you don't you get an exception, not a core dump). -The \verb\%s\ format is more relaxed: if the corresponding argument is -not a string object, it is converted to string using the \verb\str()\ -built-in function. Using \verb\*\ to pass the width or precision in -as a separate (integer) argument is supported. The C formats -\verb\%n\ and \verb\%p\ are not supported. - -\subsection{Referencing Variables By Name} - -If you have a really long format string that you don't want to split -up, it would be nice if you could reference the variables to be -formatted by name instead of by position. This can be done by using -an extension of C formats using the form \verb\%(name)format\, e.g. - -\begin{verbatim} - >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} - >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table - Jack: 4098; Sjoerd: 4127; Dcab: 8637678 - >>> -\end{verbatim} - -This is particularly useful in combination with the new built-in -\verb\vars()\ function, which returns a dictionary containing all -local variables. - -\section{Optional Function Arguments} - -It is now possible to define functions with a variable number of -arguments. There are two forms, which can be combined. - -\subsection{Default Argument Values} - -The most useful form is to specify a default value for one or more -arguments. This creates a function that can be called with fewer -arguments than it is defined, e.g. - -\begin{verbatim} - def ask_ok(prompt, retries = 4, complaint = 'Yes or no, please!'): - while 1: - ok = raw_input(prompt) - if ok in ('y', 'ye', 'yes'): return 1 - if ok in ('n', 'no', 'nop', 'nope'): return 0 - retries = retries - 1 - if retries < 0: raise IOError, 'refusenik user' - print complaint -\end{verbatim} - -This function can be called either like this: -\verb\ask_ok('Do you really want to quit?')\ or like this: -\verb\ask_ok('OK to overwrite the file?', 2)\. - -The default values are evaluated at the point of function definition -in the {\em defining} scope, so that e.g. - -\begin{verbatim} - i = 5 - def f(arg = i): print arg - i = 6 - f() -\end{verbatim} - -will print \verb\5\. - -\subsection{Arbitrary Argument Lists} - -It is also possible to specify that a function can be called with an -arbitrary number of arguments. These arguments will be wrapped up in -a tuple. Before the variable number of arguments, zero or more normal -arguments may occur, e.g. - -\begin{verbatim} - def fprintf(file, format, *args): - file.write(format % args) -\end{verbatim} - -This feature may be combined with the previous, e.g. - -\begin{verbatim} - def but_is_it_useful(required, optional = None, *remains): - print "I don't know" -\end{verbatim} - -\section{Lambda And Functional Programming Tools} - -\subsection{Lambda Forms} - -By popular demand, a few features commonly found in functional -programming languages and Lisp have been added to Python. With the -\verb\lambda\ keyword, small anonymous functions can be created. -Here's a function that returns the sum of its two arguments: -\verb\lambda a, b: a+b\. Lambda forms can be used wherever function -objects are required. They are syntactically restricted to a single -expression. Semantically, they are just syntactic sugar for a normal -function definition. Like nested function definitions, lambda forms -cannot reference variables from the containing scope, but this can be -overcome through the judicious use of default argument values, e.g. - -\begin{verbatim} - def make_incrementor(n): - return lambda x, incr=n: x+incr -\end{verbatim} - -\subsection{Map, Reduce and Filter} - -Three new built-in functions on sequences are good candidate to pass -lambda forms. - -\subsubsection{Map.} - -\verb\map(function, sequence)\ calls \verb\function(item)\ for each of -the sequence's items and returns a list of the return values. For -example, to compute some cubes: - -\begin{verbatim} - >>> map(lambda x: x*x*x, range(1, 11)) - [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] - >>> -\end{verbatim} - -More than one sequence may be passed; the function must then have as -many arguments as there are sequences and is called with the -corresponding item from each sequence (or \verb\None\ if some sequence -is shorter than another). If \verb\None\ is passed for the function, -a function returning its argument(s) is substituted. - -Combining these two special cases, we see that -\verb\map(None, list1, list2)\ is a convenient way of turning a pair -of lists into a list of pairs. For example: - -\begin{verbatim} - >>> seq = range(8) - >>> map(None, seq, map(lambda x: x*x, seq)) - [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)] - >>> -\end{verbatim} - -\subsubsection{Filter.} - -\verb\filter(function, sequence)\ returns a sequence (of the same -type, if possible) consisting of those items from the sequence for -which \verb\function(item)\ is true. For example, to compute some -primes: - -\begin{verbatim} - >>> filter(lambda x: x%2 != 0 and x%3 != 0, range(2, 25)) - [5, 7, 11, 13, 17, 19, 23] - >>> -\end{verbatim} - -\subsubsection{Reduce.} - -\verb\reduce(function, sequence)\ returns a single value constructed -by calling the (binary) function on the first two items of the -sequence, then on the result and the next item, and so on. For -example, to compute the sum of the numbers 1 through 10: - -\begin{verbatim} - >>> reduce(lambda x, y: x+y, range(1, 11)) - 55 - >>> -\end{verbatim} - -If there's only one item in the sequence, its value is returned; if -the sequence is empty, an exception is raised. - -A third argument can be passed to indicate the starting value. In this -case the starting value is returned for an empty sequence, and the -function is first applied to the starting value and the first sequence -item, then to the result and the next item, and so on. For example, - -\begin{verbatim} - >>> def sum(seq): - ... return reduce(lambda x, y: x+y, seq, 0) - ... - >>> sum(range(1, 11)) - 55 - >>> sum([]) - 0 - >>> -\end{verbatim} - -\section{Continuation Lines Without Backslashes} - -While the general mechanism for continuation of a source line on the -next physical line remains to place a backslash on the end of the -line, expressions inside matched parentheses (or square brackets, or -curly braces) can now also be continued without using a backslash. -This is particularly useful for calls to functions with many -arguments, and for initializations of large tables. - -For example: - -\begin{verbatim} - month_names = ['Januari', 'Februari', 'Maart', - 'April', 'Mei', 'Juni', - 'Juli', 'Augustus', 'September', - 'Oktober', 'November', 'December'] -\end{verbatim} - -and - -\begin{verbatim} - CopyInternalHyperLinks(self.context.hyperlinks, - copy.context.hyperlinks, - uidremap) -\end{verbatim} - -\section{Regular Expressions} - -While C's printf-style output formats, transformed into Python, are -adequate for most output formatting jobs, C's scanf-style input -formats are not very powerful. Instead of scanf-style input, Python -offers Emacs-style regular expressions as a powerful input and -scanning mechanism. Read the corresponding section in the Library -Reference for a full description. - -\section{Generalized Dictionaries} - -The keys of dictionaries are no longer restricted to strings --- they -can be any immutable basic type including strings, numbers, tuples, or -(certain) class instances. (Lists and dictionaries are not acceptable -as dictionary keys, in order to avoid problems when the object used as -a key is modified.) - -Dictionaries have two new methods: \verb\d.values()\ returns a list of -the dictionary's values, and \verb\d.items()\ returns a list of the -dictionary's (key, value) pairs. Like \verb\d.keys()\, these -operations are slow for large dictionaries. Examples: - -\begin{verbatim} - >>> d = {100: 'honderd', 1000: 'duizend', 10: 'tien'} - >>> d.keys() - [100, 10, 1000] - >>> d.values() - ['honderd', 'tien', 'duizend'] - >>> d.items() - [(100, 'honderd'), (10, 'tien'), (1000, 'duizend')] - >>> -\end{verbatim} - -\section{Miscellaneous New Built-in Functions} - -The function \verb\vars()\ returns a dictionary containing the current -local variables. With a module argument, it returns that module's -global variables. The old function \verb\dir(x)\ returns -\verb\vars(x).keys()\. - -The function \verb\round(x)\ returns a floating point number rounded -to the nearest integer (but still expressed as a floating point -number). E.g. \verb\round(3.4) == 3.0\ and \verb\round(3.5) == 4.0\. -With a second argument it rounds to the specified number of digits, -e.g. \verb\round(math.pi, 4) == 3.1416\ or even -\verb\round(123.4, -2) == 100.0\. - -The function \verb\hash(x)\ returns a hash value for an object. -All object types acceptable as dictionary keys have a hash value (and -it is this hash value that the dictionary implementation uses). - -The function \verb\id(x)\ return a unique identifier for an object. -For two objects x and y, \verb\id(x) == id(y)\ if and only if -\verb\x is y\. (In fact the object's address is used.) - -The function \verb\hasattr(x, name)\ returns whether an object has an -attribute with the given name (a string value). The function -\verb\getattr(x, name)\ returns the object's attribute with the given -name. The function \verb\setattr(x, name, value)\ assigns a value to -an object's attribute with the given name. These three functions are -useful if the attribute names are not known beforehand. Note that -\verb\getattr(x, 'spam')\ is equivalent to \verb\x.spam\, and -\verb\setattr(x, 'spam', y)\ is equivalent to \verb\x.spam = y\. By -definition, \verb\hasattr(x, name)\ returns true if and only if -\verb\getattr(x, name)\ returns without raising an exception. - -\section{Else Clause For Try Statement} - -The \verb\try...except\ statement now has an optional \verb\else\ -clause, which must follow all \verb\except\ clauses. It is useful to -place code that must be executed if the \verb\try\ clause does not -raise an exception. For example: - -\begin{verbatim} - for arg in sys.argv: - try: - f = open(arg, 'r') - except IOError: - print 'cannot open', arg - else: - print arg, 'has', len(f.readlines()), 'lines' - f.close() -\end{verbatim} - - -\section{New Class Features in Release 1.1} - -Some changes have been made to classes: the operator overloading -mechanism is more flexible, providing more support for non-numeric use -of operators (including calling an object as if it were a function), -and it is possible to trap attribute accesses. - -\subsection{New Operator Overloading} - -It is no longer necessary to coerce both sides of an operator to the -same class or type. A class may still provide a \code{__coerce__} -method, but this method may return objects of different types or -classes if it feels like it. If no \code{__coerce__} is defined, any -argument type or class is acceptable. - -In order to make it possible to implement binary operators where the -right-hand side is a class instance but the left-hand side is not, -without using coercions, right-hand versions of all binary operators -may be defined. These have an `r' prepended to their name, -e.g. \code{__radd__}. - -For example, here's a very simple class for representing times. Times -are initialized from a number of seconds (like time.time()). Times -are printed like this: \code{Wed Mar 15 12:28:48 1995}. Subtracting -two Times gives their difference in seconds. Adding or subtracting a -Time and a number gives a new Time. You can't add two times, nor can -you subtract a Time from a number. - -\begin{verbatim} -import time - -class Time: - def __init__(self, seconds): - self.seconds = seconds - def __repr__(self): - return time.ctime(self.seconds) - def __add__(self, x): - return Time(self.seconds + x) - __radd__ = __add__ # support for x+t - def __sub__(self, x): - if hasattr(x, 'seconds'): # test if x could be a Time - return self.seconds - x.seconds - else: - return self.seconds - x - -now = Time(time.time()) -tomorrow = 24*3600 + now -yesterday = now - today -print tomorrow - yesterday # prints 172800 -\end{verbatim} - -\subsection{Trapping Attribute Access} - -You can define three new ``magic'' methods in a class now: -\code{__getattr__(self, name)}, \code{__setattr__(self, name, value)} -and \code{__delattr__(self, name)}. - -The \code{__getattr__} method is called when an attribute access fails, -i.e. when an attribute access would otherwise raise AttributeError --- -this is {\em after} the instance's dictionary and its class hierarchy -have been searched for the named attribute. Note that if this method -attempts to access any undefined instance attribute it will be called -recursively! - -The \code{__setattr__} and \code{__delattr__} methods are called when -assignment to, respectively deletion of an attribute are attempted. -They are called {\em instead} of the normal action (which is to insert -or delete the attribute in the instance dictionary). If either of -these methods most set or delete any attribute, they can only do so by -using the instance dictionary directly --- \code{self.__dict__} --- else -they would be called recursively. - -For example, here's a near-universal ``Wrapper'' class that passes all -its attribute accesses to another object. Note how the -\code{__init__} method inserts the wrapped object in -\code{self.__dict__} in order to avoid endless recursion -(\code{__setattr__} would call \code{__getattr__} which would call -itself recursively). - -\begin{verbatim} -class Wrapper: - def __init__(self, wrapped): - self.__dict__['wrapped'] = wrapped - def __getattr__(self, name): - return getattr(self.wrapped, name) - def __setattr__(self, name, value): - setattr(self.wrapped, name, value) - def __delattr__(self, name): - delattr(self.wrapped, name) - -import sys -f = Wrapper(sys.stdout) -f.write('hello world\n') # prints 'hello world' -\end{verbatim} - -A simpler example of \code{__getattr__} is an attribute that is -computed each time (or the first time) it it accessed. For instance: - -\begin{verbatim} -from math import pi - -class Circle: - def __init__(self, radius): - self.radius = radius - def __getattr__(self, name): - if name == 'circumference': - return 2 * pi * self.radius - if name == 'diameter': - return 2 * self.radius - if name == 'area': - return pi * pow(self.radius, 2) - raise AttributeError, name -\end{verbatim} - -\subsection{Calling a Class Instance} - -If a class defines a method \code{__call__} it is possible to call its -instances as if they were functions. For example: - -\begin{verbatim} -class PresetSomeArguments: - def __init__(self, func, *args): - self.func, self.args = func, args - def __call__(self, *args): - return apply(self.func, self.args + args) - -f = PresetSomeArguments(pow, 2) # f(i) computes powers of 2 -for i in range(10): print f(i), # prints 1 2 4 8 16 32 64 128 256 512 -print # append newline -\end{verbatim} - - -\chapter{New in Release 1.2} - - -This chapter describes even more recent additions to the Python -language and library. - - -\section{New Class Features} - -The semantics of \code{__coerce__} have been changed to be more -reasonable. As an example, the new standard module \code{Complex} -implements fairly complete complex numbers using this. Additional -examples of classes with and without \code{__coerce__} methods can be -found in the \code{Demo/classes} subdirectory, modules \code{Rat} and -\code{Dates}. - -If a class defines no \code{__coerce__} method, this is equivalent to -the following definition: - -\begin{verbatim} -def __coerce__(self, other): return self, other -\end{verbatim} - -If \code{__coerce__} coerces itself to an object of a different type, -the operation is carried out using that type --- in release 1.1, this -would cause an error. - -Comparisons involving class instances now invoke \code{__coerce__} -exactly as if \code{cmp(x, y)} were a binary operator like \code{+} -(except if \code{x} and \code{y} are the same object). - -\section{Unix Signal Handling} - -On Unix, Python now supports signal handling. The module -\code{signal} exports functions \code{signal}, \code{pause} and -\code{alarm}, which act similar to their Unix counterparts. The -module also exports the conventional names for the various signal -classes (also usable with \code{os.kill()}) and \code{SIG_IGN} and -\code{SIG_DFL}. See the section on \code{signal} in the Library -Reference Manual for more information. - -\section{Exceptions Can Be Classes} - -User-defined exceptions are no longer limited to being string objects ---- they can be identified by classes as well. Using this mechanism it -is possible to create extensible hierarchies of exceptions. - -There are two new valid (semantic) forms for the raise statement: - -\begin{verbatim} -raise Class, instance - -raise instance -\end{verbatim} - -In the first form, \code{instance} must be an instance of \code{Class} -or of a class derived from it. The second form is a shorthand for - -\begin{verbatim} -raise instance.__class__, instance -\end{verbatim} - -An except clause may list classes as well as string objects. A class -in an except clause is compatible with an exception if it is the same -class or a base class thereof (but not the other way around --- an -except clause listing a derived class is not compatible with a base -class). For example, the following code will print B, C, D in that -order: - -\begin{verbatim} -class B: - pass -class C(B): - pass -class D(C): - pass - -for c in [B, C, D]: - try: - raise c() - except D: - print "D" - except C: - print "C" - except B: - print "B" -\end{verbatim} - -Note that if the except clauses were reversed (with ``\code{except B}'' -first), it would have printed B, B, B --- the first matching except -clause is triggered. - -When an error message is printed for an unhandled exception which is a -class, the class name is printed, then a colon and a space, and -finally the instance converted to a string using the built-in function -\code{str()}. - -In this release, the built-in exceptions are still strings. - - -\section{Object Persistency and Object Copying} - -Two new modules, \code{pickle} and \code{shelve}, support storage and -retrieval of (almost) arbitrary Python objects on disk, using the -\code{dbm} package. A third module, \code{copy}, provides flexible -object copying operations. More information on these modules is -provided in the Library Reference Manual. - -\subsection{Persistent Objects} - -The module \code{pickle} provides a general framework for objects to -disassemble themselves into a stream of bytes and to reassemble such a -stream back into an object. It copes with reference sharing, -recursive objects and instances of user-defined classes, but not -(directly) with objects that have ``magical'' links into the operating -system such as open files, sockets or windows. - -The \code{pickle} module defines a simple protocol whereby -user-defined classes can control how they are disassembled and -assembled. The method \code{__getinitargs__()}, if defined, returns -the argument list for the constructor to be used at assembly time (by -default the constructor is called without arguments). The methods -\code{__getstate__()} and \code{__setstate__()} are used to pass -additional state from disassembly to assembly; by default the -instance's \code{__dict__} is passed and restored. - -Note that \code{pickle} does not open or close any files --- it can be -used equally well for moving objects around on a network or store them -in a database. For ease of debugging, and the inevitable occasional -manual patch-up, the constructed byte streams consist of printable -\ASCII{} characters only (though it's not designed to be pretty). - -The module \code{shelve} provides a simple model for storing objects -on files. The operation \code{shelve.open(filename)} returns a -``shelf'', which is a simple persistent database with a -dictionary-like interface. Database keys are strings, objects stored -in the database can be anything that \code{pickle} will handle. - -\subsection{Copying Objects} - -The module \code{copy} exports two functions: \code{copy()} and -\code{deepcopy()}. The \code{copy()} function returns a ``shallow'' -copy of an object; \code{deepcopy()} returns a ``deep'' copy. The -difference between shallow and deep copying is only relevant for -compound objects (objects that contain other objects, like lists or -class instances): - -\begin{itemize} - -\item -A shallow copy constructs a new compound object and then (to the -extent possible) inserts {\em the same objects} into in that the -original contains. - -\item -A deep copy constructs a new compound object and then, recursively, -inserts {\em copies} into it of the objects found in the original. - -\end{itemize} - -Both functions have the same restrictions and use the same protocols -as \code{pickle} --- user-defined classes can control how they are -copied by providing methods named \code{__getinitargs__()}, -\code{__getstate__()} and \code{__setstate__()}. - - -\section{Documentation Strings} - -A variety of objects now have a new attribute, \code{__doc__}, which -is supposed to contain a documentation string (if no documentation is -present, the attribute is \code{None}). New syntax, compatible with -the old interpreter, allows for convenient initialization of the -\code{__doc__} attribute of modules, classes and functions by placing -a string literal by itself as the first statement in the suite. It -must be a literal --- an expression yielding a string object is not -accepted as a documentation string, since future tools may need to -derive documentation from source by parsing. - -Here is a hypothetical, amply documented module called \code{Spam}: - -\begin{verbatim} -"""Spam operations. - -This module exports two classes, a function and an exception: - -class Spam: full Spam functionality --- three can sizes -class SpamLight: limited Spam functionality --- only one can size - -def open(filename): open a file and return a corresponding Spam or -SpamLight object - -GoneOff: exception raised for errors; should never happen - -Note that it is always possible to convert a SpamLight object to a -Spam object by a simple method call, but that the reverse operation is -generally costly and may fail for a number of reasons. -""" - -class SpamLight: - """Limited spam functionality. - - Supports a single can size, no flavor, and only hard disks. - """ - - def __init__(self, size=12): - """Construct a new SpamLight instance. - - Argument is the can size. - """ - # etc. - - # etc. - -class Spam(SpamLight): - """Full spam functionality. - - Supports three can sizes, two flavor varieties, and all floppy - disk formats still supported by current hardware. - """ - - def __init__(self, size1=8, size2=12, size3=20): - """Construct a new Spam instance. - - Arguments are up to three can sizes. - """ - # etc. - - # etc. - -def open(filename = "/dev/null"): - """Open a can of Spam. - - Argument must be an existing file. - """ - # etc. - -class GoneOff: - """Class used for Spam exceptions. - - There shouldn't be any. - """ - pass -\end{verbatim} - -After executing ``\code{import Spam}'', the following expressions -return the various documentation strings from the module: - -\begin{verbatim} -Spam.__doc__ -Spam.SpamLight.__doc__ -Spam.SpamLight.__init__.__doc__ -Spam.Spam.__doc__ -Spam.Spam.__init__.__doc__ -Spam.open.__doc__ -Spam.GoneOff.__doc__ -\end{verbatim} - -There are emerging conventions about the content and formatting of -documentation strings. - -The first line should always be a short, concise summary of the -object's purpose. For brevity, it should not explicitly state the -object's name or type, since these are available by other means -(except if the name happens to be a verb describing a function's -operation). This line should begin with a capital letter and end with -a period. - -If there are more lines in the documentation string, the second line -should be blank, visually separating the summary from the rest of the -description. The following lines should be one of more of paragraphs -describing the objects calling conventions, its side effects, etc. - -Some people like to copy the Emacs convention of using UPPER CASE for -function parameters --- this often saves a few words or lines. - -The Python parser does not strip indentation from multi-line string -literals in Python, so tools that process documentation have to strip -indentation. This is done using the following convention. The first -non-blank line {\em after} the first line of the string determines the -amount of indentation for the entire documentation string. (We can't -use the first line since it is generally adjacent to the string's -opening quotes so its indentation is not apparent in the string -literal.) Whitespace ``equivalent'' to this indentation is then -stripped from the start of all lines of the string. Lines that are -indented less should not occur, but if they occur all their leading -whitespace should be stripped. Equivalence of whitespace should be -tested after expansion of tabs (to 8 spaces, normally). - -In this release, few of the built-in or standard functions and modules -have documentation strings. - - -\section{Customizing Import and Built-Ins} - -In preparation for a ``restricted execution mode'' which will be -usable to run code received from an untrusted source (such as a WWW -server or client), the mechanism by which modules are imported has -been redesigned. It is now possible to provide your own function -\code{__import__} which is called whenever an \code{import} statement -is executed. There's a built-in function \code{__import__} which -provides the default implementation, but more interesting, the various -steps it takes are available separately from the new built-in module -\code{imp}. (See the section on \code{imp} in the Library Reference -Manual for more information on this module -- it also contains a -complete example of how to write your own \code{__import__} function.) - -When you do \code{dir()} in a fresh interactive interpreter you will -see another ``secret'' object that's present in every module: -\code{__builtins__}. This is either a dictionary or a module -containing the set of built-in objects used by functions defined in -current module. Although normally all modules are initialized with a -reference to the same dictionary, it is now possible to use a -different set of built-ins on a per-module basis. Together with the -fact that the \code{import} statement uses the \code{__import__} -function it finds in the importing modules' dictionary of built-ins, -this forms the basis for a future restricted execution mode. - - -\section{Python and the World-Wide Web} - -There is a growing number of modules available for writing WWW tools. -The previous release already sported modules \code{gopherlib}, -\code{ftplib}, \code{httplib} and \code{urllib} (which unifies the -other three) for accessing data through the commonest WWW protocols. -This release also provides \code{cgi}, to ease the writing of -server-side scripts that use the Common Gateway Interface protocol, -supported by most WWW servers. The module \code{urlparse} provides -precise parsing of a URL string into its components (address scheme, -network location, path, parameters, query, and fragment identifier). - -A rudimentary, parser for HTML files is available in the module -\code{htmllib}. It currently supports a subset of HTML 1.0 (if you -bring it up to date, I'd love to receive your fixes!). Unfortunately -Python seems to be too slow for real-time parsing and formatting of -HTML such as required by interactive WWW browsers --- but it's good -enough to write a ``robot'' (an automated WWW browser that searches -the web for information). - - -\section{Miscellaneous} - -\begin{itemize} - -\item -The \code{socket} module now exports all the needed constants used for -socket operations, such as \code{SO_BROADCAST}. - -\item -The functions \code{popen()} and \code{fdopen()} in the \code{os} -module now follow the pattern of the built-in function \code{open()}: -the default mode argument is \code{'r'} and the optional third -argument specifies the buffer size, where \code{0} means unbuffered, -\code{1} means line-buffered, and any larger number means the size of -the buffer in bytes. - -\end{itemize} - - -\chapter{New in Release 1.3} - - -This chapter describes yet more recent additions to the Python -language and library. - - -\section{Keyword Arguments} - -Functions and methods written in Python can now be called using -keyword arguments of the form \code{\var{keyword} = \var{value}}. For -instance, the following function: - -\begin{verbatim} -def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): - print "-- This parrot wouldn't", action, - print "if you put", voltage, "Volts through it." - print "-- Lovely plumage, the", type - print "-- It's", state, "!" -\end{verbatim} - -could be called in any of the following ways: - -\begin{verbatim} -parrot(1000) -parrot(action = 'VOOOOOM', voltage = 1000000) -parrot('a thousand', state = 'pushing up the daisies') -parrot('a million', 'bereft of life', 'jump') -\end{verbatim} - -but the following calls would all be invalid: - -\begin{verbatim} -parrot() # required argument missing -parrot(voltage=5.0, 'dead') # non-keyword argument following keyword -parrot(110, voltage=220) # duplicate value for argument -parrot(actor='John Cleese') # unknown keyword -\end{verbatim} - -In general, an argument list must have the form: zero or more -positional arguments followed by zero or more keyword arguments, where -the keywords must be chosen from the formal parameter names. It's not -important whether a formal parameter has a default value or not. No -argument must receive a value more than once -- formal parameter names -corresponding to positional arguments cannot be used as keywords in -the same calls. - -Note that no special syntax is required to allow a function to be -called with keyword arguments. The additional costs incurred by -keyword arguments are only present when a call uses them. - -(As far as I know, these rules are exactly the same as used by -Modula-3, even if they are enforced by totally different means. This -is intentional.) - -When a final formal parameter of the form \code{**\var{name}} is -present, it receives a dictionary containing all keyword arguments -whose keyword doesn't correspond to a formal parameter. This may be -combined with a formal parameter of the form \code{*\var{name}} which -receives a tuple containing the positional arguments beyond the formal -parameter list. (\code{*\var{name}} must occur before -\code{**\var{name}}.) For example, if we define a function like this: - -\begin{verbatim} -def cheeseshop(kind, *arguments, **keywords): - print "-- Do you have any", kind, '?' - print "-- I'm sorry, we're all out of", kind - for arg in arguments: print arg - print '-'*40 - for kw in keywords.keys(): print kw, ':', keywords[kw] -\end{verbatim} - -It could be called like this: - -\begin{verbatim} -cheeseshop('Limburger', "It's very runny, sir.", - "It's really very, VERY runny, sir.", - client='John Cleese', - shopkeeper='Michael Palin', - sketch='Cheese Shop Sketch') -\end{verbatim} - -and of course it would print: - -\begin{verbatim} --- Do you have any Limburger ? --- I'm sorry, we're all out of Limburger -It's very runny, sir. -It's really very, VERY runny, sir. ----------------------------------------- -client : John Cleese -shopkeeper : Michael Palin -sketch : Cheese Shop Sketch -\end{verbatim} - -Consequences of this change include: - -\begin{itemize} - -\item -The built-in function \code{apply()} now has an optional third -argument, which is a dictionary specifying any keyword arguments to be -passed. For example, -\begin{verbatim} -apply(parrot, (), {'voltage': 20, 'action': 'voomm'}) -\end{verbatim} -is equivalent to -\begin{verbatim} -parrot(voltage=20, action='voomm') -\end{verbatim} - -\item -There is also a mechanism for functions and methods defined in an -extension module (i.e., implemented in C or C++) to receive a -dictionary of their keyword arguments. By default, such functions do -not accept keyword arguments, since the argument names are not -available to the interpreter. - -\item -In the effort of implementing keyword arguments, function and -especially method calls have been sped up significantly -- for a -method with ten formal parameters, the call overhead has been cut in -half; for a function with one formal parameters, the overhead has been -reduced by a third. - -\item -The format of \code{.pyc} files has changed (again). - -\item -The \code{access} statement has been disabled. The syntax is still -recognized but no code is generated for it. (There were some -unpleasant interactions with changes for keyword arguments, and my -plan is to get rid of \code{access} altogether in favor of a different -approach.) - -\end{itemize} - -\section{Changes to the WWW and Internet tools} - -\begin{itemize} - -\item -The \code{htmllib} module has been rewritten in an incompatible -fashion. The new version is considerably more complete (HTML 2.0 -except forms, but including all ISO-8859-1 entity definitions), and -easy to use. Small changes to \code{sgmllib} have also been made, to -better match the tokenization of HTML as recognized by other web -tools. - -\item -A new module \code{formatter} has been added, for use with the new -\code{htmllib} module. - -\item -The \code{urllib}and \code{httplib} modules have been changed somewhat -to allow overriding unknown URL types and to support authentication. -They now use \code{mimetools.Message} instead of \code{rfc822.Message} -to parse headers. The \code{endrequest()} method has been removed -from the HTTP class since it breaks the interaction with some servers. - -\item -The \code{rfc822.Message} class has been changed to allow a flag to be -passed in that says that the file is unseekable. - -\item -The \code{ftplib} module has been fixed to be (hopefully) more robust -on Linux. - -\item -Several new operations that are optionally supported by servers have -been added to \code{nntplib}: \code{xover}, \code{xgtitle}, -\code{xpath} and \code{date}. % thanks to Kevan Heydon - -\end{itemize} - -\section{Other Language Changes} - -\begin{itemize} - -\item -The \code{raise} statement now takes an optional argument which -specifies the traceback to be used when printing the exception's stack -trace. This must be a traceback object, such as found in -\code{sys.exc_traceback}. When omitted or given as \code{None}, the -old behavior (to generate a stack trace entry for the current stack -frame) is used. - -\item -The tokenizer is now more tolerant of alien whitespace. Control-L in -the leading whitespace of a line resets the column number to zero, -while Control-R just before the end of the line is ignored. - -\end{itemize} - -\section{Changes to Built-in Operations} - -\begin{itemize} - -\item -For file objects, \code{\var{f}.read(0)} and -\code{\var{f}.readline(0)} now return an empty string rather than -reading an unlimited number of bytes. For the latter, omit the -argument altogether or pass a negative value. - -\item -A new system variable, \code{sys.platform}, has been added. It -specifies the current platform, e.g. \code{sunos5} or \code{linux1}. - -\item -The built-in functions \code{input()} and \code{raw_input()} now use -the GNU readline library when it has been configured (formerly, only -interactive input to the interpreter itself was read using GNU -readline). The GNU readline library provides elaborate line editing -and history. The Python debugger (\code{pdb}) is the first -beneficiary of this change. - -\item -Two new built-in functions, \code{globals()} and \code{locals()}, -provide access to dictionaries containming current global and local -variables, respectively. (These augment rather than replace -\code{vars()}, which returns the current local variables when called -without an argument, and a module's global variables when called with -an argument of type module.) - -\item -The built-in function \code{compile()} now takes a third possible -value for the kind of code to be compiled: specifying \code{'single'} -generates code for a single interactive statement, which prints the -output of expression statements that evaluate to something else than -\code{None}. - -\end{itemize} - -\section{Library Changes} - -\begin{itemize} - -\item -There are new module \code{ni} and \code{ihooks} that support -importing modules with hierarchical names such as \code{A.B.C}. This -is enabled by writing \code{import ni; ni.ni()} at the very top of the -main program. These modules are amply documented in the Python -source. - -\item -The module \code{rexec} has been rewritten (incompatibly) to define a -class and to use \code{ihooks}. - -\item -The \code{string.split()} and \code{string.splitfields()} functions -are now the same function (the presence or absence of the second -argument determines which operation is invoked); similar for -\code{string.join()} and \code{string.joinfields()}. - -\item -The \code{Tkinter} module and its helper \code{Dialog} have been -revamped to use keyword arguments. Tk 4.0 is now the standard. A new -module \code{FileDialog} has been added which implements standard file -selection dialogs. - -\item -The optional built-in modules \code{dbm} and \code{gdbm} are more -coordinated --- their \code{open()} functions now take the same values -for their \var{flag} argument, and the \var{flag} and \var{mode} -argument have default values (to open the database for reading only, -and to create the database with mode \code{0666} minuse the umask, -respectively). The memory leaks have finally been fixed. - -\item -A new dbm-like module, \code{bsddb}, has been added, which uses the -BSD DB package's hash method. % thanks to David Ely - -\item -A portable (though slow) dbm-clone, implemented in Python, has been -added for systems where none of the above is provided. It is aptly -dubbed \code{dumbdbm}. - -\item -The module \code{anydbm} provides a unified interface to \code{bsddb}, -\code{gdbm}, \code{dbm}, and \code{dumbdbm}, choosing the first one -available. - -\item -A new extension module, \code{binascii}, provides a variety of -operations for conversion of text-encoded binary data. - -\item -There are three new or rewritten companion modules implemented in -Python that can encode and decode the most common such formats: -\code{uu} (uuencode), \code{base64} and \code{binhex}. - -\item -A module to handle the MIME encoding quoted-printable has also been -added: \code{quopri}. - -\item -The parser module (which provides an interface to the Python parser's -abstract syntax trees) has been rewritten (incompatibly) by Fred -Drake. It now lets you change the parse tree and compile the result! - -\item -The \code{syslog} module has been upgraded and documented. -% thanks to Steve Clift - -\end{itemize} - -\section{Other Changes} - -\begin{itemize} - -\item -The dynamic module loader recognizes the fact that different filenames -point to the same shared library and loads the library only once, so -you can have a single shared library that defines multiple modules. -(SunOS / SVR4 style shared libraries only.) - -\item -Jim Fulton's ``abstract object interface'' has been incorporated into -the run-time API. For more detailes, read the files -\code{Include/abstract.h} and \code{Objects/abstract.c}. - -\item -The Macintosh version is much more robust now. - -\item -Numerous things I have forgotten or that are so obscure no-one will -notice them anyway :-) - -\end{itemize} - -\end{document} diff --git a/Doc/tut/tut.tex b/Doc/tut/tut.tex deleted file mode 100644 index 97ebeb77da..0000000000 --- a/Doc/tut/tut.tex +++ /dev/null @@ -1,3863 +0,0 @@ -\documentstyle[twoside,11pt,myformat]{report} - -\title{Python Tutorial} - -\input{boilerplate} - -\begin{document} - -\pagenumbering{roman} - -\maketitle - -\input{copyright} - -\begin{abstract} - -\noindent -Python is a simple, yet powerful programming language that bridges the -gap between C and shell programming, and is thus ideally suited for -``throw-away programming'' -and rapid prototyping. Its syntax is put -together from constructs borrowed from a variety of other languages; -most prominent are influences from ABC, C, Modula-3 and Icon. - -The Python interpreter is easily extended with new functions and data -types implemented in C. Python is also suitable as an extension -language for highly customizable C applications such as editors or -window managers. - -Python is available for various operating systems, amongst which -several flavors of {\UNIX}, Amoeba, the Apple Macintosh O.S., -and MS-DOS. - -This tutorial introduces the reader informally to the basic concepts -and features of the Python language and system. It helps to have a -Python interpreter handy for hands-on experience, but as the examples -are self-contained, the tutorial can be read off-line as well. - -For a description of standard objects and modules, see the {\em Python -Library Reference} document. The {\em Python Reference Manual} gives -a more formal definition of the language. - -\end{abstract} - -\pagebreak -{ -\parskip = 0mm -\tableofcontents -} - -\pagebreak - -\pagenumbering{arabic} - - -\chapter{Whetting Your Appetite} - -If you ever wrote a large shell script, you probably know this -feeling: you'd love to add yet another feature, but it's already so -slow, and so big, and so complicated; or the feature involves a system -call or other function that is only accessible from C \ldots Usually -the problem at hand isn't serious enough to warrant rewriting the -script in C; perhaps because the problem requires variable-length -strings or other data types (like sorted lists of file names) that are -easy in the shell but lots of work to implement in C; or perhaps just -because you're not sufficiently familiar with C. - -In such cases, Python may be just the language for you. Python is -simple to use, but it is a real programming language, offering much -more structure and support for large programs than the shell has. On -the other hand, it also offers much more error checking than C, and, -being a {\em very-high-level language}, it has high-level data types -built in, such as flexible arrays and dictionaries that would cost you -days to implement efficiently in C. Because of its more general data -types Python is applicable to a much larger problem domain than {\em -Awk} or even {\em Perl}, yet many things are at least as easy in -Python as in those languages. - -Python allows you to split up your program in modules that can be -reused in other Python programs. It comes with a large collection of -standard modules that you can use as the basis of your programs --- or -as examples to start learning to program in Python. There are also -built-in modules that provide things like file I/O, system calls, -sockets, and even a generic interface to window systems (STDWIN). - -Python is an interpreted language, which can save you considerable time -during program development because no compilation and linking is -necessary. The interpreter can be used interactively, which makes it -easy to experiment with features of the language, to write throw-away -programs, or to test functions during bottom-up program development. -It is also a handy desk calculator. - -Python allows writing very compact and readable programs. Programs -written in Python are typically much shorter than equivalent C -programs, for several reasons: -\begin{itemize} -\item -the high-level data types allow you to express complex operations in a -single statement; -\item -statement grouping is done by indentation instead of begin/end -brackets; -\item -no variable or argument declarations are necessary. -\end{itemize} - -Python is {\em extensible}: if you know how to program in C it is easy -to add a new built-in -function or -module to the interpreter, either to -perform critical operations at maximum speed, or to link Python -programs to libraries that may only be available in binary form (such -as a vendor-specific graphics library). Once you are really hooked, -you can link the Python interpreter into an application written in C -and use it as an extension or command language for that application. - -By the way, the language is named after the BBC show ``Monty -Python's Flying Circus'' and has nothing to do with nasty reptiles... - -\section{Where From Here} - -Now that you are all excited about Python, you'll want to examine it -in some more detail. Since the best way to learn a language is -using it, you are invited here to do so. - -In the next chapter, the mechanics of using the interpreter are -explained. This is rather mundane information, but essential for -trying out the examples shown later. - -The rest of the tutorial introduces various features of the Python -language and system though examples, beginning with simple -expressions, statements and data types, through functions and modules, -and finally touching upon advanced concepts like exceptions -and user-defined classes. - -When you're through with the tutorial (or just getting bored), you -should read the Library Reference, which gives complete (though terse) -reference material about built-in and standard types, functions and -modules that can save you a lot of time when writing Python programs. - - -\chapter{Using the Python Interpreter} - -\section{Invoking the Interpreter} - -The Python interpreter is usually installed as {\tt /usr/local/bin/python} -on those machines where it is available; putting {\tt /usr/local/bin} in -your {\UNIX} shell's search path makes it possible to start it by -typing the command - -\bcode\begin{verbatim} -python -\end{verbatim}\ecode -% -to the shell. Since the choice of the directory where the interpreter -lives is an installation option, other places are possible; check with -your local Python guru or system administrator. (E.g., {\tt -/usr/local/python} is a popular alternative location.) - -The interpreter operates somewhat like the {\UNIX} shell: when called -with standard input connected to a tty device, it reads and executes -commands interactively; when called with a file name argument or with -a file as standard input, it reads and executes a {\em script} from -that file. - -A third way of starting the interpreter is -``{\tt python -c command [arg] ...}'', which -executes the statement(s) in {\tt command}, analogous to the shell's -{\tt -c} option. Since Python statements often contain spaces or other -characters that are special to the shell, it is best to quote {\tt -command} in its entirety with double quotes. - -Note that there is a difference between ``{\tt python file}'' and -``{\tt python $<$file}''. In the latter case, input requests from the -program, such as calls to {\tt input()} and {\tt raw_input()}, are -satisfied from {\em file}. Since this file has already been read -until the end by the parser before the program starts executing, the -program will encounter EOF immediately. In the former case (which is -usually what you want) they are satisfied from whatever file or device -is connected to standard input of the Python interpreter. - -When a script file is used, it is sometimes useful to be able to run -the script and enter interactive mode afterwards. This can be done by -passing {\tt -i} before the script. (This does not work if the script -is read from standard input, for the same reason as explained in the -previous paragraph.) - -\subsection{Argument Passing} - -When known to the interpreter, the script name and additional -arguments thereafter are passed to the script in the variable {\tt -sys.argv}, which is a list of strings. Its length is at least one; -when no script and no arguments are given, {\tt sys.argv[0]} is an -empty string. When the script name is given as {\tt '-'} (meaning -standard input), {\tt sys.argv[0]} is set to {\tt '-'}. When {\tt -c -command} is used, {\tt sys.argv[0]} is set to {\tt '-c'}. Options -found after {\tt -c command} are not consumed by the Python -interpreter's option processing but left in {\tt sys.argv} for the -command to handle. - -\subsection{Interactive Mode} - -When commands are read from a tty, the interpreter is said to be in -{\em interactive\ mode}. In this mode it prompts for the next command -with the {\em primary\ prompt}, usually three greater-than signs ({\tt ->>>}); for continuation lines it prompts with the -{\em secondary\ prompt}, -by default three dots ({\tt ...}). Typing an EOF (Control-D) -at the primary prompt causes the interpreter to exit with a zero exit -status. - -The interpreter prints a welcome message stating its version number -and a copyright notice before printing the first prompt, e.g.: - -\bcode\begin{verbatim} -python -Python 1.3 (Oct 13 1995) -Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam ->>> -\end{verbatim}\ecode - -\section{The Interpreter and its Environment} - -\subsection{Error Handling} - -When an error occurs, the interpreter prints an error -message and a stack trace. In interactive mode, it then returns to -the primary prompt; when input came from a file, it exits with a -nonzero exit status after printing -the stack trace. (Exceptions handled by an {\tt except} clause in a -{\tt try} statement are not errors in this context.) Some errors are -unconditionally fatal and cause an exit with a nonzero exit; this -applies to internal inconsistencies and some cases of running out of -memory. All error messages are written to the standard error stream; -normal output from the executed commands is written to standard -output. - -Typing the interrupt character (usually Control-C or DEL) to the -primary or secondary prompt cancels the input and returns to the -primary prompt.% -\footnote{ - A problem with the GNU Readline package may prevent this. -} -Typing an interrupt while a command is executing raises the {\tt -KeyboardInterrupt} exception, which may be handled by a {\tt try} -statement. - -\subsection{The Module Search Path} - -When a module named {\tt spam} is imported, the interpreter searches -for a file named {\tt spam.py} in the list of directories specified by -the environment variable {\tt PYTHONPATH}. It has the same syntax as -the {\UNIX} shell variable {\tt PATH}, i.e., a list of colon-separated -directory names. When {\tt PYTHONPATH} is not set, or when the file -is not found there, the search continues in an installation-dependent -default path, usually {\tt .:/usr/local/lib/python}. - -Actually, modules are searched in the list of directories given by the -variable {\tt sys.path} which is initialized from {\tt PYTHONPATH} and -the installation-dependent default. This allows Python programs that -know what they're doing to modify or replace the module search path. -See the section on Standard Modules later. - -\subsection{``Compiled'' Python files} - -As an important speed-up of the start-up time for short programs that -use a lot of standard modules, if a file called {\tt spam.pyc} exists -in the directory where {\tt spam.py} is found, this is assumed to -contain an already-``compiled'' version of the module {\tt spam}. The -modification time of the version of {\tt spam.py} used to create {\tt -spam.pyc} is recorded in {\tt spam.pyc}, and the file is ignored if -these don't match. - -Whenever {\tt spam.py} is successfully compiled, an attempt is made to -write the compiled version to {\tt spam.pyc}. It is not an error if -this attempt fails; if for any reason the file is not written -completely, the resulting {\tt spam.pyc} file will be recognized as -invalid and thus ignored later. - -\subsection{Executable Python scripts} - -On BSD'ish {\UNIX} systems, Python scripts can be made directly -executable, like shell scripts, by putting the line - -\bcode\begin{verbatim} -#! /usr/local/bin/python -\end{verbatim}\ecode -% -(assuming that's the name of the interpreter) at the beginning of the -script and giving the file an executable mode. The {\tt \#!} must be -the first two characters of the file. - -\subsection{The Interactive Startup File} - -When you use Python interactively, it is frequently handy to have some -standard commands executed every time the interpreter is started. You -can do this by setting an environment variable named {\tt -PYTHONSTARTUP} to the name of a file containing your start-up -commands. This is similar to the {\tt .profile} feature of the UNIX -shells. - -This file is only read in interactive sessions, not when Python reads -commands from a script, and not when {\tt /dev/tty} is given as the -explicit source of commands (which otherwise behaves like an -interactive session). It is executed in the same name space where -interactive commands are executed, so that objects that it defines or -imports can be used without qualification in the interactive session. -You can also change the prompts {\tt sys.ps1} and {\tt sys.ps2} in -this file. - -If you want to read an additional start-up file from the current -directory, you can program this in the global start-up file, e.g. -\verb\execfile('.pythonrc')\. If you want to use the startup file -in a script, you must write this explicitly in the script, e.g. -\verb\import os;\ \verb\execfile(os.environ['PYTHONSTARTUP'])\. - -\section{Interactive Input Editing and History Substitution} - -Some versions of the Python interpreter support editing of the current -input line and history substitution, similar to facilities found in -the Korn shell and the GNU Bash shell. This is implemented using the -{\em GNU\ Readline} library, which supports Emacs-style and vi-style -editing. This library has its own documentation which I won't -duplicate here; however, the basics are easily explained. - -Perhaps the quickest check to see whether command line editing is -supported is typing Control-P to the first Python prompt you get. If -it beeps, you have command line editing. If nothing appears to -happen, or if \verb/^P/ is echoed, you can skip the rest of this -section. - -\subsection{Line Editing} - -If supported, input line editing is active whenever the interpreter -prints a primary or secondary prompt. The current line can be edited -using the conventional Emacs control characters. The most important -of these are: C-A (Control-A) moves the cursor to the beginning of the -line, C-E to the end, C-B moves it one position to the left, C-F to -the right. Backspace erases the character to the left of the cursor, -C-D the character to its right. C-K kills (erases) the rest of the -line to the right of the cursor, C-Y yanks back the last killed -string. C-underscore undoes the last change you made; it can be -repeated for cumulative effect. - -\subsection{History Substitution} - -History substitution works as follows. All non-empty input lines -issued are saved in a history buffer, and when a new prompt is given -you are positioned on a new line at the bottom of this buffer. C-P -moves one line up (back) in the history buffer, C-N moves one down. -Any line in the history buffer can be edited; an asterisk appears in -front of the prompt to mark a line as modified. Pressing the Return -key passes the current line to the interpreter. C-R starts an -incremental reverse search; C-S starts a forward search. - -\subsection{Key Bindings} - -The key bindings and some other parameters of the Readline library can -be customized by placing commands in an initialization file called -{\tt \$HOME/.inputrc}. Key bindings have the form - -\bcode\begin{verbatim} -key-name: function-name -\end{verbatim}\ecode -% -or - -\bcode\begin{verbatim} -"string": function-name -\end{verbatim}\ecode -% -and options can be set with - -\bcode\begin{verbatim} -set option-name value -\end{verbatim}\ecode -% -For example: - -\bcode\begin{verbatim} -# I prefer vi-style editing: -set editing-mode vi -# Edit using a single line: -set horizontal-scroll-mode On -# Rebind some keys: -Meta-h: backward-kill-word -"\C-u": universal-argument -"\C-x\C-r": re-read-init-file -\end{verbatim}\ecode -% -Note that the default binding for TAB in Python is to insert a TAB -instead of Readline's default filename completion function. If you -insist, you can override this by putting - -\bcode\begin{verbatim} -TAB: complete -\end{verbatim}\ecode -% -in your {\tt \$HOME/.inputrc}. (Of course, this makes it hard to type -indented continuation lines...) - -\subsection{Commentary} - -This facility is an enormous step forward compared to previous -versions of the interpreter; however, some wishes are left: It would -be nice if the proper indentation were suggested on continuation lines -(the parser knows if an indent token is required next). The -completion mechanism might use the interpreter's symbol table. A -command to check (or even suggest) matching parentheses, quotes etc. -would also be useful. - - -\chapter{An Informal Introduction to Python} - -In the following examples, input and output are distinguished by the -presence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat -the example, you must type everything after the prompt, when the -prompt appears; lines that do not begin with a prompt are output from -the interpreter.% -\footnote{ - I'd prefer to use different fonts to distinguish input - from output, but the amount of LaTeX hacking that would require - is currently beyond my ability. -} -Note that a secondary prompt on a line by itself in an example means -you must type a blank line; this is used to end a multi-line command. - -\section{Using Python as a Calculator} - -Let's try some simple Python commands. Start the interpreter and wait -for the primary prompt, {\tt >>>}. (It shouldn't take long.) - -\subsection{Numbers} - -The interpreter acts as a simple calculator: you can type an -expression at it and it will write the value. Expression syntax is -straightforward: the operators {\tt +}, {\tt -}, {\tt *} and {\tt /} -work just like in most other languages (e.g., Pascal or C); parentheses -can be used for grouping. For example: - -\bcode\begin{verbatim} ->>> 2+2 -4 ->>> # This is a comment -... 2+2 -4 ->>> 2+2 # and a comment on the same line as code -4 ->>> (50-5*6)/4 -5 ->>> # Integer division returns the floor: -... 7/3 -2 ->>> 7/-3 --3 ->>> -\end{verbatim}\ecode -% -Like in C, the equal sign ({\tt =}) is used to assign a value to a -variable. The value of an assignment is not written: - -\bcode\begin{verbatim} ->>> width = 20 ->>> height = 5*9 ->>> width * height -900 ->>> -\end{verbatim}\ecode -% -A value can be assigned to several variables simultaneously: - -\bcode\begin{verbatim} ->>> x = y = z = 0 # Zero x, y and z ->>> x -0 ->>> y -0 ->>> z -0 ->>> -\end{verbatim}\ecode -% -There is full support for floating point; operators with mixed type -operands convert the integer operand to floating point: - -\bcode\begin{verbatim} ->>> 4 * 2.5 / 3.3 -3.0303030303 ->>> 7.0 / 2 -3.5 ->>> -\end{verbatim}\ecode - -\subsection{Strings} - -Besides numbers, Python can also manipulate strings, enclosed in -single quotes or double quotes: - -\bcode\begin{verbatim} ->>> 'spam eggs' -'spam eggs' ->>> 'doesn\'t' -"doesn't" ->>> "doesn't" -"doesn't" ->>> '"Yes," he said.' -'"Yes," he said.' ->>> "\"Yes,\" he said." -'"Yes," he said.' ->>> '"Isn\'t," she said.' -'"Isn\'t," she said.' ->>> -\end{verbatim}\ecode -% -Strings are written the same way as they are typed for input: inside -quotes and with quotes and other funny characters escaped by backslashes, -to show the precise value. The string is enclosed in double quotes if -the string contains a single quote and no double quotes, else it's -enclosed in single quotes. (The {\tt print} statement, described later, -can be used to write strings without quotes or escapes.) - -Strings can be concatenated (glued together) with the {\tt +} -operator, and repeated with {\tt *}: - -\bcode\begin{verbatim} ->>> word = 'Help' + 'A' ->>> word -'HelpA' ->>> '<' + word*5 + '>' -'<HelpAHelpAHelpAHelpAHelpA>' ->>> -\end{verbatim}\ecode -% -Strings can be subscripted (indexed); like in C, the first character of -a string has subscript (index) 0. - -There is no separate character type; a character is simply a string of -size one. Like in Icon, substrings can be specified with the {\em -slice} notation: two indices separated by a colon. - -\bcode\begin{verbatim} ->>> word[4] -'A' ->>> word[0:2] -'He' ->>> word[2:4] -'lp' ->>> -\end{verbatim}\ecode -% -Slice indices have useful defaults; an omitted first index defaults to -zero, an omitted second index defaults to the size of the string being -sliced. - -\bcode\begin{verbatim} ->>> word[:2] # The first two characters -'He' ->>> word[2:] # All but the first two characters -'lpA' ->>> -\end{verbatim}\ecode -% -Here's a useful invariant of slice operations: \verb\s[:i] + s[i:]\ -equals \verb\s\. - -\bcode\begin{verbatim} ->>> word[:2] + word[2:] -'HelpA' ->>> word[:3] + word[3:] -'HelpA' ->>> -\end{verbatim}\ecode -% -Degenerate slice indices are handled gracefully: an index that is too -large is replaced by the string size, an upper bound smaller than the -lower bound returns an empty string. - -\bcode\begin{verbatim} ->>> word[1:100] -'elpA' ->>> word[10:] -'' ->>> word[2:1] -'' ->>> -\end{verbatim}\ecode -% -Indices may be negative numbers, to start counting from the right. -For example: - -\bcode\begin{verbatim} ->>> word[-1] # The last character -'A' ->>> word[-2] # The last-but-one character -'p' ->>> word[-2:] # The last two characters -'pA' ->>> word[:-2] # All but the last two characters -'Hel' ->>> -\end{verbatim}\ecode -% -But note that -0 is really the same as 0, so it does not count from -the right! - -\bcode\begin{verbatim} ->>> word[-0] # (since -0 equals 0) -'H' ->>> -\end{verbatim}\ecode -% -Out-of-range negative slice indices are truncated, but don't try this -for single-element (non-slice) indices: - -\bcode\begin{verbatim} ->>> word[-100:] -'HelpA' ->>> word[-10] # error -Traceback (innermost last): - File "<stdin>", line 1 -IndexError: string index out of range ->>> -\end{verbatim}\ecode -% -The best way to remember how slices work is to think of the indices as -pointing {\em between} characters, with the left edge of the first -character numbered 0. Then the right edge of the last character of a -string of {\tt n} characters has index {\tt n}, for example: - -\bcode\begin{verbatim} - +---+---+---+---+---+ - | H | e | l | p | A | - +---+---+---+---+---+ - 0 1 2 3 4 5 --5 -4 -3 -2 -1 -\end{verbatim}\ecode -% -The first row of numbers gives the position of the indices 0...5 in -the string; the second row gives the corresponding negative indices. -The slice from \verb\i\ to \verb\j\ consists of all characters between -the edges labeled \verb\i\ and \verb\j\, respectively. - -For nonnegative indices, the length of a slice is the difference of -the indices, if both are within bounds, e.g., the length of -\verb\word[1:3]\ is 2. - -The built-in function {\tt len()} returns the length of a string: - -\bcode\begin{verbatim} ->>> s = 'supercalifragilisticexpialidocious' ->>> len(s) -34 ->>> -\end{verbatim}\ecode - -\subsection{Lists} - -Python knows a number of {\em compound} data types, used to group -together other values. The most versatile is the {\em list}, which -can be written as a list of comma-separated values (items) between -square brackets. List items need not all have the same type. - -\bcode\begin{verbatim} ->>> a = ['spam', 'eggs', 100, 1234] ->>> a -['spam', 'eggs', 100, 1234] ->>> -\end{verbatim}\ecode -% -Like string indices, list indices start at 0, and lists can be sliced, -concatenated and so on: - -\bcode\begin{verbatim} ->>> a[0] -'spam' ->>> a[3] -1234 ->>> a[-2] -100 ->>> a[1:-1] -['eggs', 100] ->>> a[:2] + ['bacon', 2*2] -['spam', 'eggs', 'bacon', 4] ->>> 3*a[:3] + ['Boe!'] -['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!'] ->>> -\end{verbatim}\ecode -% -Unlike strings, which are {\em immutable}, it is possible to change -individual elements of a list: - -\bcode\begin{verbatim} ->>> a -['spam', 'eggs', 100, 1234] ->>> a[2] = a[2] + 23 ->>> a -['spam', 'eggs', 123, 1234] ->>> -\end{verbatim}\ecode -% -Assignment to slices is also possible, and this can even change the size -of the list: - -\bcode\begin{verbatim} ->>> # Replace some items: -... a[0:2] = [1, 12] ->>> a -[1, 12, 123, 1234] ->>> # Remove some: -... a[0:2] = [] ->>> a -[123, 1234] ->>> # Insert some: -... a[1:1] = ['bletch', 'xyzzy'] ->>> a -[123, 'bletch', 'xyzzy', 1234] ->>> a[:0] = a # Insert (a copy of) itself at the beginning ->>> a -[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] ->>> -\end{verbatim}\ecode -% -The built-in function {\tt len()} also applies to lists: - -\bcode\begin{verbatim} ->>> len(a) -8 ->>> -\end{verbatim}\ecode -% -It is possible to nest lists (create lists containing other lists), -for example: - -\bcode\begin{verbatim} ->>> q = [2, 3] ->>> p = [1, q, 4] ->>> len(p) -3 ->>> p[1] -[2, 3] ->>> p[1][0] -2 ->>> p[1].append('xtra') # See section 5.1 ->>> p -[1, [2, 3, 'xtra'], 4] ->>> q -[2, 3, 'xtra'] ->>> -\end{verbatim}\ecode -% -Note that in the last example, {\tt p[1]} and {\tt q} really refer to -the same object! We'll come back to {\em object semantics} later. - -\section{First Steps Towards Programming} - -Of course, we can use Python for more complicated tasks than adding -two and two together. For instance, we can write an initial -subsequence of the {\em Fibonacci} series as follows: - -\bcode\begin{verbatim} ->>> # Fibonacci series: -... # the sum of two elements defines the next -... a, b = 0, 1 ->>> while b < 10: -... print b -... a, b = b, a+b -... -1 -1 -2 -3 -5 -8 ->>> -\end{verbatim}\ecode -% -This example introduces several new features. - -\begin{itemize} - -\item -The first line contains a {\em multiple assignment}: the variables -{\tt a} and {\tt b} simultaneously get the new values 0 and 1. On the -last line this is used again, demonstrating that the expressions on -the right-hand side are all evaluated first before any of the -assignments take place. - -\item -The {\tt while} loop executes as long as the condition (here: {\tt b < -10}) remains true. In Python, like in C, any non-zero integer value is -true; zero is false. The condition may also be a string or list value, -in fact any sequence; anything with a non-zero length is true, empty -sequences are false. The test used in the example is a simple -comparison. The standard comparison operators are written the same as -in C: {\tt <}, {\tt >}, {\tt ==}, {\tt <=}, {\tt >=} and {\tt !=}. - -\item -The {\em body} of the loop is {\em indented}: indentation is Python's -way of grouping statements. Python does not (yet!) provide an -intelligent input line editing facility, so you have to type a tab or -space(s) for each indented line. In practice you will prepare more -complicated input for Python with a text editor; most text editors have -an auto-indent facility. When a compound statement is entered -interactively, it must be followed by a blank line to indicate -completion (since the parser cannot guess when you have typed the last -line). - -\item -The {\tt print} statement writes the value of the expression(s) it is -given. It differs from just writing the expression you want to write -(as we did earlier in the calculator examples) in the way it handles -multiple expressions and strings. Strings are printed without quotes, -and a space is inserted between items, so you can format things nicely, -like this: - -\bcode\begin{verbatim} ->>> i = 256*256 ->>> print 'The value of i is', i -The value of i is 65536 ->>> -\end{verbatim}\ecode -% -A trailing comma avoids the newline after the output: - -\bcode\begin{verbatim} ->>> a, b = 0, 1 ->>> while b < 1000: -... print b, -... a, b = b, a+b -... -1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ->>> -\end{verbatim}\ecode -% -Note that the interpreter inserts a newline before it prints the next -prompt if the last line was not completed. - -\end{itemize} - - -\chapter{More Control Flow Tools} - -Besides the {\tt while} statement just introduced, Python knows the -usual control flow statements known from other languages, with some -twists. - -\section{If Statements} - -Perhaps the most well-known statement type is the {\tt if} statement. -For example: - -\bcode\begin{verbatim} ->>> if x < 0: -... x = 0 -... print 'Negative changed to zero' -... elif x == 0: -... print 'Zero' -... elif x == 1: -... print 'Single' -... else: -... print 'More' -... -\end{verbatim}\ecode -% -There can be zero or more {\tt elif} parts, and the {\tt else} part is -optional. The keyword `{\tt elif}' is short for `{\tt else if}', and is -useful to avoid excessive indentation. An {\tt if...elif...elif...} -sequence is a substitute for the {\em switch} or {\em case} statements -found in other languages. - -\section{For Statements} - -The {\tt for} statement in Python differs a bit from what you may be -used to in C or Pascal. Rather than always iterating over an -arithmetic progression of numbers (like in Pascal), or leaving the user -completely free in the iteration test and step (as C), Python's {\tt -for} statement iterates over the items of any sequence (e.g., a list -or a string), in the order that they appear in the sequence. For -example (no pun intended): - -\bcode\begin{verbatim} ->>> # Measure some strings: -... a = ['cat', 'window', 'defenestrate'] ->>> for x in a: -... print x, len(x) -... -cat 3 -window 6 -defenestrate 12 ->>> -\end{verbatim}\ecode -% -It is not safe to modify the sequence being iterated over in the loop -(this can only happen for mutable sequence types, i.e., lists). If -you need to modify the list you are iterating over, e.g., duplicate -selected items, you must iterate over a copy. The slice notation -makes this particularly convenient: - -\bcode\begin{verbatim} ->>> for x in a[:]: # make a slice copy of the entire list -... if len(x) > 6: a.insert(0, x) -... ->>> a -['defenestrate', 'cat', 'window', 'defenestrate'] ->>> -\end{verbatim}\ecode - -\section{The {\tt range()} Function} - -If you do need to iterate over a sequence of numbers, the built-in -function {\tt range()} comes in handy. It generates lists containing -arithmetic progressions, e.g.: - -\bcode\begin{verbatim} ->>> range(10) -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ->>> -\end{verbatim}\ecode -% -The given end point is never part of the generated list; {\tt range(10)} -generates a list of 10 values, exactly the legal indices for items of a -sequence of length 10. It is possible to let the range start at another -number, or to specify a different increment (even negative): - -\bcode\begin{verbatim} ->>> range(5, 10) -[5, 6, 7, 8, 9] ->>> range(0, 10, 3) -[0, 3, 6, 9] ->>> range(-10, -100, -30) -[-10, -40, -70] ->>> -\end{verbatim}\ecode -% -To iterate over the indices of a sequence, combine {\tt range()} and -{\tt len()} as follows: - -\bcode\begin{verbatim} ->>> a = ['Mary', 'had', 'a', 'little', 'lamb'] ->>> for i in range(len(a)): -... print i, a[i] -... -0 Mary -1 had -2 a -3 little -4 lamb ->>> -\end{verbatim}\ecode - -\section{Break and Continue Statements, and Else Clauses on Loops} - -The {\tt break} statement, like in C, breaks out of the smallest -enclosing {\tt for} or {\tt while} loop. - -The {\tt continue} statement, also borrowed from C, continues with the -next iteration of the loop. - -Loop statements may have an {\tt else} clause; it is executed when the -loop terminates through exhaustion of the list (with {\tt for}) or when -the condition becomes false (with {\tt while}), but not when the loop is -terminated by a {\tt break} statement. This is exemplified by the -following loop, which searches for prime numbers: - -\bcode\begin{verbatim} ->>> for n in range(2, 10): -... for x in range(2, n): -... if n % x == 0: -... print n, 'equals', x, '*', n/x -... break -... else: -... print n, 'is a prime number' -... -2 is a prime number -3 is a prime number -4 equals 2 * 2 -5 is a prime number -6 equals 2 * 3 -7 is a prime number -8 equals 2 * 4 -9 equals 3 * 3 ->>> -\end{verbatim}\ecode - -\section{Pass Statements} - -The {\tt pass} statement does nothing. -It can be used when a statement is required syntactically but the -program requires no action. -For example: - -\bcode\begin{verbatim} ->>> while 1: -... pass # Busy-wait for keyboard interrupt -... -\end{verbatim}\ecode - -\section{Defining Functions} - -We can create a function that writes the Fibonacci series to an -arbitrary boundary: - -\bcode\begin{verbatim} ->>> def fib(n): # write Fibonacci series up to n -... a, b = 0, 1 -... while b < n: -... print b, -... a, b = b, a+b -... ->>> # Now call the function we just defined: -... fib(2000) -1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 ->>> -\end{verbatim}\ecode -% -The keyword {\tt def} introduces a function {\em definition}. It must -be followed by the function name and the parenthesized list of formal -parameters. The statements that form the body of the function starts at -the next line, indented by a tab stop. - -The {\em execution} of a function introduces a new symbol table used -for the local variables of the function. More precisely, all variable -assignments in a function store the value in the local symbol table; -whereas -variable references first look in the local symbol table, then -in the global symbol table, and then in the table of built-in names. -Thus, -global variables cannot be directly assigned a value within a -function (unless named in a {\tt global} statement), although -they may be referenced. - -The actual parameters (arguments) to a function call are introduced in -the local symbol table of the called function when it is called; thus, -arguments are passed using {\em call\ by\ value}.% -\footnote{ - Actually, {\em call by object reference} would be a better - description, since if a mutable object is passed, the caller - will see any changes the callee makes to it (e.g., items - inserted into a list). -} -When a function calls another function, a new local symbol table is -created for that call. - -A function definition introduces the function name in the -current -symbol table. The value -of the function name -has a type that is recognized by the interpreter as a user-defined -function. This value can be assigned to another name which can then -also be used as a function. This serves as a general renaming -mechanism: - -\bcode\begin{verbatim} ->>> fib -<function object at 10042ed0> ->>> f = fib ->>> f(100) -1 1 2 3 5 8 13 21 34 55 89 ->>> -\end{verbatim}\ecode -% -You might object that {\tt fib} is not a function but a procedure. In -Python, like in C, procedures are just functions that don't return a -value. In fact, technically speaking, procedures do return a value, -albeit a rather boring one. This value is called {\tt None} (it's a -built-in name). Writing the value {\tt None} is normally suppressed by -the interpreter if it would be the only value written. You can see it -if you really want to: - -\bcode\begin{verbatim} ->>> print fib(0) -None ->>> -\end{verbatim}\ecode -% -It is simple to write a function that returns a list of the numbers of -the Fibonacci series, instead of printing it: - -\bcode\begin{verbatim} ->>> def fib2(n): # return Fibonacci series up to n -... result = [] -... a, b = 0, 1 -... while b < n: -... result.append(b) # see below -... a, b = b, a+b -... return result -... ->>> f100 = fib2(100) # call it ->>> f100 # write the result -[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] ->>> -\end{verbatim}\ecode -% -This example, as usual, demonstrates some new Python features: - -\begin{itemize} - -\item -The {\tt return} statement returns with a value from a function. {\tt -return} without an expression argument is used to return from the middle -of a procedure (falling off the end also returns from a procedure), in -which case the {\tt None} value is returned. - -\item -The statement {\tt result.append(b)} calls a {\em method} of the list -object {\tt result}. A method is a function that `belongs' to an -object and is named {\tt obj.methodname}, where {\tt obj} is some -object (this may be an expression), and {\tt methodname} is the name -of a method that is defined by the object's type. Different types -define different methods. Methods of different types may have the -same name without causing ambiguity. (It is possible to define your -own object types and methods, using {\em classes}, as discussed later -in this tutorial.) -The method {\tt append} shown in the example, is defined for -list objects; it adds a new element at the end of the list. In this -example -it is equivalent to {\tt result = result + [b]}, but more efficient. - -\end{itemize} - - -\chapter{Odds and Ends} - -This chapter describes some things you've learned about already in -more detail, and adds some new things as well. - -\section{More on Lists} - -The list data type has some more methods. Here are all of the methods -of lists objects: - -\begin{description} - -\item[{\tt insert(i, x)}] -Insert an item at a given position. The first argument is the index of -the element before which to insert, so {\tt a.insert(0, x)} inserts at -the front of the list, and {\tt a.insert(len(a), x)} is equivalent to -{\tt a.append(x)}. - -\item[{\tt append(x)}] -Equivalent to {\tt a.insert(len(a), x)}. - -\item[{\tt index(x)}] -Return the index in the list of the first item whose value is {\tt x}. -It is an error if there is no such item. - -\item[{\tt remove(x)}] -Remove the first item from the list whose value is {\tt x}. -It is an error if there is no such item. - -\item[{\tt sort()}] -Sort the items of the list, in place. - -\item[{\tt reverse()}] -Reverse the elements of the list, in place. - -\item[{\tt count(x)}] -Return the number of times {\tt x} appears in the list. - -\end{description} - -An example that uses all list methods: - -\bcode\begin{verbatim} ->>> a = [66.6, 333, 333, 1, 1234.5] ->>> print a.count(333), a.count(66.6), a.count('x') -2 1 0 ->>> a.insert(2, -1) ->>> a.append(333) ->>> a -[66.6, 333, -1, 333, 1, 1234.5, 333] ->>> a.index(333) -1 ->>> a.remove(333) ->>> a -[66.6, -1, 333, 1, 1234.5, 333] ->>> a.reverse() ->>> a -[333, 1234.5, 1, 333, -1, 66.6] ->>> a.sort() ->>> a -[-1, 1, 66.6, 333, 333, 1234.5] ->>> -\end{verbatim}\ecode - -\section{The {\tt del} statement} - -There is a way to remove an item from a list given its index instead -of its value: the {\tt del} statement. This can also be used to -remove slices from a list (which we did earlier by assignment of an -empty list to the slice). For example: - -\bcode\begin{verbatim} ->>> a -[-1, 1, 66.6, 333, 333, 1234.5] ->>> del a[0] ->>> a -[1, 66.6, 333, 333, 1234.5] ->>> del a[2:4] ->>> a -[1, 66.6, 1234.5] ->>> -\end{verbatim}\ecode -% -{\tt del} can also be used to delete entire variables: - -\bcode\begin{verbatim} ->>> del a ->>> -\end{verbatim}\ecode -% -Referencing the name {\tt a} hereafter is an error (at least until -another value is assigned to it). We'll find other uses for {\tt del} -later. - -\section{Tuples and Sequences} - -We saw that lists and strings have many common properties, e.g., -indexing and slicing operations. They are two examples of {\em -sequence} data types. Since Python is an evolving language, other -sequence data types may be added. There is also another standard -sequence data type: the {\em tuple}. - -A tuple consists of a number of values separated by commas, for -instance: - -\bcode\begin{verbatim} ->>> t = 12345, 54321, 'hello!' ->>> t[0] -12345 ->>> t -(12345, 54321, 'hello!') ->>> # Tuples may be nested: -... u = t, (1, 2, 3, 4, 5) ->>> u -((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) ->>> -\end{verbatim}\ecode -% -As you see, on output tuples are alway enclosed in parentheses, so -that nested tuples are interpreted correctly; they may be input with -or without surrounding parentheses, although often parentheses are -necessary anyway (if the tuple is part of a larger expression). - -Tuples have many uses, e.g., (x, y) coordinate pairs, employee records -from a database, etc. Tuples, like strings, are immutable: it is not -possible to assign to the individual items of a tuple (you can -simulate much of the same effect with slicing and concatenation, -though). - -A special problem is the construction of tuples containing 0 or 1 -items: the syntax has some extra quirks to accommodate these. Empty -tuples are constructed by an empty pair of parentheses; a tuple with -one item is constructed by following a value with a comma -(it is not sufficient to enclose a single value in parentheses). -Ugly, but effective. For example: - -\bcode\begin{verbatim} ->>> empty = () ->>> singleton = 'hello', # <-- note trailing comma ->>> len(empty) -0 ->>> len(singleton) -1 ->>> singleton -('hello',) ->>> -\end{verbatim}\ecode -% -The statement {\tt t = 12345, 54321, 'hello!'} is an example of {\em -tuple packing}: the values {\tt 12345}, {\tt 54321} and {\tt 'hello!'} -are packed together in a tuple. The reverse operation is also -possible, e.g.: - -\bcode\begin{verbatim} ->>> x, y, z = t ->>> -\end{verbatim}\ecode -% -This is called, appropriately enough, {\em tuple unpacking}. Tuple -unpacking requires that the list of variables on the left has the same -number of elements as the length of the tuple. Note that multiple -assignment is really just a combination of tuple packing and tuple -unpacking! - -Occasionally, the corresponding operation on lists is useful: {\em list -unpacking}. This is supported by enclosing the list of variables in -square brackets: - -\bcode\begin{verbatim} ->>> a = ['spam', 'eggs', 100, 1234] ->>> [a1, a2, a3, a4] = a ->>> -\end{verbatim}\ecode - -\section{Dictionaries} - -Another useful data type built into Python is the {\em dictionary}. -Dictionaries are sometimes found in other languages as ``associative -memories'' or ``associative arrays''. Unlike sequences, which are -indexed by a range of numbers, dictionaries are indexed by {\em keys}, -which are strings (the use of non-string values as keys -is supported, but beyond the scope of this tutorial). -It is best to think of a dictionary as an unordered set of -{\em key:value} pairs, with the requirement that the keys are unique -(within one dictionary). -A pair of braces creates an empty dictionary: \verb/{}/. -Placing a comma-separated list of key:value pairs within the -braces adds initial key:value pairs to the dictionary; this is also the -way dictionaries are written on output. - -The main operations on a dictionary are storing a value with some key -and extracting the value given the key. It is also possible to delete -a key:value pair -with {\tt del}. -If you store using a key that is already in use, the old value -associated with that key is forgotten. It is an error to extract a -value using a non-existent key. - -The {\tt keys()} method of a dictionary object returns a list of all the -keys used in the dictionary, in random order (if you want it sorted, -just apply the {\tt sort()} method to the list of keys). To check -whether a single key is in the dictionary, use the \verb/has_key()/ -method of the dictionary. - -Here is a small example using a dictionary: - -\bcode\begin{verbatim} ->>> tel = {'jack': 4098, 'sape': 4139} ->>> tel['guido'] = 4127 ->>> tel -{'sape': 4139, 'guido': 4127, 'jack': 4098} ->>> tel['jack'] -4098 ->>> del tel['sape'] ->>> tel['irv'] = 4127 ->>> tel -{'guido': 4127, 'irv': 4127, 'jack': 4098} ->>> tel.keys() -['guido', 'irv', 'jack'] ->>> tel.has_key('guido') -1 ->>> -\end{verbatim}\ecode - -\section{More on Conditions} - -The conditions used in {\tt while} and {\tt if} statements above can -contain other operators besides comparisons. - -The comparison operators {\tt in} and {\tt not in} check whether a value -occurs (does not occur) in a sequence. The operators {\tt is} and {\tt -is not} compare whether two objects are really the same object; this -only matters for mutable objects like lists. All comparison operators -have the same priority, which is lower than that of all numerical -operators. - -Comparisons can be chained: e.g., {\tt a < b == c} tests whether {\tt a} -is less than {\tt b} and moreover {\tt b} equals {\tt c}. - -Comparisons may be combined by the Boolean operators {\tt and} and {\tt -or}, and the outcome of a comparison (or of any other Boolean -expression) may be negated with {\tt not}. These all have lower -priorities than comparison operators again; between them, {\tt not} has -the highest priority, and {\tt or} the lowest, so that -{\tt A and not B or C} is equivalent to {\tt (A and (not B)) or C}. Of -course, parentheses can be used to express the desired composition. - -The Boolean operators {\tt and} and {\tt or} are so-called {\em -shortcut} operators: their arguments are evaluated from left to right, -and evaluation stops as soon as the outcome is determined. E.g., if -{\tt A} and {\tt C} are true but {\tt B} is false, {\tt A and B and C} -does not evaluate the expression C. In general, the return value of a -shortcut operator, when used as a general value and not as a Boolean, is -the last evaluated argument. - -It is possible to assign the result of a comparison or other Boolean -expression to a variable. For example, - -\bcode\begin{verbatim} ->>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' ->>> non_null = string1 or string2 or string3 ->>> non_null -'Trondheim' ->>> -\end{verbatim}\ecode -% -Note that in Python, unlike C, assignment cannot occur inside expressions. - -\section{Comparing Sequences and Other Types} - -Sequence objects may be compared to other objects with the same -sequence type. The comparison uses {\em lexicographical} ordering: -first the first two items are compared, and if they differ this -determines the outcome of the comparison; if they are equal, the next -two items are compared, and so on, until either sequence is exhausted. -If two items to be compared are themselves sequences of the same type, -the lexicographical comparison is carried out recursively. If all -items of two sequences compare equal, the sequences are considered -equal. If one sequence is an initial subsequence of the other, the -shorted sequence is the smaller one. Lexicographical ordering for -strings uses the \ASCII{} ordering for individual characters. Some -examples of comparisons between sequences with the same types: - -\bcode\begin{verbatim} -(1, 2, 3) < (1, 2, 4) -[1, 2, 3] < [1, 2, 4] -'ABC' < 'C' < 'Pascal' < 'Python' -(1, 2, 3, 4) < (1, 2, 4) -(1, 2) < (1, 2, -1) -(1, 2, 3) = (1.0, 2.0, 3.0) -(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) -\end{verbatim}\ecode -% -Note that comparing objects of different types is legal. The outcome -is deterministic but arbitrary: the types are ordered by their name. -Thus, a list is always smaller than a string, a string is always -smaller than a tuple, etc. Mixed numeric types are compared according -to their numeric value, so 0 equals 0.0, etc.% -\footnote{ - The rules for comparing objects of different types should - not be relied upon; they may change in a future version of - the language. -} - - -\chapter{Modules} - -If you quit from the Python interpreter and enter it again, the -definitions you have made (functions and variables) are lost. -Therefore, if you want to write a somewhat longer program, you are -better off using a text editor to prepare the input for the interpreter -and running it with that file as input instead. This is known as creating a -{\em script}. As your program gets longer, you may want to split it -into several files for easier maintenance. You may also want to use a -handy function that you've written in several programs without copying -its definition into each program. - -To support this, Python has a way to put definitions in a file and use -them in a script or in an interactive instance of the interpreter. -Such a file is called a {\em module}; definitions from a module can be -{\em imported} into other modules or into the {\em main} module (the -collection of variables that you have access to in a script -executed at the top level -and in calculator mode). - -A module is a file containing Python definitions and statements. The -file name is the module name with the suffix {\tt .py} appended. Within -a module, the module's name (as a string) is available as the value of -the global variable {\tt __name__}. For instance, use your favorite text -editor to create a file called {\tt fibo.py} in the current directory -with the following contents: - -\bcode\begin{verbatim} -# Fibonacci numbers module - -def fib(n): # write Fibonacci series up to n - a, b = 0, 1 - while b < n: - print b, - a, b = b, a+b - -def fib2(n): # return Fibonacci series up to n - result = [] - a, b = 0, 1 - while b < n: - result.append(b) - a, b = b, a+b - return result -\end{verbatim}\ecode -% -Now enter the Python interpreter and import this module with the -following command: - -\bcode\begin{verbatim} ->>> import fibo ->>> -\end{verbatim}\ecode -% -This does not enter the names of the functions defined in -{\tt fibo} -directly in the current symbol table; it only enters the module name -{\tt fibo} -there. -Using the module name you can access the functions: - -\bcode\begin{verbatim} ->>> fibo.fib(1000) -1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ->>> fibo.fib2(100) -[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] ->>> fibo.__name__ -'fibo' ->>> -\end{verbatim}\ecode -% -If you intend to use a function often you can assign it to a local name: - -\bcode\begin{verbatim} ->>> fib = fibo.fib ->>> fib(500) -1 1 2 3 5 8 13 21 34 55 89 144 233 377 ->>> -\end{verbatim}\ecode - -\section{More on Modules} - -A module can contain executable statements as well as function -definitions. -These statements are intended to initialize the module. -They are executed only the -{\em first} -time the module is imported somewhere.% -\footnote{ - In fact function definitions are also `statements' that are - `executed'; the execution enters the function name in the - module's global symbol table. -} - -Each module has its own private symbol table, which is used as the -global symbol table by all functions defined in the module. -Thus, the author of a module can use global variables in the module -without worrying about accidental clashes with a user's global -variables. -On the other hand, if you know what you are doing you can touch a -module's global variables with the same notation used to refer to its -functions, -{\tt modname.itemname}. - -Modules can import other modules. -It is customary but not required to place all -{\tt import} -statements at the beginning of a module (or script, for that matter). -The imported module names are placed in the importing module's global -symbol table. - -There is a variant of the -{\tt import} -statement that imports names from a module directly into the importing -module's symbol table. -For example: - -\bcode\begin{verbatim} ->>> from fibo import fib, fib2 ->>> fib(500) -1 1 2 3 5 8 13 21 34 55 89 144 233 377 ->>> -\end{verbatim}\ecode -% -This does not introduce the module name from which the imports are taken -in the local symbol table (so in the example, {\tt fibo} is not -defined). - -There is even a variant to import all names that a module defines: - -\bcode\begin{verbatim} ->>> from fibo import * ->>> fib(500) -1 1 2 3 5 8 13 21 34 55 89 144 233 377 ->>> -\end{verbatim}\ecode -% -This imports all names except those beginning with an underscore -({\tt _}). - -\section{Standard Modules} - -Python comes with a library of standard modules, described in a separate -document (Python Library Reference). Some modules are built into the -interpreter; these provide access to operations that are not part of the -core of the language but are nevertheless built in, either for -efficiency or to provide access to operating system primitives such as -system calls. The set of such modules is a configuration option; e.g., -the {\tt amoeba} module is only provided on systems that somehow support -Amoeba primitives. One particular module deserves some attention: {\tt -sys}, which is built into every Python interpreter. The variables {\tt -sys.ps1} and {\tt sys.ps2} define the strings used as primary and -secondary prompts: - -\bcode\begin{verbatim} ->>> import sys ->>> sys.ps1 -'>>> ' ->>> sys.ps2 -'... ' ->>> sys.ps1 = 'C> ' -C> print 'Yuck!' -Yuck! -C> -\end{verbatim}\ecode -% -These two variables are only defined if the interpreter is in -interactive mode. - -The variable -{\tt sys.path} -is a list of strings that determine the interpreter's search path for -modules. -It is initialized to a default path taken from the environment variable -{\tt PYTHONPATH}, -or from a built-in default if -{\tt PYTHONPATH} -is not set. -You can modify it using standard list operations, e.g.: - -\bcode\begin{verbatim} ->>> import sys ->>> sys.path.append('/ufs/guido/lib/python') ->>> -\end{verbatim}\ecode - -\section{The {\tt dir()} function} - -The built-in function {\tt dir} is used to find out which names a module -defines. It returns a sorted list of strings: - -\bcode\begin{verbatim} ->>> import fibo, sys ->>> dir(fibo) -['__name__', 'fib', 'fib2'] ->>> dir(sys) -['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit', -'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace', -'stderr', 'stdin', 'stdout', 'version'] ->>> -\end{verbatim}\ecode -% -Without arguments, {\tt dir()} lists the names you have defined currently: - -\bcode\begin{verbatim} ->>> a = [1, 2, 3, 4, 5] ->>> import fibo, sys ->>> fib = fibo.fib ->>> dir() -['__name__', 'a', 'fib', 'fibo', 'sys'] ->>> -\end{verbatim}\ecode -% -Note that it lists all types of names: variables, modules, functions, etc. - -{\tt dir()} does not list the names of built-in functions and variables. -If you want a list of those, they are defined in the standard module -{\tt __builtin__}: - -\bcode\begin{verbatim} ->>> import __builtin__ ->>> dir(__builtin__) -['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError', -'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt', -'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError', -'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError', -'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce', -'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float', -'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long', -'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input', -'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange'] ->>> -\end{verbatim}\ecode - - -\chapter{Output Formatting} - -So far we've encountered two ways of writing values: {\em expression -statements} and the {\tt print} statement. (A third way is using the -{\tt write} method of file objects; the standard output file can be -referenced as {\tt sys.stdout}. See the Library Reference for more -information on this.) - -Often you'll want more control over the formatting of your output than -simply printing space-separated values. The key to nice formatting in -Python is to do all the string handling yourself; using string slicing -and concatenation operations you can create any lay-out you can imagine. -The standard module {\tt string} contains some useful operations for -padding strings to a given column width; these will be discussed shortly. -Finally, the \code{\%} operator (modulo) with a string left argument -interprets this string as a C sprintf format string to be applied to the -right argument, and returns the string resulting from this formatting -operation. - -One question remains, of course: how do you convert values to strings? -Luckily, Python has a way to convert any value to a string: just write -the value between reverse quotes (\verb/``/). Some examples: - -\bcode\begin{verbatim} ->>> x = 10 * 3.14 ->>> y = 200*200 ->>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...' ->>> print s -The value of x is 31.4, and y is 40000... ->>> # Reverse quotes work on other types besides numbers: -... p = [x, y] ->>> ps = `p` ->>> ps -'[31.4, 40000]' ->>> # Converting a string adds string quotes and backslashes: -... hello = 'hello, world\n' ->>> hellos = `hello` ->>> print hellos -'hello, world\012' ->>> # The argument of reverse quotes may be a tuple: -... `x, y, ('spam', 'eggs')` -"(31.4, 40000, ('spam', 'eggs'))" ->>> -\end{verbatim}\ecode -% -Here are two ways to write a table of squares and cubes: - -\bcode\begin{verbatim} ->>> import string ->>> for x in range(1, 11): -... print string.rjust(`x`, 2), string.rjust(`x*x`, 3), -... # Note trailing comma on previous line -... print string.rjust(`x*x*x`, 4) -... - 1 1 1 - 2 4 8 - 3 9 27 - 4 16 64 - 5 25 125 - 6 36 216 - 7 49 343 - 8 64 512 - 9 81 729 -10 100 1000 ->>> for x in range(1,11): -... print '%2d %3d %4d' % (x, x*x, x*x*x) -... - 1 1 1 - 2 4 8 - 3 9 27 - 4 16 64 - 5 25 125 - 6 36 216 - 7 49 343 - 8 64 512 - 9 81 729 -10 100 1000 ->>> -\end{verbatim}\ecode -% -(Note that one space between each column was added by the way {\tt print} -works: it always adds spaces between its arguments.) - -This example demonstrates the function {\tt string.rjust()}, which -right-justifies a string in a field of a given width by padding it with -spaces on the left. There are similar functions {\tt string.ljust()} -and {\tt string.center()}. These functions do not write anything, they -just return a new string. If the input string is too long, they don't -truncate it, but return it unchanged; this will mess up your column -lay-out but that's usually better than the alternative, which would be -lying about a value. (If you really want truncation you can always add -a slice operation, as in {\tt string.ljust(x,~n)[0:n]}.) - -There is another function, {\tt string.zfill}, which pads a numeric -string on the left with zeros. It understands about plus and minus -signs: - -\bcode\begin{verbatim} ->>> string.zfill('12', 5) -'00012' ->>> string.zfill('-3.14', 7) -'-003.14' ->>> string.zfill('3.14159265359', 5) -'3.14159265359' ->>> -\end{verbatim}\ecode - - -\chapter{Errors and Exceptions} - -Until now error messages haven't been more than mentioned, but if you -have tried out the examples you have probably seen some. There are -(at least) two distinguishable kinds of errors: {\em syntax\ errors} -and {\em exceptions}. - -\section{Syntax Errors} - -Syntax errors, also known as parsing errors, are perhaps the most common -kind of complaint you get while you are still learning Python: - -\bcode\begin{verbatim} ->>> while 1 print 'Hello world' - File "<stdin>", line 1 - while 1 print 'Hello world' - ^ -SyntaxError: invalid syntax ->>> -\end{verbatim}\ecode -% -The parser repeats the offending line and displays a little `arrow' -pointing at the earliest point in the line where the error was detected. -The error is caused by (or at least detected at) the token -{\em preceding} -the arrow: in the example, the error is detected at the keyword -{\tt print}, since a colon ({\tt :}) is missing before it. -File name and line number are printed so you know where to look in case -the input came from a script. - -\section{Exceptions} - -Even if a statement or expression is syntactically correct, it may -cause an error when an attempt is made to execute it. -Errors detected during execution are called {\em exceptions} and are -not unconditionally fatal: you will soon learn how to handle them in -Python programs. Most exceptions are not handled by programs, -however, and result in error messages as shown here: - -\bcode\small\begin{verbatim} ->>> 10 * (1/0) -Traceback (innermost last): - File "<stdin>", line 1 -ZeroDivisionError: integer division or modulo ->>> 4 + spam*3 -Traceback (innermost last): - File "<stdin>", line 1 -NameError: spam ->>> '2' + 2 -Traceback (innermost last): - File "<stdin>", line 1 -TypeError: illegal argument type for built-in operation ->>> -\end{verbatim}\ecode -% -The last line of the error message indicates what happened. -Exceptions come in different types, and the type is printed as part of -the message: the types in the example are -{\tt ZeroDivisionError}, -{\tt NameError} -and -{\tt TypeError}. -The string printed as the exception type is the name of the built-in -name for the exception that occurred. This is true for all built-in -exceptions, but need not be true for user-defined exceptions (although -it is a useful convention). -Standard exception names are built-in identifiers (not reserved -keywords). - -The rest of the line is a detail whose interpretation depends on the -exception type; its meaning is dependent on the exception type. - -The preceding part of the error message shows the context where the -exception happened, in the form of a stack backtrace. -In general it contains a stack backtrace listing source lines; however, -it will not display lines read from standard input. - -The Python library reference manual lists the built-in exceptions and -their meanings. - -\section{Handling Exceptions} - -It is possible to write programs that handle selected exceptions. -Look at the following example, which prints a table of inverses of -some floating point numbers: - -\bcode\begin{verbatim} ->>> numbers = [0.3333, 2.5, 0, 10] ->>> for x in numbers: -... print x, -... try: -... print 1.0 / x -... except ZeroDivisionError: -... print '*** has no inverse ***' -... -0.3333 3.00030003 -2.5 0.4 -0 *** has no inverse *** -10 0.1 ->>> -\end{verbatim}\ecode -% -The {\tt try} statement works as follows. -\begin{itemize} -\item -First, the -{\em try\ clause} -(the statement(s) between the {\tt try} and {\tt except} keywords) is -executed. -\item -If no exception occurs, the -{\em except\ clause} -is skipped and execution of the {\tt try} statement is finished. -\item -If an exception occurs during execution of the try clause, -the rest of the clause is skipped. Then if -its type matches the exception named after the {\tt except} keyword, -the rest of the try clause is skipped, the except clause is executed, -and then execution continues after the {\tt try} statement. -\item -If an exception occurs which does not match the exception named in the -except clause, it is passed on to outer try statements; if no handler is -found, it is an -{\em unhandled\ exception} -and execution stops with a message as shown above. -\end{itemize} -A {\tt try} statement may have more than one except clause, to specify -handlers for different exceptions. -At most one handler will be executed. -Handlers only handle exceptions that occur in the corresponding try -clause, not in other handlers of the same {\tt try} statement. -An except clause may name multiple exceptions as a parenthesized list, -e.g.: - -\bcode\begin{verbatim} -... except (RuntimeError, TypeError, NameError): -... pass -\end{verbatim}\ecode -% -The last except clause may omit the exception name(s), to serve as a -wildcard. -Use this with extreme caution, since it is easy to mask a real -programming error in this way! - -When an exception occurs, it may have an associated value, also known as -the exceptions's -{\em argument}. -The presence and type of the argument depend on the exception type. -For exception types which have an argument, the except clause may -specify a variable after the exception name (or list) to receive the -argument's value, as follows: - -\bcode\begin{verbatim} ->>> try: -... spam() -... except NameError, x: -... print 'name', x, 'undefined' -... -name spam undefined ->>> -\end{verbatim}\ecode -% -If an exception has an argument, it is printed as the last part -(`detail') of the message for unhandled exceptions. - -Exception handlers don't just handle exceptions if they occur -immediately in the try clause, but also if they occur inside functions -that are called (even indirectly) in the try clause. -For example: - -\bcode\begin{verbatim} ->>> def this_fails(): -... x = 1/0 -... ->>> try: -... this_fails() -... except ZeroDivisionError, detail: -... print 'Handling run-time error:', detail -... -Handling run-time error: integer division or modulo ->>> -\end{verbatim}\ecode - -\section{Raising Exceptions} - -The {\tt raise} statement allows the programmer to force a specified -exception to occur. -For example: - -\bcode\begin{verbatim} ->>> raise NameError, 'HiThere' -Traceback (innermost last): - File "<stdin>", line 1 -NameError: HiThere ->>> -\end{verbatim}\ecode -% -The first argument to {\tt raise} names the exception to be raised. -The optional second argument specifies the exception's argument. - -\section{User-defined Exceptions} - -Programs may name their own exceptions by assigning a string to a -variable. -For example: - -\bcode\begin{verbatim} ->>> my_exc = 'my_exc' ->>> try: -... raise my_exc, 2*2 -... except my_exc, val: -... print 'My exception occurred, value:', val -... -My exception occurred, value: 4 ->>> raise my_exc, 1 -Traceback (innermost last): - File "<stdin>", line 1 -my_exc: 1 ->>> -\end{verbatim}\ecode -% -Many standard modules use this to report errors that may occur in -functions they define. - -\section{Defining Clean-up Actions} - -The {\tt try} statement has another optional clause which is intended to -define clean-up actions that must be executed under all circumstances. -For example: - -\bcode\begin{verbatim} ->>> try: -... raise KeyboardInterrupt -... finally: -... print 'Goodbye, world!' -... -Goodbye, world! -Traceback (innermost last): - File "<stdin>", line 2 -KeyboardInterrupt ->>> -\end{verbatim}\ecode -% -A {\tt finally} clause is executed whether or not an exception has -occurred in the {\tt try} clause. When an exception has occurred, it -is re-raised after the {\tt finally} clause is executed. The -{\tt finally} clause is also executed ``on the way out'' when the -{\tt try} statement is left via a {\tt break} or {\tt return} -statement. - -A {\tt try} statement must either have one or more {\tt except} -clauses or one {\tt finally} clause, but not both. - - -\chapter{Classes} - -Python's class mechanism adds classes to the language with a minimum -of new syntax and semantics. It is a mixture of the class mechanisms -found in \Cpp{} and Modula-3. As is true for modules, classes in Python -do not put an absolute barrier between definition and user, but rather -rely on the politeness of the user not to ``break into the -definition.'' The most important features of classes are retained -with full power, however: the class inheritance mechanism allows -multiple base classes, a derived class can override any methods of its -base class(es), a method can call the method of a base class with the -same name. Objects can contain an arbitrary amount of private data. - -In \Cpp{} terminology, all class members (including the data members) are -{\em public}, and all member functions are {\em virtual}. There are -no special constructors or destructors. As in Modula-3, there are no -shorthands for referencing the object's members from its methods: the -method function is declared with an explicit first argument -representing the object, which is provided implicitly by the call. As -in Smalltalk, classes themselves are objects, albeit in the wider -sense of the word: in Python, all data types are objects. This -provides semantics for importing and renaming. But, just like in \Cpp{} -or Modula-3, built-in types cannot be used as base classes for -extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most -built-in operators with special syntax (arithmetic operators, -subscripting etc.) can be redefined for class members. - - -\section{A word about terminology} - -Lacking universally accepted terminology to talk about classes, I'll -make occasional use of Smalltalk and \Cpp{} terms. (I'd use Modula-3 -terms, since its object-oriented semantics are closer to those of -Python than \Cpp{}, but I expect that few readers have heard of it...) - -I also have to warn you that there's a terminological pitfall for -object-oriented readers: the word ``object'' in Python does not -necessarily mean a class instance. Like \Cpp{} and Modula-3, and unlike -Smalltalk, not all types in Python are classes: the basic built-in -types like integers and lists aren't, and even somewhat more exotic -types like files aren't. However, {\em all} Python types share a little -bit of common semantics that is best described by using the word -object. - -Objects have individuality, and multiple names (in multiple scopes) -can be bound to the same object. This is known as aliasing in other -languages. This is usually not appreciated on a first glance at -Python, and can be safely ignored when dealing with immutable basic -types (numbers, strings, tuples). However, aliasing has an -(intended!) effect on the semantics of Python code involving mutable -objects such as lists, dictionaries, and most types representing -entities outside the program (files, windows, etc.). This is usually -used to the benefit of the program, since aliases behave like pointers -in some respects. For example, passing an object is cheap since only -a pointer is passed by the implementation; and if a function modifies -an object passed as an argument, the caller will see the change --- this -obviates the need for two different argument passing mechanisms as in -Pascal. - - -\section{Python scopes and name spaces} - -Before introducing classes, I first have to tell you something about -Python's scope rules. Class definitions play some neat tricks with -name spaces, and you need to know how scopes and name spaces work to -fully understand what's going on. Incidentally, knowledge about this -subject is useful for any advanced Python programmer. - -Let's begin with some definitions. - -A {\em name space} is a mapping from names to objects. Most name -spaces are currently implemented as Python dictionaries, but that's -normally not noticeable in any way (except for performance), and it -may change in the future. Examples of name spaces are: the set of -built-in names (functions such as \verb\abs()\, and built-in exception -names); the global names in a module; and the local names in a -function invocation. In a sense the set of attributes of an object -also form a name space. The important thing to know about name -spaces is that there is absolutely no relation between names in -different name spaces; for instance, two different modules may both -define a function ``maximize'' without confusion --- users of the -modules must prefix it with the module name. - -By the way, I use the word {\em attribute} for any name following a -dot --- for example, in the expression \verb\z.real\, \verb\real\ is -an attribute of the object \verb\z\. Strictly speaking, references to -names in modules are attribute references: in the expression -\verb\modname.funcname\, \verb\modname\ is a module object and -\verb\funcname\ is an attribute of it. In this case there happens to -be a straightforward mapping between the module's attributes and the -global names defined in the module: they share the same name space!% -\footnote{ - Except for one thing. Module objects have a secret read-only - attribute called {\tt __dict__} which returns the dictionary - used to implement the module's name space; the name - {\tt __dict__} is an attribute but not a global name. - Obviously, using this violates the abstraction of name space - implementation, and should be restricted to things like - post-mortem debuggers... -} - -Attributes may be read-only or writable. In the latter case, -assignment to attributes is possible. Module attributes are writable: -you can write \verb\modname.the_answer = 42\. Writable attributes may -also be deleted with the del statement, e.g. -\verb\del modname.the_answer\. - -Name spaces are created at different moments and have different -lifetimes. The name space containing the built-in names is created -when the Python interpreter starts up, and is never deleted. The -global name space for a module is created when the module definition -is read in; normally, module name spaces also last until the -interpreter quits. The statements executed by the top-level -invocation of the interpreter, either read from a script file or -interactively, are considered part of a module called \verb\__main__\, -so they have their own global name space. (The built-in names -actually also live in a module; this is called \verb\__builtin__\.) - -The local name space for a function is created when the function is -called, and deleted when the function returns or raises an exception -that is not handled within the function. (Actually, forgetting would -be a better way to describe what actually happens.) Of course, -recursive invocations each have their own local name space. - -A {\em scope} is a textual region of a Python program where a name space -is directly accessible. ``Directly accessible'' here means that an -unqualified reference to a name attempts to find the name in the name -space. - -Although scopes are determined statically, they are used dynamically. -At any time during execution, exactly three nested scopes are in use -(i.e., exactly three name spaces are directly accessible): the -innermost scope, which is searched first, contains the local names, -the middle scope, searched next, contains the current module's global -names, and the outermost scope (searched last) is the name space -containing built-in names. - -Usually, the local scope references the local names of the (textually) -current function. Outside of functions, the local scope references -the same name space as the global scope: the module's name space. -Class definitions place yet another name space in the local scope. - -It is important to realize that scopes are determined textually: the -global scope of a function defined in a module is that module's name -space, no matter from where or by what alias the function is called. -On the other hand, the actual search for names is done dynamically, at -run time --- however, the language definition is evolving towards -static name resolution, at ``compile'' time, so don't rely on dynamic -name resolution! (In fact, local variables are already determined -statically.) - -A special quirk of Python is that assignments always go into the -innermost scope. Assignments do not copy data --- they just -bind names to objects. The same is true for deletions: the statement -\verb\del x\ removes the binding of x from the name space referenced by the -local scope. In fact, all operations that introduce new names use the -local scope: in particular, import statements and function definitions -bind the module or function name in the local scope. (The -\verb\global\ statement can be used to indicate that particular -variables live in the global scope.) - - -\section{A first look at classes} - -Classes introduce a little bit of new syntax, three new object types, -and some new semantics. - - -\subsection{Class definition syntax} - -The simplest form of class definition looks like this: - -\begin{verbatim} - class ClassName: - <statement-1> - . - . - . - <statement-N> -\end{verbatim} - -Class definitions, like function definitions (\verb\def\ statements) -must be executed before they have any effect. (You could conceivably -place a class definition in a branch of an \verb\if\ statement, or -inside a function.) - -In practice, the statements inside a class definition will usually be -function definitions, but other statements are allowed, and sometimes -useful --- we'll come back to this later. The function definitions -inside a class normally have a peculiar form of argument list, -dictated by the calling conventions for methods --- again, this is -explained later. - -When a class definition is entered, a new name space is created, and -used as the local scope --- thus, all assignments to local variables -go into this new name space. In particular, function definitions bind -the name of the new function here. - -When a class definition is left normally (via the end), a {\em class -object} is created. This is basically a wrapper around the contents -of the name space created by the class definition; we'll learn more -about class objects in the next section. The original local scope -(the one in effect just before the class definitions was entered) is -reinstated, and the class object is bound here to class name given in -the class definition header (ClassName in the example). - - -\subsection{Class objects} - -Class objects support two kinds of operations: attribute references -and instantiation. - -{\em Attribute references} use the standard syntax used for all -attribute references in Python: \verb\obj.name\. Valid attribute -names are all the names that were in the class's name space when the -class object was created. So, if the class definition looked like -this: - -\begin{verbatim} - class MyClass: - i = 12345 - def f(x): - return 'hello world' -\end{verbatim} - -then \verb\MyClass.i\ and \verb\MyClass.f\ are valid attribute -references, returning an integer and a function object, respectively. -Class attributes can also be assigned to, so you can change the -value of \verb\MyClass.i\ by assignment. - -Class {\em instantiation} uses function notation. Just pretend that -the class object is a parameterless function that returns a new -instance of the class. For example, (assuming the above class): - -\begin{verbatim} - x = MyClass() -\end{verbatim} - -creates a new {\em instance} of the class and assigns this object to -the local variable \verb\x\. - - -\subsection{Instance objects} - -Now what can we do with instance objects? The only operations -understood by instance objects are attribute references. There are -two kinds of valid attribute names. - -The first I'll call {\em data attributes}. These correspond to -``instance variables'' in Smalltalk, and to ``data members'' in \Cpp{}. -Data attributes need not be declared; like local variables, they -spring into existence when they are first assigned to. For example, -if \verb\x\ in the instance of \verb\MyClass\ created above, the -following piece of code will print the value 16, without leaving a -trace: - -\begin{verbatim} - x.counter = 1 - while x.counter < 10: - x.counter = x.counter * 2 - print x.counter - del x.counter -\end{verbatim} - -The second kind of attribute references understood by instance objects -are {\em methods}. A method is a function that ``belongs to'' an -object. (In Python, the term method is not unique to class instances: -other object types can have methods as well, e.g., list objects have -methods called append, insert, remove, sort, and so on. However, -below, we'll use the term method exclusively to mean methods of class -instance objects, unless explicitly stated otherwise.) - -Valid method names of an instance object depend on its class. By -definition, all attributes of a class that are (user-defined) function -objects define corresponding methods of its instances. So in our -example, \verb\x.f\ is a valid method reference, since -\verb\MyClass.f\ is a function, but \verb\x.i\ is not, since -\verb\MyClass.i\ is not. But \verb\x.f\ is not the -same thing as \verb\MyClass.f\ --- it is a {\em method object}, not a -function object. - - -\subsection{Method objects} - -Usually, a method is called immediately, e.g.: - -\begin{verbatim} - x.f() -\end{verbatim} - -In our example, this will return the string \verb\'hello world'\. -However, it is not necessary to call a method right away: \verb\x.f\ -is a method object, and can be stored away and called at a later -moment, for example: - -\begin{verbatim} - xf = x.f - while 1: - print xf() -\end{verbatim} - -will continue to print \verb\hello world\ until the end of time. - -What exactly happens when a method is called? You may have noticed -that \verb\x.f()\ was called without an argument above, even though -the function definition for \verb\f\ specified an argument. What -happened to the argument? Surely Python raises an exception when a -function that requires an argument is called without any --- even if -the argument isn't actually used... - -Actually, you may have guessed the answer: the special thing about -methods is that the object is passed as the first argument of the -function. In our example, the call \verb\x.f()\ is exactly equivalent -to \verb\MyClass.f(x)\. In general, calling a method with a list of -{\em n} arguments is equivalent to calling the corresponding function -with an argument list that is created by inserting the method's object -before the first argument. - -If you still don't understand how methods work, a look at the -implementation can perhaps clarify matters. When an instance -attribute is referenced that isn't a data attribute, its class is -searched. If the name denotes a valid class attribute that is a -function object, a method object is created by packing (pointers to) -the instance object and the function object just found together in an -abstract object: this is the method object. When the method object is -called with an argument list, it is unpacked again, a new argument -list is constructed from the instance object and the original argument -list, and the function object is called with this new argument list. - - -\section{Random remarks} - - -[These should perhaps be placed more carefully...] - - -Data attributes override method attributes with the same name; to -avoid accidental name conflicts, which may cause hard-to-find bugs in -large programs, it is wise to use some kind of convention that -minimizes the chance of conflicts, e.g., capitalize method names, -prefix data attribute names with a small unique string (perhaps just -an underscore), or use verbs for methods and nouns for data attributes. - - -Data attributes may be referenced by methods as well as by ordinary -users (``clients'') of an object. In other words, classes are not -usable to implement pure abstract data types. In fact, nothing in -Python makes it possible to enforce data hiding --- it is all based -upon convention. (On the other hand, the Python implementation, -written in C, can completely hide implementation details and control -access to an object if necessary; this can be used by extensions to -Python written in C.) - - -Clients should use data attributes with care --- clients may mess up -invariants maintained by the methods by stamping on their data -attributes. Note that clients may add data attributes of their own to -an instance object without affecting the validity of the methods, as -long as name conflicts are avoided --- again, a naming convention can -save a lot of headaches here. - - -There is no shorthand for referencing data attributes (or other -methods!) from within methods. I find that this actually increases -the readability of methods: there is no chance of confusing local -variables and instance variables when glancing through a method. - - -Conventionally, the first argument of methods is often called -\verb\self\. This is nothing more than a convention: the name -\verb\self\ has absolutely no special meaning to Python. (Note, -however, that by not following the convention your code may be less -readable by other Python programmers, and it is also conceivable that -a {\em class browser} program be written which relies upon such a -convention.) - - -Any function object that is a class attribute defines a method for -instances of that class. It is not necessary that the function -definition is textually enclosed in the class definition: assigning a -function object to a local variable in the class is also ok. For -example: - -\begin{verbatim} - # Function defined outside the class - def f1(self, x, y): - return min(x, x+y) - - class C: - f = f1 - def g(self): - return 'hello world' - h = g -\end{verbatim} - -Now \verb\f\, \verb\g\ and \verb\h\ are all attributes of class -\verb\C\ that refer to function objects, and consequently they are all -methods of instances of \verb\C\ --- \verb\h\ being exactly equivalent -to \verb\g\. Note that this practice usually only serves to confuse -the reader of a program. - - -Methods may call other methods by using method attributes of the -\verb\self\ argument, e.g.: - -\begin{verbatim} - class Bag: - def empty(self): - self.data = [] - def add(self, x): - self.data.append(x) - def addtwice(self, x): - self.add(x) - self.add(x) -\end{verbatim} - - -The instantiation operation (``calling'' a class object) creates an -empty object. Many classes like to create objects in a known initial -state. Therefore a class may define a special method named -\verb\__init__\, like this: - -\begin{verbatim} - def __init__(self): - self.empty() -\end{verbatim} - -When a class defines an \verb\__init__\ method, class instantiation -automatically invokes \verb\__init__\ for the newly-created class -instance. So in the \verb\Bag\ example, a new and initialized instance -can be obtained by: - -\begin{verbatim} - x = Bag() -\end{verbatim} - -Of course, the \verb\__init__\ method may have arguments for greater -flexibility. In that case, arguments given to the class instantiation -operator are passed on to \verb\__init__\. For example, - -\bcode\begin{verbatim} ->>> class Complex: -... def __init__(self, realpart, imagpart): -... self.r = realpart -... self.i = imagpart -... ->>> x = Complex(3.0,-4.5) ->>> x.r, x.i -(3.0, -4.5) ->>> -\end{verbatim}\ecode -% -Methods may reference global names in the same way as ordinary -functions. The global scope associated with a method is the module -containing the class definition. (The class itself is never used as a -global scope!) While one rarely encounters a good reason for using -global data in a method, there are many legitimate uses of the global -scope: for one thing, functions and modules imported into the global -scope can be used by methods, as well as functions and classes defined -in it. Usually, the class containing the method is itself defined in -this global scope, and in the next section we'll find some good -reasons why a method would want to reference its own class! - - -\section{Inheritance} - -Of course, a language feature would not be worthy of the name ``class'' -without supporting inheritance. The syntax for a derived class -definition looks as follows: - -\begin{verbatim} - class DerivedClassName(BaseClassName): - <statement-1> - . - . - . - <statement-N> -\end{verbatim} - -The name \verb\BaseClassName\ must be defined in a scope containing -the derived class definition. Instead of a base class name, an -expression is also allowed. This is useful when the base class is -defined in another module, e.g., - -\begin{verbatim} - class DerivedClassName(modname.BaseClassName): -\end{verbatim} - -Execution of a derived class definition proceeds the same as for a -base class. When the class object is constructed, the base class is -remembered. This is used for resolving attribute references: if a -requested attribute is not found in the class, it is searched in the -base class. This rule is applied recursively if the base class itself -is derived from some other class. - -There's nothing special about instantiation of derived classes: -\verb\DerivedClassName()\ creates a new instance of the class. Method -references are resolved as follows: the corresponding class attribute -is searched, descending down the chain of base classes if necessary, -and the method reference is valid if this yields a function object. - -Derived classes may override methods of their base classes. Because -methods have no special privileges when calling other methods of the -same object, a method of a base class that calls another method -defined in the same base class, may in fact end up calling a method of -a derived class that overrides it. (For \Cpp{} programmers: all methods -in Python are ``virtual functions''.) - -An overriding method in a derived class may in fact want to extend -rather than simply replace the base class method of the same name. -There is a simple way to call the base class method directly: just -call \verb\BaseClassName.methodname(self, arguments)\. This is -occasionally useful to clients as well. (Note that this only works if -the base class is defined or imported directly in the global scope.) - - -\subsection{Multiple inheritance} - -Python supports a limited form of multiple inheritance as well. A -class definition with multiple base classes looks as follows: - -\begin{verbatim} - class DerivedClassName(Base1, Base2, Base3): - <statement-1> - . - . - . - <statement-N> -\end{verbatim} - -The only rule necessary to explain the semantics is the resolution -rule used for class attribute references. This is depth-first, -left-to-right. Thus, if an attribute is not found in -\verb\DerivedClassName\, it is searched in \verb\Base1\, then -(recursively) in the base classes of \verb\Base1\, and only if it is -not found there, it is searched in \verb\Base2\, and so on. - -(To some people breadth first---searching \verb\Base2\ and -\verb\Base3\ before the base classes of \verb\Base1\---looks more -natural. However, this would require you to know whether a particular -attribute of \verb\Base1\ is actually defined in \verb\Base1\ or in -one of its base classes before you can figure out the consequences of -a name conflict with an attribute of \verb\Base2\. The depth-first -rule makes no differences between direct and inherited attributes of -\verb\Base1\.) - -It is clear that indiscriminate use of multiple inheritance is a -maintenance nightmare, given the reliance in Python on conventions to -avoid accidental name conflicts. A well-known problem with multiple -inheritance is a class derived from two classes that happen to have a -common base class. While it is easy enough to figure out what happens -in this case (the instance will have a single copy of ``instance -variables'' or data attributes used by the common base class), it is -not clear that these semantics are in any way useful. - - -\section{Odds and ends} - -Sometimes it is useful to have a data type similar to the Pascal -``record'' or C ``struct'', bundling together a couple of named data -items. An empty class definition will do nicely, e.g.: - -\begin{verbatim} - class Employee: - pass - - john = Employee() # Create an empty employee record - - # Fill the fields of the record - john.name = 'John Doe' - john.dept = 'computer lab' - john.salary = 1000 -\end{verbatim} - - -A piece of Python code that expects a particular abstract data type -can often be passed a class that emulates the methods of that data -type instead. For instance, if you have a function that formats some -data from a file object, you can define a class with methods -\verb\read()\ and \verb\readline()\ that gets the data from a string -buffer instead, and pass it as an argument. (Unfortunately, this -technique has its limitations: a class can't define operations that -are accessed by special syntax such as sequence subscripting or -arithmetic operators, and assigning such a ``pseudo-file'' to -\verb\sys.stdin\ will not cause the interpreter to read further input -from it.) - - -Instance method objects have attributes, too: \verb\m.im_self\ is the -object of which the method is an instance, and \verb\m.im_func\ is the -function object corresponding to the method. - - -\chapter{Recent Additions} - -Python is an evolving language. Since this tutorial was last -thoroughly revised, several new features have been added to the -language. While ideally I should revise the tutorial to incorporate -them in the mainline of the text, lack of time currently requires me -to take a more modest approach. In this chapter I will briefly list the -most important improvements to the language and how you can use them -to your benefit. - -\section{The Last Printed Expression} - -In interactive mode, the last printed expression is assigned to the -variable \code{_}. This means that when you are using Python as a -desk calculator, it is somewhat easier to continue calculations, for -example: - -\begin{verbatim} - >>> tax = 17.5 / 100 - >>> price = 3.50 - >>> price * tax - 0.6125 - >>> price + _ - 4.1125 - >>> round(_, 2) - 4.11 - >>> -\end{verbatim} - -For reasons too embarrassing to explain, this variable is implemented -as a built-in (living in the module \code{__builtin__}), so it should -be treated as read-only by the user. I.e. don't explicitly assign a -value to it --- you would create an independent local variable with -the same name masking the built-in variable with its magic behavior. - -\section{String Literals} - -\subsection{Double Quotes} - -Python can now also use double quotes to surround string literals, -e.g. \verb\"this doesn't hurt a bit"\. There is no semantic -difference between strings surrounded by single or double quotes. - -\subsection{Continuation Of String Literals} - -String literals can span multiple lines by escaping newlines with -backslashes, e.g. - -\begin{verbatim} - hello = "This is a rather long string containing\n\ - several lines of text just as you would do in C.\n\ - Note that whitespace at the beginning of the line is\ - significant.\n" - print hello -\end{verbatim} - -which would print the following: -\begin{verbatim} - This is a rather long string containing - several lines of text just as you would do in C. - Note that whitespace at the beginning of the line is significant. -\end{verbatim} - -\subsection{Triple-quoted strings} - -In some cases, when you need to include really long strings (e.g. -containing several paragraphs of informational text), it is annoying -that you have to terminate each line with \verb@\n\@, especially if -you would like to reformat the text occasionally with a powerful text -editor like Emacs. For such situations, ``triple-quoted'' strings can -be used, e.g. - -\begin{verbatim} - hello = """ - - This string is bounded by triple double quotes (3 times "). - Unescaped newlines in the string are retained, though \ - it is still possible\nto use all normal escape sequences. - - Whitespace at the beginning of a line is - significant. If you need to include three opening quotes - you have to escape at least one of them, e.g. \""". - - This string ends in a newline. - """ -\end{verbatim} - -Triple-quoted strings can be surrounded by three single quotes as -well, again without semantic difference. - -\subsection{String Literal Juxtaposition} - -One final twist: you can juxtapose multiple string literals. Two or -more adjacent string literals (but not arbitrary expressions!) -separated only by whitespace will be concatenated (without intervening -whitespace) into a single string object at compile time. This makes -it possible to continue a long string on the next line without -sacrificing indentation or performance, unlike the use of the string -concatenation operator \verb\+\ or the continuation of the literal -itself on the next line (since leading whitespace is significant -inside all types of string literals). Note that this feature, like -all string features except triple-quoted strings, is borrowed from -Standard C. - -\section{The Formatting Operator} - -\subsection{Basic Usage} - -The chapter on output formatting is really out of date: there is now -an almost complete interface to C-style printf formats. This is done -by overloading the modulo operator (\verb\%\) for a left operand -which is a string, e.g. - -\begin{verbatim} - >>> import math - >>> print 'The value of PI is approximately %5.3f.' % math.pi - The value of PI is approximately 3.142. - >>> -\end{verbatim} - -If there is more than one format in the string you pass a tuple as -right operand, e.g. - -\begin{verbatim} - >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} - >>> for name, phone in table.items(): - ... print '%-10s ==> %10d' % (name, phone) - ... - Jack ==> 4098 - Dcab ==> 8637678 - Sjoerd ==> 4127 - >>> -\end{verbatim} - -Most formats work exactly as in C and require that you pass the proper -type (however, if you don't you get an exception, not a core dump). -The \verb\%s\ format is more relaxed: if the corresponding argument is -not a string object, it is converted to string using the \verb\str()\ -built-in function. Using \verb\*\ to pass the width or precision in -as a separate (integer) argument is supported. The C formats -\verb\%n\ and \verb\%p\ are not supported. - -\subsection{Referencing Variables By Name} - -If you have a really long format string that you don't want to split -up, it would be nice if you could reference the variables to be -formatted by name instead of by position. This can be done by using -an extension of C formats using the form \verb\%(name)format\, e.g. - -\begin{verbatim} - >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} - >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table - Jack: 4098; Sjoerd: 4127; Dcab: 8637678 - >>> -\end{verbatim} - -This is particularly useful in combination with the new built-in -\verb\vars()\ function, which returns a dictionary containing all -local variables. - -\section{Optional Function Arguments} - -It is now possible to define functions with a variable number of -arguments. There are two forms, which can be combined. - -\subsection{Default Argument Values} - -The most useful form is to specify a default value for one or more -arguments. This creates a function that can be called with fewer -arguments than it is defined, e.g. - -\begin{verbatim} - def ask_ok(prompt, retries = 4, complaint = 'Yes or no, please!'): - while 1: - ok = raw_input(prompt) - if ok in ('y', 'ye', 'yes'): return 1 - if ok in ('n', 'no', 'nop', 'nope'): return 0 - retries = retries - 1 - if retries < 0: raise IOError, 'refusenik user' - print complaint -\end{verbatim} - -This function can be called either like this: -\verb\ask_ok('Do you really want to quit?')\ or like this: -\verb\ask_ok('OK to overwrite the file?', 2)\. - -The default values are evaluated at the point of function definition -in the {\em defining} scope, so that e.g. - -\begin{verbatim} - i = 5 - def f(arg = i): print arg - i = 6 - f() -\end{verbatim} - -will print \verb\5\. - -\subsection{Arbitrary Argument Lists} - -It is also possible to specify that a function can be called with an -arbitrary number of arguments. These arguments will be wrapped up in -a tuple. Before the variable number of arguments, zero or more normal -arguments may occur, e.g. - -\begin{verbatim} - def fprintf(file, format, *args): - file.write(format % args) -\end{verbatim} - -This feature may be combined with the previous, e.g. - -\begin{verbatim} - def but_is_it_useful(required, optional = None, *remains): - print "I don't know" -\end{verbatim} - -\section{Lambda And Functional Programming Tools} - -\subsection{Lambda Forms} - -By popular demand, a few features commonly found in functional -programming languages and Lisp have been added to Python. With the -\verb\lambda\ keyword, small anonymous functions can be created. -Here's a function that returns the sum of its two arguments: -\verb\lambda a, b: a+b\. Lambda forms can be used wherever function -objects are required. They are syntactically restricted to a single -expression. Semantically, they are just syntactic sugar for a normal -function definition. Like nested function definitions, lambda forms -cannot reference variables from the containing scope, but this can be -overcome through the judicious use of default argument values, e.g. - -\begin{verbatim} - def make_incrementor(n): - return lambda x, incr=n: x+incr -\end{verbatim} - -\subsection{Map, Reduce and Filter} - -Three new built-in functions on sequences are good candidate to pass -lambda forms. - -\subsubsection{Map.} - -\verb\map(function, sequence)\ calls \verb\function(item)\ for each of -the sequence's items and returns a list of the return values. For -example, to compute some cubes: - -\begin{verbatim} - >>> map(lambda x: x*x*x, range(1, 11)) - [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] - >>> -\end{verbatim} - -More than one sequence may be passed; the function must then have as -many arguments as there are sequences and is called with the -corresponding item from each sequence (or \verb\None\ if some sequence -is shorter than another). If \verb\None\ is passed for the function, -a function returning its argument(s) is substituted. - -Combining these two special cases, we see that -\verb\map(None, list1, list2)\ is a convenient way of turning a pair -of lists into a list of pairs. For example: - -\begin{verbatim} - >>> seq = range(8) - >>> map(None, seq, map(lambda x: x*x, seq)) - [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)] - >>> -\end{verbatim} - -\subsubsection{Filter.} - -\verb\filter(function, sequence)\ returns a sequence (of the same -type, if possible) consisting of those items from the sequence for -which \verb\function(item)\ is true. For example, to compute some -primes: - -\begin{verbatim} - >>> filter(lambda x: x%2 != 0 and x%3 != 0, range(2, 25)) - [5, 7, 11, 13, 17, 19, 23] - >>> -\end{verbatim} - -\subsubsection{Reduce.} - -\verb\reduce(function, sequence)\ returns a single value constructed -by calling the (binary) function on the first two items of the -sequence, then on the result and the next item, and so on. For -example, to compute the sum of the numbers 1 through 10: - -\begin{verbatim} - >>> reduce(lambda x, y: x+y, range(1, 11)) - 55 - >>> -\end{verbatim} - -If there's only one item in the sequence, its value is returned; if -the sequence is empty, an exception is raised. - -A third argument can be passed to indicate the starting value. In this -case the starting value is returned for an empty sequence, and the -function is first applied to the starting value and the first sequence -item, then to the result and the next item, and so on. For example, - -\begin{verbatim} - >>> def sum(seq): - ... return reduce(lambda x, y: x+y, seq, 0) - ... - >>> sum(range(1, 11)) - 55 - >>> sum([]) - 0 - >>> -\end{verbatim} - -\section{Continuation Lines Without Backslashes} - -While the general mechanism for continuation of a source line on the -next physical line remains to place a backslash on the end of the -line, expressions inside matched parentheses (or square brackets, or -curly braces) can now also be continued without using a backslash. -This is particularly useful for calls to functions with many -arguments, and for initializations of large tables. - -For example: - -\begin{verbatim} - month_names = ['Januari', 'Februari', 'Maart', - 'April', 'Mei', 'Juni', - 'Juli', 'Augustus', 'September', - 'Oktober', 'November', 'December'] -\end{verbatim} - -and - -\begin{verbatim} - CopyInternalHyperLinks(self.context.hyperlinks, - copy.context.hyperlinks, - uidremap) -\end{verbatim} - -\section{Regular Expressions} - -While C's printf-style output formats, transformed into Python, are -adequate for most output formatting jobs, C's scanf-style input -formats are not very powerful. Instead of scanf-style input, Python -offers Emacs-style regular expressions as a powerful input and -scanning mechanism. Read the corresponding section in the Library -Reference for a full description. - -\section{Generalized Dictionaries} - -The keys of dictionaries are no longer restricted to strings --- they -can be any immutable basic type including strings, numbers, tuples, or -(certain) class instances. (Lists and dictionaries are not acceptable -as dictionary keys, in order to avoid problems when the object used as -a key is modified.) - -Dictionaries have two new methods: \verb\d.values()\ returns a list of -the dictionary's values, and \verb\d.items()\ returns a list of the -dictionary's (key, value) pairs. Like \verb\d.keys()\, these -operations are slow for large dictionaries. Examples: - -\begin{verbatim} - >>> d = {100: 'honderd', 1000: 'duizend', 10: 'tien'} - >>> d.keys() - [100, 10, 1000] - >>> d.values() - ['honderd', 'tien', 'duizend'] - >>> d.items() - [(100, 'honderd'), (10, 'tien'), (1000, 'duizend')] - >>> -\end{verbatim} - -\section{Miscellaneous New Built-in Functions} - -The function \verb\vars()\ returns a dictionary containing the current -local variables. With a module argument, it returns that module's -global variables. The old function \verb\dir(x)\ returns -\verb\vars(x).keys()\. - -The function \verb\round(x)\ returns a floating point number rounded -to the nearest integer (but still expressed as a floating point -number). E.g. \verb\round(3.4) == 3.0\ and \verb\round(3.5) == 4.0\. -With a second argument it rounds to the specified number of digits, -e.g. \verb\round(math.pi, 4) == 3.1416\ or even -\verb\round(123.4, -2) == 100.0\. - -The function \verb\hash(x)\ returns a hash value for an object. -All object types acceptable as dictionary keys have a hash value (and -it is this hash value that the dictionary implementation uses). - -The function \verb\id(x)\ return a unique identifier for an object. -For two objects x and y, \verb\id(x) == id(y)\ if and only if -\verb\x is y\. (In fact the object's address is used.) - -The function \verb\hasattr(x, name)\ returns whether an object has an -attribute with the given name (a string value). The function -\verb\getattr(x, name)\ returns the object's attribute with the given -name. The function \verb\setattr(x, name, value)\ assigns a value to -an object's attribute with the given name. These three functions are -useful if the attribute names are not known beforehand. Note that -\verb\getattr(x, 'spam')\ is equivalent to \verb\x.spam\, and -\verb\setattr(x, 'spam', y)\ is equivalent to \verb\x.spam = y\. By -definition, \verb\hasattr(x, name)\ returns true if and only if -\verb\getattr(x, name)\ returns without raising an exception. - -\section{Else Clause For Try Statement} - -The \verb\try...except\ statement now has an optional \verb\else\ -clause, which must follow all \verb\except\ clauses. It is useful to -place code that must be executed if the \verb\try\ clause does not -raise an exception. For example: - -\begin{verbatim} - for arg in sys.argv: - try: - f = open(arg, 'r') - except IOError: - print 'cannot open', arg - else: - print arg, 'has', len(f.readlines()), 'lines' - f.close() -\end{verbatim} - - -\section{New Class Features in Release 1.1} - -Some changes have been made to classes: the operator overloading -mechanism is more flexible, providing more support for non-numeric use -of operators (including calling an object as if it were a function), -and it is possible to trap attribute accesses. - -\subsection{New Operator Overloading} - -It is no longer necessary to coerce both sides of an operator to the -same class or type. A class may still provide a \code{__coerce__} -method, but this method may return objects of different types or -classes if it feels like it. If no \code{__coerce__} is defined, any -argument type or class is acceptable. - -In order to make it possible to implement binary operators where the -right-hand side is a class instance but the left-hand side is not, -without using coercions, right-hand versions of all binary operators -may be defined. These have an `r' prepended to their name, -e.g. \code{__radd__}. - -For example, here's a very simple class for representing times. Times -are initialized from a number of seconds (like time.time()). Times -are printed like this: \code{Wed Mar 15 12:28:48 1995}. Subtracting -two Times gives their difference in seconds. Adding or subtracting a -Time and a number gives a new Time. You can't add two times, nor can -you subtract a Time from a number. - -\begin{verbatim} -import time - -class Time: - def __init__(self, seconds): - self.seconds = seconds - def __repr__(self): - return time.ctime(self.seconds) - def __add__(self, x): - return Time(self.seconds + x) - __radd__ = __add__ # support for x+t - def __sub__(self, x): - if hasattr(x, 'seconds'): # test if x could be a Time - return self.seconds - x.seconds - else: - return self.seconds - x - -now = Time(time.time()) -tomorrow = 24*3600 + now -yesterday = now - today -print tomorrow - yesterday # prints 172800 -\end{verbatim} - -\subsection{Trapping Attribute Access} - -You can define three new ``magic'' methods in a class now: -\code{__getattr__(self, name)}, \code{__setattr__(self, name, value)} -and \code{__delattr__(self, name)}. - -The \code{__getattr__} method is called when an attribute access fails, -i.e. when an attribute access would otherwise raise AttributeError --- -this is {\em after} the instance's dictionary and its class hierarchy -have been searched for the named attribute. Note that if this method -attempts to access any undefined instance attribute it will be called -recursively! - -The \code{__setattr__} and \code{__delattr__} methods are called when -assignment to, respectively deletion of an attribute are attempted. -They are called {\em instead} of the normal action (which is to insert -or delete the attribute in the instance dictionary). If either of -these methods most set or delete any attribute, they can only do so by -using the instance dictionary directly --- \code{self.__dict__} --- else -they would be called recursively. - -For example, here's a near-universal ``Wrapper'' class that passes all -its attribute accesses to another object. Note how the -\code{__init__} method inserts the wrapped object in -\code{self.__dict__} in order to avoid endless recursion -(\code{__setattr__} would call \code{__getattr__} which would call -itself recursively). - -\begin{verbatim} -class Wrapper: - def __init__(self, wrapped): - self.__dict__['wrapped'] = wrapped - def __getattr__(self, name): - return getattr(self.wrapped, name) - def __setattr__(self, name, value): - setattr(self.wrapped, name, value) - def __delattr__(self, name): - delattr(self.wrapped, name) - -import sys -f = Wrapper(sys.stdout) -f.write('hello world\n') # prints 'hello world' -\end{verbatim} - -A simpler example of \code{__getattr__} is an attribute that is -computed each time (or the first time) it it accessed. For instance: - -\begin{verbatim} -from math import pi - -class Circle: - def __init__(self, radius): - self.radius = radius - def __getattr__(self, name): - if name == 'circumference': - return 2 * pi * self.radius - if name == 'diameter': - return 2 * self.radius - if name == 'area': - return pi * pow(self.radius, 2) - raise AttributeError, name -\end{verbatim} - -\subsection{Calling a Class Instance} - -If a class defines a method \code{__call__} it is possible to call its -instances as if they were functions. For example: - -\begin{verbatim} -class PresetSomeArguments: - def __init__(self, func, *args): - self.func, self.args = func, args - def __call__(self, *args): - return apply(self.func, self.args + args) - -f = PresetSomeArguments(pow, 2) # f(i) computes powers of 2 -for i in range(10): print f(i), # prints 1 2 4 8 16 32 64 128 256 512 -print # append newline -\end{verbatim} - - -\chapter{New in Release 1.2} - - -This chapter describes even more recent additions to the Python -language and library. - - -\section{New Class Features} - -The semantics of \code{__coerce__} have been changed to be more -reasonable. As an example, the new standard module \code{Complex} -implements fairly complete complex numbers using this. Additional -examples of classes with and without \code{__coerce__} methods can be -found in the \code{Demo/classes} subdirectory, modules \code{Rat} and -\code{Dates}. - -If a class defines no \code{__coerce__} method, this is equivalent to -the following definition: - -\begin{verbatim} -def __coerce__(self, other): return self, other -\end{verbatim} - -If \code{__coerce__} coerces itself to an object of a different type, -the operation is carried out using that type --- in release 1.1, this -would cause an error. - -Comparisons involving class instances now invoke \code{__coerce__} -exactly as if \code{cmp(x, y)} were a binary operator like \code{+} -(except if \code{x} and \code{y} are the same object). - -\section{Unix Signal Handling} - -On Unix, Python now supports signal handling. The module -\code{signal} exports functions \code{signal}, \code{pause} and -\code{alarm}, which act similar to their Unix counterparts. The -module also exports the conventional names for the various signal -classes (also usable with \code{os.kill()}) and \code{SIG_IGN} and -\code{SIG_DFL}. See the section on \code{signal} in the Library -Reference Manual for more information. - -\section{Exceptions Can Be Classes} - -User-defined exceptions are no longer limited to being string objects ---- they can be identified by classes as well. Using this mechanism it -is possible to create extensible hierarchies of exceptions. - -There are two new valid (semantic) forms for the raise statement: - -\begin{verbatim} -raise Class, instance - -raise instance -\end{verbatim} - -In the first form, \code{instance} must be an instance of \code{Class} -or of a class derived from it. The second form is a shorthand for - -\begin{verbatim} -raise instance.__class__, instance -\end{verbatim} - -An except clause may list classes as well as string objects. A class -in an except clause is compatible with an exception if it is the same -class or a base class thereof (but not the other way around --- an -except clause listing a derived class is not compatible with a base -class). For example, the following code will print B, C, D in that -order: - -\begin{verbatim} -class B: - pass -class C(B): - pass -class D(C): - pass - -for c in [B, C, D]: - try: - raise c() - except D: - print "D" - except C: - print "C" - except B: - print "B" -\end{verbatim} - -Note that if the except clauses were reversed (with ``\code{except B}'' -first), it would have printed B, B, B --- the first matching except -clause is triggered. - -When an error message is printed for an unhandled exception which is a -class, the class name is printed, then a colon and a space, and -finally the instance converted to a string using the built-in function -\code{str()}. - -In this release, the built-in exceptions are still strings. - - -\section{Object Persistency and Object Copying} - -Two new modules, \code{pickle} and \code{shelve}, support storage and -retrieval of (almost) arbitrary Python objects on disk, using the -\code{dbm} package. A third module, \code{copy}, provides flexible -object copying operations. More information on these modules is -provided in the Library Reference Manual. - -\subsection{Persistent Objects} - -The module \code{pickle} provides a general framework for objects to -disassemble themselves into a stream of bytes and to reassemble such a -stream back into an object. It copes with reference sharing, -recursive objects and instances of user-defined classes, but not -(directly) with objects that have ``magical'' links into the operating -system such as open files, sockets or windows. - -The \code{pickle} module defines a simple protocol whereby -user-defined classes can control how they are disassembled and -assembled. The method \code{__getinitargs__()}, if defined, returns -the argument list for the constructor to be used at assembly time (by -default the constructor is called without arguments). The methods -\code{__getstate__()} and \code{__setstate__()} are used to pass -additional state from disassembly to assembly; by default the -instance's \code{__dict__} is passed and restored. - -Note that \code{pickle} does not open or close any files --- it can be -used equally well for moving objects around on a network or store them -in a database. For ease of debugging, and the inevitable occasional -manual patch-up, the constructed byte streams consist of printable -\ASCII{} characters only (though it's not designed to be pretty). - -The module \code{shelve} provides a simple model for storing objects -on files. The operation \code{shelve.open(filename)} returns a -``shelf'', which is a simple persistent database with a -dictionary-like interface. Database keys are strings, objects stored -in the database can be anything that \code{pickle} will handle. - -\subsection{Copying Objects} - -The module \code{copy} exports two functions: \code{copy()} and -\code{deepcopy()}. The \code{copy()} function returns a ``shallow'' -copy of an object; \code{deepcopy()} returns a ``deep'' copy. The -difference between shallow and deep copying is only relevant for -compound objects (objects that contain other objects, like lists or -class instances): - -\begin{itemize} - -\item -A shallow copy constructs a new compound object and then (to the -extent possible) inserts {\em the same objects} into in that the -original contains. - -\item -A deep copy constructs a new compound object and then, recursively, -inserts {\em copies} into it of the objects found in the original. - -\end{itemize} - -Both functions have the same restrictions and use the same protocols -as \code{pickle} --- user-defined classes can control how they are -copied by providing methods named \code{__getinitargs__()}, -\code{__getstate__()} and \code{__setstate__()}. - - -\section{Documentation Strings} - -A variety of objects now have a new attribute, \code{__doc__}, which -is supposed to contain a documentation string (if no documentation is -present, the attribute is \code{None}). New syntax, compatible with -the old interpreter, allows for convenient initialization of the -\code{__doc__} attribute of modules, classes and functions by placing -a string literal by itself as the first statement in the suite. It -must be a literal --- an expression yielding a string object is not -accepted as a documentation string, since future tools may need to -derive documentation from source by parsing. - -Here is a hypothetical, amply documented module called \code{Spam}: - -\begin{verbatim} -"""Spam operations. - -This module exports two classes, a function and an exception: - -class Spam: full Spam functionality --- three can sizes -class SpamLight: limited Spam functionality --- only one can size - -def open(filename): open a file and return a corresponding Spam or -SpamLight object - -GoneOff: exception raised for errors; should never happen - -Note that it is always possible to convert a SpamLight object to a -Spam object by a simple method call, but that the reverse operation is -generally costly and may fail for a number of reasons. -""" - -class SpamLight: - """Limited spam functionality. - - Supports a single can size, no flavor, and only hard disks. - """ - - def __init__(self, size=12): - """Construct a new SpamLight instance. - - Argument is the can size. - """ - # etc. - - # etc. - -class Spam(SpamLight): - """Full spam functionality. - - Supports three can sizes, two flavor varieties, and all floppy - disk formats still supported by current hardware. - """ - - def __init__(self, size1=8, size2=12, size3=20): - """Construct a new Spam instance. - - Arguments are up to three can sizes. - """ - # etc. - - # etc. - -def open(filename = "/dev/null"): - """Open a can of Spam. - - Argument must be an existing file. - """ - # etc. - -class GoneOff: - """Class used for Spam exceptions. - - There shouldn't be any. - """ - pass -\end{verbatim} - -After executing ``\code{import Spam}'', the following expressions -return the various documentation strings from the module: - -\begin{verbatim} -Spam.__doc__ -Spam.SpamLight.__doc__ -Spam.SpamLight.__init__.__doc__ -Spam.Spam.__doc__ -Spam.Spam.__init__.__doc__ -Spam.open.__doc__ -Spam.GoneOff.__doc__ -\end{verbatim} - -There are emerging conventions about the content and formatting of -documentation strings. - -The first line should always be a short, concise summary of the -object's purpose. For brevity, it should not explicitly state the -object's name or type, since these are available by other means -(except if the name happens to be a verb describing a function's -operation). This line should begin with a capital letter and end with -a period. - -If there are more lines in the documentation string, the second line -should be blank, visually separating the summary from the rest of the -description. The following lines should be one of more of paragraphs -describing the objects calling conventions, its side effects, etc. - -Some people like to copy the Emacs convention of using UPPER CASE for -function parameters --- this often saves a few words or lines. - -The Python parser does not strip indentation from multi-line string -literals in Python, so tools that process documentation have to strip -indentation. This is done using the following convention. The first -non-blank line {\em after} the first line of the string determines the -amount of indentation for the entire documentation string. (We can't -use the first line since it is generally adjacent to the string's -opening quotes so its indentation is not apparent in the string -literal.) Whitespace ``equivalent'' to this indentation is then -stripped from the start of all lines of the string. Lines that are -indented less should not occur, but if they occur all their leading -whitespace should be stripped. Equivalence of whitespace should be -tested after expansion of tabs (to 8 spaces, normally). - -In this release, few of the built-in or standard functions and modules -have documentation strings. - - -\section{Customizing Import and Built-Ins} - -In preparation for a ``restricted execution mode'' which will be -usable to run code received from an untrusted source (such as a WWW -server or client), the mechanism by which modules are imported has -been redesigned. It is now possible to provide your own function -\code{__import__} which is called whenever an \code{import} statement -is executed. There's a built-in function \code{__import__} which -provides the default implementation, but more interesting, the various -steps it takes are available separately from the new built-in module -\code{imp}. (See the section on \code{imp} in the Library Reference -Manual for more information on this module -- it also contains a -complete example of how to write your own \code{__import__} function.) - -When you do \code{dir()} in a fresh interactive interpreter you will -see another ``secret'' object that's present in every module: -\code{__builtins__}. This is either a dictionary or a module -containing the set of built-in objects used by functions defined in -current module. Although normally all modules are initialized with a -reference to the same dictionary, it is now possible to use a -different set of built-ins on a per-module basis. Together with the -fact that the \code{import} statement uses the \code{__import__} -function it finds in the importing modules' dictionary of built-ins, -this forms the basis for a future restricted execution mode. - - -\section{Python and the World-Wide Web} - -There is a growing number of modules available for writing WWW tools. -The previous release already sported modules \code{gopherlib}, -\code{ftplib}, \code{httplib} and \code{urllib} (which unifies the -other three) for accessing data through the commonest WWW protocols. -This release also provides \code{cgi}, to ease the writing of -server-side scripts that use the Common Gateway Interface protocol, -supported by most WWW servers. The module \code{urlparse} provides -precise parsing of a URL string into its components (address scheme, -network location, path, parameters, query, and fragment identifier). - -A rudimentary, parser for HTML files is available in the module -\code{htmllib}. It currently supports a subset of HTML 1.0 (if you -bring it up to date, I'd love to receive your fixes!). Unfortunately -Python seems to be too slow for real-time parsing and formatting of -HTML such as required by interactive WWW browsers --- but it's good -enough to write a ``robot'' (an automated WWW browser that searches -the web for information). - - -\section{Miscellaneous} - -\begin{itemize} - -\item -The \code{socket} module now exports all the needed constants used for -socket operations, such as \code{SO_BROADCAST}. - -\item -The functions \code{popen()} and \code{fdopen()} in the \code{os} -module now follow the pattern of the built-in function \code{open()}: -the default mode argument is \code{'r'} and the optional third -argument specifies the buffer size, where \code{0} means unbuffered, -\code{1} means line-buffered, and any larger number means the size of -the buffer in bytes. - -\end{itemize} - - -\chapter{New in Release 1.3} - - -This chapter describes yet more recent additions to the Python -language and library. - - -\section{Keyword Arguments} - -Functions and methods written in Python can now be called using -keyword arguments of the form \code{\var{keyword} = \var{value}}. For -instance, the following function: - -\begin{verbatim} -def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): - print "-- This parrot wouldn't", action, - print "if you put", voltage, "Volts through it." - print "-- Lovely plumage, the", type - print "-- It's", state, "!" -\end{verbatim} - -could be called in any of the following ways: - -\begin{verbatim} -parrot(1000) -parrot(action = 'VOOOOOM', voltage = 1000000) -parrot('a thousand', state = 'pushing up the daisies') -parrot('a million', 'bereft of life', 'jump') -\end{verbatim} - -but the following calls would all be invalid: - -\begin{verbatim} -parrot() # required argument missing -parrot(voltage=5.0, 'dead') # non-keyword argument following keyword -parrot(110, voltage=220) # duplicate value for argument -parrot(actor='John Cleese') # unknown keyword -\end{verbatim} - -In general, an argument list must have the form: zero or more -positional arguments followed by zero or more keyword arguments, where -the keywords must be chosen from the formal parameter names. It's not -important whether a formal parameter has a default value or not. No -argument must receive a value more than once -- formal parameter names -corresponding to positional arguments cannot be used as keywords in -the same calls. - -Note that no special syntax is required to allow a function to be -called with keyword arguments. The additional costs incurred by -keyword arguments are only present when a call uses them. - -(As far as I know, these rules are exactly the same as used by -Modula-3, even if they are enforced by totally different means. This -is intentional.) - -When a final formal parameter of the form \code{**\var{name}} is -present, it receives a dictionary containing all keyword arguments -whose keyword doesn't correspond to a formal parameter. This may be -combined with a formal parameter of the form \code{*\var{name}} which -receives a tuple containing the positional arguments beyond the formal -parameter list. (\code{*\var{name}} must occur before -\code{**\var{name}}.) For example, if we define a function like this: - -\begin{verbatim} -def cheeseshop(kind, *arguments, **keywords): - print "-- Do you have any", kind, '?' - print "-- I'm sorry, we're all out of", kind - for arg in arguments: print arg - print '-'*40 - for kw in keywords.keys(): print kw, ':', keywords[kw] -\end{verbatim} - -It could be called like this: - -\begin{verbatim} -cheeseshop('Limburger', "It's very runny, sir.", - "It's really very, VERY runny, sir.", - client='John Cleese', - shopkeeper='Michael Palin', - sketch='Cheese Shop Sketch') -\end{verbatim} - -and of course it would print: - -\begin{verbatim} --- Do you have any Limburger ? --- I'm sorry, we're all out of Limburger -It's very runny, sir. -It's really very, VERY runny, sir. ----------------------------------------- -client : John Cleese -shopkeeper : Michael Palin -sketch : Cheese Shop Sketch -\end{verbatim} - -Consequences of this change include: - -\begin{itemize} - -\item -The built-in function \code{apply()} now has an optional third -argument, which is a dictionary specifying any keyword arguments to be -passed. For example, -\begin{verbatim} -apply(parrot, (), {'voltage': 20, 'action': 'voomm'}) -\end{verbatim} -is equivalent to -\begin{verbatim} -parrot(voltage=20, action='voomm') -\end{verbatim} - -\item -There is also a mechanism for functions and methods defined in an -extension module (i.e., implemented in C or C++) to receive a -dictionary of their keyword arguments. By default, such functions do -not accept keyword arguments, since the argument names are not -available to the interpreter. - -\item -In the effort of implementing keyword arguments, function and -especially method calls have been sped up significantly -- for a -method with ten formal parameters, the call overhead has been cut in -half; for a function with one formal parameters, the overhead has been -reduced by a third. - -\item -The format of \code{.pyc} files has changed (again). - -\item -The \code{access} statement has been disabled. The syntax is still -recognized but no code is generated for it. (There were some -unpleasant interactions with changes for keyword arguments, and my -plan is to get rid of \code{access} altogether in favor of a different -approach.) - -\end{itemize} - -\section{Changes to the WWW and Internet tools} - -\begin{itemize} - -\item -The \code{htmllib} module has been rewritten in an incompatible -fashion. The new version is considerably more complete (HTML 2.0 -except forms, but including all ISO-8859-1 entity definitions), and -easy to use. Small changes to \code{sgmllib} have also been made, to -better match the tokenization of HTML as recognized by other web -tools. - -\item -A new module \code{formatter} has been added, for use with the new -\code{htmllib} module. - -\item -The \code{urllib}and \code{httplib} modules have been changed somewhat -to allow overriding unknown URL types and to support authentication. -They now use \code{mimetools.Message} instead of \code{rfc822.Message} -to parse headers. The \code{endrequest()} method has been removed -from the HTTP class since it breaks the interaction with some servers. - -\item -The \code{rfc822.Message} class has been changed to allow a flag to be -passed in that says that the file is unseekable. - -\item -The \code{ftplib} module has been fixed to be (hopefully) more robust -on Linux. - -\item -Several new operations that are optionally supported by servers have -been added to \code{nntplib}: \code{xover}, \code{xgtitle}, -\code{xpath} and \code{date}. % thanks to Kevan Heydon - -\end{itemize} - -\section{Other Language Changes} - -\begin{itemize} - -\item -The \code{raise} statement now takes an optional argument which -specifies the traceback to be used when printing the exception's stack -trace. This must be a traceback object, such as found in -\code{sys.exc_traceback}. When omitted or given as \code{None}, the -old behavior (to generate a stack trace entry for the current stack -frame) is used. - -\item -The tokenizer is now more tolerant of alien whitespace. Control-L in -the leading whitespace of a line resets the column number to zero, -while Control-R just before the end of the line is ignored. - -\end{itemize} - -\section{Changes to Built-in Operations} - -\begin{itemize} - -\item -For file objects, \code{\var{f}.read(0)} and -\code{\var{f}.readline(0)} now return an empty string rather than -reading an unlimited number of bytes. For the latter, omit the -argument altogether or pass a negative value. - -\item -A new system variable, \code{sys.platform}, has been added. It -specifies the current platform, e.g. \code{sunos5} or \code{linux1}. - -\item -The built-in functions \code{input()} and \code{raw_input()} now use -the GNU readline library when it has been configured (formerly, only -interactive input to the interpreter itself was read using GNU -readline). The GNU readline library provides elaborate line editing -and history. The Python debugger (\code{pdb}) is the first -beneficiary of this change. - -\item -Two new built-in functions, \code{globals()} and \code{locals()}, -provide access to dictionaries containming current global and local -variables, respectively. (These augment rather than replace -\code{vars()}, which returns the current local variables when called -without an argument, and a module's global variables when called with -an argument of type module.) - -\item -The built-in function \code{compile()} now takes a third possible -value for the kind of code to be compiled: specifying \code{'single'} -generates code for a single interactive statement, which prints the -output of expression statements that evaluate to something else than -\code{None}. - -\end{itemize} - -\section{Library Changes} - -\begin{itemize} - -\item -There are new module \code{ni} and \code{ihooks} that support -importing modules with hierarchical names such as \code{A.B.C}. This -is enabled by writing \code{import ni; ni.ni()} at the very top of the -main program. These modules are amply documented in the Python -source. - -\item -The module \code{rexec} has been rewritten (incompatibly) to define a -class and to use \code{ihooks}. - -\item -The \code{string.split()} and \code{string.splitfields()} functions -are now the same function (the presence or absence of the second -argument determines which operation is invoked); similar for -\code{string.join()} and \code{string.joinfields()}. - -\item -The \code{Tkinter} module and its helper \code{Dialog} have been -revamped to use keyword arguments. Tk 4.0 is now the standard. A new -module \code{FileDialog} has been added which implements standard file -selection dialogs. - -\item -The optional built-in modules \code{dbm} and \code{gdbm} are more -coordinated --- their \code{open()} functions now take the same values -for their \var{flag} argument, and the \var{flag} and \var{mode} -argument have default values (to open the database for reading only, -and to create the database with mode \code{0666} minuse the umask, -respectively). The memory leaks have finally been fixed. - -\item -A new dbm-like module, \code{bsddb}, has been added, which uses the -BSD DB package's hash method. % thanks to David Ely - -\item -A portable (though slow) dbm-clone, implemented in Python, has been -added for systems where none of the above is provided. It is aptly -dubbed \code{dumbdbm}. - -\item -The module \code{anydbm} provides a unified interface to \code{bsddb}, -\code{gdbm}, \code{dbm}, and \code{dumbdbm}, choosing the first one -available. - -\item -A new extension module, \code{binascii}, provides a variety of -operations for conversion of text-encoded binary data. - -\item -There are three new or rewritten companion modules implemented in -Python that can encode and decode the most common such formats: -\code{uu} (uuencode), \code{base64} and \code{binhex}. - -\item -A module to handle the MIME encoding quoted-printable has also been -added: \code{quopri}. - -\item -The parser module (which provides an interface to the Python parser's -abstract syntax trees) has been rewritten (incompatibly) by Fred -Drake. It now lets you change the parse tree and compile the result! - -\item -The \code{syslog} module has been upgraded and documented. -% thanks to Steve Clift - -\end{itemize} - -\section{Other Changes} - -\begin{itemize} - -\item -The dynamic module loader recognizes the fact that different filenames -point to the same shared library and loads the library only once, so -you can have a single shared library that defines multiple modules. -(SunOS / SVR4 style shared libraries only.) - -\item -Jim Fulton's ``abstract object interface'' has been incorporated into -the run-time API. For more detailes, read the files -\code{Include/abstract.h} and \code{Objects/abstract.c}. - -\item -The Macintosh version is much more robust now. - -\item -Numerous things I have forgotten or that are so obscure no-one will -notice them anyway :-) - -\end{itemize} - -\end{document} diff --git a/Doc/whichlibs b/Doc/whichlibs deleted file mode 100755 index 56287cbee3..0000000000 --- a/Doc/whichlibs +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -sed -n 's/^\\input{\(lib[a-zA-Z0-9_]*\)}.*/\1.tex/p' lib.tex diff --git a/Grammar/Grammar b/Grammar/Grammar deleted file mode 100644 index 3d957a7994..0000000000 --- a/Grammar/Grammar +++ /dev/null @@ -1,86 +0,0 @@ -# Grammar for Python - -# Commands for Kees Blom's railroad program -#diagram:token NAME -#diagram:token NUMBER -#diagram:token STRING -#diagram:token NEWLINE -#diagram:token ENDMARKER -#diagram:token INDENT -#diagram:output\input python.bla -#diagram:token DEDENT -#diagram:output\textwidth 20.04cm\oddsidemargin 0.0cm\evensidemargin 0.0cm -#diagram:rules - -# Start symbols for the grammar: -# single_input is a single interactive statement; -# file_input is a module or sequence of commands read from an input file; -# eval_input is the input for the eval() and input() functions. -# NB: compound_stmt in single_input is followed by extra NEWLINE! -single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE -file_input: (NEWLINE | stmt)* ENDMARKER -eval_input: testlist NEWLINE* ENDMARKER - -funcdef: 'def' NAME parameters ':' suite -parameters: '(' [varargslist] ')' -varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME] | ('**'|'*' '*') NAME) | fpdef ['=' test] (',' fpdef ['=' test])* [','] -fpdef: NAME | '(' fplist ')' -fplist: fpdef (',' fpdef)* [','] - -stmt: simple_stmt | compound_stmt -simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE -small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt -expr_stmt: testlist ('=' testlist)* -# For assignments, additional restrictions enforced by the interpreter -print_stmt: 'print' (test ',')* [test] -del_stmt: 'del' exprlist -pass_stmt: 'pass' -flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt -break_stmt: 'break' -continue_stmt: 'continue' -return_stmt: 'return' [testlist] -raise_stmt: 'raise' test [',' test [',' test]] -import_stmt: 'import' dotted_name (',' dotted_name)* | 'from' dotted_name 'import' ('*' | NAME (',' NAME)*) -dotted_name: NAME ('.' NAME)* -global_stmt: 'global' NAME (',' NAME)* -access_stmt: 'access' ('*' | NAME (',' NAME)*) ':' accesstype (',' accesstype)* -accesstype: NAME+ -# accesstype should be ('public' | 'protected' | 'private') ['read'] ['write'] -# but can't be because that would create undesirable reserved words! -exec_stmt: 'exec' expr ['in' test [',' test]] - -compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef -if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] -while_stmt: 'while' test ':' suite ['else' ':' suite] -for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] -try_stmt: ('try' ':' suite (except_clause ':' suite)+ #diagram:break - ['else' ':' suite] | 'try' ':' suite 'finally' ':' suite) -# NB compile.c makes sure that the default except clause is last -except_clause: 'except' [test [',' test]] -suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT - -test: and_test ('or' and_test)* | lambdef -and_test: not_test ('and' not_test)* -not_test: 'not' not_test | comparison -comparison: expr (comp_op expr)* -comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' -expr: xor_expr ('|' xor_expr)* -xor_expr: and_expr ('^' and_expr)* -and_expr: shift_expr ('&' shift_expr)* -shift_expr: arith_expr (('<<'|'>>') arith_expr)* -arith_expr: term (('+'|'-') term)* -term: factor (('*'|'/'|'%') factor)* -factor: ('+'|'-'|'~') factor | power -power: atom trailer* ('**' factor)* -atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+ -lambdef: 'lambda' [varargslist] ':' test -trailer: '(' [arglist] ')' | '[' subscript ']' | '.' NAME -subscript: test (',' test)* [','] | [test] ':' [test] -exprlist: expr (',' expr)* [','] -testlist: test (',' test)* [','] -dictmaker: test ':' test (',' test ':' test)* [','] - -classdef: 'class' NAME ['(' testlist ')'] ':' suite - -arglist: argument (',' argument)* [','] -argument: [test '='] test # Really [keyword '='] test diff --git a/Grammar/Makefile b/Grammar/Makefile deleted file mode 100644 index fe9eaa8baf..0000000000 --- a/Grammar/Makefile +++ /dev/null @@ -1,30 +0,0 @@ -TOP= .. -PGENDIR= $(TOP)/Parser -PGEN= $(PGENDIR)/pgen -DESTH= $(TOP)/Include/graminit.h -DESTC= $(TOP)/Python/graminit.c - -all: install - -install: $(DESTH) $(DESTC) - -depend: - -$(DESTH): graminit.h - cp graminit.h $(DESTH) - -$(DESTC): graminit.c - cp graminit.c $(DESTC) - -graminit.c graminit.h: $(PGEN) Grammar - $(PGEN) Grammar - -$(PGEN): - cd $(PGENDIR); make pgen - -clean: - -rm -f *.o core *~ [@,#]* *.old *.orig *.rej - -rm -f graminit.[ch] - -clobber: clean - -rm -f tags TAGS diff --git a/Include/Makefile b/Include/Makefile deleted file mode 100644 index b70dc12f9b..0000000000 --- a/Include/Makefile +++ /dev/null @@ -1,12 +0,0 @@ -all: - @echo Nothing to make in this directory. - -clean: - find . '(' -name '*.pyc' -o -name '*.fdc' \ - -o -name core -o -name '*~' \ - -o -name '[@,#]*' -o -name '*.old' \ - -o -name '*.orig' -o -name '*.rej' \ - -o -name '*.bak' ')' \ - -print -exec rm -f {} ';' - -clobber: clean diff --git a/Include/Python.h b/Include/Python.h deleted file mode 100644 index 490848dea8..0000000000 --- a/Include/Python.h +++ /dev/null @@ -1,3 +0,0 @@ -/* Header file to be included by modules using new naming conventions */ -#define Py_USE_NEW_NAMES -#include "allobjects.h" diff --git a/Include/abstract.h b/Include/abstract.h deleted file mode 100644 index be654c979e..0000000000 --- a/Include/abstract.h +++ /dev/null @@ -1,817 +0,0 @@ -#ifndef Py_ABSTRACTOBJECT_H -#define Py_ABSTRACTOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Abstract Object Interface (many thanks to Jim Fulton) */ - -/* - PROPOSAL: A Generic Python Object Interface for Python C Modules - -Problem - - Python modules written in C that must access Python objects must do - so through routines whose interfaces are described by a set of - include files. Unfortunately, these routines vary according to the - object accessed. To use these routines, the C programmer must check - the type of the object being used and must call a routine based on - the object type. For example, to access an element of a sequence, - the programmer must determine whether the sequence is a list or a - tuple: - - if(is_tupleobject(o)) - e=gettupleitem(o,i) - else if(is_listitem(o)) - e=getlistitem(o,i) - - If the programmer wants to get an item from another type of object - that provides sequence behavior, there is no clear way to do it - correctly. - - The persistent programmer may peruse object.h and find that the - _typeobject structure provides a means of invoking up to (currently - about) 41 special operators. So, for example, a routine can get an - item from any object that provides sequence behavior. However, to - use this mechanism, the programmer must make their code dependent on - the current Python implementation. - - Also, certain semantics, especially memory management semantics, may - differ by the type of object being used. Unfortunately, these - semantics are not clearly described in the current include files. - An abstract interface providing more consistent semantics is needed. - -Proposal - - I propose the creation of a standard interface (with an associated - library of routines and/or macros) for generically obtaining the - services of Python objects. This proposal can be viewed as one - components of a Python C interface consisting of several components. - - From the viewpoint of of C access to Python services, we have (as - suggested by Guido in off-line discussions): - - - "Very high level layer": two or three functions that let you exec or - eval arbitrary Python code given as a string in a module whose name is - given, passing C values in and getting C values out using - mkvalue/getargs style format strings. This does not require the user - to declare any variables of type "PyObject *". This should be enough - to write a simple application that gets Python code from the user, - execs it, and returns the output or errors. (Error handling must also - be part of this API.) - - - "Abstract objects layer": which is the subject of this proposal. - It has many functions operating on objects, and lest you do many - things from C that you can also write in Python, without going - through the Python parser. - - - "Concrete objects layer": This is the public type-dependent - interface provided by the standard built-in types, such as floats, - strings, and lists. This interface exists and is currently - documented by the collection of include files provides with the - Python distributions. - - From the point of view of Python accessing services provided by C - modules: - - - "Python module interface": this interface consist of the basic - routines used to define modules and their members. Most of the - current extensions-writing guide deals with this interface. - - - "Built-in object interface": this is the interface that a new - built-in type must provide and the mechanisms and rules that a - developer of a new built-in type must use and follow. - - This proposal is a "first-cut" that is intended to spur - discussion. See especially the lists of notes. - - The Python C object interface will provide four protocols: object, - numeric, sequence, and mapping. Each protocol consists of a - collection of related operations. If an operation that is not - provided by a particular type is invoked, then a standard exception, - NotImplementedError is raised with a operation name as an argument. - In addition, for convenience this interface defines a set of - constructors for building objects of built-in types. This is needed - so new objects can be returned from C functions that otherwise treat - objects generically. - -Memory Management - - For all of the functions described in this proposal, if a function - retains a reference to a Python object passed as an argument, then the - function will increase the reference count of the object. It is - unnecessary for the caller to increase the reference count of an - argument in anticipation of the object's retention. - - All Python objects returned from functions should be treated as new - objects. Functions that return objects assume that the caller will - retain a reference and the reference count of the object has already - been incremented to account for this fact. A caller that does not - retain a reference to an object that is returned from a function - must decrement the reference count of the object (using - DECREF(object)) to prevent memory leaks. - - Note that the behavior mentioned here is different from the current - behavior for some objects (e.g. lists and tuples) when certain - type-specific routines are called directly (e.g. setlistitem). The - proposed abstraction layer will provide a consistent memory - management interface, correcting for inconsistent behavior for some - built-in types. - -Protocols - -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/ - -/* Object Protocol: */ - - /* Implemented elsewhere: - - int PyObject_Print(PyObject *o, FILE *fp, int flags); - - Print an object, o, on file, fp. Returns -1 on - error. The flags argument is used to enable certain printing - options. The only option currently supported is Py_Print_RAW. - - (What should be said about Py_Print_RAW?) - - */ - - /* Implemented elsewhere: - - int PyObject_HasAttrString(PyObject *o, char *attr_name); - - Returns 1 if o has the attribute attr_name, and 0 otherwise. - This is equivalent to the Python expression: - hasattr(o,attr_name). - - This function always succeeds. - - */ - - /* Implemented elsewhere: - - PyObject* PyObject_GetAttrString(PyObject *o, char *attr_name); - - Retrieve an attributed named attr_name form object o. - Returns the attribute value on success, or NULL on failure. - This is the equivalent of the Python expression: o.attr_name. - - */ - - /* Implemented elsewhere: - - int PyObject_HasAttr(PyObject *o, PyObject *attr_name); - - Returns 1 if o has the attribute attr_name, and 0 otherwise. - This is equivalent to the Python expression: - hasattr(o,attr_name). - - This function always succeeds. - - */ - - /* Implemented elsewhere: - - PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name); - - Retrieve an attributed named attr_name form object o. - Returns the attribute value on success, or NULL on failure. - This is the equivalent of the Python expression: o.attr_name. - - */ - - - /* Implemented elsewhere: - - int PyObject_SetAttrString(PyObject *o, char *attr_name, PyObject *v); - - Set the value of the attribute named attr_name, for object o, - to the value, v. Returns -1 on failure. This is - the equivalent of the Python statement: o.attr_name=v. - - */ - - /* Implemented elsewhere: - - int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v); - - Set the value of the attribute named attr_name, for object o, - to the value, v. Returns -1 on failure. This is - the equivalent of the Python statement: o.attr_name=v. - - */ - - /* implemented as a macro: - - int PyObject_DelAttrString(PyObject *o, char *attr_name); - - Delete attribute named attr_name, for object o. Returns - -1 on failure. This is the equivalent of the Python - statement: del o.attr_name. - - */ -#define PyObject_DelAttrString(O,A) PyObject_SetAttrString((O),(A),NULL) - - /* implemented as a macro: - - int PyObject_DelAttr(PyObject *o, PyObject *attr_name); - - Delete attribute named attr_name, for object o. Returns -1 - on failure. This is the equivalent of the Python - statement: del o.attr_name. - - */ -#define PyObject_DelAttr(O,A) PyObject_SetAttr((O),(A),NULL) - - int PyObject_Cmp Py_PROTO((PyObject *o1, PyObject *o2, int *result)); - - /* - Compare the values of o1 and o2 using a routine provided by - o1, if one exists, otherwise with a routine provided by o2. - The result of the comparison is returned in result. Returns - -1 on failure. This is the equivalent of the Python - statement: result=cmp(o1,o2). - - */ - - /* Implemented elsewhere: - - int PyObject_Compare(PyObject *o1, PyObject *o2); - - Compare the values of o1 and o2 using a routine provided by - o1, if one exists, otherwise with a routine provided by o2. - Returns the result of the comparison on success. On error, - the value returned is undefined. This is equivalent to the - Python expression: cmp(o1,o2). - - */ - - /* Implemented elsewhere: - - PyObject *PyObject_Repr(PyObject *o); - - Compute the string representation of object, o. Returns the - string representation on success, NULL on failure. This is - the equivalent of the Python expression: repr(o). - - Called by the repr() built-in function and by reverse quotes. - - */ - - /* Implemented elsewhere: - - PyObject *PyObject_Str(PyObject *o); - - Compute the string representation of object, o. Returns the - string representation on success, NULL on failure. This is - the equivalent of the Python expression: str(o).) - - Called by the str() built-in function and by the print - statement. - - */ - - int PyCallable_Check Py_PROTO((PyObject *o)); - - /* - Determine if the object, o, is callable. Return 1 if the - object is callable and 0 otherwise. - - This function always succeeds. - - */ - - - - PyObject *PyObject_CallObject Py_PROTO((PyObject *callable_object, - PyObject *args)); - - /* - - Call a callable Python object, callable_object, with - arguments given by the tuple, args. If no arguments are - needed, then args may be NULL. Returns the result of the - call on success, or NULL on failure. This is the equivalent - of the Python expression: apply(o,args). - - */ - - PyObject *PyObject_CallFunction Py_PROTO((PyObject *callable_object, - char *format, ...)); - - /* - Call a callable Python object, callable_object, with a - variable number of C arguments. The C arguments are described - using a mkvalue-style format string. The format may be NULL, - indicating that no arguments are provided. Returns the - result of the call on success, or NULL on failure. This is - the equivalent of the Python expression: apply(o,args). - - */ - - - PyObject *PyObject_CallMethod Py_PROTO((PyObject *o, char *m, - char *format, ...)); - - /* - Call the method named m of object o with a variable number of - C arguments. The C arguments are described by a mkvalue - format string. The format may be NULL, indicating that no - arguments are provided. Returns the result of the call on - success, or NULL on failure. This is the equivalent of the - Python expression: o.method(args). - - Note that Special method names, such as "__add__", - "__getitem__", and so on are not supported. The specific - abstract-object routines for these must be used. - - */ - - - /* Implemented elsewhere: - - long PyObject_Hash(PyObject *o); - - Compute and return the hash, hash_value, of an object, o. On - failure, return -1. This is the equivalent of the Python - expression: hash(o). - - */ - - - /* Implemented elsewhere: - - int PyObject_IsTrue(PyObject *o); - - Returns 1 if the object, o, is considered to be true, and - 0 otherwise. This is equivalent to the Python expression: - not not o - - This function always succeeds. - - */ - - PyObject *PyObject_Type Py_PROTO((PyObject *o)); - - /* - On success, returns a type object corresponding to the object - type of object o. On failure, returns NULL. This is - equivalent to the Python expression: type(o). - */ - - int PyObject_Length Py_PROTO((PyObject *o)); - - /* - Return the length of object o. If the object, o, provides - both sequence and mapping protocols, the sequence length is - returned. On error, -1 is returned. This is the equivalent - to the Python expression: len(o). - - */ - - PyObject *PyObject_GetItem Py_PROTO((PyObject *o, PyObject *key)); - - /* - Return element of o corresponding to the object, key, or NULL - on failure. This is the equivalent of the Python expression: - o[key]. - - */ - - int PyObject_SetItem Py_PROTO((PyObject *o, PyObject *key, PyObject *v)); - - /* - Map the object, key, to the value, v. Returns - -1 on failure. This is the equivalent of the Python - statement: o[key]=v. - */ - - -/* Number Protocol:*/ - - int PyNumber_Check Py_PROTO((PyObject *o)); - - /* - Returns 1 if the object, o, provides numeric protocols, and - false otherwise. - - This function always succeeds. - - */ - - PyObject *PyNumber_Add Py_PROTO((PyObject *o1, PyObject *o2)); - - /* - Returns the result of adding o1 and o2, or null on failure. - This is the equivalent of the Python expression: o1+o2. - - - */ - - PyObject *PyNumber_Subtract Py_PROTO((PyObject *o1, PyObject *o2)); - - /* - Returns the result of subtracting o2 from o1, or null on - failure. This is the equivalent of the Python expression: - o1-o2. - - */ - - PyObject *PyNumber_Multiply Py_PROTO((PyObject *o1, PyObject *o2)); - - /* - Returns the result of multiplying o1 and o2, or null on - failure. This is the equivalent of the Python expression: - o1*o2. - - - */ - - PyObject *PyNumber_Divide Py_PROTO((PyObject *o1, PyObject *o2)); - - /* - Returns the result of dividing o1 by o2, or null on failure. - This is the equivalent of the Python expression: o1/o2. - - - */ - - PyObject *PyNumber_Remainder Py_PROTO((PyObject *o1, PyObject *o2)); - - /* - Returns the remainder of dividing o1 by o2, or null on - failure. This is the equivalent of the Python expression: - o1%o2. - - - */ - - PyObject *PyNumber_Divmod Py_PROTO((PyObject *o1, PyObject *o2)); - - /* - See the built-in function divmod. Returns NULL on failure. - This is the equivalent of the Python expression: - divmod(o1,o2). - - - */ - - PyObject *PyNumber_Power Py_PROTO((PyObject *o1, PyObject *o2, PyObject *o3)); - - /* - See the built-in function pow. Returns NULL on failure. - This is the equivalent of the Python expression: - pow(o1,o2,o3), where o3 is optional. - - */ - - PyObject *PyNumber_Negative Py_PROTO((PyObject *o)); - - /* - Returns the negation of o on success, or null on failure. - This is the equivalent of the Python expression: -o. - - */ - - PyObject *PyNumber_Positive Py_PROTO((PyObject *o)); - - /* - Returns the (what?) of o on success, or NULL on failure. - This is the equivalent of the Python expression: +o. - - */ - - PyObject *PyNumber_Absolute Py_PROTO((PyObject *o)); - - /* - Returns the absolute value of o, or null on failure. This is - the equivalent of the Python expression: abs(o). - - */ - - PyObject *PyNumber_Invert Py_PROTO((PyObject *o)); - - /* - Returns the bitwise negation of o on success, or NULL on - failure. This is the equivalent of the Python expression: - ~o. - - - */ - - PyObject *PyNumber_Lshift Py_PROTO((PyObject *o1, PyObject *o2)); - - /* - Returns the result of left shifting o1 by o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1 << o2. - - - */ - - PyObject *PyNumber_Rshift Py_PROTO((PyObject *o1, PyObject *o2)); - - /* - Returns the result of right shifting o1 by o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1 >> o2. - - */ - - PyObject *PyNumber_And Py_PROTO((PyObject *o1, PyObject *o2)); - - /* - Returns the result of "anding" o2 and o2 on success and NULL - on failure. This is the equivalent of the Python - expression: o1 and o2. - - - */ - - PyObject *PyNumber_Xor Py_PROTO((PyObject *o1, PyObject *o2)); - - /* - Returns the bitwise exclusive or of o1 by o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1^o2. - - - */ - - PyObject *PyNumber_Or Py_PROTO((PyObject *o1, PyObject *o2)); - - /* - Returns the result or o1 and o2 on success, or NULL on - failure. This is the equivalent of the Python expression: - o1 or o2. - - */ - - /* Implemented elsewhere: - - int PyNumber_Coerce(PyObject *o1, PyObject *o2); - - On success, returns a tuple containing o1 and o2 converted to - a common numeric type, or None if no conversion is possible. - Returns -1 on failure. This is equivalent to the Python - expression: coerce(o1,o2). - - */ - - PyObject *PyNumber_Int Py_PROTO((PyObject *o)); - - /* - Returns the o converted to an integer object on success, or - NULL on failure. This is the equivalent of the Python - expression: int(o). - - */ - - PyObject *PyNumber_Long Py_PROTO((PyObject *o)); - - /* - Returns the o converted to a long integer object on success, - or NULL on failure. This is the equivalent of the Python - expression: long(o). - - */ - - PyObject *PyNumber_Float Py_PROTO((PyObject *o)); - - /* - Returns the o converted to a float object on success, or NULL - on failure. This is the equivalent of the Python expression: - float(o). - */ - - -/* Sequence protocol:*/ - - int PySequence_Check Py_PROTO((PyObject *o)); - - /* - Return 1 if the object provides sequence protocol, and zero - otherwise. - - This function always succeeds. - - */ - - PyObject *PySequence_Concat Py_PROTO((PyObject *o1, PyObject *o2)); - - /* - Return the concatination of o1 and o2 on success, and NULL on - failure. This is the equivalent of the Python - expression: o1+o2. - - */ - - PyObject *PySequence_Repeat Py_PROTO((PyObject *o, int count)); - - /* - Return the result of repeating sequence object o count times, - or NULL on failure. This is the equivalent of the Python - expression: o1*count. - - */ - - PyObject *PySequence_GetItem Py_PROTO((PyObject *o, int i)); - - /* - Return the ith element of o, or NULL on failure. This is the - equivalent of the Python expression: o[i]. - - */ - - PyObject *PySequence_GetSlice Py_PROTO((PyObject *o, int i1, int i2)); - - /* - Return the slice of sequence object o between i1 and i2, or - NULL on failure. This is the equivalent of the Python - expression: o[i1:i2]. - - */ - - int PySequence_SetItem Py_PROTO((PyObject *o, int i, PyObject *v)); - - /* - Assign object v to the ith element of o. Returns - -1 on failure. This is the equivalent of the Python - statement: o[i]=v. - - */ - - int PySequence_SetSlice Py_PROTO((PyObject *o, int i1, int i2, PyObject *v)); - - /* - Assign the sequence object, v, to the slice in sequence - object, o, from i1 to i2. Returns -1 on failure. This is the - equivalent of the Python statement: o[i1:i2]=v. - */ - - PyObject *PySequence_Tuple Py_PROTO((PyObject *o)); - - /* - Returns the o as a tuple on success, and NULL on failure. - This is equivalent to the Python expression: tuple(o) - */ - - int PySequence_Count Py_PROTO((PyObject *o, PyObject *value)); - - /* - Return the number of occurrences on value on o, that is, - return the number of keys for which o[key]==value. On - failure, return -1. This is equivalent to the Python - expression: o.count(value). - */ - - int PySequence_In Py_PROTO((PyObject *o, PyObject *value)); - - /* - Determine if o contains value. If an item in o is equal to - X, return 1, otherwise return 0. On error, return -1. This - is equivalent to the Python expression: value in o. - */ - - int PySequence_Index Py_PROTO((PyObject *o, PyObject *value)); - - /* - Return the first index for which o[i]=value. On error, - return -1. This is equivalent to the Python - expression: o.index(value). - */ - -/* Mapping protocol:*/ - - int PyMapping_Check Py_PROTO((PyObject *o)); - - /* - Return 1 if the object provides mapping protocol, and zero - otherwise. - - This function always succeeds. - */ - - int PyMapping_Length Py_PROTO((PyObject *o)); - - /* - Returns the number of keys in object o on success, and -1 on - failure. For objects that do not provide sequence protocol, - this is equivalent to the Python expression: len(o). - */ - - int PyMapping_DelItemString Py_PROTO((PyObject *o, char *key)); - - /* - Remove the mapping for object, key, from the object *o. - Returns -1 on failure. This is equivalent to - the Python statement: del o[key]. - */ - - int PyMapping_DelItem Py_PROTO((PyObject *o, PyObject *key)); - - /* - Remove the mapping for object, key, from the object *o. - Returns -1 on failure. This is equivalent to - the Python statement: del o[key]. - */ - - int PyMapping_HasKeyString Py_PROTO((PyObject *o, char *key)); - - /* - On success, return 1 if the mapping object has the key, key, - and 0 otherwise. This is equivalent to the Python expression: - o.has_key(key). - - This function always succeeds. - */ - - int PyMapping_HasKey Py_PROTO((PyObject *o, PyObject *key)); - - /* - Return 1 if the mapping object has the key, key, - and 0 otherwise. This is equivalent to the Python expression: - o.has_key(key). - - This function always succeeds. - - */ - - /* Implemented as macro: - - PyObject *PyMapping_Keys(PyObject *o); - - On success, return a list of the keys in object o. On - failure, return NULL. This is equivalent to the Python - expression: o.keys(). - */ -#define PyMapping_Keys(O) PyObject_CallMethod(O,"keys",NULL) - - /* Implemented as macro: - - PyObject *PyMapping_Values(PyObject *o); - - On success, return a list of the values in object o. On - failure, return NULL. This is equivalent to the Python - expression: o.values(). - */ -#define PyMapping_Values(O) PyObject_CallMethod(O,"values",NULL) - - /* Implemented as macro: - - PyObject *PyMapping_Items(PyObject *o); - - On success, return a list of the items in object o, where - each item is a tuple containing a key-value pair. On - failure, return NULL. This is equivalent to the Python - expression: o.items(). - - */ -#define PyMapping_Items(O) PyObject_CallMethod(O,"items",NULL) - - PyObject *PyMapping_GetItemString Py_PROTO((PyObject *o, char *key)); - - /* - Return element of o corresponding to the object, key, or NULL - on failure. This is the equivalent of the Python expression: - o[key]. - */ - - int PyMapping_SetItemString Py_PROTO((PyObject *o, char *key, - PyObject *value)); - - /* - Map the object, key, to the value, v. Returns - -1 on failure. This is the equivalent of the Python - statement: o[key]=v. - */ - - -#ifdef __cplusplus -} -#endif -#endif /* Py_ABSTRACTOBJECT_H */ diff --git a/Include/accessobject.h b/Include/accessobject.h deleted file mode 100644 index 0ea60fc03a..0000000000 --- a/Include/accessobject.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef Py_ACCESSOBJECT_H -#define Py_ACCESSOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Access object interface */ - -/* Access mode bits (note similarity with UNIX permissions) */ -#define AC_R 0444 -#define AC_W 0222 - -#define AC_PRIVATE 0700 -#define AC_R_PRIVATE 0400 -#define AC_W_PRIVATE 0200 - -#define AC_PROTECTED 0070 -#define AC_R_PROTECTED 0040 -#define AC_W_PROTECTED 0020 - -#define AC_PUBLIC 0007 -#define AC_R_PUBLIC 0004 -#define AC_W_PUBLIC 0002 - -extern DL_IMPORT(PyTypeObject) PyAccess_Type; - -#define PyAccess_Check(v) ((v)->ob_type == &PyAccess_Type) - -PyObject *PyAccess_FromValue Py_PROTO((PyObject *, PyObject *, PyTypeObject *, int)); -PyObject *PyAccess_AsValue Py_PROTO((PyObject *, PyObject *)); -int PyAccess_SetValue Py_PROTO((PyObject *, PyObject *, PyObject *)); - -void PyAccess_SetOwner Py_PROTO((PyObject *, PyObject *)); -PyObject *PyAccess_Clone Py_PROTO((PyObject *)); -int PyAccess_HasValue Py_PROTO((PyObject *)); - -extern DL_IMPORT(PyTypeObject) PyAnyNumber_Type, PyAnySequence_Type, PyAnyMapping_Type; - -#ifdef __cplusplus -} -#endif -#endif /* !Py_ACCESSOBJECT_H */ diff --git a/Include/allobjects.h b/Include/allobjects.h deleted file mode 100644 index 03b6363a11..0000000000 --- a/Include/allobjects.h +++ /dev/null @@ -1,110 +0,0 @@ -#ifndef Py_ALLOBJECTS_H -#define Py_ALLOBJECTS_H -/* Since this is a "meta-include" file, no #ifdef __cplusplus / extern "C" { */ - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Include nearly all Python header files */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -/* config.h may or may not define DL_IMPORT */ -#ifndef DL_IMPORT /* declarations for DLL import/export */ -#define DL_IMPORT(RTYPE) RTYPE -#endif - -#ifdef SYMANTEC__CFM68K__ -#define UsingSharedLibs -#endif - -#include <stdio.h> -#include <string.h> -#include <errno.h> -#ifdef HAVE_STDLIB_H -#include <stdlib.h> -#endif - -#include "myproto.h" - -#ifdef SYMANTEC__CFM68K__ -#pragma lib_export on -#endif - -#include "object.h" -#include "objimpl.h" - -#include "pydebug.h" - -#include "accessobject.h" -#include "intobject.h" -#include "longobject.h" -#include "floatobject.h" -#ifndef WITHOUT_COMPLEX -#include "complexobject.h" -#endif -#include "rangeobject.h" -#include "stringobject.h" -#include "tupleobject.h" -#include "listobject.h" -#include "mappingobject.h" -#include "methodobject.h" -#include "moduleobject.h" -#include "funcobject.h" -#include "classobject.h" -#include "fileobject.h" -#include "cobject.h" -#include "traceback.h" - -#include "errors.h" -#include "mymalloc.h" - -#include "modsupport.h" -#include "ceval.h" -#include "pythonrun.h" -#include "sysmodule.h" -#include "intrcheck.h" -#include "import.h" -#include "bltinmodule.h" - -#include "abstract.h" - -#define PyArg_GetInt(v, a) PyArg_Parse((v), "i", (a)) -#define PyArg_NoArgs(v) PyArg_Parse(v, "") - -/* Convert a possibly signed character to a nonnegative int */ -/* XXX This assumes characters are 8 bits wide */ -#ifdef __CHAR_UNSIGNED__ -#define Py_CHARMASK(c) (c) -#else -#define Py_CHARMASK(c) ((c) & 0xff) -#endif - -#ifndef Py_USE_NEW_NAMES -#include "rename2.h" -#endif - -#endif /* !Py_ALLOBJECTS_H */ diff --git a/Include/assert.h b/Include/assert.h deleted file mode 100644 index b0c08abee2..0000000000 --- a/Include/assert.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef Py_ASSERT_H -#define Py_ASSERT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#ifdef MPW /* This is for MPW's File command */ - -#define assert(e) { if (!(e)) { printf("### Python: Assertion failed:\n\ - File %s; Line %d\n", __FILE__, __LINE__); abort(); } } -#else -#define assert(e) { if (!(e)) { printf("Assertion failed\n"); abort(); } } -#endif - -#ifdef __cplusplus -} -#endif -#endif /* !Py_ASSERT_H */ diff --git a/Include/bitset.h b/Include/bitset.h deleted file mode 100644 index 673abb1267..0000000000 --- a/Include/bitset.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef Py_BITSET_H -#define Py_BITSET_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Bitset interface */ - -#define BYTE char - -typedef BYTE *bitset; - -bitset newbitset Py_PROTO((int nbits)); -void delbitset Py_PROTO((bitset bs)); -#define testbit(ss, ibit) (((ss)[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0) -int addbit Py_PROTO((bitset bs, int ibit)); /* Returns 0 if already set */ -int samebitset Py_PROTO((bitset bs1, bitset bs2, int nbits)); -void mergebitset Py_PROTO((bitset bs1, bitset bs2, int nbits)); - -#define BITSPERBYTE (8*sizeof(BYTE)) -#define NBYTES(nbits) (((nbits) + BITSPERBYTE - 1) / BITSPERBYTE) - -#define BIT2BYTE(ibit) ((ibit) / BITSPERBYTE) -#define BIT2SHIFT(ibit) ((ibit) % BITSPERBYTE) -#define BIT2MASK(ibit) (1 << BIT2SHIFT(ibit)) -#define BYTE2BIT(ibyte) ((ibyte) * BITSPERBYTE) - -#ifdef __cplusplus -} -#endif -#endif /* !Py_BITSET_H */ diff --git a/Include/bltinmodule.h b/Include/bltinmodule.h deleted file mode 100644 index 9ba1e77b4c..0000000000 --- a/Include/bltinmodule.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef Py_BLTINMODULE_H -#define Py_BLTINMODULE_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Built-in module interface */ - -extern void PyBuiltin_Init Py_PROTO((void)); -extern PyObject *PyBuiltin_GetDict Py_PROTO(()); -extern PyObject *PyBuiltin_GetModule Py_PROTO(()); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_BLTINMODULE_H */ diff --git a/Include/ceval.h b/Include/ceval.h deleted file mode 100644 index 70abbb4c28..0000000000 --- a/Include/ceval.h +++ /dev/null @@ -1,121 +0,0 @@ -#ifndef Py_CEVAL_H -#define Py_CEVAL_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Interface to random parts in ceval.c */ - -PyObject *PyEval_CallObject Py_PROTO((PyObject *, PyObject *)); -PyObject *PyEval_CallObjectWithKeywords - Py_PROTO((PyObject *, PyObject *, PyObject *)); - -PyObject *PyEval_GetBuiltins Py_PROTO((void)); -PyObject *PyEval_GetGlobals Py_PROTO((void)); -PyObject *PyEval_GetLocals Py_PROTO((void)); -PyObject *PyEval_GetOwner Py_PROTO((void)); -PyObject *PyEval_GetFrame Py_PROTO((void)); -int PyEval_GetRestricted Py_PROTO((void)); - -void Py_FlushLine Py_PROTO((void)); - -int Py_AddPendingCall Py_PROTO((int (*func) Py_PROTO((ANY *)), ANY *arg)); -int Py_MakePendingCalls Py_PROTO((void)); - - -/* Interface for threads. - - A module that plans to do a blocking system call (or something else - that lasts a long time and doesn't touch Python data) can allow other - threads to run as follows: - - ...preparations here... - Py_BEGIN_ALLOW_THREADS - ...blocking system call here... - Py_END_ALLOW_THREADS - ...interpret result here... - - The Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair expands to a - {}-surrounded block. - To leave the block in the middle (e.g., with return), you must insert - a line containing RET_SAVE before the return, e.g. - - if (...premature_exit...) { - Py_BLOCK_THREADS - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - - An alternative is: - - Py_BLOCK_THREADS - if (...premature_exit...) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_UNBLOCK_THREADS - - For convenience, that the value of 'errno' is restored across - Py_END_ALLOW_THREADS and RET_SAVE. - - WARNING: NEVER NEST CALLS TO Py_BEGIN_ALLOW_THREADS AND - Py_END_ALLOW_THREADS!!! - - The function PyEval_InitThreads() should be called only from - initthread() in "threadmodule.c". - - Note that not yet all candidates have been converted to use this - mechanism! -*/ - -extern void PyEval_InitThreads Py_PROTO((void)); -extern PyObject *PyEval_SaveThread Py_PROTO((void)); -extern void PyEval_RestoreThread Py_PROTO((PyObject *)); - -#ifdef WITH_THREAD - -#define Py_BEGIN_ALLOW_THREADS { \ - PyObject *_save; \ - _save = PyEval_SaveThread(); -#define Py_BLOCK_THREADS PyEval_RestoreThread(_save); -#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread(); -#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \ - } - -#else /* !WITH_THREAD */ - -#define Py_BEGIN_ALLOW_THREADS { -#define Py_BLOCK_THREADS -#define Py_UNBLOCK_THREADS -#define Py_END_ALLOW_THREADS } - -#endif /* !WITH_THREAD */ - -#ifdef __cplusplus -} -#endif -#endif /* !Py_CEVAL_H */ diff --git a/Include/cgensupport.h b/Include/cgensupport.h deleted file mode 100644 index bb7cbbc674..0000000000 --- a/Include/cgensupport.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef Py_CGENSUPPORT_H -#define Py_CGENSUPPORT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Definitions used by cgen output */ - -typedef char *string; - -#define mknewlongobject(x) PyInt_FromLong(x) -#define mknewshortobject(x) PyInt_FromLong((long)x) -#define mknewfloatobject(x) PyFloat_FromDouble(x) -#define mknewcharobject(ch) Py_BuildValue("c", ch) - -extern int PyArg_GetObject Py_PROTO((PyObject *args, int nargs, int i, PyObject **p_a)); -extern int PyArg_GetLong Py_PROTO((PyObject *args, int nargs, int i, long *p_a)); -extern int PyArg_GetShort Py_PROTO((PyObject *args, int nargs, int i, short *p_a)); -extern int PyArg_GetFloat Py_PROTO((PyObject *args, int nargs, int i, float *p_a)); -extern int PyArg_GetString Py_PROTO((PyObject *args, int nargs, int i, string *p_a)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_CGENSUPPORT_H */ diff --git a/Include/classobject.h b/Include/classobject.h deleted file mode 100644 index 807dff7bc5..0000000000 --- a/Include/classobject.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef Py_CLASSOBJECT_H -#define Py_CLASSOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Class object interface */ - -#ifdef WITH_THREAD -#include "thread.h" -#else -#define get_thread_ident() 1L -#endif - -/* Revealing some structures (not for general use) */ - -typedef struct { - PyObject_HEAD - PyObject *cl_bases; /* A tuple of class objects */ - PyObject *cl_dict; /* A dictionary */ - PyObject *cl_name; /* A string */ - /* The following three are functions or NULL */ - PyObject *cl_getattr; - PyObject *cl_setattr; - PyObject *cl_delattr; -} PyClassObject; - -typedef struct { - PyObject_HEAD - PyClassObject *in_class; /* The class object */ - PyObject *in_dict; /* A dictionary */ -} PyInstanceObject; - -extern DL_IMPORT(PyTypeObject) PyClass_Type, PyInstance_Type, PyMethod_Type; - -#define PyClass_Check(op) ((op)->ob_type == &PyClass_Type) -#define PyInstance_Check(op) ((op)->ob_type == &PyInstance_Type) -#define PyMethod_Check(op) ((op)->ob_type == &PyMethod_Type) - -extern PyObject *PyClass_New Py_PROTO((PyObject *, PyObject *, PyObject *)); -extern PyObject *PyInstance_New Py_PROTO((PyObject *, PyObject *, PyObject *)); -extern PyObject *PyMethod_New Py_PROTO((PyObject *, PyObject *, PyObject *)); - -extern PyObject *PyMethod_Function Py_PROTO((PyObject *)); -extern PyObject *PyMethod_Self Py_PROTO((PyObject *)); -extern PyObject *PyMethod_Class Py_PROTO((PyObject *)); - -extern int PyClass_IsSubclass Py_PROTO((PyObject *, PyObject *)); - -extern PyObject *PyInstance_DoBinOp - Py_PROTO((PyObject *, PyObject *, - char *, char *, - PyObject * (*) Py_PROTO((PyObject *, PyObject *)) )); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_CLASSOBJECT_H */ diff --git a/Include/cobject.h b/Include/cobject.h deleted file mode 100644 index 19693380e5..0000000000 --- a/Include/cobject.h +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef Py_COBJECT_H -#define Py_COBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* C objects to be exported from one extension module to another. - - C objects are used for communication between extension modules. - They provide a way for an extension module to export a C interface - to other extension modules, so that extension modules can use the - Python import mechanism to link to one another. - -*/ - -extern DL_IMPORT(PyTypeObject) PyCObject_Type; - -#define PyCObject_Check(op) ((op)->ob_type == &PyCObject_Type) - -/* Create a PyCObject from a pointer to a C object and an optional - destrutor function. If the second argument is non-null, then it - will be called with the first argument if and when the PyCObject is - destroyed. - -*/ - -extern PyObject * -PyCObject_FromVoidPtr Py_PROTO((void *cobj, void (*destruct)(void*))); - -/* Retrieve a pointer to a C object from a PyCObject. */ -extern void * -PyCObject_AsVoidPtr Py_PROTO((PyObject *)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_COBJECT_H */ diff --git a/Include/compile.h b/Include/compile.h deleted file mode 100644 index 02d11ddcb8..0000000000 --- a/Include/compile.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef Py_COMPILE_H -#define Py_COMPILE_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Definitions for bytecode */ - -/* Bytecode object */ -typedef struct { - PyObject_HEAD - int co_argcount; /* #arguments, except *args */ - int co_nlocals; /* #local variables */ - int co_flags; /* CO_..., see below */ - PyStringObject *co_code; /* instruction opcodes */ - PyObject *co_consts; /* list (constants used) */ - PyObject *co_names; /* list of strings (names used) */ - PyObject *co_varnames; /* tuple of strings (local variable names) */ - /* The rest doesn't count for hash/cmp */ - PyObject *co_filename; /* string (where it was loaded from) */ - PyObject *co_name; /* string (name, for reference) */ -} PyCodeObject; - -/* Masks for co_flags above */ -#define CO_OPTIMIZED 0x0001 -#define CO_NEWLOCALS 0x0002 -#define CO_VARARGS 0x0004 -#define CO_VARKEYWORDS 0x0008 - -extern DL_IMPORT(PyTypeObject) PyCode_Type; - -#define PyCode_Check(op) ((op)->ob_type == &PyCode_Type) - - -/* Public interface */ -struct _node; /* Declare the existence of this type */ -PyCodeObject *PyNode_Compile Py_PROTO((struct _node *, char *)); -PyCodeObject *PyCode_New Py_PROTO(( - int, int, int, PyObject *, PyObject *, PyObject *, PyObject *, - PyObject *, PyObject *)); /* same as struct above */ - -#ifdef __cplusplus -} -#endif -#endif /* !Py_COMPILE_H */ diff --git a/Include/complexobject.h b/Include/complexobject.h deleted file mode 100644 index a399a1e6c9..0000000000 --- a/Include/complexobject.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef COMPLEXOBJECT_H -#define COMPLEXOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/* Complex number structure */ - -typedef struct { - double real; - double imag; -} complex; - -/* Operations on complex numbers from complexmodule.c */ - -#define c_sum _Py_c_sum -#define c_diff _Py_c_diff -#define c_neg _Py_c_neg -#define c_prod _Py_c_prod -#define c_quot _Py_c_quot -#define c_pow _Py_c_pow - -extern complex c_sum(); -extern complex c_diff(); -extern complex c_neg(); -extern complex c_prod(); -extern complex c_quot(); -extern complex c_pow(); - - -/* Complex object interface */ - -/* -PyComplexObject represents a complex number with double-precision -real and imaginary parts. -*/ - -typedef struct { - PyObject_HEAD - complex cval; -} PyComplexObject; - -extern DL_IMPORT(PyTypeObject) PyComplex_Type; - -#define PyComplex_Check(op) ((op)->ob_type == &PyComplex_Type) - -extern PyObject *PyComplex_FromCComplex Py_PROTO((complex)); -extern PyObject *PyComplex_FromDoubles Py_PROTO((double real, double imag)); - -extern double PyComplex_RealAsDouble Py_PROTO((PyObject *op)); -extern double PyComplex_ImagAsDouble Py_PROTO((PyObject *op)); -extern complex PyComplex_AsCComplex Py_PROTO((PyObject *op)); - -#ifdef __cplusplus -} -#endif -#endif /* !COMPLEXOBJECT_H */ diff --git a/Include/config.h b/Include/config.h deleted file mode 100755 index 3f486fff58..0000000000 --- a/Include/config.h +++ /dev/null @@ -1,82 +0,0 @@ -/* Include/config.h. Generated automatically by configure. */ -/* NOTE: config.h.in is converted into config.h by the configure - script in the toplevel directory. - - On non-UNIX systems, manually copy config.h.in to config.h, and - edit the latter to reflect the actual configuration of your system. - - Then arrange that the symbol HAVE_CONFIG_H is defined during - compilation (usually by passing an argument of the form - `-DHAVE_CONFIG_H' to the compiler, but this is necessarily - system-dependent). */ - - -/* Types which have no traditional name -- edit the definition if necessary */ - -#define RETSIGTYPE void /* int or void: return of signal handlers */ - - -/* Types which are often defined in <sys/types.h> -- either define as - some variant of int or leave undefined. Uncomment a definition if - your <sys/types.h> does not define the type */ - -/* #define mode_t int */ -/* #define off_t long */ -/* #define pid_t int */ -/* #define size_t unsigned */ -/* #define uid_t int */ -/* #define gid_t int */ - - -/* Feature test symbols -- either define as 1 or leave undefined */ - -/* symbol name: #define as 1 if: */ - -/* #undef STDC_HEADERS */ /* the standard C header files exist - (in particular, <stdlib.h>, - <stdarg.h>, <string.h> and <float.h>) */ - -/* #undef HAVE_DLFCN_H */ /* <dlfcn.h> exists */ -#define HAVE_SIGNAL_H 1 /* <signal.h> exists */ -#define HAVE_STDARG_H 1 /* <stdarg.h> exists (else need <varargs.h>) */ -#define HAVE_STDLIB_H 1 /* <stdlib.h> exists */ -#define HAVE_UNISTD_H 1 /* <unistd.h> exists */ -#define HAVE_UTIME_H 1 /* <utime.h> exists */ - -#define HAVE_SYS_PARAM_H 1 /* <sys/param.h> exists */ -/* #undef HAVE_SYS_SELECT_H */ /* <sys/select.h> exists */ -#define HAVE_SYS_TIMES_H 1 /* <sys/times.h> exists */ -/* #undef HAVE_SYS_TIME_H */ /* <sys/time.h> exists */ -#define HAVE_SYS_UTSNAME_H 1 /* <sys.utsname.h> exists */ - -#define TIME_WITH_SYS_TIME 1 /* <sys/time.h> and <time.h> can be included - together */ - -/* #undef HAVE_TM_ZONE */ /* struct tm has a tm_zone member */ -#define HAVE_TZNAME 1 /* extern char *tzname[] exists */ - -#define HAVE_CLOCK 1 /* clock() exists */ -/* #undef HAVE_FTIME */ /* ftime() exists */ -#define HAVE_GETPGRP 1 /* getpgrp() exists */ -#define HAVE_GETTIMEOFDAY 1 /* gettimeofday() exists */ -#define HAVE_LSTAT 1 /* lstat() exists */ -#define HAVE_PROTOTYPES 1 /* the compiler understands prototypes */ -#define HAVE_READLINK 1 /* readlink() exists */ -#define HAVE_SELECT 1 /* select() exists */ -#define HAVE_SETPGID 1 /* setpgid() exists */ -#define HAVE_SETPGRP 1 /* setpgrp() exists */ -#define HAVE_SETSID 1 /* setsid() exists */ -#define HAVE_SYMLINK 1 /* symlink() exists */ -/* #undef HAVE_SIGINTERRUPT */ /* siginterrupt() exists */ -#define HAVE_TCGETPGRP 1 /* tcgetpgrp() exists */ -#define HAVE_TCSETPGRP 1 /* tcsetpgrp() exists */ -#define HAVE_TIMES 1 /* times() exists */ -#define HAVE_UNAME 1 /* uname() exists */ -#define HAVE_WAITPID 1 /* waitpid() exists */ - -/* #undef GETPGRP_HAVE_ARG */ /* getpgrp() must be called as getpgrp(0) - (and setpgrp() as setpgrp(0, 0)) */ - -#define WITH_READLINE 1 /* GNU readline() should be used */ -/* #undef USE_THREAD */ /* Build in thread support */ -/* #undef SOLARIS */ /* This is SOLARIS 2.x */ diff --git a/Include/dictobject.h b/Include/dictobject.h deleted file mode 100644 index 6c2209339a..0000000000 --- a/Include/dictobject.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef Py_DICTOBJECT_H -#define Py_DICTOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* All in the sake of backward compatibility... */ - -#include "mappingobject.h" - -#ifdef __cplusplus -} -#endif -#endif /* !Py_DICTOBJECT_H */ diff --git a/Include/errcode.h b/Include/errcode.h deleted file mode 100644 index 7ed50a59d7..0000000000 --- a/Include/errcode.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef Py_ERRCODE_H -#define Py_ERRCODE_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Error codes passed around between file input, tokenizer, parser and - interpreter. This is necessary so we can turn them into Python - exceptions at a higher level. Note that some errors have a - slightly different meaning when passed from the tokenizer to the - parser than when passed from the parser to the interpreter; e.g. - the parser only returns E_EOF when it hits EOF immediately, and it - never returns E_OK. */ - -#define E_OK 10 /* No error */ -#define E_EOF 11 /* End Of File */ -#define E_INTR 12 /* Interrupted */ -#define E_TOKEN 13 /* Bad token */ -#define E_SYNTAX 14 /* Syntax error */ -#define E_NOMEM 15 /* Ran out of memory */ -#define E_DONE 16 /* Parsing complete */ -#define E_ERROR 17 /* Execution error */ - -#ifdef __cplusplus -} -#endif -#endif /* !Py_ERRCODE_H */ diff --git a/Include/errors.h b/Include/errors.h deleted file mode 100755 index 3307b3686c..0000000000 --- a/Include/errors.h +++ /dev/null @@ -1,76 +0,0 @@ -#ifndef Py_ERRORS_H -#define Py_ERRORS_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Error handling definitions */ - -void PyErr_SetNone Py_PROTO((PyObject *)); -void PyErr_SetObject Py_PROTO((PyObject *, PyObject *)); -void PyErr_SetString Py_PROTO((PyObject *, char *)); -PyObject *PyErr_Occurred Py_PROTO((void)); -void PyErr_Clear Py_PROTO((void)); -void PyErr_Fetch Py_PROTO((PyObject **, PyObject **, PyObject **)); -void PyErr_Restore Py_PROTO((PyObject *, PyObject *, PyObject *)); - -/* Predefined exceptions */ - -extern DL_IMPORT(PyObject *) PyExc_AccessError; -extern DL_IMPORT(PyObject *) PyExc_AttributeError; -extern DL_IMPORT(PyObject *) PyExc_ConflictError; -extern DL_IMPORT(PyObject *) PyExc_EOFError; -extern DL_IMPORT(PyObject *) PyExc_IOError; -extern DL_IMPORT(PyObject *) PyExc_ImportError; -extern DL_IMPORT(PyObject *) PyExc_IndexError; -extern DL_IMPORT(PyObject *) PyExc_KeyError; -extern DL_IMPORT(PyObject *) PyExc_KeyboardInterrupt; -extern DL_IMPORT(PyObject *) PyExc_MemoryError; -extern DL_IMPORT(PyObject *) PyExc_NameError; -extern DL_IMPORT(PyObject *) PyExc_OverflowError; -extern DL_IMPORT(PyObject *) PyExc_RuntimeError; -extern DL_IMPORT(PyObject *) PyExc_SyntaxError; -extern DL_IMPORT(PyObject *) PyExc_SystemError; -extern DL_IMPORT(PyObject *) PyExc_SystemExit; -extern DL_IMPORT(PyObject *) PyExc_TypeError; -extern DL_IMPORT(PyObject *) PyExc_ValueError; -extern DL_IMPORT(PyObject *) PyExc_ZeroDivisionError; - -/* Convenience functions */ - -extern int PyErr_BadArgument Py_PROTO((void)); -extern PyObject *PyErr_NoMemory Py_PROTO((void)); -extern PyObject *PyErr_SetFromErrno Py_PROTO((PyObject *)); - -extern void PyErr_BadInternalCall Py_PROTO((void)); - -extern int PyErr_CheckSignals Py_PROTO((void)); /* In sigcheck.c or signalmodule.c */ - -#ifdef __cplusplus -} -#endif -#endif /* !Py_ERRORS_H */ diff --git a/Include/eval.h b/Include/eval.h deleted file mode 100644 index 56f9938df8..0000000000 --- a/Include/eval.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef Py_EVAL_H -#define Py_EVAL_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Interface to execute compiled code */ - -PyObject *PyEval_EvalCode Py_PROTO((PyCodeObject *, PyObject *, PyObject *)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_EVAL_H */ diff --git a/Include/fileobject.h b/Include/fileobject.h deleted file mode 100644 index 6129cdd66c..0000000000 --- a/Include/fileobject.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef Py_FILEOBJECT_H -#define Py_FILEOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* File object interface */ - -extern DL_IMPORT(PyTypeObject) PyFile_Type; - -#define PyFile_Check(op) ((op)->ob_type == &PyFile_Type) - -extern PyObject *PyFile_FromString Py_PROTO((char *, char *)); -extern void PyFile_SetBufSize Py_PROTO((PyObject *, int)); -extern PyObject *PyFile_FromFile - Py_PROTO((FILE *, char *, char *, int (*)Py_FPROTO((FILE *)))); -extern FILE *PyFile_AsFile Py_PROTO((PyObject *)); -extern PyObject *PyFile_Name Py_PROTO((PyObject *)); -extern PyObject *PyFile_GetLine Py_PROTO((PyObject *, int)); -extern int PyFile_WriteObject Py_PROTO((PyObject *, PyObject *, int)); -extern int PyFile_SoftSpace Py_PROTO((PyObject *, int)); -extern void PyFile_WriteString Py_PROTO((char *, PyObject *)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_FILEOBJECT_H */ diff --git a/Include/floatobject.h b/Include/floatobject.h deleted file mode 100644 index ba23f77a4b..0000000000 --- a/Include/floatobject.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef Py_FLOATOBJECT_H -#define Py_FLOATOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Float object interface */ - -/* -PyFloatObject represents a (double precision) floating point number. -*/ - -typedef struct { - PyObject_HEAD - double ob_fval; -} PyFloatObject; - -extern DL_IMPORT(PyTypeObject) PyFloat_Type; - -#define PyFloat_Check(op) ((op)->ob_type == &PyFloat_Type) - -extern PyObject *PyFloat_FromDouble Py_PROTO((double)); -extern double PyFloat_AsDouble Py_PROTO((PyObject *)); - -/* Macro, trading safety for speed */ -#define PyFloat_AS_DOUBLE(op) ((op)->ob_fval) - -#ifdef __cplusplus -} -#endif -#endif /* !Py_FLOATOBJECT_H */ diff --git a/Include/frameobject.h b/Include/frameobject.h deleted file mode 100644 index 5bf94c38e4..0000000000 --- a/Include/frameobject.h +++ /dev/null @@ -1,111 +0,0 @@ -#ifndef Py_FRAMEOBJECT_H -#define Py_FRAMEOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Frame object interface */ - -typedef struct { - int b_type; /* what kind of block this is */ - int b_handler; /* where to jump to find handler */ - int b_level; /* value stack level to pop to */ -} PyTryBlock; - -typedef struct _frame { - PyObject_HEAD - struct _frame *f_back; /* previous frame, or NULL */ - PyCodeObject *f_code; /* code segment */ - PyObject *f_builtins; /* builtin symbol table (PyDictObject) */ - PyObject *f_globals; /* global symbol table (PyDictObject) */ - PyObject *f_locals; /* local symbol table (PyDictObject) */ - PyObject *f_owner; /* owner (e.g. class or module) or NULL */ - PyObject *f_fastlocals; /* fast local variables (PyListObject) */ - PyObject **f_valuestack; /* malloc'ed array */ - PyTryBlock *f_blockstack; /* malloc'ed array */ - int f_nvalues; /* size of f_valuestack */ - int f_nblocks; /* size of f_blockstack */ - int f_iblock; /* index in f_blockstack */ - int f_lasti; /* Last instruction if called */ - int f_lineno; /* Current line number */ - int f_restricted; /* Flag set if restricted operations - in this scope */ - PyObject *f_trace; /* Trace function */ -} PyFrameObject; - - -/* Standard object interface */ - -extern DL_IMPORT(PyTypeObject) PyFrame_Type; - -#define PyFrame_Check(op) ((op)->ob_type == &PyFrame_Type) - -PyFrameObject * PyFrame_New - Py_PROTO((PyFrameObject *, PyCodeObject *, - PyObject *, PyObject *, PyObject *, int, int)); - - -/* The rest of the interface is specific for frame objects */ - -/* Tuple access macros */ - -#ifndef DEBUG -#define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i)) -#define GETITEMNAME(v, i) \ - PyString_AS_STRING((PyStringObject *)GETITEM((v), (i))) -#else -#define GETITEM(v, i) PyTuple_GetItem((v), (i)) -#define GETITEMNAME(v, i) PyString_AsString(GETITEM(v, i)) -#endif - -#define GETUSTRINGVALUE(s) ((unsigned char *)PyString_AS_STRING(s)) - -/* Code access macros */ - -#define Getconst(f, i) (GETITEM((f)->f_code->co_consts, (i))) -#define Getname(f, i) (GETITEMNAME((f)->f_code->co_names, (i))) -#define Getnamev(f, i) (GETITEM((f)->f_code->co_names, (i))) - - -/* Block management functions */ - -void PyFrame_BlockSetup Py_PROTO((PyFrameObject *, int, int, int)); -PyTryBlock *PyFrame_BlockPop Py_PROTO((PyFrameObject *)); - -/* Extend the value stack */ - -PyObject **PyFrame_ExtendStack Py_PROTO((PyFrameObject *, int, int)); - -/* Conversions between "fast locals" and locals in dictionary */ - -void PyFrame_LocalsToFast Py_PROTO((PyFrameObject *, int)); -void PyFrame_FastToLocals Py_PROTO((PyFrameObject *)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_FRAMEOBJECT_H */ diff --git a/Include/funcobject.h b/Include/funcobject.h deleted file mode 100644 index 2ab4698048..0000000000 --- a/Include/funcobject.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef Py_FUNCOBJECT_H -#define Py_FUNCOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Function object interface */ - -typedef struct { - PyObject_HEAD - PyObject *func_code; - PyObject *func_globals; - PyObject *func_defaults; - PyObject *func_doc; - PyObject *func_name; -} PyFunctionObject; - -extern DL_IMPORT(PyTypeObject) PyFunction_Type; - -#define PyFunction_Check(op) ((op)->ob_type == &PyFunction_Type) - -extern PyObject *PyFunction_New Py_PROTO((PyObject *, PyObject *)); -extern PyObject *PyFunction_GetCode Py_PROTO((PyObject *)); -extern PyObject *PyFunction_GetGlobals Py_PROTO((PyObject *)); -extern PyObject *PyFunction_GetDefaults Py_PROTO((PyObject *)); -extern int PyFunction_SetDefaults Py_PROTO((PyObject *, PyObject *)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_FUNCOBJECT_H */ diff --git a/Include/graminit.h b/Include/graminit.h deleted file mode 100644 index 9fa64c2d14..0000000000 --- a/Include/graminit.h +++ /dev/null @@ -1,56 +0,0 @@ -#define single_input 256 -#define file_input 257 -#define eval_input 258 -#define funcdef 259 -#define parameters 260 -#define varargslist 261 -#define fpdef 262 -#define fplist 263 -#define stmt 264 -#define simple_stmt 265 -#define small_stmt 266 -#define expr_stmt 267 -#define print_stmt 268 -#define del_stmt 269 -#define pass_stmt 270 -#define flow_stmt 271 -#define break_stmt 272 -#define continue_stmt 273 -#define return_stmt 274 -#define raise_stmt 275 -#define import_stmt 276 -#define dotted_name 277 -#define global_stmt 278 -#define access_stmt 279 -#define accesstype 280 -#define exec_stmt 281 -#define compound_stmt 282 -#define if_stmt 283 -#define while_stmt 284 -#define for_stmt 285 -#define try_stmt 286 -#define except_clause 287 -#define suite 288 -#define test 289 -#define and_test 290 -#define not_test 291 -#define comparison 292 -#define comp_op 293 -#define expr 294 -#define xor_expr 295 -#define and_expr 296 -#define shift_expr 297 -#define arith_expr 298 -#define term 299 -#define factor 300 -#define power 301 -#define atom 302 -#define lambdef 303 -#define trailer 304 -#define subscript 305 -#define exprlist 306 -#define testlist 307 -#define dictmaker 308 -#define classdef 309 -#define arglist 310 -#define argument 311 diff --git a/Include/grammar.h b/Include/grammar.h deleted file mode 100644 index 9c4dd455fc..0000000000 --- a/Include/grammar.h +++ /dev/null @@ -1,116 +0,0 @@ -#ifndef Py_GRAMMAR_H -#define Py_GRAMMAR_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Grammar interface */ - -#include "bitset.h" /* Sigh... */ - -/* A label of an arc */ - -typedef struct { - int lb_type; - char *lb_str; -} label; - -#define EMPTY 0 /* Label number 0 is by definition the empty label */ - -/* A list of labels */ - -typedef struct { - int ll_nlabels; - label *ll_label; -} labellist; - -/* An arc from one state to another */ - -typedef struct { - short a_lbl; /* Label of this arc */ - short a_arrow; /* State where this arc goes to */ -} arc; - -/* A state in a DFA */ - -typedef struct { - int s_narcs; - arc *s_arc; /* Array of arcs */ - - /* Optional accelerators */ - int s_lower; /* Lowest label index */ - int s_upper; /* Highest label index */ - int *s_accel; /* Accelerator */ - int s_accept; /* Nonzero for accepting state */ -} state; - -/* A DFA */ - -typedef struct { - int d_type; /* Non-terminal this represents */ - char *d_name; /* For printing */ - int d_initial; /* Initial state */ - int d_nstates; - state *d_state; /* Array of states */ - bitset d_first; -} dfa; - -/* A grammar */ - -typedef struct { - int g_ndfas; - dfa *g_dfa; /* Array of DFAs */ - labellist g_ll; - int g_start; /* Start symbol of the grammar */ - int g_accel; /* Set if accelerators present */ -} grammar; - -/* FUNCTIONS */ - -grammar *newgrammar Py_PROTO((int start)); -dfa *adddfa Py_PROTO((grammar *g, int type, char *name)); -int addstate Py_PROTO((dfa *d)); -void addarc Py_PROTO((dfa *d, int from, int to, int lbl)); -dfa *PyGrammar_FindDFA Py_PROTO((grammar *g, int type)); -char *typename Py_PROTO((grammar *g, int lbl)); - -int addlabel Py_PROTO((labellist *ll, int type, char *str)); -int findlabel Py_PROTO((labellist *ll, int type, char *str)); -char *PyGrammar_LabelRepr Py_PROTO((label *lb)); -void translatelabels Py_PROTO((grammar *g)); - -void addfirstsets Py_PROTO((grammar *g)); - -void PyGrammar_AddAccelerators Py_PROTO((grammar *g)); - -void printgrammar Py_PROTO((grammar *g, FILE *fp)); -void printnonterminals Py_PROTO((grammar *g, FILE *fp)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_GRAMMAR_H */ diff --git a/Include/import.h b/Include/import.h deleted file mode 100644 index b406233d3c..0000000000 --- a/Include/import.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef Py_IMPORT_H -#define Py_IMPORT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Module definition and import interface */ - -void PyImport_Init Py_PROTO((void)); -long PyImport_GetMagicNumber Py_PROTO((void)); -PyObject *PyImport_ExecCodeModule Py_PROTO((char *name, PyObject *co)); -PyObject *PyImport_GetModuleDict Py_PROTO((void)); -PyObject *PyImport_AddModule Py_PROTO((char *name)); -PyObject *PyImport_ImportModule Py_PROTO((char *name)); -PyObject *PyImport_ReloadModule Py_PROTO((PyObject *m)); -void PyImport_Cleanup Py_PROTO((void)); -int PyImport_ImportFrozenModule Py_PROTO((char *)); - -struct _inittab { - char *name; - void (*initfunc)(); -}; - -extern struct _inittab inittab[]; - -#ifdef __cplusplus -} -#endif -#endif /* !Py_IMPORT_H */ diff --git a/Include/intobject.h b/Include/intobject.h deleted file mode 100644 index 24bcbf063d..0000000000 --- a/Include/intobject.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef Py_INTOBJECT_H -#define Py_INTOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Integer object interface */ - -/* -123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 - -PyIntObject represents a (long) integer. This is an immutable object; -an integer cannot change its value after creation. - -There are functions to create new integer objects, to test an object -for integer-ness, and to get the integer value. The latter functions -returns -1 and sets errno to EBADF if the object is not an PyIntObject. -None of the functions should be applied to nil objects. - -The type PyIntObject is (unfortunately) exposed here so we can declare -_Py_TrueStruct and _Py_ZeroStruct below; don't use this. -*/ - -typedef struct { - PyObject_HEAD - long ob_ival; -} PyIntObject; - -extern DL_IMPORT(PyTypeObject) PyInt_Type; - -#define PyInt_Check(op) ((op)->ob_type == &PyInt_Type) - -extern PyObject *PyInt_FromLong Py_PROTO((long)); -extern long PyInt_AsLong Py_PROTO((PyObject *)); - - -/* -123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 - -False and True are special intobjects used by Boolean expressions. -All values of type Boolean must point to either of these; but in -contexts where integers are required they are integers (valued 0 and 1). -Hope these macros don't conflict with other people's. - -Don't forget to apply Py_INCREF() when returning True or False!!! -*/ - -extern DL_IMPORT(PyIntObject) _Py_ZeroStruct, _Py_TrueStruct; /* Don't use these directly */ - -#define Py_False ((PyObject *) &_Py_ZeroStruct) -#define Py_True ((PyObject *) &_Py_TrueStruct) - -/* Macro, trading safety for speed */ -#define PyInt_AS_LONG(op) ((op)->ob_ival) - -#ifdef __cplusplus -} -#endif -#endif /* !Py_INTOBJECT_H */ diff --git a/Include/intrcheck.h b/Include/intrcheck.h deleted file mode 100644 index e91a927a06..0000000000 --- a/Include/intrcheck.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef Py_INTRCHECK_H -#define Py_INTRCHECK_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -extern int PyOS_InterruptOccurred Py_PROTO((void)); -extern void PyOS_InitInterrupts Py_PROTO((void)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_INTRCHECK_H */ diff --git a/Include/listobject.h b/Include/listobject.h deleted file mode 100644 index 76b49be334..0000000000 --- a/Include/listobject.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef Py_LISTOBJECT_H -#define Py_LISTOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* List object interface */ - -/* -123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 - -Another generally useful object type is an list of object pointers. -This is a mutable type: the list items can be changed, and items can be -added or removed. Out-of-range indices or non-list objects are ignored. - -*** WARNING *** PyList_SetItem does not increment the new item's reference -count, but does decrement the reference count of the item it replaces, -if not nil. It does *decrement* the reference count if it is *not* -inserted in the list. Similarly, PyList_GetItem does not increment the -returned item's reference count. -*/ - -typedef struct { - PyObject_VAR_HEAD - PyObject **ob_item; -} PyListObject; - -extern DL_IMPORT(PyTypeObject) PyList_Type; - -#define PyList_Check(op) ((op)->ob_type == &PyList_Type) - -extern PyObject *PyList_New Py_PROTO((int size)); -extern int PyList_Size Py_PROTO((PyObject *)); -extern PyObject *PyList_GetItem Py_PROTO((PyObject *, int)); -extern int PyList_SetItem Py_PROTO((PyObject *, int, PyObject *)); -extern int PyList_Insert Py_PROTO((PyObject *, int, PyObject *)); -extern int PyList_Append Py_PROTO((PyObject *, PyObject *)); -extern PyObject *PyList_GetSlice Py_PROTO((PyObject *, int, int)); -extern int PyList_SetSlice Py_PROTO((PyObject *, int, int, PyObject *)); -extern int PyList_Sort Py_PROTO((PyObject *)); -extern int PyList_Reverse Py_PROTO((PyObject *)); -extern PyObject *PyList_AsTuple Py_PROTO((PyObject *)); - -/* Macro, trading safety for speed */ -#define PyList_GET_ITEM(op, i) ((op)->ob_item[i]) - -#ifdef __cplusplus -} -#endif -#endif /* !Py_LISTOBJECT_H */ diff --git a/Include/longintrepr.h b/Include/longintrepr.h deleted file mode 100644 index 2a911c24c3..0000000000 --- a/Include/longintrepr.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef Py_LONGINTREPR_H -#define Py_LONGINTREPR_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* This is published for the benefit of "friend" marshal.c only. */ - -/* Parameters of the long integer representation. - These shouldn't have to be changed as C should guarantee that a short - contains at least 16 bits, but it's made changeable any way. - Note: 'digit' should be able to hold 2*MASK+1, and 'twodigits' - should be able to hold the intermediate results in 'mul' - (at most MASK << SHIFT). - Also, x_sub assumes that 'digit' is an unsigned type, and overflow - is handled by taking the result mod 2**N for some N > SHIFT. - And, at some places it is assumed that MASK fits in an int, as well. */ - -typedef unsigned short digit; -typedef unsigned int wdigit; /* digit widened to parameter size */ -typedef unsigned long twodigits; -typedef long stwodigits; /* signed variant of twodigits */ - -#define SHIFT 15 -#define BASE ((digit)1 << SHIFT) -#define MASK ((int)(BASE - 1)) - -/* Long integer representation. - 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. - In a normalized number, ob_digit[abs(ob_size)-1] (the most significant - digit) is never zero. Also, in all cases, for all valid i, - 0 <= ob_digit[i] <= MASK. - The allocation fuction takes care of allocating extra memory - so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available. */ - -struct _longobject { - PyObject_HEAD - int ob_size; - digit ob_digit[1]; -}; - -PyLongObject *_PyLong_New Py_PROTO((int)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_LONGINTREPR_H */ diff --git a/Include/longobject.h b/Include/longobject.h deleted file mode 100644 index 77e5efe966..0000000000 --- a/Include/longobject.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef Py_LONGOBJECT_H -#define Py_LONGOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Long (arbitrary precision) integer object interface */ - -typedef struct _longobject PyLongObject; /* Revealed in longintrepr.h */ - -extern DL_IMPORT(PyTypeObject) PyLong_Type; - -#define PyLong_Check(op) ((op)->ob_type == &PyLong_Type) - -extern PyObject *PyLong_FromLong Py_PROTO((long)); -extern PyObject *PyLong_FromDouble Py_PROTO((double)); -extern long PyLong_AsLong Py_PROTO((PyObject *)); -extern double PyLong_AsDouble Py_PROTO((PyObject *)); - -PyObject *PyLong_FromString Py_PROTO((char *, char **, int)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_LONGOBJECT_H */ diff --git a/Include/mappingobject.h b/Include/mappingobject.h deleted file mode 100644 index 584ee5a48c..0000000000 --- a/Include/mappingobject.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef Py_MAPPINGOBJECT_H -#define Py_MAPPINGOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Dictionary object type -- mapping from hashable object to object */ -/* NB Should be moved back to dictobject.h */ - -extern DL_IMPORT(PyTypeObject) PyDict_Type; - -#define PyDict_Check(op) ((op)->ob_type == &PyDict_Type) - -extern PyObject *PyDict_New Py_PROTO((void)); -extern PyObject *PyDict_GetItem Py_PROTO((PyObject *mp, PyObject *key)); -extern int PyDict_SetItem Py_PROTO((PyObject *mp, PyObject *key, PyObject *item)); -extern int PyDict_DelItem Py_PROTO((PyObject *mp, PyObject *key)); -extern void PyDict_Clear Py_PROTO((PyObject *mp)); -extern int PyDict_Next - Py_PROTO((PyObject *mp, int *pos, PyObject **key, PyObject **value)); -extern PyObject *PyDict_Keys Py_PROTO((PyObject *mp)); -extern PyObject *PyDict_Values Py_PROTO((PyObject *mp)); -extern PyObject *PyDict_Items Py_PROTO((PyObject *mp)); -extern int PyDict_Size Py_PROTO((PyObject *mp)); - -extern PyObject *PyDict_GetItemString Py_PROTO((PyObject *dp, char *key)); -extern int PyDict_SetItemString Py_PROTO((PyObject *dp, char *key, PyObject *item)); -extern int PyDict_DelItemString Py_PROTO((PyObject *dp, char *key)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_MAPPINGOBJECT_H */ diff --git a/Include/marshal.h b/Include/marshal.h deleted file mode 100644 index 55396d5c2d..0000000000 --- a/Include/marshal.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef Py_MARSHAL_H -#define Py_MARSHAL_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Interface for marshal.c */ - -void PyMarshal_WriteLongToFile Py_PROTO((long, FILE *)); -void PyMarshal_WriteShortToFile Py_PROTO((int, FILE *)); -void PyMarshal_WriteObjectToFile Py_PROTO((PyObject *, FILE *)); - -long PyMarshal_ReadLongFromFile Py_PROTO((FILE *)); -int PyMarshal_ReadShortFromFile Py_PROTO((FILE *)); -PyObject *PyMarshal_ReadObjectFromFile Py_PROTO((FILE *)); -PyObject *PyMarshal_ReadObjectFromString Py_PROTO((char *, int)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_MARSHAL_H */ diff --git a/Include/metagrammar.h b/Include/metagrammar.h deleted file mode 100644 index 4d386a2196..0000000000 --- a/Include/metagrammar.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef Py_METAGRAMMAR_H -#define Py_METAGRAMMAR_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#define MSTART 256 -#define RULE 257 -#define RHS 258 -#define ALT 259 -#define ITEM 260 -#define ATOM 261 - -#ifdef __cplusplus -} -#endif -#endif /* !Py_METAGRAMMAR_H */ diff --git a/Include/methodobject.h b/Include/methodobject.h deleted file mode 100644 index 243b3be175..0000000000 --- a/Include/methodobject.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef Py_METHODOBJECT_H -#define Py_METHODOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Method object interface */ - -extern DL_IMPORT(PyTypeObject) PyCFunction_Type; - -#define PyCFunction_Check(op) ((op)->ob_type == &PyCFunction_Type) - -typedef PyObject *(*PyCFunction) Py_FPROTO((PyObject *, PyObject *)); -typedef PyObject *(*PyCFunctionWithKeywords) - Py_FPROTO((PyObject *, PyObject *, PyObject *)); - -extern PyCFunction PyCFunction_GetFunction Py_PROTO((PyObject *)); -extern PyObject *PyCFunction_GetSelf Py_PROTO((PyObject *)); -extern int PyCFunction_GetFlags Py_PROTO((PyObject *)); - -struct PyMethodDef { - char *ml_name; - PyCFunction ml_meth; - int ml_flags; - char *ml_doc; -}; -typedef struct PyMethodDef PyMethodDef; - -extern PyObject *Py_FindMethod - Py_PROTO((PyMethodDef[], PyObject *, char *)); - -extern PyObject *PyCFunction_New - Py_PROTO((PyMethodDef *, PyObject *)); - -/* Flag passed to newmethodobject */ -#define METH_VARARGS 0x0001 -#define METH_KEYWORDS 0x0002 - -typedef struct PyMethodChain { - PyMethodDef *methods; /* Methods of this type */ - struct PyMethodChain *link; /* NULL or base type */ -} PyMethodChain; - -extern PyObject *Py_FindMethodInChain - Py_PROTO((PyMethodChain *, PyObject *, char *)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_METHODOBJECT_H */ diff --git a/Include/modsupport.h b/Include/modsupport.h deleted file mode 100644 index 1ad4715fc4..0000000000 --- a/Include/modsupport.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef Py_MODSUPPORT_H -#define Py_MODSUPPORT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Module support interface */ - -#ifdef HAVE_STDARG_PROTOTYPES - -#include <stdarg.h> - -extern int PyArg_Parse Py_PROTO((PyObject *, char *, ...)); -extern int PyArg_ParseTuple Py_PROTO((PyObject *, char *, ...)); -extern PyObject *Py_BuildValue Py_PROTO((char *, ...)); - -#else - -#include <varargs.h> - -/* Better to have no prototypes at all for varargs functions in this case */ -extern int PyArg_Parse(); -extern int PyArg_ParseTuple(); -extern PyObject *Py_BuildValue(); - -#endif - -extern int PyArg_VaParse Py_PROTO((PyObject *, char *, va_list)); -extern PyObject *Py_VaBuildValue Py_PROTO((char *, va_list)); - -#define PYTHON_API_VERSION 1003 -/* The API version is maintained (independently from the Python version) - so we can detect mismatches between the interpreter and dynamically - loaded modules. - - Please add a line or two to the top of this log for each API - version change: - - 7-Nov-1995 GvR Keyword arguments (should've been done at 1.3 :-( ) - - 10-Jan-1995 GvR Renamed globals to new naming scheme - - 9-Jan-1995 GvR Initial version (incompatible with older API) -*/ - -extern PyObject *Py_InitModule4 Py_PROTO((char *, PyMethodDef *, - char *, PyObject *, int)); -#define Py_InitModule(name, methods) \ - Py_InitModule4(name, methods, (char *)NULL, (PyObject *)NULL, \ - PYTHON_API_VERSION) - -#ifdef __cplusplus -} -#endif -#endif /* !Py_MODSUPPORT_H */ diff --git a/Include/moduleobject.h b/Include/moduleobject.h deleted file mode 100644 index f8eea9c8ba..0000000000 --- a/Include/moduleobject.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef Py_MODULEOBJECT_H -#define Py_MODULEOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Module object interface */ - -extern DL_IMPORT(PyTypeObject) PyModule_Type; - -#define PyModule_Check(op) ((op)->ob_type == &PyModule_Type) - -extern PyObject *PyModule_New Py_PROTO((char *)); -extern PyObject *PyModule_GetDict Py_PROTO((PyObject *)); -extern char *PyModule_GetName Py_PROTO((PyObject *)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_MODULEOBJECT_H */ diff --git a/Include/mymalloc.h b/Include/mymalloc.h deleted file mode 100644 index f1e9352c35..0000000000 --- a/Include/mymalloc.h +++ /dev/null @@ -1,92 +0,0 @@ -#ifndef Py_MYMALLOC_H -#define Py_MYMALLOC_H -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Lowest-level memory allocation interface */ - -#ifdef macintosh -#define ANY void -#endif - -#ifdef __STDC__ -#define ANY void -#endif - -#ifdef __TURBOC__ -#define ANY void -#endif - -#ifdef __GNUC__ -#define ANY void -#endif - -#ifndef ANY -#define ANY char -#endif - -#ifdef HAVE_STDLIB_H -#include <stdlib.h> -#endif - -#ifdef __cplusplus -// Move this down here since some C++ #include's don't like to be included -// inside an extern "C" -extern "C" { -#endif - -#ifdef SYMANTEC__CFM68K__ -#pragma lib_export on -#endif - -#ifndef HAVE_STDLIB_H -extern ANY *malloc Py_PROTO((size_t)); -extern ANY *calloc Py_PROTO((size_t, size_t)); -extern ANY *realloc Py_PROTO((ANY *, size_t)); -extern void free Py_PROTO((ANY *)); /* XXX sometimes int on Unix old systems */ -#endif /* !HAVE_STDLIB */ - -#ifndef NULL -#define NULL ((ANY *)0) -#endif - -/* XXX Always allocate one extra byte, since some malloc's return NULL - XXX for malloc(0) or realloc(p, 0). */ -#define PyMem_NEW(type, n) ( (type *) malloc(1 + (n) * sizeof(type)) ) -#define PyMem_RESIZE(p, type, n) \ - if ((p) == NULL) \ - (p) = (type *) malloc(1 + (n) * sizeof(type)); \ - else \ - (p) = (type *) realloc((ANY *)(p), 1 + (n) * sizeof(type)) -#define PyMem_DEL(p) free((ANY *)p) -#define PyMem_XDEL(p) if ((p) == NULL) ; else PyMem_DEL(p) - -#ifdef __cplusplus -} -#endif - -#ifndef Py_USE_NEW_NAMES -#include "rename2.h" -#endif -#endif /* !Py_MYMALLOC_H */ diff --git a/Include/mymath.h b/Include/mymath.h deleted file mode 100644 index 36ee1eb133..0000000000 --- a/Include/mymath.h +++ /dev/null @@ -1,16 +0,0 @@ -/* On the 68K Mac, when using CFM (Code Fragment Manager), - <math.h> requires special treatment -- we need to surround it with - #pragma lib_export off / on... - This is because MathLib.o is a static library, and exporting its - symbols doesn't quite work... - XXX Not sure now... Seems to be something else going on as well... */ - -#ifdef SYMANTEC__CFM68K__ -#pragma lib_export off -#endif - -#include <math.h> - -#ifdef SYMANTEC__CFM68K__ -#pragma lib_export on -#endif diff --git a/Include/myproto.h b/Include/myproto.h deleted file mode 100644 index 6e91339ae5..0000000000 --- a/Include/myproto.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef Py_PROTO_H -#define Py_PROTO_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#ifdef HAVE_PROTOTYPES -#define Py_PROTO(x) x -#else -#define Py_PROTO(x) () -#endif - -#ifndef Py_FPROTO -#define Py_FPROTO(x) Py_PROTO(x) -#endif - -#ifdef __cplusplus -} -#endif - -#ifndef Py_USE_NEW_NAMES -#include "rename2.h" -#endif - -#endif /* !Py_PROTO_H */ diff --git a/Include/myselect.h b/Include/myselect.h deleted file mode 100644 index 0c92c7a13b..0000000000 --- a/Include/myselect.h +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef Py_MYSELECT_H -#define Py_MYSELECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Include file for users of select() */ - -/* NB caller must include <sys/types.h> */ - -#ifdef HAVE_SYS_SELECT_H - -#include <sys/select.h> - -#ifdef SYS_SELECT_WITH_SYS_TIME -#include "mytime.h" -#else /* !SYS_SELECT_WITH_SYS_TIME */ -#include <time.h> -#endif /* !SYS_SELECT_WITH_SYS_TIME */ - -#else /* !HAVE_SYS_SELECT_H */ - -#ifdef USE_GUSI -/* If we don't have sys/select the definition may be in unistd.h */ -#include <GUSI.h> -#endif - -#include "mytime.h" - -#endif /* !HAVE_SYS_SELECT_H */ - -/* If the fd manipulation macros aren't defined, - here is a set that should do the job */ - -#ifndef FD_SETSIZE -#define FD_SETSIZE 256 -#endif - -#ifndef FD_SET - -typedef long fd_mask; - -#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask */ -#ifndef howmany -#define howmany(x, y) (((x)+((y)-1))/(y)) -#endif /* howmany */ - -typedef struct fd_set { - fd_mask fds_bits[howmany(FD_SETSIZE, NFDBITS)]; -} fd_set; - -#define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS))) -#define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS))) -#define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS))) -#define FD_ZERO(p) memset((char *)(p), '\0', sizeof(*(p))) - -#endif /* FD_SET */ - -#ifdef __cplusplus -} -#endif -#endif /* !Py_MYSELECT_H */ diff --git a/Include/mytime.h b/Include/mytime.h deleted file mode 100644 index bdd939efd0..0000000000 --- a/Include/mytime.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef Py_MYTIME_H -#define Py_MYTIME_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Include file instead of <time.h> and/or <sys/time.h> */ - -#ifdef TIME_WITH_SYS_TIME -#include <sys/time.h> -#include <time.h> -#else /* !TIME_WITH_SYS_TIME */ -#ifdef HAVE_SYS_TIME_H -#include <sys/time.h> -#else /* !HAVE_SYS_TIME_H */ -#include <time.h> -#endif /* !HAVE_SYS_TIME_H */ -#endif /* !TIME_WITH_SYS_TIME */ - -#ifdef __cplusplus -} -#endif -#endif /* !Py_MYTIME_H */ diff --git a/Include/node.h b/Include/node.h deleted file mode 100644 index fbeb851dff..0000000000 --- a/Include/node.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef Py_NODE_H -#define Py_NODE_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Parse tree node interface */ - -typedef struct _node { - short n_type; - char *n_str; - short n_lineno; - short n_nchildren; - struct _node *n_child; -} node; - -extern node *PyNode_New Py_PROTO((int type)); -extern node *PyNode_AddChild Py_PROTO((node *n, int type, char *str, int lineno)); -extern void PyNode_Free Py_PROTO((node *n)); - -/* Node access functions */ -#define NCH(n) ((n)->n_nchildren) -#define CHILD(n, i) (&(n)->n_child[i]) -#define TYPE(n) ((n)->n_type) -#define STR(n) ((n)->n_str) - -/* Assert that the type of a node is what we expect */ -#ifndef DEBUG -#define REQ(n, type) { /*pass*/ ; } -#else -#define REQ(n, type) \ - { if (TYPE(n) != (type)) { \ - fprintf(stderr, "FATAL: node type %d, required %d\n", \ - TYPE(n), type); \ - abort(); \ - } } -#endif - -extern void PyNode_ListTree Py_PROTO((node *)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_NODE_H */ diff --git a/Include/object.h b/Include/object.h deleted file mode 100644 index a79d1f7356..0000000000 --- a/Include/object.h +++ /dev/null @@ -1,452 +0,0 @@ -#ifndef Py_OBJECT_H -#define Py_OBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Object and type object interface */ - -/* -123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 - -Objects are structures allocated on the heap. Special rules apply to -the use of objects to ensure they are properly garbage-collected. -Objects are never allocated statically or on the stack; they must be -accessed through special macros and functions only. (Type objects are -exceptions to the first rule; the standard types are represented by -statically initialized type objects.) - -An object has a 'reference count' that is increased or decreased when a -pointer to the object is copied or deleted; when the reference count -reaches zero there are no references to the object left and it can be -removed from the heap. - -An object has a 'type' that determines what it represents and what kind -of data it contains. An object's type is fixed when it is created. -Types themselves are represented as objects; an object contains a -pointer to the corresponding type object. The type itself has a type -pointer pointing to the object representing the type 'type', which -contains a pointer to itself!). - -Objects do not float around in memory; once allocated an object keeps -the same size and address. Objects that must hold variable-size data -can contain pointers to variable-size parts of the object. Not all -objects of the same type have the same size; but the size cannot change -after allocation. (These restrictions are made so a reference to an -object can be simply a pointer -- moving an object would require -updating all the pointers, and changing an object's size would require -moving it if there was another object right next to it.) - -Objects are always accessed through pointers of the type 'PyObject *'. -The type 'PyObject' is a structure that only contains the reference count -and the type pointer. The actual memory allocated for an object -contains other data that can only be accessed after casting the pointer -to a pointer to a longer structure type. This longer type must start -with the reference count and type fields; the macro PyObject_HEAD should be -used for this (to accomodate for future changes). The implementation -of a particular object type can cast the object pointer to the proper -type and back. - -A standard interface exists for objects that contain an array of items -whose size is determined when the object is allocated. - -123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 -*/ - -#ifdef DEBUG - -/* Turn on heavy reference debugging */ -#define Py_TRACE_REFS - -/* Turn on reference counting */ -#define Py_REF_DEBUG - -#endif /* DEBUG */ - -#ifdef Py_TRACE_REFS -#define PyObject_HEAD \ - struct _object *_ob_next, *_ob_prev; \ - int ob_refcnt; \ - struct _typeobject *ob_type; -#define PyObject_HEAD_INIT(type) 0, 0, 1, type, -#else /* !Py_TRACE_REFS */ -#define PyObject_HEAD \ - int ob_refcnt; \ - struct _typeobject *ob_type; -#define PyObject_HEAD_INIT(type) 1, type, -#endif /* !Py_TRACE_REFS */ - -#define PyObject_VAR_HEAD \ - PyObject_HEAD \ - int ob_size; /* Number of items in variable part */ - -typedef struct _object { - PyObject_HEAD -} PyObject; - -typedef struct { - PyObject_VAR_HEAD -} varobject; - - -/* -123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 - -Type objects contain a string containing the type name (to help somewhat -in debugging), the allocation parameters (see newobj() and newvarobj()), -and methods for accessing objects of the type. Methods are optional,a -nil pointer meaning that particular kind of access is not available for -this type. The Py_DECREF() macro uses the tp_dealloc method without -checking for a nil pointer; it should always be implemented except if -the implementation can guarantee that the reference count will never -reach zero (e.g., for type objects). - -NB: the methods for certain type groups are now contained in separate -method blocks. -*/ - -typedef PyObject * (*unaryfunc) Py_PROTO((PyObject *)); -typedef PyObject * (*binaryfunc) Py_PROTO((PyObject *, PyObject *)); -typedef PyObject * (*ternaryfunc) Py_PROTO((PyObject *, PyObject *, PyObject *)); -typedef int (*inquiry) Py_PROTO((PyObject *)); -typedef int (*coercion) Py_PROTO((PyObject **, PyObject **)); -typedef PyObject *(*intargfunc) Py_PROTO((PyObject *, int)); -typedef PyObject *(*intintargfunc) Py_PROTO((PyObject *, int, int)); -typedef int(*intobjargproc) Py_PROTO((PyObject *, int, PyObject *)); -typedef int(*intintobjargproc) Py_PROTO((PyObject *, int, int, PyObject *)); -typedef int(*objobjargproc) Py_PROTO((PyObject *, PyObject *, PyObject *)); - -typedef struct { - binaryfunc nb_add; - binaryfunc nb_subtract; - binaryfunc nb_multiply; - binaryfunc nb_divide; - binaryfunc nb_remainder; - binaryfunc nb_divmod; - ternaryfunc nb_power; - unaryfunc nb_negative; - unaryfunc nb_positive; - unaryfunc nb_absolute; - inquiry nb_nonzero; - unaryfunc nb_invert; - binaryfunc nb_lshift; - binaryfunc nb_rshift; - binaryfunc nb_and; - binaryfunc nb_xor; - binaryfunc nb_or; - coercion nb_coerce; - unaryfunc nb_int; - unaryfunc nb_long; - unaryfunc nb_float; - unaryfunc nb_oct; - unaryfunc nb_hex; -} PyNumberMethods; - -typedef struct { - inquiry sq_length; - binaryfunc sq_concat; - intargfunc sq_repeat; - intargfunc sq_item; - intintargfunc sq_slice; - intobjargproc sq_ass_item; - intintobjargproc sq_ass_slice; -} PySequenceMethods; - -typedef struct { - inquiry mp_length; - binaryfunc mp_subscript; - objobjargproc mp_ass_subscript; -} PyMappingMethods; - -typedef void (*destructor) Py_PROTO((PyObject *)); -typedef int (*printfunc) Py_PROTO((PyObject *, FILE *, int)); -typedef PyObject *(*getattrfunc) Py_PROTO((PyObject *, char *)); -typedef int (*setattrfunc) Py_PROTO((PyObject *, char *, PyObject *)); -typedef int (*cmpfunc) Py_PROTO((PyObject *, PyObject *)); -typedef PyObject *(*reprfunc) Py_PROTO((PyObject *)); -typedef long (*hashfunc) Py_PROTO((PyObject *)); - -typedef struct _typeobject { - PyObject_VAR_HEAD - char *tp_name; /* For printing */ - int tp_basicsize, tp_itemsize; /* For allocation */ - - /* Methods to implement standard operations */ - - destructor tp_dealloc; - printfunc tp_print; - getattrfunc tp_getattr; - setattrfunc tp_setattr; - cmpfunc tp_compare; - reprfunc tp_repr; - - /* Method suites for standard classes */ - - PyNumberMethods *tp_as_number; - PySequenceMethods *tp_as_sequence; - PyMappingMethods *tp_as_mapping; - - /* More standard operations (at end for binary compatibility) */ - - hashfunc tp_hash; - ternaryfunc tp_call; - reprfunc tp_str; - - /* Space for future expansion */ - long tp_xxx1; - long tp_xxx2; - long tp_xxx3; - long tp_xxx4; - - char *tp_doc; /* Documentation string */ - -#ifdef COUNT_ALLOCS - /* these must be last */ - int tp_alloc; - int tp_free; - int tp_maxalloc; - struct _typeobject *tp_next; -#endif -} PyTypeObject; - -extern DL_IMPORT(PyTypeObject) PyType_Type; /* The type of type objects */ - -#define PyType_Check(op) ((op)->ob_type == &PyType_Type) - -/* Generic operations on objects */ -extern int PyObject_Print Py_PROTO((PyObject *, FILE *, int)); -extern PyObject * PyObject_Repr Py_PROTO((PyObject *)); -extern PyObject * PyObject_Str Py_PROTO((PyObject *)); -extern int PyObject_Compare Py_PROTO((PyObject *, PyObject *)); -extern PyObject *PyObject_GetAttrString Py_PROTO((PyObject *, char *)); -extern int PyObject_SetAttrString Py_PROTO((PyObject *, char *, PyObject *)); -extern int PyObject_HasAttrString Py_PROTO((PyObject *, char *)); -extern PyObject *PyObject_GetAttr Py_PROTO((PyObject *, PyObject *)); -extern int PyObject_SetAttr Py_PROTO((PyObject *, PyObject *, PyObject *)); -extern long PyObject_Hash Py_PROTO((PyObject *)); -extern int PyObject_IsTrue Py_PROTO((PyObject *)); -extern int PyCallable_Check Py_PROTO((PyObject *)); -extern int PyNumber_Coerce Py_PROTO((PyObject **, PyObject **)); - -/* Flag bits for printing: */ -#define Py_PRINT_RAW 1 /* No string quotes etc. */ - -/* -123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 - -The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement -reference counts. Py_DECREF calls the object's deallocator function; for -objects that don't contain references to other objects or heap memory -this can be the standard function free(). Both macros can be used -whereever a void expression is allowed. The argument shouldn't be a -NIL pointer. The macro _Py_NewReference(op) is used only to initialize -reference counts to 1; it is defined here for convenience. - -We assume that the reference count field can never overflow; this can -be proven when the size of the field is the same as the pointer size -but even with a 16-bit reference count field it is pretty unlikely so -we ignore the possibility. (If you are paranoid, make it a long.) - -Type objects should never be deallocated; the type pointer in an object -is not considered to be a reference to the type object, to save -complications in the deallocation function. (This is actually a -decision that's up to the implementer of each new type so if you want, -you can count such references to the type object.) - -*** WARNING*** The Py_DECREF macro must have a side-effect-free argument -since it may evaluate its argument multiple times. (The alternative -would be to mace it a proper function or assign it to a global temporary -variable first, both of which are slower; and in a multi-threaded -environment the global variable trick is not safe.) -*/ - -#ifdef Py_TRACE_REFS -#ifndef Py_REF_DEBUG -#define Py_REF_DEBUG -#endif -#endif - -#ifndef Py_TRACE_REFS -#ifdef COUNT_ALLOCS -#define _Py_Dealloc(op) ((op)->ob_type->tp_free++, (*(op)->ob_type->tp_dealloc)((PyObject *)(op))) -#define _Py_ForgetReference(op) ((op)->ob_type->tp_free++) -#else -#define _Py_Dealloc(op) (*(op)->ob_type->tp_dealloc)((PyObject *)(op)) -#define _Py_ForgetReference(op) /*empty*/ -#endif -#endif - -#ifdef COUNT_ALLOCS -extern void inc_count Py_PROTO((PyTypeObject *)); -#endif - -#ifdef Py_REF_DEBUG - -extern long _Py_RefTotal; - -#ifndef Py_TRACE_REFS -#ifdef COUNT_ALLOCS -#define _Py_NewReference(op) (inc_count((op)->ob_type), _Py_RefTotal++, (op)->ob_refcnt = 1) -#else -#define _Py_NewReference(op) (_Py_RefTotal++, (op)->ob_refcnt = 1) -#endif -#endif /* !Py_TRACE_REFS */ - -#define Py_INCREF(op) (_Py_RefTotal++, (op)->ob_refcnt++) -#define Py_DECREF(op) \ - if (--_Py_RefTotal, --(op)->ob_refcnt != 0) \ - ; \ - else \ - _Py_Dealloc(op) -#else /* !Py_REF_DEBUG */ - -#ifdef COUNT_ALLOCS -#define _Py_NewReference(op) (inc_count((op)->ob_type), (op)->ob_refcnt = 1) -#else -#define _Py_NewReference(op) ((op)->ob_refcnt = 1) -#endif - -#define Py_INCREF(op) ((op)->ob_refcnt++) -#define Py_DECREF(op) \ - if (--(op)->ob_refcnt != 0) \ - ; \ - else \ - _Py_Dealloc(op) -#endif /* !Py_REF_DEBUG */ - -/* Macros to use in case the object pointer may be NULL: */ - -#define Py_XINCREF(op) if ((op) == NULL) ; else Py_INCREF(op) -#define Py_XDECREF(op) if ((op) == NULL) ; else Py_DECREF(op) - -/* Definition of NULL, so you don't have to include <stdio.h> */ - -#ifndef NULL -#define NULL 0 -#endif - - -/* -_Py_NoneStruct is an object of undefined type which can be used in contexts -where NULL (nil) is not suitable (since NULL often means 'error'). - -Don't forget to apply Py_INCREF() when returning this value!!! -*/ - -extern DL_IMPORT(PyObject) _Py_NoneStruct; /* Don't use this directly */ - -#define Py_None (&_Py_NoneStruct) - - -/* -A common programming style in Python requires the forward declaration -of static, initialized structures, e.g. for a type object that is used -by the functions whose address must be used in the initializer. -Some compilers (notably SCO ODT 3.0, I seem to remember early AIX as -well) botch this if you use the static keyword for both declarations -(they allocate two objects, and use the first, uninitialized one until -the second declaration is encountered). Therefore, the forward -declaration should use the 'forwardstatic' keyword. This expands to -static on most systems, but to extern on a few. The actual storage -and name will still be static because the second declaration is -static, so no linker visible symbols will be generated. (Standard C -compilers take offense to the extern forward declaration of a static -object, so I can't just put extern in all cases. :-( ) -*/ - -#ifdef BAD_STATIC_FORWARD -#define staticforward extern -#ifdef __SC__ -#define statichere -#else -#define statichere static -#endif /* __SC__ */ -#else /* !BAD_STATIC_FORWARD */ -#define staticforward static -#define statichere static -#endif /* !BAD_STATIC_FORWARD */ - - -/* -123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 - -More conventions -================ - -Argument Checking ------------------ - -Functions that take objects as arguments normally don't check for nil -arguments, but they do check the type of the argument, and return an -error if the function doesn't apply to the type. - -Failure Modes -------------- - -Functions may fail for a variety of reasons, including running out of -memory. This is communicated to the caller in two ways: an error string -is set (see errors.h), and the function result differs: functions that -normally return a pointer return NULL for failure, functions returning -an integer return -1 (which could be a legal return value too!), and -other functions return 0 for success and -1 for failure. -Callers should always check for errors before using the result. - -Reference Counts ----------------- - -It takes a while to get used to the proper usage of reference counts. - -Functions that create an object set the reference count to 1; such new -objects must be stored somewhere or destroyed again with Py_DECREF(). -Functions that 'store' objects such as PyTuple_SetItem() and -PyDict_SetItemString() -don't increment the reference count of the object, since the most -frequent use is to store a fresh object. Functions that 'retrieve' -objects such as PyTuple_GetItem() and PyDict_GetItemString() also -don't increment -the reference count, since most frequently the object is only looked at -quickly. Thus, to retrieve an object and store it again, the caller -must call Py_INCREF() explicitly. - -NOTE: functions that 'consume' a reference count like -PyDict_SetItemString() even -consume the reference if the object wasn't stored, to simplify error -handling. - -It seems attractive to make other functions that take an object as -argument consume a reference count; however this may quickly get -confusing (even the current practice is already confusing). Consider -it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at -times. - -123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 -*/ - -#ifdef __cplusplus -} -#endif -#endif /* !Py_OBJECT_H */ diff --git a/Include/objimpl.h b/Include/objimpl.h deleted file mode 100644 index 139e3377ae..0000000000 --- a/Include/objimpl.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef Py_OBJIMPL_H -#define Py_OBJIMPL_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* -123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 - -Additional macros for modules that implement new object types. -You must first include "object.h". - -PyObject_NEW(type, typeobj) allocates memory for a new object of the given -type; here 'type' must be the C structure type used to represent the -object and 'typeobj' the address of the corresponding type object. -Reference count and type pointer are filled in; the rest of the bytes of -the object are *undefined*! The resulting expression type is 'type *'. -The size of the object is actually determined by the tp_basicsize field -of the type object. - -PyObject_NEW_VAR(type, typeobj, n) is similar but allocates a variable-size -object with n extra items. The size is computed as tp_basicsize plus -n * tp_itemsize. This fills in the ob_size field as well. -*/ - -extern PyObject *_PyObject_New Py_PROTO((PyTypeObject *)); -extern varobject *_PyObject_NewVar Py_PROTO((PyTypeObject *, int)); - -#define PyObject_NEW(type, typeobj) ((type *) _PyObject_New(typeobj)) -#define PyObject_NEW_VAR(type, typeobj, n) ((type *) _PyObject_NewVar(typeobj, n)) - -#ifdef __cplusplus -} -#endif -#endif /* !Py_OBJIMPL_H */ diff --git a/Include/opcode.h b/Include/opcode.h deleted file mode 100644 index 401f765f5f..0000000000 --- a/Include/opcode.h +++ /dev/null @@ -1,151 +0,0 @@ -#ifndef Py_OPCODE_H -#define Py_OPCODE_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Instruction opcodes for compiled code */ - -#define STOP_CODE 0 -#define POP_TOP 1 -#define ROT_TWO 2 -#define ROT_THREE 3 -#define DUP_TOP 4 - -#define UNARY_POSITIVE 10 -#define UNARY_NEGATIVE 11 -#define UNARY_NOT 12 -#define UNARY_CONVERT 13 - -#define UNARY_INVERT 15 - -#define BINARY_POWER 19 - -#define BINARY_MULTIPLY 20 -#define BINARY_DIVIDE 21 -#define BINARY_MODULO 22 -#define BINARY_ADD 23 -#define BINARY_SUBTRACT 24 -#define BINARY_SUBSCR 25 - -#define SLICE 30 -/* Also uses 31-33 */ - -#define STORE_SLICE 40 -/* Also uses 41-43 */ - -#define DELETE_SLICE 50 -/* Also uses 51-53 */ - -#define STORE_SUBSCR 60 -#define DELETE_SUBSCR 61 - -#define BINARY_LSHIFT 62 -#define BINARY_RSHIFT 63 -#define BINARY_AND 64 -#define BINARY_XOR 65 -#define BINARY_OR 66 - - -#define PRINT_EXPR 70 -#define PRINT_ITEM 71 -#define PRINT_NEWLINE 72 - -#define BREAK_LOOP 80 - -#define LOAD_LOCALS 82 -#define RETURN_VALUE 83 - -#define EXEC_STMT 85 - -#define POP_BLOCK 87 -#define END_FINALLY 88 -#define BUILD_CLASS 89 - -#define HAVE_ARGUMENT 90 /* Opcodes from here have an argument: */ - -#define STORE_NAME 90 /* Index in name list */ -#define DELETE_NAME 91 /* "" */ -#define UNPACK_TUPLE 92 /* Number of tuple items */ -#define UNPACK_LIST 93 /* Number of list items */ -#define UNPACK_ARG 94 /* Number of arguments */ -#define STORE_ATTR 95 /* Index in name list */ -#define DELETE_ATTR 96 /* "" */ -#define STORE_GLOBAL 97 /* "" */ -#define DELETE_GLOBAL 98 /* "" */ -#define UNPACK_VARARG 99 /* Minimal number of arguments */ - -#define LOAD_CONST 100 /* Index in const list */ -#define LOAD_NAME 101 /* Index in name list */ -#define BUILD_TUPLE 102 /* Number of tuple items */ -#define BUILD_LIST 103 /* Number of list items */ -#define BUILD_MAP 104 /* Always zero for now */ -#define LOAD_ATTR 105 /* Index in name list */ -#define COMPARE_OP 106 /* Comparison operator */ -#define IMPORT_NAME 107 /* Index in name list */ -#define IMPORT_FROM 108 /* Index in name list */ -#define ACCESS_MODE 109 /* Name (mode is int on top of stack) */ - -#define JUMP_FORWARD 110 /* Number of bytes to skip */ -#define JUMP_IF_FALSE 111 /* "" */ -#define JUMP_IF_TRUE 112 /* "" */ -#define JUMP_ABSOLUTE 113 /* Target byte offset from beginning of code */ -#define FOR_LOOP 114 /* Number of bytes to skip */ - -#define LOAD_LOCAL 115 /* Index in name list */ -#define LOAD_GLOBAL 116 /* Index in name list */ - -#define SET_FUNC_ARGS 117 /* Argcount */ - -#define SETUP_LOOP 120 /* Target address (absolute) */ -#define SETUP_EXCEPT 121 /* "" */ -#define SETUP_FINALLY 122 /* "" */ - -#define LOAD_FAST 124 /* Local variable number */ -#define STORE_FAST 125 /* Local variable number */ -#define DELETE_FAST 126 /* Local variable number */ - -#define SET_LINENO 127 /* Current line number */ - -/* It used to be the case that opcodes should fit in 7 bits. This is - no longer the case -- 8 bits is fine (the instruction stream is now - a sequence of unsigned characters). We gladly use the new space - for new opcodes. */ - -#define RAISE_VARARGS 130 /* Number of raise arguments (1, 2 or 3) */ -#define CALL_FUNCTION 131 /* #args + (#kwargs<<8) */ -#define MAKE_FUNCTION 132 /* #defaults */ - -/* Comparison operator codes (argument to COMPARE_OP) */ -enum cmp_op {LT, LE, EQ, NE, GT, GE, IN, NOT_IN, IS, IS_NOT, EXC_MATCH, BAD}; - -#define HAS_ARG(op) ((op) >= HAVE_ARGUMENT) - -#ifdef __cplusplus -} -#endif -#endif /* !Py_OPCODE_H */ diff --git a/Include/osdefs.h b/Include/osdefs.h deleted file mode 100644 index 8a6b741f7a..0000000000 --- a/Include/osdefs.h +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef Py_OSDEFS_H -#define Py_OSDEFS_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Operating system dependencies */ - -#ifdef macintosh -#define SEP ':' -#define MAXPATHLEN 256 -/* Mod by Jack: newline is less likely to occur in filenames than space */ -#define DELIM '\n' -#endif - -#if defined(MSDOS) || defined(NT) || defined(__BORLANDC__) || defined(__WATCOMC__) -#define SEP '\\' -#define MAXPATHLEN 256 -#define DELIM ';' -#endif - -/* Filename separator */ -#ifndef SEP -#define SEP '/' -#endif - -/* Max pathname length */ -#ifndef MAXPATHLEN -#define MAXPATHLEN 1024 -#endif - -/* Search path entry delimiter */ -#ifndef DELIM -#define DELIM ':' -#endif - -#ifdef __cplusplus -} -#endif -#endif /* !Py_OSDEFS_H */ diff --git a/Include/parsetok.h b/Include/parsetok.h deleted file mode 100644 index 7ef64cf9f0..0000000000 --- a/Include/parsetok.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef Py_PARSETOK_H -#define Py_PARSETOK_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Parser-tokenizer link interface */ - -typedef struct { - int error; - char *filename; - int lineno; - int offset; - char *text; -} perrdetail; - -extern node *PyParser_ParseString Py_PROTO((char *, grammar *, int, perrdetail *)); -extern node *PyParser_ParseFile Py_PROTO((FILE *, char *, grammar *, int, - char *, char *, perrdetail *)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_PARSETOK_H */ diff --git a/Include/patchlevel.h b/Include/patchlevel.h deleted file mode 100644 index 8abf85bcc1..0000000000 --- a/Include/patchlevel.h +++ /dev/null @@ -1 +0,0 @@ -#define PATCHLEVEL "1.3" diff --git a/Include/pgenheaders.h b/Include/pgenheaders.h deleted file mode 100644 index cc4386f6b9..0000000000 --- a/Include/pgenheaders.h +++ /dev/null @@ -1,84 +0,0 @@ -#ifndef Py_PGENHEADERS_H -#define Py_PGENHEADERS_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Include files and extern declarations used by most of the parser. */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -/* config.h may or may not define DL_IMPORT */ -#ifndef DL_IMPORT /* declarations for DLL import/export */ -#define DL_IMPORT(RTYPE) RTYPE -#endif - -#include <stdio.h> -#include <string.h> - -#ifdef THINK_C -#define label label_ -#undef label -#endif - -#ifdef HAVE_STDLIB_H -#include <stdlib.h> -#endif - -#include "myproto.h" -#include "mymalloc.h" - -#include "pydebug.h" - -#define addarc _Py_addarc -#define addbit _Py_addbit -#define adddfa _Py_adddfa -#define addfirstsets _Py_addfirstsets -#define addlabel _Py_addlabel -#define addstate _Py_addstate -#define delbitset _Py_delbitset -#define dumptree _Py_dumptree -#define findlabel _Py_findlabel -#define mergebitset _Py_mergebitset -#define meta_grammar _Py_meta_grammar -#define newbitset _Py_newbitset -#define newgrammar _Py_newgrammar -#define pgen _Py_pgen -#define printgrammar _Py_printgrammar -#define printnonterminals _Py_printnonterminals -#define printtree _Py_printtree -#define samebitset _Py_samebitset -#define showtree _Py_showtree -#define tok_dump _Py_tok_dump -#define translatelabels _Py_translatelabels - -#ifdef __cplusplus -} -#endif -#endif /* !Py_PGENHEADERS_H */ diff --git a/Include/pydebug.h b/Include/pydebug.h deleted file mode 100644 index ba50c0bc1b..0000000000 --- a/Include/pydebug.h +++ /dev/null @@ -1,40 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#ifndef Py_PYDEBUG_H -#define Py_PYDEBUG_H -#ifdef __cplusplus -extern "C" { -#endif - -extern DL_IMPORT(int) Py_DebugFlag; -extern DL_IMPORT(int) Py_VerboseFlag; -extern DL_IMPORT(int) Py_SuppressPrintingFlag; - -void Py_FatalError Py_PROTO((char *)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_PYDEBUG_H */ diff --git a/Include/pyerrors.h b/Include/pyerrors.h deleted file mode 100644 index 3307b3686c..0000000000 --- a/Include/pyerrors.h +++ /dev/null @@ -1,76 +0,0 @@ -#ifndef Py_ERRORS_H -#define Py_ERRORS_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Error handling definitions */ - -void PyErr_SetNone Py_PROTO((PyObject *)); -void PyErr_SetObject Py_PROTO((PyObject *, PyObject *)); -void PyErr_SetString Py_PROTO((PyObject *, char *)); -PyObject *PyErr_Occurred Py_PROTO((void)); -void PyErr_Clear Py_PROTO((void)); -void PyErr_Fetch Py_PROTO((PyObject **, PyObject **, PyObject **)); -void PyErr_Restore Py_PROTO((PyObject *, PyObject *, PyObject *)); - -/* Predefined exceptions */ - -extern DL_IMPORT(PyObject *) PyExc_AccessError; -extern DL_IMPORT(PyObject *) PyExc_AttributeError; -extern DL_IMPORT(PyObject *) PyExc_ConflictError; -extern DL_IMPORT(PyObject *) PyExc_EOFError; -extern DL_IMPORT(PyObject *) PyExc_IOError; -extern DL_IMPORT(PyObject *) PyExc_ImportError; -extern DL_IMPORT(PyObject *) PyExc_IndexError; -extern DL_IMPORT(PyObject *) PyExc_KeyError; -extern DL_IMPORT(PyObject *) PyExc_KeyboardInterrupt; -extern DL_IMPORT(PyObject *) PyExc_MemoryError; -extern DL_IMPORT(PyObject *) PyExc_NameError; -extern DL_IMPORT(PyObject *) PyExc_OverflowError; -extern DL_IMPORT(PyObject *) PyExc_RuntimeError; -extern DL_IMPORT(PyObject *) PyExc_SyntaxError; -extern DL_IMPORT(PyObject *) PyExc_SystemError; -extern DL_IMPORT(PyObject *) PyExc_SystemExit; -extern DL_IMPORT(PyObject *) PyExc_TypeError; -extern DL_IMPORT(PyObject *) PyExc_ValueError; -extern DL_IMPORT(PyObject *) PyExc_ZeroDivisionError; - -/* Convenience functions */ - -extern int PyErr_BadArgument Py_PROTO((void)); -extern PyObject *PyErr_NoMemory Py_PROTO((void)); -extern PyObject *PyErr_SetFromErrno Py_PROTO((PyObject *)); - -extern void PyErr_BadInternalCall Py_PROTO((void)); - -extern int PyErr_CheckSignals Py_PROTO((void)); /* In sigcheck.c or signalmodule.c */ - -#ifdef __cplusplus -} -#endif -#endif /* !Py_ERRORS_H */ diff --git a/Include/pythonrun.h b/Include/pythonrun.h deleted file mode 100644 index afbb2c7bc2..0000000000 --- a/Include/pythonrun.h +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef Py_PYTHONRUN_H -#define Py_PYTHONRUN_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Interfaces to parse and execute pieces of python code */ - -void Py_Initialize Py_PROTO((void)); - -int PyRun_AnyFile Py_PROTO((FILE *, char *)); - -int PyRun_SimpleString Py_PROTO((char *)); -int PyRun_SimpleFile Py_PROTO((FILE *, char *)); -int PyRun_InteractiveOne Py_PROTO((FILE *, char *)); -int PyRun_InteractiveLoop Py_PROTO((FILE *, char *)); - -struct _node *PyParser_SimpleParseString Py_PROTO((char *, int)); -struct _node *PyParser_SimpleParseFile Py_PROTO((FILE *, char *, int)); - -PyObject *PyRun_String Py_PROTO((char *, int, PyObject *, PyObject *)); -PyObject *PyRun_File Py_PROTO((FILE *, char *, int, PyObject *, PyObject *)); - -PyObject *Py_CompileString Py_PROTO((char *, char *, int)); - -void PyErr_Print Py_PROTO((void)); - -int Py_AtExit Py_PROTO((void (*func) Py_PROTO((void)))); - -void Py_Exit Py_PROTO((int)); - -void Py_Cleanup Py_PROTO((void)); - -void PyImport_Init Py_PROTO((void)); -void PyBuiltin_Init Py_PROTO((void)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_PYTHONRUN_H */ diff --git a/Include/pythread.h b/Include/pythread.h deleted file mode 100644 index 3a04a8ba53..0000000000 --- a/Include/pythread.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef _THREAD_H_included -#define _THREAD_H_included - -#define NO_EXIT_PROG /* don't define exit_prog() */ - /* (the result is no use of signals on SGI) */ - -#ifndef Py_PROTO -#if defined(__STDC__) || defined(__cplusplus) -#define Py_PROTO(args) args -#else -#define Py_PROTO(args) () -#endif -#endif - -typedef void *type_lock; -typedef void *type_sema; - -#ifdef __cplusplus -extern "C" { -#endif - -void init_thread Py_PROTO((void)); -int start_new_thread Py_PROTO((void (*)(void *), void *)); -void exit_thread Py_PROTO((void)); -void _exit_thread Py_PROTO((void)); -long get_thread_ident Py_PROTO((void)); - -type_lock allocate_lock Py_PROTO((void)); -void free_lock Py_PROTO((type_lock)); -int acquire_lock Py_PROTO((type_lock, int)); -#define WAIT_LOCK 1 -#define NOWAIT_LOCK 0 -void release_lock Py_PROTO((type_lock)); - -type_sema allocate_sema Py_PROTO((int)); -void free_sema Py_PROTO((type_sema)); -void down_sema Py_PROTO((type_sema)); -void up_sema Py_PROTO((type_sema)); - -#ifndef NO_EXIT_PROG -void exit_prog Py_PROTO((int)); -void _exit_prog Py_PROTO((int)); -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/Include/rangeobject.h b/Include/rangeobject.h deleted file mode 100644 index 949e7100e3..0000000000 --- a/Include/rangeobject.h +++ /dev/null @@ -1,39 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Range object interface */ - -/* -A range object represents an integer range. This is an immutable object; -a range cannot change its value after creation. - -Range objects behave like the corresponding tuple objects except that -they are represented by a start, stop, and step datamembers. -*/ - -extern DL_IMPORT(PyTypeObject) PyRange_Type; - -#define PyRange_Check(op) ((op)->ob_type == &PyRange_Type) - -extern PyObject *PyRange_New Py_PROTO((long, long, long, int)); diff --git a/Include/rename1.h b/Include/rename1.h deleted file mode 100755 index 90f129f1ab..0000000000 --- a/Include/rename1.h +++ /dev/null @@ -1,360 +0,0 @@ -#ifndef Py_RENAME1_H -#define Py_RENAME1_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* This file contains a bunch of #defines that make it possible to use - "new style" names (e.g. PyObject) with the old style Python source - distribution. */ - -/* Remove some symbols (these conflict with X11 symbols) */ -#undef True -#undef False -#undef None - -typedef ANY *PyUnivPtr; -typedef struct methodlist PyMethodDef; - -#define Py_NO_DEBUG NDEBUG -#define Py_TRACE_REFS TRACE_REFS -#define Py_REF_DEBUG REF_DEBUG -#define Py_HAVE_PROTOTYPES HAVE_PROTOTYPES -#define Py_HAVE_STDLIB HAVE_STDLIB -#define _Py_ZeroStruct FalseObject -#define _Py_NoneStruct NoObject -#define _Py_TrueStruct TrueObject -#define Py_DebugFlag debugging -#define _PyParser_Grammar gram -#define _PySys_ProfileFunc sys_profile -#define _PySys_TraceFunc sys_trace -#define _PyThread_Started threads_started -#define _PyParser_TokenNames tok_name -#define Py_VerboseFlag verbose -#define PyExc_AttributeError AttributeError -#define PyExc_EOFError EOFError -#define PyExc_IOError IOError -#define PyExc_ImportError ImportError -#define PyExc_IndexError IndexError -#define PyExc_KeyError KeyError -#define PyExc_MemoryError MemoryError -#define PyExc_NameError NameError -#define PyExc_OverflowError OverflowError -#define PyExc_RuntimeError RuntimeError -#define PyExc_SyntaxError SyntaxError -#define PyExc_SystemError SystemError -#define PyExc_TypeError TypeError -#define PyExc_ValueError ValueError -#define PyExc_ZeroDivisionError ZeroDivisionError -#define PyExc_KeyboardInterrupt KeyboardInterrupt -#define PyExc_SystemExit SystemExit -#define PyFloat_Type Floattype -#define PyInt_Type Inttype -#define PyLong_Type Longtype -#define PyNothing_Type Notype -#define PyString_Type Stringtype -#define PyType_Type Typetype -#define PyList_Type Listtype -#define PyDict_Type Dicttype -#define PyTuple_Type Tupletype -#define PyFile_Type Filetype -#define PyClass_Type Classtype -#define PyFunction_Type Functype -#define PyMethod_Type Instancemethodtype -#define PyInstance_Type Instancetype -#define PyCFunction_Type Methodtype -#define PyModule_Type Moduletype -#define PyCode_Type Codetype -#define PyFrame_Type Frametype -#define PyFloatObject floatobject -#define PyIntObject intobject -#define PyLongObject longobject -#define PyNothingObject noobject -#define PyObject object -#define PyStringObject stringobject -#define PyTypeObject typeobject -#define PyListObject listobject -#define PyDictObject dictobject -#define PyTupleObject tupleobject -#define PyFileObject fileobject -#define PyClassObject classobject -#define PyCodeObject codeobject -#define PyFrameObject frameobject -#define PyFunctionObject funcobject -#define PyMethodObject instancemethodobject -#define PyInstanceObject instanceobject -#define PyCFunctionObject methodobject -#define PyModuleObject moduleobject -#define PyNumberMethods number_methods -#define PySequenceMethods sequence_methods -#define PyMappingMethods mapping_methods -#define PyObject_HEAD OB_HEAD -#define PyObject_VAR_HEAD OB_VARHEAD -#define PyObject_HEAD_INIT(x) OB_HEAD_INIT(x) -#define PyObject_NEW NEWOBJ -#define PyObject_NEW_VAR NEWVAROBJ -#define Py_PROTO PROTO -#define PyMem_NEW NEW -#define PyMem_RESIZE RESIZE -#define PyMem_DEL DEL -#define PyMem_XDEL XDEL -#define Py_BEGIN_ALLOW_THREADS BGN_SAVE -#define Py_BLOCK_THREADS RET_SAVE -#define Py_UNBLOCK_THREADS RES_SAVE -#define Py_END_ALLOW_THREADS END_SAVE -#define PyFloat_Check is_floatobject -#define PyInt_Check is_intobject -#define PyLong_Check is_longobject -#define PyNothing_Check is_noobject -#define PyString_Check is_stringobject -#define PyType_Check is_typeobject -#define PyList_Check is_listobject -#define PyDict_Check is_dictobject -#define PyTuple_Check is_tupleobject -#define PyFile_Check is_fileobject -#define PyClass_Check is_classobject -#define PyCode_Check is_codeobject -#define PyFrame_Check is_frameobject -#define PyFunction_Check is_funcobject -#define PyMethod_Check is_instancemethodobject -#define PyInstance_Check is_instanceobject -#define PyCFunction_Check is_methodobject -#define PyModule_Check is_moduleobject -#define Py_INCREF INCREF -#define Py_DECREF DECREF -#define Py_XINCREF XINCREF -#define Py_XDECREF XDECREF -#define _Py_NewReference NEWREF -#define _Py_Dealloc DELREF -#define _Py_ForgetReference UNREF -#define Py_None (&_Py_NoneStruct) -#define Py_False ((object *) &_Py_ZeroStruct) -#define Py_True ((object *) &_Py_TrueStruct) -#define PyObject_Compare cmpobject -#define PyObject_GetAttrString getattr -#define PyObject_GetAttr getattro -#define PyObject_Hash hashobject -#define _PyObject_New newobject -#define _PyObject_NewVar newvarobject -#define PyObject_Print printobject -#define PyObject_Repr reprobject -#define PyObject_SetAttrString setattr -#define PyObject_SetAttr setattro -#define PyObject_IsTrue testbool -#define Py_PRINT_RAW PRINT_RAW -#define PyFloat_AsString float_buf_repr -#define PyFloat_AsDouble getfloatvalue -#define PyFloat_AS_DOUBLE GETFLOATVALUE -#define PyFloat_FromDouble newfloatobject -#define PyInt_AsLong getintvalue -#define PyInt_AS_LONG GETINTVALUE -#define PyInt_FromLong newintobject -#define _PyLong_New alloclongobject -#define PyLong_AsDouble dgetlongvalue -#define PyLong_FromDouble dnewlongobject -#define PyLong_AsLong getlongvalue -#define PyLong_FromString long_scan -#define PyLong_FromLong newlongobject -#define PyString_Format formatstring -#define PyString_Size getstringsize -#define PyString_AsString getstringvalue -#define PyString_AS_STRING GETSTRINGVALUE -#define PyString_Concat joinstring -#define PyString_FromStringAndSize newsizedstringobject -#define PyString_FromString newstringobject -#define _PyString_Resize resizestring -#define PyList_Append addlistitem -#define PyList_GetItem getlistitem -#define PyList_GET_ITEM GETLISTITEM -#define PyList_Size getlistsize -#define PyList_GetSlice getlistslice -#define PyList_Insert inslistitem -#define PyList_New newlistobject -#define PyList_SetItem setlistitem -#define PyList_SetSlice setlistslice -#define PyList_Sort sortlist -#define PyDict_SetItemString dictinsert -#define PyDict_GetItemString dictlookup -#define PyDict_DelItemString dictremove -#define PyDict_Items getmappingitems -#define PyDict_Keys getmappingkeys -#define PyDict_Values getmappingvalues -#define PyDict_Clear mappingclear -#define PyDict_Next mappinggetnext -#define PyDict_SetItem mappinginsert -#define PyDict_GetItem mappinglookup -#define PyDict_DelItem mappingremove -#define PyDict_New newmappingobject -#define PyTuple_GetItem gettupleitem -#define PyTuple_GET_ITEM GETTUPLEITEM -#define PyTuple_Size gettuplesize -#define PyTuple_GetSlice gettupleslice -#define PyTuple_New newtupleobject -#define PyTuple_SetItem settupleitem -#define PyFile_GetLine filegetline -#define PyFile_AsFile getfilefile -#define PyFile_FromString newfileobject -#define PyFile_FromFile newopenfileobject -#define PyFile_SoftSpace softspace -#define PyFile_WriteObject writeobject -#define PyFile_WriteString writestring -#define PyMethod_Class instancemethodgetclass -#define PyMethod_Function instancemethodgetfunc -#define PyMethod_Self instancemethodgetself -#define PyClass_IsSubclass issubclass -#define PyClass_New newclassobject -#define PyMethod_New newinstancemethodobject -#define PyInstance_New newinstanceobject -#define PyTryBlock block -#define PyFrame_ExtendStack extend_stack -#define PyFrame_New newframeobject -#define PyFrame_BlockPop pop_block -#define PyFrame_BlockSetup setup_block -#define PyFunction_GetCode getfunccode -#define PyFunction_GetGlobals getfuncglobals -#define PyFunction_New newfuncobject -#define PyCFunction method -#define Py_FindMethod findmethod -#define PyCFunction_GetFunction getmethod -#define PyCFunction_GetSelf getself -#define PyCFunction_IsVarArgs getvarargs -#define PyCFunction_New newmethodobject -#define PyModule_GetDict getmoduledict -#define PyModule_GetName getmodulename -#define PyModule_New newmoduleobject -#define PyGrammar_AddAccelerators addaccelerators -#define PyGrammar_FindDFA finddfa -#define PyGrammar_LabelRepr labelrepr -#define PyNode_ListTree listtree -#define PyNode_AddChild addchild -#define PyNode_Free freetree -#define PyNode_New newtree -#define PyParser_AddToken addtoken -#define PyParser_Delete delparser -#define PyParser_New newparser -#define PyParser_ParseFile parsefile -#define PyParser_ParseString parsestring -#define PyToken_OneChar tok_1char -#define PyToken_TwoChars tok_2char -#define PyTokenizer_Free tok_free -#define PyTokenizer_Get tok_get -#define PyTokenizer_FromFile tok_setupf -#define PyTokenizer_FromString tok_setups -#define PyNode_Compile compile -#define PyCode_New newcodeobject -#define PyEval_CallObject call_object -#define PyEval_EvalCode eval_code -#define Py_FlushLine flushline -#define PyEval_GetBuiltins getbuiltins -#define PyEval_GetGlobals getglobals -#define PyEval_GetLocals getlocals -#define PyEval_InitThreads init_save_thread -#define PyErr_PrintTraceBack printtraceback -#define PyEval_RestoreThread restore_thread -#define PyEval_SaveThread save_thread -#define PyTraceBack_Fetch tb_fetch -#define PyTraceBack_Here tb_here -#define PyTraceBack_Print tb_print -#define PyTraceBack_Store tb_store -#define PyImport_AddModule add_module -#define PyImport_Cleanup doneimport -#define PyImport_GetModuleDict get_modules -#define PyImport_ImportModule import_module -#define PyImport_ImportFrozenModule init_frozen -#define PyImport_Init initimport -#define PyImport_ReloadModule reload_module -#define PyNumber_Coerce coerce -#define PyBuiltin_GetDict getbuiltindict -#define PyBuiltin_Init initbuiltin -#define PyMarshal_Init initmarshal -#define PyMarshal_ReadLongFromFile rd_long -#define PyMarshal_ReadObjectFromFile rd_object -#define PyMarshal_ReadObjectFromString rds_object -#define PyMarshal_WriteLongToFile wr_long -#define PyMarshal_WriteObjectToFile wr_object -#define PySys_Init initsys -#define PySys_SetArgv setpythonargv -#define PySys_SetPath setpythonpath -#define PySys_GetObject sysget -#define PySys_GetFile sysgetfile -#define PySys_SetObject sysset -#define Py_CompileString compile_string -#define Py_FatalError fatal -#define Py_Exit goaway -#define Py_Initialize initall -#define PyErr_Print print_error -#define PyParser_SimpleParseFile parse_file -#define PyParser_SimpleParseString parse_string -#define PyRun_AnyFile run -#define PyRun_SimpleFile run_script -#define PyRun_SimpleString run_command -#define PyRun_File run_file -#define PyRun_String run_string -#define PyRun_InteractiveOne run_tty_1 -#define PyRun_InteractiveLoop run_tty_loop -#define PyMember_Get getmember -#define PyMember_Set setmember -#define Py_InitModule(name, methods) initmodule(name, methods) -#define Py_BuildValue mkvalue -#define Py_VaBuildValue vmkvalue -#define PyArg_Parse getargs -#define PyArg_ParseTuple newgetargs -#define PyArg_NoArgs(v) getargs(v, "") -#define PyArg_GetChar getichararg -#define PyArg_GetDoubleArray getidoublearray -#define PyArg_GetFloat getifloatarg -#define PyArg_GetFloatArray getifloatarray -#define PyArg_GetInt getintarg -#define PyArg_GetLong getilongarg -#define PyArg_GetLongArray getilongarray -#define PyArg_GetLongArraySize getilongarraysize -#define PyArg_GetObject getiobjectarg -#define PyArg_GetShort getishortarg -#define PyArg_GetShortArray getishortarray -#define PyArg_GetShortArraySize getishortarraysize -#define PyArg_GetString getistringarg -#define PyErr_BadArgument err_badarg -#define PyErr_BadInternalCall err_badcall -#define PyErr_Input err_input -#define PyErr_NoMemory err_nomem -#define PyErr_SetFromErrno err_errno -#define PyErr_SetNone err_set -#define PyErr_SetString err_setstr -#define PyErr_SetObject err_setval -#define PyErr_Occurred err_occurred -#define PyErr_Fetch err_fetch -#define PyErr_Restore err_restore -#define PyErr_Clear err_clear -#define PyOS_InterruptableGetString fgets_intr -#define PyOS_InitInterrupts initintr -#define PyOS_InterruptOccurred intrcheck -#define PyOS_GetLastModificationTime getmtime - -#ifdef __cplusplus -} -#endif -#endif /* !Py_RENAME1_H */ diff --git a/Include/rename2.h b/Include/rename2.h deleted file mode 100644 index bcdab397bf..0000000000 --- a/Include/rename2.h +++ /dev/null @@ -1,438 +0,0 @@ -#ifndef Py_OLDNAMES_H -#define Py_OLDNAMES_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* This file contains a bunch of #defines that make it possible to use - "old style" names (e.g. object) with the new style Python source - distribution. */ - -#define True Py_True -#define False Py_False -#define None Py_None - -/* typedef ANY *PyUnivPtr; */ -#define methodlist PyMethodDef -#define methodchain PyMethodChain - -#define Accesstype PyAccess_Type -#define is_accessobject PyAccess_Check -#define newaccessobject PyAccess_FromValue -#define getaccessvalue PyAccess_AsValue -#define setaccessvalue PyAccess_SetValue -#define setaccessowner PyAccess_SetOwner -#define cloneaccessobject PyAccess_Clone -#define hasaccessvalue PyAccess_HasValue -#define Anynumbertype PyAnyNumber_Type -#define Anysequencetype PyAnySequence_Type -#define Anymappingtype PyAnyMapping_Type - -#define FalseObject _Py_ZeroStruct -#define NoObject _Py_NoneStruct -#define TrueObject _Py_TrueStruct -#define debugging Py_DebugFlag -#define gram _PyParser_Grammar -#define sys_profile _PySys_ProfileFunc -#define sys_trace _PySys_TraceFunc -#define sys_checkinterval _PySys_CheckInterval -#define threads_started _PyThread_Started -#define tok_name _PyParser_TokenNames -#define verbose Py_VerboseFlag -#define suppress_print Py_SuppressPrintingFlag -#define AccessError PyExc_AccessError -#define AttributeError PyExc_AttributeError -#define ConflictError PyExc_ConflictError -#define EOFError PyExc_EOFError -#define IOError PyExc_IOError -#define ImportError PyExc_ImportError -#define IndexError PyExc_IndexError -#define KeyError PyExc_KeyError -#define MemoryError PyExc_MemoryError -#define NameError PyExc_NameError -#define OverflowError PyExc_OverflowError -#define RuntimeError PyExc_RuntimeError -#define SyntaxError PyExc_SyntaxError -#define SystemError PyExc_SystemError -#define TypeError PyExc_TypeError -#define ValueError PyExc_ValueError -#define ZeroDivisionError PyExc_ZeroDivisionError -#define KeyboardInterrupt PyExc_KeyboardInterrupt -#define SystemExit PyExc_SystemExit -#define Floattype PyFloat_Type -#define Complextype PyComplex_Type -#define Inttype PyInt_Type -#define Longtype PyLong_Type -#define Notype PyNothing_Type -#define Stringtype PyString_Type -#define Typetype PyType_Type -#define Listtype PyList_Type -#define Dicttype PyDict_Type -#define Mappingtype PyDict_Type -#define Tupletype PyTuple_Type -#define Filetype PyFile_Type -#define Classtype PyClass_Type -#define Functype PyFunction_Type -#define Instancemethodtype PyMethod_Type -#define Instancetype PyInstance_Type -#define Methodtype PyCFunction_Type -#define Moduletype PyModule_Type -#define Codetype PyCode_Type -#define Frametype PyFrame_Type -#define Rangetype PyRange_Type -#define floatobject PyFloatObject -#define complexobject PyComplexObject -#define intobject PyIntObject -#define longobject PyLongObject -#define noobject PyNothingObject -#define object PyObject -#define stringobject PyStringObject -#define typeobject PyTypeObject -#define listobject PyListObject -#define dictobject PyDictObject -#define tupleobject PyTupleObject -#define fileobject PyFileObject -#define classobject PyClassObject -#define codeobject PyCodeObject -#define frameobject PyFrameObject -#define funcobject PyFunctionObject -#define instancemethodobject PyMethodObject -#define instanceobject PyInstanceObject -#define methodobject PyCFunctionObject -#define moduleobject PyModuleObject -#define number_methods PyNumberMethods -#define sequence_methods PySequenceMethods -#define mapping_methods PyMappingMethods -#define OB_HEAD PyObject_HEAD -#define OB_VARHEAD PyObject_VAR_HEAD -#define OB_HEAD_INIT PyObject_HEAD_INIT -#define NEWOBJ PyObject_NEW -#define NEWVAROBJ PyObject_NEW_VAR -#define PROTO Py_PROTO -#define FPROTO Py_FPROTO -#define NEW PyMem_NEW -#define RESIZE PyMem_RESIZE -#define DEL PyMem_DEL -#define XDEL PyMem_XDEL -#define BGN_SAVE Py_BEGIN_ALLOW_THREADS -#define RET_SAVE Py_BLOCK_THREADS -#define RES_SAVE Py_UNBLOCK_THREADS -#define END_SAVE Py_END_ALLOW_THREADS -#define callable PyCallable_Check -#define is_floatobject PyFloat_Check -#define is_complexobject PyComplex_Check -#define is_intobject PyInt_Check -#define is_longobject PyLong_Check -#define is_stringobject PyString_Check -#define is_typeobject PyType_Check -#define is_listobject PyList_Check -#define is_dictobject PyDict_Check -#define is_mappingobject PyDict_Check -#define is_tupleobject PyTuple_Check -#define is_fileobject PyFile_Check -#define is_classobject PyClass_Check -#define is_codeobject PyCode_Check -#define is_frameobject PyFrame_Check -#define is_funcobject PyFunction_Check -#define is_instancemethodobject PyMethod_Check -#define is_instanceobject PyInstance_Check -#define is_methodobject PyCFunction_Check -#define is_moduleobject PyModule_Check -#define INCREF Py_INCREF -#define DECREF Py_DECREF -#define XINCREF Py_XINCREF -#define XDECREF Py_XDECREF -#define NEWREF _Py_NewReference -#define DELREF _Py_Dealloc -#define UNREF _Py_ForgetReference -#define cmpobject PyObject_Compare -#define getattr PyObject_GetAttrString -#define getattro PyObject_GetAttr -#define hasattr PyObject_HasAttrString -#define hasattro PyObject_HasAttr -#define hashobject PyObject_Hash -#define newobject _PyObject_New -#define newvarobject _PyObject_NewVar -#define printobject PyObject_Print -#define reprobject PyObject_Repr -#define strobject PyObject_Str -#define setattr PyObject_SetAttrString -#define setattro PyObject_SetAttr -#define testbool PyObject_IsTrue -#define PRINT_RAW Py_PRINT_RAW -#define float_buf_repr PyFloat_AsString -#define getfloatvalue PyFloat_AsDouble -#define GETFLOATVALUE PyFloat_AS_DOUBLE -#define newfloatobject PyFloat_FromDouble -#define newcomplexobject PyComplex_FromCComplex -#define getintvalue PyInt_AsLong -#define GETINTVALUE PyInt_AS_LONG -#define getmaxint PyInt_GetMax -#define newintobject PyInt_FromLong -#define alloclongobject _PyLong_New -#define dgetlongvalue PyLong_AsDouble -#define dnewlongobject PyLong_FromDouble -#define getlongvalue PyLong_AsLong -#define long_escan PyLong_FromString -#define long_scan(a, b) PyLong_FromString((a), (char **)0, (b)) -#define newlongobject PyLong_FromLong -#define formatstring PyString_Format -#define getstringsize PyString_Size -#define getstringvalue PyString_AsString -#define GETSTRINGVALUE PyString_AS_STRING -#define joinstring PyString_Concat -#define joinstring_decref PyString_ConcatAndDel -#define newsizedstringobject PyString_FromStringAndSize -#define newstringobject PyString_FromString -#define resizestring _PyString_Resize -#define addlistitem PyList_Append -#define getlistitem PyList_GetItem -#define GETLISTITEM PyList_GET_ITEM -#define getlistsize PyList_Size -#define getlistslice PyList_GetSlice -#define inslistitem PyList_Insert -#define newlistobject PyList_New -#define setlistitem PyList_SetItem -#define setlistslice PyList_SetSlice -#define sortlist PyList_Sort -#define reverselist PyList_Reverse -#define listtuple PyList_AsTuple -#define dictinsert PyDict_SetItemString -#define dictlookup PyDict_GetItemString -#define dictremove PyDict_DelItemString -#define getmappingitems PyDict_Items -#define getdictitems PyDict_Items -#define getmappingkeys PyDict_Keys -#define getdictkeys PyDict_Keys -#define getmappingvalues PyDict_Values -#define getdictvalues PyDict_Values -#define getmappingsize PyDict_Size -#define getdictsize PyDict_Size -#define mappingclear PyDict_Clear -#define mappinggetnext PyDict_Next -#define mappinginsert PyDict_SetItem -#define dict2insert PyDict_SetItem -#define mappinglookup PyDict_GetItem -#define dict2lookup PyDict_GetItem -#define mappingremove PyDict_DelItem -#define dict2remove PyDict_DelItem -#define newmappingobject PyDict_New -#define newdictobject PyDict_New -#define gettupleitem PyTuple_GetItem -#define GETTUPLEITEM PyTuple_GET_ITEM -#define SETTUPLEITEM PyTuple_SET_ITEM -#define gettuplesize PyTuple_Size -#define gettupleslice PyTuple_GetSlice -#define newtupleobject PyTuple_New -#define settupleitem PyTuple_SetItem -#define resizetuple _PyTuple_Resize -#define filegetline PyFile_GetLine -#define getfilefile PyFile_AsFile -#define getfilename PyFile_Name -#define setfilebufsize PyFile_SetBufSize -#define newfileobject PyFile_FromString -#define newopenfileobject PyFile_FromFile -#define softspace PyFile_SoftSpace -#define writeobject PyFile_WriteObject -#define writestring PyFile_WriteString -#define instancemethodgetclass PyMethod_Class -#define instancemethodgetfunc PyMethod_Function -#define instancemethodgetself PyMethod_Self -#define issubclass PyClass_IsSubclass -#define newclassobject PyClass_New -#define newinstancemethodobject PyMethod_New -#define newinstanceobject PyInstance_New -#define instancebinop PyInstance_DoBinOp -#define block PyTryBlock -#define extend_stack PyFrame_ExtendStack -#define newframeobject PyFrame_New -#define pop_block PyFrame_BlockPop -#define setup_block PyFrame_BlockSetup -#define fast_2_locals PyFrame_FastToLocals -#define locals_2_fast PyFrame_LocalsToFast -#define getfunccode PyFunction_GetCode -#define getfuncglobals PyFunction_GetGlobals -#define getfuncargstuff PyFunction_GetArgStuff -#define setfuncargstuff PyFunction_SetArgStuff -#define mystrtol PyOS_strtol -#define mystrtoul PyOS_strtoul -#define newfuncobject PyFunction_New -#define newrangeobject PyRange_New -#define method PyCFunction -#define findmethod Py_FindMethod -#define findmethodinchain Py_FindMethodInChain -#define getmethod PyCFunction_GetFunction -#define getself PyCFunction_GetSelf -#define getflags PyCFunction_GetFlags -#define newmethodobject PyCFunction_New -#define getmoduledict PyModule_GetDict -#define getmodulename PyModule_GetName -#define newmoduleobject PyModule_New -#define addaccelerators PyGrammar_AddAccelerators -#define finddfa PyGrammar_FindDFA -#define labelrepr PyGrammar_LabelRepr -#define listtree PyNode_ListTree -#define addchild PyNode_AddChild -#define freetree PyNode_Free -#define newtree PyNode_New -#define addtoken PyParser_AddToken -#define delparser PyParser_Delete -#define newparser PyParser_New -#define parsefile PyParser_ParseFile -#define parsestring PyParser_ParseString -#define tok_1char PyToken_OneChar -#define tok_2char PyToken_TwoChars -#define tok_free PyTokenizer_Free -#define tok_get PyTokenizer_Get -#define tok_setupf PyTokenizer_FromFile -#define tok_setups PyTokenizer_FromString -#define compile PyNode_Compile -#define newcodeobject PyCode_New -#define call_object PyEval_CallObject -#define eval_code PyEval_EvalCode -#define flushline Py_FlushLine -#define getbuiltins PyEval_GetBuiltins -#define getglobals PyEval_GetGlobals -#define getlocals PyEval_GetLocals -#define getowner PyEval_GetOwner -#define getframe PyEval_GetFrame -#define getrestricted PyEval_GetRestricted -#define init_save_thread PyEval_InitThreads -#define printtraceback PyErr_PrintTraceBack -#define restore_thread PyEval_RestoreThread -#define save_thread PyEval_SaveThread -#define tb_fetch PyTraceBack_Fetch -#define tb_here PyTraceBack_Here -#define tb_print PyTraceBack_Print -#define tb_store PyTraceBack_Store -#define add_module PyImport_AddModule -#define doneimport PyImport_Cleanup -#define get_modules PyImport_GetModuleDict -#define get_pyc_magic PyImport_GetMagicNumber -#define exec_code_module PyImport_ExecCodeModule -#define import_module PyImport_ImportModule -#define init_frozen PyImport_ImportFrozenModule -#define initimport PyImport_Init -#define reload_module PyImport_ReloadModule -#define coerce PyNumber_Coerce -#define getbuiltin PyBuiltin_GetObject -#define initbuiltin PyBuiltin_Init -#define getbuiltindict PyBuiltin_GetDict -#define getbuiltinmod PyBuiltin_GetModule -#define initmarshal PyMarshal_Init -#define initmodule Py_InitModule -#define initmodule4 Py_InitModule4 -#define rd_long PyMarshal_ReadLongFromFile -#define rd_short PyMarshal_ReadShortFromFile -#define rd_object PyMarshal_ReadObjectFromFile -#define rds_object PyMarshal_ReadObjectFromString -#define wr_long PyMarshal_WriteLongToFile -#define wr_short PyMarshal_WriteShortToFile -#define wr_object PyMarshal_WriteObjectToFile -#define initsys PySys_Init -#define setpythonargv PySys_SetArgv -#define setpythonpath PySys_SetPath -#define sysget PySys_GetObject -#define sysgetfile PySys_GetFile -#define sysset PySys_SetObject -#define compile_string Py_CompileString -#define fatal Py_FatalError -#define goaway Py_Exit -#define cleanup Py_Cleanup -#define initall Py_Initialize -#define print_error PyErr_Print -#define parse_file PyParser_SimpleParseFile -#define parse_string PyParser_SimpleParseString -#define run PyRun_AnyFile -#define run_script PyRun_SimpleFile -#define run_command PyRun_SimpleString -#define run_file PyRun_File -#define run_string PyRun_String -#define run_tty_1 PyRun_InteractiveOne -#define run_tty_loop PyRun_InteractiveLoop -#define getmember PyMember_Get -#define setmember PyMember_Set -#define mkvalue Py_BuildValue -#define vmkvalue Py_VaBuildValue -#define getargs PyArg_Parse -#define vgetargs PyArgs_VaParse -#define newgetargs PyArg_ParseTuple -#define getichararg PyArg_GetChar -#define getidoublearray PyArg_GetDoubleArray -#define getifloatarg PyArg_GetFloat -#define getifloatarray PyArg_GetFloatArray -#define getnoarg(v) PyArg_NoArgs(v) -#define getintarg(v,a) getargs((v),"i",(a)) -#define getlongarg(v,a) getargs((v),"l",(a)) -#define getstrarg(v,a) getargs((v),"s",(a)) -#define getilongarg PyArg_GetLong -#define getilongarray PyArg_GetLongArray -#define getilongarraysize PyArg_GetLongArraySize -#define getiobjectarg PyArg_GetObject -#define getishortarg PyArg_GetShort -#define getishortarray PyArg_GetShortArray -#define getishortarraysize PyArg_GetShortArraySize -#define getistringarg PyArg_GetString -#define err_badarg PyErr_BadArgument -#define err_badcall PyErr_BadInternalCall -#define err_input PyErr_Input -#define err_nomem PyErr_NoMemory -#define err_errno PyErr_SetFromErrno -#define err_set PyErr_SetNone -#define err_setstr PyErr_SetString -#define err_setval PyErr_SetObject -#define err_occurred PyErr_Occurred -#define err_fetch PyErr_Fetch -#define err_restore PyErr_Restore -#define err_clear PyErr_Clear -#define fgets_intr PyOS_InterruptableGetString -#define initintr PyOS_InitInterrupts -#define intrcheck PyOS_InterruptOccurred -#define getmtime PyOS_GetLastModificationTime -#define my_readline PyOS_Readline -#define realmain Py_Main -#define ref_total _Py_RefTotal -#define sigcheck PyErr_CheckSignals - -/* Misc. stuff */ -#define getcompiler Py_GetCompiler -#define getcopyright Py_GetCopyright -#define getplatform Py_GetPlatform -#define getversion Py_GetVersion -#define getpythonpath Py_GetPath - -/* Misc. Internals */ -#define askyesno _Py_AskYesNo -#define frozen_modules _PyImport_FrozenModules -#define import_filetab _PyImport_Filetab -#define import_maxsuffixsize _PyImport_MaxSuffixSize -#define load_dynamic_module _PyImport_LoadDynamicModule - -#ifdef __cplusplus -} -#endif -#endif /* !Py_OLDNAMES_H */ diff --git a/Include/stringobject.h b/Include/stringobject.h deleted file mode 100644 index f5ebe78ee7..0000000000 --- a/Include/stringobject.h +++ /dev/null @@ -1,77 +0,0 @@ -#ifndef Py_STRINGOBJECT_H -#define Py_STRINGOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* String object interface */ - -/* -Type PyStringObject represents a character string. An extra zero byte is -reserved at the end to ensure it is zero-terminated, but a size is -present so strings with null bytes in them can be represented. This -is an immutable object type. - -There are functions to create new string objects, to test -an object for string-ness, and to get the -string value. The latter function returns a null pointer -if the object is not of the proper type. -There is a variant that takes an explicit size as well as a -variant that assumes a zero-terminated string. Note that none of the -functions should be applied to nil objects. -*/ - -/* NB The type is revealed here only because it is used in dictobject.c */ - -typedef struct { - PyObject_VAR_HEAD -#ifdef CACHE_HASH - long ob_shash; -#endif - char ob_sval[1]; -} PyStringObject; - -extern DL_IMPORT(PyTypeObject) PyString_Type; - -#define PyString_Check(op) ((op)->ob_type == &PyString_Type) - -extern PyObject *PyString_FromStringAndSize Py_PROTO((char *, int)); -extern PyObject *PyString_FromString Py_PROTO((char *)); -extern int PyString_Size Py_PROTO((PyObject *)); -extern char *PyString_AsString Py_PROTO((PyObject *)); -extern void PyString_Concat Py_PROTO((PyObject **, PyObject *)); -extern void PyString_ConcatAndDel Py_PROTO((PyObject **, PyObject *)); -extern int _PyString_Resize Py_PROTO((PyObject **, int)); -extern PyObject *PyString_Format Py_PROTO((PyObject *, PyObject *)); - -/* Macro, trading safety for speed */ -#define PyString_AS_STRING(op) ((op)->ob_sval) - -#ifdef __cplusplus -} -#endif -#endif /* !Py_STRINGOBJECT_H */ diff --git a/Include/structmember.h b/Include/structmember.h deleted file mode 100644 index 0c008561a8..0000000000 --- a/Include/structmember.h +++ /dev/null @@ -1,94 +0,0 @@ -#ifndef Py_STRUCTMEMBER_H -#define Py_STRUCTMEMBER_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Interface to map C struct members to Python object attributes */ - -#ifdef HAVE_STDDEF_H -#include <stddef.h> /* For offsetof */ -#endif - -/* The offsetof() macro calculates the offset of a structure member - in its structure. Unfortunately this cannot be written down - portably, hence it is provided by a Standard C header file. - For pre-Standard C compilers, here is a version that usually works - (but watch out!): */ - -#ifndef offsetof -#define offsetof(type, member) ( (int) & ((type*)0) -> member ) -#endif - -/* An array of memberlist structures defines the name, type and offset - of selected members of a C structure. These can be read by - PyMember_Get() and set by PyMember_Set() (except if their READONLY flag - is set). The array must be terminated with an entry whose name - pointer is NULL. */ - -struct memberlist { - char *name; - int type; - int offset; - int readonly; -}; - -/* Types */ -#define T_SHORT 0 -#define T_INT 1 -#define T_LONG 2 -#define T_FLOAT 3 -#define T_DOUBLE 4 -#define T_STRING 5 -#define T_OBJECT 6 -/* XXX the ordering here is weird for binary compatibility */ -#define T_CHAR 7 /* 1-character string */ -#define T_BYTE 8 /* 8-bit signed int */ -/* unsigned variants: */ -#define T_UBYTE 9 -#define T_USHORT 10 -#define T_UINT 11 -#define T_ULONG 12 - -/* Added by Jack: strings contained in the structure */ -#define T_STRING_INPLACE 13 -#ifdef macintosh -#define T_PSTRING 14 /* macintosh pascal-style counted string */ -#define T_PSTRING_INPLACE 15 -#endif /* macintosh */ - -/* Readonly flag */ -#define READONLY 1 -#define RO READONLY /* Shorthand */ - -PyObject *PyMember_Get Py_PROTO((char *, struct memberlist *, char *)); -int PyMember_Set Py_PROTO((char *, struct memberlist *, char *, PyObject *)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_STRUCTMEMBER_H */ diff --git a/Include/sysmodule.h b/Include/sysmodule.h deleted file mode 100644 index 3680d1bc7d..0000000000 --- a/Include/sysmodule.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef Py_SYSMODULE_H -#define Py_SYSMODULE_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* System module interface */ - -PyObject *PySys_GetObject Py_PROTO((char *)); -int PySys_SetObject Py_PROTO((char *, PyObject *)); -FILE *PySys_GetFile Py_PROTO((char *, FILE *)); -void PySys_Init Py_PROTO((void)); -void PySys_SetArgv Py_PROTO((int, char **)); -void PySys_SetPath Py_PROTO((char *)); - -extern DL_IMPORT(PyObject *) _PySys_TraceFunc, *_PySys_ProfileFunc; -extern DL_IMPORT(int) _PySys_CheckInterval; - -#ifdef __cplusplus -} -#endif -#endif /* !Py_SYSMODULE_H */ diff --git a/Include/thread.h b/Include/thread.h deleted file mode 100644 index 3a04a8ba53..0000000000 --- a/Include/thread.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef _THREAD_H_included -#define _THREAD_H_included - -#define NO_EXIT_PROG /* don't define exit_prog() */ - /* (the result is no use of signals on SGI) */ - -#ifndef Py_PROTO -#if defined(__STDC__) || defined(__cplusplus) -#define Py_PROTO(args) args -#else -#define Py_PROTO(args) () -#endif -#endif - -typedef void *type_lock; -typedef void *type_sema; - -#ifdef __cplusplus -extern "C" { -#endif - -void init_thread Py_PROTO((void)); -int start_new_thread Py_PROTO((void (*)(void *), void *)); -void exit_thread Py_PROTO((void)); -void _exit_thread Py_PROTO((void)); -long get_thread_ident Py_PROTO((void)); - -type_lock allocate_lock Py_PROTO((void)); -void free_lock Py_PROTO((type_lock)); -int acquire_lock Py_PROTO((type_lock, int)); -#define WAIT_LOCK 1 -#define NOWAIT_LOCK 0 -void release_lock Py_PROTO((type_lock)); - -type_sema allocate_sema Py_PROTO((int)); -void free_sema Py_PROTO((type_sema)); -void down_sema Py_PROTO((type_sema)); -void up_sema Py_PROTO((type_sema)); - -#ifndef NO_EXIT_PROG -void exit_prog Py_PROTO((int)); -void _exit_prog Py_PROTO((int)); -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/Include/token.h b/Include/token.h deleted file mode 100644 index 4558525fe1..0000000000 --- a/Include/token.h +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef Py_TOKEN_H -#define Py_TOKEN_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Token types */ - -#define ENDMARKER 0 -#define NAME 1 -#define NUMBER 2 -#define STRING 3 -#define NEWLINE 4 -#define INDENT 5 -#define DEDENT 6 -#define LPAR 7 -#define RPAR 8 -#define LSQB 9 -#define RSQB 10 -#define COLON 11 -#define COMMA 12 -#define SEMI 13 -#define PLUS 14 -#define MINUS 15 -#define STAR 16 -#define SLASH 17 -#define VBAR 18 -#define AMPER 19 -#define LESS 20 -#define GREATER 21 -#define EQUAL 22 -#define DOT 23 -#define PERCENT 24 -#define BACKQUOTE 25 -#define LBRACE 26 -#define RBRACE 27 -#define EQEQUAL 28 -#define NOTEQUAL 29 -#define LESSEQUAL 30 -#define GREATEREQUAL 31 -#define TILDE 32 -#define CIRCUMFLEX 33 -#define LEFTSHIFT 34 -#define RIGHTSHIFT 35 -#define DOUBLESTAR 36 -/* Don't forget to update the table _PyParser_TokenNames in tokenizer.c! */ -#define OP 37 -#define ERRORTOKEN 38 -#define N_TOKENS 39 - -/* Special definitions for cooperation with parser */ - -#define NT_OFFSET 256 - -#define ISTERMINAL(x) ((x) < NT_OFFSET) -#define ISNONTERMINAL(x) ((x) >= NT_OFFSET) -#define ISEOF(x) ((x) == ENDMARKER) - - -extern char *_PyParser_TokenNames[]; /* Token names */ -extern int PyToken_OneChar Py_PROTO((int)); -extern int PyToken_TwoChars Py_PROTO((int, int)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_TOKEN_H */ diff --git a/Include/traceback.h b/Include/traceback.h deleted file mode 100644 index 20a556b7dc..0000000000 --- a/Include/traceback.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef Py_TRACEBACK_H -#define Py_TRACEBACK_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Traceback interface */ - -struct _frame; - -int PyTraceBack_Here Py_PROTO((struct _frame *)); -PyObject *PyTraceBack_Fetch Py_PROTO((void)); -int PyTraceBack_Store Py_PROTO((PyObject *)); -int PyTraceBack_Print Py_PROTO((PyObject *, PyObject *)); - -/* Reveale traceback type so we can typecheck traceback objects */ -extern PyTypeObject PyTraceBack_Type; -#define PyTraceBack_Check(v) ((v)->ob_type == &PyTraceBack_Type) - -#ifdef __cplusplus -} -#endif -#endif /* !Py_TRACEBACK_H */ diff --git a/Include/tupleobject.h b/Include/tupleobject.h deleted file mode 100644 index 992c77085b..0000000000 --- a/Include/tupleobject.h +++ /dev/null @@ -1,72 +0,0 @@ -#ifndef Py_TUPLEOBJECT_H -#define Py_TUPLEOBJECT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Tuple object interface */ - -/* -123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 - -Another generally useful object type is an tuple of object pointers. -This is a mutable type: the tuple items can be changed (but not their -number). Out-of-range indices or non-tuple objects are ignored. - -*** WARNING *** PyTuple_SetItem does not increment the new item's reference -count, but does decrement the reference count of the item it replaces, -if not nil. It does *decrement* the reference count if it is *not* -inserted in the tuple. Similarly, PyTuple_GetItem does not increment the -returned item's reference count. -*/ - -typedef struct { - PyObject_VAR_HEAD - PyObject *ob_item[1]; -} PyTupleObject; - -extern DL_IMPORT(PyTypeObject) PyTuple_Type; - -#define PyTuple_Check(op) ((op)->ob_type == &PyTuple_Type) - -extern PyObject *PyTuple_New Py_PROTO((int size)); -extern int PyTuple_Size Py_PROTO((PyObject *)); -extern PyObject *PyTuple_GetItem Py_PROTO((PyObject *, int)); -extern int PyTuple_SetItem Py_PROTO((PyObject *, int, PyObject *)); -extern PyObject *PyTuple_GetSlice Py_PROTO((PyObject *, int, int)); -extern int _PyTuple_Resize Py_PROTO((PyObject **, int, int)); - -/* Macro, trading safety for speed */ -#define PyTuple_GET_ITEM(op, i) (((PyTupleObject *)(op))->ob_item[i]) - -/* Macro, *only* to be used to fill in brand new tuples */ -#define PyTuple_SET_ITEM(op, i, v) (((PyTupleObject *)(op))->ob_item[i] = v) - -#ifdef __cplusplus -} -#endif -#endif /* !Py_TUPLEOBJECT_H */ diff --git a/Lib/ArrayIO.py b/Lib/ArrayIO.py deleted file mode 100755 index 5b06f922d4..0000000000 --- a/Lib/ArrayIO.py +++ /dev/null @@ -1,142 +0,0 @@ -"""File-like objects that read/write an array buffer. - -This implements (nearly) all stdio methods. - -f = ArrayIO() # ready for writing -f = ArrayIO(buf) # ready for reading -f.close() # explicitly release resources held -flag = f.isatty() # always false -pos = f.tell() # get current position -f.seek(pos) # set current position -f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF -buf = f.read() # read until EOF -buf = f.read(n) # read up to n bytes -buf = f.readline() # read until end of line ('\n') or EOF -list = f.readlines()# list of f.readline() results until EOF -f.write(buf) # write at current position -f.writelines(list) # for line in list: f.write(line) -f.getvalue() # return whole file's contents as a string - -Notes: -- This is very similar to StringIO. StringIO is faster for reading, - but ArrayIO is faster for writing. -- ArrayIO uses an array object internally, but all its interfaces - accept and return strings. -- Using a real file is often faster (but less convenient). -- fileno() is left unimplemented so that code which uses it triggers - an exception early. -- Seeking far beyond EOF and then writing will insert real null - bytes that occupy space in the buffer. -- There's a simple test set (see end of this file). -""" - -import string -from array import array - -class ArrayIO: - def __init__(self, buf = ''): - self.buf = array('c', buf) - self.pos = 0 - self.closed = 0 - self.softspace = 0 - def close(self): - if not self.closed: - self.closed = 1 - del self.buf, self.pos - def isatty(self): - return 0 - def seek(self, pos, mode = 0): - if mode == 1: - pos = pos + self.pos - elif mode == 2: - pos = pos + len(self.buf) - self.pos = max(0, pos) - def tell(self): - return self.pos - def read(self, n = -1): - if n < 0: - newpos = len(self.buf) - else: - newpos = min(self.pos+n, len(self.buf)) - r = self.buf[self.pos:newpos].tostring() - self.pos = newpos - return r - def readline(self): - i = string.find(self.buf[self.pos:].tostring(), '\n') - if i < 0: - newpos = len(self.buf) - else: - newpos = self.pos+i+1 - r = self.buf[self.pos:newpos].tostring() - self.pos = newpos - return r - def readlines(self): - lines = string.splitfields(self.read(), '\n') - if not lines: - return lines - for i in range(len(lines)-1): - lines[i] = lines[i] + '\n' - if not lines[-1]: - del lines[-1] - return lines - def write(self, s): - if not s: return - a = array('c', s) - n = self.pos - len(self.buf) - if n > 0: - self.buf[len(self.buf):] = array('c', '\0')*n - newpos = self.pos + len(a) - self.buf[self.pos:newpos] = a - self.pos = newpos - def writelines(self, list): - self.write(string.joinfields(list, '')) - def flush(self): - pass - def getvalue(self): - return self.buf.tostring() - - -# A little test suite - -def test(): - import sys - if sys.argv[1:]: - file = sys.argv[1] - else: - file = '/etc/passwd' - lines = open(file, 'r').readlines() - text = open(file, 'r').read() - f = ArrayIO() - for line in lines[:-2]: - f.write(line) - f.writelines(lines[-2:]) - if f.getvalue() != text: - raise RuntimeError, 'write failed' - length = f.tell() - print 'File length =', length - f.seek(len(lines[0])) - f.write(lines[1]) - f.seek(0) - print 'First line =', `f.readline()` - here = f.tell() - line = f.readline() - print 'Second line =', `line` - f.seek(-len(line), 1) - line2 = f.read(len(line)) - if line != line2: - raise RuntimeError, 'bad result after seek back' - f.seek(len(line2), 1) - list = f.readlines() - line = list[-1] - f.seek(f.tell() - len(line)) - line2 = f.read() - if line != line2: - raise RuntimeError, 'bad result after seek back from EOF' - print 'Read', len(list), 'more lines' - print 'File length =', f.tell() - if f.tell() != length: - raise RuntimeError, 'bad length' - f.close() - -if __name__ == '__main__': - test() diff --git a/Lib/BaseHTTPServer.py b/Lib/BaseHTTPServer.py deleted file mode 100644 index 281ddf6049..0000000000 --- a/Lib/BaseHTTPServer.py +++ /dev/null @@ -1,482 +0,0 @@ -"""HTTP server base class. - -Note: the class in this module doesn't implement any HTTP request; see -SimpleHTTPServer for simple implementations of GET, HEAD and POST -(including CGI scripts). - -Contents: - -- BaseHTTPRequestHandler: HTTP request handler base class -- test: test function - -XXX To do: - -- send server version -- log requests even later (to capture byte count) -- log user-agent header and other interesting goodies -- send error log to separate file -- are request names really case sensitive? - -""" - - -# See also: -# -# HTTP Working Group T. Berners-Lee -# INTERNET-DRAFT R. T. Fielding -# <draft-ietf-http-v10-spec-00.txt> H. Frystyk Nielsen -# Expires September 8, 1995 March 8, 1995 -# -# URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt - - -# Log files -# --------- -# -# Here's a quote from the NCSA httpd docs about log file format. -# -# | The logfile format is as follows. Each line consists of: -# | -# | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb -# | -# | host: Either the DNS name or the IP number of the remote client -# | rfc931: Any information returned by identd for this person, -# | - otherwise. -# | authuser: If user sent a userid for authentication, the user name, -# | - otherwise. -# | DD: Day -# | Mon: Month (calendar name) -# | YYYY: Year -# | hh: hour (24-hour format, the machine's timezone) -# | mm: minutes -# | ss: seconds -# | request: The first line of the HTTP request as sent by the client. -# | ddd: the status code returned by the server, - if not available. -# | bbbb: the total number of bytes sent, -# | *not including the HTTP/1.0 header*, - if not available -# | -# | You can determine the name of the file accessed through request. -# -# (Actually, the latter is only true if you know the server configuration -# at the time the request was made!) - - -__version__ = "0.2" - - -import sys -import time -import socket # For gethostbyaddr() -import string -import rfc822 -import mimetools -import SocketServer - -# Default error message -DEFAULT_ERROR_MESSAGE = """\ -<head> -<title>Error response</title> -</head> -<body> -<h1>Error response</h1> -<p>Error code %(code)d. -<p>Message: %(message)s. -<p>Error code explanation: %(code)s = %(explain)s. -</body> -""" - - -class HTTPServer(SocketServer.TCPServer): - - def server_bind(self): - """Override server_bind to store the server name.""" - SocketServer.TCPServer.server_bind(self) - host, port = self.socket.getsockname() - if not host or host == '0.0.0.0': - host = socket.gethostname() - hostname, hostnames, hostaddrs = socket.gethostbyaddr(host) - if '.' not in hostname: - for host in hostnames: - if '.' in host: - hostname = host - break - self.server_name = hostname - self.server_port = port - - -class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): - - """HTTP request handler base class. - - The following explanation of HTTP serves to guide you through the - code as well as to expose any misunderstandings I may have about - HTTP (so you don't need to read the code to figure out I'm wrong - :-). - - HTTP (HyperText Transfer Protocol) is an extensible protocol on - top of a reliable stream transport (e.g. TCP/IP). The protocol - recognizes three parts to a request: - - 1. One line identifying the request type and path - 2. An optional set of RFC-822-style headers - 3. An optional data part - - The headers and data are separated by a blank line. - - The first line of the request has the form - - <command> <path> <version> - - where <command> is a (case-sensitive) keyword such as GET or POST, - <path> is a string containing path information for the request, - and <version> should be the string "HTTP/1.0". <path> is encoded - using the URL encoding scheme (using %xx to signify the ASCII - character with hex code xx). - - The protocol is vague about whether lines are separated by LF - characters or by CRLF pairs -- for compatibility with the widest - range of clients, both should be accepted. Similarly, whitespace - in the request line should be treated sensibly (allowing multiple - spaces between components and allowing trailing whitespace). - - Similarly, for output, lines ought to be separated by CRLF pairs - but most clients grok LF characters just fine. - - If the first line of the request has the form - - <command> <path> - - (i.e. <version> is left out) then this is assumed to be an HTTP - 0.9 request; this form has no optional headers and data part and - the reply consists of just the data. - - The reply form of the HTTP 1.0 protocol again has three parts: - - 1. One line giving the response code - 2. An optional set of RFC-822-style headers - 3. The data - - Again, the headers and data are separated by a blank line. - - The response code line has the form - - <version> <responsecode> <responsestring> - - where <version> is the protocol version (always "HTTP/1.0"), - <responsecode> is a 3-digit response code indicating success or - failure of the request, and <responsestring> is an optional - human-readable string explaining what the response code means. - - This server parses the request and the headers, and then calls a - function specific to the request type (<command>). Specifically, - a request SPAM will be handled by a method handle_SPAM(). If no - such method exists the server sends an error response to the - client. If it exists, it is called with no arguments: - - do_SPAM() - - Note that the request name is case sensitive (i.e. SPAM and spam - are different requests). - - The various request details are stored in instance variables: - - - client_address is the client IP address in the form (host, - port); - - - command, path and version are the broken-down request line; - - - headers is an instance of mimetools.Message (or a derived - class) containing the header information; - - - rfile is a file object open for reading positioned at the - start of the optional input data part; - - - wfile is a file object open for writing. - - IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING! - - The first thing to be written must be the response line. Then - follow 0 or more header lines, then a blank line, and then the - actual data (if any). The meaning of the header lines depends on - the command executed by the server; in most cases, when data is - returned, there should be at least one header line of the form - - Content-type: <type>/<subtype> - - where <type> and <subtype> should be registered MIME types, - e.g. "text/html" or "text/plain". - - """ - - # The Python system version, truncated to its first component. - sys_version = "Python/" + string.split(sys.version)[0] - - # The server software version. You may want to override this. - # The format is multiple whitespace-separated strings, - # where each string is of the form name[/version]. - server_version = "BaseHTTP/" + __version__ - - def handle(self): - """Handle a single HTTP request. - - You normally don't need to override this method; see the class - __doc__ string for information on how to handle specific HTTP - commands such as GET and POST. - - """ - - self.raw_requestline = self.rfile.readline() - self.request_version = version = "HTTP/0.9" # Default - requestline = self.raw_requestline - if requestline[-2:] == '\r\n': - requestline = requestline[:-2] - elif requestline[-1:] == '\n': - requestline = requestline[:-1] - self.requestline = requestline - words = string.split(requestline) - if len(words) == 3: - [command, path, version] = words - if version != self.protocol_version: - self.send_error(400, "Bad request version (%s)" % `version`) - return - elif len(words) == 2: - [command, path] = words - if command != 'GET': - self.send_error(400, - "Bad HTTP/0.9 request type (%s)" % `command`) - return - else: - self.send_error(400, "Bad request syntax (%s)" % `requestline`) - return - self.command, self.path, self.request_version = command, path, version - self.headers = self.MessageClass(self.rfile, 0) - mname = 'do_' + command - if not hasattr(self, mname): - self.send_error(501, "Unsupported method (%s)" % `mname`) - return - method = getattr(self, mname) - method() - - def send_error(self, code, message=None): - """Send and log an error reply. - - Arguments are the error code, and a detailed message. - The detailed message defaults to the short entry matching the - response code. - - This sends an error response (so it must be called before any - output has been generated), logs the error, and finally sends - a piece of HTML explaining the error to the user. - - """ - - try: - short, long = self.responses[code] - except KeyError: - short, long = '???', '???' - if not message: - message = short - explain = long - self.log_error("code %d, message %s", code, message) - self.send_response(code, message) - self.end_headers() - self.wfile.write(self.error_message_format % - {'code': code, - 'message': message, - 'explain': explain}) - - error_message_format = DEFAULT_ERROR_MESSAGE - - def send_response(self, code, message=None): - """Send the response header and log the response code. - - Also send two standard headers with the server software - version and the current date. - - """ - self.log_request(code) - if message is None: - if self.responses.has_key(code): - message = self.responses[code][1] - else: - message = '' - if self.request_version != 'HTTP/0.9': - self.wfile.write("%s %s %s\r\n" % - (self.protocol_version, str(code), message)) - self.send_header('Server', self.version_string()) - self.send_header('Date', self.date_time_string()) - - def send_header(self, keyword, value): - """Send a MIME header.""" - if self.request_version != 'HTTP/0.9': - self.wfile.write("%s: %s\r\n" % (keyword, value)) - - def end_headers(self): - """Send the blank line ending the MIME headers.""" - if self.request_version != 'HTTP/0.9': - self.wfile.write("\r\n") - - def log_request(self, code='-', size='-'): - """Log an accepted request. - - This is called by send_reponse(). - - """ - - self.log_message('"%s" %s %s', - self.requestline, str(code), str(size)) - - def log_error(self, *args): - """Log an error. - - This is called when a request cannot be fulfilled. By - default it passes the message on to log_message(). - - Arguments are the same as for log_message(). - - XXX This should go to the separate error log. - - """ - - apply(self.log_message, args) - - def log_message(self, format, *args): - """Log an arbitrary message. - - This is used by all other logging functions. Override - it if you have specific logging wishes. - - The first argument, FORMAT, is a format string for the - message to be logged. If the format string contains - any % escapes requiring parameters, they should be - specified as subsequent arguments (it's just like - printf!). - - The client host and current date/time are prefixed to - every message. - - """ - - sys.stderr.write("%s - - [%s] %s\n" % - (self.address_string(), - self.log_date_time_string(), - format%args)) - - def version_string(self): - """Return the server software version string.""" - return self.server_version + ' ' + self.sys_version - - def date_time_string(self): - """Return the current date and time formatted for a message header.""" - now = time.time() - year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now) - s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( - self.weekdayname[wd], - day, self.monthname[month], year, - hh, mm, ss) - return s - - def log_date_time_string(self): - """Return the current time formatted for logging.""" - now = time.time() - year, month, day, hh, mm, ss, x, y, z = time.localtime(now) - s = "%02d/%3s/%04d %02d:%02d:%02d" % ( - day, self.monthname[month], year, hh, mm, ss) - return s - - weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] - - monthname = [None, - 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] - - def address_string(self): - """Return the client address formatted for logging. - - This version looks up the full hostname using gethostbyaddr(), - and tries to find a name that contains at least one dot. - - """ - - (host, port) = self.client_address - try: - name, names, addresses = socket.gethostbyaddr(host) - except socket.error, msg: - return host - names.insert(0, name) - for name in names: - if '.' in name: return name - return names[0] - - - # Essentially static class variables - - # The version of the HTTP protocol we support. - # Don't override unless you know what you're doing (hint: incoming - # requests are required to have exactly this version string). - protocol_version = "HTTP/1.0" - - # The Message-like class used to parse headers - MessageClass = mimetools.Message - - # Table mapping response codes to messages; entries have the - # form {code: (shortmessage, longmessage)}. - # See http://www.w3.org/hypertext/WWW/Protocols/HTTP/HTRESP.html - responses = { - 200: ('OK', 'Request fulfilled, document follows'), - 201: ('Created', 'Document created, URL follows'), - 202: ('Accepted', - 'Request accepted, processing continues off-line'), - 203: ('Partial information', 'Request fulfilled from cache'), - 204: ('No response', 'Request fulfilled, nothing follows'), - - 301: ('Moved', 'Object moved permanently -- see URI list'), - 302: ('Found', 'Object moved temporarily -- see URI list'), - 303: ('Method', 'Object moved -- see Method and URL list'), - 304: ('Not modified', - 'Document has not changed singe given time'), - - 400: ('Bad request', - 'Bad request syntax or unsupported method'), - 401: ('Unauthorized', - 'No permission -- see authorization schemes'), - 402: ('Payment required', - 'No payment -- see charging schemes'), - 403: ('Forbidden', - 'Request forbidden -- authorization will not help'), - 404: ('Not found', 'Nothing matches the given URI'), - - 500: ('Internal error', 'Server got itself in trouble'), - 501: ('Not implemented', - 'Server does not support this operation'), - 502: ('Service temporarily overloaded', - 'The server cannot process the request due to a high load'), - 503: ('Gateway timeout', - 'The gateway server did not receive a timely response'), - - } - - -def test(HandlerClass = BaseHTTPRequestHandler, - ServerClass = HTTPServer): - """Test the HTTP request handler class. - - This runs an HTTP server on port 8000 (or the first command line - argument). - - """ - - if sys.argv[1:]: - port = string.atoi(sys.argv[1]) - else: - port = 8000 - server_address = ('', port) - - httpd = ServerClass(server_address, HandlerClass) - - print "Serving HTTP on port", port, "..." - httpd.serve_forever() - - -if __name__ == '__main__': - test() diff --git a/Lib/CGIHTTPServer.py b/Lib/CGIHTTPServer.py deleted file mode 100644 index 837f7c2ea6..0000000000 --- a/Lib/CGIHTTPServer.py +++ /dev/null @@ -1,203 +0,0 @@ -"""CGI-savvy HTTP Server. - -This module builds on SimpleHTTPServer by implementing GET and POST -requests to cgi-bin scripts. - -""" - - -__version__ = "0.3" - - -import os -import sys -import time -import socket -import string -import urllib -import BaseHTTPServer -import SimpleHTTPServer - - -class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): - - """Complete HTTP server with GET, HEAD and POST commands. - - GET and HEAD also support running CGI scripts. - - The POST command is *only* implemented for CGI scripts. - - """ - - def do_POST(self): - """Serve a POST request. - - This is only implemented for CGI scripts. - - """ - - if self.is_cgi(): - self.run_cgi() - else: - self.send_error(501, "Can only POST to CGI scripts") - - def send_head(self): - """Version of send_head that support CGI scripts""" - if self.is_cgi(): - return self.run_cgi() - else: - return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self) - - def is_cgi(self): - """test whether PATH corresponds to a CGI script. - - Return a tuple (dir, rest) if PATH requires running a - CGI script, None if not. Note that rest begins with a - slash if it is not empty. - - The default implementation tests whether the path - begins with one of the strings in the list - self.cgi_directories (and the next character is a '/' - or the end of the string). - - """ - - path = self.path - - for x in self.cgi_directories: - i = len(x) - if path[:i] == x and (not path[i:] or path[i] == '/'): - self.cgi_info = path[:i], path[i+1:] - return 1 - return 0 - - cgi_directories = ['/cgi-bin', '/htbin'] - - def run_cgi(self): - """Execute a CGI script.""" - dir, rest = self.cgi_info - i = string.rfind(rest, '?') - if i >= 0: - rest, query = rest[:i], rest[i+1:] - else: - query = '' - i = string.find(rest, '/') - if i >= 0: - script, rest = rest[:i], rest[i:] - else: - script, rest = rest, '' - scriptname = dir + '/' + script - scriptfile = self.translate_path(scriptname) - if not os.path.exists(scriptfile): - self.send_error(404, "No such CGI script (%s)" % `scriptname`) - return - if not os.path.isfile(scriptfile): - self.send_error(403, "CGI script is not a plain file (%s)" % - `scriptname`) - return - if not executable(scriptfile): - self.send_error(403, "CGI script is not executable (%s)" % - `scriptname`) - return - nobody = nobody_uid() - self.send_response(200, "Script output follows") - self.wfile.flush() # Always flush before forking - pid = os.fork() - if pid != 0: - # Parent - pid, sts = os.waitpid(pid, 0) - if sts: - self.log_error("CGI script exit status x%x" % sts) - return - # Child - try: - # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html - # XXX Much of the following could be prepared ahead of time! - env = {} - env['SERVER_SOFTWARE'] = self.version_string() - env['SERVER_NAME'] = self.server.server_name - env['GATEWAY_INTERFACE'] = 'CGI/1.1' - env['SERVER_PROTOCOL'] = self.protocol_version - env['SERVER_PORT'] = str(self.server.server_port) - env['REQUEST_METHOD'] = self.command - uqrest = urllib.unquote(rest) - env['PATH_INFO'] = uqrest - env['PATH_TRANSLATED'] = self.translate_path(uqrest) - env['SCRIPT_NAME'] = scriptname - if query: - env['QUERY_STRING'] = query - host = self.address_string() - if host != self.client_address[0]: - env['REMOTE_HOST'] = host - env['REMOTE_ADDR'] = self.client_address[0] - # AUTH_TYPE - # REMOTE_USER - # REMOTE_IDENT - env['CONTENT_TYPE'] = self.headers.type - length = self.headers.getheader('content-length') - if length: - env['CONTENT_LENGTH'] = length - accept = [] - for line in self.headers.getallmatchingheaders('accept'): - if line[:1] in string.whitespace: - accept.append(string.strip(line)) - else: - accept = accept + string.split(line[7:]) - env['HTTP_ACCEPT'] = string.joinfields(accept, ',') - ua = self.headers.getheader('user-agent') - if ua: - env['HTTP_USER_AGENT'] = ua - # XXX Other HTTP_* headers - import regsub - decoded_query = regsub.gsub('+', ' ', query) - try: - os.setuid(nobody) - except os.error: - pass - os.dup2(self.rfile.fileno(), 0) - os.dup2(self.wfile.fileno(), 1) - print scriptfile, script, decoded_query - os.execve(scriptfile, - [script, decoded_query], - env) - except: - self.server.handle_error(self.request, self.client_address) - os._exit(127) - - -nobody = None - -def nobody_uid(): - """Internal routine to get nobody's uid""" - global nobody - if nobody: - return nobody - import pwd - try: - nobody = pwd.getpwnam('nobody')[2] - except pwd.error: - nobody = 1 + max(map(lambda x: x[2], pwd.getpwall())) - return nobody - - -def executable(path): - """Test for executable file.""" - try: - st = os.stat(path) - except os.error: - return 0 - return st[0] & 0111 != 0 - - -def test(HandlerClass = CGIHTTPRequestHandler, - ServerClass = BaseHTTPServer.HTTPServer): - import sys - if sys.argv[1:2] == ['-r']: - db = MyArchive() - db.regenindices() - return - SimpleHTTPServer.test(HandlerClass, ServerClass) - - -if __name__ == '__main__': - test() diff --git a/Lib/Complex.py b/Lib/Complex.py deleted file mode 100644 index f4892f30b6..0000000000 --- a/Lib/Complex.py +++ /dev/null @@ -1,275 +0,0 @@ -# Complex numbers -# --------------- - -# 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) -# Polar([r [,phi [,fullcircle]]]) -> -# the complex number z for which r == z.radius() and phi == z.angle(fullcircle) -# (r and phi default to 0) -# -# 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. -# (I suppose it would be easy to implement a cmath module.) -# -# 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 types, math - -if not hasattr(math, 'hypot'): - def hypot(x, y): - # XXX I know there's a way to compute this without possibly causing - # overflow, but I can't remember what it is right now... - return math.sqrt(x*x + y*y) - math.hypot = hypot - -twopi = math.pi*2.0 -halfpi = math.pi/2.0 - -def IsComplex(obj): - return hasattr(obj, 're') and hasattr(obj, 'im') - -def Polar(r = 0, phi = 0, fullcircle = twopi): - phi = phi * (twopi / fullcircle) - return Complex(math.cos(phi)*r, math.sin(phi)*r) - -class Complex: - - def __init__(self, re=0, im=0): - if IsComplex(re): - im = im + re.im - re = re.re - if IsComplex(im): - re = re - im.im - im = im.re - self.re = re - self.im = im - - def __setattr__(self, name, value): - if hasattr(self, name): - raise TypeError, "Complex numbers have set-once attributes" - self.__dict__[name] = value - - def __repr__(self): - if not self.im: - return 'Complex(%s)' % `self.re` - else: - return 'Complex(%s, %s)' % (`self.re`, `self.im`) - - def __str__(self): - if not self.im: - return `self.re` - else: - return 'Complex(%s, %s)' % (`self.re`, `self.im`) - - def __coerce__(self, other): - if IsComplex(other): - return self, other - return self, Complex(other) # May fail - - def __cmp__(self, other): - return cmp(self.re, other.re) or cmp(self.im, other.im) - - def __hash__(self): - if not self.im: return hash(self.re) - mod = sys.maxint + 1L - return int((hash(self.re) + 2L*hash(self.im) + mod) % (2L*mod) - mod) - - def __neg__(self): - return Complex(-self.re, -self.im) - - def __pos__(self): - return self - - def __abs__(self): - return math.hypot(self.re, self.im) - ##return math.sqrt(self.re*self.re + self.im*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 __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): - return Complex(self.re + other.re, self.im + other.im) - - __radd__ = __add__ - - def __sub__(self, other): - return Complex(self.re - other.re, self.im - other.im) - - def __rsub__(self, other): - return Complex(other.re - self.re, other.im - self.im) - - def __mul__(self, 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): - # Deviating from the general principle of not forcing re or im - # to be floats, we cast to float here, otherwise division - # of Complex numbers with integer re and im parts would use - # the (truncating) integer division - 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): - 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: raise TypeError, 'Complex to the Complex power' - 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): - return pow(base, self) - - -# Everything below this point is part of the test suite - -def checkop(expr, a, b, value, fuzz = 1e-6): - import sys - print ' ', a, 'and', b, - try: - result = eval(expr) - except: - result = sys.exc_type - print '->', result - if (type(result) == type('') or type(value) == type('')): - ok = result == value - else: - ok = abs(result - value) <= fuzz - if not ok: - print '!!\t!!\t!! should be', value, 'diff', abs(result - value) - - -def test(): - 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), 'TypeError'), - (Complex(0,10), 1, Complex(0,10)), - (Complex(0,10), Complex(1), Complex(0,10)), - (Complex(1), Complex(0,10), 'TypeError'), - (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), - ], - } - exprs = testsuite.keys() - exprs.sort() - for expr in exprs: - print expr + ':' - t = (expr,) - for item in testsuite[expr]: - apply(checkop, t+item) - - -if __name__ == '__main__': - test() diff --git a/Lib/Makefile b/Lib/Makefile deleted file mode 100644 index b70dc12f9b..0000000000 --- a/Lib/Makefile +++ /dev/null @@ -1,12 +0,0 @@ -all: - @echo Nothing to make in this directory. - -clean: - find . '(' -name '*.pyc' -o -name '*.fdc' \ - -o -name core -o -name '*~' \ - -o -name '[@,#]*' -o -name '*.old' \ - -o -name '*.orig' -o -name '*.rej' \ - -o -name '*.bak' ')' \ - -print -exec rm -f {} ';' - -clobber: clean diff --git a/Lib/Para.py b/Lib/Para.py deleted file mode 100644 index c9b3bdd1bd..0000000000 --- a/Lib/Para.py +++ /dev/null @@ -1,409 +0,0 @@ -# Text formatting abstractions -# Note -- this module is obsolete, it's too slow anyway - - -# Oft-used type object -Int = type(0) - - -# Represent a paragraph. This is a list of words with associated -# font and size information, plus indents and justification for the -# entire paragraph. -# Once the words have been added to a paragraph, it can be laid out -# for different line widths. Once laid out, it can be rendered at -# different screen locations. Once rendered, it can be queried -# for mouse hits, and parts of the text can be highlighted -class Para: - # - def __init__(self): - self.words = [] # The words - self.just = 'l' # Justification: 'l', 'r', 'lr' or 'c' - self.indent_left = self.indent_right = self.indent_hang = 0 - # Final lay-out parameters, may change - self.left = self.top = self.right = self.bottom = \ - self.width = self.height = self.lines = None - # - # Add a word, computing size information for it. - # Words may also be added manually by appending to self.words - # Each word should be a 7-tuple: - # (font, text, width, space, stretch, ascent, descent) - def addword(self, d, font, text, space, stretch): - if font <> None: - d.setfont(font) - width = d.textwidth(text) - ascent = d.baseline() - descent = d.lineheight() - ascent - spw = d.textwidth(' ') - space = space * spw - stretch = stretch * spw - tuple = (font, text, width, space, stretch, ascent, descent) - self.words.append(tuple) - # - # Hooks to begin and end anchors -- insert numbers in the word list! - def bgn_anchor(self, id): - self.words.append(id) - # - def end_anchor(self, id): - self.words.append(0) - # - # Return the total length (width) of the text added so far, in pixels - def getlength(self): - total = 0 - for word in self.words: - if type(word) <> Int: - total = total + word[2] + word[3] - return total - # - # Tab to a given position (relative to the current left indent): - # remove all stretch, add fixed space up to the new indent. - # If the current position is already beying the tab stop, - # don't add any new space (but still remove the stretch) - def tabto(self, tab): - total = 0 - as, de = 1, 0 - for i in range(len(self.words)): - word = self.words[i] - if type(word) == Int: continue - fo, te, wi, sp, st, as, de = word - self.words[i] = fo, te, wi, sp, 0, as, de - total = total + wi + sp - if total < tab: - self.words.append(None, '', 0, tab-total, 0, as, de) - # - # Make a hanging tag: tab to hang, increment indent_left by hang, - # and reset indent_hang to -hang - def makehangingtag(self, hang): - self.tabto(hang) - self.indent_left = self.indent_left + hang - self.indent_hang = -hang - # - # Decide where the line breaks will be given some screen width - def layout(self, linewidth): - self.width = linewidth - height = 0 - self.lines = lines = [] - avail1 = self.width - self.indent_left - self.indent_right - avail = avail1 - self.indent_hang - words = self.words - i = 0 - n = len(words) - lastfont = None - while i < n: - firstfont = lastfont - charcount = 0 - width = 0 - stretch = 0 - ascent = 0 - descent = 0 - lsp = 0 - j = i - while i < n: - word = words[i] - if type(word) == Int: - if word > 0 and width >= avail: - break - i = i+1 - continue - fo, te, wi, sp, st, as, de = word - if width + wi > avail and width > 0 and wi > 0: - break - if fo <> None: - lastfont = fo - if width == 0: - firstfont = fo - charcount = charcount + len(te) + (sp > 0) - width = width + wi + sp - lsp = sp - stretch = stretch + st - lst = st - ascent = max(ascent, as) - descent = max(descent, de) - i = i+1 - while i > j and type(words[i-1]) == Int and \ - words[i-1] > 0: i = i-1 - width = width - lsp - if i < n: - stretch = stretch - lst - else: - stretch = 0 - tuple = i-j, firstfont, charcount, width, stretch, \ - ascent, descent - lines.append(tuple) - height = height + ascent + descent - avail = avail1 - self.height = height - # - # Call a function for all words in a line - def visit(self, wordfunc, anchorfunc): - avail1 = self.width - self.indent_left - self.indent_right - avail = avail1 - self.indent_hang - v = self.top - i = 0 - for tuple in self.lines: - wordcount, firstfont, charcount, width, stretch, \ - ascent, descent = tuple - h = self.left + self.indent_left - if i == 0: h = h + self.indent_hang - extra = 0 - if self.just == 'r': h = h + avail - width - elif self.just == 'c': h = h + (avail - width) / 2 - elif self.just == 'lr' and stretch > 0: - extra = avail - width - v2 = v + ascent + descent - for j in range(i, i+wordcount): - word = self.words[j] - if type(word) == Int: - ok = anchorfunc(self, tuple, word, \ - h, v) - if ok <> None: return ok - continue - fo, te, wi, sp, st, as, de = word - if extra > 0 and stretch > 0: - ex = extra * st / stretch - extra = extra - ex - stretch = stretch - st - else: - ex = 0 - h2 = h + wi + sp + ex - ok = wordfunc(self, tuple, word, h, v, \ - h2, v2, (j==i), (j==i+wordcount-1)) - if ok <> None: return ok - h = h2 - v = v2 - i = i + wordcount - avail = avail1 - # - # Render a paragraph in "drawing object" d, using the rectangle - # given by (left, top, right) with an unspecified bottom. - # Return the computed bottom of the text. - def render(self, d, left, top, right): - if self.width <> right-left: - self.layout(right-left) - self.left = left - self.top = top - self.right = right - self.bottom = self.top + self.height - self.anchorid = 0 - try: - self.d = d - self.visit(self.__class__._renderword, \ - self.__class__._renderanchor) - finally: - self.d = None - return self.bottom - # - def _renderword(self, tuple, word, h, v, h2, v2, isfirst, islast): - if word[0] <> None: self.d.setfont(word[0]) - baseline = v + tuple[5] - self.d.text((h, baseline - word[5]), word[1]) - if self.anchorid > 0: - self.d.line((h, baseline+2), (h2, baseline+2)) - # - def _renderanchor(self, tuple, word, h, v): - self.anchorid = word - # - # Return which anchor(s) was hit by the mouse - def hitcheck(self, mouseh, mousev): - self.mouseh = mouseh - self.mousev = mousev - self.anchorid = 0 - self.hits = [] - self.visit(self.__class__._hitcheckword, \ - self.__class__._hitcheckanchor) - return self.hits - # - def _hitcheckword(self, tuple, word, h, v, h2, v2, isfirst, islast): - if self.anchorid > 0 and h <= self.mouseh <= h2 and \ - v <= self.mousev <= v2: - self.hits.append(self.anchorid) - # - def _hitcheckanchor(self, tuple, word, h, v): - self.anchorid = word - # - # Return whether the given anchor id is present - def hasanchor(self, id): - return id in self.words or -id in self.words - # - # Extract the raw text from the word list, substituting one space - # for non-empty inter-word space, and terminating with '\n' - def extract(self): - text = '' - for w in self.words: - if type(w) <> Int: - word = w[1] - if w[3]: word = word + ' ' - text = text + word - return text + '\n' - # - # Return which character position was hit by the mouse, as - # an offset in the entire text as returned by extract(). - # Return None if the mouse was not in this paragraph - def whereis(self, d, mouseh, mousev): - if mousev < self.top or mousev > self.bottom: - return None - self.mouseh = mouseh - self.mousev = mousev - self.lastfont = None - self.charcount = 0 - try: - self.d = d - return self.visit(self.__class__._whereisword, \ - self.__class__._whereisanchor) - finally: - self.d = None - # - def _whereisword(self, tuple, word, h1, v1, h2, v2, isfirst, islast): - fo, te, wi, sp, st, as, de = word - if fo <> None: self.lastfont = fo - h = h1 - if isfirst: h1 = 0 - if islast: h2 = 999999 - if not (v1 <= self.mousev <= v2 and h1 <= self.mouseh <= h2): - self.charcount = self.charcount + len(te) + (sp > 0) - return - if self.lastfont <> None: - self.d.setfont(self.lastfont) - cc = 0 - for c in te: - cw = self.d.textwidth(c) - if self.mouseh <= h + cw/2: - return self.charcount + cc - cc = cc+1 - h = h+cw - self.charcount = self.charcount + cc - if self.mouseh <= (h+h2) / 2: - return self.charcount - else: - return self.charcount + 1 - # - def _whereisanchor(self, tuple, word, h, v): - pass - # - # Return screen position corresponding to position in paragraph. - # Return tuple (h, vtop, vbaseline, vbottom). - # This is more or less the inverse of whereis() - def screenpos(self, d, pos): - if pos < 0: - ascent, descent = self.lines[0][5:7] - return self.left, self.top, self.top + ascent, \ - self.top + ascent + descent - self.pos = pos - self.lastfont = None - try: - self.d = d - ok = self.visit(self.__class__._screenposword, \ - self.__class__._screenposanchor) - finally: - self.d = None - if ok == None: - ascent, descent = self.lines[-1][5:7] - ok = self.right, self.bottom - ascent - descent, \ - self.bottom - descent, self.bottom - return ok - # - def _screenposword(self, tuple, word, h1, v1, h2, v2, isfirst, islast): - fo, te, wi, sp, st, as, de = word - if fo <> None: self.lastfont = fo - cc = len(te) + (sp > 0) - if self.pos > cc: - self.pos = self.pos - cc - return - if self.pos < cc: - self.d.setfont(self.lastfont) - h = h1 + self.d.textwidth(te[:self.pos]) - else: - h = h2 - ascent, descent = tuple[5:7] - return h, v1, v1+ascent, v2 - # - def _screenposanchor(self, tuple, word, h, v): - pass - # - # Invert the stretch of text between pos1 and pos2. - # If pos1 is None, the beginning is implied; - # if pos2 is None, the end is implied. - # Undoes its own effect when called again with the same arguments - def invert(self, d, pos1, pos2): - if pos1 == None: - pos1 = self.left, self.top, self.top, self.top - else: - pos1 = self.screenpos(d, pos1) - if pos2 == None: - pos2 = self.right, self.bottom,self.bottom,self.bottom - else: - pos2 = self.screenpos(d, pos2) - h1, top1, baseline1, bottom1 = pos1 - h2, top2, baseline2, bottom2 = pos2 - if bottom1 <= top2: - d.invert((h1, top1), (self.right, bottom1)) - h1 = self.left - if bottom1 < top2: - d.invert((h1, bottom1), (self.right, top2)) - top1, bottom1 = top2, bottom2 - d.invert((h1, top1), (h2, bottom2)) - - -# Test class Para -# XXX This was last used on the Mac, hence the weird fonts... -def test(): - import stdwin - from stdwinevents import * - words = 'The', 'quick', 'brown', 'fox', 'jumps', 'over', \ - 'the', 'lazy', 'dog.' - paralist = [] - for just in 'l', 'r', 'lr', 'c': - p = Para() - p.just = just - p.addword(stdwin, ('New York', 'p', 12), words[0], 1, 1) - for word in words[1:-1]: - p.addword(stdwin, None, word, 1, 1) - p.addword(stdwin, None, words[-1], 2, 4) - p.addword(stdwin, ('New York', 'b', 18), 'Bye!', 0, 0) - p.addword(stdwin, ('New York', 'p', 10), 'Bye!', 0, 0) - paralist.append(p) - window = stdwin.open('Para.test()') - start = stop = selpara = None - while 1: - etype, win, detail = stdwin.getevent() - if etype == WE_CLOSE: - break - if etype == WE_SIZE: - window.change((0, 0), (1000, 1000)) - if etype == WE_DRAW: - width, height = window.getwinsize() - d = None - try: - d = window.begindrawing() - d.cliprect(detail) - d.erase(detail) - v = 0 - for p in paralist: - v = p.render(d, 0, v, width) - if p == selpara and \ - start <> None and stop <> None: - p.invert(d, start, stop) - finally: - if d: d.close() - if etype == WE_MOUSE_DOWN: - if selpara and start <> None and stop <> None: - d = window.begindrawing() - selpara.invert(d, start, stop) - d.close() - start = stop = selpara = None - mouseh, mousev = detail[0] - for p in paralist: - start = p.whereis(stdwin, mouseh, mousev) - if start <> None: - selpara = p - break - if etype == WE_MOUSE_UP and start <> None and selpara: - mouseh, mousev = detail[0] - stop = selpara.whereis(stdwin, mouseh, mousev) - if stop == None: start = selpara = None - else: - if start > stop: - start, stop = stop, start - d = window.begindrawing() - selpara.invert(d, start, stop) - d.close() - window.close() diff --git a/Lib/Queue.py b/Lib/Queue.py deleted file mode 100644 index 5125fd5dd2..0000000000 --- a/Lib/Queue.py +++ /dev/null @@ -1,121 +0,0 @@ -# A multi-producer, multi-consumer queue. - -Empty = 'Queue.Empty' # Exception raised by get_nowait() - -class Queue: - - # Initialize a queue object with a given maximum size - # (If maxsize is <= 0, the maximum size is infinite) - def __init__(self, maxsize): - import thread - self._init(maxsize) - self.mutex = thread.allocate_lock() - self.esema = thread.allocate_lock() - self.esema.acquire_lock() - self.fsema = thread.allocate_lock() - - # Get an approximation of the queue size (not reliable!) - def qsize(self): - self.mutex.acquire_lock() - n = self._qsize() - self.mutex.release_lock() - return n - - # Check if the queue is empty (not reliable!) - def empty(self): - self.mutex.acquire_lock() - n = self._empty() - self.mutex.release_lock() - return n - - # Check if the queue is full (not reliable!) - def full(self): - self.mutex.acquire_lock() - n = self._full() - self.mutex.release_lock() - return n - - # Put a new item into the queue - def put(self, item): - self.fsema.acquire_lock() - self.mutex.acquire_lock() - was_empty = self._empty() - self._put(item) - if was_empty: - self.esema.release_lock() - if not self._full(): - self.fsema.release_lock() - self.mutex.release_lock() - - # Get an item from the queue, - # blocking if necessary until one is available - def get(self): - self.esema.acquire_lock() - self.mutex.acquire_lock() - was_full = self._full() - item = self._get() - if was_full: - self.fsema.release_lock() - if not self._empty(): - self.esema.release_lock() - self.mutex.release_lock() - return item - - # Get an item from the queue if one is immediately available, - # raise Empty if the queue is empty or temporarily unavailable - def get_nowait(self): - locked = self.esema.acquire_lock(0) - self.mutex.acquire_lock() - if self._empty(): - # The queue is empyt -- we can't have esema - self.mutex.release_lock() - raise Empty - if not locked: - locked = self.esema.acquire_lock(0) - if not locked: - # Somebody else has esema - # but we have mutex -- - # go out of their way - self.mutex.release_lock() - raise Empty - was_full = self._full() - item = self._get() - if was_full: - self.fsema.release_lock() - if not self._empty(): - self.esema.release_lock() - self.mutex.release_lock() - return item - - # XXX Need to define put_nowait() as well. - - - # Override these methods to implement other queue organizations - # (e.g. stack or priority queue). - # These will only be called with appropriate locks held - - # Initialize the queue representation - def _init(self, maxsize): - self.maxsize = maxsize - self.queue = [] - - def _qsize(self): - return len(self.queue) - - # Check wheter the queue is empty - def _empty(self): - return not self.queue - - # Check whether the queue is full - def _full(self): - return self.maxsize > 0 and len(self.queue) == self.maxsize - - # Put a new item in the queue - def _put(self, item): - self.queue.append(item) - - # Get an item from the queue - def _get(self): - item = self.queue[0] - del self.queue[0] - return item diff --git a/Lib/SimpleHTTPServer.py b/Lib/SimpleHTTPServer.py deleted file mode 100644 index dd3107abc6..0000000000 --- a/Lib/SimpleHTTPServer.py +++ /dev/null @@ -1,168 +0,0 @@ -"""Simple HTTP Server. - -This module builds on BaseHTTPServer by implementing the standard GET -and HEAD requests in a fairly straightforward manner. - -""" - - -__version__ = "0.3" - - -import os -import pwd -import sys -import time -import socket -import string -import posixpath -import SocketServer -import BaseHTTPServer - - -def nobody_uid(): - """Internal routine to get nobody's uid""" - try: - nobody = pwd.getpwnam('nobody')[2] - except pwd.error: - nobody = 1 + max(map(lambda x: x[2], pwd.getpwall())) - return nobody - -nobody = nobody_uid() - - -class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): - - """Simple HTTP request handler with GET and HEAD commands. - - This serves files from the current directory and any of its - subdirectories. It assumes that all files are plain text files - unless they have the extension ".html" in which case it assumes - they are HTML files. - - The GET and HEAD requests are identical except that the HEAD - request omits the actual contents of the file. - - """ - - server_version = "SimpleHTTP/" + __version__ - - def do_GET(self): - """Serve a GET request.""" - f = self.send_head() - if f: - self.copyfile(f, self.wfile) - f.close() - - def do_HEAD(self): - """Serve a HEAD request.""" - f = self.send_head() - if f: - f.close() - - def send_head(self): - """Common code for GET and HEAD commands. - - This sends the response code and MIME headers. - - Return value is either a file object (which has to be copied - to the outputfile by the caller unless the command was HEAD, - and must be closed by the caller under all circumstances), or - None, in which case the caller has nothing further to do. - - """ - path = self.translate_path(self.path) - if os.path.isdir(path): - self.send_error(403, "Directory listing not supported") - return None - try: - f = open(path) - except IOError: - self.send_error(404, "File not found") - return None - self.send_response(200) - self.send_header("Content-type", self.guess_type(path)) - self.end_headers() - return f - - def translate_path(self, path): - """Translate a /-separated PATH to the local filename syntax. - - Components that mean special things to the local file system - (e.g. drive or directory names) are ignored. (XXX They should - probably be diagnosed.) - - """ - path = posixpath.normpath(path) - words = string.splitfields(path, '/') - words = filter(None, words) - path = os.getcwd() - for word in words: - drive, word = os.path.splitdrive(word) - head, word = os.path.split(word) - if word in (os.curdir, os.pardir): continue - path = os.path.join(path, word) - return path - - def copyfile(self, source, outputfile): - """Copy all data between two file objects. - - The SOURCE argument is a file object open for reading - (or anything with a read() method) and the DESTINATION - argument is a file object open for writing (or - anything with a write() method). - - The only reason for overriding this would be to change - the block size or perhaps to replace newlines by CRLF - -- note however that this the default server uses this - to copy binary data as well. - - """ - - BLOCKSIZE = 8192 - while 1: - data = source.read(BLOCKSIZE) - if not data: break - outputfile.write(data) - - def guess_type(self, path): - """Guess the type of a file. - - Argument is a PATH (a filename). - - Return value is a string of the form type/subtype, - usable for a MIME Content-type header. - - The default implementation looks the file's extension - up in the table self.extensions_map, using text/plain - as a default; however it would be permissible (if - slow) to look inside the data to make a better guess. - - """ - - base, ext = posixpath.splitext(path) - if self.extensions_map.has_key(ext): - return self.extensions_map[ext] - ext = string.lower(ext) - if self.extensions_map.has_key(ext): - return self.extensions_map[ext] - else: - return self.extensions_map[''] - - extensions_map = { - '': 'text/plain', # Default, *must* be present - '.html': 'text/html', - '.htm': 'text/html', - '.gif': 'image/gif', - '.jpg': 'image/jpeg', - '.jpeg': 'image/jpeg', - } - - -def test(HandlerClass = SimpleHTTPRequestHandler, - ServerClass = SocketServer.TCPServer): - BaseHTTPServer.test(HandlerClass, ServerClass) - - -if __name__ == '__main__': - test() diff --git a/Lib/SocketServer.py b/Lib/SocketServer.py deleted file mode 100644 index 9a646ab6eb..0000000000 --- a/Lib/SocketServer.py +++ /dev/null @@ -1,413 +0,0 @@ -"""Generic socket server classes. - -This module tries to capture the various aspects of defining a server: - -- address family: - - AF_INET: IP (Internet Protocol) sockets (default) - - AF_UNIX: Unix domain sockets - - others, e.g. AF_DECNET are conceivable (see <socket.h> -- socket type: - - SOCK_STREAM (reliable stream, e.g. TCP) - - SOCK_DGRAM (datagrams, e.g. UDP) -- client address verification before further looking at the request - (This is actually a hook for any processing that needs to look - at the request before anything else, e.g. logging) -- how to handle multiple requests: - - synchronous (one request is handled at a time) - - forking (each request is handled by a new process) - - threading (each request is handled by a new thread) - -The classes in this module favor the server type that is simplest to -write: a synchronous TCP/IP server. This is bad class design, but -save some typing. (There's also the issue that a deep class hierarchy -slows down method lookups.) - -There are four classes in an inheritance diagram that represent -synchronous servers of four types: - - +-----------+ +------------------+ - | TCPServer |------->| UnixStreamServer | - +-----------+ +------------------+ - | - v - +-----------+ +--------------------+ - | UDPServer |------->| UnixDatagramServer | - +-----------+ +--------------------+ - -(Note that UnixDatagramServer derives from UDPServer, not from -UnixStreamServer -- the only difference between an IP and a Unix -stream server is the address family, which is simply repeated in both -unix server classes.) - -Forking and threading versions of each type of server can be created -using the ForkingServer and ThreadingServer mix-in classes. For -instance, a threading UDP server class is created as follows: - - class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass - -(The Mix-in class must come first, since it overrides a method defined -in UDPServer!) - -To implement a service, you must derive a class from -BaseRequestHandler and redefine its handle() method. You can then run -various versions of the service by combining one of the server classes -with your request handler class. - -The request handler class must be different for datagram or stream -services. This can be hidden by using the mix-in request handler -classes StreamRequestHandler or DatagramRequestHandler. - -Of course, you still have to use your head! - -For instance, it makes no sense to use a forking server if the service -contains state in memory that can be modified by requests (since the -modifications in the child process would never reach the initial state -kept in the parent process and passed to each child). In this case, -you can use a threading server, but you will probably have to use -locks to avoid two requests that come in nearly simultaneous to apply -conflicting changes to the server state. - -On the other hand, if you are building e.g. an HTTP server, where all -data is stored externally (e.g. in the file system), a synchronous -class will essentially render the service "deaf" while one request is -being handled -- which may be for a very long time if a client is slow -to reqd all the data it has requested. Here a threading or forking -server is appropriate. - -In some cases, it may be appropriate to process part of a request -synchronously, but to finish processing in a forked child depending on -the request data. This can be implemented by using a synchronous -server and doing an explicit fork in the request handler class's -handle() method. - -Another approach to handling multiple simultaneous requests in an -environment that supports neither threads nor fork (or where these are -too expensive or inappropriate for the service) is to maintain an -explicit table of partially finished requests and to use select() to -decide which request to work on next (or whether to handle a new -incoming request). This is particularly important for stream services -where each client can potentially be connected for a long time (if -threads or subprocesses can't be used). - -Future work: -- Standard classes for Sun RPC (which uses either UDP or TCP) -- Standard mix-in classes to implement various authentication - and encryption schemes -- Standard framework for select-based multiplexing - -XXX Open problems: -- What to do with out-of-band data? - -""" - - -__version__ = "0.2" - - -import socket -import sys -import os - - -class TCPServer: - - """Base class for various socket-based server classes. - - Defaults to synchronous IP stream (i.e., TCP). - - Methods for the caller: - - - __init__(server_address, RequestHandlerClass) - - serve_forever() - - handle_request() # if you don't use serve_forever() - - fileno() -> int # for select() - - Methods that may be overridden: - - - server_bind() - - server_activate() - - get_request() -> request, client_address - - verify_request(request, client_address) - - process_request(request, client_address) - - handle_error() - - Methods for derived classes: - - - finish_request(request, client_address) - - Class variables that may be overridden by derived classes or - instances: - - - address_family - - socket_type - - request_queue_size (only for stream sockets) - - Instance variables: - - - server_address - - RequestHandlerClass - - socket - - """ - - address_family = socket.AF_INET - - socket_type = socket.SOCK_STREAM - - request_queue_size = 5 - - def __init__(self, server_address, RequestHandlerClass): - """Constructor. May be extended, do not override.""" - self.server_address = server_address - self.RequestHandlerClass = RequestHandlerClass - self.socket = socket.socket(self.address_family, - self.socket_type) - self.server_bind() - self.server_activate() - - def server_bind(self): - """Called by constructor to bind the socket. - - May be overridden. - - """ - self.socket.bind(self.server_address) - - def server_activate(self): - """Called by constructor to activate the server. - - May be overridden. - - """ - self.socket.listen(self.request_queue_size) - - def fileno(self): - """Return socket file number. - - Interface required by select(). - - """ - return self.socket.fileno() - - def serve_forever(self): - """Handle one request at a time until doomsday.""" - while 1: - self.handle_request() - - # The distinction between handling, getting, processing and - # finishing a request is fairly arbitrary. Remember: - # - # - handle_request() is the top-level call. It calls - # get_request(), verify_request() and process_request() - # - get_request() is different for stream or datagram sockets - # - process_request() is the place that may fork a new process - # or create a new thread to finish the request - # - finish_request() instantiates the request handler class; - # this constructor will handle the request all by itself - - def handle_request(self): - """Handle one request, possibly blocking.""" - request, client_address = self.get_request() - if self.verify_request(request, client_address): - try: - self.process_request(request, client_address) - except: - self.handle_error(request, client_address) - - def get_request(self): - """Get the request and client address from the socket. - - May be overridden. - - """ - return self.socket.accept() - - def verify_request(self, request, client_address): - """Verify the request. May be overridden. - - Return true if we should proceed with this request. - - """ - return 1 - - def process_request(self, request, client_address): - """Call finish_request. - - Overridden by ForkingMixIn and ThreadingMixIn. - - """ - self.finish_request(request, client_address) - - def finish_request(self, request, client_address): - """Finish one request by instantiating RequestHandlerClass.""" - self.RequestHandlerClass(request, client_address, self) - - def handle_error(self, request, client_address): - """Handle an error gracefully. May be overridden. - - The default is to print a traceback and continue. - - """ - exc, value, tb = sys.exc_type, sys.exc_value, sys.exc_traceback - print '-'*40 - print 'Exception happened during processing of request from', - print client_address - import traceback - traceback.print_exception(exc, value, tb) - print '-'*40 - - -class UDPServer(TCPServer): - - """UDP server class.""" - - socket_type = socket.SOCK_DGRAM - - max_packet_size = 8192 - - def get_request(self): - return self.socket.recvfrom(max_packet_size) - - -if hasattr(socket, 'AF_UNIX'): - - class UnixStreamServer(TCPServer): - - address_family = socket.AF_UNIX - - - class UnixDatagramServer(UDPServer): - - address_family = socket.AF_UNIX - - -class ForkingMixIn: - - """Mix-in class to handle each request in a new process.""" - - active_children = None - - def collect_children(self): - """Internal routine to wait for died children.""" - while self.active_children: - pid, status = os.waitpid(0, os.WNOHANG) - if not pid: break - self.active_children.remove(pid) - - def process_request(self, request, client_address): - """Fork a new subprocess to process the request.""" - self.collect_children() - pid = os.fork() - if pid: - # Parent process - if self.active_children is None: - self.active_children = [] - self.active_children.append(pid) - return - else: - # Child process. - # This must never return, hence os._exit()! - try: - self.finish_request(request, client_address) - os._exit(0) - except: - try: - self.handle_error(request, - client_address) - finally: - os._exit(1) - - -class ThreadingMixIn: - - """Mix-in class to handle each request in a new thread.""" - - def process_request(self, request, client_address): - """Start a new thread to process the request.""" - import thread - thread.start_new_thread(self.finish_request, - (request, client_address)) - - -class ForkingUDPServer(ForkingMixIn, UDPServer): pass -class ForkingTCPServer(ForkingMixIn, TCPServer): pass - -class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass -class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass - - -class BaseRequestHandler: - - """Base class for request handler classes. - - This class is instantiated for each request to be handled. The - constructor sets the instance variables request, client_address - and server, and then calls the handle() method. To implement a - specific service, all you need to do is to derive a class which - defines a handle() method. - - The handle() method can find the request as self.request, the - client address as self.client_request, and the server (in case it - needs access to per-server information) as self.server. Since a - separate instance is created for each request, the handle() method - can define arbitrary other instance variariables. - - """ - - def __init__(self, request, client_address, server): - self.request = request - self.client_address = client_address - self.server = server - try: - self.setup() - self.handle() - self.finish() - finally: - sys.exc_traceback = None # Help garbage collection - - def setup(self): - pass - - def __del__(self): - pass - - def handle(self): - pass - - def finish(self): - pass - - -# The following two classes make it possible to use the same service -# class for stream or datagram servers. -# Each class sets up these instance variables: -# - rfile: a file object from which receives the request is read -# - wfile: a file object to which the reply is written -# When the handle() method returns, wfile is flushed properly - - -class StreamRequestHandler(BaseRequestHandler): - - """Define self.rfile and self.wfile for stream sockets.""" - - def setup(self): - self.connection = self.request - self.rfile = self.connection.makefile('rb') - self.wfile = self.connection.makefile('wb', 0) - - def finish(self): - self.wfile.flush() - - -class DatagramRequestHandler(BaseRequestHandler): - - """Define self.rfile and self.wfile for datagram sockets.""" - - def setup(self): - import StringIO - self.packet, self.socket = self.request - self.rfile = StringIO.StringIO(self.packet) - self.wfile = StringIO.StringIO(self.packet) - - def finish(self): - self.socket.send(self.wfile.getvalue()) diff --git a/Lib/StringIO.py b/Lib/StringIO.py deleted file mode 100644 index 12d19a1cbf..0000000000 --- a/Lib/StringIO.py +++ /dev/null @@ -1,133 +0,0 @@ -# class StringIO implements file-like objects that read/write a -# string buffer (a.k.a. "memory files"). -# -# This implements (nearly) all stdio methods. -# -# f = StringIO() # ready for writing -# f = StringIO(buf) # ready for reading -# f.close() # explicitly release resources held -# flag = f.isatty() # always false -# pos = f.tell() # get current position -# f.seek(pos) # set current position -# f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF -# buf = f.read() # read until EOF -# buf = f.read(n) # read up to n bytes -# buf = f.readline() # read until end of line ('\n') or EOF -# list = f.readlines()# list of f.readline() results until EOF -# f.write(buf) # write at current position -# f.writelines(list) # for line in list: f.write(line) -# f.getvalue() # return whole file's contents as a string -# -# Notes: -# - Using a real file is often faster (but less convenient). -# - fileno() is left unimplemented so that code which uses it triggers -# an exception early. -# - Seeking far beyond EOF and then writing will insert real null -# bytes that occupy space in the buffer. -# - There's a simple test set (see end of this file). - -import string - -class StringIO: - def __init__(self, buf = ''): - self.buf = buf - self.pos = 0 - self.closed = 0 - self.softspace = 0 - def close(self): - if not self.closed: - self.closed = 1 - del self.buf, self.pos - def isatty(self): - return 0 - def seek(self, pos, mode = 0): - if mode == 1: - pos = pos + self.pos - elif mode == 2: - pos = pos + len(self.buf) - self.pos = max(0, pos) - def tell(self): - return self.pos - def read(self, n = -1): - if n < 0: - newpos = len(self.buf) - else: - newpos = min(self.pos+n, len(self.buf)) - r = self.buf[self.pos:newpos] - self.pos = newpos - return r - def readline(self): - i = string.find(self.buf, '\n', self.pos) - if i < 0: - newpos = len(self.buf) - else: - newpos = i+1 - r = self.buf[self.pos:newpos] - self.pos = newpos - return r - def readlines(self): - lines = [] - line = self.readline() - while line: - lines.append(line) - line = self.readline() - return lines - def write(self, s): - if not s: return - if self.pos > len(self.buf): - self.buf = self.buf + '\0'*(self.pos - len(self.buf)) - newpos = self.pos + len(s) - self.buf = self.buf[:self.pos] + s + self.buf[newpos:] - self.pos = newpos - def writelines(self, list): - self.write(string.joinfields(list, '')) - def flush(self): - pass - def getvalue(self): - return self.buf - - -# A little test suite - -def test(): - import sys - if sys.argv[1:]: - file = sys.argv[1] - else: - file = '/etc/passwd' - lines = open(file, 'r').readlines() - text = open(file, 'r').read() - f = StringIO() - for line in lines[:-2]: - f.write(line) - f.writelines(lines[-2:]) - if f.getvalue() != text: - raise RuntimeError, 'write failed' - length = f.tell() - print 'File length =', length - f.seek(len(lines[0])) - f.write(lines[1]) - f.seek(0) - print 'First line =', `f.readline()` - here = f.tell() - line = f.readline() - print 'Second line =', `line` - f.seek(-len(line), 1) - line2 = f.read(len(line)) - if line != line2: - raise RuntimeError, 'bad result after seek back' - f.seek(len(line2), 1) - list = f.readlines() - line = list[-1] - f.seek(f.tell() - len(line)) - line2 = f.read() - if line != line2: - raise RuntimeError, 'bad result after seek back from EOF' - print 'Read', len(list), 'more lines' - print 'File length =', f.tell() - if f.tell() != length: - raise RuntimeError, 'bad length' - f.close() - -if __name__ == '__main__': - test() diff --git a/Lib/UserDict.py b/Lib/UserDict.py deleted file mode 100644 index f6b2f823af..0000000000 --- a/Lib/UserDict.py +++ /dev/null @@ -1,18 +0,0 @@ -# A more or less complete user-defined wrapper around dictionary objects - -class UserDict: - def __init__(self): self.data = {} - def __repr__(self): return repr(self.data) - def __cmp__(self, dict): - if type(dict) == type(self.data): - return cmp(self.data, dict) - else: - return cmp(self.data, dict.data) - def __len__(self): return len(self.data) - def __getitem__(self, key): return self.data[key] - def __setitem__(self, key, item): self.data[key] = item - def __delitem__(self, key): del self.data[key] - def keys(self): return self.data.keys() - def items(self): return self.data.items() - def values(self): return self.data.values() - def has_key(self, key): return self.data.has_key(key) diff --git a/Lib/UserList.py b/Lib/UserList.py deleted file mode 100644 index 1f19ad9c46..0000000000 --- a/Lib/UserList.py +++ /dev/null @@ -1,50 +0,0 @@ -# A more or less complete user-defined wrapper around list objects - -class UserList: - def __init__(self, list = None): - self.data = [] - if list is not None: - if type(list) == type(self.data): - self.data[:] = list - else: - self.data[:] = list.data[:] - def __repr__(self): return repr(self.data) - def __cmp__(self, list): - if type(list) == type(self.data): - return cmp(self.data, list) - else: - return cmp(self.data, list.data) - def __len__(self): return len(self.data) - def __getitem__(self, i): return self.data[i] - def __setitem__(self, i, item): self.data[i] = item - def __delitem__(self, i): del self.data[i] - def __getslice__(self, i, j): - userlist = UserList() - userlist.data[:] = self.data[i:j] - return userlist - def __setslice__(self, i, j, list): - if type(list) == type(self.data): - self.data[i:j] = list - else: - self.data[i:j] = list.data - def __delslice__(self, i, j): del self.data[i:j] - def __add__(self, list): - if type(list) == type(self.data): - return self.__class__(self.data + list) - else: - return self.__class__(self.data + list.data) - def __radd__(self, list): - if type(list) == type(self.data): - return self.__class__(list + self.data) - else: - return self.__class__(list.data + self.data) - def __mul__(self, n): - return self.__class__(self.data*n) - __rmul__ = __mul__ - def append(self, item): self.data.append(item) - def insert(self, i, item): self.data.insert(i, item) - def remove(self, item): self.data.remove(item) - def count(self, item): return self.data.count(item) - def index(self, item): return self.data.index(item) - def reverse(self): self.data.reverse() - def sort(self, *args): apply(self.data.sort, args) diff --git a/Lib/addpack.py b/Lib/addpack.py deleted file mode 100644 index 3d09236ba9..0000000000 --- a/Lib/addpack.py +++ /dev/null @@ -1,67 +0,0 @@ -# This module provides standard support for "packages". -# -# The idea is that large groups of related modules can be placed in -# their own subdirectory, which can be added to the Python search path -# in a relatively easy way. -# -# The current version takes a package name and searches the Python -# search path for a directory by that name, and if found adds it to -# the module search path (sys.path). It maintains a list of packages -# that have already been added so adding the same package many times -# is OK. -# -# It is intended to be used in a fairly stylized manner: each module -# that wants to use a particular package, say 'Foo', is supposed to -# contain the following code: -# -# from addpack import addpack -# addpack('Foo') -# <import modules from package Foo> -# -# Additional arguments, when present, provide additional places where -# to look for the package before trying sys.path (these may be either -# strings or lists/tuples of strings). Also, if the package name is a -# full pathname, first the last component is tried in the usual way, -# then the full pathname is tried last. If the package name is a -# *relative* pathname (UNIX: contains a slash but doesn't start with -# one), then nothing special is done. The packages "/foo/bar/bletch" -# and "bletch" are considered the same, but unrelated to "bar/bletch". -# -# If the algorithm finds more than one suitable subdirectory, all are -# added to the search path -- this makes it possible to override part -# of a package. The same path will not be added more than once. -# -# If no directory is found, ImportError is raised. - -_packs = {} # {pack: [pathname, ...], ...} - -def addpack(pack, *locations): - import os - if os.path.isabs(pack): - base = os.path.basename(pack) - else: - base = pack - if _packs.has_key(base): - return - import sys - path = [] - for loc in _flatten(locations) + sys.path: - fn = os.path.join(loc, base) - if fn not in path and os.path.isdir(fn): - path.append(fn) - if pack != base and pack not in path and os.path.isdir(pack): - path.append(pack) - if not path: raise ImportError, 'package ' + pack + ' not found' - _packs[base] = path - for fn in path: - if fn not in sys.path: - sys.path.append(fn) - -def _flatten(locations): - locs = [] - for loc in locations: - if type(loc) == type(''): - locs.append(loc) - else: - locs = locs + _flatten(loc) - return locs diff --git a/Lib/aifc.py b/Lib/aifc.py deleted file mode 100644 index 54f0cfd711..0000000000 --- a/Lib/aifc.py +++ /dev/null @@ -1,1015 +0,0 @@ -# Stuff to parse AIFF-C and AIFF files. -# -# Unless explicitly stated otherwise, the description below is true -# both for AIFF-C files and AIFF files. -# -# An AIFF-C file has the following structure. -# -# +-----------------+ -# | FORM | -# +-----------------+ -# | <size> | -# +----+------------+ -# | | AIFC | -# | +------------+ -# | | <chunks> | -# | | . | -# | | . | -# | | . | -# +----+------------+ -# -# An AIFF file has the string "AIFF" instead of "AIFC". -# -# A chunk consists of an identifier (4 bytes) followed by a size (4 bytes, -# big endian order), followed by the data. The size field does not include -# the size of the 8 byte header. -# -# The following chunk types are recognized. -# -# FVER -# <version number of AIFF-C defining document> (AIFF-C only). -# MARK -# <# of markers> (2 bytes) -# list of markers: -# <marker ID> (2 bytes, must be > 0) -# <position> (4 bytes) -# <marker name> ("pstring") -# COMM -# <# of channels> (2 bytes) -# <# of sound frames> (4 bytes) -# <size of the samples> (2 bytes) -# <sampling frequency> (10 bytes, IEEE 80-bit extended -# floating point) -# in AIFF-C files only: -# <compression type> (4 bytes) -# <human-readable version of compression type> ("pstring") -# SSND -# <offset> (4 bytes, not used by this program) -# <blocksize> (4 bytes, not used by this program) -# <sound data> -# -# A pstring consists of 1 byte length, a string of characters, and 0 or 1 -# byte pad to make the total length even. -# -# Usage. -# -# Reading AIFF files: -# f = aifc.open(file, 'r') -# where file is either the name of a file or an open file pointer. -# The open file pointer must have methods read(), seek(), and close(). -# In some types of audio files, if the setpos() method is not used, -# the seek() method is not necessary. -# -# This returns an instance of a class with the following public methods: -# getnchannels() -- returns number of audio channels (1 for -# mono, 2 for stereo) -# getsampwidth() -- returns sample width in bytes -# getframerate() -- returns sampling frequency -# getnframes() -- returns number of audio frames -# getcomptype() -- returns compression type ('NONE' for AIFF files) -# getcompname() -- returns human-readable version of -# compression type ('not compressed' for AIFF files) -# getparams() -- returns a tuple consisting of all of the -# above in the above order -# getmarkers() -- get the list of marks in the audio file or None -# if there are no marks -# getmark(id) -- get mark with the specified id (raises an error -# if the mark does not exist) -# readframes(n) -- returns at most n frames of audio -# rewind() -- rewind to the beginning of the audio stream -# setpos(pos) -- seek to the specified position -# tell() -- return the current position -# close() -- close the instance (make it unusable) -# The position returned by tell(), the position given to setpos() and -# the position of marks are all compatible and have nothing to do with -# the actual postion in the file. -# The close() method is called automatically when the class instance -# is destroyed. -# -# Writing AIFF files: -# f = aifc.open(file, 'w') -# where file is either the name of a file or an open file pointer. -# The open file pointer must have methods write(), tell(), seek(), and -# close(). -# -# This returns an instance of a class with the following public methods: -# aiff() -- create an AIFF file (AIFF-C default) -# aifc() -- create an AIFF-C file -# setnchannels(n) -- set the number of channels -# setsampwidth(n) -- set the sample width -# setframerate(n) -- set the frame rate -# setnframes(n) -- set the number of frames -# setcomptype(type, name) -# -- set the compression type and the -# human-readable compression type -# setparams(nchannels, sampwidth, framerate, nframes, comptype, compname) -# -- set all parameters at once -# setmark(id, pos, name) -# -- add specified mark to the list of marks -# tell() -- return current position in output file (useful -# in combination with setmark()) -# writeframesraw(data) -# -- write audio frames without pathing up the -# file header -# writeframes(data) -# -- write audio frames and patch up the file header -# close() -- patch up the file header and close the -# output file -# You should set the parameters before the first writeframesraw or -# writeframes. The total number of frames does not need to be set, -# but when it is set to the correct value, the header does not have to -# be patched up. -# It is best to first set all parameters, perhaps possibly the -# compression type, and then write audio frames using writeframesraw. -# When all frames have been written, either call writeframes('') or -# close() to patch up the sizes in the header. -# Marks can be added anytime. If there are any marks, ypu must call -# close() after all frames have been written. -# The close() method is called automatically when the class instance -# is destroyed. -# -# When a file is opened with the extension '.aiff', an AIFF file is -# written, otherwise an AIFF-C file is written. This default can be -# changed by calling aiff() or aifc() before the first writeframes or -# writeframesraw. - -import __builtin__ -try: - import CL -except ImportError: - pass - -Error = 'aifc.Error' - -_AIFC_version = 0xA2805140 # Version 1 of AIFF-C - -_skiplist = 'COMT', 'INST', 'MIDI', 'AESD', \ - 'APPL', 'NAME', 'AUTH', '(c) ', 'ANNO' - -def _read_long(file): - x = 0L - for i in range(4): - byte = file.read(1) - if byte == '': - raise EOFError - x = x*256 + ord(byte) - if x >= 0x80000000L: - x = x - 0x100000000L - return int(x) - -def _read_ulong(file): - x = 0L - for i in range(4): - byte = file.read(1) - if byte == '': - raise EOFError - x = x*256 + ord(byte) - return x - -def _read_short(file): - x = 0 - for i in range(2): - byte = file.read(1) - if byte == '': - raise EOFError - x = x*256 + ord(byte) - if x >= 0x8000: - x = x - 0x10000 - return x - -def _read_string(file): - length = ord(file.read(1)) - if length == 0: - data = '' - else: - data = file.read(length) - if length & 1 == 0: - dummy = file.read(1) - return data - -_HUGE_VAL = 1.79769313486231e+308 # See <limits.h> - -def _read_float(f): # 10 bytes - import math - expon = _read_short(f) # 2 bytes - sign = 1 - if expon < 0: - sign = -1 - expon = expon + 0x8000 - himant = _read_ulong(f) # 4 bytes - lomant = _read_ulong(f) # 4 bytes - if expon == himant == lomant == 0: - f = 0.0 - elif expon == 0x7FFF: - f = _HUGE_VAL - else: - expon = expon - 16383 - f = (himant * 0x100000000L + lomant) * pow(2.0, expon - 63) - return sign * f - -def _write_short(f, x): - d, m = divmod(x, 256) - f.write(chr(d)) - f.write(chr(m)) - -def _write_long(f, x): - if x < 0: - x = x + 0x100000000L - data = [] - for i in range(4): - d, m = divmod(x, 256) - data.insert(0, m) - x = d - for i in range(4): - f.write(chr(int(data[i]))) - -def _write_string(f, s): - f.write(chr(len(s))) - f.write(s) - if len(s) & 1 == 0: - f.write(chr(0)) - -def _write_float(f, x): - import math - if x < 0: - sign = 0x8000 - x = x * -1 - else: - sign = 0 - if x == 0: - expon = 0 - himant = 0 - lomant = 0 - else: - fmant, expon = math.frexp(x) - if expon > 16384 or fmant >= 1: # Infinity or NaN - expon = sign|0x7FFF - himant = 0 - lomant = 0 - else: # Finite - expon = expon + 16382 - if expon < 0: # denormalized - fmant = math.ldexp(fmant, expon) - expon = 0 - expon = expon | sign - fmant = math.ldexp(fmant, 32) - fsmant = math.floor(fmant) - himant = long(fsmant) - fmant = math.ldexp(fmant - fsmant, 32) - fsmant = math.floor(fmant) - lomant = long(fsmant) - _write_short(f, expon) - _write_long(f, himant) - _write_long(f, lomant) - -class Chunk: - def __init__(self, file): - self.file = file - self.chunkname = self.file.read(4) - if len(self.chunkname) < 4: - raise EOFError - self.chunksize = _read_long(self.file) - self.size_read = 0 - self.offset = self.file.tell() - - def rewind(self): - self.file.seek(self.offset, 0) - self.size_read = 0 - - def setpos(self, pos): - if pos < 0 or pos > self.chunksize: - raise RuntimeError - self.file.seek(self.offset + pos, 0) - self.size_read = pos - - def read(self, length): - if self.size_read >= self.chunksize: - return '' - if length > self.chunksize - self.size_read: - length = self.chunksize - self.size_read - data = self.file.read(length) - self.size_read = self.size_read + len(data) - return data - - def skip(self): - try: - self.file.seek(self.chunksize - self.size_read, 1) - except RuntimeError: - while self.size_read < self.chunksize: - dummy = self.read(8192) - if not dummy: - raise EOFError - if self.chunksize & 1: - dummy = self.read(1) - -class Aifc_read: - # Variables used in this class: - # - # These variables are available to the user though appropriate - # methods of this class: - # _file -- the open file with methods read(), close(), and seek() - # set through the __init__() method - # _nchannels -- the number of audio channels - # available through the getnchannels() method - # _nframes -- the number of audio frames - # available through the getnframes() method - # _sampwidth -- the number of bytes per audio sample - # available through the getsampwidth() method - # _framerate -- the sampling frequency - # available through the getframerate() method - # _comptype -- the AIFF-C compression type ('NONE' if AIFF) - # available through the getcomptype() method - # _compname -- the human-readable AIFF-C compression type - # available through the getcomptype() method - # _markers -- the marks in the audio file - # available through the getmarkers() and getmark() - # methods - # _soundpos -- the position in the audio stream - # available through the tell() method, set through the - # setpos() method - # - # These variables are used internally only: - # _version -- the AIFF-C version number - # _decomp -- the decompressor from builtin module cl - # _comm_chunk_read -- 1 iff the COMM chunk has been read - # _aifc -- 1 iff reading an AIFF-C file - # _ssnd_seek_needed -- 1 iff positioned correctly in audio - # file for readframes() - # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk - # _framesize -- size of one frame in the file - - if 0: access _file, _nchannels, _nframes, _sampwidth, _framerate, \ - _comptype, _compname, _markers, _soundpos, _version, \ - _decomp, _comm_chunk_read, __aifc, _ssnd_seek_needed, \ - _ssnd_chunk, _framesize: private - - def initfp(self, file): - self._file = file - self._version = 0 - self._decomp = None - self._convert = None - self._markers = [] - self._soundpos = 0 - form = self._file.read(4) - if form != 'FORM': - raise Error, 'file does not start with FORM id' - formlength = _read_long(self._file) - if formlength <= 0: - raise Error, 'invalid FORM chunk data size' - formdata = self._file.read(4) - formlength = formlength - 4 - if formdata == 'AIFF': - self._aifc = 0 - elif formdata == 'AIFC': - self._aifc = 1 - else: - raise Error, 'not an AIFF or AIFF-C file' - self._comm_chunk_read = 0 - while formlength > 0: - self._ssnd_seek_needed = 1 - #DEBUG: SGI's soundfiler has a bug. There should - # be no need to check for EOF here. - try: - chunk = Chunk(self._file) - except EOFError: - if formlength == 8: - print 'Warning: FORM chunk size too large' - formlength = 0 - break - raise EOFError # different error, raise exception - if chunk.chunkname == 'COMM': - self._read_comm_chunk(chunk) - self._comm_chunk_read = 1 - elif chunk.chunkname == 'SSND': - self._ssnd_chunk = chunk - dummy = chunk.read(8) - self._ssnd_seek_needed = 0 - elif chunk.chunkname == 'FVER': - self._version = _read_long(chunk) - elif chunk.chunkname == 'MARK': - self._readmark(chunk) - elif chunk.chunkname in _skiplist: - pass - else: - raise Error, 'unrecognized chunk type '+chunk.chunkname - formlength = formlength - 8 - chunk.chunksize - if chunk.chunksize & 1: - formlength = formlength - 1 - if formlength > 0: - chunk.skip() - if not self._comm_chunk_read or not self._ssnd_chunk: - raise Error, 'COMM chunk and/or SSND chunk missing' - if self._aifc and self._decomp: - params = [CL.ORIGINAL_FORMAT, 0, - CL.BITS_PER_COMPONENT, self._sampwidth * 8, - CL.FRAME_RATE, self._framerate] - if self._nchannels == 1: - params[1] = CL.MONO - elif self._nchannels == 2: - params[1] = CL.STEREO_INTERLEAVED - else: - raise Error, 'cannot compress more than 2 channels' - self._decomp.SetParams(params) - - def __init__(self, f): - if type(f) == type(''): - f = __builtin__.open(f, 'rb') - # else, assume it is an open file object already - self.initfp(f) - - def __del__(self): - if self._file: - self.close() - - # - # User visible methods. - # - def getfp(self): - return self._file - - def rewind(self): - self._ssnd_seek_needed = 1 - self._soundpos = 0 - - def close(self): - if self._decomp: - self._decomp.CloseDecompressor() - self._decomp = None - self._file = None - - def tell(self): - return self._soundpos - - def getnchannels(self): - return self._nchannels - - def getnframes(self): - return self._nframes - - def getsampwidth(self): - return self._sampwidth - - def getframerate(self): - return self._framerate - - def getcomptype(self): - return self._comptype - - def getcompname(self): - return self._compname - -## def getversion(self): -## return self._version - - def getparams(self): - return self.getnchannels(), self.getsampwidth(), \ - self.getframerate(), self.getnframes(), \ - self.getcomptype(), self.getcompname() - - def getmarkers(self): - if len(self._markers) == 0: - return None - return self._markers - - def getmark(self, id): - for marker in self._markers: - if id == marker[0]: - return marker - raise Error, 'marker ' + `id` + ' does not exist' - - def setpos(self, pos): - if pos < 0 or pos > self._nframes: - raise Error, 'position not in range' - self._soundpos = pos - self._ssnd_seek_needed = 1 - - def readframes(self, nframes): - if self._ssnd_seek_needed: - self._ssnd_chunk.rewind() - dummy = self._ssnd_chunk.read(8) - pos = self._soundpos * self._framesize - if pos: - self._ssnd_chunk.setpos(pos + 8) - self._ssnd_seek_needed = 0 - if nframes == 0: - return '' - data = self._ssnd_chunk.read(nframes * self._framesize) - if self._convert and data: - data = self._convert(data) - self._soundpos = self._soundpos + len(data) / (self._nchannels * self._sampwidth) - return data - - # - # Internal methods. - # - if 0: access *: private - - def _decomp_data(self, data): - dummy = self._decomp.SetParam(CL.FRAME_BUFFER_SIZE, - len(data) * 2) - return self._decomp.Decompress(len(data) / self._nchannels, - data) - - def _ulaw2lin(self, data): - import audioop - return audioop.ulaw2lin(data, 2) - - def _adpcm2lin(self, data): - import audioop - if not hasattr(self, '_adpcmstate'): - # first time - self._adpcmstate = None - data, self._adpcmstate = audioop.adpcm2lin(data, 2, - self._adpcmstate) - return data - - def _read_comm_chunk(self, chunk): - self._nchannels = _read_short(chunk) - self._nframes = _read_long(chunk) - self._sampwidth = (_read_short(chunk) + 7) / 8 - self._framerate = int(_read_float(chunk)) - self._framesize = self._nchannels * self._sampwidth - if self._aifc: - #DEBUG: SGI's soundeditor produces a bad size :-( - kludge = 0 - if chunk.chunksize == 18: - kludge = 1 - print 'Warning: bad COMM chunk size' - chunk.chunksize = 23 - #DEBUG end - self._comptype = chunk.read(4) - #DEBUG start - if kludge: - length = ord(chunk.file.read(1)) - if length & 1 == 0: - length = length + 1 - chunk.chunksize = chunk.chunksize + length - chunk.file.seek(-1, 1) - #DEBUG end - self._compname = _read_string(chunk) - if self._comptype != 'NONE': - if self._comptype == 'G722': - try: - import audioop - except ImportError: - pass - else: - self._convert = self._adpcm2lin - self._framesize = self._framesize / 4 - return - # for ULAW and ALAW try Compression Library - try: - import cl, CL - except ImportError: - if self._comptype == 'ULAW': - try: - import audioop - self._convert = self._ulaw2lin - self._framesize = self._framesize / 2 - return - except ImportError: - pass - raise Error, 'cannot read compressed AIFF-C files' - if self._comptype == 'ULAW': - scheme = CL.G711_ULAW - self._framesize = self._framesize / 2 - elif self._comptype == 'ALAW': - scheme = CL.G711_ALAW - self._framesize = self._framesize / 2 - else: - raise Error, 'unsupported compression type' - self._decomp = cl.OpenDecompressor(scheme) - self._convert = self._decomp_data - else: - self._comptype = 'NONE' - self._compname = 'not compressed' - - def _readmark(self, chunk): - nmarkers = _read_short(chunk) - # Some files appear to contain invalid counts. - # Cope with this by testing for EOF. - try: - for i in range(nmarkers): - id = _read_short(chunk) - pos = _read_long(chunk) - name = _read_string(chunk) - if pos or name: - # some files appear to have - # dummy markers consisting of - # a position 0 and name '' - self._markers.append((id, pos, name)) - except EOFError: - print 'Warning: MARK chunk contains only', - print len(self._markers), - if len(self._markers) == 1: print 'marker', - else: print 'markers', - print 'instead of', nmarkers - -class Aifc_write: - # Variables used in this class: - # - # These variables are user settable through appropriate methods - # of this class: - # _file -- the open file with methods write(), close(), tell(), seek() - # set through the __init__() method - # _comptype -- the AIFF-C compression type ('NONE' in AIFF) - # set through the setcomptype() or setparams() method - # _compname -- the human-readable AIFF-C compression type - # set through the setcomptype() or setparams() method - # _nchannels -- the number of audio channels - # set through the setnchannels() or setparams() method - # _sampwidth -- the number of bytes per audio sample - # set through the setsampwidth() or setparams() method - # _framerate -- the sampling frequency - # set through the setframerate() or setparams() method - # _nframes -- the number of audio frames written to the header - # set through the setnframes() or setparams() method - # _aifc -- whether we're writing an AIFF-C file or an AIFF file - # set through the aifc() method, reset through the - # aiff() method - # - # These variables are used internally only: - # _version -- the AIFF-C version number - # _comp -- the compressor from builtin module cl - # _nframeswritten -- the number of audio frames actually written - # _datalength -- the size of the audio samples written to the header - # _datawritten -- the size of the audio samples actually written - - if 0: access _file, _comptype, _compname, _nchannels, _sampwidth, \ - _framerate, _nframes, _aifc, _version, _comp, \ - _nframeswritten, _datalength, _datawritten: private - - def __init__(self, f): - if type(f) == type(''): - filename = f - f = __builtin__.open(f, 'wb') - else: - # else, assume it is an open file object already - filename = '???' - self.initfp(f) - if filename[-5:] == '.aiff': - self._aifc = 0 - else: - self._aifc = 1 - - def initfp(self, file): - self._file = file - self._version = _AIFC_version - self._comptype = 'NONE' - self._compname = 'not compressed' - self._comp = None - self._convert = None - self._nchannels = 0 - self._sampwidth = 0 - self._framerate = 0 - self._nframes = 0 - self._nframeswritten = 0 - self._datawritten = 0 - self._datalength = 0 - self._markers = [] - self._marklength = 0 - self._aifc = 1 # AIFF-C is default - - def __del__(self): - if self._file: - self.close() - - # - # User visible methods. - # - def aiff(self): - if self._nframeswritten: - raise Error, 'cannot change parameters after starting to write' - self._aifc = 0 - - def aifc(self): - if self._nframeswritten: - raise Error, 'cannot change parameters after starting to write' - self._aifc = 1 - - def setnchannels(self, nchannels): - if self._nframeswritten: - raise Error, 'cannot change parameters after starting to write' - if nchannels < 1: - raise Error, 'bad # of channels' - self._nchannels = nchannels - - def getnchannels(self): - if not self._nchannels: - raise Error, 'number of channels not set' - return self._nchannels - - def setsampwidth(self, sampwidth): - if self._nframeswritten: - raise Error, 'cannot change parameters after starting to write' - if sampwidth < 1 or sampwidth > 4: - raise Error, 'bad sample width' - self._sampwidth = sampwidth - - def getsampwidth(self): - if not self._sampwidth: - raise Error, 'sample width not set' - return self._sampwidth - - def setframerate(self, framerate): - if self._nframeswritten: - raise Error, 'cannot change parameters after starting to write' - if framerate <= 0: - raise Error, 'bad frame rate' - self._framerate = framerate - - def getframerate(self): - if not self._framerate: - raise Error, 'frame rate not set' - return self._framerate - - def setnframes(self, nframes): - if self._nframeswritten: - raise Error, 'cannot change parameters after starting to write' - self._nframes = nframes - - def getnframes(self): - return self._nframeswritten - - def setcomptype(self, comptype, compname): - if self._nframeswritten: - raise Error, 'cannot change parameters after starting to write' - if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'): - raise Error, 'unsupported compression type' - self._comptype = comptype - self._compname = compname - - def getcomptype(self): - return self._comptype - - def getcompname(self): - return self._compname - -## def setversion(self, version): -## if self._nframeswritten: -## raise Error, 'cannot change parameters after starting to write' -## self._version = version - - def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)): - if self._nframeswritten: - raise Error, 'cannot change parameters after starting to write' - if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'): - raise Error, 'unsupported compression type' - self.setnchannels(nchannels) - self.setsampwidth(sampwidth) - self.setframerate(framerate) - self.setnframes(nframes) - self.setcomptype(comptype, compname) - - def getparams(self): - if not self._nchannels or not self._sampwidth or not self._framerate: - raise Error, 'not all parameters set' - return self._nchannels, self._sampwidth, self._framerate, \ - self._nframes, self._comptype, self._compname - - def setmark(self, id, pos, name): - if id <= 0: - raise Error, 'marker ID must be > 0' - if pos < 0: - raise Error, 'marker position must be >= 0' - if type(name) != type(''): - raise Error, 'marker name must be a string' - for i in range(len(self._markers)): - if id == self._markers[i][0]: - self._markers[i] = id, pos, name - return - self._markers.append((id, pos, name)) - - def getmark(self, id): - for marker in self._markers: - if id == marker[0]: - return marker - raise Error, 'marker ' + `id` + ' does not exist' - - def getmarkers(self): - if len(self._markers) == 0: - return None - return self._markers - - def tell(self): - return self._nframeswritten - - def writeframesraw(self, data): - self._ensure_header_written(len(data)) - nframes = len(data) / (self._sampwidth * self._nchannels) - if self._convert: - data = self._convert(data) - self._file.write(data) - self._nframeswritten = self._nframeswritten + nframes - self._datawritten = self._datawritten + len(data) - - def writeframes(self, data): - self.writeframesraw(data) - if self._nframeswritten != self._nframes or \ - self._datalength != self._datawritten: - self._patchheader() - - def close(self): - self._ensure_header_written(0) - if self._datawritten & 1: - # quick pad to even size - self._file.write(chr(0)) - self._datawritten = self._datawritten + 1 - self._writemarkers() - if self._nframeswritten != self._nframes or \ - self._datalength != self._datawritten or \ - self._marklength: - self._patchheader() - if self._comp: - self._comp.CloseCompressor() - self._comp = None - self._file.flush() - self._file = None - - # - # Internal methods. - # - if 0: access *: private - - def _comp_data(self, data): - dum = self._comp.SetParam(CL.FRAME_BUFFER_SIZE, len(data)) - dum = self._comp.SetParam(CL.COMPRESSED_BUFFER_SIZE, len(data)) - return self._comp.Compress(nframes, data) - - def _lin2ulaw(self, data): - import audioop - return audioop.lin2ulaw(data, 2) - - def _lin2adpcm(self, data): - import audioop - if not hasattr(self, '_adpcmstate'): - self._adpcmstate = None - data, self._adpcmstate = audioop.lin2adpcm(data, 2, - self._adpcmstate) - return data - - def _ensure_header_written(self, datasize): - if not self._nframeswritten: - if self._comptype in ('ULAW', 'ALAW'): - if not self._sampwidth: - self._sampwidth = 2 - if self._sampwidth != 2: - raise Error, 'sample width must be 2 when compressing with ULAW or ALAW' - if self._comptype == 'G722': - if not self._sampwidth: - self._sampwidth = 2 - if self._sampwidth != 2: - raise Error, 'sample width must be 2 when compressing with G7.22 (ADPCM)' - if not self._nchannels: - raise Error, '# channels not specified' - if not self._sampwidth: - raise Error, 'sample width not specified' - if not self._framerate: - raise Error, 'sampling rate not specified' - self._write_header(datasize) - - def _init_compression(self): - if self._comptype == 'G722': - import audioop - self._convert = self._lin2adpcm - return - try: - import cl, CL - except ImportError: - if self._comptype == 'ULAW': - try: - import audioop - self._convert = self._lin2ulaw - return - except ImportError: - pass - raise Error, 'cannot write compressed AIFF-C files' - if self._comptype == 'ULAW': - scheme = CL.G711_ULAW - elif self._comptype == 'ALAW': - scheme = CL.G711_ALAW - else: - raise Error, 'unsupported compression type' - self._comp = cl.OpenCompressor(scheme) - params = [CL.ORIGINAL_FORMAT, 0, - CL.BITS_PER_COMPONENT, self._sampwidth * 8, - CL.FRAME_RATE, self._framerate, - CL.FRAME_BUFFER_SIZE, 100, - CL.COMPRESSED_BUFFER_SIZE, 100] - if self._nchannels == 1: - params[1] = CL.MONO - elif self._nchannels == 2: - params[1] = CL.STEREO_INTERLEAVED - else: - raise Error, 'cannot compress more than 2 channels' - self._comp.SetParams(params) - # the compressor produces a header which we ignore - dummy = self._comp.Compress(0, '') - self._convert = self._comp_data - - def _write_header(self, initlength): - if self._aifc and self._comptype != 'NONE': - self._init_compression() - self._file.write('FORM') - if not self._nframes: - self._nframes = initlength / (self._nchannels * self._sampwidth) - self._datalength = self._nframes * self._nchannels * self._sampwidth - if self._datalength & 1: - self._datalength = self._datalength + 1 - if self._aifc: - if self._comptype in ('ULAW', 'ALAW'): - self._datalength = self._datalength / 2 - if self._datalength & 1: - self._datalength = self._datalength + 1 - elif self._comptype == 'G722': - self._datalength = (self._datalength + 3) / 4 - if self._datalength & 1: - self._datalength = self._datalength + 1 - self._form_length_pos = self._file.tell() - commlength = self._write_form_length(self._datalength) - if self._aifc: - self._file.write('AIFC') - self._file.write('FVER') - _write_long(self._file, 4) - _write_long(self._file, self._version) - else: - self._file.write('AIFF') - self._file.write('COMM') - _write_long(self._file, commlength) - _write_short(self._file, self._nchannels) - self._nframes_pos = self._file.tell() - _write_long(self._file, self._nframes) - _write_short(self._file, self._sampwidth * 8) - _write_float(self._file, self._framerate) - if self._aifc: - self._file.write(self._comptype) - _write_string(self._file, self._compname) - self._file.write('SSND') - self._ssnd_length_pos = self._file.tell() - _write_long(self._file, self._datalength + 8) - _write_long(self._file, 0) - _write_long(self._file, 0) - - def _write_form_length(self, datalength): - if self._aifc: - commlength = 18 + 5 + len(self._compname) - if commlength & 1: - commlength = commlength + 1 - verslength = 12 - else: - commlength = 18 - verslength = 0 - _write_long(self._file, 4 + verslength + self._marklength + \ - 8 + commlength + 16 + datalength) - return commlength - - def _patchheader(self): - curpos = self._file.tell() - if self._datawritten & 1: - datalength = self._datawritten + 1 - self._file.write(chr(0)) - else: - datalength = self._datawritten - if datalength == self._datalength and \ - self._nframes == self._nframeswritten and \ - self._marklength == 0: - self._file.seek(curpos, 0) - return - self._file.seek(self._form_length_pos, 0) - dummy = self._write_form_length(datalength) - self._file.seek(self._nframes_pos, 0) - _write_long(self._file, self._nframeswritten) - self._file.seek(self._ssnd_length_pos, 0) - _write_long(self._file, datalength + 8) - self._file.seek(curpos, 0) - self._nframes = self._nframeswritten - self._datalength = datalength - - def _writemarkers(self): - if len(self._markers) == 0: - return - self._file.write('MARK') - length = 2 - for marker in self._markers: - id, pos, name = marker - length = length + len(name) + 1 + 6 - if len(name) & 1 == 0: - length = length + 1 - _write_long(self._file, length) - self._marklength = length + 8 - _write_short(self._file, len(self._markers)) - for marker in self._markers: - id, pos, name = marker - _write_short(self._file, id) - _write_long(self._file, pos) - _write_string(self._file, name) - -def open(f, mode): - if mode == 'r': - return Aifc_read(f) - elif mode == 'w': - return Aifc_write(f) - else: - raise Error, "mode must be 'r' or 'w'" - -openfp = open # B/W compatibility diff --git a/Lib/anydbm.py b/Lib/anydbm.py deleted file mode 100644 index 2dc312d5fd..0000000000 --- a/Lib/anydbm.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Generic interface to all dbm clones. - -Instead of - - import dbm - d = dbm.open(file, 'w', 0666) - -use - - import anydbm - d = anydbm.open(file) - -The returned object is a dbhash, gdbm, dbm or dumbdbm object, -dependent on availability of the modules (tested in this order). - -It has the following interface (key and data are strings): - - d[key] = data # store data at key (may override data at - # existing key) - data = d[key] # retrieve data at key (raise KeyError if no - # such key) - del d[key] # delete data stored at key (raises KeyError - # if no such key) - flag = d.has_key(key) # true if the key exists - list = d.keys() # return a list of all existing keys (slow!) - -Future versions may change the order in which implementations are -tested for existence, add interfaces to other dbm-like -implementations, and (in the presence of multiple implementations) -decide which module to use based upon the extension or contents of an -existing database file. - -The open function has an optional second argument. This can be set to -'r' to open the database for reading only. The default is 'r', like -the dbm default. - -""" - -_names = ['dbhash', 'gdbm', 'dbm', 'dumbdbm'] - -for _name in _names: - try: - exec "import %s; _mod = %s" % (_name, _name) - except ImportError: - continue - else: - break -else: - raise ImportError, "no dbm clone found; tried %s" % _names - -error = _mod.error - -def open(file, flag = 'r', mode = 0666): - return _mod.open(file, flag, mode) diff --git a/Lib/audiodev.py b/Lib/audiodev.py deleted file mode 100644 index fcfae168e1..0000000000 --- a/Lib/audiodev.py +++ /dev/null @@ -1,244 +0,0 @@ -error = 'audiodev.error' - -class Play_Audio_sgi: - # Private instance variables - if 0: access frameratelist, nchannelslist, sampwidthlist, oldparams, \ - params, config, inited_outrate, inited_width, \ - inited_nchannels, port, converter, classinited: private - - classinited = 0 - frameratelist = nchannelslist = sampwidthlist = None - - def initclass(self): - import AL - self.frameratelist = [ - (48000, AL.RATE_48000), - (44100, AL.RATE_44100), - (32000, AL.RATE_32000), - (22050, AL.RATE_22050), - (16000, AL.RATE_16000), - (11025, AL.RATE_11025), - ( 8000, AL.RATE_8000), - ] - self.nchannelslist = [ - (1, AL.MONO), - (2, AL.STEREO), - ] - self.sampwidthlist = [ - (1, AL.SAMPLE_8), - (2, AL.SAMPLE_16), - (3, AL.SAMPLE_24), - ] - self.classinited = 1 - - def __init__(self): - import al, AL - if not self.classinited: - self.initclass() - self.oldparams = [] - self.params = [AL.OUTPUT_RATE, 0] - self.config = al.newconfig() - self.inited_outrate = 0 - self.inited_width = 0 - self.inited_nchannels = 0 - self.converter = None - self.port = None - return - - def __del__(self): - if self.port: - self.stop() - if self.oldparams: - import al, AL - al.setparams(AL.DEFAULT_DEVICE, self.oldparams) - self.oldparams = [] - - def wait(self): - if not self.port: - return - import time - while self.port.getfilled() > 0: - time.sleep(0.1) - self.stop() - - def stop(self): - if self.port: - self.port.closeport() - self.port = None - if self.oldparams: - import al, AL - al.setparams(AL.DEFAULT_DEVICE, self.oldparams) - self.oldparams = [] - - def setoutrate(self, rate): - for (raw, cooked) in self.frameratelist: - if rate == raw: - self.params[1] = cooked - self.inited_outrate = 1 - break - else: - raise error, 'bad output rate' - - def setsampwidth(self, width): - for (raw, cooked) in self.sampwidthlist: - if width == raw: - self.config.setwidth(cooked) - self.inited_width = 1 - break - else: - if width == 0: - import AL - self.inited_width = 0 - self.config.setwidth(AL.SAMPLE_16) - self.converter = self.ulaw2lin - else: - raise error, 'bad sample width' - - def setnchannels(self, nchannels): - for (raw, cooked) in self.nchannelslist: - if nchannels == raw: - self.config.setchannels(cooked) - self.inited_nchannels = 1 - break - else: - raise error, 'bad # of channels' - - def writeframes(self, data): - if not (self.inited_outrate and self.inited_nchannels): - raise error, 'params not specified' - if not self.port: - import al, AL - self.port = al.openport('Python', 'w', self.config) - self.oldparams = self.params[:] - al.getparams(AL.DEFAULT_DEVICE, self.oldparams) - al.setparams(AL.DEFAULT_DEVICE, self.params) - if self.converter: - data = self.converter(data) - self.port.writesamps(data) - - def getfilled(self): - if self.port: - return self.port.getfilled() - else: - return 0 - - def getfillable(self): - if self.port: - return self.port.getfillable() - else: - return self.config.getqueuesize() - - # private methods - if 0: access *: private - - def ulaw2lin(self, data): - import audioop - return audioop.ulaw2lin(data, 2) - -class Play_Audio_sun: - if 0: access outrate, sampwidth, nchannels, inited_outrate, inited_width, \ - inited_nchannels, converter: private - - def __init__(self): - self.outrate = 0 - self.sampwidth = 0 - self.nchannels = 0 - self.inited_outrate = 0 - self.inited_width = 0 - self.inited_nchannels = 0 - self.converter = None - self.port = None - return - - def __del__(self): - self.stop() - - def setoutrate(self, rate): - self.outrate = rate - self.inited_outrate = 1 - - def setsampwidth(self, width): - self.sampwidth = width - self.inited_width = 1 - - def setnchannels(self, nchannels): - self.nchannels = nchannels - self.inited_nchannels = 1 - - def writeframes(self, data): - if not (self.inited_outrate and self.inited_width and self.inited_nchannels): - raise error, 'params not specified' - if not self.port: - import sunaudiodev, SUNAUDIODEV - self.port = sunaudiodev.open('w') - info = self.port.getinfo() - info.o_sample_rate = self.outrate - info.o_channels = self.nchannels - if self.sampwidth == 0: - info.o_precision = 8 - self.o_encoding = SUNAUDIODEV.ENCODING_ULAW - # XXX Hack, hack -- leave defaults - else: - info.o_precision = 8 * self.sampwidth - info.o_encoding = SUNAUDIODEV.ENCODING_LINEAR - self.port.setinfo(info) - if self.converter: - data = self.converter(data) - self.port.write(data) - - def wait(self): - if not self.port: - return - self.port.drain() - self.stop() - - def stop(self): - if self.port: - self.port.flush() - self.port.close() - self.port = None - - def getfilled(self): - if self.port: - return self.port.obufcount() - else: - return 0 - - def getfillable(self): - return BUFFERSIZE - self.getfilled() - -def AudioDev(): - try: - import al - except ImportError: - try: - import sunaudiodev - return Play_Audio_sun() - except ImportError: - try: - import Audio_mac - except ImportError: - raise error, 'no audio device' - else: - return Audio_mac.Play_Audio_mac() - else: - return Play_Audio_sgi() - -def test(fn = 'f:just samples:just.aif'): - import aifc - af = aifc.open(fn, 'r') - print fn, af.getparams() - p = AudioDev() - p.setoutrate(af.getframerate()) - p.setsampwidth(af.getsampwidth()) - p.setnchannels(af.getnchannels()) - BUFSIZ = af.getframerate()/af.getsampwidth()/af.getnchannels() - while 1: - data = af.readframes(BUFSIZ) - if not data: break - print len(data) - p.writeframes(data) - p.wait() - -if __name__ == '__main__': - test() diff --git a/Lib/base64.py b/Lib/base64.py deleted file mode 100755 index c5a7ca7586..0000000000 --- a/Lib/base64.py +++ /dev/null @@ -1,78 +0,0 @@ -# Conversions to/from base64 transport encoding as per RFC-MIME (Dec 1991 -# version). - -# Parameters set by RFX-XXXX. -# -# Modified 04-Oct-95 by Jack to use binascii module - -import binascii - -MAXLINESIZE = 76 # Excluding the CRLF -MAXBINSIZE = (MAXLINESIZE/4)*3 - -# Encode a file. -def encode(input, output): - while 1: - s = input.read(MAXBINSIZE) - if not s: break - while len(s) < MAXBINSIZE: - ns = input.read(MAXBINSIZE-len(s)) - if not ns: break - s = s + ns - line = binascii.b2a_base64(s) - output.write(line) - -# Decode a file. -def decode(input, output): - while 1: - line = input.readline() - if not line: break - s = binascii.a2b_base64(line) - output.write(s) - -def encodestring(s): - import StringIO - f = StringIO.StringIO(s) - g = StringIO.StringIO() - encode(f, g) - return g.getvalue() - -def decodestring(s): - import StringIO - f = StringIO.StringIO(s) - g = StringIO.StringIO() - decode(f, g) - return g.getvalue() - -# Small test program -def test(): - import sys, getopt - try: - opts, args = getopt.getopt(sys.argv[1:], 'deut') - except getopt.error, msg: - sys.stdout = sys.stderr - print msg - print """usage: basd64 [-d] [-e] [-u] [-t] [file|-] - -d, -u: decode - -e: encode (default) - -t: decode string 'Aladdin:open sesame'""" - sys.exit(2) - func = encode - for o, a in opts: - if o == '-e': func = encode - if o == '-d': func = decode - if o == '-u': func = decode - if o == '-t': test1(); return - if args and args[0] != '-': - func(open(args[0]), sys.stdout) - else: - func(sys.stdin, sys.stdout) - -def test1(): - s0 = "Aladdin:open sesame" - s1 = encodestring(s0) - s2 = decodestring(s1) - print s0, `s1`, s2 - -if __name__ == '__main__': - test() diff --git a/Lib/bdb.py b/Lib/bdb.py deleted file mode 100644 index 6d0536db69..0000000000 --- a/Lib/bdb.py +++ /dev/null @@ -1,362 +0,0 @@ -# A generic Python debugger base class. -# This class takes care of details of the trace facility; -# a derived class should implement user interaction. -# There are two debuggers based upon this: -# 'pdb', a text-oriented debugger not unlike dbx or gdb; -# and 'wdb', a window-oriented debugger. -# And of course... you can roll your own! - -import sys - -BdbQuit = 'bdb.BdbQuit' # Exception to give up completely - - -class Bdb: # Basic Debugger - - def __init__(self): - self.breaks = {} - - def reset(self): - import linecache - linecache.checkcache() - self.botframe = None - self.stopframe = None - self.returnframe = None - self.quitting = 0 - - def trace_dispatch(self, frame, event, arg): - if self.quitting: - return # None - if event == 'line': - return self.dispatch_line(frame) - if event == 'call': - return self.dispatch_call(frame, arg) - if event == 'return': - return self.dispatch_return(frame, arg) - if event == 'exception': - return self.dispatch_exception(frame, arg) - print 'bdb.Bdb.dispatch: unknown debugging event:', `event` - return self.trace_dispatch - - def dispatch_line(self, frame): - if self.stop_here(frame) or self.break_here(frame): - self.user_line(frame) - if self.quitting: raise BdbQuit - return self.trace_dispatch - - def dispatch_call(self, frame, arg): - frame.f_locals['__args__'] = arg - if self.botframe is None: - # First call of dispatch since reset() - self.botframe = frame - return self.trace_dispatch - if not (self.stop_here(frame) or self.break_anywhere(frame)): - # No need to trace this function - return # None - self.user_call(frame, arg) - if self.quitting: raise BdbQuit - return self.trace_dispatch - - def dispatch_return(self, frame, arg): - if self.stop_here(frame) or frame == self.returnframe: - self.user_return(frame, arg) - if self.quitting: raise BdbQuit - - def dispatch_exception(self, frame, arg): - if self.stop_here(frame): - self.user_exception(frame, arg) - if self.quitting: raise BdbQuit - return self.trace_dispatch - - # Normally derived classes don't override the following - # methods, but they may if they want to redefine the - # definition of stopping and breakpoints. - - def stop_here(self, frame): - if self.stopframe is None: - return 1 - if frame is self.stopframe: - return 1 - while frame is not None and frame is not self.stopframe: - if frame is self.botframe: - return 1 - frame = frame.f_back - return 0 - - def break_here(self, frame): - if not self.breaks.has_key(frame.f_code.co_filename): - return 0 - if not frame.f_lineno in \ - self.breaks[frame.f_code.co_filename]: - return 0 - return 1 - - def break_anywhere(self, frame): - return self.breaks.has_key(frame.f_code.co_filename) - - # Derived classes should override the user_* methods - # to gain control. - - def user_call(self, frame, argument_list): - # This method is called when there is the remote possibility - # that we ever need to stop in this function - pass - - def user_line(self, frame): - # This method is called when we stop or break at this line - pass - - def user_return(self, frame, return_value): - # This method is called when a return trap is set here - pass - - def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): - # This method is called if an exception occurs, - # but only if we are to stop at or just below this level - pass - - # Derived classes and clients can call the following methods - # to affect the stepping state. - - def set_step(self): - # Stop after one line of code - self.stopframe = None - self.returnframe = None - self.quitting = 0 - - def set_next(self, frame): - # Stop on the next line in or below the given frame - self.stopframe = frame - self.returnframe = None - self.quitting = 0 - - def set_return(self, frame): - # Stop when returning from the given frame - self.stopframe = frame.f_back - self.returnframe = frame - self.quitting = 0 - - def set_trace(self): - # Start debugging from here - try: - 1 + '' - except: - frame = sys.exc_traceback.tb_frame.f_back - self.reset() - while frame: - frame.f_trace = self.trace_dispatch - self.botframe = frame - frame = frame.f_back - self.set_step() - sys.settrace(self.trace_dispatch) - - def set_continue(self): - # Don't stop except at breakpoints or when finished - self.stopframe = self.botframe - self.returnframe = None - self.quitting = 0 - if not self.breaks: - # no breakpoints; run without debugger overhead - sys.settrace(None) - try: - 1 + '' # raise an exception - except: - frame = sys.exc_traceback.tb_frame.f_back - while frame and frame is not self.botframe: - del frame.f_trace - frame = frame.f_back - - def set_quit(self): - self.stopframe = self.botframe - self.returnframe = None - self.quitting = 1 - sys.settrace(None) - - # Derived classes and clients can call the following methods - # to manipulate breakpoints. These methods return an - # error message is something went wrong, None if all is well. - # Call self.get_*break*() to see the breakpoints. - - def set_break(self, filename, lineno): - import linecache # Import as late as possible - line = linecache.getline(filename, lineno) - if not line: - return 'That line does not exist!' - if not self.breaks.has_key(filename): - self.breaks[filename] = [] - list = self.breaks[filename] - if lineno in list: - return 'There is already a breakpoint there!' - list.append(lineno) - - def clear_break(self, filename, lineno): - if not self.breaks.has_key(filename): - return 'There are no breakpoints in that file!' - if lineno not in self.breaks[filename]: - return 'There is no breakpoint there!' - self.breaks[filename].remove(lineno) - if not self.breaks[filename]: - del self.breaks[filename] - - def clear_all_file_breaks(self, filename): - if not self.breaks.has_key(filename): - return 'There are no breakpoints in that file!' - del self.breaks[filename] - - def clear_all_breaks(self): - if not self.breaks: - return 'There are no breakpoints!' - self.breaks = {} - - def get_break(self, filename, lineno): - return self.breaks.has_key(filename) and \ - lineno in self.breaks[filename] - - def get_file_breaks(self, filename): - if self.breaks.has_key(filename): - return self.breaks[filename] - else: - return [] - - def get_all_breaks(self): - return self.breaks - - # Derived classes and clients can call the following method - # to get a data structure representing a stack trace. - - def get_stack(self, f, t): - stack = [] - if t and t.tb_frame is f: - t = t.tb_next - while f is not None: - stack.append((f, f.f_lineno)) - if f is self.botframe: - break - f = f.f_back - stack.reverse() - i = max(0, len(stack) - 1) - while t is not None: - stack.append((t.tb_frame, t.tb_lineno)) - t = t.tb_next - return stack, i - - # - - def format_stack_entry(self, frame_lineno, lprefix=': '): - import linecache, repr, string - frame, lineno = frame_lineno - filename = frame.f_code.co_filename - s = filename + '(' + `lineno` + ')' - if frame.f_code.co_name: - s = s + frame.f_code.co_name - else: - s = s + "<lambda>" - if frame.f_locals.has_key('__args__'): - args = frame.f_locals['__args__'] - else: - args = None - if args: - s = s + repr.repr(args) - else: - s = s + '()' - if frame.f_locals.has_key('__return__'): - rv = frame.f_locals['__return__'] - s = s + '->' - s = s + repr.repr(rv) - line = linecache.getline(filename, lineno) - if line: s = s + lprefix + string.strip(line) - return s - - # The following two methods can be called by clients to use - # a debugger to debug a statement, given as a string. - - def run(self, cmd, globals=None, locals=None): - if globals is None: - import __main__ - globals = __main__.__dict__ - if locals is None: - locals = globals - self.reset() - sys.settrace(self.trace_dispatch) - try: - try: - exec cmd + '\n' in globals, locals - except BdbQuit: - pass - finally: - self.quitting = 1 - sys.settrace(None) - - def runeval(self, expr, globals=None, locals=None): - if globals is None: - import __main__ - globals = __main__.__dict__ - if locals is None: - locals = globals - self.reset() - sys.settrace(self.trace_dispatch) - try: - try: - return eval(expr + '\n', globals, locals) - except BdbQuit: - pass - finally: - self.quitting = 1 - sys.settrace(None) - - def runctx(self, cmd, globals, locals): - # B/W compatibility - self.run(cmd, globals, locals) - - # This method is more useful to debug a single function call. - - def runcall(self, func, *args): - self.reset() - sys.settrace(self.trace_dispatch) - res = None - try: - try: - res = apply(func, args) - except BdbQuit: - pass - finally: - self.quitting = 1 - sys.settrace(None) - return res - - -def set_trace(): - Bdb().set_trace() - -# -------------------- testing -------------------- - -class Tdb(Bdb): - def user_call(self, frame, args): - name = frame.f_code.co_name - if not name: name = '???' - print '+++ call', name, args - def user_line(self, frame): - import linecache, string - name = frame.f_code.co_name - if not name: name = '???' - fn = frame.f_code.co_filename - line = linecache.getline(fn, frame.f_lineno) - print '+++', fn, frame.f_lineno, name, ':', string.strip(line) - def user_return(self, frame, retval): - print '+++ return', retval - def user_exception(self, frame, exc_stuff): - print '+++ exception', exc_stuff - self.set_continue() - -def foo(n): - print 'foo(', n, ')' - x = bar(n*10) - print 'bar returned', x - -def bar(a): - print 'bar(', a, ')' - return a/2 - -def test(): - t = Tdb() - t.run('import bdb; bdb.foo(10)') diff --git a/Lib/binhex.py b/Lib/binhex.py deleted file mode 100644 index cdb961ef7c..0000000000 --- a/Lib/binhex.py +++ /dev/null @@ -1,505 +0,0 @@ -"""binhex - Macintosh binhex compression/decompression -easy interface: -binhex(inputfilename, outputfilename) -hexbin(inputfilename, outputfilename) -""" - -# -# Jack Jansen, CWI, August 1995. -# -# The module is supposed to be as compatible as possible. Especially the -# easy interface should work "as expected" on any platform. -# XXXX Note: currently, textfiles appear in mac-form on all platforms. -# We seem to lack a simple character-translate in python. -# (we should probably use ISO-Latin-1 on all but the mac platform). -# XXXX The simeple routines are too simple: they expect to hold the complete -# files in-core. Should be fixed. -# XXXX It would be nice to handle AppleDouble format on unix (for servers serving -# macs). -# XXXX I don't understand what happens when you get 0x90 times the same byte on -# input. The resulting code (xx 90 90) would appear to be interpreted as an -# escaped *value* of 0x90. All coders I've seen appear to ignore this nicety... -# -import sys -import os -import struct -import string -import binascii - -Error = 'binhex.Error' - -# States (what have we written) -[_DID_HEADER, _DID_DATA, _DID_RSRC] = range(3) - -# Various constants -REASONABLY_LARGE=32768 # Minimal amount we pass the rle-coder -LINELEN=64 -RUNCHAR=chr(0x90) # run-length introducer - -# -# The code is currently byte-order dependent -if struct.pack('i', 0177) != '\0\0\0\177': - raise ImportError, 'Module binhex is big-endian only' - -# -# Workarounds for non-mac machines. -if os.name == 'mac': - import macfs - import MacOS - try: - openrf = MacOS.openrf - except AttributeError: - # Backward compatability - openrf = open - - def FInfo(): - return macfs.FInfo() - - def getfileinfo(name): - finfo = macfs.FSSpec(name).GetFInfo() - dir, file = os.path.split(name) - # XXXX Get resource/data sizes - fp = open(name, 'rb') - fp.seek(0, 2) - dlen = fp.tell() - fp = openrf(name, '*rb') - fp.seek(0, 2) - rlen = fp.tell() - return file, finfo, dlen, rlen - - def openrsrc(name, *mode): - if not mode: - mode = '*rb' - else: - mode = '*' + mode[0] - return openrf(name, mode) - -else: - # - # Glue code for non-macintosh useage - # - import regsub - - class FInfo: - def __init__(self): - self.Type = '????' - self.Creator = '????' - self.Flags = 0 - - def getfileinfo(name): - finfo = FInfo() - # Quick check for textfile - fp = open(name) - data = open(name).read(256) - for c in data: - if not c in string.whitespace and (c<' ' or ord(c) > 0177): - break - else: - finfo.Type = 'TEXT' - fp.seek(0, 2) - dsize = fp.tell() - fp.close() - dir, file = os.path.split(name) - file = regsub.sub(':', '-', file) - return file, finfo, dsize, 0 - - class openrsrc: - def __init__(self, *args): - pass - - def read(self, *args): - return '' - - def write(self, *args): - pass - - def close(self): - pass - -class _Hqxcoderengine: - """Write data to the coder in 3-byte chunks""" - - def __init__(self, ofp): - self.ofp = ofp - self.data = '' - self.hqxdata = '' - self.linelen = LINELEN-1 - - def write(self, data): - self.data = self.data + data - datalen = len(self.data) - todo = (datalen/3)*3 - data = self.data[:todo] - self.data = self.data[todo:] - if not data: - return - self.hqxdata = self.hqxdata + binascii.b2a_hqx(data) - self._flush(0) - - def _flush(self, force): - first = 0 - while first <= len(self.hqxdata)-self.linelen: - last = first + self.linelen - self.ofp.write(self.hqxdata[first:last]+'\n') - self.linelen = LINELEN - first = last - self.hqxdata = self.hqxdata[first:] - if force: - self.ofp.write(self.hqxdata + ':\n') - - def close(self): - if self.data: - self.hqxdata = self.hqxdata + binascii.b2a_hqx(self.data) - self._flush(1) - self.ofp.close() - del self.ofp - -class _Rlecoderengine: - """Write data to the RLE-coder in suitably large chunks""" - - def __init__(self, ofp): - self.ofp = ofp - self.data = '' - - def write(self, data): - self.data = self.data + data - if len(self.data) < REASONABLY_LARGE: - return - rledata = binascii.rlecode_hqx(self.data) - self.ofp.write(rledata) - self.data = '' - - def close(self): - if self.data: - rledata = binascii.rlecode_hqx(self.data) - self.ofp.write(rledata) - self.ofp.close() - del self.ofp - -class BinHex: - def __init__(self, (name, finfo, dlen, rlen), ofp): - if type(ofp) == type(''): - ofname = ofp - ofp = open(ofname, 'w') - if os.name == 'mac': - fss = macfs.FSSpec(ofname) - fss.SetCreatorType('BnHq', 'TEXT') - ofp.write('(This file must be converted with BinHex 4.0)\n\n:') - hqxer = _Hqxcoderengine(ofp) - self.ofp = _Rlecoderengine(hqxer) - self.crc = 0 - if finfo == None: - finfo = FInfo() - self.dlen = dlen - self.rlen = rlen - self._writeinfo(name, finfo) - self.state = _DID_HEADER - - def _writeinfo(self, name, finfo): - name = name - nl = len(name) - if nl > 63: - raise Error, 'Filename too long' - d = chr(nl) + name + '\0' - d2 = finfo.Type + finfo.Creator - d3 = struct.pack('h', finfo.Flags) - d4 = struct.pack('ii', self.dlen, self.rlen) - info = d + d2 + d3 + d4 - self._write(info) - self._writecrc() - - def _write(self, data): - self.crc = binascii.crc_hqx(data, self.crc) - self.ofp.write(data) - - def _writecrc(self): -## self.crc = binascii.crc_hqx('\0\0', self.crc) # XXXX Should this be here?? - self.ofp.write(struct.pack('h', self.crc)) - self.crc = 0 - - def write(self, data): - if self.state != _DID_HEADER: - raise Error, 'Writing data at the wrong time' - self.dlen = self.dlen - len(data) - self._write(data) - - def close_data(self): - if self.dlen <> 0: - raise Error, 'Incorrect data size, diff='+`self.rlen` - self._writecrc() - self.state = _DID_DATA - - def write_rsrc(self, data): - if self.state < _DID_DATA: - self.close_data() - if self.state != _DID_DATA: - raise Error, 'Writing resource data at the wrong time' - self.rlen = self.rlen - len(data) - self._write(data) - - def close(self): - if self.state < _DID_DATA: - self.close_data() - if self.state != _DID_DATA: - raise Error, 'Close at the wrong time' - if self.rlen <> 0: - raise Error, "Incorrect resource-datasize, diff="+`self.rlen` - self._writecrc() - self.ofp.close() - self.state = None - del self.ofp - -def binhex(inp, out): - """(infilename, outfilename) - Create binhex-encoded copy of a file""" - finfo = getfileinfo(inp) - ofp = BinHex(finfo, out) - - ifp = open(inp, 'rb') - # XXXX Do textfile translation on non-mac systems - while 1: - d = ifp.read(128000) - if not d: break - ofp.write(d) - ofp.close_data() - ifp.close() - - ifp = openrsrc(inp, 'rb') - while 1: - d = ifp.read(128000) - if not d: break - ofp.write_rsrc(d) - ofp.close() - ifp.close() - -class _Hqxdecoderengine: - """Read data via the decoder in 4-byte chunks""" - - def __init__(self, ifp): - self.ifp = ifp - self.eof = 0 - - def read(self, totalwtd): - """Read at least wtd bytes (or until EOF)""" - decdata = '' - wtd = totalwtd - # - # The loop here is convoluted, since we don't really now how much - # to decode: there may be newlines in the incoming data. - while wtd > 0: - if self.eof: return decdata - wtd = ((wtd+2)/3)*4 - data = self.ifp.read(wtd) - # - # Next problem: there may not be a complete number of bytes in what we - # pass to a2b. Solve by yet another loop. - # - while 1: - try: - decdatacur, self.eof = binascii.a2b_hqx(data) - break - except binascii.Incomplete: - pass - newdata = self.ifp.read(1) - if not newdata: - raise Error, 'Premature EOF on binhex file' - data = data + newdata - decdata = decdata + decdatacur - wtd = totalwtd - len(decdata) - if not decdata and not self.eof: - raise Error, 'Premature EOF on binhex file' - return decdata - - def close(self): - self.ifp.close() - -class _Rledecoderengine: - """Read data via the RLE-coder""" - - def __init__(self, ifp): - self.ifp = ifp - self.pre_buffer = '' - self.post_buffer = '' - self.eof = 0 - - def read(self, wtd): - if wtd > len(self.post_buffer): - self._fill(wtd-len(self.post_buffer)) - rv = self.post_buffer[:wtd] - self.post_buffer = self.post_buffer[wtd:] - return rv - - def _fill(self, wtd): - # - # Obfuscated code ahead. We keep at least one byte in the pre_buffer, - # so we don't stumble over an orphaned RUNCHAR later on. If the - # last or second-last char is a RUNCHAR we keep more bytes. - # - self.pre_buffer = self.pre_buffer + self.ifp.read(wtd+2) - if self.ifp.eof: - self.post_buffer = self.post_buffer + \ - binascii.rledecode_hqx(self.pre_buffer) - self.pre_buffer = '' - return - - lastrle = string.rfind(self.pre_buffer, RUNCHAR) - if lastrle > 0 and lastrle == len(self.pre_buffer)-1: - # Last byte is an RLE, keep two bytes - mark = len(self.pre_buffer)-2 - elif lastrle > 0 and lastrle == len(self.pre_buffer)-2: - # second-last byte is an RLE. Decode all. - mark = len(self.pre_buffer) - else: - mark = len(self.pre_buffer)-1 - self.post_buffer = self.post_buffer + \ - binascii.rledecode_hqx(self.pre_buffer[:mark]) - self.pre_buffer = self.pre_buffer[mark:] - - def close(self): - self.ifp.close() - -class HexBin: - def __init__(self, ifp): - if type(ifp) == type(''): - ifp = open(ifp) - # - # Find initial colon. - # - while 1: - ch = ifp.read(1) - if not ch: - raise Error, "No binhex data found" - if ch == ':': - break - if ch != '\n': - dummy = ifp.readline() - - hqxifp = _Hqxdecoderengine(ifp) - self.ifp = _Rledecoderengine(hqxifp) - self.crc = 0 - self._readheader() - - def _read(self, len): - data = self.ifp.read(len) - self.crc = binascii.crc_hqx(data, self.crc) - return data - - def _checkcrc(self): - filecrc = struct.unpack('h', self.ifp.read(2))[0] & 0xffff -## self.crc = binascii.crc_hqx('\0\0', self.crc) # XXXX Is this needed?? - self.crc = self.crc & 0xffff - if filecrc != self.crc: - raise Error, 'CRC error, computed %x, read %x'%(self.crc, filecrc) - self.crc = 0 - - def _readheader(self): - len = self._read(1) - fname = self._read(ord(len)) - rest = self._read(1+4+4+2+4+4) - self._checkcrc() - - type = rest[1:5] - creator = rest[5:9] - flags = struct.unpack('h', rest[9:11])[0] - self.dlen = struct.unpack('l', rest[11:15])[0] - self.rlen = struct.unpack('l', rest[15:19])[0] - - self.FName = fname - self.FInfo = FInfo() - self.FInfo.Creator = creator - self.FInfo.Type = type - self.FInfo.Flags = flags - - self.state = _DID_HEADER - - def read(self, *n): - if self.state != _DID_HEADER: - raise Error, 'Read data at wrong time' - if n: - n = n[0] - n = min(n, self.dlen) - else: - n = self.dlen - self.dlen = self.dlen - n - return self._read(n) - - def close_data(self): - if self.state != _DID_HEADER: - raise Error, 'close_data at wrong time' - if self.dlen: - dummy = self._read(self.dlen) - self._checkcrc() - self.state = _DID_DATA - - def read_rsrc(self, *n): - if self.state == _DID_HEADER: - self.close_data() - if self.state != _DID_DATA: - raise Error, 'Read resource data at wrong time' - if n: - n = n[0] - n = min(n, self.rlen) - else: - n = self.rlen - self.rlen = self.rlen - n - return self._read(n) - - def close(self): - if self.rlen: - dummy = self.read_rsrc(self.rlen) - self._checkcrc() - self.state = _DID_RSRC - self.ifp.close() - -def hexbin(inp, out): - """(infilename, outfilename) - Decode binhexed file""" - ifp = HexBin(inp) - finfo = ifp.FInfo - if not out: - out = ifp.FName - if os.name == 'mac': - ofss = macfs.FSSpec(out) - out = ofss.as_pathname() - - ofp = open(out, 'wb') - # XXXX Do translation on non-mac systems - while 1: - d = ifp.read(128000) - if not d: break - ofp.write(d) - ofp.close() - ifp.close_data() - - d = ifp.read_rsrc(128000) - if d: - ofp = openrsrc(out, 'wb') - ofp.write(d) - while 1: - d = ifp.read_rsrc(128000) - if not d: break - ofp.write(d) - ofp.close() - - if os.name == 'mac': - nfinfo = ofss.GetFInfo() - nfinfo.Creator = finfo.Creator - nfinfo.Type = finfo.Type - nfinfo.Flags = finfo.Flags - ofss.SetFInfo(nfinfo) - - ifp.close() - -def _test(): - if os.name == 'mac': - fss, ok = macfs.PromptGetFile('File to convert:') - if not ok: - sys.exit(0) - fname = fss.as_pathname() - else: - fname = sys.argv[1] - #binhex(fname, fname+'.hqx') - #hexbin(fname+'.hqx', fname+'.viahqx') - hexbin(fname, fname+'.unpacked') - sys.exit(1) - -if __name__ == '__main__': - _test() diff --git a/Lib/bisect.py b/Lib/bisect.py deleted file mode 100644 index 688666a411..0000000000 --- a/Lib/bisect.py +++ /dev/null @@ -1,23 +0,0 @@ -# Bisection algorithms - - -# Insert item x in list a, and keep it sorted assuming a is sorted - -def insort(a, x): - lo, hi = 0, len(a) - while lo < hi: - mid = (lo+hi)/2 - if x < a[mid]: hi = mid - else: lo = mid+1 - a.insert(lo, x) - - -# Find the index where to insert item x in list a, assuming a is sorted - -def bisect(a, x): - lo, hi = 0, len(a) - while lo < hi: - mid = (lo+hi)/2 - if x < a[mid]: hi = mid - else: lo = mid+1 - return lo diff --git a/Lib/builtin.py b/Lib/builtin.py deleted file mode 100755 index 710d8253a2..0000000000 --- a/Lib/builtin.py +++ /dev/null @@ -1,3 +0,0 @@ -# B/W compat hack so code that says "import builtin" won't break after -# name change from builtin to __builtin__. -from __builtin__ import * diff --git a/Lib/calendar.py b/Lib/calendar.py deleted file mode 100644 index e9b16447fa..0000000000 --- a/Lib/calendar.py +++ /dev/null @@ -1,153 +0,0 @@ -############################### -# Calendar printing functions # -############################### - -# Revision 2: uses funtions from built-in time module - -# Import functions and variables from time module -from time import gmtime, localtime, mktime, asctime, ctime - -# Exception raised for bad input (with string parameter for details) -error = 'calendar.error' - -# Note when comparing these calendars to the ones printed by cal(1): -# My calendars have Monday as the first day of the week, and Sunday as -# the last! (I believe this is the European convention.) - -# Constants for months referenced later -January = 1 -February = 2 - -# Number of days per month (except for February in leap years) -mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - -# Full and abbreviated names of weekdays -day_name = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', \ - 'Friday', 'Saturday', 'Sunday'] -day_abbr = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] - -# Full and abbreviated names of months (1-based arrays!!!) -month_name = ['', 'January', 'February', 'March', 'April', \ - 'May', 'June', 'July', 'August', \ - 'September', 'October', 'November', 'December'] -month_abbr = [' ', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', \ - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] - -# Return 1 for leap years, 0 for non-leap years -def isleap(year): - return year % 4 == 0 and (year % 100 <> 0 or year % 400 == 0) - -# Return number of leap years in range [y1, y2) -# Assume y1 <= y2 and no funny (non-leap century) years -def leapdays(y1, y2): - return (y2+3)/4 - (y1+3)/4 - -# Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), day (1-31) -def weekday(year, month, day): - secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0)) - tuple = localtime(secs) - return tuple[6] - -# Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month -def monthrange(year, month): - if not 1 <= month <= 12: raise ValueError, 'bad month number' - day1 = weekday(year, month, 1) - ndays = mdays[month] + (month == February and isleap(year)) - return day1, ndays - -# Return a matrix representing a month's calendar -# Each row represents a week; days outside this month are zero -def _monthcalendar(year, month): - day1, ndays = monthrange(year, month) - rows = [] - r7 = range(7) - day = 1 - day1 - while day <= ndays: - row = [0, 0, 0, 0, 0, 0, 0] - for i in r7: - if 1 <= day <= ndays: row[i] = day - day = day + 1 - rows.append(row) - return rows - -# Caching interface to _monthcalendar -_mc_cache = {} -def monthcalendar(year, month): - key = (year, month) - if _mc_cache.has_key(key): - return _mc_cache[key] - else: - _mc_cache[key] = ret = _monthcalendar(year, month) - return ret - -# Center a string in a field -def _center(str, width): - n = width - len(str) - if n <= 0: return str - return ' '*((n+1)/2) + str + ' '*((n)/2) - -# XXX The following code knows that print separates items with space! - -# Print a single week (no newline) -def prweek(week, width): - for day in week: - if day == 0: s = '' - else: s = `day` - print _center(s, width), - -# Return a header for a week -def weekheader(width): - str = '' - if width >= 9: names = day_name - else: names = day_abbr - for i in range(7): - if str: str = str + ' ' - str = str + _center(names[i%7][:width], width) - return str - -# Print a month's calendar -def prmonth(year, month, w = 0, l = 0): - w = max(2, w) - l = max(1, l) - print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1), - print '\n'*l, - print weekheader(w), - print '\n'*l, - for week in monthcalendar(year, month): - prweek(week, w) - print '\n'*l, - -# Spacing of month columns -_colwidth = 7*3 - 1 # Amount printed by prweek() -_spacing = ' '*4 # Spaces between columns - -# 3-column formatting for year calendars -def format3c(a, b, c): - print _center(a, _colwidth), - print _spacing, - print _center(b, _colwidth), - print _spacing, - print _center(c, _colwidth) - -# Print a year's calendar -def prcal(year): - header = weekheader(2) - format3c('', `year`, '') - for q in range(January, January+12, 3): - print - format3c(month_name[q], month_name[q+1], month_name[q+2]) - format3c(header, header, header) - data = [] - height = 0 - for month in range(q, q+3): - cal = monthcalendar(year, month) - if len(cal) > height: height = len(cal) - data.append(cal) - for i in range(height): - for cal in data: - if i >= len(cal): - print ' '*_colwidth, - else: - prweek(cal[i], 2) - print _spacing, - print diff --git a/Lib/cgi.py b/Lib/cgi.py deleted file mode 100755 index 95e8bced68..0000000000 --- a/Lib/cgi.py +++ /dev/null @@ -1,1159 +0,0 @@ -#!/usr/local/bin/python - -"""Support module for CGI (Common Gateway Interface) scripts. - -This module defines a number of utilities for use by CGI scripts -written in Python. - - -Introduction ------------- - -A CGI script is invoked by an HTTP server, usually to process user -input submitted through an HTML <FORM> or <ISINPUT> element. - -Most often, CGI scripts live in the server's special cgi-bin -directory. The HTTP server places all sorts of information about the -request (such as the client's hostname, the requested URL, the query -string, and lots of other goodies) in the script's shell environment, -executes the script, and sends the script's output back to the client. - -The script's input is connected to the client too, and sometimes the -form data is read this way; at other times the form data is passed via -the "query string" part of the URL. This module (cgi.py) is intended -to take care of the different cases and provide a simpler interface to -the Python script. It also provides a number of utilities that help -in debugging scripts, and the latest addition is support for file -uploads from a form (if your browser supports it -- Grail 0.3 and -Netscape 2.0 do). - -The output of a CGI script should consist of two sections, separated -by a blank line. The first section contains a number of headers, -telling the client what kind of data is following. Python code to -generate a minimal header section looks like this: - - print "Content-type: text/html" # HTML is following - print # blank line, end of headers - -The second section is usually HTML, which allows the client software -to display nicely formatted text with header, in-line images, etc. -Here's Python code that prints a simple piece of HTML: - - print "<TITLE>CGI script output</TITLE>" - print "<H1>This is my first CGI script</H1>" - print "Hello, world!" - -(It may not be fully legal HTML according to the letter of the -standard, but any browser will understand it.) - - -Using the cgi module --------------------- - -Begin by writing "import cgi". Don't use "from cgi import *" -- the -module defines all sorts of names for its own use or for backward -compatibility that you don't want in your namespace. - -It's best to use the FieldStorage class. The other classes define in this -module are provided mostly for backward compatibility. Instantiate it -exactly once, without arguments. This reads the form contents from -standard input or the environment (depending on the value of various -environment variables set according to the CGI standard). Since it may -consume standard input, it should be instantiated only once. - -The FieldStorage instance can be accessed as if it were a Python -dictionary. For instance, the following code (which assumes that the -Content-type header and blank line have already been printed) checks that -the fields "name" and "addr" are both set to a non-empty string: - - form = cgi.FieldStorage() - form_ok = 0 - if form.has_key("name") and form.has_key("addr"): - if form["name"].value != "" and form["addr"].value != "": - form_ok = 1 - if not form_ok: - print "<H1>Error</H1>" - print "Please fill in the name and addr fields." - return - ...further form processing here... - -Here the fields, accessed through form[key], are themselves instances -of FieldStorage (or MiniFieldStorage, depending on the form encoding). - -If the submitted form data contains more than one field with the same -name, the object retrieved by form[key] is not a (Mini)FieldStorage -instance but a list of such instances. If you expect this possibility -(i.e., when your HTML form comtains multiple fields with the same -name), use the type() function to determine whether you have a single -instance or a list of instances. For example, here's code that -concatenates any number of username fields, separated by commas: - - username = form["username"] - if type(username) is type([]): - # Multiple username fields specified - usernames = "" - for item in username: - if usernames: - # Next item -- insert comma - usernames = usernames + "," + item.value - else: - # First item -- don't insert comma - usernames = item.value - else: - # Single username field specified - usernames = username.value - -If a field represents an uploaded file, the value attribute reads the -entire file in memory as a string. This may not be what you want. You can -test for an uploaded file by testing either the filename attribute or the -file attribute. You can then read the data at leasure from the file -attribute: - - fileitem = form["userfile"] - if fileitem.file: - # It's an uploaded file; count lines - linecount = 0 - while 1: - line = fileitem.file.readline() - if not line: break - linecount = linecount + 1 - -The file upload draft standard entertains the possibility of uploading -multiple files from one field (using a recursive multipart/* -encoding). When this occurs, the item will be a dictionary-like -FieldStorage item. This can be determined by testing its type -attribute, which should have the value "multipart/form-data" (or -perhaps another string beginning with "multipart/"). It this case, it -can be iterated over recursively just like the top-level form object. - -When a form is submitted in the "old" format (as the query string or as a -single data part of type application/x-www-form-urlencoded), the items -will actually be instances of the class MiniFieldStorage. In this case, -the list, file and filename attributes are always None. - - -Old classes ------------ - -These classes, present in earlier versions of the cgi module, are still -supported for backward compatibility. New applications should use the - -SvFormContentDict: single value form content as dictionary; assumes each -field name occurs in the form only once. - -FormContentDict: multiple value form content as dictionary (the form -items are lists of values). Useful if your form contains multiple -fields with the same name. - -Other classes (FormContent, InterpFormContentDict) are present for -backwards compatibility with really old applications only. If you still -use these and would be inconvenienced when they disappeared from a next -version of this module, drop me a note. - - -Functions ---------- - -These are useful if you want more control, or if you want to employ -some of the algorithms implemented in this module in other -circumstances. - -parse(fp): parse a form into a Python dictionary. - -parse_qs(qs): parse a query string (data of type -application/x-www-form-urlencoded). - -parse_multipart(fp, pdict): parse input of type multipart/form-data (for -file uploads). - -parse_header(string): parse a header like Content-type into a main -value and a dictionary of parameters. - -test(): complete test program. - -print_environ(): format the shell environment in HTML. - -print_form(form): format a form in HTML. - -print_environ_usage(): print a list of useful environment variables in -HTML. - -escape(): convert the characters "&", "<" and ">" to HTML-safe -sequences. Use this if you need to display text that might contain -such characters in HTML. To translate URLs for inclusion in the HREF -attribute of an <A> tag, use urllib.quote(). - - -Caring about security ---------------------- - -There's one important rule: if you invoke an external program (e.g. -via the os.system() or os.popen() functions), make very sure you don't -pass arbitrary strings received from the client to the shell. This is -a well-known security hole whereby clever hackers anywhere on the web -can exploit a gullible CGI script to invoke arbitrary shell commands. -Even parts of the URL or field names cannot be trusted, since the -request doesn't have to come from your form! - -To be on the safe side, if you must pass a string gotten from a form -to a shell command, you should make sure the string contains only -alphanumeric characters, dashes, underscores, and periods. - - -Installing your CGI script on a Unix system -------------------------------------------- - -Read the documentation for your HTTP server and check with your local -system administrator to find the directory where CGI scripts should be -installed; usually this is in a directory cgi-bin in the server tree. - -Make sure that your script is readable and executable by "others"; the -Unix file mode should be 755 (use "chmod 755 filename"). Make sure -that the first line of the script contains "#!" starting in column 1 -followed by the pathname of the Python interpreter, for instance: - - #!/usr/local/bin/python - -Make sure the Python interpreter exists and is executable by "others". - -Make sure that any files your script needs to read or write are -readable or writable, respectively, by "others" -- their mode should -be 644 for readable and 666 for writable. This is because, for -security reasons, the HTTP server executes your script as user -"nobody", without any special privileges. It can only read (write, -execute) files that everybody can read (write, execute). The current -directory at execution time is also different (it is usually the -server's cgi-bin directory) and the set of environment variables is -also different from what you get at login. in particular, don't count -on the shell's search path for executables ($PATH) or the Python -module search path ($PYTHONPATH) to be set to anything interesting. - -If you need to load modules from a directory which is not on Python's -default module search path, you can change the path in your script, -before importing other modules, e.g.: - - import sys - sys.path.insert(0, "/usr/home/joe/lib/python") - sys.path.insert(0, "/usr/local/lib/python") - -(This way, the directory inserted last will be searched first!) - -Instructions for non-Unix systems will vary; check your HTTP server's -documentation (it will usually have a section on CGI scripts). - - -Testing your CGI script ------------------------ - -Unfortunately, a CGI script will generally not run when you try it -from the command line, and a script that works perfectly from the -command line may fail mysteriously when run from the server. There's -one reason why you should still test your script from the command -line: if it contains a syntax error, the python interpreter won't -execute it at all, and the HTTP server will most likely send a cryptic -error to the client. - -Assuming your script has no syntax errors, yet it does not work, you -have no choice but to read the next section: - - -Debugging CGI scripts ---------------------- - -First of all, check for trivial installation errors -- reading the -section above on installing your CGI script carefully can save you a -lot of time. If you wonder whether you have understood the -installation procedure correctly, try installing a copy of this module -file (cgi.py) as a CGI script. When invoked as a script, the file -will dump its environment and the contents of the form in HTML form. -Give it the right mode etc, and send it a request. If it's installed -in the standard cgi-bin directory, it should be possible to send it a -request by entering a URL into your browser of the form: - - http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home - -If this gives an error of type 404, the server cannot find the script --- perhaps you need to install it in a different directory. If it -gives another error (e.g. 500), there's an installation problem that -you should fix before trying to go any further. If you get a nicely -formatted listing of the environment and form content (in this -example, the fields should be listed as "addr" with value "At Home" -and "name" with value "Joe Blow"), the cgi.py script has been -installed correctly. If you follow the same procedure for your own -script, you should now be able to debug it. - -The next step could be to call the cgi module's test() function from -your script: replace its main code with the single statement - - cgi.test() - -This should produce the same results as those gotten from installing -the cgi.py file itself. - -When an ordinary Python script raises an unhandled exception -(e.g. because of a typo in a module name, a file that can't be opened, -etc.), the Python interpreter prints a nice traceback and exits. -While the Python interpreter will still do this when your CGI script -raises an exception, most likely the traceback will end up in one of -the HTTP server's log file, or be discarded altogether. - -Fortunately, once you have managed to get your script to execute -*some* code, it is easy to catch exceptions and cause a traceback to -be printed. The test() function below in this module is an example. -Here are the rules: - - 1. Import the traceback module (before entering the - try-except!) - - 2. Make sure you finish printing the headers and the blank - line early - - 3. Assign sys.stderr to sys.stdout - - 3. Wrap all remaining code in a try-except statement - - 4. In the except clause, call traceback.print_exc() - -For example: - - import sys - import traceback - print "Content-type: text/html" - print - sys.stderr = sys.stdout - try: - ...your code here... - except: - print "\n\n<PRE>" - traceback.print_exc() - -Notes: The assignment to sys.stderr is needed because the traceback -prints to sys.stderr. The print "\n\n<PRE>" statement is necessary to -disable the word wrapping in HTML. - -If you suspect that there may be a problem in importing the traceback -module, you can use an even more robust approach (which only uses -built-in modules): - - import sys - sys.stderr = sys.stdout - print "Content-type: text/plain" - print - ...your code here... - -This relies on the Python interpreter to print the traceback. The -content type of the output is set to plain text, which disables all -HTML processing. If your script works, the raw HTML will be displayed -by your client. If it raises an exception, most likely after the -first two lines have been printed, a traceback will be displayed. -Because no HTML interpretation is going on, the traceback will -readable. - -Good luck! - - -Common problems and solutions ------------------------------ - -- Most HTTP servers buffer the output from CGI scripts until the -script is completed. This means that it is not possible to display a -progress report on the client's display while the script is running. - -- Check the installation instructions above. - -- Check the HTTP server's log files. ("tail -f logfile" in a separate -window may be useful!) - -- Always check a script for syntax errors first, by doing something -like "python script.py". - -- When using any of the debugging techniques, don't forget to add -"import sys" to the top of the script. - -- When invoking external programs, make sure they can be found. -Usually, this means using absolute path names -- $PATH is usually not -set to a very useful value in a CGI script. - -- When reading or writing external files, make sure they can be read -or written by every user on the system. - -- Don't try to give a CGI script a set-uid mode. This doesn't work on -most systems, and is a security liability as well. - - -History -------- - -Michael McLay started this module. Steve Majewski changed the -interface to SvFormContentDict and FormContentDict. The multipart -parsing was inspired by code submitted by Andreas Paepcke. Guido van -Rossum rewrote, reformatted and documented the module and is currently -responsible for its maintenance. - - -XXX The module is getting pretty heavy with all those docstrings. -Perhaps there should be a slimmed version that doesn't contain all those -backwards compatible and debugging classes and functions? - -""" - -__version__ = "2.0b1" - - -# Imports -# ======= - -import string -import sys -import os - - -# A shorthand for os.environ -environ = os.environ - - -# Parsing functions -# ================= - -def parse(fp=None): - """Parse a query in the environment or from a file (default stdin)""" - if not fp: - fp = sys.stdin - if not environ.has_key('REQUEST_METHOD'): - environ['REQUEST_METHOD'] = 'GET' # For testing stand-alone - if environ['REQUEST_METHOD'] == 'POST': - ctype, pdict = parse_header(environ['CONTENT_TYPE']) - if ctype == 'multipart/form-data': - return parse_multipart(fp, pdict) - elif ctype == 'application/x-www-form-urlencoded': - clength = string.atoi(environ['CONTENT_LENGTH']) - qs = fp.read(clength) - else: - qs = '' # Unknown content-type - environ['QUERY_STRING'] = qs # XXX Shouldn't, really - elif environ.has_key('QUERY_STRING'): - qs = environ['QUERY_STRING'] - else: - if sys.argv[1:]: - qs = sys.argv[1] - else: - qs = "" - environ['QUERY_STRING'] = qs # XXX Shouldn't, really - return parse_qs(qs) - - -def parse_qs(qs): - """Parse a query given as a string argument""" - import urllib, regsub - name_value_pairs = string.splitfields(qs, '&') - dict = {} - for name_value in name_value_pairs: - nv = string.splitfields(name_value, '=') - if len(nv) != 2: - continue - name = nv[0] - value = urllib.unquote(regsub.gsub('+', ' ', nv[1])) - if len(value): - if dict.has_key (name): - dict[name].append(value) - else: - dict[name] = [value] - return dict - - -def parse_multipart(fp, pdict): - """Parse multipart input. - - Arguments: - fp : input file - pdict: dictionary containing other parameters of conten-type header - - Returns a dictionary just like parse_qs(): keys are the field names, each - value is a list of values for that field. This is easy to use but not - much good if you are expecting megabytes to be uploaded -- in that case, - use the FieldStorage class instead which is much more flexible. Note - that content-type is the raw, unparsed contents of the content-type - header. - - XXX This does not parse nested multipart parts -- use FieldStorage for - that. - - XXX This should really be subsumed by FieldStorage altogether -- no - point in having two implementations of the same parsing algorithm. - - """ - import mimetools - if pdict.has_key('boundary'): - boundary = pdict['boundary'] - else: - boundary = "" - nextpart = "--" + boundary - lastpart = "--" + boundary + "--" - partdict = {} - terminator = "" - - while terminator != lastpart: - bytes = -1 - data = None - if terminator: - # At start of next part. Read headers first. - headers = mimetools.Message(fp) - clength = headers.getheader('content-length') - if clength: - try: - bytes = string.atoi(clength) - except string.atoi_error: - pass - if bytes > 0: - data = fp.read(bytes) - else: - data = "" - # Read lines until end of part. - lines = [] - while 1: - line = fp.readline() - if not line: - terminator = lastpart # End outer loop - break - if line[:2] == "--": - terminator = string.strip(line) - if terminator in (nextpart, lastpart): - break - if line[-2:] == '\r\n': - line = line[:-2] - elif line[-1:] == '\n': - line = line[:-1] - lines.append(line) - # Done with part. - if data is None: - continue - if bytes < 0: - data = string.joinfields(lines, "\n") - line = headers['content-disposition'] - if not line: - continue - key, params = parse_header(line) - if key != 'form-data': - continue - if params.has_key('name'): - name = params['name'] - else: - continue - if partdict.has_key(name): - partdict[name].append(data) - else: - partdict[name] = [data] - - return partdict - - -def parse_header(line): - """Parse a Content-type like header. - - Return the main content-type and a dictionary of options. - - """ - plist = map(string.strip, string.splitfields(line, ';')) - key = string.lower(plist[0]) - del plist[0] - pdict = {} - for p in plist: - i = string.find(p, '=') - if i >= 0: - name = string.lower(string.strip(p[:i])) - value = string.strip(p[i+1:]) - if len(value) >= 2 and value[0] == value[-1] == '"': - value = value[1:-1] - pdict[name] = value - return key, pdict - - -# Classes for field storage -# ========================= - -class MiniFieldStorage: - - """Like FieldStorage, for use when no file uploads are possible.""" - - # Dummy attributes - filename = None - list = None - type = None - type_options = {} - disposition = None - disposition_options = {} - headers = {} - - def __init__(self, name, value): - """Constructor from field name and value.""" - from StringIO import StringIO - self.name = name - self.value = value - self.file = StringIO(value) - - def __repr__(self): - """Return printable representation.""" - return "MiniFieldStorage(%s, %s)" % (`self.name`, `self.value`) - - -class FieldStorage: - - """Store a sequence of fields, reading multipart/form-data. - - This class provides naming, typing, files stored on disk, and - more. At the top level, it is accessible like a dictionary, whose - keys are the field names. (Note: None can occur as a field name.) - The items are either a Python list (if there's multiple values) or - another FieldStorage or MiniFieldStorage object. If it's a single - object, it has the following attributes: - - name: the field name, if specified; otherwise None - - filename: the filename, if specified; otherwise None; this is the - client side filename, *not* the file name on which it is - stored (that's a temporary file you don't deal with) - - value: the value as a *string*; for file uploads, this - transparently reads the file every time you request the value - - file: the file(-like) object from which you can read the data; - None if the data is stored a simple string - - type: the content-type, or None if not specified - - type_options: dictionary of options specified on the content-type - line - - disposition: content-disposition, or None if not specified - - disposition_options: dictionary of corresponding options - - headers: a dictionary(-like) object (sometimes rfc822.Message or a - subclass thereof) containing *all* headers - - The class is subclassable, mostly for the purpose of overriding - the make_file() method, which is called internally to come up with - a file open for reading and writing. This makes it possible to - override the default choice of storing all files in a temporary - directory and unlinking them as soon as they have been opened. - - """ - - def __init__(self, fp=None, headers=None, outerboundary=""): - """Constructor. Read multipart/* until last part. - - Arguments, all optional: - - fp : file pointer; default: sys.stdin - - headers : header dictionary-like object; default: - taken from environ as per CGI spec - - outerboundary : optional terminating multipart boundary - (for internal use only) - - """ - method = None - if environ.has_key('REQUEST_METHOD'): - method = string.upper(environ['REQUEST_METHOD']) - if not fp and method == 'GET': - qs = None - if environ.has_key('QUERY_STRING'): - qs = environ['QUERY_STRING'] - from StringIO import StringIO - fp = StringIO(qs or "") - if headers is None: - headers = {'content-type': - "application/x-www-form-urlencoded"} - if headers is None: - headers = {} - if environ.has_key('CONTENT_TYPE'): - headers['content-type'] = environ['CONTENT_TYPE'] - if environ.has_key('CONTENT_LENGTH'): - headers['content-length'] = environ['CONTENT_LENGTH'] - self.fp = fp or sys.stdin - self.headers = headers - self.outerboundary = outerboundary - - # Process content-disposition header - cdisp, pdict = "", {} - if self.headers.has_key('content-disposition'): - cdisp, pdict = parse_header(self.headers['content-disposition']) - self.disposition = cdisp - self.disposition_options = pdict - self.name = None - if pdict.has_key('name'): - self.name = pdict['name'] - self.filename = None - if pdict.has_key('filename'): - self.filename = pdict['filename'] - - # Process content-type header - ctype, pdict = "text/plain", {} - if self.headers.has_key('content-type'): - ctype, pdict = parse_header(self.headers['content-type']) - self.type = ctype - self.type_options = pdict - self.innerboundary = "" - if pdict.has_key('boundary'): - self.innerboundary = pdict['boundary'] - clen = -1 - if self.headers.has_key('content-length'): - try: - clen = string.atoi(self.headers['content-length']) - except: - pass - self.length = clen - - self.list = self.file = None - self.done = 0 - self.lines = [] - if ctype == 'application/x-www-form-urlencoded': - self.read_urlencoded() - elif ctype[:10] == 'multipart/': - self.read_multi() - else: - self.read_single() - - def __repr__(self): - """Return a printable representation.""" - return "FieldStorage(%s, %s, %s)" % ( - `self.name`, `self.filename`, `self.value`) - - def __getattr__(self, name): - if name != 'value': - raise AttributeError, name - if self.file: - self.file.seek(0) - value = self.file.read() - self.file.seek(0) - elif self.list is not None: - value = self.list - else: - value = None - return value - - def __getitem__(self, key): - """Dictionary style indexing.""" - if self.list is None: - raise TypeError, "not indexable" - found = [] - for item in self.list: - if item.name == key: found.append(item) - if not found: - raise KeyError, key - if len(found) == 1: - return found[0] - else: - return found - - def keys(self): - """Dictionary style keys() method.""" - if self.list is None: - raise TypeError, "not indexable" - keys = [] - for item in self.list: - if item.name not in keys: keys.append(item.name) - return keys - - def has_key(self, key): - """Dictionary style has_key() method.""" - if self.list is None: - raise TypeError, "not indexable" - for item in self.list: - if item.name == key: return 1 - return 0 - - def read_urlencoded(self): - """Internal: read data in query string format.""" - qs = self.fp.read(self.length) - dict = parse_qs(qs) - self.list = [] - for key, valuelist in dict.items(): - for value in valuelist: - self.list.append(MiniFieldStorage(key, value)) - self.skip_lines() - - def read_multi(self): - """Internal: read a part that is itself multipart.""" - import rfc822 - self.list = [] - part = self.__class__(self.fp, {}, self.innerboundary) - # Throw first part away - while not part.done: - headers = rfc822.Message(self.fp) - part = self.__class__(self.fp, headers, self.innerboundary) - self.list.append(part) - self.skip_lines() - - def read_single(self): - """Internal: read an atomic part.""" - if self.length >= 0: - self.read_binary() - self.skip_lines() - else: - self.read_lines() - self.file.seek(0) - - bufsize = 8*1024 # I/O buffering size for copy to file - - def read_binary(self): - """Internal: read binary data.""" - self.file = self.make_file('b') - todo = self.length - if todo >= 0: - while todo > 0: - data = self.fp.read(min(todo, self.bufsize)) - if not data: - self.done = -1 - break - self.file.write(data) - todo = todo - len(data) - - def read_lines(self): - """Internal: read lines until EOF or outerboundary.""" - self.file = self.make_file('') - if self.outerboundary: - self.read_lines_to_outerboundary() - else: - self.read_lines_to_eof() - - def read_lines_to_eof(self): - """Internal: read lines until EOF.""" - while 1: - line = self.fp.readline() - if not line: - self.done = -1 - break - self.lines.append(line) - if line[-2:] == '\r\n': - line = line[:-2] + '\n' - self.file.write(line) - - def read_lines_to_outerboundary(self): - """Internal: read lines until outerboundary.""" - next = "--" + self.outerboundary - last = next + "--" - delim = "" - while 1: - line = self.fp.readline() - if not line: - self.done = -1 - break - self.lines.append(line) - if line[:2] == "--": - strippedline = string.strip(line) - if strippedline == next: - break - if strippedline == last: - self.done = 1 - break - if line[-2:] == "\r\n": - line = line[:-2] - elif line[-1] == "\n": - line = line[:-1] - self.file.write(delim + line) - delim = "\n" - - def skip_lines(self): - """Internal: skip lines until outer boundary if defined.""" - if not self.outerboundary or self.done: - return - next = "--" + self.outerboundary - last = next + "--" - while 1: - line = self.fp.readline() - if not line: - self.done = -1 - break - self.lines.append(line) - if line[:2] == "--": - strippedline = string.strip(line) - if strippedline == next: - break - if strippedline == last: - self.done = 1 - break - - def make_file(self, binary): - """Overridable: return a readable & writable file. - - The file will be used as follows: - - data is written to it - - seek(0) - - data is read from it - - The 'binary' argument is 'b' if the file should be created in - binary mode (on non-Unix systems), '' otherwise. - - This version opens a temporary file for reading and writing, - and immediately deletes (unlinks) it. The trick (on Unix!) is - that the file can still be used, but it can't be opened by - another process, and it will automatically be deleted when it - is closed or when the current process terminates. - - If you want a more permanent file, you derive a class which - overrides this method. If you want a visible temporary file - that is nevertheless automatically deleted when the script - terminates, try defining a __del__ method in a derived class - which unlinks the temporary files you have created. - - """ - import tempfile - tfn = tempfile.mktemp() - f = open(tfn, "w%s+" % binary) - os.unlink(tfn) - return f - - -# Backwards Compatibility Classes -# =============================== - -class FormContentDict: - """Basic (multiple values per field) form content as dictionary. - - form = FormContentDict() - - form[key] -> [value, value, ...] - form.has_key(key) -> Boolean - form.keys() -> [key, key, ...] - form.values() -> [[val, val, ...], [val, val, ...], ...] - form.items() -> [(key, [val, val, ...]), (key, [val, val, ...]), ...] - form.dict == {key: [val, val, ...], ...} - - """ - def __init__( self ): - self.dict = parse() - self.query_string = environ['QUERY_STRING'] - def __getitem__(self,key): - return self.dict[key] - def keys(self): - return self.dict.keys() - def has_key(self, key): - return self.dict.has_key(key) - def values(self): - return self.dict.values() - def items(self): - return self.dict.items() - def __len__( self ): - return len(self.dict) - - -class SvFormContentDict(FormContentDict): - """Strict single-value expecting form content as dictionary. - - IF you only expect a single value for each field, then form[key] - will return that single value. It will raise an IndexError if - that expectation is not true. IF you expect a field to have - possible multiple values, than you can use form.getlist(key) to - get all of the values. values() and items() are a compromise: - they return single strings where there is a single value, and - lists of strings otherwise. - - """ - def __getitem__(self, key): - if len(self.dict[key]) > 1: - raise IndexError, 'expecting a single value' - return self.dict[key][0] - def getlist(self, key): - return self.dict[key] - def values(self): - lis = [] - for each in self.dict.values(): - if len( each ) == 1 : - lis.append(each[0]) - else: lis.append(each) - return lis - def items(self): - lis = [] - for key,value in self.dict.items(): - if len(value) == 1 : - lis.append((key, value[0])) - else: lis.append((key, value)) - return lis - - -class InterpFormContentDict(SvFormContentDict): - """This class is present for backwards compatibility only.""" - def __getitem__( self, key ): - v = SvFormContentDict.__getitem__( self, key ) - if v[0] in string.digits+'+-.' : - try: return string.atoi( v ) - except ValueError: - try: return string.atof( v ) - except ValueError: pass - return string.strip(v) - def values( self ): - lis = [] - for key in self.keys(): - try: - lis.append( self[key] ) - except IndexError: - lis.append( self.dict[key] ) - return lis - def items( self ): - lis = [] - for key in self.keys(): - try: - lis.append( (key, self[key]) ) - except IndexError: - lis.append( (key, self.dict[key]) ) - return lis - - -class FormContent(FormContentDict): - """This class is present for backwards compatibility only.""" - def values(self, key): - if self.dict.has_key(key) :return self.dict[key] - else: return None - def indexed_value(self, key, location): - if self.dict.has_key(key): - if len (self.dict[key]) > location: - return self.dict[key][location] - else: return None - else: return None - def value(self, key): - if self.dict.has_key(key): return self.dict[key][0] - else: return None - def length(self, key): - return len(self.dict[key]) - def stripped(self, key): - if self.dict.has_key(key): return string.strip(self.dict[key][0]) - else: return None - def pars(self): - return self.dict - - -# Test/debug code -# =============== - -def test(): - """Robust test CGI script, usable as main program. - - Write minimal HTTP headers and dump all information provided to - the script in HTML form. - - """ - import traceback - print "Content-type: text/html" - print - sys.stderr = sys.stdout - try: - form = FieldStorage() # Replace with other classes to test those - print_form(form) - print_environ() - print_directory() - print_arguments() - print_environ_usage() - except: - print "\n\n<PRE>" # Turn off HTML word wrap - traceback.print_exc() - -def print_environ(): - """Dump the shell environment as HTML.""" - keys = environ.keys() - keys.sort() - print - print "<H3>Shell Environment:</H3>" - print "<DL>" - for key in keys: - print "<DT>", escape(key), "<DD>", escape(environ[key]) - print "</DL>" - print - -def print_form(form): - """Dump the contents of a form as HTML.""" - keys = form.keys() - keys.sort() - print - print "<H3>Form Contents:</H3>" - print "<DL>" - for key in keys: - print "<DT>" + escape(key) + ":", - value = form[key] - print "<i>" + escape(`type(value)`) + "</i>" - print "<DD>" + escape(`value`) - print "</DL>" - print - -def print_directory(): - """Dump the current directory as HTML.""" - print - print "<H3>Current Working Directory:</H3>" - try: - pwd = os.getcwd() - except os.error, msg: - print "os.error:", escape(str(msg)) - else: - print escape(pwd) - print - -def print_arguments(): - print - print "<H3>Command Line Arguments:</H3>" - print - print sys.argv - print - -def print_environ_usage(): - """Dump a list of environment variables used by CGI as HTML.""" - print """ -<H3>These environment variables could have been set:</H3> -<UL> -<LI>AUTH_TYPE -<LI>CONTENT_LENGTH -<LI>CONTENT_TYPE -<LI>DATE_GMT -<LI>DATE_LOCAL -<LI>DOCUMENT_NAME -<LI>DOCUMENT_ROOT -<LI>DOCUMENT_URI -<LI>GATEWAY_INTERFACE -<LI>LAST_MODIFIED -<LI>PATH -<LI>PATH_INFO -<LI>PATH_TRANSLATED -<LI>QUERY_STRING -<LI>REMOTE_ADDR -<LI>REMOTE_HOST -<LI>REMOTE_IDENT -<LI>REMOTE_USER -<LI>REQUEST_METHOD -<LI>SCRIPT_NAME -<LI>SERVER_NAME -<LI>SERVER_PORT -<LI>SERVER_PROTOCOL -<LI>SERVER_ROOT -<LI>SERVER_SOFTWARE -</UL> -In addition, HTTP headers sent by the server may be passed in the -environment as well. Here are some common variable names: -<UL> -<LI>HTTP_ACCEPT -<LI>HTTP_CONNECTION -<LI>HTTP_HOST -<LI>HTTP_PRAGMA -<LI>HTTP_REFERER -<LI>HTTP_USER_AGENT -</UL> -""" - - -# Utilities -# ========= - -def escape(s): - """Replace special characters '&', '<' and '>' by SGML entities.""" - import regsub - s = regsub.gsub("&", "&amp;", s) # Must be done first! - s = regsub.gsub("<", "&lt;", s) - s = regsub.gsub(">", "&gt;", s) - return s - - -# Invoke mainline -# =============== - -# Call test() when this file is run as a script (not imported as a module) -if __name__ == '__main__': - test() diff --git a/Lib/cmd.py b/Lib/cmd.py deleted file mode 100644 index 85115bb9b5..0000000000 --- a/Lib/cmd.py +++ /dev/null @@ -1,91 +0,0 @@ -# A generic class to build line-oriented command interpreters - -import string -import sys -import linecache - -PROMPT = '(Cmd) ' -IDENTCHARS = string.letters + string.digits + '_' - -class Cmd: - - def __init__(self): - self.prompt = PROMPT - self.identchars = IDENTCHARS - self.lastcmd = '' - - def cmdloop(self): - stop = None - while not stop: - try: - line = raw_input(self.prompt) - except EOFError: - line = 'EOF' - stop = self.onecmd(line) - - def onecmd(self, line): - line = string.strip(line) - if not line: - line = self.lastcmd - else: - self.lastcmd = line - i, n = 0, len(line) - while i < n and line[i] in self.identchars: i = i+1 - cmd, arg = line[:i], string.strip(line[i:]) - if cmd == '': - return self.default(line) - else: - try: - func = getattr(self, 'do_' + cmd) - except AttributeError: - return self.default(line) - return func(arg) - - def default(self, line): - print '*** Unknown syntax:', line - - def do_help(self, arg): - if arg: - # XXX check arg syntax - try: - func = getattr(self, 'help_' + arg) - except: - print '*** No help on', `arg` - return - func() - else: - import newdir - names = newdir.dir(self.__class__) - cmds_doc = [] - cmds_undoc = [] - help = {} - for name in names: - if name[:5] == 'help_': - help[name[5:]]=1 - for name in names: - if name[:3] == 'do_': - cmd=name[3:] - if help.has_key(cmd): - cmds_doc.append(cmd) - del help[cmd] - else: - cmds_undoc.append(cmd) - print - self.print_topics("Documented commands (type help " \ - "<topic>):",cmds_doc, 15, 80) - self.print_topics("Miscellaneous help topics:", - help.keys(), 15, 80) - self.print_topics("Undocumented commands:", - cmds_undoc, 15, 80) - - def print_topics(self, header, cmds, cmdlen, maxcol): - if cmds: - print header; - print "="*len(header) - (cmds_per_line,junk)=divmod(maxcol,cmdlen) - col=cmds_per_line - for cmd in cmds: - if col==0: print - print (("%-"+`cmdlen`+"s") % cmd), - col = (col+1) % cmds_per_line - print "\n" diff --git a/Lib/cmp.py b/Lib/cmp.py deleted file mode 100644 index 4ebdfc60a2..0000000000 --- a/Lib/cmp.py +++ /dev/null @@ -1,61 +0,0 @@ -# Module 'cmp' - -# Efficiently compare files, boolean outcome only (equal / not equal). - -# Tricks (used in this order): -# - Files with identical type, size & mtime are assumed to be clones -# - Files with different type or size cannot be identical -# - We keep a cache of outcomes of earlier comparisons -# - We don't fork a process to run 'cmp' but read the files ourselves - -import os - -cache = {} - -def cmp(f1, f2): # Compare two files, use the cache if possible. - # Return 1 for identical files, 0 for different. - # Raise exceptions if either file could not be statted, read, etc. - s1, s2 = sig(os.stat(f1)), sig(os.stat(f2)) - if s1[0] <> 8 or s2[0] <> 8: - # Either is a not a plain file -- always report as different - return 0 - if s1 == s2: - # type, size & mtime match -- report same - return 1 - if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother - # types or sizes differ -- report different - return 0 - # same type and size -- look in the cache - key = f1 + ' ' + f2 - try: - cs1, cs2, outcome = cache[key] - # cache hit - if s1 == cs1 and s2 == cs2: - # cached signatures match - return outcome - # stale cached signature(s) - except KeyError: - # cache miss - pass - # really compare - outcome = do_cmp(f1, f2) - cache[key] = s1, s2, outcome - return outcome - -def sig(st): # Return signature (i.e., type, size, mtime) from raw stat data - # 0-5: st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid - # 6-9: st_size, st_atime, st_mtime, st_ctime - type = st[0] / 4096 - size = st[6] - mtime = st[8] - return type, size, mtime - -def do_cmp(f1, f2): # Compare two files, really - bufsize = 8*1024 # Could be tuned - fp1 = open(f1, 'r') - fp2 = open(f2, 'r') - while 1: - b1 = fp1.read(bufsize) - b2 = fp2.read(bufsize) - if b1 <> b2: return 0 - if not b1: return 1 diff --git a/Lib/cmpcache.py b/Lib/cmpcache.py deleted file mode 100644 index 494dcc1c46..0000000000 --- a/Lib/cmpcache.py +++ /dev/null @@ -1,68 +0,0 @@ -# Module 'cmpcache' -# -# Efficiently compare files, boolean outcome only (equal / not equal). -# -# Tricks (used in this order): -# - Use the statcache module to avoid statting files more than once -# - Files with identical type, size & mtime are assumed to be clones -# - Files with different type or size cannot be identical -# - We keep a cache of outcomes of earlier comparisons -# - We don't fork a process to run 'cmp' but read the files ourselves - -import os -from stat import * -import statcache - - -# The cache. -# -cache = {} - - -# Compare two files, use the cache if possible. -# May raise os.error if a stat or open of either fails. -# -def cmp(f1, f2): - # Return 1 for identical files, 0 for different. - # Raise exceptions if either file could not be statted, read, etc. - s1, s2 = sig(statcache.stat(f1)), sig(statcache.stat(f2)) - if not S_ISREG(s1[0]) or not S_ISREG(s2[0]): - # Either is a not a plain file -- always report as different - return 0 - if s1 == s2: - # type, size & mtime match -- report same - return 1 - if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother - # types or sizes differ -- report different - return 0 - # same type and size -- look in the cache - key = f1 + ' ' + f2 - if cache.has_key(key): - cs1, cs2, outcome = cache[key] - # cache hit - if s1 == cs1 and s2 == cs2: - # cached signatures match - return outcome - # stale cached signature(s) - # really compare - outcome = do_cmp(f1, f2) - cache[key] = s1, s2, outcome - return outcome - -# Return signature (i.e., type, size, mtime) from raw stat data. -# -def sig(st): - return S_IFMT(st[ST_MODE]), st[ST_SIZE], st[ST_MTIME] - -# Compare two files, really. -# -def do_cmp(f1, f2): - #print ' cmp', f1, f2 # XXX remove when debugged - bufsize = 8*1024 # Could be tuned - fp1 = open(f1, 'r') - fp2 = open(f2, 'r') - while 1: - b1 = fp1.read(bufsize) - b2 = fp2.read(bufsize) - if b1 <> b2: return 0 - if not b1: return 1 diff --git a/Lib/codehack.py b/Lib/codehack.py deleted file mode 100644 index 1f16814224..0000000000 --- a/Lib/codehack.py +++ /dev/null @@ -1,67 +0,0 @@ -# A subroutine for extracting a function name from a code object -# (with cache) - -import sys -from stat import * -import string -import os -import linecache - -# XXX The functions getcodename() and getfuncname() are now obsolete -# XXX as code and function objects now have a name attribute -- -# XXX co.co_name and f.func_name. - -# Extract the function or class name from a code object. -# This is a bit of a hack, since a code object doesn't contain -# the name directly. So what do we do: -# - get the filename (which *is* in the code object) -# - look in the code string to find the first SET_LINENO instruction -# (this must be the first instruction) -# - get the line from the file -# - if the line starts with 'class' or 'def' (after possible whitespace), -# extract the following identifier -# -# This breaks apart when the function was read from <stdin> -# or constructed by exec(), when the file is not accessible, -# and also when the file has been modified or when a line is -# continued with a backslash before the function or class name. -# -# Because this is a pretty expensive hack, a cache is kept. - -SET_LINENO = 127 # The opcode (see "opcode.h" in the Python source) -identchars = string.letters + string.digits + '_' # Identifier characters - -_namecache = {} # The cache - -def getcodename(co): - key = `co` # arbitrary but uniquely identifying string - if _namecache.has_key(key): return _namecache[key] - filename = co.co_filename - code = co.co_code - name = '' - if ord(code[0]) == SET_LINENO: - lineno = ord(code[1]) | ord(code[2]) << 8 - line = linecache.getline(filename, lineno) - words = string.split(line) - if len(words) >= 2 and words[0] in ('def', 'class'): - name = words[1] - for i in range(len(name)): - if name[i] not in identchars: - name = name[:i] - break - _namecache[key] = name - return name - -# Use the above routine to find a function's name. - -def getfuncname(func): - return getcodename(func.func_code) - -# A part of the above code to extract just the line number from a code object. - -def getlineno(co): - code = co.co_code - if ord(code[0]) == SET_LINENO: - return ord(code[1]) | ord(code[2]) << 8 - else: - return -1 diff --git a/Lib/colorsys.py b/Lib/colorsys.py deleted file mode 100644 index c48b2cbc30..0000000000 --- a/Lib/colorsys.py +++ /dev/null @@ -1,119 +0,0 @@ -# Conversion functions between RGB and other color systems. -# -# Define two functions for each color system XYZ: -# rgb_to_xyz(r, g, b) --> x, y, z -# xyz_to_rgb(x, y, z) --> r, g, b -# All inputs and outputs are triples of floats in the range [0.0...1.0]. -# Inputs outside this range may cause exceptions or invalid outputs. -# -# Supported color systems: -# RGB: Red, Green, Blue components -# YIQ: used by composite video signals -# HLS: Hue, Luminance, S??? -# HSV: Hue, Saturation, Value(?) -# -# References: -# XXX Where's the literature? - - -# Some floating point constants - -ONE_THIRD = 1.0/3.0 -ONE_SIXTH = 1.0/6.0 -TWO_THIRD = 2.0/3.0 - - -# YIQ: used by composite video signals (linear combinations of RGB) -# Y: perceived grey level (0.0 == black, 1.0 == white) -# I, Q: color components - -def rgb_to_yiq(r, g, b): - y = 0.30*r + 0.59*g + 0.11*b - i = 0.60*r - 0.28*g - 0.32*b - q = 0.21*r - 0.52*g + 0.31*b - return (y, i, q) - -def yiq_to_rgb(y, i, q): - r = y + 0.948262*i + 0.624013*q - g = y - 0.276066*i - 0.639810*q - b = y - 1.105450*i + 1.729860*q - if r < 0.0: r = 0.0 - if g < 0.0: g = 0.0 - if b < 0.0: b = 0.0 - if r > 1.0: r = 1.0 - if g > 1.0: g = 1.0 - if b > 1.0: b = 1.0 - return (r, g, b) - - -# HLS: Hue, Luminance, S??? -# H: position in the spectrum -# L: ??? -# S: ??? - -def rgb_to_hls(r, g, b): - maxc = max(r, g, b) - minc = min(r, g, b) - # XXX Can optimize (maxc+minc) and (maxc-minc) - l = (minc+maxc)/2.0 - if minc == maxc: return 0.0, l, 0.0 - if l <= 0.5: s = (maxc-minc) / (maxc+minc) - else: s = (maxc-minc) / (2.0-maxc-minc) - rc = (maxc-r) / (maxc-minc) - gc = (maxc-g) / (maxc-minc) - bc = (maxc-b) / (maxc-minc) - if r == maxc: h = bc-gc - elif g == maxc: h = 2.0+rc-bc - else: h = 4.0+gc-rc - h = (h/6.0) % 1.0 - return h, l, s - -def hls_to_rgb(h, l, s): - if s == 0.0: return l, l, l - if l <= 0.5: m2 = l * (1.0+s) - else: m2 = l+s-(l*s) - m1 = 2.0*l - m2 - return (_v(m1, m2, h+ONE_THIRD), _v(m1, m2, h), _v(m1, m2, h-ONE_THIRD)) - -def _v(m1, m2, hue): - hue = hue % 1.0 - if hue < ONE_SIXTH: return m1 + (m2-m1)*hue*6.0 - if hue < 0.5: return m2 - if hue < TWO_THIRD: return m1 + (m2-m1)*(TWO_THIRD-hue)*6.0 - return m1 - - -# HSV: Hue, Saturation, Value(?) -# H: position in the spectrum -# S: ??? -# V: ??? - -def rgb_to_hsv(r, g, b): - maxc = max(r, g, b) - minc = min(r, g, b) - v = maxc - if minc == maxc: return 0.0, 0.0, v - s = (maxc-minc) / maxc - rc = (maxc-r) / (maxc-minc) - gc = (maxc-g) / (maxc-minc) - bc = (maxc-b) / (maxc-minc) - if r == maxc: h = bc-gc - elif g == maxc: h = 2.0+rc-bc - else: h = 4.0+gc-rc - h = (h/6.0) % 1.0 - return h, s, v - -def hsv_to_rgb(h, s, v): - if s == 0.0: return v, v, v - i = int(h*6.0) # XXX assume int() truncates! - f = (h*6.0) - i - p = v*(1.0 - s) - q = v*(1.0 - s*f) - t = v*(1.0 - s*(1.0-f)) - if i%6 == 0: return v, t, p - if i == 1: return q, v, p - if i == 2: return p, v, t - if i == 3: return p, q, v - if i == 4: return t, p, v - if i == 5: return v, p, q - # Cannot get here diff --git a/Lib/commands.py b/Lib/commands.py deleted file mode 100644 index 6471a8db59..0000000000 --- a/Lib/commands.py +++ /dev/null @@ -1,58 +0,0 @@ -# Module 'commands' -# -# Various tools for executing commands and looking at their output and status. -# -# NB This only works (and is only relevant) for UNIX. - - -# Get 'ls -l' status for an object into a string -# -def getstatus(file): - return getoutput('ls -ld' + mkarg(file)) - - -# Get the output from a shell command into a string. -# The exit status is ignored; a trailing newline is stripped. -# Assume the command will work with '{ ... ; } 2>&1' around it.. -# -def getoutput(cmd): - return getstatusoutput(cmd)[1] - - -# Ditto but preserving the exit status. -# Returns a pair (sts, output) -# -def getstatusoutput(cmd): - import os - pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') - text = pipe.read() - sts = pipe.close() - if sts == None: sts = 0 - if text[-1:] == '\n': text = text[:-1] - return sts, text - - -# Make command argument from directory and pathname (prefix space, add quotes). -# -def mk2arg(head, x): - import os - return mkarg(os.path.join(head, x)) - - -# Make a shell command argument from a string. -# Return a string beginning with a space followed by a shell-quoted -# version of the argument. -# Two strategies: enclose in single quotes if it contains none; -# otherwise, enclose in double quotes and prefix quotable characters -# with backslash. -# -def mkarg(x): - if '\'' not in x: - return ' \'' + x + '\'' - s = ' "' - for c in x: - if c in '\\$"`': - s = s + '\\' - s = s + c - s = s + '"' - return s diff --git a/Lib/compileall.py b/Lib/compileall.py deleted file mode 100644 index 312028407d..0000000000 --- a/Lib/compileall.py +++ /dev/null @@ -1,70 +0,0 @@ -# Routines to force "compilation" of all .py files in a directory -# tree or on sys.path. By default recursion is pruned at a depth of -# 10 and the current directory, if it occurs in sys.path, is skipped. -# When called as a script, compiles argument directories, or sys.path -# if no arguments. -# After a similar module by Sjoerd Mullender. - -import os -import sys -import py_compile - -def compile_dir(dir, maxlevels = 10): - print 'Listing', dir, '...' - try: - names = os.listdir(dir) - except os.error: - print "Can't list", dir - names = [] - names.sort() - for name in names: - fullname = os.path.join(dir, name) - if os.path.isfile(fullname): - head, tail = name[:-3], name[-3:] - if tail == '.py': - print 'Compiling', fullname, '...' - try: - py_compile.compile(fullname) - except KeyboardInterrupt: - del names[:] - print '\n[interrupt]' - break - except: - if type(sys.exc_type) == type(''): - exc_type_name = sys.exc_type - else: exc_type_name = sys.exc_type.__name__ - print 'Sorry:', exc_type_name + ':', - print sys.exc_value - elif maxlevels > 0 and \ - name != os.curdir and name != os.pardir and \ - os.path.isdir(fullname) and \ - not os.path.islink(fullname): - compile_dir(fullname, maxlevels - 1) - -def compile_path(skip_curdir = 1): - for dir in sys.path: - if dir == os.curdir and skip_curdir: - print 'Skipping current directory' - else: - compile_dir(dir, 0) - -def main(): - import getopt - try: - opts, args = getopt.getopt(sys.argv[1:], 'l') - except getopt.error, msg: - print msg - print "usage: compileall [-l] [directory ...]" - print "-l: don't recurse down" - print "if no arguments, -l sys.path is assumed" - maxlevels = 10 - for o, a in opts: - if o == '-l': maxlevels = 0 - if args: - for dir in sys.argv[1:]: - compile_dir(dir, maxlevels) - else: - compile_path() - -if __name__ == '__main__': - main() diff --git a/Lib/copy.py b/Lib/copy.py deleted file mode 100644 index a48e8c8e3a..0000000000 --- a/Lib/copy.py +++ /dev/null @@ -1,273 +0,0 @@ -"""\ -Generic (shallow and deep) copying operations -============================================= - -Interface summary: - - import copy - - x = copy.copy(y) # make a shallow copy of y - x = copy.deepcopy(y) # make a deep copy of y - -For module specific errors, copy.error is raised. - -The difference between shallow and deep copying is only relevant for -compound objects (objects that contain other objects, like lists or -class instances). - -- A shallow copy constructs a new compound object and then (to the - extent possible) inserts *the same objects* into in that the - original contains. - -- A deep copy constructs a new compound object and then, recursively, - inserts *copies* into it of the objects found in the original. - -Two problems often exist with deep copy operations that don't exist -with shallow copy operations: - -(a) recursive objects (compound objects that, directly or indirectly, - contain a reference to themselves) may cause a recursive loop - -(b) because deep copy copies *everything* it may copy too much, e.g. - administrative data structures that should be shared even between - copies - -Python's deep copy operation avoids these problems by: - -(a) keeping a table of objects already copied during the current -copying pass - -(b) letting user-defined classes override the copying operation or the - set of components copied - -This version does not copy types like module, class, function, method, -nor stack trace, stack frame, nor file, socket, window, nor array, nor -any similar types. - -Classes can use the same interfaces to control copying that they use -to control pickling: they can define methods called __getinitargs__(), -__getstate__() and __setstate__(). See the __doc__ string of module -"pickle" for information on these methods. -""" - -import types - -error = 'copy.error' -Error = error # backward compatibility - -def copy(x): - """Shallow copy operation on arbitrary Python objects. - - See the module's __doc__ string for more info. - """ - - try: - copierfunction = _copy_dispatch[type(x)] - except KeyError: - try: - copier = x.__copy__ - except AttributeError: - raise error, \ - "un(shallow)copyable object of type %s" % type(x) - y = copier() - else: - y = copierfunction(x) - return y - -_copy_dispatch = d = {} - -def _copy_atomic(x): - return x -d[types.NoneType] = _copy_atomic -d[types.IntType] = _copy_atomic -d[types.LongType] = _copy_atomic -d[types.FloatType] = _copy_atomic -d[types.StringType] = _copy_atomic -d[types.CodeType] = _copy_atomic -d[types.TypeType] = _copy_atomic -d[types.XRangeType] = _copy_atomic -d[types.ClassType] = _copy_atomic - -def _copy_list(x): - return x[:] -d[types.ListType] = _copy_list - -def _copy_tuple(x): - return x[:] -d[types.TupleType] = _copy_tuple - -def _copy_dict(x): - y = {} - for key in x.keys(): - y[key] = x[key] - return y -d[types.DictionaryType] = _copy_dict - -def _copy_inst(x): - if hasattr(x, '__copy__'): - return x.__copy__() - if hasattr(x, '__getinitargs__'): - args = x.__getinitargs__() - else: - args = () - y = apply(x.__class__, args) - if hasattr(x, '__getstate__'): - state = x.__getstate__() - else: - state = x.__dict__ - if hasattr(y, '__setstate__'): - y.__setstate__(state) - else: - for key in state.keys(): - setattr(y, key, state[key]) - return y -d[types.InstanceType] = _copy_inst - -del d - -def deepcopy(x, memo = None): - """Deep copy operation on arbitrary Python objects. - - See the module's __doc__ string for more info. - """ - - if memo is None: - memo = {} - d = id(x) - if memo.has_key(d): - return memo[d] - try: - copierfunction = _deepcopy_dispatch[type(x)] - except KeyError: - try: - copier = x.__deepcopy__ - except AttributeError: - raise error, \ - "un-deep-copyable object of type %s" % type(x) - y = copier(memo) - else: - y = copierfunction(x, memo) - memo[d] = y - return y - -_deepcopy_dispatch = d = {} - -def _deepcopy_atomic(x, memo): - return x -d[types.NoneType] = _deepcopy_atomic -d[types.IntType] = _deepcopy_atomic -d[types.LongType] = _deepcopy_atomic -d[types.FloatType] = _deepcopy_atomic -d[types.StringType] = _deepcopy_atomic -d[types.CodeType] = _deepcopy_atomic -d[types.TypeType] = _deepcopy_atomic -d[types.XRangeType] = _deepcopy_atomic - -def _deepcopy_list(x, memo): - y = [] - memo[id(x)] = y - for a in x: - y.append(deepcopy(a, memo)) - return y -d[types.ListType] = _deepcopy_list - -def _deepcopy_tuple(x, memo): - y = [] - for a in x: - y.append(deepcopy(a, memo)) - d = id(x) - try: - return memo[d] - except KeyError: - pass - for i in range(len(x)): - if x[i] is not y[i]: - return tuple(y) - return x -d[types.TupleType] = _deepcopy_tuple - -def _deepcopy_dict(x, memo): - y = {} - memo[id(x)] = y - for key in x.keys(): - y[deepcopy(key, memo)] = deepcopy(x[key], memo) - return y -d[types.DictionaryType] = _deepcopy_dict - -def _deepcopy_inst(x, memo): - if hasattr(x, '__deepcopy__'): - return x.__deepcopy__() - if hasattr(x, '__getinitargs__'): - args = x.__getinitargs__() - args = deepcopy(args, memo) - else: - args = () - y = apply(x.__class__, args) - memo[id(x)] = y - if hasattr(x, '__getstate__'): - state = x.__getstate__() - else: - state = x.__dict__ - state = deepcopy(state, memo) - if hasattr(y, '__setstate__'): - y.__setstate__(state) - else: - for key in state.keys(): - setattr(y, key, state[key]) - return y -d[types.InstanceType] = _deepcopy_inst - -del d - -del types - -def _test(): - l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'], - {'abc': 'ABC'}, (), [], {}] - l1 = copy(l) - print l1==l - l1 = map(copy, l) - print l1==l - l1 = deepcopy(l) - print l1==l - class C: - def __init__(self, arg=None): - self.a = 1 - self.arg = arg - self.fp = open('copy.py') - self.fp.close() - def __getstate__(self): - return {'a': self.a, 'arg': self.arg} - def __setstate__(self, state): - for key in state.keys(): - setattr(self, key, state[key]) - def __deepcopy__(self, memo = None): - new = self.__class__(deepcopy(self.arg, memo)) - new.a = self.a - return new - c = C('argument sketch') - l.append(c) - l2 = copy(l) - print l == l2 - print l - print l2 - l2 = deepcopy(l) - print l == l2 - print l - print l2 - l.append({l[1]: l, 'xyz': l[2]}) - l3 = copy(l) - import repr - print map(repr.repr, l) - print map(repr.repr, l1) - print map(repr.repr, l2) - print map(repr.repr, l3) - l3 = deepcopy(l) - import repr - print map(repr.repr, l) - print map(repr.repr, l1) - print map(repr.repr, l2) - print map(repr.repr, l3) - -if __name__ == '__main__': - _test() diff --git a/Lib/dbhash.py b/Lib/dbhash.py deleted file mode 100644 index 57c6194b6c..0000000000 --- a/Lib/dbhash.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Provide a (g)dbm-compatible interface to bsdhash.hashopen.""" - -import bsddb - -error = bsddb.error - -def open(file, flag, mode): - return bsddb.hashopen(file, flag, mode) diff --git a/Lib/dircache.py b/Lib/dircache.py deleted file mode 100644 index ef68b429f9..0000000000 --- a/Lib/dircache.py +++ /dev/null @@ -1,35 +0,0 @@ -# Module 'dircache' -# -# Return a sorted list of the files in a directory, using a cache -# to avoid reading the directory more often than necessary. -# Also contains a subroutine to append slashes to directories. - -import os - -cache = {} - -def listdir(path): # List directory contents, using cache - try: - cached_mtime, list = cache[path] - del cache[path] - except KeyError: - cached_mtime, list = -1, [] - try: - mtime = os.stat(path)[8] - except os.error: - return [] - if mtime <> cached_mtime: - try: - list = os.listdir(path) - except os.error: - return [] - list.sort() - cache[path] = mtime, list - return list - -opendir = listdir # XXX backward compatibility - -def annotate(head, list): # Add '/' suffixes to directories - for i in range(len(list)): - if os.path.isdir(os.path.join(head, list[i])): - list[i] = list[i] + '/' diff --git a/Lib/dircmp.py b/Lib/dircmp.py deleted file mode 100644 index 1227aa753c..0000000000 --- a/Lib/dircmp.py +++ /dev/null @@ -1,203 +0,0 @@ -# Module 'dirmp' -# -# Defines a class to build directory diff tools on. - -import os - -import dircache -import cmpcache -import statcache -from stat import * - -# Directory comparison class. -# -class dircmp: - # - def new(self, a, b): # Initialize - self.a = a - self.b = b - # Properties that caller may change before calling self.run(): - self.hide = [os.curdir, os.pardir] # Names never to be shown - self.ignore = ['RCS', 'tags'] # Names ignored in comparison - # - return self - # - def run(self): # Compare everything except common subdirectories - self.a_list = filter(dircache.listdir(self.a), self.hide) - self.b_list = filter(dircache.listdir(self.b), self.hide) - self.a_list.sort() - self.b_list.sort() - self.phase1() - self.phase2() - self.phase3() - # - def phase1(self): # Compute common names - self.a_only = [] - self.common = [] - for x in self.a_list: - if x in self.b_list: - self.common.append(x) - else: - self.a_only.append(x) - # - self.b_only = [] - for x in self.b_list: - if x not in self.common: - self.b_only.append(x) - # - def phase2(self): # Distinguish files, directories, funnies - self.common_dirs = [] - self.common_files = [] - self.common_funny = [] - # - for x in self.common: - a_path = os.path.join(self.a, x) - b_path = os.path.join(self.b, x) - # - ok = 1 - try: - a_stat = statcache.stat(a_path) - except os.error, why: - # print 'Can\'t stat', a_path, ':', why[1] - ok = 0 - try: - b_stat = statcache.stat(b_path) - except os.error, why: - # print 'Can\'t stat', b_path, ':', why[1] - ok = 0 - # - if ok: - a_type = S_IFMT(a_stat[ST_MODE]) - b_type = S_IFMT(b_stat[ST_MODE]) - if a_type <> b_type: - self.common_funny.append(x) - elif S_ISDIR(a_type): - self.common_dirs.append(x) - elif S_ISREG(a_type): - self.common_files.append(x) - else: - self.common_funny.append(x) - else: - self.common_funny.append(x) - # - def phase3(self): # Find out differences between common files - xx = cmpfiles(self.a, self.b, self.common_files) - self.same_files, self.diff_files, self.funny_files = xx - # - def phase4(self): # Find out differences between common subdirectories - # A new dircmp object is created for each common subdirectory, - # these are stored in a dictionary indexed by filename. - # The hide and ignore properties are inherited from the parent - self.subdirs = {} - for x in self.common_dirs: - a_x = os.path.join(self.a, x) - b_x = os.path.join(self.b, x) - self.subdirs[x] = newdd = dircmp().new(a_x, b_x) - newdd.hide = self.hide - newdd.ignore = self.ignore - newdd.run() - # - def phase4_closure(self): # Recursively call phase4() on subdirectories - self.phase4() - for x in self.subdirs.keys(): - self.subdirs[x].phase4_closure() - # - def report(self): # Print a report on the differences between a and b - # Assume that phases 1 to 3 have been executed - # Output format is purposely lousy - print 'diff', self.a, self.b - if self.a_only: - print 'Only in', self.a, ':', self.a_only - if self.b_only: - print 'Only in', self.b, ':', self.b_only - if self.same_files: - print 'Identical files :', self.same_files - if self.diff_files: - print 'Differing files :', self.diff_files - if self.funny_files: - print 'Trouble with common files :', self.funny_files - if self.common_dirs: - print 'Common subdirectories :', self.common_dirs - if self.common_funny: - print 'Common funny cases :', self.common_funny - # - def report_closure(self): # Print reports on self and on subdirs - # If phase 4 hasn't been done, no subdir reports are printed - self.report() - try: - x = self.subdirs - except AttributeError: - return # No subdirectories computed - for x in self.subdirs.keys(): - print - self.subdirs[x].report_closure() - # - def report_phase4_closure(self): # Report and do phase 4 recursively - self.report() - self.phase4() - for x in self.subdirs.keys(): - print - self.subdirs[x].report_phase4_closure() - - -# Compare common files in two directories. -# Return: -# - files that compare equal -# - files that compare different -# - funny cases (can't stat etc.) -# -def cmpfiles(a, b, common): - res = ([], [], []) - for x in common: - res[cmp(os.path.join(a, x), os.path.join(b, x))].append(x) - return res - - -# Compare two files. -# Return: -# 0 for equal -# 1 for different -# 2 for funny cases (can't stat, etc.) -# -def cmp(a, b): - try: - if cmpcache.cmp(a, b): return 0 - return 1 - except os.error: - return 2 - - -# Remove a list item. -# NB: This modifies the list argument. -# -def remove(list, item): - for i in range(len(list)): - if list[i] == item: - del list[i] - break - - -# Return a copy with items that occur in skip removed. -# -def filter(list, skip): - result = [] - for item in list: - if item not in skip: result.append(item) - return result - - -# Demonstration and testing. -# -def demo(): - import sys - import getopt - options, args = getopt.getopt(sys.argv[1:], 'r') - if len(args) <> 2: raise getopt.error, 'need exactly two args' - dd = dircmp().new(args[0], args[1]) - dd.run() - if ('-r', '') in options: - dd.report_phase4_closure() - else: - dd.report() - -# demo() diff --git a/Lib/dis.py b/Lib/dis.py deleted file mode 100644 index 846dc32ba1..0000000000 --- a/Lib/dis.py +++ /dev/null @@ -1,190 +0,0 @@ -# Disassembler - -import sys -import string - -def dis(): - tb = sys.last_traceback - while tb.tb_next: tb = tb.tb_next - distb(tb) - -def distb(tb): - disassemble(tb.tb_frame.f_code, tb.tb_lasti) - -def disco(co): - disassemble(co, -1) - -def disassemble(co, lasti): - code = co.co_code - labels = findlabels(code) - n = len(code) - i = 0 - while i < n: - c = code[i] - op = ord(c) - if op == SET_LINENO and i > 0: print # Extra blank line - if i == lasti: print '-->', - else: print ' ', - if i in labels: print '>>', - else: print ' ', - print string.rjust(`i`, 4), - print string.ljust(opname[op], 15), - i = i+1 - if op >= HAVE_ARGUMENT: - oparg = ord(code[i]) + ord(code[i+1])*256 - i = i+2 - print string.rjust(`oparg`, 5), - if op in hasconst: - print '(' + `co.co_consts[oparg]` + ')', - elif op in hasname: - print '(' + co.co_names[oparg] + ')', - elif op in hasjrel: - print '(to ' + `i + oparg` + ')', - print - -def findlabels(code): - labels = [] - n = len(code) - i = 0 - while i < n: - c = code[i] - op = ord(c) - i = i+1 - if op >= HAVE_ARGUMENT: - oparg = ord(code[i]) + ord(code[i+1])*256 - i = i+2 - label = -1 - if op in hasjrel: - label = i+oparg - elif op in hasjabs: - label = oparg - if label >= 0: - if label not in labels: - labels.append(label) - return labels - -hasconst = [] -hasname = [] -hasjrel = [] -hasjabs = [] - -opname = [''] * 256 -for op in range(256): opname[op] = '<' + `op` + '>' - -def def_op(name, op): - opname[op] = name - -def name_op(name, op): - opname[op] = name - hasname.append(op) - -def jrel_op(name, op): - opname[op] = name - hasjrel.append(op) - -def jabs_op(name, op): - opname[op] = name - hasjabs.append(op) - -# Instruction opcodes for compiled code - -def_op('STOP_CODE', 0) -def_op('POP_TOP', 1) -def_op('ROT_TWO', 2) -def_op('ROT_THREE', 3) -def_op('DUP_TOP', 4) - -def_op('UNARY_POSITIVE', 10) -def_op('UNARY_NEGATIVE', 11) -def_op('UNARY_NOT', 12) -def_op('UNARY_CONVERT', 13) -def_op('UNARY_CALL', 14) -def_op('UNARY_INVERT', 15) - -def_op('BINARY_MULTIPLY', 20) -def_op('BINARY_DIVIDE', 21) -def_op('BINARY_MODULO', 22) -def_op('BINARY_ADD', 23) -def_op('BINARY_SUBTRACT', 24) -def_op('BINARY_SUBSCR', 25) -def_op('BINARY_CALL', 26) - -def_op('SLICE+0', 30) -def_op('SLICE+1', 31) -def_op('SLICE+2', 32) -def_op('SLICE+3', 33) - -def_op('STORE_SLICE+0', 40) -def_op('STORE_SLICE+1', 41) -def_op('STORE_SLICE+2', 42) -def_op('STORE_SLICE+3', 43) - -def_op('DELETE_SLICE+0', 50) -def_op('DELETE_SLICE+1', 51) -def_op('DELETE_SLICE+2', 52) -def_op('DELETE_SLICE+3', 53) - -def_op('STORE_SUBSCR', 60) -def_op('DELETE_SUBSCR', 61) - -def_op('PRINT_EXPR', 70) -def_op('PRINT_ITEM', 71) -def_op('PRINT_NEWLINE', 72) - -def_op('BREAK_LOOP', 80) -def_op('RAISE_EXCEPTION', 81) -def_op('LOAD_LOCALS', 82) -def_op('RETURN_VALUE', 83) -def_op('LOAD_GLOBALS', 84) -def_op('EXEC_STMT', 85) -def_op('BUILD_FUNCTION', 86) -def_op('POP_BLOCK', 87) -def_op('END_FINALLY', 88) -def_op('BUILD_CLASS', 89) - -HAVE_ARGUMENT = 90 # Opcodes from here have an argument: - -name_op('STORE_NAME', 90) # Index in name list -name_op('DELETE_NAME', 91) # "" -def_op('UNPACK_TUPLE', 92) # Number of tuple items -def_op('UNPACK_LIST', 93) # Number of list items -def_op('UNPACK_ARG', 94) # Number of arguments expected -name_op('STORE_ATTR', 95) # Index in name list -name_op('DELETE_ATTR', 96) # "" -name_op('STORE_GLOBAL', 97) # "" -name_op('DELETE_GLOBAL', 98) # "" -name_op('UNPACK_VARARG', 99) # Minimal number of arguments - -def_op('LOAD_CONST', 100) # Index in const list -hasconst.append(100) -name_op('LOAD_NAME', 101) # Index in name list -def_op('BUILD_TUPLE', 102) # Number of tuple items -def_op('BUILD_LIST', 103) # Number of list items -def_op('BUILD_MAP', 104) # Always zero for now -name_op('LOAD_ATTR', 105) # Index in name list -def_op('COMPARE_OP', 106) # Comparison operator -name_op('IMPORT_NAME', 107) # Index in name list -name_op('IMPORT_FROM', 108) # Index in name list - -jrel_op('JUMP_FORWARD', 110) # Number of bytes to skip -jrel_op('JUMP_IF_FALSE', 111) # "" -jrel_op('JUMP_IF_TRUE', 112) # "" -jabs_op('JUMP_ABSOLUTE', 113) # Target byte offset from beginning of code -jrel_op('FOR_LOOP', 114) # Number of bytes to skip - -name_op('LOAD_LOCAL', 115) # Index in name list -name_op('LOAD_GLOBAL', 116) # Index in name list -def_op('SET_FUNC_ARGS', 117) # Argcount - -jrel_op('SETUP_LOOP', 120) # Distance to target address -jrel_op('SETUP_EXCEPT', 121) # "" -jrel_op('SETUP_FINALLY', 122) # "" - -def_op('RESERVE_FAST', 123) # Number of local variables -hasconst.append(123) -def_op('LOAD_FAST', 124) # Local variable number -def_op('STORE_FAST', 125) # Local variable number -def_op('DELETE_FAST', 126) # Local variable number - -def_op('SET_LINENO', 127) # Current line number -SET_LINENO = 127 diff --git a/Lib/dospath.py b/Lib/dospath.py deleted file mode 100644 index 725b381495..0000000000 --- a/Lib/dospath.py +++ /dev/null @@ -1,345 +0,0 @@ -# Module 'dospath' -- common operations on DOS pathnames - -import os -import stat -import string - - -# Normalize the case of a pathname. -# On MS-DOS it maps the pathname to lowercase, turns slashes into -# backslashes. -# Other normalizations (such as optimizing '../' away) are not allowed -# (this is done by normpath). -# Previously, this version mapped invalid consecutive characters to a -# single '_', but this has been removed. This functionality should -# possibly be added as a new function. - -def normcase(s): - res, s = splitdrive(s) - for c in s: - if c in '/\\': - res = res + os.sep - else: - res = res + c - return string.lower(res) - - -# Return wheter a path is absolute. -# Trivial in Posix, harder on the Mac or MS-DOS. -# For DOS it is absolute if it starts with a slash or backslash (current -# volume), or if a pathname after the volume letter and colon starts with -# a slash or backslash. - -def isabs(s): - s = splitdrive(s)[1] - return s != '' and s[:1] in '/\\' - - -# Join two pathnames. -# Ignore the first part if the second part is absolute. -# Insert a '/' unless the first part is empty or already ends in '/'. - -def join(a, b): - if isabs(b): return b - if a == '' or a[-1:] in '/\\': return a + b - # Note: join('x', '') returns 'x/'; is this what we want? - return a + os.sep + b - - -# Split a path in a drive specification (a drive letter followed by a -# colon) and the path specification. -# It is always true that drivespec + pathspec == p - -def splitdrive(p): - if p[1:2] == ':': - return p[0:2], p[2:] - return '', p - - -# Split a path in head (everything up to the last '/') and tail (the -# rest). If the original path ends in '/' but is not the root, this -# '/' is stripped. After the trailing '/' is stripped, the invariant -# join(head, tail) == p holds. -# The resulting head won't end in '/' unless it is the root. - -def split(p): - d, p = splitdrive(p) - slashes = '' - while p and p[-1:] in '/\\': - slashes = slashes + p[-1] - p = p[:-1] - if p == '': - p = p + slashes - head, tail = '', '' - for c in p: - tail = tail + c - if c in '/\\': - head, tail = head + tail, '' - slashes = '' - while head and head[-1:] in '/\\': - slashes = slashes + head[-1] - head = head[:-1] - if head == '': - head = head + slashes - return d + head, tail - - -# Split a path in root and extension. -# The extension is everything starting at the first dot in the last -# pathname component; the root is everything before that. -# It is always true that root + ext == p. - -def splitext(p): - root, ext = '', '' - for c in p: - if c in '/\\': - root, ext = root + ext + c, '' - elif c == '.' or ext: - ext = ext + c - else: - root = root + c - return root, ext - - -# Return the tail (basename) part of a path. - -def basename(p): - return split(p)[1] - - -# Return the head (dirname) part of a path. - -def dirname(p): - return split(p)[0] - - -# Return the longest prefix of all list elements. - -def commonprefix(m): - if not m: return '' - prefix = m[0] - for item in m: - for i in range(len(prefix)): - if prefix[:i+1] <> item[:i+1]: - prefix = prefix[:i] - if i == 0: return '' - break - return prefix - - -# Is a path a symbolic link? -# This will always return false on systems where posix.lstat doesn't exist. - -def islink(path): - return false - - -# Does a path exist? -# This is false for dangling symbolic links. - -def exists(path): - try: - st = os.stat(path) - except os.error: - return 0 - return 1 - - -# Is a path a dos directory? -# This follows symbolic links, so both islink() and isdir() can be true -# for the same path. - -def isdir(path): - try: - st = os.stat(path) - except os.error: - return 0 - return stat.S_ISDIR(st[stat.ST_MODE]) - - -# Is a path a regular file? -# This follows symbolic links, so both islink() and isdir() can be true -# for the same path. - -def isfile(path): - try: - st = os.stat(path) - except os.error: - return 0 - return stat.S_ISREG(st[stat.ST_MODE]) - - -# Are two filenames really pointing to the same file? - -def samefile(f1, f2): - s1 = os.stat(f1) - s2 = os.stat(f2) - return samestat(s1, s2) - - -# Are two open files really referencing the same file? -# (Not necessarily the same file descriptor!) -# XXX THIS IS BROKEN UNDER DOS! ST_INO seems to indicate number of reads? - -def sameopenfile(fp1, fp2): - s1 = os.fstat(fp1.fileno()) - s2 = os.fstat(fp2.fileno()) - return samestat(s1, s2) - - -# Are two stat buffers (obtained from stat, fstat or lstat) -# describing the same file? - -def samestat(s1, s2): - return s1[stat.ST_INO] == s2[stat.ST_INO] and \ - s1[stat.ST_DEV] == s2[stat.ST_DEV] - - -# Is a path a mount point? -# XXX This degenerates in: 'is this the root?' on DOS - -def ismount(path): - return isabs(splitdrive(path)[1]) - - -# Directory tree walk. -# For each directory under top (including top itself, but excluding -# '.' and '..'), func(arg, dirname, filenames) is called, where -# dirname is the name of the directory and filenames is the list -# files files (and subdirectories etc.) in the directory. -# The func may modify the filenames list, to implement a filter, -# or to impose a different order of visiting. - -def walk(top, func, arg): - try: - names = os.listdir(top) - except os.error: - return - func(arg, top, names) - exceptions = ('.', '..') - for name in names: - if name not in exceptions: - name = join(top, name) - if isdir(name): - walk(name, func, arg) - - -# Expand paths beginning with '~' or '~user'. -# '~' means $HOME; '~user' means that user's home directory. -# If the path doesn't begin with '~', or if the user or $HOME is unknown, -# the path is returned unchanged (leaving error reporting to whatever -# function is called with the expanded path as argument). -# See also module 'glob' for expansion of *, ? and [...] in pathnames. -# (A function should also be defined to do full *sh-style environment -# variable expansion.) - -def expanduser(path): - if path[:1] <> '~': - return path - i, n = 1, len(path) - while i < n and path[i] not in '/\\': - i = i+1 - if i == 1: - if not os.environ.has_key('HOME'): - return path - userhome = os.environ['HOME'] - else: - return path - return userhome + path[i:] - - -# Expand paths containing shell variable substitutions. -# The following rules apply: -# - no expansion within single quotes -# - no escape character, except for '$$' which is translated into '$' -# - ${varname} is accepted. -# - varnames can be made out of letters, digits and the character '_' -# XXX With COMMAND.COM you can use any characters in a variable name, -# XXX except '^|<>='. - -varchars = string.letters + string.digits + '_-' - -def expandvars(path): - if '$' not in path: - return path - res = '' - index = 0 - pathlen = len(path) - while index < pathlen: - c = path[index] - if c == '\'': # no expansion within single quotes - path = path[index + 1:] - pathlen = len(path) - try: - index = string.index(path, '\'') - res = res + '\'' + path[:index + 1] - except string.index_error: - res = res + path - index = pathlen -1 - elif c == '$': # variable or '$$' - if path[index + 1:index + 2] == '$': - res = res + c - index = index + 1 - elif path[index + 1:index + 2] == '{': - path = path[index+2:] - pathlen = len(path) - try: - index = string.index(path, '}') - var = path[:index] - if os.environ.has_key(var): - res = res + os.environ[var] - except string.index_error: - res = res + path - index = pathlen - 1 - else: - var = '' - index = index + 1 - c = path[index:index + 1] - while c != '' and c in varchars: - var = var + c - index = index + 1 - c = path[index:index + 1] - if os.environ.has_key(var): - res = res + os.environ[var] - if c != '': - res = res + c - else: - res = res + c - index = index + 1 - return res - - -# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B. -# Also, components of the path are silently truncated to 8+3 notation. - -def normpath(path): - path = normcase(path) - prefix, path = splitdrive(path) - while path[:1] == os.sep: - prefix = prefix + os.sep - path = path[1:] - comps = string.splitfields(path, os.sep) - i = 0 - while i < len(comps): - if comps[i] == '.': - del comps[i] - elif comps[i] == '..' and i > 0 and \ - comps[i-1] not in ('', '..'): - del comps[i-1:i+1] - i = i-1 - elif comps[i] == '' and i > 0 and comps[i-1] <> '': - del comps[i] - elif '.' in comps[i]: - comp = string.splitfields(comps[i], '.') - comps[i] = comp[0][:8] + '.' + comp[1][:3] - i = i+1 - elif len(comps[i]) > 8: - comps[i] = comps[i][:8] - i = i+1 - else: - i = i+1 - # If the path is now empty, substitute '.' - if not prefix and not comps: - comps.append('.') - return prefix + string.joinfields(comps, os.sep) - diff --git a/Lib/dumbdbm.py b/Lib/dumbdbm.py deleted file mode 100644 index 0ae1e82fad..0000000000 --- a/Lib/dumbdbm.py +++ /dev/null @@ -1,145 +0,0 @@ -"""A dumb and slow but simple dbm clone. - -For database spam, spam.dir contains the index (a text file), -spam.bak *may* contain a backup of the index (also a text file), -while spam.dat contains the data (a binary file). - -XXX TO DO: - -- seems to contain a bug when updating... - -- reclaim free space (currently, space once occupied by deleted or expanded -items is never reused) - -- support concurrent access (currently, if two processes take turns making -updates, they can mess up the index) - -- support efficient access to large databases (currently, the whole index -is read when the database is opened, and some updates rewrite the whole index) - -- support opening for read-only (flag = 'm') - -""" - -_os = __import__('os') -import __builtin__ - -_open = __builtin__.open - -_BLOCKSIZE = 512 - -error = IOError # For anydbm - -class _Database: - - def __init__(self, file): - self._dirfile = file + '.dir' - self._datfile = file + '.dat' - self._bakfile = file + '.bak' - # Mod by Jack: create data file if needed - try: - f = _open(self._datfile, 'r') - except IOError: - f = _open(self._datfile, 'w') - f.close() - self._update() - - def _update(self): - self._index = {} - try: - f = _open(self._dirfile) - except IOError: - pass - else: - while 1: - line = f.readline() - if not line: break - key, (pos, siz) = eval(line) - self._index[key] = (pos, siz) - f.close() - - def _commit(self): - try: _os.unlink(self._bakfile) - except _os.error: pass - try: _os.rename(self._dirfile, self._bakfile) - except _os.error: pass - f = _open(self._dirfile, 'w') - for key, (pos, siz) in self._index.items(): - f.write("%s, (%s, %s)\n" % (`key`, `pos`, `siz`)) - f.close() - - def __getitem__(self, key): - pos, siz = self._index[key] # may raise KeyError - f = _open(self._datfile, 'rb') - f.seek(pos) - dat = f.read(siz) - f.close() - return dat - - def _addval(self, val): - f = _open(self._datfile, 'rb+') - f.seek(0, 2) - pos = f.tell() -## Does not work under MW compiler -## pos = ((pos + _BLOCKSIZE - 1) / _BLOCKSIZE) * _BLOCKSIZE -## f.seek(pos) - npos = ((pos + _BLOCKSIZE - 1) / _BLOCKSIZE) * _BLOCKSIZE - f.write('\0'*(npos-pos)) - pos = npos - - f.write(val) - f.close() - return (pos, len(val)) - - def _setval(self, pos, val): - f = _open(self._datfile, 'rb+') - f.seek(pos) - f.write(val) - f.close() - return (pos, len(val)) - - def _addkey(self, key, (pos, siz)): - self._index[key] = (pos, siz) - f = _open(self._dirfile, 'a') - f.write("%s, (%s, %s)\n" % (`key`, `pos`, `siz`)) - f.close() - - def __setitem__(self, key, val): - if not type(key) == type('') == type(val): - raise TypeError, "keys and values must be strings" - if not self._index.has_key(key): - (pos, siz) = self._addval(val) - self._addkey(key, (pos, siz)) - else: - pos, siz = self._index[key] - oldblocks = (siz + _BLOCKSIZE - 1) / _BLOCKSIZE - newblocks = (len(val) + _BLOCKSIZE - 1) / _BLOCKSIZE - if newblocks <= oldblocks: - pos, siz = self._setval(pos, val) - self._index[key] = pos, siz - else: - pos, siz = self._addval(val) - self._index[key] = pos, siz - self._addkey(key, (pos, siz)) - - def __delitem__(self, key): - del self._index[key] - self._commit() - - def keys(self): - return self._index.keys() - - def has_key(self, key): - return self._index.has_key(key) - - def __len__(self): - return len(self._index) - - def close(self): - self._index = None - self._datfile = self._dirfile = self._bakfile = None - - -def open(file, flag = None, mode = None): - # flag, mode arguments are currently ignored - return _Database(file) diff --git a/Lib/dump.py b/Lib/dump.py deleted file mode 100644 index ec895b7e07..0000000000 --- a/Lib/dump.py +++ /dev/null @@ -1,63 +0,0 @@ -# Module 'dump' -# -# Print python code that reconstructs a variable. -# This only works in certain cases. -# -# It works fine for: -# - ints and floats (except NaNs and other weird things) -# - strings -# - compounds and lists, provided it works for all their elements -# - imported modules, provided their name is the module name -# -# It works for top-level dictionaries but not for dictionaries -# contained in other objects (could be made to work with some hassle -# though). -# -# It does not work for functions (all sorts), classes, class objects, -# windows, files etc. -# -# Finally, objects referenced by more than one name or contained in more -# than one other object lose their sharing property (this is bad for -# strings used as exception identifiers, for instance). - -# Dump a whole symbol table -# -def dumpsymtab(dict): - for key in dict.keys(): - dumpvar(key, dict[key]) - -# Dump a single variable -# -def dumpvar(name, x): - import sys - t = type(x) - if t == type({}): - print name, '= {}' - for key in x.keys(): - item = x[key] - if not printable(item): - print '#', - print name, '[', `key`, '] =', `item` - elif t in (type(''), type(0), type(0.0), type([]), type(())): - if not printable(x): - print '#', - print name, '=', `x` - elif t == type(sys): - print 'import', name, '#', x - else: - print '#', name, '=', x - -# check if a value is printable in a way that can be read back with input() -# -def printable(x): - t = type(x) - if t in (type(''), type(0), type(0.0)): - return 1 - if t in (type([]), type(())): - for item in x: - if not printable(item): - return 0 - return 1 - if x == {}: - return 1 - return 0 diff --git a/Lib/emacs.py b/Lib/emacs.py deleted file mode 100644 index ffce099ac3..0000000000 --- a/Lib/emacs.py +++ /dev/null @@ -1,18 +0,0 @@ -# Execute Emacs code from a Python interpreter. -# This code should be imported from a Python interpreter that is -# running as an inferior process of Emacs. -# See misc/py-connect.el for the companion Emacs lisp code. -# Author: Terrence M. Brannon. - -start_marker = '+' -end_marker = '~' - -def eval (string): - tmpstr = start_marker + '(' + string + ')' + end_marker - print tmpstr - -def dired (directory): - eval( 'dired ' + '"' + directory + '"' ) - -def buffer_menu (): - eval( 'buffer-menu(buffer-list)' ) diff --git a/Lib/find.py b/Lib/find.py deleted file mode 100644 index ccd9fdb965..0000000000 --- a/Lib/find.py +++ /dev/null @@ -1,26 +0,0 @@ -import fnmatch -import os - -_debug = 0 - -_prune = ['(*)'] - -def find(pattern, dir = os.curdir): - list = [] - names = os.listdir(dir) - names.sort() - for name in names: - if name in (os.curdir, os.pardir): - continue - fullname = os.path.join(dir, name) - if fnmatch.fnmatch(name, pattern): - list.append(fullname) - if os.path.isdir(fullname) and not os.path.islink(fullname): - for p in _prune: - if fnmatch.fnmatch(name, p): - if _debug: print "skip", `fullname` - break - else: - if _debug: print "descend into", `fullname` - list = list + find(pattern, fullname) - return list diff --git a/Lib/fmt.py b/Lib/fmt.py deleted file mode 100644 index 4a655e4c90..0000000000 --- a/Lib/fmt.py +++ /dev/null @@ -1,622 +0,0 @@ -# Text formatting abstractions -# Note -- this module is obsolete, it's too slow anyway - - -import string -import Para - - -# A formatter back-end object has one method that is called by the formatter: -# addpara(p), where p is a paragraph object. For example: - - -# Formatter back-end to do nothing at all with the paragraphs -class NullBackEnd: - # - def __init__(self): - pass - # - def addpara(self, p): - pass - # - def bgn_anchor(self, id): - pass - # - def end_anchor(self, id): - pass - - -# Formatter back-end to collect the paragraphs in a list -class SavingBackEnd(NullBackEnd): - # - def __init__(self): - self.paralist = [] - # - def addpara(self, p): - self.paralist.append(p) - # - def hitcheck(self, h, v): - hits = [] - for p in self.paralist: - if p.top <= v <= p.bottom: - for id in p.hitcheck(h, v): - if id not in hits: - hits.append(id) - return hits - # - def extract(self): - text = '' - for p in self.paralist: - text = text + (p.extract()) - return text - # - def extractpart(self, long1, long2): - if long1 > long2: long1, long2 = long2, long1 - para1, pos1 = long1 - para2, pos2 = long2 - text = '' - while para1 < para2: - ptext = self.paralist[para1].extract() - text = text + ptext[pos1:] - pos1 = 0 - para1 = para1 + 1 - ptext = self.paralist[para2].extract() - return text + ptext[pos1:pos2] - # - def whereis(self, d, h, v): - total = 0 - for i in range(len(self.paralist)): - p = self.paralist[i] - result = p.whereis(d, h, v) - if result <> None: - return i, result - return None - # - def roundtowords(self, long1, long2): - i, offset = long1 - text = self.paralist[i].extract() - while offset > 0 and text[offset-1] <> ' ': offset = offset-1 - long1 = i, offset - # - i, offset = long2 - text = self.paralist[i].extract() - n = len(text) - while offset < n-1 and text[offset] <> ' ': offset = offset+1 - long2 = i, offset - # - return long1, long2 - # - def roundtoparagraphs(self, long1, long2): - long1 = long1[0], 0 - long2 = long2[0], len(self.paralist[long2[0]].extract()) - return long1, long2 - - -# Formatter back-end to send the text directly to the drawing object -class WritingBackEnd(NullBackEnd): - # - def __init__(self, d, width): - self.d = d - self.width = width - self.lineno = 0 - # - def addpara(self, p): - self.lineno = p.render(self.d, 0, self.lineno, self.width) - - -# A formatter receives a stream of formatting instructions and assembles -# these into a stream of paragraphs on to a back-end. The assembly is -# parametrized by a text measurement object, which must match the output -# operations of the back-end. The back-end is responsible for splitting -# paragraphs up in lines of a given maximum width. (This is done because -# in a windowing environment, when the window size changes, there is no -# need to redo the assembly into paragraphs, but the splitting into lines -# must be done taking the new window size into account.) - - -# Formatter base class. Initialize it with a text measurement object, -# which is used for text measurements, and a back-end object, -# which receives the completed paragraphs. The formatting methods are: -# setfont(font) -# setleftindent(nspaces) -# setjust(type) where type is 'l', 'c', 'r', or 'lr' -# flush() -# vspace(nlines) -# needvspace(nlines) -# addword(word, nspaces) -class BaseFormatter: - # - def __init__(self, d, b): - # Drawing object used for text measurements - self.d = d - # - # BackEnd object receiving completed paragraphs - self.b = b - # - # Parameters of the formatting model - self.leftindent = 0 - self.just = 'l' - self.font = None - self.blanklines = 0 - # - # Parameters derived from the current font - self.space = d.textwidth(' ') - self.line = d.lineheight() - self.ascent = d.baseline() - self.descent = self.line - self.ascent - # - # Parameter derived from the default font - self.n_space = self.space - # - # Current paragraph being built - self.para = None - self.nospace = 1 - # - # Font to set on the next word - self.nextfont = None - # - def newpara(self): - return Para.Para() - # - def setfont(self, font): - if font == None: return - self.font = self.nextfont = font - d = self.d - d.setfont(font) - self.space = d.textwidth(' ') - self.line = d.lineheight() - self.ascent = d.baseline() - self.descent = self.line - self.ascent - # - def setleftindent(self, nspaces): - self.leftindent = int(self.n_space * nspaces) - if self.para: - hang = self.leftindent - self.para.indent_left - if hang > 0 and self.para.getlength() <= hang: - self.para.makehangingtag(hang) - self.nospace = 1 - else: - self.flush() - # - def setrightindent(self, nspaces): - self.rightindent = int(self.n_space * nspaces) - if self.para: - self.para.indent_right = self.rightindent - self.flush() - # - def setjust(self, just): - self.just = just - if self.para: - self.para.just = self.just - # - def flush(self): - if self.para: - self.b.addpara(self.para) - self.para = None - if self.font <> None: - self.d.setfont(self.font) - self.nospace = 1 - # - def vspace(self, nlines): - self.flush() - if nlines > 0: - self.para = self.newpara() - tuple = None, '', 0, 0, 0, int(nlines*self.line), 0 - self.para.words.append(tuple) - self.flush() - self.blanklines = self.blanklines + nlines - # - def needvspace(self, nlines): - self.flush() # Just to be sure - if nlines > self.blanklines: - self.vspace(nlines - self.blanklines) - # - def addword(self, text, space): - if self.nospace and not text: - return - self.nospace = 0 - self.blanklines = 0 - if not self.para: - self.para = self.newpara() - self.para.indent_left = self.leftindent - self.para.just = self.just - self.nextfont = self.font - space = int(space * self.space) - self.para.words.append(self.nextfont, text, \ - self.d.textwidth(text), space, space, \ - self.ascent, self.descent) - self.nextfont = None - # - def bgn_anchor(self, id): - if not self.para: - self.nospace = 0 - self.addword('', 0) - self.para.bgn_anchor(id) - # - def end_anchor(self, id): - if not self.para: - self.nospace = 0 - self.addword('', 0) - self.para.end_anchor(id) - - -# Measuring object for measuring text as viewed on a tty -class NullMeasurer: - # - def __init__(self): - pass - # - def setfont(self, font): - pass - # - def textwidth(self, text): - return len(text) - # - def lineheight(self): - return 1 - # - def baseline(self): - return 0 - - -# Drawing object for writing plain ASCII text to a file -class FileWriter: - # - def __init__(self, fp): - self.fp = fp - self.lineno, self.colno = 0, 0 - # - def setfont(self, font): - pass - # - def text(self, (h, v), str): - if not str: return - if '\n' in str: - raise ValueError, 'can\'t write \\n' - while self.lineno < v: - self.fp.write('\n') - self.colno, self.lineno = 0, self.lineno + 1 - while self.lineno > v: - # XXX This should never happen... - self.fp.write('\033[A') # ANSI up arrow - self.lineno = self.lineno - 1 - if self.colno < h: - self.fp.write(' ' * (h - self.colno)) - elif self.colno > h: - self.fp.write('\b' * (self.colno - h)) - self.colno = h - self.fp.write(str) - self.colno = h + len(str) - - -# Formatting class to do nothing at all with the data -class NullFormatter(BaseFormatter): - # - def __init__(self): - d = NullMeasurer() - b = NullBackEnd() - BaseFormatter.__init__(self, d, b) - - -# Formatting class to write directly to a file -class WritingFormatter(BaseFormatter): - # - def __init__(self, fp, width): - dm = NullMeasurer() - dw = FileWriter(fp) - b = WritingBackEnd(dw, width) - BaseFormatter.__init__(self, dm, b) - self.blanklines = 1 - # - # Suppress multiple blank lines - def needvspace(self, nlines): - BaseFormatter.needvspace(self, min(1, nlines)) - - -# A "FunnyFormatter" writes ASCII text with a twist: *bold words*, -# _italic text_ and _underlined words_, and `quoted text'. -# It assumes that the fonts are 'r', 'i', 'b', 'u', 'q': (roman, -# italic, bold, underline, quote). -# Moreover, if the font is in upper case, the text is converted to -# UPPER CASE. -class FunnyFormatter(WritingFormatter): - # - def flush(self): - if self.para: finalize(self.para) - WritingFormatter.flush(self) - - -# Surrounds *bold words* and _italic text_ in a paragraph with -# appropriate markers, fixing the size (assuming these characters' -# width is 1). -openchar = \ - {'b':'*', 'i':'_', 'u':'_', 'q':'`', 'B':'*', 'I':'_', 'U':'_', 'Q':'`'} -closechar = \ - {'b':'*', 'i':'_', 'u':'_', 'q':'\'', 'B':'*', 'I':'_', 'U':'_', 'Q':'\''} -def finalize(para): - oldfont = curfont = 'r' - para.words.append('r', '', 0, 0, 0, 0) # temporary, deleted at end - for i in range(len(para.words)): - fo, te, wi = para.words[i][:3] - if fo <> None: curfont = fo - if curfont <> oldfont: - if closechar.has_key(oldfont): - c = closechar[oldfont] - j = i-1 - while j > 0 and para.words[j][1] == '': j = j-1 - fo1, te1, wi1 = para.words[j][:3] - te1 = te1 + c - wi1 = wi1 + len(c) - para.words[j] = (fo1, te1, wi1) + \ - para.words[j][3:] - if openchar.has_key(curfont) and te: - c = openchar[curfont] - te = c + te - wi = len(c) + wi - para.words[i] = (fo, te, wi) + \ - para.words[i][3:] - if te: oldfont = curfont - else: oldfont = 'r' - if curfont in string.uppercase: - te = string.upper(te) - para.words[i] = (fo, te, wi) + para.words[i][3:] - del para.words[-1] - - -# Formatter back-end to draw the text in a window. -# This has an option to draw while the paragraphs are being added, -# to minimize the delay before the user sees anything. -# This manages the entire "document" of the window. -class StdwinBackEnd(SavingBackEnd): - # - def __init__(self, window, drawnow): - self.window = window - self.drawnow = drawnow - self.width = window.getwinsize()[0] - self.selection = None - self.height = 0 - window.setorigin(0, 0) - window.setdocsize(0, 0) - self.d = window.begindrawing() - SavingBackEnd.__init__(self) - # - def finish(self): - self.d.close() - self.d = None - self.window.setdocsize(0, self.height) - # - def addpara(self, p): - self.paralist.append(p) - if self.drawnow: - self.height = \ - p.render(self.d, 0, self.height, self.width) - else: - p.layout(self.width) - p.left = 0 - p.top = self.height - p.right = self.width - p.bottom = self.height + p.height - self.height = p.bottom - # - def resize(self): - self.window.change((0, 0), (self.width, self.height)) - self.width = self.window.getwinsize()[0] - self.height = 0 - for p in self.paralist: - p.layout(self.width) - p.left = 0 - p.top = self.height - p.right = self.width - p.bottom = self.height + p.height - self.height = p.bottom - self.window.change((0, 0), (self.width, self.height)) - self.window.setdocsize(0, self.height) - # - def redraw(self, area): - d = self.window.begindrawing() - (left, top), (right, bottom) = area - d.erase(area) - d.cliprect(area) - for p in self.paralist: - if top < p.bottom and p.top < bottom: - v = p.render(d, p.left, p.top, p.right) - if self.selection: - self.invert(d, self.selection) - d.close() - # - def setselection(self, new): - if new: - long1, long2 = new - pos1 = long1[:3] - pos2 = long2[:3] - new = pos1, pos2 - if new <> self.selection: - d = self.window.begindrawing() - if self.selection: - self.invert(d, self.selection) - if new: - self.invert(d, new) - d.close() - self.selection = new - # - def getselection(self): - return self.selection - # - def extractselection(self): - if self.selection: - a, b = self.selection - return self.extractpart(a, b) - else: - return None - # - def invert(self, d, region): - long1, long2 = region - if long1 > long2: long1, long2 = long2, long1 - para1, pos1 = long1 - para2, pos2 = long2 - while para1 < para2: - self.paralist[para1].invert(d, pos1, None) - pos1 = None - para1 = para1 + 1 - self.paralist[para2].invert(d, pos1, pos2) - # - def search(self, prog): - import regex, string - if type(prog) == type(''): - prog = regex.compile(string.lower(prog)) - if self.selection: - iold = self.selection[0][0] - else: - iold = -1 - hit = None - for i in range(len(self.paralist)): - if i == iold or i < iold and hit: - continue - p = self.paralist[i] - text = string.lower(p.extract()) - if prog.search(text) >= 0: - a, b = prog.regs[0] - long1 = i, a - long2 = i, b - hit = long1, long2 - if i > iold: - break - if hit: - self.setselection(hit) - i = hit[0][0] - p = self.paralist[i] - self.window.show((p.left, p.top), (p.right, p.bottom)) - return 1 - else: - return 0 - # - def showanchor(self, id): - for i in range(len(self.paralist)): - p = self.paralist[i] - if p.hasanchor(id): - long1 = i, 0 - long2 = i, len(p.extract()) - hit = long1, long2 - self.setselection(hit) - self.window.show( \ - (p.left, p.top), (p.right, p.bottom)) - break - - -# GL extensions - -class GLFontCache: - # - def __init__(self): - self.reset() - self.setfont('') - # - def reset(self): - self.fontkey = None - self.fonthandle = None - self.fontinfo = None - self.fontcache = {} - # - def close(self): - self.reset() - # - def setfont(self, fontkey): - if fontkey == '': - fontkey = 'Times-Roman 12' - elif ' ' not in fontkey: - fontkey = fontkey + ' 12' - if fontkey == self.fontkey: - return - if self.fontcache.has_key(fontkey): - handle = self.fontcache[fontkey] - else: - import string - i = string.index(fontkey, ' ') - name, sizestr = fontkey[:i], fontkey[i:] - size = eval(sizestr) - key1 = name + ' 1' - key = name + ' ' + `size` - # NB key may differ from fontkey! - if self.fontcache.has_key(key): - handle = self.fontcache[key] - else: - if self.fontcache.has_key(key1): - handle = self.fontcache[key1] - else: - import fm - handle = fm.findfont(name) - self.fontcache[key1] = handle - handle = handle.scalefont(size) - self.fontcache[fontkey] = \ - self.fontcache[key] = handle - self.fontkey = fontkey - if self.fonthandle <> handle: - self.fonthandle = handle - self.fontinfo = handle.getfontinfo() - handle.setfont() - - -class GLMeasurer(GLFontCache): - # - def textwidth(self, text): - return self.fonthandle.getstrwidth(text) - # - def baseline(self): - return self.fontinfo[6] - self.fontinfo[3] - # - def lineheight(self): - return self.fontinfo[6] - - -class GLWriter(GLFontCache): - # - # NOTES: - # (1) Use gl.ortho2 to use X pixel coordinates! - # - def text(self, (h, v), text): - import gl, fm - gl.cmov2i(h, v + self.fontinfo[6] - self.fontinfo[3]) - fm.prstr(text) - # - def setfont(self, fontkey): - oldhandle = self.fonthandle - GLFontCache.setfont(fontkey) - if self.fonthandle <> oldhandle: - handle.setfont() - - -class GLMeasurerWriter(GLMeasurer, GLWriter): - pass - - -class GLBackEnd(SavingBackEnd): - # - def __init__(self, wid): - import gl - gl.winset(wid) - self.wid = wid - self.width = gl.getsize()[1] - self.height = 0 - self.d = GLMeasurerWriter() - SavingBackEnd.__init__(self) - # - def finish(self): - pass - # - def addpara(self, p): - self.paralist.append(p) - self.height = p.render(self.d, 0, self.height, self.width) - # - def redraw(self): - import gl - gl.winset(self.wid) - width = gl.getsize()[1] - if width <> self.width: - setdocsize = 1 - self.width = width - for p in self.paralist: - p.top = p.bottom = None - d = self.d - v = 0 - for p in self.paralist: - v = p.render(d, 0, v, width) diff --git a/Lib/fnmatch.py b/Lib/fnmatch.py deleted file mode 100644 index 9b31856546..0000000000 --- a/Lib/fnmatch.py +++ /dev/null @@ -1,92 +0,0 @@ -"""Filename matching with shell patterns. - -fnmatch(FILENAME, PATTERN) matches according to the local convention. -fnmatchcase(FILENAME, PATTERN) always takes case in account. - -The functions operate by translating the pattern into a regular -expression. They cache the compiled regular expressions for speed. - -The function translate(PATTERN) returns a regular expression -corresponding to PATTERN. (It does not compile it.) -""" - -_cache = {} - -def fnmatch(name, pat): - """Test whether FILENAME matches PATTERN. - - Patterns are Unix shell style: - - * matches everything - ? matches any single character - [seq] matches any character in seq - [!seq] matches any char not in seq - - An initial period in FILENAME is not special. - Both FILENAME and PATTERN are first case-normalized - if the operating system requires it. - If you don't want this, use fnmatchcase(FILENAME, PATTERN). - """ - - import os - name = os.path.normcase(name) - pat = os.path.normcase(pat) - return fnmatchcase(name, pat) - -def fnmatchcase(name, pat): - """Test wheter FILENAME matches PATTERN, including case. - - This is a version of fnmatch() which doesn't case-normalize - its arguments. - """ - - if not _cache.has_key(pat): - res = translate(pat) - import regex - save_syntax = regex.set_syntax(0) - _cache[pat] = regex.compile(res) - save_syntax = regex.set_syntax(save_syntax) - return _cache[pat].match(name) == len(name) - -def translate(pat): - """Translate a shell PATTERN to a regular expression. - - There is no way to quote meta-characters. - """ - - i, n = 0, len(pat) - res = '' - while i < n: - c = pat[i] - i = i+1 - if c == '*': - res = res + '.*' - elif c == '?': - res = res + '.' - elif c == '[': - j = i - if j < n and pat[j] == '!': - j = j+1 - if j < n and pat[j] == ']': - j = j+1 - while j < n and pat[j] != ']': - j = j+1 - if j >= n: - res = res + '\\[' - else: - stuff = pat[i:j] - i = j+1 - if stuff[0] == '!': - stuff = '[^' + stuff[1:] + ']' - elif stuff == '^'*len(stuff): - stuff = '\\^' - else: - while stuff[0] == '^': - stuff = stuff[1:] + stuff[0] - stuff = '[' + stuff + ']' - res = res + stuff - elif c in '\\.+^$': - res = res + ('\\' + c) - else: - res = res + c - return res diff --git a/Lib/formatter.py b/Lib/formatter.py deleted file mode 100644 index 026637940e..0000000000 --- a/Lib/formatter.py +++ /dev/null @@ -1,399 +0,0 @@ -import regex -import regsub -import string -import sys -from types import StringType - - -AS_IS = None - - -class NullFormatter: - - def __init__(self): pass - def end_paragraph(self, blankline): pass - def add_line_break(self): pass - def add_hor_rule(self, abswidth=None, percentwidth=1.0, - height=None, align=None): pass - def add_label_data(self, format, counter): pass - def add_flowing_data(self, data): pass - def add_literal_data(self, data): pass - def flush_softspace(self): pass - def push_alignment(self, align): pass - def pop_alignment(self): pass - def push_font(self, x): pass - def pop_font(self): pass - def push_margin(self, margin): pass - def pop_margin(self): pass - def set_spacing(self, spacing): pass - def push_style(self, *styles): pass - def pop_style(self, n=1): pass - def assert_line_data(self, flag=1): pass - - -class AbstractFormatter: - - def __init__(self, writer): - self.writer = writer # Output device - self.align = None # Current alignment - self.align_stack = [] # Alignment stack - self.font_stack = [] # Font state - self.margin_stack = [] # Margin state - self.spacing = None # Vertical spacing state - self.style_stack = [] # Other state, e.g. color - self.nospace = 1 # Should leading space be suppressed - self.softspace = 0 # Should a space be inserted - self.para_end = 1 # Just ended a paragraph - self.parskip = 0 # Skipped space between paragraphs? - self.hard_break = 1 # Have a hard break - self.have_label = 0 - - def end_paragraph(self, blankline): - if not self.hard_break: - self.writer.send_line_break() - self.have_label = 0 - if self.parskip < blankline and not self.have_label: - self.writer.send_paragraph(blankline - self.parskip) - self.parskip = blankline - self.have_label = 0 - self.hard_break = self.nospace = self.para_end = 1 - self.softspace = 0 - - def add_line_break(self): - if not (self.hard_break or self.para_end): - self.writer.send_line_break() - self.have_label = self.parskip = 0 - self.hard_break = self.nospace = 1 - self.softspace = 0 - - def add_hor_rule(self, *args, **kw): - if not self.hard_break: - self.writer.send_line_break() - apply(self.writer.send_hor_rule, args, kw) - self.hard_break = self.nospace = 1 - self.have_label = self.para_end = self.softspace = self.parskip = 0 - - def add_label_data(self, format, counter, blankline = None): - if self.have_label or not self.hard_break: - self.writer.send_line_break() - if not self.para_end: - self.writer.send_paragraph((blankline and 1) or 0) - if type(format) is StringType: - self.writer.send_label_data(self.format_counter(format, counter)) - else: - self.writer.send_label_data(format) - self.nospace = self.have_label = self.hard_break = self.para_end = 1 - self.softspace = self.parskip = 0 - - def format_counter(self, format, counter): - label = '' - for c in format: - try: - if c == '1': - label = label + ('%d' % counter) - elif c in 'aA': - if counter > 0: - label = label + self.format_letter(c, counter) - elif c in 'iI': - if counter > 0: - label = label + self.format_roman(c, counter) - else: - label = label + c - except: - label = label + c - return label - - def format_letter(self, case, counter): - label = '' - while counter > 0: - counter, x = divmod(counter-1, 26) - s = chr(ord(case) + x) - label = s + label - return label - - def format_roman(self, case, counter): - ones = ['i', 'x', 'c', 'm'] - fives = ['v', 'l', 'd'] - label, index = '', 0 - # This will die of IndexError when counter is too big - while counter > 0: - counter, x = divmod(counter, 10) - if x == 9: - label = ones[index] + ones[index+1] + label - elif x == 4: - label = ones[index] + fives[index] + label - else: - if x >= 5: - s = fives[index] - x = x-5 - else: - s = '' - s = s + ones[index]*x - label = s + label - index = index + 1 - if case == 'I': - return string.upper(label) - return label - - def add_flowing_data(self, data, - # These are only here to load them into locals: - whitespace = string.whitespace, - join = string.join, split = string.split): - if not data: return - # The following looks a bit convoluted but is a great improvement over - # data = regsub.gsub('[' + string.whitespace + ']+', ' ', data) - prespace = data[:1] in whitespace - postspace = data[-1:] in whitespace - data = join(split(data)) - if self.nospace and not data: - return - elif prespace or self.softspace: - if not data: - if not self.nospace: - self.softspace = 1 - self.parskip = 0 - return - if not self.nospace: - data = ' ' + data - self.hard_break = self.nospace = self.para_end = \ - self.parskip = self.have_label = 0 - self.softspace = postspace - self.writer.send_flowing_data(data) - - def add_literal_data(self, data): - if not data: return - # Caller is expected to cause flush_softspace() if needed. - self.hard_break = data[-1:] == '\n' - self.nospace = self.para_end = self.softspace = \ - self.parskip = self.have_label = 0 - self.writer.send_literal_data(data) - - def flush_softspace(self): - if self.softspace: - self.hard_break = self.nospace = self.para_end = self.parskip = \ - self.have_label = self.softspace = 0 - self.writer.send_flowing_data(' ') - - def push_alignment(self, align): - if align and align != self.align: - self.writer.new_alignment(align) - self.align = align - self.align_stack.append(align) - else: - self.align_stack.append(self.align) - - def pop_alignment(self): - if self.align_stack: - del self.align_stack[-1] - if self.align_stack: - self.align = align = self.align_stack[-1] - self.writer.new_alignment(align) - else: - self.align = None - self.writer.new_alignment(None) - - def push_font(self, (size, i, b, tt)): - if self.softspace: - self.hard_break = self.nospace = self.para_end = self.softspace = 0 - self.writer.send_flowing_data(' ') - if self.font_stack: - csize, ci, cb, ctt = self.font_stack[-1] - if size is AS_IS: size = csize - if i is AS_IS: i = ci - if b is AS_IS: b = cb - if tt is AS_IS: tt = ctt - font = (size, i, b, tt) - self.font_stack.append(font) - self.writer.new_font(font) - - def pop_font(self): - if self.softspace: - self.hard_break = self.nospace = self.para_end = self.softspace = 0 - self.writer.send_flowing_data(' ') - if self.font_stack: - del self.font_stack[-1] - if self.font_stack: - font = self.font_stack[-1] - else: - font = None - self.writer.new_font(font) - - def push_margin(self, margin): - self.margin_stack.append(margin) - fstack = filter(None, self.margin_stack) - if not margin and fstack: - margin = fstack[-1] - self.writer.new_margin(margin, len(fstack)) - - def pop_margin(self): - if self.margin_stack: - del self.margin_stack[-1] - fstack = filter(None, self.margin_stack) - if fstack: - margin = fstack[-1] - else: - margin = None - self.writer.new_margin(margin, len(fstack)) - - def set_spacing(self, spacing): - self.spacing = spacing - self.writer.new_spacing(spacing) - - def push_style(self, *styles): - if self.softspace: - self.hard_break = self.nospace = self.para_end = self.softspace = 0 - self.writer.send_flowing_data(' ') - for style in styles: - self.style_stack.append(style) - self.writer.new_styles(tuple(self.style_stack)) - - def pop_style(self, n=1): - if self.softspace: - self.hard_break = self.nospace = self.para_end = self.softspace = 0 - self.writer.send_flowing_data(' ') - del self.style_stack[-n:] - self.writer.new_styles(tuple(self.style_stack)) - - def assert_line_data(self, flag=1): - self.nospace = self.hard_break = not flag - self.para_end = self.have_label = 0 - - -class NullWriter: - """Minimal writer interface to use in testing. - """ - def __init__(self): pass - def new_alignment(self, align): pass - def new_font(self, font): pass - def new_margin(self, margin, level): pass - def new_spacing(self, spacing): pass - def new_styles(self, styles): pass - def send_paragraph(self, blankline): pass - def send_line_break(self): pass - def send_hor_rule(self, *args, **kw): pass - def send_label_data(self, data): pass - def send_flowing_data(self, data): pass - def send_literal_data(self, data): pass - - -class AbstractWriter(NullWriter): - - def __init__(self): - pass - - def new_alignment(self, align): - print "new_alignment(%s)" % `align` - - def new_font(self, font): - print "new_font(%s)" % `font` - - def new_margin(self, margin, level): - print "new_margin(%s, %d)" % (`margin`, level) - - def new_spacing(self, spacing): - print "new_spacing(%s)" % `spacing` - - def new_styles(self, styles): - print "new_styles(%s)" % `styles` - - def send_paragraph(self, blankline): - print "send_paragraph(%s)" % `blankline` - - def send_line_break(self): - print "send_line_break()" - - def send_hor_rule(self, *args, **kw): - print "send_hor_rule()" - - def send_label_data(self, data): - print "send_label_data(%s)" % `data` - - def send_flowing_data(self, data): - print "send_flowing_data(%s)" % `data` - - def send_literal_data(self, data): - print "send_literal_data(%s)" % `data` - - -class DumbWriter(NullWriter): - - def __init__(self, file=None, maxcol=72): - self.file = file or sys.stdout - self.maxcol = maxcol - NullWriter.__init__(self) - self.reset() - - def reset(self): - self.col = 0 - self.atbreak = 0 - - def send_paragraph(self, blankline): - self.file.write('\n' + '\n'*blankline) - self.col = 0 - self.atbreak = 0 - - def send_line_break(self): - self.file.write('\n') - self.col = 0 - self.atbreak = 0 - - def send_hor_rule(self, *args, **kw): - self.file.write('\n') - self.file.write('-'*self.maxcol) - self.file.write('\n') - self.col = 0 - self.atbreak = 0 - - def send_literal_data(self, data): - self.file.write(data) - i = string.rfind(data, '\n') - if i >= 0: - self.col = 0 - data = data[i+1:] - data = string.expandtabs(data) - self.col = self.col + len(data) - self.atbreak = 0 - - def send_flowing_data(self, data): - if not data: return - atbreak = self.atbreak or data[0] in string.whitespace - col = self.col - maxcol = self.maxcol - write = self.file.write - for word in string.split(data): - if atbreak: - if col + len(word) >= maxcol: - write('\n') - col = 0 - else: - write(' ') - col = col + 1 - write(word) - col = col + len(word) - atbreak = 1 - self.col = col - self.atbreak = data[-1] in string.whitespace - - -def test(file = None): - w = DumbWriter() - f = AbstractFormatter(w) - if file: - fp = open(file) - elif sys.argv[1:]: - fp = open(sys.argv[1]) - else: - fp = sys.stdin - while 1: - line = fp.readline() - if not line: - break - if line == '\n': - f.end_paragraph(1) - else: - f.add_flowing_data(line) - f.end_paragraph(0) - - -if __name__ == '__main__': - test() diff --git a/Lib/fpformat.py b/Lib/fpformat.py deleted file mode 100644 index 457457595c..0000000000 --- a/Lib/fpformat.py +++ /dev/null @@ -1,138 +0,0 @@ -# General floating point formatting functions. - -# Functions: -# fix(x, digits_behind) -# sci(x, digits_behind) - -# Each takes a number or a string and a number of digits as arguments. - -# Parameters: -# x: number to be formatted; or a string resembling a number -# digits_behind: number of digits behind the decimal point - - -import regex - -# Compiled regular expression to "decode" a number -decoder = regex.compile( \ - '^\([-+]?\)0*\([0-9]*\)\(\(\.[0-9]*\)?\)\(\([eE][-+]?[0-9]+\)?\)$') -# \0 the whole thing -# \1 leading sign or empty -# \2 digits left of decimal point -# \3 fraction (empty or begins with point) -# \5 exponent part (empty or begins with 'e' or 'E') - -NotANumber = 'fpformat.NotANumber' - -# Return (sign, intpart, fraction, expo) or raise an exception: -# sign is '+' or '-' -# intpart is 0 or more digits beginning with a nonzero -# fraction is 0 or more digits -# expo is an integer -def extract(s): - if decoder.match(s) < 0: raise NotANumber - (a1, b1), (a2, b2), (a3, b3), (a4, b4), (a5, b5) = decoder.regs[1:6] - sign, intpart, fraction, exppart = \ - s[a1:b1], s[a2:b2], s[a3:b3], s[a5:b5] - if sign == '+': sign = '' - if fraction: fraction = fraction[1:] - if exppart: expo = eval(exppart[1:]) - else: expo = 0 - return sign, intpart, fraction, expo - -# Remove the exponent by changing intpart and fraction -def unexpo(intpart, fraction, expo): - if expo > 0: # Move the point left - f = len(fraction) - intpart, fraction = intpart + fraction[:expo], fraction[expo:] - if expo > f: - intpart = intpart + '0'*(expo-f) - elif expo < 0: # Move the point right - i = len(intpart) - intpart, fraction = intpart[:expo], intpart[expo:] + fraction - if expo < -i: - fraction = '0'*(-expo-i) + fraction - return intpart, fraction - -# Round or extend the fraction to size digs -def roundfrac(intpart, fraction, digs): - f = len(fraction) - if f <= digs: - return intpart, fraction + '0'*(digs-f) - i = len(intpart) - if i+digs < 0: - return '0'*-digs, '' - total = intpart + fraction - nextdigit = total[i+digs] - if nextdigit >= '5': # Hard case: increment last digit, may have carry! - n = i + digs - 1 - while n >= 0: - if total[n] != '9': break - n = n-1 - else: - total = '0' + total - i = i+1 - n = 0 - total = total[:n] + chr(ord(total[n]) + 1) + '0'*(len(total)-n-1) - intpart, fraction = total[:i], total[i:] - if digs >= 0: - return intpart, fraction[:digs] - else: - return intpart[:digs] + '0'*-digs, '' - -# Format x as [-]ddd.ddd with 'digs' digits after the point -# and at least one digit before. -# If digs <= 0, the point is suppressed. -def fix(x, digs): - if type(x) != type(''): x = `x` - try: - sign, intpart, fraction, expo = extract(x) - except NotANumber: - return x - intpart, fraction = unexpo(intpart, fraction, expo) - intpart, fraction = roundfrac(intpart, fraction, digs) - while intpart and intpart[0] == '0': intpart = intpart[1:] - if intpart == '': intpart = '0' - if digs > 0: return sign + intpart + '.' + fraction - else: return sign + intpart - -# Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point -# and exactly one digit before. -# If digs is <= 0, one digit is kept and the point is suppressed. -def sci(x, digs): - if type(x) != type(''): x = `x` - sign, intpart, fraction, expo = extract(x) - if not intpart: - while fraction and fraction[0] == '0': - fraction = fraction[1:] - expo = expo - 1 - if fraction: - intpart, fraction = fraction[0], fraction[1:] - expo = expo - 1 - else: - intpart = '0' - else: - expo = expo + len(intpart) - 1 - intpart, fraction = intpart[0], intpart[1:] + fraction - digs = max(0, digs) - intpart, fraction = roundfrac(intpart, fraction, digs) - if len(intpart) > 1: - intpart, fraction, expo = \ - intpart[0], intpart[1:] + fraction[:-1], \ - expo + len(intpart) - 1 - s = sign + intpart - if digs > 0: s = s + '.' + fraction - e = `abs(expo)` - e = '0'*(3-len(e)) + e - if expo < 0: e = '-' + e - else: e = '+' + e - return s + 'e' + e - -# Interactive test run -def test(): - try: - while 1: - x, digs = input('Enter (x, digs): ') - print x, fix(x, digs), sci(x, digs) - except (EOFError, KeyboardInterrupt): - pass diff --git a/Lib/ftplib.py b/Lib/ftplib.py deleted file mode 100644 index e42ed8c6df..0000000000 --- a/Lib/ftplib.py +++ /dev/null @@ -1,546 +0,0 @@ -'''An FTP client class, and some helper functions. -Based on RFC 959: File Transfer Protocol -(FTP), by J. Postel and J. Reynolds - -Changes and improvements suggested by Steve Majewski. -Modified by Jack to work on the mac. -Modified by Siebren to support docstrings and PASV. - - -Example: - ->>> from ftplib import FTP ->>> ftp = FTP('ftp.python.org') # connect to host, default port ->>> ftp.login() # default, i.e.: user anonymous, passwd user@hostname ->>> ftp.retrlines('LIST') # list directory contents -total 9 -drwxr-xr-x 8 root wheel 1024 Jan 3 1994 . -drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .. -drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin -drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc -d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming -drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib -drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub -drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr --rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg ->>> ftp.quit() ->>> - -A nice test that reveals some of the network dialogue would be: -python ftplib.py -d localhost -l -p -l -''' - - -import os -import sys -import string - -# Import SOCKS module if it exists, else standard socket module socket -try: - import SOCKS; socket = SOCKS -except ImportError: - import socket - - -# Magic number from <socket.h> -MSG_OOB = 0x1 # Process data out of band - - -# The standard FTP server control port -FTP_PORT = 21 - - -# Exception raised when an error or invalid response is received -error_reply = 'ftplib.error_reply' # unexpected [123]xx reply -error_temp = 'ftplib.error_temp' # 4xx errors -error_perm = 'ftplib.error_perm' # 5xx errors -error_proto = 'ftplib.error_proto' # response does not begin with [1-5] - - -# All exceptions (hopefully) that may be raised here and that aren't -# (always) programming errors on our side -all_errors = (error_reply, error_temp, error_perm, error_proto, \ - socket.error, IOError, EOFError) - - -# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF) -CRLF = '\r\n' - - -# The class itself -class FTP: - - '''An FTP client class. - - To create a connection, call the class using these argument: - host, user, passwd, acct - These are all strings, and have default value ''. - Then use self.connect() with optional host and port argument. - - To download a file, use ftp.retrlines('RETR ' + filename), - or ftp.retrbinary() with slightly different arguments. - To upload a file, use ftp.storlines() or ftp.storbinary(), - which have an open file as argument (see their definitions - below for details). - The download/upload functions first issue appropriate TYPE - and PORT or PASV commands. -''' - - # Initialization method (called by class instantiation). - # Initialize host to localhost, port to standard ftp port - # Optional arguments are host (for connect()), - # and user, passwd, acct (for login()) - def __init__(self, host = '', user = '', passwd = '', acct = ''): - # Initialize the instance to something mostly harmless - self.debugging = 0 - self.host = '' - self.port = FTP_PORT - self.sock = None - self.file = None - self.welcome = None - if host: - self.connect(host) - if user: self.login(user, passwd, acct) - - def connect(self, host = '', port = 0): - '''Connect to host. Arguments are: - - host: hostname to connect to (string, default previous host) - - port: port to connect to (integer, default previous port)''' - if host: self.host = host - if port: self.port = port - self.passiveserver = 0 - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.sock.connect(self.host, self.port) - self.file = self.sock.makefile('r') - self.welcome = self.getresp() - - def getwelcome(self): - '''Get the welcome message from the server. - (this is read and squirreled away by connect())''' - if self.debugging: - print '*welcome*', self.sanitize(self.welcome) - return self.welcome - - def set_debuglevel(self, level): - '''Set the debugging level. - The required argument level means: - 0: no debugging output (default) - 1: print commands and responses but not body text etc. - 2: also print raw lines read and sent before stripping CR/LF''' - self.debugging = level - debug = set_debuglevel - - def set_pasv(self, val): - '''Use passive or active mode for data transfers. - With a false argument, use the normal PORT mode, - With a true argument, use the PASV command.''' - self.passiveserver = val - - # Internal: "sanitize" a string for printing - def sanitize(self, s): - if s[:5] == 'pass ' or s[:5] == 'PASS ': - i = len(s) - while i > 5 and s[i-1] in '\r\n': - i = i-1 - s = s[:5] + '*'*(i-5) + s[i:] - return `s` - - # Internal: send one line to the server, appending CRLF - def putline(self, line): - line = line + CRLF - if self.debugging > 1: print '*put*', self.sanitize(line) - self.sock.send(line) - - # Internal: send one command to the server (through putline()) - def putcmd(self, line): - if self.debugging: print '*cmd*', self.sanitize(line) - self.putline(line) - - # Internal: return one line from the server, stripping CRLF. - # Raise EOFError if the connection is closed - def getline(self): - line = self.file.readline() - if self.debugging > 1: - print '*get*', self.sanitize(line) - if not line: raise EOFError - if line[-2:] == CRLF: line = line[:-2] - elif line[-1:] in CRLF: line = line[:-1] - return line - - # Internal: get a response from the server, which may possibly - # consist of multiple lines. Return a single string with no - # trailing CRLF. If the response consists of multiple lines, - # these are separated by '\n' characters in the string - def getmultiline(self): - line = self.getline() - if line[3:4] == '-': - code = line[:3] - while 1: - nextline = self.getline() - line = line + ('\n' + nextline) - if nextline[:3] == code and \ - nextline[3:4] <> '-': - break - return line - - # Internal: get a response from the server. - # Raise various errors if the response indicates an error - def getresp(self): - resp = self.getmultiline() - if self.debugging: print '*resp*', self.sanitize(resp) - self.lastresp = resp[:3] - c = resp[:1] - if c == '4': - raise error_temp, resp - if c == '5': - raise error_perm, resp - if c not in '123': - raise error_proto, resp - return resp - - def voidresp(self): - """Expect a response beginning with '2'.""" - resp = self.getresp() - if resp[0] <> '2': - raise error_reply, resp - - def abort(self): - '''Abort a file transfer. Uses out-of-band data. - This does not follow the procedure from the RFC to send Telnet - IP and Synch; that doesn't seem to work with the servers I've - tried. Instead, just send the ABOR command as OOB data.''' - line = 'ABOR' + CRLF - if self.debugging > 1: print '*put urgent*', self.sanitize(line) - self.sock.send(line, MSG_OOB) - resp = self.getmultiline() - if resp[:3] not in ('426', '226'): - raise error_proto, resp - - def sendcmd(self, cmd): - '''Send a command and return the response.''' - self.putcmd(cmd) - return self.getresp() - - def voidcmd(self, cmd): - """Send a command and expect a response beginning with '2'.""" - self.putcmd(cmd) - self.voidresp() - - def sendport(self, host, port): - '''Send a PORT command with the current host and the given port number.''' - hbytes = string.splitfields(host, '.') - pbytes = [`port/256`, `port%256`] - bytes = hbytes + pbytes - cmd = 'PORT ' + string.joinfields(bytes, ',') - self.voidcmd(cmd) - - def makeport(self): - '''Create a new socket and send a PORT command for it.''' - global nextport - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.bind(('', 0)) - sock.listen(1) - dummyhost, port = sock.getsockname() # Get proper port - host, dummyport = self.sock.getsockname() # Get proper host - resp = self.sendport(host, port) - return sock - - def transfercmd(self, cmd): - '''Initiate a transfer over the data connection. - If the transfer is active, send a port command and - the transfer command, and accept the connection. - If the server is passive, send a pasv command, connect - to it, and start the transfer command. - Either way, return the socket for the connection''' - if self.passiveserver: - host, port = parse227(self.sendcmd('PASV')) - conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - conn.connect(host, port) - resp = self.sendcmd(cmd) - if resp[0] <> '1': - raise error_reply, resp - else: - sock = self.makeport() - resp = self.sendcmd(cmd) - if resp[0] <> '1': - raise error_reply, resp - conn, sockaddr = sock.accept() - return conn - - def login(self, user = '', passwd = '', acct = ''): - '''Login, default anonymous.''' - if not user: user = 'anonymous' - if user == 'anonymous' and passwd in ('', '-'): - thishost = socket.gethostname() - # Make sure it is fully qualified - if not '.' in thishost: - thisaddr = socket.gethostbyname(thishost) - firstname, names, unused = \ - socket.gethostbyaddr(thisaddr) - names.insert(0, firstname) - for name in names: - if '.' in name: - thishost = name - break - try: - if os.environ.has_key('LOGNAME'): - realuser = os.environ['LOGNAME'] - elif os.environ.has_key('USER'): - realuser = os.environ['USER'] - else: - realuser = 'anonymous' - except AttributeError: - # Not all systems have os.environ.... - realuser = 'anonymous' - passwd = passwd + realuser + '@' + thishost - resp = self.sendcmd('USER ' + user) - if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd) - if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct) - if resp[0] <> '2': - raise error_reply, resp - - def retrbinary(self, cmd, callback, blocksize): - '''Retrieve data in binary mode. - The argument is a RETR command. - The callback function is called for each block. - This creates a new port for you''' - self.voidcmd('TYPE I') - conn = self.transfercmd(cmd) - while 1: - data = conn.recv(blocksize) - if not data: - break - callback(data) - conn.close() - self.voidresp() - - def retrlines(self, cmd, callback = None): - '''Retrieve data in line mode. - The argument is a RETR or LIST command. - The callback function (2nd argument) is called for each line, - with trailing CRLF stripped. This creates a new port for you. - print_lines is the default callback.''' - if not callback: callback = print_line - resp = self.sendcmd('TYPE A') - conn = self.transfercmd(cmd) - fp = conn.makefile('r') - while 1: - line = fp.readline() - if self.debugging > 2: print '*retr*', `line` - if not line: - break - if line[-2:] == CRLF: - line = line[:-2] - elif line[:-1] == '\n': - line = line[:-1] - callback(line) - fp.close() - conn.close() - self.voidresp() - - def storbinary(self, cmd, fp, blocksize): - '''Store a file in binary mode.''' - self.voidcmd('TYPE I') - conn = self.transfercmd(cmd) - while 1: - buf = fp.read(blocksize) - if not buf: break - conn.send(buf) - conn.close() - self.voidresp() - - def storlines(self, cmd, fp): - '''Store a file in line mode.''' - self.voidcmd('TYPE A') - conn = self.transfercmd(cmd) - while 1: - buf = fp.readline() - if not buf: break - if buf[-2:] <> CRLF: - if buf[-1] in CRLF: buf = buf[:-1] - buf = buf + CRLF - conn.send(buf) - conn.close() - self.voidresp() - - def acct(self, password): - '''Send new account name.''' - cmd = 'ACCT ' + password - self.voidcmd(cmd) - - def nlst(self, *args): - '''Return a list of files in a given directory (default the current).''' - cmd = 'NLST' - for arg in args: - cmd = cmd + (' ' + arg) - files = [] - self.retrlines(cmd, files.append) - return files - - def dir(self, *args): - '''List a directory in long form. - By default list current directory to stdout. - Optional last argument is callback function; all - non-empty arguments before it are concatenated to the - LIST command. (This *should* only be used for a pathname.)''' - cmd = 'LIST' - func = None - if args[-1:] and type(args[-1]) != type(''): - args, func = args[:-1], args[-1] - for arg in args: - if arg: - cmd = cmd + (' ' + arg) - self.retrlines(cmd, func) - - def rename(self, fromname, toname): - '''Rename a file.''' - resp = self.sendcmd('RNFR ' + fromname) - if resp[0] <> '3': - raise error_reply, resp - self.voidcmd('RNTO ' + toname) - - def delete(self, filename): - '''Delete a file.''' - resp = self.sendcmd('DELE ' + filename) - if resp[:3] == '250': - return - elif resp[:1] == '5': - raise error_perm, resp - else: - raise error_reply, resp - - def cwd(self, dirname): - '''Change to a directory.''' - if dirname == '..': - try: - self.voidcmd('CDUP') - return - except error_perm, msg: - if msg[:3] != '500': - raise error_perm, msg - cmd = 'CWD ' + dirname - self.voidcmd(cmd) - - def size(self, filename): - '''Retrieve the size of a file.''' - # Note that the RFC doesn't say anything about 'SIZE' - resp = self.sendcmd('SIZE ' + filename) - if resp[:3] == '213': - return string.atoi(string.strip(resp[3:])) - - def mkd(self, dirname): - '''Make a directory, return its full pathname.''' - resp = self.sendcmd('MKD ' + dirname) - return parse257(resp) - - def pwd(self): - '''Return current working directory.''' - resp = self.sendcmd('PWD') - return parse257(resp) - - def quit(self): - '''Quit, and close the connection.''' - self.voidcmd('QUIT') - self.close() - - def close(self): - '''Close the connection without assuming anything about it.''' - self.file.close() - self.sock.close() - del self.file, self.sock - - -def parse227(resp): - '''Parse the '227' response for a PASV request. - Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)' - Return ('host.addr.as.numbers', port#) tuple.''' - - if resp[:3] <> '227': - raise error_reply, resp - left = string.find(resp, '(') - if left < 0: raise error_proto, resp - right = string.find(resp, ')', left + 1) - if right < 0: - raise error_proto, resp # should contain '(h1,h2,h3,h4,p1,p2)' - numbers = string.split(resp[left+1:right], ',') - if len(numbers) <> 6: - raise error_proto, resp - host = string.join(numbers[:4], '.') - port = (string.atoi(numbers[4]) << 8) + string.atoi(numbers[5]) - return host, port -# end parse227 - - -def parse257(resp): - '''Parse the '257' response for a MKD or RMD request. - This is a response to a MKD or RMD request: a directory name. - Returns the directoryname in the 257 reply.''' - - if resp[:3] <> '257': - raise error_reply, resp - if resp[3:5] <> ' "': - return '' # Not compliant to RFC 959, but UNIX ftpd does this - dirname = '' - i = 5 - n = len(resp) - while i < n: - c = resp[i] - i = i+1 - if c == '"': - if i >= n or resp[i] <> '"': - break - i = i+1 - dirname = dirname + c - return dirname - -def print_line(line): - '''Default retrlines callback to print a line.''' - print line - -def ftpcp(source, sourcename, target, targetname = '', type = 'I'): - '''Copy file from one FTP-instance to another.''' - if not targetname: targetname = sourcename - type = 'TYPE ' + type - source.voidcmd(type) - target.voidcmd(type) - sourcehost, sourceport = parse227(source.sendcmd('PASV')) - target.sendport(sourcehost, sourceport) - # RFC 959: the user must "listen" [...] BEFORE sending the - # transfer request. - # So: STOR before RETR, because here the target is a "user". - treply = target.sendcmd('STOR ' + targetname) - if treply[:3] not in ('125', '150'): raise error_proto # RFC 959 - sreply = source.sendcmd('RETR ' + sourcename) - if sreply[:3] not in ('125', '150'): raise error_proto # RFC 959 - source.voidresp() - target.voidresp() - -def test(): - '''Test program. - Usage: ftp [-d] host [-l[dir]] [-d[dir]] [-p] [file] ...''' - - debugging = 0 - while sys.argv[1] == '-d': - debugging = debugging+1 - del sys.argv[1] - host = sys.argv[1] - ftp = FTP(host) - ftp.set_debuglevel(debugging) - ftp.login() - for file in sys.argv[2:]: - if file[:2] == '-l': - ftp.dir(file[2:]) - elif file[:2] == '-d': - cmd = 'CWD' - if file[2:]: cmd = cmd + ' ' + file[2:] - resp = ftp.sendcmd(cmd) - elif file == '-p': - ftp.set_pasv(not ftp.passiveserver) - else: - ftp.retrbinary('RETR ' + file, \ - sys.stdout.write, 1024) - ftp.quit() - - -if __name__ == '__main__': - test() diff --git a/Lib/getopt.py b/Lib/getopt.py deleted file mode 100644 index 7feaf9d525..0000000000 --- a/Lib/getopt.py +++ /dev/null @@ -1,47 +0,0 @@ -# module getopt -- Standard command line processing. - -# Function getopt.getopt() has a different interface but provides the -# same functionality as the Unix getopt() function. - -# It has two arguments: the first should be argv[1:] (it doesn't want -# the script name), the second the string of option letters as passed -# to Unix getopt() (i.e., a string of allowable option letters, with -# options requiring an argument followed by a colon). - -# It raises the exception getopt.error with a string argument if it -# detects an error. - -# It returns two items: -# (1) a list of pairs (option, option_argument) giving the options in -# the order in which they were specified. (I'd use a dictionary -# but applications may depend on option order or multiple -# occurrences.) Boolean options have '' as option_argument. -# (2) the list of remaining arguments (may be empty). - -error = 'getopt error' - -def getopt(args, options): - list = [] - while args and args[0][:1] == '-' and args[0] <> '-': - if args[0] == '--': - args = args[1:] - break - optstring, args = args[0][1:], args[1:] - while optstring <> '': - opt, optstring = optstring[0], optstring[1:] - if classify(opt, options): # May raise exception as well - if optstring == '': - if not args: - raise error, 'option -' + opt + ' requires argument' - optstring, args = args[0], args[1:] - optarg, optstring = optstring, '' - else: - optarg = '' - list.append('-' + opt, optarg) - return list, args - -def classify(opt, options): # Helper to check type of option - for i in range(len(options)): - if opt == options[i] <> ':': - return options[i+1:i+2] == ':' - raise error, 'option -' + opt + ' not recognized' diff --git a/Lib/glob.py b/Lib/glob.py deleted file mode 100644 index bacaf183e1..0000000000 --- a/Lib/glob.py +++ /dev/null @@ -1,51 +0,0 @@ -# Module 'glob' -- filename globbing. - -import os -import fnmatch -import regex - - -def glob(pathname): - if not has_magic(pathname): - if os.path.exists(pathname): - return [pathname] - else: - return [] - dirname, basename = os.path.split(pathname) - if has_magic(dirname): - list = glob(dirname) - else: - list = [dirname] - if not has_magic(basename): - result = [] - for dirname in list: - if basename or os.path.isdir(dirname): - name = os.path.join(dirname, basename) - if os.path.exists(name): - result.append(name) - else: - result = [] - for dirname in list: - sublist = glob1(dirname, basename) - for name in sublist: - result.append(os.path.join(dirname, name)) - return result - -def glob1(dirname, pattern): - if not dirname: dirname = os.curdir - try: - names = os.listdir(dirname) - except os.error: - return [] - result = [] - for name in names: - if name[0] != '.' or pattern[0] == '.': - if fnmatch.fnmatch(name, pattern): - result.append(name) - return result - - -magic_check = regex.compile('[*?[]') - -def has_magic(s): - return magic_check.search(s) >= 0 diff --git a/Lib/gopherlib.py b/Lib/gopherlib.py deleted file mode 100644 index cf06e95830..0000000000 --- a/Lib/gopherlib.py +++ /dev/null @@ -1,191 +0,0 @@ -# Gopher protocol client interface - -import string - -# Default selector, host and port -DEF_SELECTOR = '1/' -DEF_HOST = 'gopher.micro.umn.edu' -DEF_PORT = 70 - -# Recognized file types -A_TEXT = '0' -A_MENU = '1' -A_CSO = '2' -A_ERROR = '3' -A_MACBINHEX = '4' -A_PCBINHEX = '5' -A_UUENCODED = '6' -A_INDEX = '7' -A_TELNET = '8' -A_BINARY = '9' -A_DUPLICATE = '+' -A_SOUND = 's' -A_EVENT = 'e' -A_CALENDAR = 'c' -A_HTML = 'h' -A_TN3270 = 'T' -A_MIME = 'M' -A_IMAGE = 'I' -A_WHOIS = 'w' -A_QUERY = 'q' -A_GIF = 'g' -A_HTML = 'h' # HTML file -A_WWW = 'w' # WWW address -A_PLUS_IMAGE = ':' -A_PLUS_MOVIE = ';' -A_PLUS_SOUND = '<' - - -# Function mapping all file types to strings; unknown types become TYPE='x' -_names = dir() -_type_to_name_map = None -def type_to_name(gtype): - global _type_to_name_map - if not _type_to_name_map: - for name in _names: - if name[:2] == 'A_': - _type_to_name_map[eval(name)] = name[2:] - if _type_to_name_map.has_key(gtype): - return _type_to_name_map[gtype] - return 'TYPE=' + `gtype` - -# Names for characters and strings -CRLF = '\r\n' -TAB = '\t' - -# Send a selector to a given host and port, return a file with the reply -def send_selector(selector, host, port = 0): - import socket - import string - if not port: - i = string.find(host, ':') - if i >= 0: - host, port = host[:i], string.atoi(host[i+1:]) - if not port: - port = DEF_PORT - elif type(port) == type(''): - port = string.atoi(port) - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.connect(host, port) - s.send(selector + CRLF) - s.shutdown(1) - return s.makefile('rb') - -# Send a selector and a query string -def send_query(selector, query, host, port = 0): - return send_selector(selector + '\t' + query, host, port) - -# The following functions interpret the data returned by the gopher -# server according to the expected type, e.g. textfile or directory - -# Get a directory in the form of a list of entries -def get_directory(f): - import string - list = [] - while 1: - line = f.readline() - if not line: - print '(Unexpected EOF from server)' - break - if line[-2:] == CRLF: - line = line[:-2] - elif line[-1:] in CRLF: - line = line[:-1] - if line == '.': - break - if not line: - print '(Empty line from server)' - continue - gtype = line[0] - parts = string.splitfields(line[1:], TAB) - if len(parts) < 4: - print '(Bad line from server:', `line`, ')' - continue - if len(parts) > 4: - if parts[4:] != ['+']: - print '(Extra info from server:', parts[4:], ')' - else: - parts.append('') - parts.insert(0, gtype) - list.append(parts) - return list - -# Get a text file as a list of lines, with trailing CRLF stripped -def get_textfile(f): - list = [] - get_alt_textfile(f, list.append) - return list - -# Get a text file and pass each line to a function, with trailing CRLF stripped -def get_alt_textfile(f, func): - while 1: - line = f.readline() - if not line: - print '(Unexpected EOF from server)' - break - if line[-2:] == CRLF: - line = line[:-2] - elif line[-1:] in CRLF: - line = line[:-1] - if line == '.': - break - if line[:2] == '..': - line = line[1:] - func(line) - -# Get a binary file as one solid data block -def get_binary(f): - data = f.read() - return data - -# Get a binary file and pass each block to a function -def get_alt_binary(f, func, blocksize): - while 1: - data = f.read(blocksize) - if not data: - break - func(data) - -# Trivial test program -def test(): - import sys - import getopt - opts, args = getopt.getopt(sys.argv[1:], '') - selector = DEF_SELECTOR - type = selector[0] - host = DEF_HOST - port = DEF_PORT - if args: - host = args[0] - args = args[1:] - if args: - type = args[0] - args = args[1:] - if len(type) > 1: - type, selector = type[0], type - else: - selector = '' - if args: - selector = args[0] - args = args[1:] - query = '' - if args: - query = args[0] - args = args[1:] - if type == A_INDEX: - f = send_query(selector, query, host) - else: - f = send_selector(selector, host) - if type == A_TEXT: - list = get_textfile(f) - for item in list: print item - elif type in (A_MENU, A_INDEX): - list = get_directory(f) - for item in list: print item - else: - data = get_binary(f) - print 'binary data:', len(data), 'bytes:', `data[:100]`[:40] - -# Run the test when run as script -if __name__ == '__main__': - test() diff --git a/Lib/grep.py b/Lib/grep.py deleted file mode 100644 index f4666512b7..0000000000 --- a/Lib/grep.py +++ /dev/null @@ -1,62 +0,0 @@ -# 'grep' - -import regex -from regex_syntax import * -import string - -opt_show_where = 0 -opt_show_filename = 0 -opt_show_lineno = 1 - -def grep(pat, *files): - return ggrep(RE_SYNTAX_GREP, pat, files) - -def egrep(pat, *files): - return ggrep(RE_SYNTAX_EGREP, pat, files) - -def emgrep(pat, *files): - return ggrep(RE_SYNTAX_EMACS, pat, files) - -def ggrep(syntax, pat, files): - if len(files) == 1 and type(files[0]) == type([]): - files = files[0] - global opt_show_filename - opt_show_filename = (len(files) != 1) - syntax = regex.set_syntax(syntax) - try: - prog = regex.compile(pat) - finally: - syntax = regex.set_syntax(syntax) - for filename in files: - fp = open(filename, 'r') - lineno = 0 - while 1: - line = fp.readline() - if not line: break - lineno = lineno + 1 - if prog.search(line) >= 0: - showline(filename, lineno, line, prog) - fp.close() - -def showline(filename, lineno, line, prog): - if line[-1:] == '\n': line = line[:-1] - if opt_show_lineno: - prefix = string.rjust(`lineno`, 3) + ': ' - else: - prefix = '' - if opt_show_filename: - prefix = filename + ': ' + prefix - print prefix + line - if opt_show_where: - start, end = prog.regs()[0] - line = line[:start] - if '\t' not in line: - prefix = ' ' * (len(prefix) + start) - else: - prefix = ' ' * len(prefix) - for c in line: - if c <> '\t': c = ' ' - prefix = prefix + c - if start == end: prefix = prefix + '\\' - else: prefix = prefix + '^'*(end-start) - print prefix diff --git a/Lib/htmlentitydefs.py b/Lib/htmlentitydefs.py deleted file mode 100644 index 55aefaa5ed..0000000000 --- a/Lib/htmlentitydefs.py +++ /dev/null @@ -1,105 +0,0 @@ -# Proposed entity definitions for HTML, taken from -# http://www.w3.org/hypertext/WWW/MarkUp/html-spec/html-spec_14.html - -entitydefs = { - 'lt': '<', - 'gt': '>', - 'amp': '&', - 'quot': '"', - 'nbsp': chr(160), # no-break space - 'iexcl': chr(161), # inverted exclamation mark - 'cent': chr(162), # cent sign - 'pound': chr(163), # pound sterling sign - 'curren': chr(164), # general currency sign - 'yen': chr(165), # yen sign - 'brvbar': chr(166), # broken (vertical) bar - 'sect': chr(167), # section sign - 'uml': chr(168), # umlaut (dieresis) - 'copy': chr(169), # copyright sign - 'ordf': chr(170), # ordinal indicator, feminine - 'laquo': chr(171), # angle quotation mark, left - 'not': chr(172), # not sign - 'shy': chr(173), # soft hyphen - 'reg': chr(174), # registered sign - 'macr': chr(175), # macron - 'deg': chr(176), # degree sign - 'plusmn': chr(177), # plus-or-minus sign - 'sup2': chr(178), # superscript two - 'sup3': chr(179), # superscript three - 'acute': chr(180), # acute accent - 'micro': chr(181), # micro sign - 'para': chr(182), # pilcrow (paragraph sign) - 'middot': chr(183), # middle dot - 'cedil': chr(184), # cedilla - 'sup1': chr(185), # superscript one - 'ordm': chr(186), # ordinal indicator, masculine - 'raquo': chr(187), # angle quotation mark, right - 'frac14': chr(188), # fraction one-quarter - 'frac12': chr(189), # fraction one-half - 'frac34': chr(190), # fraction three-quarters - 'iquest': chr(191), # inverted question mark - 'Agrave': chr(192), # capital A, grave accent - 'Aacute': chr(193), # capital A, acute accent - 'Acirc': chr(194), # capital A, circumflex accent - 'Atilde': chr(195), # capital A, tilde - 'Auml': chr(196), # capital A, dieresis or umlaut mark - 'Aring': chr(197), # capital A, ring - 'AElig': chr(198), # capital AE diphthong (ligature) - 'Ccedil': chr(199), # capital C, cedilla - 'Egrave': chr(200), # capital E, grave accent - 'Eacute': chr(201), # capital E, acute accent - 'Ecirc': chr(202), # capital E, circumflex accent - 'Euml': chr(203), # capital E, dieresis or umlaut mark - 'Igrave': chr(204), # capital I, grave accent - 'Iacute': chr(205), # capital I, acute accent - 'Icirc': chr(206), # capital I, circumflex accent - 'Iuml': chr(207), # capital I, dieresis or umlaut mark - 'ETH': chr(208), # capital Eth, Icelandic - 'Ntilde': chr(209), # capital N, tilde - 'Ograve': chr(210), # capital O, grave accent - 'Oacute': chr(211), # capital O, acute accent - 'Ocirc': chr(212), # capital O, circumflex accent - 'Otilde': chr(213), # capital O, tilde - 'Ouml': chr(214), # capital O, dieresis or umlaut mark - 'times': chr(215), # multiply sign - 'Oslash': chr(216), # capital O, slash - 'Ugrave': chr(217), # capital U, grave accent - 'Uacute': chr(218), # capital U, acute accent - 'Ucirc': chr(219), # capital U, circumflex accent - 'Uuml': chr(220), # capital U, dieresis or umlaut mark - 'Yacute': chr(221), # capital Y, acute accent - 'THORN': chr(222), # capital THORN, Icelandic - 'szlig': chr(223), # small sharp s, German (sz ligature) - 'agrave': chr(224), # small a, grave accent - 'aacute': chr(225), # small a, acute accent - 'acirc': chr(226), # small a, circumflex accent - 'atilde': chr(227), # small a, tilde - 'auml': chr(228), # small a, dieresis or umlaut mark - 'aring': chr(229), # small a, ring - 'aelig': chr(230), # small ae diphthong (ligature) - 'ccedil': chr(231), # small c, cedilla - 'egrave': chr(232), # small e, grave accent - 'eacute': chr(233), # small e, acute accent - 'ecirc': chr(234), # small e, circumflex accent - 'euml': chr(235), # small e, dieresis or umlaut mark - 'igrave': chr(236), # small i, grave accent - 'iacute': chr(237), # small i, acute accent - 'icirc': chr(238), # small i, circumflex accent - 'iuml': chr(239), # small i, dieresis or umlaut mark - 'eth': chr(240), # small eth, Icelandic - 'ntilde': chr(241), # small n, tilde - 'ograve': chr(242), # small o, grave accent - 'oacute': chr(243), # small o, acute accent - 'ocirc': chr(244), # small o, circumflex accent - 'otilde': chr(245), # small o, tilde - 'ouml': chr(246), # small o, dieresis or umlaut mark - 'divide': chr(247), # divide sign - 'oslash': chr(248), # small o, slash - 'ugrave': chr(249), # small u, grave accent - 'uacute': chr(250), # small u, acute accent - 'ucirc': chr(251), # small u, circumflex accent - 'uuml': chr(252), # small u, dieresis or umlaut mark - 'yacute': chr(253), # small y, acute accent - 'thorn': chr(254), # small thorn, Icelandic - 'yuml': chr(255), # small y, dieresis or umlaut mark -} diff --git a/Lib/htmllib.py b/Lib/htmllib.py deleted file mode 100644 index 840d7836a3..0000000000 --- a/Lib/htmllib.py +++ /dev/null @@ -1,428 +0,0 @@ -"""HTML 2.0 parser. - -See the HTML 2.0 specification: -http://www.w3.org/hypertext/WWW/MarkUp/html-spec/html-spec_toc.html -""" - - -import sys -import regsub -import string -from sgmllib import SGMLParser -from formatter import AS_IS - - -class HTMLParser(SGMLParser): - - from htmlentitydefs import entitydefs - - def __init__(self, formatter, verbose=0): - SGMLParser.__init__(self, verbose) - self.formatter = formatter - self.savedata = None - self.isindex = 0 - self.title = None - self.base = None - self.anchor = None - self.anchorlist = [] - self.nofill = 0 - self.list_stack = [] - - # ------ Methods used internally; some may be overridden - - # --- Formatter interface, taking care of 'savedata' mode; - # shouldn't need to be overridden - - def handle_data(self, data): - if self.savedata is not None: - self.savedata = self.savedata + data - else: - if self.nofill: - self.formatter.add_literal_data(data) - else: - self.formatter.add_flowing_data(data) - - # --- Hooks to save data; shouldn't need to be overridden - - def save_bgn(self): - self.savedata = '' - - def save_end(self): - data = self.savedata - self.savedata = None - if not self.nofill: - data = string.join(string.split(data)) - return data - - # --- Hooks for anchors; should probably be overridden - - def anchor_bgn(self, href, name, type): - self.anchor = href - if self.anchor: - self.anchorlist.append(href) - - def anchor_end(self): - if self.anchor: - self.handle_data("[%d]" % len(self.anchorlist)) - self.anchor = None - - # --- Hook for images; should probably be overridden - - def handle_image(self, src, alt, *args): - self.handle_data(alt) - - # --------- Top level elememts - - def start_html(self, attrs): pass - def end_html(self): pass - - def start_head(self, attrs): pass - def end_head(self): pass - - def start_body(self, attrs): pass - def end_body(self): pass - - # ------ Head elements - - def start_title(self, attrs): - self.save_bgn() - - def end_title(self): - self.title = self.save_end() - - def do_base(self, attrs): - for a, v in attrs: - if a == 'href': - self.base = v - - def do_isindex(self, attrs): - self.isindex = 1 - - def do_link(self, attrs): - pass - - def do_meta(self, attrs): - pass - - def do_nextid(self, attrs): # Deprecated - pass - - # ------ Body elements - - # --- Headings - - def start_h1(self, attrs): - self.formatter.end_paragraph(1) - self.formatter.push_font(('h1', 0, 1, 0)) - - def end_h1(self): - self.formatter.end_paragraph(1) - self.formatter.pop_font() - - def start_h2(self, attrs): - self.formatter.end_paragraph(1) - self.formatter.push_font(('h2', 0, 1, 0)) - - def end_h2(self): - self.formatter.end_paragraph(1) - self.formatter.pop_font() - - def start_h3(self, attrs): - self.formatter.end_paragraph(1) - self.formatter.push_font(('h3', 0, 1, 0)) - - def end_h3(self): - self.formatter.end_paragraph(1) - self.formatter.pop_font() - - def start_h4(self, attrs): - self.formatter.end_paragraph(1) - self.formatter.push_font(('h4', 0, 1, 0)) - - def end_h4(self): - self.formatter.end_paragraph(1) - self.formatter.pop_font() - - def start_h5(self, attrs): - self.formatter.end_paragraph(1) - self.formatter.push_font(('h5', 0, 1, 0)) - - def end_h5(self): - self.formatter.end_paragraph(1) - self.formatter.pop_font() - - def start_h6(self, attrs): - self.formatter.end_paragraph(1) - self.formatter.push_font(('h6', 0, 1, 0)) - - def end_h6(self): - self.formatter.end_paragraph(1) - self.formatter.pop_font() - - # --- Block Structuring Elements - - def do_p(self, attrs): - self.formatter.end_paragraph(1) - - def start_pre(self, attrs): - self.formatter.end_paragraph(1) - self.formatter.push_font((AS_IS, AS_IS, AS_IS, 1)) - self.nofill = self.nofill + 1 - - def end_pre(self): - self.formatter.end_paragraph(1) - self.formatter.pop_font() - self.nofill = max(0, self.nofill - 1) - - def start_xmp(self, attrs): - self.start_pre(attrs) - self.setliteral('xmp') # Tell SGML parser - - def end_xmp(self): - self.end_pre() - - def start_listing(self, attrs): - self.start_pre(attrs) - self.setliteral('listing') # Tell SGML parser - - def end_listing(self): - self.end_pre() - - def start_address(self, attrs): - self.formatter.end_paragraph(0) - self.formatter.push_font((AS_IS, 1, AS_IS, AS_IS)) - - def end_address(self): - self.formatter.end_paragraph(0) - self.formatter.pop_font() - - def start_blockquote(self, attrs): - self.formatter.end_paragraph(1) - self.formatter.push_margin('blockquote') - - def end_blockquote(self): - self.formatter.end_paragraph(1) - self.formatter.pop_margin() - - # --- List Elements - - def start_ul(self, attrs): - self.formatter.end_paragraph(not self.list_stack) - self.formatter.push_margin('ul') - self.list_stack.append(['ul', '*', 0]) - - def end_ul(self): - if self.list_stack: del self.list_stack[-1] - self.formatter.end_paragraph(not self.list_stack) - self.formatter.pop_margin() - - def do_li(self, attrs): - self.formatter.end_paragraph(0) - if self.list_stack: - [dummy, label, counter] = top = self.list_stack[-1] - top[2] = counter = counter+1 - else: - label, counter = '*', 0 - self.formatter.add_label_data(label, counter) - - def start_ol(self, attrs): - self.formatter.end_paragraph(not self.list_stack) - self.formatter.push_margin('ol') - label = '1.' - for a, v in attrs: - if a == 'type': - if len(v) == 1: v = v + '.' - label = v - self.list_stack.append(['ol', label, 0]) - - def end_ol(self): - if self.list_stack: del self.list_stack[-1] - self.formatter.end_paragraph(not self.list_stack) - self.formatter.pop_margin() - - def start_menu(self, attrs): - self.start_ul(attrs) - - def end_menu(self): - self.end_ul() - - def start_dir(self, attrs): - self.start_ul(attrs) - - def end_dir(self): - self.end_ul() - - def start_dl(self, attrs): - self.formatter.end_paragraph(1) - self.list_stack.append(['dl', '', 0]) - - def end_dl(self): - self.ddpop(1) - if self.list_stack: del self.list_stack[-1] - - def do_dt(self, attrs): - self.ddpop() - - def do_dd(self, attrs): - self.ddpop() - self.formatter.push_margin('dd') - self.list_stack.append(['dd', '', 0]) - - def ddpop(self, bl=0): - self.formatter.end_paragraph(bl) - if self.list_stack: - if self.list_stack[-1][0] == 'dd': - del self.list_stack[-1] - self.formatter.pop_margin() - - # --- Phrase Markup - - # Idiomatic Elements - - def start_cite(self, attrs): self.start_i(attrs) - def end_cite(self): self.end_i() - - def start_code(self, attrs): self.start_tt(attrs) - def end_code(self): self.end_tt() - - def start_em(self, attrs): self.start_i(attrs) - def end_em(self): self.end_i() - - def start_kbd(self, attrs): self.start_tt(attrs) - def end_kbd(self): self.end_tt() - - def start_samp(self, attrs): self.start_tt(attrs) - def end_samp(self): self.end_tt() - - def start_strong(self, attrs): self.start_b(attrs) - def end_strong(self): self.end_b() - - def start_var(self, attrs): self.start_i(attrs) - def end_var(self): self.end_i() - - # Typographic Elements - - def start_i(self, attrs): - self.formatter.push_font((AS_IS, 1, AS_IS, AS_IS)) - def end_i(self): - self.formatter.pop_font() - - def start_b(self, attrs): - self.formatter.push_font((AS_IS, AS_IS, 1, AS_IS)) - def end_b(self): - self.formatter.pop_font() - - def start_tt(self, attrs): - self.formatter.push_font((AS_IS, AS_IS, AS_IS, 1)) - def end_tt(self): - self.formatter.pop_font() - - def start_a(self, attrs): - href = '' - name = '' - type = '' - for attrname, value in attrs: - value = string.strip(value) - if attrname == 'href': - href = value - if attrname == 'name': - name = value - if attrname == 'type': - type = string.lower(value) - self.anchor_bgn(href, name, type) - - def end_a(self): - self.anchor_end() - - # --- Line Break - - def do_br(self, attrs): - self.formatter.add_line_break() - - # --- Horizontal Rule - - def do_hr(self, attrs): - self.formatter.add_hor_rule() - - # --- Image - - def do_img(self, attrs): - align = '' - alt = '(image)' - ismap = '' - src = '' - width = 0 - height = 0 - for attrname, value in attrs: - if attrname == 'align': - align = value - if attrname == 'alt': - alt = value - if attrname == 'ismap': - ismap = value - if attrname == 'src': - src = value - if attrname == 'width': - try: width = string.atoi(value) - except: pass - if attrname == 'height': - try: height = string.atoi(value) - except: pass - self.handle_image(src, alt, ismap, align, width, height) - - # --- Really Old Unofficial Deprecated Stuff - - def do_plaintext(self, attrs): - self.start_pre(attrs) - self.setnomoretags() # Tell SGML parser - - # --- Unhandled tags - - def unknown_starttag(self, tag, attrs): - pass - - def unknown_endtag(self, tag): - pass - - -def test(args = None): - import sys, formatter - - if not args: - args = sys.argv[1:] - - silent = args and args[0] == '-s' - if silent: - del args[0] - - if args: - file = args[0] - else: - file = 'test.html' - - if file == '-': - f = sys.stdin - else: - try: - f = open(file, 'r') - except IOError, msg: - print file, ":", msg - sys.exit(1) - - data = f.read() - - if f is not sys.stdin: - f.close() - - if silent: - f = formatter.NullFormatter() - else: - f = formatter.AbstractFormatter(formatter.DumbWriter()) - - p = HTMLParser(f) - p.feed(data) - p.close() - - -if __name__ == '__main__': - test() diff --git a/Lib/httplib.py b/Lib/httplib.py deleted file mode 100644 index ca431ab4cb..0000000000 --- a/Lib/httplib.py +++ /dev/null @@ -1,134 +0,0 @@ -# HTTP client class -# -# See the following URL for a description of the HTTP/1.0 protocol: -# http://www.w3.org/hypertext/WWW/Protocols/ -# (I actually implemented it from a much earlier draft.) -# -# Example: -# -# >>> from httplib import HTTP -# >>> h = HTTP('www.python.org') -# >>> h.putrequest('GET', '/index.html') -# >>> h.putheader('Accept', 'text/html') -# >>> h.putheader('Accept', 'text/plain') -# >>> h.endheaders() -# >>> errcode, errmsg, headers = h.getreply() -# >>> if errcode == 200: -# ... f = h.getfile() -# ... print f.read() # Print the raw HTML -# ... -# <HEAD> -# <TITLE>Python Language Home Page</TITLE> -# [...many more lines...] -# >>> -# -# Note that an HTTP object is used for a single request -- to issue a -# second request to the same server, you create a new HTTP object. -# (This is in accordance with the protocol, which uses a new TCP -# connection for each request.) - - -import os -import socket -import string -import regex -import regsub -import mimetools - -HTTP_VERSION = 'HTTP/1.0' -HTTP_PORT = 80 - -replypat = regsub.gsub('\\.', '\\\\.', HTTP_VERSION) + \ - '[ \t]+\([0-9][0-9][0-9]\)\(.*\)' -replyprog = regex.compile(replypat) - -class HTTP: - - def __init__(self, host = '', port = 0): - self.debuglevel = 0 - self.file = None - if host: self.connect(host, port) - - def set_debuglevel(self, debuglevel): - self.debuglevel = debuglevel - - def connect(self, host, port = 0): - if not port: - i = string.find(host, ':') - if i >= 0: - host, port = host[:i], host[i+1:] - try: port = string.atoi(port) - except string.atoi_error: - raise socket.error, "nonnumeric port" - if not port: port = HTTP_PORT - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - if self.debuglevel > 0: print 'connect:', (host, port) - self.sock.connect(host, port) - - def send(self, str): - if self.debuglevel > 0: print 'send:', `str` - self.sock.send(str) - - def putrequest(self, request, selector): - if not selector: selector = '/' - str = '%s %s %s\r\n' % (request, selector, HTTP_VERSION) - self.send(str) - - def putheader(self, header, *args): - str = '%s: %s\r\n' % (header, string.joinfields(args,'\r\n\t')) - self.send(str) - - def endheaders(self): - self.send('\r\n') - - def getreply(self): - self.file = self.sock.makefile('rb') - self.sock = None - line = self.file.readline() - if self.debuglevel > 0: print 'reply:', `line` - if replyprog.match(line) < 0: - self.headers = None - return -1, line, self.headers - errcode, errmsg = replyprog.group(1, 2) - errcode = string.atoi(errcode) - errmsg = string.strip(errmsg) - self.headers = mimetools.Message(self.file, 0) - return errcode, errmsg, self.headers - - def getfile(self): - return self.file - - def close(self): - if self.file: - self.file.close() - self.file = None - - -def test(): - import sys - import getopt - opts, args = getopt.getopt(sys.argv[1:], 'd') - dl = 0 - for o, a in opts: - if o == '-d': dl = dl + 1 - host = 'www.python.org' - selector = '/' - if args[0:]: host = args[0] - if args[1:]: selector = args[1] - h = HTTP() - h.set_debuglevel(dl) - h.connect(host) - h.putrequest('GET', selector) - h.endheaders() - errcode, errmsg, headers = h.getreply() - print 'errcode =', errcode - print 'errmsg =', errmsg - print - if headers: - for header in headers.headers: print string.strip(header) - print - print h.getfile().read() - - -if __name__ == '__main__': - test() diff --git a/Lib/ihooks.py b/Lib/ihooks.py deleted file mode 100644 index a6ab1a5d70..0000000000 --- a/Lib/ihooks.py +++ /dev/null @@ -1,366 +0,0 @@ -"""Import hook support. - -Consistent use of this module will make it possible to change the -different mechanisms involved in loading modules independently. - -While the built-in module imp exports interfaces to the built-in -module searching and loading algorithm, and it is possible to replace -the built-in function __import__ in order to change the semantics of -the import statement, until now it has been difficult to combine the -effect of different __import__ hacks, like loading modules from URLs -(rimport.py), implementing a hierarchical module namespace (newimp.py) -or restricted execution (rexec.py). - -This module defines three new concepts: - -(1) A "file system hooks" class provides an interface to a filesystem. - -One hooks class is defined (Hooks), which uses the interface provided -by standard modules os and os.path. It should be used as the base -class for other hooks classes. - -(2) A "module loader" class provides an interface to to search for a -module in a search path and to load it. It defines a method which -searches for a module in a single directory; by overriding this method -one can redefine the details of the search. If the directory is None, -built-in and frozen modules are searched instead. - -Two module loader class are defined, both implementing the search -strategy used by the built-in __import__ function: ModuleLoader uses -the imp module's find_module interface, while HookableModuleLoader -uses a file system hooks class to interact with the file system. Both -use the imp module's load_* interfaces to actually load the module. - -(3) A "module importer" class provides an interface to import a -module, as well as interfaces to reload and unload a module. It also -provides interfaces to install and uninstall itself instead of the -default __import__ and reload (and unload) functions. - -One module importer class is defined (ModuleImporter), which uses a -module loader instance passed in (by default HookableModuleLoader is -instantiated). - -The classes defined here should be used as base classes for extended -functionality along those lines. - -If a module mporter class supports dotted names, its import_module() -must return a different value depending on whether it is called on -behalf of a "from ... import ..." statement or not. (This is caused -by the way the __import__ hook is used by the Python interpreter.) It -would also do wise to install a different version of reload(). - -XXX Should the imp.load_* functions also be called via the hooks -instance? - -""" - - -import __builtin__ -import imp -import os -import sys - - -from imp import C_EXTENSION, PY_SOURCE, PY_COMPILED -BUILTIN_MODULE = 32 -FROZEN_MODULE = 33 - - -class _Verbose: - - def __init__(self, verbose = 0): - self.verbose = verbose - - def get_verbose(self): - return self.verbose - - def set_verbose(self, verbose): - self.verbose = verbose - - # XXX The following is an experimental interface - - def note(self, *args): - if self.verbose: - apply(self.message, args) - - def message(self, format, *args): - print format%args - - -class BasicModuleLoader(_Verbose): - - """Basic module loader. - - This provides the same functionality as built-in import. It - doesn't deal with checking sys.modules -- all it provides is - find_module() and a load_module(), as well as find_module_in_dir() - which searches just one directory, and can be overridden by a - derived class to change the module search algorithm when the basic - dependency on sys.path is unchanged. - - The interface is a little more convenient than imp's: - find_module(name, [path]) returns None or 'stuff', and - load_module(name, stuff) loads the module. - - """ - - def find_module(self, name, path = None): - if path is None: - path = [None] + self.default_path() - for dir in path: - stuff = self.find_module_in_dir(name, dir) - if stuff: return stuff - return None - - def default_path(self): - return sys.path - - def find_module_in_dir(self, name, dir): - if dir is None: - return self.find_builtin_module(name) - else: - try: - return imp.find_module(name, [dir]) - except ImportError: - return None - - def find_builtin_module(self, name): - if imp.is_builtin(name): - return None, '', ('', '', BUILTIN_MODULE) - if imp.is_frozen(name): - return None, '', ('', '', FROZEN_MODULE) - return None - - def load_module(self, name, stuff): - file, filename, (suff, mode, type) = stuff - if type == BUILTIN_MODULE: - return imp.init_builtin(name) - if type == FROZEN_MODULE: - return imp.init_frozen(name) - if type == C_EXTENSION: - return imp.load_dynamic(name, filename, file) - if type == PY_SOURCE: - return imp.load_source(name, filename, file) - if type == PY_COMPILED: - return imp.load_compiled(name, filename, file) - raise ImportError, "Unrecognized module type (%s) for %s" % \ - (`type`, name) - - -class Hooks(_Verbose): - - """Hooks into the filesystem and interpreter. - - By deriving a subclass you can redefine your filesystem interface, - e.g. to merge it with the URL space. - - This base class behaves just like the native filesystem. - - """ - - # imp interface - def get_suffixes(self): return imp.get_suffixes() - def new_module(self, name): return imp.new_module(name) - def is_builtin(self, name): return imp.is_builtin(name) - def init_builtin(self, name): return imp.init_builtin(name) - def is_frozen(self, name): return imp.is_frozen(name) - def init_frozen(self, name): return imp.init_frozen(name) - def get_frozen_object(self, name): return imp.get_frozen_object(name) - def load_source(self, name, filename, file=None): - return imp.load_source(name, filename, file) - def load_compiled(self, name, filename, file=None): - return imp.load_compiled(name, filename, file) - def load_dynamic(self, name, filename, file=None): - return imp.load_dynamic(name, filename, file) - - def add_module(self, name): - d = self.modules_dict() - if d.has_key(name): return d[name] - d[name] = m = self.new_module(name) - return m - - # sys interface - def modules_dict(self): return sys.modules - def default_path(self): return sys.path - - def path_split(self, x): return os.path.split(x) - def path_join(self, x, y): return os.path.join(x, y) - def path_isabs(self, x): return os.path.isabs(x) - # etc. - - def path_exists(self, x): return os.path.exists(x) - def path_isdir(self, x): return os.path.isdir(x) - def path_isfile(self, x): return os.path.isfile(x) - def path_islink(self, x): return os.path.islink(x) - # etc. - - def openfile(self, *x): return apply(open, x) - openfile_error = IOError - def listdir(self, x): return os.listdir(x) - listdir_error = os.error - # etc. - - -class ModuleLoader(BasicModuleLoader): - - """Default module loader; uses file system hooks. - - By defining suitable hooks, you might be able to load modules from - other sources than the file system, e.g. from compressed or - encrypted files, tar files or (if you're brave!) URLs. - - """ - - def __init__(self, hooks = None, verbose = 0): - BasicModuleLoader.__init__(self, verbose) - self.hooks = hooks or Hooks(verbose) - - def default_path(self): - return self.hooks.default_path() - - def modules_dict(self): - return self.hooks.modules_dict() - - def get_hooks(self): - return self.hooks - - def set_hooks(self, hooks): - self.hooks = hooks - - def find_builtin_module(self, name): - if self.hooks.is_builtin(name): - return None, '', ('', '', BUILTIN_MODULE) - if self.hooks.is_frozen(name): - return None, '', ('', '', FROZEN_MODULE) - return None - - def find_module_in_dir(self, name, dir): - if dir is None: - return self.find_builtin_module(name) - for info in self.hooks.get_suffixes(): - suff, mode, type = info - fullname = self.hooks.path_join(dir, name+suff) - try: - fp = self.hooks.openfile(fullname, mode) - return fp, fullname, info - except self.hooks.openfile_error: - pass - return None - - def load_module(self, name, stuff): - file, filename, (suff, mode, type) = stuff - if type == BUILTIN_MODULE: - return self.hooks.init_builtin(name) - if type == FROZEN_MODULE: - return self.hooks.init_frozen(name) - if type == C_EXTENSION: - return self.hooks.load_dynamic(name, filename, file) - if type == PY_SOURCE: - return self.hooks.load_source(name, filename, file) - if type == PY_COMPILED: - return self.hooks.load_compiled(name, filename, file) - raise ImportError, "Unrecognized module type (%s) for %s" % \ - (`type`, name) - - -class FancyModuleLoader(ModuleLoader): - - """Fancy module loader -- parses and execs the code itself.""" - - def load_module(self, name, stuff): - file, filename, (suff, mode, type) = stuff - if type == FROZEN_MODULE: - code = self.hooks.get_frozen_object(name) - elif type == PY_COMPILED: - file.seek(8) - code = marshal.load(file) - elif type == PY_SOURCE: - data = file.read() - code = compile(data, filename, 'exec') - else: - return ModuleLoader.load_module(self, name, stuff) - m = self.hooks.add_module(name) - exec code in m.__dict__ - return m - - -class ModuleImporter(_Verbose): - - """Default module importer; uses module loader. - - This provides the same functionality as built-in import, when - combined with ModuleLoader. - - """ - - def __init__(self, loader = None, verbose = 0): - _Verbose.__init__(self, verbose) - self.loader = loader or ModuleLoader(None, verbose) - self.modules = self.loader.modules_dict() - - def get_loader(self): - return self.loader - - def set_loader(self, loader): - self.loader = loader - - def get_hooks(self): - return self.loader.get_hooks() - - def set_hooks(self, hooks): - return self.loader.set_hooks(hooks) - - def import_module(self, name, globals={}, locals={}, fromlist=[]): - if self.modules.has_key(name): - return self.modules[name] # Fast path - stuff = self.loader.find_module(name) - if not stuff: - raise ImportError, "No module named %s" % name - return self.loader.load_module(name, stuff) - - def reload(self, module, path = None): - name = module.__name__ - stuff = self.loader.find_module(name, path) - if not stuff: - raise ImportError, "Module %s not found for reload" % name - return self.loader.load_module(name, stuff) - - def unload(self, module): - del self.modules[module.__name__] - # XXX Should this try to clear the module's namespace? - - def install(self): - self.save_import_module = __builtin__.__import__ - self.save_reload = __builtin__.reload - if not hasattr(__builtin__, 'unload'): - __builtin__.unload = None - self.save_unload = __builtin__.unload - __builtin__.__import__ = self.import_module - __builtin__.reload = self.reload - __builtin__.unload = self.unload - - def uninstall(self): - __builtin__.__import__ = self.save_import_module - __builtin__.reload = self.save_reload - __builtin__.unload = self.save_unload - if not __builtin__.unload: - del __builtin__.unload - - -# XXX Some experimental hacks -- importing ihooks auto-installs! -# XXX (That's supposed to be transparent anyway...) - -default_importer = None -current_importer = None - -def install(importer = None): - global current_importer - current_importer = importer or default_importer or ModuleImporter() - current_importer.install() - -def uninstall(): - global current_importer - current_importer.uninstall() - - -install() diff --git a/Lib/imghdr.py b/Lib/imghdr.py deleted file mode 100644 index 62518b5f36..0000000000 --- a/Lib/imghdr.py +++ /dev/null @@ -1,129 +0,0 @@ -# Recognizing image files based on their first few bytes. - - -#-------------------------# -# Recognize sound headers # -#-------------------------# - -def what(filename): - f = open(filename, 'r') - h = f.read(32) - for tf in tests: - res = tf(h, f) - if res: - return res - return None - - -#---------------------------------# -# Subroutines per image file type # -#---------------------------------# - -tests = [] - -def test_rgb(h, f): - # SGI image library - if h[:2] == '\001\332': - return 'rgb' - -tests.append(test_rgb) - -def test_gif(h, f): - # GIF ('87 and '89 variants) - if h[:6] in ('GIF87a', 'GIF89a'): - return 'gif' - -tests.append(test_gif) - -def test_pbm(h, f): - # PBM (portable bitmap) - if len(h) >= 3 and \ - h[0] == 'P' and h[1] in '14' and h[2] in ' \t\n\r': - return 'pbm' - -tests.append(test_pbm) - -def test_pgm(h, f): - # PGM (portable graymap) - if len(h) >= 3 and \ - h[0] == 'P' and h[1] in '25' and h[2] in ' \t\n\r': - return 'pgm' - -tests.append(test_pgm) - -def test_ppm(h, f): - # PPM (portable pixmap) - if len(h) >= 3 and \ - h[0] == 'P' and h[1] in '36' and h[2] in ' \t\n\r': - return 'ppm' - -tests.append(test_ppm) - -def test_tiff(h, f): - # TIFF (can be in Motorola or Intel byte order) - if h[:2] in ('MM', 'II'): - return 'tiff' - -tests.append(test_tiff) - -def test_rast(h, f): - # Sun raster file - if h[:4] == '\x59\xA6\x6A\x95': - return 'rast' - -tests.append(test_rast) - -def test_xbm(h, f): - # X bitmap (X10 or X11) - s = '#define ' - if h[:len(s)] == s: - return 'xbm' - -tests.append(test_xbm) - -def test_jpeg(h, f): - # JPEG data in JFIF format - if h[6:10] == 'JFIF': - return 'jpeg' - -tests.append(test_jpeg) - -#--------------------# -# Small test program # -#--------------------# - -def test(): - import sys - recursive = 0 - if sys.argv[1:] and sys.argv[1] == '-r': - del sys.argv[1:2] - recursive = 1 - try: - if sys.argv[1:]: - testall(sys.argv[1:], recursive, 1) - else: - testall(['.'], recursive, 1) - except KeyboardInterrupt: - sys.stderr.write('\n[Interrupted]\n') - sys.exit(1) - -def testall(list, recursive, toplevel): - import sys - import os - for filename in list: - if os.path.isdir(filename): - print filename + '/:', - if recursive or toplevel: - print 'recursing down:' - import glob - names = glob.glob(os.path.join(filename, '*')) - testall(names, recursive, 0) - else: - print '*** directory (use -r) ***' - else: - print filename + ':', - sys.stdout.flush() - try: - print what(filename) - except IOError: - print '*** not found ***' diff --git a/Lib/importall.py b/Lib/importall.py deleted file mode 100755 index 780862cf33..0000000000 --- a/Lib/importall.py +++ /dev/null @@ -1,36 +0,0 @@ -# THIS IS OBSOLETE -- USE MODULE 'compileall' INSTEAD! - -# Utility module to import all modules in the path, in the hope -# that this will update their ".pyc" files. - -import os -import sys - -# Sabotage 'gl' and 'stdwin' to prevent windows popping up... -for m in 'gl', 'stdwin', 'fl', 'fm': - sys.modules[m] = sys - -exceptions = ['importall'] - -for dir in sys.path: - print 'Listing', dir - try: - names = os.listdir(dir) - except os.error: - print 'Can\'t list', dir - names = [] - names.sort() - for name in names: - head, tail = name[:-3], name[-3:] - if tail == '.py' and head not in exceptions: - s = 'import ' + head - print s - try: - exec s + '\n' - except KeyboardInterrupt: - del names[:] - print '\n[interrupt]' - break - except: - print 'Sorry:', sys.exc_type + ':', - print sys.exc_value diff --git a/Lib/irix5/AL.py b/Lib/irix5/AL.py deleted file mode 100755 index c4497ab4a8..0000000000 --- a/Lib/irix5/AL.py +++ /dev/null @@ -1,60 +0,0 @@ -RATE_48000 = 48000 -RATE_44100 = 44100 -RATE_32000 = 32000 -RATE_22050 = 22050 -RATE_16000 = 16000 -RATE_11025 = 11025 -RATE_8000 = 8000 - -SAMPFMT_TWOSCOMP= 1 -SAMPFMT_FLOAT = 32 -SAMPFMT_DOUBLE = 64 - -SAMPLE_8 = 1 -SAMPLE_16 = 2 - # SAMPLE_24 is the low 24 bits of a long, sign extended to 32 bits -SAMPLE_24 = 4 - -MONO = 1 -STEREO = 2 - -INPUT_LINE = 0 -INPUT_MIC = 1 -INPUT_DIGITAL = 2 - -MONITOR_OFF = 0 -MONITOR_ON = 1 - -ERROR_NUMBER = 0 -ERROR_TYPE = 1 -ERROR_LOCATION_LSP = 2 -ERROR_LOCATION_MSP = 3 -ERROR_LENGTH = 4 - -ERROR_INPUT_UNDERFLOW = 0 -ERROR_OUTPUT_OVERFLOW = 1 - -# These seem to be not supported anymore: -##HOLD, RELEASE = 0, 1 -##ATTAIL, ATHEAD, ATMARK, ATTIME = 0, 1, 2, 3 - -DEFAULT_DEVICE = 1 - -INPUT_SOURCE = 0 -LEFT_INPUT_ATTEN = 1 -RIGHT_INPUT_ATTEN = 2 -INPUT_RATE = 3 -OUTPUT_RATE = 4 -LEFT_SPEAKER_GAIN = 5 -RIGHT_SPEAKER_GAIN = 6 -INPUT_COUNT = 7 -OUTPUT_COUNT = 8 -UNUSED_COUNT = 9 -SYNC_INPUT_TO_AES = 10 -SYNC_OUTPUT_TO_AES = 11 -MONITOR_CTL = 12 -LEFT_MONITOR_ATTEN = 13 -RIGHT_MONITOR_ATTEN = 14 - -ENUM_VALUE = 0 # only certain values are valid -RANGE_VALUE = 1 # any value in range is valid diff --git a/Lib/irix5/AWARE.py b/Lib/irix5/AWARE.py deleted file mode 100755 index 30be50b8ee..0000000000 --- a/Lib/irix5/AWARE.py +++ /dev/null @@ -1,54 +0,0 @@ -# -# Copyright (c) 1992 Aware, Inc. All rights reserved. -# -# Copyright Unpublished, Aware Inc. All Rights Reserved. -# This software contains proprietary and confidential -# information of Aware, Inc. Use, disclosure or -# reproduction is prohibited without the prior express -# written consent of Aware, Inc. -# -# - -# -# awareAudio.h - Aware Compression Library Parameter Header -# -# 01/21/92 Original Version by Brian Knittel and Jonathon Devine -# - -import CL - -# Aware Audio Specific Parameters - For both MPEG Audio and Multirate -CL.CHANNEL_POLICY = CL.NUMBER_OF_PARAMS + 0 -CL.NOISE_MARGIN = CL.NUMBER_OF_PARAMS + 1 -CL.BITRATE_POLICY = CL.NUMBER_OF_PARAMS + 2 - -# Additional parameters for MPEG Audio -CL.BITRATE_TARGET = CL.NUMBER_OF_PARAMS + 3 -CL.LAYER = CL.NUMBER_OF_PARAMS + 4 - -# read/write for compression configuration -# read for state during compression/decompression - -# -# Channel Policy -# -AWCMP_STEREO = 1 -AWCMP_JOINT_STEREO = 2 -AWCMP_INDEPENDENT = 3 - -# -# read/write for compression configuration, -# read for state during compression -# -# -# Bit-rate Policy -# -AWCMP_FIXED_RATE = 1 -AWCMP_CONST_QUAL = 2 -AWCMP_LOSSLESS = 4 - -# -# Layer values -# -AWCMP_MPEG_LAYER_I = 1 -AWCMP_MPEG_LAYER_II = 2 diff --git a/Lib/irix5/CD.py b/Lib/irix5/CD.py deleted file mode 100755 index ad56561235..0000000000 --- a/Lib/irix5/CD.py +++ /dev/null @@ -1,34 +0,0 @@ -ERROR = 0 -NODISC = 1 -READY = 2 -PLAYING = 3 -PAUSED = 4 -STILL = 5 - -AUDIO = 0 -PNUM = 1 -INDEX = 2 -PTIME = 3 -ATIME = 4 -CATALOG = 5 -IDENT = 6 -CONTROL = 7 - -CDDA_DATASIZE = 2352 - -##CDDA_SUBCODESIZE = (sizeof(struct subcodeQ)) -##CDDA_BLOCKSIZE = (sizeof(struct cdframe)) -##CDDA_NUMSAMPLES = (CDDA_DATASIZE/2) -## -##CDQ_PREEMP_MASK = 0xd -##CDQ_COPY_MASK = 0xb -##CDQ_DDATA_MASK = 0xd -##CDQ_BROADCAST_MASK = 0x8 -##CDQ_PREEMPHASIS = 0x1 -##CDQ_COPY_PERMITTED = 0x2 -##CDQ_DIGITAL_DATA = 0x4 -##CDQ_BROADCAST_USE = 0x8 -## -##CDQ_MODE1 = 0x1 -##CDQ_MODE2 = 0x2 -##CDQ_MODE3 = 0x3 diff --git a/Lib/irix5/CL.py b/Lib/irix5/CL.py deleted file mode 100755 index 468ecaaa68..0000000000 --- a/Lib/irix5/CL.py +++ /dev/null @@ -1,24 +0,0 @@ -# Backward compatible module CL. -# All relevant symbols are now defined in the module cl. -try: - from cl import * -except ImportError: - from CL_old import * -else: - del CompressImage - del DecompressImage - del GetAlgorithmName - del OpenCompressor - del OpenDecompressor - del QueryAlgorithms - del QueryMaxHeaderSize - del QueryScheme - del QuerySchemeFromName - del SetDefault - del SetMax - del SetMin - try: - del cvt_type - except NameError: - pass - del error diff --git a/Lib/irix5/CL_old.py b/Lib/irix5/CL_old.py deleted file mode 100755 index 41c56e0cca..0000000000 --- a/Lib/irix5/CL_old.py +++ /dev/null @@ -1,236 +0,0 @@ -# -# cl.h - Compression Library typedefs and prototypes -# -# 01/07/92 Cleanup by Brian Knittel -# 02/18/92 Original Version by Brian Knittel -# - -# -# originalFormat parameter values -# -MAX_NUMBER_OF_ORIGINAL_FORMATS = 32 - -# Audio -MONO = 0 -STEREO_INTERLEAVED = 1 - -# Video -# YUV is defined to be the same thing as YCrCb (luma and two chroma components). -# 422 is appended to YUV (or YCrCb) if the chroma is sub-sampled by 2 -# horizontally, packed as U Y1 V Y2 (byte order). -# 422HC is appended to YUV (or YCrCb) if the chroma is sub-sampled by 2 -# vertically in addition to horizontally, and is packed the same as -# 422 except that U & V are not valid on the second line. -# -RGB = 0 -RGBX = 1 -RGBA = 2 -RGB332 = 3 - -GRAYSCALE = 4 -Y = 4 -YUV = 5 -YCbCr = 5 -YUV422 = 6 # 4:2:2 sampling -YCbCr422 = 6 # 4:2:2 sampling -YUV422HC = 7 # 4:1:1 sampling -YCbCr422HC = 7 # 4:1:1 sampling -YUV422DC = 7 # 4:1:1 sampling -YCbCr422DC = 7 # 4:1:1 sampling - -BEST_FIT = -1 - -def BytesPerSample(s): - if s in (MONO, YUV): - return 2 - elif s == STEREO_INTERLEAVED: - return 4 - else: - return 0 - -def BytesPerPixel(f): - if f in (RGB, YUV): - return 3 - elif f in (RGBX, RGBA): - return 4 - elif f in (RGB332, GRAYSCALE): - return 1 - else: - return 2 - -def AudioFormatName(f): - if f == MONO: - return 'MONO' - elif f == STEREO_INTERLEAVED: - return 'STEREO_INTERLEAVED' - else: - return 'Not a valid format' - -def VideoFormatName(f): - if f == RGB: - return 'RGB' - elif f == RGBX: - return 'RGBX' - elif f == RGBA: - return 'RGBA' - elif f == RGB332: - return 'RGB332' - elif f == GRAYSCALE: - return 'GRAYSCALE' - elif f == YUV: - return 'YUV' - elif f == YUV422: - return 'YUV422' - elif f == YUV422DC: - return 'YUV422DC' - else: - return 'Not a valid format' - -MAX_NUMBER_OF_AUDIO_ALGORITHMS = 32 -MAX_NUMBER_OF_VIDEO_ALGORITHMS = 32 - -# -# Algorithm types -# -AUDIO = 0 -VIDEO = 1 - -def AlgorithmNumber(scheme): - return scheme & 0x7fff -def AlgorithmType(scheme): - return (scheme >> 15) & 1 -def Algorithm(type, n): - return n | ((type & 1) << 15) - -# -# "compressionScheme" argument values -# -UNKNOWN_SCHEME = -1 - -UNCOMPRESSED_AUDIO = Algorithm(AUDIO, 0) -G711_ULAW = Algorithm(AUDIO, 1) -ULAW = Algorithm(AUDIO, 1) -G711_ALAW = Algorithm(AUDIO, 2) -ALAW = Algorithm(AUDIO, 2) -AWARE_MPEG_AUDIO = Algorithm(AUDIO, 3) -AWARE_MULTIRATE = Algorithm(AUDIO, 4) - -UNCOMPRESSED = Algorithm(VIDEO, 0) -UNCOMPRESSED_VIDEO = Algorithm(VIDEO, 0) -RLE = Algorithm(VIDEO, 1) -JPEG = Algorithm(VIDEO, 2) -MPEG_VIDEO = Algorithm(VIDEO, 3) -MVC1 = Algorithm(VIDEO, 4) -RTR = Algorithm(VIDEO, 5) -RTR1 = Algorithm(VIDEO, 5) - -# -# Parameters -# -MAX_NUMBER_OF_PARAMS = 256 -# Default Parameters -IMAGE_WIDTH = 0 -IMAGE_HEIGHT = 1 -ORIGINAL_FORMAT = 2 -INTERNAL_FORMAT = 3 -COMPONENTS = 4 -BITS_PER_COMPONENT = 5 -FRAME_RATE = 6 -COMPRESSION_RATIO = 7 -EXACT_COMPRESSION_RATIO = 8 -FRAME_BUFFER_SIZE = 9 -COMPRESSED_BUFFER_SIZE = 10 -BLOCK_SIZE = 11 -PREROLL = 12 -FRAME_TYPE = 13 -ALGORITHM_ID = 14 -ALGORITHM_VERSION = 15 -ORIENTATION = 16 -NUMBER_OF_FRAMES = 17 -SPEED = 18 -LAST_FRAME_INDEX = 19 -NUMBER_OF_PARAMS = 20 - -# JPEG Specific Parameters -QUALITY_FACTOR = NUMBER_OF_PARAMS + 0 - -# MPEG Specific Parameters -END_OF_SEQUENCE = NUMBER_OF_PARAMS + 0 - -# RTR Specific Parameters -QUALITY_LEVEL = NUMBER_OF_PARAMS + 0 -ZOOM_X = NUMBER_OF_PARAMS + 1 -ZOOM_Y = NUMBER_OF_PARAMS + 2 - -# -# Parameter value types -# -ENUM_VALUE = 0 # only certain constant values are valid -RANGE_VALUE = 1 # any value in a given range is valid -FLOATING_ENUM_VALUE = 2 # only certain constant floating point values are valid -FLOATING_RANGE_VALUE = 3 # any value in a given floating point range is valid - -# -# Algorithm Functionality -# -DECOMPRESSOR = 1 -COMPRESSOR = 2 -CODEC = 3 - -# -# Buffer types -# -NONE = 0 -FRAME = 1 -DATA = 2 - -# -# Frame types -# -NONE = 0 -KEYFRAME = 1 -INTRA = 1 -PREDICTED = 2 -BIDIRECTIONAL = 3 - -# -# Orientations -# -TOP_DOWN = 0 -BOTTOM_UP = 1 - -# -# SGI Proprietaty Algorithm Header Start Code -# -HEADER_START_CODE = 0xc1C0DEC - -# -# error codes -# - -BAD_NO_BUFFERSPACE = -2 # no space for internal buffers -BAD_PVBUFFER = -3 # param/val buffer doesn't make sense -BAD_BUFFERLENGTH_NEG = -4 # negative buffer length -BAD_BUFFERLENGTH_ODD = -5 # odd length parameter/value buffer -BAD_PARAM = -6 # invalid parameter -BAD_COMPRESSION_SCHEME = -7 # compression scheme parameter invalid -BAD_COMPRESSOR_HANDLE = -8 # compression handle parameter invalid -BAD_COMPRESSOR_HANDLE_POINTER = -9 # compression handle pointer invalid -BAD_BUFFER_HANDLE = -10 # buffer handle invalid -BAD_BUFFER_QUERY_SIZE = -11 # buffer query size too large -JPEG_ERROR = -12 # error from libjpeg -BAD_FRAME_SIZE = -13 # frame size invalid -PARAM_OUT_OF_RANGE = -14 # parameter out of range -ADDED_ALGORITHM_ERROR = -15 # added algorithm had a unique error -BAD_ALGORITHM_TYPE = -16 # bad algorithm type -BAD_ALGORITHM_NAME = -17 # bad algorithm name -BAD_BUFFERING = -18 # bad buffering calls -BUFFER_NOT_CREATED = -19 # buffer not created -BAD_BUFFER_EXISTS = -20 # buffer already created -BAD_INTERNAL_FORMAT = -21 # invalid internal format -BAD_BUFFER_POINTER = -22 # invalid buffer pointer -FRAME_BUFFER_SIZE_ZERO = -23 # frame buffer has zero size -BAD_STREAM_HEADER = -24 # invalid stream header - -BAD_LICENSE = -25 # netls license not valid -AWARE_ERROR = -26 # error from libawcmp diff --git a/Lib/irix5/DEVICE.py b/Lib/irix5/DEVICE.py deleted file mode 100755 index 7ace8cb0b6..0000000000 --- a/Lib/irix5/DEVICE.py +++ /dev/null @@ -1,400 +0,0 @@ -NULLDEV = 0 -BUTOFFSET = 1 -VALOFFSET = 256 -PSEUDOFFSET = 512 -BUT2OFFSET = 3840 -TIMOFFSET = 515 -XKBDOFFSET = 143 -BUTCOUNT = 255 -VALCOUNT = 256 -TIMCOUNT = 4 -XKBDCOUNT = 28 -USERBUTOFFSET = 4096 -USERVALOFFSET = 12288 -USERPSEUDOFFSET = 16384 -BUT0 = 1 -BUT1 = 2 -BUT2 = 3 -BUT3 = 4 -BUT4 = 5 -BUT5 = 6 -BUT6 = 7 -BUT7 = 8 -BUT8 = 9 -BUT9 = 10 -BUT10 = 11 -BUT11 = 12 -BUT12 = 13 -BUT13 = 14 -BUT14 = 15 -BUT15 = 16 -BUT16 = 17 -BUT17 = 18 -BUT18 = 19 -BUT19 = 20 -BUT20 = 21 -BUT21 = 22 -BUT22 = 23 -BUT23 = 24 -BUT24 = 25 -BUT25 = 26 -BUT26 = 27 -BUT27 = 28 -BUT28 = 29 -BUT29 = 30 -BUT30 = 31 -BUT31 = 32 -BUT32 = 33 -BUT33 = 34 -BUT34 = 35 -BUT35 = 36 -BUT36 = 37 -BUT37 = 38 -BUT38 = 39 -BUT39 = 40 -BUT40 = 41 -BUT41 = 42 -BUT42 = 43 -BUT43 = 44 -BUT44 = 45 -BUT45 = 46 -BUT46 = 47 -BUT47 = 48 -BUT48 = 49 -BUT49 = 50 -BUT50 = 51 -BUT51 = 52 -BUT52 = 53 -BUT53 = 54 -BUT54 = 55 -BUT55 = 56 -BUT56 = 57 -BUT57 = 58 -BUT58 = 59 -BUT59 = 60 -BUT60 = 61 -BUT61 = 62 -BUT62 = 63 -BUT63 = 64 -BUT64 = 65 -BUT65 = 66 -BUT66 = 67 -BUT67 = 68 -BUT68 = 69 -BUT69 = 70 -BUT70 = 71 -BUT71 = 72 -BUT72 = 73 -BUT73 = 74 -BUT74 = 75 -BUT75 = 76 -BUT76 = 77 -BUT77 = 78 -BUT78 = 79 -BUT79 = 80 -BUT80 = 81 -BUT81 = 82 -BUT82 = 83 -MAXKBDBUT = 83 -BUT100 = 101 -BUT101 = 102 -BUT102 = 103 -BUT103 = 104 -BUT104 = 105 -BUT105 = 106 -BUT106 = 107 -BUT107 = 108 -BUT108 = 109 -BUT109 = 110 -BUT110 = 111 -BUT111 = 112 -BUT112 = 113 -BUT113 = 114 -BUT114 = 115 -BUT115 = 116 -BUT116 = 117 -BUT117 = 118 -BUT118 = 119 -BUT119 = 120 -BUT120 = 121 -BUT121 = 122 -BUT122 = 123 -BUT123 = 124 -BUT124 = 125 -BUT125 = 126 -BUT126 = 127 -BUT127 = 128 -BUT128 = 129 -BUT129 = 130 -BUT130 = 131 -BUT131 = 132 -BUT132 = 133 -BUT133 = 134 -BUT134 = 135 -BUT135 = 136 -BUT136 = 137 -BUT137 = 138 -BUT138 = 139 -BUT139 = 140 -BUT140 = 141 -BUT141 = 142 -BUT142 = 143 -BUT143 = 144 -BUT144 = 145 -BUT145 = 146 -BUT146 = 147 -BUT147 = 148 -BUT148 = 149 -BUT149 = 150 -BUT150 = 151 -BUT151 = 152 -BUT152 = 153 -BUT153 = 154 -BUT154 = 155 -BUT155 = 156 -BUT156 = 157 -BUT157 = 158 -BUT158 = 159 -BUT159 = 160 -BUT160 = 161 -BUT161 = 162 -BUT162 = 163 -BUT163 = 164 -BUT164 = 165 -BUT165 = 166 -BUT166 = 167 -BUT167 = 168 -BUT168 = 169 -BUT181 = 182 -BUT182 = 183 -BUT183 = 184 -BUT184 = 185 -BUT185 = 186 -BUT186 = 187 -BUT187 = 188 -BUT188 = 189 -BUT189 = 190 -MOUSE1 = 101 -MOUSE2 = 102 -MOUSE3 = 103 -LEFTMOUSE = 103 -MIDDLEMOUSE = 102 -RIGHTMOUSE = 101 -LPENBUT = 104 -BPAD0 = 105 -BPAD1 = 106 -BPAD2 = 107 -BPAD3 = 108 -LPENVALID = 109 -SWBASE = 111 -SW0 = 111 -SW1 = 112 -SW2 = 113 -SW3 = 114 -SW4 = 115 -SW5 = 116 -SW6 = 117 -SW7 = 118 -SW8 = 119 -SW9 = 120 -SW10 = 121 -SW11 = 122 -SW12 = 123 -SW13 = 124 -SW14 = 125 -SW15 = 126 -SW16 = 127 -SW17 = 128 -SW18 = 129 -SW19 = 130 -SW20 = 131 -SW21 = 132 -SW22 = 133 -SW23 = 134 -SW24 = 135 -SW25 = 136 -SW26 = 137 -SW27 = 138 -SW28 = 139 -SW29 = 140 -SW30 = 141 -SW31 = 142 -SBBASE = 182 -SBPICK = 182 -SBBUT1 = 183 -SBBUT2 = 184 -SBBUT3 = 185 -SBBUT4 = 186 -SBBUT5 = 187 -SBBUT6 = 188 -SBBUT7 = 189 -SBBUT8 = 190 -AKEY = 11 -BKEY = 36 -CKEY = 28 -DKEY = 18 -EKEY = 17 -FKEY = 19 -GKEY = 26 -HKEY = 27 -IKEY = 40 -JKEY = 34 -KKEY = 35 -LKEY = 42 -MKEY = 44 -NKEY = 37 -OKEY = 41 -PKEY = 48 -QKEY = 10 -RKEY = 24 -SKEY = 12 -TKEY = 25 -UKEY = 33 -VKEY = 29 -WKEY = 16 -XKEY = 21 -YKEY = 32 -ZKEY = 20 -ZEROKEY = 46 -ONEKEY = 8 -TWOKEY = 14 -THREEKEY = 15 -FOURKEY = 22 -FIVEKEY = 23 -SIXKEY = 30 -SEVENKEY = 31 -EIGHTKEY = 38 -NINEKEY = 39 -BREAKKEY = 1 -SETUPKEY = 2 -CTRLKEY = 3 -LEFTCTRLKEY = CTRLKEY -CAPSLOCKKEY = 4 -RIGHTSHIFTKEY = 5 -LEFTSHIFTKEY = 6 -NOSCRLKEY = 13 -ESCKEY = 7 -TABKEY = 9 -RETKEY = 51 -SPACEKEY = 83 -LINEFEEDKEY = 60 -BACKSPACEKEY = 61 -DELKEY = 62 -SEMICOLONKEY = 43 -PERIODKEY = 52 -COMMAKEY = 45 -QUOTEKEY = 50 -ACCENTGRAVEKEY = 55 -MINUSKEY = 47 -VIRGULEKEY = 53 -BACKSLASHKEY = 57 -EQUALKEY = 54 -LEFTBRACKETKEY = 49 -RIGHTBRACKETKEY = 56 -LEFTARROWKEY = 73 -DOWNARROWKEY = 74 -RIGHTARROWKEY = 80 -UPARROWKEY = 81 -PAD0 = 59 -PAD1 = 58 -PAD2 = 64 -PAD3 = 65 -PAD4 = 63 -PAD5 = 69 -PAD6 = 70 -PAD7 = 67 -PAD8 = 68 -PAD9 = 75 -PADPF1 = 72 -PADPF2 = 71 -PADPF3 = 79 -PADPF4 = 78 -PADPERIOD = 66 -PADMINUS = 76 -PADCOMMA = 77 -PADENTER = 82 -LEFTALTKEY = 143 -RIGHTALTKEY = 144 -RIGHTCTRLKEY = 145 -F1KEY = 146 -F2KEY = 147 -F3KEY = 148 -F4KEY = 149 -F5KEY = 150 -F6KEY = 151 -F7KEY = 152 -F8KEY = 153 -F9KEY = 154 -F10KEY = 155 -F11KEY = 156 -F12KEY = 157 -PRINTSCREENKEY = 158 -SCROLLLOCKKEY = 159 -PAUSEKEY = 160 -INSERTKEY = 161 -HOMEKEY = 162 -PAGEUPKEY = 163 -ENDKEY = 164 -PAGEDOWNKEY = 165 -NUMLOCKKEY = 166 -PADVIRGULEKEY = 167 -PADASTERKEY = 168 -PADPLUSKEY = 169 -SGIRESERVED = 256 -DIAL0 = 257 -DIAL1 = 258 -DIAL2 = 259 -DIAL3 = 260 -DIAL4 = 261 -DIAL5 = 262 -DIAL6 = 263 -DIAL7 = 264 -DIAL8 = 265 -MOUSEX = 266 -MOUSEY = 267 -LPENX = 268 -LPENY = 269 -BPADX = 270 -BPADY = 271 -CURSORX = 272 -CURSORY = 273 -GHOSTX = 274 -GHOSTY = 275 -SBTX = 276 -SBTY = 277 -SBTZ = 278 -SBRX = 279 -SBRY = 280 -SBRZ = 281 -SBPERIOD = 282 -TIMER0 = 515 -TIMER1 = 516 -TIMER2 = 517 -TIMER3 = 518 -KEYBD = 513 -RAWKEYBD = 514 -VALMARK = 523 -REDRAW = 528 -INPUTCHANGE = 534 -QFULL = 535 -QREADERROR = 538 -WINFREEZE = 539 -WINTHAW = 540 -REDRAWICONIC = 541 -WINQUIT = 542 -DEPTHCHANGE = 543 -WINSHUT = 546 -DRAWOVERLAY = 547 -VIDEO = 548 -MENUBUTTON = RIGHTMOUSE -WINCLOSE = 537 -KEYBDFNAMES = 544 -KEYBDFSTRINGS = 545 -MAXSGIDEVICE = 20000 -GERROR = 524 -WMSEND = 529 -WMREPLY = 530 -WMGFCLOSE = 531 -WMTXCLOSE = 532 -MODECHANGE = 533 -PIECECHANGE = 536 diff --git a/Lib/irix5/ERRNO.py b/Lib/irix5/ERRNO.py deleted file mode 100755 index d49e9641e4..0000000000 --- a/Lib/irix5/ERRNO.py +++ /dev/null @@ -1,147 +0,0 @@ -# Generated by h2py from /usr/include/errno.h - -# Included from sys/errno.h -__KBASE = 1000 -__IRIXBASE = 1000 -EPERM = 1 -ENOENT = 2 -ESRCH = 3 -EINTR = 4 -EIO = 5 -ENXIO = 6 -E2BIG = 7 -ENOEXEC = 8 -EBADF = 9 -ECHILD = 10 -EAGAIN = 11 -ENOMEM = 12 -EACCES = 13 -EFAULT = 14 -ENOTBLK = 15 -EBUSY = 16 -EEXIST = 17 -EXDEV = 18 -ENODEV = 19 -ENOTDIR = 20 -EISDIR = 21 -EINVAL = 22 -ENFILE = 23 -EMFILE = 24 -ENOTTY = 25 -ETXTBSY = 26 -EFBIG = 27 -ENOSPC = 28 -ESPIPE = 29 -EROFS = 30 -EMLINK = 31 -EPIPE = 32 -EDOM = 33 -ERANGE = 34 -ENOMSG = 35 -EIDRM = 36 -ECHRNG = 37 -EL2NSYNC = 38 -EL3HLT = 39 -EL3RST = 40 -ELNRNG = 41 -EUNATCH = 42 -ENOCSI = 43 -EL2HLT = 44 -EDEADLK = 45 -ENOLCK = 46 -EBADE = 50 -EBADR = 51 -EXFULL = 52 -ENOANO = 53 -EBADRQC = 54 -EBADSLT = 55 -EDEADLOCK = 56 -EBFONT = 57 -ENOSTR = 60 -ENODATA = 61 -ETIME = 62 -ENOSR = 63 -ENONET = 64 -ENOPKG = 65 -EREMOTE = 66 -ENOLINK = 67 -EADV = 68 -ESRMNT = 69 -ECOMM = 70 -EPROTO = 71 -EMULTIHOP = 74 -EBADMSG = 77 -ENAMETOOLONG = 78 -EOVERFLOW = 79 -ENOTUNIQ = 80 -EBADFD = 81 -EREMCHG = 82 -ELIBACC = 83 -ELIBBAD = 84 -ELIBSCN = 85 -ELIBMAX = 86 -ELIBEXEC = 87 -EILSEQ = 88 -ENOSYS = 89 -ELOOP = 90 -ERESTART = 91 -ESTRPIPE = 92 -ENOTEMPTY = 93 -EUSERS = 94 -ENOTSOCK = 95 -EDESTADDRREQ = 96 -EMSGSIZE = 97 -EPROTOTYPE = 98 -ENOPROTOOPT = 99 -EPROTONOSUPPORT = 120 -ESOCKTNOSUPPORT = 121 -EOPNOTSUPP = 122 -EPFNOSUPPORT = 123 -EAFNOSUPPORT = 124 -EADDRINUSE = 125 -EADDRNOTAVAIL = 126 -ENETDOWN = 127 -ENETUNREACH = 128 -ENETRESET = 129 -ECONNABORTED = 130 -ECONNRESET = 131 -ENOBUFS = 132 -EISCONN = 133 -ENOTCONN = 134 -ESHUTDOWN = 143 -ETOOMANYREFS = 144 -ETIMEDOUT = 145 -ECONNREFUSED = 146 -EHOSTDOWN = 147 -EHOSTUNREACH = 148 -EWOULDBLOCK = __KBASE+101 -EWOULDBLOCK = EAGAIN -EALREADY = 149 -EINPROGRESS = 150 -ESTALE = 151 -EIORESID = 500 -EUCLEAN = 135 -ENOTNAM = 137 -ENAVAIL = 138 -EISNAM = 139 -EREMOTEIO = 140 -EINIT = 141 -EREMDEV = 142 -ECANCELED = 158 -ECANCELED = 1000 -EDQUOT = 1133 -ENFSREMOTE = 1135 -ETCP_EBASE = 100 -ETCP_ELIMIT = 129 -ENAMI_EBASE = 129 -ENAMI_ELIMIT = 131 -ENFS_EBASE = 131 -ENFS_ELIMIT = 135 -ELASTERRNO = 135 -TCP_EBASE = ETCP_EBASE -TCP_ELIMIT = ETCP_ELIMIT -NAMI_EBASE = ENAMI_EBASE -NAMI_ELIMIT = ENAMI_ELIMIT -NFS_EBASE = ENFS_EBASE -NFS_ELIMIT = ENFS_ELIMIT -LASTERRNO = ELASTERRNO diff --git a/Lib/irix5/FCNTL.py b/Lib/irix5/FCNTL.py deleted file mode 100755 index 12c60fab25..0000000000 --- a/Lib/irix5/FCNTL.py +++ /dev/null @@ -1,53 +0,0 @@ -# Generated by h2py from /usr/include/sys/fcntl.h -FNDELAY = 0x04 -FAPPEND = 0x08 -FSYNC = 0x10 -FNONBLOCK = 0x80 -FASYNC = 0x1000 -FNONBLK = FNONBLOCK -FDIRECT = 0x8000 -FCREAT = 0x0100 -FTRUNC = 0x0200 -FEXCL = 0x0400 -FNOCTTY = 0x0800 -O_RDONLY = 0 -O_WRONLY = 1 -O_RDWR = 2 -O_NDELAY = 0x04 -O_APPEND = 0x08 -O_SYNC = 0x10 -O_NONBLOCK = 0x80 -O_DIRECT = 0x8000 -O_CREAT = 0x100 -O_TRUNC = 0x200 -O_EXCL = 0x400 -O_NOCTTY = 0x800 -F_DUPFD = 0 -F_GETFD = 1 -F_SETFD = 2 -F_GETFL = 3 -F_SETFL = 4 -F_GETLK = 14 -F_O_GETLK = 5 -F_GETLK = 14 -F_SETLK = 6 -F_SETLKW = 7 -F_CHKFL = 8 -F_ALLOCSP = 10 -F_FREESP = 11 -F_SETBSDLK = 12 -F_SETBSDLKW = 13 -F_DIOINFO = 30 -F_RSETLK = 20 -F_RGETLK = 21 -F_RSETLKW = 22 -F_GETOWN = 23 -F_SETOWN = 24 -F_O_GETOWN = 10 -F_O_SETOWN = 11 -F_RDLCK = 01 -F_WRLCK = 02 -F_UNLCK = 03 -O_ACCMODE = 3 -FD_CLOEXEC = 1 -FD_NODUP_FORK = 4 diff --git a/Lib/irix5/FL.py b/Lib/irix5/FL.py deleted file mode 100755 index f85237b85f..0000000000 --- a/Lib/irix5/FL.py +++ /dev/null @@ -1,289 +0,0 @@ -# Constants used by the FORMS library (module fl). -# This corresponds to "forms.h". -# Recommended use: import FL; ... FL.NORMAL_BOX ... etc. -# Alternate use: from FL import *; ... NORMAL_BOX ... etc. - -_v20 = 1 -_v21 = 1 -##import fl -##try: -## _v20 = (fl.get_rgbmode <> None) -##except: -## _v20 = 0 -##del fl - -NULL = 0 -FALSE = 0 -TRUE = 1 - -EVENT = -1 - -LABEL_SIZE = 64 -if _v20: - SHORTCUT_SIZE = 32 -PLACE_FREE = 0 -PLACE_SIZE = 1 -PLACE_ASPECT = 2 -PLACE_MOUSE = 3 -PLACE_CENTER = 4 -PLACE_POSITION = 5 -FL_PLACE_FULLSCREEN = 6 -FIND_INPUT = 0 -FIND_AUTOMATIC = 1 -FIND_MOUSE = 2 -BEGIN_GROUP = 10000 -END_GROUP = 20000 -ALIGN_TOP = 0 -ALIGN_BOTTOM = 1 -ALIGN_LEFT = 2 -ALIGN_RIGHT = 3 -ALIGN_CENTER = 4 -NO_BOX = 0 -UP_BOX = 1 -DOWN_BOX = 2 -FLAT_BOX = 3 -BORDER_BOX = 4 -SHADOW_BOX = 5 -FRAME_BOX = 6 -ROUNDED_BOX = 7 -RFLAT_BOX = 8 -RSHADOW_BOX = 9 -TOP_BOUND_COL = 51 -LEFT_BOUND_COL = 55 -BOT_BOUND_COL = 40 -RIGHT_BOUND_COL = 35 -COL1 = 47 -MCOL = 49 -LCOL = 0 -BOUND_WIDTH = 3.0 -DRAW = 0 -PUSH = 1 -RELEASE = 2 -ENTER = 3 -LEAVE = 4 -MOUSE = 5 -FOCUS = 6 -UNFOCUS = 7 -KEYBOARD = 8 -STEP = 9 -MOVE = 10 -FONT_NAME = 'Helvetica' -FONT_BOLDNAME = 'Helvetica-Bold' -FONT_ITALICNAME = 'Helvetica-Oblique' -FONT_FIXEDNAME = 'Courier' -FONT_ICONNAME = 'Icon' -SMALL_FONT = 8.0 -NORMAL_FONT = 11.0 -LARGE_FONT = 20.0 -NORMAL_STYLE = 0 -BOLD_STYLE = 1 -ITALIC_STYLE = 2 -FIXED_STYLE = 3 -ENGRAVED_STYLE = 4 -ICON_STYLE = 5 -BITMAP = 3 -NORMAL_BITMAP = 0 -BITMAP_BOXTYPE = NO_BOX -BITMAP_COL1 = 0 -BITMAP_COL2 = COL1 -BITMAP_LCOL = LCOL -BITMAP_ALIGN = ALIGN_BOTTOM -BITMAP_MAXSIZE = 128*128 -BITMAP_BW = BOUND_WIDTH -BOX = 1 -BOX_BOXTYPE = UP_BOX -BOX_COL1 = COL1 -BOX_LCOL = LCOL -BOX_ALIGN = ALIGN_CENTER -BOX_BW = BOUND_WIDTH -BROWSER = 71 -NORMAL_BROWSER = 0 -SELECT_BROWSER = 1 -HOLD_BROWSER = 2 -MULTI_BROWSER = 3 -BROWSER_BOXTYPE = DOWN_BOX -BROWSER_COL1 = COL1 -BROWSER_COL2 = 3 -BROWSER_LCOL = LCOL -BROWSER_ALIGN = ALIGN_BOTTOM -BROWSER_SLCOL = COL1 -BROWSER_BW = BOUND_WIDTH -BROWSER_LINELENGTH = 128 -BROWSER_MAXLINE = 512 -BUTTON = 11 -NORMAL_BUTTON = 0 -PUSH_BUTTON = 1 -RADIO_BUTTON = 2 -HIDDEN_BUTTON = 3 -TOUCH_BUTTON = 4 -INOUT_BUTTON = 5 -RETURN_BUTTON = 6 -if _v20: - HIDDEN_RET_BUTTON = 7 -BUTTON_BOXTYPE = UP_BOX -BUTTON_COL1 = COL1 -BUTTON_COL2 = COL1 -BUTTON_LCOL = LCOL -BUTTON_ALIGN = ALIGN_CENTER -BUTTON_MCOL1 = MCOL -BUTTON_MCOL2 = MCOL -BUTTON_BW = BOUND_WIDTH -if _v20: - CHART = 4 - BAR_CHART = 0 - HORBAR_CHART = 1 - LINE_CHART = 2 - FILLED_CHART = 3 - SPIKE_CHART = 4 - PIE_CHART = 5 - SPECIALPIE_CHART = 6 - CHART_BOXTYPE = BORDER_BOX - CHART_COL1 = COL1 - CHART_LCOL = LCOL - CHART_ALIGN = ALIGN_BOTTOM - CHART_BW = BOUND_WIDTH - CHART_MAX = 128 -CHOICE = 42 -NORMAL_CHOICE = 0 -CHOICE_BOXTYPE = DOWN_BOX -CHOICE_COL1 = COL1 -CHOICE_COL2 = LCOL -CHOICE_LCOL = LCOL -CHOICE_ALIGN = ALIGN_LEFT -CHOICE_BW = BOUND_WIDTH -CHOICE_MCOL = MCOL -CHOICE_MAXITEMS = 128 -CHOICE_MAXSTR = 64 -CLOCK = 61 -SQUARE_CLOCK = 0 -ROUND_CLOCK = 1 -CLOCK_BOXTYPE = UP_BOX -CLOCK_COL1 = 37 -CLOCK_COL2 = 42 -CLOCK_LCOL = LCOL -CLOCK_ALIGN = ALIGN_BOTTOM -CLOCK_TOPCOL = COL1 -CLOCK_BW = BOUND_WIDTH -COUNTER = 25 -NORMAL_COUNTER = 0 -SIMPLE_COUNTER = 1 -COUNTER_BOXTYPE = UP_BOX -COUNTER_COL1 = COL1 -COUNTER_COL2 = 4 -COUNTER_LCOL = LCOL -COUNTER_ALIGN = ALIGN_BOTTOM -if _v20: - COUNTER_BW = BOUND_WIDTH -else: - DEFAULT = 51 - RETURN_DEFAULT = 0 - ALWAYS_DEFAULT = 1 -DIAL = 22 -NORMAL_DIAL = 0 -LINE_DIAL = 1 -DIAL_BOXTYPE = NO_BOX -DIAL_COL1 = COL1 -DIAL_COL2 = 37 -DIAL_LCOL = LCOL -DIAL_ALIGN = ALIGN_BOTTOM -DIAL_TOPCOL = COL1 -DIAL_BW = BOUND_WIDTH -FREE = 101 -NORMAL_FREE = 1 -SLEEPING_FREE = 2 -INPUT_FREE = 3 -CONTINUOUS_FREE = 4 -ALL_FREE = 5 -INPUT = 31 -NORMAL_INPUT = 0 -if _v20: - FLOAT_INPUT = 1 - INT_INPUT = 2 - HIDDEN_INPUT = 3 - if _v21: - MULTILINE_INPUT = 4 - SECRET_INPUT = 5 -else: - ALWAYS_INPUT = 1 -INPUT_BOXTYPE = DOWN_BOX -INPUT_COL1 = 13 -INPUT_COL2 = 5 -INPUT_LCOL = LCOL -INPUT_ALIGN = ALIGN_LEFT -INPUT_TCOL = LCOL -INPUT_CCOL = 4 -INPUT_BW = BOUND_WIDTH -INPUT_MAX = 128 -LIGHTBUTTON = 12 -LIGHTBUTTON_BOXTYPE = UP_BOX -LIGHTBUTTON_COL1 = 39 -LIGHTBUTTON_COL2 = 3 -LIGHTBUTTON_LCOL = LCOL -LIGHTBUTTON_ALIGN = ALIGN_CENTER -LIGHTBUTTON_TOPCOL = COL1 -LIGHTBUTTON_MCOL = MCOL -LIGHTBUTTON_BW1 = BOUND_WIDTH -LIGHTBUTTON_BW2 = BOUND_WIDTH/2.0 -LIGHTBUTTON_MINSIZE = 12.0 -MENU = 41 -TOUCH_MENU = 0 -PUSH_MENU = 1 -MENU_BOXTYPE = BORDER_BOX -MENU_COL1 = 55 -MENU_COL2 = 37 -MENU_LCOL = LCOL -MENU_ALIGN = ALIGN_CENTER -MENU_BW = BOUND_WIDTH -MENU_MAX = 300 -POSITIONER = 23 -NORMAL_POSITIONER = 0 -POSITIONER_BOXTYPE = DOWN_BOX -POSITIONER_COL1 = COL1 -POSITIONER_COL2 = 1 -POSITIONER_LCOL = LCOL -POSITIONER_ALIGN = ALIGN_BOTTOM -POSITIONER_BW = BOUND_WIDTH -ROUNDBUTTON = 13 -ROUNDBUTTON_BOXTYPE = NO_BOX -ROUNDBUTTON_COL1 = 7 -ROUNDBUTTON_COL2 = 3 -ROUNDBUTTON_LCOL = LCOL -ROUNDBUTTON_ALIGN = ALIGN_CENTER -ROUNDBUTTON_TOPCOL = COL1 -ROUNDBUTTON_MCOL = MCOL -ROUNDBUTTON_BW = BOUND_WIDTH -SLIDER = 21 -VALSLIDER = 24 -VERT_SLIDER = 0 -HOR_SLIDER = 1 -VERT_FILL_SLIDER = 2 -HOR_FILL_SLIDER = 3 -VERT_NICE_SLIDER = 4 -HOR_NICE_SLIDER = 5 -SLIDER_BOXTYPE = DOWN_BOX -SLIDER_COL1 = COL1 -SLIDER_COL2 = COL1 -SLIDER_LCOL = LCOL -SLIDER_ALIGN = ALIGN_BOTTOM -SLIDER_BW1 = BOUND_WIDTH -SLIDER_BW2 = BOUND_WIDTH*0.75 -SLIDER_FINE = 0.05 -SLIDER_WIDTH = 0.08 -TEXT = 2 -NORMAL_TEXT = 0 -TEXT_BOXTYPE = NO_BOX -TEXT_COL1 = COL1 -TEXT_LCOL = LCOL -TEXT_ALIGN = ALIGN_LEFT -TEXT_BW = BOUND_WIDTH -TIMER = 62 -NORMAL_TIMER = 0 -VALUE_TIMER = 1 -HIDDEN_TIMER = 2 -TIMER_BOXTYPE = DOWN_BOX -TIMER_COL1 = COL1 -TIMER_COL2 = 1 -TIMER_LCOL = LCOL -TIMER_ALIGN = ALIGN_CENTER -TIMER_BW = BOUND_WIDTH -TIMER_BLINKRATE = 0.2 diff --git a/Lib/irix5/GET.py b/Lib/irix5/GET.py deleted file mode 100755 index 9c3d7d6952..0000000000 --- a/Lib/irix5/GET.py +++ /dev/null @@ -1,59 +0,0 @@ -# Symbols from <gl/get.h> - -BCKBUFFER = 0x1 -FRNTBUFFER = 0x2 -DRAWZBUFFER = 0x4 -DMRGB = 0 -DMSINGLE = 1 -DMDOUBLE = 2 -DMRGBDOUBLE = 5 -HZ30 = 0 -HZ60 = 1 -NTSC = 2 -HDTV = 3 -VGA = 4 -IRIS3K = 5 -PR60 = 6 -PAL = 9 -HZ30_SG = 11 -A343 = 14 -STR_RECT = 15 -VOF0 = 16 -VOF1 = 17 -VOF2 = 18 -VOF3 = 19 -SGI0 = 20 -SGI1 = 21 -SGI2 = 22 -HZ72 = 23 -GL_VIDEO_REG = 0x00800000 -GLV_GENLOCK = 0x00000001 -GLV_UNBLANK = 0x00000002 -GLV_SRED = 0x00000004 -GLV_SGREEN = 0x00000008 -GLV_SBLUE = 0x00000010 -GLV_SALPHA = 0x00000020 -GLV_TTLGENLOCK = 0x00000080 -GLV_TTLSYNC = GLV_TTLGENLOCK -GLV_GREENGENLOCK = 0x0000100 -LEFTPLANE = 0x0001 -RIGHTPLANE = 0x0002 -BOTTOMPLANE = 0x0004 -TOPPLANE = 0x0008 -NEARPLANE = 0x0010 -FARPLANE = 0x0020 -## GETDEF = __GL_GET_H__ -NOBUFFER = 0x0 -BOTHBUFFERS = 0x3 -DMINTENSITYSINGLE = 3 -DMINTENSITYDOUBLE = 4 -MONSPECIAL = 0x20 -HZ50 = 3 -MONA = 5 -MONB = 6 -MONC = 7 -MOND = 8 -MON_ALL = 12 -MON_GEN_ALL = 13 -CMAPMULTI = 0 -CMAPONE = 1 diff --git a/Lib/irix5/GL.py b/Lib/irix5/GL.py deleted file mode 100755 index 9f02f65f3a..0000000000 --- a/Lib/irix5/GL.py +++ /dev/null @@ -1,393 +0,0 @@ -NULL = 0 -FALSE = 0 -TRUE = 1 -ATTRIBSTACKDEPTH = 10 -VPSTACKDEPTH = 8 -MATRIXSTACKDEPTH = 32 -NAMESTACKDEPTH = 1025 -STARTTAG = -2 -ENDTAG = -3 -BLACK = 0 -RED = 1 -GREEN = 2 -YELLOW = 3 -BLUE = 4 -MAGENTA = 5 -CYAN = 6 -WHITE = 7 -PUP_CLEAR = 0 -PUP_COLOR = 1 -PUP_BLACK = 2 -PUP_WHITE = 3 -NORMALDRAW = 0x010 -PUPDRAW = 0x020 -OVERDRAW = 0x040 -UNDERDRAW = 0x080 -CURSORDRAW = 0x100 -DUALDRAW = 0x200 -PATTERN_16 = 16 -PATTERN_32 = 32 -PATTERN_64 = 64 -PATTERN_16_SIZE = 16 -PATTERN_32_SIZE = 64 -PATTERN_64_SIZE = 256 -SRC_AUTO = 0 -SRC_FRONT = 1 -SRC_BACK = 2 -SRC_ZBUFFER = 3 -SRC_PUP = 4 -SRC_OVER = 5 -SRC_UNDER = 6 -SRC_FRAMEGRABBER = 7 -BF_ZERO = 0 -BF_ONE = 1 -BF_DC = 2 -BF_SC = 2 -BF_MDC = 3 -BF_MSC = 3 -BF_SA = 4 -BF_MSA = 5 -BF_DA = 6 -BF_MDA = 7 -BF_MIN_SA_MDA = 8 -AF_NEVER = 0 -AF_LESS = 1 -AF_EQUAL = 2 -AF_LEQUAL = 3 -AF_GREATER = 4 -AF_NOTEQUAL = 5 -AF_GEQUAL = 6 -AF_ALWAYS = 7 -ZF_NEVER = 0 -ZF_LESS = 1 -ZF_EQUAL = 2 -ZF_LEQUAL = 3 -ZF_GREATER = 4 -ZF_NOTEQUAL = 5 -ZF_GEQUAL = 6 -ZF_ALWAYS = 7 -ZSRC_DEPTH = 0 -ZSRC_COLOR = 1 -SMP_OFF = 0x0 -SMP_ON = 0x1 -SMP_SMOOTHER = 0x2 -SML_OFF = 0x0 -SML_ON = 0x1 -SML_SMOOTHER = 0x2 -SML_END_CORRECT = 0x4 -PYSM_OFF = 0 -PYSM_ON = 1 -PYSM_SHRINK = 2 -DT_OFF = 0 -DT_ON = 1 -PUP_NONE = 0 -PUP_GREY = 0x1 -PUP_BOX = 0x2 -PUP_CHECK = 0x4 -GLC_OLDPOLYGON = 0 -GLC_ZRANGEMAP = 1 -GLC_MQUEUERATE = 2 -GLC_SOFTATTACH = 3 -GLC_MANAGEBG = 4 -GLC_SLOWMAPCOLORS = 5 -GLC_INPUTCHANGEBUG = 6 -GLC_NOBORDERBUG = 7 -GLC_SET_VSYNC = 8 -GLC_GET_VSYNC = 9 -GLC_VSYNC_SLEEP = 10 -GLC_COMPATRATE = 15 -C16X1 = 0 -C16X2 = 1 -C32X1 = 2 -C32X2 = 3 -CCROSS = 4 -FLAT = 0 -GOURAUD = 1 -LO_ZERO = 0x0 -LO_AND = 0x1 -LO_ANDR = 0x2 -LO_SRC = 0x3 -LO_ANDI = 0x4 -LO_DST = 0x5 -LO_XOR = 0x6 -LO_OR = 0x7 -LO_NOR = 0x8 -LO_XNOR = 0x9 -LO_NDST = 0xa -LO_ORR = 0xb -LO_NSRC = 0xc -LO_ORI = 0xd -LO_NAND = 0xe -LO_ONE = 0xf -INFOCUSSCRN = -2 -ST_KEEP = 0 -ST_ZERO = 1 -ST_REPLACE = 2 -ST_INCR = 3 -ST_DECR = 4 -ST_INVERT = 5 -SF_NEVER = 0 -SF_LESS = 1 -SF_EQUAL = 2 -SF_LEQUAL = 3 -SF_GREATER = 4 -SF_NOTEQUAL = 5 -SF_GEQUAL = 6 -SF_ALWAYS = 7 -SS_OFF = 0 -SS_DEPTH = 1 -PYM_FILL = 1 -PYM_POINT = 2 -PYM_LINE = 3 -PYM_HOLLOW = 4 -PYM_LINE_FAST = 5 -FG_OFF = 0 -FG_ON = 1 -FG_DEFINE = 2 -FG_VTX_EXP = 2 -FG_VTX_LIN = 3 -FG_PIX_EXP = 4 -FG_PIX_LIN = 5 -FG_VTX_EXP2 = 6 -FG_PIX_EXP2 = 7 -PM_SHIFT = 0 -PM_EXPAND = 1 -PM_C0 = 2 -PM_C1 = 3 -PM_ADD24 = 4 -PM_SIZE = 5 -PM_OFFSET = 6 -PM_STRIDE = 7 -PM_TTOB = 8 -PM_RTOL = 9 -PM_ZDATA = 10 -PM_WARP = 11 -PM_RDX = 12 -PM_RDY = 13 -PM_CDX = 14 -PM_CDY = 15 -PM_XSTART = 16 -PM_YSTART = 17 -PM_VO1 = 1000 -NAUTO = 0 -NNORMALIZE = 1 -AC_CLEAR = 0 -AC_ACCUMULATE = 1 -AC_CLEAR_ACCUMULATE = 2 -AC_RETURN = 3 -AC_MULT = 4 -AC_ADD = 5 -CP_OFF = 0 -CP_ON = 1 -CP_DEFINE = 2 -SB_RESET = 0 -SB_TRACK = 1 -SB_HOLD = 2 -RD_FREEZE = 0x00000001 -RD_ALPHAONE = 0x00000002 -RD_IGNORE_UNDERLAY = 0x00000004 -RD_IGNORE_OVERLAY = 0x00000008 -RD_IGNORE_PUP = 0x00000010 -RD_OFFSCREEN = 0x00000020 -GD_XPMAX = 0 -GD_YPMAX = 1 -GD_XMMAX = 2 -GD_YMMAX = 3 -GD_ZMIN = 4 -GD_ZMAX = 5 -GD_BITS_NORM_SNG_RED = 6 -GD_BITS_NORM_SNG_GREEN = 7 -GD_BITS_NORM_SNG_BLUE = 8 -GD_BITS_NORM_DBL_RED = 9 -GD_BITS_NORM_DBL_GREEN = 10 -GD_BITS_NORM_DBL_BLUE = 11 -GD_BITS_NORM_SNG_CMODE = 12 -GD_BITS_NORM_DBL_CMODE = 13 -GD_BITS_NORM_SNG_MMAP = 14 -GD_BITS_NORM_DBL_MMAP = 15 -GD_BITS_NORM_ZBUFFER = 16 -GD_BITS_OVER_SNG_CMODE = 17 -GD_BITS_UNDR_SNG_CMODE = 18 -GD_BITS_PUP_SNG_CMODE = 19 -GD_BITS_NORM_SNG_ALPHA = 21 -GD_BITS_NORM_DBL_ALPHA = 22 -GD_BITS_CURSOR = 23 -GD_OVERUNDER_SHARED = 24 -GD_BLEND = 25 -GD_CIFRACT = 26 -GD_CROSSHAIR_CINDEX = 27 -GD_DITHER = 28 -GD_LINESMOOTH_CMODE = 30 -GD_LINESMOOTH_RGB = 31 -GD_LOGICOP = 33 -GD_NSCRNS = 35 -GD_NURBS_ORDER = 36 -GD_NBLINKS = 37 -GD_NVERTEX_POLY = 39 -GD_PATSIZE_64 = 40 -GD_PNTSMOOTH_CMODE = 41 -GD_PNTSMOOTH_RGB = 42 -GD_PUP_TO_OVERUNDER = 43 -GD_READSOURCE = 44 -GD_READSOURCE_ZBUFFER = 48 -GD_STEREO = 50 -GD_SUBPIXEL_LINE = 51 -GD_SUBPIXEL_PNT = 52 -GD_SUBPIXEL_POLY = 53 -GD_TRIMCURVE_ORDER = 54 -GD_WSYS = 55 -GD_ZDRAW_GEOM = 57 -GD_ZDRAW_PIXELS = 58 -GD_SCRNTYPE = 61 -GD_TEXTPORT = 62 -GD_NMMAPS = 63 -GD_FRAMEGRABBER = 64 -GD_TIMERHZ = 66 -GD_DBBOX = 67 -GD_AFUNCTION = 68 -GD_ALPHA_OVERUNDER = 69 -GD_BITS_ACBUF = 70 -GD_BITS_ACBUF_HW = 71 -GD_BITS_STENCIL = 72 -GD_CLIPPLANES = 73 -GD_FOGVERTEX = 74 -GD_LIGHTING_TWOSIDE = 76 -GD_POLYMODE = 77 -GD_POLYSMOOTH = 78 -GD_SCRBOX = 79 -GD_TEXTURE = 80 -GD_FOGPIXEL = 81 -GD_TEXTURE_PERSP = 82 -GD_MUXPIPES = 83 -GD_NOLIMIT = -2 -GD_WSYS_NONE = 0 -GD_WSYS_4S = 1 -GD_SCRNTYPE_WM = 0 -GD_SCRNTYPE_NOWM = 1 -N_PIXEL_TOLERANCE = 1 -N_CULLING = 2 -N_DISPLAY = 3 -N_ERRORCHECKING = 4 -N_SUBDIVISIONS = 5 -N_S_STEPS = 6 -N_T_STEPS = 7 -N_TILES = 8 -N_TMP1 = 9 -N_TMP2 = 10 -N_TMP3 = 11 -N_TMP4 = 12 -N_TMP5 = 13 -N_TMP6 = 14 -N_FILL = 1.0 -N_OUTLINE_POLY = 2.0 -N_OUTLINE_PATCH = 5.0 -N_ISOLINE_S = 12.0 -N_ST = 0x8 -N_STW = 0xd -N_XYZ = 0x4c -N_XYZW = 0x51 -N_TEX = 0x88 -N_TEXW = 0x8d -N_RGBA = 0xd0 -N_RGBAW = 0xd5 -N_P2D = 0x8 -N_P2DR = 0xd -N_V3D = 0x4c -N_V3DR = 0x51 -N_T2D = 0x88 -N_T2DR = 0x8d -N_C4D = 0xd0 -N_C4DR = 0xd5 -LMNULL = 0.0 -MSINGLE = 0 -MPROJECTION = 1 -MVIEWING = 2 -MTEXTURE = 3 -MAXLIGHTS = 8 -MAXRESTRICTIONS = 4 -DEFMATERIAL = 0 -EMISSION = 1 -AMBIENT = 2 -DIFFUSE = 3 -SPECULAR = 4 -SHININESS = 5 -COLORINDEXES = 6 -ALPHA = 7 -DEFLIGHT = 100 -LCOLOR = 101 -POSITION = 102 -SPOTDIRECTION = 103 -SPOTLIGHT = 104 -DEFLMODEL = 200 -LOCALVIEWER = 201 -ATTENUATION = 202 -ATTENUATION2 = 203 -TWOSIDE = 204 -MATERIAL = 1000 -BACKMATERIAL = 1001 -LIGHT0 = 1100 -LIGHT1 = 1101 -LIGHT2 = 1102 -LIGHT3 = 1103 -LIGHT4 = 1104 -LIGHT5 = 1105 -LIGHT6 = 1106 -LIGHT7 = 1107 -LMODEL = 1200 -LMC_COLOR = 0 -LMC_EMISSION = 1 -LMC_AMBIENT = 2 -LMC_DIFFUSE = 3 -LMC_SPECULAR = 4 -LMC_AD = 5 -LMC_NULL = 6 -TX_MINFILTER = 0x100 -TX_MAGFILTER = 0x200 -TX_WRAP = 0x300 -TX_WRAP_S = 0x310 -TX_WRAP_T = 0x320 -TX_TILE = 0x400 -TX_BORDER = 0x500 -TX_NULL = 0x000 -TX_POINT = 0x110 -TX_BILINEAR = 0x220 -TX_MIPMAP = 0x120 -TX_MIPMAP_POINT = 0x121 -TX_MIPMAP_LINEAR = 0x122 -TX_MIPMAP_BILINEAR = 0x123 -TX_MIPMAP_TRILINEAR = 0x124 -TX_REPEAT = 0x301 -TX_CLAMP = 0x302 -TX_SELECT = 0x303 -TX_TEXTURE_0 = 0 -TV_MODULATE = 0x101 -TV_BLEND = 0x102 -TV_DECAL = 0x103 -TV_COLOR = 0x200 -TV_NULL = 0x000 -TV_ENV0 = 0 -TX_S = 0 -TX_T = 1 -TG_OFF = 0 -TG_ON = 1 -TG_CONTOUR = 2 -TG_LINEAR = 3 -TG_SPHEREMAP = 4 -TG_REFRACTMAP = 5 -DGLSINK = 0 -DGLLOCAL = 1 -DGLTSOCKET = 2 -DGL4DDN = 3 -PUP_CURSOR = PUP_COLOR -FATAL = 1 -WARNING = 2 -ASK_CONT = 3 -ASK_RESTART = 4 -XMAXSCREEN = 1279 -YMAXSCREEN = 1023 -XMAXMEDIUM = 1023 -YMAXMEDIUM = 767 -XMAX170 = 645 -YMAX170 = 484 -XMAXPAL = 779 -YMAXPAL = 574 diff --git a/Lib/irix5/GLWS.py b/Lib/irix5/GLWS.py deleted file mode 100755 index 69dab7143f..0000000000 --- a/Lib/irix5/GLWS.py +++ /dev/null @@ -1,12 +0,0 @@ -NOERROR = 0 -NOCONTEXT = -1 -NODISPLAY = -2 -NOWINDOW = -3 -NOGRAPHICS = -4 -NOTTOP = -5 -NOVISUAL = -6 -BUFSIZE = -7 -BADWINDOW = -8 -ALREADYBOUND = -100 -BINDFAILED = -101 -SETFAILED = -102 diff --git a/Lib/irix5/IN.py b/Lib/irix5/IN.py deleted file mode 100755 index 325a0217f7..0000000000 --- a/Lib/irix5/IN.py +++ /dev/null @@ -1,83 +0,0 @@ -# Generated by h2py from /usr/include/netinet/in.h -IPPROTO_IP = 0 -IPPROTO_ICMP = 1 -IPPROTO_IGMP = 2 -IPPROTO_GGP = 3 -IPPROTO_TCP = 6 -IPPROTO_EGP = 8 -IPPROTO_PUP = 12 -IPPROTO_UDP = 17 -IPPROTO_IDP = 22 -IPPROTO_TP = 29 -IPPROTO_XTP = 36 -IPPROTO_HELLO = 63 -IPPROTO_ND = 77 -IPPROTO_EON = 80 -IPPROTO_RAW = 255 -IPPROTO_MAX = 256 -IPPORT_RESERVED = 1024 -IPPORT_USERRESERVED = 5000 -IN_CLASSA_NET = 0xff000000 -IN_CLASSA_NSHIFT = 24 -IN_CLASSA_HOST = 0x00ffffff -IN_CLASSA_MAX = 128 -IN_CLASSB_NET = 0xffff0000 -IN_CLASSB_NSHIFT = 16 -IN_CLASSB_HOST = 0x0000ffff -IN_CLASSB_MAX = 65536 -IN_CLASSC_NET = 0xffffff00 -IN_CLASSC_NSHIFT = 8 -IN_CLASSC_HOST = 0x000000ff -IN_CLASSD_NET = 0xf0000000 -IN_CLASSD_NSHIFT = 28 -IN_CLASSD_HOST = 0x0fffffff -INADDR_ANY = 0x00000000 -INADDR_BROADCAST = 0xffffffff -INADDR_LOOPBACK = 0x7F000001 -INADDR_UNSPEC_GROUP = 0xe0000000 -INADDR_ALLHOSTS_GROUP = 0xe0000001 -INADDR_MAX_LOCAL_GROUP = 0xe00000ff -INADDR_NONE = 0xffffffff -IN_LOOPBACKNET = 127 -IP_OPTIONS = 1 -IP_MULTICAST_IF = 2 -IP_MULTICAST_TTL = 3 -IP_MULTICAST_LOOP = 4 -IP_ADD_MEMBERSHIP = 5 -IP_DROP_MEMBERSHIP = 6 -IP_HDRINCL = 7 -IP_TOS = 8 -IP_TTL = 9 -IP_RECVOPTS = 10 -IP_RECVRETOPTS = 11 -IP_RECVDSTADDR = 12 -IP_RETOPTS = 13 -IP_OPTIONS = 1 -IP_HDRINCL = 2 -IP_TOS = 3 -IP_TTL = 4 -IP_RECVOPTS = 5 -IP_RECVRETOPTS = 6 -IP_RECVDSTADDR = 7 -IP_RETOPTS = 8 -IP_MULTICAST_IF = 20 -IP_MULTICAST_TTL = 21 -IP_MULTICAST_LOOP = 22 -IP_ADD_MEMBERSHIP = 23 -IP_DROP_MEMBERSHIP = 24 -IRIX4_IP_OPTIONS = 1 -IRIX4_IP_MULTICAST_IF = 2 -IRIX4_IP_MULTICAST_TTL = 3 -IRIX4_IP_MULTICAST_LOOP = 4 -IRIX4_IP_ADD_MEMBERSHIP = 5 -IRIX4_IP_DROP_MEMBERSHIP = 6 -IRIX4_IP_HDRINCL = 7 -IRIX4_IP_TOS = 8 -IRIX4_IP_TTL = 9 -IRIX4_IP_RECVOPTS = 10 -IRIX4_IP_RECVRETOPTS = 11 -IRIX4_IP_RECVDSTADDR = 12 -IRIX4_IP_RETOPTS = 13 -IP_DEFAULT_MULTICAST_TTL = 1 -IP_DEFAULT_MULTICAST_LOOP = 1 -IP_MAX_MEMBERSHIPS = 20 diff --git a/Lib/irix5/IOCTL.py b/Lib/irix5/IOCTL.py deleted file mode 100755 index cec3c3f6a9..0000000000 --- a/Lib/irix5/IOCTL.py +++ /dev/null @@ -1,233 +0,0 @@ -# These lines were mostly generated by h2py.py (see demo/scripts) -# from <sys/ioctl.h>, <sys/termio.h> and <termios.h> on Irix 4.0.2 -# with some manual changes to cope with imperfections in h2py.py. -# The applicability on other systems is not clear; especially non-SYSV -# systems may have a totally different set of ioctls. - -IOCTYPE = 0xff00 -LIOC = (ord('l')<<8) -LIOCGETP = (LIOC|1) -LIOCSETP = (LIOC|2) -LIOCGETS = (LIOC|5) -LIOCSETS = (LIOC|6) -DIOC = (ord('d')<<8) -DIOCGETC = (DIOC|1) -DIOCGETB = (DIOC|2) -DIOCSETE = (DIOC|3) -IOCPARM_MASK = 0x7f -IOC_VOID = 0x20000000 -IOC_OUT = 0x40000000 -IOC_IN = 0x80000000 -IOC_INOUT = (IOC_IN|IOC_OUT) -int = 'i' -short = 'h' -long = 'l' -def sizeof(t): import struct; return struct.calcsize(t) -def _IO(x,y): return (IOC_VOID|((x)<<8)|y) -def _IOR(x,y,t): return (IOC_OUT|((sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|y) -def _IOW(x,y,t): return (IOC_IN|((sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|y) -# this should be _IORW, but stdio got there first -def _IOWR(x,y,t): return (IOC_INOUT|((sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|y) -FIONREAD = _IOR(ord('f'), 127, int) -FIONBIO = _IOW(ord('f'), 126, int) -FIOASYNC = _IOW(ord('f'), 125, int) -FIOSETOWN = _IOW(ord('f'), 124, int) -FIOGETOWN = _IOR(ord('f'), 123, int) -NCC = 8 -NCC_PAD = 7 -NCC_EXT = 16 -NCCS = (NCC+NCC_PAD+NCC_EXT) -VINTR = 0 -VQUIT = 1 -VERASE = 2 -VKILL = 3 -VEOF = 4 -VEOL = 5 -VEOL2 = 6 -VMIN = VEOF -VTIME = VEOL -VSWTCH = 7 -VLNEXT = (NCC+NCC_PAD+0) -VWERASE = (NCC+NCC_PAD+1) -VRPRNT = (NCC+NCC_PAD+2) -VFLUSHO = (NCC+NCC_PAD+3) -VSTOP = (NCC+NCC_PAD+4) -VSTART = (NCC+NCC_PAD+5) -CNUL = '\0' -CDEL = '\377' -CESC = '\\' -CINTR = '\177' -CQUIT = '\34' -CBRK = '\377' -def CTRL(c): return ord(c) & 0x0f -CERASE = CTRL('H') -CKILL = CTRL('U') -CEOF = CTRL('d') -CEOT = CEOF -CSTART = CTRL('q') -CSTOP = CTRL('s') -CSWTCH = CTRL('z') -CSUSP = CSWTCH -CNSWTCH = 0 -CLNEXT = CTRL('v') -CWERASE = CTRL('w') -CFLUSHO = CTRL('o') -CFLUSH = CFLUSHO -CRPRNT = CTRL('r') -CDSUSP = CTRL('y') -IGNBRK = 0000001 -BRKINT = 0000002 -IGNPAR = 0000004 -PARMRK = 0000010 -INPCK = 0000020 -ISTRIP = 0000040 -INLCR = 0000100 -IGNCR = 0000200 -ICRNL = 0000400 -IUCLC = 0001000 -IXON = 0002000 -IXANY = 0004000 -IXOFF = 0010000 -IBLKMD = 0020000 -OPOST = 0000001 -OLCUC = 0000002 -ONLCR = 0000004 -OCRNL = 0000010 -ONOCR = 0000020 -ONLRET = 0000040 -OFILL = 0000100 -OFDEL = 0000200 -NLDLY = 0000400 -NL0 = 0 -NL1 = 0000400 -CRDLY = 0003000 -CR0 = 0 -CR1 = 0001000 -CR2 = 0002000 -CR3 = 0003000 -TABDLY = 0014000 -TAB0 = 0 -TAB1 = 0004000 -TAB2 = 0010000 -TAB3 = 0014000 -BSDLY = 0020000 -BS0 = 0 -BS1 = 0020000 -VTDLY = 0040000 -VT0 = 0 -VT1 = 0040000 -FFDLY = 0100000 -FF0 = 0 -FF1 = 0100000 -CBAUD = 0000017 -B0 = 0 -B50 = 0000001 -B75 = 0000002 -B110 = 0000003 -B134 = 0000004 -B150 = 0000005 -B200 = 0000006 -B300 = 0000007 -B600 = 0000010 -B1200 = 0000011 -B1800 = 0000012 -B2400 = 0000013 -B4800 = 0000014 -B9600 = 0000015 -B19200 = 0000016 -EXTA = 0000016 -B38400 = 0000017 -EXTB = 0000017 -CSIZE = 0000060 -CS5 = 0 -CS6 = 0000020 -CS7 = 0000040 -CS8 = 0000060 -CSTOPB = 0000100 -CREAD = 0000200 -PARENB = 0000400 -PARODD = 0001000 -HUPCL = 0002000 -CLOCAL = 0004000 -LOBLK = 0040000 -ISIG = 0000001 -ICANON = 0000002 -XCASE = 0000004 -ECHO = 0000010 -ECHOE = 0000020 -ECHOK = 0000040 -ECHONL = 0000100 -NOFLSH = 0000200 -IIEXTEN = 0000400 -ITOSTOP = 0001000 -SSPEED = B9600 -IOCTYPE = 0xff00 -TIOC = (ord('T')<<8) -oTCGETA = (TIOC|1) -oTCSETA = (TIOC|2) -oTCSETAW = (TIOC|3) -oTCSETAF = (TIOC|4) -TCSBRK = (TIOC|5) -TCXONC = (TIOC|6) -TCFLSH = (TIOC|7) -TCGETA = (TIOC|8) -TCSETA = (TIOC|9) -TCSETAW = (TIOC|10) -TCSETAF = (TIOC|11) -TIOCFLUSH = (TIOC|12) -TCDSET = (TIOC|32) -TCBLKMD = (TIOC|33) -TIOCPKT = (TIOC|112) -TIOCPKT_DATA = 0x00 -TIOCPKT_FLUSHREAD = 0x01 -TIOCPKT_FLUSHWRITE = 0x02 -TIOCPKT_NOSTOP = 0x10 -TIOCPKT_DOSTOP = 0x20 -TIOCNOTTY = (TIOC|113) -TIOCSTI = (TIOC|114) -TIOCSPGRP = _IOW(ord('t'), 118, int) -TIOCGPGRP = _IOR(ord('t'), 119, int) -TIOCCONS = _IOW(ord('t'), 120, int) -struct_winsize = 'hhhh' -TIOCGWINSZ = _IOR(ord('t'), 104, struct_winsize) -TIOCSWINSZ = _IOW(ord('t'), 103, struct_winsize) -TFIOC = (ord('F')<<8) -oFIONREAD = (TFIOC|127) -LDIOC = (ord('D')<<8) -LDOPEN = (LDIOC|0) -LDCLOSE = (LDIOC|1) -LDCHG = (LDIOC|2) -LDGETT = (LDIOC|8) -LDSETT = (LDIOC|9) -TERM_NONE = 0 -TERM_TEC = 1 -TERM_V61 = 2 -TERM_V10 = 3 -TERM_TEX = 4 -TERM_D40 = 5 -TERM_H45 = 6 -TERM_D42 = 7 -TM_NONE = 0000 -TM_SNL = 0001 -TM_ANL = 0002 -TM_LCF = 0004 -TM_CECHO = 0010 -TM_CINVIS = 0020 -TM_SET = 0200 -LDISC0 = 0 -LDISC1 = 1 -NTTYDISC = LDISC1 -VSUSP = VSWTCH -TCSANOW = 0 -TCSADRAIN = 1 -TCSAFLUSH = 2 -TCIFLUSH = 0 -TCOFLUSH = 1 -TCIOFLUSH = 2 -TCOOFF = 0 -TCOON = 1 -TCIOFF = 2 -TCION = 3 -TO_STOP = LOBLK -IEXTEN = IIEXTEN -TOSTOP = ITOSTOP diff --git a/Lib/irix5/SOCKET.py b/Lib/irix5/SOCKET.py deleted file mode 100755 index 0ba0742186..0000000000 --- a/Lib/irix5/SOCKET.py +++ /dev/null @@ -1,108 +0,0 @@ -# Generated by h2py from /usr/include/sys/socket.h -SOCK_STREAM = 1 -SOCK_DGRAM = 2 -SOCK_RAW = 3 -SOCK_RDM = 4 -SOCK_SEQPACKET = 5 -NC_TPI_CLTS = 1 -NC_TPI_COTS = 2 -NC_TPI_COTS_ORD = 3 -NC_TPI_RAW = 4 -SOCK_DGRAM = NC_TPI_CLTS -SOCK_STREAM = NC_TPI_COTS -SOCK_RAW = NC_TPI_RAW -SOCK_RDM = 5 -SOCK_SEQPACKET = 6 -IRIX4_SOCK_STREAM = 1 -IRIX4_SOCK_DGRAM = 2 -IRIX4_SOCK_RAW = 3 -IRIX4_SOCK_RDM = 4 -IRIX4_SOCK_SEQPACKET = 5 -SO_DEBUG = 0x0001 -SO_ACCEPTCONN = 0x0002 -SO_REUSEADDR = 0x0004 -SO_KEEPALIVE = 0x0008 -SO_DONTROUTE = 0x0010 -SO_BROADCAST = 0x0020 -SO_USELOOPBACK = 0x0040 -SO_LINGER = 0x0080 -SO_OOBINLINE = 0x0100 -SO_REUSEPORT = 0x0200 -SO_ORDREL = 0x0200 -SO_IMASOCKET = 0x0400 -SO_CHAMELEON = 0x1000 -SO_SNDBUF = 0x1001 -SO_RCVBUF = 0x1002 -SO_SNDLOWAT = 0x1003 -SO_RCVLOWAT = 0x1004 -SO_SNDTIMEO = 0x1005 -SO_RCVTIMEO = 0x1006 -SO_ERROR = 0x1007 -SO_TYPE = 0x1008 -SO_PROTOTYPE = 0x1009 -SOL_SOCKET = 0xffff -AF_UNSPEC = 0 -AF_UNIX = 1 -AF_INET = 2 -AF_IMPLINK = 3 -AF_PUP = 4 -AF_CHAOS = 5 -AF_NS = 6 -AF_ISO = 7 -AF_ECMA = 8 -AF_DATAKIT = 9 -AF_CCITT = 10 -AF_SNA = 11 -AF_DECnet = 12 -AF_DLI = 13 -AF_LAT = 14 -AF_HYLINK = 15 -AF_APPLETALK = 16 -AF_ROUTE = 17 -AF_RAW = 18 -AF_LINK = 18 -pseudo_AF_XTP = 19 -AF_NIT = 17 -AF_802 = 18 -AF_OSI = 19 -AF_X25 = 20 -AF_OSINET = 21 -AF_GOSIP = 22 -AF_SDL = 23 -AF_MAX = (AF_SDL+1) -PF_UNSPEC = AF_UNSPEC -PF_UNIX = AF_UNIX -PF_INET = AF_INET -PF_IMPLINK = AF_IMPLINK -PF_PUP = AF_PUP -PF_CHAOS = AF_CHAOS -PF_NS = AF_NS -PF_ISO = AF_ISO -PF_ECMA = AF_ECMA -PF_DATAKIT = AF_DATAKIT -PF_CCITT = AF_CCITT -PF_SNA = AF_SNA -PF_DECnet = AF_DECnet -PF_DLI = AF_DLI -PF_LAT = AF_LAT -PF_HYLINK = AF_HYLINK -PF_APPLETALK = AF_APPLETALK -PF_ROUTE = AF_ROUTE -PF_LINK = AF_LINK -PF_XTP = pseudo_AF_XTP -PF_RAW = AF_RAW -PF_NIT = AF_NIT -PF_802 = AF_802 -PF_OSI = AF_OSI -PF_X25 = AF_X25 -PF_OSINET = AF_OSINET -PF_GOSIP = AF_GOSIP -PF_MAX = AF_MAX -SOMAXCONN = 5 -MSG_OOB = 0x1 -MSG_PEEK = 0x2 -MSG_DONTROUTE = 0x4 -MSG_EOR = 0x8 -MSG_BTAG = 0x40 -MSG_ETAG = 0x80 -MSG_MAXIOVLEN = 16 diff --git a/Lib/irix5/SV.py b/Lib/irix5/SV.py deleted file mode 100755 index 08fb91798a..0000000000 --- a/Lib/irix5/SV.py +++ /dev/null @@ -1,120 +0,0 @@ -NTSC_XMAX = 640 -NTSC_YMAX = 480 -PAL_XMAX = 768 -PAL_YMAX = 576 -BLANKING_BUFFER_SIZE = 2 - -MAX_SOURCES = 2 - -# mode parameter for Bind calls -IN_OFF = 0 # No Video -IN_OVER = 1 # Video over graphics -IN_UNDER = 2 # Video under graphics -IN_REPLACE = 3 # Video replaces entire win - -# mode parameters for LoadMap calls. Specifies buffer, always 256 entries -INPUT_COLORMAP = 0 # tuples of 8-bit RGB -CHROMA_KEY_MAP = 1 # tuples of 8-bit RGB -COLOR_SPACE_MAP = 2 # tuples of 8-bit RGB -GAMMA_MAP = 3 # tuples of 24-bit red values - -# mode parameters for UseExclusive calls -INPUT = 0 -OUTPUT = 1 -IN_OUT = 2 - -# Format constants for the capture routines -RGB8_FRAMES = 0 # noninterleaved 8 bit 3:2:3 RBG fields -RGB32_FRAMES = 1 # 32-bit 8:8:8 RGB frames -YUV411_FRAMES = 2 # interleaved, 8:2:2 YUV format -YUV411_FRAMES_AND_BLANKING_BUFFER = 3 - -# -# sv.SetParam is passed variable length argument lists, -# consisting of <name, value> pairs. The following -# constants identify argument names. -# -_NAME_BASE = 1000 -SOURCE = (_NAME_BASE + 0) -SOURCE1 = 0 -SOURCE2 = 1 -SOURCE3 = 2 -COLOR = (_NAME_BASE + 1) -DEFAULT_COLOR = 0 -USER_COLOR = 1 -MONO = 2 -OUTPUTMODE = (_NAME_BASE + 2) -LIVE_OUTPUT = 0 -STILL24_OUT = 1 -FREEZE = (_NAME_BASE + 3) -DITHER = (_NAME_BASE + 4) -OUTPUT_FILTER = (_NAME_BASE + 5) -HUE = (_NAME_BASE + 6) -GENLOCK = (_NAME_BASE + 7) -GENLOCK_OFF = 0 -GENLOCK_ON = 1 -GENLOCK_HOUSE = 2 -BROADCAST = (_NAME_BASE + 8) -NTSC = 0 -PAL = 1 -VIDEO_MODE = (_NAME_BASE + 9) -COMP = 0 -SVIDEO = 1 -INPUT_BYPASS = (_NAME_BASE + 10) -FIELDDROP = (_NAME_BASE + 11) -SLAVE = (_NAME_BASE + 12) -APERTURE_FACTOR = (_NAME_BASE + 13) -AFACTOR_0 = 0 -AFACTOR_QTR = 1 -AFACTOR_HLF = 2 -AFACTOR_ONE = 3 -CORING = (_NAME_BASE + 14) -COR_OFF = 0 -COR_1LSB = 1 -COR_2LSB = 2 -COR_3LSB = 3 -APERTURE_BANDPASS = (_NAME_BASE + 15) -ABAND_F0 = 0 -ABAND_F1 = 1 -ABAND_F2 = 2 -ABAND_F3 = 3 -PREFILTER = (_NAME_BASE + 16) -CHROMA_TRAP = (_NAME_BASE + 17) -CK_THRESHOLD = (_NAME_BASE + 18) -PAL_SENSITIVITY = (_NAME_BASE + 19) -GAIN_CONTROL = (_NAME_BASE + 20) -GAIN_SLOW = 0 -GAIN_MEDIUM = 1 -GAIN_FAST = 2 -GAIN_FROZEN = 3 -AUTO_CKILL = (_NAME_BASE + 21) -VTR_MODE = (_NAME_BASE + 22) -VTR_INPUT = 0 -CAMERA_INPUT = 1 -LUMA_DELAY = (_NAME_BASE + 23) -VNOISE = (_NAME_BASE + 24) -VNOISE_NORMAL = 0 -VNOISE_SEARCH = 1 -VNOISE_AUTO = 2 -VNOISE_BYPASS = 3 -CHCV_PAL = (_NAME_BASE + 25) -CHCV_NTSC = (_NAME_BASE + 26) -CCIR_LEVELS = (_NAME_BASE + 27) -STD_CHROMA = (_NAME_BASE + 28) -DENC_VTBYPASS = (_NAME_BASE + 29) -FAST_TIMECONSTANT = (_NAME_BASE + 30) -GENLOCK_DELAY = (_NAME_BASE + 31) -PHASE_SYNC = (_NAME_BASE + 32) -VIDEO_OUTPUT = (_NAME_BASE + 33) -CHROMA_PHASEOUT = (_NAME_BASE + 34) -CHROMA_CENTER = (_NAME_BASE + 35) -YUV_TO_RGB_INVERT = (_NAME_BASE + 36) -SOURCE1_BROADCAST = (_NAME_BASE + 37) -SOURCE1_MODE = (_NAME_BASE + 38) -SOURCE2_BROADCAST = (_NAME_BASE + 39) -SOURCE2_MODE = (_NAME_BASE + 40) -SOURCE3_BROADCAST = (_NAME_BASE + 41) -SOURCE3_MODE = (_NAME_BASE + 42) -SIGNAL_STD = (_NAME_BASE + 43) -NOSIGNAL = 2 -SIGNAL_COLOR = (_NAME_BASE + 44) diff --git a/Lib/irix5/TERMIOS.py b/Lib/irix5/TERMIOS.py deleted file mode 100755 index a360786ba5..0000000000 --- a/Lib/irix5/TERMIOS.py +++ /dev/null @@ -1,339 +0,0 @@ -# Generated by h2py from /usr/include/termios.h - -# Included from sys/termios.h - -# Included from sys/ttydev.h -B0 = 0 -B50 = 0000001 -B75 = 0000002 -B110 = 0000003 -B134 = 0000004 -B150 = 0000005 -B200 = 0000006 -B300 = 0000007 -B600 = 0000010 -B1200 = 0000011 -B1800 = 0000012 -B2400 = 0000013 -B4800 = 0000014 -B9600 = 0000015 -B19200 = 0000016 -EXTA = 0000016 -B38400 = 0000017 -EXTB = 0000017 - -# Included from sys/types.h - -# Included from sgidefs.h -_MIPS_ISA_MIPS1 = 1 -_MIPS_ISA_MIPS2 = 2 -_MIPS_ISA_MIPS3 = 3 -_MIPS_ISA_MIPS4 = 4 -_MIPS_SIM_ABI32 = 1 -_MIPS_SIM_ABI64 = 2 -P_MYID = (-1) -P_MYHOSTID = (-1) - -# Included from sys/bsd_types.h - -# Included from sys/mkdev.h -ONBITSMAJOR = 7 -ONBITSMINOR = 8 -OMAXMAJ = 0x7f -OMAXMIN = 0xff -NBITSMAJOR = 14 -NBITSMINOR = 18 -MAXMAJ = 0xff -MAXMIN = 0x3ffff -OLDDEV = 0 -NEWDEV = 1 -MKDEV_VER = NEWDEV -def major(dev): return __major(MKDEV_VER, dev) - -def minor(dev): return __minor(MKDEV_VER, dev) - - -# Included from sys/select.h -FD_SETSIZE = 1024 -NBBY = 8 -_POSIX_VDISABLE = 0 -def CTRL(c): return ((c)&037) - -IBSHIFT = 16 -NCC = 8 -NCCS = 23 -VINTR = 0 -VQUIT = 1 -VERASE = 2 -VKILL = 3 -VEOF = 4 -VEOL = 5 -VEOL2 = 6 -VMIN = 4 -VTIME = 5 -VSWTCH = 7 -VSTART = 8 -VSTOP = 9 -VSUSP = 10 -VDSUSP = 11 -VREPRINT = 12 -VDISCARD = 13 -VWERASE = 14 -VLNEXT = 15 -VRPRNT = VREPRINT -VFLUSHO = VDISCARD -VCEOF = NCC -VCEOL = (NCC + 1) -CNUL = 0 -CDEL = 0377 -CESC = ord('\\') -CINTR = 0177 -CQUIT = 034 -CERASE = CTRL(ord('H')) -CKILL = CTRL(ord('U')) -CEOL = 0 -CEOL2 = 0 -CEOF = CTRL(ord('d')) -CEOT = CEOF -CSTART = CTRL(ord('q')) -CSTOP = CTRL(ord('s')) -CSWTCH = CTRL(ord('z')) -CNSWTCH = 0 -CSUSP = CSWTCH -CLNEXT = CTRL(ord('v')) -CWERASE = CTRL(ord('w')) -CFLUSHO = CTRL(ord('o')) -CFLUSH = CFLUSHO -CRPRNT = CTRL(ord('r')) -CDSUSP = CTRL(ord('y')) -CBRK = 0377 -IGNBRK = 0000001 -BRKINT = 0000002 -IGNPAR = 0000004 -PARMRK = 0000010 -INPCK = 0000020 -ISTRIP = 0000040 -INLCR = 0000100 -IGNCR = 0000200 -ICRNL = 0000400 -IUCLC = 0001000 -IXON = 0002000 -IXANY = 0004000 -IXOFF = 0010000 -IMAXBEL = 0020000 -IBLKMD = 0040000 -OPOST = 0000001 -OLCUC = 0000002 -ONLCR = 0000004 -OCRNL = 0000010 -ONOCR = 0000020 -ONLRET = 0000040 -OFILL = 0000100 -OFDEL = 0000200 -NLDLY = 0000400 -NL0 = 0 -NL1 = 0000400 -CRDLY = 0003000 -CR0 = 0 -CR1 = 0001000 -CR2 = 0002000 -CR3 = 0003000 -TABDLY = 0014000 -TAB0 = 0 -TAB1 = 0004000 -TAB2 = 0010000 -TAB3 = 0014000 -XTABS = 0014000 -BSDLY = 0020000 -BS0 = 0 -BS1 = 0020000 -VTDLY = 0040000 -VT0 = 0 -VT1 = 0040000 -FFDLY = 0100000 -FF0 = 0 -FF1 = 0100000 -PAGEOUT = 0200000 -WRAP = 0400000 -CBAUD = 000000017 -CSIZE = 000000060 -CS5 = 0 -CS6 = 000000020 -CS7 = 000000040 -CS8 = 000000060 -CSTOPB = 000000100 -CREAD = 000000200 -PARENB = 000000400 -PARODD = 000001000 -HUPCL = 000002000 -CLOCAL = 000004000 -RCV1EN = 000010000 -XMT1EN = 000020000 -LOBLK = 000040000 -XCLUDE = 000100000 -CIBAUD = 003600000 -PAREXT = 004000000 -CNEW_RTSCTS = 010000000 -ISIG = 0000001 -ICANON = 0000002 -XCASE = 0000004 -ECHO = 0000010 -ECHOE = 0000020 -ECHOK = 0000040 -ECHONL = 0000100 -NOFLSH = 0000200 -IEXTEN = 0000400 -ITOSTOP = 0100000 -TOSTOP = ITOSTOP -ECHOCTL = 0001000 -ECHOPRT = 0002000 -ECHOKE = 0004000 -DEFECHO = 0010000 -FLUSHO = 0020000 -PENDIN = 0040000 -TIOC = (ord('T')<<8) -TCGETA = (TIOC|1) -TCSETA = (TIOC|2) -TCSETAW = (TIOC|3) -TCSETAF = (TIOC|4) -TCSBRK = (TIOC|5) -TCXONC = (TIOC|6) -TCFLSH = (TIOC|7) - -# Included from sys/ioctl.h -IOCTYPE = 0xff00 -LIOC = (ord('l')<<8) -LIOCGETP = (LIOC|1) -LIOCSETP = (LIOC|2) -LIOCGETS = (LIOC|5) -LIOCSETS = (LIOC|6) -DIOC = (ord('d')<<8) -DIOCGETC = (DIOC|1) -DIOCGETB = (DIOC|2) -DIOCSETE = (DIOC|3) - -# Included from sys/ioccom.h -IOCPARM_MASK = 0xff -IOC_VOID = 0x20000000 -IOC_OUT = 0x40000000 -IOC_IN = 0x80000000 -IOC_INOUT = (IOC_IN|IOC_OUT) - -# Included from net/soioctl.h - -# Included from sys/termio.h -CLNEXT = CTRL(ord('v')) -CWERASE = CTRL(ord('w')) -CFLUSHO = CTRL(ord('o')) -CFLUSH = CFLUSHO -CRPRNT = CTRL(ord('r')) -CDSUSP = CTRL(ord('y')) -SSPEED = B9600 -TERM_NONE = 0 -TERM_TEC = 1 -TERM_V61 = 2 -TERM_V10 = 3 -TERM_TEX = 4 -TERM_D40 = 5 -TERM_H45 = 6 -TERM_D42 = 7 -TM_NONE = 0000 -TM_SNL = 0001 -TM_ANL = 0002 -TM_LCF = 0004 -TM_CECHO = 0010 -TM_CINVIS = 0020 -TM_SET = 0200 -LDISC0 = 0 -LDISC1 = 1 -NTTYDISC = LDISC1 -TIOCFLUSH = (TIOC|12) -TCSETLABEL = (TIOC|13) -TCDSET = (TIOC|32) -TCBLKMD = (TIOC|33) -TIOCPKT = (TIOC|112) -TIOCPKT_DATA = 0x00 -TIOCPKT_FLUSHREAD = 0x01 -TIOCPKT_FLUSHWRITE = 0x02 -TIOCPKT_NOSTOP = 0x10 -TIOCPKT_DOSTOP = 0x20 -TIOCPKT_IOCTL = 0x40 -TIOCNOTTY = (TIOC|113) -TIOCSTI = (TIOC|114) -TFIOC = (ord('F')<<8) -oFIONREAD = (TFIOC|127) -TO_STOP = LOBLK -IOCTYPE = 0xff00 -TCGETS = (TIOC|13) -TCSETS = (TIOC|14) -TCSETSW = (TIOC|15) -TCSETSF = (TIOC|16) -TCSANOW = ((ord('T')<<8)|14) -TCSADRAIN = ((ord('T')<<8)|15) -TCSAFLUSH = ((ord('T')<<8)|16) -TCIFLUSH = 0 -TCOFLUSH = 1 -TCIOFLUSH = 2 -TCOOFF = 0 -TCOON = 1 -TCIOFF = 2 -TCION = 3 -tIOC = (ord('t')<<8) -TIOCGETD = (tIOC|0) -TIOCSETD = (tIOC|1) -TIOCHPCL = (tIOC|2) -TIOCGETP = (tIOC|8) -TIOCSETP = (tIOC|9) -TIOCSETN = (tIOC|10) -TIOCEXCL = (tIOC|13) -TIOCNXCL = (tIOC|14) -TIOCSETC = (tIOC|17) -TIOCGETC = (tIOC|18) -TIOCLBIS = (tIOC|127) -TIOCLBIC = (tIOC|126) -TIOCLSET = (tIOC|125) -TIOCLGET = (tIOC|124) -TIOCSBRK = (tIOC|123) -TIOCCBRK = (tIOC|122) -TIOCSDTR = (tIOC|121) -TIOCCDTR = (tIOC|120) -TIOCSLTC = (tIOC|117) -TIOCGLTC = (tIOC|116) -TIOCOUTQ = (tIOC|115) -TIOCSTOP = (tIOC|111) -TIOCSTART = (tIOC|110) -TIOCGSID = (tIOC|22) -TIOCSSID = (tIOC|24) -TIOCMSET = (tIOC|26) -TIOCMBIS = (tIOC|27) -TIOCMBIC = (tIOC|28) -TIOCMGET = (tIOC|29) -TIOCM_LE = 0001 -TIOCM_DTR = 0002 -TIOCM_RTS = 0004 -TIOCM_ST = 0010 -TIOCM_SR = 0020 -TIOCM_CTS = 0040 -TIOCM_CAR = 0100 -TIOCM_CD = TIOCM_CAR -TIOCM_RNG = 0200 -TIOCM_RI = TIOCM_RNG -TIOCM_DSR = 0400 -TIOCREMOTE = (tIOC|30) -TIOCSIGNAL = (tIOC|31) -ISPTM = ((ord('P')<<8)|1) -UNLKPT = ((ord('P')<<8)|2) -SVR4SOPEN = ((ord('P')<<8)|100) -LDIOC = (ord('D')<<8) -LDOPEN = (LDIOC|0) -LDCLOSE = (LDIOC|1) -LDCHG = (LDIOC|2) -LDGETT = (LDIOC|8) -LDSETT = (LDIOC|9) -LDSMAP = (LDIOC|10) -LDGMAP = (LDIOC|11) -LDNMAP = (LDIOC|12) -DIOC = (ord('d')<<8) -DIOCGETP = (DIOC|8) -DIOCSETP = (DIOC|9) -FIORDCHK = ((ord('f')<<8)|3) diff --git a/Lib/irix5/WAIT.py b/Lib/irix5/WAIT.py deleted file mode 100755 index bfd0133e84..0000000000 --- a/Lib/irix5/WAIT.py +++ /dev/null @@ -1,14 +0,0 @@ -# Generated by h2py from /usr/include/sys/wait.h -_WSTOPPED = 0177 -WNOHANG = 0100 -WEXITED = 0001 -WTRAPPED = 0002 -WSTOPPED = 0004 -WCONTINUED = 0010 -WNOWAIT = 0200 -WOPTMASK = (WEXITED|WTRAPPED|WSTOPPED|WCONTINUED|WNOHANG|WNOWAIT) -WSTOPFLG = 0177 -WCONTFLG = 0177777 -WCOREFLAG = 0200 -WSIGMASK = 0177 -WUNTRACED = 0004 diff --git a/Lib/irix5/auds.py b/Lib/irix5/auds.py deleted file mode 100755 index fb992a9594..0000000000 --- a/Lib/irix5/auds.py +++ /dev/null @@ -1,106 +0,0 @@ -import audio - -RATE = 8192 - -# Initialize the audio stuff -audio.setrate(3) -audio.setoutgain(100) # for speaker - -play = audio.write - -def samp(n): - savegain = audio.getoutgain() - try: - audio.setoutgain(0) - x = raw_input('Hit Enter to sample ' + `n` + ' seconds: ') - return audio.read(n*RATE) - finally: - audio.setoutgain(savegain) - -def echo(s, delay, gain): - return s[:delay] + audio.add(s[delay:], audio.amplify(s, gain, gain)) - -def save(s, file): - f = open(file, 'w') - f.write(s) - -def load(file): - return loadfp(open(file, 'r')) - -def loadfp(fp): - s = '' - while 1: - buf = fp.read(16*1024) - if not buf: break - s = s + buf - return s - -def unbias(s): - if not s: return s - a = audio.chr2num(s) - sum = 0 - for i in a: sum = sum + i - bias = (sum + len(a)/2) / len(a) - print 'Bias value:', bias - if bias: - for i in range(len(a)): - a[i] = a[i] - bias - s = audio.num2chr(a) - return s - -# Stretch by a/b. -# Think of this as converting the sampling rate from a samples/sec -# to b samples/sec. Or, if the input is a bytes long, the output -# will be b bytes long. -# -def stretch(s, a, b): - y = audio.chr2num(s) - m = len(y) - out = [] - n = m * b / a - # i, j will walk through y and out (step 1) - # ib, ja are i*b, j*a and are kept as close together as possible - i, ib = 0, 0 - j, ja = 0, 0 - for j in range(n): - ja = ja+a - while ib < ja: - i = i+1 - ib = ib+b - if i >= m: - break - if ib == ja: - out.append(y[i]) - else: - out.append((y[i]*(ja-(ib-b)) + y[i-1]*(ib-ja)) / b) - return audio.num2chr(out) - -def sinus(freq): # return a 1-second sine wave - from math import sin, pi - factor = 2.0*pi*float(freq)/float(RATE) - list = range(RATE) - for i in list: - list[i] = int(sin(float(i) * factor) * 127.0) - return audio.num2chr(list) - -def softclip(s): - if '\177' not in s and '\200' not in s: - return s - num = audio.chr2num(s) - extremes = (-128, 127) - for i in range(1, len(num)-1): - if num[i] in extremes: - num[i] = (num[i-1] + num[i+1]) / 2 - return audio.num2chr(num) - -def demo(): - gday = load('gday')[1000:6000] - save(gday, 'gday0') - gg = [gday] - for i in range(1, 10): - for g in gg: play(g) - g = stretch(gday, 10, 10-i) - save(g, 'gday' + `i`) - gg.append(g) - while 1: - for g in gg: play(g) diff --git a/Lib/irix5/cddb.py b/Lib/irix5/cddb.py deleted file mode 100755 index 57cf3c6661..0000000000 --- a/Lib/irix5/cddb.py +++ /dev/null @@ -1,208 +0,0 @@ -# This file implements a class which forms an interface to the .cddb -# directory that is maintained by SGI's cdman program. -# -# Usage is as follows: -# -# import readcd -# r = readcd.Readcd() -# c = Cddb(r.gettrackinfo()) -# -# Now you can use c.artist, c.title and c.track[trackno] (where trackno -# starts at 1). When the CD is not recognized, all values will be the empty -# string. -# It is also possible to set the above mentioned variables to new values. -# You can then use c.write() to write out the changed values to the -# .cdplayerrc file. - -import string, posix, os - -_cddbrc = '.cddb' -_DB_ID_NTRACKS = 5 -_dbid_map = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@_=+abcdefghijklmnopqrstuvwxyz' -def _dbid(v): - if v >= len(_dbid_map): - return string.zfill(v, 2) - else: - return _dbid_map[v] - -def tochash(toc): - if type(toc) == type(''): - tracklist = [] - for i in range(2, len(toc), 4): - tracklist.append((None, - (string.atoi(toc[i:i+2]), - string.atoi(toc[i+2:i+4])))) - else: - tracklist = toc - ntracks = len(tracklist) - hash = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF) - if ntracks <= _DB_ID_NTRACKS: - nidtracks = ntracks - else: - nidtracks = _DB_ID_NTRACKS - 1 - min = 0 - sec = 0 - for track in tracklist: - start, length = track - min = min + length[0] - sec = sec + length[1] - min = min + sec / 60 - sec = sec % 60 - hash = hash + _dbid(min) + _dbid(sec) - for i in range(nidtracks): - start, length = tracklist[i] - hash = hash + _dbid(length[0]) + _dbid(length[1]) - return hash - -class Cddb: - def __init__(self, tracklist): - if os.environ.has_key('CDDB_PATH'): - path = os.environ['CDDB_PATH'] - cddb_path = string.splitfields(path, ',') - else: - home = os.environ['HOME'] - cddb_path = [home + '/' + _cddbrc] - - self._get_id(tracklist) - - for dir in cddb_path: - file = dir + '/' + self.id + '.rdb' - try: - f = open(file, 'r') - self.file = file - break - except IOError: - pass - ntracks = string.atoi(self.id[:2], 16) - self.artist = '' - self.title = '' - self.track = [None] + [''] * ntracks - self.trackartist = [None] + [''] * ntracks - self.notes = [] - if not hasattr(self, 'file'): - return - import regex - reg = regex.compile('^\\([^.]*\\)\\.\\([^:]*\\):[\t ]+\\(.*\\)') - while 1: - line = f.readline() - if not line: - break - if reg.match(line) == -1: - print 'syntax error in ' + file - continue - name1 = line[reg.regs[1][0]:reg.regs[1][1]] - name2 = line[reg.regs[2][0]:reg.regs[2][1]] - value = line[reg.regs[3][0]:reg.regs[3][1]] - if name1 == 'album': - if name2 == 'artist': - self.artist = value - elif name2 == 'title': - self.title = value - elif name2 == 'toc': - if not self.toc: - self.toc = value - if self.toc != value: - print 'toc\'s don\'t match' - elif name2 == 'notes': - self.notes.append(value) - elif name1[:5] == 'track': - try: - trackno = string.atoi(name1[5:]) - except strings.atoi_error: - print 'syntax error in ' + file - continue - if trackno > ntracks: - print 'track number ' + `trackno` + \ - ' in file ' + file + \ - ' out of range' - continue - if name2 == 'title': - self.track[trackno] = value - elif name2 == 'artist': - self.trackartist[trackno] = value - f.close() - for i in range(2, len(self.track)): - track = self.track[i] - # if track title starts with `,', use initial part - # of previous track's title - if track and track[0] == ',': - try: - off = string.index(self.track[i - 1], - ',') - except string.index_error: - pass - else: - self.track[i] = self.track[i-1][:off] \ - + track - - def _get_id(self, tracklist): - # fill in self.id and self.toc. - # if the argument is a string ending in .rdb, the part - # upto the suffix is taken as the id. - if type(tracklist) == type(''): - if tracklist[-4:] == '.rdb': - self.id = tracklist[:-4] - self.toc = '' - return - t = [] - for i in range(2, len(tracklist), 4): - t.append((None, \ - (string.atoi(tracklist[i:i+2]), \ - string.atoi(tracklist[i+2:i+4])))) - tracklist = t - ntracks = len(tracklist) - self.id = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF) - if ntracks <= _DB_ID_NTRACKS: - nidtracks = ntracks - else: - nidtracks = _DB_ID_NTRACKS - 1 - min = 0 - sec = 0 - for track in tracklist: - start, length = track - min = min + length[0] - sec = sec + length[1] - min = min + sec / 60 - sec = sec % 60 - self.id = self.id + _dbid(min) + _dbid(sec) - for i in range(nidtracks): - start, length = tracklist[i] - self.id = self.id + _dbid(length[0]) + _dbid(length[1]) - self.toc = string.zfill(ntracks, 2) - for track in tracklist: - start, length = track - self.toc = self.toc + string.zfill(length[0], 2) + \ - string.zfill(length[1], 2) - - def write(self): - import posixpath - if os.environ.has_key('CDDB_WRITE_DIR'): - dir = os.environ['CDDB_WRITE_DIR'] - else: - dir = os.environ['HOME'] + '/' + _cddbrc - file = dir + '/' + self.id + '.rdb' - if posixpath.exists(file): - # make backup copy - posix.rename(file, file + '~') - f = open(file, 'w') - f.write('album.title:\t' + self.title + '\n') - f.write('album.artist:\t' + self.artist + '\n') - f.write('album.toc:\t' + self.toc + '\n') - for note in self.notes: - f.write('album.notes:\t' + note + '\n') - prevpref = None - for i in range(1, len(self.track)): - if self.trackartist[i]: - f.write('track'+`i`+'.artist:\t'+self.trackartist[i]+'\n') - track = self.track[i] - try: - off = string.index(track, ',') - except string.index_error: - prevpref = None - else: - if prevpref and track[:off] == prevpref: - track = track[off:] - else: - prevpref = track[:off] - f.write('track' + `i` + '.title:\t' + track + '\n') - f.close() diff --git a/Lib/irix5/cdplayer.py b/Lib/irix5/cdplayer.py deleted file mode 100755 index 5c2c95aa7f..0000000000 --- a/Lib/irix5/cdplayer.py +++ /dev/null @@ -1,89 +0,0 @@ -# This file implements a class which forms an interface to the .cdplayerrc -# file that is maintained by SGI's cdplayer program. -# -# Usage is as follows: -# -# import readcd -# r = readcd.Readcd() -# c = Cdplayer(r.gettrackinfo()) -# -# Now you can use c.artist, c.title and c.track[trackno] (where trackno -# starts at 1). When the CD is not recognized, all values will be the empty -# string. -# It is also possible to set the above mentioned variables to new values. -# You can then use c.write() to write out the changed values to the -# .cdplayerrc file. - -cdplayerrc = '.cdplayerrc' - -class Cdplayer: - def __init__(self, tracklist): - import string - self.artist = '' - self.title = '' - if type(tracklist) == type(''): - t = [] - for i in range(2, len(tracklist), 4): - t.append((None, \ - (string.atoi(tracklist[i:i+2]), \ - string.atoi(tracklist[i+2:i+4])))) - tracklist = t - self.track = [None] + [''] * len(tracklist) - self.id = 'd' + string.zfill(len(tracklist), 2) - for track in tracklist: - start, length = track - self.id = self.id + string.zfill(length[0], 2) + \ - string.zfill(length[1], 2) - try: - import posix - f = open(posix.environ['HOME'] + '/' + cdplayerrc, 'r') - except IOError: - return - import regex - reg = regex.compile('^\\([^:]*\\):\t\\(.*\\)') - s = self.id + '.' - l = len(s) - while 1: - line = f.readline() - if line == '': - break - if line[:l] == s: - line = line[l:] - if reg.match(line) == -1: - print 'syntax error in ~/' + cdplayerrc - continue - name = line[reg.regs[1][0]:reg.regs[1][1]] - value = line[reg.regs[2][0]:reg.regs[2][1]] - if name == 'title': - self.title = value - elif name == 'artist': - self.artist = value - elif name[:5] == 'track': - trackno = string.atoi(name[6:]) - self.track[trackno] = value - f.close() - - def write(self): - import posix - filename = posix.environ['HOME'] + '/' + cdplayerrc - try: - old = open(filename, 'r') - except IOError: - old = open('/dev/null', 'r') - new = open(filename + '.new', 'w') - s = self.id + '.' - l = len(s) - while 1: - line = old.readline() - if line == '': - break - if line[:l] <> s: - new.write(line) - new.write(self.id + '.title:\t' + self.title + '\n') - new.write(self.id + '.artist:\t' + self.artist + '\n') - for i in range(1, len(self.track)): - new.write(self.id + '.track.' + `i` + ':\t' + \ - self.track[i] + '\n') - old.close() - new.close() - posix.rename(filename + '.new', filename) diff --git a/Lib/irix5/flp.doc b/Lib/irix5/flp.doc deleted file mode 100755 index 1a2f374ae7..0000000000 --- a/Lib/irix5/flp.doc +++ /dev/null @@ -1,117 +0,0 @@ -.SH -Module flp -.LP -The flp module loads fl-forms from fd files, as generated -by fdesign. The module is designed to be flexible enough to allow -almost anything to be done with the loaded form. -.LP -Loadform defines -two types of functions: functions to parse fd files and functions to -create the forms from the templates returned by the parse functions. -There are fairly low-level create functions that create single objects, -and convenience routines that create complete forms, including callbacks, -etc. -.LP -The exception flp.error is raised whenever an error occurs while parsing a forms -definition file or creating a form. -.SH 2 -Parsing functions -.LP -There are two parsing functions, parse_form() and parse_forms(). They -take the following form: -.LP -.ft C -ftuple = parse_form(filename, formname) -.br -ftdict = parse_forms(filename) -.IP -Parse_form parses a single form, and returns a tuple (ftmp, otmplist). -Ftmp is a template for a form, otmplist is a list of templates for -objects. See below for a description of these templates. -.IP -Parse_forms parses all forms in an fd file. It returns a dictionary of -(ftmp, otmplist) tuples, indexed by formname. -.IP -Filename is the name of the forms definition file to inspect. The functions -appends '.fd' if needed, and use 'sys.path' to locate the file. -.IP -formname is the name of the form to load. This argument is mandatory, -even if the file only contains one form. -.LP -The form template and object template are structures that contain all -the information read from the fd file, in 'natural' form. A form -template record contains the following fields: -.IP -.nf -"Name", the name of the form; -"Width", the width of the form; -"Height", the height of the form; and -"Numberofobjects", the number of objects in the form. -.LP -An object template contains the following fields: -.IP -.nf -"Class", the class of object (eg. FL.BUTTON); -"Type", the sub-class (eg. FL.NORMALBUTTON); -"Box", a list with four members: [x, y, width, height]; -"Boxtype", the type of box (eg. FL.DOWNBOX); -"Colors", a list with the two object colors; -"Alignment", the label alignment (eg. FL.ALIGNLEFT); -"Style", the label style (eg. FL.BOLDSTYLE); -"Lcol", the label color; -"Label", a string containing the label; -"Name", a string containing the name of the object; -"Callback", a string containing the callback routine name; and -"Argument", a string containing the callback routine extra argument. -.SH -Low-level create routines. -.LP -The three low-level creation routines are called as follows: -.LP -.ft C -form = create_form(form_template) -.IP -Create an fl form from a form template. Returns the form created. -.LP -.ft C -obj = create_object(form, obj_template) -.IP -Create an object in an fl form. Return the new object. -An error is raised if the object has a callback routine. -.SH -High-level create routines. -.LP -The 'standard' way to handle forms in python is to define a class -that contains the form and all the objects (insofar as they are named), -and that defines all the callback functions, and use an instance of -this class to handle the form interaction. -Flp contains three routines that simplify handling this paradigm: -.LP -.ft C -create_full_form(instance, ftuple) -.IP -This routine takes an instance of your form-handling class and an -ftuple (as returned by the parsing routines) as parameters. It inserts -the form into the instance, defines all object names and arranges that -the callback methods are called. All the names inserted into the -instance are the same as the names used for the objects, etc. in the -fd file. -.LP -.ft C -merge_full_form(instance, form, ftuple) -.IP -This function does the same as create_full_form, only it does not create -the form itself nor the 'background box' that fdesign automatically -adds to each form. This is useful if your class inherits a superclass -that already defines a skeleton form (with 'OK' and 'Cancel' buttons, -for instance), and you want to merge the new form into that existing -form. The 'form' parameter is the form to which the new objects are -added. -.LP -If you use the paradigm sketched here but need slightly more control -over object creation there is a routine that creates a single object -and inserts its name (and arranges for the callback routine to be -called): -.LP -.ft C -create_object_instance(instance, form, obj_template) diff --git a/Lib/irix5/flp.py b/Lib/irix5/flp.py deleted file mode 100755 index 14e2278744..0000000000 --- a/Lib/irix5/flp.py +++ /dev/null @@ -1,455 +0,0 @@ -# -# flp - Module to load fl forms from fd files -# -# Jack Jansen, December 1991 -# -import string -import os -import sys -import FL - -SPLITLINE = '--------------------' -FORMLINE = '=============== FORM ===============' -ENDLINE = '==============================' - -error = 'flp.error' - -################################################################## -# Part 1 - The parsing routines # -################################################################## - -# -# Externally visible function. Load form. -# -def parse_form(filename, formname): - forms = checkcache(filename) - if forms is None: - forms = parse_forms(filename) - if forms.has_key(formname): - return forms[formname] - else: - raise error, 'No such form in fd file' - -# -# Externally visible function. Load all forms. -# -def parse_forms(filename): - forms = checkcache(filename) - if forms != None: return forms - fp = _open_formfile(filename) - nforms = _parse_fd_header(fp) - forms = {} - for i in range(nforms): - form = _parse_fd_form(fp, None) - forms[form[0].Name] = form - writecache(filename, forms) - return forms - -# -# Internal: see if a cached version of the file exists -# -MAGIC = '.fdc' -_internal_cache = {} # Used by frozen scripts only -def checkcache(filename): - if _internal_cache.has_key(filename): - altforms = _internal_cache[filename] - return _unpack_cache(altforms) - import marshal - fp, filename = _open_formfile2(filename) - fp.close() - cachename = filename + 'c' - try: - fp = open(cachename, 'r') - except IOError: - #print 'flp: no cache file', cachename - return None - try: - if fp.read(4) != MAGIC: - print 'flp: bad magic word in cache file', cachename - return None - cache_mtime = rdlong(fp) - file_mtime = getmtime(filename) - if cache_mtime != file_mtime: - #print 'flp: outdated cache file', cachename - return None - #print 'flp: valid cache file', cachename - altforms = marshal.load(fp) - return _unpack_cache(altforms) - finally: - fp.close() - -def _unpack_cache(altforms): - forms = {} - for name in altforms.keys(): - altobj, altlist = altforms[name] - obj = _newobj() - obj.make(altobj) - list = [] - for altobj in altlist: - nobj = _newobj() - nobj.make(altobj) - list.append(nobj) - forms[name] = obj, list - return forms - -def rdlong(fp): - s = fp.read(4) - if len(s) != 4: return None - a, b, c, d = s[0], s[1], s[2], s[3] - return ord(a)<<24 | ord(b)<<16 | ord(c)<<8 | ord(d) - -def wrlong(fp, x): - a, b, c, d = (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff - fp.write(chr(a) + chr(b) + chr(c) + chr(d)) - -def getmtime(filename): - import os - from stat import ST_MTIME - try: - return os.stat(filename)[ST_MTIME] - except os.error: - return None - -# -# Internal: write cached version of the form (parsing is too slow!) -# -def writecache(filename, forms): - import marshal - fp, filename = _open_formfile2(filename) - fp.close() - cachename = filename + 'c' - try: - fp = open(cachename, 'w') - except IOError: - print 'flp: can\'t create cache file', cachename - return # Never mind - fp.write('\0\0\0\0') # Seek back and write MAGIC when done - wrlong(fp, getmtime(filename)) - altforms = _pack_cache(forms) - marshal.dump(altforms, fp) - fp.seek(0) - fp.write(MAGIC) - fp.close() - #print 'flp: wrote cache file', cachename - -# -# External: print some statements that set up the internal cache. -# This is for use with the "freeze" script. You should call -# flp.freeze(filename) for all forms used by the script, and collect -# the output on a file in a module file named "frozenforms.py". Then -# in the main program of the script import frozenforms. -# (Don't forget to take this out when using the unfrozen version of -# the script!) -# -def freeze(filename): - forms = parse_forms(filename) - altforms = _pack_cache(forms) - print 'import flp' - print 'flp._internal_cache[', `filename`, '] =', altforms - -# -# Internal: create the data structure to be placed in the cache -# -def _pack_cache(forms): - altforms = {} - for name in forms.keys(): - obj, list = forms[name] - altobj = obj.__dict__ - altlist = [] - for obj in list: altlist.append(obj.__dict__) - altforms[name] = altobj, altlist - return altforms - -# -# Internal: Locate form file (using PYTHONPATH) and open file -# -def _open_formfile(filename): - return _open_formfile2(filename)[0] - -def _open_formfile2(filename): - if filename[-3:] <> '.fd': - filename = filename + '.fd' - if filename[0] == '/': - try: - fp = open(filename,'r') - except IOError: - fp = None - else: - for pc in sys.path: - pn = os.path.join(pc, filename) - try: - fp = open(pn, 'r') - filename = pn - break - except IOError: - fp = None - if fp == None: - raise error, 'Cannot find forms file ' + filename - return fp, filename - -# -# Internal: parse the fd file header, return number of forms -# -def _parse_fd_header(file): - # First read the magic header line - datum = _parse_1_line(file) - if datum <> ('Magic', 12321): - raise error, 'Not a forms definition file' - # Now skip until we know number of forms - while 1: - datum = _parse_1_line(file) - if type(datum) == type(()) and datum[0] == 'Numberofforms': - break - return datum[1] -# -# Internal: parse fd form, or skip if name doesn't match. -# the special value None means 'allways parse it'. -# -def _parse_fd_form(file, name): - datum = _parse_1_line(file) - if datum <> FORMLINE: - raise error, 'Missing === FORM === line' - form = _parse_object(file) - if form.Name == name or name == None: - objs = [] - for j in range(form.Numberofobjects): - obj = _parse_object(file) - objs.append(obj) - return (form, objs) - else: - for j in range(form.Numberofobjects): - _skip_object(file) - return None - -# -# Internal class: a convient place to store object info fields -# -class _newobj: - def add(self, name, value): - self.__dict__[name] = value - def make(self, dict): - for name in dict.keys(): - self.add(name, dict[name]) - -# -# Internal parsing routines. -# -def _parse_string(str): - if '\\' in str: - s = '\'' + str + '\'' - try: - return eval(s) - except: - pass - return str - -def _parse_num(str): - return eval(str) - -def _parse_numlist(str): - slist = string.split(str) - nlist = [] - for i in slist: - nlist.append(_parse_num(i)) - return nlist - -# This dictionary maps item names to parsing routines. -# If no routine is given '_parse_num' is default. -_parse_func = { \ - 'Name': _parse_string, \ - 'Box': _parse_numlist, \ - 'Colors': _parse_numlist, \ - 'Label': _parse_string, \ - 'Name': _parse_string, \ - 'Callback': _parse_string, \ - 'Argument': _parse_string } - -# This function parses a line, and returns either -# a string or a tuple (name,value) - -import regex -prog = regex.compile('^\([^:]*\): *\(.*\)') - -def _parse_line(line): - if prog.match(line) < 0: - return line - a = prog.regs - name = line[:a[1][1]] - if name[0] == 'N': - name = string.joinfields(string.split(name),'') - name = string.lower(name) - name = string.upper(name[0]) + name[1:] - value = line[a[2][0]:] - try: - pf = _parse_func[name] - except KeyError: - pf = _parse_num - value = pf(value) - return (name, value) - -def _readline(file): - line = file.readline() - if not line: - raise EOFError - return line[:-1] - -def _parse_1_line(file): - line = _readline(file) - while line == '': - line = _readline(file) - return _parse_line(line) - -def _skip_object(file): - line = '' - while not line in (SPLITLINE, FORMLINE, ENDLINE): - pos = file.tell() - line = _readline(file) - if line == FORMLINE: - file.seek(pos) - -def _parse_object(file): - obj = _newobj() - while 1: - pos = file.tell() - datum = _parse_1_line(file) - if datum in (SPLITLINE, FORMLINE, ENDLINE): - if datum == FORMLINE: - file.seek(pos) - return obj - if type(datum) <> type(()) or len(datum) <> 2: - raise error, 'Parse error, illegal line in object: '+datum - obj.add(datum[0], datum[1]) - -################################################################# -# Part 2 - High-level object/form creation routines # -################################################################# - -# -# External - Create a form an link to an instance variable. -# -def create_full_form(inst, (fdata, odatalist)): - form = create_form(fdata) - exec 'inst.'+fdata.Name+' = form\n' - for odata in odatalist: - create_object_instance(inst, form, odata) - -# -# External - Merge a form into an existing form in an instance -# variable. -# -def merge_full_form(inst, form, (fdata, odatalist)): - exec 'inst.'+fdata.Name+' = form\n' - if odatalist[0].Class <> FL.BOX: - raise error, 'merge_full_form() expects FL.BOX as first obj' - for odata in odatalist[1:]: - create_object_instance(inst, form, odata) - - -################################################################# -# Part 3 - Low-level object/form creation routines # -################################################################# - -# -# External Create_form - Create form from parameters -# -def create_form(fdata): - import fl - return fl.make_form(FL.NO_BOX, fdata.Width, fdata.Height) - -# -# External create_object - Create an object. Make sure there are -# no callbacks. Returns the object created. -# -def create_object(form, odata): - obj = _create_object(form, odata) - if odata.Callback: - raise error, 'Creating free object with callback' - return obj -# -# External create_object_instance - Create object in an instance. -# -def create_object_instance(inst, form, odata): - obj = _create_object(form, odata) - if odata.Callback: - cbfunc = eval('inst.'+odata.Callback) - obj.set_call_back(cbfunc, odata.Argument) - if odata.Name: - exec 'inst.' + odata.Name + ' = obj\n' -# -# Internal _create_object: Create the object and fill options -# -def _create_object(form, odata): - crfunc = _select_crfunc(form, odata.Class) - obj = crfunc(odata.Type, odata.Box[0], odata.Box[1], odata.Box[2], \ - odata.Box[3], odata.Label) - if not odata.Class in (FL.BEGIN_GROUP, FL.END_GROUP): - obj.boxtype = odata.Boxtype - obj.col1 = odata.Colors[0] - obj.col2 = odata.Colors[1] - obj.align = odata.Alignment - obj.lstyle = odata.Style - obj.lsize = odata.Size - obj.lcol = odata.Lcol - return obj -# -# Internal crfunc: helper function that returns correct create function -# -def _select_crfunc(fm, cl): - if cl == FL.BEGIN_GROUP: return fm.bgn_group - elif cl == FL.END_GROUP: return fm.end_group - elif cl == FL.BITMAP: return fm.add_bitmap - elif cl == FL.BOX: return fm.add_box - elif cl == FL.BROWSER: return fm.add_browser - elif cl == FL.BUTTON: return fm.add_button - elif cl == FL.CHART: return fm.add_chart - elif cl == FL.CHOICE: return fm.add_choice - elif cl == FL.CLOCK: return fm.add_clock - elif cl == FL.COUNTER: return fm.add_counter - elif cl == FL.DIAL: return fm.add_dial - elif cl == FL.FREE: return fm.add_free - elif cl == FL.INPUT: return fm.add_input - elif cl == FL.LIGHTBUTTON: return fm.add_lightbutton - elif cl == FL.MENU: return fm.add_menu - elif cl == FL.POSITIONER: return fm.add_positioner - elif cl == FL.ROUNDBUTTON: return fm.add_roundbutton - elif cl == FL.SLIDER: return fm.add_slider - elif cl == FL.VALSLIDER: return fm.add_valslider - elif cl == FL.TEXT: return fm.add_text - elif cl == FL.TIMER: return fm.add_timer - else: - raise error, 'Unknown object type: ' + `cl` - - -def test(): - import time - t0 = time.time() - if len(sys.argv) == 2: - forms = parse_forms(sys.argv[1]) - t1 = time.time() - print 'parse time:', 0.001*(t1-t0), 'sec.' - keys = forms.keys() - keys.sort() - for i in keys: - _printform(forms[i]) - elif len(sys.argv) == 3: - form = parse_form(sys.argv[1], sys.argv[2]) - t1 = time.time() - print 'parse time:', round(t1-t0, 3), 'sec.' - _printform(form) - else: - print 'Usage: test fdfile [form]' - -def _printform(form): - f = form[0] - objs = form[1] - print 'Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects - for i in objs: - print ' Obj ', i.Name, ' type ', i.Class, i.Type - print ' Box ', i.Box, ' btype ', i.Boxtype - print ' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment - print ' cols ', i.Colors - print ' cback ', i.Callback, i.Argument - -# Local variables: -# py-indent-offset: 4 -# end: diff --git a/Lib/irix5/jpeg.py b/Lib/irix5/jpeg.py deleted file mode 100755 index 85d6d837d1..0000000000 --- a/Lib/irix5/jpeg.py +++ /dev/null @@ -1,110 +0,0 @@ -# Implement 'jpeg' interface using SGI's compression library - -# XXX Options 'smooth' and 'optimize' are ignored. - -# XXX It appears that compressing grayscale images doesn't work right; -# XXX the resulting file causes weirdness. - -error = 'jpeg.error' # Exception - -options = {'quality': 75, 'optimize': 0, 'smooth': 0, 'forcegray': 0} - -comp = None -decomp = None - -def compress(imgdata, width, height, bytesperpixel): - global comp - import cl, CL - if comp is None: comp = cl.OpenCompressor(CL.JPEG) - if bytesperpixel == 1: - format = CL.GRAYSCALE - elif bytesperpixel == 4: - format = CL.RGBX - if options['forcegray']: - iformat = CL.GRAYSCALE - else: - iformat = CL.YUV - # XXX How to support 'optimize'? - params = [CL.IMAGE_WIDTH, width, CL.IMAGE_HEIGHT, height, \ - CL.ORIGINAL_FORMAT, format, \ - CL.ORIENTATION, CL.BOTTOM_UP, \ - CL.QUALITY_FACTOR, options['quality'], \ - CL.INTERNAL_FORMAT, iformat, \ - ] - comp.SetParams(params) - jpegdata = comp.Compress(1, imgdata) - return jpegdata - -def decompress(jpegdata): - global decomp - import cl, CL - if decomp is None: decomp = cl.OpenDecompressor(CL.JPEG) - headersize = decomp.ReadHeader(jpegdata) - params = [CL.IMAGE_WIDTH, 0, CL.IMAGE_HEIGHT, 0, CL.INTERNAL_FORMAT, 0] - decomp.GetParams(params) - width, height, format = params[1], params[3], params[5] - if format == CL.GRAYSCALE or options['forcegray']: - format = CL.GRAYSCALE - bytesperpixel = 1 - else: - format = CL.RGBX - bytesperpixel = 4 - # XXX How to support 'smooth'? - params = [CL.ORIGINAL_FORMAT, format, \ - CL.ORIENTATION, CL.BOTTOM_UP, \ - CL.FRAME_BUFFER_SIZE, width*height*bytesperpixel] - decomp.SetParams(params) - imgdata = decomp.Decompress(1, jpegdata) - return imgdata, width, height, bytesperpixel - -def setoption(name, value): - if type(value) <> type(0): - raise TypeError, 'jpeg.setoption: numeric options only' - if name == 'forcegrey': - name = 'forcegray' - if not options.has_key(name): - raise KeyError, 'jpeg.setoption: unknown option name' - options[name] = int(value) - -def test(): - import sys - if sys.argv[1:2] == ['-g']: - del sys.argv[1] - setoption('forcegray', 1) - if not sys.argv[1:]: - sys.argv.append('/usr/local/images/data/jpg/asterix.jpg') - for file in sys.argv[1:]: - show(file) - -def show(file): - import gl, GL, DEVICE - jpegdata = open(file, 'r').read() - imgdata, width, height, bytesperpixel = decompress(jpegdata) - gl.foreground() - gl.prefsize(width, height) - win = gl.winopen(file) - if bytesperpixel == 1: - gl.cmode() - gl.pixmode(GL.PM_SIZE, 8) - gl.gconfig() - for i in range(256): - gl.mapcolor(i, i, i, i) - else: - gl.RGBmode() - gl.pixmode(GL.PM_SIZE, 32) - gl.gconfig() - gl.qdevice(DEVICE.REDRAW) - gl.qdevice(DEVICE.ESCKEY) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.lrectwrite(0, 0, width-1, height-1, imgdata) - while 1: - dev, val = gl.qread() - if dev in (DEVICE.ESCKEY, DEVICE.WINSHUT, DEVICE.WINQUIT): - break - if dev == DEVICE.REDRAW: - gl.lrectwrite(0, 0, width-1, height-1, imgdata) - gl.winclose(win) - # Now test the compression and write the result to a fixed filename - newjpegdata = compress(imgdata, width, height, bytesperpixel) - open('/tmp/j.jpg', 'w').write(newjpegdata) diff --git a/Lib/irix5/panel.py b/Lib/irix5/panel.py deleted file mode 100755 index 2c0365c6ce..0000000000 --- a/Lib/irix5/panel.py +++ /dev/null @@ -1,281 +0,0 @@ -# Module 'panel' -# -# Support for the Panel library. -# Uses built-in module 'pnl'. -# Applciations should use 'panel.function' instead of 'pnl.function'; -# most 'pnl' functions are transparently exported by 'panel', -# but dopanel() is overridden and you have to use this version -# if you want to use callbacks. - - -import pnl - - -debug = 0 - - -# Test if an object is a list. -# -def is_list(x): - return type(x) == type([]) - - -# Reverse a list. -# -def reverse(list): - res = [] - for item in list: - res.insert(0, item) - return res - - -# Get an attribute of a list, which may itself be another list. -# Don't use 'prop' for name. -# -def getattrlist(list, name): - for item in list: - if item and is_list(item) and item[0] == name: - return item[1:] - return [] - - -# Get a property of a list, which may itself be another list. -# -def getproplist(list, name): - for item in list: - if item and is_list(item) and item[0] == 'prop': - if len(item) > 1 and item[1] == name: - return item[2:] - return [] - - -# Test if an actuator description contains the property 'end-of-group' -# -def is_endgroup(list): - x = getproplist(list, 'end-of-group') - return (x and x[0] == '#t') - - -# Neatly display an actuator definition given as S-expression -# the prefix string is printed before each line. -# -def show_actuator(prefix, a): - for item in a: - if not is_list(item): - print prefix, item - elif item and item[0] == 'al': - print prefix, 'Subactuator list:' - for a in item[1:]: - show_actuator(prefix + ' ', a) - elif len(item) == 2: - print prefix, item[0], '=>', item[1] - elif len(item) == 3 and item[0] == 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] - else: - print prefix, '?', item - - -# Neatly display a panel. -# -def show_panel(prefix, p): - for item in p: - if not is_list(item): - print prefix, item - elif item and item[0] == 'al': - print prefix, 'Actuator list:' - for a in item[1:]: - show_actuator(prefix + ' ', a) - elif len(item) == 2: - print prefix, item[0], '=>', item[1] - elif len(item) == 3 and item[0] == 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] - else: - print prefix, '?', item - - -# Exception raised by build_actuator or build_panel. -# -panel_error = 'panel error' - - -# Dummy callback used to initialize the callbacks. -# -def dummy_callback(arg): - pass - - -# Assign attributes to members of the target. -# Attribute names in exclist are ignored. -# The member name is the attribute name prefixed with the prefix. -# -def assign_members(target, attrlist, exclist, prefix): - for item in attrlist: - if is_list(item) and len(item) == 2 and item[0] not in exclist: - name, value = item[0], item[1] - ok = 1 - if value[0] in '-0123456789': - value = eval(value) - elif value[0] == '"': - value = value[1:-1] - elif value == 'move-then-resize': - # Strange default set by Panel Editor... - ok = 0 - else: - print 'unknown value', value, 'for', name - ok = 0 - if ok: - lhs = 'target.' + prefix + name - stmt = lhs + '=' + `value` - if debug: print 'exec', stmt - try: - exec stmt + '\n' - except KeyboardInterrupt: # Don't catch this! - raise KeyboardInterrupt - except: - print 'assign failed:', stmt - - -# Build a real actuator from an actuator descriptior. -# Return a pair (actuator, name). -# -def build_actuator(descr): - namelist = getattrlist(descr, 'name') - if namelist: - # Assume it is a string - actuatorname = namelist[0][1:-1] - else: - actuatorname = '' - type = descr[0] - if type[:4] == 'pnl_': type = type[4:] - act = pnl.mkact(type) - act.downfunc = act.activefunc = act.upfunc = dummy_callback - # - assign_members(act, descr[1:], ['al', 'data', 'name'], '') - # - # Treat actuator-specific data - # - datalist = getattrlist(descr, 'data') - prefix = '' - if type[-4:] == 'puck': - prefix = 'puck_' - elif type == 'mouse': - prefix = 'mouse_' - assign_members(act, datalist, [], prefix) - # - return act, actuatorname - - -# Build all sub-actuators and add them to the super-actuator. -# The super-actuator must already have been added to the panel. -# Sub-actuators with defined names are added as members to the panel -# so they can be referenced as p.name. -# -# Note: I have no idea how panel.endgroup() works when applied -# to a sub-actuator. -# -def build_subactuators(panel, super_act, al): - # - # This is nearly the same loop as below in build_panel(), - # except a call is made to addsubact() instead of addact(). - # - for a in al: - act, name = build_actuator(a) - act.addsubact(super_act) - if name: - stmt = 'panel.' + name + ' = act' - if debug: print 'exec', stmt - exec stmt + '\n' - if is_endgroup(a): - panel.endgroup() - sub_al = getattrlist(a, 'al') - if sub_al: - build_subactuators(panel, act, sub_al) - # - # Fix the actuator to which whe just added subactuators. - # This can't hurt (I hope) and is needed for the scroll actuator. - # - super_act.fixact() - - -# Build a real panel from a panel definition. -# Return a panel object p, where for each named actuator a, p.name is a -# reference to a. -# -def build_panel(descr): - # - # Sanity check - # - if (not descr) or descr[0] <> 'panel': - raise panel_error, 'panel description must start with "panel"' - # - if debug: show_panel('', descr) - # - # Create an empty panel - # - panel = pnl.mkpanel() - # - # Assign panel attributes - # - assign_members(panel, descr[1:], ['al'], '') - # - # Look for actuator list - # - al = getattrlist(descr, 'al') - # - # The order in which actuators are created is important - # because of the endgroup() operator. - # Unfortunately the Panel Editor outputs the actuator list - # in reverse order, so we reverse it here. - # - al = reverse(al) - # - for a in al: - act, name = build_actuator(a) - act.addact(panel) - if name: - stmt = 'panel.' + name + ' = act' - exec stmt + '\n' - if is_endgroup(a): - panel.endgroup() - sub_al = getattrlist(a, 'al') - if sub_al: - build_subactuators(panel, act, sub_al) - # - return panel - - -# Wrapper around pnl.dopanel() which calls call-back functions. -# -def my_dopanel(): - # Extract only the first 4 elements to allow for future expansion - a, down, active, up = pnl.dopanel()[:4] - if down: - down.downfunc(down) - if active: - active.activefunc(active) - if up: - up.upfunc(up) - return a - - -# Create one or more panels from a description file (S-expressions) -# generated by the Panel Editor. -# -def defpanellist(file): - import panelparser - descrlist = panelparser.parse_file(open(file, 'r')) - panellist = [] - for descr in descrlist: - panellist.append(build_panel(descr)) - return panellist - - -# Import everything from built-in method pnl, so the user can always -# use panel.foo() instead of pnl.foo(). -# This gives *no* performance penalty once this module is imported. -# -from pnl import * # for export - -dopanel = my_dopanel # override pnl.dopanel diff --git a/Lib/irix5/panelparser.py b/Lib/irix5/panelparser.py deleted file mode 100755 index 1b069fa075..0000000000 --- a/Lib/irix5/panelparser.py +++ /dev/null @@ -1,128 +0,0 @@ -# Module 'parser' -# -# Parse S-expressions output by the Panel Editor -# (which is written in Scheme so it can't help writing S-expressions). -# -# See notes at end of file. - - -whitespace = ' \t\n' -operators = '()\'' -separators = operators + whitespace + ';' + '"' - - -# Tokenize a string. -# Return a list of tokens (strings). -# -def tokenize_string(s): - tokens = [] - while s: - c = s[:1] - if c in whitespace: - s = s[1:] - elif c == ';': - s = '' - elif c == '"': - n = len(s) - i = 1 - while i < n: - c = s[i] - i = i+1 - if c == '"': break - if c == '\\': i = i+1 - tokens.append(s[:i]) - s = s[i:] - elif c in operators: - tokens.append(c) - s = s[1:] - else: - n = len(s) - i = 1 - while i < n: - if s[i] in separators: break - i = i+1 - tokens.append(s[:i]) - s = s[i:] - return tokens - - -# Tokenize a whole file (given as file object, not as file name). -# Return a list of tokens (strings). -# -def tokenize_file(fp): - tokens = [] - while 1: - line = fp.readline() - if not line: break - tokens = tokens + tokenize_string(line) - return tokens - - -# Exception raised by parse_exr. -# -syntax_error = 'syntax error' - - -# Parse an S-expression. -# Input is a list of tokens as returned by tokenize_*(). -# Return a pair (expr, tokens) -# where expr is a list representing the s-expression, -# and tokens contains the remaining tokens. -# May raise syntax_error. -# -def parse_expr(tokens): - if (not tokens) or tokens[0] <> '(': - raise syntax_error, 'expected "("' - tokens = tokens[1:] - expr = [] - while 1: - if not tokens: - raise syntax_error, 'missing ")"' - if tokens[0] == ')': - return expr, tokens[1:] - elif tokens[0] == '(': - subexpr, tokens = parse_expr(tokens) - expr.append(subexpr) - else: - expr.append(tokens[0]) - tokens = tokens[1:] - - -# Parse a file (given as file object, not as file name). -# Return a list of parsed S-expressions found at the top level. -# -def parse_file(fp): - tokens = tokenize_file(fp) - exprlist = [] - while tokens: - expr, tokens = parse_expr(tokens) - exprlist.append(expr) - return exprlist - - -# EXAMPLE: -# -# The input -# '(hip (hop hur-ray))' -# -# passed to tokenize_string() returns the token list -# ['(', 'hip', '(', 'hop', 'hur-ray', ')', ')'] -# -# When this is passed to parse_expr() it returns the expression -# ['hip', ['hop', 'hur-ray']] -# plus an empty token list (because there are no tokens left. -# -# When a file containing the example is passed to parse_file() it returns -# a list whose only element is the output of parse_expr() above: -# [['hip', ['hop', 'hur-ray']]] - - -# TOKENIZING: -# -# Comments start with semicolon (;) and continue till the end of the line. -# -# Tokens are separated by whitespace, except the following characters -# always form a separate token (outside strings): -# ( ) ' -# Strings are enclosed in double quotes (") and backslash (\) is used -# as escape character in strings. diff --git a/Lib/irix5/readcd.doc b/Lib/irix5/readcd.doc deleted file mode 100755 index 1be549c790..0000000000 --- a/Lib/irix5/readcd.doc +++ /dev/null @@ -1,104 +0,0 @@ -Interface to CD-ROM player. - -This module implements an interface to the built-in cd module. The -intention is to provide a more user-friendly interface than the -built-in module. - -The module defines a class Readcd with several methods. The -initialization of the class will try to open the CD player. This -means that initialization will fail if the CD player is already in -use. A RuntimeError will be raised by the cd module in that case. - -The way to work with this module is as follows. The user specifies -the parts of the CD that are to be read and he specifies callback -functions which are to be called by the system. At some point he can -tell the system to play. The specified parts of the CD will then be -read and the callbacks will be called. - -Initialization. -=============== - -r = readcd.Readcd([cd-player [, mode]]) - -The optional arguments are the name of the CD device and the mode. -When "mode" is not specified, it defaults to 'r' (which is the only -possible value); when "cd-player" also isn't specified, it defaults -to "None" which indicates the default CD player. - -Methods. -======== - -eject() -- Eject the CD from the player. - -reset() -- Reset the list of data stretches to be played. - -appendtrack(track) -- Append the specified track to the list of music -stretches. - -appendstretch(first, last) -- Append the stretch from "first" to "last" -to the list of music stretches. Both "first" and "last" can be in one -of four forms. "None": for "first", the beginning of the CD, for -"last" the end of the CD; a single integer: a track number--playing -starts at the beginning of the track or ends at the end of the -specified track; a three-tuple: the absolute time from the start of -the CD in minutes, seconds, frames; a four-tuple: track number and -relative time within the track in minutes, seconds, frames. - -settracks(tracklist) -- The argument is a list of integers. The list -of stretches is set to argument list. The old list is discarded. - -setcallback(type, func, arg) -- Set a callback function for "type". -The function will be called as func(arg, type, data) where "arg" is -the third argument of setcallback, "type" is the type of callback, -"data" is type-dependent data. See the CDsetcallback(3) manual page -for more information. The possible "type" arguments are defined in -the CD module. - -removecallback(type) -- Remove the callback for "type". - -gettrackinfo([tracklist]) -- Return a list of tuples. Each tuple -consists of start and length information of a track. The start and -length information consist of three-tuples with minutes, seconds and -frames. The optional tracklist argument gives a list of interesting -track numbers. If no tracklist is specified, information about all -tracks is returned. - -getstatus() -- Return the status information of the CD. - -play() -- Play the preprogrammed stretches of music from the CD. When -nothing was programmed, the whole CD is played. - -Specifying stretches. -===================== - -There are three methods available to specify a stretch of music to be -played. The easiest way is to use "settracklist(tracklist)" with which -a list of tracks can be specified. "settracklist(tracklist)" is -equivalent to the sequence - reset() - for track in tracklist: - appendtrack(track) - -The next method is "appendtrack(track)" with which a whole track can be -added to the list of music to be played. "appendtrack(track)" is -equivalent to "appendstretch(track, track)". - -The most complete method is "appendstretch(first, last)". Using this -method, it is possible to specify any stretch of music. - -When two consecutive tracks are played, it is possible to choose -whether the pause that may be between the tracks is played as well or -whether the pause should be skipped. When the end of a stretch is -specified using a track number and the next stretch starts at the -beginning of the following track and that was also specified using the -track number (that is, both were specified as integers, not as tuples), -the pause is played. When either value was specified using absolute -time or track-relative time (that is, as three-tuple or as -four-tuple), the pause will not be played. - -Errors. -======= - -When an error occurs, an exception will be raised. Depending on where -the error occurs, the exception may either be "readcd.Error" or -"RuntimeError". diff --git a/Lib/irix5/readcd.py b/Lib/irix5/readcd.py deleted file mode 100755 index 5c4b824250..0000000000 --- a/Lib/irix5/readcd.py +++ /dev/null @@ -1,242 +0,0 @@ -# Class interface to the CD module. - -import cd, CD - -Error = 'Readcd.Error' -_Stop = 'Readcd.Stop' - -def _doatime(self, cb_type, data): - if ((data[0] * 60) + data[1]) * 75 + data[2] > self.end: -## print 'done with list entry',`self.listindex` - raise _Stop - func, arg = self.callbacks[cb_type] - if func: - func(arg, cb_type, data) - -def _dopnum(self, cb_type, data): - if data > self.end: -## print 'done with list entry',`self.listindex` - raise _Stop - func, arg = self.callbacks[cb_type] - if func: - func(arg, cb_type, data) - -class Readcd: - def __init__(self, *arg): - if len(arg) == 0: - self.player = cd.open() - elif len(arg) == 1: - self.player = cd.open(arg[0]) - elif len(arg) == 2: - self.player = cd.open(arg[0], arg[1]) - else: - raise Error, 'bad __init__ call' - self.list = [] - self.callbacks = [(None, None)] * 8 - self.parser = cd.createparser() - self.playing = 0 - self.end = 0 - self.status = None - self.trackinfo = None - - def eject(self): - self.player.eject() - self.list = [] - self.end = 0 - self.listindex = 0 - self.status = None - self.trackinfo = None - if self.playing: -## print 'stop playing from eject' - raise _Stop - - def pmsf2msf(self, track, min, sec, frame): - if not self.status: - self.cachestatus() - if track < self.status[5] or track > self.status[6]: - raise Error, 'track number out of range' - if not self.trackinfo: - self.cacheinfo() - start, total = self.trackinfo[track] - start = ((start[0] * 60) + start[1]) * 75 + start[2] - total = ((total[0] * 60) + total[1]) * 75 + total[2] - block = ((min * 60) + sec) * 75 + frame - if block > total: - raise Error, 'out of range' - block = start + block - min, block = divmod(block, 75*60) - sec, frame = divmod(block, 75) - return min, sec, frame - - def reset(self): - self.list = [] - - def appendtrack(self, track): - self.appendstretch(track, track) - - def appendstretch(self, start, end): - if not self.status: - self.cachestatus() - if not start: - start = 1 - if not end: - end = self.status[6] - if type(end) == type(0): - if end < self.status[5] or end > self.status[6]: - raise Error, 'range error' - else: - l = len(end) - if l == 4: - prog, min, sec, frame = end - if prog < self.status[5] or prog > self.status[6]: - raise Error, 'range error' - end = self.pmsf2msf(prog, min, sec, frame) - elif l <> 3: - raise Error, 'syntax error' - if type(start) == type(0): - if start < self.status[5] or start > self.status[6]: - raise Error, 'range error' - if len(self.list) > 0: - s, e = self.list[-1] - if type(e) == type(0): - if start == e+1: - start = s - del self.list[-1] - else: - l = len(start) - if l == 4: - prog, min, sec, frame = start - if prog < self.status[5] or prog > self.status[6]: - raise Error, 'range error' - start = self.pmsf2msf(prog, min, sec, frame) - elif l <> 3: - raise Error, 'syntax error' - self.list.append((start, end)) - - def settracks(self, list): - self.list = [] - for track in list: - self.appendtrack(track) - - def setcallback(self, cb_type, func, arg): - if cb_type < 0 or cb_type >= 8: - raise Error, 'type out of range' - self.callbacks[cb_type] = (func, arg) - if self.playing: - start, end = self.list[self.listindex] - if type(end) == type(0): - if cb_type <> CD.PNUM: - self.parser.setcallback(cb_type, func, arg) - else: - if cb_type <> CD.ATIME: - self.parser.setcallback(cb_type, func, arg) - - def removecallback(self, cb_type): - if cb_type < 0 or cb_type >= 8: - raise Error, 'type out of range' - self.callbacks[cb_type] = (None, None) - if self.playing: - start, end = self.list[self.listindex] - if type(end) == type(0): - if cb_type <> CD.PNUM: - self.parser.removecallback(cb_type) - else: - if cb_type <> CD.ATIME: - self.parser.removecallback(cb_type) - - def gettrackinfo(self, *arg): - if not self.status: - self.cachestatus() - if not self.trackinfo: - self.cacheinfo() - if len(arg) == 0: - return self.trackinfo[self.status[5]:self.status[6]+1] - result = [] - for i in arg: - if i < self.status[5] or i > self.status[6]: - raise Error, 'range error' - result.append(self.trackinfo[i]) - return result - - def cacheinfo(self): - if not self.status: - self.cachestatus() - self.trackinfo = [] - for i in range(self.status[5]): - self.trackinfo.append(None) - for i in range(self.status[5], self.status[6]+1): - self.trackinfo.append(self.player.gettrackinfo(i)) - - def cachestatus(self): - self.status = self.player.getstatus() - if self.status[0] == CD.NODISC: - self.status = None - raise Error, 'no disc in player' - - def getstatus(self): - return self.player.getstatus() - - def play(self): - if not self.status: - self.cachestatus() - size = self.player.bestreadsize() - self.listindex = 0 - self.playing = 0 - for i in range(8): - func, arg = self.callbacks[i] - if func: - self.parser.setcallback(i, func, arg) - else: - self.parser.removecallback(i) - if len(self.list) == 0: - for i in range(self.status[5], self.status[6]+1): - self.appendtrack(i) - try: - while 1: - if not self.playing: - if self.listindex >= len(self.list): - return - start, end = self.list[self.listindex] - if type(start) == type(0): - dummy = self.player.seektrack( - start) - else: - min, sec, frame = start - dummy = self.player.seek( - min, sec, frame) - if type(end) == type(0): - self.parser.setcallback( - CD.PNUM, _dopnum, self) - self.end = end - func, arg = \ - self.callbacks[CD.ATIME] - if func: - self.parser.setcallback(CD.ATIME, func, arg) - else: - self.parser.removecallback(CD.ATIME) - else: - min, sec, frame = end - self.parser.setcallback( - CD.ATIME, _doatime, - self) - self.end = (min * 60 + sec) * \ - 75 + frame - func, arg = \ - self.callbacks[CD.PNUM] - if func: - self.parser.setcallback(CD.PNUM, func, arg) - else: - self.parser.removecallback(CD.PNUM) - self.playing = 1 - data = self.player.readda(size) - if data == '': - self.playing = 0 - self.listindex = self.listindex + 1 - continue - try: - self.parser.parseframe(data) - except _Stop: - self.playing = 0 - self.listindex = self.listindex + 1 - finally: - self.playing = 0 diff --git a/Lib/irix5/regen b/Lib/irix5/regen deleted file mode 100755 index 13f9d745fd..0000000000 --- a/Lib/irix5/regen +++ /dev/null @@ -1,12 +0,0 @@ -#! /bin/sh -case `uname -sr` in -'IRIX '[45].*) ;; -*) echo Probably not on an IRIX system 1>&2 - exit 1;; -esac -set -v -h2py /usr/include/sys/fcntl.h -h2py /usr/include/sys/socket.h -h2py -i '(u_long)' /usr/include/netinet/in.h -h2py /usr/include/sys/termios.h -h2py /usr/include/errno.h diff --git a/Lib/irix5/torgb.py b/Lib/irix5/torgb.py deleted file mode 100755 index f283063c00..0000000000 --- a/Lib/irix5/torgb.py +++ /dev/null @@ -1,97 +0,0 @@ -# Convert "arbitrary" image files to rgb files (SGI's image format). -# Input may be compressed. -# The uncompressed file type may be PBM, PGM, PPM, GIF, TIFF, or Sun raster. -# An exception is raised if the file is not of a recognized type. -# Returned filename is either the input filename or a temporary filename; -# in the latter case the caller must ensure that it is removed. -# Other temporary files used are removed by the function. - -import os -import tempfile -import pipes -import imghdr - -table = {} - -t = pipes.Template() -t.append('fromppm $IN $OUT', 'ff') -table['ppm'] = t - -t = pipes.Template() -t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--') -t.append('fromppm $IN $OUT', 'ff') -table['pnm'] = t -table['pgm'] = t -table['pbm'] = t - -t = pipes.Template() -t.append('fromgif $IN $OUT', 'ff') -table['gif'] = t - -t = pipes.Template() -t.append('tifftopnm', '--') -t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--') -t.append('fromppm $IN $OUT', 'ff') -table['tiff'] = t - -t = pipes.Template() -t.append('rasttopnm', '--') -t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--') -t.append('fromppm $IN $OUT', 'ff') -table['rast'] = t - -t = pipes.Template() -t.append('djpeg', '--') -t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--') -t.append('fromppm $IN $OUT', 'ff') -table['jpeg'] = t - -uncompress = pipes.Template() -uncompress.append('uncompress', '--') - - -error = 'torgb.error' # Exception - -def torgb(filename): - temps = [] - ret = None - try: - ret = _torgb(filename, temps) - finally: - for temp in temps[:]: - if temp <> ret: - try: - os.unlink(temp) - except os.error: - pass - temps.remove(temp) - return ret - -def _torgb(filename, temps): - if filename[-2:] == '.Z': - fname = tempfile.mktemp() - temps.append(fname) - sts = uncompress.copy(filename, fname) - if sts: - raise error, filename + ': uncompress failed' - else: - fname = filename - try: - ftype = imghdr.what(fname) - except IOError, msg: - if type(msg) == type(()) and len(msg) == 2 and \ - type(msg[0]) == type(0) and type(msg[1]) == type(''): - msg = msg[1] - if type(msg) <> type(''): - msg = `msg` - raise error, filename + ': ' + msg - if ftype == 'rgb': - return fname - if ftype == None or not table.has_key(ftype): - raise error, \ - filename + ': unsupported image file type ' + `ftype` - temp = tempfile.mktemp() - sts = table[ftype].copy(fname, temp) - if sts: - raise error, filename + ': conversion to rgb failed' - return temp diff --git a/Lib/lib-old/Para.py b/Lib/lib-old/Para.py deleted file mode 100644 index c9b3bdd1bd..0000000000 --- a/Lib/lib-old/Para.py +++ /dev/null @@ -1,409 +0,0 @@ -# Text formatting abstractions -# Note -- this module is obsolete, it's too slow anyway - - -# Oft-used type object -Int = type(0) - - -# Represent a paragraph. This is a list of words with associated -# font and size information, plus indents and justification for the -# entire paragraph. -# Once the words have been added to a paragraph, it can be laid out -# for different line widths. Once laid out, it can be rendered at -# different screen locations. Once rendered, it can be queried -# for mouse hits, and parts of the text can be highlighted -class Para: - # - def __init__(self): - self.words = [] # The words - self.just = 'l' # Justification: 'l', 'r', 'lr' or 'c' - self.indent_left = self.indent_right = self.indent_hang = 0 - # Final lay-out parameters, may change - self.left = self.top = self.right = self.bottom = \ - self.width = self.height = self.lines = None - # - # Add a word, computing size information for it. - # Words may also be added manually by appending to self.words - # Each word should be a 7-tuple: - # (font, text, width, space, stretch, ascent, descent) - def addword(self, d, font, text, space, stretch): - if font <> None: - d.setfont(font) - width = d.textwidth(text) - ascent = d.baseline() - descent = d.lineheight() - ascent - spw = d.textwidth(' ') - space = space * spw - stretch = stretch * spw - tuple = (font, text, width, space, stretch, ascent, descent) - self.words.append(tuple) - # - # Hooks to begin and end anchors -- insert numbers in the word list! - def bgn_anchor(self, id): - self.words.append(id) - # - def end_anchor(self, id): - self.words.append(0) - # - # Return the total length (width) of the text added so far, in pixels - def getlength(self): - total = 0 - for word in self.words: - if type(word) <> Int: - total = total + word[2] + word[3] - return total - # - # Tab to a given position (relative to the current left indent): - # remove all stretch, add fixed space up to the new indent. - # If the current position is already beying the tab stop, - # don't add any new space (but still remove the stretch) - def tabto(self, tab): - total = 0 - as, de = 1, 0 - for i in range(len(self.words)): - word = self.words[i] - if type(word) == Int: continue - fo, te, wi, sp, st, as, de = word - self.words[i] = fo, te, wi, sp, 0, as, de - total = total + wi + sp - if total < tab: - self.words.append(None, '', 0, tab-total, 0, as, de) - # - # Make a hanging tag: tab to hang, increment indent_left by hang, - # and reset indent_hang to -hang - def makehangingtag(self, hang): - self.tabto(hang) - self.indent_left = self.indent_left + hang - self.indent_hang = -hang - # - # Decide where the line breaks will be given some screen width - def layout(self, linewidth): - self.width = linewidth - height = 0 - self.lines = lines = [] - avail1 = self.width - self.indent_left - self.indent_right - avail = avail1 - self.indent_hang - words = self.words - i = 0 - n = len(words) - lastfont = None - while i < n: - firstfont = lastfont - charcount = 0 - width = 0 - stretch = 0 - ascent = 0 - descent = 0 - lsp = 0 - j = i - while i < n: - word = words[i] - if type(word) == Int: - if word > 0 and width >= avail: - break - i = i+1 - continue - fo, te, wi, sp, st, as, de = word - if width + wi > avail and width > 0 and wi > 0: - break - if fo <> None: - lastfont = fo - if width == 0: - firstfont = fo - charcount = charcount + len(te) + (sp > 0) - width = width + wi + sp - lsp = sp - stretch = stretch + st - lst = st - ascent = max(ascent, as) - descent = max(descent, de) - i = i+1 - while i > j and type(words[i-1]) == Int and \ - words[i-1] > 0: i = i-1 - width = width - lsp - if i < n: - stretch = stretch - lst - else: - stretch = 0 - tuple = i-j, firstfont, charcount, width, stretch, \ - ascent, descent - lines.append(tuple) - height = height + ascent + descent - avail = avail1 - self.height = height - # - # Call a function for all words in a line - def visit(self, wordfunc, anchorfunc): - avail1 = self.width - self.indent_left - self.indent_right - avail = avail1 - self.indent_hang - v = self.top - i = 0 - for tuple in self.lines: - wordcount, firstfont, charcount, width, stretch, \ - ascent, descent = tuple - h = self.left + self.indent_left - if i == 0: h = h + self.indent_hang - extra = 0 - if self.just == 'r': h = h + avail - width - elif self.just == 'c': h = h + (avail - width) / 2 - elif self.just == 'lr' and stretch > 0: - extra = avail - width - v2 = v + ascent + descent - for j in range(i, i+wordcount): - word = self.words[j] - if type(word) == Int: - ok = anchorfunc(self, tuple, word, \ - h, v) - if ok <> None: return ok - continue - fo, te, wi, sp, st, as, de = word - if extra > 0 and stretch > 0: - ex = extra * st / stretch - extra = extra - ex - stretch = stretch - st - else: - ex = 0 - h2 = h + wi + sp + ex - ok = wordfunc(self, tuple, word, h, v, \ - h2, v2, (j==i), (j==i+wordcount-1)) - if ok <> None: return ok - h = h2 - v = v2 - i = i + wordcount - avail = avail1 - # - # Render a paragraph in "drawing object" d, using the rectangle - # given by (left, top, right) with an unspecified bottom. - # Return the computed bottom of the text. - def render(self, d, left, top, right): - if self.width <> right-left: - self.layout(right-left) - self.left = left - self.top = top - self.right = right - self.bottom = self.top + self.height - self.anchorid = 0 - try: - self.d = d - self.visit(self.__class__._renderword, \ - self.__class__._renderanchor) - finally: - self.d = None - return self.bottom - # - def _renderword(self, tuple, word, h, v, h2, v2, isfirst, islast): - if word[0] <> None: self.d.setfont(word[0]) - baseline = v + tuple[5] - self.d.text((h, baseline - word[5]), word[1]) - if self.anchorid > 0: - self.d.line((h, baseline+2), (h2, baseline+2)) - # - def _renderanchor(self, tuple, word, h, v): - self.anchorid = word - # - # Return which anchor(s) was hit by the mouse - def hitcheck(self, mouseh, mousev): - self.mouseh = mouseh - self.mousev = mousev - self.anchorid = 0 - self.hits = [] - self.visit(self.__class__._hitcheckword, \ - self.__class__._hitcheckanchor) - return self.hits - # - def _hitcheckword(self, tuple, word, h, v, h2, v2, isfirst, islast): - if self.anchorid > 0 and h <= self.mouseh <= h2 and \ - v <= self.mousev <= v2: - self.hits.append(self.anchorid) - # - def _hitcheckanchor(self, tuple, word, h, v): - self.anchorid = word - # - # Return whether the given anchor id is present - def hasanchor(self, id): - return id in self.words or -id in self.words - # - # Extract the raw text from the word list, substituting one space - # for non-empty inter-word space, and terminating with '\n' - def extract(self): - text = '' - for w in self.words: - if type(w) <> Int: - word = w[1] - if w[3]: word = word + ' ' - text = text + word - return text + '\n' - # - # Return which character position was hit by the mouse, as - # an offset in the entire text as returned by extract(). - # Return None if the mouse was not in this paragraph - def whereis(self, d, mouseh, mousev): - if mousev < self.top or mousev > self.bottom: - return None - self.mouseh = mouseh - self.mousev = mousev - self.lastfont = None - self.charcount = 0 - try: - self.d = d - return self.visit(self.__class__._whereisword, \ - self.__class__._whereisanchor) - finally: - self.d = None - # - def _whereisword(self, tuple, word, h1, v1, h2, v2, isfirst, islast): - fo, te, wi, sp, st, as, de = word - if fo <> None: self.lastfont = fo - h = h1 - if isfirst: h1 = 0 - if islast: h2 = 999999 - if not (v1 <= self.mousev <= v2 and h1 <= self.mouseh <= h2): - self.charcount = self.charcount + len(te) + (sp > 0) - return - if self.lastfont <> None: - self.d.setfont(self.lastfont) - cc = 0 - for c in te: - cw = self.d.textwidth(c) - if self.mouseh <= h + cw/2: - return self.charcount + cc - cc = cc+1 - h = h+cw - self.charcount = self.charcount + cc - if self.mouseh <= (h+h2) / 2: - return self.charcount - else: - return self.charcount + 1 - # - def _whereisanchor(self, tuple, word, h, v): - pass - # - # Return screen position corresponding to position in paragraph. - # Return tuple (h, vtop, vbaseline, vbottom). - # This is more or less the inverse of whereis() - def screenpos(self, d, pos): - if pos < 0: - ascent, descent = self.lines[0][5:7] - return self.left, self.top, self.top + ascent, \ - self.top + ascent + descent - self.pos = pos - self.lastfont = None - try: - self.d = d - ok = self.visit(self.__class__._screenposword, \ - self.__class__._screenposanchor) - finally: - self.d = None - if ok == None: - ascent, descent = self.lines[-1][5:7] - ok = self.right, self.bottom - ascent - descent, \ - self.bottom - descent, self.bottom - return ok - # - def _screenposword(self, tuple, word, h1, v1, h2, v2, isfirst, islast): - fo, te, wi, sp, st, as, de = word - if fo <> None: self.lastfont = fo - cc = len(te) + (sp > 0) - if self.pos > cc: - self.pos = self.pos - cc - return - if self.pos < cc: - self.d.setfont(self.lastfont) - h = h1 + self.d.textwidth(te[:self.pos]) - else: - h = h2 - ascent, descent = tuple[5:7] - return h, v1, v1+ascent, v2 - # - def _screenposanchor(self, tuple, word, h, v): - pass - # - # Invert the stretch of text between pos1 and pos2. - # If pos1 is None, the beginning is implied; - # if pos2 is None, the end is implied. - # Undoes its own effect when called again with the same arguments - def invert(self, d, pos1, pos2): - if pos1 == None: - pos1 = self.left, self.top, self.top, self.top - else: - pos1 = self.screenpos(d, pos1) - if pos2 == None: - pos2 = self.right, self.bottom,self.bottom,self.bottom - else: - pos2 = self.screenpos(d, pos2) - h1, top1, baseline1, bottom1 = pos1 - h2, top2, baseline2, bottom2 = pos2 - if bottom1 <= top2: - d.invert((h1, top1), (self.right, bottom1)) - h1 = self.left - if bottom1 < top2: - d.invert((h1, bottom1), (self.right, top2)) - top1, bottom1 = top2, bottom2 - d.invert((h1, top1), (h2, bottom2)) - - -# Test class Para -# XXX This was last used on the Mac, hence the weird fonts... -def test(): - import stdwin - from stdwinevents import * - words = 'The', 'quick', 'brown', 'fox', 'jumps', 'over', \ - 'the', 'lazy', 'dog.' - paralist = [] - for just in 'l', 'r', 'lr', 'c': - p = Para() - p.just = just - p.addword(stdwin, ('New York', 'p', 12), words[0], 1, 1) - for word in words[1:-1]: - p.addword(stdwin, None, word, 1, 1) - p.addword(stdwin, None, words[-1], 2, 4) - p.addword(stdwin, ('New York', 'b', 18), 'Bye!', 0, 0) - p.addword(stdwin, ('New York', 'p', 10), 'Bye!', 0, 0) - paralist.append(p) - window = stdwin.open('Para.test()') - start = stop = selpara = None - while 1: - etype, win, detail = stdwin.getevent() - if etype == WE_CLOSE: - break - if etype == WE_SIZE: - window.change((0, 0), (1000, 1000)) - if etype == WE_DRAW: - width, height = window.getwinsize() - d = None - try: - d = window.begindrawing() - d.cliprect(detail) - d.erase(detail) - v = 0 - for p in paralist: - v = p.render(d, 0, v, width) - if p == selpara and \ - start <> None and stop <> None: - p.invert(d, start, stop) - finally: - if d: d.close() - if etype == WE_MOUSE_DOWN: - if selpara and start <> None and stop <> None: - d = window.begindrawing() - selpara.invert(d, start, stop) - d.close() - start = stop = selpara = None - mouseh, mousev = detail[0] - for p in paralist: - start = p.whereis(stdwin, mouseh, mousev) - if start <> None: - selpara = p - break - if etype == WE_MOUSE_UP and start <> None and selpara: - mouseh, mousev = detail[0] - stop = selpara.whereis(stdwin, mouseh, mousev) - if stop == None: start = selpara = None - else: - if start > stop: - start, stop = stop, start - d = window.begindrawing() - selpara.invert(d, start, stop) - d.close() - window.close() diff --git a/Lib/lib-old/addpack.py b/Lib/lib-old/addpack.py deleted file mode 100644 index 3d09236ba9..0000000000 --- a/Lib/lib-old/addpack.py +++ /dev/null @@ -1,67 +0,0 @@ -# This module provides standard support for "packages". -# -# The idea is that large groups of related modules can be placed in -# their own subdirectory, which can be added to the Python search path -# in a relatively easy way. -# -# The current version takes a package name and searches the Python -# search path for a directory by that name, and if found adds it to -# the module search path (sys.path). It maintains a list of packages -# that have already been added so adding the same package many times -# is OK. -# -# It is intended to be used in a fairly stylized manner: each module -# that wants to use a particular package, say 'Foo', is supposed to -# contain the following code: -# -# from addpack import addpack -# addpack('Foo') -# <import modules from package Foo> -# -# Additional arguments, when present, provide additional places where -# to look for the package before trying sys.path (these may be either -# strings or lists/tuples of strings). Also, if the package name is a -# full pathname, first the last component is tried in the usual way, -# then the full pathname is tried last. If the package name is a -# *relative* pathname (UNIX: contains a slash but doesn't start with -# one), then nothing special is done. The packages "/foo/bar/bletch" -# and "bletch" are considered the same, but unrelated to "bar/bletch". -# -# If the algorithm finds more than one suitable subdirectory, all are -# added to the search path -- this makes it possible to override part -# of a package. The same path will not be added more than once. -# -# If no directory is found, ImportError is raised. - -_packs = {} # {pack: [pathname, ...], ...} - -def addpack(pack, *locations): - import os - if os.path.isabs(pack): - base = os.path.basename(pack) - else: - base = pack - if _packs.has_key(base): - return - import sys - path = [] - for loc in _flatten(locations) + sys.path: - fn = os.path.join(loc, base) - if fn not in path and os.path.isdir(fn): - path.append(fn) - if pack != base and pack not in path and os.path.isdir(pack): - path.append(pack) - if not path: raise ImportError, 'package ' + pack + ' not found' - _packs[base] = path - for fn in path: - if fn not in sys.path: - sys.path.append(fn) - -def _flatten(locations): - locs = [] - for loc in locations: - if type(loc) == type(''): - locs.append(loc) - else: - locs = locs + _flatten(loc) - return locs diff --git a/Lib/lib-old/codehack.py b/Lib/lib-old/codehack.py deleted file mode 100644 index 1f16814224..0000000000 --- a/Lib/lib-old/codehack.py +++ /dev/null @@ -1,67 +0,0 @@ -# A subroutine for extracting a function name from a code object -# (with cache) - -import sys -from stat import * -import string -import os -import linecache - -# XXX The functions getcodename() and getfuncname() are now obsolete -# XXX as code and function objects now have a name attribute -- -# XXX co.co_name and f.func_name. - -# Extract the function or class name from a code object. -# This is a bit of a hack, since a code object doesn't contain -# the name directly. So what do we do: -# - get the filename (which *is* in the code object) -# - look in the code string to find the first SET_LINENO instruction -# (this must be the first instruction) -# - get the line from the file -# - if the line starts with 'class' or 'def' (after possible whitespace), -# extract the following identifier -# -# This breaks apart when the function was read from <stdin> -# or constructed by exec(), when the file is not accessible, -# and also when the file has been modified or when a line is -# continued with a backslash before the function or class name. -# -# Because this is a pretty expensive hack, a cache is kept. - -SET_LINENO = 127 # The opcode (see "opcode.h" in the Python source) -identchars = string.letters + string.digits + '_' # Identifier characters - -_namecache = {} # The cache - -def getcodename(co): - key = `co` # arbitrary but uniquely identifying string - if _namecache.has_key(key): return _namecache[key] - filename = co.co_filename - code = co.co_code - name = '' - if ord(code[0]) == SET_LINENO: - lineno = ord(code[1]) | ord(code[2]) << 8 - line = linecache.getline(filename, lineno) - words = string.split(line) - if len(words) >= 2 and words[0] in ('def', 'class'): - name = words[1] - for i in range(len(name)): - if name[i] not in identchars: - name = name[:i] - break - _namecache[key] = name - return name - -# Use the above routine to find a function's name. - -def getfuncname(func): - return getcodename(func.func_code) - -# A part of the above code to extract just the line number from a code object. - -def getlineno(co): - code = co.co_code - if ord(code[0]) == SET_LINENO: - return ord(code[1]) | ord(code[2]) << 8 - else: - return -1 diff --git a/Lib/lib-old/dump.py b/Lib/lib-old/dump.py deleted file mode 100644 index ec895b7e07..0000000000 --- a/Lib/lib-old/dump.py +++ /dev/null @@ -1,63 +0,0 @@ -# Module 'dump' -# -# Print python code that reconstructs a variable. -# This only works in certain cases. -# -# It works fine for: -# - ints and floats (except NaNs and other weird things) -# - strings -# - compounds and lists, provided it works for all their elements -# - imported modules, provided their name is the module name -# -# It works for top-level dictionaries but not for dictionaries -# contained in other objects (could be made to work with some hassle -# though). -# -# It does not work for functions (all sorts), classes, class objects, -# windows, files etc. -# -# Finally, objects referenced by more than one name or contained in more -# than one other object lose their sharing property (this is bad for -# strings used as exception identifiers, for instance). - -# Dump a whole symbol table -# -def dumpsymtab(dict): - for key in dict.keys(): - dumpvar(key, dict[key]) - -# Dump a single variable -# -def dumpvar(name, x): - import sys - t = type(x) - if t == type({}): - print name, '= {}' - for key in x.keys(): - item = x[key] - if not printable(item): - print '#', - print name, '[', `key`, '] =', `item` - elif t in (type(''), type(0), type(0.0), type([]), type(())): - if not printable(x): - print '#', - print name, '=', `x` - elif t == type(sys): - print 'import', name, '#', x - else: - print '#', name, '=', x - -# check if a value is printable in a way that can be read back with input() -# -def printable(x): - t = type(x) - if t in (type(''), type(0), type(0.0)): - return 1 - if t in (type([]), type(())): - for item in x: - if not printable(item): - return 0 - return 1 - if x == {}: - return 1 - return 0 diff --git a/Lib/lib-old/find.py b/Lib/lib-old/find.py deleted file mode 100644 index ccd9fdb965..0000000000 --- a/Lib/lib-old/find.py +++ /dev/null @@ -1,26 +0,0 @@ -import fnmatch -import os - -_debug = 0 - -_prune = ['(*)'] - -def find(pattern, dir = os.curdir): - list = [] - names = os.listdir(dir) - names.sort() - for name in names: - if name in (os.curdir, os.pardir): - continue - fullname = os.path.join(dir, name) - if fnmatch.fnmatch(name, pattern): - list.append(fullname) - if os.path.isdir(fullname) and not os.path.islink(fullname): - for p in _prune: - if fnmatch.fnmatch(name, p): - if _debug: print "skip", `fullname` - break - else: - if _debug: print "descend into", `fullname` - list = list + find(pattern, fullname) - return list diff --git a/Lib/lib-old/fmt.py b/Lib/lib-old/fmt.py deleted file mode 100644 index 4a655e4c90..0000000000 --- a/Lib/lib-old/fmt.py +++ /dev/null @@ -1,622 +0,0 @@ -# Text formatting abstractions -# Note -- this module is obsolete, it's too slow anyway - - -import string -import Para - - -# A formatter back-end object has one method that is called by the formatter: -# addpara(p), where p is a paragraph object. For example: - - -# Formatter back-end to do nothing at all with the paragraphs -class NullBackEnd: - # - def __init__(self): - pass - # - def addpara(self, p): - pass - # - def bgn_anchor(self, id): - pass - # - def end_anchor(self, id): - pass - - -# Formatter back-end to collect the paragraphs in a list -class SavingBackEnd(NullBackEnd): - # - def __init__(self): - self.paralist = [] - # - def addpara(self, p): - self.paralist.append(p) - # - def hitcheck(self, h, v): - hits = [] - for p in self.paralist: - if p.top <= v <= p.bottom: - for id in p.hitcheck(h, v): - if id not in hits: - hits.append(id) - return hits - # - def extract(self): - text = '' - for p in self.paralist: - text = text + (p.extract()) - return text - # - def extractpart(self, long1, long2): - if long1 > long2: long1, long2 = long2, long1 - para1, pos1 = long1 - para2, pos2 = long2 - text = '' - while para1 < para2: - ptext = self.paralist[para1].extract() - text = text + ptext[pos1:] - pos1 = 0 - para1 = para1 + 1 - ptext = self.paralist[para2].extract() - return text + ptext[pos1:pos2] - # - def whereis(self, d, h, v): - total = 0 - for i in range(len(self.paralist)): - p = self.paralist[i] - result = p.whereis(d, h, v) - if result <> None: - return i, result - return None - # - def roundtowords(self, long1, long2): - i, offset = long1 - text = self.paralist[i].extract() - while offset > 0 and text[offset-1] <> ' ': offset = offset-1 - long1 = i, offset - # - i, offset = long2 - text = self.paralist[i].extract() - n = len(text) - while offset < n-1 and text[offset] <> ' ': offset = offset+1 - long2 = i, offset - # - return long1, long2 - # - def roundtoparagraphs(self, long1, long2): - long1 = long1[0], 0 - long2 = long2[0], len(self.paralist[long2[0]].extract()) - return long1, long2 - - -# Formatter back-end to send the text directly to the drawing object -class WritingBackEnd(NullBackEnd): - # - def __init__(self, d, width): - self.d = d - self.width = width - self.lineno = 0 - # - def addpara(self, p): - self.lineno = p.render(self.d, 0, self.lineno, self.width) - - -# A formatter receives a stream of formatting instructions and assembles -# these into a stream of paragraphs on to a back-end. The assembly is -# parametrized by a text measurement object, which must match the output -# operations of the back-end. The back-end is responsible for splitting -# paragraphs up in lines of a given maximum width. (This is done because -# in a windowing environment, when the window size changes, there is no -# need to redo the assembly into paragraphs, but the splitting into lines -# must be done taking the new window size into account.) - - -# Formatter base class. Initialize it with a text measurement object, -# which is used for text measurements, and a back-end object, -# which receives the completed paragraphs. The formatting methods are: -# setfont(font) -# setleftindent(nspaces) -# setjust(type) where type is 'l', 'c', 'r', or 'lr' -# flush() -# vspace(nlines) -# needvspace(nlines) -# addword(word, nspaces) -class BaseFormatter: - # - def __init__(self, d, b): - # Drawing object used for text measurements - self.d = d - # - # BackEnd object receiving completed paragraphs - self.b = b - # - # Parameters of the formatting model - self.leftindent = 0 - self.just = 'l' - self.font = None - self.blanklines = 0 - # - # Parameters derived from the current font - self.space = d.textwidth(' ') - self.line = d.lineheight() - self.ascent = d.baseline() - self.descent = self.line - self.ascent - # - # Parameter derived from the default font - self.n_space = self.space - # - # Current paragraph being built - self.para = None - self.nospace = 1 - # - # Font to set on the next word - self.nextfont = None - # - def newpara(self): - return Para.Para() - # - def setfont(self, font): - if font == None: return - self.font = self.nextfont = font - d = self.d - d.setfont(font) - self.space = d.textwidth(' ') - self.line = d.lineheight() - self.ascent = d.baseline() - self.descent = self.line - self.ascent - # - def setleftindent(self, nspaces): - self.leftindent = int(self.n_space * nspaces) - if self.para: - hang = self.leftindent - self.para.indent_left - if hang > 0 and self.para.getlength() <= hang: - self.para.makehangingtag(hang) - self.nospace = 1 - else: - self.flush() - # - def setrightindent(self, nspaces): - self.rightindent = int(self.n_space * nspaces) - if self.para: - self.para.indent_right = self.rightindent - self.flush() - # - def setjust(self, just): - self.just = just - if self.para: - self.para.just = self.just - # - def flush(self): - if self.para: - self.b.addpara(self.para) - self.para = None - if self.font <> None: - self.d.setfont(self.font) - self.nospace = 1 - # - def vspace(self, nlines): - self.flush() - if nlines > 0: - self.para = self.newpara() - tuple = None, '', 0, 0, 0, int(nlines*self.line), 0 - self.para.words.append(tuple) - self.flush() - self.blanklines = self.blanklines + nlines - # - def needvspace(self, nlines): - self.flush() # Just to be sure - if nlines > self.blanklines: - self.vspace(nlines - self.blanklines) - # - def addword(self, text, space): - if self.nospace and not text: - return - self.nospace = 0 - self.blanklines = 0 - if not self.para: - self.para = self.newpara() - self.para.indent_left = self.leftindent - self.para.just = self.just - self.nextfont = self.font - space = int(space * self.space) - self.para.words.append(self.nextfont, text, \ - self.d.textwidth(text), space, space, \ - self.ascent, self.descent) - self.nextfont = None - # - def bgn_anchor(self, id): - if not self.para: - self.nospace = 0 - self.addword('', 0) - self.para.bgn_anchor(id) - # - def end_anchor(self, id): - if not self.para: - self.nospace = 0 - self.addword('', 0) - self.para.end_anchor(id) - - -# Measuring object for measuring text as viewed on a tty -class NullMeasurer: - # - def __init__(self): - pass - # - def setfont(self, font): - pass - # - def textwidth(self, text): - return len(text) - # - def lineheight(self): - return 1 - # - def baseline(self): - return 0 - - -# Drawing object for writing plain ASCII text to a file -class FileWriter: - # - def __init__(self, fp): - self.fp = fp - self.lineno, self.colno = 0, 0 - # - def setfont(self, font): - pass - # - def text(self, (h, v), str): - if not str: return - if '\n' in str: - raise ValueError, 'can\'t write \\n' - while self.lineno < v: - self.fp.write('\n') - self.colno, self.lineno = 0, self.lineno + 1 - while self.lineno > v: - # XXX This should never happen... - self.fp.write('\033[A') # ANSI up arrow - self.lineno = self.lineno - 1 - if self.colno < h: - self.fp.write(' ' * (h - self.colno)) - elif self.colno > h: - self.fp.write('\b' * (self.colno - h)) - self.colno = h - self.fp.write(str) - self.colno = h + len(str) - - -# Formatting class to do nothing at all with the data -class NullFormatter(BaseFormatter): - # - def __init__(self): - d = NullMeasurer() - b = NullBackEnd() - BaseFormatter.__init__(self, d, b) - - -# Formatting class to write directly to a file -class WritingFormatter(BaseFormatter): - # - def __init__(self, fp, width): - dm = NullMeasurer() - dw = FileWriter(fp) - b = WritingBackEnd(dw, width) - BaseFormatter.__init__(self, dm, b) - self.blanklines = 1 - # - # Suppress multiple blank lines - def needvspace(self, nlines): - BaseFormatter.needvspace(self, min(1, nlines)) - - -# A "FunnyFormatter" writes ASCII text with a twist: *bold words*, -# _italic text_ and _underlined words_, and `quoted text'. -# It assumes that the fonts are 'r', 'i', 'b', 'u', 'q': (roman, -# italic, bold, underline, quote). -# Moreover, if the font is in upper case, the text is converted to -# UPPER CASE. -class FunnyFormatter(WritingFormatter): - # - def flush(self): - if self.para: finalize(self.para) - WritingFormatter.flush(self) - - -# Surrounds *bold words* and _italic text_ in a paragraph with -# appropriate markers, fixing the size (assuming these characters' -# width is 1). -openchar = \ - {'b':'*', 'i':'_', 'u':'_', 'q':'`', 'B':'*', 'I':'_', 'U':'_', 'Q':'`'} -closechar = \ - {'b':'*', 'i':'_', 'u':'_', 'q':'\'', 'B':'*', 'I':'_', 'U':'_', 'Q':'\''} -def finalize(para): - oldfont = curfont = 'r' - para.words.append('r', '', 0, 0, 0, 0) # temporary, deleted at end - for i in range(len(para.words)): - fo, te, wi = para.words[i][:3] - if fo <> None: curfont = fo - if curfont <> oldfont: - if closechar.has_key(oldfont): - c = closechar[oldfont] - j = i-1 - while j > 0 and para.words[j][1] == '': j = j-1 - fo1, te1, wi1 = para.words[j][:3] - te1 = te1 + c - wi1 = wi1 + len(c) - para.words[j] = (fo1, te1, wi1) + \ - para.words[j][3:] - if openchar.has_key(curfont) and te: - c = openchar[curfont] - te = c + te - wi = len(c) + wi - para.words[i] = (fo, te, wi) + \ - para.words[i][3:] - if te: oldfont = curfont - else: oldfont = 'r' - if curfont in string.uppercase: - te = string.upper(te) - para.words[i] = (fo, te, wi) + para.words[i][3:] - del para.words[-1] - - -# Formatter back-end to draw the text in a window. -# This has an option to draw while the paragraphs are being added, -# to minimize the delay before the user sees anything. -# This manages the entire "document" of the window. -class StdwinBackEnd(SavingBackEnd): - # - def __init__(self, window, drawnow): - self.window = window - self.drawnow = drawnow - self.width = window.getwinsize()[0] - self.selection = None - self.height = 0 - window.setorigin(0, 0) - window.setdocsize(0, 0) - self.d = window.begindrawing() - SavingBackEnd.__init__(self) - # - def finish(self): - self.d.close() - self.d = None - self.window.setdocsize(0, self.height) - # - def addpara(self, p): - self.paralist.append(p) - if self.drawnow: - self.height = \ - p.render(self.d, 0, self.height, self.width) - else: - p.layout(self.width) - p.left = 0 - p.top = self.height - p.right = self.width - p.bottom = self.height + p.height - self.height = p.bottom - # - def resize(self): - self.window.change((0, 0), (self.width, self.height)) - self.width = self.window.getwinsize()[0] - self.height = 0 - for p in self.paralist: - p.layout(self.width) - p.left = 0 - p.top = self.height - p.right = self.width - p.bottom = self.height + p.height - self.height = p.bottom - self.window.change((0, 0), (self.width, self.height)) - self.window.setdocsize(0, self.height) - # - def redraw(self, area): - d = self.window.begindrawing() - (left, top), (right, bottom) = area - d.erase(area) - d.cliprect(area) - for p in self.paralist: - if top < p.bottom and p.top < bottom: - v = p.render(d, p.left, p.top, p.right) - if self.selection: - self.invert(d, self.selection) - d.close() - # - def setselection(self, new): - if new: - long1, long2 = new - pos1 = long1[:3] - pos2 = long2[:3] - new = pos1, pos2 - if new <> self.selection: - d = self.window.begindrawing() - if self.selection: - self.invert(d, self.selection) - if new: - self.invert(d, new) - d.close() - self.selection = new - # - def getselection(self): - return self.selection - # - def extractselection(self): - if self.selection: - a, b = self.selection - return self.extractpart(a, b) - else: - return None - # - def invert(self, d, region): - long1, long2 = region - if long1 > long2: long1, long2 = long2, long1 - para1, pos1 = long1 - para2, pos2 = long2 - while para1 < para2: - self.paralist[para1].invert(d, pos1, None) - pos1 = None - para1 = para1 + 1 - self.paralist[para2].invert(d, pos1, pos2) - # - def search(self, prog): - import regex, string - if type(prog) == type(''): - prog = regex.compile(string.lower(prog)) - if self.selection: - iold = self.selection[0][0] - else: - iold = -1 - hit = None - for i in range(len(self.paralist)): - if i == iold or i < iold and hit: - continue - p = self.paralist[i] - text = string.lower(p.extract()) - if prog.search(text) >= 0: - a, b = prog.regs[0] - long1 = i, a - long2 = i, b - hit = long1, long2 - if i > iold: - break - if hit: - self.setselection(hit) - i = hit[0][0] - p = self.paralist[i] - self.window.show((p.left, p.top), (p.right, p.bottom)) - return 1 - else: - return 0 - # - def showanchor(self, id): - for i in range(len(self.paralist)): - p = self.paralist[i] - if p.hasanchor(id): - long1 = i, 0 - long2 = i, len(p.extract()) - hit = long1, long2 - self.setselection(hit) - self.window.show( \ - (p.left, p.top), (p.right, p.bottom)) - break - - -# GL extensions - -class GLFontCache: - # - def __init__(self): - self.reset() - self.setfont('') - # - def reset(self): - self.fontkey = None - self.fonthandle = None - self.fontinfo = None - self.fontcache = {} - # - def close(self): - self.reset() - # - def setfont(self, fontkey): - if fontkey == '': - fontkey = 'Times-Roman 12' - elif ' ' not in fontkey: - fontkey = fontkey + ' 12' - if fontkey == self.fontkey: - return - if self.fontcache.has_key(fontkey): - handle = self.fontcache[fontkey] - else: - import string - i = string.index(fontkey, ' ') - name, sizestr = fontkey[:i], fontkey[i:] - size = eval(sizestr) - key1 = name + ' 1' - key = name + ' ' + `size` - # NB key may differ from fontkey! - if self.fontcache.has_key(key): - handle = self.fontcache[key] - else: - if self.fontcache.has_key(key1): - handle = self.fontcache[key1] - else: - import fm - handle = fm.findfont(name) - self.fontcache[key1] = handle - handle = handle.scalefont(size) - self.fontcache[fontkey] = \ - self.fontcache[key] = handle - self.fontkey = fontkey - if self.fonthandle <> handle: - self.fonthandle = handle - self.fontinfo = handle.getfontinfo() - handle.setfont() - - -class GLMeasurer(GLFontCache): - # - def textwidth(self, text): - return self.fonthandle.getstrwidth(text) - # - def baseline(self): - return self.fontinfo[6] - self.fontinfo[3] - # - def lineheight(self): - return self.fontinfo[6] - - -class GLWriter(GLFontCache): - # - # NOTES: - # (1) Use gl.ortho2 to use X pixel coordinates! - # - def text(self, (h, v), text): - import gl, fm - gl.cmov2i(h, v + self.fontinfo[6] - self.fontinfo[3]) - fm.prstr(text) - # - def setfont(self, fontkey): - oldhandle = self.fonthandle - GLFontCache.setfont(fontkey) - if self.fonthandle <> oldhandle: - handle.setfont() - - -class GLMeasurerWriter(GLMeasurer, GLWriter): - pass - - -class GLBackEnd(SavingBackEnd): - # - def __init__(self, wid): - import gl - gl.winset(wid) - self.wid = wid - self.width = gl.getsize()[1] - self.height = 0 - self.d = GLMeasurerWriter() - SavingBackEnd.__init__(self) - # - def finish(self): - pass - # - def addpara(self, p): - self.paralist.append(p) - self.height = p.render(self.d, 0, self.height, self.width) - # - def redraw(self): - import gl - gl.winset(self.wid) - width = gl.getsize()[1] - if width <> self.width: - setdocsize = 1 - self.width = width - for p in self.paralist: - p.top = p.bottom = None - d = self.d - v = 0 - for p in self.paralist: - v = p.render(d, 0, v, width) diff --git a/Lib/lib-old/grep.py b/Lib/lib-old/grep.py deleted file mode 100644 index f4666512b7..0000000000 --- a/Lib/lib-old/grep.py +++ /dev/null @@ -1,62 +0,0 @@ -# 'grep' - -import regex -from regex_syntax import * -import string - -opt_show_where = 0 -opt_show_filename = 0 -opt_show_lineno = 1 - -def grep(pat, *files): - return ggrep(RE_SYNTAX_GREP, pat, files) - -def egrep(pat, *files): - return ggrep(RE_SYNTAX_EGREP, pat, files) - -def emgrep(pat, *files): - return ggrep(RE_SYNTAX_EMACS, pat, files) - -def ggrep(syntax, pat, files): - if len(files) == 1 and type(files[0]) == type([]): - files = files[0] - global opt_show_filename - opt_show_filename = (len(files) != 1) - syntax = regex.set_syntax(syntax) - try: - prog = regex.compile(pat) - finally: - syntax = regex.set_syntax(syntax) - for filename in files: - fp = open(filename, 'r') - lineno = 0 - while 1: - line = fp.readline() - if not line: break - lineno = lineno + 1 - if prog.search(line) >= 0: - showline(filename, lineno, line, prog) - fp.close() - -def showline(filename, lineno, line, prog): - if line[-1:] == '\n': line = line[:-1] - if opt_show_lineno: - prefix = string.rjust(`lineno`, 3) + ': ' - else: - prefix = '' - if opt_show_filename: - prefix = filename + ': ' + prefix - print prefix + line - if opt_show_where: - start, end = prog.regs()[0] - line = line[:start] - if '\t' not in line: - prefix = ' ' * (len(prefix) + start) - else: - prefix = ' ' * len(prefix) - for c in line: - if c <> '\t': c = ' ' - prefix = prefix + c - if start == end: prefix = prefix + '\\' - else: prefix = prefix + '^'*(end-start) - print prefix diff --git a/Lib/lib-old/lockfile.py b/Lib/lib-old/lockfile.py deleted file mode 100644 index 3a251d720b..0000000000 --- a/Lib/lib-old/lockfile.py +++ /dev/null @@ -1,15 +0,0 @@ -import struct, fcntl, FCNTL - -def writelock(f): - _lock(f, FCNTL.F_WRLCK) - -def readlock(f): - _lock(f, FCNTL.F_RDLCK) - -def unlock(f): - _lock(f, FCNTL.F_UNLCK) - -def _lock(f, op): - dummy = fcntl.fcntl(f.fileno(), FCNTL.F_SETLKW, - struct.pack('2h8l', op, - 0, 0, 0, 0, 0, 0, 0, 0, 0)) diff --git a/Lib/lib-old/newdir.py b/Lib/lib-old/newdir.py deleted file mode 100644 index 937c49e67b..0000000000 --- a/Lib/lib-old/newdir.py +++ /dev/null @@ -1,73 +0,0 @@ -# New dir() function - - -# This should be the new dir(), except that it should still list -# the current local name space by default - -def listattrs(x): - try: - dictkeys = x.__dict__.keys() - except (AttributeError, TypeError): - dictkeys = [] - # - try: - methods = x.__methods__ - except (AttributeError, TypeError): - methods = [] - # - try: - members = x.__members__ - except (AttributeError, TypeError): - members = [] - # - try: - the_class = x.__class__ - except (AttributeError, TypeError): - the_class = None - # - try: - bases = x.__bases__ - except (AttributeError, TypeError): - bases = () - # - total = dictkeys + methods + members - if the_class: - # It's a class instace; add the class's attributes - # that are functions (methods)... - class_attrs = listattrs(the_class) - class_methods = [] - for name in class_attrs: - if is_function(getattr(the_class, name)): - class_methods.append(name) - total = total + class_methods - elif bases: - # It's a derived class; add the base class attributes - for base in bases: - base_attrs = listattrs(base) - total = total + base_attrs - total.sort() - return total - i = 0 - while i+1 < len(total): - if total[i] == total[i+1]: - del total[i+1] - else: - i = i+1 - return total - - -# Helper to recognize functions - -def is_function(x): - return type(x) == type(is_function) - - -# Approximation of builtin dir(); but note that this lists the user's -# variables by default, not the current local name space. - -def dir(x = None): - if x is not None: - return listattrs(x) - else: - import __main__ - return listattrs(__main__) diff --git a/Lib/lib-old/packmail.py b/Lib/lib-old/packmail.py deleted file mode 100644 index 13b1bdcdea..0000000000 --- a/Lib/lib-old/packmail.py +++ /dev/null @@ -1,112 +0,0 @@ -# Module 'packmail' -- create a self-unpacking shell archive. - -# This module works on UNIX and on the Mac; the archives can unpack -# themselves only on UNIX. - -import os -from stat import ST_MTIME -import string - -# Print help -def help(): - print 'All fns have a file open for writing as first parameter' - print 'pack(f, fullname, name): pack fullname as name' - print 'packsome(f, directory, namelist): selected files from directory' - print 'packall(f, directory): pack all files from directory' - print 'packnotolder(f, directory, name): pack all files from directory' - print ' that are not older than a file there' - print 'packtree(f, directory): pack entire directory tree' - -# Pack one file -def pack(outfp, file, name): - fp = open(file, 'r') - outfp.write('echo ' + name + '\n') - outfp.write('sed "s/^X//" >' + name + ' <<"!"\n') - while 1: - line = fp.readline() - if not line: break - if line[-1:] <> '\n': - line = line + '\n' - outfp.write('X' + line) - outfp.write('!\n') - fp.close() - -# Pack some files from a directory -def packsome(outfp, dirname, names): - for name in names: - print name - file = os.path.join(dirname, name) - pack(outfp, file, name) - -# Pack all files from a directory -def packall(outfp, dirname): - names = os.listdir(dirname) - try: - names.remove('.') - except: - pass - try: - names.remove('..') - except: - pass - names.sort() - packsome(outfp, dirname, names) - -# Pack all files from a directory that are not older than a give one -def packnotolder(outfp, dirname, oldest): - names = os.listdir(dirname) - try: - names.remove('.') - except: - pass - try: - names.remove('..') - except: - pass - oldest = os.path.join(dirname, oldest) - st = os.stat(oldest) - mtime = st[ST_MTIME] - todo = [] - for name in names: - print name, '...', - st = os.stat(os.path.join(dirname, name)) - if st[ST_MTIME] >= mtime: - print 'Yes.' - todo.append(name) - else: - print 'No.' - todo.sort() - packsome(outfp, dirname, todo) - -# Pack a whole tree (no exceptions) -def packtree(outfp, dirname): - print 'packtree', dirname - outfp.write('mkdir ' + unixfix(dirname) + '\n') - names = os.listdir(dirname) - try: - names.remove('.') - except: - pass - try: - names.remove('..') - except: - pass - subdirs = [] - for name in names: - fullname = os.path.join(dirname, name) - if os.path.isdir(fullname): - subdirs.append(fullname) - else: - print 'pack', fullname - pack(outfp, fullname, unixfix(fullname)) - for subdirname in subdirs: - packtree(outfp, subdirname) - -def unixfix(name): - comps = string.splitfields(name, os.sep) - res = '' - for comp in comps: - if comp: - if res: res = res + '/' - res = res + comp - return res diff --git a/Lib/lib-old/rand.py b/Lib/lib-old/rand.py deleted file mode 100644 index c299d0a9a9..0000000000 --- a/Lib/lib-old/rand.py +++ /dev/null @@ -1,13 +0,0 @@ -# Module 'rand' -# Don't use unless you want compatibility with C's rand()! - -import whrandom - -def srand(seed): - whrandom.seed(seed%256, seed/256%256, seed/65536%256) - -def rand(): - return int(whrandom.random() * 32768.0) % 32768 - -def choice(seq): - return seq[rand() % len(seq)] diff --git a/Lib/lib-old/tb.py b/Lib/lib-old/tb.py deleted file mode 100644 index 641e8af2e8..0000000000 --- a/Lib/lib-old/tb.py +++ /dev/null @@ -1,177 +0,0 @@ -# Print tracebacks, with a dump of local variables. -# Also an interactive stack trace browser. -# Note -- this module is obsolete -- use pdb.pm() instead. - -import sys -import os -from stat import * -import string -import linecache - -def br(): browser(sys.last_traceback) - -def tb(): printtb(sys.last_traceback) - -def browser(tb): - if not tb: - print 'No traceback.' - return - tblist = [] - while tb: - tblist.append(tb) - tb = tb.tb_next - ptr = len(tblist)-1 - tb = tblist[ptr] - while 1: - if tb <> tblist[ptr]: - tb = tblist[ptr] - print `ptr` + ':', - printtbheader(tb) - try: - line = raw_input('TB: ') - except KeyboardInterrupt: - print '\n[Interrupted]' - break - except EOFError: - print '\n[EOF]' - break - cmd = string.strip(line) - if cmd: - if cmd == 'quit': - break - elif cmd == 'list': - browserlist(tb) - elif cmd == 'up': - if ptr-1 >= 0: ptr = ptr-1 - else: print 'Bottom of stack.' - elif cmd == 'down': - if ptr+1 < len(tblist): ptr = ptr+1 - else: print 'Top of stack.' - elif cmd == 'locals': - printsymbols(tb.tb_frame.f_locals) - elif cmd == 'globals': - printsymbols(tb.tb_frame.f_globals) - elif cmd in ('?', 'help'): - browserhelp() - else: - browserexec(tb, cmd) - -def browserlist(tb): - filename = tb.tb_frame.f_code.co_filename - lineno = tb.tb_lineno - last = lineno - first = max(1, last-10) - for i in range(first, last+1): - if i == lineno: prefix = '***' + string.rjust(`i`, 4) + ':' - else: prefix = string.rjust(`i`, 7) + ':' - line = linecache.getline(filename, i) - if line[-1:] == '\n': line = line[:-1] - print prefix + line - -def browserexec(tb, cmd): - locals = tb.tb_frame.f_locals - globals = tb.tb_frame.f_globals - try: - exec cmd+'\n' in globals, locals - except: - print '*** Exception:', - if type(sys.exc_type) == type(''): - print sys.exc_type, - else: - print sys.exc_type.__name__, - if sys.exc_value <> None: - print ':', sys.exc_value, - print - print 'Type help to get help.' - -def browserhelp(): - print - print ' This is the traceback browser. Commands are:' - print ' up : move one level up in the call stack' - print ' down : move one level down in the call stack' - print ' locals : print all local variables at this level' - print ' globals : print all global variables at this level' - print ' list : list source code around the failure' - print ' help : print help (what you are reading now)' - print ' quit : back to command interpreter' - print ' Typing any other 1-line statement will execute it' - print ' using the current level\'s symbol tables' - print - -def printtb(tb): - while tb: - print1tb(tb) - tb = tb.tb_next - -def print1tb(tb): - printtbheader(tb) - if tb.tb_frame.f_locals is not tb.tb_frame.f_globals: - printsymbols(tb.tb_frame.f_locals) - -def printtbheader(tb): - filename = tb.tb_frame.f_code.co_filename - lineno = tb.tb_lineno - info = '"' + filename + '"(' + `lineno` + ')' - line = linecache.getline(filename, lineno) - if line: - info = info + ': ' + string.strip(line) - print info - -def printsymbols(d): - keys = d.keys() - keys.sort() - for name in keys: - print ' ' + string.ljust(name, 12) + ':', - printobject(d[name], 4) - print - -def printobject(v, maxlevel): - if v == None: - print 'None', - elif type(v) in (type(0), type(0.0)): - print v, - elif type(v) == type(''): - if len(v) > 20: - print `v[:17] + '...'`, - else: - print `v`, - elif type(v) == type(()): - print '(', - printlist(v, maxlevel) - print ')', - elif type(v) == type([]): - print '[', - printlist(v, maxlevel) - print ']', - elif type(v) == type({}): - print '{', - printdict(v, maxlevel) - print '}', - else: - print v, - -def printlist(v, maxlevel): - n = len(v) - if n == 0: return - if maxlevel <= 0: - print '...', - return - for i in range(min(6, n)): - printobject(v[i], maxlevel-1) - if i+1 < n: print ',', - if n > 6: print '...', - -def printdict(v, maxlevel): - keys = v.keys() - n = len(keys) - if n == 0: return - if maxlevel <= 0: - print '...', - return - keys.sort() - for i in range(min(6, n)): - key = keys[i] - print `key` + ':', - printobject(v[key], maxlevel-1) - if i+1 < n: print ',', - if n > 6: print '...', diff --git a/Lib/lib-old/util.py b/Lib/lib-old/util.py deleted file mode 100644 index 6cb1433426..0000000000 --- a/Lib/lib-old/util.py +++ /dev/null @@ -1,25 +0,0 @@ -# Module 'util' -- some useful functions that don't fit elsewhere - -# NB: These are now built-in functions, but this module is provided -# for compatibility. Don't use in new programs unless you need backward -# compatibility (i.e. need to run with old interpreters). - - -# Remove an item from a list. -# No complaints if it isn't in the list at all. -# If it occurs more than once, remove the first occurrence. -# -def remove(item, list): - if item in list: list.remove(item) - - -# Return a string containing a file's contents. -# -def readfile(fn): - return readopenfile(open(fn, 'r')) - - -# Read an open file until EOF. -# -def readopenfile(fp): - return fp.read() diff --git a/Lib/lib-old/whatsound.py b/Lib/lib-old/whatsound.py deleted file mode 100644 index b7b349c5ba..0000000000 --- a/Lib/lib-old/whatsound.py +++ /dev/null @@ -1,270 +0,0 @@ -# This module contains several routines that help recognizing sound -# files. -# -# Function whathdr() recognizes various types of sound file headers. -# It understands almost all headers that SOX can decode. -# -# The return tuple contains the following items, in this order: -# - file type (as SOX understands it) -# - sampling rate (0 if unknown or hard to decode) -# - number of channels (0 if unknown or hard to decode) -# - number of frames in the file (-1 if unknown or hard to decode) -# - number of bits/sample, or 'U' for U-LAW, or 'A' for A-LAW -# -# If the file doesn't have a recognizable type, it returns None. -# If the file can't be opened, IOError is raised. -# -# To compute the total time, divide the number of frames by the -# sampling rate (a frame contains a sample for each channel). -# -# Function whatraw() calls the "whatsound" program and interprets its -# output. You'll have to guess the sampling rate by listening though! -# -# Function what() calls whathdr() and if it doesn't recognize the file -# then calls whatraw(). -# -# Finally, the function test() is a simple main program that calls -# what() for all files mentioned on the argument list. For directory -# arguments it calls what() for all files in that directory. Default -# argument is "." (testing all files in the current directory). The -# option -r tells it to recurse down directories found inside -# explicitly given directories. -# -# The file structure is top-down except that the test program and its -# subroutine come last. - - -#------------------------------------------------------# -# Guess the type of any sound file, raw or with header # -#------------------------------------------------------# - -def what(filename): - res = whathdr(filename) - if not res: - res = whatraw(filename) - return res - - -#-----------------------------# -# Guess the type of raw sound # -#-----------------------------# - -def whatraw(filename): - # Assume it's always 1 channel, byte-sized samples - # Don't assume anything about the rate - import os - from stat import ST_SIZE - # XXX "whatsound" should be part of the distribution somehow... - cmd = 'whatsound ' + filename + ' 2>/dev/null' - cmd = 'PATH=$PATH:/ufs/guido/bin/sgi\n' + cmd - pipe = os.popen(cmd, 'r') - data = pipe.read() - sts = pipe.close() - if sts: - return None - if data[:13] == '-t raw -b -s ': - type = 'sb' - sample_size = 8 - elif data[:13] == '-t raw -b -u ': - type = 'ub' - sample_size = 8 - elif data[:13] == '-t raw -b -U ': - type = 'ul' - sample_size = 'U' - else: - return None - try: - frame_count = os.stat(filename)[ST_SIZE] - except IOError: - frame_count = -1 - return type, 0, 1, frame_count, sample_size - - -#-------------------------# -# Recognize sound headers # -#-------------------------# - -def whathdr(filename): - f = open(filename, 'r') - h = f.read(512) - for tf in tests: - res = tf(h, f) - if res: - return res - return None - - -#-----------------------------------# -# Subroutines per sound header type # -#-----------------------------------# - -tests = [] - -def test_aifc(h, f): - import aifc - if h[:4] <> 'FORM': - return None - if h[8:12] == 'AIFC': - fmt = 'aifc' - elif h[8:12] == 'AIFF': - fmt = 'aiff' - else: - return None - f.seek(0) - try: - a = aifc.openfp(f, 'r') - except (EOFError, aifc.Error): - return None - return (fmt, a.getframerate(), a.getnchannels(), \ - a.getnframes(), 8*a.getsampwidth()) - -tests.append(test_aifc) - - -def test_au(h, f): - if h[:4] == '.snd': - f = get_long_be - elif h[:4] in ('\0ds.', 'dns.'): - f = get_long_le - else: - return None - type = 'au' - hdr_size = f(h[4:8]) - data_size = f(h[8:12]) - encoding = f(h[12:16]) - rate = f(h[16:20]) - nchannels = f(h[20:24]) - sample_size = 1 # default - if encoding == 1: - sample_bits = 'U' - elif encoding == 2: - sample_bits = 8 - elif encoding == 3: - sample_bits = 16 - sample_size = 2 - else: - sample_bits = '?' - frame_size = sample_size * nchannels - return type, rate, nchannels, data_size/frame_size, sample_bits - -tests.append(test_au) - - -def test_hcom(h, f): - if h[65:69] <> 'FSSD' or h[128:132] <> 'HCOM': - return None - divisor = get_long_be(h[128+16:128+20]) - return 'hcom', 22050/divisor, 1, -1, 8 - -tests.append(test_hcom) - - -def test_voc(h, f): - if h[:20] <> 'Creative Voice File\032': - return None - sbseek = get_short_le(h[20:22]) - rate = 0 - if 0 <= sbseek < 500 and h[sbseek] == '\1': - ratecode = ord(h[sbseek+4]) - rate = int(1000000.0 / (256 - ratecode)) - return 'voc', rate, 1, -1, 8 - -tests.append(test_voc) - - -def test_wav(h, f): - # 'RIFF' <len> 'WAVE' 'fmt ' <len> - if h[:4] <> 'RIFF' or h[8:12] <> 'WAVE' or h[12:16] <> 'fmt ': - return None - style = get_short_le(h[20:22]) - nchannels = get_short_le(h[22:24]) - rate = get_long_le(h[24:28]) - sample_bits = get_short_le(h[34:36]) - return 'wav', rate, nchannels, -1, sample_bits - -tests.append(test_wav) - - -def test_8svx(h, f): - if h[:4] <> 'FORM' or h[8:12] <> '8SVX': - return None - # Should decode it to get #channels -- assume always 1 - return '8svx', 0, 1, 0, 8 - -tests.append(test_8svx) - - -def test_sndt(h, f): - if h[:5] == 'SOUND': - nsamples = get_long_le(h[8:12]) - rate = get_short_le(h[20:22]) - return 'sndt', rate, 1, nsamples, 8 - -tests.append(test_sndt) - - -def test_sndr(h, f): - if h[:2] == '\0\0': - rate = get_short_le(h[2:4]) - if 4000 <= rate <= 25000: - return 'sndr', rate, 1, -1, 8 - -tests.append(test_sndr) - - -#---------------------------------------------# -# Subroutines to extract numbers from strings # -#---------------------------------------------# - -def get_long_be(s): - return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3]) - -def get_long_le(s): - return (ord(s[3])<<24) | (ord(s[2])<<16) | (ord(s[1])<<8) | ord(s[0]) - -def get_short_be(s): - return (ord(s[0])<<8) | ord(s[1]) - -def get_short_le(s): - return (ord(s[1])<<8) | ord(s[0]) - - -#--------------------# -# Small test program # -#--------------------# - -def test(): - import sys - recursive = 0 - if sys.argv[1:] and sys.argv[1] == '-r': - del sys.argv[1:2] - recursive = 1 - try: - if sys.argv[1:]: - testall(sys.argv[1:], recursive, 1) - else: - testall(['.'], recursive, 1) - except KeyboardInterrupt: - sys.stderr.write('\n[Interrupted]\n') - sys.exit(1) - -def testall(list, recursive, toplevel): - import sys - import os - for filename in list: - if os.path.isdir(filename): - print filename + '/:', - if recursive or toplevel: - print 'recursing down:' - import glob - names = glob.glob(os.path.join(filename, '*')) - testall(names, recursive, 0) - else: - print '*** directory (use -r) ***' - else: - print filename + ':', - sys.stdout.flush() - try: - print what(filename) - except IOError: - print '*** not found ***' diff --git a/Lib/lib-stdwin/Abstract.py b/Lib/lib-stdwin/Abstract.py deleted file mode 100644 index 51bd305a86..0000000000 --- a/Lib/lib-stdwin/Abstract.py +++ /dev/null @@ -1,63 +0,0 @@ -# Abstract classes for parents and children. -# -# Do not use as base class -- this is for documentation only. -# -# Note that the tree must be built top down (create the parent, -# then add the children). -# -# Also note that the creation methods are not standardized -- -# these have extra parameters dependent on the widget type. -# For historical reasons, button creation methods are called -# define() while split creation methods are called create(). - -class AbstractParent: - # - # Upcalls from child to parent - # - def addchild(self, child): unimpl() - def delchild(self, child): unimpl() - # - def need_mouse(self, child): unimpl() - def no_mouse(self, child): unimpl() - # - def need_timer(self, child): unimpl() - def no_timer(self, child): unimpl() - # - # XXX need_kbd, no_kbd; focus??? - # - def begindrawing(self): return unimpl() - def beginmeasuring(self): return unimpl() - def getwindow(self): return unimpl() # Only for very special cases - # - def change(self, area): unimpl() - def scroll(self, area, (dh, dv)): unimpl() - def settimer(self, itimer): unimpl() - -class AbstractChild: - # - # Downcalls from parent to child - # - def destroy(self): unimpl() - # - def realize(self): return unimpl() - def getminsize(self, m, (width, height)): return unimpl() - def getbounds(self): return unimpl() - def setbounds(self, bounds): unimpl() - def draw(self, d, area): unimpl() - # - # Downcalls only made after certain upcalls - # - def mouse_down(self, detail): unimpl() - def mouse_move(self, detail): unimpl() - def mouse_up(self, detail): unimpl() - # - def timer(self): unimpl() - -# A "Split" is a child that manages one or more children. -# (This terminology is due to DEC SRC, except for CSplits.) -# A child of a split may be another split, a button, a slider, etc. -# Certain upcalls and downcalls can be handled transparently, but -# for others (e.g., all geometry related calls) this is not possible. - -class AbstractSplit(AbstractChild, AbstractParent): - pass diff --git a/Lib/lib-stdwin/BoxParent.py b/Lib/lib-stdwin/BoxParent.py deleted file mode 100644 index c792731c5b..0000000000 --- a/Lib/lib-stdwin/BoxParent.py +++ /dev/null @@ -1,40 +0,0 @@ -from TransParent import TransParent - -class BoxParent(TransParent): - # - def create(self, parent, (dh, dv)): - self = TransParent.create(self, parent) - self.dh = dh - self.dv = dv - return self - # - def getminsize(self, m, (width, height)): - width = max(0, width - 2*self.dh) - height = max(0, height - 2*self.dv) - width, height = self.child.getminsize(m, (width, height)) - return width + 2*self.dh, height + 2*self.dv - # - def setbounds(self, bounds): - (left, top), (right, bottom) = bounds - self.bounds = bounds - left = min(right, left + self.dh) - top = min(bottom, top + self.dv) - right = max(left, right - self.dh) - bottom = max(top, bottom - self.dv) - self.innerbounds = (left, top), (right, bottom) - self.child.setbounds(self.innerbounds) - # - def getbounds(self): - return self.bounds - # - def draw(self, d, area): - (left, top), (right, bottom) = self.bounds - left = left + 1 - top = top + 1 - right = right - 1 - bottom = bottom - 1 - d.box((left, top), (right, bottom)) - TransParent.draw(self, d, area) # XXX clip to innerbounds? - # - # XXX should scroll clip to innerbounds??? - # XXX currently the only user restricts itself to child's bounds diff --git a/Lib/lib-stdwin/Buttons.py b/Lib/lib-stdwin/Buttons.py deleted file mode 100644 index 9a9970789b..0000000000 --- a/Lib/lib-stdwin/Buttons.py +++ /dev/null @@ -1,411 +0,0 @@ -# Module 'Buttons' - - -# Import module 'rect' renamed as '_rect' to avoid exporting it on -# 'from Buttons import *' -# -import rect -_rect = rect -del rect - - -# Field indices in mouse event detail -# -_HV = 0 -_CLICKS = 1 -_BUTTON = 2 -_MASK = 3 - - -# LabelAppearance provides defaults for all appearance methods. -# selected state not visible -# disabled --> crossed out -# hilited --> inverted -# -class LabelAppearance: - # - # Initialization - # - def init_appearance(self): - self.bounds = _rect.empty - self.enabled = 1 - self.hilited = 0 - self.selected = 0 - self.text = '' - # - # Size enquiry - # - def getminsize(self, m, (width, height)): - width = max(width, m.textwidth(self.text) + 6) - height = max(height, m.lineheight() + 6) - return width, height - # - def getbounds(self): - return self.bounds - # - # Changing the parameters - # - def settext(self, text): - self.text = text - if self.bounds <> _rect.empty: - self.recalctextpos() - self.redraw() - # - def setbounds(self, bounds): - self.bounds = bounds - if self.bounds <> _rect.empty: - self.recalc() - # - def realize(self): - pass - # - # Changing the state bits - # - def enable(self, flag): - if flag <> self.enabled: - self.enabled = flag - if self.bounds <> _rect.empty: - self.flipenable(self.parent.begindrawing()) - # - def hilite(self, flag): - if flag <> self.hilited: - self.hilited = flag - if self.bounds <> _rect.empty: - self.fliphilite(self.parent.begindrawing()) - # - def select(self, flag): - if flag <> self.selected: - self.selected = flag - if self.bounds <> _rect.empty: - self.redraw() - # - # Recalculate the box bounds and text position. - # This can be overridden by buttons that draw different boxes - # or want their text in a different position. - # - def recalc(self): - if self.bounds <> _rect.empty: - self.recalcbounds() - self.recalctextpos() - # - def recalcbounds(self): - self.hilitebounds = _rect.inset(self.bounds, (3, 3)) - self.crossbounds = self.bounds - # - def recalctextpos(self): - (left, top), (right, bottom) = self.bounds - m = self.parent.beginmeasuring() - h = (left + right - m.textwidth(self.text)) / 2 - v = (top + bottom - m.lineheight()) / 2 - self.textpos = h, v - # - # Generic drawing interface. - # Do not override redraw() or draw() methods; override drawit() c.s. - # - def redraw(self): - if self.bounds <> _rect.empty: - d = self.parent.begindrawing() - d.erase(self.bounds) - self.draw(d, self.bounds) - # - def draw(self, d, area): - area = _rect.intersect([area, self.bounds]) - if area == _rect.empty: - return - d.cliprect(area) - self.drawit(d) - d.noclip() - # - # The drawit() method is fairly generic but may be overridden. - # - def drawit(self, d): - self.drawpict(d) - if self.text: - d.text(self.textpos, self.text) - if not self.enabled: - self.flipenable(d) - if self.hilited: - self.fliphilite(d) - # - # Default drawing detail functions. - # Overriding these is normally sufficient to get different - # appearances. - # - def drawpict(self, d): - pass - # - def flipenable(self, d): - _xorcross(d, self.crossbounds) - # - def fliphilite(self, d): - d.invert(self.hilitebounds) - - -# A Strut is a label with no width of its own. - -class StrutAppearance(LabelAppearance): - # - def getminsize(self, m, (width, height)): - height = max(height, m.lineheight() + 6) - return width, height - # - - -# ButtonAppearance displays a centered string in a box. -# selected --> bold border -# disabled --> crossed out -# hilited --> inverted -# -class ButtonAppearance(LabelAppearance): - # - def drawpict(self, d): - d.box(_rect.inset(self.bounds, (1, 1))) - if self.selected: - # Make a thicker box - d.box(self.bounds) - d.box(_rect.inset(self.bounds, (2, 2))) - d.box(_rect.inset(self.bounds, (3, 3))) - # - - -# CheckAppearance displays a small square box and a left-justified string. -# selected --> a cross appears in the box -# disabled --> whole button crossed out -# hilited --> box is inverted -# -class CheckAppearance(LabelAppearance): - # - def getminsize(self, m, (width, height)): - minwidth = m.textwidth(self.text) + 6 - minheight = m.lineheight() + 6 - width = max(width, minwidth + minheight + m.textwidth(' ')) - height = max(height, minheight) - return width, height - # - def drawpict(self, d): - d.box(self.boxbounds) - if self.selected: _xorcross(d, self.boxbounds) - # - def recalcbounds(self): - LabelAppearance.recalcbounds(self) - (left, top), (right, bottom) = self.bounds - self.size = bottom - top - 4 - self.boxbounds = (left+2, top+2), (left+2+self.size, bottom-2) - self.hilitebounds = self.boxbounds - # - def recalctextpos(self): - m = self.parent.beginmeasuring() - (left, top), (right, bottom) = self.boxbounds - h = right + m.textwidth(' ') - v = top + (self.size - m.lineheight()) / 2 - self.textpos = h, v - # - - -# RadioAppearance displays a round indicator and a left-justified string. -# selected --> a dot appears in the indicator -# disabled --> whole button crossed out -# hilited --> indicator is inverted -# -class RadioAppearance(CheckAppearance): - # - def drawpict(self, d): - (left, top), (right, bottom) = self.boxbounds - radius = self.size / 2 - center = left + radius, top + radius - d.circle(center, radius) - if self.selected: - d.fillcircle(center, radius*3/5) - # - - -# NoReactivity ignores mouse events. -# -class NoReactivity: - def init_reactivity(self): pass - - -# BaseReactivity defines hooks and asks for mouse events, -# but provides only dummy mouse event handlers. -# The trigger methods call the corresponding hooks set by the user. -# Hooks (and triggers) mean the following: -# down_hook called on some mouse-down events -# move_hook called on some mouse-move events -# up_hook called on mouse-up events -# on_hook called for buttons with on/off state, when it goes on -# hook called when a button 'fires' or a radiobutton goes on -# There are usually extra conditions, e.g., hooks are only called -# when the button is enabled, or active, or selected (on). -# -class BaseReactivity: - # - def init_reactivity(self): - self.down_hook = self.move_hook = self.up_hook = \ - self.on_hook = self.off_hook = \ - self.hook = self.active = 0 - self.parent.need_mouse(self) - # - def mousetest(self, hv): - return _rect.pointinrect(hv, self.bounds) - # - def mouse_down(self, detail): - pass - # - def mouse_move(self, detail): - pass - # - def mouse_up(self, detail): - pass - # - def down_trigger(self): - if self.down_hook: self.down_hook(self) - # - def move_trigger(self): - if self.move_hook: self.move_hook(self) - # - def up_trigger(self): - if self.up_hook: self.up_hook(self) - # - def on_trigger(self): - if self.on_hook: self.on_hook(self) - # - def off_trigger(self): - if self.off_hook: self.off_hook(self) - # - def trigger(self): - if self.hook: self.hook(self) - - -# ToggleReactivity acts like a simple pushbutton. -# It toggles its hilite state on mouse down events. -# -class ToggleReactivity(BaseReactivity): - # - def mouse_down(self, detail): - if self.enabled and self.mousetest(detail[_HV]): - self.active = 1 - self.hilite(not self.hilited) - self.down_trigger() - # - def mouse_move(self, detail): - if self.active: - self.move_trigger() - # - def mouse_up(self, detail): - if self.active: - self.up_trigger() - self.active = 0 - # - def down_trigger(self): - if self.hilited: - self.on_trigger() - else: - self.off_trigger() - self.trigger() - # - - -# TriggerReactivity acts like a fancy pushbutton. -# It hilites itself while the mouse is down within its bounds. -# -class TriggerReactivity(BaseReactivity): - # - def mouse_down(self, detail): - if self.enabled and self.mousetest(detail[_HV]): - self.active = 1 - self.hilite(1) - self.down_trigger() - # - def mouse_move(self, detail): - if self.active: - self.hilite(self.mousetest(detail[_HV])) - if self.hilited: - self.move_trigger() - # - def mouse_up(self, detail): - if self.active: - self.hilite(self.mousetest(detail[_HV])) - if self.hilited: - self.up_trigger() - self.trigger() - self.active = 0 - self.hilite(0) - # - - -# CheckReactivity handles mouse events like TriggerReactivity, -# It overrides the up_trigger method to flip its selected state. -# -class CheckReactivity(TriggerReactivity): - # - def up_trigger(self): - self.select(not self.selected) - if self.selected: - self.on_trigger() - else: - self.off_trigger() - self.trigger() - - -# RadioReactivity turns itself on and the other buttons in its group -# off when its up_trigger method is called. -# -class RadioReactivity(TriggerReactivity): - # - def init_reactivity(self): - TriggerReactivity.init_reactivity(self) - self.group = [] - # - def up_trigger(self): - for b in self.group: - if b <> self: - if b.selected: - b.select(0) - b.off_trigger() - self.select(1) - self.on_trigger() - self.trigger() - - -# Auxiliary class for 'define' method. -# Call the initializers in the right order. -# -class Define: - # - def define(self, parent): - self.parent = parent - parent.addchild(self) - self.init_appearance() - self.init_reactivity() - return self - # - def destroy(self): - self.parent = 0 - # - def definetext(self, parent, text): - self = self.define(parent) - self.settext(text) - return self - - -# Subroutine to cross out a rectangle. -# -def _xorcross(d, bounds): - ((left, top), (right, bottom)) = bounds - # This is s bit funny to make it look better - left = left + 2 - right = right - 2 - top = top + 2 - bottom = bottom - 3 - d.xorline(((left, top), (right, bottom))) - d.xorline((left, bottom), (right, top)) - - -# Ready-made button classes. -# -class Label(NoReactivity, LabelAppearance, Define): pass -class Strut(NoReactivity, StrutAppearance, Define): pass -class PushButton(TriggerReactivity, ButtonAppearance, Define): pass -class CheckButton(CheckReactivity, CheckAppearance, Define): pass -class RadioButton(RadioReactivity, RadioAppearance, Define): pass -class ToggleButton(ToggleReactivity, ButtonAppearance, Define): pass diff --git a/Lib/lib-stdwin/CSplit.py b/Lib/lib-stdwin/CSplit.py deleted file mode 100644 index 90d51119c3..0000000000 --- a/Lib/lib-stdwin/CSplit.py +++ /dev/null @@ -1,69 +0,0 @@ -# A CSplit is a Clock-shaped split: the children are grouped in a circle. -# The numbering is a little different from a real clock: the 12 o'clock -# position is called 0, not 12. This is a little easier since Python -# usually counts from zero. (BTW, there needn't be exactly 12 children.) - - -from math import pi, sin, cos -from Split import Split - -class CSplit(Split): - # - def getminsize(self, m, (width, height)): - # Since things look best if the children are spaced evenly - # along the circle (and often all children have the same - # size anyway) we compute the max child size and assume - # this is each child's size. - for child in self.children: - wi, he = child.getminsize(m, (0, 0)) - width = max(width, wi) - height = max(height, he) - # In approximation, the diameter of the circle we need is - # (diameter of box) * (#children) / pi. - # We approximate pi by 3 (so we slightly overestimate - # our minimal size requirements -- not so bad). - # Because the boxes stick out of the circle we add the - # box size to each dimension. - # Because we really deal with ellipses, do everything - # separate in each dimension. - n = len(self.children) - return width + (width*n + 2)/3, height + (height*n + 2)/3 - # - def getbounds(self): - return self.bounds - # - def setbounds(self, bounds): - self.bounds = bounds - # Place the children. This involves some math. - # Compute center positions for children as if they were - # ellipses with a diameter about 1/N times the - # circumference of the big ellipse. - # (There is some rounding involved to make it look - # reasonable for small and large N alike.) - # XXX One day Python will have automatic conversions... - n = len(self.children) - fn = float(n) - if n == 0: return - (left, top), (right, bottom) = bounds - width, height = right-left, bottom-top - child_width, child_height = width*3/(n+4), height*3/(n+4) - half_width, half_height = \ - float(width-child_width)/2.0, \ - float(height-child_height)/2.0 - center_h, center_v = center = (left+right)/2, (top+bottom)/2 - fch, fcv = float(center_h), float(center_v) - alpha = 2.0 * pi / fn - for i in range(n): - child = self.children[i] - fi = float(i) - fh, fv = \ - fch + half_width*sin(fi*alpha), \ - fcv - half_height*cos(fi*alpha) - left, top = \ - int(fh) - child_width/2, \ - int(fv) - child_height/2 - right, bottom = \ - left + child_width, \ - top + child_height - child.setbounds(((left, top), (right, bottom))) - # diff --git a/Lib/lib-stdwin/DirList.py b/Lib/lib-stdwin/DirList.py deleted file mode 100644 index 446d33b04c..0000000000 --- a/Lib/lib-stdwin/DirList.py +++ /dev/null @@ -1,58 +0,0 @@ -# DirList -- Directory Listing widget - -# XXX Displays messy paths when following '..' - -import os -import stdwin, rect -from stdwinevents import * -from Buttons import PushButton -from WindowParent import WindowParent -from HVSplit import HSplit, VSplit - -class DirList(VSplit): - # - def create(self, parent, dirname): - self = VSplit.create(self, parent) - names = os.listdir(dirname) - for name in names: - if os.path.isdir(os.path.join(dirname, name)): - fullname = os.path.join(dirname, name) - btn = SubdirButton().definetext(self, fullname) - elif name[-3:] == '.py': - btn = ModuleButton().definetext(self, name) - else: - btn = FileButton().definetext(self, name) - return self - # - -class DirListWindow(WindowParent): - # - def create(self, dirname): - self = WindowParent.create(self, dirname, (0, 0)) - child = DirList().create(self, dirname) - self.realize() - return self - # - -class SubdirButton(PushButton): - # - def drawpict(self, d): - PushButton.drawpict(self, d) - d.box(rect.inset(self.bounds, (3, 1))) - # - def up_trigger(self): - window = DirListWindow().create(self.text) - # - -class FileButton(PushButton): - # - def up_trigger(self): - stdwin.fleep() - # - -class ModuleButton(FileButton): - # - def drawpict(self, d): - PushButton.drawpict(self, d) - d.box(rect.inset(self.bounds, (1, 3))) - # diff --git a/Lib/lib-stdwin/FormSplit.py b/Lib/lib-stdwin/FormSplit.py deleted file mode 100644 index 271cb23fc1..0000000000 --- a/Lib/lib-stdwin/FormSplit.py +++ /dev/null @@ -1,58 +0,0 @@ -# A FormSplit lets you place its children exactly where you want them -# (including silly places!). -# It does no explicit geometry management except moving its children -# when it is moved. -# The interface to place children is as follows. -# Before you add a child, you may specify its (left, top) position -# relative to the FormSplit. If you don't specify a position for -# a child, it goes right below the previous child; the first child -# goes to (0, 0) by default. -# NB: This places data attributes named form_* on its children. -# XXX Yes, I know, there should be options to do all sorts of relative -# placement, but for now this will do. - -from Split import Split - -class FormSplit(Split): - # - def create(self, parent): - self.next_left = self.next_top = 0 - self.last_child = None - return Split.create(self, parent) - # - def getminsize(self, m, sugg_size): - max_width, max_height = 0, 0 - for c in self.children: - c.form_width, c.form_height = c.getminsize(m, (0, 0)) - max_width = max(max_width, c.form_width + c.form_left) - max_height = max(max_height, \ - c.form_height + c.form_top) - return max_width, max_height - # - def getbounds(self): - return self.bounds - # - def setbounds(self, bounds): - self.bounds = bounds - fleft, ftop = bounds[0] - for c in self.children: - left, top = c.form_left + fleft, c.form_top + ftop - right, bottom = left + c.form_width, top + c.form_height - c.setbounds(((left, top), (right, bottom))) - # - def placenext(self, left, top): - self.next_left = left - self.next_top = top - self.last_child = None - # - def addchild(self, child): - if self.last_child: - width, height = \ - self.last_child.getminsize(self.beginmeasuring(), \ - (0, 0)) - self.next_top = self.next_top + height - child.form_left = self.next_left - child.form_top = self.next_top - Split.addchild(self, child) - self.last_child = child - # diff --git a/Lib/lib-stdwin/HVSplit.py b/Lib/lib-stdwin/HVSplit.py deleted file mode 100644 index 62e0de75f7..0000000000 --- a/Lib/lib-stdwin/HVSplit.py +++ /dev/null @@ -1,62 +0,0 @@ -# HVSplit contains generic code for HSplit and VSplit. -# HSplit and VSplit are specializations to either dimension. - -# XXX This does not yet stretch/shrink children if there is too much -# XXX or too little space in the split dimension. -# XXX (NB There is no interface to ask children for stretch preferences.) - -from Split import Split - -class HVSplit(Split): - # - def create(self, parent, hv): - # hv is 0 for HSplit, 1 for VSplit - self = Split.create(self, parent) - self.hv = hv - return self - # - def getminsize(self, m, sugg_size): - hv, vh = self.hv, 1 - self.hv - size = [0, 0] - sugg_size = [sugg_size[0], sugg_size[1]] - sugg_size[hv] = 0 - sugg_size = sugg_size[0], sugg_size[1] # Make a tuple - for c in self.children: - csize = c.getminsize(m, sugg_size) - if csize[vh] > size[vh]: size[vh] = csize[vh] - size[hv] = size[hv] + csize[hv] - return size[0], size[1] - # - def getbounds(self): - return self.bounds - # - def setbounds(self, bounds): - self.bounds = bounds - hv, vh = self.hv, 1 - self.hv - mf = self.parent.beginmeasuring - begin, end = bounds - sugg_size = end[0] - begin[0], end[1] - begin[1] - size = self.getminsize(mf(), sugg_size) - origin = [begin[0], begin[1]] - sugg_size = [sugg_size[0], sugg_size[1]] # Make a list - sugg_size[hv] = 0 - sugg_size = sugg_size[0], sugg_size[1] # Make a tuple - for c in self.children: - size = c.getminsize(mf(), sugg_size) - corner = [0, 0] - corner[vh] = end[vh] - corner[hv] = origin[hv] + size[hv] - c.setbounds(((origin[0], origin[1]), \ - (corner[0], corner[1]))) - origin[hv] = corner[hv] - # XXX stretch - # XXX too-small - # - -class HSplit(HVSplit): - def create(self, parent): - return HVSplit.create(self, parent, 0) - -class VSplit(HVSplit): - def create(self, parent): - return HVSplit.create(self, parent, 1) diff --git a/Lib/lib-stdwin/Histogram.py b/Lib/lib-stdwin/Histogram.py deleted file mode 100644 index 74a75f374f..0000000000 --- a/Lib/lib-stdwin/Histogram.py +++ /dev/null @@ -1,36 +0,0 @@ -# Module 'Histogram' - -from Buttons import * - -# A Histogram displays a histogram of numeric data. -# -class HistogramAppearance(LabelAppearance, Define): - # - def define(self, parent): - Define.define(self, (parent, '')) - self.ydata = [] - self.scale = (0, 100) - return self - # - def setdata(self, ydata, scale): - self.ydata = ydata - self.scale = scale # (min, max) - self.parent.change(self.bounds) - # - def drawpict(self, d): - (left, top), (right, bottom) = self.bounds - min, max = self.scale - size = max-min - width, height = right-left, bottom-top - ydata = self.ydata - npoints = len(ydata) - v1 = top + height # constant - h1 = left # changed in loop - for i in range(npoints): - h0 = h1 - v0 = top + height - (ydata[i]-min)*height/size - h1 = left + (i+1) * width/npoints - d.paint((h0, v0), (h1, v1)) - # - -class Histogram(NoReactivity, HistogramAppearance): pass diff --git a/Lib/lib-stdwin/Sliders.py b/Lib/lib-stdwin/Sliders.py deleted file mode 100644 index cbf776daee..0000000000 --- a/Lib/lib-stdwin/Sliders.py +++ /dev/null @@ -1,174 +0,0 @@ -# Module 'Sliders' - - -import stdwin -from stdwinevents import * -import rect -from Buttons import * -from HVSplit import HSplit - - -# Field indices in event detail -# -_HV = 0 -_CLICKS = 1 -_BUTTON = 2 -_MASK = 3 - - -# DragSlider is the simplest possible slider. -# It looks like a button but dragging the mouse left or right -# changes the controlled value. -# It does not support any of the triggers or hooks defined by Buttons, -# but defines its own setval_trigger and setval_hook. -# -class DragSliderReactivity(BaseReactivity): - # - def mouse_down(self, detail): - h, v = hv = detail[_HV] - if self.enabled and self.mousetest(hv): - self.anchor = h - self.oldval = self.val - self.active = 1 - # - def mouse_move(self, detail): - if self.active: - h, v = detail[_HV] - self.setval(self.oldval + (h - self.anchor)) - # - def mouse_up(self, detail): - if self.active: - h, v = detail[_HV] - self.setval(self.oldval + (h - self.anchor)) - self.active = 0 - # - -class DragSliderAppearance(ButtonAppearance): - # - # INVARIANTS maintained by the setval method: - # - # self.min <= self.val <= self.max - # self.text = self.pretext + `self.val` + self.postext - # - # (Notice that unlike Python ranges, the end point belongs - # to the range.) - # - def init_appearance(self): - ButtonAppearance.init_appearance(self) - self.min = 0 - self.val = 0 - self.max = 100 - self.hook = 0 - self.pretext = self.postext = '' - self.recalctext() - # - # The 'get*' and 'set*' methods belong to the generic slider interface - # - def getval(self): return self.val - # - def sethook(self, hook): - self.hook = hook - # - def setminvalmax(self, min, val, max): - self.min = min - self.max = max - self.setval(val) - # - def settexts(self, pretext, postext): - self.pretext = pretext - self.postext = postext - self.recalctext() - # - def setval(self, val): - val = min(self.max, max(self.min, val)) - if val <> self.val: - self.val = val - self.recalctext() - self.trigger() - # - def trigger(self): - if self.hook: - self.hook(self) - # - def recalctext(self): - self.settext(self.pretext + `self.val` + self.postext) - # - -class DragSlider(DragSliderReactivity, DragSliderAppearance, Define): - def definetext(self, parent, text): - raise RuntimeError, 'DragSlider.definetext() not supported' - - -# Auxiliary class for PushButton incorporated in ComplexSlider -# -class _StepButton(PushButton): - def define(self, parent): - self = PushButton.define(self, parent) - self.step = 0 - return self - def setstep(self, step): - self.step = step - def definetextstep(self, parent, text, step): - self = self.definetext(parent, text) - self.setstep(step) - return self - def init_reactivity(self): - PushButton.init_reactivity(self) - self.parent.need_timer(self) - def step_trigger(self): - self.parent.setval(self.parent.getval() + self.step) - def down_trigger(self): - self.step_trigger() - self.parent.settimer(5) - def timer(self): - if self.hilited: - self.step_trigger() - if self.active: - self.parent.settimer(1) - - -# A complex slider is an HSplit initialized to three buttons: -# one to step down, a dragslider, and one to step up. -# -class ComplexSlider(HSplit): - # - # Override Slider define() method - # - def define(self, parent): - self = self.create(parent) # HSplit - # - self.downbutton = _StepButton().definetextstep(self, '-', -1) - self.dragbutton = DragSlider().define(self) - self.upbutton = _StepButton().definetextstep(self, '+', 1) - # - return self - # - # Override HSplit methods - # - def getminsize(self, m, (width, height)): - w1, h1 = self.downbutton.getminsize(m, (0, height)) - w3, h3 = self.upbutton.getminsize(m, (0, height)) - w1 = max(w1, h1) - w3 = max(w3, h3) - w2, h2 = self.dragbutton.getminsize(m, (width-w1-w3, height)) - return w1+w2+w3, max(h1, h2, h3) - # - def setbounds(self, bounds): - (left, top), (right, bottom) = self.bounds = bounds - size = bottom - top - self.downbutton.setbounds(((left, top), (left+size, bottom))) - self.dragbutton.setbounds(((left+size, top), \ - (right-size, bottom))) - self.upbutton.setbounds(((right-size, top), (right, bottom))) - # - # Pass other Slider methods on to dragbutton - # - def getval(self): return self.dragbutton.getval() - def sethook(self, hook): self.dragbutton.sethook(hook) - def setminvalmax(self, args): self.dragbutton.setminvalmax(args) - def settexts(self, args): self.dragbutton.settexts(args) - def setval(self, val): self.dragbutton.setval(val) - def enable(self, flag): - self.downbutton.enable(flag) - self.dragbutton.enable(flag) - self.upbutton.enable(flag) diff --git a/Lib/lib-stdwin/Soundogram.py b/Lib/lib-stdwin/Soundogram.py deleted file mode 100644 index e3c797e3dd..0000000000 --- a/Lib/lib-stdwin/Soundogram.py +++ /dev/null @@ -1,36 +0,0 @@ -# Module 'Soundogram' - -import audio -from Histogram import Histogram - -class Soundogram(Histogram): - # - def define(self, win, chunk): - width, height = corner = win.getwinsize() - bounds = (0, 0), corner - self.chunk = chunk - self.step = (len(chunk)-1)/(width/2+1) + 1 - ydata = _make_ydata(chunk, self.step) - return Histogram.define(self, (win, bounds, ydata, (0, 128))) - # - def setchunk(self, chunk): - self.chunk = chunk - self.recompute() - # - def recompute(self): - (left, top), (right, bottom) = self.bounds - width = right - left - self.step = (len(chunk)-1)/width + 1 - ydata = _make_ydata(chunk, self.step) - self.setdata(ydata, (0, 128)) - # - - -def _make_ydata(chunk, step): - ydata = [] - for i in range(0, len(chunk), step): - piece = audio.chr2num(chunk[i:i+step]) - mi, ma = min(piece), max(piece) - y = max(abs(mi), abs(ma)) - ydata.append(y) - return ydata diff --git a/Lib/lib-stdwin/Split.py b/Lib/lib-stdwin/Split.py deleted file mode 100644 index 5ff98088c4..0000000000 --- a/Lib/lib-stdwin/Split.py +++ /dev/null @@ -1,211 +0,0 @@ -# Generic Split implementation. -# Use as a base class for other splits. -# Derived classes should at least implement the methods that call -# unimpl() below: getminsize(), getbounds() and setbounds(). - -Error = 'Split.Error' # Exception - -import rect -from stdwinevents import * - -class Split: - # - # Calls from creator - # NB derived classes may add parameters to create() - # - def create(self, parent): - parent.addchild(self) - self.parent = parent - self.children = [] - self.mouse_interest = [] - self.keybd_interest = [] - self.timer_interest = [] - self.altdraw_interest = [] - self.mouse_focus = None - self.keybd_focus = None - return self - # - # Downcalls from parent to child - # - def destroy(self): - self.parent = None - for child in self.children: - child.destroy() - del self.children[:] - del self.mouse_interest[:] - del self.keybd_interest[:] - del self.timer_interest[:] - del self.altdraw_interest[:] - self.mouse_focus = None - self.keybd_focus = None - # - def getminsize(self, m, (width, height)): - return unimpl() # Should ask children - def getbounds(self): - return unimpl() - def setbounds(self, bounds): - unimpl() # Should tell children - # - def realize(self): - for child in self.children: - child.realize() - # - def draw(self, d, detail): - # (Could avoid calls to children outside the area) - for child in self.children: - child.draw(d, detail) - # - def altdraw(self, detail): - for child in self.altdraw_interest: - child.altdraw(detail) - # - # Keyboard focus handling (used internally) - # XXX This is not enough if two levels of splits - # XXX surround text fields! - # - def set_keybd_focus(self, child): - if self.keybd_focus <> child: - if self.keybd_focus: - self.keybd_focus.deactivate() - self.keybd_focus = None - if child: - child.activate() - self.keybd_focus = child - def next_keybd_focus(self): - if not self.keybd_interest: - self.set_keybd_focus(None) - return - if self.keybd_focus in self.keybd_interest: - i = self.keybd_interest.index(self.keybd_focus) - i = (i+1) % len(self.keybd_interest) - else: - i = 0 - self.set_keybd_focus(self.keybd_interest[i]) - # - # Downcalls only made after certain upcalls - # - def mouse_down(self, detail): - if self.mouse_focus: - self.mouse_focus.mouse_down(detail) - return - p = detail[0] - for child in self.mouse_interest: - if rect.pointinrect(p, child.getbounds()): - self.mouse_focus = child - if child in self.keybd_interest: - self.set_keybd_focus(child) - child.mouse_down(detail) - def mouse_move(self, detail): - if self.mouse_focus: - self.mouse_focus.mouse_move(detail) - def mouse_up(self, detail): - if self.mouse_focus: - self.mouse_focus.mouse_up(detail) - self.mouse_focus = None - # - def activate(self): - if self.keybd_focus: - self.keybd_focus.activate() - else: - self.next_keybd_focus() - def deactivate(self): - if self.keybd_focus: - self.keybd_focus.deactivate() - # - def keybd(self, type, detail): - if not self.keybd_focus: - self.set_keybd_focus(self.keybd_interest[0]) - if type == WE_COMMAND and detail == WC_TAB and \ - len(self.keybd_interest) > 1: - self.next_keybd_focus() - return - self.keybd_focus.keybd(type, detail) - # - def timer(self): - for child in self.timer_interest: - child.timer() - # - # Upcalls from child to parent - # - def addchild(self, child): - if child in self.children: - raise Error, 'addchild: child already inlist' - self.children.append(child) - def delchild(self, child): - if child not in self.children: - raise Error, 'delchild: child not in list' - self.children.remove(child) - if child in self.mouse_interest: - self.mouse_interest.remove(child) - if child in self.keybd_interest: - self.keybd_interest.remove(child) - if child in self.timer_interest: - self.timer_interest.remove(child) - if child in self.altdraw_interest: - self.altdraw_interest.remove(child) - if child == self.mouse_focus: - self.mouse_focus = None - if child == self.keybd_focus: - self.keybd_focus = None - # - def need_mouse(self, child): - if child not in self.mouse_interest: - self.mouse_interest.append(child) - self.parent.need_mouse(self) - def no_mouse(self, child): - if child == self.mouse_focus: - self.mouse_focus = None - if child in self.mouse_interest: - self.mouse_interest.remove(child) - if not self.mouse_interest: - self.parent.no_mouse(self) - # - def need_keybd(self, child): - if child not in self.keybd_interest: - self.keybd_interest.append(child) - self.parent.need_keybd(self) - if not self.keybd_focus: - self.set_keybd_focus(child) - def no_keybd(self, child): - if child == self.keybd_focus: - self.keybd_focus = None # Don't call child.deactivate() - if child in self.keybd_interest: - self.keybd_interest.remove(child) - if not self.keybd_interest: - self.parent.no_keybd(self) - # - def need_timer(self, child): - if child not in self.timer_interest: - self.timer_interest.append(child) - self.parent.need_timer(self) - def no_timer(self, child): - if child in self.timer_interest: - self.timer_interest.remove(child) - if not self.timer_interest: - self.parent.no_timer(self) - # - def need_altdraw(self, child): - if child not in self.altdraw_interest: - self.altdraw_interest.append(child) - self.parent.need_altdraw(self) - def no_altdraw(self, child): - if child in self.altdraw_interest: - self.altdraw_interest.remove(child) - if not self.altdraw_interest: - self.parent.no_altdraw(self) - # - # The rest are transparent: - # - def begindrawing(self): - return self.parent.begindrawing() - def beginmeasuring(self): - return self.parent.beginmeasuring() - def getwindow(self): - return self.parent.getwindow() - # - def change(self, area): - self.parent.change(area) - def scroll(self, area, vector): - self.parent.scroll(area, vector) - def settimer(self, itimer): - self.parent.settimer(itimer) diff --git a/Lib/lib-stdwin/StripChart.py b/Lib/lib-stdwin/StripChart.py deleted file mode 100644 index afec007ae4..0000000000 --- a/Lib/lib-stdwin/StripChart.py +++ /dev/null @@ -1,70 +0,0 @@ -# Module 'StripChart' - -import rect -from Buttons import LabelAppearance, NoReactivity - -# A StripChart doesn't really look like a label but it needs a base class. -# LabelAppearance allows it to be disabled and hilited. - -class StripChart(LabelAppearance, NoReactivity): - # - def define(self, parent, scale): - self.parent = parent - parent.addchild(self) - self.init_appearance() - self.init_reactivity() - self.ydata = [] - self.scale = scale - self.resetbounds() - return self - # - def destroy(self): - self.parent = 0 - # - def setbounds(self, bounds): - LabelAppearance.setbounds(self, bounds) - self.resetbounds() - # - def resetbounds(self): - (left, top), (right, bottom) = self.bounds - self.width = right-left - self.height = bottom-top - excess = len(self.ydata) - self.width - if excess > 0: - del self.ydata[:excess] - elif excess < 0: - while len(self.ydata) < self.width: - self.ydata.insert(0, 0) - # - def append(self, y): - self.ydata.append(y) - excess = len(self.ydata) - self.width - if excess > 0: - del self.ydata[:excess] - if self.bounds <> rect.empty: - self.parent.scroll(self.bounds, (-excess, 0)) - if self.bounds <> rect.empty: - (left, top), (right, bottom) = self.bounds - i = len(self.ydata) - area = (left+i-1, top), (left+i, bottom) - self.draw(self.parent.begindrawing(), area) - # - def draw(self, d, area): - area = rect.intersect([area, self.bounds]) - if area == rect.empty: - return - d.cliprect(area) - d.erase(self.bounds) - (a_left, a_top), (a_right, a_bottom) = area - (left, top), (right, bottom) = self.bounds - height = bottom - top - i1 = a_left - left - i2 = a_right - left - for i in range(max(0, i1), min(len(self.ydata), i2)): - split = bottom-self.ydata[i]*height/self.scale - d.paint((left+i, split), (left+i+1, bottom)) - if not self.enabled: - self.flipenable(d) - if self.hilited: - self.fliphilite(d) - d.noclip() diff --git a/Lib/lib-stdwin/TextEdit.py b/Lib/lib-stdwin/TextEdit.py deleted file mode 100644 index e08e496811..0000000000 --- a/Lib/lib-stdwin/TextEdit.py +++ /dev/null @@ -1,126 +0,0 @@ -# Text editing widget - -# NB: this always assumes fixed bounds. -# For auto-growing TextEdit windows, different code would be needed. - -from stdwinevents import * - -class TextEdit: - # - def create(self, parent, (cols, rows)): - parent.addchild(self) - self.parent = parent - self.cols = cols - self.rows = rows - self.text = '' - # Creation of the editor is done in realize() - self.editor = None - self.dh = self.dv = 0 - return self - # - def createboxed(self, parent, (cols, rows), (dh, dv)): - self = self.create(parent, (cols, rows)) - self.dh = max(0, dh) - self.dv = max(0, dv) - return self - # - def settext(self, text): - self.editor.settext(text) - # - def gettext(self): - return self.editor.gettext(text) - # - # Downcalls from parent to child - # - def destroy(self): - del self.parent - del self.editor - del self.window - # - def getminsize(self, m, (width, height)): - width = max(0, width - 2*self.dh) - height = max(0, height - 2*self.dv) - if width > 0 and self.editor: - (left, top), (right, bottom) = self.editor.getrect() - act_width, act_height = right - left, bottom - top - if width >= act_width: - width = width + 2*self.dh - height = max(height, act_height) + 2*self.dv - return width, height - width = max(width, self.cols*m.textwidth('in')/2) + 2*self.dh - height = max(height, self.rows*m.lineheight()) + 2*self.dv - return width, height - # - def setbounds(self, bounds): - self.bounds = bounds - if self.editor: - (left, top), (right, bottom) = bounds - left = left + self.dh - top = top + self.dv - right = right - self.dh - bottom = bottom - self.dv - self.editor.move((left, top), (right, bottom)) - if self.dh and self.dv: - (left, top), (right, bottom) = bounds - left = left + 1 - top = top + 1 - right = right - 1 - bottom = bottom - 1 - bounds = (left, top), (right, bottom) - self.editor.setview(bounds) - # - def getbounds(self): - return self.bounds - # - def realize(self): - self.window = self.parent.getwindow() - (left, top), (right, bottom) = self.bounds - left = left + self.dh - top = top + self.dv - right = right - self.dh - bottom = bottom - self.dv - self.editor = \ - self.window.textcreate((left, top), (right, bottom)) - self.editor.setactive(0) - bounds = self.bounds - if self.dh and self.dv: - (left, top), (right, bottom) = bounds - left = left + 1 - top = top + 1 - right = right - 1 - bottom = bottom - 1 - bounds = (left, top), (right, bottom) - self.editor.setview(bounds) - self.editor.settext(self.text) - self.parent.need_mouse(self) - self.parent.need_keybd(self) - self.parent.need_altdraw(self) - # - def draw(self, d, area): - if self.dh and self.dv: - d.box(self.bounds) - # - def altdraw(self, area): - self.editor.draw(area) - # - # Event downcalls - # - def mouse_down(self, detail): - x = self.editor.event(WE_MOUSE_DOWN, self.window, detail) - # - def mouse_move(self, detail): - x = self.editor.event(WE_MOUSE_MOVE, self.window, detail) - # - def mouse_up(self, detail): - x = self.editor.event(WE_MOUSE_UP, self.window, detail) - # - def keybd(self, type, detail): - x = self.editor.event(type, self.window, detail) - # - def activate(self): - self.editor.setfocus(0, 30000) - self.editor.setactive(1) - # - def deactivate(self): - self.editor.setactive(0) - # diff --git a/Lib/lib-stdwin/TransParent.py b/Lib/lib-stdwin/TransParent.py deleted file mode 100644 index 49dcd3d071..0000000000 --- a/Lib/lib-stdwin/TransParent.py +++ /dev/null @@ -1,123 +0,0 @@ -# A class that sits transparently between a parent and one child. -# First create the parent, then this thing, then the child. -# Use this as a base class for objects that are almost transparent. -# Don't use as a base class for parents with multiple children. - -Error = 'TransParent.Error' # Exception - -class ManageOneChild: - # - # Upcalls shared with other single-child parents - # - def addchild(self, child): - if self.child: - raise Error, 'addchild: one child only' - if not child: - raise Error, 'addchild: bad child' - self.child = child - # - def delchild(self, child): - if not self.child: - raise Error, 'delchild: no child' - if child <> self.child: - raise Error, 'delchild: not my child' - self.child = 0 - -class TransParent(ManageOneChild): - # - # Calls from creator - # NB derived classes may add parameters to create() - # - def create(self, parent): - parent.addchild(self) - self.parent = parent - self.child = None # No child yet - return self - # - # Downcalls from parent to child - # - def destroy(self): - del self.parent - if self.child: self.child.destroy() - del self.child - # - def getminsize(self, args): - if not self.child: - m, size = args - return size - else: - return self.child.getminsize(args) - def getbounds(self, bounds): - if not self.child: - raise Error, 'getbounds w/o child' - else: - return self.child.getbounds() - def setbounds(self, bounds): - if not self.child: - raise Error, 'setbounds w/o child' - else: - self.child.setbounds(bounds) - def realize(self): - if self.child: - self.child.realize() - def draw(self, d, area): - if self.child: - self.child.draw(d, area) - def altdraw(self, area): - if self.child: - self.child.altdraw(area) - # - # Downcalls only made after certain upcalls - # - def mouse_down(self, detail): - if self.child: self.child.mouse_down(detail) - def mouse_move(self, detail): - if self.child: self.child.mouse_move(detail) - def mouse_up(self, detail): - if self.child: self.child.mouse_up(detail) - # - def keybd(self, type_detail): - self.child.keybd(type_detail) - def activate(self): - self.child.activate() - def deactivate(self): - self.child.deactivate() - # - def timer(self): - if self.child: self.child.timer() - # - # Upcalls from child to parent - # - def need_mouse(self, child): - self.parent.need_mouse(self) - def no_mouse(self, child): - self.parent.no_mouse(self) - # - def need_timer(self, child): - self.parent.need_timer(self) - def no_timer(self, child): - self.parent.no_timer(self) - # - def need_altdraw(self, child): - self.parent.need_altdraw(self) - def no_altdraw(self, child): - self.parent.no_altdraw(self) - # - def need_keybd(self, child): - self.parent.need_keybd(self) - def no_keybd(self, child): - self.parent.no_keybd(self) - # - def begindrawing(self): - return self.parent.begindrawing() - def beginmeasuring(self): - return self.parent.beginmeasuring() - def getwindow(self): - return self.parent.getwindow() - # - def change(self, area): - self.parent.change(area) - def scroll(self, area, vector): - self.parent.scroll(area, vector) - def settimer(self, itimer): - self.parent.settimer(itimer) diff --git a/Lib/lib-stdwin/VUMeter.py b/Lib/lib-stdwin/VUMeter.py deleted file mode 100644 index ed9a4738c1..0000000000 --- a/Lib/lib-stdwin/VUMeter.py +++ /dev/null @@ -1,47 +0,0 @@ -# Module 'VUMeter' - -import audio -from StripChart import StripChart - -K = 1024 -Rates = [0, 32*K, 16*K, 8*K] - -class VUMeter(StripChart): - # - # Override define() and timer() methods - # - def define(self, parent): - self = StripChart.define(self, (parent, 128)) - self.parent.need_timer(self) - self.sampling = 0 - self.rate = 3 - self.enable(0) - return self - # - def timer(self): - if self.sampling: - chunk = audio.wait_recording() - self.sampling = 0 - nums = audio.chr2num(chunk) - ampl = max(abs(min(nums)), abs(max(nums))) - self.append(ampl) - if self.enabled and not self.sampling: - audio.setrate(self.rate) - size = Rates[self.rate]/10 - size = size/48*48 - audio.start_recording(size) - self.sampling = 1 - if self.sampling: - self.parent.settimer(1) - # - # New methods: start() and stop() - # - def stop(self): - if self.sampling: - chunk = audio.stop_recording() - self.sampling = 0 - self.enable(0) - # - def start(self): - self.enable(1) - self.timer() diff --git a/Lib/lib-stdwin/WindowParent.py b/Lib/lib-stdwin/WindowParent.py deleted file mode 100644 index cdec10b283..0000000000 --- a/Lib/lib-stdwin/WindowParent.py +++ /dev/null @@ -1,189 +0,0 @@ -# A 'WindowParent' is the only module that uses real stdwin functionality. -# It is the root of the tree. -# It should have exactly one child when realized. -# -# There is also an alternative interface to "mainloop" here. - -import stdwin -from stdwinevents import * -import mainloop - -from TransParent import ManageOneChild - -Error = 'WindowParent.Error' # Exception - -class WindowParent(ManageOneChild): - # - def create(self, title, size): - self.title = title - self.size = size # (width, height) - self._reset() - self.close_hook = WindowParent.delayed_destroy - return self - # - def _reset(self): - self.child = None - self.win = None - self.itimer = 0 - self.do_mouse = 0 - self.do_keybd = 0 - self.do_timer = 0 - self.do_altdraw = 0 - self.pending_destroy = 0 - self.close_hook = None - self.menu_hook = None - # - def destroy(self): - mainloop.unregister(self.win) - if self.child: self.child.destroy() - self._reset() - # - def delayed_destroy(self): - # This interface to be used by 'Close' buttons etc.; - # destroying a window from within a button hook - # is not a good idea... - self.pending_destroy = 1 - # - def close_trigger(self): - if self.close_hook: self.close_hook(self) - # - def menu_trigger(self, menu, item): - if self.menu_hook: - self.menu_hook(self, menu, item) - # - def need_mouse(self, child): self.do_mouse = 1 - def no_mouse(self, child): self.do_mouse = 0 - # - def need_keybd(self, child): - self.do_keybd = 1 - self.child.activate() - def no_keybd(self, child): - self.do_keybd = 0 - self.child.deactivate() - # - def need_timer(self, child): self.do_timer = 1 - def no_timer(self, child): self.do_timer = 0 - # - def need_altdraw(self, child): self.do_altdraw = 1 - def no_altdraw(self, child): self.do_altdraw = 0 - # - def realize(self): - if self.win: - raise Error, 'realize(): called twice' - if not self.child: - raise Error, 'realize(): no child' - # Compute suggested size - self.size = self.child.getminsize(self.beginmeasuring(), \ - self.size) - save_defsize = stdwin.getdefwinsize() - scrwidth, scrheight = stdwin.getscrsize() - width, height = self.size - if width > scrwidth: - width = scrwidth * 2/3 - if height > scrheight: - height = scrheight * 2/3 - stdwin.setdefwinsize(width, height) - self.hbar, self.vbar = stdwin.getdefscrollbars() - self.win = stdwin.open(self.title) - stdwin.setdefwinsize(save_defsize) - self.win.setdocsize(self.size) - if self.itimer: - self.win.settimer(self.itimer) - width, height = self.win.getwinsize() - if self.hbar: - width = self.size[0] - if self.vbar: - height = self.size[1] - self.child.setbounds(((0, 0), (width, height))) - self.child.realize() - self.win.dispatch = self.dispatch - mainloop.register(self.win) - # - def fixup(self): - # XXX This could share code with realize() above - self.size = self.child.getminsize(self.beginmeasuring(), \ - self.win.getwinsize()) - self.win.setdocsize(self.size) - width, height = self.win.getwinsize() - if self.hbar: - width = self.size[0] - if self.vbar: - height = self.size[1] - self.child.setbounds(((0, 0), (width, height))) - # Force a redraw of the entire window: - self.win.change((0, 0), self.size) - # - def beginmeasuring(self): - # Return something with which a child can measure text - if self.win: - return self.win.begindrawing() - else: - return stdwin - # - def begindrawing(self): - if self.win: - return self.win.begindrawing() - else: - raise Error, 'begindrawing(): not realized yet' - # - def getwindow(self): - if self.win: - return self.win - else: - raise Error, 'getwindow(): not realized yet' - # - def change(self, area): - if self.win: - self.win.change(area) - # - def scroll(self, area, vector): - if self.win: - self.win.scroll(area, vector) - # - def settimer(self, itimer): - if self.win: - self.win.settimer(itimer) - else: - self.itimer = itimer - # - # Only call dispatch once we are realized - # - def dispatch(self, (type, win, detail)): - if type == WE_DRAW: - d = self.win.begindrawing() - self.child.draw(d, detail) - del d - if self.do_altdraw: self.child.altdraw(detail) - elif type == WE_MOUSE_DOWN: - if self.do_mouse: self.child.mouse_down(detail) - elif type == WE_MOUSE_MOVE: - if self.do_mouse: self.child.mouse_move(detail) - elif type == WE_MOUSE_UP: - if self.do_mouse: self.child.mouse_up(detail) - elif type in (WE_CHAR, WE_COMMAND): - if self.do_keybd: self.child.keybd(type, detail) - elif type == WE_TIMER: - if self.do_timer: self.child.timer() - elif type == WE_SIZE: - self.fixup() - elif type == WE_CLOSE: - self.close_trigger() - elif type == WE_MENU: - self.menu_trigger(detail) - if self.pending_destroy: - self.destroy() - # - -def MainLoop(): - mainloop.mainloop() - -def Dispatch(event): - mainloop.dispatch(event) - -# Interface used by WindowSched: - -def CountWindows(): - return mainloop.countwindows() - -def AnyWindow(): - return mainloop.anywindow() diff --git a/Lib/lib-stdwin/WindowSched.py b/Lib/lib-stdwin/WindowSched.py deleted file mode 100644 index b2fbe76563..0000000000 --- a/Lib/lib-stdwin/WindowSched.py +++ /dev/null @@ -1,61 +0,0 @@ -# Combine a real-time scheduling queue and stdwin event handling. -# Keeps times in milliseconds. - -import stdwin, stdwinq -from stdwinevents import WE_TIMER -import mainloop -import sched -import time - -# Delay function called by the scheduler when it has nothing to do. -# Return immediately when something is done, or when the delay is up. -# -def delayfunc(msecs): - # - # Check for immediate stdwin event - # - event = stdwinq.pollevent() - if event: - mainloop.dispatch(event) - return - # - # Use sleep for very short delays or if there are no windows - # - if msecs < 100 or mainloop.countwindows() == 0: - if msecs > 0: - time.sleep(msecs * 0.001) - return - # - # Post a timer event on an arbitrary window and wait for it - # - window = mainloop.anywindow() - window.settimer(msecs/100) - event = stdwinq.getevent() - window.settimer(0) - if event[0] <> WE_TIMER: - mainloop.dispatch(event) - -def millitimer(): - return int(1000 * time.time()) - -q = sched.scheduler(millitimer, delayfunc) - -# Export functions enter, enterabs and cancel just like a scheduler -# -enter = q.enter -enterabs = q.enterabs -cancel = q.cancel - -# Emptiness check must check both queues -# -def empty(): - return q.empty() and mainloop.countwindows() == 0 - -# Run until there is nothing left to do -# -def run(): - while not empty(): - if q.empty(): - mainloop.dispatch(stdwinq.getevent()) - else: - q.run() diff --git a/Lib/lib-stdwin/anywin.py b/Lib/lib-stdwin/anywin.py deleted file mode 100644 index 38ee8690a6..0000000000 --- a/Lib/lib-stdwin/anywin.py +++ /dev/null @@ -1,14 +0,0 @@ -# Module 'anywin' -# Open a file or directory in a window - -import dirwin -import filewin -import os - -def open(name): - print 'opening', name, '...' - if os.path.isdir(name): - w = dirwin.open(name) - else: - w = filewin.open(name) - return w diff --git a/Lib/lib-stdwin/basewin.py b/Lib/lib-stdwin/basewin.py deleted file mode 100644 index 7a43536967..0000000000 --- a/Lib/lib-stdwin/basewin.py +++ /dev/null @@ -1,64 +0,0 @@ -# basewin.py - -import stdwin -import mainloop -from stdwinevents import * - -class BaseWindow: - - def __init__(self, title): - self.win = stdwin.open(title) - self.win.dispatch = self.dispatch - mainloop.register(self.win) - -# def reopen(self): -# title = self.win.gettitle() -# winpos = self.win.getwinpos() -# winsize = self.win.getwinsize() -# origin = self.win.getorigin() -# docsize = self.win.getdocsize() -# mainloop.unregister(self.win) -# del self.win.dispatch -# self.win.close() -# stdwin.setdefwinpos(winpos) -# stdwin.setdefwinsize(winsize) -# self.win = stdwin.open(title) -# stdwin.setdefwinpos(0, 0) -# stdwin.setdefwinsize(0, 0) -# self.win.setdocsize(docsize) -# self.win.setorigin(origin) -# self.win.dispatch = self.dispatch -# mainloop.register(self.win) - - def popup(self): - if self.win is not stdwin.getactive(): - self.win.setactive() - - def close(self): - mainloop.unregister(self.win) - del self.win.dispatch - self.win.close() - - def dispatch(self, event): - type, win, detail = event - if type == WE_CHAR: - self.char(detail) - elif type == WE_COMMAND: - self.command(detail) - elif type == WE_MOUSE_DOWN: - self.mouse_down(detail) - elif type == WE_MOUSE_MOVE: - self.mouse_move(detail) - elif type == WE_MOUSE_UP: - self.mouse_up(detail) - elif type == WE_DRAW: - self.draw(detail) - elif type == WE_CLOSE: - self.close() - - def no_op(self, detail): - pass - char = command = mouse_down = mouse_move = mouse_up = draw = no_op - - def refreshall(self): - self.win.change((-10, 0), (10000, 30000)) diff --git a/Lib/lib-stdwin/dirwin.py b/Lib/lib-stdwin/dirwin.py deleted file mode 100644 index e8b0170207..0000000000 --- a/Lib/lib-stdwin/dirwin.py +++ /dev/null @@ -1,29 +0,0 @@ -# Module 'dirwin' - -# Directory windows, a subclass of listwin - -import os -import gwin -import listwin -import anywin -import dircache - -def action(w, string, i, detail): - (h, v), clicks, button, mask = detail - if clicks == 2: - name = os.path.join(w.name, string) - try: - w2 = anywin.open(name) - w2.parent = w - except os.error, why: - stdwin.message('Can\'t open ' + name + ': ' + why[1]) - -def open(name): - name = os.path.join(name, '') - list = dircache.opendir(name)[:] - list.sort() - dircache.annotate(name, list) - w = listwin.open(name, list) - w.name = name - w.action = action - return w diff --git a/Lib/lib-stdwin/filewin.py b/Lib/lib-stdwin/filewin.py deleted file mode 100644 index df6aa7d7f7..0000000000 --- a/Lib/lib-stdwin/filewin.py +++ /dev/null @@ -1,20 +0,0 @@ -# Module 'filewin' -# File windows, a subclass of textwin (which is a subclass of gwin) - -import textwin -import __builtin__ - - -# FILE WINDOW - -def open_readonly(fn): # Open a file window - fp = __builtin__.open(fn, 'r') - w = textwin.open_readonly(fn, fp.read()) - w.fn = fn - return w - -def open(fn): # Open a file window - fp = __builtin__.open(fn, 'r') - w = textwin.open(fn, fp.read()) - w.fn = fn - return w diff --git a/Lib/lib-stdwin/formatter.py b/Lib/lib-stdwin/formatter.py deleted file mode 100644 index 7ddfc1d680..0000000000 --- a/Lib/lib-stdwin/formatter.py +++ /dev/null @@ -1,207 +0,0 @@ -# A class to help applications that do fancy text formatting. -# You create an instance each time you must redraw the window. -# Set the initial left, top and right coordinates; -# then feed it words, font changes and vertical movements. -# -# This class should eventually be extended to support much fancier -# formatting, along the lines of TeX; for now, a very simple model -# is sufficient. -# -class formatter: - # - # Initialize a formatter instance. - # Pass the window's drawing object, and left, top, right - # coordinates of the drawing space as arguments. - # - def __init__(self, d, left, top, right): - self.d = d # Drawing object - self.left = left # Left margin - self.right = right # Right margin - self.v = top # Top of current line - self.center = 0 - self.justify = 1 - self.setfont('') # Default font - self._reset() # Prepare for new line - # - # Reset for start of fresh line. - # - def _reset(self): - self.boxes = [] # Boxes and glue still to be output - self.sum_width = 0 # Total width of boxes - self.sum_space = 0 # Total space between boxes - self.sum_stretch = 0 # Total stretch for space between boxes - self.max_ascent = 0 # Max ascent of current line - self.max_descent = 0 # Max descent of current line - self.avail_width = self.right - self.left - self.hang_indent = 0 - # - # Set the current font, and compute some values from it. - # - def setfont(self, font): - self.font = font - self.d.setfont(font) - self.font_space = self.d.textwidth(' ') - self.font_ascent = self.d.baseline() - self.font_descent = self.d.lineheight() - self.font_ascent - # - # Add a word to the list of boxes; first flush if line is full. - # Space and stretch factors are expressed in fractions - # of the current font's space width. - # (Two variations: one without, one with explicit stretch factor.) - # - def addword(self, word, spacefactor): - self.addwordstretch(word, spacefactor, spacefactor) - # - def addwordstretch(self, word, spacefactor, stretchfactor): - width = self.d.textwidth(word) - if width > self.avail_width: - self._flush(1) - space = int(float(self.font_space) * float(spacefactor)) - stretch = int(float(self.font_space) * float(stretchfactor)) - box = (self.font, word, width, space, stretch) - self.boxes.append(box) - self.sum_width = self.sum_width + width - self.sum_space = self.sum_space + space - self.sum_stretch = self.sum_stretch + stretch - self.max_ascent = max(self.font_ascent, self.max_ascent) - self.max_descent = max(self.font_descent, self.max_descent) - self.avail_width = self.avail_width - width - space - # - # Flush current line and start a new one. - # Flushing twice is harmless (i.e. does not introduce a blank line). - # (Two versions: the internal one has a parameter for justification.) - # - def flush(self): - self._flush(0) - # - def _flush(self, justify): - if not self.boxes: - return - # - # Compute amount of stretch needed. - # - if justify and self.justify or self.center: - # - # Compute extra space to fill; - # this is avail_width plus glue from last box. - # Also compute available stretch. - # - last_box = self.boxes[len(self.boxes)-1] - font, word, width, space, stretch = last_box - tot_extra = self.avail_width + space - tot_stretch = self.sum_stretch - stretch - else: - tot_extra = tot_stretch = 0 - # - # Output the boxes. - # - baseline = self.v + self.max_ascent - h = self.left + self.hang_indent - if self.center: - h = h + tot_extra / 2 - tot_extra = tot_stretch = 0 - for font, word, width, space, stretch in self.boxes: - self.d.setfont(font) - v = baseline - self.d.baseline() - self.d.text((h, v), word) - h = h + width + space - if tot_extra > 0 and tot_stretch > 0: - extra = stretch * tot_extra / tot_stretch - h = h + extra - tot_extra = tot_extra - extra - tot_stretch = tot_stretch - stretch - # - # Prepare for next line. - # - self.v = baseline + self.max_descent - self.d.setfont(self.font) - self._reset() - # - # Add vertical space; first flush. - # Vertical space is expressed in fractions of the current - # font's line height. - # - def vspace(self, lines): - self.vspacepixels(int(lines * self.d.lineheight())) - # - # Add vertical space given in pixels. - # - def vspacepixels(self, dv): - self.flush() - self.v = self.v + dv - # - # Set temporary (hanging) indent, for paragraph start. - # First flush. - # - def tempindent(self, space): - self.flush() - hang = int(float(self.font_space) * float(space)) - self.hang_indent = hang - self.avail_width = self.avail_width - hang - # - # Add (permanent) left indentation. First flush. - # - def addleftindent(self, space): - self.flush() - self.left = self.left \ - + int(float(self.font_space) * float(space)) - self._reset() - # - - -# Test procedure -# -def test(): - import stdwin, stdwinq - from stdwinevents import * - try: - import mac - # Mac font assignments: - font1 = 'times', '', 12 - font2 = 'times', 'b', 14 - except ImportError: - # X11R4 font assignments - font1 = '*times-medium-r-*-120-*' - font2 = '*times-bold-r-*-140-*' - words = \ - ['The','quick','brown','fox','jumps','over','the','lazy','dog.'] - words = words * 2 - stage = 0 - stages = [(0,0,'ragged'), (1,0,'justified'), (0,1,'centered')] - justify, center, title = stages[stage] - stdwin.setdefwinsize(300,200) - w = stdwin.open(title) - winsize = w.getwinsize() - while 1: - type, window, detail = stdwinq.getevent() - if type == WE_CLOSE: - break - elif type == WE_SIZE: - newsize = w.getwinsize() - if newsize <> winsize: - w.change((0,0), winsize) - winsize = newsize - w.change((0,0), winsize) - elif type == WE_MOUSE_DOWN: - stage = (stage + 1) % len(stages) - justify, center, title = stages[stage] - w.settitle(title) - w.change((0, 0), (1000, 1000)) - elif type == WE_DRAW: - width, height = winsize - f = formatter(w.begindrawing(), 0, 0, width) - f.center = center - f.justify = justify - if not center: - f.tempindent(5) - for font in font1, font2, font1: - f.setfont(font) - for word in words: - space = 1 + (word[-1:] == '.') - f.addword(word, space) - if center and space > 1: - f.flush() - f.flush() - height = f.v - del f - w.setdocsize(0, height) diff --git a/Lib/lib-stdwin/gwin.py b/Lib/lib-stdwin/gwin.py deleted file mode 100644 index 626c8fa2fb..0000000000 --- a/Lib/lib-stdwin/gwin.py +++ /dev/null @@ -1,110 +0,0 @@ -# Module 'gwin' -# Generic stdwin windows - -# This is used as a base class from which to derive other window types. -# XXX DON'T USE THIS CODE ANY MORE! It is ages old! - -import stdwin, stdwinq -from stdwinevents import * -from mainloop import mainloop, register, unregister, windows - -# Open a window - -def open(title): # Open a generic window - w = stdwin.open(title) - stdwin.setdefwinsize(0, 0) - # Set default event handlers - w.draw = nop - w.char = nop - w.mdown = nop - w.mmove = nop - w.mup = nop - w.m2down = m2down - w.m2up = m2up - w.size = nop - w.move = nop - w.activate = w.deactivate = nop - w.timer = nop - # default command handlers - w.close = close - w.tab = tab - w.enter = enter - w.backspace = backspace - w.arrow = arrow - w.kleft = w.kup = w.kright = w.kdown = nop - w.dispatch = treatevent - register(w) - return w - - -def treatevent(e): # Handle a stdwin event - type, w, detail = e - if type == WE_DRAW: - w.draw(w, detail) - elif type == WE_MENU: - m, item = detail - m.action[item](w, m, item) - elif type == WE_COMMAND: - treatcommand(w, detail) - elif type == WE_CHAR: - w.char(w, detail) - elif type == WE_MOUSE_DOWN: - if detail[1] > 1: w.m2down(w, detail) - else: w.mdown(w, detail) - elif type == WE_MOUSE_MOVE: - w.mmove(w, detail) - elif type == WE_MOUSE_UP: - if detail[1] > 1: w.m2up(w, detail) - else: w.mup(w, detail) - elif type == WE_SIZE: - w.size(w, w.getwinsize()) - elif type == WE_ACTIVATE: - w.activate(w) - elif type == WE_DEACTIVATE: - w.deactivate(w) - elif type == WE_MOVE: - w.move(w) - elif type == WE_TIMER: - w.timer(w) - elif type == WE_CLOSE: - w.close(w) - -def treatcommand(w, type): # Handle a we_command event - if type == WC_CLOSE: - w.close(w) - elif type == WC_RETURN: - w.enter(w) - elif type == WC_TAB: - w.tab(w) - elif type == WC_BACKSPACE: - w.backspace(w) - elif type in (WC_LEFT, WC_UP, WC_RIGHT, WC_DOWN): - w.arrow(w, type) - - -# Methods - -def close(w): # Close method - unregister(w) - del w.close # Delete our close function - w.close() # Call the close method - -def arrow(w, detail): # Arrow key method - if detail == WC_LEFT: - w.kleft(w) - elif detail == WC_UP: - w.kup(w) - elif detail == WC_RIGHT: - w.kright(w) - elif detail == WC_DOWN: - w.kdown(w) - - -# Trivial methods - -def tab(w): w.char(w, '\t') -def enter(w): w.char(w, '\n') # 'return' is a Python reserved word -def backspace(w): w.char(w, '\b') -def m2down(w, detail): w.mdown(w, detail) -def m2up(w, detail): w.mup(w, detail) -def nop(*args): pass diff --git a/Lib/lib-stdwin/listwin.py b/Lib/lib-stdwin/listwin.py deleted file mode 100644 index 9480a81fc9..0000000000 --- a/Lib/lib-stdwin/listwin.py +++ /dev/null @@ -1,47 +0,0 @@ -# Module 'listwin' -# List windows, a subclass of gwin - -import gwin -import stdwin - -def maxlinewidth(a): # Compute maximum textwidth of lines in a sequence - max = 0 - for line in a: - width = stdwin.textwidth(line) - if width > max: max = width - return max - -def action(w, string, i, detail): # Default item selection method - pass - -def mup(w, detail): # Mouse up method - (h, v), clicks, button, mask = detail - i = divmod(v, w.lineheight)[0] - if 0 <= i < len(w.data): - w.action(w, w.data[i], i, detail) - -def draw(w, ((left, top), (right, bottom))): # Text window draw method - data = w.data - d = w.begindrawing() - lh = w.lineheight - itop = top/lh - ibot = (bottom-1)/lh + 1 - if itop < 0: itop = 0 - if ibot > len(data): ibot = len(data) - for i in range(itop, ibot): d.text((0, i*lh), data[i]) - -def open(title, data): # Display a list of texts in a window - lineheight = stdwin.lineheight() - h, v = maxlinewidth(data), len(data)*lineheight - h0, v0 = h + stdwin.textwidth(' '), v + lineheight - if h0 > stdwin.textwidth(' ')*80: h0 = 0 - if v0 > stdwin.lineheight()*24: v0 = 0 - stdwin.setdefwinsize(h0, v0) - w = gwin.open(title) - w.setdocsize(h, v) - w.lineheight = lineheight - w.data = data - w.draw = draw - w.action = action - w.mup = mup - return w diff --git a/Lib/lib-stdwin/mainloop.py b/Lib/lib-stdwin/mainloop.py deleted file mode 100644 index aa40c34b4e..0000000000 --- a/Lib/lib-stdwin/mainloop.py +++ /dev/null @@ -1,256 +0,0 @@ -# Standard main loop for *all* STDWIN applications. -# This requires that applications: -# - register their windows on creation and unregister them when closed -# - have a 'dispatch' function as a window member - - -import stdwin, stdwinq -from stdwinevents import * - - -# List of windows known to the main loop. -# -windows = [] - - -# Last window that ever received an event -# -last_window = None - - -# Function to register a window. -# -def register(win): - # First test the dispatch function by passing it a null event -- - # this catches registration of unconforming windows. - win.dispatch((WE_NULL, win, None)) - if win not in windows: - windows.append(win) - - -# Function to unregister a window. -# It is not an error to unregister an already unregistered window -# (this is useful for cleanup actions). -# -def unregister(win): - global last_window - if win == last_window: - last_window = None - if win in windows: - windows.remove(win) # Not in 0.9.1 - # 0.9.1 solution: - #for i in range(len(windows)): - # if windows[i] = win: - # del windows[i] - # break - - -# Interfaces used by WindowSched. -# -def countwindows(): - return len(windows) -# -def anywindow(): - if windows: - return windows[0] - else: - return None - - -# NEW: register any number of file descriptors -# -fdlist = [] -select_args = None -select_handlers = None -# -def registerfd(fd, mode, handler): - if mode not in ('r', 'w', 'x'): - raise ValueError, 'mode must be r, w or x' - if type(fd) <> type(0): - fd = fd.fileno() # If this fails it's not a proper select arg - for i in range(len(fdlist)): - if fdlist[i][:2] == (fd, mode): - raise ValueError, \ - '(fd, mode) combination already registered' - fdlist.append((fd, mode, handler)) - make_select_args() -# -def unregisterfd(fd, *args): - if type(fd) <> type(0): - fd = fd.fileno() # If this fails it's not a proper select arg - args = (fd,) + args - n = len(args) - for i in range(len(fdlist)): - if fdlist[i][:n] == args: - del fdlist[i] - make_select_args() -# -def make_select_args(): - global select_args, select_handlers - rlist, wlist, xlist = [], [], [] - rhandlers, whandlers, xhandlers = {}, {}, {} - for fd, mode, handler in fdlist: - if mode == 'r': - rlist.append(fd) - rhandlers[`fd`] = handler - if mode == 'w': - wlist.append(fd) - whandlers[`fd`] = handler - if mode == 'x': - xlist.append(fd) - xhandlers[`fd`] = handler - if rlist or wlist or xlist: - select_args = rlist, wlist, xlist - select_handlers = rhandlers, whandlers, xhandlers - else: - select_args = None - select_handlers = None -# -def do_select(): - import select - reply = apply(select.select, select_args) - for mode in 0, 1, 2: - list = reply[mode] - for fd in list: - handler = select_handlers[mode][`fd`] - handler(fd, 'rwx'[mode]) - - -# Event processing main loop. -# Return when there are no windows left, or when an unhandled -# exception occurs. (It is safe to restart the main loop after -# an unsuccessful exit.) -# Python's stdwin.getevent() turns WE_COMMAND/WC_CANCEL events -# into KeyboardInterrupt exceptions; these are turned back in events. -# -recursion_level = 0 # Hack to make it reentrant -def mainloop(): - global recursion_level - recursion_level = recursion_level + 1 - try: - stdwin_select_handler() # Process events already in queue - while 1: - if windows and not fdlist: - while windows and not fdlist: - try: - event = stdwinq.getevent() - except KeyboardInterrupt: - event = (WE_COMMAND, \ - None, WC_CANCEL) - dispatch(event) - elif windows and fdlist: - fd = stdwin.fileno() - if recursion_level == 1: - registerfd(fd, 'r', stdwin_select_handler) - try: - while windows: - do_select() - stdwin_select_handler() - finally: - if recursion_level == 1: - unregisterfd(fd) - elif fdlist: - while fdlist and not windows: - do_select() - else: - break - finally: - recursion_level = recursion_level - 1 - - -# Check for events without ever blocking -# -def check(): - stdwin_select_handler() - # XXX Should check for socket stuff as well - - -# Handle stdwin events until none are left -# -def stdwin_select_handler(*args): - while 1: - try: - event = stdwinq.pollevent() - except KeyboardInterrupt: - event = (WE_COMMAND, None, WC_CANCEL) - if event is None: - break - dispatch(event) - - -# Run a modal dialog loop for a window. The dialog window must have -# been registered first. This prohibits most events (except size/draw -# events) to other windows. The modal dialog loop ends when the -# dialog window unregisters itself. -# -passthrough = WE_SIZE, WE_DRAW -beeping = WE_MOUSE_DOWN, WE_COMMAND, WE_CHAR, WE_KEY, WE_CLOSE, WE_MENU -# -def modaldialog(window): - if window not in windows: - raise ValueError, 'modaldialog window not registered' - while window in windows: - try: - event = stdwinq.getevent() - except KeyboardInterrupt: - event = WE_COMMAND, None, WC_CANCEL - etype, ewindow, edetail = event - if etype not in passthrough and ewindow <> window: - if etype in beeping: - stdwin.fleep() - continue - dispatch(event) - - -# Dispatch a single event. -# Events for the no window in particular are sent to the active window -# or to the last window that received an event (these hacks are for the -# WE_LOST_SEL event, which is directed to no particular window). -# Windows not in the windows list don't get their events: -# events for such windows are silently ignored. -# -def dispatch(event): - global last_window - if event[1] == None: - active = stdwin.getactive() - if active: last_window = active - else: - last_window = event[1] - if last_window in windows: - last_window.dispatch(event) - - -# Dialog base class -# -class Dialog: - # - def __init__(self, title): - self.window = stdwin.open(title) - self.window.dispatch = self.dispatch - register(self.window) - # - def close(self): - unregister(self.window) - del self.window.dispatch - self.window.close() - # - def dispatch(self, event): - etype, ewindow, edetail = event - if etype == WE_CLOSE: - self.close() - - -# Standard modal dialogs -# XXX implemented using stdwin dialogs for now -# -def askstr(prompt, default): - return stdwin.askstr(prompt, default) -# -def askync(prompt, yesorno): - return stdwin.askync(prompt, yesorno) -# -def askfile(prompt, default, new): - return stdwin.askfile(prompt, default, new) -# -def message(msg): - stdwin.message(msg) diff --git a/Lib/lib-stdwin/rect.py b/Lib/lib-stdwin/rect.py deleted file mode 100644 index 393eafd769..0000000000 --- a/Lib/lib-stdwin/rect.py +++ /dev/null @@ -1,89 +0,0 @@ -# Module 'rect'. -# -# Operations on rectangles. -# There is some normalization: all results return the object 'empty' -# if their result would contain no points. - - -# Exception. -# -error = 'rect.error' - - -# The empty rectangle. -# -empty = (0, 0), (0, 0) - - -# Check if a rectangle is empty. -# -def is_empty(r): - (left, top), (right, bottom) = r - return left >= right or top >= bottom - - -# Compute the intersection or two or more rectangles. -# This works with a list or tuple argument. -# -def intersect(list): - if not list: raise error, 'intersect called with empty list' - if is_empty(list[0]): return empty - (left, top), (right, bottom) = list[0] - for rect in list[1:]: - if is_empty(rect): - return empty - (l, t), (r, b) = rect - if left < l: left = l - if top < t: top = t - if right > r: right = r - if bottom > b: bottom = b - if is_empty(((left, top), (right, bottom))): - return empty - return (left, top), (right, bottom) - - -# Compute the smallest rectangle containing all given rectangles. -# This works with a list or tuple argument. -# -def union(list): - (left, top), (right, bottom) = list[0] - for (l, t), (r, b) in list[1:]: - if not is_empty(((l, t), (r, b))): - if l < left: left = l - if t < top: top = t - if r > right: right = r - if b > bottom: bottom = b - res = (left, top), (right, bottom) - if is_empty(res): - return empty - return res - - -# Check if a point is in a rectangle. -# -def pointinrect((h, v), ((left, top), (right, bottom))): - return left <= h < right and top <= v < bottom - - -# Return a rectangle that is dh, dv inside another -# -def inset(((left, top), (right, bottom)), (dh, dv)): - left = left + dh - top = top + dv - right = right - dh - bottom = bottom - dv - r = (left, top), (right, bottom) - if is_empty(r): - return empty - else: - return r - - -# Conversions between rectangles and 'geometry tuples', -# given as origin (h, v) and dimensions (width, height). -# -def rect2geom((left, top), (right, bottom)): - return (left, top), (right-left, bottom-top) - -def geom2rect((h, v), (width, height)): - return (h, v), (h+width, v+height) diff --git a/Lib/lib-stdwin/srcwin.py b/Lib/lib-stdwin/srcwin.py deleted file mode 100644 index 29b78010a6..0000000000 --- a/Lib/lib-stdwin/srcwin.py +++ /dev/null @@ -1,129 +0,0 @@ -# srcwin.py -- a source listing window - -import stdwin -from stdwinevents import * -import basewin - -WIDTH = 40 -MAXHEIGHT = 24 - - -class TextWindow(basewin.BaseWindow): - - def __init__(self, title, contents): - self.contents = contents - self.linecount = countlines(self.contents) - # - self.lineheight = lh = stdwin.lineheight() - self.leftmargin = self.getmargin() - self.top = 0 - self.rightmargin = 30000 # Infinity - self.bottom = lh * self.linecount - # - width = WIDTH*stdwin.textwidth('0') - height = lh*min(MAXHEIGHT, self.linecount) - stdwin.setdefwinsize(width, height) - basewin.BaseWindow.__init__(self, title) - # - self.win.setdocsize(0, self.bottom) - self.initeditor() - - def initeditor(self): - r = (self.leftmargin, self.top), (self.rightmargin, self.bottom) - self.editor = self.win.textcreate(r) - self.editor.settext(self.contents) - - def closeeditor(self): - self.editor.close() - -# def reopen(self): -# self.closeeditor() -# basewin.BaseWindow.reopen(self) -# self.initeditor() - - # Override the following two methods to format line numbers differently - - def getmark(self, lineno): - return `lineno` - - def getmargin(self): - return stdwin.textwidth(`self.linecount + 1` + ' ') - - # Event dispatcher, called from mainloop.mainloop() - - def dispatch(self, event): - if event[0] == WE_NULL: return # Dummy tested by mainloop - if event[0] == WE_DRAW or not self.editor.event(event): - basewin.BaseWindow.dispatch(self, event) - - # Event handlers - - def close(self): - self.closeeditor() - basewin.BaseWindow.close(self) - - def draw(self, detail): - dummy = self.editor.draw(detail) - # Draw line numbers - (left, top), (right, bottom) = detail - topline = top/self.lineheight - botline = bottom/self.lineheight + 1 - botline = min(self.linecount, botline) - d = self.win.begindrawing() - try: - h, v = 0, self.lineheight * topline - for lineno in range(topline+1, botline+1): - d.text((h, v), self.getmark(lineno)) - v = v + self.lineheight - finally: - d.close() - - # Calls from outside - - def changemark(self, lineno): # redraw the mark for a line - left = 0 - top = (lineno-1) * self.lineheight - right = self.leftmargin - bottom = lineno * self.lineheight - d = self.win.begindrawing() - try: - d.erase((left, top), (right, bottom)) - d.text((left, top), self.getmark(lineno)) - finally: - d.close() - - def showline(self, lineno): # scroll to make a line visible - left = 0 - top = (lineno-1) * self.lineheight - right = self.leftmargin - bottom = lineno * self.lineheight - self.win.show((left, top), (right, bottom)) - - -# Subroutine to count the number of lines in a string - -def countlines(text): - n = 0 - for c in text: - if c == '\n': n = n+1 - if text and text[-1] != '\n': n = n+1 # Partial last line - return n - - -class SourceWindow(TextWindow): - - def __init__(self, filename): - self.filename = filename - f = open(self.filename, 'r') - contents = f.read() - f.close() - TextWindow.__init__(self, self.filename, contents) - -# ------------------------------ testing ------------------------------ - -TESTFILE = 'srcwin.py' - -def test(): - import mainloop - sw = SourceWindow(TESTFILE) - mainloop.mainloop() diff --git a/Lib/lib-stdwin/stdwinevents.py b/Lib/lib-stdwin/stdwinevents.py deleted file mode 100644 index 62cf8d2931..0000000000 --- a/Lib/lib-stdwin/stdwinevents.py +++ /dev/null @@ -1,61 +0,0 @@ -# Module 'stdwinevents' -- Constants for stdwin event types -# -# Suggested usage: -# from stdwinevents import * - -# The function stdwin.getevent() returns a tuple containing: -# (type, window, detail) -# where detail may be <no value> or a value depending on type, see below: - -# Values for type: - -WE_NULL = 0 # not reported -- means 'no event' internally -WE_ACTIVATE = 1 # detail is None -WE_CHAR = 2 # detail is the character -WE_COMMAND = 3 # detail is one of the WC_* constants below -WE_MOUSE_DOWN = 4 # detail is ((h, v), clicks, button, mask) -WE_MOUSE_MOVE = 5 # ditto -WE_MOUSE_UP = 6 # ditto -WE_MENU = 7 # detail is (menu, item) -WE_SIZE = 8 # detail is (width, height) -WE_MOVE = 9 # not reported -- reserved for future use -WE_DRAW = 10 # detail is ((left, top), (right, bottom)) -WE_TIMER = 11 # detail is None -WE_DEACTIVATE = 12 # detail is None -WE_EXTERN = 13 # detail is None -WE_KEY = 14 # detail is ??? -WE_LOST_SEL = 15 # detail is selection number -WE_CLOSE = 16 # detail is None - -# Values for detail when type is WE_COMMAND: - -WC_CLOSE = 1 # obsolete; now reported as WE_CLOSE -WC_LEFT = 2 # left arrow key -WC_RIGHT = 3 # right arrow key -WC_UP = 4 # up arrow key -WC_DOWN = 5 # down arrow key -WC_CANCEL = 6 # not reported -- turned into KeyboardInterrupt -WC_BACKSPACE = 7 # backspace key -WC_TAB = 8 # tab key -WC_RETURN = 9 # return or enter key - -# Selection numbers - -WS_CLIPBOARD = 0 -WS_PRIMARY = 1 -WS_SECONDARY = 2 - -# Modifier masks in key and mouse events - -WM_SHIFT = (1 << 0) -WM_LOCK = (1 << 1) -WM_CONTROL = (1 << 2) -WM_META = (1 << 3) -WM_OPTION = (1 << 4) -WM_NUM = (1 << 5) - -WM_BUTTON1 = (1 << 8) -WM_BUTTON2 = (1 << 9) -WM_BUTTON3 = (1 << 10) -WM_BUTTON4 = (1 << 11) -WM_BUTTON5 = (1 << 12) diff --git a/Lib/lib-stdwin/stdwinq.py b/Lib/lib-stdwin/stdwinq.py deleted file mode 100644 index af72986d68..0000000000 --- a/Lib/lib-stdwin/stdwinq.py +++ /dev/null @@ -1,53 +0,0 @@ -# Replacements for getevent() and pollevent(), -# and new functions ungetevent() and sync(). - - -# Every library module should ideally use this instead of -# stdwin.{get,poll}event(), so applications can use the services -# of ungetevent() and sync(). - - -import stdwin - - -# Events read ahead are stored in this queue. -# -queue = [] - - -# Replacement for getevent(). -# -def getevent(): - if queue: - event = queue[0] - del queue[0] - return event - else: - return stdwin.getevent() - - -# Replacement for pollevent(). -# -def pollevent(): - if queue: - return getevent() - else: - return stdwin.pollevent() - - -# Push an event back in the queue. -# -def ungetevent(event): - queue.insert(0, event) - - -# Synchronize the display. It turns out that this is the way to -# force STDWIN to call XSync(), which some (esoteric) applications need. -# (This is stronger than just flushing -- it actually waits for a -# positive response from the X server on the last command issued.) -# -def sync(): - while 1: - event = stdwin.pollevent() - if not event: break - queue.append(event) diff --git a/Lib/lib-stdwin/tablewin.py b/Lib/lib-stdwin/tablewin.py deleted file mode 100644 index eba161d6f3..0000000000 --- a/Lib/lib-stdwin/tablewin.py +++ /dev/null @@ -1,236 +0,0 @@ -# Module 'tablewin' - -# Display a table, with per-item actions: - -# A1 | A2 | A3 | .... | AN -# B1 | B2 | B3 | .... | BN -# C1 | C2 | C3 | .... | CN -# .. | .. | .. | .... | .. -# Z1 | Z2 | Z3 | .... | ZN - -# Not all columns need to have the same length. -# The data structure is a list of columns; -# each column is a list of items. -# Each item is a pair of a string and an action procedure. -# The first item may be a column title. - -import stdwin -import gwin -from stdwinevents import * - -def open(title, data): # Public function to open a table window - # - # Set geometry parameters (one day, these may be changeable) - # - margin = stdwin.textwidth(' ') - lineheight = stdwin.lineheight() - # - # Geometry calculations - # - colstarts = [0] - totwidth = 0 - maxrows = 0 - for coldata in data: - # Height calculations - rows = len(coldata) - if rows > maxrows: maxrows = rows - # Width calculations - width = colwidth(coldata) + margin - totwidth = totwidth + width - colstarts.append(totwidth) - # - # Calculate document and window height - # - docwidth, docheight = totwidth, maxrows*lineheight - winwidth, winheight = docwidth, docheight - if winwidth > stdwin.textwidth('n')*100: winwidth = 0 - if winheight > stdwin.lineheight()*30: winheight = 0 - # - # Create the window - # - stdwin.setdefwinsize(winwidth, winheight) - w = gwin.open(title) - # - # Set properties and override methods - # - w.data = data - w.margin = margin - w.lineheight = lineheight - w.colstarts = colstarts - w.totwidth = totwidth - w.maxrows = maxrows - w.selection = (-1, -1) - w.lastselection = (-1, -1) - w.selshown = 0 - w.setdocsize(docwidth, docheight) - w.draw = draw - w.mup = mup - w.arrow = arrow - # - # Return - # - return w - -def update(w, data): # Change the data - # - # Hide selection - # - hidesel(w, w.begindrawing()) - # - # Get old geometry parameters - # - margin = w.margin - lineheight = w.lineheight - # - # Geometry calculations - # - colstarts = [0] - totwidth = 0 - maxrows = 0 - for coldata in data: - # Height calculations - rows = len(coldata) - if rows > maxrows: maxrows = rows - # Width calculations - width = colwidth(coldata) + margin - totwidth = totwidth + width - colstarts.append(totwidth) - # - # Calculate document and window height - # - docwidth, docheight = totwidth, maxrows*lineheight - # - # Set changed properties and change window size - # - w.data = data - w.colstarts = colstarts - w.totwidth = totwidth - w.maxrows = maxrows - w.change((0, 0), (10000, 10000)) - w.setdocsize(docwidth, docheight) - w.change((0, 0), (docwidth, docheight)) - # - # Show selection, or forget it if out of range - # - showsel(w, w.begindrawing()) - if not w.selshown: w.selection = (-1, -1) - -def colwidth(coldata): # Subroutine to calculate column width - maxwidth = 0 - for string, action in coldata: - width = stdwin.textwidth(string) - if width > maxwidth: maxwidth = width - return maxwidth - -def draw(w, ((left, top), (right, bottom))): # Draw method - ileft = whichcol(w, left) - iright = whichcol(w, right-1) + 1 - if iright > len(w.data): iright = len(w.data) - itop = divmod(top, w.lineheight)[0] - if itop < 0: itop = 0 - ibottom, remainder = divmod(bottom, w.lineheight) - if remainder: ibottom = ibottom + 1 - d = w.begindrawing() - if ileft <= w.selection[0] < iright: - if itop <= w.selection[1] < ibottom: - hidesel(w, d) - d.erase((left, top), (right, bottom)) - for i in range(ileft, iright): - col = w.data[i] - jbottom = len(col) - if ibottom < jbottom: jbottom = ibottom - h = w.colstarts[i] - v = itop * w.lineheight - for j in range(itop, jbottom): - string, action = col[j] - d.text((h, v), string) - v = v + w.lineheight - showsel(w, d) - -def mup(w, detail): # Mouse up method - (h, v), nclicks, button, mask = detail - icol = whichcol(w, h) - if 0 <= icol < len(w.data): - irow = divmod(v, w.lineheight)[0] - col = w.data[icol] - if 0 <= irow < len(col): - string, action = col[irow] - action(w, string, (icol, irow), detail) - -def whichcol(w, h): # Return column number (may be >= len(w.data)) - for icol in range(0, len(w.data)): - if h < w.colstarts[icol+1]: - return icol - return len(w.data) - -def arrow(w, type): - if type == WC_LEFT: - incr = -1, 0 - elif type == WC_UP: - incr = 0, -1 - elif type == WC_RIGHT: - incr = 1, 0 - elif type == WC_DOWN: - incr = 0, 1 - else: - return - icol, irow = w.lastselection - icol = icol + incr[0] - if icol < 0: icol = len(w.data)-1 - if icol >= len(w.data): icol = 0 - if 0 <= icol < len(w.data): - irow = irow + incr[1] - if irow < 0: irow = len(w.data[icol]) - 1 - if irow >= len(w.data[icol]): irow = 0 - else: - irow = 0 - if 0 <= icol < len(w.data) and 0 <= irow < len(w.data[icol]): - w.lastselection = icol, irow - string, action = w.data[icol][irow] - detail = (0, 0), 1, 1, 1 - action(w, string, (icol, irow), detail) - - -# Selection management -# TO DO: allow multiple selected entries - -def select(w, selection): # Public function to set the item selection - d = w.begindrawing() - hidesel(w, d) - w.selection = selection - showsel(w, d) - if w.selshown: lastselection = selection - -def hidesel(w, d): # Hide the selection, if shown - if w.selshown: invertsel(w, d) - -def showsel(w, d): # Show the selection, if hidden - if not w.selshown: invertsel(w, d) - -def invertsel(w, d): # Invert the selection, if valid - icol, irow = w.selection - if 0 <= icol < len(w.data) and 0 <= irow < len(w.data[icol]): - left = w.colstarts[icol] - right = w.colstarts[icol+1] - top = irow * w.lineheight - bottom = (irow+1) * w.lineheight - d.invert((left, top), (right, bottom)) - w.selshown = (not w.selshown) - - -# Demonstration - -def demo_action(w, string, (icol, irow), detail): # Action function for demo - select(w, (irow, icol)) - -def demo(): # Demonstration - da = demo_action # shorthand - col0 = [('a1', da), ('bbb1', da), ('c1', da)] - col1 = [('a2', da), ('bbb2', da)] - col2 = [('a3', da), ('b3', da), ('c3', da), ('d4', da), ('d5', da)] - col3 = [] - for i in range(1, 31): col3.append('xxx' + `i`, da) - data = [col0, col1, col2, col3] - w = open('tablewin.demo', data) - gwin.mainloop() - return w diff --git a/Lib/lib-stdwin/textwin.py b/Lib/lib-stdwin/textwin.py deleted file mode 100644 index 778717fe14..0000000000 --- a/Lib/lib-stdwin/textwin.py +++ /dev/null @@ -1,117 +0,0 @@ -# Module 'textwin' - -# Text windows, a subclass of gwin - -import stdwin -import gwin -from stdwinevents import * - - -def fixsize(w): - docwidth, docheight = w.text.getrect()[1] - winheight = w.getwinsize()[1] - if winheight > docheight: docheight = winheight - w.setdocsize(0, docheight) - fixeditmenu(w) - -def cut(w, m, id): - s = w.text.getfocustext() - if s: - stdwin.setcutbuffer(0, s) - w.text.replace('') - fixsize(w) - -def copy(w, m, id): - s = w.text.getfocustext() - if s: - stdwin.setcutbuffer(0, s) - fixeditmenu(w) - -def paste(w, m, id): - w.text.replace(stdwin.getcutbuffer(0)) - fixsize(w) - -def addeditmenu(w): - m = w.editmenu = w.menucreate('Edit') - m.action = [] - m.additem('Cut', 'X') - m.action.append(cut) - m.additem('Copy', 'C') - m.action.append(copy) - m.additem('Paste', 'V') - m.action.append(paste) - -def fixeditmenu(w): - m = w.editmenu - f = w.text.getfocus() - can_copy = (f[0] < f[1]) - m.enable(1, can_copy) - if not w.readonly: - m.enable(0, can_copy) - m.enable(2, (stdwin.getcutbuffer(0) <> '')) - -def draw(w, area): # Draw method - w.text.draw(area) - -def size(w, newsize): # Size method - w.text.move((0, 0), newsize) - fixsize(w) - -def close(w): # Close method - del w.text # Break circular ref - gwin.close(w) - -def char(w, c): # Char method - w.text.replace(c) - fixsize(w) - -def backspace(w): # Backspace method - void = w.text.event(WE_COMMAND, w, WC_BACKSPACE) - fixsize(w) - -def arrow(w, detail): # Arrow method - w.text.arrow(detail) - fixeditmenu(w) - -def mdown(w, detail): # Mouse down method - void = w.text.event(WE_MOUSE_DOWN, w, detail) - fixeditmenu(w) - -def mmove(w, detail): # Mouse move method - void = w.text.event(WE_MOUSE_MOVE, w, detail) - -def mup(w, detail): # Mouse up method - void = w.text.event(WE_MOUSE_UP, w, detail) - fixeditmenu(w) - -def activate(w): # Activate method - fixeditmenu(w) - -def open(title, str): # Display a string in a window - w = gwin.open(title) - w.readonly = 0 - w.text = w.textcreate((0, 0), w.getwinsize()) - w.text.replace(str) - w.text.setfocus(0, 0) - addeditmenu(w) - fixsize(w) - w.draw = draw - w.size = size - w.close = close - w.mdown = mdown - w.mmove = mmove - w.mup = mup - w.char = char - w.backspace = backspace - w.arrow = arrow - w.activate = activate - return w - -def open_readonly(title, str): # Same with char input disabled - w = open(title, str) - w.readonly = 1 - w.char = w.backspace = gwin.nop - # Disable Cut and Paste menu item; leave Copy alone - w.editmenu.enable(0, 0) - w.editmenu.enable(2, 0) - return w diff --git a/Lib/lib-stdwin/wdb.py b/Lib/lib-stdwin/wdb.py deleted file mode 100644 index 27bbe5147c..0000000000 --- a/Lib/lib-stdwin/wdb.py +++ /dev/null @@ -1,316 +0,0 @@ -# wdb.py -- a window-based Python debugger - -# XXX To do: -# - don't fall out of bottom frame - - -import stdwin -from stdwinevents import * -import sys -import basewin -import bdb -import repr - -WIDTH = 40 -HEIGHT = 8 - -WdbDone = 'wdb.WdbDone' # Exception to continue execution - - -class Wdb(bdb.Bdb, basewin.BaseWindow): # Window debugger - - def __init__(self): - self.sourcewindows = {} - self.framewindows = {} - bdb.Bdb.__init__(self) - width = WIDTH*stdwin.textwidth('0') - height = HEIGHT*stdwin.lineheight() - stdwin.setdefwinsize(width, height) - basewin.BaseWindow.__init__(self, '--Stack--') - self.closed = 0 - - def reset(self): - if self.closed: raise RuntimeError, 'already closed' - bdb.Bdb.reset(self) - self.forget() - - def forget(self): - self.lineno = None - self.stack = [] - self.curindex = 0 - self.curframe = None - for fn in self.sourcewindows.keys(): - self.sourcewindows[fn].resetlineno() - - def setup(self, f, t): - self.forget() - self.stack, self.curindex = self.get_stack(f, t) - self.curframe = self.stack[self.curindex][0] - # Build a list of current frames - cfl = [] - for f, i in self.stack: cfl.append(f) - # Remove deactivated frame windows - for name in self.framewindows.keys(): - fw = self.framewindows[name] - if fw.frame not in cfl: fw.close() - else: fw.refreshframe() - # Refresh the stack window - self.refreshstack() - - # Override Bdb methods (except user_call, for now) - - def user_line(self, frame): - # This function is called when we stop or break at this line - self.interaction(frame, None) - - def user_return(self, frame, return_value): - # This function is called when a return trap is set here - frame.f_locals['__return__'] = return_value - self.settitle('--Return--') - self.interaction(frame, None) - if not self.closed: - self.settitle('--Stack--') - - def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): - # This function is called if an exception occurs, - # but only if we are to stop at or just below this level - frame.f_locals['__exception__'] = exc_type, exc_value - if type(exc_type) == type(''): - exc_type_name = exc_type - else: exc_type_name = exc_type.__name__ - self.settitle(exc_type_name + ': ' + repr.repr(exc_value)) - stdwin.fleep() - self.interaction(frame, exc_traceback) - if not self.closed: - self.settitle('--Stack--') - - # Change the title - - def settitle(self, title): - self.savetitle = self.win.gettitle() - self.win.settitle(title) - - # General interaction function - - def interaction(self, frame, traceback): - import mainloop - self.popup() - self.setup(frame, traceback) - try: - mainloop.mainloop() - except WdbDone: - pass - self.forget() - - # Functions whose name is do_X for some character X - # are callable directly from the keyboard. - - def do_up(self): - if self.curindex == 0: - stdwin.fleep() - else: - self.curindex = self.curindex - 1 - self.curframe = self.stack[self.curindex][0] - self.refreshstack() - do_u = do_up - - def do_down(self): - if self.curindex + 1 == len(self.stack): - stdwin.fleep() - else: - self.curindex = self.curindex + 1 - self.curframe = self.stack[self.curindex][0] - self.refreshstack() - do_d = do_down - - def do_step(self): - self.set_step() - raise WdbDone - do_s = do_step - - def do_next(self): - self.set_next(self.curframe) - raise WdbDone - do_n = do_next - - def do_return(self): - self.set_return(self.curframe) - raise WdbDone - do_r = do_return - - def do_continue(self): - self.set_continue() - raise WdbDone - do_c = do_cont = do_continue - - def do_quit(self): - self.close() - raise WdbDone - do_q = do_quit - - def do_list(self): - fn = self.curframe.f_code.co_filename - if not self.sourcewindows.has_key(fn): - import wdbsrcwin - try: - self.sourcewindows[fn] = wdbsrcwin. \ - DebuggerSourceWindow(self, fn) - except IOError: - stdwin.fleep() - return - w = self.sourcewindows[fn] - lineno = self.stack[self.curindex][1] - w.setlineno(lineno) - w.popup() - do_l = do_list - - def do_frame(self): - name = 'locals' + `self.curframe`[16:-1] - if self.framewindows.has_key(name): - self.framewindows[name].popup() - else: - import wdbframewin - self.framewindows[name] = \ - wdbframewin.FrameWindow(self, \ - self.curframe, \ - self.curframe.f_locals, name) - do_f = do_frame - - def do_globalframe(self): - name = 'globals' + `self.curframe`[16:-1] - if self.framewindows.has_key(name): - self.framewindows[name].popup() - else: - import wdbframewin - self.framewindows[name] = \ - wdbframewin.FrameWindow(self, \ - self.curframe, \ - self.curframe.f_globals, name) - do_g = do_globalframe - - # Link between the debugger and the window - - def refreshstack(self): - height = stdwin.lineheight() * (1 + len(self.stack)) - self.win.setdocsize((0, height)) - self.refreshall() # XXX be more subtle later - # Also pass the information on to the source windows - filename = self.curframe.f_code.co_filename - lineno = self.curframe.f_lineno - for fn in self.sourcewindows.keys(): - w = self.sourcewindows[fn] - if fn == filename: - w.setlineno(lineno) - else: - w.resetlineno() - - # The remaining methods override BaseWindow methods - - def close(self): - if not self.closed: - basewin.BaseWindow.close(self) - self.closed = 1 - for key in self.sourcewindows.keys(): - self.sourcewindows[key].close() - for key in self.framewindows.keys(): - self.framewindows[key].close() - self.set_quit() - - def char(self, detail): - try: - func = eval('self.do_' + detail) - except (AttributeError, SyntaxError): - stdwin.fleep() - return - func() - - def command(self, detail): - if detail == WC_UP: - self.do_up() - elif detail == WC_DOWN: - self.do_down() - - def mouse_down(self, detail): - (h, v), clicks, button, mask = detail - i = v / stdwin.lineheight() - if 0 <= i < len(self.stack): - if i != self.curindex: - self.curindex = i - self.curframe = self.stack[self.curindex][0] - self.refreshstack() - elif clicks == 2: - self.do_frame() - else: - stdwin.fleep() - - def draw(self, detail): - import linecache, string - d = self.win.begindrawing() - try: - h, v = 0, 0 - for f, lineno in self.stack: - fn = f.f_code.co_filename - if f is self.curframe: - s = '> ' - else: - s = ' ' - s = s + fn + '(' + `lineno` + ')' - s = s + f.f_code.co_name - if f.f_locals.has_key('__args__'): - args = f.f_locals['__args__'] - if args is not None: - s = s + repr.repr(args) - if f.f_locals.has_key('__return__'): - rv = f.f_locals['__return__'] - s = s + '->' - s = s + repr.repr(rv) - line = linecache.getline(fn, lineno) - if line: s = s + ': ' + string.strip(line) - d.text((h, v), s) - v = v + d.lineheight() - finally: - d.close() - - -# Simplified interface - -def run(statement, globals=None, locals=None): - x = Wdb() - try: x.run(statement, globals, locals) - finally: x.close() - -def runeval(expression, globals=None, locals=None): - x = Wdb() - try: return x.runeval(expression, globals, locals) - finally: x.close() - -def runctx(statement, globals, locals): - # B/W compatibility - run(statement, globals, locals) - -def runcall(*args): - x = Wdb() - try: return apply(x.runcall, args) - finally: x.close() - -def set_trace(): - Wdb().set_trace() - -# Post-Mortem interface - -def post_mortem(traceback): - x = Wdb() - x.reset() - x.interaction(None, traceback) - -def pm(): - import sys - post_mortem(sys.last_traceback) - - -# Main program for testing - -TESTCMD = 'import x; x.main()' - -def test(): - run(TESTCMD) diff --git a/Lib/lib-stdwin/wdbframewin.py b/Lib/lib-stdwin/wdbframewin.py deleted file mode 100644 index 7a0ff39c80..0000000000 --- a/Lib/lib-stdwin/wdbframewin.py +++ /dev/null @@ -1,146 +0,0 @@ -# wdbframewin.py -- frame window for wdb.py - -# XXX To do: -# - display function name in window title -# - execute arbitrary statements instead of just evaluating expressions -# - allow setting variables by editing their values - - -import stdwin -from stdwinevents import * -import basewin -import sys - -WIDTH = 40 -MINHEIGHT = 8 -MAXHEIGHT = 16 - -class FrameWindow(basewin.BaseWindow): - - def __init__(self, debugger, frame, dict, name): - self.debugger = debugger - self.frame = frame # Not used except for identity tests - self.dict = dict - self.name = name - nl = max(MINHEIGHT, len(self.dict) + 5) - nl = min(nl, MAXHEIGHT) - width = WIDTH*stdwin.textwidth('0') - height = nl*stdwin.lineheight() - stdwin.setdefwinsize(width, height) - basewin.BaseWindow.__init__( - self, '--Frame ' + name + '--') - # XXX Should use current function name - self.initeditor() - self.displaylist = ['>>>', '', '-'*WIDTH] - self.refreshframe() - - def initeditor(self): - r = (stdwin.textwidth('>>> '), 0), (30000, stdwin.lineheight()) - self.editor = self.win.textcreate(r) - - def closeeditor(self): - self.editor.close() - - def dispatch(self, event): - type, win, detail = event - if type == WE_NULL: return # Dummy tested by mainloop - if type in (WE_DRAW, WE_COMMAND) \ - or not self.editor.event(event): - basewin.BaseWindow.dispatch(self, event) - - def close(self): - del self.debugger.framewindows[self.name] - del self.debugger, self.dict - self.closeeditor() - basewin.BaseWindow.close(self) - - def command(self, detail): - if detail == WC_RETURN: - self.re_eval() - else: - dummy = self.editor.event(WE_COMMAND, \ - self.win, detail) - - def mouse_down(self, detail): - (h, v), clicks, button, mask = detail - if clicks != 2: - return - i = v / stdwin.lineheight() - if 5 <= i < len(self.displaylist): - import string - name = string.splitfields(self.displaylist[i],' = ')[0] - if not self.dict.has_key(name): - stdwin.fleep() - return - value = self.dict[name] - if not hasattr(value, '__dict__'): - stdwin.fleep() - return - name = 'instance ' + `value` - if self.debugger.framewindows.has_key(name): - self.debugger.framewindows[name].popup() - else: - self.debugger.framewindows[name] = \ - FrameWindow(self.debugger, - self.frame, value.__dict__, - name) - return - stdwin.fleep() - - def re_eval(self): - import string, repr - expr = string.strip(self.editor.gettext()) - if expr == '': - output = '' - else: - globals = self.frame.f_globals - globals['__privileged__'] = 1 - locals = self.dict - try: - value = eval(expr, globals, locals) - output = repr.repr(value) - except: - if type(sys.exc_type) == type(''): - exc_type_name = sys.exc_type - else: exc_type_name = sys.exc_type.__name__ - output = exc_type_name + ': ' + `sys.exc_value` - self.displaylist[1] = output - lh = stdwin.lineheight() - r = (-10, 0), (30000, 2*lh) - self.win.change(r) - self.editor.setfocus(0, len(expr)) - - def draw(self, detail): - (left, top), (right, bottom) = detail - dummy = self.editor.draw(detail) - d = self.win.begindrawing() - try: - lh = d.lineheight() - h, v = 0, 0 - for line in self.displaylist: - if v+lh > top and v < bottom: - d.text((h, v), line) - v = v + lh - finally: - d.close() - - def refreshframe(self): - import repr - del self.displaylist[3:] - self.re_eval() - names = self.dict.keys() - for key, label in ('__args__', 'Args: '), \ - ('__return__', 'Return: '): - if self.dict.has_key(key): - names.remove(key) - value = self.dict[key] - label = label + repr.repr(value) - self.displaylist.append(label) - names.sort() - for name in names: - value = self.dict[name] - line = name + ' = ' + repr.repr(value) - self.displaylist.append(line) - self.win.setdocsize(0, \ - stdwin.lineheight() * len(self.displaylist)) - self.refreshall() # XXX Be more subtle later diff --git a/Lib/lib-stdwin/wdbsrcwin.py b/Lib/lib-stdwin/wdbsrcwin.py deleted file mode 100644 index f79fab94be..0000000000 --- a/Lib/lib-stdwin/wdbsrcwin.py +++ /dev/null @@ -1,100 +0,0 @@ -# wdbsrcwin.py -- source window for wdb - -import stdwin -from stdwinevents import * -import srcwin - - -class DebuggerSourceWindow(srcwin.SourceWindow): - - def __init__(self, debugger, filename): - self.debugger = debugger - self.curlineno = 0 - self.focus = 0 - srcwin.SourceWindow.__init__(self, filename) - - def close(self): - del self.debugger.sourcewindows[self.filename] - del self.debugger - srcwin.SourceWindow.close(self) - - def dispatch(self, event): - type, win, detail = event - if type == WE_CHAR: - self.char(detail) - elif type == WE_COMMAND: - self.command(detail) - elif type == WE_MOUSE_DOWN: - self.mouse_down(detail) - else: - srcwin.SourceWindow.dispatch(self, event) - - def char(self, detail): - self.debugger.char(detail) - - def command(self, detail): - self.debugger.command(detail) - - def mouse_down(self, detail): - (h, v), clicks, button, mask = detail - if h >= self.leftmargin: - srcwin.SourceWindow.dispatch(self, \ - (WE_MOUSE_DOWN, self.win, detail)) - return - lineno = v/self.lineheight + 1 - if 1 <= lineno <= self.linecount: - if self.debugger.get_break(self.filename, lineno): - f = self.debugger.clear_break - else: - f = self.debugger.set_break - err = f(self.filename, lineno) - if err: stdwin.message(err) - else: self.changemark(lineno) - else: - stdwin.fleep() - - def getmark(self, lineno): - s = `lineno` - if lineno == self.focus: - s = '[' + s + ']' - else: - s = ' ' + s + ' ' - if lineno == self.curlineno: - s = s + '->' - else: - s = s + ' ' - br = self.debugger.breaks - if br.has_key(self.filename) and lineno in br[self.filename]: - s = s + 'B' - else: - s = s + ' ' - return s - - def getmargin(self): - return stdwin.textwidth('[' + `self.linecount+1` + ']->B ') - - def setlineno(self, newlineno): - if newlineno != self.curlineno: - oldlineno = self.curlineno - self.curlineno = newlineno - self.changemark(oldlineno) - self.changemark(newlineno) - if newlineno != 0: - self.showline(newlineno) - - def resetlineno(self): - self.setlineno(0) - - def setfocus(self, newfocus): - if newfocus != self.focus: - oldfocus = self.focus - self.focus = newfocus - self.changemark(oldfocus) - self.changemark(newfocus) - if newfocus != 0: - self.showline(newfocus) - - def resetfocus(self): - self.setfocus(0) - -# XXX Should get rid of focus stuff again diff --git a/Lib/lib-tk/Canvas.py b/Lib/lib-tk/Canvas.py deleted file mode 100644 index 1e4a5c8694..0000000000 --- a/Lib/lib-tk/Canvas.py +++ /dev/null @@ -1,190 +0,0 @@ -# This module exports classes for the various canvas item types - -from Tkinter import Canvas - -StringType = type('') -DictionaryType = type({}) - -def _flatten(tuple): - res = () - for item in tuple: - if type(item) in (TupleType, ListType): - res = res + _flatten(item) - elif item is not None: - res = res + (item,) - return res - -class CanvasItem: - def __init__(self, canvas, itemType, *args, **kw): - self.canvas = canvas - self.id = canvas._create(itemType, args, kw) - if not hasattr(canvas, 'items'): - canvas.items = {} - canvas.items[self.id] = self - def __str__(self): - return str(self.id) - def __repr__(self): - return '<%s, id=%d>' % (self.__class__.__name__, self.id) - def delete(self): - del self.canvas.items[self.id] - self.canvas.delete(self.id) - def __getitem__(self, key): - v = self.canvas.tk.split(self.canvas.tk.call( - self.canvas._w, 'itemconfigure', - self.id, '-' + key)) - return v[4] - def __setitem__(self, key, value): - self.canvas.itemconfig(self.id, {key: value}) - def keys(self): - if not hasattr(self, '_keys'): - self._keys = map(lambda x, tk=self.canvas.tk: - tk.splitlist(x)[0][1:], - self.canvas.tk.splitlist( - self.canvas._do( - 'itemconfigure', - (self.id,)))) - return self._keys - def has_key(self, key): - return key in self.keys() - def addtag(self, tag, option='withtag'): - self.canvas.addtag(tag, option, self.id) - def bbox(self): - x1, y1, x2, y2 = self.canvas.bbox(self.id) - return (x1, y1), (x2, y2) - def bind(self, sequence=None, command=None): - return self.canvas.bind(self.id, sequence, command) - def config(self, cnf=None): - return self.canvas.itemconfig(self.id, cnf) - def coords(self, pts = ()): - flat = () - for x, y in pts: flat = flat + (x, y) - return apply(self.canvas.coords, (self.id,) + flat) - def dchars(self, first, last=None): - self.canvas.dchars(self.id, first, last) - def dtag(self, ttd): - self.canvas.dtag(self.id, ttd) - def focus(self): - self.canvas.focus(self.id) - def gettags(self): - return self.canvas.gettags(self.id) - def icursor(self): - self.canvas.icursor(self.id) - def index(self): - return self.canvas.index(self.id) - def insert(self, beforethis, string): - self.canvas.insert(self.id, beforethis, string) - def lower(self, belowthis=None): - self.canvas.lower(self.id, belowthis) - def move(self, xamount, yamount): - self.canvas.move(self.id, xamount, yamount) - def tkraise(self, abovethis=None): - self.canvas.tkraise(self.id, abovethis) - raise_ = tkraise # BW compat - def scale(self, xorigin, yorigin, xscale, yscale): - self.canvas.scale(self.id, xorigin, yorigin, xscale, yscale) - def type(self): - return self.canvas.type(self.id) - -class Arc(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'arc', args) - -class Bitmap(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'bitmap', args) - -class ImageItem(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'image', args) - -class Line(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'line', args) - -class Oval(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'oval', args) - -class Polygon(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'polygon', args) - -class Rectangle(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'rectangle', args) - -# XXX "Text" is taken by the Text widget... -class CanvasText(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'text', args) - -class Window(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'window', args) - -class Group: - def __init__(self, canvas, tag=None): - if not tag: - tag = 'Group%d' % id(self) - self.tag = self.id = tag - self.canvas = canvas - self.canvas.dtag(self.tag) - def str(self): - return self.tag - def _do(self, cmd, *args): - return self.canvas._do(cmd, (self.tag,) + _flatten(args)) - def addtag_above(self, tagOrId): - self._do('addtag', 'above', tagOrId) - def addtag_all(self): - self._do('addtag', 'all') - def addtag_below(self, tagOrId): - self._do('addtag', 'below', tagOrId) - def addtag_closest(self, x, y, halo=None, start=None): - self._do('addtag', 'closest', x, y, halo, start) - def addtag_enclosed(self, x1, y1, x2, y2): - self._do('addtag', 'enclosed', x1, y1, x2, y2) - def addtag_overlapping(self, x1, y1, x2, y2): - self._do('addtag', 'overlapping', x1, y1, x2, y2) - def addtag_withtag(self, tagOrId): - self._do('addtag', 'withtag', tagOrId) - def bbox(self): - return self._getints(self._do('bbox')) - def bind(self, sequence=None, command=None): # XXX args? - return self._do('bind', sequence, command) - def coords(self, *pts): - return self._do('coords', pts) - def dchars(self, first, last=None): - self._do('dchars', first, last) - def delete(self): - self._do('delete') - def dtag(self, tagToDelete=None): - self._do('dtag', tagToDelete) - def focus(self): - self._do('focus') - def gettags(self): - return self.canvas.tk.splitlist(self._do('gettags', self.tag)) - def icursor(self, index): - return self._do('icursor') - def index(self, index): - return self.canvas.tk.getint(self._do('index', index)) - def insert(self, beforeThis, string): - self._do('insert', beforeThis, string) - def config(self, cnf=None): - return self.canvas.itemconfigure(self.tag, cnf) - def lower(self, belowThis=None): - self._do('lower', belowThis) - def move(self, xAmount, yAmount): - self._do('move', xAmount, yAmount) - def tkraise(self, aboveThis=None): - self._do('raise', aboveThis) - lift = tkraise - def scale(self, xOrigin, yOrigin, xScale, yScale): - self._do('scale', xOrigin, yOrigin, xScale, yScale) - def select_adjust(self, index): - self.canvas._do('select', ('adjust', self.tag, index)) - def select_from(self, index): - self.canvas._do('select', ('from', self.tag, index)) - def select_to(self, index): - self.canvas._do('select', ('to', self.tag, index)) - def type(self): - return self._do('type') diff --git a/Lib/lib-tk/Dialog.py b/Lib/lib-tk/Dialog.py deleted file mode 100644 index 67e7dc90ec..0000000000 --- a/Lib/lib-tk/Dialog.py +++ /dev/null @@ -1,49 +0,0 @@ -# Dialog.py -- Tkinter interface to the tk_dialog script. - -from Tkinter import * -from Tkinter import _cnfmerge - -if TkVersion <= 3.6: - DIALOG_ICON = 'warning' -else: - DIALOG_ICON = 'questhead' - - -class Dialog(Widget): - def __init__(self, master=None, cnf={}, **kw): - cnf = _cnfmerge((cnf, kw)) - self.widgetName = '__dialog__' - Widget._setup(self, master, cnf) - self.num = self.tk.getint( - apply(self.tk.call, - ('tk_dialog', self._w, - cnf['title'], cnf['text'], - cnf['bitmap'], cnf['default']) - + cnf['strings'])) - try: Widget.destroy(self) - except TclError: pass - def destroy(self): pass - -def _test(): - d = Dialog(None, {'title': 'File Modified', - 'text': - 'File "Python.h" has been modified' - ' since the last time it was saved.' - ' Do you want to save it before' - ' exiting the application.', - 'bitmap': DIALOG_ICON, - 'default': 0, - 'strings': ('Save File', - 'Discard Changes', - 'Return to Editor')}) - print d.num - - -if __name__ == '__main__': - t = Button(None, {'text': 'Test', - 'command': _test, - Pack: {}}) - q = Button(None, {'text': 'Quit', - 'command': t.quit, - Pack: {}}) - t.mainloop() diff --git a/Lib/lib-tk/FileDialog.py b/Lib/lib-tk/FileDialog.py deleted file mode 100644 index 76271af5d5..0000000000 --- a/Lib/lib-tk/FileDialog.py +++ /dev/null @@ -1,267 +0,0 @@ -"""File selection dialog classes. - -Classes: - -- FileDialog -- LoadFileDialog -- SaveFileDialog - -""" - -from Tkinter import * -from Dialog import Dialog - -ANCHOR = 'anchor' - -import os -import fnmatch - - -dialogstates = {} - - -class FileDialog: - - """Standard file selection dialog -- no checks on selected file. - - Usage: - - d = FileDialog(master) - file = d.go(dir_or_file, pattern, default, key) - if file is None: ...canceled... - else: ...open file... - - All arguments to go() are optional. - - The 'key' argument specifies a key in the global dictionary - 'dialogstates', which keeps track of the values for the directory - and pattern arguments, overriding the values passed in (it does - not keep track of the default argument!). If no key is specified, - the dialog keeps no memory of previous state. Note that memory is - kept even when the dialog is cancelled. (All this emulates the - behavior of the Macintosh file selection dialogs.) - - """ - - title = "File Selection Dialog" - - def __init__(self, master, title=None): - if title is None: title = self.title - self.master = master - self.directory = None - - self.top = Toplevel(master) - self.top.title(title) - self.top.iconname(title) - - self.botframe = Frame(self.top) - self.botframe.pack(side=BOTTOM, fill=X) - - self.selection = Entry(self.top) - self.selection.pack(side=BOTTOM, fill=X) - self.selection.bind('<Return>', self.ok_event) - - self.filter = Entry(self.top) - self.filter.pack(side=TOP, fill=X) - self.filter.bind('<Return>', self.filter_command) - - self.midframe = Frame(self.top) - self.midframe.pack(expand=YES, fill=BOTH) - - self.filesbar = Scrollbar(self.midframe) - self.filesbar.pack(side=RIGHT, fill=Y) - self.files = Listbox(self.midframe, exportselection=0, - yscrollcommand=(self.filesbar, 'set')) - self.files.pack(side=RIGHT, expand=YES, fill=BOTH) - self.files.bind('<ButtonRelease-1>', self.files_select_event) - self.files.bind('<Double-ButtonRelease-1>', self.files_double_event) - self.filesbar.config(command=(self.files, 'yview')) - - self.dirsbar = Scrollbar(self.midframe) - self.dirsbar.pack(side=LEFT, fill=Y) - self.dirs = Listbox(self.midframe, exportselection=0, - yscrollcommand=(self.dirsbar, 'set')) - self.dirs.pack(side=LEFT, expand=YES, fill=BOTH) - self.dirsbar.config(command=(self.dirs, 'yview')) - self.dirs.bind('<ButtonRelease-1>', self.dirs_select_event) - self.dirs.bind('<Double-ButtonRelease-1>', self.dirs_double_event) - - self.ok_button = Button(self.botframe, - text="OK", - command=self.ok_command) - self.ok_button.pack(side=LEFT) - self.filter_button = Button(self.botframe, - text="Filter", - command=self.filter_command) - self.filter_button.pack(side=LEFT, expand=YES) - self.cancel_button = Button(self.botframe, - text="Cancel", - command=self.cancel_command) - self.cancel_button.pack(side=RIGHT) - - self.top.protocol('WM_DELETE_WINDOW', self.cancel_command) - # XXX Are the following okay for a general audience? - self.top.bind('<Alt-w>', self.cancel_command) - self.top.bind('<Alt-W>', self.cancel_command) - - def go(self, dir_or_file=os.curdir, pattern="*", default="", key=None): - if key and dialogstates.has_key(key): - self.directory, pattern = dialogstates[key] - else: - dir_or_file = os.path.expanduser(dir_or_file) - if os.path.isdir(dir_or_file): - self.directory = dir_or_file - else: - self.directory, default = os.path.split(dir_or_file) - self.set_filter(self.directory, pattern) - self.set_selection(default) - self.filter_command() - self.selection.focus_set() - self.top.grab_set() - self.how = None - self.master.mainloop() # Exited by self.quit(how) - if key: dialogstates[key] = self.get_filter() - self.top.destroy() - return self.how - - def quit(self, how=None): - self.how = how - self.master.quit() # Exit mainloop() - - def dirs_double_event(self, event): - self.filter_command() - - def dirs_select_event(self, event): - dir, pat = self.get_filter() - subdir = self.dirs.get(ANCHOR) - dir = os.path.normpath(os.path.join(self.directory, subdir)) - self.set_filter(dir, pat) - - def files_double_event(self, event): - self.ok_command() - - def files_select_event(self, event): - file = self.files.get(ANCHOR) - self.set_selection(file) - - def ok_event(self, event): - self.ok_command() - - def ok_command(self): - self.quit(self.get_selection()) - - def filter_command(self, event=None): - dir, pat = self.get_filter() - try: - names = os.listdir(dir) - except os.error: - self.master.bell() - return - self.directory = dir - self.set_filter(dir, pat) - names.sort() - subdirs = [os.pardir] - matchingfiles = [] - for name in names: - fullname = os.path.join(dir, name) - if os.path.isdir(fullname): - subdirs.append(name) - elif fnmatch.fnmatch(name, pat): - matchingfiles.append(name) - self.dirs.delete(0, END) - for name in subdirs: - self.dirs.insert(END, name) - self.files.delete(0, END) - for name in matchingfiles: - self.files.insert(END, name) - head, tail = os.path.split(self.get_selection()) - if tail == os.curdir: tail = '' - self.set_selection(tail) - - def get_filter(self): - filter = self.filter.get() - filter = os.path.expanduser(filter) - if filter[-1:] == os.sep or os.path.isdir(filter): - filter = os.path.join(filter, "*") - return os.path.split(filter) - - def get_selection(self): - file = self.selection.get() - file = os.path.expanduser(file) - return file - - def cancel_command(self, event=None): - self.quit() - - def set_filter(self, dir, pat): - if not os.path.isabs(dir): - try: - pwd = os.getcwd() - except os.error: - pwd = None - if pwd: - dir = os.path.join(pwd, dir) - dir = os.path.normpath(dir) - self.filter.delete(0, END) - self.filter.insert(END, os.path.join(dir or os.curdir, pat or "*")) - - def set_selection(self, file): - self.selection.delete(0, END) - self.selection.insert(END, os.path.join(self.directory, file)) - - -class LoadFileDialog(FileDialog): - - """File selection dialog which checks that the file exists.""" - - title = "Load File Selection Dialog" - - def ok_command(self): - file = self.get_selection() - if not os.path.isfile(file): - self.master.bell() - else: - self.quit(file) - - -class SaveFileDialog(FileDialog): - - """File selection dialog which checks that the file may be created.""" - - title = "Save File Selection Dialog" - - def ok_command(self): - file = self.get_selection() - if os.path.exists(file): - if os.path.isdir(file): - self.master.bell() - return - d = Dialog(self.top, - title="Overwrite Existing File Question", - text="Overwrite existing file %s?" % `file`, - bitmap='questhead', - default=1, - strings=("Yes", "Cancel")) - if d.num != 0: - return - else: - head, tail = os.path.split(file) - if not os.path.isdir(head): - self.master.bell() - return - self.quit(file) - - -def test(): - """Simple test program.""" - root = Tk() - root.withdraw() - fd = LoadFileDialog(root) - loadfile = fd.go(key="test") - fd = SaveFileDialog(root) - savefile = fd.go(key="test") - print loadfile, savefile - - -if __name__ == '__main__': - test() diff --git a/Lib/lib-tk/ScrolledText.py b/Lib/lib-tk/ScrolledText.py deleted file mode 100644 index 0261d907aa..0000000000 --- a/Lib/lib-tk/ScrolledText.py +++ /dev/null @@ -1,37 +0,0 @@ -# A ScrolledText widget feels like a text widget but also has a -# vertical scroll bar on its right. (Later, options may be added to -# add a horizontal bar as well, to make the bars disappear -# automatically when not needed, to move them to the other side of the -# window, etc.) -# -# Configuration options are passed to the Text widget. -# A Frame widget is inserted between the master and the text, to hold -# the Scrollbar widget. -# Most methods calls are inherited from the Text widget; Pack methods -# are redirected to the Frame widget however. - -from Tkinter import * -from Tkinter import _cnfmerge - -class ScrolledText(Text): - def __init__(self, master=None, cnf={}): - cnf = _cnfmerge(cnf) - fcnf = {} - vcnf = {'name': 'vbar', - Pack: {'side': 'right', 'fill': 'y'},} - for k in cnf.keys(): - if type(k) == ClassType or k == 'name': - fcnf[k] = cnf[k] - del cnf[k] - self.frame = Frame(master, fcnf) - self.vbar = Scrollbar(self.frame, vcnf) - cnf[Pack] = {'side': 'left', 'fill': 'both', 'expand': 'yes'} - cnf['name'] = 'text' - Text.__init__(self, self.frame, cnf) - self['yscrollcommand'] = (self.vbar, 'set') - self.vbar['command'] = (self, 'yview') - - # Copy Pack methods of self.frame -- hack! - for m in Pack.__dict__.keys(): - if m[0] != '_' and m != 'config': - setattr(self, m, getattr(self.frame, m)) diff --git a/Lib/lib-tk/Tkconstants.py b/Lib/lib-tk/Tkconstants.py deleted file mode 100644 index dd4fb0ef32..0000000000 --- a/Lib/lib-tk/Tkconstants.py +++ /dev/null @@ -1,76 +0,0 @@ -# Symbolic constants for Tk - -# Booleans -NO=FALSE=OFF=0 -YES=TRUE=ON=1 - -# -anchor -N='n' -S='s' -W='w' -E='e' -NW='nw' -SW='sw' -NE='ne' -SE='se' -CENTER='center' - -# -fill -NONE='none' -X='x' -Y='y' -BOTH='both' - -# -side -LEFT='left' -TOP='top' -RIGHT='right' -BOTTOM='bottom' - -# -relief -RAISED='raised' -SUNKEN='sunken' -FLAT='flat' -RIDGE='ridge' -GROOVE='groove' - -# -orient -HORIZONTAL='horizontal' -VERTICAL='vertical' - -# -tabs -NUMERIC='numeric' - -# -wrap -CHAR='char' -WORD='word' - -# -align -BASELINE='baseline' - -# Special tags, marks and insert positions -SEL='sel' -SEL_FIRST='sel.first' -SEL_LAST='sel.last' -END='end' -INSERT='insert' -CURRENT='current' -ANCHOR='anchor' - -# Text widget and button states -NORMAL='normal' -DISABLED='disabled' -ACTIVE='active' - -# Menu item types -CASCADE='cascade' -CHECKBUTTON='checkbutton' -COMMAND='command' -RADIOBUTTON='radiobutton' -SEPARATOR='separator' - -# Selection modes for list boxes -SINGLE='single' -BROWSE='browse' -MULTIPLE='multiple' -EXTENDED='extended' diff --git a/Lib/lib-tk/Tkinter.py b/Lib/lib-tk/Tkinter.py deleted file mode 100644 index d033823f88..0000000000 --- a/Lib/lib-tk/Tkinter.py +++ /dev/null @@ -1,1569 +0,0 @@ -# Tkinter.py -- Tk/Tcl widget wrappers - -__version__ = "$Revision$" - -try: - # See if modern _tkinter is present - import _tkinter - tkinter = _tkinter # b/w compat -except ImportError: - # No modern _tkinter -- try oldfashioned tkinter - import tkinter - if hasattr(tkinter, "__path__"): - import sys, os - # Append standard platform specific directory - p = tkinter.__path__ - for dir in sys.path: - if (dir not in p and - os.path.basename(dir) == sys.platform): - p.append(dir) - del sys, os, p, dir - from tkinter import tkinter -TclError = tkinter.TclError -from types import * -from Tkconstants import * -import string; _string = string; del string - -TkVersion = _string.atof(tkinter.TK_VERSION) -TclVersion = _string.atof(tkinter.TCL_VERSION) - -###################################################################### -# Since the values of file event masks changed from Tk 4.0 to Tk 4.1, -# they are defined here (and not in Tkconstants): -###################################################################### -if TkVersion >= 4.1: - READABLE = 2 - WRITABLE = 4 - EXCEPTION = 8 -else: - READABLE = 1 - WRITABLE = 2 - EXCEPTION = 4 - - -def _flatten(tuple): - res = () - for item in tuple: - if type(item) in (TupleType, ListType): - res = res + _flatten(item) - elif item is not None: - res = res + (item,) - return res - -def _cnfmerge(cnfs): - if type(cnfs) is DictionaryType: - return cnfs - elif type(cnfs) in (NoneType, StringType): - - return cnfs - else: - cnf = {} - for c in _flatten(cnfs): - for k, v in c.items(): - cnf[k] = v - return cnf - -class Event: - pass - -_default_root = None - -def _tkerror(err): - pass - -def _exit(code='0'): - raise SystemExit, code - -_varnum = 0 -class Variable: - def __init__(self, master=None): - global _default_root - global _varnum - if master: - self._tk = master.tk - else: - self._tk = _default_root.tk - self._name = 'PY_VAR' + `_varnum` - _varnum = _varnum + 1 - def __del__(self): - self._tk.globalunsetvar(self._name) - def __str__(self): - return self._name - def set(self, value): - return self._tk.globalsetvar(self._name, value) - -class StringVar(Variable): - def __init__(self, master=None): - Variable.__init__(self, master) - def get(self): - return self._tk.globalgetvar(self._name) - -class IntVar(Variable): - def __init__(self, master=None): - Variable.__init__(self, master) - def get(self): - return self._tk.getint(self._tk.globalgetvar(self._name)) - -class DoubleVar(Variable): - def __init__(self, master=None): - Variable.__init__(self, master) - def get(self): - return self._tk.getdouble(self._tk.globalgetvar(self._name)) - -class BooleanVar(Variable): - def __init__(self, master=None): - Variable.__init__(self, master) - def get(self): - return self._tk.getboolean(self._tk.globalgetvar(self._name)) - -def mainloop(n=0): - _default_root.tk.mainloop(n) - -def getint(s): - return _default_root.tk.getint(s) - -def getdouble(s): - return _default_root.tk.getdouble(s) - -def getboolean(s): - return _default_root.tk.getboolean(s) - -class Misc: - def tk_strictMotif(self, boolean=None): - return self.tk.getboolean(self.tk.call( - 'set', 'tk_strictMotif', boolean)) - def tk_menuBar(self, *args): - apply(self.tk.call, ('tk_menuBar', self._w) + args) - def wait_variable(self, name='PY_VAR'): - self.tk.call('tkwait', 'variable', name) - waitvar = wait_variable # XXX b/w compat - def wait_window(self, window=None): - if window == None: - window = self - self.tk.call('tkwait', 'window', window._w) - def wait_visibility(self, window=None): - if window == None: - window = self - self.tk.call('tkwait', 'visibility', window._w) - def setvar(self, name='PY_VAR', value='1'): - self.tk.setvar(name, value) - def getvar(self, name='PY_VAR'): - return self.tk.getvar(name) - def getint(self, s): - return self.tk.getint(s) - def getdouble(self, s): - return self.tk.getdouble(s) - def getboolean(self, s): - return self.tk.getboolean(s) - def focus_set(self): - self.tk.call('focus', self._w) - focus = focus_set # XXX b/w compat? - def focus_default_set(self): - self.tk.call('focus', 'default', self._w) - def focus_default_none(self): - self.tk.call('focus', 'default', 'none') - focus_default = focus_default_set - def focus_none(self): - self.tk.call('focus', 'none') - def focus_get(self): - name = self.tk.call('focus') - if name == 'none': return None - return self._nametowidget(name) - def tk_focusNext(self): - name = self.tk.call('tk_focusNext', self._w) - if not name: return None - return self._nametowidget(name) - def tk_focusPrev(self): - name = self.tk.call('tk_focusPrev', self._w) - if not name: return None - return self._nametowidget(name) - def after(self, ms, func=None, *args): - if not func: - # I'd rather use time.sleep(ms*0.001) - self.tk.call('after', ms) - else: - # XXX Disgusting hack to clean up after calling func - tmp = [] - def callit(func=func, args=args, tk=self.tk, tmp=tmp): - try: - apply(func, args) - finally: - tk.deletecommand(tmp[0]) - name = self._register(callit) - tmp.append(name) - return self.tk.call('after', ms, name) - def after_idle(self, func, *args): - return apply(self.after, ('idle', func) + args) - def after_cancel(self, id): - self.tk.call('after', 'cancel', id) - def bell(self, displayof=None): - if displayof: - self.tk.call('bell', '-displayof', displayof) - else: - self.tk.call('bell', '-displayof', self._w) - # XXX grab current w/o window argument - def grab_current(self): - name = self.tk.call('grab', 'current', self._w) - if not name: return None - return self._nametowidget(name) - def grab_release(self): - self.tk.call('grab', 'release', self._w) - def grab_set(self): - self.tk.call('grab', 'set', self._w) - def grab_set_global(self): - self.tk.call('grab', 'set', '-global', self._w) - def grab_status(self): - status = self.tk.call('grab', 'status', self._w) - if status == 'none': status = None - return status - def lower(self, belowThis=None): - self.tk.call('lower', self._w, belowThis) - def option_add(self, pattern, value, priority = None): - self.tk.call('option', 'add', pattern, value, priority) - def option_clear(self): - self.tk.call('option', 'clear') - def option_get(self, name, className): - return self.tk.call('option', 'get', self._w, name, className) - def option_readfile(self, fileName, priority = None): - self.tk.call('option', 'readfile', fileName, priority) - def selection_clear(self): - self.tk.call('selection', 'clear', self._w) - def selection_get(self, type=None): - return self.tk.call('selection', 'get', type) - def selection_handle(self, func, type=None, format=None): - name = self._register(func) - self.tk.call('selection', 'handle', self._w, - name, type, format) - def selection_own(self, func=None): - name = self._register(func) - self.tk.call('selection', 'own', self._w, name) - def selection_own_get(self): - return self._nametowidget(self.tk.call('selection', 'own')) - def send(self, interp, cmd, *args): - return apply(self.tk.call, ('send', interp, cmd) + args) - def lower(self, belowThis=None): - self.tk.call('lift', self._w, belowThis) - def tkraise(self, aboveThis=None): - self.tk.call('raise', self._w, aboveThis) - lift = tkraise - def colormodel(self, value=None): - return self.tk.call('tk', 'colormodel', self._w, value) - def winfo_atom(self, name): - return self.tk.getint(self.tk.call('winfo', 'atom', name)) - def winfo_atomname(self, id): - return self.tk.call('winfo', 'atomname', id) - def winfo_cells(self): - return self.tk.getint( - self.tk.call('winfo', 'cells', self._w)) - def winfo_children(self): - return map(self._nametowidget, - self.tk.splitlist(self.tk.call( - 'winfo', 'children', self._w))) - def winfo_class(self): - return self.tk.call('winfo', 'class', self._w) - def winfo_containing(self, rootX, rootY): - return self.tk.call('winfo', 'containing', rootX, rootY) - def winfo_depth(self): - return self.tk.getint(self.tk.call('winfo', 'depth', self._w)) - def winfo_exists(self): - return self.tk.getint( - self.tk.call('winfo', 'exists', self._w)) - def winfo_fpixels(self, number): - return self.tk.getdouble(self.tk.call( - 'winfo', 'fpixels', self._w, number)) - def winfo_geometry(self): - return self.tk.call('winfo', 'geometry', self._w) - def winfo_height(self): - return self.tk.getint( - self.tk.call('winfo', 'height', self._w)) - def winfo_id(self): - return self.tk.getint( - self.tk.call('winfo', 'id', self._w)) - def winfo_interps(self): - return self.tk.splitlist( - self.tk.call('winfo', 'interps')) - def winfo_ismapped(self): - return self.tk.getint( - self.tk.call('winfo', 'ismapped', self._w)) - def winfo_name(self): - return self.tk.call('winfo', 'name', self._w) - def winfo_parent(self): - return self.tk.call('winfo', 'parent', self._w) - def winfo_pathname(self, id): - return self.tk.call('winfo', 'pathname', id) - def winfo_pixels(self, number): - return self.tk.getint( - self.tk.call('winfo', 'pixels', self._w, number)) - def winfo_reqheight(self): - return self.tk.getint( - self.tk.call('winfo', 'reqheight', self._w)) - def winfo_reqwidth(self): - return self.tk.getint( - self.tk.call('winfo', 'reqwidth', self._w)) - def winfo_rgb(self, color): - return self._getints( - self.tk.call('winfo', 'rgb', self._w, color)) - def winfo_rootx(self): - return self.tk.getint( - self.tk.call('winfo', 'rootx', self._w)) - def winfo_rooty(self): - return self.tk.getint( - self.tk.call('winfo', 'rooty', self._w)) - def winfo_screen(self): - return self.tk.call('winfo', 'screen', self._w) - def winfo_screencells(self): - return self.tk.getint( - self.tk.call('winfo', 'screencells', self._w)) - def winfo_screendepth(self): - return self.tk.getint( - self.tk.call('winfo', 'screendepth', self._w)) - def winfo_screenheight(self): - return self.tk.getint( - self.tk.call('winfo', 'screenheight', self._w)) - def winfo_screenmmheight(self): - return self.tk.getint( - self.tk.call('winfo', 'screenmmheight', self._w)) - def winfo_screenmmwidth(self): - return self.tk.getint( - self.tk.call('winfo', 'screenmmwidth', self._w)) - def winfo_screenvisual(self): - return self.tk.call('winfo', 'screenvisual', self._w) - def winfo_screenwidth(self): - return self.tk.getint( - self.tk.call('winfo', 'screenwidth', self._w)) - def winfo_toplevel(self): - return self._nametowidget(self.tk.call( - 'winfo', 'toplevel', self._w)) - def winfo_visual(self): - return self.tk.call('winfo', 'visual', self._w) - def winfo_vrootheight(self): - return self.tk.getint( - self.tk.call('winfo', 'vrootheight', self._w)) - def winfo_vrootwidth(self): - return self.tk.getint( - self.tk.call('winfo', 'vrootwidth', self._w)) - def winfo_vrootx(self): - return self.tk.getint( - self.tk.call('winfo', 'vrootx', self._w)) - def winfo_vrooty(self): - return self.tk.getint( - self.tk.call('winfo', 'vrooty', self._w)) - def winfo_width(self): - return self.tk.getint( - self.tk.call('winfo', 'width', self._w)) - def winfo_x(self): - return self.tk.getint( - self.tk.call('winfo', 'x', self._w)) - def winfo_y(self): - return self.tk.getint( - self.tk.call('winfo', 'y', self._w)) - def update(self): - self.tk.call('update') - def update_idletasks(self): - self.tk.call('update', 'idletasks') - def bindtags(self, tagList=None): - if tagList is None: - return self.tk.splitlist( - self.tk.call('bindtags', self._w)) - else: - self.tk.call('bindtags', self._w, tagList) - def _bind(self, what, sequence, func, add): - if func: - cmd = ("%sset _tkinter_break [%s %s]\n" - 'if {"$_tkinter_break" == "break"} break\n') \ - % (add and '+' or '', - self._register(func, self._substitute), - _string.join(self._subst_format)) - apply(self.tk.call, what + (sequence, cmd)) - elif func == '': - apply(self.tk.call, what + (sequence, func)) - else: - return apply(self.tk.call, what + (sequence,)) - def bind(self, sequence=None, func=None, add=None): - return self._bind(('bind', self._w), sequence, func, add) - def unbind(self, sequence): - self.tk.call('bind', self._w, sequence, '') - def bind_all(self, sequence=None, func=None, add=None): - return self._bind(('bind', 'all'), sequence, func, add) - def unbind_all(self, sequence): - self.tk.call('bind', 'all' , sequence, '') - def bind_class(self, className, sequence=None, func=None, add=None): - self._bind(('bind', className), sequence, func, add) - def unbind_class(self, className, sequence): - self.tk.call('bind', className , sequence, '') - def mainloop(self, n=0): - self.tk.mainloop(n) - def quit(self): - self.tk.quit() - def _getints(self, string): - if not string: return None - return tuple(map(self.tk.getint, self.tk.splitlist(string))) - def _getdoubles(self, string): - if not string: return None - return tuple(map(self.tk.getdouble, self.tk.splitlist(string))) - def _getboolean(self, string): - if string: - return self.tk.getboolean(string) - def _options(self, cnf, kw = None): - if kw: - cnf = _cnfmerge((cnf, kw)) - else: - cnf = _cnfmerge(cnf) - res = () - for k, v in cnf.items(): - if k[-1] == '_': k = k[:-1] - if callable(v): - v = self._register(v) - res = res + ('-'+k, v) - return res - def _nametowidget(self, name): - w = self - if name[0] == '.': - w = w._root() - name = name[1:] - find = _string.find - while name: - i = find(name, '.') - if i >= 0: - name, tail = name[:i], name[i+1:] - else: - tail = '' - w = w.children[name] - name = tail - return w - def _register(self, func, subst=None): - f = CallWrapper(func, subst, self).__call__ - name = `id(f)` - try: - func = func.im_func - except AttributeError: - pass - try: - name = name + func.__name__ - except AttributeError: - pass - self.tk.createcommand(name, f) - return name - register = _register - def _root(self): - w = self - while w.master: w = w.master - return w - _subst_format = ('%#', '%b', '%f', '%h', '%k', - '%s', '%t', '%w', '%x', '%y', - '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y') - def _substitute(self, *args): - tk = self.tk - if len(args) != len(self._subst_format): return args - nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y = args - # Missing: (a, c, d, m, o, v, B, R) - e = Event() - e.serial = tk.getint(nsign) - e.num = tk.getint(b) - try: e.focus = tk.getboolean(f) - except TclError: pass - e.height = tk.getint(h) - e.keycode = tk.getint(k) - # For Visibility events, event state is a string and - # not an integer: - try: - e.state = tk.getint(s) - except TclError: - e.state = s - e.time = tk.getint(t) - e.width = tk.getint(w) - e.x = tk.getint(x) - e.y = tk.getint(y) - e.char = A - try: e.send_event = tk.getboolean(E) - except TclError: pass - e.keysym = K - e.keysym_num = tk.getint(N) - e.type = T - e.widget = self._nametowidget(W) - e.x_root = tk.getint(X) - e.y_root = tk.getint(Y) - return (e,) - def _report_exception(self): - import sys - exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback - root = self._root() - root.report_callback_exception(exc, val, tb) - -class CallWrapper: - def __init__(self, func, subst, widget): - self.func = func - self.subst = subst - self.widget = widget - def __call__(self, *args): - try: - if self.subst: - args = apply(self.subst, args) - return apply(self.func, args) - except SystemExit, msg: - raise SystemExit, msg - except: - self.widget._report_exception() - -class Wm: - def aspect(self, - minNumer=None, minDenom=None, - maxNumer=None, maxDenom=None): - return self._getints( - self.tk.call('wm', 'aspect', self._w, - minNumer, minDenom, - maxNumer, maxDenom)) - def client(self, name=None): - return self.tk.call('wm', 'client', self._w, name) - def command(self, value=None): - return self.tk.call('wm', 'command', self._w, value) - def deiconify(self): - return self.tk.call('wm', 'deiconify', self._w) - def focusmodel(self, model=None): - return self.tk.call('wm', 'focusmodel', self._w, model) - def frame(self): - return self.tk.call('wm', 'frame', self._w) - def geometry(self, newGeometry=None): - return self.tk.call('wm', 'geometry', self._w, newGeometry) - def grid(self, - baseWidht=None, baseHeight=None, - widthInc=None, heightInc=None): - return self._getints(self.tk.call( - 'wm', 'grid', self._w, - baseWidht, baseHeight, widthInc, heightInc)) - def group(self, pathName=None): - return self.tk.call('wm', 'group', self._w, pathName) - def iconbitmap(self, bitmap=None): - return self.tk.call('wm', 'iconbitmap', self._w, bitmap) - def iconify(self): - return self.tk.call('wm', 'iconify', self._w) - def iconmask(self, bitmap=None): - return self.tk.call('wm', 'iconmask', self._w, bitmap) - def iconname(self, newName=None): - return self.tk.call('wm', 'iconname', self._w, newName) - def iconposition(self, x=None, y=None): - return self._getints(self.tk.call( - 'wm', 'iconposition', self._w, x, y)) - def iconwindow(self, pathName=None): - return self.tk.call('wm', 'iconwindow', self._w, pathName) - def maxsize(self, width=None, height=None): - return self._getints(self.tk.call( - 'wm', 'maxsize', self._w, width, height)) - def minsize(self, width=None, height=None): - return self._getints(self.tk.call( - 'wm', 'minsize', self._w, width, height)) - def overrideredirect(self, boolean=None): - return self._getboolean(self.tk.call( - 'wm', 'overrideredirect', self._w, boolean)) - def positionfrom(self, who=None): - return self.tk.call('wm', 'positionfrom', self._w, who) - def protocol(self, name=None, func=None): - if callable(func): - command = self._register(func) - else: - command = func - return self.tk.call( - 'wm', 'protocol', self._w, name, command) - def resizable(self, width=None, height=None): - return self.tk.call('wm', 'resizable', self._w, width, height) - def sizefrom(self, who=None): - return self.tk.call('wm', 'sizefrom', self._w, who) - def state(self): - return self.tk.call('wm', 'state', self._w) - def title(self, string=None): - return self.tk.call('wm', 'title', self._w, string) - def transient(self, master=None): - return self.tk.call('wm', 'transient', self._w, master) - def withdraw(self): - return self.tk.call('wm', 'withdraw', self._w) - -class Tk(Misc, Wm): - _w = '.' - def __init__(self, screenName=None, baseName=None, className='Tk'): - global _default_root - self.master = None - self.children = {} - if baseName is None: - import sys, os - baseName = os.path.basename(sys.argv[0]) - if baseName[-3:] == '.py': baseName = baseName[:-3] - self.tk = tkinter.create(screenName, baseName, className) - try: - # Disable event scanning except for Command-Period - import MacOS - MacOS.EnableAppswitch(0) - except ImportError: - pass - else: - # Work around nasty MacTk bug - self.update() - # Version sanity checks - tk_version = self.tk.getvar('tk_version') - if tk_version != tkinter.TK_VERSION: - raise RuntimeError, \ - "tk.h version (%s) doesn't match libtk.a version (%s)" \ - % (tkinter.TK_VERSION, tk_version) - tcl_version = self.tk.getvar('tcl_version') - if tcl_version != tkinter.TCL_VERSION: - raise RuntimeError, \ - "tcl.h version (%s) doesn't match libtcl.a version (%s)" \ - % (tkinter.TCL_VERSION, tcl_version) - if TkVersion < 4.0: - raise RuntimeError, \ - "Tk 4.0 or higher is required; found Tk %s" \ - % str(TkVersion) - self.tk.createcommand('tkerror', _tkerror) - self.tk.createcommand('exit', _exit) - self.readprofile(baseName, className) - if not _default_root: - _default_root = self - def destroy(self): - for c in self.children.values(): c.destroy() - self.tk.call('destroy', self._w) - def __str__(self): - return self._w - def readprofile(self, baseName, className): - import os - if os.environ.has_key('HOME'): home = os.environ['HOME'] - else: home = os.curdir - class_tcl = os.path.join(home, '.%s.tcl' % className) - class_py = os.path.join(home, '.%s.py' % className) - base_tcl = os.path.join(home, '.%s.tcl' % baseName) - base_py = os.path.join(home, '.%s.py' % baseName) - dir = {'self': self} - exec 'from Tkinter import *' in dir - if os.path.isfile(class_tcl): - print 'source', `class_tcl` - self.tk.call('source', class_tcl) - if os.path.isfile(class_py): - print 'execfile', `class_py` - execfile(class_py, dir) - if os.path.isfile(base_tcl): - print 'source', `base_tcl` - self.tk.call('source', base_tcl) - if os.path.isfile(base_py): - print 'execfile', `base_py` - execfile(base_py, dir) - def report_callback_exception(self, exc, val, tb): - import traceback - print "Exception in Tkinter callback" - traceback.print_exception(exc, val, tb) - -class Pack: - def config(self, cnf={}, **kw): - apply(self.tk.call, - ('pack', 'configure', self._w) - + self._options(cnf, kw)) - configure = config - pack = config - def __setitem__(self, key, value): - Pack.config({key: value}) - def forget(self): - self.tk.call('pack', 'forget', self._w) - pack_forget = forget - def info(self): - words = self.tk.splitlist( - self.tk.call('pack', 'info', self._w)) - dict = {} - for i in range(0, len(words), 2): - key = words[i][1:] - value = words[i+1] - if value[:1] == '.': - value = self._nametowidget(value) - dict[key] = value - return dict - pack_info = info - _noarg_ = ['_noarg_'] - def propagate(self, flag=_noarg_): - if flag is Pack._noarg_: - return self._getboolean(self.tk.call( - 'pack', 'propagate', self._w)) - else: - self.tk.call('pack', 'propagate', self._w, flag) - pack_propagate = propagate - def slaves(self): - return map(self._nametowidget, - self.tk.splitlist( - self.tk.call('pack', 'slaves', self._w))) - pack_slaves = slaves - -class Place: - def config(self, cnf={}, **kw): - for k in ['in_']: - if kw.has_key(k): - kw[k[:-1]] = kw[k] - del kw[k] - apply(self.tk.call, - ('place', 'configure', self._w) - + self._options(cnf, kw)) - configure = config - place = config - def __setitem__(self, key, value): - Place.config({key: value}) - def forget(self): - self.tk.call('place', 'forget', self._w) - place_forget = forget - def info(self): - words = self.tk.splitlist( - self.tk.call('place', 'info', self._w)) - dict = {} - for i in range(0, len(words), 2): - key = words[i][1:] - value = words[i+1] - if value[:1] == '.': - value = self._nametowidget(value) - dict[key] = value - return dict - place_info = info - def slaves(self): - return map(self._nametowidget, - self.tk.splitlist( - self.tk.call( - 'place', 'slaves', self._w))) - place_slaves = slaves - -class Grid: - # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu) - def config(self, cnf={}, **kw): - apply(self.tk.call, - ('grid', 'configure', self._w) - + self._options(cnf, kw)) - grid = config - def __setitem__(self, key, value): - Grid.config({key: value}) - def bbox(self, column, row): - return self._getints( - self.tk.call( - 'grid', 'bbox', self._w, column, row)) or None - grid_bbox = bbox - def columnconfigure(self, index, cnf={}, **kw): - if type(cnf) is not DictionaryType and not kw: - options = self._options({cnf: None}) - else: - options = self._options(cnf, kw) - res = apply(self.tk.call, - ('grid', 'columnconfigure', self._w, index) - + options) - if options == ('-minsize', None): - return self.tk.getint(res) or None - elif options == ('-weight', None): - return self.tk.getdouble(res) or None - def forget(self): - self.tk.call('grid', 'forget', self._w) - grid_forget = forget - def info(self): - words = self.tk.splitlist( - self.tk.call('grid', 'info', self._w)) - dict = {} - for i in range(0, len(words), 2): - key = words[i][1:] - value = words[i+1] - if value[:1] == '.': - value = self._nametowidget(value) - dict[key] = value - return dict - grid_info = info - def location(self, x, y): - return self._getints( - self.tk.call( - 'grid', 'location', self._w, x, y)) or None - _noarg_ = ['_noarg_'] - def propagate(self, flag=_noarg_): - if flag is Grid._noarg_: - return self._getboolean(self.tk.call( - 'grid', 'propagate', self._w)) - else: - self.tk.call('grid', 'propagate', self._w, flag) - grid_propagate = propagate - def rowconfigure(self, index, cnf={}, **kw): - if type(cnf) is not DictionaryType and not kw: - options = self._options({cnf: None}) - else: - options = self._options(cnf, kw) - res = apply(self.tk.call, - ('grid', 'rowconfigure', self._w, index) - + options) - if options == ('-minsize', None): - return self.tk.getint(res) or None - elif options == ('-weight', None): - return self.tk.getdouble(res) or None - def size(self): - return self._getints( - self.tk.call('grid', 'size', self._w)) or None - def slaves(self, *args): - return map(self._nametowidget, - self.tk.splitlist( - apply(self.tk.call, - ('grid', 'slaves', self._w) + args))) - grid_slaves = slaves - -class Widget(Misc, Pack, Place, Grid): - def _setup(self, master, cnf): - global _default_root - if not master: - if not _default_root: - _default_root = Tk() - master = _default_root - if not _default_root: - _default_root = master - self.master = master - self.tk = master.tk - if cnf.has_key('name'): - name = cnf['name'] - del cnf['name'] - else: - name = `id(self)` - self._name = name - if master._w=='.': - self._w = '.' + name - else: - self._w = master._w + '.' + name - self.children = {} - if self.master.children.has_key(self._name): - self.master.children[self._name].destroy() - self.master.children[self._name] = self - def __init__(self, master, widgetName, cnf={}, kw={}, extra=()): - if kw: - cnf = _cnfmerge((cnf, kw)) - self.widgetName = widgetName - Widget._setup(self, master, cnf) - apply(self.tk.call, - (widgetName, self._w) + extra + self._options(cnf)) - def config(self, cnf=None, **kw): - # XXX ought to generalize this so tag_config etc. can use it - if kw: - cnf = _cnfmerge((cnf, kw)) - elif cnf: - cnf = _cnfmerge(cnf) - if cnf is None: - cnf = {} - for x in self.tk.split( - self.tk.call(self._w, 'configure')): - cnf[x[0][1:]] = (x[0][1:],) + x[1:] - return cnf - if type(cnf) is StringType: - x = self.tk.split(self.tk.call( - self._w, 'configure', '-'+cnf)) - return (x[0][1:],) + x[1:] - for k in cnf.keys(): - if type(k) is ClassType: - k.config(self, cnf[k]) - del cnf[k] - apply(self.tk.call, (self._w, 'configure') - + self._options(cnf)) - configure = config - def cget(self, key): - return self.tk.call(self._w, 'cget', '-' + key) - __getitem__ = cget - def __setitem__(self, key, value): - Widget.config(self, {key: value}) - def keys(self): - return map(lambda x: x[0][1:], - self.tk.split(self.tk.call(self._w, 'configure'))) - def __str__(self): - return self._w - def destroy(self): - for c in self.children.values(): c.destroy() - if self.master.children.has_key(self._name): - del self.master.children[self._name] - self.tk.call('destroy', self._w) - def _do(self, name, args=()): - return apply(self.tk.call, (self._w, name) + args) - -class Toplevel(Widget, Wm): - def __init__(self, master=None, cnf={}, **kw): - if kw: - cnf = _cnfmerge((cnf, kw)) - extra = () - for wmkey in ['screen', 'class_', 'class', 'visual', - 'colormap']: - if cnf.has_key(wmkey): - val = cnf[wmkey] - # TBD: a hack needed because some keys - # are not valid as keyword arguments - if wmkey[-1] == '_': opt = '-'+wmkey[:-1] - else: opt = '-'+wmkey - extra = extra + (opt, val) - del cnf[wmkey] - Widget.__init__(self, master, 'toplevel', cnf, {}, extra) - root = self._root() - self.iconname(root.iconname()) - self.title(root.title()) - -class Button(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'button', cnf, kw) - def tkButtonEnter(self, *dummy): - self.tk.call('tkButtonEnter', self._w) - def tkButtonLeave(self, *dummy): - self.tk.call('tkButtonLeave', self._w) - def tkButtonDown(self, *dummy): - self.tk.call('tkButtonDown', self._w) - def tkButtonUp(self, *dummy): - self.tk.call('tkButtonUp', self._w) - def tkButtonInvoke(self, *dummy): - self.tk.call('tkButtonInvoke', self._w) - def flash(self): - self.tk.call(self._w, 'flash') - def invoke(self): - self.tk.call(self._w, 'invoke') - -# Indices: -# XXX I don't like these -- take them away -def AtEnd(): - return 'end' -def AtInsert(*args): - s = 'insert' - for a in args: - if a: s = s + (' ' + a) - return s -def AtSelFirst(): - return 'sel.first' -def AtSelLast(): - return 'sel.last' -def At(x, y=None): - if y is None: - return '@' + `x` - else: - return '@' + `x` + ',' + `y` - -class Canvas(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'canvas', cnf, kw) - def addtag(self, *args): - self._do('addtag', args) - def addtag_above(self, tagOrId): - self.addtag('above', tagOrId) - def addtag_all(self): - self.addtag('all') - def addtag_below(self, tagOrId): - self.addtag('below', tagOrId) - def addtag_closest(self, x, y, halo=None, start=None): - self.addtag('closest', x, y, halo, start) - def addtag_enclosed(self, x1, y1, x2, y2): - self.addtag('enclosed', x1, y1, x2, y2) - def addtag_overlapping(self, x1, y1, x2, y2): - self.addtag('overlapping', x1, y1, x2, y2) - def addtag_withtag(self, tagOrId): - self.addtag('withtag', tagOrId) - def bbox(self, *args): - return self._getints(self._do('bbox', args)) or None - def tag_unbind(self, tagOrId, sequence): - self.tk.call(self._w, 'bind', tagOrId, sequence, '') - def tag_bind(self, tagOrId, sequence=None, func=None, add=None): - return self._bind((self._w, 'tag', 'bind', tagOrId), - sequence, func, add) - def canvasx(self, screenx, gridspacing=None): - return self.tk.getdouble(self.tk.call( - self._w, 'canvasx', screenx, gridspacing)) - def canvasy(self, screeny, gridspacing=None): - return self.tk.getdouble(self.tk.call( - self._w, 'canvasy', screeny, gridspacing)) - def coords(self, *args): - return self._do('coords', args) - def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={}) - args = _flatten(args) - cnf = args[-1] - if type(cnf) in (DictionaryType, TupleType): - args = args[:-1] - else: - cnf = {} - return self.tk.getint(apply( - self.tk.call, - (self._w, 'create', itemType) - + args + self._options(cnf, kw))) - def create_arc(self, *args, **kw): - return self._create('arc', args, kw) - def create_bitmap(self, *args, **kw): - return self._create('bitmap', args, kw) - def create_image(self, *args, **kw): - return self._create('image', args, kw) - def create_line(self, *args, **kw): - return self._create('line', args, kw) - def create_oval(self, *args, **kw): - return self._create('oval', args, kw) - def create_polygon(self, *args, **kw): - return self._create('polygon', args, kw) - def create_rectangle(self, *args, **kw): - return self._create('rectangle', args, kw) - def create_text(self, *args, **kw): - return self._create('text', args, kw) - def create_window(self, *args, **kw): - return self._create('window', args, kw) - def dchars(self, *args): - self._do('dchars', args) - def delete(self, *args): - self._do('delete', args) - def dtag(self, *args): - self._do('dtag', args) - def find(self, *args): - return self._getints(self._do('find', args)) or () - def find_above(self, tagOrId): - return self.find('above', tagOrId) - def find_all(self): - return self.find('all') - def find_below(self, tagOrId): - return self.find('below', tagOrId) - def find_closest(self, x, y, halo=None, start=None): - return self.find('closest', x, y, halo, start) - def find_enclosed(self, x1, y1, x2, y2): - return self.find('enclosed', x1, y1, x2, y2) - def find_overlapping(self, x1, y1, x2, y2): - return self.find('overlapping', x1, y1, x2, y2) - def find_withtag(self, tagOrId): - return self.find('withtag', tagOrId) - def focus(self, *args): - return self._do('focus', args) - def gettags(self, *args): - return self.tk.splitlist(self._do('gettags', args)) - def icursor(self, *args): - self._do('icursor', args) - def index(self, *args): - return self.tk.getint(self._do('index', args)) - def insert(self, *args): - self._do('insert', args) - def itemcget(self, tagOrId, option): - return self._do('itemcget', (tagOrId, '-'+option)) - def itemconfig(self, tagOrId, cnf=None, **kw): - if cnf is None and not kw: - cnf = {} - for x in self.tk.split( - self._do('itemconfigure', (tagOrId))): - cnf[x[0][1:]] = (x[0][1:],) + x[1:] - return cnf - if type(cnf) == StringType and not kw: - x = self.tk.split(self._do('itemconfigure', - (tagOrId, '-'+cnf,))) - return (x[0][1:],) + x[1:] - self._do('itemconfigure', (tagOrId,) - + self._options(cnf, kw)) - itemconfigure = itemconfig - def lower(self, *args): - self._do('lower', args) - def move(self, *args): - self._do('move', args) - def postscript(self, cnf={}, **kw): - return self._do('postscript', self._options(cnf, kw)) - def tkraise(self, *args): - self._do('raise', args) - lift = tkraise - def scale(self, *args): - self._do('scale', args) - def scan_mark(self, x, y): - self.tk.call(self._w, 'scan', 'mark', x, y) - def scan_dragto(self, x, y): - self.tk.call(self._w, 'scan', 'dragto', x, y) - def select_adjust(self, tagOrId, index): - self.tk.call(self._w, 'select', 'adjust', tagOrId, index) - def select_clear(self): - self.tk.call(self._w, 'select', 'clear') - def select_from(self, tagOrId, index): - self.tk.call(self._w, 'select', 'set', tagOrId, index) - def select_item(self): - self.tk.call(self._w, 'select', 'item') - def select_to(self, tagOrId, index): - self.tk.call(self._w, 'select', 'to', tagOrId, index) - def type(self, tagOrId): - return self.tk.call(self._w, 'type', tagOrId) or None - def xview(self, *args): - if not args: - return self._getdoubles(self.tk.call(self._w, 'xview')) - apply(self.tk.call, (self._w, 'xview')+args) - def yview(self, *args): - if not args: - return self._getdoubles(self.tk.call(self._w, 'yview')) - apply(self.tk.call, (self._w, 'yview')+args) - -class Checkbutton(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'checkbutton', cnf, kw) - def deselect(self): - self.tk.call(self._w, 'deselect') - def flash(self): - self.tk.call(self._w, 'flash') - def invoke(self): - self.tk.call(self._w, 'invoke') - def select(self): - self.tk.call(self._w, 'select') - def toggle(self): - self.tk.call(self._w, 'toggle') - -class Entry(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'entry', cnf, kw) - def delete(self, first, last=None): - self.tk.call(self._w, 'delete', first, last) - def get(self): - return self.tk.call(self._w, 'get') - def icursor(self, index): - self.tk.call(self._w, 'icursor', index) - def index(self, index): - return self.tk.getint(self.tk.call( - self._w, 'index', index)) - def insert(self, index, string): - self.tk.call(self._w, 'insert', index, string) - def scan_mark(self, x): - self.tk.call(self._w, 'scan', 'mark', x) - def scan_dragto(self, x): - self.tk.call(self._w, 'scan', 'dragto', x) - def selection_adjust(self, index): - self.tk.call(self._w, 'selection', 'adjust', index) - select_adjust = selection_adjust - def selection_clear(self): - self.tk.call(self._w, 'selection', 'clear') - select_clear = selection_clear - def selection_from(self, index): - self.tk.call(self._w, 'selection', 'set', index) - select_from = selection_from - def selection_present(self): - return self.tk.getboolean( - self.tk.call(self._w, 'selection', 'present')) - select_present = selection_present - def selection_range(self, start, end): - self.tk.call(self._w, 'selection', 'range', start, end) - select_range = selection_range - def selection_to(self, index): - self.tk.call(self._w, 'selection', 'to', index) - select_to = selection_to - def xview(self, index): - self.tk.call(self._w, 'xview', index) - def xview_moveto(self, fraction): - self.tk.call(self._w, 'xview', 'moveto', fraction) - def xview_scroll(self, number, what): - self.tk.call(self._w, 'xview', 'scroll', number, what) - -class Frame(Widget): - def __init__(self, master=None, cnf={}, **kw): - cnf = _cnfmerge((cnf, kw)) - extra = () - if cnf.has_key('class'): - extra = ('-class', cnf['class']) - del cnf['class'] - Widget.__init__(self, master, 'frame', cnf, {}, extra) - -class Label(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'label', cnf, kw) - -class Listbox(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'listbox', cnf, kw) - def activate(self, index): - self.tk.call(self._w, 'activate', index) - def bbox(self, *args): - return self._getints(self._do('bbox', args)) or None - def curselection(self): - # XXX Ought to apply self._getints()... - return self.tk.splitlist(self.tk.call( - self._w, 'curselection')) - def delete(self, first, last=None): - self.tk.call(self._w, 'delete', first, last) - def get(self, first, last=None): - if last: - return self.tk.splitlist(self.tk.call( - self._w, 'get', first, last)) - else: - return self.tk.call(self._w, 'get', first) - def insert(self, index, *elements): - apply(self.tk.call, - (self._w, 'insert', index) + elements) - def nearest(self, y): - return self.tk.getint(self.tk.call( - self._w, 'nearest', y)) - def scan_mark(self, x, y): - self.tk.call(self._w, 'scan', 'mark', x, y) - def scan_dragto(self, x, y): - self.tk.call(self._w, 'scan', 'dragto', x, y) - def see(self, index): - self.tk.call(self._w, 'see', index) - def index(self, index): - i = self.tk.call(self._w, 'index', index) - if i == 'none': return None - return self.tk.getint(i) - def select_adjust(self, index): - self.tk.call(self._w, 'select', 'adjust', index) - def select_anchor(self, index): - self.tk.call(self._w, 'selection', 'anchor', index) - def select_clear(self, first, last=None): - self.tk.call(self._w, - 'selection', 'clear', first, last) - def select_includes(self, index): - return self.tk.getboolean(self.tk.call( - self._w, 'selection', 'includes', index)) - def select_set(self, first, last=None): - self.tk.call(self._w, 'selection', 'set', first, last) - def size(self): - return self.tk.getint(self.tk.call(self._w, 'size')) - def xview(self, *what): - if not what: - return self._getdoubles(self.tk.call(self._w, 'xview')) - apply(self.tk.call, (self._w, 'xview')+what) - def yview(self, *what): - if not what: - return self._getdoubles(self.tk.call(self._w, 'yview')) - apply(self.tk.call, (self._w, 'yview')+what) - -class Menu(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'menu', cnf, kw) - def tk_bindForTraversal(self): - self.tk.call('tk_bindForTraversal', self._w) - def tk_mbPost(self): - self.tk.call('tk_mbPost', self._w) - def tk_mbUnpost(self): - self.tk.call('tk_mbUnpost') - def tk_traverseToMenu(self, char): - self.tk.call('tk_traverseToMenu', self._w, char) - def tk_traverseWithinMenu(self, char): - self.tk.call('tk_traverseWithinMenu', self._w, char) - def tk_getMenuButtons(self): - return self.tk.call('tk_getMenuButtons', self._w) - def tk_nextMenu(self, count): - self.tk.call('tk_nextMenu', count) - def tk_nextMenuEntry(self, count): - self.tk.call('tk_nextMenuEntry', count) - def tk_invokeMenu(self): - self.tk.call('tk_invokeMenu', self._w) - def tk_firstMenu(self): - self.tk.call('tk_firstMenu', self._w) - def tk_mbButtonDown(self): - self.tk.call('tk_mbButtonDown', self._w) - def tk_popup(self, x, y, entry=""): - self.tk.call('tk_popup', self._w, x, y, entry) - def activate(self, index): - self.tk.call(self._w, 'activate', index) - def add(self, itemType, cnf={}, **kw): - apply(self.tk.call, (self._w, 'add', itemType) - + self._options(cnf, kw)) - def add_cascade(self, cnf={}, **kw): - self.add('cascade', cnf or kw) - def add_checkbutton(self, cnf={}, **kw): - self.add('checkbutton', cnf or kw) - def add_command(self, cnf={}, **kw): - self.add('command', cnf or kw) - def add_radiobutton(self, cnf={}, **kw): - self.add('radiobutton', cnf or kw) - def add_separator(self, cnf={}, **kw): - self.add('separator', cnf or kw) - def delete(self, index1, index2=None): - self.tk.call(self._w, 'delete', index1, index2) - def entryconfig(self, index, cnf=None, **kw): - if cnf is None and not kw: - cnf = {} - for x in self.tk.split(apply(self.tk.call, - (self._w, 'entryconfigure', index))): - cnf[x[0][1:]] = (x[0][1:],) + x[1:] - return cnf - if type(cnf) == StringType and not kw: - x = self.tk.split(apply(self.tk.call, - (self._w, 'entryconfigure', index, '-'+cnf))) - return (x[0][1:],) + x[1:] - apply(self.tk.call, (self._w, 'entryconfigure', index) - + self._options(cnf, kw)) - entryconfigure = entryconfig - def index(self, index): - i = self.tk.call(self._w, 'index', index) - if i == 'none': return None - return self.tk.getint(i) - def invoke(self, index): - return self.tk.call(self._w, 'invoke', index) - def post(self, x, y): - self.tk.call(self._w, 'post', x, y) - def unpost(self): - self.tk.call(self._w, 'unpost') - def yposition(self, index): - return self.tk.getint(self.tk.call( - self._w, 'yposition', index)) - -class Menubutton(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'menubutton', cnf, kw) - -class Message(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'message', cnf, kw) - -class Radiobutton(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'radiobutton', cnf, kw) - def deselect(self): - self.tk.call(self._w, 'deselect') - def flash(self): - self.tk.call(self._w, 'flash') - def invoke(self): - self.tk.call(self._w, 'invoke') - def select(self): - self.tk.call(self._w, 'select') - -class Scale(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'scale', cnf, kw) - def get(self): - return self.tk.getint(self.tk.call(self._w, 'get')) - def set(self, value): - self.tk.call(self._w, 'set', value) - -class Scrollbar(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'scrollbar', cnf, kw) - def activate(self, index): - self.tk.call(self._w, 'activate', index) - def delta(self, deltax, deltay): - return self.getdouble(self.tk.call( - self._w, 'delta', deltax, deltay)) - def fraction(self, x, y): - return self.getdouble(self.tk.call( - self._w, 'fraction', x, y)) - def identify(self, x, y): - return self.tk.call(self._w, 'identify', x, y) - def get(self): - return self._getdoubles(self.tk.call(self._w, 'get')) - def set(self, *args): - apply(self.tk.call, (self._w, 'set')+args) - -class Text(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'text', cnf, kw) - self.bind('<Delete>', self.bspace) - def bbox(self, *args): - return self._getints(self._do('bbox', args)) or None - def bspace(self, *args): - self.delete('insert') - def tk_textSelectTo(self, index): - self.tk.call('tk_textSelectTo', self._w, index) - def tk_textBackspace(self): - self.tk.call('tk_textBackspace', self._w) - def tk_textIndexCloser(self, a, b, c): - self.tk.call('tk_textIndexCloser', self._w, a, b, c) - def tk_textResetAnchor(self, index): - self.tk.call('tk_textResetAnchor', self._w, index) - def compare(self, index1, op, index2): - return self.tk.getboolean(self.tk.call( - self._w, 'compare', index1, op, index2)) - def debug(self, boolean=None): - return self.tk.getboolean(self.tk.call( - self._w, 'debug', boolean)) - def delete(self, index1, index2=None): - self.tk.call(self._w, 'delete', index1, index2) - def dlineinfo(self, index): - return self._getints(self.tk.call(self._w, 'dlineinfo', index)) - def get(self, index1, index2=None): - return self.tk.call(self._w, 'get', index1, index2) - def index(self, index): - return self.tk.call(self._w, 'index', index) - def insert(self, index, chars, *args): - apply(self.tk.call, (self._w, 'insert', index, chars)+args) - def mark_gravity(self, markName, direction=None): - return apply(self.tk.call, - (self._w, 'mark', 'gravity', markName, direction)) - def mark_names(self): - return self.tk.splitlist(self.tk.call( - self._w, 'mark', 'names')) - def mark_set(self, markName, index): - self.tk.call(self._w, 'mark', 'set', markName, index) - def mark_unset(self, *markNames): - apply(self.tk.call, (self._w, 'mark', 'unset') + markNames) - def scan_mark(self, x, y): - self.tk.call(self._w, 'scan', 'mark', x, y) - def scan_dragto(self, x, y): - self.tk.call(self._w, 'scan', 'dragto', x, y) - def search(self, pattern, index, stopindex=None, - forwards=None, backwards=None, exact=None, - regexp=None, nocase=None, count=None): - args = [self._w, 'search'] - if forwards: args.append('-forwards') - if backwards: args.append('-backwards') - if exact: args.append('-exact') - if regexp: args.append('-regexp') - if nocase: args.append('-nocase') - if count: args.append('-count'); args.append(count) - if pattern[0] == '-': args.append('--') - args.append(pattern) - args.append(index) - if stopindex: args.append(stopindex) - return apply(self.tk.call, tuple(args)) - def see(self, index): - self.tk.call(self._w, 'see', index) - def tag_add(self, tagName, index1, index2=None): - self.tk.call( - self._w, 'tag', 'add', tagName, index1, index2) - def tag_unbind(self, tagName, sequence): - self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '') - def tag_bind(self, tagName, sequence, func, add=None): - return self._bind((self._w, 'tag', 'bind', tagName), - sequence, func, add) - def tag_cget(self, tagName, option): - return self.tk.call(self._w, 'tag', 'cget', tagName, option) - def tag_config(self, tagName, cnf={}, **kw): - if type(cnf) == StringType: - x = self.tk.split(self.tk.call( - self._w, 'tag', 'configure', tagName, '-'+cnf)) - return (x[0][1:],) + x[1:] - apply(self.tk.call, - (self._w, 'tag', 'configure', tagName) - + self._options(cnf, kw)) - tag_configure = tag_config - def tag_delete(self, *tagNames): - apply(self.tk.call, (self._w, 'tag', 'delete') + tagNames) - def tag_lower(self, tagName, belowThis=None): - self.tk.call(self._w, 'tag', 'lower', tagName, belowThis) - def tag_names(self, index=None): - return self.tk.splitlist( - self.tk.call(self._w, 'tag', 'names', index)) - def tag_nextrange(self, tagName, index1, index2=None): - return self.tk.splitlist(self.tk.call( - self._w, 'tag', 'nextrange', tagName, index1, index2)) - def tag_raise(self, tagName, aboveThis=None): - self.tk.call( - self._w, 'tag', 'raise', tagName, aboveThis) - def tag_ranges(self, tagName): - return self.tk.splitlist(self.tk.call( - self._w, 'tag', 'ranges', tagName)) - def tag_remove(self, tagName, index1, index2=None): - self.tk.call( - self._w, 'tag', 'remove', tagName, index1, index2) - def window_cget(self, index, option): - return self.tk.call(self._w, 'window', 'cget', index, option) - def window_config(self, index, cnf={}, **kw): - if type(cnf) == StringType: - x = self.tk.split(self.tk.call( - self._w, 'window', 'configure', - index, '-'+cnf)) - return (x[0][1:],) + x[1:] - apply(self.tk.call, - (self._w, 'window', 'configure', index) - + self._options(cnf, kw)) - window_configure = window_config - def window_create(self, index, cnf={}, **kw): - apply(self.tk.call, - (self._w, 'window', 'create', index) - + self._options(cnf, kw)) - def window_names(self): - return self.tk.splitlist( - self.tk.call(self._w, 'window', 'names')) - def xview(self, *what): - if not what: - return self._getdoubles(self.tk.call(self._w, 'xview')) - apply(self.tk.call, (self._w, 'xview')+what) - def yview(self, *what): - if not what: - return self._getdoubles(self.tk.call(self._w, 'yview')) - apply(self.tk.call, (self._w, 'yview')+what) - def yview_pickplace(self, *what): - apply(self.tk.call, (self._w, 'yview', '-pickplace')+what) - -class OptionMenu(Widget): - def __init__(self, master, variable, value, *values): - self.widgetName = 'tk_optionMenu' - Widget._setup(self, master, {}) - self.menuname = apply( - self.tk.call, - (self.widgetName, self._w, variable, value) + values) - -class Image: - def __init__(self, imgtype, name=None, cnf={}, **kw): - self.name = None - master = _default_root - if not master: raise RuntimeError, 'Too early to create image' - self.tk = master.tk - if not name: name = `id(self)` - if kw and cnf: cnf = _cnfmerge((cnf, kw)) - elif kw: cnf = kw - options = () - for k, v in cnf.items(): - if callable(v): - v = self._register(v) - options = options + ('-'+k, v) - apply(self.tk.call, - ('image', 'create', imgtype, name,) + options) - self.name = name - def __str__(self): return self.name - def __del__(self): - if self.name: - self.tk.call('image', 'delete', self.name) - def __setitem__(self, key, value): - self.tk.call(self.name, 'configure', '-'+key, value) - def __getitem__(self, key): - return self.tk.call(self.name, 'configure', '-'+key) - def height(self): - return self.tk.getint( - self.tk.call('image', 'height', self.name)) - def type(self): - return self.tk.call('image', 'type', self.name) - def width(self): - return self.tk.getint( - self.tk.call('image', 'width', self.name)) - -class PhotoImage(Image): - def __init__(self, name=None, cnf={}, **kw): - apply(Image.__init__, (self, 'photo', name, cnf), kw) - def blank(self): - self.tk.call(self.name, 'blank') - def cget(self, option): - return self.tk.call(self.name, 'cget', '-' + option) - # XXX config - def __getitem__(self, key): - return self.tk.call(self.name, 'cget', '-' + key) - def copy(self): - destImage = PhotoImage() - self.tk.call(destImage, 'copy', self.name) - return destImage - def zoom(self,x,y=''): - destImage = PhotoImage() - if y=='': y=x - self.tk.call(destImage, 'copy', self.name, '-zoom',x,y) - return destImage - def subsample(self,x,y=''): - destImage = PhotoImage() - if y=='': y=x - self.tk.call(destImage, 'copy', self.name, '-subsample',x,y) - return destImage - def get(self, x, y): - return self.tk.call(self.name, 'get', x, y) - def put(self, data, to=None): - args = (self.name, 'put', data) - if to: - args = args + to - apply(self.tk.call, args) - # XXX read - def write(self, filename, format=None, from_coords=None): - args = (self.name, 'write', filename) - if format: - args = args + ('-format', format) - if from_coords: - args = args + ('-from',) + tuple(from_coords) - apply(self.tk.call, args) - -class BitmapImage(Image): - def __init__(self, name=None, cnf={}, **kw): - apply(Image.__init__, (self, 'bitmap', name, cnf), kw) - -def image_names(): return _default_root.tk.call('image', 'names') -def image_types(): return _default_root.tk.call('image', 'types') - -###################################################################### -# Extensions: - -class Studbutton(Button): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'studbutton', cnf, kw) - self.bind('<Any-Enter>', self.tkButtonEnter) - self.bind('<Any-Leave>', self.tkButtonLeave) - self.bind('<1>', self.tkButtonDown) - self.bind('<ButtonRelease-1>', self.tkButtonUp) - -class Tributton(Button): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'tributton', cnf, kw) - self.bind('<Any-Enter>', self.tkButtonEnter) - self.bind('<Any-Leave>', self.tkButtonLeave) - self.bind('<1>', self.tkButtonDown) - self.bind('<ButtonRelease-1>', self.tkButtonUp) - self['fg'] = self['bg'] - self['activebackground'] = self['bg'] - - -# Emacs cruft -# Local Variables: -# py-indent-offset: 8 -# End: diff --git a/Lib/linecache.py b/Lib/linecache.py deleted file mode 100644 index 7de373fc54..0000000000 --- a/Lib/linecache.py +++ /dev/null @@ -1,90 +0,0 @@ -# Cache lines from files. -# This is intended to read lines from modules imported -- hence if a filename -# is not found, it will look down the module search path for a file by -# that name. - -import sys -import os -from stat import * - -def getline(filename, lineno): - lines = getlines(filename) - if 1 <= lineno <= len(lines): - return lines[lineno-1] - else: - return '' - - -# The cache - -cache = {} # The cache - - -# Clear the cache entirely - -def clearcache(): - global cache - cache = {} - - -# Get the lines for a file from the cache. -# Update the cache if it doesn't contain an entry for this file already. - -def getlines(filename): - if cache.has_key(filename): - return cache[filename][2] - else: - return updatecache(filename) - - -# Discard cache entries that are out of date. -# (This is not checked upon each call!) - -def checkcache(): - for filename in cache.keys(): - size, mtime, lines, fullname = cache[filename] - try: - stat = os.stat(fullname) - except os.error: - del cache[filename] - continue - if size <> stat[ST_SIZE] or mtime <> stat[ST_MTIME]: - del cache[filename] - - -# Update a cache entry and return its list of lines. -# If something's wrong, print a message, discard the cache entry, -# and return an empty list. - -def updatecache(filename): - if cache.has_key(filename): - del cache[filename] - if not filename or filename[0] + filename[-1] == '<>': - return [] - fullname = filename - try: - stat = os.stat(fullname) - except os.error, msg: - # Try looking through the module search path - basename = os.path.split(filename)[1] - for dirname in sys.path: - fullname = os.path.join(dirname, basename) - try: - stat = os.stat(fullname) - break - except os.error: - pass - else: - # No luck -## print '*** Cannot stat', filename, ':', msg - return [] - try: - fp = open(fullname, 'r') - lines = fp.readlines() - fp.close() - except IOError, msg: -## print '*** Cannot open', fullname, ':', msg - return [] - size, mtime = stat[ST_SIZE], stat[ST_MTIME] - cache[filename] = size, mtime, lines, fullname - return lines diff --git a/Lib/linux1/FCNTL.py b/Lib/linux1/FCNTL.py deleted file mode 100755 index f65c4fa389..0000000000 --- a/Lib/linux1/FCNTL.py +++ /dev/null @@ -1,101 +0,0 @@ -# Generated by h2py from /usr/include/sys/fcntl.h - -# Included from fcntl.h - -# Included from features.h -_FEATURES_H = 1 -_GNU_SOURCE = 1 -__USE_ANSI = 1 -__FAVOR_BSD = 1 -_BSD_SOURCE = 1 -_SVID_SOURCE = 1 -_POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 2 -__USE_POSIX = 1 -__USE_POSIX2 = 1 -__USE_MISC = 1 -__USE_BSD = 1 -__USE_SVID = 1 -__USE_GNU = 1 -__GNU_LIBRARY__ = 1 - -# Included from sys/cdefs.h -_SYS_CDEFS_H = 1 -def __P(args): return args - -def __P(args): return args - -def __P(args): return () - -def __STRING(x): return #x - -def __STRING(x): return "x" - - -# Included from sys/types.h - -# Included from linux/types.h -__FD_SETSIZE = 256 - -# Included from asm/types.h -def __FD_ZERO(fdsetp): return \ - - -# Included from sys/bitypes.h - -# Included from gnu/types.h -_GNU_TYPES_H = 1 -__FDSET_LONGS = 8 -def __FD_ZERO(fdsetp): return \ - -__FD_SETSIZE = 256 -def __FDELT(d): return ((d) / __NFDBITS) - -def __FDMASK(d): return (1 << ((d) % __NFDBITS)) - -def __FD_ZERO(set): return \ - - -# Included from linux/fcntl.h - -# Included from asm/fcntl.h -O_ACCMODE = 0003 -O_RDONLY = 00 -O_WRONLY = 01 -O_RDWR = 02 -O_CREAT = 0100 -O_EXCL = 0200 -O_NOCTTY = 0400 -O_TRUNC = 01000 -O_APPEND = 02000 -O_NONBLOCK = 04000 -O_NDELAY = O_NONBLOCK -O_SYNC = 010000 -FASYNC = 020000 -F_DUPFD = 0 -F_GETFD = 1 -F_SETFD = 2 -F_GETFL = 3 -F_SETFL = 4 -F_GETLK = 5 -F_SETLK = 6 -F_SETLKW = 7 -F_SETOWN = 8 -F_GETOWN = 9 -FD_CLOEXEC = 1 -F_RDLCK = 0 -F_WRLCK = 1 -F_UNLCK = 2 -F_EXLCK = 4 -F_SHLCK = 8 -LOCK_SH = 1 -LOCK_EX = 2 -LOCK_NB = 4 -LOCK_UN = 8 -F_POSIX = 1 -F_FLOCK = 2 -FNDELAY = O_NDELAY -F_ULOCK = 0 -F_LOCK = 1 -F_TLOCK = 2 -F_TEST = 3 diff --git a/Lib/linux1/IN.py b/Lib/linux1/IN.py deleted file mode 100755 index 86710d13c2..0000000000 --- a/Lib/linux1/IN.py +++ /dev/null @@ -1,239 +0,0 @@ -# Generated by h2py from /usr/include/netinet/in.h -_NETINET_IN_H = 1 - -# Included from features.h -_FEATURES_H = 1 -_GNU_SOURCE = 1 -__USE_ANSI = 1 -__FAVOR_BSD = 1 -_BSD_SOURCE = 1 -_SVID_SOURCE = 1 -_POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 2 -__USE_POSIX = 1 -__USE_POSIX2 = 1 -__USE_MISC = 1 -__USE_BSD = 1 -__USE_SVID = 1 -__USE_GNU = 1 -__GNU_LIBRARY__ = 1 - -# Included from sys/cdefs.h -_SYS_CDEFS_H = 1 -def __P(args): return args - -def __P(args): return args - -def __P(args): return () - -def __STRING(x): return #x - -def __STRING(x): return "x" - - -# Included from sys/socket.h - -# Included from linux/socket.h - -# Included from asm/socket.h -FIOSETOWN = 0x8901 -SIOCSPGRP = 0x8902 -FIOGETOWN = 0x8903 -SIOCGPGRP = 0x8904 -SIOCATMARK = 0x8905 -SIOCGSTAMP = 0x8906 -SOL_SOCKET = 1 -SO_DEBUG = 1 -SO_REUSEADDR = 2 -SO_TYPE = 3 -SO_ERROR = 4 -SO_DONTROUTE = 5 -SO_BROADCAST = 6 -SO_SNDBUF = 7 -SO_RCVBUF = 8 -SO_KEEPALIVE = 9 -SO_OOBINLINE = 10 -SO_NO_CHECK = 11 -SO_PRIORITY = 12 -SO_LINGER = 13 - -# Included from linux/sockios.h -SIOCADDRT = 0x890B -SIOCDELRT = 0x890C -SIOCGIFNAME = 0x8910 -SIOCSIFLINK = 0x8911 -SIOCGIFCONF = 0x8912 -SIOCGIFFLAGS = 0x8913 -SIOCSIFFLAGS = 0x8914 -SIOCGIFADDR = 0x8915 -SIOCSIFADDR = 0x8916 -SIOCGIFDSTADDR = 0x8917 -SIOCSIFDSTADDR = 0x8918 -SIOCGIFBRDADDR = 0x8919 -SIOCSIFBRDADDR = 0x891a -SIOCGIFNETMASK = 0x891b -SIOCSIFNETMASK = 0x891c -SIOCGIFMETRIC = 0x891d -SIOCSIFMETRIC = 0x891e -SIOCGIFMEM = 0x891f -SIOCSIFMEM = 0x8920 -SIOCGIFMTU = 0x8921 -SIOCSIFMTU = 0x8922 -SIOCSIFHWADDR = 0x8924 -SIOCGIFENCAP = 0x8925 -SIOCSIFENCAP = 0x8926 -SIOCGIFHWADDR = 0x8927 -SIOCGIFSLAVE = 0x8929 -SIOCSIFSLAVE = 0x8930 -SIOCADDMULTI = 0x8931 -SIOCDELMULTI = 0x8932 -OLD_SIOCDARP = 0x8950 -OLD_SIOCGARP = 0x8951 -OLD_SIOCSARP = 0x8952 -SIOCDARP = 0x8953 -SIOCGARP = 0x8954 -SIOCSARP = 0x8955 -SIOCDRARP = 0x8960 -SIOCGRARP = 0x8961 -SIOCSRARP = 0x8962 -SIOCGIFMAP = 0x8970 -SIOCSIFMAP = 0x8971 -SIOCDEVPRIVATE = 0x89F0 -SIOCPROTOPRIVATE = 0x89E0 - -# Included from linux/uio.h -MAX_IOVEC = 8 -SOCK_STREAM = 1 -SOCK_DGRAM = 2 -SOCK_RAW = 3 -SOCK_RDM = 4 -SOCK_SEQPACKET = 5 -SOCK_PACKET = 10 -AF_UNSPEC = 0 -AF_UNIX = 1 -AF_INET = 2 -AF_AX25 = 3 -AF_IPX = 4 -AF_APPLETALK = 5 -AF_NETROM = 6 -AF_BRIDGE = 7 -AF_AAL5 = 8 -AF_X25 = 9 -AF_INET6 = 10 -AF_MAX = 12 -PF_UNSPEC = AF_UNSPEC -PF_UNIX = AF_UNIX -PF_INET = AF_INET -PF_AX25 = AF_AX25 -PF_IPX = AF_IPX -PF_APPLETALK = AF_APPLETALK -PF_NETROM = AF_NETROM -PF_BRIDGE = AF_BRIDGE -PF_AAL5 = AF_AAL5 -PF_X25 = AF_X25 -PF_INET6 = AF_INET6 -PF_MAX = AF_MAX -SOMAXCONN = 128 -MSG_OOB = 1 -MSG_PEEK = 2 -MSG_DONTROUTE = 4 -SOL_IP = 0 -SOL_IPX = 256 -SOL_AX25 = 257 -SOL_ATALK = 258 -SOL_NETROM = 259 -SOL_TCP = 6 -SOL_UDP = 17 -IP_TOS = 1 -IPTOS_LOWDELAY = 0x10 -IPTOS_THROUGHPUT = 0x08 -IPTOS_RELIABILITY = 0x04 -IP_TTL = 2 -IP_HDRINCL = 3 -IP_OPTIONS = 4 -IP_MULTICAST_IF = 32 -IP_MULTICAST_TTL = 33 -IP_MULTICAST_LOOP = 34 -IP_ADD_MEMBERSHIP = 35 -IP_DROP_MEMBERSHIP = 36 -IP_DEFAULT_MULTICAST_TTL = 1 -IP_DEFAULT_MULTICAST_LOOP = 1 -IP_MAX_MEMBERSHIPS = 20 -IPX_TYPE = 1 -TCP_NODELAY = 1 -TCP_MAXSEG = 2 -SOPRI_INTERACTIVE = 0 -SOPRI_NORMAL = 1 -SOPRI_BACKGROUND = 2 - -# Included from sys/types.h - -# Included from linux/types.h -__FD_SETSIZE = 256 - -# Included from asm/types.h -def __FD_ZERO(fdsetp): return \ - - -# Included from sys/bitypes.h - -# Included from pthread/mit/posix.h - -# Included from pthread/mit/types.h - -# Included from pthread/mit/xtypes.h - -# Included from pthread/mit/sys/types.h -IMPLINK_IP = 155 -IMPLINK_LOWEXPER = 156 -IMPLINK_HIGHEXPER = 158 - -# Included from linux/in.h -__SOCK_SIZE__ = 16 -IN_CLASSA_NET = 0xff000000 -IN_CLASSA_NSHIFT = 24 -IN_CLASSA_HOST = (0xffffffff & ~IN_CLASSA_NET) -IN_CLASSA_MAX = 128 -IN_CLASSB_NET = 0xffff0000 -IN_CLASSB_NSHIFT = 16 -IN_CLASSB_HOST = (0xffffffff & ~IN_CLASSB_NET) -IN_CLASSB_MAX = 65536 -IN_CLASSC_NET = 0xffffff00 -IN_CLASSC_NSHIFT = 8 -IN_CLASSC_HOST = (0xffffffff & ~IN_CLASSC_NET) -def IN_MULTICAST(a): return IN_CLASSD(a) - -IN_MULTICAST_NET = 0xF0000000 -INADDR_NONE = 0xffffffff -IN_LOOPBACKNET = 127 -INADDR_LOOPBACK = 0x7f000001 -INADDR_UNSPEC_GROUP = 0xe0000000 -INADDR_ALLHOSTS_GROUP = 0xe0000001 -INADDR_MAX_LOCAL_GROUP = 0xe00000ff - -# Included from asm/byteorder.h -__LITTLE_ENDIAN = 1234 -def __constant_ntohl(x): return \ - -def __constant_ntohs(x): return \ - -def __htonl(x): return __ntohl(x) - -def __htons(x): return __ntohs(x) - -def __constant_htonl(x): return __constant_ntohl(x) - -def __constant_htons(x): return __constant_ntohs(x) - -def ntohl(x): return \ - -def ntohs(x): return \ - -def htonl(x): return \ - -def htons(x): return \ - -def LOOPBACK(x): return (((x) & htonl(0xff000000)) == htonl(0x7f000000)) - -def MULTICAST(x): return (((x) & htonl(0xf0000000)) == htonl(0xe0000000)) - diff --git a/Lib/linux1/SOCKET.py b/Lib/linux1/SOCKET.py deleted file mode 100755 index 71077c3912..0000000000 --- a/Lib/linux1/SOCKET.py +++ /dev/null @@ -1,183 +0,0 @@ -# Generated by h2py from /usr/include/sys/socket.h - -# Included from features.h -_FEATURES_H = 1 -_GNU_SOURCE = 1 -__USE_ANSI = 1 -__FAVOR_BSD = 1 -_BSD_SOURCE = 1 -_SVID_SOURCE = 1 -_POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 2 -__USE_POSIX = 1 -__USE_POSIX2 = 1 -__USE_MISC = 1 -__USE_BSD = 1 -__USE_SVID = 1 -__USE_GNU = 1 -__GNU_LIBRARY__ = 1 - -# Included from sys/cdefs.h -_SYS_CDEFS_H = 1 -def __P(args): return args - -def __P(args): return args - -def __P(args): return () - -def __STRING(x): return #x - -def __STRING(x): return "x" - - -# Included from linux/socket.h - -# Included from asm/socket.h -FIOSETOWN = 0x8901 -SIOCSPGRP = 0x8902 -FIOGETOWN = 0x8903 -SIOCGPGRP = 0x8904 -SIOCATMARK = 0x8905 -SIOCGSTAMP = 0x8906 -SOL_SOCKET = 1 -SO_DEBUG = 1 -SO_REUSEADDR = 2 -SO_TYPE = 3 -SO_ERROR = 4 -SO_DONTROUTE = 5 -SO_BROADCAST = 6 -SO_SNDBUF = 7 -SO_RCVBUF = 8 -SO_KEEPALIVE = 9 -SO_OOBINLINE = 10 -SO_NO_CHECK = 11 -SO_PRIORITY = 12 -SO_LINGER = 13 - -# Included from linux/sockios.h -SIOCADDRT = 0x890B -SIOCDELRT = 0x890C -SIOCGIFNAME = 0x8910 -SIOCSIFLINK = 0x8911 -SIOCGIFCONF = 0x8912 -SIOCGIFFLAGS = 0x8913 -SIOCSIFFLAGS = 0x8914 -SIOCGIFADDR = 0x8915 -SIOCSIFADDR = 0x8916 -SIOCGIFDSTADDR = 0x8917 -SIOCSIFDSTADDR = 0x8918 -SIOCGIFBRDADDR = 0x8919 -SIOCSIFBRDADDR = 0x891a -SIOCGIFNETMASK = 0x891b -SIOCSIFNETMASK = 0x891c -SIOCGIFMETRIC = 0x891d -SIOCSIFMETRIC = 0x891e -SIOCGIFMEM = 0x891f -SIOCSIFMEM = 0x8920 -SIOCGIFMTU = 0x8921 -SIOCSIFMTU = 0x8922 -SIOCSIFHWADDR = 0x8924 -SIOCGIFENCAP = 0x8925 -SIOCSIFENCAP = 0x8926 -SIOCGIFHWADDR = 0x8927 -SIOCGIFSLAVE = 0x8929 -SIOCSIFSLAVE = 0x8930 -SIOCADDMULTI = 0x8931 -SIOCDELMULTI = 0x8932 -OLD_SIOCDARP = 0x8950 -OLD_SIOCGARP = 0x8951 -OLD_SIOCSARP = 0x8952 -SIOCDARP = 0x8953 -SIOCGARP = 0x8954 -SIOCSARP = 0x8955 -SIOCDRARP = 0x8960 -SIOCGRARP = 0x8961 -SIOCSRARP = 0x8962 -SIOCGIFMAP = 0x8970 -SIOCSIFMAP = 0x8971 -SIOCDEVPRIVATE = 0x89F0 -SIOCPROTOPRIVATE = 0x89E0 - -# Included from linux/uio.h -MAX_IOVEC = 8 -SOCK_STREAM = 1 -SOCK_DGRAM = 2 -SOCK_RAW = 3 -SOCK_RDM = 4 -SOCK_SEQPACKET = 5 -SOCK_PACKET = 10 -AF_UNSPEC = 0 -AF_UNIX = 1 -AF_INET = 2 -AF_AX25 = 3 -AF_IPX = 4 -AF_APPLETALK = 5 -AF_NETROM = 6 -AF_BRIDGE = 7 -AF_AAL5 = 8 -AF_X25 = 9 -AF_INET6 = 10 -AF_MAX = 12 -PF_UNSPEC = AF_UNSPEC -PF_UNIX = AF_UNIX -PF_INET = AF_INET -PF_AX25 = AF_AX25 -PF_IPX = AF_IPX -PF_APPLETALK = AF_APPLETALK -PF_NETROM = AF_NETROM -PF_BRIDGE = AF_BRIDGE -PF_AAL5 = AF_AAL5 -PF_X25 = AF_X25 -PF_INET6 = AF_INET6 -PF_MAX = AF_MAX -SOMAXCONN = 128 -MSG_OOB = 1 -MSG_PEEK = 2 -MSG_DONTROUTE = 4 -SOL_IP = 0 -SOL_IPX = 256 -SOL_AX25 = 257 -SOL_ATALK = 258 -SOL_NETROM = 259 -SOL_TCP = 6 -SOL_UDP = 17 -IP_TOS = 1 -IPTOS_LOWDELAY = 0x10 -IPTOS_THROUGHPUT = 0x08 -IPTOS_RELIABILITY = 0x04 -IP_TTL = 2 -IP_HDRINCL = 3 -IP_OPTIONS = 4 -IP_MULTICAST_IF = 32 -IP_MULTICAST_TTL = 33 -IP_MULTICAST_LOOP = 34 -IP_ADD_MEMBERSHIP = 35 -IP_DROP_MEMBERSHIP = 36 -IP_DEFAULT_MULTICAST_TTL = 1 -IP_DEFAULT_MULTICAST_LOOP = 1 -IP_MAX_MEMBERSHIPS = 20 -IPX_TYPE = 1 -TCP_NODELAY = 1 -TCP_MAXSEG = 2 -SOPRI_INTERACTIVE = 0 -SOPRI_NORMAL = 1 -SOPRI_BACKGROUND = 2 - -# Included from sys/types.h - -# Included from linux/types.h -__FD_SETSIZE = 256 - -# Included from asm/types.h -def __FD_ZERO(fdsetp): return \ - - -# Included from sys/bitypes.h - -# Included from pthread/mit/posix.h - -# Included from pthread/mit/types.h - -# Included from pthread/mit/xtypes.h - -# Included from pthread/mit/sys/types.h diff --git a/Lib/linux1/TERMIOS.py b/Lib/linux1/TERMIOS.py deleted file mode 100755 index 4b17df64a1..0000000000 --- a/Lib/linux1/TERMIOS.py +++ /dev/null @@ -1,270 +0,0 @@ -# Generated by h2py from /usr/include/termios.h - -# Included from features.h -_FEATURES_H = 1 -_GNU_SOURCE = 1 -__USE_ANSI = 1 -__FAVOR_BSD = 1 -_BSD_SOURCE = 1 -_SVID_SOURCE = 1 -_POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 2 -__USE_POSIX = 1 -__USE_POSIX2 = 1 -__USE_MISC = 1 -__USE_BSD = 1 -__USE_SVID = 1 -__USE_GNU = 1 -__GNU_LIBRARY__ = 1 - -# Included from sys/cdefs.h -_SYS_CDEFS_H = 1 -def __P(args): return args - -def __P(args): return args - -def __P(args): return () - -def __STRING(x): return #x - -def __STRING(x): return "x" - - -# Included from sys/types.h - -# Included from linux/types.h -__FD_SETSIZE = 256 - -# Included from asm/types.h -def __FD_ZERO(fdsetp): return \ - - -# Included from sys/bitypes.h - -# Included from linux/termios.h - -# Included from asm/termios.h -TCGETS = 0x5401 -TCSETS = 0x5402 -TCSETSW = 0x5403 -TCSETSF = 0x5404 -TCGETA = 0x5405 -TCSETA = 0x5406 -TCSETAW = 0x5407 -TCSETAF = 0x5408 -TCSBRK = 0x5409 -TCXONC = 0x540A -TCFLSH = 0x540B -TIOCEXCL = 0x540C -TIOCNXCL = 0x540D -TIOCSCTTY = 0x540E -TIOCGPGRP = 0x540F -TIOCSPGRP = 0x5410 -TIOCOUTQ = 0x5411 -TIOCSTI = 0x5412 -TIOCGWINSZ = 0x5413 -TIOCSWINSZ = 0x5414 -TIOCMGET = 0x5415 -TIOCMBIS = 0x5416 -TIOCMBIC = 0x5417 -TIOCMSET = 0x5418 -TIOCGSOFTCAR = 0x5419 -TIOCSSOFTCAR = 0x541A -FIONREAD = 0x541B -TIOCINQ = FIONREAD -TIOCLINUX = 0x541C -TIOCCONS = 0x541D -TIOCGSERIAL = 0x541E -TIOCSSERIAL = 0x541F -TIOCPKT = 0x5420 -FIONBIO = 0x5421 -TIOCNOTTY = 0x5422 -TIOCSETD = 0x5423 -TIOCGETD = 0x5424 -TCSBRKP = 0x5425 -TIOCTTYGSTRUCT = 0x5426 -FIONCLEX = 0x5450 -FIOCLEX = 0x5451 -FIOASYNC = 0x5452 -TIOCSERCONFIG = 0x5453 -TIOCSERGWILD = 0x5454 -TIOCSERSWILD = 0x5455 -TIOCGLCKTRMIOS = 0x5456 -TIOCSLCKTRMIOS = 0x5457 -TIOCSERGSTRUCT = 0x5458 -TIOCSERGETLSR = 0x5459 -TIOCSERGETMULTI = 0x545A -TIOCSERSETMULTI = 0x545B -TIOCPKT_DATA = 0 -TIOCPKT_FLUSHREAD = 1 -TIOCPKT_FLUSHWRITE = 2 -TIOCPKT_STOP = 4 -TIOCPKT_START = 8 -TIOCPKT_NOSTOP = 16 -TIOCPKT_DOSTOP = 32 -NCC = 8 -NCCS = 19 -VINTR = 0 -VQUIT = 1 -VERASE = 2 -VKILL = 3 -VEOF = 4 -VTIME = 5 -VMIN = 6 -VSWTC = 7 -VSTART = 8 -VSTOP = 9 -VSUSP = 10 -VEOL = 11 -VREPRINT = 12 -VDISCARD = 13 -VWERASE = 14 -VLNEXT = 15 -VEOL2 = 16 -INIT_C_CC = "\003\034\177\025\004\0\1\0\021\023\032\0\022\017\027\026\0" -IGNBRK = 0000001 -BRKINT = 0000002 -IGNPAR = 0000004 -PARMRK = 0000010 -INPCK = 0000020 -ISTRIP = 0000040 -INLCR = 0000100 -IGNCR = 0000200 -ICRNL = 0000400 -IUCLC = 0001000 -IXON = 0002000 -IXANY = 0004000 -IXOFF = 0010000 -IMAXBEL = 0020000 -OPOST = 0000001 -OLCUC = 0000002 -ONLCR = 0000004 -OCRNL = 0000010 -ONOCR = 0000020 -ONLRET = 0000040 -OFILL = 0000100 -OFDEL = 0000200 -NLDLY = 0000400 -NL0 = 0000000 -NL1 = 0000400 -CRDLY = 0003000 -CR0 = 0000000 -CR1 = 0001000 -CR2 = 0002000 -CR3 = 0003000 -TABDLY = 0014000 -TAB0 = 0000000 -TAB1 = 0004000 -TAB2 = 0010000 -TAB3 = 0014000 -XTABS = 0014000 -BSDLY = 0020000 -BS0 = 0000000 -BS1 = 0020000 -VTDLY = 0040000 -VT0 = 0000000 -VT1 = 0040000 -FFDLY = 0100000 -FF0 = 0000000 -FF1 = 0100000 -CBAUD = 0010017 -B0 = 0000000 -B50 = 0000001 -B75 = 0000002 -B110 = 0000003 -B134 = 0000004 -B150 = 0000005 -B200 = 0000006 -B300 = 0000007 -B600 = 0000010 -B1200 = 0000011 -B1800 = 0000012 -B2400 = 0000013 -B4800 = 0000014 -B9600 = 0000015 -B19200 = 0000016 -B38400 = 0000017 -EXTA = B19200 -EXTB = B38400 -CSIZE = 0000060 -CS5 = 0000000 -CS6 = 0000020 -CS7 = 0000040 -CS8 = 0000060 -CSTOPB = 0000100 -CREAD = 0000200 -PARENB = 0000400 -PARODD = 0001000 -HUPCL = 0002000 -CLOCAL = 0004000 -CBAUDEX = 0010000 -B57600 = 0010001 -B115200 = 0010002 -B230400 = 0010003 -CIBAUD = 002003600000 -CRTSCTS = 020000000000 -ISIG = 0000001 -ICANON = 0000002 -XCASE = 0000004 -ECHO = 0000010 -ECHOE = 0000020 -ECHOK = 0000040 -ECHONL = 0000100 -NOFLSH = 0000200 -TOSTOP = 0000400 -ECHOCTL = 0001000 -ECHOPRT = 0002000 -ECHOKE = 0004000 -FLUSHO = 0010000 -PENDIN = 0040000 -IEXTEN = 0100000 -TIOCM_LE = 0x001 -TIOCM_DTR = 0x002 -TIOCM_RTS = 0x004 -TIOCM_ST = 0x008 -TIOCM_SR = 0x010 -TIOCM_CTS = 0x020 -TIOCM_CAR = 0x040 -TIOCM_RNG = 0x080 -TIOCM_DSR = 0x100 -TIOCM_CD = TIOCM_CAR -TIOCM_RI = TIOCM_RNG -TIOCSER_TEMT = 0x01 -TCOOFF = 0 -TCOON = 1 -TCIOFF = 2 -TCION = 3 -TCIFLUSH = 0 -TCOFLUSH = 1 -TCIOFLUSH = 2 -TCSANOW = 0 -TCSADRAIN = 1 -TCSAFLUSH = 2 -N_TTY = 0 -N_SLIP = 1 -N_MOUSE = 2 -N_PPP = 3 -def CTRL(ch): return ((ch)&0x1F) - -IBSHIFT = 16 -CNUL = 0 -CDEL = 0177 -CESC = ord('\\') -CINTR = 0177 -CQUIT = 034 -CERASE = ord('#') -CKILL = ord('@') -CEOT = 04 -CEOL = 0 -CEOL2 = 0 -CEOF = 4 -CSTART = 021 -CSTOP = 023 -CSWTCH = 032 -NSWTCH = 0 -CSUSP = CTRL(ord('Z')) -CDSUSP = CTRL(ord('Y')) -CRPRNT = CTRL(ord('R')) -CFLUSH = CTRL(ord('O')) -CWERASE = CTRL(ord('W')) -CLNEXT = CTRL(ord('V')) diff --git a/Lib/linux1/regen b/Lib/linux1/regen deleted file mode 100755 index d8dbc04c17..0000000000 --- a/Lib/linux1/regen +++ /dev/null @@ -1,11 +0,0 @@ -#! /bin/sh -case `uname` in -Linux*) ;; -*) echo Probably not on a Linux system 1>&2 - exit 1;; -esac -set -v -h2py /usr/include/sys/fcntl.h -h2py /usr/include/sys/socket.h -h2py -i '(u_long)' /usr/include/netinet/in.h -h2py /usr/include/termios.h diff --git a/Lib/lockfile.py b/Lib/lockfile.py deleted file mode 100644 index 3a251d720b..0000000000 --- a/Lib/lockfile.py +++ /dev/null @@ -1,15 +0,0 @@ -import struct, fcntl, FCNTL - -def writelock(f): - _lock(f, FCNTL.F_WRLCK) - -def readlock(f): - _lock(f, FCNTL.F_RDLCK) - -def unlock(f): - _lock(f, FCNTL.F_UNLCK) - -def _lock(f, op): - dummy = fcntl.fcntl(f.fileno(), FCNTL.F_SETLKW, - struct.pack('2h8l', op, - 0, 0, 0, 0, 0, 0, 0, 0, 0)) diff --git a/Lib/macpath.py b/Lib/macpath.py deleted file mode 100644 index 71748c9315..0000000000 --- a/Lib/macpath.py +++ /dev/null @@ -1,169 +0,0 @@ -# module 'macpath' -- pathname (or -related) operations for the Macintosh - -import string -import mac -from stat import * - - -# Normalize the case of a pathname. Dummy in Posix, but string.lower here. - -normcase = string.lower - - -# Return true if a path is absolute. -# On the Mac, relative paths begin with a colon, -# but as a special case, paths with no colons at all are also relative. -# Anything else is absolute (the string up to the first colon is the -# volume name). - -def isabs(s): - return ':' in s and s[0] <> ':' - - -# Join two pathnames. -# The result is equivalent to what the second pathname would refer to -# if the first pathname were the current directory. - -def join(s, t): - if (not s) or isabs(t): return t - if t[:1] == ':': t = t[1:] - if ':' not in s: - s = ':' + s - if s[-1:] <> ':': - s = s + ':' - return s + t - - -# Split a pathname in two parts: the directory leading up to the final bit, -# and the basename (the filename, without colons, in that directory). -# The result (s, t) is such that join(s, t) yields the original argument. - -def split(s): - if ':' not in s: return '', s - colon = 0 - for i in range(len(s)): - if s[i] == ':': colon = i+1 - return s[:colon-1], s[colon:] - - -# Split a pathname into a drive specification and the rest of the -# path. Useful on DOS/Windows/NT; on the Mac, the drive is always -# empty (don't use the volume name -- it doesn't have the same -# syntactic and semantic oddities as DOS drive letters, such as there -# being a separate current directory per drive). - -def splitdrive(p): - return '', p - - -# Short interfaces to split() - -def dirname(s): return split(s)[0] -def basename(s): return split(s)[1] - - -# Return true if the pathname refers to an existing directory. - -def isdir(s): - try: - st = mac.stat(s) - except mac.error: - return 0 - return S_ISDIR(st[ST_MODE]) - - -# Return true if the pathname refers to a symbolic link. -# (Always false on the Mac, until we understand Aliases.) - -def islink(s): - return 0 - - -# Return true if the pathname refers to an existing regular file. - -def isfile(s): - try: - st = mac.stat(s) - except mac.error: - return 0 - return S_ISREG(st[ST_MODE]) - - -# Return true if the pathname refers to an existing file or directory. - -def exists(s): - try: - st = mac.stat(s) - except mac.error: - return 0 - return 1 - -# -# dummy expandvars to retain interface-compatability with other -# operating systems. -def expandvars(path): - return path - -# -# dummy expanduser to retain interface-compatability with other -# operating systems. -def expanduser(path): - return path - -# Normalize a pathname: get rid of '::' sequences by backing up, -# e.g., 'foo:bar::bletch' becomes 'foo:bletch'. -# Raise the exception norm_error below if backing up is impossible, -# e.g., for '::foo'. -# XXX The Unix version doesn't raise an exception but simply -# returns an unnormalized path. Should do so here too. - -norm_error = 'macpath.norm_error: path cannot be normalized' - -def normpath(s): - import string - if ':' not in s: - return ':' + s - f = string.splitfields(s, ':') - pre = [] - post = [] - if not f[0]: - pre = f[:1] - f = f[1:] - if not f[len(f)-1]: - post = f[-1:] - f = f[:-1] - res = [] - for seg in f: - if seg: - res.append(seg) - else: - if not res: raise norm_error, 'path starts with ::' - del res[len(res)-1] - if not (pre or res): - raise norm_error, 'path starts with volume::' - if pre: res = pre + res - if post: res = res + post - s = res[0] - for seg in res[1:]: - s = s + ':' + seg - return s - - -# Directory tree walk. -# For each directory under top (including top itself), -# func(arg, dirname, filenames) is called, where -# dirname is the name of the directory and filenames is the list -# of files (and subdirectories etc.) in the directory. -# The func may modify the filenames list, to implement a filter, -# or to impose a different order of visiting. - -def walk(top, func, arg): - try: - names = mac.listdir(top) - except mac.error: - return - func(arg, top, names) - for name in names: - name = join(top, name) - if isdir(name): - walk(name, func, arg) diff --git a/Lib/macstat.py b/Lib/macstat.py deleted file mode 100755 index 4b53953634..0000000000 --- a/Lib/macstat.py +++ /dev/null @@ -1,83 +0,0 @@ -# Module 'stat' -# -# Defines constants and functions for interpreting stat/lstat struct -# as returned by os.stat() and os.lstat() (if it exists). -# -# Suggested usage: from stat import * -# -# XXX Strictly spoken, this module may have to be adapted for each POSIX -# implementation; in practice, however, the numeric constants used by -# stat() are almost universal (even for stat() emulations on non-UNIX -# systems like MS-DOS). - -# Indices for stat struct members in tuple returned by os.stat() - -ST_MODE = 0 -ST_INO = 1 -ST_DEV = 2 -ST_NLINK = 3 -ST_UID = 4 -ST_GID = 5 -ST_SIZE = 6 -ST_ATIME = 7 -ST_MTIME = 8 -ST_CTIME = 9 - -# Extract bits from the mode - -def S_IMODE(mode): - return 0 - -def S_IFMT(mode): - return mode & 0xFFFF - -# Constants used as S_IFMT() for various file types -# (not all are implemented on all systems) - -S_IFDIR = 0x0000 -S_IFREG = 0x0003 - -# Functions to test for each file type - -def S_ISDIR(mode): - return S_IFMT(mode) == S_IFDIR - -def S_ISCHR(mode): - return 0 - -def S_ISBLK(mode): - return 0 - -def S_ISREG(mode): - return S_IFMT(mode) == S_IFREG - -def S_ISFIFO(mode): - return 0 - -def S_ISLNK(mode): - return 0 - -def S_ISSOCK(mode): - return 0 - -# Names for permission bits - -S_ISUID = 04000 -S_ISGID = 02000 -S_ENFMT = S_ISGID -S_ISVTX = 01000 -S_IREAD = 00400 -S_IWRITE = 00200 -S_IEXEC = 00100 -S_IRWXU = 00700 -S_IRUSR = 00400 -S_IWUSR = 00200 -S_IXUSR = 00100 -S_IRWXG = 00070 -S_IRGRP = 00040 -S_IWGRP = 00020 -S_IXGRP = 00010 -S_IRWXO = 00007 -S_IROTH = 00004 -S_IWOTH = 00002 -S_IXOTH = 00001 diff --git a/Lib/macurl2path.py b/Lib/macurl2path.py deleted file mode 100644 index 65afe69c13..0000000000 --- a/Lib/macurl2path.py +++ /dev/null @@ -1,76 +0,0 @@ -"""Mac specific module for conversion between pathnames and URLs.""" - -import string -import urllib -import os - -def url2pathname(pathname): - "Convert /-delimited pathname to mac pathname" - # - # XXXX The .. handling should be fixed... - # - tp = urllib.splittype(pathname)[0] - if tp and tp <> 'file': - raise RuntimeError, 'Cannot convert non-local URL to pathname' - components = string.split(pathname, '/') - # Remove . and embedded .. - i = 0 - while i < len(components): - if components[i] == '.': - del components[i] - elif components[i] == '..' and i > 0 and \ - components[i-1] not in ('', '..'): - del components[i-1:i+1] - i = i-1 - elif components[i] == '' and i > 0 and components[i-1] <> '': - del components[i] - else: - i = i+1 - if not components[0]: - # Absolute unix path, don't start with colon - return string.join(components[1:], ':') - else: - # relative unix path, start with colon. First replace - # leading .. by empty strings (giving ::file) - i = 0 - while i < len(components) and components[i] == '..': - components[i] = '' - i = i + 1 - return ':' + string.join(components, ':') - -def pathname2url(pathname): - "convert mac pathname to /-delimited pathname" - if '/' in pathname: - raise RuntimeError, "Cannot convert pathname containing slashes" - components = string.split(pathname, ':') - # Replace empty string ('::') by .. (will result in '/../' later) - for i in range(1, len(components)): - if components[i] == '': - components[i] = '..' - # Truncate names longer than 31 bytes - components = map(lambda x: x[:31], components) - - if os.path.isabs(pathname): - return '/' + string.join(components, '/') - else: - return string.join(components, '/') - -def test(): - for url in ["index.html", - "bar/index.html", - "/foo/bar/index.html", - "/foo/bar/", - "/"]: - print `url`, '->', `url2pathname(url)` - for path in ["drive:", - "drive:dir:", - "drive:dir:file", - "drive:file", - "file", - ":file", - ":dir:", - ":dir:file"]: - print `path`, '->', `pathname2url(path)` - -if __name__ == '__main__': - test() diff --git a/Lib/mailbox.py b/Lib/mailbox.py deleted file mode 100755 index e60b73b966..0000000000 --- a/Lib/mailbox.py +++ /dev/null @@ -1,168 +0,0 @@ -# -# A class to hand a unix-style or mmdf-style mailboxes -# -# Jack Jansen, CWI, March 1994. -# -import rfc822 -import os -import regex - -class _Mailbox: - def __init__(self, fp): - self.fp = fp - self.seekp = 0 - - def seek(self, pos, whence=0): - if whence==1: # Relative to current position - self.pos = self.pos + pos - if whence==2: # Relative to file's end - self.pos = self.stop + pos - else: # Default - absolute position - self.pos = self.start + pos - - def next(self): - while 1: - self.fp.seek(self.seekp) - try: - self._search_start() - except EOFError: - self.seekp = self.fp.tell() - return None - start = self.fp.tell() - self._search_end() - self.seekp = stop = self.fp.tell() - if start <> stop: - break - return rfc822.Message(_Subfile(self.fp, start, stop)) - -class _Subfile: - def __init__(self, fp, start, stop): - self.fp = fp - self.start = start - self.stop = stop - self.pos = self.start - - def read(self, length = None): - if self.pos >= self.stop: - return '' - if length is None: - length = self.stop - self.pos - self.fp.seek(self.pos) - self.pos = self.pos + length - return self.fp.read(length) - - def readline(self, length = None): - if self.pos >= self.stop: - return '' - if length is None: - length = self.stop - self.pos - self.fp.seek(self.pos) - data = self.fp.readline(length) - if len(data) < length: - length = len(data) - self.pos = self.pos + length - return data - - def tell(self): - return self.pos - self.start - - def seek(self, pos, whence=0): - if whence == 0: - self.pos = self.start + pos - elif whence == 1: - self.pos = self.pos + pos - elif whence == 2: - self.pos = self.stop + pos - - def close(self): - pass - -class UnixMailbox(_Mailbox): - def _search_start(self): - while 1: - line = self.fp.readline() - if not line: - raise EOFError - if line[:5] == 'From ': - return - - def _search_end(self): - while 1: - pos = self.fp.tell() - line = self.fp.readline() - if not line: - return - if line[:5] == 'From ': - self.fp.seek(pos) - return - -class MmdfMailbox(_Mailbox): - def _search_start(self): - while 1: - line = self.fp.readline() - if not line: - raise EOFError - if line[:5] == '\001\001\001\001\n': - return - - def _search_end(self): - while 1: - pos = self.fp.tell() - line = self.fp.readline() - if not line: - return - if line == '\001\001\001\001\n': - self.fp.seek(pos) - return - -class MHMailbox: - def __init__(self, dirname): - pat = regex.compile('^[0-9][0-9]*$') - self.dirname = dirname - files = os.listdir(self.dirname) - self.boxes = [] - for f in files: - if pat.match(f) == len(f): - self.boxes.append(f) - - def next(self): - if not self.boxes: - return None - fn = self.boxes[0] - del self.boxes[0] - fp = open(os.path.join(self.dirname, fn)) - return rfc822.Message(fp) - - -if __name__ == '__main__': - import posix - import time - import sys - import string -## mbox = '/usr/mail/'+posix.environ['USER'] -## fp = open(mbox, 'r') -## mb = UnixMailbox(fp) - - mbox = posix.environ['HOME']+'/Mail/inbox' - mb = MHMailbox(mbox) - - msgs = [] - while 1: - msg = mb.next() - if not msg: - break - msgs.append(msg) - if len(sys.argv) > 1: - num = string.atoi(sys.argv[1]) - print 'Message %d body:'%num - msg = msgs[num-1] - msg.rewindbody() - sys.stdout.write(msg.fp.read()) - sys.exit(0) - print 'Mailbox',mbox,'has',len(msgs),'messages:' - for msg in msgs: - f = msg.getheader('from') - s = msg.getheader('subject') - d = (msg.getheader('date')) - print '%20.20s %18.18s %-30.30s'%(f, d[5:], s) - diff --git a/Lib/mailcap.py b/Lib/mailcap.py deleted file mode 100644 index 9da57d704e..0000000000 --- a/Lib/mailcap.py +++ /dev/null @@ -1,223 +0,0 @@ -# Mailcap file handling. See RFC 1524. - -import os -import string -import tempfile - - -# Part 1: top-level interface. - -def getcaps(): - caps = {} - for mailcap in listmailcapfiles(): - try: - fp = open(mailcap, 'r') - except: - continue - morecaps = readmailcapfile(fp) - fp.close() - for key in morecaps.keys(): - if not caps.has_key(key): - caps[key] = morecaps[key] - else: - caps[key] = caps[key] + morecaps[key] - return caps - -def listmailcapfiles(): - # XXX Actually, this is Unix-specific - if os.environ.has_key('MAILCAPS'): - str = os.environ['MAILCAPS'] - mailcaps = string.splitfields(str, ':') - else: - if os.environ.has_key('HOME'): - home = os.environ['HOME'] - else: - # Don't bother with getpwuid() - home = '.' # Last resort - mailcaps = [home + '/.mailcap', '/etc/mailcap', - '/usr/etc/mailcap', '/usr/local/etc/mailcap'] - return mailcaps - - -# Part 2: the parser. - -def readmailcapfile(fp): - caps = {} - while 1: - line = fp.readline() - if not line: break - # Ignore comments and blank lines - if line[0] == '#' or string.strip(line) == '': - continue - nextline = line - # Join continuation lines - while nextline[-2:] == '\\\n': - nextline = fp.readline() - if not nextline: nextline = '\n' - line = line[:-2] + nextline - # Parse the line - key, fields = parseline(line) - if not (key and fields): - cotinue - # Normalize the key - types = string.splitfields(key, '/') - for j in range(len(types)): - types[j] = string.strip(types[j]) - key = string.lower(string.joinfields(types, '/')) - # Update the database - if caps.has_key(key): - caps[key].append(fields) - else: - caps[key] = [fields] - return caps - -def parseline(line): - fields = [] - i, n = 0, len(line) - while i < n: - field, i = parsefield(line, i, n) - fields.append(field) - i = i+1 # Skip semicolon - if len(fields) < 2: - return None, None - key, view, rest = fields[0], fields[1], fields[2:] - fields = {'view': view} - for field in rest: - i = string.find(field, '=') - if i < 0: - fkey = field - fvalue = "" - else: - fkey = string.strip(field[:i]) - fvalue = string.strip(field[i+1:]) - if fields.has_key(fkey): - # Ignore it - pass - else: - fields[fkey] = fvalue - return key, fields - -def parsefield(line, i, n): - start = i - while i < n: - c = line[i] - if c == ';': - break - elif c == '\\': - i = i+2 - else: - i = i+1 - return string.strip(line[start:i]), i - - -# Part 3: using the database. - -def findmatch(caps, type, key='view', filename="/dev/null", plist=[]): - entries = lookup(caps, type, key) - for e in entries: - if e.has_key('test'): - test = subst(e['test'], filename, plist) - if test and os.system(test) != 0: - continue - command = subst(e[key], type, filename, plist) - return command, e - return None, None - -def lookup(caps, type, key=None): - entries = [] - if caps.has_key(type): - entries = entries + caps[type] - types = string.splitfields(type, '/') - type = types[0] + '/*' - if caps.has_key(type): - entries = entries + caps[type] - if key is not None: - entries = filter(lambda e, key=key: e.has_key(key), entries) - return entries - -def subst(field, type, filename, plist=[]): - # XXX Actually, this is Unix-specific - res = '' - i, n = 0, len(field) - while i < n: - c = field[i]; i = i+1 - if c <> '%': - if c == '\\': - c = field[i:i+1]; i = i+1 - res = res + c - else: - c = field[i]; i = i+1 - if c == '%': - res = res + c - elif c == 's': - res = res + filename - elif c == 't': - res = res + type - elif c == '{': - start = i - while i < n and field[i] <> '}': - i = i+1 - name = field[start:i] - i = i+1 - res = res + findparam(name, plist) - # XXX To do: - # %n == number of parts if type is multipart/* - # %F == list of alternating type and filename for parts - else: - res = res + '%' + c - return res - -def findparam(name, plist): - name = string.lower(name) + '=' - n = len(name) - for p in plist: - if string.lower(p[:n]) == name: - return p[n:] - return '' - - -# Part 4: test program. - -def test(): - import sys - caps = getcaps() - if not sys.argv[1:]: - show(caps) - return - for i in range(1, len(sys.argv), 2): - args = sys.argv[i:i+2] - if len(args) < 2: - print "usage: mailcap [type file] ..." - return - type = args[0] - file = args[1] - command, e = findmatch(caps, type, 'view', file) - if not command: - print "No viewer found for", type - else: - print "Executing:", command - sts = os.system(command) - if sts: - print "Exit status:", sts - -def show(caps): - print "Mailcap files:" - for fn in listmailcapfiles(): print "\t" + fn - print - if not caps: caps = getcaps() - print "Mailcap entries:" - print - ckeys = caps.keys() - ckeys.sort() - for type in ckeys: - print type - entries = caps[type] - for e in entries: - keys = e.keys() - keys.sort() - for k in keys: - print " %-15s" % k, e[k] - print - -if __name__ == '__main__': - test() diff --git a/Lib/mhlib.py b/Lib/mhlib.py deleted file mode 100644 index 79eee26ddb..0000000000 --- a/Lib/mhlib.py +++ /dev/null @@ -1,867 +0,0 @@ -# MH interface -- purely object-oriented (well, almost) -# -# Executive summary: -# -# import mhlib -# -# mh = mhlib.MH() # use default mailbox directory and profile -# mh = mhlib.MH(mailbox) # override mailbox location (default from profile) -# mh = mhlib.MH(mailbox, profile) # override mailbox and profile -# -# mh.error(format, ...) # print error message -- can be overridden -# s = mh.getprofile(key) # profile entry (None if not set) -# path = mh.getpath() # mailbox pathname -# name = mh.getcontext() # name of current folder -# mh.setcontext(name) # set name of current folder -# -# list = mh.listfolders() # names of top-level folders -# list = mh.listallfolders() # names of all folders, including subfolders -# list = mh.listsubfolders(name) # direct subfolders of given folder -# list = mh.listallsubfolders(name) # all subfolders of given folder -# -# mh.makefolder(name) # create new folder -# mh.deletefolder(name) # delete folder -- must have no subfolders -# -# f = mh.openfolder(name) # new open folder object -# -# f.error(format, ...) # same as mh.error(format, ...) -# path = f.getfullname() # folder's full pathname -# path = f.getsequencesfilename() # full pathname of folder's sequences file -# path = f.getmessagefilename(n) # full pathname of message n in folder -# -# list = f.listmessages() # list of messages in folder (as numbers) -# n = f.getcurrent() # get current message -# f.setcurrent(n) # set current message -# list = f.parsesequence(seq) # parse msgs syntax into list of messages -# n = f.getlast() # get last message (0 if no messagse) -# f.setlast(n) # set last message (internal use only) -# -# dict = f.getsequences() # dictionary of sequences in folder {name: list} -# f.putsequences(dict) # write sequences back to folder -# -# f.removemessages(list) # remove messages in list from folder -# f.refilemessages(list, tofolder) # move messages in list to other folder -# f.movemessage(n, tofolder, ton) # move one message to a given destination -# f.copymessage(n, tofolder, ton) # copy one message to a given destination -# -# m = f.openmessage(n) # new open message object (costs a file descriptor) -# m is a derived class of mimetools.Message(rfc822.Message), with: -# s = m.getheadertext() # text of message's headers -# s = m.getheadertext(pred) # text of message's headers, filtered by pred -# s = m.getbodytext() # text of message's body, decoded -# s = m.getbodytext(0) # text of message's body, not decoded -# -# XXX To do, functionality: -# - annotate messages -# - create, send messages -# -# XXX To do, organization: -# - move IntSet to separate file -# - move most Message functionality to module mimetools - - -# Customizable defaults - -MH_PROFILE = '~/.mh_profile' -PATH = '~/Mail' -MH_SEQUENCES = '.mh_sequences' -FOLDER_PROTECT = 0700 - - -# Imported modules - -import os -import sys -from stat import ST_NLINK -import regex -import string -import mimetools -import multifile -import shutil - - -# Exported constants - -Error = 'mhlib.Error' - - -# Class representing a particular collection of folders. -# Optional constructor arguments are the pathname for the directory -# containing the collection, and the MH profile to use. -# If either is omitted or empty a default is used; the default -# directory is taken from the MH profile if it is specified there. - -class MH: - - # Constructor - def __init__(self, path = None, profile = None): - if not profile: profile = MH_PROFILE - self.profile = os.path.expanduser(profile) - if not path: path = self.getprofile('Path') - if not path: path = PATH - if not os.path.isabs(path) and path[0] != '~': - path = os.path.join('~', path) - path = os.path.expanduser(path) - if not os.path.isdir(path): raise Error, 'MH() path not found' - self.path = path - - # String representation - def __repr__(self): - return 'MH(%s, %s)' % (`self.path`, `self.profile`) - - # Routine to print an error. May be overridden by a derived class - def error(self, msg, *args): - sys.stderr.write('MH error: %s\n' % (msg % args)) - - # Return a profile entry, None if not found - def getprofile(self, key): - return pickline(self.profile, key) - - # Return the path (the name of the collection's directory) - def getpath(self): - return self.path - - # Return the name of the current folder - def getcontext(self): - context = pickline(os.path.join(self.getpath(), 'context'), - 'Current-Folder') - if not context: context = 'inbox' - return context - - # Set the name of the current folder - def setcontext(self, context): - fn = os.path.join(self.getpath(), 'context') - f = open(fn, "w") - f.write("Current-Folder: %s\n" % context) - f.close() - - # Return the names of the top-level folders - def listfolders(self): - folders = [] - path = self.getpath() - for name in os.listdir(path): - if name in (os.curdir, os.pardir): continue - fullname = os.path.join(path, name) - if os.path.isdir(fullname): - folders.append(name) - folders.sort() - return folders - - # Return the names of the subfolders in a given folder - # (prefixed with the given folder name) - def listsubfolders(self, name): - fullname = os.path.join(self.path, name) - # Get the link count so we can avoid listing folders - # that have no subfolders. - st = os.stat(fullname) - nlinks = st[ST_NLINK] - if nlinks <= 2: - return [] - subfolders = [] - subnames = os.listdir(fullname) - for subname in subnames: - if subname in (os.curdir, os.pardir): continue - fullsubname = os.path.join(fullname, subname) - if os.path.isdir(fullsubname): - name_subname = os.path.join(name, subname) - subfolders.append(name_subname) - # Stop looking for subfolders when - # we've seen them all - nlinks = nlinks - 1 - if nlinks <= 2: - break - subfolders.sort() - return subfolders - - # Return the names of all folders, including subfolders, recursively - def listallfolders(self): - return self.listallsubfolders('') - - # Return the names of subfolders in a given folder, recursively - def listallsubfolders(self, name): - fullname = os.path.join(self.path, name) - # Get the link count so we can avoid listing folders - # that have no subfolders. - st = os.stat(fullname) - nlinks = st[ST_NLINK] - if nlinks <= 2: - return [] - subfolders = [] - subnames = os.listdir(fullname) - for subname in subnames: - if subname in (os.curdir, os.pardir): continue - if subname[0] == ',' or isnumeric(subname): continue - fullsubname = os.path.join(fullname, subname) - if os.path.isdir(fullsubname): - name_subname = os.path.join(name, subname) - subfolders.append(name_subname) - if not os.path.islink(fullsubname): - subsubfolders = self.listallsubfolders( - name_subname) - subfolders = subfolders + subsubfolders - # Stop looking for subfolders when - # we've seen them all - nlinks = nlinks - 1 - if nlinks <= 2: - break - subfolders.sort() - return subfolders - - # Return a new Folder object for the named folder - def openfolder(self, name): - return Folder(self, name) - - # Create a new folder. This raises os.error if the folder - # cannot be created - def makefolder(self, name): - protect = pickline(self.profile, 'Folder-Protect') - if protect and isnumeric(protect): - mode = string.atoi(protect, 8) - else: - mode = FOLDER_PROTECT - os.mkdir(os.path.join(self.getpath(), name), mode) - - # Delete a folder. This removes files in the folder but not - # subdirectories. If deleting the folder itself fails it - # raises os.error - def deletefolder(self, name): - fullname = os.path.join(self.getpath(), name) - for subname in os.listdir(fullname): - if subname in (os.curdir, os.pardir): continue - fullsubname = os.path.join(fullname, subname) - try: - os.unlink(fullsubname) - except os.error: - self.error('%s not deleted, continuing...' % - fullsubname) - os.rmdir(fullname) - - -# Class representing a particular folder - -numericprog = regex.compile('[1-9][0-9]*') -def isnumeric(str): - return numericprog.match(str) == len(str) - -class Folder: - - # Constructor - def __init__(self, mh, name): - self.mh = mh - self.name = name - if not os.path.isdir(self.getfullname()): - raise Error, 'no folder %s' % name - - # String representation - def __repr__(self): - return 'Folder(%s, %s)' % (`self.mh`, `self.name`) - - # Error message handler - def error(self, *args): - apply(self.mh.error, args) - - # Return the full pathname of the folder - def getfullname(self): - return os.path.join(self.mh.path, self.name) - - # Return the full pathname of the folder's sequences file - def getsequencesfilename(self): - return os.path.join(self.getfullname(), MH_SEQUENCES) - - # Return the full pathname of a message in the folder - def getmessagefilename(self, n): - return os.path.join(self.getfullname(), str(n)) - - # Return list of direct subfolders - def listsubfolders(self): - return self.mh.listsubfolders(self.name) - - # Return list of all subfolders - def listallsubfolders(self): - return self.mh.listallsubfolders(self.name) - - # Return the list of messages currently present in the folder. - # As a side effect, set self.last to the last message (or 0) - def listmessages(self): - messages = [] - for name in os.listdir(self.getfullname()): - if name[0] != "," and \ - numericprog.match(name) == len(name): - messages.append(string.atoi(name)) - messages.sort() - if messages: - self.last = max(messages) - else: - self.last = 0 - return messages - - # Return the set of sequences for the folder - def getsequences(self): - sequences = {} - fullname = self.getsequencesfilename() - try: - f = open(fullname, 'r') - except IOError: - return sequences - while 1: - line = f.readline() - if not line: break - fields = string.splitfields(line, ':') - if len(fields) <> 2: - self.error('bad sequence in %s: %s' % - (fullname, string.strip(line))) - key = string.strip(fields[0]) - value = IntSet(string.strip(fields[1]), ' ').tolist() - sequences[key] = value - return sequences - - # Write the set of sequences back to the folder - def putsequences(self, sequences): - fullname = self.getsequencesfilename() - f = None - for key in sequences.keys(): - s = IntSet('', ' ') - s.fromlist(sequences[key]) - if not f: f = open(fullname, 'w') - f.write('%s: %s\n' % (key, s.tostring())) - if not f: - try: - os.unlink(fullname) - except os.error: - pass - else: - f.close() - - # Return the current message. Raise KeyError when there is none - def getcurrent(self): - return min(self.getsequences()['cur']) - - # Set the current message - def setcurrent(self, n): - updateline(self.getsequencesfilename(), 'cur', str(n), 0) - - # Parse an MH sequence specification into a message list. - def parsesequence(self, seq): - if seq == "all": - return self.listmessages() - try: - n = string.atoi(seq, 10) - except string.atoi_error: - n = 0 - if n > 0: - return [n] - if regex.match("^last:", seq) >= 0: - try: - n = string.atoi(seq[5:]) - except string.atoi_error: - n = 0 - if n > 0: - return self.listmessages()[-n:] - if regex.match("^first:", seq) >= 0: - try: - n = string.atoi(seq[6:]) - except string.atoi_error: - n = 0 - if n > 0: - return self.listmessages()[:n] - dict = self.getsequences() - if dict.has_key(seq): - return dict[seq] - context = self.mh.getcontext() - # Complex syntax -- use pick - pipe = os.popen("pick +%s %s 2>/dev/null" % (self.name, seq)) - data = pipe.read() - sts = pipe.close() - self.mh.setcontext(context) - if sts: - raise Error, "unparseable sequence %s" % `seq` - items = string.split(data) - return map(string.atoi, items) - - # Open a message -- returns a Message object - def openmessage(self, n): - return Message(self, n) - - # Remove one or more messages -- may raise os.error - def removemessages(self, list): - errors = [] - deleted = [] - for n in list: - path = self.getmessagefilename(n) - commapath = self.getmessagefilename(',' + str(n)) - try: - os.unlink(commapath) - except os.error: - pass - try: - os.rename(path, commapath) - except os.error, msg: - errors.append(msg) - else: - deleted.append(n) - if deleted: - self.removefromallsequences(deleted) - if errors: - if len(errors) == 1: - raise os.error, errors[0] - else: - raise os.error, ('multiple errors:', errors) - - # Refile one or more messages -- may raise os.error. - # 'tofolder' is an open folder object - def refilemessages(self, list, tofolder): - errors = [] - refiled = [] - for n in list: - ton = tofolder.getlast() + 1 - path = self.getmessagefilename(n) - topath = tofolder.getmessagefilename(ton) - try: - os.rename(path, topath) - except os.error: - # Try copying - try: - shutil.copy2(path, topath) - os.unlink(path) - except (IOError, os.error), msg: - errors.append(msg) - try: - os.unlink(topath) - except os.error: - pass - continue - tofolder.setlast(ton) - refiled.append(n) - if refiled: - self.removefromallsequences(refiled) - if errors: - if len(errors) == 1: - raise os.error, errors[0] - else: - raise os.error, ('multiple errors:', errors) - - # Move one message over a specific destination message, - # which may or may not already exist. - def movemessage(self, n, tofolder, ton): - path = self.getmessagefilename(n) - # Open it to check that it exists - f = open(path) - f.close() - del f - topath = tofolder.getmessagefilename(ton) - backuptopath = tofolder.getmessagefilename(',%d' % ton) - try: - os.rename(topath, backuptopath) - except os.error: - pass - try: - os.rename(path, topath) - except os.error: - # Try copying - ok = 0 - try: - tofolder.setlast(None) - shutil.copy2(path, topath) - ok = 1 - finally: - if not ok: - try: - os.unlink(topath) - except os.error: - pass - os.unlink(path) - self.removefromallsequences([n]) - - # Copy one message over a specific destination message, - # which may or may not already exist. - def copymessage(self, n, tofolder, ton): - path = self.getmessagefilename(n) - # Open it to check that it exists - f = open(path) - f.close() - del f - topath = tofolder.getmessagefilename(ton) - backuptopath = tofolder.getmessagefilename(',%d' % ton) - try: - os.rename(topath, backuptopath) - except os.error: - pass - ok = 0 - try: - tofolder.setlast(None) - shutil.copy2(path, topath) - ok = 1 - finally: - if not ok: - try: - os.unlink(topath) - except os.error: - pass - - # Remove one or more messages from all sequeuces (including last) - def removefromallsequences(self, list): - if hasattr(self, 'last') and self.last in list: - del self.last - sequences = self.getsequences() - changed = 0 - for name, seq in sequences.items(): - for n in list: - if n in seq: - seq.remove(n) - changed = 1 - if not seq: - del sequences[name] - if changed: - self.putsequences(sequences) - - # Return the last message number - def getlast(self): - if not hasattr(self, 'last'): - messages = self.listmessages() - return self.last - - # Set the last message number - def setlast(self, last): - if last is None: - if hasattr(self, 'last'): - del self.last - else: - self.last = last - -class Message(mimetools.Message): - - # Constructor - def __init__(self, f, n, fp = None): - self.folder = f - self.number = n - if not fp: - path = f.getmessagefilename(n) - fp = open(path, 'r') - mimetools.Message.__init__(self, fp) - - # String representation - def __repr__(self): - return 'Message(%s, %s)' % (repr(self.folder), self.number) - - # Return the message's header text as a string. If an - # argument is specified, it is used as a filter predicate to - # decide which headers to return (its argument is the header - # name converted to lower case). - def getheadertext(self, pred = None): - if not pred: - return string.joinfields(self.headers, '') - headers = [] - hit = 0 - for line in self.headers: - if line[0] not in string.whitespace: - i = string.find(line, ':') - if i > 0: - hit = pred(string.lower(line[:i])) - if hit: headers.append(line) - return string.joinfields(headers, '') - - # Return the message's body text as string. This undoes a - # Content-Transfer-Encoding, but does not interpret other MIME - # features (e.g. multipart messages). To suppress to - # decoding, pass a 0 as argument - def getbodytext(self, decode = 1): - self.fp.seek(self.startofbody) - encoding = self.getencoding() - if not decode or encoding in ('7bit', '8bit', 'binary'): - return self.fp.read() - from StringIO import StringIO - output = StringIO() - mimetools.decode(self.fp, output, encoding) - return output.getvalue() - - # Only for multipart messages: return the message's body as a - # list of SubMessage objects. Each submessage object behaves - # (almost) as a Message object. - def getbodyparts(self): - if self.getmaintype() != 'multipart': - raise Error, \ - 'Content-Type is not multipart/*' - bdry = self.getparam('boundary') - if not bdry: - raise Error, 'multipart/* without boundary param' - self.fp.seek(self.startofbody) - mf = multifile.MultiFile(self.fp) - mf.push(bdry) - parts = [] - while mf.next(): - n = str(self.number) + '.' + `1 + len(parts)` - part = SubMessage(self.folder, n, mf) - parts.append(part) - mf.pop() - return parts - - # Return body, either a string or a list of messages - def getbody(self): - if self.getmaintype() == 'multipart': - return self.getbodyparts() - else: - return self.getbodytext() - - -class SubMessage(Message): - - # Constructor - def __init__(self, f, n, fp): - Message.__init__(self, f, n, fp) - if self.getmaintype() == 'multipart': - self.body = Message.getbodyparts(self) - else: - self.body = Message.getbodytext(self) - # XXX If this is big, should remember file pointers - - # String representation - def __repr__(self): - f, n, fp = self.folder, self.number, self.fp - return 'SubMessage(%s, %s, %s)' % (f, n, fp) - - def getbodytext(self): - if type(self.body) == type(''): - return self.body - - def getbodyparts(self): - if type(self.body) == type([]): - return self.body - - def getbody(self): - return self.body - - -# Class implementing sets of integers. -# -# This is an efficient representation for sets consisting of several -# continuous ranges, e.g. 1-100,200-400,402-1000 is represented -# internally as a list of three pairs: [(1,100), (200,400), -# (402,1000)]. The internal representation is always kept normalized. -# -# The constructor has up to three arguments: -# - the string used to initialize the set (default ''), -# - the separator between ranges (default ',') -# - the separator between begin and end of a range (default '-') -# The separators may be regular expressions and should be different. -# -# The tostring() function yields a string that can be passed to another -# IntSet constructor; __repr__() is a valid IntSet constructor itself. -# -# XXX The default begin/end separator means that negative numbers are -# not supported very well. -# -# XXX There are currently no operations to remove set elements. - -class IntSet: - - def __init__(self, data = None, sep = ',', rng = '-'): - self.pairs = [] - self.sep = sep - self.rng = rng - if data: self.fromstring(data) - - def reset(self): - self.pairs = [] - - def __cmp__(self, other): - return cmp(self.pairs, other.pairs) - - def __hash__(self): - return hash(self.pairs) - - def __repr__(self): - return 'IntSet(%s, %s, %s)' % (`self.tostring()`, - `self.sep`, `self.rng`) - - def normalize(self): - self.pairs.sort() - i = 1 - while i < len(self.pairs): - alo, ahi = self.pairs[i-1] - blo, bhi = self.pairs[i] - if ahi >= blo-1: - self.pairs[i-1:i+1] = [ - (alo, max(ahi, bhi))] - else: - i = i+1 - - def tostring(self): - s = '' - for lo, hi in self.pairs: - if lo == hi: t = `lo` - else: t = `lo` + self.rng + `hi` - if s: s = s + (self.sep + t) - else: s = t - return s - - def tolist(self): - l = [] - for lo, hi in self.pairs: - m = range(lo, hi+1) - l = l + m - return l - - def fromlist(self, list): - for i in list: - self.append(i) - - def clone(self): - new = IntSet() - new.pairs = self.pairs[:] - return new - - def min(self): - return self.pairs[0][0] - - def max(self): - return self.pairs[-1][-1] - - def contains(self, x): - for lo, hi in self.pairs: - if lo <= x <= hi: return 1 - return 0 - - def append(self, x): - for i in range(len(self.pairs)): - lo, hi = self.pairs[i] - if x < lo: # Need to insert before - if x+1 == lo: - self.pairs[i] = (x, hi) - else: - self.pairs.insert(i, (x, x)) - if i > 0 and x-1 == self.pairs[i-1][1]: - # Merge with previous - self.pairs[i-1:i+1] = [ - (self.pairs[i-1][0], - self.pairs[i][1]) - ] - return - if x <= hi: # Already in set - return - i = len(self.pairs) - 1 - if i >= 0: - lo, hi = self.pairs[i] - if x-1 == hi: - self.pairs[i] = lo, x - return - self.pairs.append((x, x)) - - def addpair(self, xlo, xhi): - if xlo > xhi: return - self.pairs.append((xlo, xhi)) - self.normalize() - - def fromstring(self, data): - import string, regsub - new = [] - for part in regsub.split(data, self.sep): - list = [] - for subp in regsub.split(part, self.rng): - s = string.strip(subp) - list.append(string.atoi(s)) - if len(list) == 1: - new.append((list[0], list[0])) - elif len(list) == 2 and list[0] <= list[1]: - new.append((list[0], list[1])) - else: - raise ValueError, 'bad data passed to IntSet' - self.pairs = self.pairs + new - self.normalize() - - -# Subroutines to read/write entries in .mh_profile and .mh_sequences - -def pickline(file, key, casefold = 1): - try: - f = open(file, 'r') - except IOError: - return None - pat = key + ':' - if casefold: - prog = regex.compile(pat, regex.casefold) - else: - prog = regex.compile(pat) - while 1: - line = f.readline() - if not line: break - if prog.match(line) >= 0: - text = line[len(key)+1:] - while 1: - line = f.readline() - if not line or \ - line[0] not in string.whitespace: - break - text = text + line - return string.strip(text) - return None - -def updateline(file, key, value, casefold = 1): - try: - f = open(file, 'r') - lines = f.readlines() - f.close() - except IOError: - lines = [] - pat = key + ':\(.*\)\n' - if casefold: - prog = regex.compile(pat, regex.casefold) - else: - prog = regex.compile(pat) - if value is None: - newline = None - else: - newline = '%s: %s\n' % (key, value) - for i in range(len(lines)): - line = lines[i] - if prog.match(line) == len(line): - if newline is None: - del lines[i] - else: - lines[i] = newline - break - else: - if newline is not None: - lines.append(newline) - tempfile = file + "~" - f = open(tempfile, 'w') - for line in lines: - f.write(line) - f.close() - os.rename(tempfile, file) - - -# Test program - -def test(): - global mh, f - os.system('rm -rf $HOME/Mail/@test') - mh = MH() - def do(s): print s; print eval(s) - do('mh.listfolders()') - do('mh.listallfolders()') - testfolders = ['@test', '@test/test1', '@test/test2', - '@test/test1/test11', '@test/test1/test12', - '@test/test1/test11/test111'] - for t in testfolders: do('mh.makefolder(%s)' % `t`) - do('mh.listsubfolders(\'@test\')') - do('mh.listallsubfolders(\'@test\')') - f = mh.openfolder('@test') - do('f.listsubfolders()') - do('f.listallsubfolders()') - do('f.getsequences()') - seqs = f.getsequences() - seqs['foo'] = IntSet('1-10 12-20', ' ').tolist() - print seqs - f.putsequences(seqs) - do('f.getsequences()') - testfolders.reverse() - for t in testfolders: do('mh.deletefolder(%s)' % `t`) - do('mh.getcontext()') - context = mh.getcontext() - f = mh.openfolder(context) - do('f.listmessages()') - do('f.getcurrent()') - - -if __name__ == '__main__': - test() diff --git a/Lib/mimetools.py b/Lib/mimetools.py deleted file mode 100644 index da33a7777b..0000000000 --- a/Lib/mimetools.py +++ /dev/null @@ -1,187 +0,0 @@ -# Various tools used by MIME-reading or MIME-writing programs. - - -import os -import rfc822 -import string -import tempfile - - -# A derived class of rfc822.Message that knows about MIME headers and -# contains some hooks for decoding encoded and multipart messages. - -class Message(rfc822.Message): - - def __init__(self, fp, seekable = 1): - rfc822.Message.__init__(self, fp, seekable) - self.encodingheader = \ - self.getheader('content-transfer-encoding') - self.typeheader = \ - self.getheader('content-type') - self.parsetype() - self.parseplist() - - def parsetype(self): - str = self.typeheader - if str == None: - str = 'text/plain' - if ';' in str: - i = string.index(str, ';') - self.plisttext = str[i:] - str = str[:i] - else: - self.plisttext = '' - fields = string.splitfields(str, '/') - for i in range(len(fields)): - fields[i] = string.lower(string.strip(fields[i])) - self.type = string.joinfields(fields, '/') - self.maintype = fields[0] - self.subtype = string.joinfields(fields[1:], '/') - - def parseplist(self): - str = self.plisttext - self.plist = [] - while str[:1] == ';': - str = str[1:] - if ';' in str: - # XXX Should parse quotes! - end = string.index(str, ';') - else: - end = len(str) - f = str[:end] - if '=' in f: - i = string.index(f, '=') - f = string.lower(string.strip(f[:i])) + \ - '=' + string.strip(f[i+1:]) - self.plist.append(string.strip(f)) - str = str[end:] - - def getplist(self): - return self.plist - - def getparam(self, name): - name = string.lower(name) + '=' - n = len(name) - for p in self.plist: - if p[:n] == name: - return rfc822.unquote(p[n:]) - return None - - def getencoding(self): - if self.encodingheader == None: - return '7bit' - return string.lower(self.encodingheader) - - def gettype(self): - return self.type - - def getmaintype(self): - return self.maintype - - def getsubtype(self): - return self.subtype - - - - -# Utility functions -# ----------------- - - -# Return a random string usable as a multipart boundary. -# The method used is so that it is *very* unlikely that the same -# string of characters will every occur again in the Universe, -# so the caller needn't check the data it is packing for the -# occurrence of the boundary. -# -# The boundary contains dots so you have to quote it in the header. - -_prefix = None - -def choose_boundary(): - global _prefix - import time - import rand - if _prefix == None: - import socket - import os - hostid = socket.gethostbyname(socket.gethostname()) - uid = `os.getuid()` - pid = `os.getpid()` - seed = `rand.rand()` - _prefix = hostid + '.' + uid + '.' + pid - timestamp = `int(time.time())` - seed = `rand.rand()` - return _prefix + '.' + timestamp + '.' + seed - - -# Subroutines for decoding some common content-transfer-types - -# XXX This requires that uudecode and mmencode are in $PATH - -def decode(input, output, encoding): - if decodetab.has_key(encoding): - pipethrough(input, decodetab[encoding], output) - else: - raise ValueError, \ - 'unknown Content-Transfer-Encoding: %s' % encoding - -def encode(input, output, encoding): - if encodetab.has_key(encoding): - pipethrough(input, encodetab[encoding], output) - else: - raise ValueError, \ - 'unknown Content-Transfer-Encoding: %s' % encoding - -uudecode_pipe = '''( -TEMP=/tmp/@uu.$$ -sed "s%^begin [0-7][0-7]* .*%begin 600 $TEMP%" | uudecode -cat $TEMP -rm $TEMP -)''' - -decodetab = { - 'uuencode': uudecode_pipe, - 'x-uuencode': uudecode_pipe, - 'quoted-printable': 'mmencode -u -q', - 'base64': 'mmencode -u -b', -} - -encodetab = { - 'x-uuencode': 'uuencode tempfile', - 'uuencode': 'uuencode tempfile', - 'quoted-printable': 'mmencode -q', - 'base64': 'mmencode -b', -} - -def pipeto(input, command): - pipe = os.popen(command, 'w') - copyliteral(input, pipe) - pipe.close() - -def pipethrough(input, command, output): - tempname = tempfile.mktemp() - try: - temp = open(tempname, 'w') - except IOError: - print '*** Cannot create temp file', `tempname` - return - copyliteral(input, temp) - temp.close() - pipe = os.popen(command + ' <' + tempname, 'r') - copybinary(pipe, output) - pipe.close() - os.unlink(tempname) - -def copyliteral(input, output): - while 1: - line = input.readline() - if not line: break - output.write(line) - -def copybinary(input, output): - BUFSIZE = 8192 - while 1: - line = input.read(BUFSIZE) - if not line: break - output.write(line) diff --git a/Lib/mimify.py b/Lib/mimify.py deleted file mode 100755 index 3f41de4cc8..0000000000 --- a/Lib/mimify.py +++ /dev/null @@ -1,415 +0,0 @@ -#!/usr/local/bin/python - -'''Mimification and unmimification of mail messages. - -decode quoted-printable parts of a mail message or encode using -quoted-printable. - -Usage: - mimify(input, output) - unmimify(input, output) -to encode and decode respectively. Input and output may be the name -of a file or an open file object. Only a readline() method is used -on the input file, only a write() method is used on the output file. -When using file names, the input and output file names may be the -same. - -Interactive usage: - mimify.py -e [infile [outfile]] - mimify.py -d [infile [outfile]] -to encode and decode respectively. Infile defaults to standard -input and outfile to standard output. -''' - -# Configure -MAXLEN = 200 # if lines longer than this, encode as quoted-printable -CHARSET = 'ISO-8859-1' # default charset for non-US-ASCII mail -QUOTE = '> ' # string replies are quoted with -# End configure - -import regex, regsub, string - -qp = regex.compile('^content-transfer-encoding:[\000-\377]*quoted-printable', - regex.casefold) -mp = regex.compile('^content-type:[\000-\377]*multipart/[\000-\377]*boundary="?\\([^;"\n]*\\)', - regex.casefold) -chrset = regex.compile('^\\(content-type:.*charset="\\)\\(us-ascii\\|iso-8859-[0-9]+\\)\\("[\000-\377]*\\)', - regex.casefold) -he = regex.compile('^-*$') -mime_code = regex.compile('=\\([0-9a-f][0-9a-f]\\)', regex.casefold) -mime_head = regex.compile('=\\?iso-8859-1\\?q\\?\\([^?]+\\)\\?=', - regex.casefold) -repl = regex.compile('^subject:[ \t]+re: ', regex.casefold) - -class File: - '''A simple fake file object that knows about limited - read-ahead and boundaries. - The only supported method is readline().''' - - def __init__(self, file, boundary): - self.file = file - self.boundary = boundary - self.peek = None - - def readline(self): - if self.peek is not None: - return '' - line = self.file.readline() - if not line: - return line - if self.boundary: - if line == self.boundary + '\n': - self.peek = line - return '' - if line == self.boundary + '--\n': - self.peek = line - return '' - return line - -class HeaderFile: - def __init__(self, file): - self.file = file - self.peek = None - - def readline(self): - if self.peek is not None: - line = self.peek - self.peek = None - else: - line = self.file.readline() - if not line: - return line - if he.match(line) >= 0: - return line - while 1: - self.peek = self.file.readline() - if len(self.peek) == 0 or \ - (self.peek[0] != ' ' and self.peek[0] != '\t'): - return line - line = line + self.peek - self.peek = None - -def mime_decode(line): - '''Decode a single line of quoted-printable text to 8bit.''' - newline = '' - while 1: - i = mime_code.search(line) - if i < 0: - break - newline = newline + line[:i] + \ - chr(string.atoi(mime_code.group(1), 16)) - line = line[i+3:] - return newline + line - -def mime_decode_header(line): - '''Decode a header line to 8bit.''' - newline = '' - while 1: - i = mime_head.search(line) - if i < 0: - break - match = mime_head.group(0, 1) - newline = newline + line[:i] + mime_decode(match[1]) - line = line[i + len(match[0]):] - return newline + line - -def unmimify_part(ifile, ofile): - '''Convert a quoted-printable part of a MIME mail message to 8bit.''' - multipart = None - quoted_printable = 0 - is_repl = 0 - if ifile.boundary and ifile.boundary[:2] == QUOTE: - prefix = QUOTE - else: - prefix = '' - - # read header - hfile = HeaderFile(ifile) - while 1: - line = hfile.readline() - if not line: - return - if prefix and line[:len(prefix)] == prefix: - line = line[len(prefix):] - pref = prefix - else: - pref = '' - line = mime_decode_header(line) - if qp.match(line) >= 0: - quoted_printable = 1 - continue # skip this header - ofile.write(pref + line) - if not prefix and repl.match(line) >= 0: - # we're dealing with a reply message - is_repl = 1 - if mp.match(line) >= 0: - multipart = '--' + mp.group(1) - if he.match(line) >= 0: - break - if is_repl and (quoted_printable or multipart): - is_repl = 0 - - # read body - while 1: - line = ifile.readline() - if not line: - return - line = regsub.gsub(mime_head, '\\1', line) - if prefix and line[:len(prefix)] == prefix: - line = line[len(prefix):] - pref = prefix - else: - pref = '' -## if is_repl and len(line) >= 4 and line[:4] == QUOTE+'--' and line[-3:] != '--\n': -## multipart = line[:-1] - while multipart: - if line == multipart + '--\n': - ofile.write(pref + line) - multipart = None - line = None - break - if line == multipart + '\n': - ofile.write(pref + line) - nifile = File(ifile, multipart) - unmimify_part(nifile, ofile) - line = nifile.peek - continue - # not a boundary between parts - break - if line and quoted_printable: - while line[-2:] == '=\n': - line = line[:-2] - newline = ifile.readline() - if newline[:len(QUOTE)] == QUOTE: - newline = newline[len(QUOTE):] - line = line + newline - line = mime_decode(line) - if line: - ofile.write(pref + line) - -def unmimify(infile, outfile): - '''Convert quoted-printable parts of a MIME mail message to 8bit.''' - if type(infile) == type(''): - ifile = open(infile) - if type(outfile) == type('') and infile == outfile: - import os - d, f = os.path.split(infile) - os.rename(infile, os.path.join(d, ',' + f)) - else: - ifile = infile - if type(outfile) == type(''): - ofile = open(outfile, 'w') - else: - ofile = outfile - nifile = File(ifile, None) - unmimify_part(nifile, ofile) - ofile.flush() - -mime_char = regex.compile('[=\240-\377]') # quote these chars in body -mime_header_char = regex.compile('[=?\240-\377]') # quote these in header - -def mime_encode(line, header): - '''Code a single line as quoted-printable. - If header is set, quote some extra characters.''' - if header: - reg = mime_header_char - else: - reg = mime_char - newline = '' - if len(line) >= 5 and line[:5] == 'From ': - # quote 'From ' at the start of a line for stupid mailers - newline = string.upper('=%02x' % ord('F')) - line = line[1:] - while 1: - i = reg.search(line) - if i < 0: - break - newline = newline + line[:i] + \ - string.upper('=%02x' % ord(line[i])) - line = line[i+1:] - line = newline + line - - newline = '' - while len(line) >= 75: - i = 73 - while line[i] == '=' or line[i-1] == '=': - i = i - 1 - i = i + 1 - newline = newline + line[:i] + '=\n' - line = line[i:] - return newline + line - -mime_header = regex.compile('\\([ \t(]\\|^\\)\\([-a-zA-Z0-9_+]*[\240-\377][-a-zA-Z0-9_+\240-\377]*\\)\\([ \t)]\\|$\\)') - -def mime_encode_header(line): - '''Code a single header line as quoted-printable.''' - newline = '' - while 1: - i = mime_header.search(line) - if i < 0: - break - newline = newline + line[:i] + mime_header.group(1) + \ - '=?' + CHARSET + '?Q?' + \ - mime_encode(mime_header.group(2), 1) + \ - '?=' + mime_header.group(3) - line = line[i+len(mime_header.group(0)):] - return newline + line - -mv = regex.compile('^mime-version:', regex.casefold) -cte = regex.compile('^content-transfer-encoding:', regex.casefold) -iso_char = regex.compile('[\240-\377]') - -def mimify_part(ifile, ofile, is_mime): - '''Convert an 8bit part of a MIME mail message to quoted-printable.''' - has_cte = is_qp = 0 - multipart = None - must_quote_body = must_quote_header = has_iso_chars = 0 - - header = [] - header_end = '' - message = [] - message_end = '' - # read header - hfile = HeaderFile(ifile) - while 1: - line = hfile.readline() - if not line: - break - if not must_quote_header and iso_char.search(line) >= 0: - must_quote_header = 1 - if mv.match(line) >= 0: - is_mime = 1 - if cte.match(line) >= 0: - has_cte = 1 - if qp.match(line) >= 0: - is_qp = 1 - if mp.match(line) >= 0: - multipart = '--' + mp.group(1) - if he.match(line) >= 0: - header_end = line - break - header.append(line) - - # read body - while 1: - line = ifile.readline() - if not line: - break - if multipart: - if line == multipart + '--\n': - message_end = line - break - if line == multipart + '\n': - message_end = line - break - if is_qp: - while line[-2:] == '=\n': - line = line[:-2] - newline = ifile.readline() - if newline[:len(QUOTE)] == QUOTE: - newline = newline[len(QUOTE):] - line = line + newline - line = mime_decode(line) - message.append(line) - if not has_iso_chars: - if iso_char.search(line) >= 0: - has_iso_chars = must_quote_body = 1 - if not must_quote_body: - if len(line) > MAXLEN: - must_quote_body = 1 - - # convert and output header and body - for line in header: - if must_quote_header: - line = mime_encode_header(line) - if chrset.match(line) >= 0: - if has_iso_chars: - # change us-ascii into iso-8859-1 - if string.lower(chrset.group(2)) == 'us-ascii': - line = chrset.group(1) + \ - CHARSET + chrset.group(3) - else: - # change iso-8859-* into us-ascii - line = chrset.group(1) + 'us-ascii' + chrset.group(3) - if has_cte and cte.match(line) >= 0: - line = 'Content-Transfer-Encoding: ' - if must_quote_body: - line = line + 'quoted-printable\n' - else: - line = line + '7bit\n' - ofile.write(line) - if (must_quote_header or must_quote_body) and not is_mime: - ofile.write('Mime-Version: 1.0\n') - ofile.write('Content-Type: text/plain; ') - if has_iso_chars: - ofile.write('charset="%s"\n' % CHARSET) - else: - ofile.write('charset="us-ascii"\n') - if must_quote_body and not has_cte: - ofile.write('Content-Transfer-Encoding: quoted-printable\n') - ofile.write(header_end) - - for line in message: - if must_quote_body: - line = mime_encode(line, 0) - ofile.write(line) - ofile.write(message_end) - - line = message_end - while multipart: - if line == multipart + '--\n': - return - if line == multipart + '\n': - nifile = File(ifile, multipart) - mimify_part(nifile, ofile, 1) - line = nifile.peek - ofile.write(line) - continue - -def mimify(infile, outfile): - '''Convert 8bit parts of a MIME mail message to quoted-printable.''' - if type(infile) == type(''): - ifile = open(infile) - if type(outfile) == type('') and infile == outfile: - import os - d, f = os.path.split(infile) - os.rename(infile, os.path.join(d, ',' + f)) - else: - ifile = infile - if type(outfile) == type(''): - ofile = open(outfile, 'w') - else: - ofile = outfile - nifile = File(ifile, None) - mimify_part(nifile, ofile, 0) - ofile.flush() - -import sys -if __name__ == '__main__' or (len(sys.argv) > 0 and sys.argv[0] == 'mimify'): - import getopt - usage = 'Usage: mimify [-l len] -[ed] [infile [outfile]]' - - opts, args = getopt.getopt(sys.argv[1:], 'l:ed') - if len(args) not in (0, 1, 2): - print usage - sys.exit(1) - if (('-e', '') in opts) == (('-d', '') in opts): - print usage - sys.exit(1) - for o, a in opts: - if o == '-e': - encode = mimify - elif o == '-d': - encode = unmimify - elif o == '-l': - try: - MAXLEN = string.atoi(a) - except: - print usage - sys.exit(1) - if len(args) == 0: - encode(sys.stdin, sys.stdout) - elif len(args) == 1: - encode(args[0], sys.stdout) - else: - encode(args[0], args[1]) diff --git a/Lib/multifile.py b/Lib/multifile.py deleted file mode 100644 index 71e0dd0d46..0000000000 --- a/Lib/multifile.py +++ /dev/null @@ -1,128 +0,0 @@ -# A class that makes each part of a multipart message "feel" like an -# ordinary file, as long as you use fp.readline(). Allows recursive -# use, for nested multipart messages. Probably best used together -# with module mimetools. -# -# Suggested use: -# -# real_fp = open(...) -# fp = MultiFile(real_fp) -# -# "read some lines from fp" -# fp.push(separator) -# while 1: -# "read lines from fp until it returns an empty string" (A) -# if not fp.next(): break -# fp.pop() -# "read remaining lines from fp until it returns an empty string" -# -# The latter sequence may be used recursively at (A). -# It is also allowed to use multiple push()...pop() sequences. -# Note that if a nested multipart message is terminated by a separator -# for an outer message, this is not reported, even though it is really -# illegal input. - -import sys -import string - -err = sys.stderr.write - -Error = 'multifile.Error' - -class MultiFile: - # - def __init__(self, fp): - self.fp = fp - self.stack = [] # Grows down - self.level = 0 - self.last = 0 - self.start = self.fp.tell() - self.posstack = [] # Grows down - # - def tell(self): - if self.level > 0: - return self.lastpos - return self.fp.tell() - self.start - # - def seek(self, pos): - if not 0 <= pos <= self.tell() or \ - self.level > 0 and pos > self.lastpos: - raise Error, 'bad MultiFile.seek() call' - self.fp.seek(pos + self.start) - self.level = 0 - self.last = 0 - # - def readline(self): - if self.level > 0: return '' - line = self.fp.readline() - if not line: - self.level = len(self.stack) - self.last = (self.level > 0) - if self.last: - err('*** Sudden EOF in MultiFile.readline()\n') - return '' - if line[:2] <> '--': return line - n = len(line) - k = n - while k > 0 and line[k-1] in string.whitespace: k = k-1 - mark = line[2:k] - if mark[-2:] == '--': mark1 = mark[:-2] - else: mark1 = None - for i in range(len(self.stack)): - sep = self.stack[i] - if sep == mark: - self.last = 0 - break - elif mark1 <> None and sep == mark1: - self.last = 1 - break - else: - return line - # Get here after break out of loop - self.lastpos = self.tell() - len(line) - self.level = i+1 - if self.level > 1: - err('*** Missing endmarker in MultiFile.readline()\n') - return '' - # - def readlines(self): - list = [] - while 1: - line = self.readline() - if not line: break - list.append(line) - return list - # - def read(self): # Note: no size argument -- read until EOF only! - return string.joinfields(self.readlines(), '') - # - def next(self): - while self.readline(): pass - if self.level > 1 or self.last: - return 0 - self.level = 0 - self.last = 0 - self.start = self.fp.tell() - return 1 - # - def push(self, sep): - if self.level > 0: - raise Error, 'bad MultiFile.push() call' - self.stack.insert(0, sep) - self.posstack.insert(0, self.start) - self.start = self.fp.tell() - # - def pop(self): - if self.stack == []: - raise Error, 'bad MultiFile.pop() call' - if self.level <= 1: - self.last = 0 - else: - abslastpos = self.lastpos + self.start - self.level = max(0, self.level - 1) - del self.stack[0] - self.start = self.posstack[0] - del self.posstack[0] - if self.level > 0: - self.lastpos = abslastpos - self.start - # diff --git a/Lib/mutex.py b/Lib/mutex.py deleted file mode 100644 index b897863574..0000000000 --- a/Lib/mutex.py +++ /dev/null @@ -1,58 +0,0 @@ -# Mutual exclusion -- for use with module sched - -# A mutex has two pieces of state -- a 'locked' bit and a queue. -# When the mutex is not locked, the queue is empty. -# Otherwise, the queue contains 0 or more (function, argument) pairs -# representing functions (or methods) waiting to acquire the lock. -# When the mutex is unlocked while the queue is not empty, -# the first queue entry is removed and its function(argument) pair called, -# implying it now has the lock. -# -# Of course, no multi-threading is implied -- hence the funny interface -# for lock, where a function is called once the lock is aquired. -# -class mutex: - # - # Create a new mutex -- initially unlocked - # - def __init__(self): - self.locked = 0 - self.queue = [] - # - # Test the locked bit of the mutex - # - def test(self): - return self.locked - # - # Atomic test-and-set -- grab the lock if it is not set, - # return true if it succeeded - # - def testandset(self): - if not self.locked: - self.locked = 1 - return 1 - else: - return 0 - # - # Lock a mutex, call the function with supplied argument - # when it is acquired. - # If the mutex is already locked, place function and argument - # in the queue. - # - def lock(self, function, argument): - if self.testandset(): - function(argument) - else: - self.queue.append(function, argument) - # - # Unlock a mutex. If the queue is not empty, call the next - # function with its argument. - # - def unlock(self): - if self.queue: - function, argument = self.queue[0] - del self.queue[0] - function(argument) - else: - self.locked = 0 - # diff --git a/Lib/newdir.py b/Lib/newdir.py deleted file mode 100644 index 937c49e67b..0000000000 --- a/Lib/newdir.py +++ /dev/null @@ -1,73 +0,0 @@ -# New dir() function - - -# This should be the new dir(), except that it should still list -# the current local name space by default - -def listattrs(x): - try: - dictkeys = x.__dict__.keys() - except (AttributeError, TypeError): - dictkeys = [] - # - try: - methods = x.__methods__ - except (AttributeError, TypeError): - methods = [] - # - try: - members = x.__members__ - except (AttributeError, TypeError): - members = [] - # - try: - the_class = x.__class__ - except (AttributeError, TypeError): - the_class = None - # - try: - bases = x.__bases__ - except (AttributeError, TypeError): - bases = () - # - total = dictkeys + methods + members - if the_class: - # It's a class instace; add the class's attributes - # that are functions (methods)... - class_attrs = listattrs(the_class) - class_methods = [] - for name in class_attrs: - if is_function(getattr(the_class, name)): - class_methods.append(name) - total = total + class_methods - elif bases: - # It's a derived class; add the base class attributes - for base in bases: - base_attrs = listattrs(base) - total = total + base_attrs - total.sort() - return total - i = 0 - while i+1 < len(total): - if total[i] == total[i+1]: - del total[i+1] - else: - i = i+1 - return total - - -# Helper to recognize functions - -def is_function(x): - return type(x) == type(is_function) - - -# Approximation of builtin dir(); but note that this lists the user's -# variables by default, not the current local name space. - -def dir(x = None): - if x is not None: - return listattrs(x) - else: - import __main__ - return listattrs(__main__) diff --git a/Lib/newimp.py b/Lib/newimp.py deleted file mode 100755 index 231a33dcea..0000000000 --- a/Lib/newimp.py +++ /dev/null @@ -1,1570 +0,0 @@ -"""Prototype of 'import' functionality enhanced to implement packages. - -Why packages? Packages enable module nesting and sibling module -imports. 'Til now, the python module namespace was flat, which -means every module had to have a unique name, in order to not -conflict with names of other modules on the load path. Furthermore, -suites of modules could not be structurally affiliated with one -another. - -With packages, a suite of, eg, email-oriented modules can include a -module named 'mailbox', without conflicting with the, eg, 'mailbox' -module of a shared-memory suite - 'email.mailbox' vs -'shmem.mailbox'. Packages also enable modules within a suite to -load other modules within their package without having the package -name hard-coded. Similarly, package suites of modules can be loaded -as a unit, by loading the package that contains them. - -Usage: once installed (newimp.install(); newimp.revert() to revert to -the prior __import__ routine), 'import ...' and 'from ... import ...' -can be used to: - - - import modules from the search path, as before. - - - import modules from within other directory "packages" on the search - path using a '.' dot-delimited nesting syntax. The nesting is fully - recursive. - - For example, 'import test.test_types' will import the test_types - module within the 'test' package. The calling environment would - then access the module as 'test.test_types', which is the name of - the fully-loaded 'test_types' module. It is found contained within - the stub (ie, only partially loaded) 'test' module, hence accessed as - 'test.test_types'. - - - import siblings from modules within a package, using '__.' as a shorthand - prefix to refer to the parent package. This enables referential - transparency - package modules need not know their package name. - - The '__' package references are actually names assigned within - modules, to refer to their containing package. This means that - variable references can be made to imported modules, or to variables - defined via 'import ... from', also using the '__.var' shorthand - notation. This establishes a proper equivalence between the import - reference '__.sibling' and the var reference '__.sibling'. - - - import an entire package as a unit, by importing the package directory. - If there is a module named '__init__.py' in the package, it controls the - load. Otherwise, all the modules in the dir, including packages, are - inherently loaded into the package module's namespace. - - For example, 'import test' will load the modules of the entire 'test' - package, at least until a test failure is encountered. - - In a package, a module with the name '__init__' has a special role. - If present in a package directory, then it is loaded into the package - module, instead of loading the contents of the directory. This - enables the __init__ module to control the load, possibly loading - the entire directory deliberately (using 'import __', or even - 'from __ import *', to load all the module contents directly into the - package module). - - - perform any combination of the above - have a package that contains - packages, etc. - -Modules have a few new attributes in support of packages. As mentioned -above, '__' is a shorthand attribute denoting the modules' parent package, -also denoted in the module by '__package__'. Additionally, modules have -associated with them a '__pkgpath__', a path by which sibling modules are -found.""" - -__version__ = "$Revision$" - -# $Id$ First release: -# Ken.Manheimer@nist.gov, 5-Apr-1995, for python 1.2 - -# Issues (scattered in code - search for three asterisks) -# *** Despite my efforts, 'reload(newimp)' will foul things up. -# *** Normalize_pathname will only work for Unix - which we need to detect. -# *** when a module with the name of the platform (as indicated by -# to-be-created var sys.platform), the package path gets '.' and the -# platform dir. -# *** use sys.impadmin for things like an import load-hooks var -# *** Import-load-hook keying module name versus package path, which dictates -# additions to the default ('.' and os-specific dir) path -# *** Document that the __init__.py can set __.__pkgpath__, in which case that -# will be used for the package-relative loads. -# *** Add a 'recursive' option to reload, for reload of package constituent -# modules (including subpackages), as well. Or maybe that should be the -# default, and eg stub-completion should override that default. ??? - -# Developers Notes: -# -# - 'sys.stub_modules' registers "incidental" (partially loaded) modules. -# A stub module is promoted to the fully-loaded 'sys.modules' list when it is -# explicitly loaded as a unit. -# - One load nuance - the actual load of most module types goes into the -# already-generated stub module. HOWEVER, eg dynamically loaded modules -# generate a new module object, which must supplant the existing stub. One -# consequence is that the import process must use indirection through -# sys.stub_modules or sys.modules to track the actual modules across some of -# the phases. -# - The test routines are cool, including a transient directory -# hierarchy facility, and a means of skipping to later tests by giving -# the test routine a numeric arg. -# - There may still be some loose ends, not to mention bugs. But the full -# functionality should be there. -# - The ImportStack object is necessary to carry the list of in-process imports -# across very open-ended recursions, where the state cannot be passed -# explicitly via the import_module calls; for a primary example, via exec of -# an 'import' statement within a module. -# - Python's (current) handling of extension modules, via imp.load_dynamic, -# does too much, some of which needs to be undone. See comments in -# load_module. Among other things, we actually change the __name__ of the -# module, which conceivably may break something. - -try: - VERBOSE -except NameError: - VERBOSE = 0 # Will be reset by init(1), also. - -import sys, string, regex, types, os, marshal, traceback -import __main__, __builtin__ - -newimp_globals = vars() - -try: - import imp # Build on this recent addition -except ImportError: - raise ImportError, 'Pkg import module depends on optional "imp" module'#==X - -from imp import SEARCH_ERROR, PY_SOURCE, PY_COMPILED, C_EXTENSION - -def defvar(varNm, envDict, val, override=0): - """If VARNAME does not have value in DICT, assign VAL to it. Optional arg - OVERRIDE means force the assignment in any case.""" - if (not envDict.has_key(varNm)) or override: - envDict[varNm] = val - -def init(full_reset=0): - """Do environment initialization, including retrofitting sys.modules with - module attributes.""" - # Retrofit all existing modules with package attributes, under auspices of - # __root__: - - locals, globals = vars(), newimp_globals - - if full_reset: - global VERBOSE - VERBOSE = 0 - - # sys.stub_modules tracks modules partially loaded modules, ie loaded only - # incidental to load of nested components. Together with sys.modules and - # the import stack, it serves as part of the module registration mechanism. - defvar('stub_modules', sys.__dict__, {}, full_reset) - - # Environment setup - "root" module, '__root__' - # Establish root package '__root__' in __main__ and newimp envs. - - # Longhand for name of variable identifying module's containing package: - defvar('PKG_NM', globals, "__package__", full_reset) - # Shorthand for module's container: - defvar('PKG_SHORT_NM', globals, "__", full_reset) - defvar('PKG_SHORT_NM_LEN', globals, len(PKG_SHORT_NM), full_reset) - - # Name of controlling module for a package, if any: - defvar('INIT_MOD_NM', globals, "__init__", full_reset) - - # Paths eventually will be extended to accomodate non-filesystem media - - # eg, URLs, composite objects, who knows. - - # Name assigned in sys for general import administration: - defvar('IMP_SYS_NM', globals, "imp_admin", full_reset) - defvar('MOD_LOAD_HOOKS', globals, "mod_load_hooks", full_reset) - if full_reset: - defvar(IMP_SYS_NM, sys.__dict__, {MOD_LOAD_HOOKS: {}}, full_reset) - - - # Name assigned in each module to tuple describing module import attrs: - defvar('IMP_ADMIN', globals, "__impadmin__", full_reset) - # The load-path obtaining for this package. Not defined for non-packages. - # If not set, package directory is used. If no package directory - # registered, sys.path is used. - defvar('PKG_PATH', globals, 0, full_reset) - # File from which module was loaded - may be None, eg, for __root__: - defvar('MOD_TYPE', globals, 1, full_reset) - # Exact path from which the module was loaded: - defvar('MOD_PATHNAME', globals, 2, full_reset) - # Package within which the module was found: - defvar('MOD_PACKAGE', globals, 3, full_reset) - defvar('USE_PATH', globals, 'either PKG_PATH or my dir', full_reset) - - # We're aliasing the top-level __main__ module as '__root__': - defvar('__root__', globals, __main__, full_reset) - defvar('ROOT_MOD_NM', globals, "__root__", full_reset) - if not sys.modules.has_key('__root__') or full_reset: - # and register it as an imported module: - sys.modules[ROOT_MOD_NM] = __root__ - - # Register package information in all existing top-level modules - they'll - # the None's mean, among other things, that their USE_PATH's all defer to - # sys.path. - for aMod in sys.modules.values(): - if (not aMod.__dict__.has_key(PKG_NM)) or full_reset: - set_mod_attrs(aMod, None, __root__, None, None) - - try: - __builtin__.__import__ - defvar('origImportFunc', globals, __builtin__.__import__) - defvar('origReloadFunc', globals, __builtin__.reload) - except AttributeError: - pass - - defvar('PY_PACKAGE', globals, 4, full_reset) - defvar('PY_FROZEN', globals, 5, full_reset) - defvar('PY_BUILTIN', globals, 6, full_reset) - - # Establish lookup table from mod-type "constants" to names: - defvar('mod_types', globals, - {SEARCH_ERROR: 'SEARCH_ERROR', - PY_SOURCE: 'PY_SOURCE', - PY_COMPILED: 'PY_COMPILED', - C_EXTENSION: 'C_EXTENSION', - PY_PACKAGE: 'PY_PACKAGE', - PY_FROZEN: 'PY_FROZEN', - PY_BUILTIN: 'PY_BUILTIN'}, - full_reset) - - defvar('stack', globals, ImportStack(), full_reset) - -def install(): - """Install newimp import_module() routine, for package support. - - newimp.revert() reverts to __import__ routine that was superceded.""" - __builtin__.__import__ = import_module - __builtin__.reload = reload - __builtin__.unload = unload - __builtin__.bypass = bypass - return 'Enhanced import functionality in place.' -def revert(): - """Revert to original __builtin__.__import__ func, if newimp.install() has - been executed.""" - if not (origImportFunc and origReloadFunc): - raise SystemError, "Can't find original import and reload funcs." # ==X - __builtin__.__import__ = origImportFunc - __builtin__.reload = origReloadFunc - del __builtin__.unload, __builtin__.bypass - return 'Original import routines back in place.' - -def import_module(name, - envLocals=None, envGlobals=None, - froms=None, - inPkg=None): - """Primary service routine implementing 'import' with package nesting. - - NAME: name as specified to 'import NAME' or 'from NAME...' - LOCALS, GLOBALS: local and global dicts obtaining for import - FROMS: list of strings of "..." in 'import blat from ...' - INPKG: package to which the name search is restricted, for use - by recursive package loads (from import_module()). - - A subtle difference from the old import - modules that do fail - initialization will not be registered in sys.modules, ie will not, in - effect, be registered as being loaded. Note further that packages which - fail their overall load, but have successfully loaded constituent modules, - will be accessible in the importing namespace as stub modules. - - A new routine, 'newimp.bypass()', provides the means to circumvent - constituent modules that fail their load, in order to enable load of the - remainder of a package.""" - - rootMod = sys.modules[ROOT_MOD_NM] - - note("import_module: seeking '%s'" % name, 1) - - # We need callers environment dict for local path and resulting module - # binding. - if not envGlobals: - # This should not happen, but does for imports called from within - # functions. - envLocals, envGlobals = exterior() - - if inPkg: - pkg = inPkg - elif envGlobals.has_key(PKG_NM): - pkg = envGlobals[PKG_NM] - else: - # ** KLUDGE - cover for modules that lack package attributes: - pkg = rootMod - - if pkg != rootMod: - note(' - relative to package %s' % pkg) - - modList = theMod = absNm = nesting = None - - # Normalize - # - absNm is absolute w.r.t. __root__ - # - relNm is relative w.r.t. pkg. - if inPkg: - absNm, relNm = pkg.__name__ + '.' + name, name - else: - absNm, relNm, pkg = normalize_import_ref(name, pkg) - note("Normalized: %s%s" % (absNm, (((relNm != absNm) - and (" ('%s' in %s)" % (relNm, pkg))) - or '')), 3) - - pkgPath = get_mod_attrs(pkg, USE_PATH) - - try: # try...finally guards import stack integrity. - - if stack.push(absNm): - # We're nested inside a containing import of this module, perhaps - # indirectly. Avoid infinite recursion at this point by using the - # existing stub module, for now. Load of it will be completed by - # the superior import. - note('recursion on in-process module %s, punting with stub' % - absNm) - theMod = stack.mod(absNm) - - else: - - # Try to find already-imported: - if sys.modules.has_key(absNm): - note('found ' + absNm + ' already imported') - theMod = sys.modules[absNm] - stack.mod(absNm, theMod) - - else: # Actually do load, of one sort or another: - - # Seek builtin or frozen first: - theMod = imp.init_builtin(absNm) - if theMod: - set_mod_attrs(theMod, None, pkg, None, PY_BUILTIN) - stack.mod(absNm, theMod) - note('found builtin ' + absNm) - else: - theMod = imp.init_frozen(absNm) - if theMod: - set_mod_attrs(theMod, None, pkg, None, PY_FROZEN) - stack.mod(absNm, theMod) - note('found frozen ' + absNm) - - if not theMod: - # Not already-loaded, in-process, builtin, or frozen - - # we're seeking in the outside world (filesystem): - - if sys.stub_modules.has_key(absNm): - - # A package for which we have a stub: - theMod = reload(sys.stub_modules[absNm], inPkg) - - else: - - # Now we actually search the fs. - - if type(pkgPath) == types.StringType: - pkgPath = [pkgPath] - - # Find a path leading to the module: - modList = find_module(relNm, pkgPath, absNm) - if not modList: - raise ImportError, ("module '%s' not found" % #==X - absNm) - - # We have a list of successively nested dirs leading - # to the module, register with import admin, as stubs: - nesting = register_mod_nesting(modList, pkg) - - # Load from file if necessary and possible: - modNm, modf, path, ty = modList[-1] - note('found type %s - %s' % (mod_types[ty[2]], absNm)) - - # Establish the module object in question: - theMod = procure_module(absNm) - stack.mod(absNm, theMod) - - # Do the load: - theMod = load_module(theMod, ty[2], modf, inPkg) - - commit_mod_containment(absNm) - - # Successful load - promote to fully-imported status: - register_module(theMod, theMod.__name__) - - - # We have a loaded module (perhaps stub): situate specified components, - # and return appropriate thing. According to guido: - # - # "Note that for "from spam.ham import bacon" your function should - # return the object denoted by 'spam.ham', while for "import - # spam.ham" it should return the object denoted by 'spam' -- the - # STORE instructions following the import statement expect it this - # way." - # *** The above rationale should probably be reexamined, since newimp - # actually takes care of populating the caller's namespace. - - if not froms: - - # Return the outermost container, possibly stub: - if nesting: - return find_mod_registration(nesting[0][0]) - else: - return find_mod_registration(string.splitfields(absNm,'.')[0]) - else: - - return theMod - - finally: # Decrement stack registration: - stack.pop(absNm) - - -def reload(module, inPkg = None): - """Re-parse and re-initialize an already (or partially) imported MODULE. - - The argument can be an already loaded module object or a string name of a - loaded module or a "stub" module that was partially loaded package module - incidental to the full load of a contained module. - - This is useful if you have edited the module source file using an external - editor and want to try out the new version without leaving the Python - interpreter. The return value is the resulting module object. - - Contrary to the old 'reload', the load is sought from the same location - where the module was originally found. If you wish to do a fresh load from - a different module on the path, do an 'unload()' and then an import. - - When a module is reloaded, its dictionary (containing the module's - global variables) is retained. Redefinitions of names will - override the old definitions, so this is generally not a problem. - If the new version of a module does not define a name that was - defined by the old version, the old definition remains. This - feature can be used to the module's advantage if it maintains a - global table or cache of objects -- with a `try' statement it can - test for the table's presence and skip its initialization if - desired. - - It is legal though generally not very useful to reload built-in or - dynamically loaded modules, except for `sys', `__main__' and - `__builtin__'. In certain cases, however, extension modules are - not designed to be initialized more than once, and may fail in - arbitrary ways when reloaded. - - If a module imports objects from another module using `from' ... - `import' ..., calling `reload()' for the other module does not - redefine the objects imported from it -- one way around this is to - re-execute the `from' statement, another is to use `import' and - qualified names (MODULE.NAME) instead. - - If a module instantiates instances of a class, reloading the module - that defines the class does not affect the method definitions of - the instances, unless they are reinstantiated -- they continue to use the - old class definition. The same is true for derived classes.""" - - if type(module) == types.StringType: - theMod = find_mod_registration(module) - elif type(module) == types.ModuleType: - theMod = module - else: - raise ImportError, '%s not already imported' # ==X - - if theMod in [sys.modules[ROOT_MOD_NM], sys.modules['__builtin__']]: - raise ImportError, 'cannot re-init internal module' # ==X - - try: - thePath = get_mod_attrs(theMod, MOD_PATHNAME) - except KeyError: - thePath = None - - if not thePath: - # If we have no path for the module, we can only reload it from - # scratch: - note('no pathname registered for %s, doing full reload' % theMod) - unload(theMod) - envGlobals, envLocals = exterior() - return import_module(theMod.__name__, - envGlobals, envLocals, None, inPkg) - else: - - stack.mod(theMod.__name__, theMod) - ty = get_mod_attrs(theMod, MOD_TYPE) - if ty in [PY_SOURCE, PY_COMPILED]: - note('reload invoked for %s %s' % (mod_types[ty], theMod)) - thePath, ty, openFile = prefer_compiled(thePath, ty) - else: - openFile = open(thePath, get_suffixes(ty)[1]) - return load_module(theMod, # ==> - ty, - openFile, - inPkg) -def unload(module): - """Remove registration for a module, so import will do a fresh load. - - Returns the module registries (sys.modules and/or sys.stub_modules) where - it was found.""" - if type(module) == types.ModuleType: - module = module.__name__ - gotit = [] - for which in ['sys.modules', 'sys.stub_modules']: - m = eval(which) - try: - del m[module] - gotit.append(which) - except KeyError: - pass - if not gotit: - raise ValueError, '%s not a module or a stub' % module # ==X - else: return gotit -def bypass(modNm): - """Register MODULE-NAME so module will be skipped, eg in package load.""" - if sys.modules.has_key(modNm): - raise ImportError("'%s' already imported, cannot be bypassed." % modNm) - else: - sys.modules[modNm] = imp.new_module('bypass()ed module %s' % modNm) - commit_mod_containment(modNm) - - -def normalize_import_ref(name, pkg): - """Produce absolute and relative nm and relative pkg given MODNM and origin - PACKAGE, reducing out all '__'s in the process.""" - - # First reduce out all the '__' container-refs we can: - outwards, inwards = 0, [] - for nm in string.splitfields(name, '.'): - if nm == PKG_SHORT_NM: - if inwards: - # Pop a containing inwards: - del inwards[-1] - else: - # (Effectively) leading '__' - notch outwards: - outwards = outwards + 1 - else: - inwards.append(nm) - inwards = string.joinfields(inwards, '.') - - # Now identify the components: - - if not outwards: - pkg = sys.modules[ROOT_MOD_NM] - else: - while outwards > 1: - pkg = pkg.__dict__[PKG_NM] # We'll just loop at top - if pkg == __root__: - break # ==v - outwards = outwards - 1 - - if not inwards: # Entire package: - return pkg.__name__, pkg.__name__, pkg # ==> - else: # Name relative to package: - if pkg == __root__: - return inwards, inwards, pkg # ==> - else: - return pkg.__name__ + '.' + inwards, inwards, pkg # ==> - -class ImportStack: - """Provide judicious support for mutually recursive import loops. - - Mutually recursive imports, eg a module that imports the package that - contains it, which in turn imports the module, are not uncommon, and must - be supported judiciously. This class is used to track cycles, so a module - already in the process of being imported (via 'stack.push(module)', and - concluded via 'stack.release(module)') is not redundantly pursued; *except* - when a module master '__init__.py' loads the module, in which case it is - 'stack.relax(module)'ed, so the full import is pursued.""" - - def __init__(self): - self._cycles = {} - self._mods = {} - self._looped = [] - def in_process(self, modNm): - """1 if modNm load already in process, 0 otherwise.""" - return self._cycles.has_key(modNm) # ==> - def looped(self, modNm): - """1 if modNm load has looped once or more, 0 otherwise.""" - return modNm in self._looped - def push(self, modNm): - """1 if modNm already in process and not 'relax'ed, 0 otherwise. - (Note that the 'looped' status remains even when the cycle count - returns to 1. This is so error messages can indicate that it was, at - some point, looped during the import process.)""" - if self.in_process(modNm): - self._looped.append(modNm) - self._cycles[modNm] = self._cycles[modNm] + 1 - return 1 # ==> - else: - self._cycles[modNm] = 1 - return 0 # ==> - def mod(self, modNm, mod=None): - """Associate MOD-NAME with MODULE, for easy reference.""" - if mod: - self._mods[modNm] = mod - else: - try: - return self._mods[modNm] # ==> - except KeyError: - return None - def pop(self, modNm): - """Decrement stack count of MODNM""" - if self.in_process(modNm): - amt = self._cycles[modNm] = self._cycles[modNm] - 1 - if amt < 1: - del self._cycles[modNm] - if modNm in self._looped: - self._looped.remove(modNm) - if self._mods.has_key(modNm): - del self._mods[modNm] - def relax(self, modNm): - """Enable modNm load despite being registered as already in-process.""" - if self._cycles.has_key(modNm): - del self._cycles[modNm] - -def find_module(name, path, absNm=''): - """Locate module NAME on PATH. PATH is pathname string or a list of them. - - Note that up-to-date compiled versions of a module are preferred to plain - source, and compilation is automatically performed when necessary and - possible. - - Returns a list of the tuples returned by 'find_mod_file()', one for - each nested level, deepest last.""" - - checked = [] # For avoiding redundant dir lists. - - if not absNm: absNm = name - - # Parse name into list of nested components, - expNm = string.splitfields(name, '.') - - for curPath in path: - - if (type(curPath) != types.StringType) or (curPath in checked): - # Disregard bogus or already investigated path elements: - continue # ==^ - else: - # Register it for subsequent disregard. - checked.append(curPath) - - if len(expNm) == 1: - - # Non-nested module name: - - got = find_mod_file(curPath, absNm) - if got: - note('using %s' % got[2], 3) - return [got] # ==> - - else: - - # Composite name specifying nested module: - - gotList = []; nameAccume = expNm[0] - - got = find_mod_file(curPath, nameAccume) - if not got: # Continue to next prospective path. - continue # ==^ - else: - gotList.append(got) - nm, file, fullPath, ty = got - - # Work on successively nested components: - for component in expNm[1:]: - # 'ty'pe of containing component must be package: - if ty[2] != PY_PACKAGE: - gotList, got = [], None - break # ==v - if nameAccume: - nameAccume = nameAccume + '.' + component - else: - nameAccume = component - got = find_mod_file(fullPath, nameAccume) - if got: - gotList.append(got) - nm, file, fullPath, ty = got - else: - # Clear state vars: - gotList, got, nameAccume = [], None, '' - break # ==v - # Found nesting all the way to the specified tip: - if got: - return gotList # ==> - - # Failed. - return None - -def find_mod_file(pathNm, modname): - """Find right module file given DIR and module NAME, compiling if needed. - - If successful, returns quadruple consisting of: - - mod name, - - file object, - - full pathname for the found file, - - a description triple as contained in the list returned by get_suffixes. - - Otherwise, returns None. - - Note that up-to-date compiled versions of a module are preferred to plain - source, and compilation is automatically performed, when necessary and - possible.""" - - relNm = modname[1 + string.rfind(modname, '.'):] - - for suff, mode, ty in get_suffixes(): - fullPath = os.path.join(pathNm, relNm + suff) - note('trying ' + fullPath + '...', 4) - try: - modf = open(fullPath, mode) - except IOError: - # ** ?? Skip unreadable ones: - continue # ==^ - - if ty == PY_PACKAGE: - # Enforce directory characteristic: - if not os.path.isdir(fullPath): - note('Skipping non-dir match ' + fullPath, 3) - continue # ==^ - else: - return (modname, modf, fullPath, (suff, mode, ty)) # ==> - - - elif ty in [PY_SOURCE, PY_COMPILED]: - usePath, useTy, openFile = prefer_compiled(fullPath, ty) - return (modname, # ==> - openFile, - usePath, - get_suffixes(useTy)) - - elif ty == C_EXTENSION: - note('found C_EXTENSION ' + fullPath, 3) - return (modname, modf, fullPath, (suff, mode, ty)) # ==> - - else: - raise SystemError, 'Unanticipated module type encountered' # ==X - - return None - -def prefer_compiled(path, ty, modf=None): - """Given a path to a .py or .pyc file, attempt to return a path to a - current pyc file, compiling the .py in the process if necessary. Returns - the path to the most current version we can get.""" - - if ty == PY_SOURCE: - if not modf: - try: - modf = open(path, 'r') - except IOError: - pass - note('working from PY_SOURCE', 3) - # Try for a compiled version: - pyc = path + 'c' # Sadly, we're presuming '.py' suff. - if (not os.path.exists(pyc) or - (os.stat(path)[8] > os.stat(pyc)[8])): - # Try to compile: - pyc = compile_source(path, modf) - if pyc and not (os.stat(path)[8] > os.stat(pyc)[8]): - # Either pyc was already newer or we just made it so; in either - # case it's what we crave: - note('but got newer compiled, ' + pyc, 3) - try: - return (pyc, PY_COMPILED, open(pyc, 'rb')) # ==> - except IOError: - if modf: - return (path, PY_SOURCE, modf) # ==> - else: - raise ImportError, 'Failed acces to .py and .pyc' # ==X - else: - note("couldn't get newer compiled, using PY_SOURCE", 3) - if modf: - return (path, PY_SOURCE, modf) # ==> - else: - raise ImportError, 'Failed acces to .py and .pyc' # ==X - - elif ty == PY_COMPILED: - note('working from PY_COMPILED', 3) - if not modf: - try: - modf = open(path, 'rb') - except IOError: - return prefer_compiled(path[:-1], PY_SOURCE) - # Make sure it is current, trying to compile if necessary, and - # prefer source failing that: - note('found compiled ' + path, 3) - py = path[:-1] # ** Presuming '.pyc' suffix - if not os.path.exists(py): - note('pyc SANS py: ' + path, 3) - return (path, PY_COMPILED, open(py, 'r')) # ==> - elif (os.stat(py)[8] > os.stat(path)[8]): - note('Forced to compile: ' + py, 3) - pyc = compile_source(py, open(py, 'r')) - if pyc: - return (pyc, PY_COMPILED, modf) # ==> - else: - note('failed compile - must use more recent .py', 3) - return (py, PY_SOURCE, open(py, 'r')) # ==> - else: - return (path, PY_COMPILED, modf) # ==> - -def load_module(theMod, ty, theFile, fromMod): - """Load module NAME, of TYPE, from FILE, within MODULE. - - Optional arg fromMod indicates the module from which the load is being done - - necessary for detecting import of __ from a package's __init__ module. - - Return the populated module object.""" - - # Note: we mint and register intermediate package directories, as necessary - - name = theMod.__name__ - nameTail = name[1 + string.rfind(name, '.'):] - thePath = theFile.name - - if ty == PY_SOURCE: - exec_into(theFile, theMod, theFile.name) - - elif ty == PY_COMPILED: - pyc = open(theFile.name, 'rb').read() - if pyc[0:4] != imp.get_magic(): - raise ImportError, 'bad magic number: ' + theFile.name # ==X - code = marshal.loads(pyc[8:]) - exec_into(code, theMod, theFile.name) - - elif ty == C_EXTENSION: - # Dynamically loaded C_EXTENSION modules do too much import admin, - # themselves, which we need to *undo* in order to integrate them with - # the new import scheme. - # 1 They register themselves in sys.modules, registering themselves - # under their top-level names. Have to rectify that. - # 2 The produce their own module objects, *unless* they find an - # existing module already registered a la 1, above. We employ this - # quirk to make it use the already generated module. - try: - # Stash a ref to any module that is already registered under the - # dyamic module's simple name (nameTail), so we can reestablish it - # after the dynamic takes over its' slot: - protMod = None - if nameTail != name: - if sys.modules.has_key(nameTail): - protMod = sys.modules[nameTail] - # Trick the dynamic load, by registering the module we generated - # under the nameTail of the module we're loading, so the one we're - # loading will use that established module, rather than producing a - # new one: - sys.modules[nameTail] = theMod - theMod = imp.load_dynamic(nameTail, thePath, theFile) - theMod.__name__ = name - # Cleanup dynamic mod's bogus self-registration, if necessary: - if nameTail != name: - if protMod: - # ... reinstating the one that was already there... - sys.modules[nameTail] = protMod - else: - if sys.modules.has_key(nameTail): - # Certain, as long os dynamics continue to misbehave. - del sys.modules[nameTail] - stack.mod(name, theMod) - if sys.stub_modules.has_key(name): - sys.stub_modules[name] = theMod - elif sys.modules.has_key(name): - sys.modules[name] = theMod - except: - # Provide import-nesting info, including signs of circularity: - raise sys.exc_type, import_trail_msg(str(sys.exc_value),# ==X - sys.exc_traceback, - name) - elif ty == PY_PACKAGE: - # Load package constituents, doing the controlling module *if* it - # exists *and* it isn't already in process: - - init_mod_f = init_mod = None - if not stack.in_process(name + '.' + INIT_MOD_NM): - # Not already doing __init__ - check for it: - init_mod_f = find_mod_file(thePath, INIT_MOD_NM) - else: - note('skipping already-in-process %s.%s' % (theMod.__name__, - INIT_MOD_NM)) - got = {} - if init_mod_f: - note("Found package's __init__: " + init_mod_f[2]) - # Enable full continuance of containing-package-load from __init__: - if stack.in_process(theMod.__name__): - stack.relax(theMod.__name__) - init_mod = import_module(INIT_MOD_NM, - theMod.__dict__, theMod.__dict__, - None, - theMod) - else: - # ... or else recursively load all constituent modules, except - # __init__: - for prospect in mod_prospects(thePath): - if prospect != INIT_MOD_NM: - import_module(prospect, - theMod.__dict__, theMod.__dict__, - None, - theMod) - - else: - raise ImportError, 'Unimplemented import type: %s' % ty # ==X - - return theMod - -def exec_into(obj, module, path): - """Helper for load_module, execfile/exec path or code OBJ within MODULE.""" - - # This depends on ability of exec and execfile to mutilate, erhm, mutate - # the __dict__ of a module. It will not work if/when this becomes - # disallowed, as it is for normal assignments. - - try: - if type(obj) == types.FileType: - execfile(path, module.__dict__, module.__dict__) - elif type(obj) in [types.CodeType, types.StringType]: - exec obj in module.__dict__, module.__dict__ - except: - # Make the error message nicer? - raise sys.exc_type, import_trail_msg(str(sys.exc_value), # ==X - sys.exc_traceback, - module.__name__) - - -def mod_prospects(path): - """Return a list of prospective modules within directory PATH. - - We actually return the distinct names resulting from stripping the dir - entries (excluding os.curdir and os.pardir) of their suffixes (as - represented by 'get_suffixes'). - - (Note that matches for the PY_PACKAGE type with null suffix are - implicitly constrained to be directories.)""" - - # We actually strip the longest matching suffixes, so eg 'dbmmodule.so' - # mates with 'module.so' rather than '.so'. - - dirList = os.listdir(path) - excludes = [os.curdir, os.pardir] - sortedSuffs = sorted_suffixes() - entries = [] - for item in dirList: - if item in excludes: continue # ==^ - for suff in sortedSuffs: - # *** ?? maybe platform-specific: - sub = -1 * len(suff) - if sub == 0: - if os.path.isdir(os.path.join(path, item)): - entries.append(item) - elif item[sub:] == suff: - it = item[:sub] - if not it in entries: - entries.append(it) - break # ==v - return entries - - - -def procure_module(name): - """Return an established or else new module object having NAME. - - First checks sys.modules, then sys.stub_modules.""" - - if sys.modules.has_key(name): - return sys.modules[name] # ==> - elif sys.stub_modules.has_key(name): - return sys.stub_modules[name] # ==> - else: - return (stack.mod(name) or imp.new_module(name)) # ==> - -def commit_mod_containment(name): - """Bind a module object and its containers within their respective - containers.""" - cume, pkg = '', find_mod_registration(ROOT_MOD_NM) - for next in string.splitfields(name, '.'): - if cume: - cume = cume + '.' + next - else: - cume = next - cumeMod = find_mod_registration(cume) - pkg.__dict__[next] = cumeMod - pkg = cumeMod - -def register_mod_nesting(modList, pkg): - """Given find_module()-style NEST-LIST and parent PACKAGE, register new - package components as stub modules, and return list of nested - module/relative-name pairs. - - Note that the modules objects are not situated in their containing packages - here - that is left 'til after a successful load, and done by - commit_mod_nesting().""" - nesting = [] - - for modNm, modF, path, ty in modList: - - relNm = modNm[1 + string.rfind(modNm, '.'):] - - if sys.modules.has_key(modNm): - theMod = sys.modules[modNm] # Nestle in containing package - pkg = theMod # Set as parent for next in sequence. - elif sys.stub_modules.has_key(modNm): - # Similar to above... - theMod = sys.stub_modules[modNm] - pkg = theMod - else: - theMod = procure_module(modNm) - stack.mod(modNm, theMod) - # *** ??? Should we be using 'path' instead of modF.name? If not, - # should we get rid of the 'path' return val? - set_mod_attrs(theMod, normalize_pathname(modF.name), - pkg, None, ty[2]) - if ty[2] == PY_PACKAGE: - # Register as a stub: - register_module(theMod, modNm, 1) - pkg = theMod - nesting.append((theMod.__name__,relNm)) - - return nesting - -def register_module(theMod, name, stub=0): - """Properly register MODULE, NAME, and optional STUB qualification.""" - - if stub: - sys.stub_modules[name] = theMod - else: - sys.modules[name] = theMod - if sys.stub_modules.has_key(name): - del sys.stub_modules[name] - -def find_mod_registration(name): - """Find module named NAME sys.modules, .stub_modules, or on the stack.""" - if sys.stub_modules.has_key(name): - return sys.stub_modules[name] # ==> - elif sys.modules.has_key(name): - return sys.modules[name] # ==> - else: - if stack.in_process(name): - it = stack.mod(name) - if it: - return it # ==> - else: - raise ValueError, '%s %s in %s or %s' % (name, # ==X - 'not registered', - 'sys.modules', - 'sys.stub_modules') - -def get_mod_attrs(theMod, which = None): - """Get MODULE object's path, containing-package, and designated path. - - Virtual attribute USE_PATH is derived from PKG_PATH, MOD_PATHNAME, - and/or sys.path, depending on the module type and settings.""" - it = theMod.__dict__[IMP_ADMIN] - if which: - # Load path is either the explicitly designated load path for the - # package, or else the directory in which it resides: - if which == USE_PATH: - if it[PKG_PATH]: - # Return explicitly designated path: - return it[PKG_PATH] # ==> - if it[MOD_PATHNAME]: - if it[MOD_TYPE] == PY_PACKAGE: - # Return the package's directory path: - return [it[MOD_PATHNAME]] # ==> - else: - # Return the directory where the module resides: - return [os.path.split(it[MOD_PATHNAME])[0]] # ==> - # No explicitly designated path - use sys.path, eg for system - # modules, etc: - return sys.path - return it[which] # ==> - else: - return it # ==> - -def set_mod_attrs(theMod, path, pkg, pkgPath, ty): - """Register MOD import attrs PATH, PKG container, and PKGPATH, linking - the package container into the module along the way.""" - theDict = theMod.__dict__ - try: - # Get existing one, if any: - it = theDict[IMP_ADMIN] - except KeyError: - # None existing, gen a new one: - it = [None] * 4 - for fld, val in ((MOD_PATHNAME, path), (MOD_PACKAGE, pkg), - (PKG_PATH, pkgPath), (MOD_TYPE, ty)): - if val: - it[fld] = val - - theDict[IMP_ADMIN] = it - if pkg: - theDict[PKG_NM] = theDict[PKG_SHORT_NM] = pkg - return it # ==> - -def format_tb_msg(tb, recursive): - """This should be in traceback.py, and traceback.print_tb() should use it - and traceback.extract_tb(), instead of print_tb() and extract_tb() having - so much redundant code!""" - tb_lines, formed = traceback.extract_tb(tb), '' - for line in tb_lines: - f, lno, nm, ln = line - if f[-1 * (len(__name__) + 3):] == __name__ + '.py': - # Skip newimp notices - agregious hack, justified only by the fact - # that this functionality will be properly doable in new impending - # exception mechanism: - continue - formed = formed + ('\n%s File "%s", line %d, in %s%s' % - (((recursive and '*') or ' '), - f, lno, nm, - ((ln and '\n ' + string.strip(ln)) or ''))) - return formed - -def import_trail_msg(msg, tb, modNm): - """Doctor an error message to include the path of the current import, and - a sign that it is a circular import, if so.""" - return (msg + - format_tb_msg(tb, - (stack.looped(modNm) and stack.in_process(modNm)))) - -def compile_source(sourcePath, sourceFile): - """Given python code source path and file obj, Create a compiled version. - - Return path of compiled version, or None if file creation is not - successful. (Compilation errors themselves are passed without restraint.) - - This is an import-private interface, and not well-behaved for general use. - - In particular, we presume the validity of the sourcePath, and that it - includes a '.py' extension.""" - - compiledPath = sourcePath[:-3] + '.pyc' - try: - compiledFile = open(compiledPath, 'wb') - except IOError: - note("write permission denied to " + compiledPath, 3) - return None - mtime = os.stat(sourcePath)[8] - - try: - compiled = compile(sourceFile.read(), sourcePath, 'exec') - except SyntaxError: - # Doctor the exception a bit, to include the source file name in - # the report, and then reraise the doctored version. - os.unlink(compiledFile.name) - sys.exc_value = ((sys.exc_value[0] + ' in ' + sourceFile.name,) - + sys.exc_value[1:]) - raise sys.exc_type, sys.exc_value # ==X - - # Ok, we have a valid compilation. - try: - compiledFile.write(imp.get_magic()) # compiled magic number - compiledFile.seek(8, 0) # mtime space holder - marshal.dump(compiled, compiledFile) # write the code obj - compiledFile.seek(4, 0) # position for mtime - compiledFile.write(marshal.dumps(mtime)[1:]) # register mtime - compiledFile.flush() - compiledFile.close() - return compiledPath - except IOError: - return None # ==> - - -got_suffixes = None -got_suffixes_dict = {} -def get_suffixes(ty=None): - """Produce a list of triples, each describing a type of import file. - - Triples have the form '(SUFFIX, MODE, TYPE)', where: - - SUFFIX is a string found appended to a module name to make a filename for - that type of import file. - - MODE is the mode string to be passed to the built-in 'open' function - "r" - for text files, "rb" for binary. - - TYPE is the file type: - - PY_SOURCE: python source code, - PY_COMPILED: byte-compiled python source, - C_EXTENSION: compiled-code object file, - PY_PACKAGE: python library directory, or - SEARCH_ERROR: no module found. """ - - # Note: sorted_suffixes() depends on this function's value being invariant. - # sorted_suffixes() must be revised if this becomes untrue. - - global got_suffixes, got_suffixes_dict - - if not got_suffixes: - # Ensure that the .pyc suffix precedes the .py: - got_suffixes = [('', 'r', PY_PACKAGE)] - got_suffixes_dict[PY_PACKAGE] = ('', 'r', PY_PACKAGE) - py = pyc = None - for suff in imp.get_suffixes(): - got_suffixes_dict[suff[2]] = suff - if suff[0] == '.py': - py = suff - elif suff[0] == '.pyc': - pyc = suff - else: - got_suffixes.append(suff) - got_suffixes.append(pyc) - got_suffixes.append(py) - if ty: - return got_suffixes_dict[ty] # ==> - else: - return got_suffixes # ==> - - -sortedSuffs = [] # State vars for sorted_suffixes(). Go -def sorted_suffixes(): - """Helper function ~efficiently~ tracks sorted list of module suffixes.""" - - # Produce sortedSuffs once - this presumes that get_suffixes does not - # change from call to call during a python session. Needs to be - # corrected if that becomes no longer true. - - global sortedsuffs - if not sortedSuffs: # do compute only the "first" time - for item in get_suffixes(): - sortedSuffs.append(item[0]) - # Sort them in descending order: - sortedSuffs.sort(lambda x, y: (((len(x) > len(y)) and 1) or - ((len(x) < len(y)) and -1))) - sortedSuffs.reverse() - return sortedSuffs - - -def normalize_pathname(path): - """Given PATHNAME, return an absolute pathname relative to cwd, reducing - unnecessary components where convenient (eg, on Unix).""" - - # We do a lot more when we have posix-style paths, eg os.sep == '/'. - - if os.sep != '/': - return os.path.join(os.getcwd, path) # ==> - - outwards, inwards = 0, [] - for nm in string.splitfields(path, os.sep): - if nm != os.curdir: - if nm == os.pardir: - # Translate parent-dir entries to outward notches: - if inwards: - # Pop a containing inwards: - del inwards[-1] - else: - # Register leading outward notches: - outwards = outwards + 1 - else: - inwards.append(nm) - inwards = string.joinfields(inwards, os.sep) - - if (not inwards) or (inwards[0] != os.sep): - # Relative path - join with current working directory, (ascending - # outwards to account for leading parent-dir components): - cwd = os.getcwd() - if outwards: - cwd = string.splitfields(cwd, os.sep) - cwd = string.joinfields(cwd[:len(cwd) - outwards], os.sep) - if inwards: - return os.path.join(cwd, inwards) # ==> - else: - return cwd # ==> - else: - return inwards # ==> - - -# exterior(): Utility routine, obtain local and global dicts of environment -# containing/outside the callers environment, ie that of the -# caller's caller. Routines can use exterior() to determine the -# environment from which they were called. - -def exterior(): - """Return dyad containing locals and globals of caller's caller. - - Locals will be None if same as globals, ie env is global env.""" - - bogus = 'bogus' # A locally usable exception - try: raise bogus # Force an exception object - except bogus: - at = sys.exc_traceback.tb_frame.f_back # The external frame. - if at.f_back: at = at.f_back # And further, if any. - globals, locals = at.f_globals, at.f_locals - if locals == globals: # Exterior is global? - locals = None - return (locals, globals) - -######################################################################### -# TESTING FACILITIES # - -def note(msg, threshold=2): - if VERBOSE >= threshold: sys.stderr.write('(import: ' + msg + ')\n') - -class TestDirHier: - """Populate a transient directory hierarchy according to a definition - template - so we can create package/module hierarchies with which to - exercise the new import facilities...""" - - def __init__(self, template, where='/var/tmp'): - """Establish a dir hierarchy, according to TEMPLATE, that will be - deleted upon deletion of this object (or deliberate invocation of the - __del__ method).""" - self.PKG_NM = 'tdh_' - rev = 0 - while os.path.exists(os.path.join(where, self.PKG_NM+str(rev))): - rev = rev + 1 - sys.exc_traceback = None # Ensure Discard of try/except obj ref - self.PKG_NM = self.PKG_NM + str(rev) - self.root = os.path.join(where, self.PKG_NM) - self.createDir(self.root) - self.add(template) - - def __del__(self): - """Cleanup the test hierarchy.""" - self.remove() - def add(self, template, root=None): - """Populate directory according to template dictionary. - - Keys indicate file names, possibly directories themselves. - - String values dictate contents of flat files. - - Dictionary values dictate recursively embedded dictionary templates.""" - if root == None: root = self.root - for key, val in template.items(): - name = os.path.join(root, key) - if type(val) == types.StringType: # flat file - self.createFile(name, val) - elif type(val) == types.DictionaryType: # embedded dir - self.createDir(name) - self.add(val, name) - else: - raise ValueError, ('invalid file-value type, %s' % # ==X - type(val)) - def remove(self, name=''): - """Dispose of the NAME (or keys in dictionary), using 'rm -r'.""" - name = os.path.join(self.root, name) - sys.exc_traceback = None # Ensure Discard of try/except obj ref - if os.path.exists(name): - print '(TestDirHier: eradicating %s)' % name - os.system('rm -r ' + name) - else: - raise IOError, "can't remove non-existent " + name # ==X - def createFile(self, name, contents=None): - """Establish file NAME with CONTENTS. - - If no contents specfied, contents will be 'print NAME'.""" - f = open(name, 'w') - if not contents: - f.write("print '" + name + "'\n") - else: - f.write(contents) - f.close - def createDir(self, name): - """Create dir with NAME.""" - return os.mkdir(name, 0755) - -skipToTest = 0 -atTest = 1 -def testExec(msg, execList, locals, globals): - global skipToTest, atTest - print 'Import Test:', '(' + str(atTest) + ')', msg, '...' - atTest = atTest + 1 - if skipToTest > (atTest - 1): - print ' ... skipping til test', skipToTest - return - else: - print '' - for stmt in execList: - exec stmt in locals, globals - -def test(number=0, leaveHiers=0): - """Exercise import functionality, creating a transient dir hierarchy for - the purpose. - - We actually install the new import functionality, temporarily, resuming the - existing function on cleanup.""" - - import __builtin__ - - global skipToTest, atTest - skipToTest = number - hier = None - - def unloadFull(mod): - """Unload module and offspring submodules, if any.""" - modMod = '' - if type(mod) == types.StringType: - modNm = mod - elif type(mod) == types.ModuleType: - modNm = modMod.__name__ - for subj in sys.modules.keys() + sys.stub_modules.keys(): - if subj[0:len(modNm)] == modNm: - unload(subj) - - try: - __main__.testMods - except AttributeError: - __main__.testMods = [] - testMods = __main__.testMods - - - # Install the newimp routines, within a try/finally: - try: - sys.exc_traceback = None - wasImport = __builtin__.__import__ # Stash default - wasPath = sys.path - except AttributeError: - wasImport = None - try: - hiers = []; modules = [] - global VERBOSE - wasVerbose, VERBOSE = VERBOSE, 1 - __builtin__.__import__ = import_module # Install new version - - if testMods: # Clear out imports from previous tests - for m in testMods[:]: - unloadFull(m) - testMods.remove(m) - - # ------ - # Test 1 - testExec("already imported module: %s" % sys.modules.keys()[0], - ['import ' + sys.modules.keys()[0]], - vars(), newimp_globals) - no_sirree = 'no_sirree_does_not_exist' - # ------ - # Test 2 - testExec("non-existent module: %s" % no_sirree, - ['try: import ' + no_sirree + - '\nexcept ImportError: pass'], - vars(), newimp_globals) - got = None - - # ------ - # Test 3 - # Find a module that's not yet loaded, from a list of prospects: - for mod in ['Complex', 'UserDict', 'UserList', 'calendar', - 'cmd', 'dis', 'mailbox', 'profile', 'random', 'rfc822']: - if not (mod in sys.modules.keys()): - got = mod - break # ==v - if got: - testExec("not-yet loaded module: %s" % mod, - ['import ' + mod, 'modules.append(got)'], - vars(), newimp_globals) - else: - testExec("not-yet loaded module: list exhausted, never mind", - [], vars(), newimp_globals) - - # Now some package stuff. - - # ------ - # Test 4 - # First change the path to include our temp dir, copying so the - # addition can be revoked on cleanup in the finally, below: - sys.path = ['/var/tmp'] + sys.path[:] - # Now create a trivial package: - stmts = ["hier1 = TestDirHier({'a.py': 'print \"a.py executing\"'})", - "hiers.append(hier1)", - "base = hier1.PKG_NM", - "exec 'import ' + base", - "testMods.append(base)"] - testExec("trivial package, with one module, a.py", - stmts, vars(), newimp_globals) - - # ------ - # Test 5 - # Slightly less trivial package - reference to '__': - stmts = [("hier2 = TestDirHier({'ref.py': 'print \"Pkg __:\", __'})"), - "base = hier2.PKG_NM", - "hiers.append(hier2)", - "exec 'import ' + base", - "testMods.append(base)"] - testExec("trivial package, with module that has pkg shorthand ref", - stmts, vars(), newimp_globals) - - # ------ - # Test 6 - # Nested package, plus '__' references: - - complexTemplate = {'ref.py': 'print "ref.py loading..."', - 'suite': {'s1.py': 'print "s1.py, in pkg:", __', - 'subsuite': {'sub1.py': - 'print "sub1.py"'}}} - stmts = [('print """%s\n%s\n%s\n%s\n%s\n%s"""' % - ('.../', - ' ref.py\t\t\t"ref.py loading..."', - ' suite/', - ' s1.py \t\t"s1.py, in pkg: xxxx.suite"', - ' subsuite/', - ' sub1.py "sub1.py" ')), - "hier3 = TestDirHier(complexTemplate)", - "base = hier3.PKG_NM", - "hiers.append(hier3)", - "exec 'import ' + base", - "testMods.append(base)"] - testExec("Significantly nestled package:", - stmts, vars(), newimp_globals) - - # ------ - # Test 7 - # Try an elaborate hierarchy which includes an __init__ master in one - # one portion, a ref across packages within the hierarchies, and an - # indirect recursive import which cannot be satisfied (and hence, - # prevents load of part of the hierarchy). - complexTemplate = {'mid': - {'prime': - {'__init__.py': 'import __.easy, __.nother', - 'easy.py': 'print "easy.py:", __name__', - 'nother.py': ('%s\n%s\n%s\n' % - ('import __.easy', - 'print "nother got __.easy"', - # __.__.awry should be found but - # should not load successfully, - # disrupting nother, but not easy - 'import __.__.awry'))}, - # continuing dict 'mid': - 'awry': - {'__init__.py': - ('%s\n%s' % - ('print "got " + __name__', - 'from __ import *')), - # This mutual recursion (b->a, a->d->b) should be - # ok, since a.py sets ax before recursing. - 'a.py': 'ax = 1; from __.b import bx', - 'b.py': 'bx = 1; from __.a import ax'}}} - stmts = ["hier5 = TestDirHier(complexTemplate)", - "base = hier5.PKG_NM", - "testMods.append(base)", - "hiers.append(hier5)", - "exec 'import %s.mid.prime' % base", - "print eval(base)", # Verify the base was bound - "testMods.append(base)"] - testExec("Elaborate, clean hierarchy", - stmts, vars(), newimp_globals) - - # ------ - # test 8 - # Here we disrupt the mutual recursion in the mid.awry package, so the - # import should now fail. - complexTemplate['mid']['awry']['a.py'] = 'from __.b import bx; ax = 1' - complexTemplate['mid']['awry']['b.py'] = 'from __.a import ax; bx = 1' - stmts = ["hier6 = TestDirHier(complexTemplate)", - "base = hier6.PKG_NM", - "testMods.append(base)", - "hiers.append(hier6)", - "work = ('import %s.mid.prime' % base)", - ("try: exec work" + - "\nexcept ImportError: print ' -- import failed, as ought'" + - "\nelse: raise SystemError, sys.exc_value"), - "testMods.append(base)"] - testExec("Elaborate hier w/ deliberately flawed import recursion", - stmts, vars(), newimp_globals) - - sys.exc_traceback = None # Signify clean conclusion. - - finally: - skipToTest = 0 - atTest = 1 - sys.path = wasPath - VERBOSE = wasVerbose - if wasImport: # Resurrect prior routine - __builtin__.__import__ = wasImport - else: - del __builtin__.__import__ - if leaveHiers: - print 'Cleanup inhibited' - else: - if sys.exc_traceback: - print ' ** Import test FAILURE... cleanup.' - else: - print ' Import test SUCCESS... cleanup' - for h in hiers: h.remove(); del h # Dispose of test directories - -init() - -if __name__ == '__main__': - test() diff --git a/Lib/ni.py b/Lib/ni.py deleted file mode 100644 index fae23a9b92..0000000000 --- a/Lib/ni.py +++ /dev/null @@ -1,435 +0,0 @@ -"""New import scheme with package support. - -Quick Reference ---------------- - -- To enable package support, execute "import ni" before importing any - packages. Importing this module automatically installs the relevant - import hooks. - -- To create a package named spam containing sub-modules ham, bacon and - eggs, create a directory spam somewhere on Python's module search - path (i.e. spam's parent directory must be one of the directories in - sys.path or $PYTHONPATH); then create files ham.py, bacon.py and - eggs.py inside spam. - -- To import module ham from package spam and use function hamneggs() - from that module, you can either do - - import spam.ham # *not* "import spam" !!! - spam.ham.hamneggs() - - or - - from spam import ham - ham.hamneggs() - - or - - from spam.ham import hamneggs - hamneggs() - -- Importing just "spam" does not do what you expect: it creates an - empty package named spam if one does not already exist, but it does - not import spam's submodules. The only submodule that is guaranteed - to be imported is spam.__init__, if it exists. Note that - spam.__init__ is a submodule of package spam. It can reference to - spam's namespace via the '__.' prefix, for instance - - __.spam_inited = 1 # Set a package-level variable - - - -Theory of Operation -------------------- - -A Package is a module that can contain other modules. Packages can be -nested. Package introduce dotted names for modules, like P.Q.M, which -could correspond to a file P/Q/M.py found somewhere on sys.path. It -is possible to import a package itself, though this makes little sense -unless the package contains a module called __init__. - -A package has two variables that control the namespace used for -packages and modules, both initialized to sensible defaults the first -time the package is referenced. - -(1) A package's *module search path*, contained in the per-package -variable __path__, defines a list of *directories* where submodules or -subpackages of the package are searched. It is initialized to the -directory containing the package. Setting this variable to None makes -the module search path default to sys.path (this is not quite the same -as setting it to sys.path, since the latter won't track later -assignments to sys.path). - -(2) A package's *import domain*, contained in the per-package variable -__domain__, defines a list of *packages* that are searched (using -their respective module search paths) to satisfy imports. It is -initialized to the list cosisting of the package itself, its parent -package, its parent's parent, and so on, ending with the root package -(the nameless package containing all top-level packages and modules, -whose module search path is None, implying sys.path). - -The default domain implements a search algorithm called "expanding -search". An alternative search algorithm called "explicit search" -fixes the import search path to contain only the root package, -requiring the modules in the package to name all imported modules by -their full name. The convention of using '__' to refer to the current -package (both as a per-module variable and in module names) can be -used by packages using explicit search to refer to modules in the same -package; this combination is known as "explicit-relative search". - -The PackageImporter and PackageLoader classes together implement the -following policies: - -- There is a root package, whose name is ''. It cannot be imported - directly but may be referenced, e.g. by using '__' from a top-level - module. - -- In each module or package, the variable '__' contains a reference to - the parent package; in the root package, '__' points to itself. - -- In the name for imported modules (e.g. M in "import M" or "from M - import ..."), a leading '__' refers to the current package (i.e. - the package containing the current module); leading '__.__' and so - on refer to the current package's parent, and so on. The use of - '__' elsewhere in the module name is not supported. - -- Modules are searched using the "expanding search" algorithm by - virtue of the default value for __domain__. - -- If A.B.C is imported, A is searched using __domain__; then - subpackage B is searched in A using its __path__, and so on. - -- Built-in modules have priority: even if a file sys.py exists in a - package, "import sys" imports the built-in sys module. - -- The same holds for frozen modules, for better or for worse. - -- Submodules and subpackages are not automatically loaded when their - parent packages is loaded. - -- The construct "from package import *" is illegal. (It can still be - used to import names from a module.) - -- When "from package import module1, module2, ..." is used, those - modules are explicitly loaded. - -- When a package is loaded, if it has a submodule __init__, that - module is loaded. This is the place where required submodules can - be loaded, the __path__ variable extended, etc. The __init__ module - is loaded even if the package was loaded only in order to create a - stub for a sub-package: if "import P.Q.R" is the first reference to - P, and P has a submodule __init__, P.__init__ is loaded before P.Q - is even searched. - -Caveats: - -- It is possible to import a package that has no __init__ submodule; - this is not particularly useful but there may be useful applications - for it (e.g. to manipulate its search paths from the outside!). - -- There are no special provisions for os.chdir(). If you plan to use - os.chdir() before you have imported all your modules, it is better - not to have relative pathnames in sys.path. (This could actually be - fixed by changing the implementation of path_join() in the hook to - absolutize paths.) - -- Packages and modules are introduced in sys.modules as soon as their - loading is started. When the loading is terminated by an exception, - the sys.modules entries remain around. - -- There are no special measures to support mutually recursive modules, - but it will work under the same conditions where it works in the - flat module space system. - -- Sometimes dummy entries (whose value is None) are entered in - sys.modules, to indicate that a particular module does not exist -- - this is done to speed up the expanding search algorithm when a - module residing at a higher level is repeatedly imported (Python - promises that importing a previously imported module is cheap!) - -- Although dynamically loaded extensions are allowed inside packages, - the current implementation (hardcoded in the interpreter) of their - initialization may cause problems if an extension invokes the - interpreter during its initialization. - -- reload() may find another version of the module only if it occurs on - the package search path. Thus, it keeps the connection to the - package to which the module belongs, but may find a different file. - -XXX Need to have an explicit name for '', e.g. '__root__'. - -""" - - -import imp -import string -import sys -import __builtin__ - -import ihooks -from ihooks import ModuleLoader, ModuleImporter - - -class PackageLoader(ModuleLoader): - - """A subclass of ModuleLoader with package support. - - find_module_in_dir() will succeed if there's a subdirectory with - the given name; load_module() will create a stub for a package and - load its __init__ module if it exists. - - """ - - def find_module_in_dir(self, name, dir): - if dir is not None: - dirname = self.hooks.path_join(dir, name) - if self.hooks.path_isdir(dirname): - return None, dirname, ('', '', 'PACKAGE') - return ModuleLoader.find_module_in_dir(self, name, dir) - - def load_module(self, name, stuff): - file, filename, info = stuff - suff, mode, type = info - if type == 'PACKAGE': - return self.load_package(name, stuff) - if sys.modules.has_key(name): - m = sys.modules[name] - else: - sys.modules[name] = m = imp.new_module(name) - self.set_parent(m) - if type == imp.C_EXTENSION and '.' in name: - return self.load_dynamic(name, stuff) - else: - return ModuleLoader.load_module(self, name, stuff) - - def load_dynamic(self, name, stuff): - file, filename, (suff, mode, type) = stuff - # Hack around restriction in imp.load_dynamic() - i = string.rfind(name, '.') - tail = name[i+1:] - if sys.modules.has_key(tail): - save = sys.modules[tail] - else: - save = None - sys.modules[tail] = imp.new_module(name) - try: - m = imp.load_dynamic(tail, filename, file) - finally: - if save: - sys.modules[tail] = save - else: - del sys.modules[tail] - sys.modules[name] = m - return m - - def load_package(self, name, stuff): - file, filename, info = stuff - if sys.modules.has_key(name): - package = sys.modules[name] - else: - sys.modules[name] = package = imp.new_module(name) - package.__path__ = [filename] - self.init_package(package) - return package - - def init_package(self, package): - self.set_parent(package) - self.set_domain(package) - self.call_init_module(package) - - def set_parent(self, m): - name = m.__name__ - if '.' in name: - name = name[:string.rfind(name, '.')] - else: - name = '' - m.__ = sys.modules[name] - - def set_domain(self, package): - name = package.__name__ - package.__domain__ = domain = [name] - while '.' in name: - name = name[:string.rfind(name, '.')] - domain.append(name) - if name: - domain.append('') - - def call_init_module(self, package): - stuff = self.find_module('__init__', package.__path__) - if stuff: - m = self.load_module(package.__name__ + '.__init__', stuff) - package.__init__ = m - - -class PackageImporter(ModuleImporter): - - """Importer that understands packages and '__'.""" - - def __init__(self, loader = None, verbose = 0): - ModuleImporter.__init__(self, - loader or PackageLoader(None, verbose), verbose) - - def import_module(self, name, globals={}, locals={}, fromlist=[]): - if globals.has_key('__'): - package = globals['__'] - else: - # No calling context, assume in root package - package = sys.modules[''] - if name[:3] in ('__.', '__'): - p = package - name = name[3:] - while name[:3] in ('__.', '__'): - p = package.__ - name = name[3:] - if not name: - return self.finish(package, p, '', fromlist) - if '.' in name: - i = string.find(name, '.') - name, tail = name[:i], name[i:] - else: - tail = '' - mname = p.__name__ and p.__name__+'.'+name or name - m = self.get1(mname) - return self.finish(package, m, tail, fromlist) - if '.' in name: - i = string.find(name, '.') - name, tail = name[:i], name[i:] - else: - tail = '' - for pname in package.__domain__: - mname = pname and pname+'.'+name or name - m = self.get0(mname) - if m: break - else: - raise ImportError, "No such module %s" % name - return self.finish(m, m, tail, fromlist) - - def finish(self, module, m, tail, fromlist): - # Got ....A; now get ....A.B.C.D - yname = m.__name__ - if tail and sys.modules.has_key(yname + tail): # Fast path - yname, tail = yname + tail, '' - m = self.get1(yname) - while tail: - i = string.find(tail, '.', 1) - if i > 0: - head, tail = tail[:i], tail[i:] - else: - head, tail = tail, '' - yname = yname + head - m = self.get1(yname) - - # Got ....A.B.C.D; now finalize things depending on fromlist - if not fromlist: - return module - if '__' in fromlist: - raise ImportError, "Can't import __ from anywhere" - if not hasattr(m, '__path__'): return m - if '*' in fromlist: - raise ImportError, "Can't import * from a package" - for f in fromlist: - if hasattr(m, f): continue - fname = yname + '.' + f - self.get1(fname) - return m - - def get1(self, name): - m = self.get(name) - if not m: - raise ImportError, "No module named %s" % name - return m - - def get0(self, name): - m = self.get(name) - if not m: - sys.modules[name] = None - return m - - def get(self, name): - # Internal routine to get or load a module when its parent exists - if sys.modules.has_key(name): - return sys.modules[name] - if '.' in name: - i = string.rfind(name, '.') - head, tail = name[:i], name[i+1:] - else: - head, tail = '', name - path = sys.modules[head].__path__ - stuff = self.loader.find_module(tail, path) - if not stuff: - return None - sys.modules[name] = m = self.loader.load_module(name, stuff) - if head: - setattr(sys.modules[head], tail, m) - return m - - def reload(self, module): - name = module.__name__ - if '.' in name: - i = string.rfind(name, '.') - head, tail = name[:i], name[i+1:] - path = sys.modules[head].__path__ - else: - tail = name - path = sys.modules[''].__path__ - stuff = self.loader.find_module(tail, path) - if not stuff: - raise ImportError, "No module named %s" % name - return self.loader.load_module(name, stuff) - - def unload(self, module): - if hasattr(module, '__path__'): - raise ImportError, "don't know how to unload packages yet" - PackageImporter.unload(self, module) - - def install(self): - if not sys.modules.has_key(''): - sys.modules[''] = package = imp.new_module('') - package.__path__ = None - self.loader.init_package(package) - for m in sys.modules.values(): - if not m: continue - if not hasattr(m, '__'): - self.loader.set_parent(m) - ModuleImporter.install(self) - - -def install(v = 0): - ihooks.install(PackageImporter(None, v)) - -def uninstall(): - ihooks.uninstall() - -def ni(v = 0): - install(v) - -def no(): - uninstall() - -def test(): - import pdb - try: - testproper() - except: - sys.last_type, sys.last_value, sys.last_traceback = ( - sys.exc_type, sys.exc_value, sys.exc_traceback) - print - print sys.last_type, ':', sys.last_value - print - pdb.pm() - -def testproper(): - install(1) - try: - import mactest - print dir(mactest) - raw_input('OK?') - finally: - uninstall() - - -if __name__ == '__main__': - test() -else: - install() diff --git a/Lib/ni1.py b/Lib/ni1.py deleted file mode 100644 index fae23a9b92..0000000000 --- a/Lib/ni1.py +++ /dev/null @@ -1,435 +0,0 @@ -"""New import scheme with package support. - -Quick Reference ---------------- - -- To enable package support, execute "import ni" before importing any - packages. Importing this module automatically installs the relevant - import hooks. - -- To create a package named spam containing sub-modules ham, bacon and - eggs, create a directory spam somewhere on Python's module search - path (i.e. spam's parent directory must be one of the directories in - sys.path or $PYTHONPATH); then create files ham.py, bacon.py and - eggs.py inside spam. - -- To import module ham from package spam and use function hamneggs() - from that module, you can either do - - import spam.ham # *not* "import spam" !!! - spam.ham.hamneggs() - - or - - from spam import ham - ham.hamneggs() - - or - - from spam.ham import hamneggs - hamneggs() - -- Importing just "spam" does not do what you expect: it creates an - empty package named spam if one does not already exist, but it does - not import spam's submodules. The only submodule that is guaranteed - to be imported is spam.__init__, if it exists. Note that - spam.__init__ is a submodule of package spam. It can reference to - spam's namespace via the '__.' prefix, for instance - - __.spam_inited = 1 # Set a package-level variable - - - -Theory of Operation -------------------- - -A Package is a module that can contain other modules. Packages can be -nested. Package introduce dotted names for modules, like P.Q.M, which -could correspond to a file P/Q/M.py found somewhere on sys.path. It -is possible to import a package itself, though this makes little sense -unless the package contains a module called __init__. - -A package has two variables that control the namespace used for -packages and modules, both initialized to sensible defaults the first -time the package is referenced. - -(1) A package's *module search path*, contained in the per-package -variable __path__, defines a list of *directories* where submodules or -subpackages of the package are searched. It is initialized to the -directory containing the package. Setting this variable to None makes -the module search path default to sys.path (this is not quite the same -as setting it to sys.path, since the latter won't track later -assignments to sys.path). - -(2) A package's *import domain*, contained in the per-package variable -__domain__, defines a list of *packages* that are searched (using -their respective module search paths) to satisfy imports. It is -initialized to the list cosisting of the package itself, its parent -package, its parent's parent, and so on, ending with the root package -(the nameless package containing all top-level packages and modules, -whose module search path is None, implying sys.path). - -The default domain implements a search algorithm called "expanding -search". An alternative search algorithm called "explicit search" -fixes the import search path to contain only the root package, -requiring the modules in the package to name all imported modules by -their full name. The convention of using '__' to refer to the current -package (both as a per-module variable and in module names) can be -used by packages using explicit search to refer to modules in the same -package; this combination is known as "explicit-relative search". - -The PackageImporter and PackageLoader classes together implement the -following policies: - -- There is a root package, whose name is ''. It cannot be imported - directly but may be referenced, e.g. by using '__' from a top-level - module. - -- In each module or package, the variable '__' contains a reference to - the parent package; in the root package, '__' points to itself. - -- In the name for imported modules (e.g. M in "import M" or "from M - import ..."), a leading '__' refers to the current package (i.e. - the package containing the current module); leading '__.__' and so - on refer to the current package's parent, and so on. The use of - '__' elsewhere in the module name is not supported. - -- Modules are searched using the "expanding search" algorithm by - virtue of the default value for __domain__. - -- If A.B.C is imported, A is searched using __domain__; then - subpackage B is searched in A using its __path__, and so on. - -- Built-in modules have priority: even if a file sys.py exists in a - package, "import sys" imports the built-in sys module. - -- The same holds for frozen modules, for better or for worse. - -- Submodules and subpackages are not automatically loaded when their - parent packages is loaded. - -- The construct "from package import *" is illegal. (It can still be - used to import names from a module.) - -- When "from package import module1, module2, ..." is used, those - modules are explicitly loaded. - -- When a package is loaded, if it has a submodule __init__, that - module is loaded. This is the place where required submodules can - be loaded, the __path__ variable extended, etc. The __init__ module - is loaded even if the package was loaded only in order to create a - stub for a sub-package: if "import P.Q.R" is the first reference to - P, and P has a submodule __init__, P.__init__ is loaded before P.Q - is even searched. - -Caveats: - -- It is possible to import a package that has no __init__ submodule; - this is not particularly useful but there may be useful applications - for it (e.g. to manipulate its search paths from the outside!). - -- There are no special provisions for os.chdir(). If you plan to use - os.chdir() before you have imported all your modules, it is better - not to have relative pathnames in sys.path. (This could actually be - fixed by changing the implementation of path_join() in the hook to - absolutize paths.) - -- Packages and modules are introduced in sys.modules as soon as their - loading is started. When the loading is terminated by an exception, - the sys.modules entries remain around. - -- There are no special measures to support mutually recursive modules, - but it will work under the same conditions where it works in the - flat module space system. - -- Sometimes dummy entries (whose value is None) are entered in - sys.modules, to indicate that a particular module does not exist -- - this is done to speed up the expanding search algorithm when a - module residing at a higher level is repeatedly imported (Python - promises that importing a previously imported module is cheap!) - -- Although dynamically loaded extensions are allowed inside packages, - the current implementation (hardcoded in the interpreter) of their - initialization may cause problems if an extension invokes the - interpreter during its initialization. - -- reload() may find another version of the module only if it occurs on - the package search path. Thus, it keeps the connection to the - package to which the module belongs, but may find a different file. - -XXX Need to have an explicit name for '', e.g. '__root__'. - -""" - - -import imp -import string -import sys -import __builtin__ - -import ihooks -from ihooks import ModuleLoader, ModuleImporter - - -class PackageLoader(ModuleLoader): - - """A subclass of ModuleLoader with package support. - - find_module_in_dir() will succeed if there's a subdirectory with - the given name; load_module() will create a stub for a package and - load its __init__ module if it exists. - - """ - - def find_module_in_dir(self, name, dir): - if dir is not None: - dirname = self.hooks.path_join(dir, name) - if self.hooks.path_isdir(dirname): - return None, dirname, ('', '', 'PACKAGE') - return ModuleLoader.find_module_in_dir(self, name, dir) - - def load_module(self, name, stuff): - file, filename, info = stuff - suff, mode, type = info - if type == 'PACKAGE': - return self.load_package(name, stuff) - if sys.modules.has_key(name): - m = sys.modules[name] - else: - sys.modules[name] = m = imp.new_module(name) - self.set_parent(m) - if type == imp.C_EXTENSION and '.' in name: - return self.load_dynamic(name, stuff) - else: - return ModuleLoader.load_module(self, name, stuff) - - def load_dynamic(self, name, stuff): - file, filename, (suff, mode, type) = stuff - # Hack around restriction in imp.load_dynamic() - i = string.rfind(name, '.') - tail = name[i+1:] - if sys.modules.has_key(tail): - save = sys.modules[tail] - else: - save = None - sys.modules[tail] = imp.new_module(name) - try: - m = imp.load_dynamic(tail, filename, file) - finally: - if save: - sys.modules[tail] = save - else: - del sys.modules[tail] - sys.modules[name] = m - return m - - def load_package(self, name, stuff): - file, filename, info = stuff - if sys.modules.has_key(name): - package = sys.modules[name] - else: - sys.modules[name] = package = imp.new_module(name) - package.__path__ = [filename] - self.init_package(package) - return package - - def init_package(self, package): - self.set_parent(package) - self.set_domain(package) - self.call_init_module(package) - - def set_parent(self, m): - name = m.__name__ - if '.' in name: - name = name[:string.rfind(name, '.')] - else: - name = '' - m.__ = sys.modules[name] - - def set_domain(self, package): - name = package.__name__ - package.__domain__ = domain = [name] - while '.' in name: - name = name[:string.rfind(name, '.')] - domain.append(name) - if name: - domain.append('') - - def call_init_module(self, package): - stuff = self.find_module('__init__', package.__path__) - if stuff: - m = self.load_module(package.__name__ + '.__init__', stuff) - package.__init__ = m - - -class PackageImporter(ModuleImporter): - - """Importer that understands packages and '__'.""" - - def __init__(self, loader = None, verbose = 0): - ModuleImporter.__init__(self, - loader or PackageLoader(None, verbose), verbose) - - def import_module(self, name, globals={}, locals={}, fromlist=[]): - if globals.has_key('__'): - package = globals['__'] - else: - # No calling context, assume in root package - package = sys.modules[''] - if name[:3] in ('__.', '__'): - p = package - name = name[3:] - while name[:3] in ('__.', '__'): - p = package.__ - name = name[3:] - if not name: - return self.finish(package, p, '', fromlist) - if '.' in name: - i = string.find(name, '.') - name, tail = name[:i], name[i:] - else: - tail = '' - mname = p.__name__ and p.__name__+'.'+name or name - m = self.get1(mname) - return self.finish(package, m, tail, fromlist) - if '.' in name: - i = string.find(name, '.') - name, tail = name[:i], name[i:] - else: - tail = '' - for pname in package.__domain__: - mname = pname and pname+'.'+name or name - m = self.get0(mname) - if m: break - else: - raise ImportError, "No such module %s" % name - return self.finish(m, m, tail, fromlist) - - def finish(self, module, m, tail, fromlist): - # Got ....A; now get ....A.B.C.D - yname = m.__name__ - if tail and sys.modules.has_key(yname + tail): # Fast path - yname, tail = yname + tail, '' - m = self.get1(yname) - while tail: - i = string.find(tail, '.', 1) - if i > 0: - head, tail = tail[:i], tail[i:] - else: - head, tail = tail, '' - yname = yname + head - m = self.get1(yname) - - # Got ....A.B.C.D; now finalize things depending on fromlist - if not fromlist: - return module - if '__' in fromlist: - raise ImportError, "Can't import __ from anywhere" - if not hasattr(m, '__path__'): return m - if '*' in fromlist: - raise ImportError, "Can't import * from a package" - for f in fromlist: - if hasattr(m, f): continue - fname = yname + '.' + f - self.get1(fname) - return m - - def get1(self, name): - m = self.get(name) - if not m: - raise ImportError, "No module named %s" % name - return m - - def get0(self, name): - m = self.get(name) - if not m: - sys.modules[name] = None - return m - - def get(self, name): - # Internal routine to get or load a module when its parent exists - if sys.modules.has_key(name): - return sys.modules[name] - if '.' in name: - i = string.rfind(name, '.') - head, tail = name[:i], name[i+1:] - else: - head, tail = '', name - path = sys.modules[head].__path__ - stuff = self.loader.find_module(tail, path) - if not stuff: - return None - sys.modules[name] = m = self.loader.load_module(name, stuff) - if head: - setattr(sys.modules[head], tail, m) - return m - - def reload(self, module): - name = module.__name__ - if '.' in name: - i = string.rfind(name, '.') - head, tail = name[:i], name[i+1:] - path = sys.modules[head].__path__ - else: - tail = name - path = sys.modules[''].__path__ - stuff = self.loader.find_module(tail, path) - if not stuff: - raise ImportError, "No module named %s" % name - return self.loader.load_module(name, stuff) - - def unload(self, module): - if hasattr(module, '__path__'): - raise ImportError, "don't know how to unload packages yet" - PackageImporter.unload(self, module) - - def install(self): - if not sys.modules.has_key(''): - sys.modules[''] = package = imp.new_module('') - package.__path__ = None - self.loader.init_package(package) - for m in sys.modules.values(): - if not m: continue - if not hasattr(m, '__'): - self.loader.set_parent(m) - ModuleImporter.install(self) - - -def install(v = 0): - ihooks.install(PackageImporter(None, v)) - -def uninstall(): - ihooks.uninstall() - -def ni(v = 0): - install(v) - -def no(): - uninstall() - -def test(): - import pdb - try: - testproper() - except: - sys.last_type, sys.last_value, sys.last_traceback = ( - sys.exc_type, sys.exc_value, sys.exc_traceback) - print - print sys.last_type, ':', sys.last_value - print - pdb.pm() - -def testproper(): - install(1) - try: - import mactest - print dir(mactest) - raw_input('OK?') - finally: - uninstall() - - -if __name__ == '__main__': - test() -else: - install() diff --git a/Lib/nntplib.py b/Lib/nntplib.py deleted file mode 100644 index b6b395703d..0000000000 --- a/Lib/nntplib.py +++ /dev/null @@ -1,448 +0,0 @@ -# An NNTP client class. Based on RFC 977: Network News Transfer -# Protocol, by Brian Kantor and Phil Lapsley. - - -# Example: -# -# >>> from nntplib import NNTP -# >>> s = NNTP('news') -# >>> resp, count, first, last, name = s.group('comp.lang.python') -# >>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last -# Group comp.lang.python has 51 articles, range 5770 to 5821 -# >>> resp, subs = s.xhdr('subject', first + '-' + last) -# >>> resp = s.quit() -# >>> -# -# Here 'resp' is the server response line. -# Error responses are turned into exceptions. -# -# To post an article from a file: -# >>> f = open(filename, 'r') # file containing article, including header -# >>> resp = s.post(f) -# >>> -# -# For descriptions of all methods, read the comments in the code below. -# Note that all arguments and return values representing article numbers -# are strings, not numbers, since they are rarely used for calculations. - -# (xover, xgtitle, xpath, date methods by Kevan Heydon) - - -# Imports -import regex -import socket -import string - - -# Exception raised when an error or invalid response is received - -error_reply = 'nntplib.error_reply' # unexpected [123]xx reply -error_temp = 'nntplib.error_temp' # 4xx errors -error_perm = 'nntplib.error_perm' # 5xx errors -error_proto = 'nntplib.error_proto' # response does not begin with [1-5] -error_data = 'nntplib.error_data' # error in response data - - -# Standard port used by NNTP servers -NNTP_PORT = 119 - - -# Response numbers that are followed by additional text (e.g. article) -LONGRESP = ['100', '215', '220', '221', '222', '224', '230', '231', '282'] - - -# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF) -CRLF = '\r\n' - - -# The class itself - -class NNTP: - - # Initialize an instance. Arguments: - # - host: hostname to connect to - # - port: port to connect to (default the standard NNTP port) - - def __init__(self, host, port = NNTP_PORT): - self.host = host - self.port = port - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.sock.connect(self.host, self.port) - self.file = self.sock.makefile('rb') - self.debugging = 0 - self.welcome = self.getresp() - - # Get the welcome message from the server - # (this is read and squirreled away by __init__()). - # If the response code is 200, posting is allowed; - # if it 201, posting is not allowed - - def getwelcome(self): - if self.debugging: print '*welcome*', `self.welcome` - return self.welcome - - # Set the debugging level. Argument level means: - # 0: no debugging output (default) - # 1: print commands and responses but not body text etc. - # 2: also print raw lines read and sent before stripping CR/LF - - def set_debuglevel(self, level): - self.debugging = level - debug = set_debuglevel - - # Internal: send one line to the server, appending CRLF - def putline(self, line): - line = line + CRLF - if self.debugging > 1: print '*put*', `line` - self.sock.send(line) - - # Internal: send one command to the server (through putline()) - def putcmd(self, line): - if self.debugging: print '*cmd*', `line` - self.putline(line) - - # Internal: return one line from the server, stripping CRLF. - # Raise EOFError if the connection is closed - def getline(self): - line = self.file.readline() - if self.debugging > 1: - print '*get*', `line` - if not line: raise EOFError - if line[-2:] == CRLF: line = line[:-2] - elif line[-1:] in CRLF: line = line[:-1] - return line - - # Internal: get a response from the server. - # Raise various errors if the response indicates an error - def getresp(self): - resp = self.getline() - if self.debugging: print '*resp*', `resp` - c = resp[:1] - if c == '4': - raise error_temp, resp - if c == '5': - raise error_perm, resp - if c not in '123': - raise error_proto, resp - return resp - - # Internal: get a response plus following text from the server. - # Raise various errors if the response indicates an error - def getlongresp(self): - resp = self.getresp() - if resp[:3] not in LONGRESP: - raise error_reply, resp - list = [] - while 1: - line = self.getline() - if line == '.': - break - list.append(line) - return resp, list - - # Internal: send a command and get the response - def shortcmd(self, line): - self.putcmd(line) - return self.getresp() - - # Internal: send a command and get the response plus following text - def longcmd(self, line): - self.putcmd(line) - return self.getlongresp() - - # Process a NEWGROUPS command. Arguments: - # - date: string 'yymmdd' indicating the date - # - time: string 'hhmmss' indicating the time - # Return: - # - resp: server response if succesful - # - list: list of newsgroup names - - def newgroups(self, date, time): - return self.longcmd('NEWGROUPS ' + date + ' ' + time) - - # Process a NEWNEWS command. Arguments: - # - group: group name or '*' - # - date: string 'yymmdd' indicating the date - # - time: string 'hhmmss' indicating the time - # Return: - # - resp: server response if succesful - # - list: list of article ids - - def newnews(self, group, date, time): - cmd = 'NEWNEWS ' + group + ' ' + date + ' ' + time - return self.longcmd(cmd) - - # Process a LIST command. Return: - # - resp: server response if succesful - # - list: list of (group, last, first, flag) (strings) - - def list(self): - resp, list = self.longcmd('LIST') - for i in range(len(list)): - # Parse lines into "group last first flag" - list[i] = string.split(list[i]) - return resp, list - - # Process a GROUP command. Argument: - # - group: the group name - # Returns: - # - resp: server response if succesful - # - count: number of articles (string) - # - first: first article number (string) - # - last: last article number (string) - # - name: the group name - - def group(self, name): - resp = self.shortcmd('GROUP ' + name) - if resp[:3] <> '211': - raise error_reply, resp - words = string.split(resp) - count = first = last = 0 - n = len(words) - if n > 1: - count = words[1] - if n > 2: - first = words[2] - if n > 3: - last = words[3] - if n > 4: - name = string.lower(words[4]) - return resp, count, first, last, name - - # Process a HELP command. Returns: - # - resp: server response if succesful - # - list: list of strings - - def help(self): - return self.longcmd('HELP') - - # Internal: parse the response of a STAT, NEXT or LAST command - def statparse(self, resp): - if resp[:2] <> '22': - raise error_reply, resp - words = string.split(resp) - nr = 0 - id = '' - n = len(words) - if n > 1: - nr = words[1] - if n > 2: - id = string.lower(words[2]) - return resp, nr, id - - # Internal: process a STAT, NEXT or LAST command - def statcmd(self, line): - resp = self.shortcmd(line) - return self.statparse(resp) - - # Process a STAT command. Argument: - # - id: article number or message id - # Returns: - # - resp: server response if succesful - # - nr: the article number - # - id: the article id - - def stat(self, id): - return self.statcmd('STAT ' + id) - - # Process a NEXT command. No arguments. Return as for STAT - - def next(self): - return self.statcmd('NEXT') - - # Process a LAST command. No arguments. Return as for STAT - - def last(self): - return self.statcmd('LAST') - - # Internal: process a HEAD, BODY or ARTICLE command - def artcmd(self, line): - resp, list = self.longcmd(line) - resp, nr, id = self.statparse(resp) - return resp, nr, id, list - - # Process a HEAD command. Argument: - # - id: article number or message id - # Returns: - # - resp: server response if succesful - # - list: the lines of the article's header - - def head(self, id): - return self.artcmd('HEAD ' + id) - - # Process a BODY command. Argument: - # - id: article number or message id - # Returns: - # - resp: server response if succesful - # - list: the lines of the article's body - - def body(self, id): - return self.artcmd('BODY ' + id) - - # Process an ARTICLE command. Argument: - # - id: article number or message id - # Returns: - # - resp: server response if succesful - # - list: the lines of the article - - def article(self, id): - return self.artcmd('ARTICLE ' + id) - - # Process a SLAVE command. Returns: - # - resp: server response if succesful - - def slave(self): - return self.shortcmd('SLAVE') - - # Process an XHDR command (optional server extension). Arguments: - # - hdr: the header type (e.g. 'subject') - # - str: an article nr, a message id, or a range nr1-nr2 - # Returns: - # - resp: server response if succesful - # - list: list of (nr, value) strings - - def xhdr(self, hdr, str): - resp, lines = self.longcmd('XHDR ' + hdr + ' ' + str) - for i in range(len(lines)): - line = lines[i] - n = regex.match('^[0-9]+', line) - nr = line[:n] - if n < len(line) and line[n] == ' ': n = n+1 - lines[i] = (nr, line[n:]) - return resp, lines - - # Process an XOVER command (optional server extension) Arguments: - # - start: start of range - # - end: end of range - # Returns: - # - resp: server response if succesful - # - list: list of (art-nr, subject, poster, date, id, refrences, size, lines) - - def xover(self,start,end): - resp, lines = self.longcmd('XOVER ' + start + '-' + end) - xover_lines = [] - for line in lines: - elem = string.splitfields(line,"\t") - try: - xover_lines.append(elem[0], - elem[1], - elem[2], - elem[3], - elem[4], - elem[5:-2], - elem[-2], - elem[-1]) - except IndexError: - raise error_data,line - return resp,xover_lines - - # Process an XGTITLE command (optional server extension) Arguments: - # - group: group name wildcard (i.e. news.*) - # Returns: - # - resp: server response if succesful - # - list: list of (name,title) strings - - def xgtitle(self, group): - line_pat = regex.compile("^\([^ \t]+\)[ \t]+\(.*\)$") - resp, raw_lines = self.longcmd('XGTITLE ' + group) - lines = [] - for raw_line in raw_lines: - if line_pat.search(string.strip(raw_line)) == 0: - lines.append(line_pat.group(1), - line_pat.group(2)) - - return resp, lines - - # Process an XPATH command (optional server extension) Arguments: - # - id: Message id of article - # Returns: - # resp: server response if succesful - # path: directory path to article - - def xpath(self,id): - resp = self.shortcmd("XPATH " + id) - if resp[:3] <> '223': - raise error_reply, resp - try: - [resp_num, path] = string.split(resp) - except ValueError: - raise error_reply, resp - else: - return resp, path - - # Process the DATE command. Arguments: - # None - # Returns: - # resp: server response if succesful - # date: Date suitable for newnews/newgroups commands etc. - # time: Time suitable for newnews/newgroups commands etc. - - def date (self): - resp = self.shortcmd("DATE") - if resp[:3] <> '111': - raise error_reply, resp - elem = string.split(resp) - if len(elem) != 2: - raise error_data, resp - date = elem[1][2:8] - time = elem[1][-6:] - if len(date) != 6 or len(time) != 6: - raise error_data, resp - return resp, date, time - - - # Process a POST command. Arguments: - # - f: file containing the article - # Returns: - # - resp: server response if succesful - - def post(self, f): - resp = self.shortcmd('POST') - # Raises error_??? if posting is not allowed - if resp[0] <> '3': - raise error_reply, resp - while 1: - line = f.readline() - if not line: - break - if line[-1] == '\n': - line = line[:-1] - if line == '.': - line = '..' - self.putline(line) - self.putline('.') - return self.getresp() - - # Process an IHAVE command. Arguments: - # - id: message-id of the article - # - f: file containing the article - # Returns: - # - resp: server response if succesful - # Note that if the server refuses the article an exception is raised - - def ihave(self, id, f): - resp = self.shortcmd('IHAVE ' + id) - # Raises error_??? if the server already has it - if resp[0] <> '3': - raise error_reply, resp - while 1: - line = f.readline() - if not line: - break - if line[-1] == '\n': - line = line[:-1] - if line == '.': - line = '..' - self.putline(line) - self.putline('.') - return self.getresp() - - # Process a QUIT command and close the socket. Returns: - # - resp: server response if succesful - - def quit(self): - resp = self.shortcmd('QUIT') - self.file.close() - self.sock.close() - del self.file, self.sock - return resp diff --git a/Lib/ntpath.py b/Lib/ntpath.py deleted file mode 100644 index 1109d44811..0000000000 --- a/Lib/ntpath.py +++ /dev/null @@ -1,347 +0,0 @@ -# Module 'ntpath' -- common operations on DOS pathnames - -import os -import stat -import string - - -# Normalize the case of a pathname. -# On MS-DOS it maps the pathname to lowercase, turns slashes into -# backslashes. -# Other normalizations (such as optimizing '../' away) are not allowed -# (this is done by normpath). -# Previously, this version mapped invalid consecutive characters to a -# single '_', but this has been removed. This functionality should -# possibly be added as a new function. - -def normcase(s): - res, s = splitdrive(s) - for c in s: - if c in '/\\': - res = res + os.sep - else: - res = res + c - return string.lower(res) - -# Return wheter a path is absolute. -# Trivial in Posix, harder on the Mac or MS-DOS. -# For DOS it is absolute if it starts with a slash or backslash (current -# volume), or if a pathname after the volume letter and colon starts with -# a slash or backslash. - -def isabs(s): - s = splitdrive(s)[1] - return s != '' and s[:1] in '/\\' - - -# Join two pathnames. -# Ignore the first part if the second part is absolute. -# Insert a '/' unless the first part is empty or already ends in '/'. - -def join(a, b): - if isabs(b): return b - if a == '' or a[-1:] in '/\\': return a + b - # Note: join('x', '') returns 'x/'; is this what we want? - return a + os.sep + b - - -# Split a path in a drive specification (a drive letter followed by a -# colon) and the path specification. -# It is always true that drivespec + pathspec == p -def splitdrive(p): - if p[1:2] == ':': - return p[0:2], p[2:] - return '', p - - -# Split a path in head (everything up to the last '/') and tail (the -# rest). If the original path ends in '/' but is not the root, this -# '/' is stripped. After the trailing '/' is stripped, the invariant -# join(head, tail) == p holds. -# The resulting head won't end in '/' unless it is the root. - -def split(p): - d, p = splitdrive(p) - slashes = '' - while p and p[-1:] in '/\\': - slashes = slashes + p[-1] - p = p[:-1] - if p == '': - p = p + slashes - head, tail = '', '' - for c in p: - tail = tail + c - if c in '/\\': - head, tail = head + tail, '' - slashes = '' - while head and head[-1:] in '/\\': - slashes = slashes + head[-1] - head = head[:-1] - if head == '': - head = head + slashes - return d + head, tail - - -# Split a path in root and extension. -# The extension is everything starting at the first dot in the last -# pathname component; the root is everything before that. -# It is always true that root + ext == p. - -def splitext(p): - root, ext = '', '' - for c in p: - if c in '/\\': - root, ext = root + ext + c, '' - elif c == '.' or ext: - ext = ext + c - else: - root = root + c - return root, ext - - -# Return the tail (basename) part of a path. - -def basename(p): - return split(p)[1] - - -# Return the head (dirname) part of a path. - -def dirname(p): - return split(p)[0] - - -# Return the longest prefix of all list elements. - -def commonprefix(m): - if not m: return '' - prefix = m[0] - for item in m: - for i in range(len(prefix)): - if prefix[:i+1] <> item[:i+1]: - prefix = prefix[:i] - if i == 0: return '' - break - return prefix - - -# Is a path a symbolic link? -# This will always return false on systems where posix.lstat doesn't exist. - -def islink(path): - return false - - -# Does a path exist? -# This is false for dangling symbolic links. - -def exists(path): - try: - st = os.stat(path) - except os.error: - return 0 - return 1 - - -# Is a path a dos directory? -# This follows symbolic links, so both islink() and isdir() can be true -# for the same path. - -def isdir(path): - try: - st = os.stat(path) - except os.error: - return 0 - return stat.S_ISDIR(st[stat.ST_MODE]) - - -# Is a path a regular file? -# This follows symbolic links, so both islink() and isdir() can be true -# for the same path. - -def isfile(path): - try: - st = os.stat(path) - except os.error: - return 0 - return stat.S_ISREG(st[stat.ST_MODE]) - - -# Are two filenames really pointing to the same file? - -def samefile(f1, f2): - s1 = os.stat(f1) - s2 = os.stat(f2) - return samestat(s1, s2) - - -# Are two open files really referencing the same file? -# (Not necessarily the same file descriptor!) -# XXX THIS IS BROKEN UNDER DOS! ST_INO seems to indicate number of reads? - -def sameopenfile(fp1, fp2): - s1 = os.fstat(fp1.fileno()) - s2 = os.fstat(fp2.fileno()) - return samestat(s1, s2) - - -# Are two stat buffers (obtained from stat, fstat or lstat) -# describing the same file? - -def samestat(s1, s2): - return s1[stat.ST_INO] == s2[stat.ST_INO] and \ - s1[stat.ST_DEV] == s2[stat.ST_DEV] - - -# Is a path a mount point? -# XXX This degenerates in: 'is this the root?' on DOS - -def ismount(path): - return isabs(splitdrive(path)[1]) - - -# Directory tree walk. -# For each directory under top (including top itself, but excluding -# '.' and '..'), func(arg, dirname, filenames) is called, where -# dirname is the name of the directory and filenames is the list -# files files (and subdirectories etc.) in the directory. -# The func may modify the filenames list, to implement a filter, -# or to impose a different order of visiting. - -def walk(top, func, arg): - try: - names = os.listdir(top) - except os.error: - return - func(arg, top, names) - exceptions = ('.', '..') - for name in names: - if name not in exceptions: - name = join(top, name) - if isdir(name): - walk(name, func, arg) - - -# Expand paths beginning with '~' or '~user'. -# '~' means $HOME; '~user' means that user's home directory. -# If the path doesn't begin with '~', or if the user or $HOME is unknown, -# the path is returned unchanged (leaving error reporting to whatever -# function is called with the expanded path as argument). -# See also module 'glob' for expansion of *, ? and [...] in pathnames. -# (A function should also be defined to do full *sh-style environment -# variable expansion.) - -def expanduser(path): - if path[:1] <> '~': - return path - i, n = 1, len(path) - while i < n and path[i] not in '/\\': - i = i+1 - if i == 1: - try: - drive=os.environ['HOMEDRIVE'] - except KeyError: - drive = '' - if not os.environ.has_key('HOMEPATH'): - return path - userhome = join(drive, os.environ['HOMEPATH']) - else: - return path - return userhome + path[i:] - - -# Expand paths containing shell variable substitutions. -# The following rules apply: -# - no expansion within single quotes -# - no escape character, except for '$$' which is translated into '$' -# - ${varname} is accepted. -# - varnames can be made out of letters, digits and the character '_' -# XXX With COMMAND.COM you can use any characters in a variable name, -# XXX except '^|<>='. - -varchars = string.letters + string.digits + '_-' - -def expandvars(path): - if '$' not in path: - return path - res = '' - index = 0 - pathlen = len(path) - while index < pathlen: - c = path[index] - if c == '\'': # no expansion within single quotes - path = path[index + 1:] - pathlen = len(path) - try: - index = string.index(path, '\'') - res = res + '\'' + path[:index + 1] - except string.index_error: - res = res + path - index = pathlen -1 - elif c == '$': # variable or '$$' - if path[index + 1:index + 2] == '$': - res = res + c - index = index + 1 - elif path[index + 1:index + 2] == '{': - path = path[index+2:] - pathlen = len(path) - try: - index = string.index(path, '}') - var = path[:index] - if os.environ.has_key(var): - res = res + os.environ[var] - except string.index_error: - res = res + path - index = pathlen - 1 - else: - var = '' - index = index + 1 - c = path[index:index + 1] - while c != '' and c in varchars: - var = var + c - index = index + 1 - c = path[index:index + 1] - if os.environ.has_key(var): - res = res + os.environ[var] - if c != '': - res = res + c - else: - res = res + c - index = index + 1 - return res - - -# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B. -# Also, components of the path are silently truncated to 8+3 notation. - -def normpath(path): - path = normcase(path) - prefix, path = splitdrive(path) - while path[:1] == os.sep: - prefix = prefix + os.sep - path = path[1:] - comps = string.splitfields(path, os.sep) - i = 0 - while i < len(comps): - if comps[i] == '.': - del comps[i] - elif comps[i] == '..' and i > 0 and \ - comps[i-1] not in ('', '..'): - del comps[i-1:i+1] - i = i-1 - elif comps[i] == '' and i > 0 and comps[i-1] <> '': - del comps[i] - elif '.' in comps[i]: - comp = string.splitfields(comps[i], '.') - comps[i] = comp[0][:8] + '.' + comp[1][:3] - i = i+1 - elif len(comps[i]) > 8: - comps[i] = comps[i][:8] - i = i+1 - else: - i = i+1 - # If the path is now empty, substitute '.' - if not prefix and not comps: - comps.append('.') - return prefix + string.joinfields(comps, os.sep) - diff --git a/Lib/os.py b/Lib/os.py deleted file mode 100644 index d974c59fa0..0000000000 --- a/Lib/os.py +++ /dev/null @@ -1,123 +0,0 @@ -# os.py -- either mac, dos or posix depending on what system we're on. - -# This exports: -# - all functions from either posix or mac, e.g., os.unlink, os.stat, etc. -# - os.path is either module posixpath or macpath -# - os.name is either 'posix' or 'mac' -# - os.curdir is a string representing the current directory ('.' or ':') -# - os.pardir is a string representing the parent directory ('..' or '::') -# - os.sep is the (or a most common) pathname separator ('/' or ':') -# - os.pathsep is the component separator used in $PATH etc -# - os.defpath is the default search path for executables - -# Programs that import and use 'os' stand a better chance of being -# portable between different platforms. Of course, they must then -# only use functions that are defined by all platforms (e.g., unlink -# and opendir), and leave all pathname manipulation to os.path -# (e.g., split and join). - -_osindex = { - 'posix': ('.', '..', '/', ':', ':/bin:/usr/bin'), - 'dos': ('.', '..', '\\', ';', '.;C:\\bin'), - 'nt': ('.', '..', '\\', ';', '.;C:\\bin'), - 'mac': (':', '::', ':', '\n', ':'), -} - -# For freeze.py script: -if 0: - import posix - import posixpath - -import sys -for name in _osindex.keys(): - if name in sys.builtin_module_names: - curdir, pardir, sep, pathsep, defpath = _osindex[name] - exec 'from %s import *' % name - exec 'import %spath' % name - exec 'path = %spath' % name - exec 'del %spath' % name - try: - exec 'from %s import _exit' % name - except ImportError: - pass - try: - environ - except: - environ = {} # Make sure os.environ exists, at least - break -else: - del name - raise ImportError, 'no os specific module found' - -def execl(file, *args): - execv(file, args) - -def execle(file, *args): - env = args[-1] - execve(file, args[:-1], env) - -def execlp(file, *args): - execvp(file, args) - -def execlpe(file, *args): - env = args[-1] - execvpe(file, args[:-1], env) - -def execvp(file, args): - _execvpe(file, args) - -def execvpe(file, args, env): - _execvpe(file, args, env) - -_notfound = None -def _execvpe(file, args, env = None): - if env: - func = execve - argrest = (args, env) - else: - func = execv - argrest = (args,) - env = environ - global _notfound - head, tail = path.split(file) - if head: - apply(func, (file,) + argrest) - return - if env.has_key('PATH'): - envpath = env['PATH'] - else: - envpath = defpath - import string - PATH = string.splitfields(envpath, pathsep) - if not _notfound: - import tempfile - # Exec a file that is guaranteed not to exist - try: execv(tempfile.mktemp(), ()) - except error, _notfound: pass - exc, arg = error, _notfound - for dir in PATH: - fullname = path.join(dir, file) - try: - apply(func, (fullname,) + argrest) - except error, (errno, msg): - if errno != arg[0]: - exc, arg = error, (errno, msg) - raise exc, arg - -# Provide listdir for Windows NT that doesn't have it built in -if name == 'nt': - try: - _tmp = listdir - del _tmp - except NameError: - def listdir(name): - if path.ismount(name): - list = ['.'] - else: - list = ['.', '..'] - f = popen('dir/l/b ' + name, 'r') - line = f.readline() - while line: - list.append(line[:-1]) - line = f.readline() - return list diff --git a/Lib/ospath.py b/Lib/ospath.py deleted file mode 100644 index 1e66759d10..0000000000 --- a/Lib/ospath.py +++ /dev/null @@ -1,3 +0,0 @@ -# ospath.py is obsolete -import os -exec 'from %s import *' % os.name diff --git a/Lib/packmail.py b/Lib/packmail.py deleted file mode 100644 index 13b1bdcdea..0000000000 --- a/Lib/packmail.py +++ /dev/null @@ -1,112 +0,0 @@ -# Module 'packmail' -- create a self-unpacking shell archive. - -# This module works on UNIX and on the Mac; the archives can unpack -# themselves only on UNIX. - -import os -from stat import ST_MTIME -import string - -# Print help -def help(): - print 'All fns have a file open for writing as first parameter' - print 'pack(f, fullname, name): pack fullname as name' - print 'packsome(f, directory, namelist): selected files from directory' - print 'packall(f, directory): pack all files from directory' - print 'packnotolder(f, directory, name): pack all files from directory' - print ' that are not older than a file there' - print 'packtree(f, directory): pack entire directory tree' - -# Pack one file -def pack(outfp, file, name): - fp = open(file, 'r') - outfp.write('echo ' + name + '\n') - outfp.write('sed "s/^X//" >' + name + ' <<"!"\n') - while 1: - line = fp.readline() - if not line: break - if line[-1:] <> '\n': - line = line + '\n' - outfp.write('X' + line) - outfp.write('!\n') - fp.close() - -# Pack some files from a directory -def packsome(outfp, dirname, names): - for name in names: - print name - file = os.path.join(dirname, name) - pack(outfp, file, name) - -# Pack all files from a directory -def packall(outfp, dirname): - names = os.listdir(dirname) - try: - names.remove('.') - except: - pass - try: - names.remove('..') - except: - pass - names.sort() - packsome(outfp, dirname, names) - -# Pack all files from a directory that are not older than a give one -def packnotolder(outfp, dirname, oldest): - names = os.listdir(dirname) - try: - names.remove('.') - except: - pass - try: - names.remove('..') - except: - pass - oldest = os.path.join(dirname, oldest) - st = os.stat(oldest) - mtime = st[ST_MTIME] - todo = [] - for name in names: - print name, '...', - st = os.stat(os.path.join(dirname, name)) - if st[ST_MTIME] >= mtime: - print 'Yes.' - todo.append(name) - else: - print 'No.' - todo.sort() - packsome(outfp, dirname, todo) - -# Pack a whole tree (no exceptions) -def packtree(outfp, dirname): - print 'packtree', dirname - outfp.write('mkdir ' + unixfix(dirname) + '\n') - names = os.listdir(dirname) - try: - names.remove('.') - except: - pass - try: - names.remove('..') - except: - pass - subdirs = [] - for name in names: - fullname = os.path.join(dirname, name) - if os.path.isdir(fullname): - subdirs.append(fullname) - else: - print 'pack', fullname - pack(outfp, fullname, unixfix(fullname)) - for subdirname in subdirs: - packtree(outfp, subdirname) - -def unixfix(name): - comps = string.splitfields(name, os.sep) - res = '' - for comp in comps: - if comp: - if res: res = res + '/' - res = res + comp - return res diff --git a/Lib/pdb.doc b/Lib/pdb.doc deleted file mode 100644 index 43a91c24b2..0000000000 --- a/Lib/pdb.doc +++ /dev/null @@ -1,166 +0,0 @@ -The Python Debugger -=================== - -To use the debugger in its simplest form: - - >>> import pdb - >>> pdb.run('<a statement>') - -The debugger's prompt is '(Pdb) '. This will stop in the first -function call in <a statement>. - -Alternatively, if a statement terminated with an unhandled exception, -you can use pdb's post-mortem facility to inspect the contents of the -traceback: - - >>> <a statement> - <exception traceback> - >>> import pdb - >>> pdb.pm() - -The commands recognized by the debugger are listed in the next -section. Most can be abbreviated as indicated; e.g., h(elp) means -that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel', -nor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in -square brackets. - -A blank line repeats the previous command literally. (Except for -'list', where it lists the next 11 lines.) - -Commands that the debugger doesn't recognize are assumed to be Python -statements and are executed in the context of the program being -debugged. Python statements can also be prefixed with an exclamation -point ('!'). This is a powerful way to inspect the program being -debugged; it is even possible to change variables. When an exception -occurs in such a statement, the exception name is printed but the -debugger's state is not changed. - -The debugger is not directly programmable; but it is implemented as a -class from which you can derive your own debugger class, so you can -make as fancy as you like. - - -Debugger commands -================= - -h(elp) - Without argument, print the list of available commands. - With a command name as argument, print help about that command - (this is currently not implemented). - -w(here) - Print a stack trace, with the most recent frame at the bottom. - An arrow indicates the "current frame", which determines the - context of most commands. - -d(own) - Move the current frame one level down in the stack trace - (to an older frame). - -u(p) - Move the current frame one level up in the stack trace - (to a newer frame). - -b(reak) [lineno | function] - With a line number argument, set a break there in the current - file. With a function name, set a break at the entry of that - function. Without argument, list all breaks. - -cl(ear) [lineno] - With a line number argument, clear that break in the current file. - Without argument, clear all breaks (but first ask confirmation). - -s(tep) - Execute the current line, stop at the first possible occasion - (either in a function that is called or in the current function). - -n(ext) - Continue execution until the next line in the current function - is reached or it returns. - -r(eturn) - Continue execution until the current function returns. - -c(ont(inue)) - Continue execution, only stop when a breakpoint is encountered. - -l(ist) [first [,last]] - List source code for the current file. - Without arguments, list 11 lines around the current line - or continue the previous listing. - With one argument, list 11 lines starting at that line. - With two arguments, list the given range; - if the second argument is less than the first, it is a count. - -a(rgs) - Print the argument list of the current function. - -p expression - Print the value of the expression. - -(!) statement - Execute the (one-line) statement in the context of - the current stack frame. - The exclamation point can be omitted unless the first word - of the statement resembles a debugger command. - To assign to a global variable you must always prefix the - command with a 'global' command, e.g.: - (Pdb) global list_options; list_options = ['-l'] - (Pdb) - -q(uit) - Quit from the debugger. - The program being executed is aborted. - - -How it works -============ - -Some changes were made to the interpreter: -- sys.settrace(func) sets the global trace function -- there can also a local trace function (see later) - -Trace functions have three arguments: (frame, event, arg) - - frame is the current stack frame - - event is a string: 'call', 'line', 'return' or 'exception' - - arg is dependent on the event type -A trace function should return a new trace function or None. -Class methods are accepted (and most useful!) as trace methods. - -The events have the following meaning: - - 'call': A function is called (or some other code block entered). - The global trace function is called; - arg is the argument list to the function; - the return value specifies the local trace function. - - 'line': The interpreter is about to execute a new line of code - (sometimes multiple line events on one line exist). - The local trace function is called; arg in None; - the return value specifies the new local trace function. - - 'return': A function (or other code block) is about to return. - The local trace function is called; - arg is the value that will be returned. - The trace function's return value is ignored. - - 'exception': An exception has occurred. - The local trace function is called; - arg is a triple (exception, value, traceback); - the return value specifies the new local trace function - -Note that as an exception is propagated down the chain of callers, an -'exception' event is generated at each level. - -Stack frame objects have the following read-only attributes: - f_code: the code object being executed - f_lineno: the current line number (-1 for 'call' events) - f_back: the stack frame of the caller, or None - f_locals: dictionary containing local name bindings - f_globals: dictionary containing global name bindings - -Code objects have the following read-only attributes: - co_code: the code string - co_names: the list of names used by the code - co_consts: the list of (literal) constants used by the code - co_filename: the filename from which the code was compiled diff --git a/Lib/pdb.py b/Lib/pdb.py deleted file mode 100755 index f44c7e08dd..0000000000 --- a/Lib/pdb.py +++ /dev/null @@ -1,492 +0,0 @@ -# pdb.py -- finally, a Python debugger! - -# (See pdb.doc for documentation.) - -import string -import sys -import linecache -import cmd -import bdb -import repr - - -# Interaction prompt line will separate file and call info from code -# text using value of line_prefix string. A newline and arrow may -# be to your liking. You can set it once pdb is imported using the -# command "pdb.line_prefix = '\n% '". -# line_prefix = ': ' # Use this to get the old situation back -line_prefix = '\n-> ' # Probably a better default - -class Pdb(bdb.Bdb, cmd.Cmd): - - def __init__(self): - bdb.Bdb.__init__(self) - cmd.Cmd.__init__(self) - self.prompt = '(Pdb) ' - - def reset(self): - bdb.Bdb.reset(self) - self.forget() - - def forget(self): - self.lineno = None - self.stack = [] - self.curindex = 0 - self.curframe = None - - def setup(self, f, t): - self.forget() - self.stack, self.curindex = self.get_stack(f, t) - self.curframe = self.stack[self.curindex][0] - - # Override Bdb methods (except user_call, for now) - - def user_line(self, frame): - # This function is called when we stop or break at this line - self.interaction(frame, None) - - def user_return(self, frame, return_value): - # This function is called when a return trap is set here - frame.f_locals['__return__'] = return_value - print '--Return--' - self.interaction(frame, None) - - def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): - # This function is called if an exception occurs, - # but only if we are to stop at or just below this level - frame.f_locals['__exception__'] = exc_type, exc_value - if type(exc_type) == type(''): - exc_type_name = exc_type - else: exc_type_name = exc_type.__name__ - print exc_type_name + ':', repr.repr(exc_value) - self.interaction(frame, exc_traceback) - - # General interaction function - - def interaction(self, frame, traceback): - self.setup(frame, traceback) - self.print_stack_entry(self.stack[self.curindex]) - self.cmdloop() - self.forget() - - def default(self, line): - if line[:1] == '!': line = line[1:] - locals = self.curframe.f_locals - globals = self.curframe.f_globals - globals['__privileged__'] = 1 - code = compile(line + '\n', '<stdin>', 'single') - try: - exec code in globals, locals - except: - if type(sys.exc_type) == type(''): - exc_type_name = sys.exc_type - else: exc_type_name = sys.exc_type.__name__ - print '***', exc_type_name + ':', sys.exc_value - - # Command definitions, called by cmdloop() - # The argument is the remaining string on the command line - # Return true to exit from the command loop - - do_h = cmd.Cmd.do_help - - def do_break(self, arg): - if not arg: - print self.get_all_breaks() # XXX - return - # Try line number as argument - try: - lineno = int(eval(arg)) - filename = self.curframe.f_code.co_filename - except: - # Try function name as the argument - import codehack - try: - func = eval(arg, self.curframe.f_globals, - self.curframe.f_locals) - if hasattr(func, 'im_func'): - func = func.im_func - code = func.func_code - except: - print '*** Could not eval argument:', arg - return - lineno = codehack.getlineno(code) - filename = code.co_filename - - # now set the break point - err = self.set_break(filename, lineno) - if err: print '***', err - do_b = do_break - - def do_clear(self, arg): - if not arg: - try: - reply = raw_input('Clear all breaks? ') - except EOFError: - reply = 'no' - reply = string.lower(string.strip(reply)) - if reply in ('y', 'yes'): - self.clear_all_breaks() - return - try: - lineno = int(eval(arg)) - except: - print '*** Error in argument:', `arg` - return - filename = self.curframe.f_code.co_filename - err = self.clear_break(filename, lineno) - if err: print '***', err - do_cl = do_clear # 'c' is already an abbreviation for 'continue' - - def do_where(self, arg): - self.print_stack_trace() - do_w = do_where - - def do_up(self, arg): - if self.curindex == 0: - print '*** Oldest frame' - else: - self.curindex = self.curindex - 1 - self.curframe = self.stack[self.curindex][0] - self.print_stack_entry(self.stack[self.curindex]) - self.lineno = None - do_u = do_up - - def do_down(self, arg): - if self.curindex + 1 == len(self.stack): - print '*** Newest frame' - else: - self.curindex = self.curindex + 1 - self.curframe = self.stack[self.curindex][0] - self.print_stack_entry(self.stack[self.curindex]) - self.lineno = None - do_d = do_down - - def do_step(self, arg): - self.set_step() - return 1 - do_s = do_step - - def do_next(self, arg): - self.set_next(self.curframe) - return 1 - do_n = do_next - - def do_return(self, arg): - self.set_return(self.curframe) - return 1 - do_r = do_return - - def do_continue(self, arg): - self.set_continue() - return 1 - do_c = do_cont = do_continue - - def do_quit(self, arg): - self.set_quit() - return 1 - do_q = do_quit - - def do_args(self, arg): - if self.curframe.f_locals.has_key('__args__'): - print `self.curframe.f_locals['__args__']` - else: - print '*** No arguments?!' - do_a = do_args - - def do_retval(self, arg): - if self.curframe.f_locals.has_key('__return__'): - print self.curframe.f_locals['__return__'] - else: - print '*** Not yet returned!' - do_rv = do_retval - - def do_p(self, arg): - self.curframe.f_globals['__privileged__'] = 1 - try: - value = eval(arg, self.curframe.f_globals, \ - self.curframe.f_locals) - except: - if type(sys.exc_type) == type(''): - exc_type_name = sys.exc_type - else: exc_type_name = sys.exc_type.__name__ - print '***', exc_type_name + ':', `sys.exc_value` - return - - print `value` - - def do_list(self, arg): - self.lastcmd = 'list' - last = None - if arg: - try: - x = eval(arg, {}, {}) - if type(x) == type(()): - first, last = x - first = int(first) - last = int(last) - if last < first: - # Assume it's a count - last = first + last - else: - first = max(1, int(x) - 5) - except: - print '*** Error in argument:', `arg` - return - elif self.lineno is None: - first = max(1, self.curframe.f_lineno - 5) - else: - first = self.lineno + 1 - if last == None: - last = first + 10 - filename = self.curframe.f_code.co_filename - breaklist = self.get_file_breaks(filename) - try: - for lineno in range(first, last+1): - line = linecache.getline(filename, lineno) - if not line: - print '[EOF]' - break - else: - s = string.rjust(`lineno`, 3) - if len(s) < 4: s = s + ' ' - if lineno in breaklist: s = s + 'B' - else: s = s + ' ' - if lineno == self.curframe.f_lineno: - s = s + '->' - print s + '\t' + line, - self.lineno = lineno - except KeyboardInterrupt: - pass - do_l = do_list - - def do_whatis(self, arg): - try: - value = eval(arg, self.curframe.f_globals, \ - self.curframe.f_locals) - except: - if type(sys.exc_type) == type(''): - exc_type_name = sys.exc_type - else: exc_type_name = sys.exc_type.__name__ - print '***', exc_type_name + ':', `sys.exc_value` - return - code = None - # Is it a function? - try: code = value.func_code - except: pass - if code: - print 'Function', code.co_name - return - # Is it an instance method? - try: code = value.im_func.func_code - except: pass - if code: - print 'Method', code.co_name - return - # None of the above... - print type(value) - - # Print a traceback starting at the top stack frame. - # The most recently entered frame is printed last; - # this is different from dbx and gdb, but consistent with - # the Python interpreter's stack trace. - # It is also consistent with the up/down commands (which are - # compatible with dbx and gdb: up moves towards 'main()' - # and down moves towards the most recent stack frame). - - def print_stack_trace(self): - try: - for frame_lineno in self.stack: - self.print_stack_entry(frame_lineno) - except KeyboardInterrupt: - pass - - def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix): - frame, lineno = frame_lineno - if frame is self.curframe: - print '>', - else: - print ' ', - print self.format_stack_entry(frame_lineno, prompt_prefix) - - - # Help methods (derived from pdb.doc) - - def help_help(self): - self.help_h() - - def help_h(self): - print """h(elp) - Without argument, print the list of available commands. - With a command name as argument, print help about that command - "help pdb" pipes the full documentation file to the $PAGER - "help exec" gives help on the ! command""" - - def help_where(self): - self.help_w() - - def help_w(self): - print """w(here) - Print a stack trace, with the most recent frame at the bottom. - An arrow indicates the "current frame", which determines the - context of most commands.""" - - def help_down(self): - self.help_d() - - def help_d(self): - print """d(own) - Move the current frame one level down in the stack trace - (to an older frame).""" - - def help_up(self): - self.help_u() - - def help_u(self): - print """u(p) - Move the current frame one level up in the stack trace - (to a newer frame).""" - - def help_break(self): - self.help_b() - - def help_b(self): - print """b(reak) [lineno | function] - With a line number argument, set a break there in the current - file. With a function name, set a break at the entry of that - function. Without argument, list all breaks.""" - - def help_clear(self): - self.help_cl() - - def help_cl(self): - print """cl(ear) [lineno] - With a line number argument, clear that break in the current file. - Without argument, clear all breaks (but first ask confirmation).""" - - def help_step(self): - self.help_s() - - def help_s(self): - print """s(tep) - Execute the current line, stop at the first possible occasion - (either in a function that is called or in the current function).""" - - def help_next(self): - self.help_n() - - def help_n(self): - print """n(ext) - Continue execution until the next line in the current function - is reached or it returns.""" - - def help_return(self): - self.help_r() - - def help_r(self): - print """r(eturn) - Continue execution until the current function returns.""" - - def help_continue(self): - self.help_c() - - def help_cont(self): - self.help_c() - - def help_c(self): - print """c(ont(inue)) - Continue execution, only stop when a breakpoint is encountered.""" - - def help_list(self): - self.help_l() - - def help_l(self): - print """l(ist) [first [,last]] - List source code for the current file. - Without arguments, list 11 lines around the current line - or continue the previous listing. - With one argument, list 11 lines starting at that line. - With two arguments, list the given range; - if the second argument is less than the first, it is a count.""" - - def help_args(self): - self.help_a() - - def help_a(self): - print """a(rgs) - Print the argument list of the current function.""" - - def help_p(self): - print """p expression - Print the value of the expression.""" - - def help_exec(self): - print """(!) statement - Execute the (one-line) statement in the context of - the current stack frame. - The exclamation point can be omitted unless the first word - of the statement resembles a debugger command. - To assign to a global variable you must always prefix the - command with a 'global' command, e.g.: - (Pdb) global list_options; list_options = ['-l'] - (Pdb)""" - - def help_quit(self): - self.help_q() - - def help_q(self): - print """q(uit) Quit from the debugger. - The program being executed is aborted.""" - - def help_pdb(self): - help() - -# Simplified interface - -def run(statement, globals=None, locals=None): - Pdb().run(statement, globals, locals) - -def runeval(expression, globals=None, locals=None): - return Pdb().runeval(expression, globals, locals) - -def runctx(statement, globals, locals): - # B/W compatibility - run(statement, globals, locals) - -def runcall(*args): - return apply(Pdb().runcall, args) - -def set_trace(): - Pdb().set_trace() - -# Post-Mortem interface - -def post_mortem(t): - p = Pdb() - p.reset() - while t.tb_next <> None: t = t.tb_next - p.interaction(t.tb_frame, t) - -def pm(): - import sys - post_mortem(sys.last_traceback) - - -# Main program for testing - -TESTCMD = 'import x; x.main()' - -def test(): - run(TESTCMD) - -# print help -def help(): - import os - for dirname in sys.path: - fullname = os.path.join(dirname, 'pdb.doc') - if os.path.exists(fullname): - sts = os.system('${PAGER-more} '+fullname) - if sts: print '*** Pager exit status:', sts - break - else: - print 'Sorry, can\'t find the help file "pdb.doc"', - print 'along the Python search path' diff --git a/Lib/persist.py b/Lib/persist.py deleted file mode 100755 index 8f0f164bc6..0000000000 --- a/Lib/persist.py +++ /dev/null @@ -1,297 +0,0 @@ -# persist.py -# -# Implement limited persistence. -# -# Simple interface: -# persist.save() save __main__ module on file (overwrite) -# persist.load() load __main__ module from file (merge) -# -# These use the filename persist.defaultfile, initialized to 'wsrestore.py'. -# -# A raw interface also exists: -# persist.writedict(dict, fp) save dictionary to open file -# persist.readdict(dict, fp) read (merge) dictionary from open file -# -# Internally, the function dump() and a whole bunch of support of functions -# traverse a graph of objects and print them in a restorable form -# (which happens to be a Python module). -# -# XXX Limitations: -# - Volatile objects are dumped as strings: -# - open files, windows etc. -# - Other 'obscure' objects are dumped as strings: -# - classes, instances and methods -# - compiled regular expressions -# - anything else reasonably obscure (e.g., capabilities) -# - type objects for obscure objects -# - It's slow when there are many of lists or dictionaries -# (This could be fixed if there were a quick way to compute a hash -# function of any object, even if recursive) - -defaultfile = 'wsrestore.py' - -def save(): - import __main__ - import os - # XXX On SYSV, if len(defaultfile) >= 14, this is wrong! - backup = defaultfile + '~' - try: - os.unlink(backup) - except os.error: - pass - try: - os.rename(defaultfile, backup) - except os.error: - pass - fp = open(defaultfile, 'w') - writedict(__main__.__dict__, fp) - fp.close() - -def load(): - import __main__ - fp = open(defaultfile, 'r') - readdict(__main__.__dict__, fp) - -def writedict(dict, fp): - import sys - savestdout = sys.stdout - try: - sys.stdout = fp - dump(dict) # Writes to sys.stdout - finally: - sys.stdout = savestdout - -def readdict(dict, fp): - contents = fp.read() - globals = {} - exec(contents, globals) - top = globals['top'] - for key in top.keys(): - if dict.has_key(key): - print 'warning:', key, 'not overwritten' - else: - dict[key] = top[key] - - -# Function dump(x) prints (on sys.stdout!) a sequence of Python statements -# that, when executed in an empty environment, will reconstruct the -# contents of an arbitrary dictionary. - -import sys - -# Name used for objects dict on output. -# -FUNNYNAME = FN = 'A' - -# Top-level function. Call with the object you want to dump. -# -def dump(x): - types = {} - stack = [] # Used by test for recursive objects - print FN, '= {}' - topuid = dumpobject(x, types, stack) - print 'top =', FN, '[', `topuid`, ']' - -# Generic function to dump any object. -# -dumpswitch = {} -# -def dumpobject(x, types, stack): - typerepr = `type(x)` - if not types.has_key(typerepr): - types[typerepr] = {} - typedict = types[typerepr] - if dumpswitch.has_key(typerepr): - return dumpswitch[typerepr](x, typedict, types, stack) - else: - return dumpbadvalue(x, typedict, types, stack) - -# Generic function to dump unknown values. -# This assumes that the Python interpreter prints such values as -# <foo object at xxxxxxxx>. -# The object will be read back as a string: '<foo object at xxxxxxxx>'. -# In some cases it may be possible to fix the dump manually; -# to ease the editing, these cases are labeled with an XXX comment. -# -def dumpbadvalue(x, typedict, types, stack): - xrepr = `x` - if typedict.has_key(xrepr): - return typedict[xrepr] - uid = genuid() - typedict[xrepr] = uid - print FN, '[', `uid`, '] =', `xrepr`, '# XXX' - return uid - -# Generic function to dump pure, simple values, except strings -# -def dumpvalue(x, typedict, types, stack): - xrepr = `x` - if typedict.has_key(xrepr): - return typedict[xrepr] - uid = genuid() - typedict[xrepr] = uid - print FN, '[', `uid`, '] =', `x` - return uid - -# Functions to dump string objects -# -def dumpstring(x, typedict, types, stack): - # XXX This can break if strings have embedded '\0' bytes - # XXX because of a bug in the dictionary module - if typedict.has_key(x): - return typedict[x] - uid = genuid() - typedict[x] = uid - print FN, '[', `uid`, '] =', `x` - return uid - -# Function to dump type objects -# -typeswitch = {} -class some_class: - def method(self): pass -some_instance = some_class() -# -def dumptype(x, typedict, types, stack): - xrepr = `x` - if typedict.has_key(xrepr): - return typedict[xrepr] - uid = genuid() - typedict[xrepr] = uid - if typeswitch.has_key(xrepr): - print FN, '[', `uid`, '] =', typeswitch[xrepr] - elif x == type(sys): - print 'import sys' - print FN, '[', `uid`, '] = type(sys)' - elif x == type(sys.stderr): - print 'import sys' - print FN, '[', `uid`, '] = type(sys.stderr)' - elif x == type(dumptype): - print 'def some_function(): pass' - print FN, '[', `uid`, '] = type(some_function)' - elif x == type(some_class): - print 'class some_class: pass' - print FN, '[', `uid`, '] = type(some_class)' - elif x == type(some_instance): - print 'class another_class: pass' - print 'some_instance = another_class()' - print FN, '[', `uid`, '] = type(some_instance)' - elif x == type(some_instance.method): - print 'class yet_another_class:' - print ' def method(): pass' - print 'another_instance = yet_another_class()' - print FN, '[', `uid`, '] = type(another_instance.method)' - else: - # Unknown type - print FN, '[', `uid`, '] =', `xrepr`, '# XXX' - return uid - -# Initialize the typeswitch -# -for x in None, 0, 0.0, '', (), [], {}: - typeswitch[`type(x)`] = 'type(' + `x` + ')' -for s in 'type(0)', 'abs', '[].append': - typeswitch[`type(eval(s))`] = 'type(' + s + ')' - -# Dump a tuple object -# -def dumptuple(x, typedict, types, stack): - item_uids = [] - xrepr = '' - for item in x: - item_uid = dumpobject(item, types, stack) - item_uids.append(item_uid) - xrepr = xrepr + ' ' + item_uid - del stack[-1:] - if typedict.has_key(xrepr): - return typedict[xrepr] - uid = genuid() - typedict[xrepr] = uid - print FN, '[', `uid`, '] = (', - for item_uid in item_uids: - print FN, '[', `item_uid`, '],', - print ')' - return uid - -# Dump a list object -# -def dumplist(x, typedict, types, stack): - # Check for recursion - for x1, uid1 in stack: - if x is x1: return uid1 - # Check for occurrence elsewhere in the typedict - for uid1 in typedict.keys(): - if x is typedict[uid1]: return uid1 - # This uses typedict differently! - uid = genuid() - typedict[uid] = x - print FN, '[', `uid`, '] = []' - stack.append(x, uid) - item_uids = [] - for item in x: - item_uid = dumpobject(item, types, stack) - item_uids.append(item_uid) - del stack[-1:] - for item_uid in item_uids: - print FN, '[', `uid`, '].append(', FN, '[', `item_uid`, '])' - return uid - -# Dump a dictionary object -# -def dumpdict(x, typedict, types, stack): - # Check for recursion - for x1, uid1 in stack: - if x is x1: return uid1 - # Check for occurrence elsewhere in the typedict - for uid1 in typedict.keys(): - if x is typedict[uid1]: return uid1 - # This uses typedict differently! - uid = genuid() - typedict[uid] = x - print FN, '[', `uid`, '] = {}' - stack.append(x, uid) - item_uids = [] - for key in x.keys(): - val_uid = dumpobject(x[key], types, stack) - item_uids.append(key, val_uid) - del stack[-1:] - for key, val_uid in item_uids: - print FN, '[', `uid`, '][', `key`, '] =', - print FN, '[', `val_uid`, ']' - return uid - -# Dump a module object -# -def dumpmodule(x, typedict, types, stack): - xrepr = `x` - if typedict.has_key(xrepr): - return typedict[xrepr] - from string import split - # `x` has the form <module 'foo'> - name = xrepr[9:-2] - uid = genuid() - typedict[xrepr] = uid - print 'import', name - print FN, '[', `uid`, '] =', name - return uid - - -# Initialize dumpswitch, a table of functions to dump various objects, -# indexed by `type(x)`. -# -for x in None, 0, 0.0: - dumpswitch[`type(x)`] = dumpvalue -for x, f in ('', dumpstring), (type(0), dumptype), ((), dumptuple), \ - ([], dumplist), ({}, dumpdict), (sys, dumpmodule): - dumpswitch[`type(x)`] = f - - -# Generate the next unique id; a string consisting of digits. -# The seed is stored as seed[0]. -# -seed = [0] -# -def genuid(): - x = seed[0] - seed[0] = seed[0] + 1 - return `x` diff --git a/Lib/pickle.py b/Lib/pickle.py deleted file mode 100644 index 8f5da40af1..0000000000 --- a/Lib/pickle.py +++ /dev/null @@ -1,569 +0,0 @@ -"""\ -Pickling Algorithm ------------------- - -This module implements a basic but powerful algorithm for "pickling" (a.k.a. -serializing, marshalling or flattening) nearly arbitrary Python objects. -This is a more primitive notion than persistency -- although pickle -reads and writes file objects, it does not handle the issue of naming -persistent objects, nor the (even more complicated) area of concurrent -access to persistent objects. The pickle module can transform a complex -object into a byte stream and it can transform the byte stream into -an object with the same internal structure. The most obvious thing to -do with these byte streams is to write them onto a file, but it is also -conceivable to send them across a network or store them in a database. - -Unlike the built-in marshal module, pickle handles the following correctly: - -- recursive objects -- pointer sharing -- classes and class instances - -Pickle is Python-specific. This has the advantage that there are no -restrictions imposed by external standards such as CORBA (which probably -can't represent pointer sharing or recursive objects); however it means -that non-Python programs may not be able to reconstruct pickled Python -objects. - -Pickle uses a printable ASCII representation. This is slightly more -voluminous than a binary representation. However, small integers actually -take *less* space when represented as minimal-size decimal strings than -when represented as 32-bit binary numbers, and strings are only much longer -if they contain control characters or 8-bit characters. The big advantage -of using printable ASCII (and of some other characteristics of pickle's -representation) is that for debugging or recovery purposes it is possible -for a human to read the pickled file with a standard text editor. (I could -have gone a step further and used a notation like S-expressions, but the -parser would have been considerably more complicated and slower, and the -files would probably have become much larger.) - -Pickle doesn't handle code objects, which marshal does. -I suppose pickle could, and maybe it should, but there's probably no -great need for it right now (as long as marshal continues to be used -for reading and writing code objects), and at least this avoids -the possibility of smuggling Trojan horses into a program. - -For the benefit of persistency modules written using pickle, it supports -the notion of a reference to an object outside the pickled data stream. -Such objects are referenced by a name, which is an arbitrary string of -printable ASCII characters. The resolution of such names is not defined -by the pickle module -- the persistent object module will have to implement -a method "persistent_load". To write references to persistent objects, -the persistent module must define a method "persistent_id" which returns -either None or the persistent ID of the object. - -There are some restrictions on the pickling of class instances. - -First of all, the class must be defined at the top level in a module. - -Next, it must normally be possible to create class instances by calling -the class without arguments. If this is undesirable, the class can -define a method __getinitargs__ (XXX not a pretty name!), which should -return a *tuple* containing the arguments to be passed to the class -constructor. - -Classes can influence how their instances are pickled -- if the class defines -the method __getstate__, it is called and the return state is pickled -as the contents for the instance, and if the class defines the -method __setstate__, it is called with the unpickled state. (Note -that these methods can also be used to implement copying class instances.) -If there is no __getstate__ method, the instance's __dict__ -is pickled. If there is no __setstate__ method, the pickled object -must be a dictionary and its items are assigned to the new instance's -dictionary. (If a class defines both __getstate__ and __setstate__, -the state object needn't be a dictionary -- these methods can do what they -want.) - -Note that when class instances are pickled, their class's code and data -is not pickled along with them. Only the instance data is pickled. -This is done on purpose, so you can fix bugs in a class or add methods and -still load objects that were created with an earlier version of the -class. If you plan to have long-lived objects that will see many versions -of a class, it may be worth to put a version number in the objects so -that suitable conversions can be made by the class's __setstate__ method. - -The interface is as follows: - -To pickle an object x onto a file f, open for writing: - - p = pickle.Pickler(f) - p.dump(x) - -To unpickle an object x from a file f, open for reading: - - u = pickle.Unpickler(f) - x = u.load() - -The Pickler class only calls the method f.write with a string argument -(XXX possibly the interface should pass f.write instead of f). -The Unpickler calls the methods f.read(with an integer argument) -and f.readline(without argument), both returning a string. -It is explicitly allowed to pass non-file objects here, as long as they -have the right methods. - -The following types can be pickled: - -- None -- integers, long integers, floating point numbers -- strings -- tuples, lists and dictionaries containing only picklable objects -- class instances whose __dict__ or __setstate__() is picklable -- classes - -Attempts to pickle unpicklable objects will raise an exception -after having written an unspecified number of bytes to the file argument. - -It is possible to make multiple calls to Pickler.dump() or to -Unpickler.load(), as long as there is a one-to-one correspondence -between pickler and Unpickler objects and between dump and load calls -for any pair of corresponding Pickler and Unpicklers. WARNING: this -is intended for pickleing multiple objects without intervening modifications -to the objects or their parts. If you modify an object and then pickle -it again using the same Pickler instance, the object is not pickled -again -- a reference to it is pickled and the Unpickler will return -the old value, not the modified one. (XXX There are two problems here: -(a) detecting changes, and (b) marshalling a minimal set of changes. -I have no answers. Garbage Collection may also become a problem here.) -""" - -__version__ = "1.5" # Code version - -from types import * -import string - -format_version = "1.1" # File format version we write -compatible_formats = ["1.0"] # Old format versions we can read - -PicklingError = "pickle.PicklingError" - -AtomicTypes = [NoneType, IntType, FloatType, StringType] - -def safe(object): - t = type(object) - if t in AtomicTypes: - return 1 - if t is TupleType: - for item in object: - if not safe(item): return 0 - return 1 - return 0 - -MARK = '(' -POP = '0' -DUP = '2' -STOP = '.' -TUPLE = 't' -LIST = 'l' -DICT = 'd' -INST = 'i' -CLASS = 'c' -GET = 'g' -PUT = 'p' -APPEND = 'a' -SETITEM = 's' -BUILD = 'b' -NONE = 'N' -INT = 'I' -LONG = 'L' -FLOAT = 'F' -STRING = 'S' -PERSID = 'P' -AtomicKeys = [NONE, INT, LONG, FLOAT, STRING] -AtomicMap = { - NoneType: NONE, - IntType: INT, - LongType: LONG, - FloatType: FLOAT, - StringType: STRING, -} - -class Pickler: - - def __init__(self, file): - self.write = file.write - self.memo = {} - - def dump(self, object): - self.save(object) - self.write(STOP) - - def save(self, object): - pid = self.persistent_id(object) - if pid: - self.write(PERSID + str(pid) + '\n') - return - d = id(object) - if self.memo.has_key(d): - self.write(GET + `d` + '\n') - return - t = type(object) - try: - f = self.dispatch[t] - except KeyError: - raise PicklingError, \ - "can't pickle %s objects" % `t.__name__` - f(self, object) - - def persistent_id(self, object): - return None - - dispatch = {} - - def save_none(self, object): - self.write(NONE) - dispatch[NoneType] = save_none - - def save_int(self, object): - self.write(INT + `object` + '\n') - dispatch[IntType] = save_int - - def save_long(self, object): - self.write(LONG + `object` + '\n') - dispatch[LongType] = save_long - - def save_float(self, object): - self.write(FLOAT + `object` + '\n') - dispatch[FloatType] = save_float - - def save_string(self, object): - d = id(object) - self.write(STRING + `object` + '\n') - self.write(PUT + `d` + '\n') - self.memo[d] = object - dispatch[StringType] = save_string - - def save_tuple(self, object): - d = id(object) - self.write(MARK) - n = len(object) - for k in range(n): - self.save(object[k]) - if self.memo.has_key(d): - # Saving object[k] has saved us! - while k >= 0: - self.write(POP) - k = k-1 - self.write(GET + `d` + '\n') - break - else: - self.write(TUPLE + PUT + `d` + '\n') - self.memo[d] = object - dispatch[TupleType] = save_tuple - - def save_list(self, object): - d = id(object) - self.write(MARK) - n = len(object) - for k in range(n): - item = object[k] - if not safe(item): - break - self.save(item) - else: - k = n - self.write(LIST + PUT + `d` + '\n') - self.memo[d] = object - for k in range(k, n): - item = object[k] - self.save(item) - self.write(APPEND) - dispatch[ListType] = save_list - - def save_dict(self, object): - d = id(object) - self.write(MARK) - items = object.items() - n = len(items) - for k in range(n): - key, value = items[k] - if not safe(key) or not safe(value): - break - self.save(key) - self.save(value) - else: - k = n - self.write(DICT + PUT + `d` + '\n') - self.memo[d] = object - for k in range(k, n): - key, value = items[k] - self.save(key) - self.save(value) - self.write(SETITEM) - dispatch[DictionaryType] = save_dict - - def save_inst(self, object): - d = id(object) - cls = object.__class__ - module = whichmodule(cls) - name = cls.__name__ - if hasattr(object, '__getinitargs__'): - args = object.__getinitargs__() - len(args) # XXX Assert it's a sequence - else: - args = () - self.write(MARK) - for arg in args: - self.save(arg) - self.write(INST + module + '\n' + name + '\n' + - PUT + `d` + '\n') - self.memo[d] = object - try: - getstate = object.__getstate__ - except AttributeError: - stuff = object.__dict__ - else: - stuff = getstate() - self.save(stuff) - self.write(BUILD) - dispatch[InstanceType] = save_inst - - def save_class(self, object): - d = id(object) - module = whichmodule(object) - name = object.__name__ - self.write(CLASS + module + '\n' + name + '\n' + - PUT + `d` + '\n') - dispatch[ClassType] = save_class - - -classmap = {} - -def whichmodule(cls): - """Figure out the module in which a class occurs. - - Search sys.modules for the module. - Cache in classmap. - Return a module name. - If the class cannot be found, return __main__. - """ - if classmap.has_key(cls): - return classmap[cls] - import sys - clsname = cls.__name__ - for name, module in sys.modules.items(): - if name != '__main__' and \ - hasattr(module, clsname) and \ - getattr(module, clsname) is cls: - break - else: - name = '__main__' - classmap[cls] = name - return name - - -class Unpickler: - - def __init__(self, file): - self.readline = file.readline - self.read = file.read - self.memo = {} - - def load(self): - self.mark = ['spam'] # Any new unique object - self.stack = [] - try: - while 1: - key = self.read(1) - self.dispatch[key](self) - except STOP, value: - return value - - def marker(self): - k = len(self.stack)-1 - while self.stack[k] != self.mark: k = k-1 - return k - - dispatch = {} - - def load_eof(self): - raise EOFError - dispatch[''] = load_eof - - def load_persid(self): - pid = self.readline()[:-1] - self.stack.append(self.persistent_load(pid)) - dispatch[PERSID] = load_persid - - def load_none(self): - self.stack.append(None) - dispatch[NONE] = load_none - - def load_int(self): - self.stack.append(string.atoi(self.readline()[:-1], 0)) - dispatch[INT] = load_int - - def load_long(self): - self.stack.append(string.atol(self.readline()[:-1], 0)) - dispatch[LONG] = load_long - - def load_float(self): - self.stack.append(string.atof(self.readline()[:-1])) - dispatch[FLOAT] = load_float - - def load_string(self): - self.stack.append(eval(self.readline()[:-1])) - dispatch[STRING] = load_string - - def load_tuple(self): - k = self.marker() - self.stack[k:] = [tuple(self.stack[k+1:])] - dispatch[TUPLE] = load_tuple - - def load_list(self): - k = self.marker() - self.stack[k:] = [self.stack[k+1:]] - dispatch[LIST] = load_list - - def load_dict(self): - k = self.marker() - d = {} - items = self.stack[k+1:] - for i in range(0, len(items), 2): - key = items[i] - value = items[i+1] - d[key] = value - self.stack[k:] = [d] - dispatch[DICT] = load_dict - - def load_inst(self): - k = self.marker() - args = tuple(self.stack[k+1:]) - del self.stack[k:] - module = self.readline()[:-1] - name = self.readline()[:-1] - klass = self.find_class(module, name) - value = apply(klass, args) - self.stack.append(value) - dispatch[INST] = load_inst - - def load_class(self): - module = self.readline()[:-1] - name = self.readline()[:-1] - klass = self.find_class(module, name) - self.stack.append(klass) - return klass - dispatch[CLASS] = load_class - - def find_class(self, module, name): - env = {} - try: - exec 'from %s import %s' % (module, name) in env - except ImportError: - raise SystemError, \ - "Failed to import class %s from module %s" % \ - (name, module) - klass = env[name] - if type(klass) != ClassType: - raise SystemError, \ - "Imported object %s from module %s is not a class" % \ - (name, module) - return klass - - def load_pop(self): - del self.stack[-1] - dispatch[POP] = load_pop - - def load_dup(self): - stack.append(stack[-1]) - dispatch[DUP] = load_dup - - def load_get(self): - self.stack.append(self.memo[self.readline()[:-1]]) - dispatch[GET] = load_get - - def load_put(self): - self.memo[self.readline()[:-1]] = self.stack[-1] - dispatch[PUT] = load_put - - def load_append(self): - value = self.stack[-1] - del self.stack[-1] - list = self.stack[-1] - list.append(value) - dispatch[APPEND] = load_append - - def load_setitem(self): - value = self.stack[-1] - key = self.stack[-2] - del self.stack[-2:] - dict = self.stack[-1] - dict[key] = value - dispatch[SETITEM] = load_setitem - - def load_build(self): - value = self.stack[-1] - del self.stack[-1] - inst = self.stack[-1] - try: - setstate = inst.__setstate__ - except AttributeError: - for key in value.keys(): - inst.__dict__[key] = value[key] - else: - setstate(value) - dispatch[BUILD] = load_build - - def load_mark(self): - self.stack.append(self.mark) - dispatch[MARK] = load_mark - - def load_stop(self): - value = self.stack[-1] - del self.stack[-1] - raise STOP, value - dispatch[STOP] = load_stop - - -# Shorthands - -def dump(object, file): - Pickler(file).dump(object) - -def dumps(object): - import StringIO - file = StringIO.StringIO() - Pickler(file).dump(object) - return file.getvalue() - -def load(file): - return Unpickler(file).load() - -def loads(str): - import StringIO - file = StringIO.StringIO(str) - return Unpickler(file).load() - - -# The rest is used for testing only - -class C: - def __cmp__(self, other): - return cmp(self.__dict__, other.__dict__) - -def test(): - fn = 'pickle_tmp' - c = C() - c.foo = 1 - c.bar = 2L - x = [0,1,2,3] - y = ('abc', 'abc', c, c) - x.append(y) - x.append(y) - x.append(5) - f = open(fn, 'w') - F = Pickler(f) - F.dump(x) - f.close() - f = open(fn, 'r') - U = Unpickler(f) - x2 = U.load() - print x - print x2 - print x == x2 - print map(id, x) - print map(id, x2) - print F.memo - print U.memo - -if __name__ == '__main__': - test() diff --git a/Lib/pipes.py b/Lib/pipes.py deleted file mode 100644 index 0ae0b8c9ed..0000000000 --- a/Lib/pipes.py +++ /dev/null @@ -1,301 +0,0 @@ -# Conversion pipeline templates -# ============================= - - -# The problem: -# ------------ -# -# Suppose you have some data that you want to convert to another format -# (e.g. from GIF image format to PPM image format). Maybe the -# conversion involves several steps (e.g. piping it through compress or -# uuencode). Some of the conversion steps may require that their input -# is a disk file, others may be able to read standard input; similar for -# their output. The input to the entire conversion may also be read -# from a disk file or from an open file, and similar for its output. -# -# The module lets you construct a pipeline template by sticking one or -# more conversion steps together. It will take care of creating and -# removing temporary files if they are necessary to hold intermediate -# data. You can then use the template to do conversions from many -# different sources to many different destinations. The temporary -# file names used are different each time the template is used. -# -# The templates are objects so you can create templates for many -# different conversion steps and store them in a dictionary, for -# instance. - - -# Directions: -# ----------- -# -# To create a template: -# t = Template() -# -# To add a conversion step to a template: -# t.append(command, kind) -# where kind is a string of two characters: the first is '-' if the -# command reads its standard input or 'f' if it requires a file; the -# second likewise for the output. The command must be valid /bin/sh -# syntax. If input or output files are required, they are passed as -# $IN and $OUT; otherwise, it must be possible to use the command in -# a pipeline. -# -# To add a conversion step at the beginning: -# t.prepend(command, kind) -# -# To convert a file to another file using a template: -# sts = t.copy(infile, outfile) -# If infile or outfile are the empty string, standard input is read or -# standard output is written, respectively. The return value is the -# exit status of the conversion pipeline. -# -# To open a file for reading or writing through a conversion pipeline: -# fp = t.open(file, mode) -# where mode is 'r' to read the file, or 'w' to write it -- just like -# for the built-in function open() or for os.popen(). -# -# To create a new template object initialized to a given one: -# t2 = t.clone() -# -# For an example, see the function test() at the end of the file. - - -import sys -import regex - -import os -import tempfile -import string - - -# Conversion step kinds - -FILEIN_FILEOUT = 'ff' # Must read & write real files -STDIN_FILEOUT = '-f' # Must write a real file -FILEIN_STDOUT = 'f-' # Must read a real file -STDIN_STDOUT = '--' # Normal pipeline element -SOURCE = '.-' # Must be first, writes stdout -SINK = '-.' # Must be last, reads stdin - -stepkinds = [FILEIN_FILEOUT, STDIN_FILEOUT, FILEIN_STDOUT, STDIN_STDOUT, \ - SOURCE, SINK] - - -# A pipeline template is a Template object: - -class Template: - - # Template() returns a fresh pipeline template - def __init__(self): - self.debugging = 0 - self.reset() - - # t.__repr__() implements `t` - def __repr__(self): - return '<Template instance, steps=' + `self.steps` + '>' - - # t.reset() restores a pipeline template to its initial state - def reset(self): - self.steps = [] - - # t.clone() returns a new pipeline template with identical - # initial state as the current one - def clone(self): - t = Template() - t.steps = self.steps[:] - t.debugging = self.debugging - return t - - # t.debug(flag) turns debugging on or off - def debug(self, flag): - self.debugging = flag - - # t.append(cmd, kind) adds a new step at the end - def append(self, cmd, kind): - if type(cmd) <> type(''): - raise TypeError, \ - 'Template.append: cmd must be a string' - if kind not in stepkinds: - raise ValueError, \ - 'Template.append: bad kind ' + `kind` - if kind == SOURCE: - raise ValueError, \ - 'Template.append: SOURCE can only be prepended' - if self.steps <> [] and self.steps[-1][1] == SINK: - raise ValueError, \ - 'Template.append: already ends with SINK' - if kind[0] == 'f' and regex.search('\$IN', cmd) < 0: - raise ValueError, \ - 'Template.append: missing $IN in cmd' - if kind[1] == 'f' and regex.search('\$OUT', cmd) < 0: - raise ValueError, \ - 'Template.append: missing $OUT in cmd' - self.steps.append((cmd, kind)) - - # t.prepend(cmd, kind) adds a new step at the front - def prepend(self, cmd, kind): - if type(cmd) <> type(''): - raise TypeError, \ - 'Template.prepend: cmd must be a string' - if kind not in stepkinds: - raise ValueError, \ - 'Template.prepend: bad kind ' + `kind` - if kind == SINK: - raise ValueError, \ - 'Template.prepend: SINK can only be appended' - if self.steps <> [] and self.steps[0][1] == SOURCE: - raise ValueError, \ - 'Template.prepend: already begins with SOURCE' - if kind[0] == 'f' and regex.search('\$IN\>', cmd) < 0: - raise ValueError, \ - 'Template.prepend: missing $IN in cmd' - if kind[1] == 'f' and regex.search('\$OUT\>', cmd) < 0: - raise ValueError, \ - 'Template.prepend: missing $OUT in cmd' - self.steps.insert(0, (cmd, kind)) - - # t.open(file, rw) returns a pipe or file object open for - # reading or writing; the file is the other end of the pipeline - def open(self, file, rw): - if rw == 'r': - return self.open_r(file) - if rw == 'w': - return self.open_w(file) - raise ValueError, \ - 'Template.open: rw must be \'r\' or \'w\', not ' + `rw` - - # t.open_r(file) and t.open_w(file) implement - # t.open(file, 'r') and t.open(file, 'w') respectively - - def open_r(self, file): - if self.steps == []: - return open(file, 'r') - if self.steps[-1][1] == SINK: - raise ValueError, \ - 'Template.open_r: pipeline ends width SINK' - cmd = self.makepipeline(file, '') - return os.popen(cmd, 'r') - - def open_w(self, file): - if self.steps == []: - return open(file, 'w') - if self.steps[0][1] == SOURCE: - raise ValueError, \ - 'Template.open_w: pipeline begins with SOURCE' - cmd = self.makepipeline('', file) - return os.popen(cmd, 'w') - - def copy(self, infile, outfile): - return os.system(self.makepipeline(infile, outfile)) - - def makepipeline(self, infile, outfile): - cmd = makepipeline(infile, self.steps, outfile) - if self.debugging: - print cmd - cmd = 'set -x; ' + cmd - return cmd - - -def makepipeline(infile, steps, outfile): - # Build a list with for each command: - # [input filename or '', command string, kind, output filename or ''] - - list = [] - for cmd, kind in steps: - list.append(['', cmd, kind, '']) - # - # Make sure there is at least one step - # - if list == []: - list.append(['', 'cat', '--', '']) - # - # Take care of the input and output ends - # - [cmd, kind] = list[0][1:3] - if kind[0] == 'f' and not infile: - list.insert(0, ['', 'cat', '--', '']) - list[0][0] = infile - # - [cmd, kind] = list[-1][1:3] - if kind[1] == 'f' and not outfile: - list.append(['', 'cat', '--', '']) - list[-1][-1] = outfile - # - # Invent temporary files to connect stages that need files - # - garbage = [] - for i in range(1, len(list)): - lkind = list[i-1][2] - rkind = list[i][2] - if lkind[1] == 'f' or rkind[0] == 'f': - temp = tempfile.mktemp() - garbage.append(temp) - list[i-1][-1] = list[i][0] = temp - # - for item in list: - [inf, cmd, kind, outf] = item - if kind[1] == 'f': - cmd = 'OUT=' + quote(outf) + '; ' + cmd - if kind[0] == 'f': - cmd = 'IN=' + quote(inf) + '; ' + cmd - if kind[0] == '-' and inf: - cmd = cmd + ' <' + quote(inf) - if kind[1] == '-' and outf: - cmd = cmd + ' >' + quote(outf) - item[1] = cmd - # - cmdlist = list[0][1] - for item in list[1:]: - [cmd, kind] = item[1:3] - if item[0] == '': - if 'f' in kind: - cmd = '{ ' + cmd + '; }' - cmdlist = cmdlist + ' |\n' + cmd - else: - cmdlist = cmdlist + '\n' + cmd - # - if garbage: - rmcmd = 'rm -f' - for file in garbage: - rmcmd = rmcmd + ' ' + quote(file) - trapcmd = 'trap ' + quote(rmcmd + '; exit') + ' 1 2 3 13 14 15' - cmdlist = trapcmd + '\n' + cmdlist + '\n' + rmcmd - # - return cmdlist - - -# Reliably quote a string as a single argument for /bin/sh - -_safechars = string.letters + string.digits + '!@%_-+=:,./' # Safe unquoted -_funnychars = '"`$\\' # Unsafe inside "double quotes" - -def quote(file): - for c in file: - if c not in _safechars: - break - else: - return file - if '\'' not in file: - return '\'' + file + '\'' - res = '' - for c in file: - if c in _funnychars: - c = '\\' + c - res = res + c - return '"' + res + '"' - - -# Small test program and example - -def test(): - import os - print 'Testing...' - t = Template() - t.append('togif $IN $OUT', 'ff') - t.append('giftoppm', '--') - t.append('ppmtogif >$OUT', '-f') - t.append('fromgif $IN $OUT', 'ff') - t.debug(1) - FILE = '/usr/local/images/rgb/rogues/guido.rgb' - t.copy(FILE, '@temp') - print 'Done.' diff --git a/Lib/plat-irix5/AL.py b/Lib/plat-irix5/AL.py deleted file mode 100755 index c4497ab4a8..0000000000 --- a/Lib/plat-irix5/AL.py +++ /dev/null @@ -1,60 +0,0 @@ -RATE_48000 = 48000 -RATE_44100 = 44100 -RATE_32000 = 32000 -RATE_22050 = 22050 -RATE_16000 = 16000 -RATE_11025 = 11025 -RATE_8000 = 8000 - -SAMPFMT_TWOSCOMP= 1 -SAMPFMT_FLOAT = 32 -SAMPFMT_DOUBLE = 64 - -SAMPLE_8 = 1 -SAMPLE_16 = 2 - # SAMPLE_24 is the low 24 bits of a long, sign extended to 32 bits -SAMPLE_24 = 4 - -MONO = 1 -STEREO = 2 - -INPUT_LINE = 0 -INPUT_MIC = 1 -INPUT_DIGITAL = 2 - -MONITOR_OFF = 0 -MONITOR_ON = 1 - -ERROR_NUMBER = 0 -ERROR_TYPE = 1 -ERROR_LOCATION_LSP = 2 -ERROR_LOCATION_MSP = 3 -ERROR_LENGTH = 4 - -ERROR_INPUT_UNDERFLOW = 0 -ERROR_OUTPUT_OVERFLOW = 1 - -# These seem to be not supported anymore: -##HOLD, RELEASE = 0, 1 -##ATTAIL, ATHEAD, ATMARK, ATTIME = 0, 1, 2, 3 - -DEFAULT_DEVICE = 1 - -INPUT_SOURCE = 0 -LEFT_INPUT_ATTEN = 1 -RIGHT_INPUT_ATTEN = 2 -INPUT_RATE = 3 -OUTPUT_RATE = 4 -LEFT_SPEAKER_GAIN = 5 -RIGHT_SPEAKER_GAIN = 6 -INPUT_COUNT = 7 -OUTPUT_COUNT = 8 -UNUSED_COUNT = 9 -SYNC_INPUT_TO_AES = 10 -SYNC_OUTPUT_TO_AES = 11 -MONITOR_CTL = 12 -LEFT_MONITOR_ATTEN = 13 -RIGHT_MONITOR_ATTEN = 14 - -ENUM_VALUE = 0 # only certain values are valid -RANGE_VALUE = 1 # any value in range is valid diff --git a/Lib/plat-irix5/AWARE.py b/Lib/plat-irix5/AWARE.py deleted file mode 100755 index 30be50b8ee..0000000000 --- a/Lib/plat-irix5/AWARE.py +++ /dev/null @@ -1,54 +0,0 @@ -# -# Copyright (c) 1992 Aware, Inc. All rights reserved. -# -# Copyright Unpublished, Aware Inc. All Rights Reserved. -# This software contains proprietary and confidential -# information of Aware, Inc. Use, disclosure or -# reproduction is prohibited without the prior express -# written consent of Aware, Inc. -# -# - -# -# awareAudio.h - Aware Compression Library Parameter Header -# -# 01/21/92 Original Version by Brian Knittel and Jonathon Devine -# - -import CL - -# Aware Audio Specific Parameters - For both MPEG Audio and Multirate -CL.CHANNEL_POLICY = CL.NUMBER_OF_PARAMS + 0 -CL.NOISE_MARGIN = CL.NUMBER_OF_PARAMS + 1 -CL.BITRATE_POLICY = CL.NUMBER_OF_PARAMS + 2 - -# Additional parameters for MPEG Audio -CL.BITRATE_TARGET = CL.NUMBER_OF_PARAMS + 3 -CL.LAYER = CL.NUMBER_OF_PARAMS + 4 - -# read/write for compression configuration -# read for state during compression/decompression - -# -# Channel Policy -# -AWCMP_STEREO = 1 -AWCMP_JOINT_STEREO = 2 -AWCMP_INDEPENDENT = 3 - -# -# read/write for compression configuration, -# read for state during compression -# -# -# Bit-rate Policy -# -AWCMP_FIXED_RATE = 1 -AWCMP_CONST_QUAL = 2 -AWCMP_LOSSLESS = 4 - -# -# Layer values -# -AWCMP_MPEG_LAYER_I = 1 -AWCMP_MPEG_LAYER_II = 2 diff --git a/Lib/plat-irix5/CD.py b/Lib/plat-irix5/CD.py deleted file mode 100755 index ad56561235..0000000000 --- a/Lib/plat-irix5/CD.py +++ /dev/null @@ -1,34 +0,0 @@ -ERROR = 0 -NODISC = 1 -READY = 2 -PLAYING = 3 -PAUSED = 4 -STILL = 5 - -AUDIO = 0 -PNUM = 1 -INDEX = 2 -PTIME = 3 -ATIME = 4 -CATALOG = 5 -IDENT = 6 -CONTROL = 7 - -CDDA_DATASIZE = 2352 - -##CDDA_SUBCODESIZE = (sizeof(struct subcodeQ)) -##CDDA_BLOCKSIZE = (sizeof(struct cdframe)) -##CDDA_NUMSAMPLES = (CDDA_DATASIZE/2) -## -##CDQ_PREEMP_MASK = 0xd -##CDQ_COPY_MASK = 0xb -##CDQ_DDATA_MASK = 0xd -##CDQ_BROADCAST_MASK = 0x8 -##CDQ_PREEMPHASIS = 0x1 -##CDQ_COPY_PERMITTED = 0x2 -##CDQ_DIGITAL_DATA = 0x4 -##CDQ_BROADCAST_USE = 0x8 -## -##CDQ_MODE1 = 0x1 -##CDQ_MODE2 = 0x2 -##CDQ_MODE3 = 0x3 diff --git a/Lib/plat-irix5/CL.py b/Lib/plat-irix5/CL.py deleted file mode 100755 index 468ecaaa68..0000000000 --- a/Lib/plat-irix5/CL.py +++ /dev/null @@ -1,24 +0,0 @@ -# Backward compatible module CL. -# All relevant symbols are now defined in the module cl. -try: - from cl import * -except ImportError: - from CL_old import * -else: - del CompressImage - del DecompressImage - del GetAlgorithmName - del OpenCompressor - del OpenDecompressor - del QueryAlgorithms - del QueryMaxHeaderSize - del QueryScheme - del QuerySchemeFromName - del SetDefault - del SetMax - del SetMin - try: - del cvt_type - except NameError: - pass - del error diff --git a/Lib/plat-irix5/CL_old.py b/Lib/plat-irix5/CL_old.py deleted file mode 100755 index 41c56e0cca..0000000000 --- a/Lib/plat-irix5/CL_old.py +++ /dev/null @@ -1,236 +0,0 @@ -# -# cl.h - Compression Library typedefs and prototypes -# -# 01/07/92 Cleanup by Brian Knittel -# 02/18/92 Original Version by Brian Knittel -# - -# -# originalFormat parameter values -# -MAX_NUMBER_OF_ORIGINAL_FORMATS = 32 - -# Audio -MONO = 0 -STEREO_INTERLEAVED = 1 - -# Video -# YUV is defined to be the same thing as YCrCb (luma and two chroma components). -# 422 is appended to YUV (or YCrCb) if the chroma is sub-sampled by 2 -# horizontally, packed as U Y1 V Y2 (byte order). -# 422HC is appended to YUV (or YCrCb) if the chroma is sub-sampled by 2 -# vertically in addition to horizontally, and is packed the same as -# 422 except that U & V are not valid on the second line. -# -RGB = 0 -RGBX = 1 -RGBA = 2 -RGB332 = 3 - -GRAYSCALE = 4 -Y = 4 -YUV = 5 -YCbCr = 5 -YUV422 = 6 # 4:2:2 sampling -YCbCr422 = 6 # 4:2:2 sampling -YUV422HC = 7 # 4:1:1 sampling -YCbCr422HC = 7 # 4:1:1 sampling -YUV422DC = 7 # 4:1:1 sampling -YCbCr422DC = 7 # 4:1:1 sampling - -BEST_FIT = -1 - -def BytesPerSample(s): - if s in (MONO, YUV): - return 2 - elif s == STEREO_INTERLEAVED: - return 4 - else: - return 0 - -def BytesPerPixel(f): - if f in (RGB, YUV): - return 3 - elif f in (RGBX, RGBA): - return 4 - elif f in (RGB332, GRAYSCALE): - return 1 - else: - return 2 - -def AudioFormatName(f): - if f == MONO: - return 'MONO' - elif f == STEREO_INTERLEAVED: - return 'STEREO_INTERLEAVED' - else: - return 'Not a valid format' - -def VideoFormatName(f): - if f == RGB: - return 'RGB' - elif f == RGBX: - return 'RGBX' - elif f == RGBA: - return 'RGBA' - elif f == RGB332: - return 'RGB332' - elif f == GRAYSCALE: - return 'GRAYSCALE' - elif f == YUV: - return 'YUV' - elif f == YUV422: - return 'YUV422' - elif f == YUV422DC: - return 'YUV422DC' - else: - return 'Not a valid format' - -MAX_NUMBER_OF_AUDIO_ALGORITHMS = 32 -MAX_NUMBER_OF_VIDEO_ALGORITHMS = 32 - -# -# Algorithm types -# -AUDIO = 0 -VIDEO = 1 - -def AlgorithmNumber(scheme): - return scheme & 0x7fff -def AlgorithmType(scheme): - return (scheme >> 15) & 1 -def Algorithm(type, n): - return n | ((type & 1) << 15) - -# -# "compressionScheme" argument values -# -UNKNOWN_SCHEME = -1 - -UNCOMPRESSED_AUDIO = Algorithm(AUDIO, 0) -G711_ULAW = Algorithm(AUDIO, 1) -ULAW = Algorithm(AUDIO, 1) -G711_ALAW = Algorithm(AUDIO, 2) -ALAW = Algorithm(AUDIO, 2) -AWARE_MPEG_AUDIO = Algorithm(AUDIO, 3) -AWARE_MULTIRATE = Algorithm(AUDIO, 4) - -UNCOMPRESSED = Algorithm(VIDEO, 0) -UNCOMPRESSED_VIDEO = Algorithm(VIDEO, 0) -RLE = Algorithm(VIDEO, 1) -JPEG = Algorithm(VIDEO, 2) -MPEG_VIDEO = Algorithm(VIDEO, 3) -MVC1 = Algorithm(VIDEO, 4) -RTR = Algorithm(VIDEO, 5) -RTR1 = Algorithm(VIDEO, 5) - -# -# Parameters -# -MAX_NUMBER_OF_PARAMS = 256 -# Default Parameters -IMAGE_WIDTH = 0 -IMAGE_HEIGHT = 1 -ORIGINAL_FORMAT = 2 -INTERNAL_FORMAT = 3 -COMPONENTS = 4 -BITS_PER_COMPONENT = 5 -FRAME_RATE = 6 -COMPRESSION_RATIO = 7 -EXACT_COMPRESSION_RATIO = 8 -FRAME_BUFFER_SIZE = 9 -COMPRESSED_BUFFER_SIZE = 10 -BLOCK_SIZE = 11 -PREROLL = 12 -FRAME_TYPE = 13 -ALGORITHM_ID = 14 -ALGORITHM_VERSION = 15 -ORIENTATION = 16 -NUMBER_OF_FRAMES = 17 -SPEED = 18 -LAST_FRAME_INDEX = 19 -NUMBER_OF_PARAMS = 20 - -# JPEG Specific Parameters -QUALITY_FACTOR = NUMBER_OF_PARAMS + 0 - -# MPEG Specific Parameters -END_OF_SEQUENCE = NUMBER_OF_PARAMS + 0 - -# RTR Specific Parameters -QUALITY_LEVEL = NUMBER_OF_PARAMS + 0 -ZOOM_X = NUMBER_OF_PARAMS + 1 -ZOOM_Y = NUMBER_OF_PARAMS + 2 - -# -# Parameter value types -# -ENUM_VALUE = 0 # only certain constant values are valid -RANGE_VALUE = 1 # any value in a given range is valid -FLOATING_ENUM_VALUE = 2 # only certain constant floating point values are valid -FLOATING_RANGE_VALUE = 3 # any value in a given floating point range is valid - -# -# Algorithm Functionality -# -DECOMPRESSOR = 1 -COMPRESSOR = 2 -CODEC = 3 - -# -# Buffer types -# -NONE = 0 -FRAME = 1 -DATA = 2 - -# -# Frame types -# -NONE = 0 -KEYFRAME = 1 -INTRA = 1 -PREDICTED = 2 -BIDIRECTIONAL = 3 - -# -# Orientations -# -TOP_DOWN = 0 -BOTTOM_UP = 1 - -# -# SGI Proprietaty Algorithm Header Start Code -# -HEADER_START_CODE = 0xc1C0DEC - -# -# error codes -# - -BAD_NO_BUFFERSPACE = -2 # no space for internal buffers -BAD_PVBUFFER = -3 # param/val buffer doesn't make sense -BAD_BUFFERLENGTH_NEG = -4 # negative buffer length -BAD_BUFFERLENGTH_ODD = -5 # odd length parameter/value buffer -BAD_PARAM = -6 # invalid parameter -BAD_COMPRESSION_SCHEME = -7 # compression scheme parameter invalid -BAD_COMPRESSOR_HANDLE = -8 # compression handle parameter invalid -BAD_COMPRESSOR_HANDLE_POINTER = -9 # compression handle pointer invalid -BAD_BUFFER_HANDLE = -10 # buffer handle invalid -BAD_BUFFER_QUERY_SIZE = -11 # buffer query size too large -JPEG_ERROR = -12 # error from libjpeg -BAD_FRAME_SIZE = -13 # frame size invalid -PARAM_OUT_OF_RANGE = -14 # parameter out of range -ADDED_ALGORITHM_ERROR = -15 # added algorithm had a unique error -BAD_ALGORITHM_TYPE = -16 # bad algorithm type -BAD_ALGORITHM_NAME = -17 # bad algorithm name -BAD_BUFFERING = -18 # bad buffering calls -BUFFER_NOT_CREATED = -19 # buffer not created -BAD_BUFFER_EXISTS = -20 # buffer already created -BAD_INTERNAL_FORMAT = -21 # invalid internal format -BAD_BUFFER_POINTER = -22 # invalid buffer pointer -FRAME_BUFFER_SIZE_ZERO = -23 # frame buffer has zero size -BAD_STREAM_HEADER = -24 # invalid stream header - -BAD_LICENSE = -25 # netls license not valid -AWARE_ERROR = -26 # error from libawcmp diff --git a/Lib/plat-irix5/DEVICE.py b/Lib/plat-irix5/DEVICE.py deleted file mode 100755 index 7ace8cb0b6..0000000000 --- a/Lib/plat-irix5/DEVICE.py +++ /dev/null @@ -1,400 +0,0 @@ -NULLDEV = 0 -BUTOFFSET = 1 -VALOFFSET = 256 -PSEUDOFFSET = 512 -BUT2OFFSET = 3840 -TIMOFFSET = 515 -XKBDOFFSET = 143 -BUTCOUNT = 255 -VALCOUNT = 256 -TIMCOUNT = 4 -XKBDCOUNT = 28 -USERBUTOFFSET = 4096 -USERVALOFFSET = 12288 -USERPSEUDOFFSET = 16384 -BUT0 = 1 -BUT1 = 2 -BUT2 = 3 -BUT3 = 4 -BUT4 = 5 -BUT5 = 6 -BUT6 = 7 -BUT7 = 8 -BUT8 = 9 -BUT9 = 10 -BUT10 = 11 -BUT11 = 12 -BUT12 = 13 -BUT13 = 14 -BUT14 = 15 -BUT15 = 16 -BUT16 = 17 -BUT17 = 18 -BUT18 = 19 -BUT19 = 20 -BUT20 = 21 -BUT21 = 22 -BUT22 = 23 -BUT23 = 24 -BUT24 = 25 -BUT25 = 26 -BUT26 = 27 -BUT27 = 28 -BUT28 = 29 -BUT29 = 30 -BUT30 = 31 -BUT31 = 32 -BUT32 = 33 -BUT33 = 34 -BUT34 = 35 -BUT35 = 36 -BUT36 = 37 -BUT37 = 38 -BUT38 = 39 -BUT39 = 40 -BUT40 = 41 -BUT41 = 42 -BUT42 = 43 -BUT43 = 44 -BUT44 = 45 -BUT45 = 46 -BUT46 = 47 -BUT47 = 48 -BUT48 = 49 -BUT49 = 50 -BUT50 = 51 -BUT51 = 52 -BUT52 = 53 -BUT53 = 54 -BUT54 = 55 -BUT55 = 56 -BUT56 = 57 -BUT57 = 58 -BUT58 = 59 -BUT59 = 60 -BUT60 = 61 -BUT61 = 62 -BUT62 = 63 -BUT63 = 64 -BUT64 = 65 -BUT65 = 66 -BUT66 = 67 -BUT67 = 68 -BUT68 = 69 -BUT69 = 70 -BUT70 = 71 -BUT71 = 72 -BUT72 = 73 -BUT73 = 74 -BUT74 = 75 -BUT75 = 76 -BUT76 = 77 -BUT77 = 78 -BUT78 = 79 -BUT79 = 80 -BUT80 = 81 -BUT81 = 82 -BUT82 = 83 -MAXKBDBUT = 83 -BUT100 = 101 -BUT101 = 102 -BUT102 = 103 -BUT103 = 104 -BUT104 = 105 -BUT105 = 106 -BUT106 = 107 -BUT107 = 108 -BUT108 = 109 -BUT109 = 110 -BUT110 = 111 -BUT111 = 112 -BUT112 = 113 -BUT113 = 114 -BUT114 = 115 -BUT115 = 116 -BUT116 = 117 -BUT117 = 118 -BUT118 = 119 -BUT119 = 120 -BUT120 = 121 -BUT121 = 122 -BUT122 = 123 -BUT123 = 124 -BUT124 = 125 -BUT125 = 126 -BUT126 = 127 -BUT127 = 128 -BUT128 = 129 -BUT129 = 130 -BUT130 = 131 -BUT131 = 132 -BUT132 = 133 -BUT133 = 134 -BUT134 = 135 -BUT135 = 136 -BUT136 = 137 -BUT137 = 138 -BUT138 = 139 -BUT139 = 140 -BUT140 = 141 -BUT141 = 142 -BUT142 = 143 -BUT143 = 144 -BUT144 = 145 -BUT145 = 146 -BUT146 = 147 -BUT147 = 148 -BUT148 = 149 -BUT149 = 150 -BUT150 = 151 -BUT151 = 152 -BUT152 = 153 -BUT153 = 154 -BUT154 = 155 -BUT155 = 156 -BUT156 = 157 -BUT157 = 158 -BUT158 = 159 -BUT159 = 160 -BUT160 = 161 -BUT161 = 162 -BUT162 = 163 -BUT163 = 164 -BUT164 = 165 -BUT165 = 166 -BUT166 = 167 -BUT167 = 168 -BUT168 = 169 -BUT181 = 182 -BUT182 = 183 -BUT183 = 184 -BUT184 = 185 -BUT185 = 186 -BUT186 = 187 -BUT187 = 188 -BUT188 = 189 -BUT189 = 190 -MOUSE1 = 101 -MOUSE2 = 102 -MOUSE3 = 103 -LEFTMOUSE = 103 -MIDDLEMOUSE = 102 -RIGHTMOUSE = 101 -LPENBUT = 104 -BPAD0 = 105 -BPAD1 = 106 -BPAD2 = 107 -BPAD3 = 108 -LPENVALID = 109 -SWBASE = 111 -SW0 = 111 -SW1 = 112 -SW2 = 113 -SW3 = 114 -SW4 = 115 -SW5 = 116 -SW6 = 117 -SW7 = 118 -SW8 = 119 -SW9 = 120 -SW10 = 121 -SW11 = 122 -SW12 = 123 -SW13 = 124 -SW14 = 125 -SW15 = 126 -SW16 = 127 -SW17 = 128 -SW18 = 129 -SW19 = 130 -SW20 = 131 -SW21 = 132 -SW22 = 133 -SW23 = 134 -SW24 = 135 -SW25 = 136 -SW26 = 137 -SW27 = 138 -SW28 = 139 -SW29 = 140 -SW30 = 141 -SW31 = 142 -SBBASE = 182 -SBPICK = 182 -SBBUT1 = 183 -SBBUT2 = 184 -SBBUT3 = 185 -SBBUT4 = 186 -SBBUT5 = 187 -SBBUT6 = 188 -SBBUT7 = 189 -SBBUT8 = 190 -AKEY = 11 -BKEY = 36 -CKEY = 28 -DKEY = 18 -EKEY = 17 -FKEY = 19 -GKEY = 26 -HKEY = 27 -IKEY = 40 -JKEY = 34 -KKEY = 35 -LKEY = 42 -MKEY = 44 -NKEY = 37 -OKEY = 41 -PKEY = 48 -QKEY = 10 -RKEY = 24 -SKEY = 12 -TKEY = 25 -UKEY = 33 -VKEY = 29 -WKEY = 16 -XKEY = 21 -YKEY = 32 -ZKEY = 20 -ZEROKEY = 46 -ONEKEY = 8 -TWOKEY = 14 -THREEKEY = 15 -FOURKEY = 22 -FIVEKEY = 23 -SIXKEY = 30 -SEVENKEY = 31 -EIGHTKEY = 38 -NINEKEY = 39 -BREAKKEY = 1 -SETUPKEY = 2 -CTRLKEY = 3 -LEFTCTRLKEY = CTRLKEY -CAPSLOCKKEY = 4 -RIGHTSHIFTKEY = 5 -LEFTSHIFTKEY = 6 -NOSCRLKEY = 13 -ESCKEY = 7 -TABKEY = 9 -RETKEY = 51 -SPACEKEY = 83 -LINEFEEDKEY = 60 -BACKSPACEKEY = 61 -DELKEY = 62 -SEMICOLONKEY = 43 -PERIODKEY = 52 -COMMAKEY = 45 -QUOTEKEY = 50 -ACCENTGRAVEKEY = 55 -MINUSKEY = 47 -VIRGULEKEY = 53 -BACKSLASHKEY = 57 -EQUALKEY = 54 -LEFTBRACKETKEY = 49 -RIGHTBRACKETKEY = 56 -LEFTARROWKEY = 73 -DOWNARROWKEY = 74 -RIGHTARROWKEY = 80 -UPARROWKEY = 81 -PAD0 = 59 -PAD1 = 58 -PAD2 = 64 -PAD3 = 65 -PAD4 = 63 -PAD5 = 69 -PAD6 = 70 -PAD7 = 67 -PAD8 = 68 -PAD9 = 75 -PADPF1 = 72 -PADPF2 = 71 -PADPF3 = 79 -PADPF4 = 78 -PADPERIOD = 66 -PADMINUS = 76 -PADCOMMA = 77 -PADENTER = 82 -LEFTALTKEY = 143 -RIGHTALTKEY = 144 -RIGHTCTRLKEY = 145 -F1KEY = 146 -F2KEY = 147 -F3KEY = 148 -F4KEY = 149 -F5KEY = 150 -F6KEY = 151 -F7KEY = 152 -F8KEY = 153 -F9KEY = 154 -F10KEY = 155 -F11KEY = 156 -F12KEY = 157 -PRINTSCREENKEY = 158 -SCROLLLOCKKEY = 159 -PAUSEKEY = 160 -INSERTKEY = 161 -HOMEKEY = 162 -PAGEUPKEY = 163 -ENDKEY = 164 -PAGEDOWNKEY = 165 -NUMLOCKKEY = 166 -PADVIRGULEKEY = 167 -PADASTERKEY = 168 -PADPLUSKEY = 169 -SGIRESERVED = 256 -DIAL0 = 257 -DIAL1 = 258 -DIAL2 = 259 -DIAL3 = 260 -DIAL4 = 261 -DIAL5 = 262 -DIAL6 = 263 -DIAL7 = 264 -DIAL8 = 265 -MOUSEX = 266 -MOUSEY = 267 -LPENX = 268 -LPENY = 269 -BPADX = 270 -BPADY = 271 -CURSORX = 272 -CURSORY = 273 -GHOSTX = 274 -GHOSTY = 275 -SBTX = 276 -SBTY = 277 -SBTZ = 278 -SBRX = 279 -SBRY = 280 -SBRZ = 281 -SBPERIOD = 282 -TIMER0 = 515 -TIMER1 = 516 -TIMER2 = 517 -TIMER3 = 518 -KEYBD = 513 -RAWKEYBD = 514 -VALMARK = 523 -REDRAW = 528 -INPUTCHANGE = 534 -QFULL = 535 -QREADERROR = 538 -WINFREEZE = 539 -WINTHAW = 540 -REDRAWICONIC = 541 -WINQUIT = 542 -DEPTHCHANGE = 543 -WINSHUT = 546 -DRAWOVERLAY = 547 -VIDEO = 548 -MENUBUTTON = RIGHTMOUSE -WINCLOSE = 537 -KEYBDFNAMES = 544 -KEYBDFSTRINGS = 545 -MAXSGIDEVICE = 20000 -GERROR = 524 -WMSEND = 529 -WMREPLY = 530 -WMGFCLOSE = 531 -WMTXCLOSE = 532 -MODECHANGE = 533 -PIECECHANGE = 536 diff --git a/Lib/plat-irix5/ERRNO.py b/Lib/plat-irix5/ERRNO.py deleted file mode 100755 index d49e9641e4..0000000000 --- a/Lib/plat-irix5/ERRNO.py +++ /dev/null @@ -1,147 +0,0 @@ -# Generated by h2py from /usr/include/errno.h - -# Included from sys/errno.h -__KBASE = 1000 -__IRIXBASE = 1000 -EPERM = 1 -ENOENT = 2 -ESRCH = 3 -EINTR = 4 -EIO = 5 -ENXIO = 6 -E2BIG = 7 -ENOEXEC = 8 -EBADF = 9 -ECHILD = 10 -EAGAIN = 11 -ENOMEM = 12 -EACCES = 13 -EFAULT = 14 -ENOTBLK = 15 -EBUSY = 16 -EEXIST = 17 -EXDEV = 18 -ENODEV = 19 -ENOTDIR = 20 -EISDIR = 21 -EINVAL = 22 -ENFILE = 23 -EMFILE = 24 -ENOTTY = 25 -ETXTBSY = 26 -EFBIG = 27 -ENOSPC = 28 -ESPIPE = 29 -EROFS = 30 -EMLINK = 31 -EPIPE = 32 -EDOM = 33 -ERANGE = 34 -ENOMSG = 35 -EIDRM = 36 -ECHRNG = 37 -EL2NSYNC = 38 -EL3HLT = 39 -EL3RST = 40 -ELNRNG = 41 -EUNATCH = 42 -ENOCSI = 43 -EL2HLT = 44 -EDEADLK = 45 -ENOLCK = 46 -EBADE = 50 -EBADR = 51 -EXFULL = 52 -ENOANO = 53 -EBADRQC = 54 -EBADSLT = 55 -EDEADLOCK = 56 -EBFONT = 57 -ENOSTR = 60 -ENODATA = 61 -ETIME = 62 -ENOSR = 63 -ENONET = 64 -ENOPKG = 65 -EREMOTE = 66 -ENOLINK = 67 -EADV = 68 -ESRMNT = 69 -ECOMM = 70 -EPROTO = 71 -EMULTIHOP = 74 -EBADMSG = 77 -ENAMETOOLONG = 78 -EOVERFLOW = 79 -ENOTUNIQ = 80 -EBADFD = 81 -EREMCHG = 82 -ELIBACC = 83 -ELIBBAD = 84 -ELIBSCN = 85 -ELIBMAX = 86 -ELIBEXEC = 87 -EILSEQ = 88 -ENOSYS = 89 -ELOOP = 90 -ERESTART = 91 -ESTRPIPE = 92 -ENOTEMPTY = 93 -EUSERS = 94 -ENOTSOCK = 95 -EDESTADDRREQ = 96 -EMSGSIZE = 97 -EPROTOTYPE = 98 -ENOPROTOOPT = 99 -EPROTONOSUPPORT = 120 -ESOCKTNOSUPPORT = 121 -EOPNOTSUPP = 122 -EPFNOSUPPORT = 123 -EAFNOSUPPORT = 124 -EADDRINUSE = 125 -EADDRNOTAVAIL = 126 -ENETDOWN = 127 -ENETUNREACH = 128 -ENETRESET = 129 -ECONNABORTED = 130 -ECONNRESET = 131 -ENOBUFS = 132 -EISCONN = 133 -ENOTCONN = 134 -ESHUTDOWN = 143 -ETOOMANYREFS = 144 -ETIMEDOUT = 145 -ECONNREFUSED = 146 -EHOSTDOWN = 147 -EHOSTUNREACH = 148 -EWOULDBLOCK = __KBASE+101 -EWOULDBLOCK = EAGAIN -EALREADY = 149 -EINPROGRESS = 150 -ESTALE = 151 -EIORESID = 500 -EUCLEAN = 135 -ENOTNAM = 137 -ENAVAIL = 138 -EISNAM = 139 -EREMOTEIO = 140 -EINIT = 141 -EREMDEV = 142 -ECANCELED = 158 -ECANCELED = 1000 -EDQUOT = 1133 -ENFSREMOTE = 1135 -ETCP_EBASE = 100 -ETCP_ELIMIT = 129 -ENAMI_EBASE = 129 -ENAMI_ELIMIT = 131 -ENFS_EBASE = 131 -ENFS_ELIMIT = 135 -ELASTERRNO = 135 -TCP_EBASE = ETCP_EBASE -TCP_ELIMIT = ETCP_ELIMIT -NAMI_EBASE = ENAMI_EBASE -NAMI_ELIMIT = ENAMI_ELIMIT -NFS_EBASE = ENFS_EBASE -NFS_ELIMIT = ENFS_ELIMIT -LASTERRNO = ELASTERRNO diff --git a/Lib/plat-irix5/FCNTL.py b/Lib/plat-irix5/FCNTL.py deleted file mode 100755 index 12c60fab25..0000000000 --- a/Lib/plat-irix5/FCNTL.py +++ /dev/null @@ -1,53 +0,0 @@ -# Generated by h2py from /usr/include/sys/fcntl.h -FNDELAY = 0x04 -FAPPEND = 0x08 -FSYNC = 0x10 -FNONBLOCK = 0x80 -FASYNC = 0x1000 -FNONBLK = FNONBLOCK -FDIRECT = 0x8000 -FCREAT = 0x0100 -FTRUNC = 0x0200 -FEXCL = 0x0400 -FNOCTTY = 0x0800 -O_RDONLY = 0 -O_WRONLY = 1 -O_RDWR = 2 -O_NDELAY = 0x04 -O_APPEND = 0x08 -O_SYNC = 0x10 -O_NONBLOCK = 0x80 -O_DIRECT = 0x8000 -O_CREAT = 0x100 -O_TRUNC = 0x200 -O_EXCL = 0x400 -O_NOCTTY = 0x800 -F_DUPFD = 0 -F_GETFD = 1 -F_SETFD = 2 -F_GETFL = 3 -F_SETFL = 4 -F_GETLK = 14 -F_O_GETLK = 5 -F_GETLK = 14 -F_SETLK = 6 -F_SETLKW = 7 -F_CHKFL = 8 -F_ALLOCSP = 10 -F_FREESP = 11 -F_SETBSDLK = 12 -F_SETBSDLKW = 13 -F_DIOINFO = 30 -F_RSETLK = 20 -F_RGETLK = 21 -F_RSETLKW = 22 -F_GETOWN = 23 -F_SETOWN = 24 -F_O_GETOWN = 10 -F_O_SETOWN = 11 -F_RDLCK = 01 -F_WRLCK = 02 -F_UNLCK = 03 -O_ACCMODE = 3 -FD_CLOEXEC = 1 -FD_NODUP_FORK = 4 diff --git a/Lib/plat-irix5/FL.py b/Lib/plat-irix5/FL.py deleted file mode 100755 index f85237b85f..0000000000 --- a/Lib/plat-irix5/FL.py +++ /dev/null @@ -1,289 +0,0 @@ -# Constants used by the FORMS library (module fl). -# This corresponds to "forms.h". -# Recommended use: import FL; ... FL.NORMAL_BOX ... etc. -# Alternate use: from FL import *; ... NORMAL_BOX ... etc. - -_v20 = 1 -_v21 = 1 -##import fl -##try: -## _v20 = (fl.get_rgbmode <> None) -##except: -## _v20 = 0 -##del fl - -NULL = 0 -FALSE = 0 -TRUE = 1 - -EVENT = -1 - -LABEL_SIZE = 64 -if _v20: - SHORTCUT_SIZE = 32 -PLACE_FREE = 0 -PLACE_SIZE = 1 -PLACE_ASPECT = 2 -PLACE_MOUSE = 3 -PLACE_CENTER = 4 -PLACE_POSITION = 5 -FL_PLACE_FULLSCREEN = 6 -FIND_INPUT = 0 -FIND_AUTOMATIC = 1 -FIND_MOUSE = 2 -BEGIN_GROUP = 10000 -END_GROUP = 20000 -ALIGN_TOP = 0 -ALIGN_BOTTOM = 1 -ALIGN_LEFT = 2 -ALIGN_RIGHT = 3 -ALIGN_CENTER = 4 -NO_BOX = 0 -UP_BOX = 1 -DOWN_BOX = 2 -FLAT_BOX = 3 -BORDER_BOX = 4 -SHADOW_BOX = 5 -FRAME_BOX = 6 -ROUNDED_BOX = 7 -RFLAT_BOX = 8 -RSHADOW_BOX = 9 -TOP_BOUND_COL = 51 -LEFT_BOUND_COL = 55 -BOT_BOUND_COL = 40 -RIGHT_BOUND_COL = 35 -COL1 = 47 -MCOL = 49 -LCOL = 0 -BOUND_WIDTH = 3.0 -DRAW = 0 -PUSH = 1 -RELEASE = 2 -ENTER = 3 -LEAVE = 4 -MOUSE = 5 -FOCUS = 6 -UNFOCUS = 7 -KEYBOARD = 8 -STEP = 9 -MOVE = 10 -FONT_NAME = 'Helvetica' -FONT_BOLDNAME = 'Helvetica-Bold' -FONT_ITALICNAME = 'Helvetica-Oblique' -FONT_FIXEDNAME = 'Courier' -FONT_ICONNAME = 'Icon' -SMALL_FONT = 8.0 -NORMAL_FONT = 11.0 -LARGE_FONT = 20.0 -NORMAL_STYLE = 0 -BOLD_STYLE = 1 -ITALIC_STYLE = 2 -FIXED_STYLE = 3 -ENGRAVED_STYLE = 4 -ICON_STYLE = 5 -BITMAP = 3 -NORMAL_BITMAP = 0 -BITMAP_BOXTYPE = NO_BOX -BITMAP_COL1 = 0 -BITMAP_COL2 = COL1 -BITMAP_LCOL = LCOL -BITMAP_ALIGN = ALIGN_BOTTOM -BITMAP_MAXSIZE = 128*128 -BITMAP_BW = BOUND_WIDTH -BOX = 1 -BOX_BOXTYPE = UP_BOX -BOX_COL1 = COL1 -BOX_LCOL = LCOL -BOX_ALIGN = ALIGN_CENTER -BOX_BW = BOUND_WIDTH -BROWSER = 71 -NORMAL_BROWSER = 0 -SELECT_BROWSER = 1 -HOLD_BROWSER = 2 -MULTI_BROWSER = 3 -BROWSER_BOXTYPE = DOWN_BOX -BROWSER_COL1 = COL1 -BROWSER_COL2 = 3 -BROWSER_LCOL = LCOL -BROWSER_ALIGN = ALIGN_BOTTOM -BROWSER_SLCOL = COL1 -BROWSER_BW = BOUND_WIDTH -BROWSER_LINELENGTH = 128 -BROWSER_MAXLINE = 512 -BUTTON = 11 -NORMAL_BUTTON = 0 -PUSH_BUTTON = 1 -RADIO_BUTTON = 2 -HIDDEN_BUTTON = 3 -TOUCH_BUTTON = 4 -INOUT_BUTTON = 5 -RETURN_BUTTON = 6 -if _v20: - HIDDEN_RET_BUTTON = 7 -BUTTON_BOXTYPE = UP_BOX -BUTTON_COL1 = COL1 -BUTTON_COL2 = COL1 -BUTTON_LCOL = LCOL -BUTTON_ALIGN = ALIGN_CENTER -BUTTON_MCOL1 = MCOL -BUTTON_MCOL2 = MCOL -BUTTON_BW = BOUND_WIDTH -if _v20: - CHART = 4 - BAR_CHART = 0 - HORBAR_CHART = 1 - LINE_CHART = 2 - FILLED_CHART = 3 - SPIKE_CHART = 4 - PIE_CHART = 5 - SPECIALPIE_CHART = 6 - CHART_BOXTYPE = BORDER_BOX - CHART_COL1 = COL1 - CHART_LCOL = LCOL - CHART_ALIGN = ALIGN_BOTTOM - CHART_BW = BOUND_WIDTH - CHART_MAX = 128 -CHOICE = 42 -NORMAL_CHOICE = 0 -CHOICE_BOXTYPE = DOWN_BOX -CHOICE_COL1 = COL1 -CHOICE_COL2 = LCOL -CHOICE_LCOL = LCOL -CHOICE_ALIGN = ALIGN_LEFT -CHOICE_BW = BOUND_WIDTH -CHOICE_MCOL = MCOL -CHOICE_MAXITEMS = 128 -CHOICE_MAXSTR = 64 -CLOCK = 61 -SQUARE_CLOCK = 0 -ROUND_CLOCK = 1 -CLOCK_BOXTYPE = UP_BOX -CLOCK_COL1 = 37 -CLOCK_COL2 = 42 -CLOCK_LCOL = LCOL -CLOCK_ALIGN = ALIGN_BOTTOM -CLOCK_TOPCOL = COL1 -CLOCK_BW = BOUND_WIDTH -COUNTER = 25 -NORMAL_COUNTER = 0 -SIMPLE_COUNTER = 1 -COUNTER_BOXTYPE = UP_BOX -COUNTER_COL1 = COL1 -COUNTER_COL2 = 4 -COUNTER_LCOL = LCOL -COUNTER_ALIGN = ALIGN_BOTTOM -if _v20: - COUNTER_BW = BOUND_WIDTH -else: - DEFAULT = 51 - RETURN_DEFAULT = 0 - ALWAYS_DEFAULT = 1 -DIAL = 22 -NORMAL_DIAL = 0 -LINE_DIAL = 1 -DIAL_BOXTYPE = NO_BOX -DIAL_COL1 = COL1 -DIAL_COL2 = 37 -DIAL_LCOL = LCOL -DIAL_ALIGN = ALIGN_BOTTOM -DIAL_TOPCOL = COL1 -DIAL_BW = BOUND_WIDTH -FREE = 101 -NORMAL_FREE = 1 -SLEEPING_FREE = 2 -INPUT_FREE = 3 -CONTINUOUS_FREE = 4 -ALL_FREE = 5 -INPUT = 31 -NORMAL_INPUT = 0 -if _v20: - FLOAT_INPUT = 1 - INT_INPUT = 2 - HIDDEN_INPUT = 3 - if _v21: - MULTILINE_INPUT = 4 - SECRET_INPUT = 5 -else: - ALWAYS_INPUT = 1 -INPUT_BOXTYPE = DOWN_BOX -INPUT_COL1 = 13 -INPUT_COL2 = 5 -INPUT_LCOL = LCOL -INPUT_ALIGN = ALIGN_LEFT -INPUT_TCOL = LCOL -INPUT_CCOL = 4 -INPUT_BW = BOUND_WIDTH -INPUT_MAX = 128 -LIGHTBUTTON = 12 -LIGHTBUTTON_BOXTYPE = UP_BOX -LIGHTBUTTON_COL1 = 39 -LIGHTBUTTON_COL2 = 3 -LIGHTBUTTON_LCOL = LCOL -LIGHTBUTTON_ALIGN = ALIGN_CENTER -LIGHTBUTTON_TOPCOL = COL1 -LIGHTBUTTON_MCOL = MCOL -LIGHTBUTTON_BW1 = BOUND_WIDTH -LIGHTBUTTON_BW2 = BOUND_WIDTH/2.0 -LIGHTBUTTON_MINSIZE = 12.0 -MENU = 41 -TOUCH_MENU = 0 -PUSH_MENU = 1 -MENU_BOXTYPE = BORDER_BOX -MENU_COL1 = 55 -MENU_COL2 = 37 -MENU_LCOL = LCOL -MENU_ALIGN = ALIGN_CENTER -MENU_BW = BOUND_WIDTH -MENU_MAX = 300 -POSITIONER = 23 -NORMAL_POSITIONER = 0 -POSITIONER_BOXTYPE = DOWN_BOX -POSITIONER_COL1 = COL1 -POSITIONER_COL2 = 1 -POSITIONER_LCOL = LCOL -POSITIONER_ALIGN = ALIGN_BOTTOM -POSITIONER_BW = BOUND_WIDTH -ROUNDBUTTON = 13 -ROUNDBUTTON_BOXTYPE = NO_BOX -ROUNDBUTTON_COL1 = 7 -ROUNDBUTTON_COL2 = 3 -ROUNDBUTTON_LCOL = LCOL -ROUNDBUTTON_ALIGN = ALIGN_CENTER -ROUNDBUTTON_TOPCOL = COL1 -ROUNDBUTTON_MCOL = MCOL -ROUNDBUTTON_BW = BOUND_WIDTH -SLIDER = 21 -VALSLIDER = 24 -VERT_SLIDER = 0 -HOR_SLIDER = 1 -VERT_FILL_SLIDER = 2 -HOR_FILL_SLIDER = 3 -VERT_NICE_SLIDER = 4 -HOR_NICE_SLIDER = 5 -SLIDER_BOXTYPE = DOWN_BOX -SLIDER_COL1 = COL1 -SLIDER_COL2 = COL1 -SLIDER_LCOL = LCOL -SLIDER_ALIGN = ALIGN_BOTTOM -SLIDER_BW1 = BOUND_WIDTH -SLIDER_BW2 = BOUND_WIDTH*0.75 -SLIDER_FINE = 0.05 -SLIDER_WIDTH = 0.08 -TEXT = 2 -NORMAL_TEXT = 0 -TEXT_BOXTYPE = NO_BOX -TEXT_COL1 = COL1 -TEXT_LCOL = LCOL -TEXT_ALIGN = ALIGN_LEFT -TEXT_BW = BOUND_WIDTH -TIMER = 62 -NORMAL_TIMER = 0 -VALUE_TIMER = 1 -HIDDEN_TIMER = 2 -TIMER_BOXTYPE = DOWN_BOX -TIMER_COL1 = COL1 -TIMER_COL2 = 1 -TIMER_LCOL = LCOL -TIMER_ALIGN = ALIGN_CENTER -TIMER_BW = BOUND_WIDTH -TIMER_BLINKRATE = 0.2 diff --git a/Lib/plat-irix5/GET.py b/Lib/plat-irix5/GET.py deleted file mode 100755 index 9c3d7d6952..0000000000 --- a/Lib/plat-irix5/GET.py +++ /dev/null @@ -1,59 +0,0 @@ -# Symbols from <gl/get.h> - -BCKBUFFER = 0x1 -FRNTBUFFER = 0x2 -DRAWZBUFFER = 0x4 -DMRGB = 0 -DMSINGLE = 1 -DMDOUBLE = 2 -DMRGBDOUBLE = 5 -HZ30 = 0 -HZ60 = 1 -NTSC = 2 -HDTV = 3 -VGA = 4 -IRIS3K = 5 -PR60 = 6 -PAL = 9 -HZ30_SG = 11 -A343 = 14 -STR_RECT = 15 -VOF0 = 16 -VOF1 = 17 -VOF2 = 18 -VOF3 = 19 -SGI0 = 20 -SGI1 = 21 -SGI2 = 22 -HZ72 = 23 -GL_VIDEO_REG = 0x00800000 -GLV_GENLOCK = 0x00000001 -GLV_UNBLANK = 0x00000002 -GLV_SRED = 0x00000004 -GLV_SGREEN = 0x00000008 -GLV_SBLUE = 0x00000010 -GLV_SALPHA = 0x00000020 -GLV_TTLGENLOCK = 0x00000080 -GLV_TTLSYNC = GLV_TTLGENLOCK -GLV_GREENGENLOCK = 0x0000100 -LEFTPLANE = 0x0001 -RIGHTPLANE = 0x0002 -BOTTOMPLANE = 0x0004 -TOPPLANE = 0x0008 -NEARPLANE = 0x0010 -FARPLANE = 0x0020 -## GETDEF = __GL_GET_H__ -NOBUFFER = 0x0 -BOTHBUFFERS = 0x3 -DMINTENSITYSINGLE = 3 -DMINTENSITYDOUBLE = 4 -MONSPECIAL = 0x20 -HZ50 = 3 -MONA = 5 -MONB = 6 -MONC = 7 -MOND = 8 -MON_ALL = 12 -MON_GEN_ALL = 13 -CMAPMULTI = 0 -CMAPONE = 1 diff --git a/Lib/plat-irix5/GL.py b/Lib/plat-irix5/GL.py deleted file mode 100755 index 9f02f65f3a..0000000000 --- a/Lib/plat-irix5/GL.py +++ /dev/null @@ -1,393 +0,0 @@ -NULL = 0 -FALSE = 0 -TRUE = 1 -ATTRIBSTACKDEPTH = 10 -VPSTACKDEPTH = 8 -MATRIXSTACKDEPTH = 32 -NAMESTACKDEPTH = 1025 -STARTTAG = -2 -ENDTAG = -3 -BLACK = 0 -RED = 1 -GREEN = 2 -YELLOW = 3 -BLUE = 4 -MAGENTA = 5 -CYAN = 6 -WHITE = 7 -PUP_CLEAR = 0 -PUP_COLOR = 1 -PUP_BLACK = 2 -PUP_WHITE = 3 -NORMALDRAW = 0x010 -PUPDRAW = 0x020 -OVERDRAW = 0x040 -UNDERDRAW = 0x080 -CURSORDRAW = 0x100 -DUALDRAW = 0x200 -PATTERN_16 = 16 -PATTERN_32 = 32 -PATTERN_64 = 64 -PATTERN_16_SIZE = 16 -PATTERN_32_SIZE = 64 -PATTERN_64_SIZE = 256 -SRC_AUTO = 0 -SRC_FRONT = 1 -SRC_BACK = 2 -SRC_ZBUFFER = 3 -SRC_PUP = 4 -SRC_OVER = 5 -SRC_UNDER = 6 -SRC_FRAMEGRABBER = 7 -BF_ZERO = 0 -BF_ONE = 1 -BF_DC = 2 -BF_SC = 2 -BF_MDC = 3 -BF_MSC = 3 -BF_SA = 4 -BF_MSA = 5 -BF_DA = 6 -BF_MDA = 7 -BF_MIN_SA_MDA = 8 -AF_NEVER = 0 -AF_LESS = 1 -AF_EQUAL = 2 -AF_LEQUAL = 3 -AF_GREATER = 4 -AF_NOTEQUAL = 5 -AF_GEQUAL = 6 -AF_ALWAYS = 7 -ZF_NEVER = 0 -ZF_LESS = 1 -ZF_EQUAL = 2 -ZF_LEQUAL = 3 -ZF_GREATER = 4 -ZF_NOTEQUAL = 5 -ZF_GEQUAL = 6 -ZF_ALWAYS = 7 -ZSRC_DEPTH = 0 -ZSRC_COLOR = 1 -SMP_OFF = 0x0 -SMP_ON = 0x1 -SMP_SMOOTHER = 0x2 -SML_OFF = 0x0 -SML_ON = 0x1 -SML_SMOOTHER = 0x2 -SML_END_CORRECT = 0x4 -PYSM_OFF = 0 -PYSM_ON = 1 -PYSM_SHRINK = 2 -DT_OFF = 0 -DT_ON = 1 -PUP_NONE = 0 -PUP_GREY = 0x1 -PUP_BOX = 0x2 -PUP_CHECK = 0x4 -GLC_OLDPOLYGON = 0 -GLC_ZRANGEMAP = 1 -GLC_MQUEUERATE = 2 -GLC_SOFTATTACH = 3 -GLC_MANAGEBG = 4 -GLC_SLOWMAPCOLORS = 5 -GLC_INPUTCHANGEBUG = 6 -GLC_NOBORDERBUG = 7 -GLC_SET_VSYNC = 8 -GLC_GET_VSYNC = 9 -GLC_VSYNC_SLEEP = 10 -GLC_COMPATRATE = 15 -C16X1 = 0 -C16X2 = 1 -C32X1 = 2 -C32X2 = 3 -CCROSS = 4 -FLAT = 0 -GOURAUD = 1 -LO_ZERO = 0x0 -LO_AND = 0x1 -LO_ANDR = 0x2 -LO_SRC = 0x3 -LO_ANDI = 0x4 -LO_DST = 0x5 -LO_XOR = 0x6 -LO_OR = 0x7 -LO_NOR = 0x8 -LO_XNOR = 0x9 -LO_NDST = 0xa -LO_ORR = 0xb -LO_NSRC = 0xc -LO_ORI = 0xd -LO_NAND = 0xe -LO_ONE = 0xf -INFOCUSSCRN = -2 -ST_KEEP = 0 -ST_ZERO = 1 -ST_REPLACE = 2 -ST_INCR = 3 -ST_DECR = 4 -ST_INVERT = 5 -SF_NEVER = 0 -SF_LESS = 1 -SF_EQUAL = 2 -SF_LEQUAL = 3 -SF_GREATER = 4 -SF_NOTEQUAL = 5 -SF_GEQUAL = 6 -SF_ALWAYS = 7 -SS_OFF = 0 -SS_DEPTH = 1 -PYM_FILL = 1 -PYM_POINT = 2 -PYM_LINE = 3 -PYM_HOLLOW = 4 -PYM_LINE_FAST = 5 -FG_OFF = 0 -FG_ON = 1 -FG_DEFINE = 2 -FG_VTX_EXP = 2 -FG_VTX_LIN = 3 -FG_PIX_EXP = 4 -FG_PIX_LIN = 5 -FG_VTX_EXP2 = 6 -FG_PIX_EXP2 = 7 -PM_SHIFT = 0 -PM_EXPAND = 1 -PM_C0 = 2 -PM_C1 = 3 -PM_ADD24 = 4 -PM_SIZE = 5 -PM_OFFSET = 6 -PM_STRIDE = 7 -PM_TTOB = 8 -PM_RTOL = 9 -PM_ZDATA = 10 -PM_WARP = 11 -PM_RDX = 12 -PM_RDY = 13 -PM_CDX = 14 -PM_CDY = 15 -PM_XSTART = 16 -PM_YSTART = 17 -PM_VO1 = 1000 -NAUTO = 0 -NNORMALIZE = 1 -AC_CLEAR = 0 -AC_ACCUMULATE = 1 -AC_CLEAR_ACCUMULATE = 2 -AC_RETURN = 3 -AC_MULT = 4 -AC_ADD = 5 -CP_OFF = 0 -CP_ON = 1 -CP_DEFINE = 2 -SB_RESET = 0 -SB_TRACK = 1 -SB_HOLD = 2 -RD_FREEZE = 0x00000001 -RD_ALPHAONE = 0x00000002 -RD_IGNORE_UNDERLAY = 0x00000004 -RD_IGNORE_OVERLAY = 0x00000008 -RD_IGNORE_PUP = 0x00000010 -RD_OFFSCREEN = 0x00000020 -GD_XPMAX = 0 -GD_YPMAX = 1 -GD_XMMAX = 2 -GD_YMMAX = 3 -GD_ZMIN = 4 -GD_ZMAX = 5 -GD_BITS_NORM_SNG_RED = 6 -GD_BITS_NORM_SNG_GREEN = 7 -GD_BITS_NORM_SNG_BLUE = 8 -GD_BITS_NORM_DBL_RED = 9 -GD_BITS_NORM_DBL_GREEN = 10 -GD_BITS_NORM_DBL_BLUE = 11 -GD_BITS_NORM_SNG_CMODE = 12 -GD_BITS_NORM_DBL_CMODE = 13 -GD_BITS_NORM_SNG_MMAP = 14 -GD_BITS_NORM_DBL_MMAP = 15 -GD_BITS_NORM_ZBUFFER = 16 -GD_BITS_OVER_SNG_CMODE = 17 -GD_BITS_UNDR_SNG_CMODE = 18 -GD_BITS_PUP_SNG_CMODE = 19 -GD_BITS_NORM_SNG_ALPHA = 21 -GD_BITS_NORM_DBL_ALPHA = 22 -GD_BITS_CURSOR = 23 -GD_OVERUNDER_SHARED = 24 -GD_BLEND = 25 -GD_CIFRACT = 26 -GD_CROSSHAIR_CINDEX = 27 -GD_DITHER = 28 -GD_LINESMOOTH_CMODE = 30 -GD_LINESMOOTH_RGB = 31 -GD_LOGICOP = 33 -GD_NSCRNS = 35 -GD_NURBS_ORDER = 36 -GD_NBLINKS = 37 -GD_NVERTEX_POLY = 39 -GD_PATSIZE_64 = 40 -GD_PNTSMOOTH_CMODE = 41 -GD_PNTSMOOTH_RGB = 42 -GD_PUP_TO_OVERUNDER = 43 -GD_READSOURCE = 44 -GD_READSOURCE_ZBUFFER = 48 -GD_STEREO = 50 -GD_SUBPIXEL_LINE = 51 -GD_SUBPIXEL_PNT = 52 -GD_SUBPIXEL_POLY = 53 -GD_TRIMCURVE_ORDER = 54 -GD_WSYS = 55 -GD_ZDRAW_GEOM = 57 -GD_ZDRAW_PIXELS = 58 -GD_SCRNTYPE = 61 -GD_TEXTPORT = 62 -GD_NMMAPS = 63 -GD_FRAMEGRABBER = 64 -GD_TIMERHZ = 66 -GD_DBBOX = 67 -GD_AFUNCTION = 68 -GD_ALPHA_OVERUNDER = 69 -GD_BITS_ACBUF = 70 -GD_BITS_ACBUF_HW = 71 -GD_BITS_STENCIL = 72 -GD_CLIPPLANES = 73 -GD_FOGVERTEX = 74 -GD_LIGHTING_TWOSIDE = 76 -GD_POLYMODE = 77 -GD_POLYSMOOTH = 78 -GD_SCRBOX = 79 -GD_TEXTURE = 80 -GD_FOGPIXEL = 81 -GD_TEXTURE_PERSP = 82 -GD_MUXPIPES = 83 -GD_NOLIMIT = -2 -GD_WSYS_NONE = 0 -GD_WSYS_4S = 1 -GD_SCRNTYPE_WM = 0 -GD_SCRNTYPE_NOWM = 1 -N_PIXEL_TOLERANCE = 1 -N_CULLING = 2 -N_DISPLAY = 3 -N_ERRORCHECKING = 4 -N_SUBDIVISIONS = 5 -N_S_STEPS = 6 -N_T_STEPS = 7 -N_TILES = 8 -N_TMP1 = 9 -N_TMP2 = 10 -N_TMP3 = 11 -N_TMP4 = 12 -N_TMP5 = 13 -N_TMP6 = 14 -N_FILL = 1.0 -N_OUTLINE_POLY = 2.0 -N_OUTLINE_PATCH = 5.0 -N_ISOLINE_S = 12.0 -N_ST = 0x8 -N_STW = 0xd -N_XYZ = 0x4c -N_XYZW = 0x51 -N_TEX = 0x88 -N_TEXW = 0x8d -N_RGBA = 0xd0 -N_RGBAW = 0xd5 -N_P2D = 0x8 -N_P2DR = 0xd -N_V3D = 0x4c -N_V3DR = 0x51 -N_T2D = 0x88 -N_T2DR = 0x8d -N_C4D = 0xd0 -N_C4DR = 0xd5 -LMNULL = 0.0 -MSINGLE = 0 -MPROJECTION = 1 -MVIEWING = 2 -MTEXTURE = 3 -MAXLIGHTS = 8 -MAXRESTRICTIONS = 4 -DEFMATERIAL = 0 -EMISSION = 1 -AMBIENT = 2 -DIFFUSE = 3 -SPECULAR = 4 -SHININESS = 5 -COLORINDEXES = 6 -ALPHA = 7 -DEFLIGHT = 100 -LCOLOR = 101 -POSITION = 102 -SPOTDIRECTION = 103 -SPOTLIGHT = 104 -DEFLMODEL = 200 -LOCALVIEWER = 201 -ATTENUATION = 202 -ATTENUATION2 = 203 -TWOSIDE = 204 -MATERIAL = 1000 -BACKMATERIAL = 1001 -LIGHT0 = 1100 -LIGHT1 = 1101 -LIGHT2 = 1102 -LIGHT3 = 1103 -LIGHT4 = 1104 -LIGHT5 = 1105 -LIGHT6 = 1106 -LIGHT7 = 1107 -LMODEL = 1200 -LMC_COLOR = 0 -LMC_EMISSION = 1 -LMC_AMBIENT = 2 -LMC_DIFFUSE = 3 -LMC_SPECULAR = 4 -LMC_AD = 5 -LMC_NULL = 6 -TX_MINFILTER = 0x100 -TX_MAGFILTER = 0x200 -TX_WRAP = 0x300 -TX_WRAP_S = 0x310 -TX_WRAP_T = 0x320 -TX_TILE = 0x400 -TX_BORDER = 0x500 -TX_NULL = 0x000 -TX_POINT = 0x110 -TX_BILINEAR = 0x220 -TX_MIPMAP = 0x120 -TX_MIPMAP_POINT = 0x121 -TX_MIPMAP_LINEAR = 0x122 -TX_MIPMAP_BILINEAR = 0x123 -TX_MIPMAP_TRILINEAR = 0x124 -TX_REPEAT = 0x301 -TX_CLAMP = 0x302 -TX_SELECT = 0x303 -TX_TEXTURE_0 = 0 -TV_MODULATE = 0x101 -TV_BLEND = 0x102 -TV_DECAL = 0x103 -TV_COLOR = 0x200 -TV_NULL = 0x000 -TV_ENV0 = 0 -TX_S = 0 -TX_T = 1 -TG_OFF = 0 -TG_ON = 1 -TG_CONTOUR = 2 -TG_LINEAR = 3 -TG_SPHEREMAP = 4 -TG_REFRACTMAP = 5 -DGLSINK = 0 -DGLLOCAL = 1 -DGLTSOCKET = 2 -DGL4DDN = 3 -PUP_CURSOR = PUP_COLOR -FATAL = 1 -WARNING = 2 -ASK_CONT = 3 -ASK_RESTART = 4 -XMAXSCREEN = 1279 -YMAXSCREEN = 1023 -XMAXMEDIUM = 1023 -YMAXMEDIUM = 767 -XMAX170 = 645 -YMAX170 = 484 -XMAXPAL = 779 -YMAXPAL = 574 diff --git a/Lib/plat-irix5/GLWS.py b/Lib/plat-irix5/GLWS.py deleted file mode 100755 index 69dab7143f..0000000000 --- a/Lib/plat-irix5/GLWS.py +++ /dev/null @@ -1,12 +0,0 @@ -NOERROR = 0 -NOCONTEXT = -1 -NODISPLAY = -2 -NOWINDOW = -3 -NOGRAPHICS = -4 -NOTTOP = -5 -NOVISUAL = -6 -BUFSIZE = -7 -BADWINDOW = -8 -ALREADYBOUND = -100 -BINDFAILED = -101 -SETFAILED = -102 diff --git a/Lib/plat-irix5/IN.py b/Lib/plat-irix5/IN.py deleted file mode 100755 index 325a0217f7..0000000000 --- a/Lib/plat-irix5/IN.py +++ /dev/null @@ -1,83 +0,0 @@ -# Generated by h2py from /usr/include/netinet/in.h -IPPROTO_IP = 0 -IPPROTO_ICMP = 1 -IPPROTO_IGMP = 2 -IPPROTO_GGP = 3 -IPPROTO_TCP = 6 -IPPROTO_EGP = 8 -IPPROTO_PUP = 12 -IPPROTO_UDP = 17 -IPPROTO_IDP = 22 -IPPROTO_TP = 29 -IPPROTO_XTP = 36 -IPPROTO_HELLO = 63 -IPPROTO_ND = 77 -IPPROTO_EON = 80 -IPPROTO_RAW = 255 -IPPROTO_MAX = 256 -IPPORT_RESERVED = 1024 -IPPORT_USERRESERVED = 5000 -IN_CLASSA_NET = 0xff000000 -IN_CLASSA_NSHIFT = 24 -IN_CLASSA_HOST = 0x00ffffff -IN_CLASSA_MAX = 128 -IN_CLASSB_NET = 0xffff0000 -IN_CLASSB_NSHIFT = 16 -IN_CLASSB_HOST = 0x0000ffff -IN_CLASSB_MAX = 65536 -IN_CLASSC_NET = 0xffffff00 -IN_CLASSC_NSHIFT = 8 -IN_CLASSC_HOST = 0x000000ff -IN_CLASSD_NET = 0xf0000000 -IN_CLASSD_NSHIFT = 28 -IN_CLASSD_HOST = 0x0fffffff -INADDR_ANY = 0x00000000 -INADDR_BROADCAST = 0xffffffff -INADDR_LOOPBACK = 0x7F000001 -INADDR_UNSPEC_GROUP = 0xe0000000 -INADDR_ALLHOSTS_GROUP = 0xe0000001 -INADDR_MAX_LOCAL_GROUP = 0xe00000ff -INADDR_NONE = 0xffffffff -IN_LOOPBACKNET = 127 -IP_OPTIONS = 1 -IP_MULTICAST_IF = 2 -IP_MULTICAST_TTL = 3 -IP_MULTICAST_LOOP = 4 -IP_ADD_MEMBERSHIP = 5 -IP_DROP_MEMBERSHIP = 6 -IP_HDRINCL = 7 -IP_TOS = 8 -IP_TTL = 9 -IP_RECVOPTS = 10 -IP_RECVRETOPTS = 11 -IP_RECVDSTADDR = 12 -IP_RETOPTS = 13 -IP_OPTIONS = 1 -IP_HDRINCL = 2 -IP_TOS = 3 -IP_TTL = 4 -IP_RECVOPTS = 5 -IP_RECVRETOPTS = 6 -IP_RECVDSTADDR = 7 -IP_RETOPTS = 8 -IP_MULTICAST_IF = 20 -IP_MULTICAST_TTL = 21 -IP_MULTICAST_LOOP = 22 -IP_ADD_MEMBERSHIP = 23 -IP_DROP_MEMBERSHIP = 24 -IRIX4_IP_OPTIONS = 1 -IRIX4_IP_MULTICAST_IF = 2 -IRIX4_IP_MULTICAST_TTL = 3 -IRIX4_IP_MULTICAST_LOOP = 4 -IRIX4_IP_ADD_MEMBERSHIP = 5 -IRIX4_IP_DROP_MEMBERSHIP = 6 -IRIX4_IP_HDRINCL = 7 -IRIX4_IP_TOS = 8 -IRIX4_IP_TTL = 9 -IRIX4_IP_RECVOPTS = 10 -IRIX4_IP_RECVRETOPTS = 11 -IRIX4_IP_RECVDSTADDR = 12 -IRIX4_IP_RETOPTS = 13 -IP_DEFAULT_MULTICAST_TTL = 1 -IP_DEFAULT_MULTICAST_LOOP = 1 -IP_MAX_MEMBERSHIPS = 20 diff --git a/Lib/plat-irix5/IOCTL.py b/Lib/plat-irix5/IOCTL.py deleted file mode 100755 index cec3c3f6a9..0000000000 --- a/Lib/plat-irix5/IOCTL.py +++ /dev/null @@ -1,233 +0,0 @@ -# These lines were mostly generated by h2py.py (see demo/scripts) -# from <sys/ioctl.h>, <sys/termio.h> and <termios.h> on Irix 4.0.2 -# with some manual changes to cope with imperfections in h2py.py. -# The applicability on other systems is not clear; especially non-SYSV -# systems may have a totally different set of ioctls. - -IOCTYPE = 0xff00 -LIOC = (ord('l')<<8) -LIOCGETP = (LIOC|1) -LIOCSETP = (LIOC|2) -LIOCGETS = (LIOC|5) -LIOCSETS = (LIOC|6) -DIOC = (ord('d')<<8) -DIOCGETC = (DIOC|1) -DIOCGETB = (DIOC|2) -DIOCSETE = (DIOC|3) -IOCPARM_MASK = 0x7f -IOC_VOID = 0x20000000 -IOC_OUT = 0x40000000 -IOC_IN = 0x80000000 -IOC_INOUT = (IOC_IN|IOC_OUT) -int = 'i' -short = 'h' -long = 'l' -def sizeof(t): import struct; return struct.calcsize(t) -def _IO(x,y): return (IOC_VOID|((x)<<8)|y) -def _IOR(x,y,t): return (IOC_OUT|((sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|y) -def _IOW(x,y,t): return (IOC_IN|((sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|y) -# this should be _IORW, but stdio got there first -def _IOWR(x,y,t): return (IOC_INOUT|((sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|y) -FIONREAD = _IOR(ord('f'), 127, int) -FIONBIO = _IOW(ord('f'), 126, int) -FIOASYNC = _IOW(ord('f'), 125, int) -FIOSETOWN = _IOW(ord('f'), 124, int) -FIOGETOWN = _IOR(ord('f'), 123, int) -NCC = 8 -NCC_PAD = 7 -NCC_EXT = 16 -NCCS = (NCC+NCC_PAD+NCC_EXT) -VINTR = 0 -VQUIT = 1 -VERASE = 2 -VKILL = 3 -VEOF = 4 -VEOL = 5 -VEOL2 = 6 -VMIN = VEOF -VTIME = VEOL -VSWTCH = 7 -VLNEXT = (NCC+NCC_PAD+0) -VWERASE = (NCC+NCC_PAD+1) -VRPRNT = (NCC+NCC_PAD+2) -VFLUSHO = (NCC+NCC_PAD+3) -VSTOP = (NCC+NCC_PAD+4) -VSTART = (NCC+NCC_PAD+5) -CNUL = '\0' -CDEL = '\377' -CESC = '\\' -CINTR = '\177' -CQUIT = '\34' -CBRK = '\377' -def CTRL(c): return ord(c) & 0x0f -CERASE = CTRL('H') -CKILL = CTRL('U') -CEOF = CTRL('d') -CEOT = CEOF -CSTART = CTRL('q') -CSTOP = CTRL('s') -CSWTCH = CTRL('z') -CSUSP = CSWTCH -CNSWTCH = 0 -CLNEXT = CTRL('v') -CWERASE = CTRL('w') -CFLUSHO = CTRL('o') -CFLUSH = CFLUSHO -CRPRNT = CTRL('r') -CDSUSP = CTRL('y') -IGNBRK = 0000001 -BRKINT = 0000002 -IGNPAR = 0000004 -PARMRK = 0000010 -INPCK = 0000020 -ISTRIP = 0000040 -INLCR = 0000100 -IGNCR = 0000200 -ICRNL = 0000400 -IUCLC = 0001000 -IXON = 0002000 -IXANY = 0004000 -IXOFF = 0010000 -IBLKMD = 0020000 -OPOST = 0000001 -OLCUC = 0000002 -ONLCR = 0000004 -OCRNL = 0000010 -ONOCR = 0000020 -ONLRET = 0000040 -OFILL = 0000100 -OFDEL = 0000200 -NLDLY = 0000400 -NL0 = 0 -NL1 = 0000400 -CRDLY = 0003000 -CR0 = 0 -CR1 = 0001000 -CR2 = 0002000 -CR3 = 0003000 -TABDLY = 0014000 -TAB0 = 0 -TAB1 = 0004000 -TAB2 = 0010000 -TAB3 = 0014000 -BSDLY = 0020000 -BS0 = 0 -BS1 = 0020000 -VTDLY = 0040000 -VT0 = 0 -VT1 = 0040000 -FFDLY = 0100000 -FF0 = 0 -FF1 = 0100000 -CBAUD = 0000017 -B0 = 0 -B50 = 0000001 -B75 = 0000002 -B110 = 0000003 -B134 = 0000004 -B150 = 0000005 -B200 = 0000006 -B300 = 0000007 -B600 = 0000010 -B1200 = 0000011 -B1800 = 0000012 -B2400 = 0000013 -B4800 = 0000014 -B9600 = 0000015 -B19200 = 0000016 -EXTA = 0000016 -B38400 = 0000017 -EXTB = 0000017 -CSIZE = 0000060 -CS5 = 0 -CS6 = 0000020 -CS7 = 0000040 -CS8 = 0000060 -CSTOPB = 0000100 -CREAD = 0000200 -PARENB = 0000400 -PARODD = 0001000 -HUPCL = 0002000 -CLOCAL = 0004000 -LOBLK = 0040000 -ISIG = 0000001 -ICANON = 0000002 -XCASE = 0000004 -ECHO = 0000010 -ECHOE = 0000020 -ECHOK = 0000040 -ECHONL = 0000100 -NOFLSH = 0000200 -IIEXTEN = 0000400 -ITOSTOP = 0001000 -SSPEED = B9600 -IOCTYPE = 0xff00 -TIOC = (ord('T')<<8) -oTCGETA = (TIOC|1) -oTCSETA = (TIOC|2) -oTCSETAW = (TIOC|3) -oTCSETAF = (TIOC|4) -TCSBRK = (TIOC|5) -TCXONC = (TIOC|6) -TCFLSH = (TIOC|7) -TCGETA = (TIOC|8) -TCSETA = (TIOC|9) -TCSETAW = (TIOC|10) -TCSETAF = (TIOC|11) -TIOCFLUSH = (TIOC|12) -TCDSET = (TIOC|32) -TCBLKMD = (TIOC|33) -TIOCPKT = (TIOC|112) -TIOCPKT_DATA = 0x00 -TIOCPKT_FLUSHREAD = 0x01 -TIOCPKT_FLUSHWRITE = 0x02 -TIOCPKT_NOSTOP = 0x10 -TIOCPKT_DOSTOP = 0x20 -TIOCNOTTY = (TIOC|113) -TIOCSTI = (TIOC|114) -TIOCSPGRP = _IOW(ord('t'), 118, int) -TIOCGPGRP = _IOR(ord('t'), 119, int) -TIOCCONS = _IOW(ord('t'), 120, int) -struct_winsize = 'hhhh' -TIOCGWINSZ = _IOR(ord('t'), 104, struct_winsize) -TIOCSWINSZ = _IOW(ord('t'), 103, struct_winsize) -TFIOC = (ord('F')<<8) -oFIONREAD = (TFIOC|127) -LDIOC = (ord('D')<<8) -LDOPEN = (LDIOC|0) -LDCLOSE = (LDIOC|1) -LDCHG = (LDIOC|2) -LDGETT = (LDIOC|8) -LDSETT = (LDIOC|9) -TERM_NONE = 0 -TERM_TEC = 1 -TERM_V61 = 2 -TERM_V10 = 3 -TERM_TEX = 4 -TERM_D40 = 5 -TERM_H45 = 6 -TERM_D42 = 7 -TM_NONE = 0000 -TM_SNL = 0001 -TM_ANL = 0002 -TM_LCF = 0004 -TM_CECHO = 0010 -TM_CINVIS = 0020 -TM_SET = 0200 -LDISC0 = 0 -LDISC1 = 1 -NTTYDISC = LDISC1 -VSUSP = VSWTCH -TCSANOW = 0 -TCSADRAIN = 1 -TCSAFLUSH = 2 -TCIFLUSH = 0 -TCOFLUSH = 1 -TCIOFLUSH = 2 -TCOOFF = 0 -TCOON = 1 -TCIOFF = 2 -TCION = 3 -TO_STOP = LOBLK -IEXTEN = IIEXTEN -TOSTOP = ITOSTOP diff --git a/Lib/plat-irix5/SOCKET.py b/Lib/plat-irix5/SOCKET.py deleted file mode 100755 index 0ba0742186..0000000000 --- a/Lib/plat-irix5/SOCKET.py +++ /dev/null @@ -1,108 +0,0 @@ -# Generated by h2py from /usr/include/sys/socket.h -SOCK_STREAM = 1 -SOCK_DGRAM = 2 -SOCK_RAW = 3 -SOCK_RDM = 4 -SOCK_SEQPACKET = 5 -NC_TPI_CLTS = 1 -NC_TPI_COTS = 2 -NC_TPI_COTS_ORD = 3 -NC_TPI_RAW = 4 -SOCK_DGRAM = NC_TPI_CLTS -SOCK_STREAM = NC_TPI_COTS -SOCK_RAW = NC_TPI_RAW -SOCK_RDM = 5 -SOCK_SEQPACKET = 6 -IRIX4_SOCK_STREAM = 1 -IRIX4_SOCK_DGRAM = 2 -IRIX4_SOCK_RAW = 3 -IRIX4_SOCK_RDM = 4 -IRIX4_SOCK_SEQPACKET = 5 -SO_DEBUG = 0x0001 -SO_ACCEPTCONN = 0x0002 -SO_REUSEADDR = 0x0004 -SO_KEEPALIVE = 0x0008 -SO_DONTROUTE = 0x0010 -SO_BROADCAST = 0x0020 -SO_USELOOPBACK = 0x0040 -SO_LINGER = 0x0080 -SO_OOBINLINE = 0x0100 -SO_REUSEPORT = 0x0200 -SO_ORDREL = 0x0200 -SO_IMASOCKET = 0x0400 -SO_CHAMELEON = 0x1000 -SO_SNDBUF = 0x1001 -SO_RCVBUF = 0x1002 -SO_SNDLOWAT = 0x1003 -SO_RCVLOWAT = 0x1004 -SO_SNDTIMEO = 0x1005 -SO_RCVTIMEO = 0x1006 -SO_ERROR = 0x1007 -SO_TYPE = 0x1008 -SO_PROTOTYPE = 0x1009 -SOL_SOCKET = 0xffff -AF_UNSPEC = 0 -AF_UNIX = 1 -AF_INET = 2 -AF_IMPLINK = 3 -AF_PUP = 4 -AF_CHAOS = 5 -AF_NS = 6 -AF_ISO = 7 -AF_ECMA = 8 -AF_DATAKIT = 9 -AF_CCITT = 10 -AF_SNA = 11 -AF_DECnet = 12 -AF_DLI = 13 -AF_LAT = 14 -AF_HYLINK = 15 -AF_APPLETALK = 16 -AF_ROUTE = 17 -AF_RAW = 18 -AF_LINK = 18 -pseudo_AF_XTP = 19 -AF_NIT = 17 -AF_802 = 18 -AF_OSI = 19 -AF_X25 = 20 -AF_OSINET = 21 -AF_GOSIP = 22 -AF_SDL = 23 -AF_MAX = (AF_SDL+1) -PF_UNSPEC = AF_UNSPEC -PF_UNIX = AF_UNIX -PF_INET = AF_INET -PF_IMPLINK = AF_IMPLINK -PF_PUP = AF_PUP -PF_CHAOS = AF_CHAOS -PF_NS = AF_NS -PF_ISO = AF_ISO -PF_ECMA = AF_ECMA -PF_DATAKIT = AF_DATAKIT -PF_CCITT = AF_CCITT -PF_SNA = AF_SNA -PF_DECnet = AF_DECnet -PF_DLI = AF_DLI -PF_LAT = AF_LAT -PF_HYLINK = AF_HYLINK -PF_APPLETALK = AF_APPLETALK -PF_ROUTE = AF_ROUTE -PF_LINK = AF_LINK -PF_XTP = pseudo_AF_XTP -PF_RAW = AF_RAW -PF_NIT = AF_NIT -PF_802 = AF_802 -PF_OSI = AF_OSI -PF_X25 = AF_X25 -PF_OSINET = AF_OSINET -PF_GOSIP = AF_GOSIP -PF_MAX = AF_MAX -SOMAXCONN = 5 -MSG_OOB = 0x1 -MSG_PEEK = 0x2 -MSG_DONTROUTE = 0x4 -MSG_EOR = 0x8 -MSG_BTAG = 0x40 -MSG_ETAG = 0x80 -MSG_MAXIOVLEN = 16 diff --git a/Lib/plat-irix5/SV.py b/Lib/plat-irix5/SV.py deleted file mode 100755 index 08fb91798a..0000000000 --- a/Lib/plat-irix5/SV.py +++ /dev/null @@ -1,120 +0,0 @@ -NTSC_XMAX = 640 -NTSC_YMAX = 480 -PAL_XMAX = 768 -PAL_YMAX = 576 -BLANKING_BUFFER_SIZE = 2 - -MAX_SOURCES = 2 - -# mode parameter for Bind calls -IN_OFF = 0 # No Video -IN_OVER = 1 # Video over graphics -IN_UNDER = 2 # Video under graphics -IN_REPLACE = 3 # Video replaces entire win - -# mode parameters for LoadMap calls. Specifies buffer, always 256 entries -INPUT_COLORMAP = 0 # tuples of 8-bit RGB -CHROMA_KEY_MAP = 1 # tuples of 8-bit RGB -COLOR_SPACE_MAP = 2 # tuples of 8-bit RGB -GAMMA_MAP = 3 # tuples of 24-bit red values - -# mode parameters for UseExclusive calls -INPUT = 0 -OUTPUT = 1 -IN_OUT = 2 - -# Format constants for the capture routines -RGB8_FRAMES = 0 # noninterleaved 8 bit 3:2:3 RBG fields -RGB32_FRAMES = 1 # 32-bit 8:8:8 RGB frames -YUV411_FRAMES = 2 # interleaved, 8:2:2 YUV format -YUV411_FRAMES_AND_BLANKING_BUFFER = 3 - -# -# sv.SetParam is passed variable length argument lists, -# consisting of <name, value> pairs. The following -# constants identify argument names. -# -_NAME_BASE = 1000 -SOURCE = (_NAME_BASE + 0) -SOURCE1 = 0 -SOURCE2 = 1 -SOURCE3 = 2 -COLOR = (_NAME_BASE + 1) -DEFAULT_COLOR = 0 -USER_COLOR = 1 -MONO = 2 -OUTPUTMODE = (_NAME_BASE + 2) -LIVE_OUTPUT = 0 -STILL24_OUT = 1 -FREEZE = (_NAME_BASE + 3) -DITHER = (_NAME_BASE + 4) -OUTPUT_FILTER = (_NAME_BASE + 5) -HUE = (_NAME_BASE + 6) -GENLOCK = (_NAME_BASE + 7) -GENLOCK_OFF = 0 -GENLOCK_ON = 1 -GENLOCK_HOUSE = 2 -BROADCAST = (_NAME_BASE + 8) -NTSC = 0 -PAL = 1 -VIDEO_MODE = (_NAME_BASE + 9) -COMP = 0 -SVIDEO = 1 -INPUT_BYPASS = (_NAME_BASE + 10) -FIELDDROP = (_NAME_BASE + 11) -SLAVE = (_NAME_BASE + 12) -APERTURE_FACTOR = (_NAME_BASE + 13) -AFACTOR_0 = 0 -AFACTOR_QTR = 1 -AFACTOR_HLF = 2 -AFACTOR_ONE = 3 -CORING = (_NAME_BASE + 14) -COR_OFF = 0 -COR_1LSB = 1 -COR_2LSB = 2 -COR_3LSB = 3 -APERTURE_BANDPASS = (_NAME_BASE + 15) -ABAND_F0 = 0 -ABAND_F1 = 1 -ABAND_F2 = 2 -ABAND_F3 = 3 -PREFILTER = (_NAME_BASE + 16) -CHROMA_TRAP = (_NAME_BASE + 17) -CK_THRESHOLD = (_NAME_BASE + 18) -PAL_SENSITIVITY = (_NAME_BASE + 19) -GAIN_CONTROL = (_NAME_BASE + 20) -GAIN_SLOW = 0 -GAIN_MEDIUM = 1 -GAIN_FAST = 2 -GAIN_FROZEN = 3 -AUTO_CKILL = (_NAME_BASE + 21) -VTR_MODE = (_NAME_BASE + 22) -VTR_INPUT = 0 -CAMERA_INPUT = 1 -LUMA_DELAY = (_NAME_BASE + 23) -VNOISE = (_NAME_BASE + 24) -VNOISE_NORMAL = 0 -VNOISE_SEARCH = 1 -VNOISE_AUTO = 2 -VNOISE_BYPASS = 3 -CHCV_PAL = (_NAME_BASE + 25) -CHCV_NTSC = (_NAME_BASE + 26) -CCIR_LEVELS = (_NAME_BASE + 27) -STD_CHROMA = (_NAME_BASE + 28) -DENC_VTBYPASS = (_NAME_BASE + 29) -FAST_TIMECONSTANT = (_NAME_BASE + 30) -GENLOCK_DELAY = (_NAME_BASE + 31) -PHASE_SYNC = (_NAME_BASE + 32) -VIDEO_OUTPUT = (_NAME_BASE + 33) -CHROMA_PHASEOUT = (_NAME_BASE + 34) -CHROMA_CENTER = (_NAME_BASE + 35) -YUV_TO_RGB_INVERT = (_NAME_BASE + 36) -SOURCE1_BROADCAST = (_NAME_BASE + 37) -SOURCE1_MODE = (_NAME_BASE + 38) -SOURCE2_BROADCAST = (_NAME_BASE + 39) -SOURCE2_MODE = (_NAME_BASE + 40) -SOURCE3_BROADCAST = (_NAME_BASE + 41) -SOURCE3_MODE = (_NAME_BASE + 42) -SIGNAL_STD = (_NAME_BASE + 43) -NOSIGNAL = 2 -SIGNAL_COLOR = (_NAME_BASE + 44) diff --git a/Lib/plat-irix5/TERMIOS.py b/Lib/plat-irix5/TERMIOS.py deleted file mode 100755 index a360786ba5..0000000000 --- a/Lib/plat-irix5/TERMIOS.py +++ /dev/null @@ -1,339 +0,0 @@ -# Generated by h2py from /usr/include/termios.h - -# Included from sys/termios.h - -# Included from sys/ttydev.h -B0 = 0 -B50 = 0000001 -B75 = 0000002 -B110 = 0000003 -B134 = 0000004 -B150 = 0000005 -B200 = 0000006 -B300 = 0000007 -B600 = 0000010 -B1200 = 0000011 -B1800 = 0000012 -B2400 = 0000013 -B4800 = 0000014 -B9600 = 0000015 -B19200 = 0000016 -EXTA = 0000016 -B38400 = 0000017 -EXTB = 0000017 - -# Included from sys/types.h - -# Included from sgidefs.h -_MIPS_ISA_MIPS1 = 1 -_MIPS_ISA_MIPS2 = 2 -_MIPS_ISA_MIPS3 = 3 -_MIPS_ISA_MIPS4 = 4 -_MIPS_SIM_ABI32 = 1 -_MIPS_SIM_ABI64 = 2 -P_MYID = (-1) -P_MYHOSTID = (-1) - -# Included from sys/bsd_types.h - -# Included from sys/mkdev.h -ONBITSMAJOR = 7 -ONBITSMINOR = 8 -OMAXMAJ = 0x7f -OMAXMIN = 0xff -NBITSMAJOR = 14 -NBITSMINOR = 18 -MAXMAJ = 0xff -MAXMIN = 0x3ffff -OLDDEV = 0 -NEWDEV = 1 -MKDEV_VER = NEWDEV -def major(dev): return __major(MKDEV_VER, dev) - -def minor(dev): return __minor(MKDEV_VER, dev) - - -# Included from sys/select.h -FD_SETSIZE = 1024 -NBBY = 8 -_POSIX_VDISABLE = 0 -def CTRL(c): return ((c)&037) - -IBSHIFT = 16 -NCC = 8 -NCCS = 23 -VINTR = 0 -VQUIT = 1 -VERASE = 2 -VKILL = 3 -VEOF = 4 -VEOL = 5 -VEOL2 = 6 -VMIN = 4 -VTIME = 5 -VSWTCH = 7 -VSTART = 8 -VSTOP = 9 -VSUSP = 10 -VDSUSP = 11 -VREPRINT = 12 -VDISCARD = 13 -VWERASE = 14 -VLNEXT = 15 -VRPRNT = VREPRINT -VFLUSHO = VDISCARD -VCEOF = NCC -VCEOL = (NCC + 1) -CNUL = 0 -CDEL = 0377 -CESC = ord('\\') -CINTR = 0177 -CQUIT = 034 -CERASE = CTRL(ord('H')) -CKILL = CTRL(ord('U')) -CEOL = 0 -CEOL2 = 0 -CEOF = CTRL(ord('d')) -CEOT = CEOF -CSTART = CTRL(ord('q')) -CSTOP = CTRL(ord('s')) -CSWTCH = CTRL(ord('z')) -CNSWTCH = 0 -CSUSP = CSWTCH -CLNEXT = CTRL(ord('v')) -CWERASE = CTRL(ord('w')) -CFLUSHO = CTRL(ord('o')) -CFLUSH = CFLUSHO -CRPRNT = CTRL(ord('r')) -CDSUSP = CTRL(ord('y')) -CBRK = 0377 -IGNBRK = 0000001 -BRKINT = 0000002 -IGNPAR = 0000004 -PARMRK = 0000010 -INPCK = 0000020 -ISTRIP = 0000040 -INLCR = 0000100 -IGNCR = 0000200 -ICRNL = 0000400 -IUCLC = 0001000 -IXON = 0002000 -IXANY = 0004000 -IXOFF = 0010000 -IMAXBEL = 0020000 -IBLKMD = 0040000 -OPOST = 0000001 -OLCUC = 0000002 -ONLCR = 0000004 -OCRNL = 0000010 -ONOCR = 0000020 -ONLRET = 0000040 -OFILL = 0000100 -OFDEL = 0000200 -NLDLY = 0000400 -NL0 = 0 -NL1 = 0000400 -CRDLY = 0003000 -CR0 = 0 -CR1 = 0001000 -CR2 = 0002000 -CR3 = 0003000 -TABDLY = 0014000 -TAB0 = 0 -TAB1 = 0004000 -TAB2 = 0010000 -TAB3 = 0014000 -XTABS = 0014000 -BSDLY = 0020000 -BS0 = 0 -BS1 = 0020000 -VTDLY = 0040000 -VT0 = 0 -VT1 = 0040000 -FFDLY = 0100000 -FF0 = 0 -FF1 = 0100000 -PAGEOUT = 0200000 -WRAP = 0400000 -CBAUD = 000000017 -CSIZE = 000000060 -CS5 = 0 -CS6 = 000000020 -CS7 = 000000040 -CS8 = 000000060 -CSTOPB = 000000100 -CREAD = 000000200 -PARENB = 000000400 -PARODD = 000001000 -HUPCL = 000002000 -CLOCAL = 000004000 -RCV1EN = 000010000 -XMT1EN = 000020000 -LOBLK = 000040000 -XCLUDE = 000100000 -CIBAUD = 003600000 -PAREXT = 004000000 -CNEW_RTSCTS = 010000000 -ISIG = 0000001 -ICANON = 0000002 -XCASE = 0000004 -ECHO = 0000010 -ECHOE = 0000020 -ECHOK = 0000040 -ECHONL = 0000100 -NOFLSH = 0000200 -IEXTEN = 0000400 -ITOSTOP = 0100000 -TOSTOP = ITOSTOP -ECHOCTL = 0001000 -ECHOPRT = 0002000 -ECHOKE = 0004000 -DEFECHO = 0010000 -FLUSHO = 0020000 -PENDIN = 0040000 -TIOC = (ord('T')<<8) -TCGETA = (TIOC|1) -TCSETA = (TIOC|2) -TCSETAW = (TIOC|3) -TCSETAF = (TIOC|4) -TCSBRK = (TIOC|5) -TCXONC = (TIOC|6) -TCFLSH = (TIOC|7) - -# Included from sys/ioctl.h -IOCTYPE = 0xff00 -LIOC = (ord('l')<<8) -LIOCGETP = (LIOC|1) -LIOCSETP = (LIOC|2) -LIOCGETS = (LIOC|5) -LIOCSETS = (LIOC|6) -DIOC = (ord('d')<<8) -DIOCGETC = (DIOC|1) -DIOCGETB = (DIOC|2) -DIOCSETE = (DIOC|3) - -# Included from sys/ioccom.h -IOCPARM_MASK = 0xff -IOC_VOID = 0x20000000 -IOC_OUT = 0x40000000 -IOC_IN = 0x80000000 -IOC_INOUT = (IOC_IN|IOC_OUT) - -# Included from net/soioctl.h - -# Included from sys/termio.h -CLNEXT = CTRL(ord('v')) -CWERASE = CTRL(ord('w')) -CFLUSHO = CTRL(ord('o')) -CFLUSH = CFLUSHO -CRPRNT = CTRL(ord('r')) -CDSUSP = CTRL(ord('y')) -SSPEED = B9600 -TERM_NONE = 0 -TERM_TEC = 1 -TERM_V61 = 2 -TERM_V10 = 3 -TERM_TEX = 4 -TERM_D40 = 5 -TERM_H45 = 6 -TERM_D42 = 7 -TM_NONE = 0000 -TM_SNL = 0001 -TM_ANL = 0002 -TM_LCF = 0004 -TM_CECHO = 0010 -TM_CINVIS = 0020 -TM_SET = 0200 -LDISC0 = 0 -LDISC1 = 1 -NTTYDISC = LDISC1 -TIOCFLUSH = (TIOC|12) -TCSETLABEL = (TIOC|13) -TCDSET = (TIOC|32) -TCBLKMD = (TIOC|33) -TIOCPKT = (TIOC|112) -TIOCPKT_DATA = 0x00 -TIOCPKT_FLUSHREAD = 0x01 -TIOCPKT_FLUSHWRITE = 0x02 -TIOCPKT_NOSTOP = 0x10 -TIOCPKT_DOSTOP = 0x20 -TIOCPKT_IOCTL = 0x40 -TIOCNOTTY = (TIOC|113) -TIOCSTI = (TIOC|114) -TFIOC = (ord('F')<<8) -oFIONREAD = (TFIOC|127) -TO_STOP = LOBLK -IOCTYPE = 0xff00 -TCGETS = (TIOC|13) -TCSETS = (TIOC|14) -TCSETSW = (TIOC|15) -TCSETSF = (TIOC|16) -TCSANOW = ((ord('T')<<8)|14) -TCSADRAIN = ((ord('T')<<8)|15) -TCSAFLUSH = ((ord('T')<<8)|16) -TCIFLUSH = 0 -TCOFLUSH = 1 -TCIOFLUSH = 2 -TCOOFF = 0 -TCOON = 1 -TCIOFF = 2 -TCION = 3 -tIOC = (ord('t')<<8) -TIOCGETD = (tIOC|0) -TIOCSETD = (tIOC|1) -TIOCHPCL = (tIOC|2) -TIOCGETP = (tIOC|8) -TIOCSETP = (tIOC|9) -TIOCSETN = (tIOC|10) -TIOCEXCL = (tIOC|13) -TIOCNXCL = (tIOC|14) -TIOCSETC = (tIOC|17) -TIOCGETC = (tIOC|18) -TIOCLBIS = (tIOC|127) -TIOCLBIC = (tIOC|126) -TIOCLSET = (tIOC|125) -TIOCLGET = (tIOC|124) -TIOCSBRK = (tIOC|123) -TIOCCBRK = (tIOC|122) -TIOCSDTR = (tIOC|121) -TIOCCDTR = (tIOC|120) -TIOCSLTC = (tIOC|117) -TIOCGLTC = (tIOC|116) -TIOCOUTQ = (tIOC|115) -TIOCSTOP = (tIOC|111) -TIOCSTART = (tIOC|110) -TIOCGSID = (tIOC|22) -TIOCSSID = (tIOC|24) -TIOCMSET = (tIOC|26) -TIOCMBIS = (tIOC|27) -TIOCMBIC = (tIOC|28) -TIOCMGET = (tIOC|29) -TIOCM_LE = 0001 -TIOCM_DTR = 0002 -TIOCM_RTS = 0004 -TIOCM_ST = 0010 -TIOCM_SR = 0020 -TIOCM_CTS = 0040 -TIOCM_CAR = 0100 -TIOCM_CD = TIOCM_CAR -TIOCM_RNG = 0200 -TIOCM_RI = TIOCM_RNG -TIOCM_DSR = 0400 -TIOCREMOTE = (tIOC|30) -TIOCSIGNAL = (tIOC|31) -ISPTM = ((ord('P')<<8)|1) -UNLKPT = ((ord('P')<<8)|2) -SVR4SOPEN = ((ord('P')<<8)|100) -LDIOC = (ord('D')<<8) -LDOPEN = (LDIOC|0) -LDCLOSE = (LDIOC|1) -LDCHG = (LDIOC|2) -LDGETT = (LDIOC|8) -LDSETT = (LDIOC|9) -LDSMAP = (LDIOC|10) -LDGMAP = (LDIOC|11) -LDNMAP = (LDIOC|12) -DIOC = (ord('d')<<8) -DIOCGETP = (DIOC|8) -DIOCSETP = (DIOC|9) -FIORDCHK = ((ord('f')<<8)|3) diff --git a/Lib/plat-irix5/WAIT.py b/Lib/plat-irix5/WAIT.py deleted file mode 100755 index bfd0133e84..0000000000 --- a/Lib/plat-irix5/WAIT.py +++ /dev/null @@ -1,14 +0,0 @@ -# Generated by h2py from /usr/include/sys/wait.h -_WSTOPPED = 0177 -WNOHANG = 0100 -WEXITED = 0001 -WTRAPPED = 0002 -WSTOPPED = 0004 -WCONTINUED = 0010 -WNOWAIT = 0200 -WOPTMASK = (WEXITED|WTRAPPED|WSTOPPED|WCONTINUED|WNOHANG|WNOWAIT) -WSTOPFLG = 0177 -WCONTFLG = 0177777 -WCOREFLAG = 0200 -WSIGMASK = 0177 -WUNTRACED = 0004 diff --git a/Lib/plat-irix5/cddb.py b/Lib/plat-irix5/cddb.py deleted file mode 100755 index 57cf3c6661..0000000000 --- a/Lib/plat-irix5/cddb.py +++ /dev/null @@ -1,208 +0,0 @@ -# This file implements a class which forms an interface to the .cddb -# directory that is maintained by SGI's cdman program. -# -# Usage is as follows: -# -# import readcd -# r = readcd.Readcd() -# c = Cddb(r.gettrackinfo()) -# -# Now you can use c.artist, c.title and c.track[trackno] (where trackno -# starts at 1). When the CD is not recognized, all values will be the empty -# string. -# It is also possible to set the above mentioned variables to new values. -# You can then use c.write() to write out the changed values to the -# .cdplayerrc file. - -import string, posix, os - -_cddbrc = '.cddb' -_DB_ID_NTRACKS = 5 -_dbid_map = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@_=+abcdefghijklmnopqrstuvwxyz' -def _dbid(v): - if v >= len(_dbid_map): - return string.zfill(v, 2) - else: - return _dbid_map[v] - -def tochash(toc): - if type(toc) == type(''): - tracklist = [] - for i in range(2, len(toc), 4): - tracklist.append((None, - (string.atoi(toc[i:i+2]), - string.atoi(toc[i+2:i+4])))) - else: - tracklist = toc - ntracks = len(tracklist) - hash = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF) - if ntracks <= _DB_ID_NTRACKS: - nidtracks = ntracks - else: - nidtracks = _DB_ID_NTRACKS - 1 - min = 0 - sec = 0 - for track in tracklist: - start, length = track - min = min + length[0] - sec = sec + length[1] - min = min + sec / 60 - sec = sec % 60 - hash = hash + _dbid(min) + _dbid(sec) - for i in range(nidtracks): - start, length = tracklist[i] - hash = hash + _dbid(length[0]) + _dbid(length[1]) - return hash - -class Cddb: - def __init__(self, tracklist): - if os.environ.has_key('CDDB_PATH'): - path = os.environ['CDDB_PATH'] - cddb_path = string.splitfields(path, ',') - else: - home = os.environ['HOME'] - cddb_path = [home + '/' + _cddbrc] - - self._get_id(tracklist) - - for dir in cddb_path: - file = dir + '/' + self.id + '.rdb' - try: - f = open(file, 'r') - self.file = file - break - except IOError: - pass - ntracks = string.atoi(self.id[:2], 16) - self.artist = '' - self.title = '' - self.track = [None] + [''] * ntracks - self.trackartist = [None] + [''] * ntracks - self.notes = [] - if not hasattr(self, 'file'): - return - import regex - reg = regex.compile('^\\([^.]*\\)\\.\\([^:]*\\):[\t ]+\\(.*\\)') - while 1: - line = f.readline() - if not line: - break - if reg.match(line) == -1: - print 'syntax error in ' + file - continue - name1 = line[reg.regs[1][0]:reg.regs[1][1]] - name2 = line[reg.regs[2][0]:reg.regs[2][1]] - value = line[reg.regs[3][0]:reg.regs[3][1]] - if name1 == 'album': - if name2 == 'artist': - self.artist = value - elif name2 == 'title': - self.title = value - elif name2 == 'toc': - if not self.toc: - self.toc = value - if self.toc != value: - print 'toc\'s don\'t match' - elif name2 == 'notes': - self.notes.append(value) - elif name1[:5] == 'track': - try: - trackno = string.atoi(name1[5:]) - except strings.atoi_error: - print 'syntax error in ' + file - continue - if trackno > ntracks: - print 'track number ' + `trackno` + \ - ' in file ' + file + \ - ' out of range' - continue - if name2 == 'title': - self.track[trackno] = value - elif name2 == 'artist': - self.trackartist[trackno] = value - f.close() - for i in range(2, len(self.track)): - track = self.track[i] - # if track title starts with `,', use initial part - # of previous track's title - if track and track[0] == ',': - try: - off = string.index(self.track[i - 1], - ',') - except string.index_error: - pass - else: - self.track[i] = self.track[i-1][:off] \ - + track - - def _get_id(self, tracklist): - # fill in self.id and self.toc. - # if the argument is a string ending in .rdb, the part - # upto the suffix is taken as the id. - if type(tracklist) == type(''): - if tracklist[-4:] == '.rdb': - self.id = tracklist[:-4] - self.toc = '' - return - t = [] - for i in range(2, len(tracklist), 4): - t.append((None, \ - (string.atoi(tracklist[i:i+2]), \ - string.atoi(tracklist[i+2:i+4])))) - tracklist = t - ntracks = len(tracklist) - self.id = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF) - if ntracks <= _DB_ID_NTRACKS: - nidtracks = ntracks - else: - nidtracks = _DB_ID_NTRACKS - 1 - min = 0 - sec = 0 - for track in tracklist: - start, length = track - min = min + length[0] - sec = sec + length[1] - min = min + sec / 60 - sec = sec % 60 - self.id = self.id + _dbid(min) + _dbid(sec) - for i in range(nidtracks): - start, length = tracklist[i] - self.id = self.id + _dbid(length[0]) + _dbid(length[1]) - self.toc = string.zfill(ntracks, 2) - for track in tracklist: - start, length = track - self.toc = self.toc + string.zfill(length[0], 2) + \ - string.zfill(length[1], 2) - - def write(self): - import posixpath - if os.environ.has_key('CDDB_WRITE_DIR'): - dir = os.environ['CDDB_WRITE_DIR'] - else: - dir = os.environ['HOME'] + '/' + _cddbrc - file = dir + '/' + self.id + '.rdb' - if posixpath.exists(file): - # make backup copy - posix.rename(file, file + '~') - f = open(file, 'w') - f.write('album.title:\t' + self.title + '\n') - f.write('album.artist:\t' + self.artist + '\n') - f.write('album.toc:\t' + self.toc + '\n') - for note in self.notes: - f.write('album.notes:\t' + note + '\n') - prevpref = None - for i in range(1, len(self.track)): - if self.trackartist[i]: - f.write('track'+`i`+'.artist:\t'+self.trackartist[i]+'\n') - track = self.track[i] - try: - off = string.index(track, ',') - except string.index_error: - prevpref = None - else: - if prevpref and track[:off] == prevpref: - track = track[off:] - else: - prevpref = track[:off] - f.write('track' + `i` + '.title:\t' + track + '\n') - f.close() diff --git a/Lib/plat-irix5/cdplayer.py b/Lib/plat-irix5/cdplayer.py deleted file mode 100755 index 5c2c95aa7f..0000000000 --- a/Lib/plat-irix5/cdplayer.py +++ /dev/null @@ -1,89 +0,0 @@ -# This file implements a class which forms an interface to the .cdplayerrc -# file that is maintained by SGI's cdplayer program. -# -# Usage is as follows: -# -# import readcd -# r = readcd.Readcd() -# c = Cdplayer(r.gettrackinfo()) -# -# Now you can use c.artist, c.title and c.track[trackno] (where trackno -# starts at 1). When the CD is not recognized, all values will be the empty -# string. -# It is also possible to set the above mentioned variables to new values. -# You can then use c.write() to write out the changed values to the -# .cdplayerrc file. - -cdplayerrc = '.cdplayerrc' - -class Cdplayer: - def __init__(self, tracklist): - import string - self.artist = '' - self.title = '' - if type(tracklist) == type(''): - t = [] - for i in range(2, len(tracklist), 4): - t.append((None, \ - (string.atoi(tracklist[i:i+2]), \ - string.atoi(tracklist[i+2:i+4])))) - tracklist = t - self.track = [None] + [''] * len(tracklist) - self.id = 'd' + string.zfill(len(tracklist), 2) - for track in tracklist: - start, length = track - self.id = self.id + string.zfill(length[0], 2) + \ - string.zfill(length[1], 2) - try: - import posix - f = open(posix.environ['HOME'] + '/' + cdplayerrc, 'r') - except IOError: - return - import regex - reg = regex.compile('^\\([^:]*\\):\t\\(.*\\)') - s = self.id + '.' - l = len(s) - while 1: - line = f.readline() - if line == '': - break - if line[:l] == s: - line = line[l:] - if reg.match(line) == -1: - print 'syntax error in ~/' + cdplayerrc - continue - name = line[reg.regs[1][0]:reg.regs[1][1]] - value = line[reg.regs[2][0]:reg.regs[2][1]] - if name == 'title': - self.title = value - elif name == 'artist': - self.artist = value - elif name[:5] == 'track': - trackno = string.atoi(name[6:]) - self.track[trackno] = value - f.close() - - def write(self): - import posix - filename = posix.environ['HOME'] + '/' + cdplayerrc - try: - old = open(filename, 'r') - except IOError: - old = open('/dev/null', 'r') - new = open(filename + '.new', 'w') - s = self.id + '.' - l = len(s) - while 1: - line = old.readline() - if line == '': - break - if line[:l] <> s: - new.write(line) - new.write(self.id + '.title:\t' + self.title + '\n') - new.write(self.id + '.artist:\t' + self.artist + '\n') - for i in range(1, len(self.track)): - new.write(self.id + '.track.' + `i` + ':\t' + \ - self.track[i] + '\n') - old.close() - new.close() - posix.rename(filename + '.new', filename) diff --git a/Lib/plat-irix5/flp.doc b/Lib/plat-irix5/flp.doc deleted file mode 100755 index 1a2f374ae7..0000000000 --- a/Lib/plat-irix5/flp.doc +++ /dev/null @@ -1,117 +0,0 @@ -.SH -Module flp -.LP -The flp module loads fl-forms from fd files, as generated -by fdesign. The module is designed to be flexible enough to allow -almost anything to be done with the loaded form. -.LP -Loadform defines -two types of functions: functions to parse fd files and functions to -create the forms from the templates returned by the parse functions. -There are fairly low-level create functions that create single objects, -and convenience routines that create complete forms, including callbacks, -etc. -.LP -The exception flp.error is raised whenever an error occurs while parsing a forms -definition file or creating a form. -.SH 2 -Parsing functions -.LP -There are two parsing functions, parse_form() and parse_forms(). They -take the following form: -.LP -.ft C -ftuple = parse_form(filename, formname) -.br -ftdict = parse_forms(filename) -.IP -Parse_form parses a single form, and returns a tuple (ftmp, otmplist). -Ftmp is a template for a form, otmplist is a list of templates for -objects. See below for a description of these templates. -.IP -Parse_forms parses all forms in an fd file. It returns a dictionary of -(ftmp, otmplist) tuples, indexed by formname. -.IP -Filename is the name of the forms definition file to inspect. The functions -appends '.fd' if needed, and use 'sys.path' to locate the file. -.IP -formname is the name of the form to load. This argument is mandatory, -even if the file only contains one form. -.LP -The form template and object template are structures that contain all -the information read from the fd file, in 'natural' form. A form -template record contains the following fields: -.IP -.nf -"Name", the name of the form; -"Width", the width of the form; -"Height", the height of the form; and -"Numberofobjects", the number of objects in the form. -.LP -An object template contains the following fields: -.IP -.nf -"Class", the class of object (eg. FL.BUTTON); -"Type", the sub-class (eg. FL.NORMALBUTTON); -"Box", a list with four members: [x, y, width, height]; -"Boxtype", the type of box (eg. FL.DOWNBOX); -"Colors", a list with the two object colors; -"Alignment", the label alignment (eg. FL.ALIGNLEFT); -"Style", the label style (eg. FL.BOLDSTYLE); -"Lcol", the label color; -"Label", a string containing the label; -"Name", a string containing the name of the object; -"Callback", a string containing the callback routine name; and -"Argument", a string containing the callback routine extra argument. -.SH -Low-level create routines. -.LP -The three low-level creation routines are called as follows: -.LP -.ft C -form = create_form(form_template) -.IP -Create an fl form from a form template. Returns the form created. -.LP -.ft C -obj = create_object(form, obj_template) -.IP -Create an object in an fl form. Return the new object. -An error is raised if the object has a callback routine. -.SH -High-level create routines. -.LP -The 'standard' way to handle forms in python is to define a class -that contains the form and all the objects (insofar as they are named), -and that defines all the callback functions, and use an instance of -this class to handle the form interaction. -Flp contains three routines that simplify handling this paradigm: -.LP -.ft C -create_full_form(instance, ftuple) -.IP -This routine takes an instance of your form-handling class and an -ftuple (as returned by the parsing routines) as parameters. It inserts -the form into the instance, defines all object names and arranges that -the callback methods are called. All the names inserted into the -instance are the same as the names used for the objects, etc. in the -fd file. -.LP -.ft C -merge_full_form(instance, form, ftuple) -.IP -This function does the same as create_full_form, only it does not create -the form itself nor the 'background box' that fdesign automatically -adds to each form. This is useful if your class inherits a superclass -that already defines a skeleton form (with 'OK' and 'Cancel' buttons, -for instance), and you want to merge the new form into that existing -form. The 'form' parameter is the form to which the new objects are -added. -.LP -If you use the paradigm sketched here but need slightly more control -over object creation there is a routine that creates a single object -and inserts its name (and arranges for the callback routine to be -called): -.LP -.ft C -create_object_instance(instance, form, obj_template) diff --git a/Lib/plat-irix5/flp.py b/Lib/plat-irix5/flp.py deleted file mode 100755 index 14e2278744..0000000000 --- a/Lib/plat-irix5/flp.py +++ /dev/null @@ -1,455 +0,0 @@ -# -# flp - Module to load fl forms from fd files -# -# Jack Jansen, December 1991 -# -import string -import os -import sys -import FL - -SPLITLINE = '--------------------' -FORMLINE = '=============== FORM ===============' -ENDLINE = '==============================' - -error = 'flp.error' - -################################################################## -# Part 1 - The parsing routines # -################################################################## - -# -# Externally visible function. Load form. -# -def parse_form(filename, formname): - forms = checkcache(filename) - if forms is None: - forms = parse_forms(filename) - if forms.has_key(formname): - return forms[formname] - else: - raise error, 'No such form in fd file' - -# -# Externally visible function. Load all forms. -# -def parse_forms(filename): - forms = checkcache(filename) - if forms != None: return forms - fp = _open_formfile(filename) - nforms = _parse_fd_header(fp) - forms = {} - for i in range(nforms): - form = _parse_fd_form(fp, None) - forms[form[0].Name] = form - writecache(filename, forms) - return forms - -# -# Internal: see if a cached version of the file exists -# -MAGIC = '.fdc' -_internal_cache = {} # Used by frozen scripts only -def checkcache(filename): - if _internal_cache.has_key(filename): - altforms = _internal_cache[filename] - return _unpack_cache(altforms) - import marshal - fp, filename = _open_formfile2(filename) - fp.close() - cachename = filename + 'c' - try: - fp = open(cachename, 'r') - except IOError: - #print 'flp: no cache file', cachename - return None - try: - if fp.read(4) != MAGIC: - print 'flp: bad magic word in cache file', cachename - return None - cache_mtime = rdlong(fp) - file_mtime = getmtime(filename) - if cache_mtime != file_mtime: - #print 'flp: outdated cache file', cachename - return None - #print 'flp: valid cache file', cachename - altforms = marshal.load(fp) - return _unpack_cache(altforms) - finally: - fp.close() - -def _unpack_cache(altforms): - forms = {} - for name in altforms.keys(): - altobj, altlist = altforms[name] - obj = _newobj() - obj.make(altobj) - list = [] - for altobj in altlist: - nobj = _newobj() - nobj.make(altobj) - list.append(nobj) - forms[name] = obj, list - return forms - -def rdlong(fp): - s = fp.read(4) - if len(s) != 4: return None - a, b, c, d = s[0], s[1], s[2], s[3] - return ord(a)<<24 | ord(b)<<16 | ord(c)<<8 | ord(d) - -def wrlong(fp, x): - a, b, c, d = (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff - fp.write(chr(a) + chr(b) + chr(c) + chr(d)) - -def getmtime(filename): - import os - from stat import ST_MTIME - try: - return os.stat(filename)[ST_MTIME] - except os.error: - return None - -# -# Internal: write cached version of the form (parsing is too slow!) -# -def writecache(filename, forms): - import marshal - fp, filename = _open_formfile2(filename) - fp.close() - cachename = filename + 'c' - try: - fp = open(cachename, 'w') - except IOError: - print 'flp: can\'t create cache file', cachename - return # Never mind - fp.write('\0\0\0\0') # Seek back and write MAGIC when done - wrlong(fp, getmtime(filename)) - altforms = _pack_cache(forms) - marshal.dump(altforms, fp) - fp.seek(0) - fp.write(MAGIC) - fp.close() - #print 'flp: wrote cache file', cachename - -# -# External: print some statements that set up the internal cache. -# This is for use with the "freeze" script. You should call -# flp.freeze(filename) for all forms used by the script, and collect -# the output on a file in a module file named "frozenforms.py". Then -# in the main program of the script import frozenforms. -# (Don't forget to take this out when using the unfrozen version of -# the script!) -# -def freeze(filename): - forms = parse_forms(filename) - altforms = _pack_cache(forms) - print 'import flp' - print 'flp._internal_cache[', `filename`, '] =', altforms - -# -# Internal: create the data structure to be placed in the cache -# -def _pack_cache(forms): - altforms = {} - for name in forms.keys(): - obj, list = forms[name] - altobj = obj.__dict__ - altlist = [] - for obj in list: altlist.append(obj.__dict__) - altforms[name] = altobj, altlist - return altforms - -# -# Internal: Locate form file (using PYTHONPATH) and open file -# -def _open_formfile(filename): - return _open_formfile2(filename)[0] - -def _open_formfile2(filename): - if filename[-3:] <> '.fd': - filename = filename + '.fd' - if filename[0] == '/': - try: - fp = open(filename,'r') - except IOError: - fp = None - else: - for pc in sys.path: - pn = os.path.join(pc, filename) - try: - fp = open(pn, 'r') - filename = pn - break - except IOError: - fp = None - if fp == None: - raise error, 'Cannot find forms file ' + filename - return fp, filename - -# -# Internal: parse the fd file header, return number of forms -# -def _parse_fd_header(file): - # First read the magic header line - datum = _parse_1_line(file) - if datum <> ('Magic', 12321): - raise error, 'Not a forms definition file' - # Now skip until we know number of forms - while 1: - datum = _parse_1_line(file) - if type(datum) == type(()) and datum[0] == 'Numberofforms': - break - return datum[1] -# -# Internal: parse fd form, or skip if name doesn't match. -# the special value None means 'allways parse it'. -# -def _parse_fd_form(file, name): - datum = _parse_1_line(file) - if datum <> FORMLINE: - raise error, 'Missing === FORM === line' - form = _parse_object(file) - if form.Name == name or name == None: - objs = [] - for j in range(form.Numberofobjects): - obj = _parse_object(file) - objs.append(obj) - return (form, objs) - else: - for j in range(form.Numberofobjects): - _skip_object(file) - return None - -# -# Internal class: a convient place to store object info fields -# -class _newobj: - def add(self, name, value): - self.__dict__[name] = value - def make(self, dict): - for name in dict.keys(): - self.add(name, dict[name]) - -# -# Internal parsing routines. -# -def _parse_string(str): - if '\\' in str: - s = '\'' + str + '\'' - try: - return eval(s) - except: - pass - return str - -def _parse_num(str): - return eval(str) - -def _parse_numlist(str): - slist = string.split(str) - nlist = [] - for i in slist: - nlist.append(_parse_num(i)) - return nlist - -# This dictionary maps item names to parsing routines. -# If no routine is given '_parse_num' is default. -_parse_func = { \ - 'Name': _parse_string, \ - 'Box': _parse_numlist, \ - 'Colors': _parse_numlist, \ - 'Label': _parse_string, \ - 'Name': _parse_string, \ - 'Callback': _parse_string, \ - 'Argument': _parse_string } - -# This function parses a line, and returns either -# a string or a tuple (name,value) - -import regex -prog = regex.compile('^\([^:]*\): *\(.*\)') - -def _parse_line(line): - if prog.match(line) < 0: - return line - a = prog.regs - name = line[:a[1][1]] - if name[0] == 'N': - name = string.joinfields(string.split(name),'') - name = string.lower(name) - name = string.upper(name[0]) + name[1:] - value = line[a[2][0]:] - try: - pf = _parse_func[name] - except KeyError: - pf = _parse_num - value = pf(value) - return (name, value) - -def _readline(file): - line = file.readline() - if not line: - raise EOFError - return line[:-1] - -def _parse_1_line(file): - line = _readline(file) - while line == '': - line = _readline(file) - return _parse_line(line) - -def _skip_object(file): - line = '' - while not line in (SPLITLINE, FORMLINE, ENDLINE): - pos = file.tell() - line = _readline(file) - if line == FORMLINE: - file.seek(pos) - -def _parse_object(file): - obj = _newobj() - while 1: - pos = file.tell() - datum = _parse_1_line(file) - if datum in (SPLITLINE, FORMLINE, ENDLINE): - if datum == FORMLINE: - file.seek(pos) - return obj - if type(datum) <> type(()) or len(datum) <> 2: - raise error, 'Parse error, illegal line in object: '+datum - obj.add(datum[0], datum[1]) - -################################################################# -# Part 2 - High-level object/form creation routines # -################################################################# - -# -# External - Create a form an link to an instance variable. -# -def create_full_form(inst, (fdata, odatalist)): - form = create_form(fdata) - exec 'inst.'+fdata.Name+' = form\n' - for odata in odatalist: - create_object_instance(inst, form, odata) - -# -# External - Merge a form into an existing form in an instance -# variable. -# -def merge_full_form(inst, form, (fdata, odatalist)): - exec 'inst.'+fdata.Name+' = form\n' - if odatalist[0].Class <> FL.BOX: - raise error, 'merge_full_form() expects FL.BOX as first obj' - for odata in odatalist[1:]: - create_object_instance(inst, form, odata) - - -################################################################# -# Part 3 - Low-level object/form creation routines # -################################################################# - -# -# External Create_form - Create form from parameters -# -def create_form(fdata): - import fl - return fl.make_form(FL.NO_BOX, fdata.Width, fdata.Height) - -# -# External create_object - Create an object. Make sure there are -# no callbacks. Returns the object created. -# -def create_object(form, odata): - obj = _create_object(form, odata) - if odata.Callback: - raise error, 'Creating free object with callback' - return obj -# -# External create_object_instance - Create object in an instance. -# -def create_object_instance(inst, form, odata): - obj = _create_object(form, odata) - if odata.Callback: - cbfunc = eval('inst.'+odata.Callback) - obj.set_call_back(cbfunc, odata.Argument) - if odata.Name: - exec 'inst.' + odata.Name + ' = obj\n' -# -# Internal _create_object: Create the object and fill options -# -def _create_object(form, odata): - crfunc = _select_crfunc(form, odata.Class) - obj = crfunc(odata.Type, odata.Box[0], odata.Box[1], odata.Box[2], \ - odata.Box[3], odata.Label) - if not odata.Class in (FL.BEGIN_GROUP, FL.END_GROUP): - obj.boxtype = odata.Boxtype - obj.col1 = odata.Colors[0] - obj.col2 = odata.Colors[1] - obj.align = odata.Alignment - obj.lstyle = odata.Style - obj.lsize = odata.Size - obj.lcol = odata.Lcol - return obj -# -# Internal crfunc: helper function that returns correct create function -# -def _select_crfunc(fm, cl): - if cl == FL.BEGIN_GROUP: return fm.bgn_group - elif cl == FL.END_GROUP: return fm.end_group - elif cl == FL.BITMAP: return fm.add_bitmap - elif cl == FL.BOX: return fm.add_box - elif cl == FL.BROWSER: return fm.add_browser - elif cl == FL.BUTTON: return fm.add_button - elif cl == FL.CHART: return fm.add_chart - elif cl == FL.CHOICE: return fm.add_choice - elif cl == FL.CLOCK: return fm.add_clock - elif cl == FL.COUNTER: return fm.add_counter - elif cl == FL.DIAL: return fm.add_dial - elif cl == FL.FREE: return fm.add_free - elif cl == FL.INPUT: return fm.add_input - elif cl == FL.LIGHTBUTTON: return fm.add_lightbutton - elif cl == FL.MENU: return fm.add_menu - elif cl == FL.POSITIONER: return fm.add_positioner - elif cl == FL.ROUNDBUTTON: return fm.add_roundbutton - elif cl == FL.SLIDER: return fm.add_slider - elif cl == FL.VALSLIDER: return fm.add_valslider - elif cl == FL.TEXT: return fm.add_text - elif cl == FL.TIMER: return fm.add_timer - else: - raise error, 'Unknown object type: ' + `cl` - - -def test(): - import time - t0 = time.time() - if len(sys.argv) == 2: - forms = parse_forms(sys.argv[1]) - t1 = time.time() - print 'parse time:', 0.001*(t1-t0), 'sec.' - keys = forms.keys() - keys.sort() - for i in keys: - _printform(forms[i]) - elif len(sys.argv) == 3: - form = parse_form(sys.argv[1], sys.argv[2]) - t1 = time.time() - print 'parse time:', round(t1-t0, 3), 'sec.' - _printform(form) - else: - print 'Usage: test fdfile [form]' - -def _printform(form): - f = form[0] - objs = form[1] - print 'Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects - for i in objs: - print ' Obj ', i.Name, ' type ', i.Class, i.Type - print ' Box ', i.Box, ' btype ', i.Boxtype - print ' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment - print ' cols ', i.Colors - print ' cback ', i.Callback, i.Argument - -# Local variables: -# py-indent-offset: 4 -# end: diff --git a/Lib/plat-irix5/jpeg.py b/Lib/plat-irix5/jpeg.py deleted file mode 100755 index 85d6d837d1..0000000000 --- a/Lib/plat-irix5/jpeg.py +++ /dev/null @@ -1,110 +0,0 @@ -# Implement 'jpeg' interface using SGI's compression library - -# XXX Options 'smooth' and 'optimize' are ignored. - -# XXX It appears that compressing grayscale images doesn't work right; -# XXX the resulting file causes weirdness. - -error = 'jpeg.error' # Exception - -options = {'quality': 75, 'optimize': 0, 'smooth': 0, 'forcegray': 0} - -comp = None -decomp = None - -def compress(imgdata, width, height, bytesperpixel): - global comp - import cl, CL - if comp is None: comp = cl.OpenCompressor(CL.JPEG) - if bytesperpixel == 1: - format = CL.GRAYSCALE - elif bytesperpixel == 4: - format = CL.RGBX - if options['forcegray']: - iformat = CL.GRAYSCALE - else: - iformat = CL.YUV - # XXX How to support 'optimize'? - params = [CL.IMAGE_WIDTH, width, CL.IMAGE_HEIGHT, height, \ - CL.ORIGINAL_FORMAT, format, \ - CL.ORIENTATION, CL.BOTTOM_UP, \ - CL.QUALITY_FACTOR, options['quality'], \ - CL.INTERNAL_FORMAT, iformat, \ - ] - comp.SetParams(params) - jpegdata = comp.Compress(1, imgdata) - return jpegdata - -def decompress(jpegdata): - global decomp - import cl, CL - if decomp is None: decomp = cl.OpenDecompressor(CL.JPEG) - headersize = decomp.ReadHeader(jpegdata) - params = [CL.IMAGE_WIDTH, 0, CL.IMAGE_HEIGHT, 0, CL.INTERNAL_FORMAT, 0] - decomp.GetParams(params) - width, height, format = params[1], params[3], params[5] - if format == CL.GRAYSCALE or options['forcegray']: - format = CL.GRAYSCALE - bytesperpixel = 1 - else: - format = CL.RGBX - bytesperpixel = 4 - # XXX How to support 'smooth'? - params = [CL.ORIGINAL_FORMAT, format, \ - CL.ORIENTATION, CL.BOTTOM_UP, \ - CL.FRAME_BUFFER_SIZE, width*height*bytesperpixel] - decomp.SetParams(params) - imgdata = decomp.Decompress(1, jpegdata) - return imgdata, width, height, bytesperpixel - -def setoption(name, value): - if type(value) <> type(0): - raise TypeError, 'jpeg.setoption: numeric options only' - if name == 'forcegrey': - name = 'forcegray' - if not options.has_key(name): - raise KeyError, 'jpeg.setoption: unknown option name' - options[name] = int(value) - -def test(): - import sys - if sys.argv[1:2] == ['-g']: - del sys.argv[1] - setoption('forcegray', 1) - if not sys.argv[1:]: - sys.argv.append('/usr/local/images/data/jpg/asterix.jpg') - for file in sys.argv[1:]: - show(file) - -def show(file): - import gl, GL, DEVICE - jpegdata = open(file, 'r').read() - imgdata, width, height, bytesperpixel = decompress(jpegdata) - gl.foreground() - gl.prefsize(width, height) - win = gl.winopen(file) - if bytesperpixel == 1: - gl.cmode() - gl.pixmode(GL.PM_SIZE, 8) - gl.gconfig() - for i in range(256): - gl.mapcolor(i, i, i, i) - else: - gl.RGBmode() - gl.pixmode(GL.PM_SIZE, 32) - gl.gconfig() - gl.qdevice(DEVICE.REDRAW) - gl.qdevice(DEVICE.ESCKEY) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.lrectwrite(0, 0, width-1, height-1, imgdata) - while 1: - dev, val = gl.qread() - if dev in (DEVICE.ESCKEY, DEVICE.WINSHUT, DEVICE.WINQUIT): - break - if dev == DEVICE.REDRAW: - gl.lrectwrite(0, 0, width-1, height-1, imgdata) - gl.winclose(win) - # Now test the compression and write the result to a fixed filename - newjpegdata = compress(imgdata, width, height, bytesperpixel) - open('/tmp/j.jpg', 'w').write(newjpegdata) diff --git a/Lib/plat-irix5/panel.py b/Lib/plat-irix5/panel.py deleted file mode 100755 index 2c0365c6ce..0000000000 --- a/Lib/plat-irix5/panel.py +++ /dev/null @@ -1,281 +0,0 @@ -# Module 'panel' -# -# Support for the Panel library. -# Uses built-in module 'pnl'. -# Applciations should use 'panel.function' instead of 'pnl.function'; -# most 'pnl' functions are transparently exported by 'panel', -# but dopanel() is overridden and you have to use this version -# if you want to use callbacks. - - -import pnl - - -debug = 0 - - -# Test if an object is a list. -# -def is_list(x): - return type(x) == type([]) - - -# Reverse a list. -# -def reverse(list): - res = [] - for item in list: - res.insert(0, item) - return res - - -# Get an attribute of a list, which may itself be another list. -# Don't use 'prop' for name. -# -def getattrlist(list, name): - for item in list: - if item and is_list(item) and item[0] == name: - return item[1:] - return [] - - -# Get a property of a list, which may itself be another list. -# -def getproplist(list, name): - for item in list: - if item and is_list(item) and item[0] == 'prop': - if len(item) > 1 and item[1] == name: - return item[2:] - return [] - - -# Test if an actuator description contains the property 'end-of-group' -# -def is_endgroup(list): - x = getproplist(list, 'end-of-group') - return (x and x[0] == '#t') - - -# Neatly display an actuator definition given as S-expression -# the prefix string is printed before each line. -# -def show_actuator(prefix, a): - for item in a: - if not is_list(item): - print prefix, item - elif item and item[0] == 'al': - print prefix, 'Subactuator list:' - for a in item[1:]: - show_actuator(prefix + ' ', a) - elif len(item) == 2: - print prefix, item[0], '=>', item[1] - elif len(item) == 3 and item[0] == 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] - else: - print prefix, '?', item - - -# Neatly display a panel. -# -def show_panel(prefix, p): - for item in p: - if not is_list(item): - print prefix, item - elif item and item[0] == 'al': - print prefix, 'Actuator list:' - for a in item[1:]: - show_actuator(prefix + ' ', a) - elif len(item) == 2: - print prefix, item[0], '=>', item[1] - elif len(item) == 3 and item[0] == 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] - else: - print prefix, '?', item - - -# Exception raised by build_actuator or build_panel. -# -panel_error = 'panel error' - - -# Dummy callback used to initialize the callbacks. -# -def dummy_callback(arg): - pass - - -# Assign attributes to members of the target. -# Attribute names in exclist are ignored. -# The member name is the attribute name prefixed with the prefix. -# -def assign_members(target, attrlist, exclist, prefix): - for item in attrlist: - if is_list(item) and len(item) == 2 and item[0] not in exclist: - name, value = item[0], item[1] - ok = 1 - if value[0] in '-0123456789': - value = eval(value) - elif value[0] == '"': - value = value[1:-1] - elif value == 'move-then-resize': - # Strange default set by Panel Editor... - ok = 0 - else: - print 'unknown value', value, 'for', name - ok = 0 - if ok: - lhs = 'target.' + prefix + name - stmt = lhs + '=' + `value` - if debug: print 'exec', stmt - try: - exec stmt + '\n' - except KeyboardInterrupt: # Don't catch this! - raise KeyboardInterrupt - except: - print 'assign failed:', stmt - - -# Build a real actuator from an actuator descriptior. -# Return a pair (actuator, name). -# -def build_actuator(descr): - namelist = getattrlist(descr, 'name') - if namelist: - # Assume it is a string - actuatorname = namelist[0][1:-1] - else: - actuatorname = '' - type = descr[0] - if type[:4] == 'pnl_': type = type[4:] - act = pnl.mkact(type) - act.downfunc = act.activefunc = act.upfunc = dummy_callback - # - assign_members(act, descr[1:], ['al', 'data', 'name'], '') - # - # Treat actuator-specific data - # - datalist = getattrlist(descr, 'data') - prefix = '' - if type[-4:] == 'puck': - prefix = 'puck_' - elif type == 'mouse': - prefix = 'mouse_' - assign_members(act, datalist, [], prefix) - # - return act, actuatorname - - -# Build all sub-actuators and add them to the super-actuator. -# The super-actuator must already have been added to the panel. -# Sub-actuators with defined names are added as members to the panel -# so they can be referenced as p.name. -# -# Note: I have no idea how panel.endgroup() works when applied -# to a sub-actuator. -# -def build_subactuators(panel, super_act, al): - # - # This is nearly the same loop as below in build_panel(), - # except a call is made to addsubact() instead of addact(). - # - for a in al: - act, name = build_actuator(a) - act.addsubact(super_act) - if name: - stmt = 'panel.' + name + ' = act' - if debug: print 'exec', stmt - exec stmt + '\n' - if is_endgroup(a): - panel.endgroup() - sub_al = getattrlist(a, 'al') - if sub_al: - build_subactuators(panel, act, sub_al) - # - # Fix the actuator to which whe just added subactuators. - # This can't hurt (I hope) and is needed for the scroll actuator. - # - super_act.fixact() - - -# Build a real panel from a panel definition. -# Return a panel object p, where for each named actuator a, p.name is a -# reference to a. -# -def build_panel(descr): - # - # Sanity check - # - if (not descr) or descr[0] <> 'panel': - raise panel_error, 'panel description must start with "panel"' - # - if debug: show_panel('', descr) - # - # Create an empty panel - # - panel = pnl.mkpanel() - # - # Assign panel attributes - # - assign_members(panel, descr[1:], ['al'], '') - # - # Look for actuator list - # - al = getattrlist(descr, 'al') - # - # The order in which actuators are created is important - # because of the endgroup() operator. - # Unfortunately the Panel Editor outputs the actuator list - # in reverse order, so we reverse it here. - # - al = reverse(al) - # - for a in al: - act, name = build_actuator(a) - act.addact(panel) - if name: - stmt = 'panel.' + name + ' = act' - exec stmt + '\n' - if is_endgroup(a): - panel.endgroup() - sub_al = getattrlist(a, 'al') - if sub_al: - build_subactuators(panel, act, sub_al) - # - return panel - - -# Wrapper around pnl.dopanel() which calls call-back functions. -# -def my_dopanel(): - # Extract only the first 4 elements to allow for future expansion - a, down, active, up = pnl.dopanel()[:4] - if down: - down.downfunc(down) - if active: - active.activefunc(active) - if up: - up.upfunc(up) - return a - - -# Create one or more panels from a description file (S-expressions) -# generated by the Panel Editor. -# -def defpanellist(file): - import panelparser - descrlist = panelparser.parse_file(open(file, 'r')) - panellist = [] - for descr in descrlist: - panellist.append(build_panel(descr)) - return panellist - - -# Import everything from built-in method pnl, so the user can always -# use panel.foo() instead of pnl.foo(). -# This gives *no* performance penalty once this module is imported. -# -from pnl import * # for export - -dopanel = my_dopanel # override pnl.dopanel diff --git a/Lib/plat-irix5/panelparser.py b/Lib/plat-irix5/panelparser.py deleted file mode 100755 index 1b069fa075..0000000000 --- a/Lib/plat-irix5/panelparser.py +++ /dev/null @@ -1,128 +0,0 @@ -# Module 'parser' -# -# Parse S-expressions output by the Panel Editor -# (which is written in Scheme so it can't help writing S-expressions). -# -# See notes at end of file. - - -whitespace = ' \t\n' -operators = '()\'' -separators = operators + whitespace + ';' + '"' - - -# Tokenize a string. -# Return a list of tokens (strings). -# -def tokenize_string(s): - tokens = [] - while s: - c = s[:1] - if c in whitespace: - s = s[1:] - elif c == ';': - s = '' - elif c == '"': - n = len(s) - i = 1 - while i < n: - c = s[i] - i = i+1 - if c == '"': break - if c == '\\': i = i+1 - tokens.append(s[:i]) - s = s[i:] - elif c in operators: - tokens.append(c) - s = s[1:] - else: - n = len(s) - i = 1 - while i < n: - if s[i] in separators: break - i = i+1 - tokens.append(s[:i]) - s = s[i:] - return tokens - - -# Tokenize a whole file (given as file object, not as file name). -# Return a list of tokens (strings). -# -def tokenize_file(fp): - tokens = [] - while 1: - line = fp.readline() - if not line: break - tokens = tokens + tokenize_string(line) - return tokens - - -# Exception raised by parse_exr. -# -syntax_error = 'syntax error' - - -# Parse an S-expression. -# Input is a list of tokens as returned by tokenize_*(). -# Return a pair (expr, tokens) -# where expr is a list representing the s-expression, -# and tokens contains the remaining tokens. -# May raise syntax_error. -# -def parse_expr(tokens): - if (not tokens) or tokens[0] <> '(': - raise syntax_error, 'expected "("' - tokens = tokens[1:] - expr = [] - while 1: - if not tokens: - raise syntax_error, 'missing ")"' - if tokens[0] == ')': - return expr, tokens[1:] - elif tokens[0] == '(': - subexpr, tokens = parse_expr(tokens) - expr.append(subexpr) - else: - expr.append(tokens[0]) - tokens = tokens[1:] - - -# Parse a file (given as file object, not as file name). -# Return a list of parsed S-expressions found at the top level. -# -def parse_file(fp): - tokens = tokenize_file(fp) - exprlist = [] - while tokens: - expr, tokens = parse_expr(tokens) - exprlist.append(expr) - return exprlist - - -# EXAMPLE: -# -# The input -# '(hip (hop hur-ray))' -# -# passed to tokenize_string() returns the token list -# ['(', 'hip', '(', 'hop', 'hur-ray', ')', ')'] -# -# When this is passed to parse_expr() it returns the expression -# ['hip', ['hop', 'hur-ray']] -# plus an empty token list (because there are no tokens left. -# -# When a file containing the example is passed to parse_file() it returns -# a list whose only element is the output of parse_expr() above: -# [['hip', ['hop', 'hur-ray']]] - - -# TOKENIZING: -# -# Comments start with semicolon (;) and continue till the end of the line. -# -# Tokens are separated by whitespace, except the following characters -# always form a separate token (outside strings): -# ( ) ' -# Strings are enclosed in double quotes (") and backslash (\) is used -# as escape character in strings. diff --git a/Lib/plat-irix5/readcd.doc b/Lib/plat-irix5/readcd.doc deleted file mode 100755 index 1be549c790..0000000000 --- a/Lib/plat-irix5/readcd.doc +++ /dev/null @@ -1,104 +0,0 @@ -Interface to CD-ROM player. - -This module implements an interface to the built-in cd module. The -intention is to provide a more user-friendly interface than the -built-in module. - -The module defines a class Readcd with several methods. The -initialization of the class will try to open the CD player. This -means that initialization will fail if the CD player is already in -use. A RuntimeError will be raised by the cd module in that case. - -The way to work with this module is as follows. The user specifies -the parts of the CD that are to be read and he specifies callback -functions which are to be called by the system. At some point he can -tell the system to play. The specified parts of the CD will then be -read and the callbacks will be called. - -Initialization. -=============== - -r = readcd.Readcd([cd-player [, mode]]) - -The optional arguments are the name of the CD device and the mode. -When "mode" is not specified, it defaults to 'r' (which is the only -possible value); when "cd-player" also isn't specified, it defaults -to "None" which indicates the default CD player. - -Methods. -======== - -eject() -- Eject the CD from the player. - -reset() -- Reset the list of data stretches to be played. - -appendtrack(track) -- Append the specified track to the list of music -stretches. - -appendstretch(first, last) -- Append the stretch from "first" to "last" -to the list of music stretches. Both "first" and "last" can be in one -of four forms. "None": for "first", the beginning of the CD, for -"last" the end of the CD; a single integer: a track number--playing -starts at the beginning of the track or ends at the end of the -specified track; a three-tuple: the absolute time from the start of -the CD in minutes, seconds, frames; a four-tuple: track number and -relative time within the track in minutes, seconds, frames. - -settracks(tracklist) -- The argument is a list of integers. The list -of stretches is set to argument list. The old list is discarded. - -setcallback(type, func, arg) -- Set a callback function for "type". -The function will be called as func(arg, type, data) where "arg" is -the third argument of setcallback, "type" is the type of callback, -"data" is type-dependent data. See the CDsetcallback(3) manual page -for more information. The possible "type" arguments are defined in -the CD module. - -removecallback(type) -- Remove the callback for "type". - -gettrackinfo([tracklist]) -- Return a list of tuples. Each tuple -consists of start and length information of a track. The start and -length information consist of three-tuples with minutes, seconds and -frames. The optional tracklist argument gives a list of interesting -track numbers. If no tracklist is specified, information about all -tracks is returned. - -getstatus() -- Return the status information of the CD. - -play() -- Play the preprogrammed stretches of music from the CD. When -nothing was programmed, the whole CD is played. - -Specifying stretches. -===================== - -There are three methods available to specify a stretch of music to be -played. The easiest way is to use "settracklist(tracklist)" with which -a list of tracks can be specified. "settracklist(tracklist)" is -equivalent to the sequence - reset() - for track in tracklist: - appendtrack(track) - -The next method is "appendtrack(track)" with which a whole track can be -added to the list of music to be played. "appendtrack(track)" is -equivalent to "appendstretch(track, track)". - -The most complete method is "appendstretch(first, last)". Using this -method, it is possible to specify any stretch of music. - -When two consecutive tracks are played, it is possible to choose -whether the pause that may be between the tracks is played as well or -whether the pause should be skipped. When the end of a stretch is -specified using a track number and the next stretch starts at the -beginning of the following track and that was also specified using the -track number (that is, both were specified as integers, not as tuples), -the pause is played. When either value was specified using absolute -time or track-relative time (that is, as three-tuple or as -four-tuple), the pause will not be played. - -Errors. -======= - -When an error occurs, an exception will be raised. Depending on where -the error occurs, the exception may either be "readcd.Error" or -"RuntimeError". diff --git a/Lib/plat-irix5/readcd.py b/Lib/plat-irix5/readcd.py deleted file mode 100755 index 5c4b824250..0000000000 --- a/Lib/plat-irix5/readcd.py +++ /dev/null @@ -1,242 +0,0 @@ -# Class interface to the CD module. - -import cd, CD - -Error = 'Readcd.Error' -_Stop = 'Readcd.Stop' - -def _doatime(self, cb_type, data): - if ((data[0] * 60) + data[1]) * 75 + data[2] > self.end: -## print 'done with list entry',`self.listindex` - raise _Stop - func, arg = self.callbacks[cb_type] - if func: - func(arg, cb_type, data) - -def _dopnum(self, cb_type, data): - if data > self.end: -## print 'done with list entry',`self.listindex` - raise _Stop - func, arg = self.callbacks[cb_type] - if func: - func(arg, cb_type, data) - -class Readcd: - def __init__(self, *arg): - if len(arg) == 0: - self.player = cd.open() - elif len(arg) == 1: - self.player = cd.open(arg[0]) - elif len(arg) == 2: - self.player = cd.open(arg[0], arg[1]) - else: - raise Error, 'bad __init__ call' - self.list = [] - self.callbacks = [(None, None)] * 8 - self.parser = cd.createparser() - self.playing = 0 - self.end = 0 - self.status = None - self.trackinfo = None - - def eject(self): - self.player.eject() - self.list = [] - self.end = 0 - self.listindex = 0 - self.status = None - self.trackinfo = None - if self.playing: -## print 'stop playing from eject' - raise _Stop - - def pmsf2msf(self, track, min, sec, frame): - if not self.status: - self.cachestatus() - if track < self.status[5] or track > self.status[6]: - raise Error, 'track number out of range' - if not self.trackinfo: - self.cacheinfo() - start, total = self.trackinfo[track] - start = ((start[0] * 60) + start[1]) * 75 + start[2] - total = ((total[0] * 60) + total[1]) * 75 + total[2] - block = ((min * 60) + sec) * 75 + frame - if block > total: - raise Error, 'out of range' - block = start + block - min, block = divmod(block, 75*60) - sec, frame = divmod(block, 75) - return min, sec, frame - - def reset(self): - self.list = [] - - def appendtrack(self, track): - self.appendstretch(track, track) - - def appendstretch(self, start, end): - if not self.status: - self.cachestatus() - if not start: - start = 1 - if not end: - end = self.status[6] - if type(end) == type(0): - if end < self.status[5] or end > self.status[6]: - raise Error, 'range error' - else: - l = len(end) - if l == 4: - prog, min, sec, frame = end - if prog < self.status[5] or prog > self.status[6]: - raise Error, 'range error' - end = self.pmsf2msf(prog, min, sec, frame) - elif l <> 3: - raise Error, 'syntax error' - if type(start) == type(0): - if start < self.status[5] or start > self.status[6]: - raise Error, 'range error' - if len(self.list) > 0: - s, e = self.list[-1] - if type(e) == type(0): - if start == e+1: - start = s - del self.list[-1] - else: - l = len(start) - if l == 4: - prog, min, sec, frame = start - if prog < self.status[5] or prog > self.status[6]: - raise Error, 'range error' - start = self.pmsf2msf(prog, min, sec, frame) - elif l <> 3: - raise Error, 'syntax error' - self.list.append((start, end)) - - def settracks(self, list): - self.list = [] - for track in list: - self.appendtrack(track) - - def setcallback(self, cb_type, func, arg): - if cb_type < 0 or cb_type >= 8: - raise Error, 'type out of range' - self.callbacks[cb_type] = (func, arg) - if self.playing: - start, end = self.list[self.listindex] - if type(end) == type(0): - if cb_type <> CD.PNUM: - self.parser.setcallback(cb_type, func, arg) - else: - if cb_type <> CD.ATIME: - self.parser.setcallback(cb_type, func, arg) - - def removecallback(self, cb_type): - if cb_type < 0 or cb_type >= 8: - raise Error, 'type out of range' - self.callbacks[cb_type] = (None, None) - if self.playing: - start, end = self.list[self.listindex] - if type(end) == type(0): - if cb_type <> CD.PNUM: - self.parser.removecallback(cb_type) - else: - if cb_type <> CD.ATIME: - self.parser.removecallback(cb_type) - - def gettrackinfo(self, *arg): - if not self.status: - self.cachestatus() - if not self.trackinfo: - self.cacheinfo() - if len(arg) == 0: - return self.trackinfo[self.status[5]:self.status[6]+1] - result = [] - for i in arg: - if i < self.status[5] or i > self.status[6]: - raise Error, 'range error' - result.append(self.trackinfo[i]) - return result - - def cacheinfo(self): - if not self.status: - self.cachestatus() - self.trackinfo = [] - for i in range(self.status[5]): - self.trackinfo.append(None) - for i in range(self.status[5], self.status[6]+1): - self.trackinfo.append(self.player.gettrackinfo(i)) - - def cachestatus(self): - self.status = self.player.getstatus() - if self.status[0] == CD.NODISC: - self.status = None - raise Error, 'no disc in player' - - def getstatus(self): - return self.player.getstatus() - - def play(self): - if not self.status: - self.cachestatus() - size = self.player.bestreadsize() - self.listindex = 0 - self.playing = 0 - for i in range(8): - func, arg = self.callbacks[i] - if func: - self.parser.setcallback(i, func, arg) - else: - self.parser.removecallback(i) - if len(self.list) == 0: - for i in range(self.status[5], self.status[6]+1): - self.appendtrack(i) - try: - while 1: - if not self.playing: - if self.listindex >= len(self.list): - return - start, end = self.list[self.listindex] - if type(start) == type(0): - dummy = self.player.seektrack( - start) - else: - min, sec, frame = start - dummy = self.player.seek( - min, sec, frame) - if type(end) == type(0): - self.parser.setcallback( - CD.PNUM, _dopnum, self) - self.end = end - func, arg = \ - self.callbacks[CD.ATIME] - if func: - self.parser.setcallback(CD.ATIME, func, arg) - else: - self.parser.removecallback(CD.ATIME) - else: - min, sec, frame = end - self.parser.setcallback( - CD.ATIME, _doatime, - self) - self.end = (min * 60 + sec) * \ - 75 + frame - func, arg = \ - self.callbacks[CD.PNUM] - if func: - self.parser.setcallback(CD.PNUM, func, arg) - else: - self.parser.removecallback(CD.PNUM) - self.playing = 1 - data = self.player.readda(size) - if data == '': - self.playing = 0 - self.listindex = self.listindex + 1 - continue - try: - self.parser.parseframe(data) - except _Stop: - self.playing = 0 - self.listindex = self.listindex + 1 - finally: - self.playing = 0 diff --git a/Lib/plat-irix5/regen b/Lib/plat-irix5/regen deleted file mode 100755 index 13f9d745fd..0000000000 --- a/Lib/plat-irix5/regen +++ /dev/null @@ -1,12 +0,0 @@ -#! /bin/sh -case `uname -sr` in -'IRIX '[45].*) ;; -*) echo Probably not on an IRIX system 1>&2 - exit 1;; -esac -set -v -h2py /usr/include/sys/fcntl.h -h2py /usr/include/sys/socket.h -h2py -i '(u_long)' /usr/include/netinet/in.h -h2py /usr/include/sys/termios.h -h2py /usr/include/errno.h diff --git a/Lib/plat-irix5/torgb.py b/Lib/plat-irix5/torgb.py deleted file mode 100755 index f283063c00..0000000000 --- a/Lib/plat-irix5/torgb.py +++ /dev/null @@ -1,97 +0,0 @@ -# Convert "arbitrary" image files to rgb files (SGI's image format). -# Input may be compressed. -# The uncompressed file type may be PBM, PGM, PPM, GIF, TIFF, or Sun raster. -# An exception is raised if the file is not of a recognized type. -# Returned filename is either the input filename or a temporary filename; -# in the latter case the caller must ensure that it is removed. -# Other temporary files used are removed by the function. - -import os -import tempfile -import pipes -import imghdr - -table = {} - -t = pipes.Template() -t.append('fromppm $IN $OUT', 'ff') -table['ppm'] = t - -t = pipes.Template() -t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--') -t.append('fromppm $IN $OUT', 'ff') -table['pnm'] = t -table['pgm'] = t -table['pbm'] = t - -t = pipes.Template() -t.append('fromgif $IN $OUT', 'ff') -table['gif'] = t - -t = pipes.Template() -t.append('tifftopnm', '--') -t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--') -t.append('fromppm $IN $OUT', 'ff') -table['tiff'] = t - -t = pipes.Template() -t.append('rasttopnm', '--') -t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--') -t.append('fromppm $IN $OUT', 'ff') -table['rast'] = t - -t = pipes.Template() -t.append('djpeg', '--') -t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--') -t.append('fromppm $IN $OUT', 'ff') -table['jpeg'] = t - -uncompress = pipes.Template() -uncompress.append('uncompress', '--') - - -error = 'torgb.error' # Exception - -def torgb(filename): - temps = [] - ret = None - try: - ret = _torgb(filename, temps) - finally: - for temp in temps[:]: - if temp <> ret: - try: - os.unlink(temp) - except os.error: - pass - temps.remove(temp) - return ret - -def _torgb(filename, temps): - if filename[-2:] == '.Z': - fname = tempfile.mktemp() - temps.append(fname) - sts = uncompress.copy(filename, fname) - if sts: - raise error, filename + ': uncompress failed' - else: - fname = filename - try: - ftype = imghdr.what(fname) - except IOError, msg: - if type(msg) == type(()) and len(msg) == 2 and \ - type(msg[0]) == type(0) and type(msg[1]) == type(''): - msg = msg[1] - if type(msg) <> type(''): - msg = `msg` - raise error, filename + ': ' + msg - if ftype == 'rgb': - return fname - if ftype == None or not table.has_key(ftype): - raise error, \ - filename + ': unsupported image file type ' + `ftype` - temp = tempfile.mktemp() - sts = table[ftype].copy(fname, temp) - if sts: - raise error, filename + ': conversion to rgb failed' - return temp diff --git a/Lib/plat-linux1/FCNTL.py b/Lib/plat-linux1/FCNTL.py deleted file mode 100755 index f65c4fa389..0000000000 --- a/Lib/plat-linux1/FCNTL.py +++ /dev/null @@ -1,101 +0,0 @@ -# Generated by h2py from /usr/include/sys/fcntl.h - -# Included from fcntl.h - -# Included from features.h -_FEATURES_H = 1 -_GNU_SOURCE = 1 -__USE_ANSI = 1 -__FAVOR_BSD = 1 -_BSD_SOURCE = 1 -_SVID_SOURCE = 1 -_POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 2 -__USE_POSIX = 1 -__USE_POSIX2 = 1 -__USE_MISC = 1 -__USE_BSD = 1 -__USE_SVID = 1 -__USE_GNU = 1 -__GNU_LIBRARY__ = 1 - -# Included from sys/cdefs.h -_SYS_CDEFS_H = 1 -def __P(args): return args - -def __P(args): return args - -def __P(args): return () - -def __STRING(x): return #x - -def __STRING(x): return "x" - - -# Included from sys/types.h - -# Included from linux/types.h -__FD_SETSIZE = 256 - -# Included from asm/types.h -def __FD_ZERO(fdsetp): return \ - - -# Included from sys/bitypes.h - -# Included from gnu/types.h -_GNU_TYPES_H = 1 -__FDSET_LONGS = 8 -def __FD_ZERO(fdsetp): return \ - -__FD_SETSIZE = 256 -def __FDELT(d): return ((d) / __NFDBITS) - -def __FDMASK(d): return (1 << ((d) % __NFDBITS)) - -def __FD_ZERO(set): return \ - - -# Included from linux/fcntl.h - -# Included from asm/fcntl.h -O_ACCMODE = 0003 -O_RDONLY = 00 -O_WRONLY = 01 -O_RDWR = 02 -O_CREAT = 0100 -O_EXCL = 0200 -O_NOCTTY = 0400 -O_TRUNC = 01000 -O_APPEND = 02000 -O_NONBLOCK = 04000 -O_NDELAY = O_NONBLOCK -O_SYNC = 010000 -FASYNC = 020000 -F_DUPFD = 0 -F_GETFD = 1 -F_SETFD = 2 -F_GETFL = 3 -F_SETFL = 4 -F_GETLK = 5 -F_SETLK = 6 -F_SETLKW = 7 -F_SETOWN = 8 -F_GETOWN = 9 -FD_CLOEXEC = 1 -F_RDLCK = 0 -F_WRLCK = 1 -F_UNLCK = 2 -F_EXLCK = 4 -F_SHLCK = 8 -LOCK_SH = 1 -LOCK_EX = 2 -LOCK_NB = 4 -LOCK_UN = 8 -F_POSIX = 1 -F_FLOCK = 2 -FNDELAY = O_NDELAY -F_ULOCK = 0 -F_LOCK = 1 -F_TLOCK = 2 -F_TEST = 3 diff --git a/Lib/plat-linux1/IN.py b/Lib/plat-linux1/IN.py deleted file mode 100755 index 86710d13c2..0000000000 --- a/Lib/plat-linux1/IN.py +++ /dev/null @@ -1,239 +0,0 @@ -# Generated by h2py from /usr/include/netinet/in.h -_NETINET_IN_H = 1 - -# Included from features.h -_FEATURES_H = 1 -_GNU_SOURCE = 1 -__USE_ANSI = 1 -__FAVOR_BSD = 1 -_BSD_SOURCE = 1 -_SVID_SOURCE = 1 -_POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 2 -__USE_POSIX = 1 -__USE_POSIX2 = 1 -__USE_MISC = 1 -__USE_BSD = 1 -__USE_SVID = 1 -__USE_GNU = 1 -__GNU_LIBRARY__ = 1 - -# Included from sys/cdefs.h -_SYS_CDEFS_H = 1 -def __P(args): return args - -def __P(args): return args - -def __P(args): return () - -def __STRING(x): return #x - -def __STRING(x): return "x" - - -# Included from sys/socket.h - -# Included from linux/socket.h - -# Included from asm/socket.h -FIOSETOWN = 0x8901 -SIOCSPGRP = 0x8902 -FIOGETOWN = 0x8903 -SIOCGPGRP = 0x8904 -SIOCATMARK = 0x8905 -SIOCGSTAMP = 0x8906 -SOL_SOCKET = 1 -SO_DEBUG = 1 -SO_REUSEADDR = 2 -SO_TYPE = 3 -SO_ERROR = 4 -SO_DONTROUTE = 5 -SO_BROADCAST = 6 -SO_SNDBUF = 7 -SO_RCVBUF = 8 -SO_KEEPALIVE = 9 -SO_OOBINLINE = 10 -SO_NO_CHECK = 11 -SO_PRIORITY = 12 -SO_LINGER = 13 - -# Included from linux/sockios.h -SIOCADDRT = 0x890B -SIOCDELRT = 0x890C -SIOCGIFNAME = 0x8910 -SIOCSIFLINK = 0x8911 -SIOCGIFCONF = 0x8912 -SIOCGIFFLAGS = 0x8913 -SIOCSIFFLAGS = 0x8914 -SIOCGIFADDR = 0x8915 -SIOCSIFADDR = 0x8916 -SIOCGIFDSTADDR = 0x8917 -SIOCSIFDSTADDR = 0x8918 -SIOCGIFBRDADDR = 0x8919 -SIOCSIFBRDADDR = 0x891a -SIOCGIFNETMASK = 0x891b -SIOCSIFNETMASK = 0x891c -SIOCGIFMETRIC = 0x891d -SIOCSIFMETRIC = 0x891e -SIOCGIFMEM = 0x891f -SIOCSIFMEM = 0x8920 -SIOCGIFMTU = 0x8921 -SIOCSIFMTU = 0x8922 -SIOCSIFHWADDR = 0x8924 -SIOCGIFENCAP = 0x8925 -SIOCSIFENCAP = 0x8926 -SIOCGIFHWADDR = 0x8927 -SIOCGIFSLAVE = 0x8929 -SIOCSIFSLAVE = 0x8930 -SIOCADDMULTI = 0x8931 -SIOCDELMULTI = 0x8932 -OLD_SIOCDARP = 0x8950 -OLD_SIOCGARP = 0x8951 -OLD_SIOCSARP = 0x8952 -SIOCDARP = 0x8953 -SIOCGARP = 0x8954 -SIOCSARP = 0x8955 -SIOCDRARP = 0x8960 -SIOCGRARP = 0x8961 -SIOCSRARP = 0x8962 -SIOCGIFMAP = 0x8970 -SIOCSIFMAP = 0x8971 -SIOCDEVPRIVATE = 0x89F0 -SIOCPROTOPRIVATE = 0x89E0 - -# Included from linux/uio.h -MAX_IOVEC = 8 -SOCK_STREAM = 1 -SOCK_DGRAM = 2 -SOCK_RAW = 3 -SOCK_RDM = 4 -SOCK_SEQPACKET = 5 -SOCK_PACKET = 10 -AF_UNSPEC = 0 -AF_UNIX = 1 -AF_INET = 2 -AF_AX25 = 3 -AF_IPX = 4 -AF_APPLETALK = 5 -AF_NETROM = 6 -AF_BRIDGE = 7 -AF_AAL5 = 8 -AF_X25 = 9 -AF_INET6 = 10 -AF_MAX = 12 -PF_UNSPEC = AF_UNSPEC -PF_UNIX = AF_UNIX -PF_INET = AF_INET -PF_AX25 = AF_AX25 -PF_IPX = AF_IPX -PF_APPLETALK = AF_APPLETALK -PF_NETROM = AF_NETROM -PF_BRIDGE = AF_BRIDGE -PF_AAL5 = AF_AAL5 -PF_X25 = AF_X25 -PF_INET6 = AF_INET6 -PF_MAX = AF_MAX -SOMAXCONN = 128 -MSG_OOB = 1 -MSG_PEEK = 2 -MSG_DONTROUTE = 4 -SOL_IP = 0 -SOL_IPX = 256 -SOL_AX25 = 257 -SOL_ATALK = 258 -SOL_NETROM = 259 -SOL_TCP = 6 -SOL_UDP = 17 -IP_TOS = 1 -IPTOS_LOWDELAY = 0x10 -IPTOS_THROUGHPUT = 0x08 -IPTOS_RELIABILITY = 0x04 -IP_TTL = 2 -IP_HDRINCL = 3 -IP_OPTIONS = 4 -IP_MULTICAST_IF = 32 -IP_MULTICAST_TTL = 33 -IP_MULTICAST_LOOP = 34 -IP_ADD_MEMBERSHIP = 35 -IP_DROP_MEMBERSHIP = 36 -IP_DEFAULT_MULTICAST_TTL = 1 -IP_DEFAULT_MULTICAST_LOOP = 1 -IP_MAX_MEMBERSHIPS = 20 -IPX_TYPE = 1 -TCP_NODELAY = 1 -TCP_MAXSEG = 2 -SOPRI_INTERACTIVE = 0 -SOPRI_NORMAL = 1 -SOPRI_BACKGROUND = 2 - -# Included from sys/types.h - -# Included from linux/types.h -__FD_SETSIZE = 256 - -# Included from asm/types.h -def __FD_ZERO(fdsetp): return \ - - -# Included from sys/bitypes.h - -# Included from pthread/mit/posix.h - -# Included from pthread/mit/types.h - -# Included from pthread/mit/xtypes.h - -# Included from pthread/mit/sys/types.h -IMPLINK_IP = 155 -IMPLINK_LOWEXPER = 156 -IMPLINK_HIGHEXPER = 158 - -# Included from linux/in.h -__SOCK_SIZE__ = 16 -IN_CLASSA_NET = 0xff000000 -IN_CLASSA_NSHIFT = 24 -IN_CLASSA_HOST = (0xffffffff & ~IN_CLASSA_NET) -IN_CLASSA_MAX = 128 -IN_CLASSB_NET = 0xffff0000 -IN_CLASSB_NSHIFT = 16 -IN_CLASSB_HOST = (0xffffffff & ~IN_CLASSB_NET) -IN_CLASSB_MAX = 65536 -IN_CLASSC_NET = 0xffffff00 -IN_CLASSC_NSHIFT = 8 -IN_CLASSC_HOST = (0xffffffff & ~IN_CLASSC_NET) -def IN_MULTICAST(a): return IN_CLASSD(a) - -IN_MULTICAST_NET = 0xF0000000 -INADDR_NONE = 0xffffffff -IN_LOOPBACKNET = 127 -INADDR_LOOPBACK = 0x7f000001 -INADDR_UNSPEC_GROUP = 0xe0000000 -INADDR_ALLHOSTS_GROUP = 0xe0000001 -INADDR_MAX_LOCAL_GROUP = 0xe00000ff - -# Included from asm/byteorder.h -__LITTLE_ENDIAN = 1234 -def __constant_ntohl(x): return \ - -def __constant_ntohs(x): return \ - -def __htonl(x): return __ntohl(x) - -def __htons(x): return __ntohs(x) - -def __constant_htonl(x): return __constant_ntohl(x) - -def __constant_htons(x): return __constant_ntohs(x) - -def ntohl(x): return \ - -def ntohs(x): return \ - -def htonl(x): return \ - -def htons(x): return \ - -def LOOPBACK(x): return (((x) & htonl(0xff000000)) == htonl(0x7f000000)) - -def MULTICAST(x): return (((x) & htonl(0xf0000000)) == htonl(0xe0000000)) - diff --git a/Lib/plat-linux1/SOCKET.py b/Lib/plat-linux1/SOCKET.py deleted file mode 100755 index 71077c3912..0000000000 --- a/Lib/plat-linux1/SOCKET.py +++ /dev/null @@ -1,183 +0,0 @@ -# Generated by h2py from /usr/include/sys/socket.h - -# Included from features.h -_FEATURES_H = 1 -_GNU_SOURCE = 1 -__USE_ANSI = 1 -__FAVOR_BSD = 1 -_BSD_SOURCE = 1 -_SVID_SOURCE = 1 -_POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 2 -__USE_POSIX = 1 -__USE_POSIX2 = 1 -__USE_MISC = 1 -__USE_BSD = 1 -__USE_SVID = 1 -__USE_GNU = 1 -__GNU_LIBRARY__ = 1 - -# Included from sys/cdefs.h -_SYS_CDEFS_H = 1 -def __P(args): return args - -def __P(args): return args - -def __P(args): return () - -def __STRING(x): return #x - -def __STRING(x): return "x" - - -# Included from linux/socket.h - -# Included from asm/socket.h -FIOSETOWN = 0x8901 -SIOCSPGRP = 0x8902 -FIOGETOWN = 0x8903 -SIOCGPGRP = 0x8904 -SIOCATMARK = 0x8905 -SIOCGSTAMP = 0x8906 -SOL_SOCKET = 1 -SO_DEBUG = 1 -SO_REUSEADDR = 2 -SO_TYPE = 3 -SO_ERROR = 4 -SO_DONTROUTE = 5 -SO_BROADCAST = 6 -SO_SNDBUF = 7 -SO_RCVBUF = 8 -SO_KEEPALIVE = 9 -SO_OOBINLINE = 10 -SO_NO_CHECK = 11 -SO_PRIORITY = 12 -SO_LINGER = 13 - -# Included from linux/sockios.h -SIOCADDRT = 0x890B -SIOCDELRT = 0x890C -SIOCGIFNAME = 0x8910 -SIOCSIFLINK = 0x8911 -SIOCGIFCONF = 0x8912 -SIOCGIFFLAGS = 0x8913 -SIOCSIFFLAGS = 0x8914 -SIOCGIFADDR = 0x8915 -SIOCSIFADDR = 0x8916 -SIOCGIFDSTADDR = 0x8917 -SIOCSIFDSTADDR = 0x8918 -SIOCGIFBRDADDR = 0x8919 -SIOCSIFBRDADDR = 0x891a -SIOCGIFNETMASK = 0x891b -SIOCSIFNETMASK = 0x891c -SIOCGIFMETRIC = 0x891d -SIOCSIFMETRIC = 0x891e -SIOCGIFMEM = 0x891f -SIOCSIFMEM = 0x8920 -SIOCGIFMTU = 0x8921 -SIOCSIFMTU = 0x8922 -SIOCSIFHWADDR = 0x8924 -SIOCGIFENCAP = 0x8925 -SIOCSIFENCAP = 0x8926 -SIOCGIFHWADDR = 0x8927 -SIOCGIFSLAVE = 0x8929 -SIOCSIFSLAVE = 0x8930 -SIOCADDMULTI = 0x8931 -SIOCDELMULTI = 0x8932 -OLD_SIOCDARP = 0x8950 -OLD_SIOCGARP = 0x8951 -OLD_SIOCSARP = 0x8952 -SIOCDARP = 0x8953 -SIOCGARP = 0x8954 -SIOCSARP = 0x8955 -SIOCDRARP = 0x8960 -SIOCGRARP = 0x8961 -SIOCSRARP = 0x8962 -SIOCGIFMAP = 0x8970 -SIOCSIFMAP = 0x8971 -SIOCDEVPRIVATE = 0x89F0 -SIOCPROTOPRIVATE = 0x89E0 - -# Included from linux/uio.h -MAX_IOVEC = 8 -SOCK_STREAM = 1 -SOCK_DGRAM = 2 -SOCK_RAW = 3 -SOCK_RDM = 4 -SOCK_SEQPACKET = 5 -SOCK_PACKET = 10 -AF_UNSPEC = 0 -AF_UNIX = 1 -AF_INET = 2 -AF_AX25 = 3 -AF_IPX = 4 -AF_APPLETALK = 5 -AF_NETROM = 6 -AF_BRIDGE = 7 -AF_AAL5 = 8 -AF_X25 = 9 -AF_INET6 = 10 -AF_MAX = 12 -PF_UNSPEC = AF_UNSPEC -PF_UNIX = AF_UNIX -PF_INET = AF_INET -PF_AX25 = AF_AX25 -PF_IPX = AF_IPX -PF_APPLETALK = AF_APPLETALK -PF_NETROM = AF_NETROM -PF_BRIDGE = AF_BRIDGE -PF_AAL5 = AF_AAL5 -PF_X25 = AF_X25 -PF_INET6 = AF_INET6 -PF_MAX = AF_MAX -SOMAXCONN = 128 -MSG_OOB = 1 -MSG_PEEK = 2 -MSG_DONTROUTE = 4 -SOL_IP = 0 -SOL_IPX = 256 -SOL_AX25 = 257 -SOL_ATALK = 258 -SOL_NETROM = 259 -SOL_TCP = 6 -SOL_UDP = 17 -IP_TOS = 1 -IPTOS_LOWDELAY = 0x10 -IPTOS_THROUGHPUT = 0x08 -IPTOS_RELIABILITY = 0x04 -IP_TTL = 2 -IP_HDRINCL = 3 -IP_OPTIONS = 4 -IP_MULTICAST_IF = 32 -IP_MULTICAST_TTL = 33 -IP_MULTICAST_LOOP = 34 -IP_ADD_MEMBERSHIP = 35 -IP_DROP_MEMBERSHIP = 36 -IP_DEFAULT_MULTICAST_TTL = 1 -IP_DEFAULT_MULTICAST_LOOP = 1 -IP_MAX_MEMBERSHIPS = 20 -IPX_TYPE = 1 -TCP_NODELAY = 1 -TCP_MAXSEG = 2 -SOPRI_INTERACTIVE = 0 -SOPRI_NORMAL = 1 -SOPRI_BACKGROUND = 2 - -# Included from sys/types.h - -# Included from linux/types.h -__FD_SETSIZE = 256 - -# Included from asm/types.h -def __FD_ZERO(fdsetp): return \ - - -# Included from sys/bitypes.h - -# Included from pthread/mit/posix.h - -# Included from pthread/mit/types.h - -# Included from pthread/mit/xtypes.h - -# Included from pthread/mit/sys/types.h diff --git a/Lib/plat-linux1/TERMIOS.py b/Lib/plat-linux1/TERMIOS.py deleted file mode 100755 index 4b17df64a1..0000000000 --- a/Lib/plat-linux1/TERMIOS.py +++ /dev/null @@ -1,270 +0,0 @@ -# Generated by h2py from /usr/include/termios.h - -# Included from features.h -_FEATURES_H = 1 -_GNU_SOURCE = 1 -__USE_ANSI = 1 -__FAVOR_BSD = 1 -_BSD_SOURCE = 1 -_SVID_SOURCE = 1 -_POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 2 -__USE_POSIX = 1 -__USE_POSIX2 = 1 -__USE_MISC = 1 -__USE_BSD = 1 -__USE_SVID = 1 -__USE_GNU = 1 -__GNU_LIBRARY__ = 1 - -# Included from sys/cdefs.h -_SYS_CDEFS_H = 1 -def __P(args): return args - -def __P(args): return args - -def __P(args): return () - -def __STRING(x): return #x - -def __STRING(x): return "x" - - -# Included from sys/types.h - -# Included from linux/types.h -__FD_SETSIZE = 256 - -# Included from asm/types.h -def __FD_ZERO(fdsetp): return \ - - -# Included from sys/bitypes.h - -# Included from linux/termios.h - -# Included from asm/termios.h -TCGETS = 0x5401 -TCSETS = 0x5402 -TCSETSW = 0x5403 -TCSETSF = 0x5404 -TCGETA = 0x5405 -TCSETA = 0x5406 -TCSETAW = 0x5407 -TCSETAF = 0x5408 -TCSBRK = 0x5409 -TCXONC = 0x540A -TCFLSH = 0x540B -TIOCEXCL = 0x540C -TIOCNXCL = 0x540D -TIOCSCTTY = 0x540E -TIOCGPGRP = 0x540F -TIOCSPGRP = 0x5410 -TIOCOUTQ = 0x5411 -TIOCSTI = 0x5412 -TIOCGWINSZ = 0x5413 -TIOCSWINSZ = 0x5414 -TIOCMGET = 0x5415 -TIOCMBIS = 0x5416 -TIOCMBIC = 0x5417 -TIOCMSET = 0x5418 -TIOCGSOFTCAR = 0x5419 -TIOCSSOFTCAR = 0x541A -FIONREAD = 0x541B -TIOCINQ = FIONREAD -TIOCLINUX = 0x541C -TIOCCONS = 0x541D -TIOCGSERIAL = 0x541E -TIOCSSERIAL = 0x541F -TIOCPKT = 0x5420 -FIONBIO = 0x5421 -TIOCNOTTY = 0x5422 -TIOCSETD = 0x5423 -TIOCGETD = 0x5424 -TCSBRKP = 0x5425 -TIOCTTYGSTRUCT = 0x5426 -FIONCLEX = 0x5450 -FIOCLEX = 0x5451 -FIOASYNC = 0x5452 -TIOCSERCONFIG = 0x5453 -TIOCSERGWILD = 0x5454 -TIOCSERSWILD = 0x5455 -TIOCGLCKTRMIOS = 0x5456 -TIOCSLCKTRMIOS = 0x5457 -TIOCSERGSTRUCT = 0x5458 -TIOCSERGETLSR = 0x5459 -TIOCSERGETMULTI = 0x545A -TIOCSERSETMULTI = 0x545B -TIOCPKT_DATA = 0 -TIOCPKT_FLUSHREAD = 1 -TIOCPKT_FLUSHWRITE = 2 -TIOCPKT_STOP = 4 -TIOCPKT_START = 8 -TIOCPKT_NOSTOP = 16 -TIOCPKT_DOSTOP = 32 -NCC = 8 -NCCS = 19 -VINTR = 0 -VQUIT = 1 -VERASE = 2 -VKILL = 3 -VEOF = 4 -VTIME = 5 -VMIN = 6 -VSWTC = 7 -VSTART = 8 -VSTOP = 9 -VSUSP = 10 -VEOL = 11 -VREPRINT = 12 -VDISCARD = 13 -VWERASE = 14 -VLNEXT = 15 -VEOL2 = 16 -INIT_C_CC = "\003\034\177\025\004\0\1\0\021\023\032\0\022\017\027\026\0" -IGNBRK = 0000001 -BRKINT = 0000002 -IGNPAR = 0000004 -PARMRK = 0000010 -INPCK = 0000020 -ISTRIP = 0000040 -INLCR = 0000100 -IGNCR = 0000200 -ICRNL = 0000400 -IUCLC = 0001000 -IXON = 0002000 -IXANY = 0004000 -IXOFF = 0010000 -IMAXBEL = 0020000 -OPOST = 0000001 -OLCUC = 0000002 -ONLCR = 0000004 -OCRNL = 0000010 -ONOCR = 0000020 -ONLRET = 0000040 -OFILL = 0000100 -OFDEL = 0000200 -NLDLY = 0000400 -NL0 = 0000000 -NL1 = 0000400 -CRDLY = 0003000 -CR0 = 0000000 -CR1 = 0001000 -CR2 = 0002000 -CR3 = 0003000 -TABDLY = 0014000 -TAB0 = 0000000 -TAB1 = 0004000 -TAB2 = 0010000 -TAB3 = 0014000 -XTABS = 0014000 -BSDLY = 0020000 -BS0 = 0000000 -BS1 = 0020000 -VTDLY = 0040000 -VT0 = 0000000 -VT1 = 0040000 -FFDLY = 0100000 -FF0 = 0000000 -FF1 = 0100000 -CBAUD = 0010017 -B0 = 0000000 -B50 = 0000001 -B75 = 0000002 -B110 = 0000003 -B134 = 0000004 -B150 = 0000005 -B200 = 0000006 -B300 = 0000007 -B600 = 0000010 -B1200 = 0000011 -B1800 = 0000012 -B2400 = 0000013 -B4800 = 0000014 -B9600 = 0000015 -B19200 = 0000016 -B38400 = 0000017 -EXTA = B19200 -EXTB = B38400 -CSIZE = 0000060 -CS5 = 0000000 -CS6 = 0000020 -CS7 = 0000040 -CS8 = 0000060 -CSTOPB = 0000100 -CREAD = 0000200 -PARENB = 0000400 -PARODD = 0001000 -HUPCL = 0002000 -CLOCAL = 0004000 -CBAUDEX = 0010000 -B57600 = 0010001 -B115200 = 0010002 -B230400 = 0010003 -CIBAUD = 002003600000 -CRTSCTS = 020000000000 -ISIG = 0000001 -ICANON = 0000002 -XCASE = 0000004 -ECHO = 0000010 -ECHOE = 0000020 -ECHOK = 0000040 -ECHONL = 0000100 -NOFLSH = 0000200 -TOSTOP = 0000400 -ECHOCTL = 0001000 -ECHOPRT = 0002000 -ECHOKE = 0004000 -FLUSHO = 0010000 -PENDIN = 0040000 -IEXTEN = 0100000 -TIOCM_LE = 0x001 -TIOCM_DTR = 0x002 -TIOCM_RTS = 0x004 -TIOCM_ST = 0x008 -TIOCM_SR = 0x010 -TIOCM_CTS = 0x020 -TIOCM_CAR = 0x040 -TIOCM_RNG = 0x080 -TIOCM_DSR = 0x100 -TIOCM_CD = TIOCM_CAR -TIOCM_RI = TIOCM_RNG -TIOCSER_TEMT = 0x01 -TCOOFF = 0 -TCOON = 1 -TCIOFF = 2 -TCION = 3 -TCIFLUSH = 0 -TCOFLUSH = 1 -TCIOFLUSH = 2 -TCSANOW = 0 -TCSADRAIN = 1 -TCSAFLUSH = 2 -N_TTY = 0 -N_SLIP = 1 -N_MOUSE = 2 -N_PPP = 3 -def CTRL(ch): return ((ch)&0x1F) - -IBSHIFT = 16 -CNUL = 0 -CDEL = 0177 -CESC = ord('\\') -CINTR = 0177 -CQUIT = 034 -CERASE = ord('#') -CKILL = ord('@') -CEOT = 04 -CEOL = 0 -CEOL2 = 0 -CEOF = 4 -CSTART = 021 -CSTOP = 023 -CSWTCH = 032 -NSWTCH = 0 -CSUSP = CTRL(ord('Z')) -CDSUSP = CTRL(ord('Y')) -CRPRNT = CTRL(ord('R')) -CFLUSH = CTRL(ord('O')) -CWERASE = CTRL(ord('W')) -CLNEXT = CTRL(ord('V')) diff --git a/Lib/plat-linux1/regen b/Lib/plat-linux1/regen deleted file mode 100755 index d8dbc04c17..0000000000 --- a/Lib/plat-linux1/regen +++ /dev/null @@ -1,11 +0,0 @@ -#! /bin/sh -case `uname` in -Linux*) ;; -*) echo Probably not on a Linux system 1>&2 - exit 1;; -esac -set -v -h2py /usr/include/sys/fcntl.h -h2py /usr/include/sys/socket.h -h2py -i '(u_long)' /usr/include/netinet/in.h -h2py /usr/include/termios.h diff --git a/Lib/plat-sunos4/FCNTL.py b/Lib/plat-sunos4/FCNTL.py deleted file mode 100755 index 1256d8100a..0000000000 --- a/Lib/plat-sunos4/FCNTL.py +++ /dev/null @@ -1,67 +0,0 @@ -# Generated by h2py from stdin -_FOPEN = (-1) -_FREAD = 0x0001 -_FWRITE = 0x0002 -_FNDELAY = 0x0004 -_FAPPEND = 0x0008 -_FSETBLK = 0x0010 -_FASYNC = 0x0040 -_FSHLOCK = 0x0080 -_FEXLOCK = 0x0100 -_FCREAT = 0x0200 -_FTRUNC = 0x0400 -_FEXCL = 0x0800 -_FNBIO = 0x1000 -_FSYNC = 0x2000 -_FNONBLOCK = 0x4000 -_FNOCTTY = 0x8000 -_FMARK = 0x10000 -_FDEFER = 0x20000 -O_RDONLY = 0 -O_WRONLY = 1 -O_RDWR = 2 -O_APPEND = _FAPPEND -O_CREAT = _FCREAT -O_TRUNC = _FTRUNC -O_EXCL = _FEXCL -O_NONBLOCK = _FNONBLOCK -O_NOCTTY = _FNOCTTY -O_SYNC = _FSYNC -FAPPEND = _FAPPEND -FSYNC = _FSYNC -FASYNC = _FASYNC -FNBIO = _FNBIO -FNONBIO = _FNONBLOCK -FNDELAY = _FNDELAY -FREAD = _FREAD -FWRITE = _FWRITE -FMARK = _FMARK -FDEFER = _FDEFER -FSETBLK = _FSETBLK -FSHLOCK = _FSHLOCK -FEXLOCK = _FEXLOCK -FOPEN = _FOPEN -FCREAT = _FCREAT -FTRUNC = _FTRUNC -FEXCL = _FEXCL -FNOCTTY = _FNOCTTY -FD_CLOEXEC = 1 -F_DUPFD = 0 -F_GETFD = 1 -F_SETFD = 2 -F_GETFL = 3 -F_SETFL = 4 -F_GETOWN = 5 -F_SETOWN = 6 -F_GETLK = 7 -F_SETLK = 8 -F_SETLKW = 9 -F_RGETLK = 10 -F_RSETLK = 11 -F_CNVT = 12 -F_RSETLKW = 13 -F_RDLCK = 1 -F_WRLCK = 2 -F_UNLCK = 3 -F_UNLKSYS = 4 -O_ACCMODE = (O_RDONLY|O_WRONLY|O_RDWR) diff --git a/Lib/plat-sunos4/IN.py b/Lib/plat-sunos4/IN.py deleted file mode 100755 index a05a9445b5..0000000000 --- a/Lib/plat-sunos4/IN.py +++ /dev/null @@ -1,59 +0,0 @@ -# Generated by h2py from /usr/include/netinet/in.h -IPPROTO_IP = 0 -IPPROTO_ICMP = 1 -IPPROTO_IGMP = 2 -IPPROTO_GGP = 3 -IPPROTO_TCP = 6 -IPPROTO_EGP = 8 -IPPROTO_PUP = 12 -IPPROTO_UDP = 17 -IPPROTO_IDP = 22 -IPPROTO_HELLO = 63 -IPPROTO_ND = 77 -IPPROTO_RAW = 255 -IPPROTO_MAX = 256 -IPPORT_ECHO = 7 -IPPORT_DISCARD = 9 -IPPORT_SYSTAT = 11 -IPPORT_DAYTIME = 13 -IPPORT_NETSTAT = 15 -IPPORT_FTP = 21 -IPPORT_TELNET = 23 -IPPORT_SMTP = 25 -IPPORT_TIMESERVER = 37 -IPPORT_NAMESERVER = 42 -IPPORT_WHOIS = 43 -IPPORT_MTP = 57 -IPPORT_TFTP = 69 -IPPORT_RJE = 77 -IPPORT_FINGER = 79 -IPPORT_TTYLINK = 87 -IPPORT_SUPDUP = 95 -IPPORT_EXECSERVER = 512 -IPPORT_LOGINSERVER = 513 -IPPORT_CMDSERVER = 514 -IPPORT_EFSSERVER = 520 -IPPORT_BIFFUDP = 512 -IPPORT_WHOSERVER = 513 -IPPORT_ROUTESERVER = 520 -IPPORT_RESERVED = 1024 -IPPORT_USERRESERVED = 5000 -IMPLINK_IP = 155 -IMPLINK_LOWEXPER = 156 -IMPLINK_HIGHEXPER = 158 -IN_CLASSA_NET = 0xff000000 -IN_CLASSA_NSHIFT = 24 -IN_CLASSA_HOST = 0x00ffffff -IN_CLASSA_MAX = 128 -IN_CLASSB_NET = 0xffff0000 -IN_CLASSB_NSHIFT = 16 -IN_CLASSB_HOST = 0x0000ffff -IN_CLASSB_MAX = 65536 -IN_CLASSC_NET = 0xffffff00 -IN_CLASSC_NSHIFT = 8 -IN_CLASSC_HOST = 0x000000ff -INADDR_ANY = 0x00000000 -INADDR_LOOPBACK = 0x7F000001 -INADDR_BROADCAST = 0xffffffff -IN_LOOPBACKNET = 127 -IP_OPTIONS = 1 diff --git a/Lib/plat-sunos4/SOCKET.py b/Lib/plat-sunos4/SOCKET.py deleted file mode 100755 index 65ce4bc4cb..0000000000 --- a/Lib/plat-sunos4/SOCKET.py +++ /dev/null @@ -1,78 +0,0 @@ -# Generated by h2py from /usr/include/sys/socket.h -SOCK_STREAM = 1 -SOCK_DGRAM = 2 -SOCK_RAW = 3 -SOCK_RDM = 4 -SOCK_SEQPACKET = 5 -SO_DEBUG = 0x0001 -SO_ACCEPTCONN = 0x0002 -SO_REUSEADDR = 0x0004 -SO_KEEPALIVE = 0x0008 -SO_DONTROUTE = 0x0010 -SO_BROADCAST = 0x0020 -SO_USELOOPBACK = 0x0040 -SO_LINGER = 0x0080 -SO_OOBINLINE = 0x0100 -SO_DONTLINGER = (~SO_LINGER) -SO_SNDBUF = 0x1001 -SO_RCVBUF = 0x1002 -SO_SNDLOWAT = 0x1003 -SO_RCVLOWAT = 0x1004 -SO_SNDTIMEO = 0x1005 -SO_RCVTIMEO = 0x1006 -SO_ERROR = 0x1007 -SO_TYPE = 0x1008 -SOL_SOCKET = 0xffff -AF_UNSPEC = 0 -AF_UNIX = 1 -AF_INET = 2 -AF_IMPLINK = 3 -AF_PUP = 4 -AF_CHAOS = 5 -AF_NS = 6 -AF_NBS = 7 -AF_ECMA = 8 -AF_DATAKIT = 9 -AF_CCITT = 10 -AF_SNA = 11 -AF_DECnet = 12 -AF_DLI = 13 -AF_LAT = 14 -AF_HYLINK = 15 -AF_APPLETALK = 16 -AF_NIT = 17 -AF_802 = 18 -AF_OSI = 19 -AF_X25 = 20 -AF_OSINET = 21 -AF_GOSIP = 22 -AF_MAX = 21 -PF_UNSPEC = AF_UNSPEC -PF_UNIX = AF_UNIX -PF_INET = AF_INET -PF_IMPLINK = AF_IMPLINK -PF_PUP = AF_PUP -PF_CHAOS = AF_CHAOS -PF_NS = AF_NS -PF_NBS = AF_NBS -PF_ECMA = AF_ECMA -PF_DATAKIT = AF_DATAKIT -PF_CCITT = AF_CCITT -PF_SNA = AF_SNA -PF_DECnet = AF_DECnet -PF_DLI = AF_DLI -PF_LAT = AF_LAT -PF_HYLINK = AF_HYLINK -PF_APPLETALK = AF_APPLETALK -PF_NIT = AF_NIT -PF_802 = AF_802 -PF_OSI = AF_OSI -PF_X25 = AF_X25 -PF_OSINET = AF_OSINET -PF_GOSIP = AF_GOSIP -PF_MAX = AF_MAX -SOMAXCONN = 5 -MSG_OOB = 0x1 -MSG_PEEK = 0x2 -MSG_DONTROUTE = 0x4 -MSG_MAXIOVLEN = 16 diff --git a/Lib/plat-sunos4/SUNAUDIODEV.py b/Lib/plat-sunos4/SUNAUDIODEV.py deleted file mode 100755 index b66610d903..0000000000 --- a/Lib/plat-sunos4/SUNAUDIODEV.py +++ /dev/null @@ -1,38 +0,0 @@ -# Symbolic constants for use with sunaudiodev module -# The names are the same as in audioio.h with the leading AUDIO_ -# removed. - -# Not all values are supported on all releases of SunOS. - -# Encoding types, for fields i_encoding and o_encoding - -ENCODING_NONE = 0 # no encoding assigned -ENCODING_ULAW = 1 # u-law encoding -ENCODING_ALAW = 2 # A-law encoding -ENCODING_LINEAR = 3 # Linear PCM encoding - -# Gain ranges for i_gain, o_gain and monitor_gain - -MIN_GAIN = 0 # minimum gain value -MAX_GAIN = 255 # maximum gain value - -# Balance values for i_balance and o_balance - -LEFT_BALANCE = 0 # left channel only -MID_BALANCE = 32 # equal left/right channel -RIGHT_BALANCE = 64 # right channel only -BALANCE_SHIFT = 3 - -# Port names for i_port and o_port - -PORT_A = 1 -PORT_B = 2 -PORT_C = 3 -PORT_D = 4 - -SPEAKER = 0x01 # output to built-in speaker -HEADPHONE = 0x02 # output to headphone jack -LINE_OUT = 0x04 # output to line out - -MICROPHONE = 0x01 # input from microphone -LINE_IN = 0x02 # input from line in diff --git a/Lib/plat-sunos4/WAIT.py b/Lib/plat-sunos4/WAIT.py deleted file mode 100755 index 43612f00c0..0000000000 --- a/Lib/plat-sunos4/WAIT.py +++ /dev/null @@ -1,13 +0,0 @@ -# Generated by h2py from /usr/include/sys/wait.h -WUNTRACED = 0004 -WNOHANG = 0100 -WEXITED = 0001 -WTRAPPED = 0002 -WSTOPPED = WUNTRACED -WCONTINUED = 0010 -WNOWAIT = 0200 -WOPTMASK = (WEXITED|WTRAPPED|WSTOPPED|WCONTINUED|WNOHANG|WNOWAIT) -WSTOPFLG = 0177 -WCONTFLG = 0177777 -WCOREFLG = 0200 -WSIGMASK = 0177 diff --git a/Lib/plat-sunos4/regen b/Lib/plat-sunos4/regen deleted file mode 100755 index 8b52d741bf..0000000000 --- a/Lib/plat-sunos4/regen +++ /dev/null @@ -1,12 +0,0 @@ -#! /bin/sh -case `uname -sr` in -'SunOS 4.'*) ;; -*) echo Probably not on a SunOS 4 system 1>&2 - exit 1;; -esac -set -v -h2py </usr/include/sys/fcntlcom.h >FCNTL.py -echo "O_ACCMODE = (O_RDONLY|O_WRONLY|O_RDWR)" >>FCNTL.py -h2py /usr/include/sys/socket.h -h2py /usr/include/sys/wait.h -h2py -i '(u_long)' /usr/include/netinet/in.h diff --git a/Lib/plat-sunos5/FCNTL.py b/Lib/plat-sunos5/FCNTL.py deleted file mode 100755 index 89ce2ed38e..0000000000 --- a/Lib/plat-sunos5/FCNTL.py +++ /dev/null @@ -1,47 +0,0 @@ -# Generated by h2py from /usr/include/sys/fcntl.h -O_RDONLY = 0 -O_WRONLY = 1 -O_RDWR = 2 -O_NDELAY = 0x04 -O_APPEND = 0x08 -O_SYNC = 0x10 -O_DSYNC = 0x40 -O_RSYNC = 0x8000 -O_NONBLOCK = 0x80 -O_PRIV = 0x1000 -O_CREAT = 0x100 -O_TRUNC = 0x200 -O_EXCL = 0x400 -O_NOCTTY = 0x800 -F_DUPFD = 0 -F_GETFD = 1 -F_SETFD = 2 -F_GETFL = 3 -F_SETFL = 4 -F_SETLK = 6 -F_SETLKW = 7 -F_O_GETLK = 5 -F_SETLK = 6 -F_SETLKW = 7 -F_CHKFL = 8 -F_ALLOCSP = 10 -F_FREESP = 11 -F_ISSTREAM = 13 -F_GETLK = 14 -F_PRIV = 15 -F_NPRIV = 16 -F_QUOTACTL = 17 -F_BLOCKS = 18 -F_BLKSIZE = 19 -F_RSETLK = 20 -F_RGETLK = 21 -F_RSETLKW = 22 -F_GETOWN = 23 -F_SETOWN = 24 -F_REVOKE = 25 -F_RDLCK = 01 -F_WRLCK = 02 -F_UNLCK = 03 -F_UNLKSYS = 04 -O_ACCMODE = 3 -FD_CLOEXEC = 1 diff --git a/Lib/plat-sunos5/IN.py b/Lib/plat-sunos5/IN.py deleted file mode 100755 index b4421ba7f0..0000000000 --- a/Lib/plat-sunos5/IN.py +++ /dev/null @@ -1,81 +0,0 @@ -# Generated by h2py from /usr/include/netinet/in.h -IPPROTO_IP = 0 -IPPROTO_ICMP = 1 -IPPROTO_IGMP = 2 -IPPROTO_GGP = 3 -IPPROTO_ENCAP = 4 -IPPROTO_TCP = 6 -IPPROTO_EGP = 8 -IPPROTO_PUP = 12 -IPPROTO_UDP = 17 -IPPROTO_IDP = 22 -IPPROTO_HELLO = 63 -IPPROTO_ND = 77 -IPPROTO_EON = 80 -IPPROTO_RAW = 255 -IPPROTO_MAX = 256 -IPPORT_ECHO = 7 -IPPORT_DISCARD = 9 -IPPORT_SYSTAT = 11 -IPPORT_DAYTIME = 13 -IPPORT_NETSTAT = 15 -IPPORT_FTP = 21 -IPPORT_TELNET = 23 -IPPORT_SMTP = 25 -IPPORT_TIMESERVER = 37 -IPPORT_NAMESERVER = 42 -IPPORT_WHOIS = 43 -IPPORT_MTP = 57 -IPPORT_TFTP = 69 -IPPORT_RJE = 77 -IPPORT_FINGER = 79 -IPPORT_TTYLINK = 87 -IPPORT_SUPDUP = 95 -IPPORT_EXECSERVER = 512 -IPPORT_LOGINSERVER = 513 -IPPORT_CMDSERVER = 514 -IPPORT_EFSSERVER = 520 -IPPORT_BIFFUDP = 512 -IPPORT_WHOSERVER = 513 -IPPORT_ROUTESERVER = 520 -IPPORT_RESERVED = 1024 -IPPORT_USERRESERVED = 5000 -IMPLINK_IP = 155 -IMPLINK_LOWEXPER = 156 -IMPLINK_HIGHEXPER = 158 -IN_CLASSA_NET = 0xff000000 -IN_CLASSA_NSHIFT = 24 -IN_CLASSA_HOST = 0x00ffffff -IN_CLASSA_MAX = 128 -IN_CLASSB_NET = 0xffff0000 -IN_CLASSB_NSHIFT = 16 -IN_CLASSB_HOST = 0x0000ffff -IN_CLASSB_MAX = 65536 -IN_CLASSC_NET = 0xffffff00 -IN_CLASSC_NSHIFT = 8 -IN_CLASSC_HOST = 0x000000ff -IN_CLASSD_NET = 0xf0000000 -IN_CLASSD_NSHIFT = 28 -IN_CLASSD_HOST = 0x0fffffff -INADDR_ANY = 0x00000000 -INADDR_LOOPBACK = 0x7F000001 -INADDR_BROADCAST = 0xffffffff -INADDR_UNSPEC_GROUP = 0xe0000000 -INADDR_ALLHOSTS_GROUP = 0xe0000001 -INADDR_MAX_LOCAL_GROUP = 0xe00000ff -IN_LOOPBACKNET = 127 -IP_OPTIONS = 1 -IP_HDRINCL = 2 -IP_TOS = 3 -IP_TTL = 4 -IP_RECVOPTS = 5 -IP_RECVRETOPTS = 6 -IP_RECVDSTADDR = 7 -IP_RETOPTS = 8 -IP_MULTICAST_IF = 0x10 -IP_MULTICAST_TTL = 0x11 -IP_MULTICAST_LOOP = 0x12 -IP_ADD_MEMBERSHIP = 0x13 -IP_DROP_MEMBERSHIP = 0x14 -IP_DEFAULT_MULTICAST_TTL = 1 -IP_DEFAULT_MULTICAST_LOOP = 1 diff --git a/Lib/plat-sunos5/SOCKET.py b/Lib/plat-sunos5/SOCKET.py deleted file mode 100755 index 3ac2740c0e..0000000000 --- a/Lib/plat-sunos5/SOCKET.py +++ /dev/null @@ -1,103 +0,0 @@ -# Generated by h2py from /usr/include/sys/socket.h -NC_TPI_CLTS = 1 -NC_TPI_COTS = 2 -NC_TPI_COTS_ORD = 3 -NC_TPI_RAW = 4 -SOCK_STREAM = NC_TPI_COTS -SOCK_DGRAM = NC_TPI_CLTS -SOCK_RAW = NC_TPI_RAW -SOCK_RDM = 5 -SOCK_SEQPACKET = 6 -SO_DEBUG = 0x0001 -SO_ACCEPTCONN = 0x0002 -SO_REUSEADDR = 0x0004 -SO_KEEPALIVE = 0x0008 -SO_DONTROUTE = 0x0010 -SO_BROADCAST = 0x0020 -SO_USELOOPBACK = 0x0040 -SO_LINGER = 0x0080 -SO_OOBINLINE = 0x0100 -SO_DONTLINGER = (~SO_LINGER) -SO_SNDBUF = 0x1001 -SO_RCVBUF = 0x1002 -SO_SNDLOWAT = 0x1003 -SO_RCVLOWAT = 0x1004 -SO_SNDTIMEO = 0x1005 -SO_RCVTIMEO = 0x1006 -SO_ERROR = 0x1007 -SO_TYPE = 0x1008 -SO_PROTOTYPE = 0x1009 -SOL_SOCKET = 0xffff -AF_UNSPEC = 0 -AF_UNIX = 1 -AF_INET = 2 -AF_IMPLINK = 3 -AF_PUP = 4 -AF_CHAOS = 5 -AF_NS = 6 -AF_NBS = 7 -AF_ECMA = 8 -AF_DATAKIT = 9 -AF_CCITT = 10 -AF_SNA = 11 -AF_DECnet = 12 -AF_DLI = 13 -AF_LAT = 14 -AF_HYLINK = 15 -AF_APPLETALK = 16 -AF_NIT = 17 -AF_802 = 18 -AF_OSI = 19 -AF_X25 = 20 -AF_OSINET = 21 -AF_GOSIP = 22 -AF_MAX = 22 -PF_UNSPEC = AF_UNSPEC -PF_UNIX = AF_UNIX -PF_INET = AF_INET -PF_IMPLINK = AF_IMPLINK -PF_PUP = AF_PUP -PF_CHAOS = AF_CHAOS -PF_NS = AF_NS -PF_NBS = AF_NBS -PF_ECMA = AF_ECMA -PF_DATAKIT = AF_DATAKIT -PF_CCITT = AF_CCITT -PF_SNA = AF_SNA -PF_DECnet = AF_DECnet -PF_DLI = AF_DLI -PF_LAT = AF_LAT -PF_HYLINK = AF_HYLINK -PF_APPLETALK = AF_APPLETALK -PF_NIT = AF_NIT -PF_802 = AF_802 -PF_OSI = AF_OSI -PF_X25 = AF_X25 -PF_OSINET = AF_OSINET -PF_GOSIP = AF_GOSIP -PF_MAX = AF_MAX -SOMAXCONN = 5 -MSG_OOB = 0x1 -MSG_PEEK = 0x2 -MSG_DONTROUTE = 0x4 -MSG_MAXIOVLEN = 16 -SOCKETSYS = 88 -SOCKETSYS = 83 -SO_ACCEPT = 1 -SO_BIND = 2 -SO_CONNECT = 3 -SO_GETPEERNAME = 4 -SO_GETSOCKNAME = 5 -SO_GETSOCKOPT = 6 -SO_LISTEN = 7 -SO_RECV = 8 -SO_RECVFROM = 9 -SO_SEND = 10 -SO_SENDTO = 11 -SO_SETSOCKOPT = 12 -SO_SHUTDOWN = 13 -SO_SOCKET = 14 -SO_SOCKPOLL = 15 -SO_GETIPDOMAIN = 16 -SO_SETIPDOMAIN = 17 -SO_ADJTIME = 18 diff --git a/Lib/plat-sunos5/SUNAUDIODEV.py b/Lib/plat-sunos5/SUNAUDIODEV.py deleted file mode 100755 index b66610d903..0000000000 --- a/Lib/plat-sunos5/SUNAUDIODEV.py +++ /dev/null @@ -1,38 +0,0 @@ -# Symbolic constants for use with sunaudiodev module -# The names are the same as in audioio.h with the leading AUDIO_ -# removed. - -# Not all values are supported on all releases of SunOS. - -# Encoding types, for fields i_encoding and o_encoding - -ENCODING_NONE = 0 # no encoding assigned -ENCODING_ULAW = 1 # u-law encoding -ENCODING_ALAW = 2 # A-law encoding -ENCODING_LINEAR = 3 # Linear PCM encoding - -# Gain ranges for i_gain, o_gain and monitor_gain - -MIN_GAIN = 0 # minimum gain value -MAX_GAIN = 255 # maximum gain value - -# Balance values for i_balance and o_balance - -LEFT_BALANCE = 0 # left channel only -MID_BALANCE = 32 # equal left/right channel -RIGHT_BALANCE = 64 # right channel only -BALANCE_SHIFT = 3 - -# Port names for i_port and o_port - -PORT_A = 1 -PORT_B = 2 -PORT_C = 3 -PORT_D = 4 - -SPEAKER = 0x01 # output to built-in speaker -HEADPHONE = 0x02 # output to headphone jack -LINE_OUT = 0x04 # output to line out - -MICROPHONE = 0x01 # input from microphone -LINE_IN = 0x02 # input from line in diff --git a/Lib/plat-sunos5/TERMIOS.py b/Lib/plat-sunos5/TERMIOS.py deleted file mode 100755 index 264c884cc5..0000000000 --- a/Lib/plat-sunos5/TERMIOS.py +++ /dev/null @@ -1,385 +0,0 @@ -# Generated by h2py from /usr/include/termios.h - -# Included from sys/termios.h - -# Included from sys/feature_tests.h -_POSIX_C_SOURCE = 1 - -# Included from sys/ttydev.h -B0 = 0 -B50 = 1 -B75 = 2 -B110 = 3 -B134 = 4 -B150 = 5 -B200 = 6 -B300 = 7 -B600 = 8 -B1200 = 9 -B1800 = 10 -B2400 = 11 -B4800 = 12 -B9600 = 13 -B19200 = 14 -B38400 = 15 -EXTA = 14 -EXTB = 15 - -# Included from sys/types.h - -# Included from sys/machtypes.h - -# Included from sys/isa_defs.h -SHRT_MIN = -32768 -SHRT_MAX = 32767 -INT_MIN = (-2147483647-1) -INT_MAX = 2147483647 -LONG_MIN = (-2147483647-1) -LONG_MAX = 2147483647 -P_MYID = (-1) - -# Included from sys/select.h - -# Included from sys/time.h -DST_NONE = 0 -DST_USA = 1 -DST_AUST = 2 -DST_WET = 3 -DST_MET = 4 -DST_EET = 5 -DST_CAN = 6 -DST_GB = 7 -DST_RUM = 8 -DST_TUR = 9 -DST_AUSTALT = 10 -ITIMER_REAL = 0 -ITIMER_VIRTUAL = 1 -ITIMER_PROF = 2 -ITIMER_REALPROF = 3 -SEC = 1 -MILLISEC = 1000 -MICROSEC = 1000000 -NANOSEC = 1000000000 -CLOCK_REALTIME = 0 -CLOCK_VIRTUAL = 1 -CLOCK_PROF = 2 -TIMER_RELTIME = 0x0 -TIMER_ABSTIME = 0x1 - -# Included from sys/mutex.h - -# Included from sys/dki_lkinfo.h - -# Included from sys/dl.h -NOSTATS = 1 -LSB_NLKDS = 91 -def MUTEX_HELD(x): return (mutex_owned(x)) - - -# Included from time.h -NULL = 0 -CLOCKS_PER_SEC = 1000000 - -# Included from sys/siginfo.h -SIGEV_NONE = 1 -SIGEV_SIGNAL = 2 -SI_NOINFO = 32767 -SI_USER = 0 -SI_LWP = (-1) -SI_QUEUE = (-2) -SI_TIMER = (-3) -SI_ASYNCIO = (-4) -SI_MESGQ = (-5) - -# Included from sys/machsig.h -ILL_ILLOPC = 1 -ILL_ILLOPN = 2 -ILL_ILLADR = 3 -ILL_ILLTRP = 4 -ILL_PRVOPC = 5 -ILL_PRVREG = 6 -ILL_COPROC = 7 -ILL_BADSTK = 8 -NSIGILL = 8 -EMT_TAGOVF = 1 -NSIGEMT = 1 -FPE_INTDIV = 1 -FPE_INTOVF = 2 -FPE_FLTDIV = 3 -FPE_FLTOVF = 4 -FPE_FLTUND = 5 -FPE_FLTRES = 6 -FPE_FLTINV = 7 -FPE_FLTSUB = 8 -NSIGFPE = 8 -SEGV_MAPERR = 1 -SEGV_ACCERR = 2 -NSIGSEGV = 2 -BUS_ADRALN = 1 -BUS_ADRERR = 2 -BUS_OBJERR = 3 -NSIGBUS = 3 -TRAP_BRKPT = 1 -TRAP_TRACE = 2 -NSIGTRAP = 2 -CLD_EXITED = 1 -CLD_KILLED = 2 -CLD_DUMPED = 3 -CLD_TRAPPED = 4 -CLD_STOPPED = 5 -CLD_CONTINUED = 6 -NSIGCLD = 6 -POLL_IN = 1 -POLL_OUT = 2 -POLL_MSG = 3 -POLL_ERR = 4 -POLL_PRI = 5 -POLL_HUP = 6 -NSIGPOLL = 6 -PROF_SIG = 1 -NSIGPROF = 1 -SI_MAXSZ = 128 -FD_SETSIZE = 1024 -NBBY = 8 -_POSIX_VDISABLE = 0 -def CTRL(c): return ((c)&037) - -IBSHIFT = 16 -NCC = 8 -NCCS = 19 -VINTR = 0 -VQUIT = 1 -VERASE = 2 -VKILL = 3 -VEOF = 4 -VEOL = 5 -VEOL2 = 6 -VMIN = 4 -VTIME = 5 -VSWTCH = 7 -VSTART = 8 -VSTOP = 9 -VSUSP = 10 -VDSUSP = 11 -VREPRINT = 12 -VDISCARD = 13 -VWERASE = 14 -VLNEXT = 15 -VCEOF = NCC -VCEOL = (NCC + 1) -CNUL = 0 -CDEL = 0177 -CESC = ord('\\') -CINTR = CTRL(ord('c')) -CQUIT = 034 -CERASE = 0177 -CKILL = CTRL(ord('u')) -CEOT = 04 -CEOL = 0 -CEOL2 = 0 -CEOF = 04 -CSTART = 021 -CSTOP = 023 -CSWTCH = 032 -CNSWTCH = 0 -CSUSP = CTRL(ord('z')) -CDSUSP = CTRL(ord('y')) -CRPRNT = CTRL(ord('r')) -CFLUSH = CTRL(ord('o')) -CWERASE = CTRL(ord('w')) -CLNEXT = CTRL(ord('v')) -IGNBRK = 0000001 -BRKINT = 0000002 -IGNPAR = 0000004 -PARMRK = 0000010 -INPCK = 0000020 -ISTRIP = 0000040 -INLCR = 0000100 -IGNCR = 0000200 -ICRNL = 0000400 -IUCLC = 0001000 -IXON = 0002000 -IXANY = 0004000 -IXOFF = 0010000 -IMAXBEL = 0020000 -DOSMODE = 0100000 -OPOST = 0000001 -OLCUC = 0000002 -ONLCR = 0000004 -OCRNL = 0000010 -ONOCR = 0000020 -ONLRET = 0000040 -OFILL = 0000100 -OFDEL = 0000200 -NLDLY = 0000400 -NL0 = 0 -NL1 = 0000400 -CRDLY = 0003000 -CR0 = 0 -CR1 = 0001000 -CR2 = 0002000 -CR3 = 0003000 -TABDLY = 0014000 -TAB0 = 0 -TAB1 = 0004000 -TAB2 = 0010000 -TAB3 = 0014000 -XTABS = 0014000 -BSDLY = 0020000 -BS0 = 0 -BS1 = 0020000 -VTDLY = 0040000 -VT0 = 0 -VT1 = 0040000 -FFDLY = 0100000 -FF0 = 0 -FF1 = 0100000 -PAGEOUT = 0200000 -WRAP = 0400000 -CBAUD = 0000017 -CSIZE = 0000060 -CS5 = 0 -CS6 = 0000020 -CS7 = 0000040 -CS8 = 0000060 -CSTOPB = 0000100 -CREAD = 0000200 -PARENB = 0000400 -PARODD = 0001000 -HUPCL = 0002000 -CLOCAL = 0004000 -RCV1EN = 0010000 -XMT1EN = 0020000 -LOBLK = 0040000 -XCLUDE = 0100000 -CRTSCTS = 020000000000 -CIBAUD = 03600000 -PAREXT = 04000000 -ISIG = 0000001 -ICANON = 0000002 -XCASE = 0000004 -ECHO = 0000010 -ECHOE = 0000020 -ECHOK = 0000040 -ECHONL = 0000100 -NOFLSH = 0000200 -TOSTOP = 0000400 -ECHOCTL = 0001000 -ECHOPRT = 0002000 -ECHOKE = 0004000 -DEFECHO = 0010000 -FLUSHO = 0020000 -PENDIN = 0040000 -IEXTEN = 0100000 -_TIOC = (ord('T')<<8) -TIOC = _TIOC -TCGETA = (_TIOC|1) -TCSETA = (_TIOC|2) -TCSETAW = (_TIOC|3) -TCSETAF = (_TIOC|4) -TCSBRK = (_TIOC|5) -TCXONC = (_TIOC|6) -TCFLSH = (_TIOC|7) -TIOCKBON = (_TIOC|8) -TIOCKBOF = (_TIOC|9) -KBENABLED = (_TIOC|10) -IOCTYPE = 0xff00 -TCDSET = (_TIOC|32) -RTS_TOG = (_TIOC|33) -TIOCGWINSZ = (_TIOC|104) -TIOCSWINSZ = (_TIOC|103) -TIOCGSOFTCAR = (_TIOC|105) -TIOCSSOFTCAR = (_TIOC|106) -TCGETS = (_TIOC|13) -TCSETS = (_TIOC|14) -TCSANOW = (_TIOC|14) -TCSETSW = (_TIOC|15) -TCSADRAIN = (_TIOC|15) -TCSETSF = (_TIOC|16) -TCSAFLUSH = (_TIOC|16) -TCIFLUSH = 0 -TCOFLUSH = 1 -TCIOFLUSH = 2 -TCOOFF = 0 -TCOON = 1 -TCIOFF = 2 -TCION = 3 -tIOC = (ord('t')<<8) -TIOCGETD = (tIOC|0) -TIOCSETD = (tIOC|1) -TIOCHPCL = (tIOC|2) -TIOCGETP = (tIOC|8) -TIOCSETP = (tIOC|9) -TIOCSETN = (tIOC|10) -TIOCEXCL = (tIOC|13) -TIOCNXCL = (tIOC|14) -TIOCFLUSH = (tIOC|16) -TIOCSETC = (tIOC|17) -TIOCGETC = (tIOC|18) -TIOCLBIS = (tIOC|127) -TIOCLBIC = (tIOC|126) -TIOCLSET = (tIOC|125) -TIOCLGET = (tIOC|124) -TIOCSBRK = (tIOC|123) -TIOCCBRK = (tIOC|122) -TIOCSDTR = (tIOC|121) -TIOCCDTR = (tIOC|120) -TIOCSLTC = (tIOC|117) -TIOCGLTC = (tIOC|116) -TIOCOUTQ = (tIOC|115) -TIOCNOTTY = (tIOC|113) -TIOCSTOP = (tIOC|111) -TIOCSTART = (tIOC|110) -TIOCGPGRP = (tIOC|20) -TIOCSPGRP = (tIOC|21) -TIOCGSID = (tIOC|22) -TIOCSSID = (tIOC|24) -TIOCSTI = (tIOC|23) -TIOCMSET = (tIOC|26) -TIOCMBIS = (tIOC|27) -TIOCMBIC = (tIOC|28) -TIOCMGET = (tIOC|29) -TIOCM_LE = 0001 -TIOCM_DTR = 0002 -TIOCM_RTS = 0004 -TIOCM_ST = 0010 -TIOCM_SR = 0020 -TIOCM_CTS = 0040 -TIOCM_CAR = 0100 -TIOCM_CD = TIOCM_CAR -TIOCM_RNG = 0200 -TIOCM_RI = TIOCM_RNG -TIOCM_DSR = 0400 -TIOCREMOTE = (tIOC|30) -TIOCSIGNAL = (tIOC|31) -LDIOC = (ord('D')<<8) -LDOPEN = (LDIOC|0) -LDCLOSE = (LDIOC|1) -LDCHG = (LDIOC|2) -LDGETT = (LDIOC|8) -LDSETT = (LDIOC|9) -LDSMAP = (LDIOC|110) -LDGMAP = (LDIOC|111) -LDNMAP = (LDIOC|112) -LDEMAP = (LDIOC|113) -LDDMAP = (LDIOC|114) -DIOC = (ord('d')<<8) -DIOCGETP = (DIOC|8) -DIOCSETP = (DIOC|9) -FIORDCHK = ((ord('f')<<8)|3) -B0 = 0 -B50 = 1 -B75 = 2 -B110 = 3 -B134 = 4 -B150 = 5 -B200 = 6 -B300 = 7 -B600 = 8 -B1200 = 9 -B1800 = 10 -B2400 = 11 -B4800 = 12 -B9600 = 13 -B19200 = 14 -B38400 = 15 diff --git a/Lib/plat-sunos5/regen b/Lib/plat-sunos5/regen deleted file mode 100755 index 2f2cdeff91..0000000000 --- a/Lib/plat-sunos5/regen +++ /dev/null @@ -1,11 +0,0 @@ -#! /bin/sh -case `uname -sr` in -'SunOS 5.'*) ;; -*) echo Probably not on a Solaris 2 system 1>&2 - exit 1;; -esac -set -v -h2py /usr/include/sys/fcntl.h -h2py /usr/include/sys/socket.h -h2py -i '(u_long)' /usr/include/netinet/in.h -h2py /usr/include/termios.h diff --git a/Lib/poly.py b/Lib/poly.py deleted file mode 100644 index 57bd2032d4..0000000000 --- a/Lib/poly.py +++ /dev/null @@ -1,52 +0,0 @@ -# module 'poly' -- Polynomials - -# A polynomial is represented by a list of coefficients, e.g., -# [1, 10, 5] represents 1*x**0 + 10*x**1 + 5*x**2 (or 1 + 10x + 5x**2). -# There is no way to suppress internal zeros; trailing zeros are -# taken out by normalize(). - -def normalize(p): # Strip unnecessary zero coefficients - n = len(p) - while p: - if p[n-1]: return p[:n] - n = n-1 - return [] - -def plus(a, b): - if len(a) < len(b): a, b = b, a # make sure a is the longest - res = a[:] # make a copy - for i in range(len(b)): - res[i] = res[i] + b[i] - return normalize(res) - -def minus(a, b): - neg_b = map(lambda x: -x, b[:]) - return plus(a, neg_b) - -def one(power, coeff): # Representation of coeff * x**power - res = [] - for i in range(power): res.append(0) - return res + [coeff] - -def times(a, b): - res = [] - for i in range(len(a)): - for j in range(len(b)): - res = plus(res, one(i+j, a[i]*b[j])) - return res - -def power(a, n): # Raise polynomial a to the positive integral power n - if n == 0: return [1] - if n == 1: return a - if n/2*2 == n: - b = power(a, n/2) - return times(b, b) - return times(power(a, n-1), a) - -def der(a): # First derivative - res = a[1:] - for i in range(len(res)): - res[i] = res[i] * (i+1) - return res - -# Computing a primitive function would require rational arithmetic... diff --git a/Lib/popen2.py b/Lib/popen2.py deleted file mode 100644 index 45dcbb9ab3..0000000000 --- a/Lib/popen2.py +++ /dev/null @@ -1,35 +0,0 @@ -import os -import sys -import string - -MAXFD = 100 # Max number of file descriptors (os.getdtablesize()???) - -def popen2(cmd): - cmd = ['/bin/sh', '-c', cmd] - p2cread, p2cwrite = os.pipe() - c2pread, c2pwrite = os.pipe() - pid = os.fork() - if pid == 0: - # Child - os.close(0) - os.close(1) - if os.dup(p2cread) <> 0: - sys.stderr.write('popen2: bad read dup\n') - if os.dup(c2pwrite) <> 1: - sys.stderr.write('popen2: bad write dup\n') - for i in range(3, MAXFD): - try: - os.close(i) - except: - pass - try: - os.execv(cmd[0], cmd) - finally: - os._exit(1) - # Shouldn't come here, I guess - os._exit(1) - os.close(p2cread) - tochild = os.fdopen(p2cwrite, 'w') - os.close(c2pwrite) - fromchild = os.fdopen(c2pread, 'r') - return fromchild, tochild diff --git a/Lib/posixfile.py b/Lib/posixfile.py deleted file mode 100644 index 459cd52078..0000000000 --- a/Lib/posixfile.py +++ /dev/null @@ -1,207 +0,0 @@ -# -# Start of posixfile.py -# - -# -# Extended file operations -# -# f = posixfile.open(filename, [mode, [bufsize]]) -# will create a new posixfile object -# -# f = posixfile.fileopen(fileobject) -# will create a posixfile object from a builtin file object -# -# f.file() -# will return the original builtin file object -# -# f.dup() -# will return a new file object based on a new filedescriptor -# -# f.dup2(fd) -# will return a new file object based on the given filedescriptor -# -# f.flags(mode) -# will turn on the associated flag (merge) -# mode can contain the following characters: -# -# (character representing a flag) -# a append only flag -# c close on exec flag -# n no delay flag -# s synchronization flag -# (modifiers) -# ! turn flags 'off' instead of default 'on' -# = copy flags 'as is' instead of default 'merge' -# ? return a string in which the characters represent the flags -# that are set -# -# note: - the '!' and '=' modifiers are mutually exclusive. -# - the '?' modifier will return the status of the flags after they -# have been changed by other characters in the mode string -# -# f.lock(mode [, len [, start [, whence]]]) -# will (un)lock a region -# mode can contain the following characters: -# -# (character representing type of lock) -# u unlock -# r read lock -# w write lock -# (modifiers) -# | wait until the lock can be granted -# ? return the first lock conflicting with the requested lock -# or 'None' if there is no conflict. The lock returned is in the -# format (mode, len, start, whence, pid) where mode is a -# character representing the type of lock ('r' or 'w') -# -# note: - the '?' modifier prevents a region from being locked; it is -# query only -# - -class _posixfile_: - states = ['open', 'closed'] - - # - # Internal routines - # - def __repr__(self): - file = self._file_ - return "<%s posixfile '%s', mode '%s' at %s>" % \ - (self.states[file.closed], file.name, file.mode, \ - hex(id(self))[2:]) - - def __del__(self): - self._file_.close() - - # - # Initialization routines - # - def open(self, name, mode='r', bufsize=-1): - import __builtin__ - return self.fileopen(__builtin__.open(name, mode, bufsize)) - - def fileopen(self, file): - if `type(file)` != "<type 'file'>": - raise TypeError, 'posixfile.fileopen() arg must be file object' - self._file_ = file - # Copy basic file methods - for method in file.__methods__: - setattr(self, method, getattr(file, method)) - return self - - # - # New methods - # - def file(self): - return self._file_ - - def dup(self): - import posix - - try: ignore = posix.fdopen - except: raise AttributeError, 'dup() method unavailable' - - return posix.fdopen(posix.dup(self._file_.fileno()), self._file_.mode) - - def dup2(self, fd): - import posix - - try: ignore = posix.fdopen - except: raise AttributeError, 'dup() method unavailable' - - posix.dup2(self._file_.fileno(), fd) - return posix.fdopen(fd, self._file_.mode) - - def flags(self, *which): - import fcntl, FCNTL - - if which: - if len(which) > 1: - raise TypeError, 'Too many arguments' - which = which[0] - else: which = '?' - - l_flags = 0 - if 'n' in which: l_flags = l_flags | FCNTL.O_NDELAY - if 'a' in which: l_flags = l_flags | FCNTL.O_APPEND - if 's' in which: l_flags = l_flags | FCNTL.O_SYNC - - file = self._file_ - - if '=' not in which: - cur_fl = fcntl.fcntl(file.fileno(), FCNTL.F_GETFL, 0) - if '!' in which: l_flags = cur_fl & ~ l_flags - else: l_flags = cur_fl | l_flags - - l_flags = fcntl.fcntl(file.fileno(), FCNTL.F_SETFL, l_flags) - - if 'c' in which: - arg = ('!' not in which) # 0 is don't, 1 is do close on exec - l_flags = fcntl.fcntl(file.fileno(), FCNTL.F_SETFD, arg) - - if '?' in which: - which = '' # Return current flags - l_flags = fcntl.fcntl(file.fileno(), FCNTL.F_GETFL, 0) - if FCNTL.O_APPEND & l_flags: which = which + 'a' - if fcntl.fcntl(file.fileno(), FCNTL.F_GETFD, 0) & 1: - which = which + 'c' - if FCNTL.O_NDELAY & l_flags: which = which + 'n' - if FCNTL.O_SYNC & l_flags: which = which + 's' - return which - - def lock(self, how, *args): - import struct, fcntl, FCNTL - - if 'w' in how: l_type = FCNTL.F_WRLCK - elif 'r' in how: l_type = FCNTL.F_RDLCK - elif 'u' in how: l_type = FCNTL.F_UNLCK - else: raise TypeError, 'no type of lock specified' - - if '|' in how: cmd = FCNTL.F_SETLKW - elif '?' in how: cmd = FCNTL.F_GETLK - else: cmd = FCNTL.F_SETLK - - l_whence = 0 - l_start = 0 - l_len = 0 - - if len(args) == 1: - l_len = args[0] - elif len(args) == 2: - l_len, l_start = args - elif len(args) == 3: - l_len, l_start, l_whence = args - elif len(args) > 3: - raise TypeError, 'too many arguments' - - flock = struct.pack('hhllhh', l_type, l_whence, l_start, l_len, 0, 0) - flock = fcntl.fcntl(self._file_.fileno(), cmd, flock) - - if '?' in how: - l_type, l_whence, l_start, l_len, l_sysid, l_pid = \ - struct.unpack('hhllhh', flock) - if l_type != FCNTL.F_UNLCK: - if l_type == FCNTL.F_RDLCK: - return 'r', l_len, l_start, l_whence, l_pid - else: - return 'w', l_len, l_start, l_whence, l_pid - -# -# Public routine to obtain a posixfile object -# -def open(name, mode='r', bufsize=-1): - return _posixfile_().open(name, mode, bufsize) - -def fileopen(file): - return _posixfile_().fileopen(file) - -# -# Constants -# -SEEK_SET = 0 -SEEK_CUR = 1 -SEEK_END = 2 - -# -# End of posixfile.py -# diff --git a/Lib/posixpath.py b/Lib/posixpath.py deleted file mode 100644 index d284834488..0000000000 --- a/Lib/posixpath.py +++ /dev/null @@ -1,307 +0,0 @@ -# Module 'posixpath' -- common operations on POSIX pathnames - -import posix -import stat - - -# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac. -# On MS-DOS this may also turn slashes into backslashes; however, other -# normalizations (such as optimizing '../' away) are not allowed -# (another function should be defined to do that). - -def normcase(s): - return s - - -# Return wheter a path is absolute. -# Trivial in Posix, harder on the Mac or MS-DOS. - -def isabs(s): - return s[:1] == '/' - - -# Join two pathnames. -# Ignore the first part if the second part is absolute. -# Insert a '/' unless the first part is empty or already ends in '/'. - -def join(a, b): - if b[:1] == '/': return b - if a == '' or a[-1:] == '/': return a + b - # Note: join('x', '') returns 'x/'; is this what we want? - return a + '/' + b - - -# Split a path in head (everything up to the last '/') and tail (the -# rest). If the path ends in '/', tail will be empty. If there is no -# '/' in the path, head will be empty. -# Trailing '/'es are stripped from head unless it is the root. - -def split(p): - import string - i = string.rfind(p, '/') + 1 - head, tail = p[:i], p[i:] - if head and head <> '/'*len(head): - while head[-1] == '/': - head = head[:-1] - return head, tail - - -# Split a path in root and extension. -# The extension is everything starting at the first dot in the last -# pathname component; the root is everything before that. -# It is always true that root + ext == p. - -def splitext(p): - root, ext = '', '' - for c in p: - if c == '/': - root, ext = root + ext + c, '' - elif c == '.': - if ext: - root, ext = root + ext, c - else: - ext = c - elif ext: - ext = ext + c - else: - root = root + c - return root, ext - - -# Split a pathname into a drive specification and the rest of the -# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty. - -def splitdrive(p): - return '', p - - -# Return the tail (basename) part of a path. - -def basename(p): - return split(p)[1] - - -# Return the head (dirname) part of a path. - -def dirname(p): - return split(p)[0] - - -# Return the longest prefix of all list elements. - -def commonprefix(m): - if not m: return '' - prefix = m[0] - for item in m: - for i in range(len(prefix)): - if prefix[:i+1] <> item[:i+1]: - prefix = prefix[:i] - if i == 0: return '' - break - return prefix - - -# Is a path a symbolic link? -# This will always return false on systems where posix.lstat doesn't exist. - -def islink(path): - try: - st = posix.lstat(path) - except (posix.error, AttributeError): - return 0 - return stat.S_ISLNK(st[stat.ST_MODE]) - - -# Does a path exist? -# This is false for dangling symbolic links. - -def exists(path): - try: - st = posix.stat(path) - except posix.error: - return 0 - return 1 - - -# Is a path a posix directory? -# This follows symbolic links, so both islink() and isdir() can be true -# for the same path. - -def isdir(path): - try: - st = posix.stat(path) - except posix.error: - return 0 - return stat.S_ISDIR(st[stat.ST_MODE]) - - -# Is a path a regular file? -# This follows symbolic links, so both islink() and isfile() can be true -# for the same path. - -def isfile(path): - try: - st = posix.stat(path) - except posix.error: - return 0 - return stat.S_ISREG(st[stat.ST_MODE]) - - -# Are two filenames really pointing to the same file? - -def samefile(f1, f2): - s1 = posix.stat(f1) - s2 = posix.stat(f2) - return samestat(s1, s2) - - -# Are two open files really referencing the same file? -# (Not necessarily the same file descriptor!) -# XXX Oops, posix.fstat() doesn't exist yet! - -def sameopenfile(fp1, fp2): - s1 = posix.fstat(fp1) - s2 = posix.fstat(fp2) - return samestat(s1, s2) - - -# Are two stat buffers (obtained from stat, fstat or lstat) -# describing the same file? - -def samestat(s1, s2): - return s1[stat.ST_INO] == s2[stat.ST_INO] and \ - s1[stat.ST_DEV] == s2[stat.ST_DEV] - - -# Is a path a mount point? -# (Does this work for all UNIXes? Is it even guaranteed to work by POSIX?) - -def ismount(path): - try: - s1 = posix.stat(path) - s2 = posix.stat(join(path, '..')) - except posix.error: - return 0 # It doesn't exist -- so not a mount point :-) - dev1 = s1[stat.ST_DEV] - dev2 = s2[stat.ST_DEV] - if dev1 != dev2: - return 1 # path/.. on a different device as path - ino1 = s1[stat.ST_INO] - ino2 = s2[stat.ST_INO] - if ino1 == ino2: - return 1 # path/.. is the same i-node as path - return 0 - - -# Directory tree walk. -# For each directory under top (including top itself, but excluding -# '.' and '..'), func(arg, dirname, filenames) is called, where -# dirname is the name of the directory and filenames is the list -# files files (and subdirectories etc.) in the directory. -# The func may modify the filenames list, to implement a filter, -# or to impose a different order of visiting. - -def walk(top, func, arg): - try: - names = posix.listdir(top) - except posix.error: - return - func(arg, top, names) - exceptions = ('.', '..') - for name in names: - if name not in exceptions: - name = join(top, name) - if isdir(name) and not islink(name): - walk(name, func, arg) - - -# Expand paths beginning with '~' or '~user'. -# '~' means $HOME; '~user' means that user's home directory. -# If the path doesn't begin with '~', or if the user or $HOME is unknown, -# the path is returned unchanged (leaving error reporting to whatever -# function is called with the expanded path as argument). -# See also module 'glob' for expansion of *, ? and [...] in pathnames. -# (A function should also be defined to do full *sh-style environment -# variable expansion.) - -def expanduser(path): - if path[:1] <> '~': - return path - i, n = 1, len(path) - while i < n and path[i] <> '/': - i = i+1 - if i == 1: - if not posix.environ.has_key('HOME'): - return path - userhome = posix.environ['HOME'] - else: - import pwd - try: - pwent = pwd.getpwnam(path[1:i]) - except KeyError: - return path - userhome = pwent[5] - if userhome[-1:] == '/': i = i+1 - return userhome + path[i:] - - -# Expand paths containing shell variable substitutions. -# This expands the forms $variable and ${variable} only. -# Non-existant variables are left unchanged. - -_varprog = None - -def expandvars(path): - global _varprog - if '$' not in path: - return path - if not _varprog: - import regex - _varprog = regex.compile('$\([a-zA-Z0-9_]+\|{[^}]*}\)') - i = 0 - while 1: - i = _varprog.search(path, i) - if i < 0: - break - name = _varprog.group(1) - j = i + len(_varprog.group(0)) - if name[:1] == '{' and name[-1:] == '}': - name = name[1:-1] - if posix.environ.has_key(name): - tail = path[j:] - path = path[:i] + posix.environ[name] - i = len(path) - path = path + tail - else: - i = j - return path - - -# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B. -# It should be understood that this may change the meaning of the path -# if it contains symbolic links! - -def normpath(path): - import string - # Treat initial slashes specially - slashes = '' - while path[:1] == '/': - slashes = slashes + '/' - path = path[1:] - comps = string.splitfields(path, '/') - i = 0 - while i < len(comps): - if comps[i] == '.': - del comps[i] - elif comps[i] == '..' and i > 0 and \ - comps[i-1] not in ('', '..'): - del comps[i-1:i+1] - i = i-1 - elif comps[i] == '' and i > 0 and comps[i-1] <> '': - del comps[i] - else: - i = i+1 - # If the path is now empty, substitute '.' - if not comps and not slashes: - comps.append('.') - return slashes + string.joinfields(comps, '/') diff --git a/Lib/profile.doc b/Lib/profile.doc deleted file mode 100644 index bf5d8e3af0..0000000000 --- a/Lib/profile.doc +++ /dev/null @@ -1,702 +0,0 @@ -profile.doc last updated 6/23/94 [by Guido] - - PROFILER DOCUMENTATION and (mini) USER'S MANUAL - -Copyright 1994, by InfoSeek Corporation, all rights reserved. -Written by James Roskind - -Permission to use, copy, modify, and distribute this Python software -and its associated documentation for any purpose (subject to the -restriction in the following sentence) without fee is hereby granted, -provided that the above copyright notice appears in all copies, and -that both that copyright notice and this permission notice appear in -supporting documentation, and that the name of InfoSeek not be used in -advertising or publicity pertaining to distribution of the software -without specific, written prior permission. This permission is -explicitly restricted to the copying and modification of the software -to remain in Python, compiled Python, or other languages (such as C) -wherein the modified or derived code is exclusively imported into a -Python module. - -INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS -SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION 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. - - -The profiler was written after only programming in Python for 3 weeks. -As a result, it is probably clumsy code, but I don't know for sure yet -'cause I'm a beginner :-). I did work hard to make the code run fast, -so that profiling would be a reasonable thing to do. I tried not to -repeat code fragments, but I'm sure I did some stuff in really awkward -ways at times. Please send suggestions for improvements to: -jar@infoseek.com. I won't promise *any* support. ...but I'd -appreciate the feedback. - - -SECTION HEADING LIST: - INTRODUCTION - HOW IS THIS profile DIFFERENT FROM THE OLD profile MODULE? - INSTANT USERS MANUAL - WHAT IS DETERMINISTIC PROFILING? - REFERENCE MANUAL - FUNCTION profile.run(string, filename_opt) - CLASS Stats(filename, ...) - METHOD strip_dirs() - METHOD add(filename, ...) - METHOD sort_stats(key, ...) - METHOD reverse_order() - METHOD print_stats(restriction, ...) - METHOD print_callers(restrictions, ...) - METHOD print_callees(restrictions, ...) - METHOD ignore() - LIMITATIONS - CALIBRATION - EXTENSIONS: Deriving Better Profilers - - - -INTRODUCTION - -A "profiler" is a program that describes the run time performance of a -program, providing a variety of statistics. This documentation -describes the profiler functionality provided in the modules -"profile" and "pstats." This profiler provides "deterministic -profiling" of any Python programs. It also provides a series of -report generation tools to allow users to rapidly examine the results -of a profile operation. - - -HOW IS THIS profile DIFFERENT FROM THE OLD profile MODULE? - -The big changes from standard profiling module are that you get more -information, and you pay less CPU time. It's not a trade-off, it's a -trade-up. - -To be specific: - - bugs removed: local stack frame is no longer molested, execution time - is now charged to correct functions, .... - - accuracy increased: profiler execution time is no longer charged to - user's code, calibration for platform is supported, file reads - are not done *by* profiler *during* profiling (and charged to - user's code!), ... - - speed increased: Overhead CPU cost was reduced by more than a factor of - two (perhaps a factor of five), lightweight profiler module is - all that must be loaded, and the report generating module - (pstats) is not needed during profiling. - - recursive functions support: cumulative times in recursive functions - are correctly calculated; recursive entries are counted; ... - - large growth in report generating UI: distinct profiles runs can be added - together forming a comprehensive report; functions that import - statistics take arbitrary lists of files; sorting criteria is now - based on keywords (instead of 4 integer options); reports shows - what functions were profiled as well as what profile file was - referenced; output format has been improved, ... - - -INSTANT USERS MANUAL - -This section is provided for users that "don't want to read the -manual." It provides a very brief overview, and allows a user to -rapidly perform profiling on an existing application. - -To profile an application with a main entry point of "foo()", you -would add the following to your module: - - import profile - profile.run("foo()") - -The above action would cause "foo()" to be run, and a series of -informative lines (the profile) to be printed. The above approach is -most useful when working with the interpreter. If you would like to -save the results of a profile into a file for later examination, you -can supply a file name as the second argument to the run() function: - - import profile - profile.run("foo()", 'fooprof') - -When you wish to review the profile, you should use the methods in the -pstats module. Typically you would load the statistics data as -follows: - - import pstats - p = pstats.Stats('fooprof') - -The class "Stats" (the above code just created an instance of this -class) has a variety of methods for manipulating and printing the data -that was just read into "p". When you ran profile.run() above, what -was printed was the result of three method calls: - - p.strip_dirs().sort_stats(-1).print_stats() - -The first method removed the extraneous path from all the module -names. The second method sorted all the entries according to the -standard module/line/name string that is printed (this is to comply -with the semantics of the old profiler). The third method printed out -all the statistics. You might try the following sort calls: - - p.sort_stats('name') - p.print_stats() - -The first call will actually sort the list by function name, and the -second call will print out the statistics. The following are some -interesting calls to experiment with: - - p.sort_stats('cumulative').print_stats(10) - -This sorts the profile by cumulative time in a function, and then only -prints the ten most significant lines. If you want to understand what -algorithms are taking time, the above line is what you would use. - -If you were looking to see what functions were looping a lot, and -taking a lot of time, you would do: - - p.sort_stats('time').print_stats(10) - -to sort according to time spent within each function, and then print -the statistics for the top ten functions. - -You might also try: - - p.sort_stats('file').print_stats('__init__') - -This will sort all the statistics by file name, and then print out -statistics for only the class init methods ('cause they are spelled -with "__init__" in them). As one final example, you could try: - - p.sort_stats('time', 'cum').print_stats(.5, 'init') - -This line sorts stats with a primary key of time, and a secondary key -of cumulative time, and then prints out some of the statistics. To be -specific, the list is first culled down to 50% (re: .5) of its -original size, then only lines containing "init" are maintained, and -that sub-sub-list is printed. - -If you wondered what functions called the above functions, you could -now (p is still sorted according to the last criteria) do: - - p.print_callers(.5, 'init') - -and you would get a list of callers for each of the listed functions. - -If you want more functionality, you're going to have to read the -manual (or guess) what the following functions do: - - p.print_callees() - p.add('fooprof') - - -WHAT IS DETERMINISTIC PROFILING? - -"Deterministic profiling" is meant to reflect the fact that all -"function call", "function return", and "exception" events are -monitored, and precise timings are made for the intervals between -these events (during which time the user's code is executing). In -contrast, "statistical profiling" (which is not done by this module) -randomly samples the effective instruction pointer, and deduces where -time is being spent. The latter technique traditionally involves less -overhead (as the code does not need to be instrumented), but provides -only relative indications of where time is being spent. - -In Python, since there is an interpreter active during execution, the -presence of instrumented code is not required to do deterministic -profiling. Python automatically provides a hook (optional callback) -for each event. In addition, the interpreted nature of Python tends -to add so much overhead to execution, that deterministic profiling -tends to only add small processing overhead, in typical applications. -The result is that deterministic profiling is not that expensive, but -yet provides extensive run time statistics about the execution of a -Python program. - -Call count statistics can be used to identify bugs in code (surprising -counts), and to identify possible inline-expansion points (high call -counts). Internal time statistics can be used to identify hot loops -that should be carefully optimized. Cumulative time statistics should -be used to identify high level errors in the selection of algorithms. -Note that the unusual handling of cumulative times in this profiler -allows statistics for recursive implementations of algorithms to be -directly compared to iterative implementations. - - -REFERENCE MANUAL - -The primary entry point for the profiler is the global function -profile.run(). It is typically used to create any profile -information. The reports are formatted and printed using methods for -the class pstats.Stats. The following is a description of all of -these standard entry points and functions. For a more in-depth view -of some of the code, consider reading the later section on "Profiler -Extensions," which includes discussion of how to derive "better" -profilers from the classes presented, or reading the source code for -these modules. - - -FUNCTION profile.run(string, filename_opt) - -This function takes a single argument that has can be passed to the -"exec" statement, and an optional file name. In all cases this -routine attempts to "exec" its first argument, and gather profiling -statistics from the execution. If no file name is present, then this -function automatically prints a simple profiling report, sorted by the -standard name string (file/line/function-name) that is presented in -each line. The following is a typical output from such a call: - -cut here---- - - main() - 2706 function calls (2004 primitive calls) in 4.504 CPU seconds - - Ordered by: standard name - - ncalls tottime percall cumtime percall filename:lineno(function) - 2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects) - 43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate) - ... - -cut here---- - -The first line indicates that this profile was generated by the call: -profile.run('main()'), and hence the exec'ed string is 'main()'. The -second line indicates that 2706 calls were monitored. Of those calls, -2004 were "primitive." We define "primitive" to mean that the call -was not induced via recursion. The next line: "Ordered by: standard -name", indicates that the text string in the far right column was used -to sort the output. The column headings include: - - "ncalls" for the number of calls, - "tottime" for the total time spent in the given function - (and excluding time made in calls to sub-functions), - "percall" is the quotient of "tottime" divided by "ncalls" - "cumtime" is the total time spent in this and all subfunctions - (i.e., from invocation till exit). This figure is - accurate *even* for recursive functions. - "percall" is the quotient of "cumtime" divided by primitive - calls - "filename:lineno(function)" provides the respective data of - each function - -When there are two numbers in the first column (e.g.: 43/3), then the -latter is the number of primitive calls, and the former is the actual -number of calls. Note that when the function does not recurse, these -two values are the same, and only the single figure is printed. - - -CLASS Stats(filename, ...) - -This class constructor creates an instance of a statistics object from -a filename (or set of filenames). Stats objects are manipulated by -methods, in order to print useful reports. - -The file selected by the above constructor must have been created by -the corresponding version of profile. To be specific, there is *NO* -file compatibility guaranteed with future versions of this profiler, -and there is no compatibility with files produced by other profilers -(e.g., the standard system profiler). - -If several files are provided, all the statistics for identical -functions will be coalesced, so that an overall view of several -processes can be considered in a single report. If additional files -need to be combined with data in an existing Stats object, the add() -method can be used. - - -METHOD strip_dirs() - -This method for the Stats class removes all leading path information -from file names. It is very useful in reducing the size of the -printout to fit within (close to) 80 columns. This method modifies -the object, and the striped information is lost. After performing a -strip operation, the object is considered to have its entries in a -"random" order, as it was just after object initialization and -loading. If strip_dir() causes two function names to be -indistinguishable (i.e., they are on the same line of the same -filename, and have the same function name), then the statistics for -these two entries are accumulated into a single entry. - - -METHOD add(filename, ...) - -This methods of the Stats class accumulates additional profiling -information into the current profiling object. Its arguments should -refer to filenames created my the corresponding version of -profile.run(). Statistics for identically named (re: file, line, -name) functions are automatically accumulated into single function -statistics. - - -METHOD sort_stats(key, ...) - -This method modifies the Stats object by sorting it according to the -supplied criteria. The argument is typically a string identifying the -basis of a sort (example: "time" or "name"). - -When more than one key is provided, then additional keys are used as -secondary criteria when the there is equality in all keys selected -before them. For example, sort_stats('name', 'file') will sort all -the entries according to their function name, and resolve all ties -(identical function names) by sorting by file name. - -Abbreviations can be used for any key names, as long as the -abbreviation is unambiguous. The following are the keys currently -defined: - - Valid Arg Meaning - "calls" call count - "cumulative" cumulative time - "file" file name - "module" file name - "pcalls" primitive call count - "line" line number - "name" function name - "nfl" name/file/line - "stdname" standard name - "time" internal time - -Note that all sorts on statistics are in descending order (placing most -time consuming items first), where as name, file, and line number -searches are in ascending order (i.e., alphabetical). The subtle -distinction between "nfl" and "stdname" is that the standard name is a -sort of the name as printed, which means that the embedded line -numbers get compared in an odd way. For example, lines 3, 20, and 40 -would (if the file names were the same) appear in the string order -"20" "3" and "40". In contrast, "nfl" does a numeric compare of the -line numbers. In fact, sort_stats("nfl") is the same as -sort_stats("name", "file", "line"). - -For compatibility with the standard profiler, the numeric argument -1, -0, 1, and 2 are permitted. They are interpreted as "stdname", -"calls", "time", and "cumulative" respectively. If this old style -format (numeric) is used, only one sort key (the numeric key) will be -used, and additionally arguments will be silently ignored. - - -METHOD reverse_order() - -This method for the Stats class reverses the ordering of the basic -list within the object. This method is provided primarily for -compatibility with the standard profiler. Its utility is questionable -now that ascending vs descending order is properly selected based on -the sort key of choice. - - -METHOD print_stats(restriction, ...) - -This method for the Stats class prints out a report as described in -the profile.run() definition. - -The order of the printing is based on the last sort_stats() operation -done on the object (subject to caveats in add() and strip_dirs()). - -The arguments provided (if any) can be used to limit the list down to -the significant entries. Initially, the list is taken to be the -complete set of profiled functions. Each restriction is either an -integer (to select a count of lines), or a decimal fraction between -0.0 and 1.0 inclusive (to select a percentage of lines), or a regular -expression (to pattern match the standard name that is printed). If -several restrictions are provided, then they are applied sequentially. -For example: - - print_stats(.1, "foo:") - -would first limit the printing to first 10% of list, and then only -print functions that were part of filename ".*foo:". In contrast, the -command: - - print_stats("foo:", .1) - -would limit the list to all functions having file names ".*foo:", and -then proceed to only print the first 10% of them. - - -METHOD print_callers(restrictions, ...) - -This method for the Stats class prints a list of all functions that -called each function in the profiled database. The ordering is -identical to that provided by print_stats(), and the definition of the -restricting argument is also identical. For convenience, a number is -shown in parentheses after each caller to show how many times this -specific call was made. A second non-parenthesized number is the -cumulative time spent in the function at the right. - - -METHOD print_callees(restrictions, ...) - -This method for the Stats class prints a list of all function that -were called by the indicated function. Aside from this reversal of -direction of calls (re: called vs was called by), the arguments and -ordering are identical to the print_callers() method. - - -METHOD ignore() - -This method of the Stats class is used to dispose of the value -returned by earlier methods. All standard methods in this class -return the instance that is being processed, so that the commands can -be strung together. For example: - -pstats.Stats('foofile').strip_dirs().sort_stats('cum').print_stats().ignore() - -would perform all the indicated functions, but it would not return -the final reference to the Stats instance. - - - - -LIMITATIONS - -There are two fundamental limitations on this profiler. The first is -that it relies on the Python interpreter to dispatch "call", "return", -and "exception" events. Compiled C code does not get interpreted, -and hence is "invisible" to the profiler. All time spent in C code -(including builtin functions) will be charged to the Python function -that was invoked the C code. IF the C code calls out to some native -Python code, then those calls will be profiled properly. - -The second limitation has to do with accuracy of timing information. -There is a fundamental problem with deterministic profilers involving -accuracy. The most obvious restriction is that the underlying "clock" -is only ticking at a rate (typically) of about .001 seconds. Hence no -measurements will be more accurate that that underlying clock. If -enough measurements are taken, then the "error" will tend to average -out. Unfortunately, removing this first error induces a second source -of error... - -The second problem is that it "takes a while" from when an event is -dispatched until the profiler's call to get the time actually *gets* -the state of the clock. Similarly, there is a certain lag when -exiting the profiler event handler from the time that the clock's -value was obtained (and then squirreled away), until the user's code -is once again executing. As a result, functions that are called many -times, or call many functions, will typically accumulate this error. -The error that accumulates in this fashion is typically less than the -accuracy of the clock (i.e., less than one clock tick), but it *can* -accumulate and become very significant. This profiler provides a -means of calibrating itself for a give platform so that this error can -be probabilistically (i.e., on the average) removed. After the -profiler is calibrated, it will be more accurate (in a least square -sense), but it will sometimes produce negative numbers (when call -counts are exceptionally low, and the gods of probability work against -you :-). ) Do *NOT* be alarmed by negative numbers in the profile. -They should *only* appear if you have calibrated your profiler, and -the results are actually better than without calibration. - - -CALIBRATION - -The profiler class has a hard coded constant that is added to each -event handling time to compensate for the overhead of calling the time -function, and socking away the results. The following procedure can -be used to obtain this constant for a given platform (see discussion -in LIMITATIONS above). - - import profile - pr = profile.Profile() - pr.calibrate(100) - pr.calibrate(100) - pr.calibrate(100) - -The argument to calibrate() is the number of times to try to do the -sample calls to get the CPU times. If your computer is *very* fast, -you might have to do: - - pr.calibrate(1000) - -or even: - - pr.calibrate(10000) - -The object of this exercise is to get a fairly consistent result. -When you have a consistent answer, you are ready to use that number in -the source code. For a Sun Sparcstation 1000 running Solaris 2.3, the -magical number is about .00053. If you have a choice, you are better -off with a smaller constant, and your results will "less often" show -up as negative in profile statistics. - -The following shows how the trace_dispatch() method in the Profile -class should be modified to install the calibration constant on a Sun -Sparcstation 1000: - - def trace_dispatch(self, frame, event, arg): - t = self.timer() - t = t[0] + t[1] - self.t - .00053 # Calibration constant - - if self.dispatch[event](frame,t): - t = self.timer() - self.t = t[0] + t[1] - else: - r = self.timer() - self.t = r[0] + r[1] - t # put back unrecorded delta - return - -Note that if there is no calibration constant, then the line -containing the callibration constant should simply say: - - t = t[0] + t[1] - self.t # no calibration constant - -You can also achieve the same results using a derived class (and the -profiler will actually run equally fast!!), but the above method is -the simplest to use. I could have made the profiler "self -calibrating", but it would have made the initialization of the -profiler class slower, and would have required some *very* fancy -coding, or else the use of a variable where the constant .00053 was -placed in the code shown. This is a ****VERY**** critical performance -section, and there is no reason to use a variable lookup at this -point, when a constant can be used. - - -EXTENSIONS: Deriving Better Profilers - -The Profile class of profile was written so that derived classes -could be developed to extend the profiler. Rather than describing all -the details of such an effort, I'll just present the following two -examples of derived classes that can be used to do profiling. If the -reader is an avid Python programmer, then it should be possible to use -these as a model and create similar (and perchance better) profile -classes. - -If all you want to do is change how the timer is called, or which -timer function is used, then the basic class has an option for that in -the constructor for the class. Consider passing the name of a -function to call into the constructor: - - pr = profile.Profile(your_time_func) - -The resulting profiler will call your time function instead of -os.times(). The function should return either a single number, or a -list of numbers (like what os.times() returns). If the function -returns a single time number, or the list of returned numbers has -length 2, then you will get an especially fast version of the dispatch -routine. - -Be warned that you *should* calibrate the profiler class for the -timer function that you choose. For most machines, a timer that -returns a lone integer value will provide the best results in terms of -low overhead during profiling. (os.times is *pretty* bad, 'cause it -returns a tuple of floating point values, so all arithmetic is -floating point in the profiler!). If you want to be substitute a -better timer in the cleanest fashion, you should derive a class, and -simply put in the replacement dispatch method that better handles your timer -call, along with the appropriate calibration constant :-). - - -cut here------------------------------------------------------------------ -#**************************************************************************** -# OldProfile class documentation -#**************************************************************************** -# -# The following derived profiler simulates the old style profile, providing -# errant results on recursive functions. The reason for the usefulness of this -# profiler is that it runs faster (i.e., less overhead) than the old -# profiler. It still creates all the caller stats, and is quite -# useful when there is *no* recursion in the user's code. It is also -# a lot more accurate than the old profiler, as it does not charge all -# its overhead time to the user's code. -#**************************************************************************** -class OldProfile(Profile): - def trace_dispatch_exception(self, frame, t): - rt, rtt, rct, rfn, rframe, rcur = self.cur - if rcur and not rframe is frame: - return self.trace_dispatch_return(rframe, t) - return 0 - - def trace_dispatch_call(self, frame, t): - fn = `frame.f_code` - - self.cur = (t, 0, 0, fn, frame, self.cur) - if self.timings.has_key(fn): - tt, ct, callers = self.timings[fn] - self.timings[fn] = tt, ct, callers - else: - self.timings[fn] = 0, 0, {} - return 1 - - def trace_dispatch_return(self, frame, t): - rt, rtt, rct, rfn, frame, rcur = self.cur - rtt = rtt + t - sft = rtt + rct - - pt, ptt, pct, pfn, pframe, pcur = rcur - self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur - - tt, ct, callers = self.timings[rfn] - if callers.has_key(pfn): - callers[pfn] = callers[pfn] + 1 - else: - callers[pfn] = 1 - self.timings[rfn] = tt+rtt, ct + sft, callers - - return 1 - - - def snapshot_stats(self): - self.stats = {} - for func in self.timings.keys(): - tt, ct, callers = self.timings[func] - nor_func = self.func_normalize(func) - nor_callers = {} - nc = 0 - for func_caller in callers.keys(): - nor_callers[self.func_normalize(func_caller)]=\ - callers[func_caller] - nc = nc + callers[func_caller] - self.stats[nor_func] = nc, nc, tt, ct, nor_callers - - - -#**************************************************************************** -# HotProfile class documentation -#**************************************************************************** -# -# This profiler is the fastest derived profile example. It does not -# calculate caller-callee relationships, and does not calculate cumulative -# time under a function. It only calculates time spent in a function, so -# it runs very quickly (re: very low overhead). In truth, the basic -# profiler is so fast, that is probably not worth the savings to give -# up the data, but this class still provides a nice example. -#**************************************************************************** -class HotProfile(Profile): - def trace_dispatch_exception(self, frame, t): - rt, rtt, rfn, rframe, rcur = self.cur - if rcur and not rframe is frame: - return self.trace_dispatch_return(rframe, t) - return 0 - - def trace_dispatch_call(self, frame, t): - self.cur = (t, 0, frame, self.cur) - return 1 - - def trace_dispatch_return(self, frame, t): - rt, rtt, frame, rcur = self.cur - - rfn = `frame.f_code` - - pt, ptt, pframe, pcur = rcur - self.cur = pt, ptt+rt, pframe, pcur - - if self.timings.has_key(rfn): - nc, tt = self.timings[rfn] - self.timings[rfn] = nc + 1, rt + rtt + tt - else: - self.timings[rfn] = 1, rt + rtt - - return 1 - - - def snapshot_stats(self): - self.stats = {} - for func in self.timings.keys(): - nc, tt = self.timings[func] - nor_func = self.func_normalize(func) - self.stats[nor_func] = nc, nc, tt, 0, {} - - - -cut here------------------------------------------------------------------ diff --git a/Lib/profile.py b/Lib/profile.py deleted file mode 100755 index 7f4abed60c..0000000000 --- a/Lib/profile.py +++ /dev/null @@ -1,614 +0,0 @@ -# -# Class for profiling python code. rev 1.0 6/2/94 -# -# Based on prior profile module by Sjoerd Mullender... -# which was hacked somewhat by: Guido van Rossum -# -# See profile.doc for more information - - -# Copyright 1994, by InfoSeek Corporation, all rights reserved. -# Written by James Roskind -# -# Permission to use, copy, modify, and distribute this Python software -# and its associated documentation for any purpose (subject to the -# restriction in the following sentence) without fee is hereby granted, -# provided that the above copyright notice appears in all copies, and -# that both that copyright notice and this permission notice appear in -# supporting documentation, and that the name of InfoSeek not be used in -# advertising or publicity pertaining to distribution of the software -# without specific, written prior permission. This permission is -# explicitly restricted to the copying and modification of the software -# to remain in Python, compiled Python, or other languages (such as C) -# wherein the modified or derived code is exclusively imported into a -# Python module. -# -# INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS -# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -# FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION 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 -import os -import time -import string -import marshal - - -# Global variables -func_norm_dict = {} -func_norm_counter = 0 -if hasattr(os, 'getpid'): - pid_string = `os.getpid()` -else: - pid_string = '' - - -# Sample timer for use with -#i_count = 0 -#def integer_timer(): -# global i_count -# i_count = i_count + 1 -# return i_count -#itimes = integer_timer # replace with C coded timer returning integers - -#************************************************************************** -# The following are the static member functions for the profiler class -# Note that an instance of Profile() is *not* needed to call them. -#************************************************************************** - - -# simplified user interface -def run(statement, *args): - prof = Profile() - try: - prof = prof.run(statement) - except SystemExit: - pass - if args: - prof.dump_stats(args[0]) - else: - return prof.print_stats() - -# print help -def help(): - for dirname in sys.path: - fullname = os.path.join(dirname, 'profile.doc') - if os.path.exists(fullname): - sts = os.system('${PAGER-more} '+fullname) - if sts: print '*** Pager exit status:', sts - break - else: - print 'Sorry, can\'t find the help file "profile.doc"', - print 'along the Python search path' - - -#************************************************************************** -# class Profile documentation: -#************************************************************************** -# self.cur is always a tuple. Each such tuple corresponds to a stack -# frame that is currently active (self.cur[-2]). The following are the -# definitions of its members. We use this external "parallel stack" to -# avoid contaminating the program that we are profiling. (old profiler -# used to write into the frames local dictionary!!) Derived classes -# can change the definition of some entries, as long as they leave -# [-2:] intact. -# -# [ 0] = Time that needs to be charged to the parent frame's function. It is -# used so that a function call will not have to access the timing data -# for the parents frame. -# [ 1] = Total time spent in this frame's function, excluding time in -# subfunctions -# [ 2] = Cumulative time spent in this frame's function, including time in -# all subfunctions to this frame. -# [-3] = Name of the function that corresonds to this frame. -# [-2] = Actual frame that we correspond to (used to sync exception handling) -# [-1] = Our parent 6-tuple (corresonds to frame.f_back) -#************************************************************************** -# Timing data for each function is stored as a 5-tuple in the dictionary -# self.timings[]. The index is always the name stored in self.cur[4]. -# The following are the definitions of the members: -# -# [0] = The number of times this function was called, not counting direct -# or indirect recursion, -# [1] = Number of times this function appears on the stack, minus one -# [2] = Total time spent internal to this function -# [3] = Cumulative time that this function was present on the stack. In -# non-recursive functions, this is the total execution time from start -# to finish of each invocation of a function, including time spent in -# all subfunctions. -# [5] = A dictionary indicating for each function name, the number of times -# it was called by us. -#************************************************************************** -# We produce function names via a repr() call on the f_code object during -# profiling. This save a *lot* of CPU time. This results in a string that -# always looks like: -# <code object main at 87090, file "/a/lib/python-local/myfib.py", line 76> -# After we "normalize it, it is a tuple of filename, line, function-name. -# We wait till we are done profiling to do the normalization. -# *IF* this repr format changes, then only the normalization routine should -# need to be fixed. -#************************************************************************** -class Profile: - - def __init__(self, timer=None): - self.timings = {} - self.cur = None - self.cmd = "" - - self.dispatch = { \ - 'call' : self.trace_dispatch_call, \ - 'return' : self.trace_dispatch_return, \ - 'exception': self.trace_dispatch_exception, \ - } - - if not timer: - if hasattr(os, 'times'): - self.timer = os.times - self.dispatcher = self.trace_dispatch - else: - self.timer = time.time - self.dispatcher = self.trace_dispatch_i - else: - self.timer = timer - t = self.timer() # test out timer function - try: - if len(t) == 2: - self.dispatcher = self.trace_dispatch - else: - self.dispatcher = self.trace_dispatch_l - except TypeError: - self.dispatcher = self.trace_dispatch_i - self.t = self.get_time() - self.simulate_call('profiler') - - - def get_time(self): # slow simulation of method to acquire time - t = self.timer() - if type(t) == type(()) or type(t) == type([]): - t = reduce(lambda x,y: x+y, t, 0) - return t - - - # Heavily optimized dispatch routine for os.times() timer - - def trace_dispatch(self, frame, event, arg): - t = self.timer() - t = t[0] + t[1] - self.t # No Calibration constant - # t = t[0] + t[1] - self.t - .00053 # Calibration constant - - if self.dispatch[event](frame,t): - t = self.timer() - self.t = t[0] + t[1] - else: - r = self.timer() - self.t = r[0] + r[1] - t # put back unrecorded delta - return - - - - # Dispatch routine for best timer program (return = scalar integer) - - def trace_dispatch_i(self, frame, event, arg): - t = self.timer() - self.t # - 1 # Integer calibration constant - if self.dispatch[event](frame,t): - self.t = self.timer() - else: - self.t = self.timer() - t # put back unrecorded delta - return - - - # SLOW generic dispatch rountine for timer returning lists of numbers - - def trace_dispatch_l(self, frame, event, arg): - t = self.get_time() - self.t - - if self.dispatch[event](frame,t): - self.t = self.get_time() - else: - self.t = self.get_time()-t # put back unrecorded delta - return - - - def trace_dispatch_exception(self, frame, t): - rt, rtt, rct, rfn, rframe, rcur = self.cur - if (not rframe is frame) and rcur: - return self.trace_dispatch_return(rframe, t) - return 0 - - - def trace_dispatch_call(self, frame, t): - fn = `frame.f_code` - - # The following should be about the best approach, but - # we would need a function that maps from id() back to - # the actual code object. - # fn = id(frame.f_code) - # Note we would really use our own function, which would - # return the code address, *and* bump the ref count. We - # would then fix up the normalize function to do the - # actualy repr(fn) call. - - # The following is an interesting alternative - # It doesn't do as good a job, and it doesn't run as - # fast 'cause repr() is written in C, and this is Python. - #fcode = frame.f_code - #code = fcode.co_code - #if ord(code[0]) == 127: # == SET_LINENO - # # see "opcode.h" in the Python source - # fn = (fcode.co_filename, ord(code[1]) | \ - # ord(code[2]) << 8, fcode.co_name) - #else: - # fn = (fcode.co_filename, 0, fcode.co_name) - - self.cur = (t, 0, 0, fn, frame, self.cur) - if self.timings.has_key(fn): - cc, ns, tt, ct, callers = self.timings[fn] - self.timings[fn] = cc, ns + 1, tt, ct, callers - else: - self.timings[fn] = 0, 0, 0, 0, {} - return 1 - - def trace_dispatch_return(self, frame, t): - # if not frame is self.cur[-2]: raise "Bad return", self.cur[3] - - # Prefix "r" means part of the Returning or exiting frame - # Prefix "p" means part of the Previous or older frame - - rt, rtt, rct, rfn, frame, rcur = self.cur - rtt = rtt + t - sft = rtt + rct - - pt, ptt, pct, pfn, pframe, pcur = rcur - self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur - - cc, ns, tt, ct, callers = self.timings[rfn] - if not ns: - ct = ct + sft - cc = cc + 1 - if callers.has_key(pfn): - callers[pfn] = callers[pfn] + 1 # hack: gather more - # stats such as the amount of time added to ct courtesy - # of this specific call, and the contribution to cc - # courtesy of this call. - else: - callers[pfn] = 1 - self.timings[rfn] = cc, ns - 1, tt+rtt, ct, callers - - return 1 - - # The next few function play with self.cmd. By carefully preloading - # our paralell stack, we can force the profiled result to include - # an arbitrary string as the name of the calling function. - # We use self.cmd as that string, and the resulting stats look - # very nice :-). - - def set_cmd(self, cmd): - if self.cur[-1]: return # already set - self.cmd = cmd - self.simulate_call(cmd) - - class fake_code: - def __init__(self, filename, line, name): - self.co_filename = filename - self.co_line = line - self.co_name = name - self.co_code = '\0' # anything but 127 - - def __repr__(self): - return (self.co_filename, self.co_line, self.co_name) - - class fake_frame: - def __init__(self, code, prior): - self.f_code = code - self.f_back = prior - - def simulate_call(self, name): - code = self.fake_code('profile', 0, name) - if self.cur: - pframe = self.cur[-2] - else: - pframe = None - frame = self.fake_frame(code, pframe) - a = self.dispatch['call'](frame, 0) - return - - # collect stats from pending stack, including getting final - # timings for self.cmd frame. - - def simulate_cmd_complete(self): - t = self.get_time() - self.t - while self.cur[-1]: - # We *can* cause assertion errors here if - # dispatch_trace_return checks for a frame match! - a = self.dispatch['return'](self.cur[-2], t) - t = 0 - self.t = self.get_time() - t - - - def print_stats(self): - import pstats - pstats.Stats(self).strip_dirs().sort_stats(-1). \ - print_stats() - - def dump_stats(self, file): - f = open(file, 'w') - self.create_stats() - marshal.dump(self.stats, f) - f.close() - - def create_stats(self): - self.simulate_cmd_complete() - self.snapshot_stats() - - def snapshot_stats(self): - self.stats = {} - for func in self.timings.keys(): - cc, ns, tt, ct, callers = self.timings[func] - nor_func = self.func_normalize(func) - nor_callers = {} - nc = 0 - for func_caller in callers.keys(): - nor_callers[self.func_normalize(func_caller)]=\ - callers[func_caller] - nc = nc + callers[func_caller] - self.stats[nor_func] = cc, nc, tt, ct, nor_callers - - - # Override the following function if you can figure out - # a better name for the binary f_code entries. I just normalize - # them sequentially in a dictionary. It would be nice if we could - # *really* see the name of the underlying C code :-). Sometimes - # you can figure out what-is-what by looking at caller and callee - # lists (and knowing what your python code does). - - def func_normalize(self, func_name): - global func_norm_dict - global func_norm_counter - global func_sequence_num - - if func_norm_dict.has_key(func_name): - return func_norm_dict[func_name] - if type(func_name) == type(""): - long_name = string.split(func_name) - file_name = long_name[-3][1:-2] - func = long_name[2] - lineno = long_name[-1][:-1] - if '?' == func: # Until I find out how to may 'em... - file_name = 'python' - func_norm_counter = func_norm_counter + 1 - func = pid_string + ".C." + `func_norm_counter` - result = file_name , string.atoi(lineno) , func - else: - result = func_name - func_norm_dict[func_name] = result - return result - - - # The following two methods can be called by clients to use - # a profiler to profile a statement, given as a string. - - def run(self, cmd): - import __main__ - dict = __main__.__dict__ - return self.runctx(cmd, dict, dict) - - def runctx(self, cmd, globals, locals): - self.set_cmd(cmd) - sys.setprofile(self.dispatcher) - try: - exec cmd in globals, locals - finally: - sys.setprofile(None) - return self - - # This method is more useful to profile a single function call. - def runcall(self, func, *args): - self.set_cmd(`func`) - sys.setprofile(self.dispatcher) - try: - return apply(func, args) - finally: - sys.setprofile(None) - - - #****************************************************************** - # The following calculates the overhead for using a profiler. The - # problem is that it takes a fair amount of time for the profiler - # to stop the stopwatch (from the time it recieves an event). - # Similarly, there is a delay from the time that the profiler - # re-starts the stopwatch before the user's code really gets to - # continue. The following code tries to measure the difference on - # a per-event basis. The result can the be placed in the - # Profile.dispatch_event() routine for the given platform. Note - # that this difference is only significant if there are a lot of - # events, and relatively little user code per event. For example, - # code with small functions will typically benefit from having the - # profiler calibrated for the current platform. This *could* be - # done on the fly during init() time, but it is not worth the - # effort. Also note that if too large a value specified, then - # execution time on some functions will actually appear as a - # negative number. It is *normal* for some functions (with very - # low call counts) to have such negative stats, even if the - # calibration figure is "correct." - # - # One alternative to profile-time calibration adjustments (i.e., - # adding in the magic little delta during each event) is to track - # more carefully the number of events (and cumulatively, the number - # of events during sub functions) that are seen. If this were - # done, then the arithmetic could be done after the fact (i.e., at - # display time). Currintly, we track only call/return events. - # These values can be deduced by examining the callees and callers - # vectors for each functions. Hence we *can* almost correct the - # internal time figure at print time (note that we currently don't - # track exception event processing counts). Unfortunately, there - # is currently no similar information for cumulative sub-function - # time. It would not be hard to "get all this info" at profiler - # time. Specifically, we would have to extend the tuples to keep - # counts of this in each frame, and then extend the defs of timing - # tuples to include the significant two figures. I'm a bit fearful - # that this additional feature will slow the heavily optimized - # event/time ratio (i.e., the profiler would run slower, fur a very - # low "value added" feature.) - # - # Plugging in the calibration constant doesn't slow down the - # profiler very much, and the accuracy goes way up. - #************************************************************** - - def calibrate(self, m): - n = m - s = self.timer() - while n: - self.simple() - n = n - 1 - f = self.timer() - my_simple = f[0]+f[1]-s[0]-s[1] - #print "Simple =", my_simple, - - n = m - s = self.timer() - while n: - self.instrumented() - n = n - 1 - f = self.timer() - my_inst = f[0]+f[1]-s[0]-s[1] - # print "Instrumented =", my_inst - avg_cost = (my_inst - my_simple)/m - #print "Delta/call =", avg_cost, "(profiler fixup constant)" - return avg_cost - - # simulate a program with no profiler activity - def simple(self): - a = 1 - pass - - # simulate a program with call/return event processing - def instrumented(self): - a = 1 - self.profiler_simulation(a, a, a) - - # simulate an event processing activity (from user's perspective) - def profiler_simulation(self, x, y, z): - t = self.timer() - t = t[0] + t[1] - self.ut = t - - - -#**************************************************************************** -# OldProfile class documentation -#**************************************************************************** -# -# The following derived profiler simulates the old style profile, providing -# errant results on recursive functions. The reason for the usefulnes of this -# profiler is that it runs faster (i.e., less overhead). It still creates -# all the caller stats, and is quite useful when there is *no* recursion -# in the user's code. -# -# This code also shows how easy it is to create a modified profiler. -#**************************************************************************** -class OldProfile(Profile): - def trace_dispatch_exception(self, frame, t): - rt, rtt, rct, rfn, rframe, rcur = self.cur - if rcur and not rframe is frame: - return self.trace_dispatch_return(rframe, t) - return 0 - - def trace_dispatch_call(self, frame, t): - fn = `frame.f_code` - - self.cur = (t, 0, 0, fn, frame, self.cur) - if self.timings.has_key(fn): - tt, ct, callers = self.timings[fn] - self.timings[fn] = tt, ct, callers - else: - self.timings[fn] = 0, 0, {} - return 1 - - def trace_dispatch_return(self, frame, t): - rt, rtt, rct, rfn, frame, rcur = self.cur - rtt = rtt + t - sft = rtt + rct - - pt, ptt, pct, pfn, pframe, pcur = rcur - self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur - - tt, ct, callers = self.timings[rfn] - if callers.has_key(pfn): - callers[pfn] = callers[pfn] + 1 - else: - callers[pfn] = 1 - self.timings[rfn] = tt+rtt, ct + sft, callers - - return 1 - - - def snapshot_stats(self): - self.stats = {} - for func in self.timings.keys(): - tt, ct, callers = self.timings[func] - nor_func = self.func_normalize(func) - nor_callers = {} - nc = 0 - for func_caller in callers.keys(): - nor_callers[self.func_normalize(func_caller)]=\ - callers[func_caller] - nc = nc + callers[func_caller] - self.stats[nor_func] = nc, nc, tt, ct, nor_callers - - - -#**************************************************************************** -# HotProfile class documentation -#**************************************************************************** -# -# This profiler is the fastest derived profile example. It does not -# calculate caller-callee relationships, and does not calculate cumulative -# time under a function. It only calculates time spent in a function, so -# it runs very quickly (re: very low overhead) -#**************************************************************************** -class HotProfile(Profile): - def trace_dispatch_exception(self, frame, t): - rt, rtt, rfn, rframe, rcur = self.cur - if rcur and not rframe is frame: - return self.trace_dispatch_return(rframe, t) - return 0 - - def trace_dispatch_call(self, frame, t): - self.cur = (t, 0, frame, self.cur) - return 1 - - def trace_dispatch_return(self, frame, t): - rt, rtt, frame, rcur = self.cur - - rfn = `frame.f_code` - - pt, ptt, pframe, pcur = rcur - self.cur = pt, ptt+rt, pframe, pcur - - if self.timings.has_key(rfn): - nc, tt = self.timings[rfn] - self.timings[rfn] = nc + 1, rt + rtt + tt - else: - self.timings[rfn] = 1, rt + rtt - - return 1 - - - def snapshot_stats(self): - self.stats = {} - for func in self.timings.keys(): - nc, tt = self.timings[func] - nor_func = self.func_normalize(func) - self.stats[nor_func] = nc, nc, tt, 0, {} - - - -#**************************************************************************** -def Stats(*args): - print 'Report generating functions are in the "pstats" module\a' diff --git a/Lib/pstats.py b/Lib/pstats.py deleted file mode 100644 index e87478ea7d..0000000000 --- a/Lib/pstats.py +++ /dev/null @@ -1,532 +0,0 @@ -# -# Class for printing reports on profiled python code. rev 1.0 4/1/94 -# -# Based on prior profile module by Sjoerd Mullender... -# which was hacked somewhat by: Guido van Rossum -# -# see jprofile.doc and jprofile.py for more info. - -# Copyright 1994, by InfoSeek Corporation, all rights reserved. -# Written by James Roskind -# -# Permission to use, copy, modify, and distribute this Python software -# and its associated documentation for any purpose (subject to the -# restriction in the following sentence) without fee is hereby granted, -# provided that the above copyright notice appears in all copies, and -# that both that copyright notice and this permission notice appear in -# supporting documentation, and that the name of InfoSeek not be used in -# advertising or publicity pertaining to distribution of the software -# without specific, written prior permission. This permission is -# explicitly restricted to the copying and modification of the software -# to remain in Python, compiled Python, or other languages (such as C) -# wherein the modified or derived code is exclusively imported into a -# Python module. -# -# INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS -# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -# FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION 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 os -import time -import string -import marshal -import regex - -#************************************************************************** -# Class Stats documentation -#************************************************************************** -# This class is used for creating reports from data generated by the -# Profile class. It is a "friend" of that class, and imports data either -# by direct access to members of Profile class, or by reading in a dictionary -# that was emitted (via marshal) from the Profile class. -# -# The big change from the previous Profiler (in terms of raw functionality) -# is that an "add()" method has been provided to combine Stats from -# several distinct profile runs. Both the constructor and the add() -# method now take arbitrarilly many file names as arguments. -# -# All the print methods now take an argument that indicats how many lines -# to print. If the arg is a floating point number between 0 and 1.0, then -# it is taken as a decimal percentage of the availabel lines to be printed -# (e.g., .1 means print 10% of all available lines). If it is an integer, -# it is taken to mean the number of lines of data that you wish to have -# printed. -# -# The sort_stats() method now processes some additionaly options (i.e., in -# addition to the old -1, 0, 1, or 2). It takes an arbitrary number of quoted -# strings to select the sort order. For example sort_stats('time', 'name') -# sorts on the major key of "internal function time", and on the minor -# key of 'the name of the function'. Look at the two tables in sort_stats() -# and get_sort_arg_defs(self) for more examples. -# -# All methods now return "self", so you can string together commands like: -# Stats('foo', 'goo').strip_dirs().sort_stats('calls').\ -# print_stats(5).print_callers(5) -# -#************************************************************************** -import fpformat - -class Stats: - def __init__(self, *args): - if not len(args): - arg = None - else: - arg = args[0] - args = args[1:] - self.init(arg) - apply(self.add, args).ignore() - - def init(self, arg): - self.all_callees = None # calc only if needed - self.files = [] - self.fcn_list = None - self.total_tt = 0 - self.total_calls = 0 - self.prim_calls = 0 - self.max_name_len = 0 - self.top_level = {} - self.stats = {} - self.sort_arg_dict = {} - self.load_stats(arg) - trouble = 1 - try: - self.get_top_level_stats() - trouble = 0 - finally: - if trouble: - print "Invalid timing data", - if self.files: print self.files[-1], - print - - - def load_stats(self, arg): - if not arg: self.stats = {} - elif type(arg) == type(""): - f = open(arg, 'r') - self.stats = marshal.load(f) - f.close() - try: - file_stats = os.stat(arg) - arg = time.ctime(file_stats[8]) + " " + arg - except: # in case this is not unix - pass - self.files = [ arg ] - elif hasattr(arg, 'create_stats'): - arg.create_stats() - self.stats = arg.stats - arg.stats = {} - if not self.stats: - raise TypeError, "Cannot create or construct a " \ - + `self.__class__` \ - + " object from '" + `arg` + "'" - return - - def get_top_level_stats(self): - for func in self.stats.keys(): - cc, nc, tt, ct, callers = self.stats[func] - self.total_calls = self.total_calls + nc - self.prim_calls = self.prim_calls + cc - self.total_tt = self.total_tt + tt - if callers.has_key(("jprofile", 0, "profiler")): - self.top_level[func] = None - if len(func_std_string(func)) > self.max_name_len: - self.max_name_len = len(func_std_string(func)) - - def add(self, *arg_list): - if not arg_list: return self - if len(arg_list) > 1: apply(self.add, arg_list[1:]) - other = arg_list[0] - if type(self) != type(other) or \ - self.__class__ != other.__class__: - other = Stats(other) - self.files = self.files + other.files - self.total_calls = self.total_calls + other.total_calls - self.prim_calls = self.prim_calls + other.prim_calls - self.total_tt = self.total_tt + other.total_tt - for func in other.top_level.keys(): - self.top_level[func] = None - - if self.max_name_len < other.max_name_len: - self.max_name_len = other.max_name_len - - self.fcn_list = None - - for func in other.stats.keys(): - if self.stats.has_key(func): - old_func_stat = self.stats[func] - else: - old_func_stat = (0, 0, 0, 0, {},) - self.stats[func] = add_func_stats(old_func_stat, \ - other.stats[func]) - return self - - - - # list the tuple indicies and directions for sorting, - # along with some printable description - sort_arg_dict_default = {\ - "calls" : (((1,-1), ), "call count"),\ - "cumulative": (((3,-1), ), "cumulative time"),\ - "file" : (((4, 1), ), "file name"),\ - "line" : (((5, 1), ), "line number"),\ - "module" : (((4, 1), ), "file name"),\ - "name" : (((6, 1), ), "function name"),\ - "nfl" : (((6, 1),(4, 1),(5, 1),), "name/file/line"), \ - "pcalls" : (((0,-1), ), "call count"),\ - "stdname" : (((7, 1), ), "standard name"),\ - "time" : (((2,-1), ), "internal time"),\ - } - - # Expand all abbreviations that are unique - def get_sort_arg_defs(self): - if not self.sort_arg_dict: - self.sort_arg_dict = dict = {} - std_list = dict.keys() - bad_list = {} - for word in self.sort_arg_dict_default.keys(): - fragment = word - while fragment: - if not fragment: - break - if dict.has_key(fragment): - bad_list[fragment] = 0 - break - dict[fragment] = self. \ - sort_arg_dict_default[word] - fragment = fragment[:-1] - for word in bad_list.keys(): - del dict[word] - return self.sort_arg_dict - - - def sort_stats(self, *field): - if not field: - self.fcn_list = 0 - return self - if len(field) == 1 and type(field[0]) == type(1): - # Be compatible with old profiler - field = [ {-1: "stdname", \ - 0:"calls", \ - 1:"time", \ - 2: "cumulative" } [ field[0] ] ] - - sort_arg_defs = self.get_sort_arg_defs() - sort_tuple = () - self.sort_type = "" - connector = "" - for word in field: - sort_tuple = sort_tuple + sort_arg_defs[word][0] - self.sort_type = self.sort_type + connector + \ - sort_arg_defs[word][1] - connector = ", " - - stats_list = [] - for func in self.stats.keys(): - cc, nc, tt, ct, callers = self.stats[func] - stats_list.append((cc, nc, tt, ct) + func_split(func) \ - + (func_std_string(func), func,) ) - - stats_list.sort(TupleComp(sort_tuple).compare) - - self.fcn_list = fcn_list = [] - for tuple in stats_list: - fcn_list.append(tuple[-1]) - return self - - - def reverse_order(self): - if self.fcn_list: self.fcn_list.reverse() - return self - - def strip_dirs(self): - oldstats = self.stats - self.stats = newstats = {} - max_name_len = 0 - for func in oldstats.keys(): - cc, nc, tt, ct, callers = oldstats[func] - newfunc = func_strip_path(func) - if len(func_std_string(newfunc)) > max_name_len: - max_name_len = len(func_std_string(newfunc)) - newcallers = {} - for func2 in callers.keys(): - newcallers[func_strip_path(func2)] = \ - callers[func2] - - if newstats.has_key(newfunc): - newstats[newfunc] = add_func_stats( \ - newstats[newfunc],\ - (cc, nc, tt, ct, newcallers)) - else: - newstats[newfunc] = (cc, nc, tt, ct, newcallers) - old_top = self.top_level - self.top_level = new_top = {} - for func in old_top.keys(): - new_top[func_strip_path(func)] = None - - self.max_name_len = max_name_len - - self.fcn_list = None - self.all_callees = None - return self - - - - def calc_callees(self): - if self.all_callees: return - self.all_callees = all_callees = {} - for func in self.stats.keys(): - if not all_callees.has_key(func): - all_callees[func] = {} - cc, nc, tt, ct, callers = self.stats[func] - for func2 in callers.keys(): - if not all_callees.has_key(func2): - all_callees[func2] = {} - all_callees[func2][func] = callers[func2] - return - - #****************************************************************** - # The following functions support actual printing of reports - #****************************************************************** - - # Optional "amount" is either a line count, or a percentage of lines. - - def eval_print_amount(self, sel, list, msg): - new_list = list - if type(sel) == type(""): - new_list = [] - for func in list: - if 0<=regex.search(sel, func_std_string(func)): - new_list.append(func) - else: - count = len(list) - if type(sel) == type(1.0) and 0.0 <= sel < 1.0: - count = int (count * sel + .5) - new_list = list[:count] - elif type(sel) == type(1) and 0 <= sel < count: - count = sel - new_list = list[:count] - if len(list) != len(new_list): - msg = msg + " List reduced from " + `len(list)` \ - + " to " + `len(new_list)` + \ - " due to restriction <" + `sel` + ">\n" - - return new_list, msg - - - - def get_print_list(self, sel_list): - width = self.max_name_len - if self.fcn_list: - list = self.fcn_list[:] - msg = " Ordered by: " + self.sort_type + '\n' - else: - list = self.stats.keys() - msg = " Random listing order was used\n" - - for selection in sel_list: - list,msg = self.eval_print_amount(selection, list, msg) - - count = len(list) - - if not list: - return 0, list - print msg - if count < len(self.stats): - width = 0 - for func in list: - if len(func_std_string(func)) > width: - width = len(func_std_string(func)) - return width+2, list - - def print_stats(self, *amount): - for filename in self.files: - print filename - if self.files: print - indent = " " - for func in self.top_level.keys(): - print indent, func_get_function_name(func) - - print indent, self.total_calls, "function calls", - if self.total_calls != self.prim_calls: - print "(" + `self.prim_calls`, "primitive calls)", - print "in", fpformat.fix(self.total_tt, 3), "CPU seconds" - print - width, list = self.get_print_list(amount) - if list: - self.print_title() - for func in list: - self.print_line(func) - print - print - return self - - - def print_callees(self, *amount): - width, list = self.get_print_list(amount) - if list: - self.calc_callees() - - self.print_call_heading(width, "called...") - for func in list: - if self.all_callees.has_key(func): - self.print_call_line(width, \ - func, self.all_callees[func]) - else: - self.print_call_line(width, func, {}) - print - print - return self - - def print_callers(self, *amount): - width, list = self.get_print_list(amount) - if list: - self.print_call_heading(width, "was called by...") - for func in list: - cc, nc, tt, ct, callers = self.stats[func] - self.print_call_line(width, func, callers) - print - print - return self - - def print_call_heading(self, name_size, column_title): - print string.ljust("Function ", name_size) + column_title - - - def print_call_line(self, name_size, source, call_dict): - print string.ljust(func_std_string(source), name_size), - if not call_dict: - print "--" - return - clist = call_dict.keys() - clist.sort() - name_size = name_size + 1 - indent = "" - for func in clist: - name = func_std_string(func) - print indent*name_size + name + '(' \ - + `call_dict[func]`+')', \ - f8(self.stats[func][3]) - indent = " " - - - - def print_title(self): - print string.rjust('ncalls', 9), - print string.rjust('tottime', 8), - print string.rjust('percall', 8), - print string.rjust('cumtime', 8), - print string.rjust('percall', 8), - print 'filename:lineno(function)' - - - def print_line(self, func): # hack : should print percentages - cc, nc, tt, ct, callers = self.stats[func] - c = `nc` - if nc != cc: - c = c + '/' + `cc` - print string.rjust(c, 9), - print f8(tt), - if nc == 0: - print ' '*8, - else: - print f8(tt/nc), - print f8(ct), - if cc == 0: - print ' '*8, - else: - print f8(ct/cc), - print func_std_string(func) - - - def ignore(self): - pass # has no return value, so use at end of line :-) - - -#************************************************************************** -# class TupleComp Documentation -#************************************************************************** -# This class provides a generic function for comparing any two tuples. -# Each instance records a list of tuple-indicies (from most significant -# to least significant), and sort direction (ascending or decending) for -# each tuple-index. The compare functions can then be used as the function -# argument to the system sort() function when a list of tuples need to be -# sorted in the instances order. -#************************************************************************** -class TupleComp: - def __init__(self, comp_select_list): - self.comp_select_list = comp_select_list - - def compare (self, left, right): - for index, direction in self.comp_select_list: - l = left[index] - r = right[index] - if l < r: - return -direction - if l > r: - return direction - return 0 - - - -#************************************************************************** - -def func_strip_path(func_name): - file, line, name = func_name - return os.path.basename(file), line, name - -def func_get_function_name(func): - return func[2] - -def func_std_string(func_name): # match what old profile produced - file, line, name = func_name - return file + ":" + `line` + "(" + name + ")" - -def func_split(func_name): - return func_name - -#************************************************************************** -# The following functions combine statists for pairs functions. -# The bulk of the processing involves correctly handling "call" lists, -# such as callers and callees. -#************************************************************************** - - # Add together all the stats for two profile entries -def add_func_stats(target, source): - cc, nc, tt, ct, callers = source - t_cc, t_nc, t_tt, t_ct, t_callers = target - return (cc+t_cc, nc+t_nc, tt+t_tt, ct+t_ct, \ - add_callers(t_callers, callers)) - - - # Combine two caller lists in a single list. -def add_callers(target, source): - new_callers = {} - for func in target.keys(): - new_callers[func] = target[func] - for func in source.keys(): - if new_callers.has_key(func): - new_callers[func] = source[func] + new_callers[func] - else: - new_callers[func] = source[func] - return new_callers - - # Sum the caller statistics to get total number of calls recieved -def count_calls(callers): - nc = 0 - for func in callers.keys(): - nc = nc + callers[func] - return nc - -#************************************************************************** -# The following functions support printing of reports -#************************************************************************** - -def f8(x): - return string.rjust(fpformat.fix(x, 3), 8) - - diff --git a/Lib/pty.py b/Lib/pty.py deleted file mode 100644 index 53a4b2d3a9..0000000000 --- a/Lib/pty.py +++ /dev/null @@ -1,106 +0,0 @@ -# pty.py -- Pseudo terminal utilities. - -# Bugs: No signal handling. Doesn't set slave termios and window size. -# Only tested on Linux. -# See: W. Richard Stevens. 1992. Advanced Programming in the -# UNIX Environment. Chapter 19. -# Author: Steen Lumholt -- with additions by Guido. - -from select import select -import os, sys, FCNTL -import tty - -STDIN_FILENO = 0 -STDOUT_FILENO = 1 -STDERR_FILENO = 2 - -CHILD = 0 - -# Open pty master. Returns (master_fd, tty_name). SGI and Linux/BSD version. -def master_open(): - try: - import sgi - except ImportError: - pass - else: - try: - tty_name, master_fd = sgi._getpty(FCNTL.O_RDWR, 0666, 0) - except IOError, msg: - raise os.error, msg - return master_fd, tty_name - for x in 'pqrstuvwxyzPQRST': - for y in '0123456789abcdef': - pty_name = '/dev/pty' + x + y - try: - fd = os.open(pty_name, FCNTL.O_RDWR) - except os.error: - continue - return (fd, '/dev/tty' + x + y) - raise os.error, 'out of pty devices' - -# Open the pty slave. Acquire the controlling terminal. -# Returns file descriptor. Linux version. (Should be universal? --Guido) -def slave_open(tty_name): - return os.open(tty_name, FCNTL.O_RDWR) - -# Fork and make the child a session leader with a controlling terminal. -# Returns (pid, master_fd) -def fork(): - master_fd, tty_name = master_open() - pid = os.fork() - if pid == CHILD: - # Establish a new session. - os.setsid() - - # Acquire controlling terminal. - slave_fd = slave_open(tty_name) - os.close(master_fd) - - # Slave becomes stdin/stdout/stderr of child. - os.dup2(slave_fd, STDIN_FILENO) - os.dup2(slave_fd, STDOUT_FILENO) - os.dup2(slave_fd, STDERR_FILENO) - if (slave_fd > STDERR_FILENO): - os.close (slave_fd) - - # Parent and child process. - return pid, master_fd - -# Write all the data to a descriptor. -def writen(fd, data): - while data != '': - n = os.write(fd, data) - data = data[n:] - -# Default read function. -def read(fd): - return os.read(fd, 1024) - -# Parent copy loop. -# Copies -# pty master -> standard output (master_read) -# standard input -> pty master (stdin_read) -def copy(master_fd, master_read=read, stdin_read=read): - while 1: - rfds, wfds, xfds = select( - [master_fd, STDIN_FILENO], [], []) - if master_fd in rfds: - data = master_read(master_fd) - os.write(STDOUT_FILENO, data) - if STDIN_FILENO in rfds: - data = stdin_read(STDIN_FILENO) - writen(master_fd, data) - -# Create a spawned process. -def spawn(argv, master_read=read, stdin_read=read): - if type(argv) == type(''): - argv = (argv,) - pid, master_fd = fork() - if pid == CHILD: - apply(os.execlp, (argv[0],) + argv) - mode = tty.tcgetattr(STDIN_FILENO) - tty.setraw(STDIN_FILENO) - try: - copy(master_fd, master_read, stdin_read) - except: - tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode) diff --git a/Lib/py_compile.py b/Lib/py_compile.py deleted file mode 100644 index 2e68ba82c5..0000000000 --- a/Lib/py_compile.py +++ /dev/null @@ -1,31 +0,0 @@ -# Routine to "compile" a .py file to a .pyc file. -# This has intimate knowledge of how Python/import.c does it. -# By Sjoerd Mullender (I forced him to write it :-). - -import imp -MAGIC = imp.get_magic() - -def wr_long(f, x): - f.write(chr( x & 0xff)) - f.write(chr((x >> 8) & 0xff)) - f.write(chr((x >> 16) & 0xff)) - f.write(chr((x >> 24) & 0xff)) - -def compile(file, cfile = None): - import os, marshal, __builtin__ - f = open(file) - codestring = f.read() - f.close() - timestamp = os.stat(file)[8] - codeobject = __builtin__.compile(codestring, file, 'exec') - if not cfile: - cfile = file + 'c' - fc = open(cfile, 'wb') - fc.write(MAGIC) - wr_long(fc, timestamp) - marshal.dump(codeobject, fc) - fc.close() - if os.name == 'mac': - import macfs - macfs.FSSpec(cfile).SetCreatorType('Pyth', 'PYC ') - macfs.FSSpec(file).SetCreatorType('Pyth', 'TEXT') diff --git a/Lib/pyclbr.py b/Lib/pyclbr.py deleted file mode 100644 index f6f5bb932e..0000000000 --- a/Lib/pyclbr.py +++ /dev/null @@ -1,205 +0,0 @@ -'''Parse a Python file and retrieve classes and methods. - -Parse enough of a Python file to recognize class and method -definitions and to find out the superclasses of a class. - -The interface consists of a single function: - readmodule(module, path) -module is the name of a Python module, path is an optional list of -directories where the module is to be searched. If present, path is -prepended to the system search path sys.path. -The return value is a dictionary. The keys of the dictionary are -the names of the classes defined in the module (including classes -that are defined via the from XXX import YYY construct). The values -are class instances of the class Class defined here. - -A class is described by the class Class in this module. Instances -of this class have the following instance variables: - name -- the name of the class - super -- a list of super classes (Class instances) - methods -- a dictionary of methods - file -- the file in which the class was defined - lineno -- the line in the file on which the class statement occurred -The dictionary of methods uses the method names as keys and the line -numbers on which the method was defined as values. -If the name of a super class is not recognized, the corresponding -entry in the list of super classes is not a class instance but a -string giving the name of the super class. Since import statements -are recognized and imported modules are scanned as well, this -shouldn't happen often. - -BUGS -Continuation lines are not dealt with at all and strings may confuse -the hell out of the parser, but it usually works.''' - -import os -import sys -import imp -import regex -import string - -id = '\\(<id>[A-Za-z_][A-Za-z0-9_]*\\)' # match identifier -blank_line = regex.compile('^[ \t]*\\($\\|#\\)') -is_class = regex.symcomp('^class[ \t]+'+id+'[ \t]*\\(<sup>([^)]*)\\)?[ \t]*:') -is_method = regex.symcomp('^[ \t]+def[ \t]+'+id+'[ \t]*(') -is_import = regex.symcomp('^import[ \t]*\\(<imp>[^#]+\\)') -is_from = regex.symcomp('^from[ \t]+'+id+'[ \t]+import[ \t]+\\(<imp>[^#]+\\)') -dedent = regex.compile('^[^ \t]') -indent = regex.compile('^[^ \t]*') - -_modules = {} # cache of modules we've seen - -# each Python class is represented by an instance of this class -class Class: - '''Class to represent a Python class.''' - def __init__(self, module, name, super, file, lineno): - self.module = module - self.name = name - if super is None: - super = [] - self.super = super - self.methods = {} - self.file = file - self.lineno = lineno - - def _addmethod(self, name, lineno): - self.methods[name] = lineno - -def readmodule(module, path = []): - '''Read a module file and return a dictionary of classes. - - Search for MODULE in PATH and sys.path, read and parse the - module and return a dictionary with one entry for each class - found in the module.''' - - if _modules.has_key(module): - # we've seen this module before... - return _modules[module] - if module in sys.builtin_module_names: - # this is a built-in module - dict = {} - _modules[module] = dict - return dict - - # search the path for the module - f = None - suffixes = imp.get_suffixes() - for dir in path + sys.path: - for suff, mode, type in suffixes: - file = os.path.join(dir, module + suff) - try: - f = open(file, mode) - except IOError: - pass - else: - # found the module - break - if f: - break - if not f: - raise IOError, 'module ' + module + ' not found' - if type != imp.PY_SOURCE: - # not Python source, can't do anything with this module - f.close() - dict = {} - _modules[module] = dict - return dict - - cur_class = None - dict = {} - _modules[module] = dict - imports = [] - lineno = 0 - while 1: - line = f.readline() - if not line: - break - lineno = lineno + 1 # count lines - line = line[:-1] # remove line feed - if blank_line.match(line) >= 0: - # ignore blank (and comment only) lines - continue -## if indent.match(line) >= 0: -## indentation = len(string.expandtabs(indent.group(0), 8)) - if is_import.match(line) >= 0: - # import module - for n in string.splitfields(is_import.group('imp'), ','): - n = string.strip(n) - try: - # recursively read the - # imported module - d = readmodule(n, path) - except: - print 'module',n,'not found' - pass - continue - if is_from.match(line) >= 0: - # from module import stuff - mod = is_from.group('id') - names = string.splitfields(is_from.group('imp'), ',') - try: - # recursively read the imported module - d = readmodule(mod, path) - except: - print 'module',mod,'not found' - continue - # add any classes that were defined in the - # imported module to our name space if they - # were mentioned in the list - for n in names: - n = string.strip(n) - if d.has_key(n): - dict[n] = d[n] - elif n == '*': - # only add a name if not - # already there (to mimic what - # Python does internally) - for n in d.keys(): - if not dict.has_key(n): - dict[n] = d[n] - continue - if is_class.match(line) >= 0: - # we found a class definition - class_name = is_class.group('id') - inherit = is_class.group('sup') - if inherit: - # the class inherits from other classes - inherit = string.strip(inherit[1:-1]) - names = [] - for n in string.splitfields(inherit, ','): - n = string.strip(n) - if dict.has_key(n): - # we know this super class - n = dict[n] - else: - c = string.splitfields(n, '.') - if len(c) > 1: - # super class - # is of the - # form module.class: - # look in - # module for class - m = c[-2] - c = c[-1] - if _modules.has_key(m): - d = _modules[m] - if d.has_key(c): - n = d[c] - names.append(n) - inherit = names - # remember this class - cur_class = Class(module, class_name, inherit, file, lineno) - dict[class_name] = cur_class - continue - if is_method.match(line) >= 0: - # found a method definition - if cur_class: - # and we know the class it belongs to - meth_name = is_method.group('id') - cur_class._addmethod(meth_name, lineno) - continue - if dedent.match(line) >= 0: - # end of class definition - cur_class = None - f.close() - return dict diff --git a/Lib/quopri.py b/Lib/quopri.py deleted file mode 100755 index 55608d1206..0000000000 --- a/Lib/quopri.py +++ /dev/null @@ -1,133 +0,0 @@ -# Conversions to/from quoted-printable transport encoding as per RFC-XXXX -# (Dec 1991 version). - -ESCAPE = '=' -MAXLINESIZE = 76 -HEX = '0123456789ABCDEF' - -def needsquoting(c, quotetabs): - if c == '\t': - return not quotetabs - return c == ESCAPE or not(' ' <= c <= '~') - -def quote(c): - if c == ESCAPE: - return ESCAPE * 2 - else: - i = ord(c) - return ESCAPE + HEX[i/16] + HEX[i%16] - -def encode(input, output, quotetabs): - while 1: - line = input.readline() - if not line: break - new = '' - last = line[-1:] - if last == '\n': line = line[:-1] - else: last = '' - prev = '' - for c in line: - if needsquoting(c, quotetabs): - c = quote(c) - if len(new) + len(c) >= MAXLINESIZE: - output.write(new + ESCAPE + '\n') - new = '' - new = new + c - prev = c - if prev in (' ', '\t'): - output.write(new + ESCAPE + '\n\n') - else: - output.write(new + '\n') - -def decode(input, output): - new = '' - while 1: - line = input.readline() - if not line: break - i, n = 0, len(line) - if n > 0 and line[n-1] == '\n': - partial = 0; n = n-1 - # Strip trailing whitespace - while n > 0 and line[n-1] in (' ', '\t'): - n = n-1 - else: - partial = 1 - while i < n: - c = line[i] - if c <> ESCAPE: - new = new + c; i = i+1 - elif i+1 == n and not partial: - partial = 1; break - elif i+1 < n and line[i+1] == ESCAPE: - new = new + ESCAPE; i = i+2 - elif i+2 < n and ishex(line[i+1]) and ishex(line[i+2]): - new = new + chr(unhex(line[i+1:i+3])); i = i+3 - else: # Bad escape sequence -- leave it in - new = new + c; i = i+1 - if not partial: - output.write(new + '\n') - new = '' - if new: - output.write(new) - -def ishex(c): - return '0' <= c <= '9' or 'a' <= c <= 'f' or 'A' <= c <= 'F' - -def unhex(s): - bits = 0 - for c in s: - if '0' <= c <= '9': - i = ord('0') - elif 'a' <= c <= 'f': - i = ord('a')-10 - elif 'A' <= c <= 'F': - i = ord('A')-10 - else: - break - bits = bits*16 + (ord(c) - i) - return bits - -def test(): - import sys - import getopt - try: - opts, args = getopt.getopt(sys.argv[1:], 'td') - except getopt.error, msg: - sys.stdout = sys.stderr - print msg - print "usage: quopri [-t | -d] [file] ..." - print "-t: quote tabs" - print "-d: decode; default encode" - sys.exit(2) - deco = 0 - tabs = 0 - for o, a in opts: - if o == '-t': tabs = 1 - if o == '-d': deco = 1 - if tabs and deco: - sys.stdout = sys.stderr - print "-t and -d are mutually exclusive" - sys.exit(2) - if not args: args = ['-'] - sts = 0 - for file in args: - if file == '-': - fp = sys.stdin - else: - try: - fp = open(file) - except IOError, msg: - sys.stderr.write("%s: can't open (%s)\n" % (file, msg)) - sts = 1 - continue - if deco: - decode(fp, sys.stdout) - else: - encode(fp, sys.stdout, tabs) - if fp is not sys.stdin: - fp.close() - if sts: - sys.exit(sts) - -if __name__ == '__main__': - test() diff --git a/Lib/rand.py b/Lib/rand.py deleted file mode 100644 index c299d0a9a9..0000000000 --- a/Lib/rand.py +++ /dev/null @@ -1,13 +0,0 @@ -# Module 'rand' -# Don't use unless you want compatibility with C's rand()! - -import whrandom - -def srand(seed): - whrandom.seed(seed%256, seed/256%256, seed/65536%256) - -def rand(): - return int(whrandom.random() * 32768.0) % 32768 - -def choice(seq): - return seq[rand() % len(seq)] diff --git a/Lib/random.py b/Lib/random.py deleted file mode 100644 index 608203f547..0000000000 --- a/Lib/random.py +++ /dev/null @@ -1,260 +0,0 @@ -# R A N D O M V A R I A B L E G E N E R A T O R S -# -# distributions on the real line: -# ------------------------------ -# normal (Gaussian) -# lognormal -# negative exponential -# gamma -# beta -# -# distributions on the circle (angles 0 to 2pi) -# --------------------------------------------- -# circular uniform -# von Mises - -# Translated from anonymously contributed C/C++ source. - -from whrandom import random, uniform, randint, choice # Also for export! -from math import log, exp, pi, e, sqrt, acos, cos, sin - -# Housekeeping function to verify that magic constants have been -# computed correctly - -def verify(name, expected): - computed = eval(name) - if abs(computed - expected) > 1e-7: - raise ValueError, \ - 'computed value for %s deviates too much (computed %g, expected %g)' % \ - (name, computed, expected) - -# -------------------- normal distribution -------------------- - -NV_MAGICCONST = 4*exp(-0.5)/sqrt(2.0) -verify('NV_MAGICCONST', 1.71552776992141) -def normalvariate(mu, sigma): - # mu = mean, sigma = standard deviation - - # Uses Kinderman and Monahan method. Reference: Kinderman, - # A.J. and Monahan, J.F., "Computer generation of random - # variables using the ratio of uniform deviates", ACM Trans - # Math Software, 3, (1977), pp257-260. - - while 1: - u1 = random() - u2 = random() - z = NV_MAGICCONST*(u1-0.5)/u2 - zz = z*z/4.0 - if zz <= -log(u2): - break - return mu+z*sigma - -# -------------------- lognormal distribution -------------------- - -def lognormvariate(mu, sigma): - return exp(normalvariate(mu, sigma)) - -# -------------------- circular uniform -------------------- - -def cunifvariate(mean, arc): - # mean: mean angle (in radians between 0 and pi) - # arc: range of distribution (in radians between 0 and pi) - - return (mean + arc * (random() - 0.5)) % pi - -# -------------------- exponential distribution -------------------- - -def expovariate(lambd): - # lambd: rate lambd = 1/mean - # ('lambda' is a Python reserved word) - - u = random() - while u <= 1e-7: - u = random() - return -log(u)/lambd - -# -------------------- von Mises distribution -------------------- - -TWOPI = 2.0*pi -verify('TWOPI', 6.28318530718) - -def vonmisesvariate(mu, kappa): - # mu: mean angle (in radians between 0 and 180 degrees) - # kappa: concentration parameter kappa (>= 0) - - # if kappa = 0 generate uniform random angle - if kappa <= 1e-6: - return TWOPI * random() - - a = 1.0 + sqrt(1.0 + 4.0 * kappa * kappa) - b = (a - sqrt(2.0 * a))/(2.0 * kappa) - r = (1.0 + b * b)/(2.0 * b) - - while 1: - u1 = random() - - z = cos(pi * u1) - f = (1.0 + r * z)/(r + z) - c = kappa * (r - f) - - u2 = random() - - if not (u2 >= c * (2.0 - c) and u2 > c * exp(1.0 - c)): - break - - u3 = random() - if u3 > 0.5: - theta = mu + 0.5*acos(f) - else: - theta = mu - 0.5*acos(f) - - return theta % pi - -# -------------------- gamma distribution -------------------- - -LOG4 = log(4.0) -verify('LOG4', 1.38629436111989) - -def gammavariate(alpha, beta): - # beta times standard gamma - ainv = sqrt(2.0 * alpha - 1.0) - return beta * stdgamma(alpha, ainv, alpha - LOG4, alpha + ainv) - -SG_MAGICCONST = 1.0 + log(4.5) -verify('SG_MAGICCONST', 2.50407739677627) - -def stdgamma(alpha, ainv, bbb, ccc): - # ainv = sqrt(2 * alpha - 1) - # bbb = alpha - log(4) - # ccc = alpha + ainv - - if alpha <= 0.0: - raise ValueError, 'stdgamma: alpha must be > 0.0' - - if alpha > 1.0: - - # Uses R.C.H. Cheng, "The generation of Gamma - # variables with non-integral shape parameters", - # Applied Statistics, (1977), 26, No. 1, p71-74 - - while 1: - u1 = random() - u2 = random() - v = log(u1/(1.0-u1))/ainv - x = alpha*exp(v) - z = u1*u1*u2 - r = bbb+ccc*v-x - if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= log(z): - return x - - elif alpha == 1.0: - # expovariate(1) - u = random() - while u <= 1e-7: - u = random() - return -log(u) - - else: # alpha is between 0 and 1 (exclusive) - - # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle - - while 1: - u = random() - b = (e + alpha)/e - p = b*u - if p <= 1.0: - x = pow(p, 1.0/alpha) - else: - # p > 1 - x = -log((b-p)/alpha) - u1 = random() - if not (((p <= 1.0) and (u1 > exp(-x))) or - ((p > 1) and (u1 > pow(x, alpha - 1.0)))): - break - return x - - -# -------------------- Gauss (faster alternative) -------------------- - -gauss_next = None -def gauss(mu, sigma): - - # When x and y are two variables from [0, 1), uniformly - # distributed, then - # - # cos(2*pi*x)*log(1-y) - # sin(2*pi*x)*log(1-y) - # - # are two *independent* variables with normal distribution - # (mu = 0, sigma = 1). - # (Lambert Meertens) - - global gauss_next - - if gauss_next != None: - z = gauss_next - gauss_next = None - else: - x2pi = random() * TWOPI - log1_y = log(1.0 - random()) - z = cos(x2pi) * log1_y - gauss_next = sin(x2pi) * log1_y - - return mu + z*sigma - -# -------------------- beta -------------------- - -def betavariate(alpha, beta): - - # Discrete Event Simulation in C, pp 87-88. - - y = expovariate(alpha) - z = expovariate(1.0/beta) - return z/(y+z) - -# -------------------- test program -------------------- - -def test(N = 200): - print 'TWOPI =', TWOPI - print 'LOG4 =', LOG4 - print 'NV_MAGICCONST =', NV_MAGICCONST - print 'SG_MAGICCONST =', SG_MAGICCONST - test_generator(N, 'random()') - test_generator(N, 'normalvariate(0.0, 1.0)') - test_generator(N, 'lognormvariate(0.0, 1.0)') - test_generator(N, 'cunifvariate(0.0, 1.0)') - test_generator(N, 'expovariate(1.0)') - test_generator(N, 'vonmisesvariate(0.0, 1.0)') - test_generator(N, 'gammavariate(0.5, 1.0)') - test_generator(N, 'gammavariate(0.9, 1.0)') - test_generator(N, 'gammavariate(1.0, 1.0)') - test_generator(N, 'gammavariate(2.0, 1.0)') - test_generator(N, 'gammavariate(20.0, 1.0)') - test_generator(N, 'gammavariate(200.0, 1.0)') - test_generator(N, 'gauss(0.0, 1.0)') - test_generator(N, 'betavariate(3.0, 3.0)') - -def test_generator(n, funccall): - import time - print n, 'times', funccall - code = compile(funccall, funccall, 'eval') - sum = 0.0 - sqsum = 0.0 - smallest = 1e10 - largest = -1e10 - t0 = time.time() - for i in range(n): - x = eval(code) - sum = sum + x - sqsum = sqsum + x*x - smallest = min(x, smallest) - largest = max(x, largest) - t1 = time.time() - print round(t1-t0, 3), 'sec,', - avg = sum/n - stddev = sqrt(sqsum/n - avg*avg) - print 'avg %g, stddev %g, min %g, max %g' % \ - (avg, stddev, smallest, largest) - -if __name__ == '__main__': - test() diff --git a/Lib/regex_syntax.py b/Lib/regex_syntax.py deleted file mode 100644 index bb80f4e88d..0000000000 --- a/Lib/regex_syntax.py +++ /dev/null @@ -1,41 +0,0 @@ -# These bits are passed to regex.set_syntax() to choose among -# alternative regexp syntaxes. - -# 1 means plain parentheses serve as grouping, and backslash -# parentheses are needed for literal searching. -# 0 means backslash-parentheses are grouping, and plain parentheses -# are for literal searching. -RE_NO_BK_PARENS = 1 - -# 1 means plain | serves as the "or"-operator, and \| is a literal. -# 0 means \| serves as the "or"-operator, and | is a literal. -RE_NO_BK_VBAR = 2 - -# 0 means plain + or ? serves as an operator, and \+, \? are literals. -# 1 means \+, \? are operators and plain +, ? are literals. -RE_BK_PLUS_QM = 4 - -# 1 means | binds tighter than ^ or $. -# 0 means the contrary. -RE_TIGHT_VBAR = 8 - -# 1 means treat \n as an _OR operator -# 0 means treat it as a normal character -RE_NEWLINE_OR = 16 - -# 0 means that a special characters (such as *, ^, and $) always have -# their special meaning regardless of the surrounding context. -# 1 means that special characters may act as normal characters in some -# contexts. Specifically, this applies to: -# ^ - only special at the beginning, or after ( or | -# $ - only special at the end, or before ) or | -# *, +, ? - only special when not after the beginning, (, or | -RE_CONTEXT_INDEP_OPS = 32 - -# Now define combinations of bits for the standard possibilities. -RE_SYNTAX_AWK = (RE_NO_BK_PARENS | RE_NO_BK_VBAR | RE_CONTEXT_INDEP_OPS) -RE_SYNTAX_EGREP = (RE_SYNTAX_AWK | RE_NEWLINE_OR) -RE_SYNTAX_GREP = (RE_BK_PLUS_QM | RE_NEWLINE_OR) -RE_SYNTAX_EMACS = 0 - -# (Python's obsolete "regexp" module used a syntax similar to awk.) diff --git a/Lib/regexp.py b/Lib/regexp.py deleted file mode 100644 index 4b5db73e03..0000000000 --- a/Lib/regexp.py +++ /dev/null @@ -1,32 +0,0 @@ -# Provide backward compatibility for module "regexp" using "regex". - -import regex -from regex_syntax import * - -class Prog: - def __init__(self, pat): - save_syntax = regex.set_syntax(RE_SYNTAX_AWK) - try: - self.prog = regex.compile(pat) - finally: - xxx = regex.set_syntax(save_syntax) - def match(self, str, offset = 0): - if self.prog.search(str, offset) < 0: - return () - regs = self.prog.regs - i = len(regs) - while i > 0 and regs[i-1] == (-1, -1): - i = i-1 - return regs[:i] - -def compile(pat): - return Prog(pat) - -cache_pat = None -cache_prog = None - -def match(pat, str): - global cache_pat, cache_prog - if pat <> cache_pat: - cache_pat, cache_prog = pat, compile(pat) - return cache_prog.match(str) diff --git a/Lib/regsub.py b/Lib/regsub.py deleted file mode 100644 index 507e542882..0000000000 --- a/Lib/regsub.py +++ /dev/null @@ -1,148 +0,0 @@ -# Regular expression subroutines: -# sub(pat, repl, str): replace first occurrence of pattern in string -# gsub(pat, repl, str): replace all occurrences of pattern in string -# split(str, pat): split string using pattern as delimiter - - -import regex - - -# Replace first occurrence of pattern pat in string str by replacement -# repl. If the pattern isn't found, the string is returned unchanged. -# The replacement may contain references \digit to subpatterns and -# escaped backslashes. The pattern may be a string or an already -# compiled pattern. - -def sub(pat, repl, str): - prog = compile(pat) - if prog.search(str) >= 0: - regs = prog.regs - a, b = regs[0] - str = str[:a] + expand(repl, regs, str) + str[b:] - return str - - -# Replace all (non-overlapping) occurrences of pattern pat in string -# str by replacement repl. The same rules as for sub() apply. -# Empty matches for the pattern are replaced only when not adjacent to -# a previous match, so e.g. gsub('', '-', 'abc') returns '-a-b-c-'. - -def gsub(pat, repl, str): - prog = compile(pat) - new = '' - start = 0 - first = 1 - while prog.search(str, start) >= 0: - regs = prog.regs - a, b = regs[0] - if a == b == start and not first: - if start >= len(str) or prog.search(str, start+1) < 0: - break - regs = prog.regs - a, b = regs[0] - new = new + str[start:a] + expand(repl, regs, str) - start = b - first = 0 - new = new + str[start:] - return new - - -# Split string str in fields separated by delimiters matching pattern -# pat. Only non-empty matches for the pattern are considered, so e.g. -# split('abc', '') returns ['abc']. - -def split(str, pat): - prog = compile(pat) - res = [] - start = next = 0 - while prog.search(str, next) >= 0: - regs = prog.regs - a, b = regs[0] - if a == b: - next = next + 1 - if next >= len(str): - break - else: - res.append(str[start:a]) - start = next = b - res.append(str[start:]) - return res - - -# Internal subroutines: -# compile(pat): compile a pattern, caching already compiled patterns -# expand(repl, regs, str): expand \digit escapes in replacement string - - -# Manage a cache of compiled regular expressions. -# If the pattern is a string a compiled version of it is returned. -# If the pattern has been used before we return an already compiled -# version from the cache; otherwise we compile it now and save the -# compiled version in the cache. -# Instead of a string, a compiled regular expression can also be -# passed. -# WARNING: if the pattern syntax is changed, the cache should be -# flushed! - -cache = {} - -def compile(pat): - if type(pat) <> type(''): - return pat # Assume it is a compiled regex - if cache.has_key(pat): - prog = cache[pat] # Get it from the cache - else: - prog = cache[pat] = regex.compile(pat) - return prog - - -# Expand \digit in the replacement. -# Each occurrence of \digit is replaced by the substring of str -# indicated by regs[digit]. To include a literal \ in the -# replacement, double it; other \ escapes are left unchanged (i.e. -# the \ and the following character are both copied). - -def expand(repl, regs, str): - if '\\' not in repl: - return repl - new = '' - i = 0 - ord0 = ord('0') - while i < len(repl): - c = repl[i]; i = i+1 - if c <> '\\' or i >= len(repl): - new = new + c - else: - c = repl[i]; i = i+1 - if '0' <= c <= '9': - a, b = regs[ord(c)-ord0] - new = new + str[a:b] - elif c == '\\': - new = new + c - else: - new = new + '\\' + c - return new - - -# Test program, reads sequences "pat repl str" from stdin. -# Optional argument specifies pattern used to split lines. - -def test(): - import sys - if sys.argv[1:]: - delpat = sys.argv[1] - else: - delpat = '[ \t\n]+' - while 1: - if sys.stdin.isatty(): sys.stderr.write('--> ') - line = sys.stdin.readline() - if not line: break - if line[-1] == '\n': line = line[:-1] - fields = split(line, delpat) - if len(fields) <> 3: - print 'Sorry, not three fields' - print 'split:', `fields` - continue - [pat, repl, str] = split(line, delpat) - print 'sub :', `sub(pat, repl, str)` - print 'gsub:', `gsub(pat, repl, str)` diff --git a/Lib/repr.py b/Lib/repr.py deleted file mode 100644 index f8ef71d681..0000000000 --- a/Lib/repr.py +++ /dev/null @@ -1,95 +0,0 @@ -# Redo the `...` (representation) but with limits on most sizes. - -import string - -class Repr: - def __init__(self): - self.maxlevel = 6 - self.maxtuple = 6 - self.maxlist = 6 - self.maxdict = 4 - self.maxstring = 30 - self.maxlong = 40 - self.maxother = 20 - def repr(self, x): - return self.repr1(x, self.maxlevel) - def repr1(self, x, level): - typename = `type(x)`[7:-2] # "<type '......'>" - if ' ' in typename: - parts = string.split(typename) - typename = string.joinfields(parts, '_') - if hasattr(self, 'repr_' + typename): - return getattr(self, 'repr_' + typename)(x, level) - else: - s = `x` - if len(s) > self.maxother: - i = max(0, (self.maxother-3)/2) - j = max(0, self.maxother-3-i) - s = s[:i] + '...' + s[len(s)-j:] - return s - def repr_tuple(self, x, level): - n = len(x) - if n == 0: return '()' - if level <= 0: return '(...)' - s = '' - for i in range(min(n, self.maxtuple)): - if s: s = s + ', ' - s = s + self.repr1(x[i], level-1) - if n > self.maxtuple: s = s + ', ...' - elif n == 1: s = s + ',' - return '(' + s + ')' - def repr_list(self, x, level): - n = len(x) - if n == 0: return '[]' - if level <= 0: return '[...]' - s = '' - for i in range(min(n, self.maxlist)): - if s: s = s + ', ' - s = s + self.repr1(x[i], level-1) - if n > self.maxlist: s = s + ', ...' - return '[' + s + ']' - def repr_dictionary(self, x, level): - n = len(x) - if n == 0: return '{}' - if level <= 0: return '{...}' - s = '' - keys = x.keys() - keys.sort() - for i in range(min(n, self.maxdict)): - if s: s = s + ', ' - key = keys[i] - s = s + self.repr1(key, level-1) - s = s + ': ' + self.repr1(x[key], level-1) - if n > self.maxlist: s = s + ', ...' - return '{' + s + '}' - def repr_string(self, x, level): - s = `x[:self.maxstring]` - if len(s) > self.maxstring: - i = max(0, (self.maxstring-3)/2) - j = max(0, self.maxstring-3-i) - s = `x[:i] + x[len(x)-j:]` - s = s[:i] + '...' + s[len(s)-j:] - return s - def repr_long_int(self, x, level): - s = `x` # XXX Hope this isn't too slow... - if len(s) > self.maxlong: - i = max(0, (self.maxlong-3)/2) - j = max(0, self.maxlong-3-i) - s = s[:i] + '...' + s[len(s)-j:] - return s - def repr_instance(self, x, level): - try: - s = `x` - # Bugs in x.__repr__() can cause arbitrary - # exceptions -- then make up something - except: - return '<' + x.__class__.__name__ + ' instance at ' + \ - hex(id(x))[2:] + '>' - if len(s) > self.maxstring: - i = max(0, (self.maxstring-3)/2) - j = max(0, self.maxstring-3-i) - s = s[:i] + '...' + s[len(s)-j:] - return s - -aRepr = Repr() -repr = aRepr.repr diff --git a/Lib/rexec.py b/Lib/rexec.py deleted file mode 100644 index b4ec0f2f74..0000000000 --- a/Lib/rexec.py +++ /dev/null @@ -1,357 +0,0 @@ -"""Restricted execution facilities. - -The class RExec exports methods r_exec(), r_eval(), r_execfile(), and -r_import(), which correspond roughly to the built-in operations -exec, eval(), execfile() and import, but executing the code in an -environment that only exposes those built-in operations that are -deemed safe. To this end, a modest collection of 'fake' modules is -created which mimics the standard modules by the same names. It is a -policy decision which built-in modules and operations are made -available; this module provides a reasonable default, but derived -classes can change the policies e.g. by overriding or extending class -variables like ok_builtin_modules or methods like make_sys(). - -XXX To do: -- r_open should allow writing tmp dir -- r_exec etc. with explicit globals/locals? (Use rexec("exec ... in ...")?) - -""" - - -import sys -import __builtin__ -import os -import marshal -import ihooks - - -class FileBase: - - ok_file_methods = ('fileno', 'flush', 'isatty', 'read', 'readline', - 'readlines', 'seek', 'tell', 'write', 'writelines') - - -class FileWrapper(FileBase): - - def __init__(self, f): - self.f = f - for m in self.ok_file_methods: - if not hasattr(self, m): - setattr(self, m, getattr(f, m)) - - def close(f): - self.flush() - - -TEMPLATE = """ -def %s(self, *args): - return apply(getattr(self.mod, self.name).%s, args) -""" - -class FileDelegate(FileBase): - - def __init__(self, mod, name): - self.mod = mod - self.name = name - - for m in FileBase.ok_file_methods + ('close',): - exec TEMPLATE % (m, m) - - -class RHooks(ihooks.Hooks): - - def __init__(self, *args): - # Hacks to support both old and new interfaces: - # old interface was RHooks(rexec[, verbose]) - # new interface is RHooks([verbose]) - verbose = 0 - rexec = None - if args and type(args[-1]) == type(0): - verbose = args[-1] - args = args[:-1] - if args and hasattr(args[0], '__class__'): - rexec = args[0] - args = args[1:] - if args: - raise TypeError, "too many arguments" - ihooks.Hooks.__init__(self, verbose) - self.rexec = rexec - - def set_rexec(self, rexec): - # Called by RExec instance to complete initialization - self.rexec = rexec - - def is_builtin(self, name): - return self.rexec.is_builtin(name) - - def init_builtin(self, name): - m = __import__(name) - return self.rexec.copy_except(m, ()) - - def init_frozen(self, name): raise SystemError, "don't use this" - def load_source(self, *args): raise SystemError, "don't use this" - def load_compiled(self, *args): raise SystemError, "don't use this" - - def load_dynamic(self, name, filename, file): - return self.rexec.load_dynamic(name, filename, file) - - def add_module(self, name): - return self.rexec.add_module(name) - - def modules_dict(self): - return self.rexec.modules - - def default_path(self): - return self.rexec.modules['sys'].path - - -class RModuleLoader(ihooks.FancyModuleLoader): - - def load_module(self, name, stuff): - file, filename, info = stuff - m = ihooks.FancyModuleLoader.load_module(self, name, stuff) - m.__filename__ = filename - return m - - -class RModuleImporter(ihooks.ModuleImporter): - - def reload(self, module, path=None): - if path is None and hasattr(module, '__filename__'): - head, tail = os.path.split(module.__filename__) - path = [os.path.join(head, '')] - return ihooks.ModuleImporter.reload(self, module, path) - - -class RExec(ihooks._Verbose): - - """Restricted Execution environment.""" - - ok_path = tuple(sys.path) # That's a policy decision - - ok_builtin_modules = ('array', 'binascii', 'audioop', 'imageop', - 'marshal', 'math', - 'md5', 'parser', 'regex', 'rotor', 'select', - 'strop', 'struct', 'time') - - ok_posix_names = ('error', 'fstat', 'listdir', 'lstat', 'readlink', - 'stat', 'times', 'uname', 'getpid', 'getppid', - 'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid') - - ok_sys_names = ('ps1', 'ps2', 'copyright', 'version', - 'platform', 'exit', 'maxint') - - nok_builtin_names = ('open', 'reload', '__import__') - - def __init__(self, hooks = None, verbose = 0): - ihooks._Verbose.__init__(self, verbose) - # XXX There's a circular reference here: - self.hooks = hooks or RHooks(verbose) - self.hooks.set_rexec(self) - self.modules = {} - self.ok_dynamic_modules = self.ok_builtin_modules - list = [] - for mname in self.ok_builtin_modules: - if mname in sys.builtin_module_names: - list.append(mname) - self.ok_builtin_modules = list - self.set_trusted_path() - self.make_builtin() - self.make_initial_modules() - # make_sys must be last because it adds the already created - # modules to its builtin_module_names - self.make_sys() - self.loader = RModuleLoader(self.hooks, verbose) - self.importer = RModuleImporter(self.loader, verbose) - - def set_trusted_path(self): - # Set the path from which dynamic modules may be loaded. - # Those dynamic modules must also occur in ok_builtin_modules - self.trusted_path = filter(os.path.isabs, sys.path) - - def load_dynamic(self, name, filename, file): - if name not in self.ok_dynamic_modules: - raise ImportError, "untrusted dynamic module: %s" % name - if sys.modules.has_key(name): - src = sys.modules[name] - else: - import imp - src = imp.load_dynamic(name, filename, file) - dst = self.copy_except(src, []) - return dst - - def make_initial_modules(self): - self.make_main() - self.make_osname() - - # Helpers for RHooks - - def is_builtin(self, mname): - return mname in self.ok_builtin_modules - - # The make_* methods create specific built-in modules - - def make_builtin(self): - m = self.copy_except(__builtin__, self.nok_builtin_names) - m.__import__ = self.r_import - m.reload = self.r_reload - m.open = self.r_open - - def make_main(self): - m = self.add_module('__main__') - - def make_osname(self): - osname = os.name - src = __import__(osname) - dst = self.copy_only(src, self.ok_posix_names) - dst.environ = e = {} - for key, value in os.environ.items(): - e[key] = value - - def make_sys(self): - m = self.copy_only(sys, self.ok_sys_names) - m.modules = self.modules - m.argv = ['RESTRICTED'] - m.path = map(None, self.ok_path) - m = self.modules['sys'] - m.builtin_module_names = \ - self.modules.keys() + self.ok_builtin_modules - m.builtin_module_names.sort() - - # The copy_* methods copy existing modules with some changes - - def copy_except(self, src, exceptions): - dst = self.copy_none(src) - for name in dir(src): - setattr(dst, name, getattr(src, name)) - for name in exceptions: - try: - delattr(dst, name) - except KeyError: - pass - return dst - - def copy_only(self, src, names): - dst = self.copy_none(src) - for name in names: - try: - value = getattr(src, name) - except AttributeError: - continue - setattr(dst, name, value) - return dst - - def copy_none(self, src): - return self.add_module(src.__name__) - - # Add a module -- return an existing module or create one - - def add_module(self, mname): - if self.modules.has_key(mname): - return self.modules[mname] - self.modules[mname] = m = self.hooks.new_module(mname) - m.__builtins__ = self.modules['__builtin__'] - return m - - # The r* methods are public interfaces - - def r_exec(self, code): - m = self.add_module('__main__') - exec code in m.__dict__ - - def r_eval(self, code): - m = self.add_module('__main__') - return eval(code, m.__dict__) - - def r_execfile(self, file): - m = self.add_module('__main__') - return execfile(file, m.__dict__) - - def r_import(self, mname, globals={}, locals={}, fromlist=[]): - return self.importer.import_module(mname, globals, locals, fromlist) - - def r_reload(self, m): - return self.importer.reload(m) - - def r_unload(self, m): - return self.importer.unload(m) - - # The s_* methods are similar but also swap std{in,out,err} - - def set_files(self): - s = self.modules['sys'] - s.stdin = FileWrapper(sys.stdin) - s.stdout = FileWrapper(sys.stdout) - s.stderr = FileWrapper(sys.stderr) - sys.stdin = FileDelegate(s, 'stdin') - sys.stdout = FileDelegate(s, 'stdout') - sys.stderr = FileDelegate(s, 'stderr') - - def save_files(self): - self.save_stdin = sys.stdin - self.save_stdout = sys.stdout - self.save_stderr = sys.stderr - - def restore_files(files): - sys.stdin = self.save_sydin - sys.stdout = self.save_stdout - sys.stderr = self.save_stderr - - def s_apply(self, func, *args, **kw): - self.save_files() - try: - self.set_files() - r = apply(func, args, kw) - finally: - self.restore_files() - - def s_exec(self, *args): - self.s_apply(self.r_exec, args) - - def s_eval(self, *args): - self.s_apply(self.r_eval, args) - - def s_execfile(self, *args): - self.s_apply(self.r_execfile, args) - - def s_import(self, *args): - self.s_apply(self.r_import, args) - - def s_reload(self, *args): - self.s_apply(self.r_reload, args) - - def s_unload(self, *args): - self.s_apply(self.r_unload, args) - - # Restricted open(...) - - def r_open(self, file, mode='r', buf=-1): - if mode not in ('r', 'rb'): - raise IOError, "can't open files for writing in restricted mode" - return open(file, mode, buf) - - -def test(): - import traceback - r = RExec(None, '-v' in sys.argv[1:]) - print "*** RESTRICTED *** Python", sys.version - print sys.copyright - while 1: - try: - try: - s = raw_input('>>> ') - except EOFError: - print - break - if s and s[0] != '#': - s = s + '\n' - c = compile(s, '<stdin>', 'single') - r.r_exec(c) - except SystemExit, n: - sys.exit(n) - except: - traceback.print_exc() - - -if __name__ == '__main__': - test() diff --git a/Lib/rfc822.py b/Lib/rfc822.py deleted file mode 100644 index 64deaec2d9..0000000000 --- a/Lib/rfc822.py +++ /dev/null @@ -1,405 +0,0 @@ -# RFC-822 message manipulation class. -# -# XXX This is only a very rough sketch of a full RFC-822 parser; -# in particular the tokenizing of addresses does not adhere to all the -# quoting rules. -# -# Directions for use: -# -# To create a Message object: first open a file, e.g.: -# fp = open(file, 'r') -# (or use any other legal way of getting an open file object, e.g. use -# sys.stdin or call os.popen()). -# Then pass the open file object to the Message() constructor: -# m = Message(fp) -# -# To get the text of a particular header there are several methods: -# str = m.getheader(name) -# str = m.getrawheader(name) -# where name is the name of the header, e.g. 'Subject'. -# The difference is that getheader() strips the leading and trailing -# whitespace, while getrawheader() doesn't. Both functions retain -# embedded whitespace (including newlines) exactly as they are -# specified in the header, and leave the case of the text unchanged. -# -# For addresses and address lists there are functions -# realname, mailaddress = m.getaddr(name) and -# list = m.getaddrlist(name) -# where the latter returns a list of (realname, mailaddr) tuples. -# -# There is also a method -# time = m.getdate(name) -# which parses a Date-like field and returns a time-compatible tuple, -# i.e. a tuple such as returned by time.localtime() or accepted by -# time.mktime(). -# -# See the class definition for lower level access methods. -# -# There are also some utility functions here. - - -import regex -import string -import time - - -_blanklines = ('\r\n', '\n') # Optimization for islast() - - -class Message: - - # Initialize the class instance and read the headers. - - def __init__(self, fp, seekable = 1): - self.fp = fp - self.seekable = seekable - self.startofheaders = None - self.startofbody = None - # - if self.seekable: - try: - self.startofheaders = self.fp.tell() - except IOError: - self.seekable = 0 - # - self.readheaders() - # - if self.seekable: - try: - self.startofbody = self.fp.tell() - except IOError: - self.seekable = 0 - - - # Rewind the file to the start of the body (if seekable). - - def rewindbody(self): - if not self.seekable: - raise IOError, "unseekable file" - self.fp.seek(self.startofbody) - - - # Read header lines up to the entirely blank line that - # terminates them. The (normally blank) line that ends the - # headers is skipped, but not included in the returned list. - # If a non-header line ends the headers, (which is an error), - # an attempt is made to backspace over it; it is never - # included in the returned list. - # - # The variable self.status is set to the empty string if all - # went well, otherwise it is an error message. - # The variable self.headers is a completely uninterpreted list - # of lines contained in the header (so printing them will - # reproduce the header exactly as it appears in the file). - - def readheaders(self): - self.dict = {} - self.unixfrom = '' - self.headers = list = [] - self.status = '' - headerseen = "" - firstline = 1 - while 1: - line = self.fp.readline() - if not line: - self.status = 'EOF in headers' - break - # Skip unix From name time lines - if firstline and line[:5] == 'From ': - self.unixfrom = self.unixfrom + line - continue - firstline = 0 - if self.islast(line): - break - elif headerseen and line[0] in ' \t': - # It's a continuation line. - list.append(line) - x = (self.dict[headerseen] + "\n " + - string.strip(line)) - self.dict[headerseen] = string.strip(x) - elif ':' in line: - # It's a header line. - list.append(line) - i = string.find(line, ':') - headerseen = string.lower(line[:i]) - self.dict[headerseen] = string.strip( - line[i+1:]) - else: - # It's not a header line; stop here. - if not headerseen: - self.status = 'No headers' - else: - self.status = 'Bad header' - # Try to undo the read. - if self.seekable: - self.fp.seek(-len(line), 1) - else: - self.status = \ - self.status + '; bad seek' - break - - - # Method to determine whether a line is a legal end of - # RFC-822 headers. You may override this method if your - # application wants to bend the rules, e.g. to strip trailing - # whitespace, or to recognise MH template separators - # ('--------'). For convenience (e.g. for code reading from - # sockets) a line consisting of \r\n also matches. - - def islast(self, line): - return line in _blanklines - - - # Look through the list of headers and find all lines matching - # a given header name (and their continuation lines). - # A list of the lines is returned, without interpretation. - # If the header does not occur, an empty list is returned. - # If the header occurs multiple times, all occurrences are - # returned. Case is not important in the header name. - - def getallmatchingheaders(self, name): - name = string.lower(name) + ':' - n = len(name) - list = [] - hit = 0 - for line in self.headers: - if string.lower(line[:n]) == name: - hit = 1 - elif line[:1] not in string.whitespace: - hit = 0 - if hit: - list.append(line) - return list - - - # Similar, but return only the first matching header (and its - # continuation lines). - - def getfirstmatchingheader(self, name): - name = string.lower(name) + ':' - n = len(name) - list = [] - hit = 0 - for line in self.headers: - if hit: - if line[:1] not in string.whitespace: - break - elif string.lower(line[:n]) == name: - hit = 1 - if hit: - list.append(line) - return list - - - # A higher-level interface to getfirstmatchingheader(). - # Return a string containing the literal text of the header - # but with the keyword stripped. All leading, trailing and - # embedded whitespace is kept in the string, however. - # Return None if the header does not occur. - - def getrawheader(self, name): - list = self.getfirstmatchingheader(name) - if not list: - return None - list[0] = list[0][len(name) + 1:] - return string.joinfields(list, '') - - - # The normal interface: return a stripped version of the - # header value with a name, or None if it doesn't exist. This - # uses the dictionary version which finds the *last* such - # header. - - def getheader(self, name): - try: - return self.dict[string.lower(name)] - except KeyError: - return None - - - # Retrieve a single address from a header as a tuple, e.g. - # ('Guido van Rossum', 'guido@cwi.nl'). - - def getaddr(self, name): - try: - data = self[name] - except KeyError: - return None, None - return parseaddr(data) - - # Retrieve a list of addresses from a header, where each - # address is a tuple as returned by getaddr(). - - def getaddrlist(self, name): - # XXX This function is not really correct. The split - # on ',' might fail in the case of commas within - # quoted strings. - try: - data = self[name] - except KeyError: - return [] - data = string.splitfields(data, ',') - for i in range(len(data)): - data[i] = parseaddr(data[i]) - return data - - # Retrieve a date field from a header as a tuple compatible - # with time.mktime(). - - def getdate(self, name): - try: - data = self[name] - except KeyError: - return None - return parsedate(data) - - - # Access as a dictionary (only finds *last* header of each type): - - def __len__(self): - return len(self.dict) - - def __getitem__(self, name): - return self.dict[string.lower(name)] - - def has_key(self, name): - return self.dict.has_key(string.lower(name)) - - def keys(self): - return self.dict.keys() - - def values(self): - return self.dict.values() - - def items(self): - return self.dict.items() - - - -# Utility functions -# ----------------- - -# XXX Should fix these to be really conformant. -# XXX The inverses of the parse functions may also be useful. - - -# Remove quotes from a string. - -def unquote(str): - if len(str) > 1: - if str[0] == '"' and str[-1:] == '"': - return str[1:-1] - if str[0] == '<' and str[-1:] == '>': - return str[1:-1] - return str - - -# Parse an address into (name, address) tuple - -def parseaddr(address): - # This is probably not perfect - address = string.strip(address) - # Case 1: part of the address is in <xx@xx> form. - pos = regex.search('<.*>', address) - if pos >= 0: - name = address[:pos] - address = address[pos:] - length = regex.match('<.*>', address) - name = name + address[length:] - address = address[:length] - else: - # Case 2: part of the address is in (comment) form - pos = regex.search('(.*)', address) - if pos >= 0: - name = address[pos:] - address = address[:pos] - length = regex.match('(.*)', name) - address = address + name[length:] - name = name[:length] - else: - # Case 3: neither. Only an address - name = '' - name = string.strip(name) - address = string.strip(address) - if address and address[0] == '<' and address[-1] == '>': - address = address[1:-1] - if name and name[0] == '(' and name[-1] == ')': - name = name[1:-1] - return name, address - - -# Parse a date field - -_monthnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', - 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] - -def parsedate(data): - # XXX This still mostly ignores timezone matters at the moment... - data = string.split(data) - if data[0][-1] == ',': - # There's a dayname here. Skip it - del data[0] - if len(data) == 4: - s = data[3] - i = string.find(s, '+') - if i > 0: - data[3:] = [s[:i], s[i+1:]] - else: - data.append('') # Dummy tz - if len(data) < 5: - return None - data = data[:5] - [dd, mm, yy, tm, tz] = data - if not mm in _monthnames: - return None - mm = _monthnames.index(mm)+1 - tm = string.splitfields(tm, ':') - if len(tm) == 2: - [thh, tmm] = tm - tss = '0' - else: - [thh, tmm, tss] = tm - try: - yy = string.atoi(yy) - dd = string.atoi(dd) - thh = string.atoi(thh) - tmm = string.atoi(tmm) - tss = string.atoi(tss) - except string.atoi_error: - return None - tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0) - return tuple - - -# When used as script, run a small test program. -# The first command line argument must be a filename containing one -# message in RFC-822 format. - -if __name__ == '__main__': - import sys - file = '/ufs/guido/Mail/drafts/,1' - if sys.argv[1:]: file = sys.argv[1] - f = open(file, 'r') - m = Message(f) - print 'From:', m.getaddr('from') - print 'To:', m.getaddrlist('to') - print 'Subject:', m.getheader('subject') - print 'Date:', m.getheader('date') - date = m.getdate('date') - if date: - print 'ParsedDate:', time.asctime(date) - else: - print 'ParsedDate:', None - m.rewindbody() - n = 0 - while f.readline(): - n = n + 1 - print 'Lines:', n - print '-'*70 - print 'len =', len(m) - if m.has_key('Date'): print 'Date =', m['Date'] - if m.has_key('X-Nonsense'): pass - print 'keys =', m.keys() - print 'values =', m.values() - print 'items =', m.items() - diff --git a/Lib/sched.py b/Lib/sched.py deleted file mode 100644 index 60b0a1bacf..0000000000 --- a/Lib/sched.py +++ /dev/null @@ -1,99 +0,0 @@ -# Module sched -- a generally useful event scheduler class - -# Each instance of this class manages its own queue. -# No multi-threading is implied; you are supposed to hack that -# yourself, or use a single instance per application. -# -# Each instance is parametrized with two functions, one that is -# supposed to return the current time, one that is supposed to -# implement a delay. You can implement real-time scheduling by -# substituting time and sleep from built-in module time, or you can -# implement simulated time by writing your own functions. This can -# also be used to integrate scheduling with STDWIN events; the delay -# function is allowed to modify the queue. Time can be expressed as -# integers or floating point numbers, as long as it is consistent. - -# Events are specified by tuples (time, priority, action, argument). -# As in UNIX, lower priority numbers mean higher priority; in this -# way the queue can be maintained fully sorted. Execution of the -# event means calling the action function, passing it the argument. -# Remember that in Python, multiple function arguments can be packed -# in a tuple. The action function may be an instance method so it -# has another way to reference private data (besides global variables). -# Parameterless functions or methods cannot be used, however. - -# XXX The timefunc and delayfunc should have been defined as methods -# XXX so you can define new kinds of schedulers using subclassing -# XXX instead of having to define a module or class just to hold -# XXX the global state of your particular time and delay functtions. - -import bisect - -class scheduler: - # - # Initialize a new instance, passing the time and delay functions - # - def __init__(self, timefunc, delayfunc): - self.queue = [] - self.timefunc = timefunc - self.delayfunc = delayfunc - # - # Enter a new event in the queue at an absolute time. - # Returns an ID for the event which can be used - # to remove it, if necessary. - # - def enterabs(self, time, priority, action, argument): - event = time, priority, action, argument - bisect.insort(self.queue, event) - return event # The ID - # - # A variant that specifies the time as a relative time. - # This is actually the more commonly used interface. - # - def enter(self, delay, priority, action, argument): - time = self.timefunc() + delay - return self.enterabs(time, priority, action, argument) - # - # Remove an event from the queue. - # This must be presented the ID as returned by enter(). - # If the event is not in the queue, this raises RuntimeError. - # - def cancel(self, event): - self.queue.remove(event) - # - # Check whether the queue is empty. - # - def empty(self): - return len(self.queue) == 0 - # - # Run: execute events until the queue is empty. - # - # When there is a positive delay until the first event, the - # delay function is called and the event is left in the queue; - # otherwise, the event is removed from the queue and executed - # (its action function is called, passing it the argument). - # If the delay function returns prematurely, it is simply - # restarted. - # - # It is legal for both the delay function and the action - # function to to modify the queue or to raise an exception; - # exceptions are not caught but the scheduler's state - # remains well-defined so run() may be called again. - # - # A questionably hack is added to allow other threads to run: - # just after an event is executed, a delay of 0 is executed, - # to avoid monopolizing the CPU when other threads are also - # runnable. - # - def run(self): - q = self.queue - while q: - time, priority, action, argument = q[0] - now = self.timefunc() - if now < time: - self.delayfunc(time - now) - else: - del q[0] - void = apply(action, argument) - self.delayfunc(0) # Let other threads run - # diff --git a/Lib/sgmllib.py b/Lib/sgmllib.py deleted file mode 100644 index 304bbdbff0..0000000000 --- a/Lib/sgmllib.py +++ /dev/null @@ -1,446 +0,0 @@ -# A parser for SGML, using the derived class as static DTD. - -# XXX This only supports those SGML features used by HTML. - -# XXX There should be a way to distinguish between PCDATA (parsed -# character data -- the normal case), RCDATA (replaceable character -# data -- only char and entity references and end tags are special) -# and CDATA (character data -- only end tags are special). - - -import regex -import string - - -# Regular expressions used for parsing - -interesting = regex.compile('[&<]') -incomplete = regex.compile('&\([a-zA-Z][a-zA-Z0-9]*\|#[0-9]*\)?\|' - '<\([a-zA-Z][^<>]*\|' - '/\([a-zA-Z][^<>]*\)?\|' - '![^<>]*\)?') - -entityref = regex.compile('&\([a-zA-Z][a-zA-Z0-9]*\)[^a-zA-Z0-9]') -charref = regex.compile('&#\([0-9]+\)[^0-9]') - -starttagopen = regex.compile('<[>a-zA-Z]') -shorttagopen = regex.compile('<[a-zA-Z][a-zA-Z0-9]*/') -shorttag = regex.compile('<\([a-zA-Z][a-zA-Z0-9]*\)/\([^/]*\)/') -endtagopen = regex.compile('</[<>a-zA-Z]') -endbracket = regex.compile('[<>]') -special = regex.compile('<![^<>]*>') -commentopen = regex.compile('<!--') -commentclose = regex.compile('--[ \t\n]*>') -tagfind = regex.compile('[a-zA-Z][a-zA-Z0-9]*') -attrfind = regex.compile( - '[ \t\n]+\([a-zA-Z_][a-zA-Z_0-9]*\)' - '\([ \t\n]*=[ \t\n]*' - '\(\'[^\']*\'\|"[^"]*"\|[-a-zA-Z0-9./:+*%?!()_#=~]*\)\)?') - - -# SGML parser base class -- find tags and call handler functions. -# Usage: p = SGMLParser(); p.feed(data); ...; p.close(). -# The dtd is defined by deriving a class which defines methods -# with special names to handle tags: start_foo and end_foo to handle -# <foo> and </foo>, respectively, or do_foo to handle <foo> by itself. -# (Tags are converted to lower case for this purpose.) The data -# between tags is passed to the parser by calling self.handle_data() -# with some data as argument (the data may be split up in arbutrary -# chunks). Entity references are passed by calling -# self.handle_entityref() with the entity reference as argument. - -class SGMLParser: - - # Interface -- initialize and reset this instance - def __init__(self, verbose=0): - self.verbose = verbose - self.reset() - - # Interface -- reset this instance. Loses all unprocessed data - def reset(self): - self.rawdata = '' - self.stack = [] - self.lasttag = '???' - self.nomoretags = 0 - self.literal = 0 - - # For derived classes only -- enter literal mode (CDATA) till EOF - def setnomoretags(self): - self.nomoretags = self.literal = 1 - - # For derived classes only -- enter literal mode (CDATA) - def setliteral(self, *args): - self.literal = 1 - - # Interface -- feed some data to the parser. Call this as - # often as you want, with as little or as much text as you - # want (may include '\n'). (This just saves the text, all the - # processing is done by goahead().) - def feed(self, data): - self.rawdata = self.rawdata + data - self.goahead(0) - - # Interface -- handle the remaining data - def close(self): - self.goahead(1) - - # Internal -- handle data as far as reasonable. May leave state - # and data to be processed by a subsequent call. If 'end' is - # true, force handling all data as if followed by EOF marker. - def goahead(self, end): - rawdata = self.rawdata - i = 0 - n = len(rawdata) - while i < n: - if self.nomoretags: - self.handle_data(rawdata[i:n]) - i = n - break - j = interesting.search(rawdata, i) - if j < 0: j = n - if i < j: self.handle_data(rawdata[i:j]) - i = j - if i == n: break - if rawdata[i] == '<': - if starttagopen.match(rawdata, i) >= 0: - if self.literal: - self.handle_data(rawdata[i]) - i = i+1 - continue - k = self.parse_starttag(i) - if k < 0: break - i = k - continue - if endtagopen.match(rawdata, i) >= 0: - k = self.parse_endtag(i) - if k < 0: break - i = k - self.literal = 0 - continue - if commentopen.match(rawdata, i) >= 0: - if self.literal: - self.handle_data(rawdata[i]) - i = i+1 - continue - k = self.parse_comment(i) - if k < 0: break - i = i+k - continue - k = special.match(rawdata, i) - if k >= 0: - if self.literal: - self.handle_data(rawdata[i]) - i = i+1 - continue - i = i+k - continue - elif rawdata[i] == '&': - k = charref.match(rawdata, i) - if k >= 0: - k = i+k - if rawdata[k-1] != ';': k = k-1 - name = charref.group(1) - self.handle_charref(name) - i = k - continue - k = entityref.match(rawdata, i) - if k >= 0: - k = i+k - if rawdata[k-1] != ';': k = k-1 - name = entityref.group(1) - self.handle_entityref(name) - i = k - continue - else: - raise RuntimeError, 'neither < nor & ??' - # We get here only if incomplete matches but - # nothing else - k = incomplete.match(rawdata, i) - if k < 0: - self.handle_data(rawdata[i]) - i = i+1 - continue - j = i+k - if j == n: - break # Really incomplete - self.handle_data(rawdata[i:j]) - i = j - # end while - if end and i < n: - self.handle_data(rawdata[i:n]) - i = n - self.rawdata = rawdata[i:] - # XXX if end: check for empty stack - - # Internal -- parse comment, return length or -1 if not terminated - def parse_comment(self, i): - rawdata = self.rawdata - if rawdata[i:i+4] <> '<!--': - raise RuntimeError, 'unexpected call to handle_comment' - j = commentclose.search(rawdata, i+4) - if j < 0: - return -1 - self.handle_comment(rawdata[i+4: j]) - j = j+commentclose.match(rawdata, j) - return j-i - - # Internal -- handle starttag, return length or -1 if not terminated - def parse_starttag(self, i): - rawdata = self.rawdata - if shorttagopen.match(rawdata, i) >= 0: - # SGML shorthand: <tag/data/ == <tag>data</tag> - # XXX Can data contain &... (entity or char refs)? - # XXX Can data contain < or > (tag characters)? - # XXX Can there be whitespace before the first /? - j = shorttag.match(rawdata, i) - if j < 0: - return -1 - tag, data = shorttag.group(1, 2) - tag = string.lower(tag) - self.finish_shorttag(tag, data) - k = i+j - if rawdata[k-1] == '<': - k = k-1 - return k - # XXX The following should skip matching quotes (' or ") - j = endbracket.search(rawdata, i+1) - if j < 0: - return -1 - # Now parse the data between i+1 and j into a tag and attrs - attrs = [] - if rawdata[i:i+2] == '<>': - # SGML shorthand: <> == <last open tag seen> - k = j - tag = self.lasttag - else: - k = tagfind.match(rawdata, i+1) - if k < 0: - raise RuntimeError, 'unexpected call to parse_starttag' - k = i+1+k - tag = string.lower(rawdata[i+1:k]) - self.lasttag = tag - while k < j: - l = attrfind.match(rawdata, k) - if l < 0: break - attrname, rest, attrvalue = attrfind.group(1, 2, 3) - if not rest: - attrvalue = attrname - elif attrvalue[:1] == '\'' == attrvalue[-1:] or \ - attrvalue[:1] == '"' == attrvalue[-1:]: - attrvalue = attrvalue[1:-1] - attrs.append((string.lower(attrname), attrvalue)) - k = k + l - if rawdata[j] == '>': - j = j+1 - self.finish_starttag(tag, attrs) - return j - - # Internal -- parse endtag - def parse_endtag(self, i): - rawdata = self.rawdata - j = endbracket.search(rawdata, i+1) - if j < 0: - return -1 - tag = string.lower(string.strip(rawdata[i+2:j])) - if rawdata[j] == '>': - j = j+1 - self.finish_endtag(tag) - return j - - # Internal -- finish parsing of <tag/data/ (same as <tag>data</tag>) - def finish_shorttag(self, tag, data): - self.finish_starttag(tag, []) - self.handle_data(data) - self.finish_endtag(tag) - - # Internal -- finish processing of start tag - # Return -1 for unknown tag, 0 for open-only tag, 1 for balanced tag - def finish_starttag(self, tag, attrs): - try: - method = getattr(self, 'start_' + tag) - except AttributeError: - try: - method = getattr(self, 'do_' + tag) - except AttributeError: - self.unknown_starttag(tag, attrs) - return -1 - else: - self.handle_starttag(tag, method, attrs) - return 0 - else: - self.stack.append(tag) - self.handle_starttag(tag, method, attrs) - return 1 - - # Internal -- finish processing of end tag - def finish_endtag(self, tag): - if not tag: - found = len(self.stack) - 1 - if found < 0: - self.unknown_endtag(tag) - return - else: - if tag not in self.stack: - try: - method = getattr(self, 'end_' + tag) - except AttributeError: - self.unknown_endtag(tag) - return - found = len(self.stack) - for i in range(found): - if self.stack[i] == tag: found = i - while len(self.stack) > found: - tag = self.stack[-1] - try: - method = getattr(self, 'end_' + tag) - except AttributeError: - method = None - if method: - self.handle_endtag(tag, method) - else: - self.unknown_endtag(tag) - del self.stack[-1] - - # Overridable -- handle start tag - def handle_starttag(self, tag, method, attrs): - method(attrs) - - # Overridable -- handle end tag - def handle_endtag(self, tag, method): - method() - - # Example -- report an unbalanced </...> tag. - def report_unbalanced(self, tag): - if self.verbose: - print '*** Unbalanced </' + tag + '>' - print '*** Stack:', self.stack - - # Example -- handle character reference, no need to override - def handle_charref(self, name): - try: - n = string.atoi(name) - except string.atoi_error: - self.unknown_charref(name) - return - if not 0 <= n <= 255: - self.unknown_charref(name) - return - self.handle_data(chr(n)) - - # Definition of entities -- derived classes may override - entitydefs = \ - {'lt': '<', 'gt': '>', 'amp': '&', 'quot': '"', 'apos': '\''} - - # Example -- handle entity reference, no need to override - def handle_entityref(self, name): - table = self.entitydefs - if table.has_key(name): - self.handle_data(table[name]) - else: - self.unknown_entityref(name) - return - - # Example -- handle data, should be overridden - def handle_data(self, data): - pass - - # Example -- handle comment, could be overridden - def handle_comment(self, data): - pass - - # To be overridden -- handlers for unknown objects - def unknown_starttag(self, tag, attrs): pass - def unknown_endtag(self, tag): pass - def unknown_charref(self, ref): pass - def unknown_entityref(self, ref): pass - - -class TestSGMLParser(SGMLParser): - - def __init__(self, verbose=0): - self.testdata = "" - SGMLParser.__init__(self, verbose) - - def handle_data(self, data): - self.testdata = self.testdata + data - if len(`self.testdata`) >= 70: - self.flush() - - def flush(self): - data = self.testdata - if data: - self.testdata = "" - print 'data:', `data` - - def handle_comment(self, data): - self.flush() - r = `data` - if len(r) > 68: - r = r[:32] + '...' + r[-32:] - print 'comment:', r - - def unknown_starttag(self, tag, attrs): - self.flush() - if not attrs: - print 'start tag: <' + tag + '>' - else: - print 'start tag: <' + tag, - for name, value in attrs: - print name + '=' + '"' + value + '"', - print '>' - - def unknown_endtag(self, tag): - self.flush() - print 'end tag: </' + tag + '>' - - def unknown_entityref(self, ref): - self.flush() - print '*** unknown entity ref: &' + ref + ';' - - def unknown_charref(self, ref): - self.flush() - print '*** unknown char ref: &#' + ref + ';' - - def close(self): - SGMLParser.close(self) - self.flush() - - -def test(args = None): - import sys - - if not args: - args = sys.argv[1:] - - if args and args[0] == '-s': - args = args[1:] - klass = SGMLParser - else: - klass = TestSGMLParser - - if args: - file = args[0] - else: - file = 'test.html' - - if file == '-': - f = sys.stdin - else: - try: - f = open(file, 'r') - except IOError, msg: - print file, ":", msg - sys.exit(1) - - data = f.read() - if f is not sys.stdin: - f.close() - - x = klass() - for c in data: - x.feed(c) - x.close() - - -if __name__ == '__main__': - test() diff --git a/Lib/shelve.py b/Lib/shelve.py deleted file mode 100644 index 18aa905a9a..0000000000 --- a/Lib/shelve.py +++ /dev/null @@ -1,136 +0,0 @@ -"""Manage shelves of pickled objects. - -A "shelf" is a persistent, dictionary-like object. The difference -with dbm databases is that the values (not the keys!) in a shelf can -be essentially arbitrary Python objects -- anything that the "pickle" -module can handle. This includes most class instances, recursive data -types, and objects containing lots of shared sub-objects. The keys -are ordinary strings. - -To summarize the interface (key is a string, data is an arbitrary -object): - - import shelve - d = shelve.open(filename) # open, with (g)dbm filename -- no suffix - - d[key] = data # store data at key (overwrites old data if - # using an existing key) - data = d[key] # retrieve data at key (raise KeyError if no - # such key) - del d[key] # delete data stored at key (raises KeyError - # if no such key) - flag = d.has_key(key) # true if the key exists - list = d.keys() # a list of all existing keys (slow!) - - d.close() # close it - -Dependent on the implementation, closing a persistent dictionary may -or may not be necessary to flush changes to disk. -""" - -import pickle -import StringIO - - -class Shelf: - """Base class for shelf implementations. - - This is initialized with a dictionary-like object. - See the module's __doc__ string for an overview of the interface. - """ - - def __init__(self, dict): - self.dict = dict - - def keys(self): - return self.dict.keys() - - def __len__(self): - return self.dict.len() - - def has_key(self, key): - return self.dict.has_key(key) - - def __getitem__(self, key): - f = StringIO.StringIO(self.dict[key]) - return pickle.Unpickler(f).load() - - def __setitem__(self, key, value): - f = StringIO.StringIO() - p = pickle.Pickler(f) - p.dump(value) - self.dict[key] = f.getvalue() - - def __delitem__(self, key): - del self.dict[key] - - def close(self): - if hasattr(self.dict, 'close'): - self.dict.close() - self.dict = None - - def __del__(self): - self.close() - - -class BsdDbShelf(Shelf): - """Shelf implementation using the "BSD" db interface. - - The actual database is opened using one of thethe "bsddb" modules - "open" routines (i.e. bsddb.hashopen, bsddb.btopen or bsddb.rnopen.) - - This class is initialized with the the database object - returned from one of the bsddb open functions. - - See the module's __doc__ string for an overview of the interface. - """ - - def __init__(self, dict): - Shelf.__init__(self, dict) - - def set_location(self, key): - (key, value) = self.dict.set_location(key) - f = StringIO.StringIO(value) - return (key, pickle.Unpickler(f).load()) - - def next(self): - (key, value) = self.dict.next() - f = StringIO.StringIO(value) - return (key, pickle.Unpickler(f).load()) - - def previous(self): - (key, value) = self.dict.previous() - f = StringIO.StringIO(value) - return (key, pickle.Unpickler(f).load()) - - def first(self): - (key, value) = self.dict.first() - f = StringIO.StringIO(value) - return (key, pickle.Unpickler(f).load()) - - def last(self): - (key, value) = self.dict.last() - f = StringIO.StringIO(value) - return (key, pickle.Unpickler(f).load()) - - -class DbfilenameShelf(Shelf): - """Shelf implementation using the "anydbm" generic dbm interface. - - This is initialized with the filename for the dbm database. - See the module's __doc__ string for an overview of the interface. - """ - - def __init__(self, filename, flag='c'): - import anydbm - Shelf.__init__(self, anydbm.open(filename, flag)) - - -def open(filename, flag='c'): - """Open a persistent dictionary for reading and writing. - - Argument is the filename for the dbm database. - See the module's __doc__ string for an overview of the interface. - """ - - return DbfilenameShelf(filename, flag) diff --git a/Lib/shutil.py b/Lib/shutil.py deleted file mode 100644 index dba4ee161c..0000000000 --- a/Lib/shutil.py +++ /dev/null @@ -1,69 +0,0 @@ -# Module 'shutil' -- utility functions usable in a shell-like program - -import os - -MODEBITS = 010000 # Lower 12 mode bits -# Change this to 01000 (9 mode bits) to avoid copying setuid etc. - -# Copy data from src to dst -# -def copyfile(src, dst): - fsrc = open(src, 'r') - fdst = open(dst, 'w') - while 1: - buf = fsrc.read(16*1024) - if not buf: break - fdst.write(buf) - -# Copy mode bits from src to dst -# -def copymode(src, dst): - st = os.stat(src) - mode = divmod(st[0], MODEBITS)[1] - os.chmod(dst, mode) - -# Copy all stat info (mode bits, atime and mtime) from src to dst -# -def copystat(src, dst): - st = os.stat(src) - mode = divmod(st[0], MODEBITS)[1] - os.chmod(dst, mode) - os.utime(dst, st[7:9]) - -# Copy data and mode bits ("cp src dst") -# -def copy(src, dst): - copyfile(src, dst) - copymode(src, dst) - -# Copy data and all stat info ("cp -p src dst") -# -def copy2(src, dst): - copyfile(src, dst) - copystat(src, dst) - -# Recursively copy a directory tree. -# The destination must not already exist. -# -def copytree(src, dst): - names = os.listdir(src) - os.mkdir(dst, 0777) - dot_dotdot = (os.curdir, os.pardir) - for name in names: - if name not in dot_dotdot: - srcname = os.path.join(src, name) - dstname = os.path.join(dst, name) - #print 'Copying', srcname, 'to', dstname - try: - #if os.path.islink(srcname): - # linkto = os.readlink(srcname) - # os.symlink(linkto, dstname) - #elif os.path.isdir(srcname): - if os.path.isdir(srcname): - copytree(srcname, dstname) - else: - copy2(srcname, dstname) - # XXX What about devices, sockets etc.? - except os.error, why: - print 'Could not copy', srcname, 'to', dstname, - print '(', why[1], ')' diff --git a/Lib/sndhdr.py b/Lib/sndhdr.py deleted file mode 100644 index b7b349c5ba..0000000000 --- a/Lib/sndhdr.py +++ /dev/null @@ -1,270 +0,0 @@ -# This module contains several routines that help recognizing sound -# files. -# -# Function whathdr() recognizes various types of sound file headers. -# It understands almost all headers that SOX can decode. -# -# The return tuple contains the following items, in this order: -# - file type (as SOX understands it) -# - sampling rate (0 if unknown or hard to decode) -# - number of channels (0 if unknown or hard to decode) -# - number of frames in the file (-1 if unknown or hard to decode) -# - number of bits/sample, or 'U' for U-LAW, or 'A' for A-LAW -# -# If the file doesn't have a recognizable type, it returns None. -# If the file can't be opened, IOError is raised. -# -# To compute the total time, divide the number of frames by the -# sampling rate (a frame contains a sample for each channel). -# -# Function whatraw() calls the "whatsound" program and interprets its -# output. You'll have to guess the sampling rate by listening though! -# -# Function what() calls whathdr() and if it doesn't recognize the file -# then calls whatraw(). -# -# Finally, the function test() is a simple main program that calls -# what() for all files mentioned on the argument list. For directory -# arguments it calls what() for all files in that directory. Default -# argument is "." (testing all files in the current directory). The -# option -r tells it to recurse down directories found inside -# explicitly given directories. -# -# The file structure is top-down except that the test program and its -# subroutine come last. - - -#------------------------------------------------------# -# Guess the type of any sound file, raw or with header # -#------------------------------------------------------# - -def what(filename): - res = whathdr(filename) - if not res: - res = whatraw(filename) - return res - - -#-----------------------------# -# Guess the type of raw sound # -#-----------------------------# - -def whatraw(filename): - # Assume it's always 1 channel, byte-sized samples - # Don't assume anything about the rate - import os - from stat import ST_SIZE - # XXX "whatsound" should be part of the distribution somehow... - cmd = 'whatsound ' + filename + ' 2>/dev/null' - cmd = 'PATH=$PATH:/ufs/guido/bin/sgi\n' + cmd - pipe = os.popen(cmd, 'r') - data = pipe.read() - sts = pipe.close() - if sts: - return None - if data[:13] == '-t raw -b -s ': - type = 'sb' - sample_size = 8 - elif data[:13] == '-t raw -b -u ': - type = 'ub' - sample_size = 8 - elif data[:13] == '-t raw -b -U ': - type = 'ul' - sample_size = 'U' - else: - return None - try: - frame_count = os.stat(filename)[ST_SIZE] - except IOError: - frame_count = -1 - return type, 0, 1, frame_count, sample_size - - -#-------------------------# -# Recognize sound headers # -#-------------------------# - -def whathdr(filename): - f = open(filename, 'r') - h = f.read(512) - for tf in tests: - res = tf(h, f) - if res: - return res - return None - - -#-----------------------------------# -# Subroutines per sound header type # -#-----------------------------------# - -tests = [] - -def test_aifc(h, f): - import aifc - if h[:4] <> 'FORM': - return None - if h[8:12] == 'AIFC': - fmt = 'aifc' - elif h[8:12] == 'AIFF': - fmt = 'aiff' - else: - return None - f.seek(0) - try: - a = aifc.openfp(f, 'r') - except (EOFError, aifc.Error): - return None - return (fmt, a.getframerate(), a.getnchannels(), \ - a.getnframes(), 8*a.getsampwidth()) - -tests.append(test_aifc) - - -def test_au(h, f): - if h[:4] == '.snd': - f = get_long_be - elif h[:4] in ('\0ds.', 'dns.'): - f = get_long_le - else: - return None - type = 'au' - hdr_size = f(h[4:8]) - data_size = f(h[8:12]) - encoding = f(h[12:16]) - rate = f(h[16:20]) - nchannels = f(h[20:24]) - sample_size = 1 # default - if encoding == 1: - sample_bits = 'U' - elif encoding == 2: - sample_bits = 8 - elif encoding == 3: - sample_bits = 16 - sample_size = 2 - else: - sample_bits = '?' - frame_size = sample_size * nchannels - return type, rate, nchannels, data_size/frame_size, sample_bits - -tests.append(test_au) - - -def test_hcom(h, f): - if h[65:69] <> 'FSSD' or h[128:132] <> 'HCOM': - return None - divisor = get_long_be(h[128+16:128+20]) - return 'hcom', 22050/divisor, 1, -1, 8 - -tests.append(test_hcom) - - -def test_voc(h, f): - if h[:20] <> 'Creative Voice File\032': - return None - sbseek = get_short_le(h[20:22]) - rate = 0 - if 0 <= sbseek < 500 and h[sbseek] == '\1': - ratecode = ord(h[sbseek+4]) - rate = int(1000000.0 / (256 - ratecode)) - return 'voc', rate, 1, -1, 8 - -tests.append(test_voc) - - -def test_wav(h, f): - # 'RIFF' <len> 'WAVE' 'fmt ' <len> - if h[:4] <> 'RIFF' or h[8:12] <> 'WAVE' or h[12:16] <> 'fmt ': - return None - style = get_short_le(h[20:22]) - nchannels = get_short_le(h[22:24]) - rate = get_long_le(h[24:28]) - sample_bits = get_short_le(h[34:36]) - return 'wav', rate, nchannels, -1, sample_bits - -tests.append(test_wav) - - -def test_8svx(h, f): - if h[:4] <> 'FORM' or h[8:12] <> '8SVX': - return None - # Should decode it to get #channels -- assume always 1 - return '8svx', 0, 1, 0, 8 - -tests.append(test_8svx) - - -def test_sndt(h, f): - if h[:5] == 'SOUND': - nsamples = get_long_le(h[8:12]) - rate = get_short_le(h[20:22]) - return 'sndt', rate, 1, nsamples, 8 - -tests.append(test_sndt) - - -def test_sndr(h, f): - if h[:2] == '\0\0': - rate = get_short_le(h[2:4]) - if 4000 <= rate <= 25000: - return 'sndr', rate, 1, -1, 8 - -tests.append(test_sndr) - - -#---------------------------------------------# -# Subroutines to extract numbers from strings # -#---------------------------------------------# - -def get_long_be(s): - return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3]) - -def get_long_le(s): - return (ord(s[3])<<24) | (ord(s[2])<<16) | (ord(s[1])<<8) | ord(s[0]) - -def get_short_be(s): - return (ord(s[0])<<8) | ord(s[1]) - -def get_short_le(s): - return (ord(s[1])<<8) | ord(s[0]) - - -#--------------------# -# Small test program # -#--------------------# - -def test(): - import sys - recursive = 0 - if sys.argv[1:] and sys.argv[1] == '-r': - del sys.argv[1:2] - recursive = 1 - try: - if sys.argv[1:]: - testall(sys.argv[1:], recursive, 1) - else: - testall(['.'], recursive, 1) - except KeyboardInterrupt: - sys.stderr.write('\n[Interrupted]\n') - sys.exit(1) - -def testall(list, recursive, toplevel): - import sys - import os - for filename in list: - if os.path.isdir(filename): - print filename + '/:', - if recursive or toplevel: - print 'recursing down:' - import glob - names = glob.glob(os.path.join(filename, '*')) - testall(names, recursive, 0) - else: - print '*** directory (use -r) ***' - else: - print filename + ':', - sys.stdout.flush() - try: - print what(filename) - except IOError: - print '*** not found ***' diff --git a/Lib/stat.py b/Lib/stat.py deleted file mode 100644 index 5f6f522dc2..0000000000 --- a/Lib/stat.py +++ /dev/null @@ -1,88 +0,0 @@ -# Module 'stat' -# -# Defines constants and functions for interpreting stat/lstat struct -# as returned by os.stat() and os.lstat() (if it exists). -# -# Suggested usage: from stat import * -# -# XXX Strictly spoken, this module may have to be adapted for each POSIX -# implementation; in practice, however, the numeric constants used by -# stat() are almost universal (even for stat() emulations on non-UNIX -# systems like MS-DOS). - -# Indices for stat struct members in tuple returned by os.stat() - -ST_MODE = 0 -ST_INO = 1 -ST_DEV = 2 -ST_NLINK = 3 -ST_UID = 4 -ST_GID = 5 -ST_SIZE = 6 -ST_ATIME = 7 -ST_MTIME = 8 -ST_CTIME = 9 - -# Extract bits from the mode - -def S_IMODE(mode): - return mode & 07777 - -def S_IFMT(mode): - return mode & 0170000 - -# Constants used as S_IFMT() for various file types -# (not all are implemented on all systems) - -S_IFDIR = 0040000 -S_IFCHR = 0020000 -S_IFBLK = 0060000 -S_IFREG = 0100000 -S_IFIFO = 0010000 -S_IFLNK = 0120000 -S_IFSOCK = 0140000 - -# Functions to test for each file type - -def S_ISDIR(mode): - return S_IFMT(mode) == S_IFDIR - -def S_ISCHR(mode): - return S_IFMT(mode) == S_IFCHR - -def S_ISBLK(mode): - return S_IFMT(mode) == S_IFBLK - -def S_ISREG(mode): - return S_IFMT(mode) == S_IFREG - -def S_ISFIFO(mode): - return S_IFMT(mode) == S_IFIFO - -def S_ISLNK(mode): - return S_IFMT(mode) == S_IFLNK - -def S_ISSOCK(mode): - return S_IFMT(mode) == S_IFSOCK - -# Names for permission bits - -S_ISUID = 04000 -S_ISGID = 02000 -S_ENFMT = S_ISGID -S_ISVTX = 01000 -S_IREAD = 00400 -S_IWRITE = 00200 -S_IEXEC = 00100 -S_IRWXU = 00700 -S_IRUSR = 00400 -S_IWUSR = 00200 -S_IXUSR = 00100 -S_IRWXG = 00070 -S_IRGRP = 00040 -S_IWGRP = 00020 -S_IXGRP = 00010 -S_IRWXO = 00007 -S_IROTH = 00004 -S_IWOTH = 00002 -S_IXOTH = 00001 diff --git a/Lib/statcache.py b/Lib/statcache.py deleted file mode 100644 index 770aef0662..0000000000 --- a/Lib/statcache.py +++ /dev/null @@ -1,82 +0,0 @@ -# Module 'statcache' -# -# Maintain a cache of file stats. -# There are functions to reset the cache or to selectively remove items. - -import os -from stat import * - -# The cache. -# Keys are pathnames, values are `os.stat' outcomes. -# -cache = {} - - -# Stat a file, possibly out of the cache. -# -def stat(path): - if cache.has_key(path): - return cache[path] - cache[path] = ret = os.stat(path) - return ret - - -# Reset the cache completely. -# -def reset(): - global cache - cache = {} - - -# Remove a given item from the cache, if it exists. -# -def forget(path): - if cache.has_key(path): - del cache[path] - - -# Remove all pathnames with a given prefix. -# -def forget_prefix(prefix): - n = len(prefix) - for path in cache.keys(): - if path[:n] == prefix: - del cache[path] - - -# Forget about a directory and all entries in it, but not about -# entries in subdirectories. -# -def forget_dir(prefix): - if prefix[-1:] == '/' and prefix <> '/': - prefix = prefix[:-1] - forget(prefix) - if prefix[-1:] <> '/': - prefix = prefix + '/' - n = len(prefix) - for path in cache.keys(): - if path[:n] == prefix: - rest = path[n:] - if rest[-1:] == '/': rest = rest[:-1] - if '/' not in rest: - del cache[path] - - -# Remove all pathnames except with a given prefix. -# Normally used with prefix = '/' after a chdir(). -# -def forget_except_prefix(prefix): - n = len(prefix) - for path in cache.keys(): - if path[:n] <> prefix: - del cache[path] - - -# Check for directory. -# -def isdir(path): - try: - st = stat(path) - except os.error: - return 0 - return S_ISDIR(st[ST_MODE]) diff --git a/Lib/stdwin/Abstract.py b/Lib/stdwin/Abstract.py deleted file mode 100755 index 51bd305a86..0000000000 --- a/Lib/stdwin/Abstract.py +++ /dev/null @@ -1,63 +0,0 @@ -# Abstract classes for parents and children. -# -# Do not use as base class -- this is for documentation only. -# -# Note that the tree must be built top down (create the parent, -# then add the children). -# -# Also note that the creation methods are not standardized -- -# these have extra parameters dependent on the widget type. -# For historical reasons, button creation methods are called -# define() while split creation methods are called create(). - -class AbstractParent: - # - # Upcalls from child to parent - # - def addchild(self, child): unimpl() - def delchild(self, child): unimpl() - # - def need_mouse(self, child): unimpl() - def no_mouse(self, child): unimpl() - # - def need_timer(self, child): unimpl() - def no_timer(self, child): unimpl() - # - # XXX need_kbd, no_kbd; focus??? - # - def begindrawing(self): return unimpl() - def beginmeasuring(self): return unimpl() - def getwindow(self): return unimpl() # Only for very special cases - # - def change(self, area): unimpl() - def scroll(self, area, (dh, dv)): unimpl() - def settimer(self, itimer): unimpl() - -class AbstractChild: - # - # Downcalls from parent to child - # - def destroy(self): unimpl() - # - def realize(self): return unimpl() - def getminsize(self, m, (width, height)): return unimpl() - def getbounds(self): return unimpl() - def setbounds(self, bounds): unimpl() - def draw(self, d, area): unimpl() - # - # Downcalls only made after certain upcalls - # - def mouse_down(self, detail): unimpl() - def mouse_move(self, detail): unimpl() - def mouse_up(self, detail): unimpl() - # - def timer(self): unimpl() - -# A "Split" is a child that manages one or more children. -# (This terminology is due to DEC SRC, except for CSplits.) -# A child of a split may be another split, a button, a slider, etc. -# Certain upcalls and downcalls can be handled transparently, but -# for others (e.g., all geometry related calls) this is not possible. - -class AbstractSplit(AbstractChild, AbstractParent): - pass diff --git a/Lib/stdwin/BoxParent.py b/Lib/stdwin/BoxParent.py deleted file mode 100755 index c792731c5b..0000000000 --- a/Lib/stdwin/BoxParent.py +++ /dev/null @@ -1,40 +0,0 @@ -from TransParent import TransParent - -class BoxParent(TransParent): - # - def create(self, parent, (dh, dv)): - self = TransParent.create(self, parent) - self.dh = dh - self.dv = dv - return self - # - def getminsize(self, m, (width, height)): - width = max(0, width - 2*self.dh) - height = max(0, height - 2*self.dv) - width, height = self.child.getminsize(m, (width, height)) - return width + 2*self.dh, height + 2*self.dv - # - def setbounds(self, bounds): - (left, top), (right, bottom) = bounds - self.bounds = bounds - left = min(right, left + self.dh) - top = min(bottom, top + self.dv) - right = max(left, right - self.dh) - bottom = max(top, bottom - self.dv) - self.innerbounds = (left, top), (right, bottom) - self.child.setbounds(self.innerbounds) - # - def getbounds(self): - return self.bounds - # - def draw(self, d, area): - (left, top), (right, bottom) = self.bounds - left = left + 1 - top = top + 1 - right = right - 1 - bottom = bottom - 1 - d.box((left, top), (right, bottom)) - TransParent.draw(self, d, area) # XXX clip to innerbounds? - # - # XXX should scroll clip to innerbounds??? - # XXX currently the only user restricts itself to child's bounds diff --git a/Lib/stdwin/Buttons.py b/Lib/stdwin/Buttons.py deleted file mode 100755 index 9a9970789b..0000000000 --- a/Lib/stdwin/Buttons.py +++ /dev/null @@ -1,411 +0,0 @@ -# Module 'Buttons' - - -# Import module 'rect' renamed as '_rect' to avoid exporting it on -# 'from Buttons import *' -# -import rect -_rect = rect -del rect - - -# Field indices in mouse event detail -# -_HV = 0 -_CLICKS = 1 -_BUTTON = 2 -_MASK = 3 - - -# LabelAppearance provides defaults for all appearance methods. -# selected state not visible -# disabled --> crossed out -# hilited --> inverted -# -class LabelAppearance: - # - # Initialization - # - def init_appearance(self): - self.bounds = _rect.empty - self.enabled = 1 - self.hilited = 0 - self.selected = 0 - self.text = '' - # - # Size enquiry - # - def getminsize(self, m, (width, height)): - width = max(width, m.textwidth(self.text) + 6) - height = max(height, m.lineheight() + 6) - return width, height - # - def getbounds(self): - return self.bounds - # - # Changing the parameters - # - def settext(self, text): - self.text = text - if self.bounds <> _rect.empty: - self.recalctextpos() - self.redraw() - # - def setbounds(self, bounds): - self.bounds = bounds - if self.bounds <> _rect.empty: - self.recalc() - # - def realize(self): - pass - # - # Changing the state bits - # - def enable(self, flag): - if flag <> self.enabled: - self.enabled = flag - if self.bounds <> _rect.empty: - self.flipenable(self.parent.begindrawing()) - # - def hilite(self, flag): - if flag <> self.hilited: - self.hilited = flag - if self.bounds <> _rect.empty: - self.fliphilite(self.parent.begindrawing()) - # - def select(self, flag): - if flag <> self.selected: - self.selected = flag - if self.bounds <> _rect.empty: - self.redraw() - # - # Recalculate the box bounds and text position. - # This can be overridden by buttons that draw different boxes - # or want their text in a different position. - # - def recalc(self): - if self.bounds <> _rect.empty: - self.recalcbounds() - self.recalctextpos() - # - def recalcbounds(self): - self.hilitebounds = _rect.inset(self.bounds, (3, 3)) - self.crossbounds = self.bounds - # - def recalctextpos(self): - (left, top), (right, bottom) = self.bounds - m = self.parent.beginmeasuring() - h = (left + right - m.textwidth(self.text)) / 2 - v = (top + bottom - m.lineheight()) / 2 - self.textpos = h, v - # - # Generic drawing interface. - # Do not override redraw() or draw() methods; override drawit() c.s. - # - def redraw(self): - if self.bounds <> _rect.empty: - d = self.parent.begindrawing() - d.erase(self.bounds) - self.draw(d, self.bounds) - # - def draw(self, d, area): - area = _rect.intersect([area, self.bounds]) - if area == _rect.empty: - return - d.cliprect(area) - self.drawit(d) - d.noclip() - # - # The drawit() method is fairly generic but may be overridden. - # - def drawit(self, d): - self.drawpict(d) - if self.text: - d.text(self.textpos, self.text) - if not self.enabled: - self.flipenable(d) - if self.hilited: - self.fliphilite(d) - # - # Default drawing detail functions. - # Overriding these is normally sufficient to get different - # appearances. - # - def drawpict(self, d): - pass - # - def flipenable(self, d): - _xorcross(d, self.crossbounds) - # - def fliphilite(self, d): - d.invert(self.hilitebounds) - - -# A Strut is a label with no width of its own. - -class StrutAppearance(LabelAppearance): - # - def getminsize(self, m, (width, height)): - height = max(height, m.lineheight() + 6) - return width, height - # - - -# ButtonAppearance displays a centered string in a box. -# selected --> bold border -# disabled --> crossed out -# hilited --> inverted -# -class ButtonAppearance(LabelAppearance): - # - def drawpict(self, d): - d.box(_rect.inset(self.bounds, (1, 1))) - if self.selected: - # Make a thicker box - d.box(self.bounds) - d.box(_rect.inset(self.bounds, (2, 2))) - d.box(_rect.inset(self.bounds, (3, 3))) - # - - -# CheckAppearance displays a small square box and a left-justified string. -# selected --> a cross appears in the box -# disabled --> whole button crossed out -# hilited --> box is inverted -# -class CheckAppearance(LabelAppearance): - # - def getminsize(self, m, (width, height)): - minwidth = m.textwidth(self.text) + 6 - minheight = m.lineheight() + 6 - width = max(width, minwidth + minheight + m.textwidth(' ')) - height = max(height, minheight) - return width, height - # - def drawpict(self, d): - d.box(self.boxbounds) - if self.selected: _xorcross(d, self.boxbounds) - # - def recalcbounds(self): - LabelAppearance.recalcbounds(self) - (left, top), (right, bottom) = self.bounds - self.size = bottom - top - 4 - self.boxbounds = (left+2, top+2), (left+2+self.size, bottom-2) - self.hilitebounds = self.boxbounds - # - def recalctextpos(self): - m = self.parent.beginmeasuring() - (left, top), (right, bottom) = self.boxbounds - h = right + m.textwidth(' ') - v = top + (self.size - m.lineheight()) / 2 - self.textpos = h, v - # - - -# RadioAppearance displays a round indicator and a left-justified string. -# selected --> a dot appears in the indicator -# disabled --> whole button crossed out -# hilited --> indicator is inverted -# -class RadioAppearance(CheckAppearance): - # - def drawpict(self, d): - (left, top), (right, bottom) = self.boxbounds - radius = self.size / 2 - center = left + radius, top + radius - d.circle(center, radius) - if self.selected: - d.fillcircle(center, radius*3/5) - # - - -# NoReactivity ignores mouse events. -# -class NoReactivity: - def init_reactivity(self): pass - - -# BaseReactivity defines hooks and asks for mouse events, -# but provides only dummy mouse event handlers. -# The trigger methods call the corresponding hooks set by the user. -# Hooks (and triggers) mean the following: -# down_hook called on some mouse-down events -# move_hook called on some mouse-move events -# up_hook called on mouse-up events -# on_hook called for buttons with on/off state, when it goes on -# hook called when a button 'fires' or a radiobutton goes on -# There are usually extra conditions, e.g., hooks are only called -# when the button is enabled, or active, or selected (on). -# -class BaseReactivity: - # - def init_reactivity(self): - self.down_hook = self.move_hook = self.up_hook = \ - self.on_hook = self.off_hook = \ - self.hook = self.active = 0 - self.parent.need_mouse(self) - # - def mousetest(self, hv): - return _rect.pointinrect(hv, self.bounds) - # - def mouse_down(self, detail): - pass - # - def mouse_move(self, detail): - pass - # - def mouse_up(self, detail): - pass - # - def down_trigger(self): - if self.down_hook: self.down_hook(self) - # - def move_trigger(self): - if self.move_hook: self.move_hook(self) - # - def up_trigger(self): - if self.up_hook: self.up_hook(self) - # - def on_trigger(self): - if self.on_hook: self.on_hook(self) - # - def off_trigger(self): - if self.off_hook: self.off_hook(self) - # - def trigger(self): - if self.hook: self.hook(self) - - -# ToggleReactivity acts like a simple pushbutton. -# It toggles its hilite state on mouse down events. -# -class ToggleReactivity(BaseReactivity): - # - def mouse_down(self, detail): - if self.enabled and self.mousetest(detail[_HV]): - self.active = 1 - self.hilite(not self.hilited) - self.down_trigger() - # - def mouse_move(self, detail): - if self.active: - self.move_trigger() - # - def mouse_up(self, detail): - if self.active: - self.up_trigger() - self.active = 0 - # - def down_trigger(self): - if self.hilited: - self.on_trigger() - else: - self.off_trigger() - self.trigger() - # - - -# TriggerReactivity acts like a fancy pushbutton. -# It hilites itself while the mouse is down within its bounds. -# -class TriggerReactivity(BaseReactivity): - # - def mouse_down(self, detail): - if self.enabled and self.mousetest(detail[_HV]): - self.active = 1 - self.hilite(1) - self.down_trigger() - # - def mouse_move(self, detail): - if self.active: - self.hilite(self.mousetest(detail[_HV])) - if self.hilited: - self.move_trigger() - # - def mouse_up(self, detail): - if self.active: - self.hilite(self.mousetest(detail[_HV])) - if self.hilited: - self.up_trigger() - self.trigger() - self.active = 0 - self.hilite(0) - # - - -# CheckReactivity handles mouse events like TriggerReactivity, -# It overrides the up_trigger method to flip its selected state. -# -class CheckReactivity(TriggerReactivity): - # - def up_trigger(self): - self.select(not self.selected) - if self.selected: - self.on_trigger() - else: - self.off_trigger() - self.trigger() - - -# RadioReactivity turns itself on and the other buttons in its group -# off when its up_trigger method is called. -# -class RadioReactivity(TriggerReactivity): - # - def init_reactivity(self): - TriggerReactivity.init_reactivity(self) - self.group = [] - # - def up_trigger(self): - for b in self.group: - if b <> self: - if b.selected: - b.select(0) - b.off_trigger() - self.select(1) - self.on_trigger() - self.trigger() - - -# Auxiliary class for 'define' method. -# Call the initializers in the right order. -# -class Define: - # - def define(self, parent): - self.parent = parent - parent.addchild(self) - self.init_appearance() - self.init_reactivity() - return self - # - def destroy(self): - self.parent = 0 - # - def definetext(self, parent, text): - self = self.define(parent) - self.settext(text) - return self - - -# Subroutine to cross out a rectangle. -# -def _xorcross(d, bounds): - ((left, top), (right, bottom)) = bounds - # This is s bit funny to make it look better - left = left + 2 - right = right - 2 - top = top + 2 - bottom = bottom - 3 - d.xorline(((left, top), (right, bottom))) - d.xorline((left, bottom), (right, top)) - - -# Ready-made button classes. -# -class Label(NoReactivity, LabelAppearance, Define): pass -class Strut(NoReactivity, StrutAppearance, Define): pass -class PushButton(TriggerReactivity, ButtonAppearance, Define): pass -class CheckButton(CheckReactivity, CheckAppearance, Define): pass -class RadioButton(RadioReactivity, RadioAppearance, Define): pass -class ToggleButton(ToggleReactivity, ButtonAppearance, Define): pass diff --git a/Lib/stdwin/CSplit.py b/Lib/stdwin/CSplit.py deleted file mode 100755 index 90d51119c3..0000000000 --- a/Lib/stdwin/CSplit.py +++ /dev/null @@ -1,69 +0,0 @@ -# A CSplit is a Clock-shaped split: the children are grouped in a circle. -# The numbering is a little different from a real clock: the 12 o'clock -# position is called 0, not 12. This is a little easier since Python -# usually counts from zero. (BTW, there needn't be exactly 12 children.) - - -from math import pi, sin, cos -from Split import Split - -class CSplit(Split): - # - def getminsize(self, m, (width, height)): - # Since things look best if the children are spaced evenly - # along the circle (and often all children have the same - # size anyway) we compute the max child size and assume - # this is each child's size. - for child in self.children: - wi, he = child.getminsize(m, (0, 0)) - width = max(width, wi) - height = max(height, he) - # In approximation, the diameter of the circle we need is - # (diameter of box) * (#children) / pi. - # We approximate pi by 3 (so we slightly overestimate - # our minimal size requirements -- not so bad). - # Because the boxes stick out of the circle we add the - # box size to each dimension. - # Because we really deal with ellipses, do everything - # separate in each dimension. - n = len(self.children) - return width + (width*n + 2)/3, height + (height*n + 2)/3 - # - def getbounds(self): - return self.bounds - # - def setbounds(self, bounds): - self.bounds = bounds - # Place the children. This involves some math. - # Compute center positions for children as if they were - # ellipses with a diameter about 1/N times the - # circumference of the big ellipse. - # (There is some rounding involved to make it look - # reasonable for small and large N alike.) - # XXX One day Python will have automatic conversions... - n = len(self.children) - fn = float(n) - if n == 0: return - (left, top), (right, bottom) = bounds - width, height = right-left, bottom-top - child_width, child_height = width*3/(n+4), height*3/(n+4) - half_width, half_height = \ - float(width-child_width)/2.0, \ - float(height-child_height)/2.0 - center_h, center_v = center = (left+right)/2, (top+bottom)/2 - fch, fcv = float(center_h), float(center_v) - alpha = 2.0 * pi / fn - for i in range(n): - child = self.children[i] - fi = float(i) - fh, fv = \ - fch + half_width*sin(fi*alpha), \ - fcv - half_height*cos(fi*alpha) - left, top = \ - int(fh) - child_width/2, \ - int(fv) - child_height/2 - right, bottom = \ - left + child_width, \ - top + child_height - child.setbounds(((left, top), (right, bottom))) - # diff --git a/Lib/stdwin/DirList.py b/Lib/stdwin/DirList.py deleted file mode 100755 index 446d33b04c..0000000000 --- a/Lib/stdwin/DirList.py +++ /dev/null @@ -1,58 +0,0 @@ -# DirList -- Directory Listing widget - -# XXX Displays messy paths when following '..' - -import os -import stdwin, rect -from stdwinevents import * -from Buttons import PushButton -from WindowParent import WindowParent -from HVSplit import HSplit, VSplit - -class DirList(VSplit): - # - def create(self, parent, dirname): - self = VSplit.create(self, parent) - names = os.listdir(dirname) - for name in names: - if os.path.isdir(os.path.join(dirname, name)): - fullname = os.path.join(dirname, name) - btn = SubdirButton().definetext(self, fullname) - elif name[-3:] == '.py': - btn = ModuleButton().definetext(self, name) - else: - btn = FileButton().definetext(self, name) - return self - # - -class DirListWindow(WindowParent): - # - def create(self, dirname): - self = WindowParent.create(self, dirname, (0, 0)) - child = DirList().create(self, dirname) - self.realize() - return self - # - -class SubdirButton(PushButton): - # - def drawpict(self, d): - PushButton.drawpict(self, d) - d.box(rect.inset(self.bounds, (3, 1))) - # - def up_trigger(self): - window = DirListWindow().create(self.text) - # - -class FileButton(PushButton): - # - def up_trigger(self): - stdwin.fleep() - # - -class ModuleButton(FileButton): - # - def drawpict(self, d): - PushButton.drawpict(self, d) - d.box(rect.inset(self.bounds, (1, 3))) - # diff --git a/Lib/stdwin/FormSplit.py b/Lib/stdwin/FormSplit.py deleted file mode 100755 index 271cb23fc1..0000000000 --- a/Lib/stdwin/FormSplit.py +++ /dev/null @@ -1,58 +0,0 @@ -# A FormSplit lets you place its children exactly where you want them -# (including silly places!). -# It does no explicit geometry management except moving its children -# when it is moved. -# The interface to place children is as follows. -# Before you add a child, you may specify its (left, top) position -# relative to the FormSplit. If you don't specify a position for -# a child, it goes right below the previous child; the first child -# goes to (0, 0) by default. -# NB: This places data attributes named form_* on its children. -# XXX Yes, I know, there should be options to do all sorts of relative -# placement, but for now this will do. - -from Split import Split - -class FormSplit(Split): - # - def create(self, parent): - self.next_left = self.next_top = 0 - self.last_child = None - return Split.create(self, parent) - # - def getminsize(self, m, sugg_size): - max_width, max_height = 0, 0 - for c in self.children: - c.form_width, c.form_height = c.getminsize(m, (0, 0)) - max_width = max(max_width, c.form_width + c.form_left) - max_height = max(max_height, \ - c.form_height + c.form_top) - return max_width, max_height - # - def getbounds(self): - return self.bounds - # - def setbounds(self, bounds): - self.bounds = bounds - fleft, ftop = bounds[0] - for c in self.children: - left, top = c.form_left + fleft, c.form_top + ftop - right, bottom = left + c.form_width, top + c.form_height - c.setbounds(((left, top), (right, bottom))) - # - def placenext(self, left, top): - self.next_left = left - self.next_top = top - self.last_child = None - # - def addchild(self, child): - if self.last_child: - width, height = \ - self.last_child.getminsize(self.beginmeasuring(), \ - (0, 0)) - self.next_top = self.next_top + height - child.form_left = self.next_left - child.form_top = self.next_top - Split.addchild(self, child) - self.last_child = child - # diff --git a/Lib/stdwin/HVSplit.py b/Lib/stdwin/HVSplit.py deleted file mode 100755 index 62e0de75f7..0000000000 --- a/Lib/stdwin/HVSplit.py +++ /dev/null @@ -1,62 +0,0 @@ -# HVSplit contains generic code for HSplit and VSplit. -# HSplit and VSplit are specializations to either dimension. - -# XXX This does not yet stretch/shrink children if there is too much -# XXX or too little space in the split dimension. -# XXX (NB There is no interface to ask children for stretch preferences.) - -from Split import Split - -class HVSplit(Split): - # - def create(self, parent, hv): - # hv is 0 for HSplit, 1 for VSplit - self = Split.create(self, parent) - self.hv = hv - return self - # - def getminsize(self, m, sugg_size): - hv, vh = self.hv, 1 - self.hv - size = [0, 0] - sugg_size = [sugg_size[0], sugg_size[1]] - sugg_size[hv] = 0 - sugg_size = sugg_size[0], sugg_size[1] # Make a tuple - for c in self.children: - csize = c.getminsize(m, sugg_size) - if csize[vh] > size[vh]: size[vh] = csize[vh] - size[hv] = size[hv] + csize[hv] - return size[0], size[1] - # - def getbounds(self): - return self.bounds - # - def setbounds(self, bounds): - self.bounds = bounds - hv, vh = self.hv, 1 - self.hv - mf = self.parent.beginmeasuring - begin, end = bounds - sugg_size = end[0] - begin[0], end[1] - begin[1] - size = self.getminsize(mf(), sugg_size) - origin = [begin[0], begin[1]] - sugg_size = [sugg_size[0], sugg_size[1]] # Make a list - sugg_size[hv] = 0 - sugg_size = sugg_size[0], sugg_size[1] # Make a tuple - for c in self.children: - size = c.getminsize(mf(), sugg_size) - corner = [0, 0] - corner[vh] = end[vh] - corner[hv] = origin[hv] + size[hv] - c.setbounds(((origin[0], origin[1]), \ - (corner[0], corner[1]))) - origin[hv] = corner[hv] - # XXX stretch - # XXX too-small - # - -class HSplit(HVSplit): - def create(self, parent): - return HVSplit.create(self, parent, 0) - -class VSplit(HVSplit): - def create(self, parent): - return HVSplit.create(self, parent, 1) diff --git a/Lib/stdwin/Histogram.py b/Lib/stdwin/Histogram.py deleted file mode 100755 index 74a75f374f..0000000000 --- a/Lib/stdwin/Histogram.py +++ /dev/null @@ -1,36 +0,0 @@ -# Module 'Histogram' - -from Buttons import * - -# A Histogram displays a histogram of numeric data. -# -class HistogramAppearance(LabelAppearance, Define): - # - def define(self, parent): - Define.define(self, (parent, '')) - self.ydata = [] - self.scale = (0, 100) - return self - # - def setdata(self, ydata, scale): - self.ydata = ydata - self.scale = scale # (min, max) - self.parent.change(self.bounds) - # - def drawpict(self, d): - (left, top), (right, bottom) = self.bounds - min, max = self.scale - size = max-min - width, height = right-left, bottom-top - ydata = self.ydata - npoints = len(ydata) - v1 = top + height # constant - h1 = left # changed in loop - for i in range(npoints): - h0 = h1 - v0 = top + height - (ydata[i]-min)*height/size - h1 = left + (i+1) * width/npoints - d.paint((h0, v0), (h1, v1)) - # - -class Histogram(NoReactivity, HistogramAppearance): pass diff --git a/Lib/stdwin/Sliders.py b/Lib/stdwin/Sliders.py deleted file mode 100755 index cbf776daee..0000000000 --- a/Lib/stdwin/Sliders.py +++ /dev/null @@ -1,174 +0,0 @@ -# Module 'Sliders' - - -import stdwin -from stdwinevents import * -import rect -from Buttons import * -from HVSplit import HSplit - - -# Field indices in event detail -# -_HV = 0 -_CLICKS = 1 -_BUTTON = 2 -_MASK = 3 - - -# DragSlider is the simplest possible slider. -# It looks like a button but dragging the mouse left or right -# changes the controlled value. -# It does not support any of the triggers or hooks defined by Buttons, -# but defines its own setval_trigger and setval_hook. -# -class DragSliderReactivity(BaseReactivity): - # - def mouse_down(self, detail): - h, v = hv = detail[_HV] - if self.enabled and self.mousetest(hv): - self.anchor = h - self.oldval = self.val - self.active = 1 - # - def mouse_move(self, detail): - if self.active: - h, v = detail[_HV] - self.setval(self.oldval + (h - self.anchor)) - # - def mouse_up(self, detail): - if self.active: - h, v = detail[_HV] - self.setval(self.oldval + (h - self.anchor)) - self.active = 0 - # - -class DragSliderAppearance(ButtonAppearance): - # - # INVARIANTS maintained by the setval method: - # - # self.min <= self.val <= self.max - # self.text = self.pretext + `self.val` + self.postext - # - # (Notice that unlike Python ranges, the end point belongs - # to the range.) - # - def init_appearance(self): - ButtonAppearance.init_appearance(self) - self.min = 0 - self.val = 0 - self.max = 100 - self.hook = 0 - self.pretext = self.postext = '' - self.recalctext() - # - # The 'get*' and 'set*' methods belong to the generic slider interface - # - def getval(self): return self.val - # - def sethook(self, hook): - self.hook = hook - # - def setminvalmax(self, min, val, max): - self.min = min - self.max = max - self.setval(val) - # - def settexts(self, pretext, postext): - self.pretext = pretext - self.postext = postext - self.recalctext() - # - def setval(self, val): - val = min(self.max, max(self.min, val)) - if val <> self.val: - self.val = val - self.recalctext() - self.trigger() - # - def trigger(self): - if self.hook: - self.hook(self) - # - def recalctext(self): - self.settext(self.pretext + `self.val` + self.postext) - # - -class DragSlider(DragSliderReactivity, DragSliderAppearance, Define): - def definetext(self, parent, text): - raise RuntimeError, 'DragSlider.definetext() not supported' - - -# Auxiliary class for PushButton incorporated in ComplexSlider -# -class _StepButton(PushButton): - def define(self, parent): - self = PushButton.define(self, parent) - self.step = 0 - return self - def setstep(self, step): - self.step = step - def definetextstep(self, parent, text, step): - self = self.definetext(parent, text) - self.setstep(step) - return self - def init_reactivity(self): - PushButton.init_reactivity(self) - self.parent.need_timer(self) - def step_trigger(self): - self.parent.setval(self.parent.getval() + self.step) - def down_trigger(self): - self.step_trigger() - self.parent.settimer(5) - def timer(self): - if self.hilited: - self.step_trigger() - if self.active: - self.parent.settimer(1) - - -# A complex slider is an HSplit initialized to three buttons: -# one to step down, a dragslider, and one to step up. -# -class ComplexSlider(HSplit): - # - # Override Slider define() method - # - def define(self, parent): - self = self.create(parent) # HSplit - # - self.downbutton = _StepButton().definetextstep(self, '-', -1) - self.dragbutton = DragSlider().define(self) - self.upbutton = _StepButton().definetextstep(self, '+', 1) - # - return self - # - # Override HSplit methods - # - def getminsize(self, m, (width, height)): - w1, h1 = self.downbutton.getminsize(m, (0, height)) - w3, h3 = self.upbutton.getminsize(m, (0, height)) - w1 = max(w1, h1) - w3 = max(w3, h3) - w2, h2 = self.dragbutton.getminsize(m, (width-w1-w3, height)) - return w1+w2+w3, max(h1, h2, h3) - # - def setbounds(self, bounds): - (left, top), (right, bottom) = self.bounds = bounds - size = bottom - top - self.downbutton.setbounds(((left, top), (left+size, bottom))) - self.dragbutton.setbounds(((left+size, top), \ - (right-size, bottom))) - self.upbutton.setbounds(((right-size, top), (right, bottom))) - # - # Pass other Slider methods on to dragbutton - # - def getval(self): return self.dragbutton.getval() - def sethook(self, hook): self.dragbutton.sethook(hook) - def setminvalmax(self, args): self.dragbutton.setminvalmax(args) - def settexts(self, args): self.dragbutton.settexts(args) - def setval(self, val): self.dragbutton.setval(val) - def enable(self, flag): - self.downbutton.enable(flag) - self.dragbutton.enable(flag) - self.upbutton.enable(flag) diff --git a/Lib/stdwin/Soundogram.py b/Lib/stdwin/Soundogram.py deleted file mode 100755 index e3c797e3dd..0000000000 --- a/Lib/stdwin/Soundogram.py +++ /dev/null @@ -1,36 +0,0 @@ -# Module 'Soundogram' - -import audio -from Histogram import Histogram - -class Soundogram(Histogram): - # - def define(self, win, chunk): - width, height = corner = win.getwinsize() - bounds = (0, 0), corner - self.chunk = chunk - self.step = (len(chunk)-1)/(width/2+1) + 1 - ydata = _make_ydata(chunk, self.step) - return Histogram.define(self, (win, bounds, ydata, (0, 128))) - # - def setchunk(self, chunk): - self.chunk = chunk - self.recompute() - # - def recompute(self): - (left, top), (right, bottom) = self.bounds - width = right - left - self.step = (len(chunk)-1)/width + 1 - ydata = _make_ydata(chunk, self.step) - self.setdata(ydata, (0, 128)) - # - - -def _make_ydata(chunk, step): - ydata = [] - for i in range(0, len(chunk), step): - piece = audio.chr2num(chunk[i:i+step]) - mi, ma = min(piece), max(piece) - y = max(abs(mi), abs(ma)) - ydata.append(y) - return ydata diff --git a/Lib/stdwin/Split.py b/Lib/stdwin/Split.py deleted file mode 100755 index 5ff98088c4..0000000000 --- a/Lib/stdwin/Split.py +++ /dev/null @@ -1,211 +0,0 @@ -# Generic Split implementation. -# Use as a base class for other splits. -# Derived classes should at least implement the methods that call -# unimpl() below: getminsize(), getbounds() and setbounds(). - -Error = 'Split.Error' # Exception - -import rect -from stdwinevents import * - -class Split: - # - # Calls from creator - # NB derived classes may add parameters to create() - # - def create(self, parent): - parent.addchild(self) - self.parent = parent - self.children = [] - self.mouse_interest = [] - self.keybd_interest = [] - self.timer_interest = [] - self.altdraw_interest = [] - self.mouse_focus = None - self.keybd_focus = None - return self - # - # Downcalls from parent to child - # - def destroy(self): - self.parent = None - for child in self.children: - child.destroy() - del self.children[:] - del self.mouse_interest[:] - del self.keybd_interest[:] - del self.timer_interest[:] - del self.altdraw_interest[:] - self.mouse_focus = None - self.keybd_focus = None - # - def getminsize(self, m, (width, height)): - return unimpl() # Should ask children - def getbounds(self): - return unimpl() - def setbounds(self, bounds): - unimpl() # Should tell children - # - def realize(self): - for child in self.children: - child.realize() - # - def draw(self, d, detail): - # (Could avoid calls to children outside the area) - for child in self.children: - child.draw(d, detail) - # - def altdraw(self, detail): - for child in self.altdraw_interest: - child.altdraw(detail) - # - # Keyboard focus handling (used internally) - # XXX This is not enough if two levels of splits - # XXX surround text fields! - # - def set_keybd_focus(self, child): - if self.keybd_focus <> child: - if self.keybd_focus: - self.keybd_focus.deactivate() - self.keybd_focus = None - if child: - child.activate() - self.keybd_focus = child - def next_keybd_focus(self): - if not self.keybd_interest: - self.set_keybd_focus(None) - return - if self.keybd_focus in self.keybd_interest: - i = self.keybd_interest.index(self.keybd_focus) - i = (i+1) % len(self.keybd_interest) - else: - i = 0 - self.set_keybd_focus(self.keybd_interest[i]) - # - # Downcalls only made after certain upcalls - # - def mouse_down(self, detail): - if self.mouse_focus: - self.mouse_focus.mouse_down(detail) - return - p = detail[0] - for child in self.mouse_interest: - if rect.pointinrect(p, child.getbounds()): - self.mouse_focus = child - if child in self.keybd_interest: - self.set_keybd_focus(child) - child.mouse_down(detail) - def mouse_move(self, detail): - if self.mouse_focus: - self.mouse_focus.mouse_move(detail) - def mouse_up(self, detail): - if self.mouse_focus: - self.mouse_focus.mouse_up(detail) - self.mouse_focus = None - # - def activate(self): - if self.keybd_focus: - self.keybd_focus.activate() - else: - self.next_keybd_focus() - def deactivate(self): - if self.keybd_focus: - self.keybd_focus.deactivate() - # - def keybd(self, type, detail): - if not self.keybd_focus: - self.set_keybd_focus(self.keybd_interest[0]) - if type == WE_COMMAND and detail == WC_TAB and \ - len(self.keybd_interest) > 1: - self.next_keybd_focus() - return - self.keybd_focus.keybd(type, detail) - # - def timer(self): - for child in self.timer_interest: - child.timer() - # - # Upcalls from child to parent - # - def addchild(self, child): - if child in self.children: - raise Error, 'addchild: child already inlist' - self.children.append(child) - def delchild(self, child): - if child not in self.children: - raise Error, 'delchild: child not in list' - self.children.remove(child) - if child in self.mouse_interest: - self.mouse_interest.remove(child) - if child in self.keybd_interest: - self.keybd_interest.remove(child) - if child in self.timer_interest: - self.timer_interest.remove(child) - if child in self.altdraw_interest: - self.altdraw_interest.remove(child) - if child == self.mouse_focus: - self.mouse_focus = None - if child == self.keybd_focus: - self.keybd_focus = None - # - def need_mouse(self, child): - if child not in self.mouse_interest: - self.mouse_interest.append(child) - self.parent.need_mouse(self) - def no_mouse(self, child): - if child == self.mouse_focus: - self.mouse_focus = None - if child in self.mouse_interest: - self.mouse_interest.remove(child) - if not self.mouse_interest: - self.parent.no_mouse(self) - # - def need_keybd(self, child): - if child not in self.keybd_interest: - self.keybd_interest.append(child) - self.parent.need_keybd(self) - if not self.keybd_focus: - self.set_keybd_focus(child) - def no_keybd(self, child): - if child == self.keybd_focus: - self.keybd_focus = None # Don't call child.deactivate() - if child in self.keybd_interest: - self.keybd_interest.remove(child) - if not self.keybd_interest: - self.parent.no_keybd(self) - # - def need_timer(self, child): - if child not in self.timer_interest: - self.timer_interest.append(child) - self.parent.need_timer(self) - def no_timer(self, child): - if child in self.timer_interest: - self.timer_interest.remove(child) - if not self.timer_interest: - self.parent.no_timer(self) - # - def need_altdraw(self, child): - if child not in self.altdraw_interest: - self.altdraw_interest.append(child) - self.parent.need_altdraw(self) - def no_altdraw(self, child): - if child in self.altdraw_interest: - self.altdraw_interest.remove(child) - if not self.altdraw_interest: - self.parent.no_altdraw(self) - # - # The rest are transparent: - # - def begindrawing(self): - return self.parent.begindrawing() - def beginmeasuring(self): - return self.parent.beginmeasuring() - def getwindow(self): - return self.parent.getwindow() - # - def change(self, area): - self.parent.change(area) - def scroll(self, area, vector): - self.parent.scroll(area, vector) - def settimer(self, itimer): - self.parent.settimer(itimer) diff --git a/Lib/stdwin/StripChart.py b/Lib/stdwin/StripChart.py deleted file mode 100755 index afec007ae4..0000000000 --- a/Lib/stdwin/StripChart.py +++ /dev/null @@ -1,70 +0,0 @@ -# Module 'StripChart' - -import rect -from Buttons import LabelAppearance, NoReactivity - -# A StripChart doesn't really look like a label but it needs a base class. -# LabelAppearance allows it to be disabled and hilited. - -class StripChart(LabelAppearance, NoReactivity): - # - def define(self, parent, scale): - self.parent = parent - parent.addchild(self) - self.init_appearance() - self.init_reactivity() - self.ydata = [] - self.scale = scale - self.resetbounds() - return self - # - def destroy(self): - self.parent = 0 - # - def setbounds(self, bounds): - LabelAppearance.setbounds(self, bounds) - self.resetbounds() - # - def resetbounds(self): - (left, top), (right, bottom) = self.bounds - self.width = right-left - self.height = bottom-top - excess = len(self.ydata) - self.width - if excess > 0: - del self.ydata[:excess] - elif excess < 0: - while len(self.ydata) < self.width: - self.ydata.insert(0, 0) - # - def append(self, y): - self.ydata.append(y) - excess = len(self.ydata) - self.width - if excess > 0: - del self.ydata[:excess] - if self.bounds <> rect.empty: - self.parent.scroll(self.bounds, (-excess, 0)) - if self.bounds <> rect.empty: - (left, top), (right, bottom) = self.bounds - i = len(self.ydata) - area = (left+i-1, top), (left+i, bottom) - self.draw(self.parent.begindrawing(), area) - # - def draw(self, d, area): - area = rect.intersect([area, self.bounds]) - if area == rect.empty: - return - d.cliprect(area) - d.erase(self.bounds) - (a_left, a_top), (a_right, a_bottom) = area - (left, top), (right, bottom) = self.bounds - height = bottom - top - i1 = a_left - left - i2 = a_right - left - for i in range(max(0, i1), min(len(self.ydata), i2)): - split = bottom-self.ydata[i]*height/self.scale - d.paint((left+i, split), (left+i+1, bottom)) - if not self.enabled: - self.flipenable(d) - if self.hilited: - self.fliphilite(d) - d.noclip() diff --git a/Lib/stdwin/TextEdit.py b/Lib/stdwin/TextEdit.py deleted file mode 100755 index e08e496811..0000000000 --- a/Lib/stdwin/TextEdit.py +++ /dev/null @@ -1,126 +0,0 @@ -# Text editing widget - -# NB: this always assumes fixed bounds. -# For auto-growing TextEdit windows, different code would be needed. - -from stdwinevents import * - -class TextEdit: - # - def create(self, parent, (cols, rows)): - parent.addchild(self) - self.parent = parent - self.cols = cols - self.rows = rows - self.text = '' - # Creation of the editor is done in realize() - self.editor = None - self.dh = self.dv = 0 - return self - # - def createboxed(self, parent, (cols, rows), (dh, dv)): - self = self.create(parent, (cols, rows)) - self.dh = max(0, dh) - self.dv = max(0, dv) - return self - # - def settext(self, text): - self.editor.settext(text) - # - def gettext(self): - return self.editor.gettext(text) - # - # Downcalls from parent to child - # - def destroy(self): - del self.parent - del self.editor - del self.window - # - def getminsize(self, m, (width, height)): - width = max(0, width - 2*self.dh) - height = max(0, height - 2*self.dv) - if width > 0 and self.editor: - (left, top), (right, bottom) = self.editor.getrect() - act_width, act_height = right - left, bottom - top - if width >= act_width: - width = width + 2*self.dh - height = max(height, act_height) + 2*self.dv - return width, height - width = max(width, self.cols*m.textwidth('in')/2) + 2*self.dh - height = max(height, self.rows*m.lineheight()) + 2*self.dv - return width, height - # - def setbounds(self, bounds): - self.bounds = bounds - if self.editor: - (left, top), (right, bottom) = bounds - left = left + self.dh - top = top + self.dv - right = right - self.dh - bottom = bottom - self.dv - self.editor.move((left, top), (right, bottom)) - if self.dh and self.dv: - (left, top), (right, bottom) = bounds - left = left + 1 - top = top + 1 - right = right - 1 - bottom = bottom - 1 - bounds = (left, top), (right, bottom) - self.editor.setview(bounds) - # - def getbounds(self): - return self.bounds - # - def realize(self): - self.window = self.parent.getwindow() - (left, top), (right, bottom) = self.bounds - left = left + self.dh - top = top + self.dv - right = right - self.dh - bottom = bottom - self.dv - self.editor = \ - self.window.textcreate((left, top), (right, bottom)) - self.editor.setactive(0) - bounds = self.bounds - if self.dh and self.dv: - (left, top), (right, bottom) = bounds - left = left + 1 - top = top + 1 - right = right - 1 - bottom = bottom - 1 - bounds = (left, top), (right, bottom) - self.editor.setview(bounds) - self.editor.settext(self.text) - self.parent.need_mouse(self) - self.parent.need_keybd(self) - self.parent.need_altdraw(self) - # - def draw(self, d, area): - if self.dh and self.dv: - d.box(self.bounds) - # - def altdraw(self, area): - self.editor.draw(area) - # - # Event downcalls - # - def mouse_down(self, detail): - x = self.editor.event(WE_MOUSE_DOWN, self.window, detail) - # - def mouse_move(self, detail): - x = self.editor.event(WE_MOUSE_MOVE, self.window, detail) - # - def mouse_up(self, detail): - x = self.editor.event(WE_MOUSE_UP, self.window, detail) - # - def keybd(self, type, detail): - x = self.editor.event(type, self.window, detail) - # - def activate(self): - self.editor.setfocus(0, 30000) - self.editor.setactive(1) - # - def deactivate(self): - self.editor.setactive(0) - # diff --git a/Lib/stdwin/TransParent.py b/Lib/stdwin/TransParent.py deleted file mode 100755 index 49dcd3d071..0000000000 --- a/Lib/stdwin/TransParent.py +++ /dev/null @@ -1,123 +0,0 @@ -# A class that sits transparently between a parent and one child. -# First create the parent, then this thing, then the child. -# Use this as a base class for objects that are almost transparent. -# Don't use as a base class for parents with multiple children. - -Error = 'TransParent.Error' # Exception - -class ManageOneChild: - # - # Upcalls shared with other single-child parents - # - def addchild(self, child): - if self.child: - raise Error, 'addchild: one child only' - if not child: - raise Error, 'addchild: bad child' - self.child = child - # - def delchild(self, child): - if not self.child: - raise Error, 'delchild: no child' - if child <> self.child: - raise Error, 'delchild: not my child' - self.child = 0 - -class TransParent(ManageOneChild): - # - # Calls from creator - # NB derived classes may add parameters to create() - # - def create(self, parent): - parent.addchild(self) - self.parent = parent - self.child = None # No child yet - return self - # - # Downcalls from parent to child - # - def destroy(self): - del self.parent - if self.child: self.child.destroy() - del self.child - # - def getminsize(self, args): - if not self.child: - m, size = args - return size - else: - return self.child.getminsize(args) - def getbounds(self, bounds): - if not self.child: - raise Error, 'getbounds w/o child' - else: - return self.child.getbounds() - def setbounds(self, bounds): - if not self.child: - raise Error, 'setbounds w/o child' - else: - self.child.setbounds(bounds) - def realize(self): - if self.child: - self.child.realize() - def draw(self, d, area): - if self.child: - self.child.draw(d, area) - def altdraw(self, area): - if self.child: - self.child.altdraw(area) - # - # Downcalls only made after certain upcalls - # - def mouse_down(self, detail): - if self.child: self.child.mouse_down(detail) - def mouse_move(self, detail): - if self.child: self.child.mouse_move(detail) - def mouse_up(self, detail): - if self.child: self.child.mouse_up(detail) - # - def keybd(self, type_detail): - self.child.keybd(type_detail) - def activate(self): - self.child.activate() - def deactivate(self): - self.child.deactivate() - # - def timer(self): - if self.child: self.child.timer() - # - # Upcalls from child to parent - # - def need_mouse(self, child): - self.parent.need_mouse(self) - def no_mouse(self, child): - self.parent.no_mouse(self) - # - def need_timer(self, child): - self.parent.need_timer(self) - def no_timer(self, child): - self.parent.no_timer(self) - # - def need_altdraw(self, child): - self.parent.need_altdraw(self) - def no_altdraw(self, child): - self.parent.no_altdraw(self) - # - def need_keybd(self, child): - self.parent.need_keybd(self) - def no_keybd(self, child): - self.parent.no_keybd(self) - # - def begindrawing(self): - return self.parent.begindrawing() - def beginmeasuring(self): - return self.parent.beginmeasuring() - def getwindow(self): - return self.parent.getwindow() - # - def change(self, area): - self.parent.change(area) - def scroll(self, area, vector): - self.parent.scroll(area, vector) - def settimer(self, itimer): - self.parent.settimer(itimer) diff --git a/Lib/stdwin/VUMeter.py b/Lib/stdwin/VUMeter.py deleted file mode 100755 index ed9a4738c1..0000000000 --- a/Lib/stdwin/VUMeter.py +++ /dev/null @@ -1,47 +0,0 @@ -# Module 'VUMeter' - -import audio -from StripChart import StripChart - -K = 1024 -Rates = [0, 32*K, 16*K, 8*K] - -class VUMeter(StripChart): - # - # Override define() and timer() methods - # - def define(self, parent): - self = StripChart.define(self, (parent, 128)) - self.parent.need_timer(self) - self.sampling = 0 - self.rate = 3 - self.enable(0) - return self - # - def timer(self): - if self.sampling: - chunk = audio.wait_recording() - self.sampling = 0 - nums = audio.chr2num(chunk) - ampl = max(abs(min(nums)), abs(max(nums))) - self.append(ampl) - if self.enabled and not self.sampling: - audio.setrate(self.rate) - size = Rates[self.rate]/10 - size = size/48*48 - audio.start_recording(size) - self.sampling = 1 - if self.sampling: - self.parent.settimer(1) - # - # New methods: start() and stop() - # - def stop(self): - if self.sampling: - chunk = audio.stop_recording() - self.sampling = 0 - self.enable(0) - # - def start(self): - self.enable(1) - self.timer() diff --git a/Lib/stdwin/WindowParent.py b/Lib/stdwin/WindowParent.py deleted file mode 100755 index cdec10b283..0000000000 --- a/Lib/stdwin/WindowParent.py +++ /dev/null @@ -1,189 +0,0 @@ -# A 'WindowParent' is the only module that uses real stdwin functionality. -# It is the root of the tree. -# It should have exactly one child when realized. -# -# There is also an alternative interface to "mainloop" here. - -import stdwin -from stdwinevents import * -import mainloop - -from TransParent import ManageOneChild - -Error = 'WindowParent.Error' # Exception - -class WindowParent(ManageOneChild): - # - def create(self, title, size): - self.title = title - self.size = size # (width, height) - self._reset() - self.close_hook = WindowParent.delayed_destroy - return self - # - def _reset(self): - self.child = None - self.win = None - self.itimer = 0 - self.do_mouse = 0 - self.do_keybd = 0 - self.do_timer = 0 - self.do_altdraw = 0 - self.pending_destroy = 0 - self.close_hook = None - self.menu_hook = None - # - def destroy(self): - mainloop.unregister(self.win) - if self.child: self.child.destroy() - self._reset() - # - def delayed_destroy(self): - # This interface to be used by 'Close' buttons etc.; - # destroying a window from within a button hook - # is not a good idea... - self.pending_destroy = 1 - # - def close_trigger(self): - if self.close_hook: self.close_hook(self) - # - def menu_trigger(self, menu, item): - if self.menu_hook: - self.menu_hook(self, menu, item) - # - def need_mouse(self, child): self.do_mouse = 1 - def no_mouse(self, child): self.do_mouse = 0 - # - def need_keybd(self, child): - self.do_keybd = 1 - self.child.activate() - def no_keybd(self, child): - self.do_keybd = 0 - self.child.deactivate() - # - def need_timer(self, child): self.do_timer = 1 - def no_timer(self, child): self.do_timer = 0 - # - def need_altdraw(self, child): self.do_altdraw = 1 - def no_altdraw(self, child): self.do_altdraw = 0 - # - def realize(self): - if self.win: - raise Error, 'realize(): called twice' - if not self.child: - raise Error, 'realize(): no child' - # Compute suggested size - self.size = self.child.getminsize(self.beginmeasuring(), \ - self.size) - save_defsize = stdwin.getdefwinsize() - scrwidth, scrheight = stdwin.getscrsize() - width, height = self.size - if width > scrwidth: - width = scrwidth * 2/3 - if height > scrheight: - height = scrheight * 2/3 - stdwin.setdefwinsize(width, height) - self.hbar, self.vbar = stdwin.getdefscrollbars() - self.win = stdwin.open(self.title) - stdwin.setdefwinsize(save_defsize) - self.win.setdocsize(self.size) - if self.itimer: - self.win.settimer(self.itimer) - width, height = self.win.getwinsize() - if self.hbar: - width = self.size[0] - if self.vbar: - height = self.size[1] - self.child.setbounds(((0, 0), (width, height))) - self.child.realize() - self.win.dispatch = self.dispatch - mainloop.register(self.win) - # - def fixup(self): - # XXX This could share code with realize() above - self.size = self.child.getminsize(self.beginmeasuring(), \ - self.win.getwinsize()) - self.win.setdocsize(self.size) - width, height = self.win.getwinsize() - if self.hbar: - width = self.size[0] - if self.vbar: - height = self.size[1] - self.child.setbounds(((0, 0), (width, height))) - # Force a redraw of the entire window: - self.win.change((0, 0), self.size) - # - def beginmeasuring(self): - # Return something with which a child can measure text - if self.win: - return self.win.begindrawing() - else: - return stdwin - # - def begindrawing(self): - if self.win: - return self.win.begindrawing() - else: - raise Error, 'begindrawing(): not realized yet' - # - def getwindow(self): - if self.win: - return self.win - else: - raise Error, 'getwindow(): not realized yet' - # - def change(self, area): - if self.win: - self.win.change(area) - # - def scroll(self, area, vector): - if self.win: - self.win.scroll(area, vector) - # - def settimer(self, itimer): - if self.win: - self.win.settimer(itimer) - else: - self.itimer = itimer - # - # Only call dispatch once we are realized - # - def dispatch(self, (type, win, detail)): - if type == WE_DRAW: - d = self.win.begindrawing() - self.child.draw(d, detail) - del d - if self.do_altdraw: self.child.altdraw(detail) - elif type == WE_MOUSE_DOWN: - if self.do_mouse: self.child.mouse_down(detail) - elif type == WE_MOUSE_MOVE: - if self.do_mouse: self.child.mouse_move(detail) - elif type == WE_MOUSE_UP: - if self.do_mouse: self.child.mouse_up(detail) - elif type in (WE_CHAR, WE_COMMAND): - if self.do_keybd: self.child.keybd(type, detail) - elif type == WE_TIMER: - if self.do_timer: self.child.timer() - elif type == WE_SIZE: - self.fixup() - elif type == WE_CLOSE: - self.close_trigger() - elif type == WE_MENU: - self.menu_trigger(detail) - if self.pending_destroy: - self.destroy() - # - -def MainLoop(): - mainloop.mainloop() - -def Dispatch(event): - mainloop.dispatch(event) - -# Interface used by WindowSched: - -def CountWindows(): - return mainloop.countwindows() - -def AnyWindow(): - return mainloop.anywindow() diff --git a/Lib/stdwin/WindowSched.py b/Lib/stdwin/WindowSched.py deleted file mode 100755 index b2fbe76563..0000000000 --- a/Lib/stdwin/WindowSched.py +++ /dev/null @@ -1,61 +0,0 @@ -# Combine a real-time scheduling queue and stdwin event handling. -# Keeps times in milliseconds. - -import stdwin, stdwinq -from stdwinevents import WE_TIMER -import mainloop -import sched -import time - -# Delay function called by the scheduler when it has nothing to do. -# Return immediately when something is done, or when the delay is up. -# -def delayfunc(msecs): - # - # Check for immediate stdwin event - # - event = stdwinq.pollevent() - if event: - mainloop.dispatch(event) - return - # - # Use sleep for very short delays or if there are no windows - # - if msecs < 100 or mainloop.countwindows() == 0: - if msecs > 0: - time.sleep(msecs * 0.001) - return - # - # Post a timer event on an arbitrary window and wait for it - # - window = mainloop.anywindow() - window.settimer(msecs/100) - event = stdwinq.getevent() - window.settimer(0) - if event[0] <> WE_TIMER: - mainloop.dispatch(event) - -def millitimer(): - return int(1000 * time.time()) - -q = sched.scheduler(millitimer, delayfunc) - -# Export functions enter, enterabs and cancel just like a scheduler -# -enter = q.enter -enterabs = q.enterabs -cancel = q.cancel - -# Emptiness check must check both queues -# -def empty(): - return q.empty() and mainloop.countwindows() == 0 - -# Run until there is nothing left to do -# -def run(): - while not empty(): - if q.empty(): - mainloop.dispatch(stdwinq.getevent()) - else: - q.run() diff --git a/Lib/stdwin/anywin.py b/Lib/stdwin/anywin.py deleted file mode 100755 index 38ee8690a6..0000000000 --- a/Lib/stdwin/anywin.py +++ /dev/null @@ -1,14 +0,0 @@ -# Module 'anywin' -# Open a file or directory in a window - -import dirwin -import filewin -import os - -def open(name): - print 'opening', name, '...' - if os.path.isdir(name): - w = dirwin.open(name) - else: - w = filewin.open(name) - return w diff --git a/Lib/stdwin/basewin.py b/Lib/stdwin/basewin.py deleted file mode 100755 index 7a43536967..0000000000 --- a/Lib/stdwin/basewin.py +++ /dev/null @@ -1,64 +0,0 @@ -# basewin.py - -import stdwin -import mainloop -from stdwinevents import * - -class BaseWindow: - - def __init__(self, title): - self.win = stdwin.open(title) - self.win.dispatch = self.dispatch - mainloop.register(self.win) - -# def reopen(self): -# title = self.win.gettitle() -# winpos = self.win.getwinpos() -# winsize = self.win.getwinsize() -# origin = self.win.getorigin() -# docsize = self.win.getdocsize() -# mainloop.unregister(self.win) -# del self.win.dispatch -# self.win.close() -# stdwin.setdefwinpos(winpos) -# stdwin.setdefwinsize(winsize) -# self.win = stdwin.open(title) -# stdwin.setdefwinpos(0, 0) -# stdwin.setdefwinsize(0, 0) -# self.win.setdocsize(docsize) -# self.win.setorigin(origin) -# self.win.dispatch = self.dispatch -# mainloop.register(self.win) - - def popup(self): - if self.win is not stdwin.getactive(): - self.win.setactive() - - def close(self): - mainloop.unregister(self.win) - del self.win.dispatch - self.win.close() - - def dispatch(self, event): - type, win, detail = event - if type == WE_CHAR: - self.char(detail) - elif type == WE_COMMAND: - self.command(detail) - elif type == WE_MOUSE_DOWN: - self.mouse_down(detail) - elif type == WE_MOUSE_MOVE: - self.mouse_move(detail) - elif type == WE_MOUSE_UP: - self.mouse_up(detail) - elif type == WE_DRAW: - self.draw(detail) - elif type == WE_CLOSE: - self.close() - - def no_op(self, detail): - pass - char = command = mouse_down = mouse_move = mouse_up = draw = no_op - - def refreshall(self): - self.win.change((-10, 0), (10000, 30000)) diff --git a/Lib/stdwin/dirwin.py b/Lib/stdwin/dirwin.py deleted file mode 100755 index e8b0170207..0000000000 --- a/Lib/stdwin/dirwin.py +++ /dev/null @@ -1,29 +0,0 @@ -# Module 'dirwin' - -# Directory windows, a subclass of listwin - -import os -import gwin -import listwin -import anywin -import dircache - -def action(w, string, i, detail): - (h, v), clicks, button, mask = detail - if clicks == 2: - name = os.path.join(w.name, string) - try: - w2 = anywin.open(name) - w2.parent = w - except os.error, why: - stdwin.message('Can\'t open ' + name + ': ' + why[1]) - -def open(name): - name = os.path.join(name, '') - list = dircache.opendir(name)[:] - list.sort() - dircache.annotate(name, list) - w = listwin.open(name, list) - w.name = name - w.action = action - return w diff --git a/Lib/stdwin/filewin.py b/Lib/stdwin/filewin.py deleted file mode 100755 index df6aa7d7f7..0000000000 --- a/Lib/stdwin/filewin.py +++ /dev/null @@ -1,20 +0,0 @@ -# Module 'filewin' -# File windows, a subclass of textwin (which is a subclass of gwin) - -import textwin -import __builtin__ - - -# FILE WINDOW - -def open_readonly(fn): # Open a file window - fp = __builtin__.open(fn, 'r') - w = textwin.open_readonly(fn, fp.read()) - w.fn = fn - return w - -def open(fn): # Open a file window - fp = __builtin__.open(fn, 'r') - w = textwin.open(fn, fp.read()) - w.fn = fn - return w diff --git a/Lib/stdwin/formatter.py b/Lib/stdwin/formatter.py deleted file mode 100755 index 7ddfc1d680..0000000000 --- a/Lib/stdwin/formatter.py +++ /dev/null @@ -1,207 +0,0 @@ -# A class to help applications that do fancy text formatting. -# You create an instance each time you must redraw the window. -# Set the initial left, top and right coordinates; -# then feed it words, font changes and vertical movements. -# -# This class should eventually be extended to support much fancier -# formatting, along the lines of TeX; for now, a very simple model -# is sufficient. -# -class formatter: - # - # Initialize a formatter instance. - # Pass the window's drawing object, and left, top, right - # coordinates of the drawing space as arguments. - # - def __init__(self, d, left, top, right): - self.d = d # Drawing object - self.left = left # Left margin - self.right = right # Right margin - self.v = top # Top of current line - self.center = 0 - self.justify = 1 - self.setfont('') # Default font - self._reset() # Prepare for new line - # - # Reset for start of fresh line. - # - def _reset(self): - self.boxes = [] # Boxes and glue still to be output - self.sum_width = 0 # Total width of boxes - self.sum_space = 0 # Total space between boxes - self.sum_stretch = 0 # Total stretch for space between boxes - self.max_ascent = 0 # Max ascent of current line - self.max_descent = 0 # Max descent of current line - self.avail_width = self.right - self.left - self.hang_indent = 0 - # - # Set the current font, and compute some values from it. - # - def setfont(self, font): - self.font = font - self.d.setfont(font) - self.font_space = self.d.textwidth(' ') - self.font_ascent = self.d.baseline() - self.font_descent = self.d.lineheight() - self.font_ascent - # - # Add a word to the list of boxes; first flush if line is full. - # Space and stretch factors are expressed in fractions - # of the current font's space width. - # (Two variations: one without, one with explicit stretch factor.) - # - def addword(self, word, spacefactor): - self.addwordstretch(word, spacefactor, spacefactor) - # - def addwordstretch(self, word, spacefactor, stretchfactor): - width = self.d.textwidth(word) - if width > self.avail_width: - self._flush(1) - space = int(float(self.font_space) * float(spacefactor)) - stretch = int(float(self.font_space) * float(stretchfactor)) - box = (self.font, word, width, space, stretch) - self.boxes.append(box) - self.sum_width = self.sum_width + width - self.sum_space = self.sum_space + space - self.sum_stretch = self.sum_stretch + stretch - self.max_ascent = max(self.font_ascent, self.max_ascent) - self.max_descent = max(self.font_descent, self.max_descent) - self.avail_width = self.avail_width - width - space - # - # Flush current line and start a new one. - # Flushing twice is harmless (i.e. does not introduce a blank line). - # (Two versions: the internal one has a parameter for justification.) - # - def flush(self): - self._flush(0) - # - def _flush(self, justify): - if not self.boxes: - return - # - # Compute amount of stretch needed. - # - if justify and self.justify or self.center: - # - # Compute extra space to fill; - # this is avail_width plus glue from last box. - # Also compute available stretch. - # - last_box = self.boxes[len(self.boxes)-1] - font, word, width, space, stretch = last_box - tot_extra = self.avail_width + space - tot_stretch = self.sum_stretch - stretch - else: - tot_extra = tot_stretch = 0 - # - # Output the boxes. - # - baseline = self.v + self.max_ascent - h = self.left + self.hang_indent - if self.center: - h = h + tot_extra / 2 - tot_extra = tot_stretch = 0 - for font, word, width, space, stretch in self.boxes: - self.d.setfont(font) - v = baseline - self.d.baseline() - self.d.text((h, v), word) - h = h + width + space - if tot_extra > 0 and tot_stretch > 0: - extra = stretch * tot_extra / tot_stretch - h = h + extra - tot_extra = tot_extra - extra - tot_stretch = tot_stretch - stretch - # - # Prepare for next line. - # - self.v = baseline + self.max_descent - self.d.setfont(self.font) - self._reset() - # - # Add vertical space; first flush. - # Vertical space is expressed in fractions of the current - # font's line height. - # - def vspace(self, lines): - self.vspacepixels(int(lines * self.d.lineheight())) - # - # Add vertical space given in pixels. - # - def vspacepixels(self, dv): - self.flush() - self.v = self.v + dv - # - # Set temporary (hanging) indent, for paragraph start. - # First flush. - # - def tempindent(self, space): - self.flush() - hang = int(float(self.font_space) * float(space)) - self.hang_indent = hang - self.avail_width = self.avail_width - hang - # - # Add (permanent) left indentation. First flush. - # - def addleftindent(self, space): - self.flush() - self.left = self.left \ - + int(float(self.font_space) * float(space)) - self._reset() - # - - -# Test procedure -# -def test(): - import stdwin, stdwinq - from stdwinevents import * - try: - import mac - # Mac font assignments: - font1 = 'times', '', 12 - font2 = 'times', 'b', 14 - except ImportError: - # X11R4 font assignments - font1 = '*times-medium-r-*-120-*' - font2 = '*times-bold-r-*-140-*' - words = \ - ['The','quick','brown','fox','jumps','over','the','lazy','dog.'] - words = words * 2 - stage = 0 - stages = [(0,0,'ragged'), (1,0,'justified'), (0,1,'centered')] - justify, center, title = stages[stage] - stdwin.setdefwinsize(300,200) - w = stdwin.open(title) - winsize = w.getwinsize() - while 1: - type, window, detail = stdwinq.getevent() - if type == WE_CLOSE: - break - elif type == WE_SIZE: - newsize = w.getwinsize() - if newsize <> winsize: - w.change((0,0), winsize) - winsize = newsize - w.change((0,0), winsize) - elif type == WE_MOUSE_DOWN: - stage = (stage + 1) % len(stages) - justify, center, title = stages[stage] - w.settitle(title) - w.change((0, 0), (1000, 1000)) - elif type == WE_DRAW: - width, height = winsize - f = formatter(w.begindrawing(), 0, 0, width) - f.center = center - f.justify = justify - if not center: - f.tempindent(5) - for font in font1, font2, font1: - f.setfont(font) - for word in words: - space = 1 + (word[-1:] == '.') - f.addword(word, space) - if center and space > 1: - f.flush() - f.flush() - height = f.v - del f - w.setdocsize(0, height) diff --git a/Lib/stdwin/gwin.py b/Lib/stdwin/gwin.py deleted file mode 100755 index 626c8fa2fb..0000000000 --- a/Lib/stdwin/gwin.py +++ /dev/null @@ -1,110 +0,0 @@ -# Module 'gwin' -# Generic stdwin windows - -# This is used as a base class from which to derive other window types. -# XXX DON'T USE THIS CODE ANY MORE! It is ages old! - -import stdwin, stdwinq -from stdwinevents import * -from mainloop import mainloop, register, unregister, windows - -# Open a window - -def open(title): # Open a generic window - w = stdwin.open(title) - stdwin.setdefwinsize(0, 0) - # Set default event handlers - w.draw = nop - w.char = nop - w.mdown = nop - w.mmove = nop - w.mup = nop - w.m2down = m2down - w.m2up = m2up - w.size = nop - w.move = nop - w.activate = w.deactivate = nop - w.timer = nop - # default command handlers - w.close = close - w.tab = tab - w.enter = enter - w.backspace = backspace - w.arrow = arrow - w.kleft = w.kup = w.kright = w.kdown = nop - w.dispatch = treatevent - register(w) - return w - - -def treatevent(e): # Handle a stdwin event - type, w, detail = e - if type == WE_DRAW: - w.draw(w, detail) - elif type == WE_MENU: - m, item = detail - m.action[item](w, m, item) - elif type == WE_COMMAND: - treatcommand(w, detail) - elif type == WE_CHAR: - w.char(w, detail) - elif type == WE_MOUSE_DOWN: - if detail[1] > 1: w.m2down(w, detail) - else: w.mdown(w, detail) - elif type == WE_MOUSE_MOVE: - w.mmove(w, detail) - elif type == WE_MOUSE_UP: - if detail[1] > 1: w.m2up(w, detail) - else: w.mup(w, detail) - elif type == WE_SIZE: - w.size(w, w.getwinsize()) - elif type == WE_ACTIVATE: - w.activate(w) - elif type == WE_DEACTIVATE: - w.deactivate(w) - elif type == WE_MOVE: - w.move(w) - elif type == WE_TIMER: - w.timer(w) - elif type == WE_CLOSE: - w.close(w) - -def treatcommand(w, type): # Handle a we_command event - if type == WC_CLOSE: - w.close(w) - elif type == WC_RETURN: - w.enter(w) - elif type == WC_TAB: - w.tab(w) - elif type == WC_BACKSPACE: - w.backspace(w) - elif type in (WC_LEFT, WC_UP, WC_RIGHT, WC_DOWN): - w.arrow(w, type) - - -# Methods - -def close(w): # Close method - unregister(w) - del w.close # Delete our close function - w.close() # Call the close method - -def arrow(w, detail): # Arrow key method - if detail == WC_LEFT: - w.kleft(w) - elif detail == WC_UP: - w.kup(w) - elif detail == WC_RIGHT: - w.kright(w) - elif detail == WC_DOWN: - w.kdown(w) - - -# Trivial methods - -def tab(w): w.char(w, '\t') -def enter(w): w.char(w, '\n') # 'return' is a Python reserved word -def backspace(w): w.char(w, '\b') -def m2down(w, detail): w.mdown(w, detail) -def m2up(w, detail): w.mup(w, detail) -def nop(*args): pass diff --git a/Lib/stdwin/listwin.py b/Lib/stdwin/listwin.py deleted file mode 100755 index 9480a81fc9..0000000000 --- a/Lib/stdwin/listwin.py +++ /dev/null @@ -1,47 +0,0 @@ -# Module 'listwin' -# List windows, a subclass of gwin - -import gwin -import stdwin - -def maxlinewidth(a): # Compute maximum textwidth of lines in a sequence - max = 0 - for line in a: - width = stdwin.textwidth(line) - if width > max: max = width - return max - -def action(w, string, i, detail): # Default item selection method - pass - -def mup(w, detail): # Mouse up method - (h, v), clicks, button, mask = detail - i = divmod(v, w.lineheight)[0] - if 0 <= i < len(w.data): - w.action(w, w.data[i], i, detail) - -def draw(w, ((left, top), (right, bottom))): # Text window draw method - data = w.data - d = w.begindrawing() - lh = w.lineheight - itop = top/lh - ibot = (bottom-1)/lh + 1 - if itop < 0: itop = 0 - if ibot > len(data): ibot = len(data) - for i in range(itop, ibot): d.text((0, i*lh), data[i]) - -def open(title, data): # Display a list of texts in a window - lineheight = stdwin.lineheight() - h, v = maxlinewidth(data), len(data)*lineheight - h0, v0 = h + stdwin.textwidth(' '), v + lineheight - if h0 > stdwin.textwidth(' ')*80: h0 = 0 - if v0 > stdwin.lineheight()*24: v0 = 0 - stdwin.setdefwinsize(h0, v0) - w = gwin.open(title) - w.setdocsize(h, v) - w.lineheight = lineheight - w.data = data - w.draw = draw - w.action = action - w.mup = mup - return w diff --git a/Lib/stdwin/mainloop.py b/Lib/stdwin/mainloop.py deleted file mode 100755 index aa40c34b4e..0000000000 --- a/Lib/stdwin/mainloop.py +++ /dev/null @@ -1,256 +0,0 @@ -# Standard main loop for *all* STDWIN applications. -# This requires that applications: -# - register their windows on creation and unregister them when closed -# - have a 'dispatch' function as a window member - - -import stdwin, stdwinq -from stdwinevents import * - - -# List of windows known to the main loop. -# -windows = [] - - -# Last window that ever received an event -# -last_window = None - - -# Function to register a window. -# -def register(win): - # First test the dispatch function by passing it a null event -- - # this catches registration of unconforming windows. - win.dispatch((WE_NULL, win, None)) - if win not in windows: - windows.append(win) - - -# Function to unregister a window. -# It is not an error to unregister an already unregistered window -# (this is useful for cleanup actions). -# -def unregister(win): - global last_window - if win == last_window: - last_window = None - if win in windows: - windows.remove(win) # Not in 0.9.1 - # 0.9.1 solution: - #for i in range(len(windows)): - # if windows[i] = win: - # del windows[i] - # break - - -# Interfaces used by WindowSched. -# -def countwindows(): - return len(windows) -# -def anywindow(): - if windows: - return windows[0] - else: - return None - - -# NEW: register any number of file descriptors -# -fdlist = [] -select_args = None -select_handlers = None -# -def registerfd(fd, mode, handler): - if mode not in ('r', 'w', 'x'): - raise ValueError, 'mode must be r, w or x' - if type(fd) <> type(0): - fd = fd.fileno() # If this fails it's not a proper select arg - for i in range(len(fdlist)): - if fdlist[i][:2] == (fd, mode): - raise ValueError, \ - '(fd, mode) combination already registered' - fdlist.append((fd, mode, handler)) - make_select_args() -# -def unregisterfd(fd, *args): - if type(fd) <> type(0): - fd = fd.fileno() # If this fails it's not a proper select arg - args = (fd,) + args - n = len(args) - for i in range(len(fdlist)): - if fdlist[i][:n] == args: - del fdlist[i] - make_select_args() -# -def make_select_args(): - global select_args, select_handlers - rlist, wlist, xlist = [], [], [] - rhandlers, whandlers, xhandlers = {}, {}, {} - for fd, mode, handler in fdlist: - if mode == 'r': - rlist.append(fd) - rhandlers[`fd`] = handler - if mode == 'w': - wlist.append(fd) - whandlers[`fd`] = handler - if mode == 'x': - xlist.append(fd) - xhandlers[`fd`] = handler - if rlist or wlist or xlist: - select_args = rlist, wlist, xlist - select_handlers = rhandlers, whandlers, xhandlers - else: - select_args = None - select_handlers = None -# -def do_select(): - import select - reply = apply(select.select, select_args) - for mode in 0, 1, 2: - list = reply[mode] - for fd in list: - handler = select_handlers[mode][`fd`] - handler(fd, 'rwx'[mode]) - - -# Event processing main loop. -# Return when there are no windows left, or when an unhandled -# exception occurs. (It is safe to restart the main loop after -# an unsuccessful exit.) -# Python's stdwin.getevent() turns WE_COMMAND/WC_CANCEL events -# into KeyboardInterrupt exceptions; these are turned back in events. -# -recursion_level = 0 # Hack to make it reentrant -def mainloop(): - global recursion_level - recursion_level = recursion_level + 1 - try: - stdwin_select_handler() # Process events already in queue - while 1: - if windows and not fdlist: - while windows and not fdlist: - try: - event = stdwinq.getevent() - except KeyboardInterrupt: - event = (WE_COMMAND, \ - None, WC_CANCEL) - dispatch(event) - elif windows and fdlist: - fd = stdwin.fileno() - if recursion_level == 1: - registerfd(fd, 'r', stdwin_select_handler) - try: - while windows: - do_select() - stdwin_select_handler() - finally: - if recursion_level == 1: - unregisterfd(fd) - elif fdlist: - while fdlist and not windows: - do_select() - else: - break - finally: - recursion_level = recursion_level - 1 - - -# Check for events without ever blocking -# -def check(): - stdwin_select_handler() - # XXX Should check for socket stuff as well - - -# Handle stdwin events until none are left -# -def stdwin_select_handler(*args): - while 1: - try: - event = stdwinq.pollevent() - except KeyboardInterrupt: - event = (WE_COMMAND, None, WC_CANCEL) - if event is None: - break - dispatch(event) - - -# Run a modal dialog loop for a window. The dialog window must have -# been registered first. This prohibits most events (except size/draw -# events) to other windows. The modal dialog loop ends when the -# dialog window unregisters itself. -# -passthrough = WE_SIZE, WE_DRAW -beeping = WE_MOUSE_DOWN, WE_COMMAND, WE_CHAR, WE_KEY, WE_CLOSE, WE_MENU -# -def modaldialog(window): - if window not in windows: - raise ValueError, 'modaldialog window not registered' - while window in windows: - try: - event = stdwinq.getevent() - except KeyboardInterrupt: - event = WE_COMMAND, None, WC_CANCEL - etype, ewindow, edetail = event - if etype not in passthrough and ewindow <> window: - if etype in beeping: - stdwin.fleep() - continue - dispatch(event) - - -# Dispatch a single event. -# Events for the no window in particular are sent to the active window -# or to the last window that received an event (these hacks are for the -# WE_LOST_SEL event, which is directed to no particular window). -# Windows not in the windows list don't get their events: -# events for such windows are silently ignored. -# -def dispatch(event): - global last_window - if event[1] == None: - active = stdwin.getactive() - if active: last_window = active - else: - last_window = event[1] - if last_window in windows: - last_window.dispatch(event) - - -# Dialog base class -# -class Dialog: - # - def __init__(self, title): - self.window = stdwin.open(title) - self.window.dispatch = self.dispatch - register(self.window) - # - def close(self): - unregister(self.window) - del self.window.dispatch - self.window.close() - # - def dispatch(self, event): - etype, ewindow, edetail = event - if etype == WE_CLOSE: - self.close() - - -# Standard modal dialogs -# XXX implemented using stdwin dialogs for now -# -def askstr(prompt, default): - return stdwin.askstr(prompt, default) -# -def askync(prompt, yesorno): - return stdwin.askync(prompt, yesorno) -# -def askfile(prompt, default, new): - return stdwin.askfile(prompt, default, new) -# -def message(msg): - stdwin.message(msg) diff --git a/Lib/stdwin/rect.py b/Lib/stdwin/rect.py deleted file mode 100755 index 393eafd769..0000000000 --- a/Lib/stdwin/rect.py +++ /dev/null @@ -1,89 +0,0 @@ -# Module 'rect'. -# -# Operations on rectangles. -# There is some normalization: all results return the object 'empty' -# if their result would contain no points. - - -# Exception. -# -error = 'rect.error' - - -# The empty rectangle. -# -empty = (0, 0), (0, 0) - - -# Check if a rectangle is empty. -# -def is_empty(r): - (left, top), (right, bottom) = r - return left >= right or top >= bottom - - -# Compute the intersection or two or more rectangles. -# This works with a list or tuple argument. -# -def intersect(list): - if not list: raise error, 'intersect called with empty list' - if is_empty(list[0]): return empty - (left, top), (right, bottom) = list[0] - for rect in list[1:]: - if is_empty(rect): - return empty - (l, t), (r, b) = rect - if left < l: left = l - if top < t: top = t - if right > r: right = r - if bottom > b: bottom = b - if is_empty(((left, top), (right, bottom))): - return empty - return (left, top), (right, bottom) - - -# Compute the smallest rectangle containing all given rectangles. -# This works with a list or tuple argument. -# -def union(list): - (left, top), (right, bottom) = list[0] - for (l, t), (r, b) in list[1:]: - if not is_empty(((l, t), (r, b))): - if l < left: left = l - if t < top: top = t - if r > right: right = r - if b > bottom: bottom = b - res = (left, top), (right, bottom) - if is_empty(res): - return empty - return res - - -# Check if a point is in a rectangle. -# -def pointinrect((h, v), ((left, top), (right, bottom))): - return left <= h < right and top <= v < bottom - - -# Return a rectangle that is dh, dv inside another -# -def inset(((left, top), (right, bottom)), (dh, dv)): - left = left + dh - top = top + dv - right = right - dh - bottom = bottom - dv - r = (left, top), (right, bottom) - if is_empty(r): - return empty - else: - return r - - -# Conversions between rectangles and 'geometry tuples', -# given as origin (h, v) and dimensions (width, height). -# -def rect2geom((left, top), (right, bottom)): - return (left, top), (right-left, bottom-top) - -def geom2rect((h, v), (width, height)): - return (h, v), (h+width, v+height) diff --git a/Lib/stdwin/srcwin.py b/Lib/stdwin/srcwin.py deleted file mode 100755 index 29b78010a6..0000000000 --- a/Lib/stdwin/srcwin.py +++ /dev/null @@ -1,129 +0,0 @@ -# srcwin.py -- a source listing window - -import stdwin -from stdwinevents import * -import basewin - -WIDTH = 40 -MAXHEIGHT = 24 - - -class TextWindow(basewin.BaseWindow): - - def __init__(self, title, contents): - self.contents = contents - self.linecount = countlines(self.contents) - # - self.lineheight = lh = stdwin.lineheight() - self.leftmargin = self.getmargin() - self.top = 0 - self.rightmargin = 30000 # Infinity - self.bottom = lh * self.linecount - # - width = WIDTH*stdwin.textwidth('0') - height = lh*min(MAXHEIGHT, self.linecount) - stdwin.setdefwinsize(width, height) - basewin.BaseWindow.__init__(self, title) - # - self.win.setdocsize(0, self.bottom) - self.initeditor() - - def initeditor(self): - r = (self.leftmargin, self.top), (self.rightmargin, self.bottom) - self.editor = self.win.textcreate(r) - self.editor.settext(self.contents) - - def closeeditor(self): - self.editor.close() - -# def reopen(self): -# self.closeeditor() -# basewin.BaseWindow.reopen(self) -# self.initeditor() - - # Override the following two methods to format line numbers differently - - def getmark(self, lineno): - return `lineno` - - def getmargin(self): - return stdwin.textwidth(`self.linecount + 1` + ' ') - - # Event dispatcher, called from mainloop.mainloop() - - def dispatch(self, event): - if event[0] == WE_NULL: return # Dummy tested by mainloop - if event[0] == WE_DRAW or not self.editor.event(event): - basewin.BaseWindow.dispatch(self, event) - - # Event handlers - - def close(self): - self.closeeditor() - basewin.BaseWindow.close(self) - - def draw(self, detail): - dummy = self.editor.draw(detail) - # Draw line numbers - (left, top), (right, bottom) = detail - topline = top/self.lineheight - botline = bottom/self.lineheight + 1 - botline = min(self.linecount, botline) - d = self.win.begindrawing() - try: - h, v = 0, self.lineheight * topline - for lineno in range(topline+1, botline+1): - d.text((h, v), self.getmark(lineno)) - v = v + self.lineheight - finally: - d.close() - - # Calls from outside - - def changemark(self, lineno): # redraw the mark for a line - left = 0 - top = (lineno-1) * self.lineheight - right = self.leftmargin - bottom = lineno * self.lineheight - d = self.win.begindrawing() - try: - d.erase((left, top), (right, bottom)) - d.text((left, top), self.getmark(lineno)) - finally: - d.close() - - def showline(self, lineno): # scroll to make a line visible - left = 0 - top = (lineno-1) * self.lineheight - right = self.leftmargin - bottom = lineno * self.lineheight - self.win.show((left, top), (right, bottom)) - - -# Subroutine to count the number of lines in a string - -def countlines(text): - n = 0 - for c in text: - if c == '\n': n = n+1 - if text and text[-1] != '\n': n = n+1 # Partial last line - return n - - -class SourceWindow(TextWindow): - - def __init__(self, filename): - self.filename = filename - f = open(self.filename, 'r') - contents = f.read() - f.close() - TextWindow.__init__(self, self.filename, contents) - -# ------------------------------ testing ------------------------------ - -TESTFILE = 'srcwin.py' - -def test(): - import mainloop - sw = SourceWindow(TESTFILE) - mainloop.mainloop() diff --git a/Lib/stdwin/stdwinevents.py b/Lib/stdwin/stdwinevents.py deleted file mode 100755 index 62cf8d2931..0000000000 --- a/Lib/stdwin/stdwinevents.py +++ /dev/null @@ -1,61 +0,0 @@ -# Module 'stdwinevents' -- Constants for stdwin event types -# -# Suggested usage: -# from stdwinevents import * - -# The function stdwin.getevent() returns a tuple containing: -# (type, window, detail) -# where detail may be <no value> or a value depending on type, see below: - -# Values for type: - -WE_NULL = 0 # not reported -- means 'no event' internally -WE_ACTIVATE = 1 # detail is None -WE_CHAR = 2 # detail is the character -WE_COMMAND = 3 # detail is one of the WC_* constants below -WE_MOUSE_DOWN = 4 # detail is ((h, v), clicks, button, mask) -WE_MOUSE_MOVE = 5 # ditto -WE_MOUSE_UP = 6 # ditto -WE_MENU = 7 # detail is (menu, item) -WE_SIZE = 8 # detail is (width, height) -WE_MOVE = 9 # not reported -- reserved for future use -WE_DRAW = 10 # detail is ((left, top), (right, bottom)) -WE_TIMER = 11 # detail is None -WE_DEACTIVATE = 12 # detail is None -WE_EXTERN = 13 # detail is None -WE_KEY = 14 # detail is ??? -WE_LOST_SEL = 15 # detail is selection number -WE_CLOSE = 16 # detail is None - -# Values for detail when type is WE_COMMAND: - -WC_CLOSE = 1 # obsolete; now reported as WE_CLOSE -WC_LEFT = 2 # left arrow key -WC_RIGHT = 3 # right arrow key -WC_UP = 4 # up arrow key -WC_DOWN = 5 # down arrow key -WC_CANCEL = 6 # not reported -- turned into KeyboardInterrupt -WC_BACKSPACE = 7 # backspace key -WC_TAB = 8 # tab key -WC_RETURN = 9 # return or enter key - -# Selection numbers - -WS_CLIPBOARD = 0 -WS_PRIMARY = 1 -WS_SECONDARY = 2 - -# Modifier masks in key and mouse events - -WM_SHIFT = (1 << 0) -WM_LOCK = (1 << 1) -WM_CONTROL = (1 << 2) -WM_META = (1 << 3) -WM_OPTION = (1 << 4) -WM_NUM = (1 << 5) - -WM_BUTTON1 = (1 << 8) -WM_BUTTON2 = (1 << 9) -WM_BUTTON3 = (1 << 10) -WM_BUTTON4 = (1 << 11) -WM_BUTTON5 = (1 << 12) diff --git a/Lib/stdwin/stdwinq.py b/Lib/stdwin/stdwinq.py deleted file mode 100755 index af72986d68..0000000000 --- a/Lib/stdwin/stdwinq.py +++ /dev/null @@ -1,53 +0,0 @@ -# Replacements for getevent() and pollevent(), -# and new functions ungetevent() and sync(). - - -# Every library module should ideally use this instead of -# stdwin.{get,poll}event(), so applications can use the services -# of ungetevent() and sync(). - - -import stdwin - - -# Events read ahead are stored in this queue. -# -queue = [] - - -# Replacement for getevent(). -# -def getevent(): - if queue: - event = queue[0] - del queue[0] - return event - else: - return stdwin.getevent() - - -# Replacement for pollevent(). -# -def pollevent(): - if queue: - return getevent() - else: - return stdwin.pollevent() - - -# Push an event back in the queue. -# -def ungetevent(event): - queue.insert(0, event) - - -# Synchronize the display. It turns out that this is the way to -# force STDWIN to call XSync(), which some (esoteric) applications need. -# (This is stronger than just flushing -- it actually waits for a -# positive response from the X server on the last command issued.) -# -def sync(): - while 1: - event = stdwin.pollevent() - if not event: break - queue.append(event) diff --git a/Lib/stdwin/tablewin.py b/Lib/stdwin/tablewin.py deleted file mode 100755 index eba161d6f3..0000000000 --- a/Lib/stdwin/tablewin.py +++ /dev/null @@ -1,236 +0,0 @@ -# Module 'tablewin' - -# Display a table, with per-item actions: - -# A1 | A2 | A3 | .... | AN -# B1 | B2 | B3 | .... | BN -# C1 | C2 | C3 | .... | CN -# .. | .. | .. | .... | .. -# Z1 | Z2 | Z3 | .... | ZN - -# Not all columns need to have the same length. -# The data structure is a list of columns; -# each column is a list of items. -# Each item is a pair of a string and an action procedure. -# The first item may be a column title. - -import stdwin -import gwin -from stdwinevents import * - -def open(title, data): # Public function to open a table window - # - # Set geometry parameters (one day, these may be changeable) - # - margin = stdwin.textwidth(' ') - lineheight = stdwin.lineheight() - # - # Geometry calculations - # - colstarts = [0] - totwidth = 0 - maxrows = 0 - for coldata in data: - # Height calculations - rows = len(coldata) - if rows > maxrows: maxrows = rows - # Width calculations - width = colwidth(coldata) + margin - totwidth = totwidth + width - colstarts.append(totwidth) - # - # Calculate document and window height - # - docwidth, docheight = totwidth, maxrows*lineheight - winwidth, winheight = docwidth, docheight - if winwidth > stdwin.textwidth('n')*100: winwidth = 0 - if winheight > stdwin.lineheight()*30: winheight = 0 - # - # Create the window - # - stdwin.setdefwinsize(winwidth, winheight) - w = gwin.open(title) - # - # Set properties and override methods - # - w.data = data - w.margin = margin - w.lineheight = lineheight - w.colstarts = colstarts - w.totwidth = totwidth - w.maxrows = maxrows - w.selection = (-1, -1) - w.lastselection = (-1, -1) - w.selshown = 0 - w.setdocsize(docwidth, docheight) - w.draw = draw - w.mup = mup - w.arrow = arrow - # - # Return - # - return w - -def update(w, data): # Change the data - # - # Hide selection - # - hidesel(w, w.begindrawing()) - # - # Get old geometry parameters - # - margin = w.margin - lineheight = w.lineheight - # - # Geometry calculations - # - colstarts = [0] - totwidth = 0 - maxrows = 0 - for coldata in data: - # Height calculations - rows = len(coldata) - if rows > maxrows: maxrows = rows - # Width calculations - width = colwidth(coldata) + margin - totwidth = totwidth + width - colstarts.append(totwidth) - # - # Calculate document and window height - # - docwidth, docheight = totwidth, maxrows*lineheight - # - # Set changed properties and change window size - # - w.data = data - w.colstarts = colstarts - w.totwidth = totwidth - w.maxrows = maxrows - w.change((0, 0), (10000, 10000)) - w.setdocsize(docwidth, docheight) - w.change((0, 0), (docwidth, docheight)) - # - # Show selection, or forget it if out of range - # - showsel(w, w.begindrawing()) - if not w.selshown: w.selection = (-1, -1) - -def colwidth(coldata): # Subroutine to calculate column width - maxwidth = 0 - for string, action in coldata: - width = stdwin.textwidth(string) - if width > maxwidth: maxwidth = width - return maxwidth - -def draw(w, ((left, top), (right, bottom))): # Draw method - ileft = whichcol(w, left) - iright = whichcol(w, right-1) + 1 - if iright > len(w.data): iright = len(w.data) - itop = divmod(top, w.lineheight)[0] - if itop < 0: itop = 0 - ibottom, remainder = divmod(bottom, w.lineheight) - if remainder: ibottom = ibottom + 1 - d = w.begindrawing() - if ileft <= w.selection[0] < iright: - if itop <= w.selection[1] < ibottom: - hidesel(w, d) - d.erase((left, top), (right, bottom)) - for i in range(ileft, iright): - col = w.data[i] - jbottom = len(col) - if ibottom < jbottom: jbottom = ibottom - h = w.colstarts[i] - v = itop * w.lineheight - for j in range(itop, jbottom): - string, action = col[j] - d.text((h, v), string) - v = v + w.lineheight - showsel(w, d) - -def mup(w, detail): # Mouse up method - (h, v), nclicks, button, mask = detail - icol = whichcol(w, h) - if 0 <= icol < len(w.data): - irow = divmod(v, w.lineheight)[0] - col = w.data[icol] - if 0 <= irow < len(col): - string, action = col[irow] - action(w, string, (icol, irow), detail) - -def whichcol(w, h): # Return column number (may be >= len(w.data)) - for icol in range(0, len(w.data)): - if h < w.colstarts[icol+1]: - return icol - return len(w.data) - -def arrow(w, type): - if type == WC_LEFT: - incr = -1, 0 - elif type == WC_UP: - incr = 0, -1 - elif type == WC_RIGHT: - incr = 1, 0 - elif type == WC_DOWN: - incr = 0, 1 - else: - return - icol, irow = w.lastselection - icol = icol + incr[0] - if icol < 0: icol = len(w.data)-1 - if icol >= len(w.data): icol = 0 - if 0 <= icol < len(w.data): - irow = irow + incr[1] - if irow < 0: irow = len(w.data[icol]) - 1 - if irow >= len(w.data[icol]): irow = 0 - else: - irow = 0 - if 0 <= icol < len(w.data) and 0 <= irow < len(w.data[icol]): - w.lastselection = icol, irow - string, action = w.data[icol][irow] - detail = (0, 0), 1, 1, 1 - action(w, string, (icol, irow), detail) - - -# Selection management -# TO DO: allow multiple selected entries - -def select(w, selection): # Public function to set the item selection - d = w.begindrawing() - hidesel(w, d) - w.selection = selection - showsel(w, d) - if w.selshown: lastselection = selection - -def hidesel(w, d): # Hide the selection, if shown - if w.selshown: invertsel(w, d) - -def showsel(w, d): # Show the selection, if hidden - if not w.selshown: invertsel(w, d) - -def invertsel(w, d): # Invert the selection, if valid - icol, irow = w.selection - if 0 <= icol < len(w.data) and 0 <= irow < len(w.data[icol]): - left = w.colstarts[icol] - right = w.colstarts[icol+1] - top = irow * w.lineheight - bottom = (irow+1) * w.lineheight - d.invert((left, top), (right, bottom)) - w.selshown = (not w.selshown) - - -# Demonstration - -def demo_action(w, string, (icol, irow), detail): # Action function for demo - select(w, (irow, icol)) - -def demo(): # Demonstration - da = demo_action # shorthand - col0 = [('a1', da), ('bbb1', da), ('c1', da)] - col1 = [('a2', da), ('bbb2', da)] - col2 = [('a3', da), ('b3', da), ('c3', da), ('d4', da), ('d5', da)] - col3 = [] - for i in range(1, 31): col3.append('xxx' + `i`, da) - data = [col0, col1, col2, col3] - w = open('tablewin.demo', data) - gwin.mainloop() - return w diff --git a/Lib/stdwin/textwin.py b/Lib/stdwin/textwin.py deleted file mode 100755 index 778717fe14..0000000000 --- a/Lib/stdwin/textwin.py +++ /dev/null @@ -1,117 +0,0 @@ -# Module 'textwin' - -# Text windows, a subclass of gwin - -import stdwin -import gwin -from stdwinevents import * - - -def fixsize(w): - docwidth, docheight = w.text.getrect()[1] - winheight = w.getwinsize()[1] - if winheight > docheight: docheight = winheight - w.setdocsize(0, docheight) - fixeditmenu(w) - -def cut(w, m, id): - s = w.text.getfocustext() - if s: - stdwin.setcutbuffer(0, s) - w.text.replace('') - fixsize(w) - -def copy(w, m, id): - s = w.text.getfocustext() - if s: - stdwin.setcutbuffer(0, s) - fixeditmenu(w) - -def paste(w, m, id): - w.text.replace(stdwin.getcutbuffer(0)) - fixsize(w) - -def addeditmenu(w): - m = w.editmenu = w.menucreate('Edit') - m.action = [] - m.additem('Cut', 'X') - m.action.append(cut) - m.additem('Copy', 'C') - m.action.append(copy) - m.additem('Paste', 'V') - m.action.append(paste) - -def fixeditmenu(w): - m = w.editmenu - f = w.text.getfocus() - can_copy = (f[0] < f[1]) - m.enable(1, can_copy) - if not w.readonly: - m.enable(0, can_copy) - m.enable(2, (stdwin.getcutbuffer(0) <> '')) - -def draw(w, area): # Draw method - w.text.draw(area) - -def size(w, newsize): # Size method - w.text.move((0, 0), newsize) - fixsize(w) - -def close(w): # Close method - del w.text # Break circular ref - gwin.close(w) - -def char(w, c): # Char method - w.text.replace(c) - fixsize(w) - -def backspace(w): # Backspace method - void = w.text.event(WE_COMMAND, w, WC_BACKSPACE) - fixsize(w) - -def arrow(w, detail): # Arrow method - w.text.arrow(detail) - fixeditmenu(w) - -def mdown(w, detail): # Mouse down method - void = w.text.event(WE_MOUSE_DOWN, w, detail) - fixeditmenu(w) - -def mmove(w, detail): # Mouse move method - void = w.text.event(WE_MOUSE_MOVE, w, detail) - -def mup(w, detail): # Mouse up method - void = w.text.event(WE_MOUSE_UP, w, detail) - fixeditmenu(w) - -def activate(w): # Activate method - fixeditmenu(w) - -def open(title, str): # Display a string in a window - w = gwin.open(title) - w.readonly = 0 - w.text = w.textcreate((0, 0), w.getwinsize()) - w.text.replace(str) - w.text.setfocus(0, 0) - addeditmenu(w) - fixsize(w) - w.draw = draw - w.size = size - w.close = close - w.mdown = mdown - w.mmove = mmove - w.mup = mup - w.char = char - w.backspace = backspace - w.arrow = arrow - w.activate = activate - return w - -def open_readonly(title, str): # Same with char input disabled - w = open(title, str) - w.readonly = 1 - w.char = w.backspace = gwin.nop - # Disable Cut and Paste menu item; leave Copy alone - w.editmenu.enable(0, 0) - w.editmenu.enable(2, 0) - return w diff --git a/Lib/stdwin/wdb.py b/Lib/stdwin/wdb.py deleted file mode 100755 index 27bbe5147c..0000000000 --- a/Lib/stdwin/wdb.py +++ /dev/null @@ -1,316 +0,0 @@ -# wdb.py -- a window-based Python debugger - -# XXX To do: -# - don't fall out of bottom frame - - -import stdwin -from stdwinevents import * -import sys -import basewin -import bdb -import repr - -WIDTH = 40 -HEIGHT = 8 - -WdbDone = 'wdb.WdbDone' # Exception to continue execution - - -class Wdb(bdb.Bdb, basewin.BaseWindow): # Window debugger - - def __init__(self): - self.sourcewindows = {} - self.framewindows = {} - bdb.Bdb.__init__(self) - width = WIDTH*stdwin.textwidth('0') - height = HEIGHT*stdwin.lineheight() - stdwin.setdefwinsize(width, height) - basewin.BaseWindow.__init__(self, '--Stack--') - self.closed = 0 - - def reset(self): - if self.closed: raise RuntimeError, 'already closed' - bdb.Bdb.reset(self) - self.forget() - - def forget(self): - self.lineno = None - self.stack = [] - self.curindex = 0 - self.curframe = None - for fn in self.sourcewindows.keys(): - self.sourcewindows[fn].resetlineno() - - def setup(self, f, t): - self.forget() - self.stack, self.curindex = self.get_stack(f, t) - self.curframe = self.stack[self.curindex][0] - # Build a list of current frames - cfl = [] - for f, i in self.stack: cfl.append(f) - # Remove deactivated frame windows - for name in self.framewindows.keys(): - fw = self.framewindows[name] - if fw.frame not in cfl: fw.close() - else: fw.refreshframe() - # Refresh the stack window - self.refreshstack() - - # Override Bdb methods (except user_call, for now) - - def user_line(self, frame): - # This function is called when we stop or break at this line - self.interaction(frame, None) - - def user_return(self, frame, return_value): - # This function is called when a return trap is set here - frame.f_locals['__return__'] = return_value - self.settitle('--Return--') - self.interaction(frame, None) - if not self.closed: - self.settitle('--Stack--') - - def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): - # This function is called if an exception occurs, - # but only if we are to stop at or just below this level - frame.f_locals['__exception__'] = exc_type, exc_value - if type(exc_type) == type(''): - exc_type_name = exc_type - else: exc_type_name = exc_type.__name__ - self.settitle(exc_type_name + ': ' + repr.repr(exc_value)) - stdwin.fleep() - self.interaction(frame, exc_traceback) - if not self.closed: - self.settitle('--Stack--') - - # Change the title - - def settitle(self, title): - self.savetitle = self.win.gettitle() - self.win.settitle(title) - - # General interaction function - - def interaction(self, frame, traceback): - import mainloop - self.popup() - self.setup(frame, traceback) - try: - mainloop.mainloop() - except WdbDone: - pass - self.forget() - - # Functions whose name is do_X for some character X - # are callable directly from the keyboard. - - def do_up(self): - if self.curindex == 0: - stdwin.fleep() - else: - self.curindex = self.curindex - 1 - self.curframe = self.stack[self.curindex][0] - self.refreshstack() - do_u = do_up - - def do_down(self): - if self.curindex + 1 == len(self.stack): - stdwin.fleep() - else: - self.curindex = self.curindex + 1 - self.curframe = self.stack[self.curindex][0] - self.refreshstack() - do_d = do_down - - def do_step(self): - self.set_step() - raise WdbDone - do_s = do_step - - def do_next(self): - self.set_next(self.curframe) - raise WdbDone - do_n = do_next - - def do_return(self): - self.set_return(self.curframe) - raise WdbDone - do_r = do_return - - def do_continue(self): - self.set_continue() - raise WdbDone - do_c = do_cont = do_continue - - def do_quit(self): - self.close() - raise WdbDone - do_q = do_quit - - def do_list(self): - fn = self.curframe.f_code.co_filename - if not self.sourcewindows.has_key(fn): - import wdbsrcwin - try: - self.sourcewindows[fn] = wdbsrcwin. \ - DebuggerSourceWindow(self, fn) - except IOError: - stdwin.fleep() - return - w = self.sourcewindows[fn] - lineno = self.stack[self.curindex][1] - w.setlineno(lineno) - w.popup() - do_l = do_list - - def do_frame(self): - name = 'locals' + `self.curframe`[16:-1] - if self.framewindows.has_key(name): - self.framewindows[name].popup() - else: - import wdbframewin - self.framewindows[name] = \ - wdbframewin.FrameWindow(self, \ - self.curframe, \ - self.curframe.f_locals, name) - do_f = do_frame - - def do_globalframe(self): - name = 'globals' + `self.curframe`[16:-1] - if self.framewindows.has_key(name): - self.framewindows[name].popup() - else: - import wdbframewin - self.framewindows[name] = \ - wdbframewin.FrameWindow(self, \ - self.curframe, \ - self.curframe.f_globals, name) - do_g = do_globalframe - - # Link between the debugger and the window - - def refreshstack(self): - height = stdwin.lineheight() * (1 + len(self.stack)) - self.win.setdocsize((0, height)) - self.refreshall() # XXX be more subtle later - # Also pass the information on to the source windows - filename = self.curframe.f_code.co_filename - lineno = self.curframe.f_lineno - for fn in self.sourcewindows.keys(): - w = self.sourcewindows[fn] - if fn == filename: - w.setlineno(lineno) - else: - w.resetlineno() - - # The remaining methods override BaseWindow methods - - def close(self): - if not self.closed: - basewin.BaseWindow.close(self) - self.closed = 1 - for key in self.sourcewindows.keys(): - self.sourcewindows[key].close() - for key in self.framewindows.keys(): - self.framewindows[key].close() - self.set_quit() - - def char(self, detail): - try: - func = eval('self.do_' + detail) - except (AttributeError, SyntaxError): - stdwin.fleep() - return - func() - - def command(self, detail): - if detail == WC_UP: - self.do_up() - elif detail == WC_DOWN: - self.do_down() - - def mouse_down(self, detail): - (h, v), clicks, button, mask = detail - i = v / stdwin.lineheight() - if 0 <= i < len(self.stack): - if i != self.curindex: - self.curindex = i - self.curframe = self.stack[self.curindex][0] - self.refreshstack() - elif clicks == 2: - self.do_frame() - else: - stdwin.fleep() - - def draw(self, detail): - import linecache, string - d = self.win.begindrawing() - try: - h, v = 0, 0 - for f, lineno in self.stack: - fn = f.f_code.co_filename - if f is self.curframe: - s = '> ' - else: - s = ' ' - s = s + fn + '(' + `lineno` + ')' - s = s + f.f_code.co_name - if f.f_locals.has_key('__args__'): - args = f.f_locals['__args__'] - if args is not None: - s = s + repr.repr(args) - if f.f_locals.has_key('__return__'): - rv = f.f_locals['__return__'] - s = s + '->' - s = s + repr.repr(rv) - line = linecache.getline(fn, lineno) - if line: s = s + ': ' + string.strip(line) - d.text((h, v), s) - v = v + d.lineheight() - finally: - d.close() - - -# Simplified interface - -def run(statement, globals=None, locals=None): - x = Wdb() - try: x.run(statement, globals, locals) - finally: x.close() - -def runeval(expression, globals=None, locals=None): - x = Wdb() - try: return x.runeval(expression, globals, locals) - finally: x.close() - -def runctx(statement, globals, locals): - # B/W compatibility - run(statement, globals, locals) - -def runcall(*args): - x = Wdb() - try: return apply(x.runcall, args) - finally: x.close() - -def set_trace(): - Wdb().set_trace() - -# Post-Mortem interface - -def post_mortem(traceback): - x = Wdb() - x.reset() - x.interaction(None, traceback) - -def pm(): - import sys - post_mortem(sys.last_traceback) - - -# Main program for testing - -TESTCMD = 'import x; x.main()' - -def test(): - run(TESTCMD) diff --git a/Lib/stdwin/wdbframewin.py b/Lib/stdwin/wdbframewin.py deleted file mode 100755 index 7a0ff39c80..0000000000 --- a/Lib/stdwin/wdbframewin.py +++ /dev/null @@ -1,146 +0,0 @@ -# wdbframewin.py -- frame window for wdb.py - -# XXX To do: -# - display function name in window title -# - execute arbitrary statements instead of just evaluating expressions -# - allow setting variables by editing their values - - -import stdwin -from stdwinevents import * -import basewin -import sys - -WIDTH = 40 -MINHEIGHT = 8 -MAXHEIGHT = 16 - -class FrameWindow(basewin.BaseWindow): - - def __init__(self, debugger, frame, dict, name): - self.debugger = debugger - self.frame = frame # Not used except for identity tests - self.dict = dict - self.name = name - nl = max(MINHEIGHT, len(self.dict) + 5) - nl = min(nl, MAXHEIGHT) - width = WIDTH*stdwin.textwidth('0') - height = nl*stdwin.lineheight() - stdwin.setdefwinsize(width, height) - basewin.BaseWindow.__init__( - self, '--Frame ' + name + '--') - # XXX Should use current function name - self.initeditor() - self.displaylist = ['>>>', '', '-'*WIDTH] - self.refreshframe() - - def initeditor(self): - r = (stdwin.textwidth('>>> '), 0), (30000, stdwin.lineheight()) - self.editor = self.win.textcreate(r) - - def closeeditor(self): - self.editor.close() - - def dispatch(self, event): - type, win, detail = event - if type == WE_NULL: return # Dummy tested by mainloop - if type in (WE_DRAW, WE_COMMAND) \ - or not self.editor.event(event): - basewin.BaseWindow.dispatch(self, event) - - def close(self): - del self.debugger.framewindows[self.name] - del self.debugger, self.dict - self.closeeditor() - basewin.BaseWindow.close(self) - - def command(self, detail): - if detail == WC_RETURN: - self.re_eval() - else: - dummy = self.editor.event(WE_COMMAND, \ - self.win, detail) - - def mouse_down(self, detail): - (h, v), clicks, button, mask = detail - if clicks != 2: - return - i = v / stdwin.lineheight() - if 5 <= i < len(self.displaylist): - import string - name = string.splitfields(self.displaylist[i],' = ')[0] - if not self.dict.has_key(name): - stdwin.fleep() - return - value = self.dict[name] - if not hasattr(value, '__dict__'): - stdwin.fleep() - return - name = 'instance ' + `value` - if self.debugger.framewindows.has_key(name): - self.debugger.framewindows[name].popup() - else: - self.debugger.framewindows[name] = \ - FrameWindow(self.debugger, - self.frame, value.__dict__, - name) - return - stdwin.fleep() - - def re_eval(self): - import string, repr - expr = string.strip(self.editor.gettext()) - if expr == '': - output = '' - else: - globals = self.frame.f_globals - globals['__privileged__'] = 1 - locals = self.dict - try: - value = eval(expr, globals, locals) - output = repr.repr(value) - except: - if type(sys.exc_type) == type(''): - exc_type_name = sys.exc_type - else: exc_type_name = sys.exc_type.__name__ - output = exc_type_name + ': ' + `sys.exc_value` - self.displaylist[1] = output - lh = stdwin.lineheight() - r = (-10, 0), (30000, 2*lh) - self.win.change(r) - self.editor.setfocus(0, len(expr)) - - def draw(self, detail): - (left, top), (right, bottom) = detail - dummy = self.editor.draw(detail) - d = self.win.begindrawing() - try: - lh = d.lineheight() - h, v = 0, 0 - for line in self.displaylist: - if v+lh > top and v < bottom: - d.text((h, v), line) - v = v + lh - finally: - d.close() - - def refreshframe(self): - import repr - del self.displaylist[3:] - self.re_eval() - names = self.dict.keys() - for key, label in ('__args__', 'Args: '), \ - ('__return__', 'Return: '): - if self.dict.has_key(key): - names.remove(key) - value = self.dict[key] - label = label + repr.repr(value) - self.displaylist.append(label) - names.sort() - for name in names: - value = self.dict[name] - line = name + ' = ' + repr.repr(value) - self.displaylist.append(line) - self.win.setdocsize(0, \ - stdwin.lineheight() * len(self.displaylist)) - self.refreshall() # XXX Be more subtle later diff --git a/Lib/stdwin/wdbsrcwin.py b/Lib/stdwin/wdbsrcwin.py deleted file mode 100755 index f79fab94be..0000000000 --- a/Lib/stdwin/wdbsrcwin.py +++ /dev/null @@ -1,100 +0,0 @@ -# wdbsrcwin.py -- source window for wdb - -import stdwin -from stdwinevents import * -import srcwin - - -class DebuggerSourceWindow(srcwin.SourceWindow): - - def __init__(self, debugger, filename): - self.debugger = debugger - self.curlineno = 0 - self.focus = 0 - srcwin.SourceWindow.__init__(self, filename) - - def close(self): - del self.debugger.sourcewindows[self.filename] - del self.debugger - srcwin.SourceWindow.close(self) - - def dispatch(self, event): - type, win, detail = event - if type == WE_CHAR: - self.char(detail) - elif type == WE_COMMAND: - self.command(detail) - elif type == WE_MOUSE_DOWN: - self.mouse_down(detail) - else: - srcwin.SourceWindow.dispatch(self, event) - - def char(self, detail): - self.debugger.char(detail) - - def command(self, detail): - self.debugger.command(detail) - - def mouse_down(self, detail): - (h, v), clicks, button, mask = detail - if h >= self.leftmargin: - srcwin.SourceWindow.dispatch(self, \ - (WE_MOUSE_DOWN, self.win, detail)) - return - lineno = v/self.lineheight + 1 - if 1 <= lineno <= self.linecount: - if self.debugger.get_break(self.filename, lineno): - f = self.debugger.clear_break - else: - f = self.debugger.set_break - err = f(self.filename, lineno) - if err: stdwin.message(err) - else: self.changemark(lineno) - else: - stdwin.fleep() - - def getmark(self, lineno): - s = `lineno` - if lineno == self.focus: - s = '[' + s + ']' - else: - s = ' ' + s + ' ' - if lineno == self.curlineno: - s = s + '->' - else: - s = s + ' ' - br = self.debugger.breaks - if br.has_key(self.filename) and lineno in br[self.filename]: - s = s + 'B' - else: - s = s + ' ' - return s - - def getmargin(self): - return stdwin.textwidth('[' + `self.linecount+1` + ']->B ') - - def setlineno(self, newlineno): - if newlineno != self.curlineno: - oldlineno = self.curlineno - self.curlineno = newlineno - self.changemark(oldlineno) - self.changemark(newlineno) - if newlineno != 0: - self.showline(newlineno) - - def resetlineno(self): - self.setlineno(0) - - def setfocus(self, newfocus): - if newfocus != self.focus: - oldfocus = self.focus - self.focus = newfocus - self.changemark(oldfocus) - self.changemark(newfocus) - if newfocus != 0: - self.showline(newfocus) - - def resetfocus(self): - self.setfocus(0) - -# XXX Should get rid of focus stuff again diff --git a/Lib/string.py b/Lib/string.py deleted file mode 100644 index c9593476df..0000000000 --- a/Lib/string.py +++ /dev/null @@ -1,274 +0,0 @@ -# module 'string' -- A collection of string operations - -# Warning: most of the code you see here isn't normally used nowadays. -# At the end of this file most functions are replaced by built-in -# functions imported from built-in module "strop". - -# Some strings for ctype-style character classification -whitespace = ' \t\n\r\v\f' -lowercase = 'abcdefghijklmnopqrstuvwxyz' -uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' -letters = lowercase + uppercase -digits = '0123456789' -hexdigits = digits + 'abcdef' + 'ABCDEF' -octdigits = '01234567' - -# Case conversion helpers -_idmap = '' -for i in range(256): _idmap = _idmap + chr(i) -_lower = _idmap[:ord('A')] + lowercase + _idmap[ord('Z')+1:] -_upper = _idmap[:ord('a')] + uppercase + _idmap[ord('z')+1:] -_swapcase = _upper[:ord('A')] + lowercase + _upper[ord('Z')+1:] -del i - -# Backward compatible names for exceptions -index_error = ValueError -atoi_error = ValueError -atof_error = ValueError -atol_error = ValueError - -# convert UPPER CASE letters to lower case -def lower(s): - res = '' - for c in s: - res = res + _lower[ord(c)] - return res - -# Convert lower case letters to UPPER CASE -def upper(s): - res = '' - for c in s: - res = res + _upper[ord(c)] - return res - -# Swap lower case letters and UPPER CASE -def swapcase(s): - res = '' - for c in s: - res = res + _swapcase[ord(c)] - return res - -# Strip leading and trailing tabs and spaces -def strip(s): - i, j = 0, len(s) - while i < j and s[i] in whitespace: i = i+1 - while i < j and s[j-1] in whitespace: j = j-1 - return s[i:j] - -# Split a string into a list of space/tab-separated words -# NB: split(s) is NOT the same as splitfields(s, ' ')! -def split(s, sep=None): - if sep is not None: return splitfields(s, sep) - res = [] - i, n = 0, len(s) - while i < n: - while i < n and s[i] in whitespace: i = i+1 - if i == n: break - j = i - while j < n and s[j] not in whitespace: j = j+1 - res.append(s[i:j]) - i = j - return res - -# Split a list into fields separated by a given string -# NB: splitfields(s, ' ') is NOT the same as split(s)! -# splitfields(s, '') returns [s] (in analogy with split() in nawk) -def splitfields(s, sep=None): - if sep is None: return split(s) - res = [] - nsep = len(sep) - if nsep == 0: - return [s] - ns = len(s) - i = j = 0 - while j+nsep <= ns: - if s[j:j+nsep] == sep: - res.append(s[i:j]) - i = j = j + nsep - else: - j = j + 1 - res.append(s[i:]) - return res - -# Join words with spaces between them -def join(words, sep = ' '): - return joinfields(words, sep) - -# Join fields with optional separator -def joinfields(words, sep = ' '): - res = '' - for w in words: - res = res + (sep + w) - return res[len(sep):] - -# Find substring, raise exception if not found -def index(s, sub, i = 0): - res = find(s, sub, i) - if res < 0: - raise ValueError, 'substring not found in string.index' - return res - -# Find last substring, raise exception if not found -def rindex(s, sub, i = 0): - res = rfind(s, sub, i) - if res < 0: - raise ValueError, 'substring not found in string.index' - return res - -# Count non-overlapping occurrences of substring -def count(s, sub, i = 0): - if i < 0: i = max(0, i + len(s)) - n = len(sub) - m = len(s) + 1 - n - if n == 0: return m-i - r = 0 - while i < m: - if sub == s[i:i+n]: - r = r+1 - i = i+n - else: - i = i+1 - return r - -# Find substring, return -1 if not found -def find(s, sub, i = 0): - if i < 0: i = max(0, i + len(s)) - n = len(sub) - m = len(s) + 1 - n - while i < m: - if sub == s[i:i+n]: return i - i = i+1 - return -1 - -# Find last substring, return -1 if not found -def rfind(s, sub, i = 0): - if i < 0: i = max(0, i + len(s)) - n = len(sub) - m = len(s) + 1 - n - r = -1 - while i < m: - if sub == s[i:i+n]: r = i - i = i+1 - return r - -# Convert string to float -def atof(str): - import regex - sign = '' - s = str - if s and s[0] in '+-': - sign = s[0] - s = s[1:] - if not s: - raise ValueError, 'non-float argument to string.atof' - while s[0] == '0' and len(s) > 1 and s[1] in digits: s = s[1:] - if regex.match('[0-9]*\(\.[0-9]*\)?\([eE][-+]?[0-9]+\)?', s) != len(s): - raise ValueError, 'non-float argument to string.atof' - try: - return float(eval(sign + s)) - except SyntaxError: - raise ValueError, 'non-float argument to string.atof' - -# Convert string to integer -def atoi(str, base=10): - if base != 10: - # We only get here if strop doesn't define atoi() - raise ValueError, "this string.atoi doesn't support base != 10" - sign = '' - s = str - if s and s[0] in '+-': - sign = s[0] - s = s[1:] - if not s: - raise ValueError, 'non-integer argument to string.atoi' - while s[0] == '0' and len(s) > 1: s = s[1:] - for c in s: - if c not in digits: - raise ValueError, 'non-integer argument to string.atoi' - return eval(sign + s) - -# Convert string to long integer -def atol(str, base=10): - if base != 10: - # We only get here if strop doesn't define atol() - raise ValueError, "this string.atol doesn't support base != 10" - sign = '' - s = str - if s and s[0] in '+-': - sign = s[0] - s = s[1:] - if not s: - raise ValueError, 'non-integer argument to string.atol' - while s[0] == '0' and len(s) > 1: s = s[1:] - for c in s: - if c not in digits: - raise ValueError, 'non-integer argument to string.atol' - return eval(sign + s + 'L') - -# Left-justify a string -def ljust(s, width): - n = width - len(s) - if n <= 0: return s - return s + ' '*n - -# Right-justify a string -def rjust(s, width): - n = width - len(s) - if n <= 0: return s - return ' '*n + s - -# Center a string -def center(s, width): - n = width - len(s) - if n <= 0: return s - half = n/2 - if n%2 and width%2: - # This ensures that center(center(s, i), j) = center(s, j) - half = half+1 - return ' '*half + s + ' '*(n-half) - -# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03' -# Decadent feature: the argument may be a string or a number -# (Use of this is deprecated; it should be a string as with ljust c.s.) -def zfill(x, width): - if type(x) == type(''): s = x - else: s = `x` - n = len(s) - if n >= width: return s - sign = '' - if s[0] in ('-', '+'): - sign, s = s[0], s[1:] - return sign + '0'*(width-n) + s - -# Expand tabs in a string. -# Doesn't take non-printing chars into account, but does understand \n. -def expandtabs(s, tabsize=8): - res = line = '' - for c in s: - if c == '\t': - c = ' '*(tabsize - len(line)%tabsize) - line = line + c - if c == '\n': - res = res + line - line = '' - return res + line - -# Character translation through look-up table. -def translate(s, table): - if type(table) != type('') or len(table) != 256: - raise TypeError, "translation table must be 256-char string" - res = "" - for c in s: - res = res + table[ord(c)] - return res - -# Try importing optional built-in module "strop" -- if it exists, -# it redefines some string operations that are 100-1000 times faster. -# It also defines values for whitespace, lowercase and uppercase -# that match <ctype.h>'s definitions. - -try: - from strop import * - letters = lowercase + uppercase -except ImportError: - pass # Use the original, slow versions diff --git a/Lib/stringold.py b/Lib/stringold.py deleted file mode 100644 index c9593476df..0000000000 --- a/Lib/stringold.py +++ /dev/null @@ -1,274 +0,0 @@ -# module 'string' -- A collection of string operations - -# Warning: most of the code you see here isn't normally used nowadays. -# At the end of this file most functions are replaced by built-in -# functions imported from built-in module "strop". - -# Some strings for ctype-style character classification -whitespace = ' \t\n\r\v\f' -lowercase = 'abcdefghijklmnopqrstuvwxyz' -uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' -letters = lowercase + uppercase -digits = '0123456789' -hexdigits = digits + 'abcdef' + 'ABCDEF' -octdigits = '01234567' - -# Case conversion helpers -_idmap = '' -for i in range(256): _idmap = _idmap + chr(i) -_lower = _idmap[:ord('A')] + lowercase + _idmap[ord('Z')+1:] -_upper = _idmap[:ord('a')] + uppercase + _idmap[ord('z')+1:] -_swapcase = _upper[:ord('A')] + lowercase + _upper[ord('Z')+1:] -del i - -# Backward compatible names for exceptions -index_error = ValueError -atoi_error = ValueError -atof_error = ValueError -atol_error = ValueError - -# convert UPPER CASE letters to lower case -def lower(s): - res = '' - for c in s: - res = res + _lower[ord(c)] - return res - -# Convert lower case letters to UPPER CASE -def upper(s): - res = '' - for c in s: - res = res + _upper[ord(c)] - return res - -# Swap lower case letters and UPPER CASE -def swapcase(s): - res = '' - for c in s: - res = res + _swapcase[ord(c)] - return res - -# Strip leading and trailing tabs and spaces -def strip(s): - i, j = 0, len(s) - while i < j and s[i] in whitespace: i = i+1 - while i < j and s[j-1] in whitespace: j = j-1 - return s[i:j] - -# Split a string into a list of space/tab-separated words -# NB: split(s) is NOT the same as splitfields(s, ' ')! -def split(s, sep=None): - if sep is not None: return splitfields(s, sep) - res = [] - i, n = 0, len(s) - while i < n: - while i < n and s[i] in whitespace: i = i+1 - if i == n: break - j = i - while j < n and s[j] not in whitespace: j = j+1 - res.append(s[i:j]) - i = j - return res - -# Split a list into fields separated by a given string -# NB: splitfields(s, ' ') is NOT the same as split(s)! -# splitfields(s, '') returns [s] (in analogy with split() in nawk) -def splitfields(s, sep=None): - if sep is None: return split(s) - res = [] - nsep = len(sep) - if nsep == 0: - return [s] - ns = len(s) - i = j = 0 - while j+nsep <= ns: - if s[j:j+nsep] == sep: - res.append(s[i:j]) - i = j = j + nsep - else: - j = j + 1 - res.append(s[i:]) - return res - -# Join words with spaces between them -def join(words, sep = ' '): - return joinfields(words, sep) - -# Join fields with optional separator -def joinfields(words, sep = ' '): - res = '' - for w in words: - res = res + (sep + w) - return res[len(sep):] - -# Find substring, raise exception if not found -def index(s, sub, i = 0): - res = find(s, sub, i) - if res < 0: - raise ValueError, 'substring not found in string.index' - return res - -# Find last substring, raise exception if not found -def rindex(s, sub, i = 0): - res = rfind(s, sub, i) - if res < 0: - raise ValueError, 'substring not found in string.index' - return res - -# Count non-overlapping occurrences of substring -def count(s, sub, i = 0): - if i < 0: i = max(0, i + len(s)) - n = len(sub) - m = len(s) + 1 - n - if n == 0: return m-i - r = 0 - while i < m: - if sub == s[i:i+n]: - r = r+1 - i = i+n - else: - i = i+1 - return r - -# Find substring, return -1 if not found -def find(s, sub, i = 0): - if i < 0: i = max(0, i + len(s)) - n = len(sub) - m = len(s) + 1 - n - while i < m: - if sub == s[i:i+n]: return i - i = i+1 - return -1 - -# Find last substring, return -1 if not found -def rfind(s, sub, i = 0): - if i < 0: i = max(0, i + len(s)) - n = len(sub) - m = len(s) + 1 - n - r = -1 - while i < m: - if sub == s[i:i+n]: r = i - i = i+1 - return r - -# Convert string to float -def atof(str): - import regex - sign = '' - s = str - if s and s[0] in '+-': - sign = s[0] - s = s[1:] - if not s: - raise ValueError, 'non-float argument to string.atof' - while s[0] == '0' and len(s) > 1 and s[1] in digits: s = s[1:] - if regex.match('[0-9]*\(\.[0-9]*\)?\([eE][-+]?[0-9]+\)?', s) != len(s): - raise ValueError, 'non-float argument to string.atof' - try: - return float(eval(sign + s)) - except SyntaxError: - raise ValueError, 'non-float argument to string.atof' - -# Convert string to integer -def atoi(str, base=10): - if base != 10: - # We only get here if strop doesn't define atoi() - raise ValueError, "this string.atoi doesn't support base != 10" - sign = '' - s = str - if s and s[0] in '+-': - sign = s[0] - s = s[1:] - if not s: - raise ValueError, 'non-integer argument to string.atoi' - while s[0] == '0' and len(s) > 1: s = s[1:] - for c in s: - if c not in digits: - raise ValueError, 'non-integer argument to string.atoi' - return eval(sign + s) - -# Convert string to long integer -def atol(str, base=10): - if base != 10: - # We only get here if strop doesn't define atol() - raise ValueError, "this string.atol doesn't support base != 10" - sign = '' - s = str - if s and s[0] in '+-': - sign = s[0] - s = s[1:] - if not s: - raise ValueError, 'non-integer argument to string.atol' - while s[0] == '0' and len(s) > 1: s = s[1:] - for c in s: - if c not in digits: - raise ValueError, 'non-integer argument to string.atol' - return eval(sign + s + 'L') - -# Left-justify a string -def ljust(s, width): - n = width - len(s) - if n <= 0: return s - return s + ' '*n - -# Right-justify a string -def rjust(s, width): - n = width - len(s) - if n <= 0: return s - return ' '*n + s - -# Center a string -def center(s, width): - n = width - len(s) - if n <= 0: return s - half = n/2 - if n%2 and width%2: - # This ensures that center(center(s, i), j) = center(s, j) - half = half+1 - return ' '*half + s + ' '*(n-half) - -# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03' -# Decadent feature: the argument may be a string or a number -# (Use of this is deprecated; it should be a string as with ljust c.s.) -def zfill(x, width): - if type(x) == type(''): s = x - else: s = `x` - n = len(s) - if n >= width: return s - sign = '' - if s[0] in ('-', '+'): - sign, s = s[0], s[1:] - return sign + '0'*(width-n) + s - -# Expand tabs in a string. -# Doesn't take non-printing chars into account, but does understand \n. -def expandtabs(s, tabsize=8): - res = line = '' - for c in s: - if c == '\t': - c = ' '*(tabsize - len(line)%tabsize) - line = line + c - if c == '\n': - res = res + line - line = '' - return res + line - -# Character translation through look-up table. -def translate(s, table): - if type(table) != type('') or len(table) != 256: - raise TypeError, "translation table must be 256-char string" - res = "" - for c in s: - res = res + table[ord(c)] - return res - -# Try importing optional built-in module "strop" -- if it exists, -# it redefines some string operations that are 100-1000 times faster. -# It also defines values for whitespace, lowercase and uppercase -# that match <ctype.h>'s definitions. - -try: - from strop import * - letters = lowercase + uppercase -except ImportError: - pass # Use the original, slow versions diff --git a/Lib/sunau.py b/Lib/sunau.py deleted file mode 100644 index 66fec94302..0000000000 --- a/Lib/sunau.py +++ /dev/null @@ -1,474 +0,0 @@ -# Stuff to parse Sun and NeXT audio files. -# -# An audio consists of a header followed by the data. The structure -# of the header is as follows. -# -# +---------------+ -# | magic word | -# +---------------+ -# | header size | -# +---------------+ -# | data size | -# +---------------+ -# | encoding | -# +---------------+ -# | sample rate | -# +---------------+ -# | # of channels | -# +---------------+ -# | info | -# | | -# +---------------+ -# -# The magic word consists of the 4 characters '.snd'. Apart from the -# info field, all header fields are 4 bytes in size. They are all -# 32-bit unsigned integers encoded in big-endian byte order. -# -# The header size really gives the start of the data. -# The data size is the physical size of the data. From the other -# parameter the number of frames can be calculated. -# The encoding gives the way in which audio samples are encoded. -# Possible values are listed below. -# The info field currently consists of an ASCII string giving a -# human-readable description of the audio file. The info field is -# padded with NUL bytes to the header size. -# -# Usage. -# -# Reading audio files: -# f = sunau.open(file, 'r') -# where file is either the name of a file or an open file pointer. -# The open file pointer must have methods read(), seek(), and close(). -# When the setpos() and rewind() methods are not used, the seek() -# method is not necessary. -# -# This returns an instance of a class with the following public methods: -# getnchannels() -- returns number of audio channels (1 for -# mono, 2 for stereo) -# getsampwidth() -- returns sample width in bytes -# getframerate() -- returns sampling frequency -# getnframes() -- returns number of audio frames -# getcomptype() -- returns compression type ('NONE' for AIFF files) -# getcompname() -- returns human-readable version of -# compression type ('not compressed' for AIFF files) -# getparams() -- returns a tuple consisting of all of the -# above in the above order -# getmarkers() -- returns None (for compatibility with the -# aifc module) -# getmark(id) -- raises an error since the mark does not -# exist (for compatibility with the aifc module) -# readframes(n) -- returns at most n frames of audio -# rewind() -- rewind to the beginning of the audio stream -# setpos(pos) -- seek to the specified position -# tell() -- return the current position -# close() -- close the instance (make it unusable) -# The position returned by tell() and the position given to setpos() -# are compatible and have nothing to do with the actual postion in the -# file. -# The close() method is called automatically when the class instance -# is destroyed. -# -# Writing audio files: -# f = sunau.open(file, 'w') -# where file is either the name of a file or an open file pointer. -# The open file pointer must have methods write(), tell(), seek(), and -# close(). -# -# This returns an instance of a class with the following public methods: -# setnchannels(n) -- set the number of channels -# setsampwidth(n) -- set the sample width -# setframerate(n) -- set the frame rate -# setnframes(n) -- set the number of frames -# setcomptype(type, name) -# -- set the compression type and the -# human-readable compression type -# setparams(nchannels, sampwidth, framerate, nframes, comptype, compname) -# -- set all parameters at once -# tell() -- return current position in output file -# writeframesraw(data) -# -- write audio frames without pathing up the -# file header -# writeframes(data) -# -- write audio frames and patch up the file header -# close() -- patch up the file header and close the -# output file -# You should set the parameters before the first writeframesraw or -# writeframes. The total number of frames does not need to be set, -# but when it is set to the correct value, the header does not have to -# be patched up. -# It is best to first set all parameters, perhaps possibly the -# compression type, and then write audio frames using writeframesraw. -# When all frames have been written, either call writeframes('') or -# close() to patch up the sizes in the header. -# The close() method is called automatically when the class instance -# is destroyed. - -# from <multimedia/audio_filehdr.h> -AUDIO_FILE_MAGIC = 0x2e736e64 -AUDIO_FILE_ENCODING_MULAW_8 = 1 -AUDIO_FILE_ENCODING_LINEAR_8 = 2 -AUDIO_FILE_ENCODING_LINEAR_16 = 3 -AUDIO_FILE_ENCODING_LINEAR_24 = 4 -AUDIO_FILE_ENCODING_LINEAR_32 = 5 -AUDIO_FILE_ENCODING_FLOAT = 6 -AUDIO_FILE_ENCODING_DOUBLE = 7 -AUDIO_FILE_ENCODING_ADPCM_G721 = 23 -AUDIO_FILE_ENCODING_ADPCM_G722 = 24 -AUDIO_FILE_ENCODING_ADPCM_G723_3 = 25 -AUDIO_FILE_ENCODING_ADPCM_G723_5 = 26 -AUDIO_FILE_ENCODING_ALAW_8 = 27 - -# from <multimedia/audio_hdr.h> -AUDIO_UNKNOWN_SIZE = 0xFFFFFFFFL # ((unsigned)(~0)) - -_simple_encodings = [AUDIO_FILE_ENCODING_MULAW_8, - AUDIO_FILE_ENCODING_LINEAR_8, - AUDIO_FILE_ENCODING_LINEAR_16, - AUDIO_FILE_ENCODING_LINEAR_24, - AUDIO_FILE_ENCODING_LINEAR_32, - AUDIO_FILE_ENCODING_ALAW_8] - -Error = 'sunau.Error' - -def _read_u32(file): - x = 0L - for i in range(4): - byte = file.read(1) - if byte == '': - raise EOFError - x = x*256 + ord(byte) - return x - -def _write_u32(file, x): - data = [] - for i in range(4): - d, m = divmod(x, 256) - data.insert(0, m) - x = d - for i in range(4): - file.write(chr(int(data[i]))) - -class Au_read: - access _file, _soundpos, _hdr_size, _data_size, _encoding, \ - _sampwidth, _framesize, _framerate, _nchannels, \ - _info: private - - def __init__(self, f): - if type(f) == type(''): - import __builtin__ - f = __builtin__.open(f, 'r') - self.initfp(f) - - def __del__(self): - if self._file: - self.close() - - def initfp(self, file): - self._file = file - self._soundpos = 0 - magic = int(_read_u32(file)) - if magic != AUDIO_FILE_MAGIC: - raise Error, 'bad magic number' - self._hdr_size = int(_read_u32(file)) - if self._hdr_size < 24: - raise Error, 'header size too small' - if self._hdr_size > 100: - raise Error, 'header size rediculously large' - self._data_size = _read_u32(file) - if self._data_size != AUDIO_UNKNOWN_SIZE: - self._data_size = int(self._data_size) - self._encoding = int(_read_u32(file)) - if self._encoding not in _simple_encodings: - raise Error, 'encoding not (yet) supported' - if self._encoding in (AUDIO_FILE_ENCODING_MULAW_8, - AUDIO_FILE_ENCODING_LINEAR_8, - AUDIO_FILE_ENCODING_ALAW_8): - self._sampwidth = 2 - self._framesize = 1 - elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_16: - self._framesize = self._sampwidth = 2 - elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_24: - self._framesize = self._sampwidth = 3 - elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_32: - self._framesize = self._sampwidth = 4 - else: - raise Error, 'unknown encoding' - self._framerate = int(_read_u32(file)) - self._nchannels = int(_read_u32(file)) - self._framesize = self._framesize * self._nchannels - if self._hdr_size > 24: - self._info = file.read(self._hdr_size - 24) - for i in range(len(self._info)): - if self._info[i] == '\0': - self._info = self._info[:i] - break - else: - self._info = '' - - def getfp(self): - return self._file - - def getnchannels(self): - return self._nchannels - - def getsampwidth(self): - return self._sampwidth - - def getframerate(self): - return self._framerate - - def getnframes(self): - if self._data_size == AUDIO_UNKNOWN_SIZE: - return AUDIO_UNKNOWN_SIZE - if self._encoding in _simple_encodings: - return self._data_size / self._framesize - return 0 # XXX--must do some arithmetic here - - def getcomptype(self): - if self._encoding == AUDIO_FILE_ENCODING_MULAW_8: - return 'ULAW' - elif self._encoding == AUDIO_FILE_ENCODING_ALAW_8: - return 'ALAW' - else: - return 'NONE' - - def getcompname(self): - if self._encoding == AUDIO_FILE_ENCODING_MULAW_8: - return 'CCITT G.711 u-law' - elif self._encoding == AUDIO_FILE_ENCODING_ALAW_8: - return 'CCITT G.711 A-law' - else: - return 'not compressed' - - def getparams(self): - return self.getnchannels(), self.getsampwidth(), \ - self.getframerate(), self.getnframes(), \ - self.getcomptype(), self.getcompname() - - def getmarkers(self): - return None - - def getmark(self, id): - raise Error, 'no marks' - - def readframes(self, nframes): - if self._encoding in _simple_encodings: - if nframes == AUDIO_UNKNOWN_SIZE: - data = self._file.read() - else: - data = self._file.read(nframes * self._framesize * self._nchannels) - if self._encoding == AUDIO_FILE_ENCODING_MULAW_8: - import audioop - data = audioop.ulaw2lin(data, self._sampwidth) - return data - return None # XXX--not implemented yet - - def rewind(self): - self._soundpos = 0 - self._file.seek(self._hdr_size) - - def tell(self): - return self._soundpos - - def setpos(self, pos): - if pos < 0 or pos > self.getnframes(): - raise Error, 'position not in range' - self._file.seek(pos * self._framesize + self._hdr_size) - self._soundpos = pos - - def close(self): - self._file = None - -class Au_write: - access _file, _framerate, _nchannels, _sampwidth, _framesize, \ - _nframes, _nframeswritten, _datawritten, _info, \ - _comptype: private - - def __init__(self, f): - if type(f) == type(''): - import __builtin__ - f = __builtin__.open(f, 'w') - self.initfp(f) - - def __del__(self): - if self._file: - self.close() - - def initfp(self, file): - self._file = file - self._framerate = 0 - self._nchannels = 0 - self._sampwidth = 0 - self._framesize = 0 - self._nframes = AUDIO_UNKNOWN_SIZE - self._nframeswritten = 0 - self._datawritten = 0 - self._datalength = 0 - self._info = '' - self._comptype = 'ULAW' # default is U-law - - def setnchannels(self, nchannels): - if self._nframeswritten: - raise Error, 'cannot change parameters after starting to write' - if nchannels not in (1, 2, 4): - raise Error, 'only 1, 2, or 4 channels supported' - self._nchannels = nchannels - - def getnchannels(self): - if not self._nchannels: - raise Error, 'number of channels not set' - return self._nchannels - - def setsampwidth(self, sampwidth): - if self._nframeswritten: - raise Error, 'cannot change parameters after starting to write' - if sampwidth not in (1, 2, 4): - raise Error, 'bad sample width' - self._sampwidth = sampwidth - - def getsampwidth(self): - if not self._framerate: - raise Error, 'sample width not specified' - return self._sampwidth - - def setframerate(self, framerate): - if self._nframeswritten: - raise Error, 'cannot change parameters after starting to write' - self._framerate = framerate - - def getframerate(self): - if not self._framerate: - raise Error, 'frame rate not set' - return self._framerate - - def setnframes(self, nframes): - if self._nframeswritten: - raise Error, 'cannot change parameters after starting to write' - if nframes < 0: - raise Error, '# of frames cannot be negative' - self._nframes = nframes - - def getnframes(self): - return self._nframeswritten - - def setcomptype(self, type, name): - if type in ('NONE', 'ULAW'): - self._comptype = type - else: - raise Error, 'unknown compression type' - - def getcomptype(self): - return self._comptype - - def getcompname(self): - if self._comptype == 'ULAW': - return 'CCITT G.711 u-law' - elif self._comptype == 'ALAW': - return 'CCITT G.711 A-law' - else: - return 'not compressed' - - def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)): - self.setnchannels(nchannels) - self.setsampwidth(sampwidth) - self.setframerate(framerate) - self.setnframes(nframes) - self.setcomptype(comptype, compname) - - def getparams(self): - return self.getnchannels(), self.getsampwidth(), \ - self.getframerate(), self.getnframes(), \ - self.getcomptype(), self.getcompname() - - def tell(self): - return self._nframeswritten - - def writeframesraw(self, data): - self._ensure_header_written() - nframes = len(data) / self._framesize - if self._comptype == 'ULAW': - import audioop - data = audioop.lin2ulaw(data, self._sampwidth) - self._file.write(data) - self._nframeswritten = self._nframeswritten + nframes - self._datawritten = self._datawritten + len(data) - - def writeframes(self, data): - self.writeframesraw(data) - if self._nframeswritten != self._nframes or \ - self._datalength != self._datawritten: - self._patchheader() - - def close(self): - self._ensure_header_written() - if self._nframeswritten != self._nframes or \ - self._datalength != self._datawritten: - self._patchheader() - self._file.flush() - self._file = None - - # - # private methods - # - if 0: access *: private - - def _ensure_header_written(self): - if not self._nframeswritten: - if not self._nchannels: - raise Error, '# of channels not specified' - if not self._sampwidth: - raise Error, 'sample width not specified' - if not self._framerate: - raise Error, 'frame rate not specified' - self._write_header() - - def _write_header(self): - if self._comptype == 'NONE': - if self._sampwidth == 1: - encoding = AUDIO_FILE_ENCODING_LINEAR_8 - self._framesize = 1 - elif self._sampwidth == 2: - encoding = AUDIO_FILE_ENCODING_LINEAR_16 - self._framesize = 2 - elif self._sampwidth == 4: - encoding = AUDIO_FILE_ENCODING_LINEAR_32 - self._framesize = 4 - else: - raise Error, 'internal error' - elif self._comptype == 'ULAW': - encoding = AUDIO_FILE_ENCODING_MULAW_8 - self._framesize = 1 - else: - raise Error, 'internal error' - self._framesize = self._framesize * self._nchannels - _write_u32(self._file, AUDIO_FILE_MAGIC) - header_size = 25 + len(self._info) - header_size = (header_size + 7) & ~7 - _write_u32(self._file, header_size) - if self._nframes == AUDIO_UNKNOWN_SIZE: - length = AUDIO_UNKNOWN_SIZE - else: - length = self._nframes * self._framesize - _write_u32(self._file, length) - self._datalength = length - _write_u32(self._file, encoding) - _write_u32(self._file, self._framerate) - _write_u32(self._file, self._nchannels) - self._file.write(self._info) - self._file.write('\0'*(header_size - len(self._info) - 24)) - - def _patchheader(self): - self._file.seek(8) - _write_u32(self._file, self._datawritten) - self._datalength = self._datawritten - self._file.seek(0, 2) - -def open(f, mode): - if mode == 'r': - return Au_read(f) - elif mode == 'w': - return Au_write(f) - else: - raise Error, "mode must be 'r' or 'w'" - -openfp = open diff --git a/Lib/sunaudio.py b/Lib/sunaudio.py deleted file mode 100644 index 96def15a19..0000000000 --- a/Lib/sunaudio.py +++ /dev/null @@ -1,46 +0,0 @@ -# Module 'sunaudio' -- interpret sun audio headers - -MAGIC = '.snd' - -error = 'sunaudio sound header conversion error' - - -# convert a 4-char value to integer - -def get_long_be(s): - return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3]) - - -# read a sound header from an open file - -def gethdr(fp): - if fp.read(4) <> MAGIC: - raise error, 'gethdr: bad magic word' - hdr_size = get_long_be(fp.read(4)) - data_size = get_long_be(fp.read(4)) - encoding = get_long_be(fp.read(4)) - sample_rate = get_long_be(fp.read(4)) - channels = get_long_be(fp.read(4)) - excess = hdr_size - 24 - if excess < 0: - raise error, 'gethdr: bad hdr_size' - if excess > 0: - info = fp.read(excess) - else: - info = '' - return (data_size, encoding, sample_rate, channels, info) - - -# read and print the sound header of a named file - -def printhdr(file): - hdr = gethdr(open(file, 'r')) - data_size, encoding, sample_rate, channels, info = hdr - while info[-1:] == '\0': - info = info[:-1] - print 'File name: ', file - print 'Data size: ', data_size - print 'Encoding: ', encoding - print 'Sample rate:', sample_rate - print 'Channels: ', channels - print 'Info: ', `info` diff --git a/Lib/sunos4/FCNTL.py b/Lib/sunos4/FCNTL.py deleted file mode 100755 index 1256d8100a..0000000000 --- a/Lib/sunos4/FCNTL.py +++ /dev/null @@ -1,67 +0,0 @@ -# Generated by h2py from stdin -_FOPEN = (-1) -_FREAD = 0x0001 -_FWRITE = 0x0002 -_FNDELAY = 0x0004 -_FAPPEND = 0x0008 -_FSETBLK = 0x0010 -_FASYNC = 0x0040 -_FSHLOCK = 0x0080 -_FEXLOCK = 0x0100 -_FCREAT = 0x0200 -_FTRUNC = 0x0400 -_FEXCL = 0x0800 -_FNBIO = 0x1000 -_FSYNC = 0x2000 -_FNONBLOCK = 0x4000 -_FNOCTTY = 0x8000 -_FMARK = 0x10000 -_FDEFER = 0x20000 -O_RDONLY = 0 -O_WRONLY = 1 -O_RDWR = 2 -O_APPEND = _FAPPEND -O_CREAT = _FCREAT -O_TRUNC = _FTRUNC -O_EXCL = _FEXCL -O_NONBLOCK = _FNONBLOCK -O_NOCTTY = _FNOCTTY -O_SYNC = _FSYNC -FAPPEND = _FAPPEND -FSYNC = _FSYNC -FASYNC = _FASYNC -FNBIO = _FNBIO -FNONBIO = _FNONBLOCK -FNDELAY = _FNDELAY -FREAD = _FREAD -FWRITE = _FWRITE -FMARK = _FMARK -FDEFER = _FDEFER -FSETBLK = _FSETBLK -FSHLOCK = _FSHLOCK -FEXLOCK = _FEXLOCK -FOPEN = _FOPEN -FCREAT = _FCREAT -FTRUNC = _FTRUNC -FEXCL = _FEXCL -FNOCTTY = _FNOCTTY -FD_CLOEXEC = 1 -F_DUPFD = 0 -F_GETFD = 1 -F_SETFD = 2 -F_GETFL = 3 -F_SETFL = 4 -F_GETOWN = 5 -F_SETOWN = 6 -F_GETLK = 7 -F_SETLK = 8 -F_SETLKW = 9 -F_RGETLK = 10 -F_RSETLK = 11 -F_CNVT = 12 -F_RSETLKW = 13 -F_RDLCK = 1 -F_WRLCK = 2 -F_UNLCK = 3 -F_UNLKSYS = 4 -O_ACCMODE = (O_RDONLY|O_WRONLY|O_RDWR) diff --git a/Lib/sunos4/IN.py b/Lib/sunos4/IN.py deleted file mode 100755 index a05a9445b5..0000000000 --- a/Lib/sunos4/IN.py +++ /dev/null @@ -1,59 +0,0 @@ -# Generated by h2py from /usr/include/netinet/in.h -IPPROTO_IP = 0 -IPPROTO_ICMP = 1 -IPPROTO_IGMP = 2 -IPPROTO_GGP = 3 -IPPROTO_TCP = 6 -IPPROTO_EGP = 8 -IPPROTO_PUP = 12 -IPPROTO_UDP = 17 -IPPROTO_IDP = 22 -IPPROTO_HELLO = 63 -IPPROTO_ND = 77 -IPPROTO_RAW = 255 -IPPROTO_MAX = 256 -IPPORT_ECHO = 7 -IPPORT_DISCARD = 9 -IPPORT_SYSTAT = 11 -IPPORT_DAYTIME = 13 -IPPORT_NETSTAT = 15 -IPPORT_FTP = 21 -IPPORT_TELNET = 23 -IPPORT_SMTP = 25 -IPPORT_TIMESERVER = 37 -IPPORT_NAMESERVER = 42 -IPPORT_WHOIS = 43 -IPPORT_MTP = 57 -IPPORT_TFTP = 69 -IPPORT_RJE = 77 -IPPORT_FINGER = 79 -IPPORT_TTYLINK = 87 -IPPORT_SUPDUP = 95 -IPPORT_EXECSERVER = 512 -IPPORT_LOGINSERVER = 513 -IPPORT_CMDSERVER = 514 -IPPORT_EFSSERVER = 520 -IPPORT_BIFFUDP = 512 -IPPORT_WHOSERVER = 513 -IPPORT_ROUTESERVER = 520 -IPPORT_RESERVED = 1024 -IPPORT_USERRESERVED = 5000 -IMPLINK_IP = 155 -IMPLINK_LOWEXPER = 156 -IMPLINK_HIGHEXPER = 158 -IN_CLASSA_NET = 0xff000000 -IN_CLASSA_NSHIFT = 24 -IN_CLASSA_HOST = 0x00ffffff -IN_CLASSA_MAX = 128 -IN_CLASSB_NET = 0xffff0000 -IN_CLASSB_NSHIFT = 16 -IN_CLASSB_HOST = 0x0000ffff -IN_CLASSB_MAX = 65536 -IN_CLASSC_NET = 0xffffff00 -IN_CLASSC_NSHIFT = 8 -IN_CLASSC_HOST = 0x000000ff -INADDR_ANY = 0x00000000 -INADDR_LOOPBACK = 0x7F000001 -INADDR_BROADCAST = 0xffffffff -IN_LOOPBACKNET = 127 -IP_OPTIONS = 1 diff --git a/Lib/sunos4/SOCKET.py b/Lib/sunos4/SOCKET.py deleted file mode 100755 index 65ce4bc4cb..0000000000 --- a/Lib/sunos4/SOCKET.py +++ /dev/null @@ -1,78 +0,0 @@ -# Generated by h2py from /usr/include/sys/socket.h -SOCK_STREAM = 1 -SOCK_DGRAM = 2 -SOCK_RAW = 3 -SOCK_RDM = 4 -SOCK_SEQPACKET = 5 -SO_DEBUG = 0x0001 -SO_ACCEPTCONN = 0x0002 -SO_REUSEADDR = 0x0004 -SO_KEEPALIVE = 0x0008 -SO_DONTROUTE = 0x0010 -SO_BROADCAST = 0x0020 -SO_USELOOPBACK = 0x0040 -SO_LINGER = 0x0080 -SO_OOBINLINE = 0x0100 -SO_DONTLINGER = (~SO_LINGER) -SO_SNDBUF = 0x1001 -SO_RCVBUF = 0x1002 -SO_SNDLOWAT = 0x1003 -SO_RCVLOWAT = 0x1004 -SO_SNDTIMEO = 0x1005 -SO_RCVTIMEO = 0x1006 -SO_ERROR = 0x1007 -SO_TYPE = 0x1008 -SOL_SOCKET = 0xffff -AF_UNSPEC = 0 -AF_UNIX = 1 -AF_INET = 2 -AF_IMPLINK = 3 -AF_PUP = 4 -AF_CHAOS = 5 -AF_NS = 6 -AF_NBS = 7 -AF_ECMA = 8 -AF_DATAKIT = 9 -AF_CCITT = 10 -AF_SNA = 11 -AF_DECnet = 12 -AF_DLI = 13 -AF_LAT = 14 -AF_HYLINK = 15 -AF_APPLETALK = 16 -AF_NIT = 17 -AF_802 = 18 -AF_OSI = 19 -AF_X25 = 20 -AF_OSINET = 21 -AF_GOSIP = 22 -AF_MAX = 21 -PF_UNSPEC = AF_UNSPEC -PF_UNIX = AF_UNIX -PF_INET = AF_INET -PF_IMPLINK = AF_IMPLINK -PF_PUP = AF_PUP -PF_CHAOS = AF_CHAOS -PF_NS = AF_NS -PF_NBS = AF_NBS -PF_ECMA = AF_ECMA -PF_DATAKIT = AF_DATAKIT -PF_CCITT = AF_CCITT -PF_SNA = AF_SNA -PF_DECnet = AF_DECnet -PF_DLI = AF_DLI -PF_LAT = AF_LAT -PF_HYLINK = AF_HYLINK -PF_APPLETALK = AF_APPLETALK -PF_NIT = AF_NIT -PF_802 = AF_802 -PF_OSI = AF_OSI -PF_X25 = AF_X25 -PF_OSINET = AF_OSINET -PF_GOSIP = AF_GOSIP -PF_MAX = AF_MAX -SOMAXCONN = 5 -MSG_OOB = 0x1 -MSG_PEEK = 0x2 -MSG_DONTROUTE = 0x4 -MSG_MAXIOVLEN = 16 diff --git a/Lib/sunos4/SUNAUDIODEV.py b/Lib/sunos4/SUNAUDIODEV.py deleted file mode 100755 index b66610d903..0000000000 --- a/Lib/sunos4/SUNAUDIODEV.py +++ /dev/null @@ -1,38 +0,0 @@ -# Symbolic constants for use with sunaudiodev module -# The names are the same as in audioio.h with the leading AUDIO_ -# removed. - -# Not all values are supported on all releases of SunOS. - -# Encoding types, for fields i_encoding and o_encoding - -ENCODING_NONE = 0 # no encoding assigned -ENCODING_ULAW = 1 # u-law encoding -ENCODING_ALAW = 2 # A-law encoding -ENCODING_LINEAR = 3 # Linear PCM encoding - -# Gain ranges for i_gain, o_gain and monitor_gain - -MIN_GAIN = 0 # minimum gain value -MAX_GAIN = 255 # maximum gain value - -# Balance values for i_balance and o_balance - -LEFT_BALANCE = 0 # left channel only -MID_BALANCE = 32 # equal left/right channel -RIGHT_BALANCE = 64 # right channel only -BALANCE_SHIFT = 3 - -# Port names for i_port and o_port - -PORT_A = 1 -PORT_B = 2 -PORT_C = 3 -PORT_D = 4 - -SPEAKER = 0x01 # output to built-in speaker -HEADPHONE = 0x02 # output to headphone jack -LINE_OUT = 0x04 # output to line out - -MICROPHONE = 0x01 # input from microphone -LINE_IN = 0x02 # input from line in diff --git a/Lib/sunos4/WAIT.py b/Lib/sunos4/WAIT.py deleted file mode 100755 index 43612f00c0..0000000000 --- a/Lib/sunos4/WAIT.py +++ /dev/null @@ -1,13 +0,0 @@ -# Generated by h2py from /usr/include/sys/wait.h -WUNTRACED = 0004 -WNOHANG = 0100 -WEXITED = 0001 -WTRAPPED = 0002 -WSTOPPED = WUNTRACED -WCONTINUED = 0010 -WNOWAIT = 0200 -WOPTMASK = (WEXITED|WTRAPPED|WSTOPPED|WCONTINUED|WNOHANG|WNOWAIT) -WSTOPFLG = 0177 -WCONTFLG = 0177777 -WCOREFLG = 0200 -WSIGMASK = 0177 diff --git a/Lib/sunos4/regen b/Lib/sunos4/regen deleted file mode 100755 index 8b52d741bf..0000000000 --- a/Lib/sunos4/regen +++ /dev/null @@ -1,12 +0,0 @@ -#! /bin/sh -case `uname -sr` in -'SunOS 4.'*) ;; -*) echo Probably not on a SunOS 4 system 1>&2 - exit 1;; -esac -set -v -h2py </usr/include/sys/fcntlcom.h >FCNTL.py -echo "O_ACCMODE = (O_RDONLY|O_WRONLY|O_RDWR)" >>FCNTL.py -h2py /usr/include/sys/socket.h -h2py /usr/include/sys/wait.h -h2py -i '(u_long)' /usr/include/netinet/in.h diff --git a/Lib/sunos5/FCNTL.py b/Lib/sunos5/FCNTL.py deleted file mode 100755 index 89ce2ed38e..0000000000 --- a/Lib/sunos5/FCNTL.py +++ /dev/null @@ -1,47 +0,0 @@ -# Generated by h2py from /usr/include/sys/fcntl.h -O_RDONLY = 0 -O_WRONLY = 1 -O_RDWR = 2 -O_NDELAY = 0x04 -O_APPEND = 0x08 -O_SYNC = 0x10 -O_DSYNC = 0x40 -O_RSYNC = 0x8000 -O_NONBLOCK = 0x80 -O_PRIV = 0x1000 -O_CREAT = 0x100 -O_TRUNC = 0x200 -O_EXCL = 0x400 -O_NOCTTY = 0x800 -F_DUPFD = 0 -F_GETFD = 1 -F_SETFD = 2 -F_GETFL = 3 -F_SETFL = 4 -F_SETLK = 6 -F_SETLKW = 7 -F_O_GETLK = 5 -F_SETLK = 6 -F_SETLKW = 7 -F_CHKFL = 8 -F_ALLOCSP = 10 -F_FREESP = 11 -F_ISSTREAM = 13 -F_GETLK = 14 -F_PRIV = 15 -F_NPRIV = 16 -F_QUOTACTL = 17 -F_BLOCKS = 18 -F_BLKSIZE = 19 -F_RSETLK = 20 -F_RGETLK = 21 -F_RSETLKW = 22 -F_GETOWN = 23 -F_SETOWN = 24 -F_REVOKE = 25 -F_RDLCK = 01 -F_WRLCK = 02 -F_UNLCK = 03 -F_UNLKSYS = 04 -O_ACCMODE = 3 -FD_CLOEXEC = 1 diff --git a/Lib/sunos5/IN.py b/Lib/sunos5/IN.py deleted file mode 100755 index b4421ba7f0..0000000000 --- a/Lib/sunos5/IN.py +++ /dev/null @@ -1,81 +0,0 @@ -# Generated by h2py from /usr/include/netinet/in.h -IPPROTO_IP = 0 -IPPROTO_ICMP = 1 -IPPROTO_IGMP = 2 -IPPROTO_GGP = 3 -IPPROTO_ENCAP = 4 -IPPROTO_TCP = 6 -IPPROTO_EGP = 8 -IPPROTO_PUP = 12 -IPPROTO_UDP = 17 -IPPROTO_IDP = 22 -IPPROTO_HELLO = 63 -IPPROTO_ND = 77 -IPPROTO_EON = 80 -IPPROTO_RAW = 255 -IPPROTO_MAX = 256 -IPPORT_ECHO = 7 -IPPORT_DISCARD = 9 -IPPORT_SYSTAT = 11 -IPPORT_DAYTIME = 13 -IPPORT_NETSTAT = 15 -IPPORT_FTP = 21 -IPPORT_TELNET = 23 -IPPORT_SMTP = 25 -IPPORT_TIMESERVER = 37 -IPPORT_NAMESERVER = 42 -IPPORT_WHOIS = 43 -IPPORT_MTP = 57 -IPPORT_TFTP = 69 -IPPORT_RJE = 77 -IPPORT_FINGER = 79 -IPPORT_TTYLINK = 87 -IPPORT_SUPDUP = 95 -IPPORT_EXECSERVER = 512 -IPPORT_LOGINSERVER = 513 -IPPORT_CMDSERVER = 514 -IPPORT_EFSSERVER = 520 -IPPORT_BIFFUDP = 512 -IPPORT_WHOSERVER = 513 -IPPORT_ROUTESERVER = 520 -IPPORT_RESERVED = 1024 -IPPORT_USERRESERVED = 5000 -IMPLINK_IP = 155 -IMPLINK_LOWEXPER = 156 -IMPLINK_HIGHEXPER = 158 -IN_CLASSA_NET = 0xff000000 -IN_CLASSA_NSHIFT = 24 -IN_CLASSA_HOST = 0x00ffffff -IN_CLASSA_MAX = 128 -IN_CLASSB_NET = 0xffff0000 -IN_CLASSB_NSHIFT = 16 -IN_CLASSB_HOST = 0x0000ffff -IN_CLASSB_MAX = 65536 -IN_CLASSC_NET = 0xffffff00 -IN_CLASSC_NSHIFT = 8 -IN_CLASSC_HOST = 0x000000ff -IN_CLASSD_NET = 0xf0000000 -IN_CLASSD_NSHIFT = 28 -IN_CLASSD_HOST = 0x0fffffff -INADDR_ANY = 0x00000000 -INADDR_LOOPBACK = 0x7F000001 -INADDR_BROADCAST = 0xffffffff -INADDR_UNSPEC_GROUP = 0xe0000000 -INADDR_ALLHOSTS_GROUP = 0xe0000001 -INADDR_MAX_LOCAL_GROUP = 0xe00000ff -IN_LOOPBACKNET = 127 -IP_OPTIONS = 1 -IP_HDRINCL = 2 -IP_TOS = 3 -IP_TTL = 4 -IP_RECVOPTS = 5 -IP_RECVRETOPTS = 6 -IP_RECVDSTADDR = 7 -IP_RETOPTS = 8 -IP_MULTICAST_IF = 0x10 -IP_MULTICAST_TTL = 0x11 -IP_MULTICAST_LOOP = 0x12 -IP_ADD_MEMBERSHIP = 0x13 -IP_DROP_MEMBERSHIP = 0x14 -IP_DEFAULT_MULTICAST_TTL = 1 -IP_DEFAULT_MULTICAST_LOOP = 1 diff --git a/Lib/sunos5/SOCKET.py b/Lib/sunos5/SOCKET.py deleted file mode 100755 index 3ac2740c0e..0000000000 --- a/Lib/sunos5/SOCKET.py +++ /dev/null @@ -1,103 +0,0 @@ -# Generated by h2py from /usr/include/sys/socket.h -NC_TPI_CLTS = 1 -NC_TPI_COTS = 2 -NC_TPI_COTS_ORD = 3 -NC_TPI_RAW = 4 -SOCK_STREAM = NC_TPI_COTS -SOCK_DGRAM = NC_TPI_CLTS -SOCK_RAW = NC_TPI_RAW -SOCK_RDM = 5 -SOCK_SEQPACKET = 6 -SO_DEBUG = 0x0001 -SO_ACCEPTCONN = 0x0002 -SO_REUSEADDR = 0x0004 -SO_KEEPALIVE = 0x0008 -SO_DONTROUTE = 0x0010 -SO_BROADCAST = 0x0020 -SO_USELOOPBACK = 0x0040 -SO_LINGER = 0x0080 -SO_OOBINLINE = 0x0100 -SO_DONTLINGER = (~SO_LINGER) -SO_SNDBUF = 0x1001 -SO_RCVBUF = 0x1002 -SO_SNDLOWAT = 0x1003 -SO_RCVLOWAT = 0x1004 -SO_SNDTIMEO = 0x1005 -SO_RCVTIMEO = 0x1006 -SO_ERROR = 0x1007 -SO_TYPE = 0x1008 -SO_PROTOTYPE = 0x1009 -SOL_SOCKET = 0xffff -AF_UNSPEC = 0 -AF_UNIX = 1 -AF_INET = 2 -AF_IMPLINK = 3 -AF_PUP = 4 -AF_CHAOS = 5 -AF_NS = 6 -AF_NBS = 7 -AF_ECMA = 8 -AF_DATAKIT = 9 -AF_CCITT = 10 -AF_SNA = 11 -AF_DECnet = 12 -AF_DLI = 13 -AF_LAT = 14 -AF_HYLINK = 15 -AF_APPLETALK = 16 -AF_NIT = 17 -AF_802 = 18 -AF_OSI = 19 -AF_X25 = 20 -AF_OSINET = 21 -AF_GOSIP = 22 -AF_MAX = 22 -PF_UNSPEC = AF_UNSPEC -PF_UNIX = AF_UNIX -PF_INET = AF_INET -PF_IMPLINK = AF_IMPLINK -PF_PUP = AF_PUP -PF_CHAOS = AF_CHAOS -PF_NS = AF_NS -PF_NBS = AF_NBS -PF_ECMA = AF_ECMA -PF_DATAKIT = AF_DATAKIT -PF_CCITT = AF_CCITT -PF_SNA = AF_SNA -PF_DECnet = AF_DECnet -PF_DLI = AF_DLI -PF_LAT = AF_LAT -PF_HYLINK = AF_HYLINK -PF_APPLETALK = AF_APPLETALK -PF_NIT = AF_NIT -PF_802 = AF_802 -PF_OSI = AF_OSI -PF_X25 = AF_X25 -PF_OSINET = AF_OSINET -PF_GOSIP = AF_GOSIP -PF_MAX = AF_MAX -SOMAXCONN = 5 -MSG_OOB = 0x1 -MSG_PEEK = 0x2 -MSG_DONTROUTE = 0x4 -MSG_MAXIOVLEN = 16 -SOCKETSYS = 88 -SOCKETSYS = 83 -SO_ACCEPT = 1 -SO_BIND = 2 -SO_CONNECT = 3 -SO_GETPEERNAME = 4 -SO_GETSOCKNAME = 5 -SO_GETSOCKOPT = 6 -SO_LISTEN = 7 -SO_RECV = 8 -SO_RECVFROM = 9 -SO_SEND = 10 -SO_SENDTO = 11 -SO_SETSOCKOPT = 12 -SO_SHUTDOWN = 13 -SO_SOCKET = 14 -SO_SOCKPOLL = 15 -SO_GETIPDOMAIN = 16 -SO_SETIPDOMAIN = 17 -SO_ADJTIME = 18 diff --git a/Lib/sunos5/SUNAUDIODEV.py b/Lib/sunos5/SUNAUDIODEV.py deleted file mode 100755 index b66610d903..0000000000 --- a/Lib/sunos5/SUNAUDIODEV.py +++ /dev/null @@ -1,38 +0,0 @@ -# Symbolic constants for use with sunaudiodev module -# The names are the same as in audioio.h with the leading AUDIO_ -# removed. - -# Not all values are supported on all releases of SunOS. - -# Encoding types, for fields i_encoding and o_encoding - -ENCODING_NONE = 0 # no encoding assigned -ENCODING_ULAW = 1 # u-law encoding -ENCODING_ALAW = 2 # A-law encoding -ENCODING_LINEAR = 3 # Linear PCM encoding - -# Gain ranges for i_gain, o_gain and monitor_gain - -MIN_GAIN = 0 # minimum gain value -MAX_GAIN = 255 # maximum gain value - -# Balance values for i_balance and o_balance - -LEFT_BALANCE = 0 # left channel only -MID_BALANCE = 32 # equal left/right channel -RIGHT_BALANCE = 64 # right channel only -BALANCE_SHIFT = 3 - -# Port names for i_port and o_port - -PORT_A = 1 -PORT_B = 2 -PORT_C = 3 -PORT_D = 4 - -SPEAKER = 0x01 # output to built-in speaker -HEADPHONE = 0x02 # output to headphone jack -LINE_OUT = 0x04 # output to line out - -MICROPHONE = 0x01 # input from microphone -LINE_IN = 0x02 # input from line in diff --git a/Lib/sunos5/TERMIOS.py b/Lib/sunos5/TERMIOS.py deleted file mode 100755 index 264c884cc5..0000000000 --- a/Lib/sunos5/TERMIOS.py +++ /dev/null @@ -1,385 +0,0 @@ -# Generated by h2py from /usr/include/termios.h - -# Included from sys/termios.h - -# Included from sys/feature_tests.h -_POSIX_C_SOURCE = 1 - -# Included from sys/ttydev.h -B0 = 0 -B50 = 1 -B75 = 2 -B110 = 3 -B134 = 4 -B150 = 5 -B200 = 6 -B300 = 7 -B600 = 8 -B1200 = 9 -B1800 = 10 -B2400 = 11 -B4800 = 12 -B9600 = 13 -B19200 = 14 -B38400 = 15 -EXTA = 14 -EXTB = 15 - -# Included from sys/types.h - -# Included from sys/machtypes.h - -# Included from sys/isa_defs.h -SHRT_MIN = -32768 -SHRT_MAX = 32767 -INT_MIN = (-2147483647-1) -INT_MAX = 2147483647 -LONG_MIN = (-2147483647-1) -LONG_MAX = 2147483647 -P_MYID = (-1) - -# Included from sys/select.h - -# Included from sys/time.h -DST_NONE = 0 -DST_USA = 1 -DST_AUST = 2 -DST_WET = 3 -DST_MET = 4 -DST_EET = 5 -DST_CAN = 6 -DST_GB = 7 -DST_RUM = 8 -DST_TUR = 9 -DST_AUSTALT = 10 -ITIMER_REAL = 0 -ITIMER_VIRTUAL = 1 -ITIMER_PROF = 2 -ITIMER_REALPROF = 3 -SEC = 1 -MILLISEC = 1000 -MICROSEC = 1000000 -NANOSEC = 1000000000 -CLOCK_REALTIME = 0 -CLOCK_VIRTUAL = 1 -CLOCK_PROF = 2 -TIMER_RELTIME = 0x0 -TIMER_ABSTIME = 0x1 - -# Included from sys/mutex.h - -# Included from sys/dki_lkinfo.h - -# Included from sys/dl.h -NOSTATS = 1 -LSB_NLKDS = 91 -def MUTEX_HELD(x): return (mutex_owned(x)) - - -# Included from time.h -NULL = 0 -CLOCKS_PER_SEC = 1000000 - -# Included from sys/siginfo.h -SIGEV_NONE = 1 -SIGEV_SIGNAL = 2 -SI_NOINFO = 32767 -SI_USER = 0 -SI_LWP = (-1) -SI_QUEUE = (-2) -SI_TIMER = (-3) -SI_ASYNCIO = (-4) -SI_MESGQ = (-5) - -# Included from sys/machsig.h -ILL_ILLOPC = 1 -ILL_ILLOPN = 2 -ILL_ILLADR = 3 -ILL_ILLTRP = 4 -ILL_PRVOPC = 5 -ILL_PRVREG = 6 -ILL_COPROC = 7 -ILL_BADSTK = 8 -NSIGILL = 8 -EMT_TAGOVF = 1 -NSIGEMT = 1 -FPE_INTDIV = 1 -FPE_INTOVF = 2 -FPE_FLTDIV = 3 -FPE_FLTOVF = 4 -FPE_FLTUND = 5 -FPE_FLTRES = 6 -FPE_FLTINV = 7 -FPE_FLTSUB = 8 -NSIGFPE = 8 -SEGV_MAPERR = 1 -SEGV_ACCERR = 2 -NSIGSEGV = 2 -BUS_ADRALN = 1 -BUS_ADRERR = 2 -BUS_OBJERR = 3 -NSIGBUS = 3 -TRAP_BRKPT = 1 -TRAP_TRACE = 2 -NSIGTRAP = 2 -CLD_EXITED = 1 -CLD_KILLED = 2 -CLD_DUMPED = 3 -CLD_TRAPPED = 4 -CLD_STOPPED = 5 -CLD_CONTINUED = 6 -NSIGCLD = 6 -POLL_IN = 1 -POLL_OUT = 2 -POLL_MSG = 3 -POLL_ERR = 4 -POLL_PRI = 5 -POLL_HUP = 6 -NSIGPOLL = 6 -PROF_SIG = 1 -NSIGPROF = 1 -SI_MAXSZ = 128 -FD_SETSIZE = 1024 -NBBY = 8 -_POSIX_VDISABLE = 0 -def CTRL(c): return ((c)&037) - -IBSHIFT = 16 -NCC = 8 -NCCS = 19 -VINTR = 0 -VQUIT = 1 -VERASE = 2 -VKILL = 3 -VEOF = 4 -VEOL = 5 -VEOL2 = 6 -VMIN = 4 -VTIME = 5 -VSWTCH = 7 -VSTART = 8 -VSTOP = 9 -VSUSP = 10 -VDSUSP = 11 -VREPRINT = 12 -VDISCARD = 13 -VWERASE = 14 -VLNEXT = 15 -VCEOF = NCC -VCEOL = (NCC + 1) -CNUL = 0 -CDEL = 0177 -CESC = ord('\\') -CINTR = CTRL(ord('c')) -CQUIT = 034 -CERASE = 0177 -CKILL = CTRL(ord('u')) -CEOT = 04 -CEOL = 0 -CEOL2 = 0 -CEOF = 04 -CSTART = 021 -CSTOP = 023 -CSWTCH = 032 -CNSWTCH = 0 -CSUSP = CTRL(ord('z')) -CDSUSP = CTRL(ord('y')) -CRPRNT = CTRL(ord('r')) -CFLUSH = CTRL(ord('o')) -CWERASE = CTRL(ord('w')) -CLNEXT = CTRL(ord('v')) -IGNBRK = 0000001 -BRKINT = 0000002 -IGNPAR = 0000004 -PARMRK = 0000010 -INPCK = 0000020 -ISTRIP = 0000040 -INLCR = 0000100 -IGNCR = 0000200 -ICRNL = 0000400 -IUCLC = 0001000 -IXON = 0002000 -IXANY = 0004000 -IXOFF = 0010000 -IMAXBEL = 0020000 -DOSMODE = 0100000 -OPOST = 0000001 -OLCUC = 0000002 -ONLCR = 0000004 -OCRNL = 0000010 -ONOCR = 0000020 -ONLRET = 0000040 -OFILL = 0000100 -OFDEL = 0000200 -NLDLY = 0000400 -NL0 = 0 -NL1 = 0000400 -CRDLY = 0003000 -CR0 = 0 -CR1 = 0001000 -CR2 = 0002000 -CR3 = 0003000 -TABDLY = 0014000 -TAB0 = 0 -TAB1 = 0004000 -TAB2 = 0010000 -TAB3 = 0014000 -XTABS = 0014000 -BSDLY = 0020000 -BS0 = 0 -BS1 = 0020000 -VTDLY = 0040000 -VT0 = 0 -VT1 = 0040000 -FFDLY = 0100000 -FF0 = 0 -FF1 = 0100000 -PAGEOUT = 0200000 -WRAP = 0400000 -CBAUD = 0000017 -CSIZE = 0000060 -CS5 = 0 -CS6 = 0000020 -CS7 = 0000040 -CS8 = 0000060 -CSTOPB = 0000100 -CREAD = 0000200 -PARENB = 0000400 -PARODD = 0001000 -HUPCL = 0002000 -CLOCAL = 0004000 -RCV1EN = 0010000 -XMT1EN = 0020000 -LOBLK = 0040000 -XCLUDE = 0100000 -CRTSCTS = 020000000000 -CIBAUD = 03600000 -PAREXT = 04000000 -ISIG = 0000001 -ICANON = 0000002 -XCASE = 0000004 -ECHO = 0000010 -ECHOE = 0000020 -ECHOK = 0000040 -ECHONL = 0000100 -NOFLSH = 0000200 -TOSTOP = 0000400 -ECHOCTL = 0001000 -ECHOPRT = 0002000 -ECHOKE = 0004000 -DEFECHO = 0010000 -FLUSHO = 0020000 -PENDIN = 0040000 -IEXTEN = 0100000 -_TIOC = (ord('T')<<8) -TIOC = _TIOC -TCGETA = (_TIOC|1) -TCSETA = (_TIOC|2) -TCSETAW = (_TIOC|3) -TCSETAF = (_TIOC|4) -TCSBRK = (_TIOC|5) -TCXONC = (_TIOC|6) -TCFLSH = (_TIOC|7) -TIOCKBON = (_TIOC|8) -TIOCKBOF = (_TIOC|9) -KBENABLED = (_TIOC|10) -IOCTYPE = 0xff00 -TCDSET = (_TIOC|32) -RTS_TOG = (_TIOC|33) -TIOCGWINSZ = (_TIOC|104) -TIOCSWINSZ = (_TIOC|103) -TIOCGSOFTCAR = (_TIOC|105) -TIOCSSOFTCAR = (_TIOC|106) -TCGETS = (_TIOC|13) -TCSETS = (_TIOC|14) -TCSANOW = (_TIOC|14) -TCSETSW = (_TIOC|15) -TCSADRAIN = (_TIOC|15) -TCSETSF = (_TIOC|16) -TCSAFLUSH = (_TIOC|16) -TCIFLUSH = 0 -TCOFLUSH = 1 -TCIOFLUSH = 2 -TCOOFF = 0 -TCOON = 1 -TCIOFF = 2 -TCION = 3 -tIOC = (ord('t')<<8) -TIOCGETD = (tIOC|0) -TIOCSETD = (tIOC|1) -TIOCHPCL = (tIOC|2) -TIOCGETP = (tIOC|8) -TIOCSETP = (tIOC|9) -TIOCSETN = (tIOC|10) -TIOCEXCL = (tIOC|13) -TIOCNXCL = (tIOC|14) -TIOCFLUSH = (tIOC|16) -TIOCSETC = (tIOC|17) -TIOCGETC = (tIOC|18) -TIOCLBIS = (tIOC|127) -TIOCLBIC = (tIOC|126) -TIOCLSET = (tIOC|125) -TIOCLGET = (tIOC|124) -TIOCSBRK = (tIOC|123) -TIOCCBRK = (tIOC|122) -TIOCSDTR = (tIOC|121) -TIOCCDTR = (tIOC|120) -TIOCSLTC = (tIOC|117) -TIOCGLTC = (tIOC|116) -TIOCOUTQ = (tIOC|115) -TIOCNOTTY = (tIOC|113) -TIOCSTOP = (tIOC|111) -TIOCSTART = (tIOC|110) -TIOCGPGRP = (tIOC|20) -TIOCSPGRP = (tIOC|21) -TIOCGSID = (tIOC|22) -TIOCSSID = (tIOC|24) -TIOCSTI = (tIOC|23) -TIOCMSET = (tIOC|26) -TIOCMBIS = (tIOC|27) -TIOCMBIC = (tIOC|28) -TIOCMGET = (tIOC|29) -TIOCM_LE = 0001 -TIOCM_DTR = 0002 -TIOCM_RTS = 0004 -TIOCM_ST = 0010 -TIOCM_SR = 0020 -TIOCM_CTS = 0040 -TIOCM_CAR = 0100 -TIOCM_CD = TIOCM_CAR -TIOCM_RNG = 0200 -TIOCM_RI = TIOCM_RNG -TIOCM_DSR = 0400 -TIOCREMOTE = (tIOC|30) -TIOCSIGNAL = (tIOC|31) -LDIOC = (ord('D')<<8) -LDOPEN = (LDIOC|0) -LDCLOSE = (LDIOC|1) -LDCHG = (LDIOC|2) -LDGETT = (LDIOC|8) -LDSETT = (LDIOC|9) -LDSMAP = (LDIOC|110) -LDGMAP = (LDIOC|111) -LDNMAP = (LDIOC|112) -LDEMAP = (LDIOC|113) -LDDMAP = (LDIOC|114) -DIOC = (ord('d')<<8) -DIOCGETP = (DIOC|8) -DIOCSETP = (DIOC|9) -FIORDCHK = ((ord('f')<<8)|3) -B0 = 0 -B50 = 1 -B75 = 2 -B110 = 3 -B134 = 4 -B150 = 5 -B200 = 6 -B300 = 7 -B600 = 8 -B1200 = 9 -B1800 = 10 -B2400 = 11 -B4800 = 12 -B9600 = 13 -B19200 = 14 -B38400 = 15 diff --git a/Lib/sunos5/regen b/Lib/sunos5/regen deleted file mode 100755 index 2f2cdeff91..0000000000 --- a/Lib/sunos5/regen +++ /dev/null @@ -1,11 +0,0 @@ -#! /bin/sh -case `uname -sr` in -'SunOS 5.'*) ;; -*) echo Probably not on a Solaris 2 system 1>&2 - exit 1;; -esac -set -v -h2py /usr/include/sys/fcntl.h -h2py /usr/include/sys/socket.h -h2py -i '(u_long)' /usr/include/netinet/in.h -h2py /usr/include/termios.h diff --git a/Lib/symbol.py b/Lib/symbol.py deleted file mode 100755 index f3ec122625..0000000000 --- a/Lib/symbol.py +++ /dev/null @@ -1,60 +0,0 @@ -# Non-terminal symbols of Python grammar (from "graminit.h") - -single_input = 256 -file_input = 257 -eval_input = 258 -funcdef = 259 -parameters = 260 -varargslist = 261 -fpdef = 262 -fplist = 263 -stmt = 264 -simple_stmt = 265 -small_stmt = 266 -expr_stmt = 267 -print_stmt = 268 -del_stmt = 269 -pass_stmt = 270 -flow_stmt = 271 -break_stmt = 272 -continue_stmt = 273 -return_stmt = 274 -raise_stmt = 275 -import_stmt = 276 -global_stmt = 277 -access_stmt = 278 -accesstype = 279 -exec_stmt = 280 -compound_stmt = 281 -if_stmt = 282 -while_stmt = 283 -for_stmt = 284 -try_stmt = 285 -except_clause = 286 -suite = 287 -test = 288 -and_test = 289 -not_test = 290 -comparison = 291 -comp_op = 292 -expr = 293 -xor_expr = 294 -and_expr = 295 -shift_expr = 296 -arith_expr = 297 -term = 298 -factor = 299 -atom = 300 -lambdef = 301 -trailer = 302 -subscript = 303 -exprlist = 304 -testlist = 305 -dictmaker = 306 -classdef = 307 - -names = dir() -sym_name = {} -for name in names: - number = eval(name) - sym_name[number] = name diff --git a/Lib/tb.py b/Lib/tb.py deleted file mode 100644 index 641e8af2e8..0000000000 --- a/Lib/tb.py +++ /dev/null @@ -1,177 +0,0 @@ -# Print tracebacks, with a dump of local variables. -# Also an interactive stack trace browser. -# Note -- this module is obsolete -- use pdb.pm() instead. - -import sys -import os -from stat import * -import string -import linecache - -def br(): browser(sys.last_traceback) - -def tb(): printtb(sys.last_traceback) - -def browser(tb): - if not tb: - print 'No traceback.' - return - tblist = [] - while tb: - tblist.append(tb) - tb = tb.tb_next - ptr = len(tblist)-1 - tb = tblist[ptr] - while 1: - if tb <> tblist[ptr]: - tb = tblist[ptr] - print `ptr` + ':', - printtbheader(tb) - try: - line = raw_input('TB: ') - except KeyboardInterrupt: - print '\n[Interrupted]' - break - except EOFError: - print '\n[EOF]' - break - cmd = string.strip(line) - if cmd: - if cmd == 'quit': - break - elif cmd == 'list': - browserlist(tb) - elif cmd == 'up': - if ptr-1 >= 0: ptr = ptr-1 - else: print 'Bottom of stack.' - elif cmd == 'down': - if ptr+1 < len(tblist): ptr = ptr+1 - else: print 'Top of stack.' - elif cmd == 'locals': - printsymbols(tb.tb_frame.f_locals) - elif cmd == 'globals': - printsymbols(tb.tb_frame.f_globals) - elif cmd in ('?', 'help'): - browserhelp() - else: - browserexec(tb, cmd) - -def browserlist(tb): - filename = tb.tb_frame.f_code.co_filename - lineno = tb.tb_lineno - last = lineno - first = max(1, last-10) - for i in range(first, last+1): - if i == lineno: prefix = '***' + string.rjust(`i`, 4) + ':' - else: prefix = string.rjust(`i`, 7) + ':' - line = linecache.getline(filename, i) - if line[-1:] == '\n': line = line[:-1] - print prefix + line - -def browserexec(tb, cmd): - locals = tb.tb_frame.f_locals - globals = tb.tb_frame.f_globals - try: - exec cmd+'\n' in globals, locals - except: - print '*** Exception:', - if type(sys.exc_type) == type(''): - print sys.exc_type, - else: - print sys.exc_type.__name__, - if sys.exc_value <> None: - print ':', sys.exc_value, - print - print 'Type help to get help.' - -def browserhelp(): - print - print ' This is the traceback browser. Commands are:' - print ' up : move one level up in the call stack' - print ' down : move one level down in the call stack' - print ' locals : print all local variables at this level' - print ' globals : print all global variables at this level' - print ' list : list source code around the failure' - print ' help : print help (what you are reading now)' - print ' quit : back to command interpreter' - print ' Typing any other 1-line statement will execute it' - print ' using the current level\'s symbol tables' - print - -def printtb(tb): - while tb: - print1tb(tb) - tb = tb.tb_next - -def print1tb(tb): - printtbheader(tb) - if tb.tb_frame.f_locals is not tb.tb_frame.f_globals: - printsymbols(tb.tb_frame.f_locals) - -def printtbheader(tb): - filename = tb.tb_frame.f_code.co_filename - lineno = tb.tb_lineno - info = '"' + filename + '"(' + `lineno` + ')' - line = linecache.getline(filename, lineno) - if line: - info = info + ': ' + string.strip(line) - print info - -def printsymbols(d): - keys = d.keys() - keys.sort() - for name in keys: - print ' ' + string.ljust(name, 12) + ':', - printobject(d[name], 4) - print - -def printobject(v, maxlevel): - if v == None: - print 'None', - elif type(v) in (type(0), type(0.0)): - print v, - elif type(v) == type(''): - if len(v) > 20: - print `v[:17] + '...'`, - else: - print `v`, - elif type(v) == type(()): - print '(', - printlist(v, maxlevel) - print ')', - elif type(v) == type([]): - print '[', - printlist(v, maxlevel) - print ']', - elif type(v) == type({}): - print '{', - printdict(v, maxlevel) - print '}', - else: - print v, - -def printlist(v, maxlevel): - n = len(v) - if n == 0: return - if maxlevel <= 0: - print '...', - return - for i in range(min(6, n)): - printobject(v[i], maxlevel-1) - if i+1 < n: print ',', - if n > 6: print '...', - -def printdict(v, maxlevel): - keys = v.keys() - n = len(keys) - if n == 0: return - if maxlevel <= 0: - print '...', - return - keys.sort() - for i in range(min(6, n)): - key = keys[i] - print `key` + ':', - printobject(v[key], maxlevel-1) - if i+1 < n: print ',', - if n > 6: print '...', diff --git a/Lib/tempfile.py b/Lib/tempfile.py deleted file mode 100644 index f95920d5a4..0000000000 --- a/Lib/tempfile.py +++ /dev/null @@ -1,69 +0,0 @@ -# Temporary file name allocation -# -# XXX This tries to be not UNIX specific, but I don't know beans about -# how to choose a temp directory or filename on MS-DOS or other -# systems so it may have to be changed... - - -import os - - -# Parameters that the caller may set to override the defaults - -tempdir = None -template = None - - -# Function to calculate the directory to use - -def gettempdir(): - global tempdir - attempdirs = ['/usr/tmp', '/tmp', os.getcwd(), os.curdir] - if os.environ.has_key('TMPDIR'): - attempdirs.insert(0, os.environ['TMPDIR']) - testfile = gettempprefix() + '-*-writetest-*-' - for dir in attempdirs: - try: - filename = os.path.join(dir, testfile) - fp = open(filename, 'w') - fp.write('blat') - fp.close() - os.unlink(filename) - tempdir = dir - break - except IOError: - pass - if tempdir is None: - msg = "Can't find a usable temporary directory amongst " + `attempdirs` - raise IOError, msg - return tempdir - - -# Function to calculate a prefix of the filename to use - -def gettempprefix(): - global template - if template == None: - if os.name == 'posix': - template = '@' + `os.getpid()` + '.' - else: - template = 'tmp' # XXX might choose a better one - return template - - -# Counter for generating unique names - -counter = 0 - - -# User-callable function to return a unique temporary file name - -def mktemp(): - global counter - dir = gettempdir() - pre = gettempprefix() - while 1: - counter = counter + 1 - file = os.path.join(dir, pre + `counter`) - if not os.path.exists(file): - return file diff --git a/Lib/test/autotest.py b/Lib/test/autotest.py deleted file mode 100644 index 79d9b11553..0000000000 --- a/Lib/test/autotest.py +++ /dev/null @@ -1,67 +0,0 @@ -# Automatic Python regression test. -# -# Some essential parts of the Python interpreter are tested by the module -# 'testall'. (Despite its name, it doesn't test everything -- that would -# be a truly Herculean task!) When a test fails, 'testall' raises an -# exception. When all tests succeed, it produces quite a lot of output. -# -# For a normal regression test, this output is never looked at unless -# something goes wrong. Thus, it would be wise to suppress the output -# normally. This module does that, but it doesn't just throw the output -# from 'testall' away -- it compares it with the output from a previous -# run. If a difference is noticed it raises an exception; if all is well, -# it prints nothing except 'All tests OK.' at the very end. -# -# The output from a previous run is supposed to be in a file 'testall.out' -# somewhere on the search path for modules (sys.path, initialized from -# $PYTHONPATH plus some default places). -# -# Of course, if the normal output of the tests is changed because the -# tests have been changed (rather than a test producing the wrong output), -# 'autotest' will fail as well. In this case, run 'testall' manually -# and direct its output to 'testall.out'. -# -# The comparison uses (and demonstrates!) a rather new Python feature: -# program output that normally goes to stdout (by 'print' statements -# or by writing directly to sys.stdout) can be redirected to an -# arbitrary class instance as long as it has a 'write' method. - -import os -import sys - -# Function to find a file somewhere on sys.path -def findfile(filename): - for dirname in sys.path: - fullname = os.path.join(dirname, filename) - if os.path.exists(fullname): - return fullname - return filename # Will cause exception later - -# Exception raised when the test failed (not the same as in test_support) -TestFailed = 'autotest.TestFailed' - -# Class substituted for sys.stdout, to compare it with the given file -class Compare: - def __init__(self, filename): - self.fp = open(filename, 'r') - def write(self, data): - expected = self.fp.read(len(data)) - if data <> expected: - raise TestFailed, \ - 'Writing: '+`data`+', expected: '+`expected` - def close(self): - self.fp.close() - -# The main program -def main(): - import sys - filename = findfile('testall.out') - real_stdout = sys.stdout - try: - sys.stdout = Compare(filename) - import testall - finally: - sys.stdout = real_stdout - print 'All tests OK.' - -main() diff --git a/Lib/test/pystone.py b/Lib/test/pystone.py deleted file mode 100755 index 954e6c9ebf..0000000000 --- a/Lib/test/pystone.py +++ /dev/null @@ -1,229 +0,0 @@ -#! /usr/local/bin/python - -""" -"PYSTONE" Benchmark Program - -Version: Python/1.0 (corresponds to C/1.1) - -Author: Reinhold P. Weicker, CACM Vol 27, No 10, 10/84 pg. 1013. - - Translated from ADA to C by Rick Richardson. - Every method to preserve ADA-likeness has been used, - at the expense of C-ness. - - Translated from C to Python by Guido van Rossum. -""" - -LOOPS = 1000 - -from time import clock - -__version__ = "1.0" - -[Ident1, Ident2, Ident3, Ident4, Ident5] = range(1, 6) - -class Record: - - def __init__(self, PtrComp = None, Discr = 0, EnumComp = 0, - IntComp = 0, StringComp = 0): - self.PtrComp = PtrComp - self.Discr = Discr - self.EnumComp = EnumComp - self.IntComp = IntComp - self.StringComp = StringComp - - def copy(self): - return Record(self.PtrComp, self.Discr, self.EnumComp, - self.IntComp, self.StringComp) - -TRUE = 1 -FALSE = 0 - -def main(): - Proc0() - -IntGlob = 0 -BoolGlob = FALSE -Char1Glob = '\0' -Char2Glob = '\0' -Array1Glob = [0]*51 -Array2Glob = map(lambda x: x[:], [Array1Glob]*51) -PtrGlb = None -PtrGlbNext = None - -def Proc0(): - global IntGlob - global BoolGlob - global Char1Glob - global Char2Glob - global Array1Glob - global Array2Glob - global PtrGlb - global PtrGlbNext - - starttime = clock() - for i in range(LOOPS): - pass - nulltime = clock() - starttime - - PtrGlbNext = Record() - PtrGlb = Record() - PtrGlb.PtrComp = PtrGlbNext - PtrGlb.Discr = Ident1 - PtrGlb.EnumComp = Ident3 - PtrGlb.IntComp = 40 - PtrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING" - String1Loc = "DHRYSTONE PROGRAM, 1'ST STRING" - Array2Glob[8][7] = 10 - - starttime = clock() - - for i in range(LOOPS): - Proc5() - Proc4() - IntLoc1 = 2 - IntLoc2 = 3 - String2Loc = "DHRYSTONE PROGRAM, 2'ND STRING" - EnumLoc = Ident2 - BoolGlob = not Func2(String1Loc, String2Loc) - while IntLoc1 < IntLoc2: - IntLoc3 = 5 * IntLoc1 - IntLoc2 - IntLoc3 = Proc7(IntLoc1, IntLoc2) - IntLoc1 = IntLoc1 + 1 - Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3) - PtrGlb = Proc1(PtrGlb) - CharIndex = 'A' - while CharIndex <= Char2Glob: - if EnumLoc == Func1(CharIndex, 'C'): - EnumLoc = Proc6(Ident1) - CharIndex = chr(ord(CharIndex)+1) - IntLoc3 = IntLoc2 * IntLoc1 - IntLoc2 = IntLoc3 / IntLoc1 - IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1 - IntLoc1 = Proc2(IntLoc1) - - benchtime = clock() - starttime - nulltime - print "Pystone(%s) time for %d passes = %g" % \ - (__version__, LOOPS, benchtime) - print "This machine benchmarks at %g pystones/second" % \ - (LOOPS/benchtime) - -def Proc1(PtrParIn): - PtrParIn.PtrComp = NextRecord = PtrGlb.copy() - PtrParIn.IntComp = 5 - NextRecord.IntComp = PtrParIn.IntComp - NextRecord.PtrComp = PtrParIn.PtrComp - NextRecord.PtrComp = Proc3(NextRecord.PtrComp) - if NextRecord.Discr == Ident1: - NextRecord.IntComp = 6 - NextRecord.EnumComp = Proc6(PtrParIn.EnumComp) - NextRecord.PtrComp = PtrGlb.PtrComp - NextRecord.IntComp = Proc7(NextRecord.IntComp, 10) - else: - PtrParIn = NextRecord.copy() - return PtrParIn - -def Proc2(IntParIO): - IntLoc = IntParIO + 10 - while 1: - if Char1Glob == 'A': - IntLoc = IntLoc - 1 - IntParIO = IntLoc - IntGlob - EnumLoc = Ident1 - if EnumLoc == Ident1: - break - return IntParIO - -def Proc3(PtrParOut): - global IntGlob - - if PtrGlb != None: - PtrParOut = PtrGlb.PtrComp - else: - IntGlob = 100 - PtrGlb.IntComp = Proc7(10, IntGlob) - return PtrParOut - -def Proc4(): - global Char2Glob - - BoolLoc = Char1Glob == 'A' - BoolLoc = BoolLoc or BoolGlob - Char2Glob = 'B' - -def Proc5(): - global Char1Glob - global BoolGlob - - Char1Glob = 'A' - BoolGlob = FALSE - -def Proc6(EnumParIn): - EnumParOut = EnumParIn - if not Func3(EnumParIn): - EnumParOut = Ident4 - if EnumParIn == Ident1: - EnumParOut = Ident1 - elif EnumParIn == Ident2: - if IntGlob > 100: - EnumParOut = Ident1 - else: - EnumParOut = Ident4 - elif EnumParIn == Ident3: - EnumParOut = Ident2 - elif EnumParIn == Ident4: - pass - elif EnumParIn == Ident5: - EnumParOut = Ident3 - return EnumParOut - -def Proc7(IntParI1, IntParI2): - IntLoc = IntParI1 + 2 - IntParOut = IntParI2 + IntLoc - return IntParOut - -def Proc8(Array1Par, Array2Par, IntParI1, IntParI2): - global IntGlob - - IntLoc = IntParI1 + 5 - Array1Par[IntLoc] = IntParI2 - Array1Par[IntLoc+1] = Array1Par[IntLoc] - Array1Par[IntLoc+30] = IntLoc - for IntIndex in range(IntLoc, IntLoc+2): - Array2Par[IntLoc][IntIndex] = IntLoc - Array2Par[IntLoc][IntLoc-1] = Array2Par[IntLoc][IntLoc-1] + 1 - Array2Par[IntLoc+20][IntLoc] = Array1Par[IntLoc] - IntGlob = 5 - -def Func1(CharPar1, CharPar2): - CharLoc1 = CharPar1 - CharLoc2 = CharLoc1 - if CharLoc2 != CharPar2: - return Ident1 - else: - return Ident2 - -def Func2(StrParI1, StrParI2): - IntLoc = 1 - while IntLoc <= 1: - if Func1(StrParI1[IntLoc], StrParI2[IntLoc+1]) == Ident1: - CharLoc = 'A' - IntLoc = IntLoc + 1 - if CharLoc >= 'W' and CharLoc <= 'Z': - IntLoc = 7 - if CharLoc == 'X': - return TRUE - else: - if StrParI1 > StrParI2: - IntLoc = IntLoc + 7 - return TRUE - else: - return FALSE - -def Func3(EnumParIn): - EnumLoc = EnumParIn - if EnumLoc == Ident3: return TRUE - return FALSE - -if __name__ == '__main__': - main() diff --git a/Lib/test/test.rawimg b/Lib/test/test.rawimg deleted file mode 100644 index a6a0480948..0000000000 --- a/Lib/test/test.rawimg +++ /dev/null @@ -1,82 +0,0 @@ -ÿÿùøÿ!ÿ)#ÿÿÿÿÿ"ÿÿÿÿÿÿÿÿÿÿÿ!ÿÿÿ:76ÿ<:=ÿEDJÿIILÿOORÿ!ÿ#&ÿ"$ÿIFLÿGDJÿDBEÿ97:ÿDBEÿNLOÿQORÿÿÿ)%-ÿTV[ÿUW\ÿUW\ÿ\^cÿ\^cÿÿÿ"!(ÿYX^ÿUX]ÿX\^ÿY[^ÿÿ $ÿÿQSQÿ\ZUÿWVOÿSQSÿÿ"ÿHFHÿ=>8ÿIJDÿ)'*ÿ"&ÿ$#)ÿZ[\ÿ[YVÿ^XVÿ�||ÿ�~}ÿ^_`ÿPTVÿTW\ÿSUZÿRT[ÿNPWÿKMTÿFHOÿCELÿDIOÿHIPÿHGNÿFGNÿJOUÿIJQÿHGNÿCELÿIKRÿHIPÿFGNÿCDKÿBDLÿ@BJÿCELÿFINÿEHMÿDGLÿ@CHÿDGLÿACHÿCBHÿ?>DÿCBHÿACHÿ9<Aÿ;@Eÿ@?Eÿ>@Eÿ:<Aÿ:<Aÿ:<Aÿ;;>ÿ?=@ÿÿ%#&ÿÿ425ÿÿ'%(ÿÿÿÿÿÿùîõÿ>4>ÿ&+ÿ!ÿÿÿÿÿÿÿÿÿÿÿÿÿÿ,'-ÿ!ÿÿÿÿÿÿA?BÿIGJÿÿ#ÿÿÿÿÿ ÿ"!ÿ$#ÿ(#'ÿÿÿ$ÿKOQÿMORÿPPSÿQQTÿTTWÿÿÿ/-0ÿiifÿUVWÿQSQÿQPOÿÿ#(ÿÿXXUÿXXUÿ[XSÿTPRÿ ÿ!ÿXVXÿ[ZSÿ[YTÿ%"!ÿ!%ÿÿ_]`ÿGEGÿ-+-ÿ" "ÿ('&ÿRSMÿy~xÿ‘‘ŽÿojlÿWWZÿRTWÿQSVÿPRWÿNOVÿIPVÿHOUÿDHPÿEFQÿFHPÿGIPÿFHOÿDFMÿACJÿDFMÿACJÿ@BIÿ@BIÿACJÿDFMÿACJÿ>AFÿBEJÿADIÿDGLÿACJÿACJÿ=?Fÿ@BIÿ@BGÿ>@Eÿ?AFÿ>@Eÿ9;@ÿ=?Dÿ<>Cÿ:<Aÿ=;>ÿ757ÿ202ÿ0.0ÿ-)+ÿ&"$ÿÿÿÿ -ÿÿÿÿÿõúÿ/%.ÿG>Kÿ!"ÿÿÿÿÿÿÿÿÿÿÿ - ÿvrtÿIDJÿÿÿÿÿÿÿÿÿ - ÿÿ"ÿÿÿÿÿÿÿÿÿÿÿ!ÿÿ!!ÿ1/1ÿ?=?ÿLJLÿÿÿ%#&ÿQQNÿQSQÿORLÿRROÿÿ#&ÿÿYYVÿUURÿVSNÿXTVÿ ÿÿXWVÿYZTÿXYRÿ%#%ÿ!ÿ ÿ\[aÿ]\bÿa`fÿÿ$$'ÿWXYÿPPMÿWQOÿ^VTÿVRPÿz}wÿ`c]ÿWYWÿVWXÿLQVÿKOWÿJPZÿGJVÿNPXÿJLSÿGIPÿGIPÿEGNÿFHOÿGIPÿDFMÿ>@Gÿ@BIÿ;=DÿCELÿ@CHÿADIÿJMRÿ>AFÿ?AHÿ?AHÿ>@GÿBDKÿ>@Eÿ>@Eÿ?AFÿ>@Eÿ::=ÿ225ÿ--0ÿ''*ÿ+)+ÿ(&(ÿ*(*ÿ#!#ÿ%!#ÿ)%'ÿ" ÿ.*,ÿÿÿÿÿÿúññÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ!ÿÿÿÿÿÿÿÿÿÿÿÿÿÿ# ÿ'$#ÿ!ÿÿÿ !ÿKKHÿMOLÿNRJÿNOHÿÿ!ÿÿVVSÿZZWÿ\YTÿYUWÿÿ ÿ`_eÿ]^_ÿabcÿ=<Cÿÿ"ÿabiÿbbkÿaalÿ ÿ"#*ÿNPUÿSUZÿWRXÿ'#ÿ%$#ÿ[[Xÿ]^Xÿkjiÿ•“•ÿ„€‚ÿYVUÿXX[ÿSUZÿPRYÿNPWÿKMTÿIKRÿKMTÿGIPÿBDKÿDFMÿDFMÿCELÿACJÿACJÿ>AFÿ@CHÿ@CHÿADIÿ<>Eÿ=?Fÿ=?Fÿ>@Gÿ=?Dÿ<>Cÿ=?Dÿ8:?ÿ203ÿ*(*ÿ+)+ÿ(&(ÿ(&(ÿ)')ÿ'%'ÿ$"$ÿ'#%ÿ($&ÿ)%'ÿ)%'ÿ% $ÿÿÿÿÿûòòÿ& ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ4*9ÿÿÿÿÿÿÿ -ÿ - -ÿÿ"ÿÿÿÿÿÿ -ÿÿ -ÿÿÿÿÿÿÿ-((ÿEA?ÿ=:9ÿÿÿ)&,ÿRQPÿMQOÿQSPÿRSMÿ'$#ÿ %ÿ"ÿ[][ÿcbaÿ][Xÿgceÿÿ!ÿZZcÿbcjÿhipÿEEPÿÿ!ÿ__hÿddoÿbbmÿÿ$ÿabiÿ^`hÿa_hÿ#ÿ#ÿ>@>ÿ:8:ÿÿ(%+ÿZUPÿ`[Vÿvrpÿda`ÿVX[ÿWY\ÿZ\aÿQSXÿLQWÿJNVÿEIQÿHJQÿEGNÿEFMÿCELÿEGNÿBEJÿ<?Dÿ=@EÿADIÿ=@Eÿ>@Gÿ<>Eÿ<>Eÿ8:?ÿ:9?ÿ,+1ÿ)(.ÿ.,.ÿ*(*ÿ*(*ÿ'%'ÿ)')ÿ%#%ÿ(&(ÿ%#%ÿ&"$ÿ'#%ÿ" ÿ%!#ÿ&!%ÿ#"ÿ726ÿ$#ÿÿüðóÿÿ1),ÿ,')ÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿ -ÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿ!ÿÿJFDÿUPJÿ#"!ÿÿÿ-,2ÿSTUÿMPUÿVY^ÿ^]cÿ0-3ÿ ÿÿ^ciÿbahÿbagÿcbiÿÿ ÿ^_fÿ`ahÿ`ahÿTV[ÿ!ÿÿedjÿedjÿ_^dÿ ÿ#ÿMMPÿ130ÿ''*ÿ!ÿÿA@?ÿ-+.ÿ $ÿ'$*ÿ@=8ÿB>@ÿ!$ÿ"ÿde_ÿ‚ƒ}ÿ–•”ÿgehÿUY[ÿUX]ÿNPWÿJJSÿHGNÿFGNÿEGNÿAFLÿ>CHÿ@EJÿ>CHÿ=BGÿ>@Cÿ>>Aÿ447ÿ//2ÿ,*-ÿ+),ÿ*(+ÿ*(+ÿ+)+ÿ(&(ÿ)')ÿ(&(ÿ)'*ÿ&$'ÿ%#&ÿ%#&ÿ&$&ÿ$"$ÿ$"$ÿ$"$ÿ$"$ÿ$"$ÿ" "ÿ&$&ÿÿÿöùÿ ÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿ %ÿ #ÿ(,.ÿ!ÿÿÿÿÿÿÿÿphlÿÿÿÿÿÿÿÿÿÿOKSÿ728ÿ# ÿ=;3ÿWPDÿZPAÿ^WKÿÿÿ869ÿ<;:ÿ>ABÿQSXÿQRYÿ,-4ÿ#ÿÿaflÿhgnÿmlrÿonuÿÿ$ÿ][dÿffiÿghiÿ[Z`ÿÿ ÿccfÿhjhÿefgÿÿÿVWXÿ_a^ÿVVYÿÿÿ@?>ÿ'%(ÿÿ"%ÿgcaÿa\`ÿ ÿ! &ÿGEGÿÿ(&(ÿ^\^ÿzupÿ©¡�ÿwrtÿ[X^ÿTU\ÿNNWÿDFNÿ=CKÿ8;@ÿ9<Aÿ/27ÿ),1ÿ+),ÿ/*.ÿ-(,ÿ-(,ÿ+),ÿ((+ÿ&&)ÿ&&)ÿ&&)ÿ%%(ÿ((+ÿ''*ÿ''*ÿ$$'ÿ$$'ÿ%%(ÿ(&(ÿ'%'ÿ%#%ÿ%#%ÿ%#%ÿ%#%ÿ(&(ÿ" "ÿ-)+ÿøðóÿ)$&ÿÿÿ|w{ÿÿÿÿÿÿÿ&!%ÿKECÿ�‹…ÿ‹‰„ÿ"ÿbglÿRXZÿJNPÿ77:ÿ+-0ÿ(*-ÿ$&)ÿÿÿÿÿ -ÿÿÿÿÿÿÿÿÿÿ>8@ÿÿ'#ÿJE9ÿ^RCÿlYGÿu`Tÿ)!%ÿ2-3ÿD@BÿB@=ÿUPJÿQLFÿGBBÿ:59ÿ#ÿÿSX^ÿSRYÿONTÿWV]ÿÿ;8Dÿ3/8ÿ[Y[ÿ[\VÿXVYÿ#ÿÿ[\]ÿ_c[ÿ`b`ÿÿÿ_a_ÿ`b_ÿ^^aÿÿÿEDCÿ647ÿÿ ÿkffÿmhnÿÿ"ÿolrÿ ÿ#!$ÿWUWÿ& $ÿ,$(ÿRMMÿ[VVÿ€{{ÿ…€‚ÿD@Bÿ424ÿ$$'ÿ$ÿ ÿÿ""%ÿ(&)ÿ+),ÿ203ÿ247ÿ79<ÿ9;>ÿ:<?ÿ9;@ÿ8:?ÿ68=ÿ57<ÿ247ÿ,.1ÿ(*-ÿ'),ÿ*(*ÿ(&(ÿ(&(ÿ(&(ÿ'%'ÿ'%'ÿ&$&ÿ(&(ÿÿüô÷ÿ'"$ÿÿÿ’�“ÿÿÿÿÿÿÿÿD<8ÿ—‘‡ÿ™˜‘ÿÁÄÅÿ´¹¾ÿ¯³µÿ¶´·ÿÁ¹½ÿeceÿgjkÿ]`aÿ367ÿ$))ÿ!&&ÿ #$ÿ#$%ÿ" "ÿÿÿÿÿÿÿ -ÿ"!ÿ?9=ÿ,&$ÿ^WKÿkaVÿ]O@ÿ|dUÿ~dYÿ-"ÿ(#)ÿ735ÿ>;6ÿeZOÿaWIÿWLEÿ<64ÿÿÿ<?Dÿ=<Bÿ!ÿ!ÿ -ÿ&"+ÿ-"'ÿ%"ÿZ\SÿSQTÿ$ÿ"ÿY\]ÿW\VÿZ\Yÿÿÿ^b`ÿoqoÿddgÿÿ!ÿ?A?ÿ)),ÿÿ!ÿ?=?ÿ ÿÿÿ106ÿÿÿjihÿ"+ÿ )ÿPKOÿLFDÿ*"ÿ( ÿOJEÿhe`ÿ‰…‡ÿXVYÿIGJÿÿILQÿFINÿ<?Dÿ@CHÿ>AFÿBEJÿEHMÿ@CHÿADIÿ?@Gÿ:;Bÿ<=Dÿ9;@ÿ;=@ÿ=?Bÿ/14ÿ+,-ÿ,*,ÿ)')ÿ)')ÿ(&(ÿ(&(ÿ(&(ÿÿÿöòðÿ?::ÿ-+-ÿ''*ÿš˜›ÿÿÿÿÿÿÿÿÿš•�ÿ™”ŽÿÖÙÚÿÏÓÕÿÐÐÓÿÍÈÊÿË¿ÀÿbVWÿGBBÿ�ÿb_^ÿSSPÿBB?ÿ330ÿ..+ÿ8;5ÿ463ÿ+-+ÿ##&ÿÿÿ ÿÿ ÿEC<ÿVSHÿmcUÿ€rcÿseVÿn\Nÿo[Mÿ]NOÿ[W_ÿ(+0ÿEB=ÿg[RÿfYLÿ[PEÿJFDÿ#'ÿÿUURÿÿÿÿÿÿH.!ÿJ8*ÿRSLÿFEKÿ 'ÿ!ÿ^gmÿbglÿhgfÿ ÿ&ÿBDLÿ8:=ÿ-,3ÿÿÿ<A=ÿ -ÿÿÿÿEGLÿÿÿLNLÿÿ# &ÿfdfÿ,(1ÿ#ÿhfhÿ]Z`ÿ# &ÿFDGÿ!"ÿ$"%ÿPJHÿE?=ÿFDGÿÿbdiÿPOUÿLKQÿIHNÿIKPÿFHMÿ?AFÿ@BGÿMLRÿ54:ÿ0/5ÿ-,2ÿ+*0ÿ+*0ÿ*)/ÿ)(.ÿ''*ÿ)*+ÿ)*+ÿ)*+ÿ+),ÿ)'*ÿ*(+ÿÿÿóõòÿ<><ÿ!!ÿ�ŠŽÿOMPÿÿÿÿ#ÿÿ !ÿÿÿ�‘‹ÿ¢›•ÿÕÏÍÿÖËÊÿÕÉÅÿÓÊÄÿÍÇ¿ÿž’“ÿÿÿÿÿÿÿÿ%& ÿ25/ÿ@C=ÿBE?ÿ22/ÿ..+ÿ! ÿÿ ÿDB;ÿDA6ÿ\RDÿzk^ÿSD7ÿB3&ÿSB5ÿZKKÿÿ#%(ÿRMGÿmbWÿeXKÿk^Qÿe\UÿRMQÿNKJÿjhcÿÿÿÿÿ*ÿX=,ÿM8&ÿh_Xÿnjlÿ!ÿ &ÿS[_ÿaegÿ‰ˆ‡ÿÿÿ‚€ƒÿ�~ÿccfÿÿÿNLGÿÿÿÿ $ÿTV[ÿÿ "'ÿYZ[ÿÿ('.ÿddgÿ409ÿ#ÿgegÿa^dÿÿWUXÿÿ#!$ÿecfÿ!ÿÿGJUÿ ÿd__ÿ‚}}ÿ]XXÿNLOÿJJMÿOORÿFFIÿ@BGÿBDIÿ>@Eÿ=?Dÿ>@Eÿ9;@ÿ>@Eÿ=?Dÿ==@ÿ??Bÿ>>Aÿ??Bÿ>>Aÿ<<?ÿ336ÿ #ÿÿüú÷ÿ+('ÿÿÿ--0ÿÿÿÿ$ÿÿÿ)&!ÿ ÿ�Ž�ÿž˜�ÿÓÎÉÿÓËÉÿÕËÇÿÓÊÄÿËŽÿ£—˜ÿÿÿÿÿÿÿÿÿÿÿ$'!ÿ ÿ@C=ÿ%'$ÿÿÿIG@ÿVSHÿi_Qÿxf\ÿXH>ÿE8-ÿRG<ÿbSSÿÿÿrldÿe[Qÿm`SÿjZJÿsf[ÿUPKÿig`ÿZXQÿÿÿÿÿE61ÿ[>,ÿJ0ÿ–†}ÿ†ÿ$$ÿ)&,ÿbhjÿ|€ÿ‰Š‹ÿÿÿ{wuÿoqhÿbdaÿ ÿÿE@;ÿOIGÿÿÿ"&ÿ9;@ÿÿÿGILÿÿ%ÿPRWÿ61=ÿ#ÿa_aÿXU[ÿÿXVYÿÿ ÿ;:@ÿÿÿÿÿ ÿ*$(ÿJDHÿRPRÿtrtÿ\Z\ÿXVXÿKMRÿGJOÿFINÿBEJÿ?BGÿ;>Cÿ8;@ÿ36;ÿ.05ÿ.-3ÿ.-3ÿ.-3ÿ+-0ÿ+-0ÿ.03ÿ+-0ÿ  ÿÿôõÿ/'*ÿÿ{~ÿ“”•ÿÿ ÿiegÿmlrÿÿ&'(ÿÿ,(*ÿ�‹‹ÿ˜”ŒÿÎÍÆÿÔÑÐÿÑÌÌÿÖÐÎÿÊÀ¼ÿ¦š�ÿÿÿÿÿÿÿÿ -ÿ!ÿÿ ÿ(-'ÿ<A;ÿ+0,ÿ+0,ÿ/+)ÿA<6ÿWQGÿh^PÿbPFÿP@6ÿE:/ÿ]SHÿ_RMÿÿÿnicÿlbXÿ{naÿyk\ÿ„wjÿc\Vÿ`\Tÿqlfÿÿÿÿ ÿTA9ÿaC-ÿT7%ÿ�}uÿ�‡…ÿ+$+ÿ`_eÿPTVÿPSTÿLMNÿ ÿ#!$ÿEA?ÿRVMÿ&(%ÿ#ÿÿMF@ÿXPNÿÿÿ(04ÿVX]ÿÿÿDFIÿÿ(ÿDFKÿ-+4ÿ"ÿNLNÿOLRÿÿXVYÿÿÿ ÿÿÿ!ÿÿÿÿ!ÿÿ !ÿ ÿRPSÿoqtÿUY[ÿMQSÿJNPÿCHMÿ?DIÿ>CHÿ?DIÿ@AHÿCBIÿBAHÿBAHÿ=?Dÿ=ACÿ:>@ÿ6:<ÿÿúòõÿ4/5ÿ$#)ÿojjÿ–’�ÿÿ-(,ÿ •”ÿ‹{ÿÿÿÿÿ•��ÿž•ŽÿÏÊÅÿÖÏÏÿØÏÏÿÔÊÆÿØÌÇÿ�””ÿÿÿÿÿÿÿÿÿÿÿÿ',&ÿ9><ÿ*//ÿ&,(ÿ54-ÿ/*$ÿKE=ÿ[SIÿsjÿMA8ÿE;1ÿME;ÿpcVÿ!ÿ/+-ÿOD=ÿreXÿ}pcÿ}rgÿ†{pÿph^ÿebWÿrphÿ624ÿÿÿ-("ÿ:(ÿbB,ÿH/ÿ¾¯ªÿia_ÿ1-/ÿcgiÿalmÿY_aÿTZ\ÿ7=?ÿ;ACÿ,24ÿOSUÿÿ - -ÿ !ÿ<94ÿ�ˆˆÿ!#ÿ# &ÿ16;ÿ^`eÿÿ ÿJKLÿ #ÿ ÿ&$'ÿ!"ÿÿHFIÿJHKÿÿQNTÿ"ÿ -ÿÿÿÿÿÿÿÿ!ÿÿÿÿÿ%#%ÿ%#%ÿGEGÿusuÿ__bÿNPUÿJLQÿCEJÿACHÿ>@Eÿ<>Cÿ;=Bÿ136ÿ136ÿ469ÿ/14ÿÿøðóÿGBHÿ+*0ÿÿogeÿ$#ÿ "%ÿ ÿ!ÿÿÿÿ.,.ÿ�ˆˆÿž•ŽÿÏÊÅÿÒËËÿ×ÎÎÿÜÒÎÿÖÊÅÿ ——ÿ$!ÿÿÿÿÿÿÿÿÿÿÿ',&ÿ7<:ÿ*//ÿ%+'ÿ/1.ÿ(&#ÿ<94ÿD?9ÿG?=ÿÿ#ÿÿ3*$ÿD<8ÿRMMÿh_YÿfZQÿqf[ÿzm`ÿ…whÿyqgÿfcXÿlk`ÿ530ÿ !ÿ" "ÿ($"ÿ-ÿF+ÿ8!ÿÔÆÃÿ”ŒŠÿÿ]_\ÿalgÿZ`\ÿ_eaÿiokÿ]c_ÿ=C?ÿJOOÿÿÿÿ74/ÿLGGÿ "ÿÿ49>ÿ\^cÿYV\ÿ027ÿPQRÿÿ $ÿÿÿÿÿ !ÿÿ$!'ÿÿ!ÿÿÿÿÿÿÿÿÿÿÿÿÿÿ $ÿÿ#'ÿ567ÿSUSÿegeÿJLJÿJLOÿDFIÿACFÿ>@CÿBDGÿ?ADÿ;=@ÿ>@Cÿ99<ÿûóöÿ'"(ÿ! &ÿŽ‰‰ÿuomÿ*%)ÿÿ½·µÿ½µ±ÿÿÿÿÿ’��ÿž•ŽÿÊÅÀÿÖÏÏÿÝÔÔÿÜÒÎÿÒÆÁÿ ——ÿÿÿÿÿÿÿÿÿÿÿÿ$)#ÿ5:8ÿ.33ÿ&,(ÿ45/ÿ,)$ÿKF@ÿIC;ÿcYUÿYQMÿJE@ÿ961ÿ0,.ÿ$"%ÿÿÿÿÿ,%ÿ€vlÿg[\ÿb\Zÿifaÿ@=<ÿÿÿ42/ÿ'ÿJ3'ÿ9%ÿʽ¼ÿƒyuÿ ÿ,*,ÿ3::ÿHKLÿ)*+ÿabcÿ}~ÿÿ³µ¸ÿ ÿÿÿ)&!ÿ½¸¸ÿ`Zbÿÿ27<ÿ8:?ÿ"ÿ(*/ÿ@ABÿÿ'#+ÿÿ - -ÿ203ÿÿÿ"ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿ,*-ÿ-+.ÿRPSÿIJKÿEHIÿDGHÿCFGÿ?ADÿ>@CÿACFÿBDGÿ@BEÿÿøûÿ"%ÿÿÿ<64ÿ ÿ#!ÿ.ÿ'ÿ"ÿÿÿ@ABÿˆ†ƒÿ›•�ÿǽÿÖÏÏÿÝÔÔÿÛÑÍÿÑÅÁÿž——ÿÿÿÿÿÿÿÿÿÿ0.0ÿÿ%*&ÿ275ÿ388ÿ$*&ÿ<80ÿ($ÿolgÿb\Tÿuqÿlc\ÿmh\ÿpj`ÿujcÿrf]ÿsf[ÿj\SÿRNLÿRNPÿ]XSÿmd]ÿj^aÿE:?ÿÿ.*,ÿÿÿ$#"ÿÿ4%ÿ'ÿWRTÿ{sqÿ% ÿ%$*ÿ&*,ÿ #ÿ(&)ÿÿhgmÿ %ÿœž¡ÿÿÿÿ#ÿÄÁÀÿhgmÿ# &ÿÿÿÿÿ+,-ÿÿ $ÿÿÿ536ÿ - ÿÿ1.4ÿ84<ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ -ÿÿ84<ÿ+(.ÿ'),ÿrvtÿRTRÿJMNÿDHJÿDFIÿCEHÿFFIÿFHKÿÿòóÿ*%)ÿ ")ÿB>@ÿC;9ÿ5/3ÿÿ“‹Žÿš’�ÿ*%)ÿÿÿ)&%ÿ�Ž‡ÿ••ŒÿĽÿÖÎÌÿÕÊÉÿÚÏÎÿÍÂÁÿ¡�›ÿ'$#ÿÿÿÿÿÿÿÿÿ#!#ÿÿ$(&ÿ9><ÿ/42ÿ$)'ÿ;;8ÿ#-ÿ6F`ÿCOjÿ5:Sÿ0:Nÿ=O]ÿ,<Lÿ',>ÿ+2@ÿ:DOÿ^bjÿhgfÿngoÿ€ysÿ„zoÿsd^ÿŸ—•ÿOMOÿIGDÿÿÿ#%(ÿ>JSÿ-2ÿObnÿŽ¨µÿ%%ÿ% ÿ<?@ÿHMKÿVVSÿMLKÿLMNÿ²´·ÿ ÿ´¯³ÿÿ"#ÿÿ!ÿ¹µ³ÿXSWÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿ73;ÿ2.7ÿ"ÿÿÿÿÿÿ -ÿ !ÿÿÿÿÿÿÿÿÿÿÿÿÿQORÿÿnopÿfdaÿ…€zÿTSRÿLPRÿEIKÿHHKÿJHKÿGEHÿÿðìÿ;44ÿ)*+ÿMGEÿ5-+ÿ604ÿÿYQTÿc[Yÿ'"&ÿ"ÿ&$&ÿ632ÿ�Ž‡ÿ˜˜�ÿĽÿÙÑÏÿ×ÌËÿÚÏÎÿź¹ÿª¦¤ÿOLKÿÿÿÿÿÿÿÿÿÿÿ"&$ÿ8=;ÿ053ÿ#(&ÿ597ÿ)ÿ 2ÿ 7ÿ2ÿ+<jÿ9vÿ)K}ÿ'P�ÿ>lžÿ,ZŒÿ2[ŒÿEh�ÿNf�ÿLT^ÿ—�‚ÿwkbÿ820ÿ?@AÿHHEÿjneÿjnfÿuƒ†ÿ;]qÿ}¯Äÿ Çàÿx¢²ÿu„„ÿ„{{ÿC?Aÿ# ÿ-3/ÿCHFÿuzzÿ¸ÀÂÿ#ÿ½»¾ÿÿÿÿÿ·©¦ÿ›€†ÿÿÿÿÿÿÿÿÿÿÿÿÿÿ!ÿÿ -ÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ202ÿÿ¡œœÿ�„ƒÿh\Wÿf]]ÿ`\^ÿ^Z\ÿJFHÿQMOÿRPSÿÿôôÿ,')ÿ %ÿ!ÿ.&$ÿLFJÿ# &ÿ&!ÿ*" ÿÿÿÿvsrÿƒ‚{ÿ˜˜�ÿ¼ºµÿØÐÎÿÞÓÒÿÙÎÍÿź¹ÿª¦¤ÿGDCÿÿÿÿÿÿÿÿÿÿÿ#!ÿ164ÿ386ÿ" ÿ861ÿ$"ÿ"ÿÿ(ÿ07Uÿ1Uÿ 6\ÿ/Twÿ;j�ÿ-Z‚ÿEoÿ,Uyÿ.Hoÿ|ƒ‰ÿž��ÿl`WÿEA?ÿ.12ÿ*/+ÿ_cZÿ�zÿ]fmÿY|“ÿož¶ÿŸÁÛÿƒ¥¹ÿ¡¦«ÿ3,,ÿ456ÿUZXÿ~€}ÿlkjÿ),-ÿ ¤¦ÿ^chÿÂÀÃÿÿÿÿ#!ÿ¸¯©ÿ‹||ÿÿÿÿÿÿÿÿÿÿÿÿÿÿIGJÿÿÿÿÿ !ÿ" #ÿ#!$ÿÿDBEÿÿÿÿÿÿ'#+ÿ1.4ÿ839ÿNHPÿaZdÿÿÿ ÿB=Aÿ­¨ªÿ²ª¨ÿ{ojÿleeÿ‹‚‚ÿpggÿleeÿ\WWÿC>Bÿÿùúÿ'&-ÿ*/;ÿ54:ÿ(" ÿWQUÿ!ÿ–‘“ÿ´¬ªÿ>9=ÿÿÿÿ€~wÿ•“‹ÿ¼ºµÿ×ÑÏÿÛÐÏÿ×ÌËÿ·¶ÿ­©§ÿ$! ÿÿÿÿÿÿÿÿÿÿÿ#!ÿ/74ÿ8=;ÿ!ÿ48:ÿ!&ÿÿÿ,ÿ"#ÿCXRÿy�—ÿ–±¼ÿ|˜ ÿ^xƒÿCWeÿHeqÿ2Gdÿy{yÿ–„vÿpeZÿKGEÿBEFÿ162ÿŽ�ˆÿzwvÿ&ÿAZqÿ�°Âÿ™ÅÙÿŒ·Éÿª¹¹ÿ854ÿ9>>ÿdigÿÍÉÇÿ�ŠŠÿÿŽŽ‘ÿachÿ¦¤§ÿÿ034ÿ%"!ÿ’†�ÿd_Yÿÿÿÿÿÿÿÿÿÿÿÿÿ - ÿÿPOUÿHGMÿÿÿ -ÿÿÿÿÿ ÿÿÿFBJÿ?=Fÿ::Eÿÿ2)0ÿ@5:ÿ‰~ƒÿXGQÿi]lÿdZkÿwn{ÿohoÿ£ž ÿ�—•ÿJGBÿUSUÿÖÊËÿ[SQÿJCCÿÿÿÿøóÿA=FÿSXjÿÿ$$!ÿodiÿÿÿ(ÿÿÿÿ�ŠŠÿxrÿ�—�ÿ­«¦ÿÒÐÍÿØÐÌÿ×ËÇÿ­¨£ÿ«©¦ÿÿÿÿÿÿÿÿÿÿÿ987ÿ$#"ÿ)84ÿ597ÿÿ/40ÿ%"(ÿÿ"ÿ;ÿ!ÿ[YVÿ‹˜�ÿ‰£¦ÿ…™�ÿemoÿXb_ÿWolÿ%Brÿx}{ÿ‹usÿoeZÿOIGÿ$%&ÿ#%"ÿ�”�ÿ]lqÿ.Eÿ+Cÿ}¥ºÿ›Ëçÿ¡Ìäÿ¼ÀÂÿPGGÿ)')ÿ`dbÿÎÈÆÿ™””ÿÿ»»¾ÿJLQÿ¸·¾ÿÿ`cdÿÿ!ÿ&!!ÿÿÿÿ" #ÿÿÿÿÿÿÿÿÿ - ÿÿ3;Kÿÿÿÿÿÿ$"%ÿÿÿÿÿÿÿ -ÿ ÿÿÿÿÿ~igÿ}brÿH.IÿS=WÿB6?ÿ�‚�ÿVQQÿ9;>ÿ-/4ÿÎÂÃÿ.31ÿLMNÿÿÿÿôñÿ94:ÿ$ÿ&!%ÿ)+(ÿ}rwÿÿŠ‹Œÿ²§¦ÿpjnÿÿÿÿwpjÿ›•�ÿ¸¶±ÿ½½ºÿÁ¾¹ÿ©¡�ÿœš•ÿœš—ÿ%"!ÿ ÿÿÿÿÿÿÿÿ  ÿÿÿ*95ÿ7;9ÿÿ.62ÿ'"&ÿ'&ÿ$)5ÿ&Kÿ!ÿ?;9ÿ„‰Žÿ—¬®ÿ�–˜ÿx†…ÿemiÿ]toÿ$Aqÿy~|ÿ•}ÿwmbÿHB@ÿ)*+ÿ#%"ÿŸ�‹ÿ#'ÿ6_rÿ[�¨ÿe“¯ÿ]‘²ÿP}›ÿª°ºÿ_UXÿ,*,ÿÿÐÊÈÿ ››ÿÿ°°³ÿBDIÿ²°³ÿÿsuxÿÿ"$ÿ%)+ÿÿÿÿÿÿÿÿÿÿÿÿÿ -ÿÿ&<ÿ%ÿÿ% $ÿÿÿ,*-ÿÿÿÿMIKÿ)$&ÿÿÿÿ!"ÿÿ ÿ,)(ÿÿdZmÿ*ÿŒ€•ÿ�v}ÿE<<ÿ!ÿ<@>ÿ020ÿÏÄÃÿ053ÿGHIÿ ÿÿÿóòÿ( #ÿ$!'ÿ!ÿ?A>ÿtinÿ -ÿ%&'ÿ5*)ÿ'!%ÿÿÿ[VVÿg`Zÿ š’ÿ¥£žÿ€…�ÿœ�—ÿ’�‹ÿvysÿxxuÿÿÿÿÿÿÿÿÿÿ#!#ÿÿÿ'62ÿ8<:ÿÿ/;8ÿ%"!ÿ60&ÿ&,<ÿ'Pÿ#ÿ"ÿT[[ÿTggÿtŠ‰ÿ{Žˆÿ`jaÿYpkÿ.K{ÿw|zÿ™ƒ�ÿuk`ÿvpnÿ*+,ÿ02/ÿ�Žƒÿjb`ÿ '2ÿq¨Àÿƒ±Íÿb–·ÿy¢Àÿ³³¼ÿnbcÿ$"$ÿ.20ÿÏÉÇÿŸššÿ,*,ÿ¦¦©ÿ*,1ÿ±­«ÿÿbcjÿ'$1ÿ<9Eÿ!")ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ#Aÿ - -ÿ ÿ(#%ÿÿÿ$"%ÿ !ÿÿ" "ÿjfhÿ&!#ÿÿ#ÿÿ%0ÿ&:ÿ9=Eÿ'"ÿ5/'ÿlkjÿ -ÿ¤¢Ÿÿ50+ÿ!ÿÿ>C?ÿLJEÿŹµÿGLJÿ./0ÿÿÿùíîÿ'"ÿÿÿÿšŽ‘ÿ(%+ÿ()*ÿ1)'ÿ*%'ÿÿ" "ÿ~yyÿ[VPÿ£š“ÿ”’�ÿnunÿ‘–�ÿz}wÿnunÿrsmÿÿÿÿÿÿÿÿÿÿ  ÿÿÿ'30ÿ497ÿÿ8>@ÿ!ÿÿFN^ÿ$-\ÿ&ÿ ÿ&43ÿ†›�ÿs‰‹ÿawuÿ[d]ÿ^upÿ.Ozÿx|~ÿœ‡‚ÿgZMÿŠ‚~ÿ !ÿ/1/ÿ‡Ž‚ÿ©•�ÿPXbÿd”©ÿy¨Àÿ›Íèÿ[|“ÿ¼·½ÿ‚vwÿ !ÿ;>?ÿÏÉÇÿ¨¡¡ÿ1/1ÿ//2ÿ*)/ÿ\XVÿÿCBHÿ ÿ"ÿ "ÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿ#Cÿ0ÿÿÿ)%.ÿ'$*ÿ0-3ÿ.,/ÿ1/1ÿ&$&ÿÿB=?ÿ"%>ÿJQgÿ,ÿ#3MÿJVuÿ ÿ!ÿa\JÿC>9ÿÿ¢�Ÿÿ*$,ÿÿÿILFÿPOHÿ¬¢žÿÿÿ(&)ÿ0.0ÿÿúùÿ+#'ÿÿÿywtÿ¦—˜ÿÿ)-/ÿ»µ³ÿœ—™ÿÿÿÿEIAÿ¨�–ÿ…ƒ~ÿeofÿ…�ƒÿltjÿgoeÿimeÿÿÿÿÿÿÿÿÿÿÿÿÿ(//ÿ2;;ÿÿ50<ÿ"&ÿ ÿ)0ÿ!6lÿ$ÿ"ÿ!-4ÿŠ¤§ÿ‚�¤ÿ]tyÿFROÿQjoÿ-U|ÿty‹ÿ‘€rÿs`Vÿž’�ÿ!"#ÿÿ’Š†ÿ§�’ÿ™ª·ÿv¢¼ÿ˜ÄØÿ©Íâÿ*;Hÿˆƒƒÿ�˜“ÿ!ÿKJPÿÅÀÂÿ®¦©ÿ:8:ÿ8;<ÿKNOÿ>CCÿÿ‚~€ÿÿÿÿÿÿÿÿÿ==@ÿ"ÿÿ"ÿÿÿÿÿÿ"=ÿ"*Vÿ6ÿ!ÿTLgÿ@>Gÿ+'/ÿ!ÿƒ�~ÿRONÿÿ'"&ÿ -$ÿ#1ÿ25@ÿgmƒÿv� ÿ$6ÿÿ8-&ÿ#ÿÿ­§¥ÿ+(.ÿ#ÿÿbc]ÿÿ31,ÿÿÿ)-+ÿÿÿø÷ÿC;?ÿ$ÿÿ%%"ÿ±¥¦ÿÿÿÿÿÿÿ’��ÿEIAÿ¢—�ÿ}xÿ\e^ÿfmeÿ`g_ÿah`ÿdh`ÿÿÿÿÿÿÿÿÿÿÿÿÿ&--ÿ4==ÿÿ30<ÿ!(ÿÿ ÿ)aÿ'ÿ'!ÿÿ4KJÿ…¡¤ÿdx|ÿMVVÿRihÿ3Xwÿqr}ÿ—€mÿ…wnÿ¨ žÿ!"ÿÿ�Š…ÿ¨¡•ÿ‘¢¯ÿ%Oiÿ³ÏäÿµÊÜÿ'ÿŠ…ÿƒ€{ÿ"$ÿY[`ÿ¿»½ÿ½¹»ÿ,11ÿ4@?ÿ4==ÿLXWÿ$'(ÿ”Œ�ÿÿÿÿÿÿÿ!ÿ!ÿCCFÿ**-ÿ #ÿ**-ÿÿÿÿ ÿÿ!<ÿ%Tÿ'Jÿ25NÿbTzÿ€~‡ÿ -ÿÿ - ÿPMLÿÿ ÿCBHÿVTVÿc\\ÿ¦¢ªÿnovÿÿÿ1%!ÿÿÿ©£¡ÿÿÿ -ÿbc]ÿ››˜ÿ==:ÿÿÿ-.(ÿÿÿø÷ÿLDHÿ%$*ÿ ÿ/40ÿ¿¶¶ÿÿ$$'ÿ³«©ÿºµ·ÿÿÿÿ#ÿ¡–�ÿ€~yÿ4<8ÿ9?;ÿ-3/ÿ5;7ÿ]`Zÿÿÿÿÿÿÿÿÿÿÿÿÿ!((ÿ1::ÿÿ--8ÿ#+!ÿ#"ÿ%-ÿ-eÿ65Fÿ782ÿ?A>ÿ382ÿ™¥¤ÿ™¥©ÿnuuÿOecÿ3Yyÿt|�ÿˆ€~ÿ†��ÿ¬¦ªÿÿÿ�Žˆÿ�˜ŒÿHYfÿGmˆÿ¯ÏåÿtŽ£ÿDT^ÿ„„�ÿ™š”ÿ'-/ÿ05:ÿ°®°ÿÿÁÿdiiÿ\hgÿt{{ÿ„‰‰ÿ‘�‘ÿ¨ £ÿÿÿÿÿÿÿÿ ÿ!ÿ"ÿÿÿÿ -ÿÿÿÿ6ÿ#Pÿ%Jÿ7ÿeO|ÿ~y…ÿÿ'ÿÿURQÿ($&ÿ0+/ÿ'#%ÿ"ÿ2%*ÿypwÿA65ÿ`VYÿÿÿÿÿ•��ÿÿÿÿ]^Xÿžž›ÿ123ÿÿÿKJCÿ‡„ƒÿÿõòÿ@:>ÿ#ÿÿxzwÿ¼µµÿÿÿ&ÿÿÿ"ÿ‹††ÿ*+$ÿ�”�ÿƒ�|ÿ/74ÿ(-+ÿÿ-3/ÿSYQÿÿÿÿÿÿÿÿÿÿÿÿÿ"''ÿ,55ÿ ÿ57?ÿÿÿ'ÿ$6nÿ/ÿ&*"ÿ-0*ÿ6-&ÿ;66ÿmpqÿFOOÿ0QcÿP†ÿ;sÿ8Ozÿ\hwÿº²¶ÿ"#ÿ ÿ��†ÿ¢Ÿ”ÿS`kÿKlƒÿGk€ÿ!BXÿ!6Bÿ)+)ÿŸ¡žÿÃÆÇÿ„‰ŽÿÃÄÅÿ¿¼»ÿZ]^ÿ¾ÃÃÿ>ABÿÍÉËÿaY\ÿ—�’ÿÿ%%(ÿÿÿÿÿ!ÿ##&ÿ((+ÿÿÿÿÿÿÿÿ!ÿ0ÿ!KÿAÿ;ÿfOyÿsp}ÿ*56ÿ +ÿ}zyÿGDCÿÿ-(,ÿGBHÿE;DÿC4?ÿ„|†ÿaSTÿ¡™�ÿÿÿÿÿ—‘�ÿ - ÿÿÿef`ÿkifÿ567ÿ!ÿÿTRJÿ½º¹ÿÿöðÿUOSÿ5:Fÿ(%+ÿ$ ÿ±®­ÿÿÿaVUÿcYUÿÿÿ*ÿ()"ÿ•”‰ÿ‡ˆ‚ÿ%,,ÿ&&ÿ&#ÿ*2.ÿJVMÿÿÿÿÿÿÿÿÿÿÿÿÿ"#ÿ'32ÿ ÿ-52ÿ ÿÿ!,ÿ0eÿ!3ÿ!ÿ,*%ÿ<:+ÿ'"ÿJG<ÿ‚ˆ„ÿ#Bdÿ,W…ÿ@‹ÿ-N–ÿIg}ÿÀ®²ÿ$ÿ#ÿ���ÿžœ•ÿŒŽ“ÿ™¤«ÿ—£²ÿGXeÿ:FJÿŽ†‚ÿ¨¥¤ÿÝÕØÿ“˜˜ÿ©ª«ÿÁ¿¼ÿº¹¸ÿØÓ×ÿº¶´ÿÉÂÂÿsnnÿ…‚�ÿ/.-ÿÿÿÿÿ -ÿX[\ÿQTUÿ"%&ÿ !ÿ$"%ÿÿÿÿÿÿÿ&>ÿ#QÿBÿ <ÿ.:ÿafrÿY^^ÿkmjÿ•“ŽÿQMKÿÿ,(0ÿ#ÿ2+2ÿ:18ÿ~yÿTKKÿ©  ÿÿÿÿÿ¥Ÿ�ÿÿÿÿ��xÿ™–‘ÿ<86ÿ&"$ÿÿSMCÿÀ½¼ÿÿôðÿ}vvÿ!ÿÿˆ„‚ÿª§¦ÿÿÿtihÿnfdÿÿÿ/'*ÿ ÿ6=3ÿ:B>ÿ&--ÿ#&'ÿÿ).*ÿFPGÿÿÿÿÿÿÿÿÿÿÿÿÿ!"ÿ#/.ÿÿ+30ÿ%ÿÿ)ÿ1hÿ/3HÿHFCÿ$$!ÿ-+#ÿ:03ÿ93+ÿ?=:ÿ$@bÿ,W…ÿF‘ÿ*K“ÿD_wÿ·¥©ÿÿ"ÿ��~ÿ£ ”ÿxpnÿÁµ¸ÿÒËÕÿ&ÿ8;<ÿµ¨£ÿ©¤¤ÿÙÏÒÿ}‚‚ÿ›žŸÿÊÅÀÿº´²ÿÜÒÕÿȾºÿÎÆÄÿ~yyÿ‰†…ÿÿÿÿÿÿÿÿ?@Aÿ ÿ'%(ÿ%#&ÿ !ÿÿÿÿ -ÿÿ%=ÿ!Qÿ@ÿ4ÿ/ 9ÿinzÿdiiÿhjgÿ‰‡‚ÿRNLÿ$#ÿ<8@ÿFEKÿ -ÿ:18ÿŒ‡�ÿcZZÿ¢™™ÿÿÿÿÿª¤¢ÿ4/3ÿÿ'&%ÿvÿ}zuÿ?60ÿ+&!ÿÿVLAÿËÁÄÿÿôñÿ¡–•ÿÿÿ743ÿ¶³²ÿÿÿÿÿ ÿ"ÿwpwÿ$ ÿŠ�‰ÿy~|ÿ5A@ÿ9BBÿ9C@ÿ;FAÿBNEÿÿÿÿÿÿÿÿÿÿÿÿÿ !ÿ".-ÿ ''ÿ,41ÿ$ÿÿ  ÿ2kÿ5ÿ@?>ÿ@B@ÿ+0*ÿ"ÿ64-ÿ796ÿ6Yÿ)W„ÿF�ÿ+J’ÿ9Roÿ±Ÿ¡ÿÿ& ÿŠ‹~ÿ¥Ÿ—ÿhZ[ÿêÙÙÿèØÜÿ946ÿyyvÿÕÉÄÿ¥žžÿØÌÏÿ�’’ÿ|ƒƒÿÈÆ¿ÿ½¸³ÿà××ÿÊÁ»ÿ¿·µÿŠ……ÿqnmÿ.-,ÿÿÿÿÿ -ÿÿÿ$"$ÿÿÿÿÿÿÿÿÿ+ÿ%Eÿ1ÿ-ÿXIbÿdiuÿdiiÿVXUÿ…ƒ~ÿQMKÿÿRNVÿ~„ÿxÿ€w~ÿ¶±·ÿ…||ÿ¦��ÿÿÿ!ÿÿ­§¥ÿ†�…ÿ;9<ÿ/.-ÿ††}ÿ�š•ÿIE=ÿÿÿ4-'ÿ¾¸¼ÿÿúúÿ¼±°ÿ'""ÿ$ "ÿ$ÿ�Š‰ÿ -ÿÿ²¨¤ÿ·«§ÿÿÿÿ $"ÿ––“ÿ_bcÿ4BAÿ8FEÿ:IEÿ>MHÿCOFÿÿÿÿÿÿÿÿÿÿÿÿÿ!!ÿ&21ÿ"))ÿ%,,ÿ,ÿÿ!ÿ!;tÿ8ÿ'&%ÿ+-*ÿ4;4ÿ589ÿ/3+ÿ160ÿ1Sÿ+V„ÿDŽÿ.M•ÿ8Qtÿ«˜˜ÿ"ÿÿ|{tÿ¢š–ÿ`TWÿå×ØÿëÜÝÿ.*(ÿÀÁ»ÿ°©£ÿ¨¡¡ÿÜÍÑÿ†‹‹ÿajjÿÕÔÍÿ½ºµÿßÙ×ÿËľÿ¼·²ÿ�ˆŠÿ`]\ÿ321ÿÿÿÿÿÿÿÿ&$&ÿ!ÿÿÿÿÿÿÿÿÿ.ÿ - ÿ"ÿ%-ÿ'-5ÿ6;9ÿTVSÿURMÿTPNÿÿQNTÿ.+1ÿ"#ÿ.%,ÿnioÿMDDÿ®¥¥ÿÿÿ -ÿÿ¬§§ÿ|xzÿ868ÿ00-ÿ––�ÿ¡œ–ÿLJCÿÿ#!#ÿ(##ÿ·µ¸ÿÿñíÿªž¡ÿ!$ÿÿ…€€ÿ¶±±ÿÿÿÿ+$$ÿÿÿhbfÿÿš�žÿ:=>ÿ.??ÿ1BBÿ4FDÿ:LHÿJSLÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿ"/0ÿ"$ÿ"*.ÿ'ÿ" ÿ)ÿ!:uÿ$&Aÿ*% ÿQQFÿ;;.ÿXYLÿ14(ÿ ÿ/LÿJtÿ 6}ÿ*K”ÿ"?oÿį«ÿ ÿ&!ÿttqÿ¨£�ÿI?;ÿêÛÛÿòÜÝÿ" ÿŸ—•ÿÖÇÇÿ¹¹¶ÿÛÏÐÿ˜™šÿV\^ÿÏÈÈÿº²°ÿÚÒÐÿº¸ÿ»³¯ÿ¥›¤ÿRMMÿ" ÿ$ÿÿÿÿ -ÿÿÿ+)+ÿ++.ÿ ÿÿÿ$%&ÿ567ÿ>?@ÿKLMÿ(&)ÿÿ,11ÿfhfÿPTRÿ<>;ÿWRMÿl`[ÿslÿrjhÿÿPJNÿ!"ÿ -ÿ,&.ÿlfnÿ\SSÿ­¤¤ÿÿÿÿÿ"+ÿÿÿÿ¢��ÿ¦žœÿJHAÿFD=ÿNICÿRLDÿwsÿÿðìÿ±¥¨ÿ!ÿÿ% ÿuppÿÿÿª££ÿ²««ÿÿÿÿ!)&ÿ±®­ÿÁ¼¼ÿw|�ÿIQUÿCKMÿBKKÿJOIÿÿÿÿÿÿÿÿÿÿÿÿÿ!ÿ -.ÿ"*,ÿ#)+ÿ%,ÿ#%#ÿ%&1ÿ&B{ÿ$>ÿ'#!ÿ560ÿGE=ÿVVKÿMOFÿ!#!ÿ,Iÿ Kuÿ 6}ÿ&G�ÿ9iÿ±œ˜ÿ!ÿ&!ÿSSPÿœ—‘ÿ@62ÿîßßÿïÙÚÿ0.+ÿÙÑÏÿßÐÐÿ{yvÿÛÍÎÿŸ�ŸÿEIKÿÓÐÏÿ­«¨ÿÕÓÐÿ¼º·ÿ£ž™ÿ©Ÿ¨ÿ4//ÿÿ58=ÿ##ÿÿ8:7ÿ3/1ÿÿpmlÿFDAÿ('&ÿ464ÿ¢¤¢ÿ#%#ÿ_a^ÿJLIÿAC@ÿ?A>ÿY[XÿNNKÿa\Wÿ™�ˆÿ·¥¡ÿÈ´°ÿѸ³ÿѵ®ÿÍ´§ÿTC=ÿ#!ÿUOWÿxrzÿxq{ÿ~w�ÿ®§±ÿ¨ŸŸÿ¯¦¦ÿÿÿ ÿ ÿ#"3ÿ.ÿ-ÿ"ÿ%ÿ ÿ ÿ410ÿ?>3ÿKH<ÿ86/ÿÿóïÿ·«®ÿÿÿuppÿ=88ÿÿÿ&ÿÿÿÿJIHÿ4<8ÿû¹ÿêÛÛÿàÑÒÿâÐÔÿÙÈÈÿÓÃÀÿŸš”ÿÿÿÿÿÿÿÿÿÿÿÿÿÿ -.ÿ#+-ÿ(+,ÿ*/ÿ%+'ÿ,.6ÿ$Awÿ%+Eÿ#!ÿ$&$ÿ?=6ÿQQHÿ]^Wÿÿ$DÿDnÿ3zÿ(I’ÿ;kÿ»¦¢ÿ $,ÿ% ÿKKHÿ¡œ–ÿ:0,ÿåÖÖÿðÚÛÿ641ÿØÐÎÿÞÏÏÿš–”ÿÞÏÐÿ¥¡£ÿJLOÿÐÉÉÿ¬¦¤ÿÔÎÌÿÀº¸ÿļ¸ÿ½³¼ÿ2--ÿ20-ÿHFHÿ››˜ÿ˜–‘ÿ=;4ÿ©¥£ÿ3/-ÿ¯¬§ÿ@>7ÿœš•ÿ9:4ÿuvpÿ'("ÿEIAÿ6:2ÿDH@ÿBF>ÿFLDÿTPHÿÊ·¯ÿʲ©ÿɱ¨ÿé ÿ¼¡–ÿÕ¸¬ÿ¿¬¢ÿC73ÿÿGBHÿÿÿ%!#ÿB>@ÿ?75ÿ£ššÿÿÿÿÿ - ÿ%ÿ3ÿ2ÿ/ÿ(ÿ4ÿ&#0ÿ42-ÿ42+ÿPUSÿÿöòÿÁ´³ÿ$ÿÿÿ$ÿ!ÿÿ4)(ÿC87ÿÿÿDFDÿ084ÿùµÿñÜÚÿçÛ×ÿáÕÑÿÝÐËÿÙÍÆÿž—‘ÿ# ÿÿÿ"#ÿ ÿ #ÿ""%ÿ%)+ÿ%+-ÿ&,.ÿ*02ÿ,02ÿ28:ÿ%23ÿ&12ÿ*/-ÿ*1ÿ%0)ÿ%'.ÿ$?uÿ)1Kÿ$"$ÿ'()ÿGGDÿTUOÿRUOÿ&(+ÿ$@ÿCoÿ2|ÿ&G�ÿ#>mÿ¸§§ÿ0/5ÿ+&!ÿ31.ÿ ›•ÿ4,(ÿëÜÝÿïÙÚÿ,)(ÿÖÍÍÿÛÌÌÿ{soÿ×ÆÆÿ°««ÿJJMÿÛÓÑÿº¯®ÿÊ¿¾ÿŸ·ÿƼ¸ÿÉ¿Èÿ,(*ÿÀ¼ºÿztrÿ±¬§ÿ=82ÿŠ�zÿNLEÿe^XÿŒ†~ÿDA6ÿ¡ ™ÿ./(ÿª©¢ÿ,+$ÿ^`Wÿ@D;ÿCG>ÿAE<ÿX_Sÿ¥ž’ÿɯ¦ÿŪŸÿʲ©ÿʲ©ÿÇ°¤ÿʳ§ÿ;/+ÿ>:<ÿ ÿ-*)ÿHICÿJKEÿRSMÿRSMÿLHFÿKFFÿÿÿÿÿÿÿ*ÿ+ÿ/ÿ4ÿ!<ÿ,ÿÿ%$#ÿˆƒ‡ÿÿòòÿͼ¶ÿ &ÿ!ÿCA>ÿ%$#ÿÿÿŒ~ÿšŒ�ÿ!ÿ !ÿ:??ÿ575ÿ¿ºµÿðáÜÿíßÜÿãÕÒÿÚÊÇÿáÑÎÿ²«¥ÿ?A?ÿ/:;ÿ.:9ÿ-98ÿ-98ÿ.:9ÿ/;:ÿ-89ÿ.9:ÿ4?@ÿ2=>ÿ.;<ÿ/<=ÿ&34ÿ -.ÿ.$ÿ!%4ÿ*)ÿ08:ÿ%=tÿ(3Lÿ !ÿ)&%ÿ))&ÿJMGÿ:>6ÿ678ÿ!0ÿ;gÿ<€ÿ@ÿ*=gÿŸ›£ÿC87ÿ'%(ÿ+& ÿŸ�–ÿ3.)ÿëÜÝÿïØÙÿ+&*ÿÏÇËÿäÎÏÿ¼¯ªÿÉ¿»ÿ·±¯ÿNKJÿÛÒÌÿ´¬¨ÿÉÀÀÿÖÇÂÿÐÀ½ÿÍÅÉÿ((+ÿÉÁ¿ÿÓÅÂÿÁ½»ÿ9=5ÿ¡˜‘ÿ+2&ÿ´¬¢ÿC=3ÿŽ�‚ÿ ž—ÿ][Tÿ¬§¡ÿB;5ÿ__VÿIL@ÿ`cWÿUXLÿIL@ÿ÷®ÿÔ¹²ÿ¬–Žÿ¿¦ŸÿáÈÃÿÚÁÀÿÓ½¿ÿÿÿ_]Zÿ&$ÿ;?=ÿ,/0ÿ;>?ÿ7:;ÿ9=;ÿ^`^ÿ_`aÿKKNÿÿÿÿ*ÿ-ÿ-ÿ1ÿ7ÿ95Kÿ329ÿDFDÿCECÿÑÈÈÿÿó÷ÿμ¹ÿ)ÿ+ÿLIHÿÿÿÿÿ "ÿÿÿGLLÿ=?=ÿ¿ºµÿìÝØÿðÝ×ÿн·ÿè×ÑÿàÑËÿ«ª£ÿ9@@ÿ/;?ÿ(02ÿ,55ÿ)54ÿ(43ÿ'32ÿ$/0ÿ#./ÿ#./ÿ"-.ÿ&12ÿ+67ÿ*56ÿ'23ÿ,6-ÿ5EYÿ'ÿ!$ÿ-H~ÿ*4Oÿ##&ÿ,(*ÿ/-&ÿXWLÿcbWÿ\XVÿ -'ÿ &Qÿ:|ÿD‚ÿ'9_ÿ²­³ÿ+&(ÿ#ÿ$ÿœœ“ÿ1/(ÿîâÝÿñÛÜÿ97:ÿÊÄÈÿßÌÌÿ¹¬§ÿÁ·³ÿÀº¸ÿRONÿÚÑËÿ¼´°ÿº³³ÿÌýÿÖÈÅÿÎÆÊÿ%%(ÿÌÄÂÿÚÌÉÿ[SQÿ981ÿÁ½µÿ"'ÿ€}rÿ9<0ÿ·¼°ÿ]XRÿ¥ž˜ÿ˜�‰ÿymhÿDD;ÿRUIÿJMAÿEH<ÿaaVÿƸ¯ÿïÓÌÿàÇÀÿåÊ¿ÿð×ÐÿÒÃÃÿ ÿÿÿ%"!ÿ/-*ÿÿ513ÿC?Aÿÿ&!!ÿXSSÿuprÿ‹…‰ÿÿ;ÿ,ZÿAÿ2ÿ-ÿ:ÿ'%Fÿ20@ÿ&%+ÿ''*ÿ()*ÿØÊËÿþïðÿÆ´°ÿ><Eÿ$(0ÿÿÿÿÿ¢�Ÿÿ¯§ªÿÿÿ%**ÿ575ÿµ°«ÿÜÍÈÿàÑÑÿ�††ÿjeeÿ]\[ÿIOKÿ+67ÿ.:?ÿ.6:ÿ*33ÿ*65ÿ&21ÿ".-ÿ&12ÿ"-.ÿ"-.ÿ#./ÿ ÿ#%ÿ%'ÿ (*ÿ/1(ÿ$@[ÿ /ÿ!ÿ ;qÿ$-Kÿÿ#"ÿÿ970ÿJH@ÿLGGÿ.ÿ-Qÿ7cÿ)@jÿ)DÿZTXÿ(%+ÿ 'ÿÿ$"$ÿ(&#ÿæÜØÿïÜÜÿCCFÿkfjÿØÉÉÿ¿²­ÿ·­©ÿľ¼ÿQNMÿÓÊÄÿ½³¯ÿ¨¥¤ÿÊÅ¿ÿ±¥¡ÿļÀÿ--0ÿ·¯­ÿÞÐÍÿ3('ÿ¡œ–ÿTTKÿjj_ÿÀ¶¬ÿ6;/ÿ�¢–ÿA?8ÿ»º³ÿA?8ÿ®©£ÿTTKÿ;>2ÿVYMÿRUIÿNMBÿ×ǾÿôÕÏÿêÏÈÿÖ¿ºÿ©—“ÿH??ÿÿÿÿÿ0-,ÿÿÿ'#%ÿÿÿ-((ÿNIKÿ›•™ÿ ?ÿ§¢Ìÿ¶³¿ÿ®£Øÿ<ÿ ?ÿ)&Cÿbcnÿ:;<ÿ&&)ÿ$#*ÿ,,/ÿÒÊÈÿÿòíÿ„rhÿÿÿ^]VÿIGDÿÿÿ"ÿ ÿÿÿÿ)-+ÿ«¦¦ÿßÐËÿ²««ÿ046ÿ*24ÿ+89ÿ*63ÿ/<=ÿ*6;ÿ+37ÿ)22ÿ)54ÿ$0/ÿ$0/ÿ*24ÿ*24ÿ (*ÿ#$ÿ"$ÿ &(ÿ(.0ÿ&,.ÿ,,#ÿ;]ÿ.ÿÿ7pÿ'3Rÿ'%(ÿÿ$#ÿÿ$#"ÿ(&)ÿ##ÿ$ÿ##,ÿ# ÿ(ÿ(#'ÿ&%+ÿ,(0ÿ3,3ÿ.)-ÿ758ÿÕÌÌÿèÖÓÿŽ��ÿ™”˜ÿÔÅÅÿǸ³ÿ®¤ ÿƾ¼ÿ^YYÿ̾ÿ�ŠˆÿGHIÿÇÅÀÿ2*(ÿÌÄÈÿ$$'ÿ¸°¬ÿØÊÇÿÎÁÀÿ„}wÿ"$ÿÊƾÿH<5ÿ¬¬£ÿ¬¬£ÿ0/(ÿ«¬¥ÿ7;3ÿ�’‰ÿ??4ÿDE8ÿqqdÿfgZÿ‘‹ƒÿØÅ¿ÿÞ¿ÿ©‘Žÿ'ÿ) ÿ -ÿ ÿ++ÿ25ÿ14ÿ/3ÿ.0-ÿ234ÿ123ÿ123ÿ*)(ÿÿÿNLOÿ;ÿ¡œ¶ÿfa\ÿ§¢ºÿ?ÿ#"?ÿ[[nÿ382ÿ9=5ÿ %ÿ+(4ÿedjÿÈÂÀÿôêôÿWFFÿ%!)ÿ%ÿÿÿÿ ÿ!ÿÿÿÿ !ÿÿÿ2(+ÿÚÎÊÿIRRÿ5=Aÿ5=?ÿ1<=ÿ/79ÿ*24ÿ'/1ÿ')ÿ#%ÿ!#ÿ!#ÿ $&ÿ!ÿÿ!#ÿ%&ÿ)*ÿ!,-ÿ!,-ÿ.5)ÿ7Ieÿ)ÿÿ",Nÿ+4Eÿ " ÿ#ÿ!&ÿ"%&ÿ#&'ÿ(--ÿ053ÿ256ÿ439ÿ<8Aÿ>69ÿXSNÿ†~zÿ´¨«ÿÁ¼¾ÿ¦›”ÿGDJÿäÝÝÿòÛÖÿyttÿÚÒÕÿÙÈÈÿл¹ÿ‚zvÿĸ¹ÿ&!#ÿÂÁÀÿPNQÿ46;ÿ¿½¿ÿ_]_ÿ¼±¸ÿ+')ÿ»²¬ÿÞÎËÿaYWÿ65.ÿÉŽÿgf_ÿ?:4ÿú´ÿ970ÿ®¢�ÿlf^ÿ::/ÿttgÿigXÿ€{iÿwo[ÿtpaÿ.)$ÿ ÿÿÿÿÿÿ ÿ71!ÿ;7!ÿ44!ÿ64,ÿÿ$"$ÿ$"$ÿ!!ÿÿÿÿ!$ÿ -0ÿ7.cÿ´£ÙÿE8kÿQLdÿ%ÿ>AFÿ ÿ-1/ÿ��¦ÿ{y‰ÿ*+2ÿÄ¿ºÿðæïÿB.&ÿ7+$ÿ4+%ÿ<-'ÿE60ÿ8+ ÿD8)ÿN=0ÿUB6ÿYH8ÿk[Hÿv\NÿƒgLÿƒnQÿ…|uÿáÏÌÿÊÆÈÿ79>ÿ#)+ÿ#+-ÿ,24ÿ'-/ÿ%+-ÿ"(*ÿ "ÿ#)+ÿÿ#%(ÿÿ!#ÿ!#ÿ#%ÿ')ÿ"*,ÿ%-/ÿ)=.ÿho{ÿ'#3ÿ&-ÿ )Aÿ%3Jÿ!2ÿ=8>ÿC?=ÿpljÿ¦žœÿ˾½ÿÕÊÉÿæ×Ñÿí×ÏÿîÓÒÿíØÖÿéÖÌÿÙÉ¿ÿ'$#ÿ(+0ÿ —�ÿXSUÿäÛÛÿìÔÑÿzuuÿÑÉÌÿØÇÇÿÙÆÆÿ# ÿ¿º¼ÿNNQÿƒ�|ÿš–”ÿ›™›ÿËÇÅÿvwqÿÁ¸¸ÿ*&(ÿº±«ÿàÐÍÿ°¨¦ÿÁÀ¹ÿhd\ÿ<71ÿª¨¡ÿSNHÿ64-ÿÀ»µÿ2.&ÿÁ¾³ÿzwkÿ{yjÿyiÿ|vfÿ<:3ÿ495ÿÿ $"ÿÿ" "ÿ(&(ÿ'&%ÿ(&!ÿ750ÿÿ$ ÿJGFÿÿÿÿÿÿÿÿÿ=B>ÿ#'6ÿ\^sÿ�‘Œÿlc]ÿJEEÿ‘”•ÿ3<<ÿFKIÿ‘‘šÿ,ÿ()0ÿ��ˆÿÿïâÿ¼’jÿ¹�aÿ­‰\ÿ®ƒUÿ·‹_ÿ´‰Yÿ´‹Wÿ·‹Yÿ¼Ž[ÿ·ŠTÿ·‹Sÿ½‰Wÿ©€Vÿ‘y^ÿØÊ»ÿäÑËÿ,-.ÿÿÿÿÿ(*-ÿÿ'),ÿÿ&(+ÿÿ%'*ÿÿ!#ÿ"$ÿ%'ÿ!')ÿ#)+ÿ)/1ÿ,;:ÿ ")ÿ .Gÿ:Ilÿ)9eÿS_„ÿÎÈÖÿßÍÉÿéÐËÿðÔÑÿõÙÖÿõÙÖÿòÖÙÿôÖÔÿëÔÏÿãÛßÿ��žÿÏÇËÿN<8ÿ217ÿ")ÿž˜ŽÿukgÿåÙÜÿðØÕÿ}xxÿÊÂÅÿÙÈÈÿÞÊÆÿŠ…ÿÏÇÃÿwurÿÊƾÿ~wqÿŽŠˆÿÈ¿¸ÿoofÿ¿·³ÿ# ÿ»±­ÿÞÎËÿwuÿONGÿ:6.ÿÁº´ÿ}{tÿ10)ÿ³®¨ÿMLEÿxvnÿ�yoÿwrfÿ~zkÿ{tfÿlf\ÿÿPLJÿSKGÿ!ÿ ÿ.)-ÿ<<9ÿPSMÿ478ÿ#!ÿ"ÿÿÿÿÿÿÿÿÿÿÿPDYÿE>Hÿ`^Yÿ¹§±ÿ.#(ÿž›šÿŸ ¡ÿ#&'ÿ(,*ÿ‰‰’ÿ'%5ÿ'(/ÿ486ÿÿðãÿÌ�mÿÊšgÿËœeÿÔZÿÆ”[ÿÂ�WÿÁ�XÿÀ“WÿÀ�\ÿÁŒVÿ¾�Sÿ©}KÿF/ÿacaÿÌÅÅÿÝÑÍÿ''ÿÿ$ÿ "ÿÿ'),ÿÿ'+-ÿÿ)+.ÿÿ(*/ÿÿ %ÿ"$ÿ#((ÿ,11ÿ28:ÿ+05ÿ=CKÿ¡¢­ÿ(=Zÿ]f�ÿÙÌßÿðÙÚÿõÕËÿðÙÚÿðÚØÿñÙÖÿîÜØÿïàÛÿíáØÿãØ×ÿ]e…ÿ>Q—ÿ-L|ÿ½ÃÓÿPDGÿNLUÿ(/ÿŸ™�ÿ~uoÿåÙÜÿìÓÒÿRONÿB=?ÿØÉÉÿæÑÌÿš�„ÿËÁ·ÿ*(!ÿ¿¹¯ÿŽ…~ÿwrlÿƾ´ÿ^^Qÿ€zrÿ" ÿ±ª¤ÿàÎËÿ„yxÿ¨£�ÿµ±©ÿ20(ÿ65.ÿ½¼µÿ¤Ÿšÿ#$ÿ™•�ÿqe\ÿunbÿkfZÿythÿ ÿ"ÿÿ>=6ÿ03-ÿMSOÿgegÿbb_ÿFKEÿ)..ÿ"))ÿ*-2ÿÿÿš’•ÿ ˜›ÿ£›žÿ®¦©ÿ³ªªÿ»²²ÿ¼µµÿÄ¿¿ÿÄνÿ[`ZÿXY`ÿ«³¯ÿ+-0ÿ–’šÿ1,0ÿ624ÿwuwÿ‰‰”ÿ$"2ÿ%ÿ-35ÿÿôîÿÔ›aÿÌžqÿ¾…Cÿ“]ÿ¿�VÿÄ•[ÿÀ‘Wÿ¿‘Wÿ¿ŒWÿÁ‘Rÿ’lEÿ- -ÿ\SSÿ``WÿÒÇÀÿÝÎÏÿ+13ÿ-28ÿ>@Eÿ%)+ÿ&(+ÿ-35ÿ"*,ÿ$,.ÿÿ,02ÿÿ)+0ÿÿ439ÿ!"ÿ ÿ#+-ÿ&.2ÿ+06ÿ846ÿÔÉÎÿàÏ×ÿé×ÔÿíÙÑÿñÚÕÿñÙÖÿóÚÙÿøÜÙÿó×ÓÿáÉÆÿøãßÿ£™•ÿ63@ÿ%TŽÿ3�ÿ+SŠÿÁÂÍÿWPWÿ'#ÿtxzÿŸ—�ÿ‡‚}ÿÝÓÖÿÞÉÎÿÿ™—™ÿÎÀÁÿØÇÇÿfYTÿÏÉÁÿ('&ÿEB=ÿ‚{uÿ><5ÿ[ZSÿA<7ÿ ÿ -ÿª¢ ÿÎÃÂÿļ¸ÿPNGÿ@D;ÿZTLÿ¶ª¥ÿJC=ÿ,-&ÿ·°¤ÿ‚xjÿ•‹€ÿ”‰~ÿaYOÿ/-*ÿ8;@ÿacfÿbe_ÿSTMÿ21*ÿLJCÿ.,)ÿ242ÿ#**ÿÿ ÿÿ!$ÿ-/2ÿ—�‰ÿ¡”�ÿ£–‘ÿ›Ž‰ÿ•Œ†ÿ‘ˆ‚ÿŒƒ}ÿŒƒ}ÿ„}wÿ*&(ÿaajÿ¶²»ÿ2.6ÿŽ‹‘ÿÿÿ…ƒÿzu�ÿ*):ÿ))2ÿLQVÿÿñëÿÅŒRÿÀ’eÿÏ–Tÿ“]ÿÉ™bÿȘaÿÅ•^ÿÊ—VÿÈ™iÿ`E ÿ&ÿ" ÿ!(ÿOOLÿÏüÿçÖÖÿ/35ÿ ÿ"ÿ#')ÿ ÿ#)+ÿ08:ÿ(//ÿÿ+./ÿÿ;<6ÿFICÿ)00ÿ#'ÿ#/ÿ#&1ÿ639ÿÑÈÈÿèÖÒÿíÚÔÿößÚÿøßÚÿòÜÔÿóÜ×ÿ÷ÛØÿö××ÿìÔÑÿƱ¯ÿ%ÿ/)1ÿfhoÿ)ÿ!W‘ÿ$;ˆÿ#Lˆÿ½½Ìÿ_X_ÿhWgÿ"'ÿ¢š�ÿ�‹†ÿÝÓÖÿÙÉÍÿ:AAÿÅÂÁÿÞËËÿɽ¾ÿ:76ÿÿ!ÿ'"&ÿ$ "ÿÿÿ #ÿÿÿqgjÿ‹ƒ†ÿž™™ÿtpnÿ«¨£ÿμ¸ÿ.( ÿ/2%ÿǽ®ÿŸ�|ÿ›Ž}ÿ‘ˆ�ÿ]\[ÿNQVÿ9AKÿ5?Jÿ9>Dÿ)1.ÿ/73ÿ>C?ÿ<>;ÿ#"!ÿ.33ÿ'/1ÿ).3ÿ!#ÿ!')ÿ')ÿ+89ÿbdgÿrpsÿmknÿhfiÿ`dfÿX^`ÿTZ\ÿPVXÿQRSÿONUÿffuÿ¯©·ÿxt}ÿˆ…‹ÿ†„‡ÿ©§©ÿŠ„ˆÿz†ÿ%$5ÿ88AÿlnqÿÿôîÿמdÿΠsÿÖ�[ÿÍ�jÿÊ™dÿÌ›fÿÍœgÿ¶�^ÿ`??ÿ#ÿ!ÿVPHÿjdhÿ?@9ÿÓÇÀÿçÓÕÿ8:=ÿ#ÿÿ-13ÿ68;ÿ'-/ÿ)13ÿ-22ÿÿ575ÿEDCÿ./0ÿÿ ÿ*,/ÿSNTÿÏÄÉÿëØØÿôÝØÿ÷ÜÕÿ÷ÝÒÿöÜÓÿùÝÚÿð×ÒÿïØÓÿêÕÑÿ¦”‘ÿyqtÿ3.4ÿ-/7ÿnt~ÿmorÿ /ÿL…ÿ!<‰ÿ$LŠÿ¾¿Êÿ|wwÿ#!ÿÿš’ˆÿ‡‚}ÿÐÆÉÿßÉËÿ›�›ÿÉÅÃÿÔÄÁÿÙÊÅÿ;36ÿÿÿ%#&ÿ!ÿ!#&ÿ)-/ÿ(*1ÿNQVÿÿ‘‰‡ÿÓÀÀÿн½ÿ¤˜”ÿLC=ÿCD=ÿSWNÿŠ„|ÿœ‹…ÿicaÿZZ]ÿ<DNÿ7DUÿ7G[ÿ1BYÿ:I\ÿ3<Cÿ*02ÿ!')ÿ6:<ÿÿ''*ÿ28:ÿ3?Cÿ+28ÿ.:>ÿ,78ÿ!#ÿ(,.ÿÚÒÕÿÛÒÒÿáØØÿÞÕÕÿèÙÚÿçÕ×ÿèÖØÿçÕ×ÿôããÿÔÉÎÿxsÿ°­¹ÿzv~ÿ€}ƒÿ³±´ÿ­«­ÿ‚|€ÿ„‹ÿ'&7ÿ%%.ÿljlÿÿòéÿߨnÿÄ™mÿݦfÿÇ›iÿΚhÿÃ�[ÿ¿’iÿ@7ÿ1"Aÿ -ÿÿ™‰€ÿ��|ÿNK@ÿÖÉÄÿñÛÜÿ478ÿ %ÿÿ,02ÿÿ!%'ÿ##ÿ051ÿDICÿ22/ÿÿ('.ÿÿnelÿÝÎÒÿôÞÜÿùßÜÿøÜØÿÿàÜÿøÜØÿøÞÕÿ÷ßÖÿñØÙÿñ×ÔÿnZVÿ1("ÿ-'ÿ,(*ÿ-$ÿ*!ÿ50+ÿ("ÿ(ÿL‚ÿ(F�ÿ&Mˆÿ½ÂÈÿ–”�ÿ$ ÿÿ�‰ÿ‡„ÿËÂÂÿÝÄÅÿ¼µµÿÈÂÀÿÑÄ¿ÿÙÄ¿ÿYLKÿ(,.ÿ"''ÿ"#ÿÿ$$ÿ/66ÿÿÿÿ72,ÿÎÁ¼ÿÁ¹µÿ9;2ÿ{„wÿ��ˆÿ. ÿÿ -ÿ/@Nÿ5EUÿ7Kaÿ2Gcÿ.C_ÿ1F^ÿ1BYÿ4<Fÿÿÿ:7=ÿÿÿ/7;ÿ)-ÿ!*1ÿ#14ÿ#01ÿ025ÿ+%)ÿçÓÏÿòÛÖÿïÚÕÿ÷âÝÿ÷âÞÿúåáÿõàÛÿ÷âÝÿýâÛÿϹºÿhbjÿ©«°ÿ‘�•ÿ~{�ÿ¸µ»ÿ§¥¨ÿmgkÿzwƒÿ#$5ÿ()0ÿ)')ÿÿõëÿÙ¥lÿͦ|ÿÚ¤aÿÊ¡`ÿÅ•^ÿ½”cÿ -�ÿ :ÿ0*Fÿ*)0ÿ<<9ÿOJEÿ94.ÿ=51ÿÔÄÁÿíÙÕÿ6;9ÿ#(-ÿ$$'ÿ-22ÿÿ131ÿ?>=ÿ-22ÿ"&(ÿ'),ÿÿlfdÿÄ·²ÿîÖÓÿñ×ÔÿöÝØÿóÞÙÿñÞØÿøßÚÿîÛÓÿùÜØÿâÓÓÿRJNÿ$ÿ,7Hÿ",ÿkb[ÿ ,Iÿ)$$ÿ')&ÿ3=Rÿ''4ÿ-Fÿ=hœÿ3X™ÿ-KƒÿÄÆÕÿžž›ÿÿÿ‚…yÿ‡…‚ÿÉ¿»ÿÖÈÅÿ¼¯´ÿj`cÿÑÅÁÿ̽¸ÿmgeÿ&(+ÿ"'-ÿ69>ÿ&*,ÿJNPÿ;?AÿGLLÿ;>?ÿ !"ÿÿÖÊÍÿƼ¿ÿÿÿ16;ÿ*$(ÿ"ÿ.?Mÿ1?Xÿ9CMÿ=Pbÿ0D`ÿ&3Fÿÿ:GXÿ.9Dÿÿ+0<ÿ,,/ÿaadÿ,4>ÿ7AEÿ ,+ÿ,5;ÿ$16ÿ+7;ÿ&,.ÿ-+-ÿçØÓÿïÚÕÿòÝÙÿõßÝÿøáâÿöàÞÿöáÝÿøáÜÿÿçàÿæÕÕÿrqxÿ­¯´ÿ™”šÿqlrÿ°«±ÿ¨£©ÿ‚}ÿZ\dÿ&4ÿ018ÿ‹Œ�ÿýðëÿá«qÿΣsÿÝ£^ÿÚ§kÿ­…kÿ(ÿÿ ÿÿ63.ÿ94/ÿ1)'ÿÿ0+&ÿ˽ºÿíÛØÿ9>>ÿ!'ÿ %ÿ17/ÿGKBÿ34.ÿÿ)%'ÿ' ÿ�|ÿØþÿîØÏÿ÷ÝÔÿûß×ÿóÝÔÿøÞÕÿôÞÕÿòâØÿõâØÿáÏËÿØÅËÿ<DTÿ-AUÿ;EZÿ'Alÿ .ÿŸ“„ÿ 1Uÿ[]dÿ$ÿ3Zÿ#0Iÿ,Mÿ'V�ÿ,Y™ÿ1M†ÿ¾¾Íÿ®°­ÿ@8;ÿÿ�„xÿ€~{ÿƼ¸ÿÕÆÁÿº®±ÿ�y}ÿƽ½ÿɽ¾ÿD@Bÿÿ!ÿ#')ÿÿÿÿÿ ÿ1/1ÿ957ÿ617ÿ89@ÿ79@ÿ"ÿ&//ÿ"!'ÿ*7ÿ->Vÿ1>Qÿ%*/ÿ(7ÿEOdÿ–•›ÿ®©¤ÿw~Šÿ0:Hÿ²­­ÿ9?IÿABCÿÑÍÏÿ04<ÿ5=Aÿ$$ÿ,39ÿ -2ÿ1=Aÿ ÿÿßÐËÿòÝØÿõÛØÿùÜÛÿ÷ÛÝÿöÝÞÿðÙÚÿïÚØÿïÙ×ÿšŽ‘ÿ„†�ÿ¨«°ÿ ›Ÿÿfaeÿ¬§«ÿ¦¡¥ÿsnpÿÿ &6ÿ..7ÿ¡�ŸÿüðëÿݧmÿÊ rÿÆ—]ÿ®�zÿ9"3ÿ5ÿ+$Bÿ(!3ÿÿÿ ÿÿÿ)%#ÿνÿóÜ×ÿ?=:ÿ979ÿaZZÿ685ÿÿ'%"ÿ/**ÿ˜Œ…ÿ¦–�ÿÓ½´ÿïÓËÿåÏÆÿðØÏÿíÑÉÿìÖÍÿòÖÓÿâÉÈÿ² �ÿ¸¦£ÿF:6ÿÖÎØÿ4GYÿ4N\ÿ;>Iÿ8V‚ÿ"ÿ±š}ÿ%;bÿCELÿ:??ÿ1Tÿ 4ÿ 2Nÿ8mÿ'L�ÿ,@zÿ»¹Éÿ‚Š†ÿ$ "ÿÿwznÿvtqÿµ«§ÿ×Ǿÿ¾±°ÿ`[_ÿRMOÿ°ª®ÿˆŠ�ÿ!&+ÿ$ÿÿ-13ÿ268ÿ'+-ÿ%&'ÿÿÿ™”–ÿ87=ÿFKQÿ/4:ÿÿ $"ÿ!$ÿ!.;ÿ0@Pÿ9;Cÿ©¢¢ÿ ¢±ÿMWfÿ{{~ÿæàÞÿ’™§ÿ6?Mÿø·ÿ8=Cÿ9><ÿÌÈÆÿ79Aÿ:?Dÿ!!ÿ05;ÿ ÿ#(ÿ,*-ÿ)!$ÿçÓÏÿíØÓÿëÙÕÿòäáÿúäÜÿöÝÖÿñÜ×ÿÞÌÈÿé×ÙÿICKÿ|…Œÿ˜› ÿ¥£¥ÿJFHÿ¤ ¢ÿ¢ž ÿyswÿ''4ÿ#(:ÿ,,7ÿ­¥¨ÿÿòéÿÙ£jÿÀ—mÿ}\8ÿÿÿÿ%ÿ4.Bÿ -ÿÿÿ -ÿÿ+('ÿÅ»·ÿðÖÍÿ«¢›ÿkecÿ#ÿ% $ÿÿÿÿ - -ÿ"ÿÿ#$ÿ*ÿ4$!ÿ8#!ÿ.ÿ'ÿ"ÿ" ÿuywÿCECÿÖÑÓÿZk{ÿ&*ÿ$ÿ&N†ÿ+ÿrbRÿ4^ÿss|ÿVUNÿ"0Gÿ\blÿ)0Fÿ Lÿ"<{ÿ(:tÿ¸µÇÿ]c_ÿ789ÿÿtvmÿRPMÿg_[ÿѼÿº¯®ÿJHJÿˆ…„ÿˆƒ‡ÿJLQÿ,16ÿ-05ÿ%)+ÿ)+.ÿ!#&ÿÿÿÿÿ‹„„ÿ336ÿ149ÿ+/1ÿÿÿ ÿ&0ÿ ,3ÿ½·»ÿèÛÚÿ|}Žÿ<LVÿqx~ÿßÚÞÿ7=Mÿ6=KÿÇ»·ÿAFLÿ9?;ÿØÒÐÿ23:ÿ25:ÿ+/1ÿ+-4ÿ**3ÿ"ÿ¼´¸ÿ„x{ÿãÎÉÿ‘}uÿ>5/ÿFD?ÿòáÔÿŸ‡xÿ¬šŒÿƒwnÿßÐÔÿA@Gÿ]fmÿ@CHÿ›™›ÿÿš–˜ÿ§£¥ÿpkoÿ""1ÿ%(:ÿ//8ÿ®¦ªÿÿîÖÿÇ›sÿ>ÿÿÿÿÿÿÿÿÿÿÿÿÿ¾²®ÿèÕÍÿj]Xÿ%ÿJ@<ÿJEEÿÿÿÿQKOÿ5/3ÿ& $ÿ937ÿÿÿÿÿÿÿ:DAÿQVPÿ27CÿìÛÎÿ5CXÿ'#!ÿ&ÿ4Z�ÿ*ÿS@8ÿ)Fÿ.ÿÿ1ÿ%0ÿ 9ÿ9ÿ#7dÿ =wÿ­±Æÿ’��ÿ-/4ÿÿproÿ45/ÿHF?ÿË»¸ÿ¯¥¨ÿ)+)ÿ@;5ÿ»³¯ÿ‰„„ÿ}~ÿ)-/ÿ!ÿ!ÿ'"$ÿHC=ÿÿÿ)'*ÿ†~|ÿ/-0ÿÿÿ*.,ÿgfeÿ012ÿ %ÿ9>Dÿ536ÿ-,+ÿ@CUÿ1AJÿ‚��ÿÝÙÛÿ04Iÿ6@Oÿ¿·³ÿ5:@ÿ<A?ÿÍÉÇÿ/18ÿ67>ÿ>>Gÿ'*5ÿ%%2ÿ"(ÿ‡‚„ÿµ®µÿÞÓÈÿ†qeÿSRGÿ-,%ÿßÐËÿŽymÿ©˜ˆÿhd\ÿÒÂÆÿ?AHÿ6:BÿCBHÿ˜–˜ÿ" ÿ•‘“ÿ—“•ÿjhkÿ%%0ÿ!#2ÿ447ÿ­¨®ÿÿíàÿ,ÿ"ÿ ÿ!ÿÿÿÿÿ !ÿ/-0ÿ758ÿ9;@ÿ?@GÿVQWÿƹ´ÿîÛÓÿŠ|yÿE6:ÿ)ÿÿÿÿ\XZÿkeiÿ]W[ÿHBFÿ[UYÿUPTÿÿÿ -ÿ�‡…ÿ­¥£ÿ½¸³ÿ¸°¬ÿ¥¤«ÿ±¤ÿRb|ÿ# ÿ#ÿF[‹ÿ#ÿ^SHÿ1ÿ+ÿÿ+ÿ*3:ÿ,ÿ)ÿ=ÿ#Ayÿ£©¿ÿŠ‚†ÿ)!+ÿÿfedÿ""ÿ34.ÿŽ…ÿ¢œšÿÿ*'"ÿˆ€|ÿŒ……ÿÿÿÿÿÿ1&ÿe]YÿXSWÿ425ÿˆ€~ÿUQOÿ€‚ÿ†ˆ…ÿ7<8ÿ ÿccfÿniiÿ°¬®ÿ½º¹ÿwwnÿ;>Cÿ8CDÿ|ˆ…ÿÜØÚÿ9=Rÿ1;Jÿ¾¶²ÿ38>ÿ>CAÿÏËÉÿ24;ÿBCJÿ77@ÿ-0;ÿ%(3ÿ#-1ÿ¼³³ÿ¶«°ÿàÓÆÿˆn`ÿRI;ÿbXMÿñÜ×ÿ�znÿœ�~ÿic[ÿÔÄÈÿ8:Aÿ8<Dÿ>=Cÿ�Ž�ÿ ÿ^Z\ÿ402ÿmknÿ&&1ÿ!#2ÿ336ÿ¯ª°ÿø×èÿÿÿÿÿÿÿÿ97:ÿ?=@ÿJHKÿECFÿ@BIÿCEMÿGBHÿп¹ÿí×Ïÿ„uvÿ ÿÿÿÿ/+-ÿLHJÿ[UYÿLFJÿÿ#!ÿ1,0ÿ@;?ÿÿÿº¯¨ÿű©ÿ ‰„ÿ€lhÿkcfÿ¸¦˜ÿ3Fdÿÿÿ#&Pÿÿ\XIÿ+ÿ(ÿÿ ÿ#,2ÿ%ÿÿ1ÿ":kÿ”—¨ÿ¤››ÿC>BÿÿA<@ÿÿÿJH@ÿ¡ž™ÿÿ,+*ÿ@@=ÿ2/.ÿÿÿÿ(,*ÿiifÿbRIÿ·ª¥ÿº¾ÿ% $ÿg_]ÿŸ—“ÿâÞÜÿqsqÿKOQÿ68=ÿ_ZUÿbVQÿOMPÿXRVÿMMBÿKJIÿÿu~~ÿÝÙÛÿ<@Uÿ*4Cÿ¿·³ÿDIOÿ8=;ÿÏËÉÿ)+2ÿ=>Eÿ@@Iÿ+.9ÿ&,4ÿ$%ÿÁ¶µÿ²¶ÿãÔÎÿu]TÿPF;ÿ[QCÿëÔÏÿl`ÿ‹‚qÿf`XÿÔÂÆÿACJÿ:>FÿEDJÿ~|~ÿ#!ÿÿ" ÿigjÿ#ÿ&ÿLLOÿ²­±ÿùØ÷ÿÿ!ÿÿÿÿÿÿ -ÿ504ÿFDGÿPMSÿFGRÿVYdÿLGMÿƵ¯ÿçÒÎÿŒ~ÿÿÿÿÿÿÿ ÿ ÿ ÿÿÿ ÿÿÿ?>3ÿ½´¦ÿÀ²©ÿ¼¶®ÿÇ¿»ÿª›ŽÿH[yÿSPVÿÿ+&Jÿ!ÿXVGÿ&ÿ&ÿÿÿ%,2ÿ"ÿ -ÿ'ÿ AÿFFQÿÀ¹³ÿ&(&ÿÿÿÿÿ%&ÿVSNÿ#!ÿ!#!ÿ$)%ÿ?DBÿ#!ÿSQSÿnliÿŠ‰ˆÿÿ‹xnÿÈ´°ÿÖÇËÿ#!ÿZTRÿý»ÿâÚÝÿ�~„ÿ(*1ÿ !ÿqeaÿ~slÿ:<AÿÿXVNÿ410ÿ:8;ÿmqsÿÙÖÕÿ:?Qÿ1;Iÿº¶ÿ@EKÿ9><ÿÈÃÃÿ'+-ÿ>@CÿFGNÿ(+6ÿ26>ÿ"#ÿùµÿÆ´¶ÿ×ÎÈÿRC=ÿB>6ÿPH>ÿìÔÑÿpaTÿvr]ÿa[SÿÕÃÇÿEHMÿ9=Eÿ639ÿompÿ%!#ÿÿ ÿusvÿ€Œÿ,->ÿ138ÿ°«¯ÿíÛéÿ""ÿÿÿÿÿÿÿ ÿ2.,ÿJEIÿ;7?ÿKHTÿIIVÿ95>ÿ¹¬«ÿk]^ÿKC?ÿojdÿ_[YÿÿE@Dÿ£ž¢ÿÿ%#ÿICGÿ„~‚ÿoimÿgaeÿgaeÿ€z~ÿÿ/*$ÿ©Ÿ•ÿ��xÿkcYÿq`Zÿ’�ˆÿ@Seÿ!'ÿÿ#!4ÿ !(ÿfa[ÿÿ*ÿ!ÿ)ÿ'*6ÿ-0<ÿ!ÿ ÿ.ÿ!)ÿ‡„ƒÿÿÿ'%(ÿ0.1ÿÿÿ-,+ÿ432ÿBA@ÿ.-,ÿ+-*ÿx}wÿ ž—ÿŽˆ†ÿàÕÚÿÿm\OÿÝÈÃÿíÕÚÿ1)-ÿA<<ÿµ·µÿâØÛÿ†„‡ÿ2:>ÿ$ÿjdhÿhe`ÿQVPÿigbÿDA<ÿc_]ÿ%"!ÿ‰‰ŒÿãÝÛÿ<@Oÿ<FTÿ·²­ÿAFLÿ=@Aÿ ž¡ÿ0:7ÿ@FBÿIHNÿ69Dÿ)*5ÿ"*,ÿŸÿĵ¹ÿÙÍÈÿMD=ÿA;3ÿRG@ÿäÓÓÿ\RHÿgdSÿWJEÿÕÀÆÿDGLÿ�„‰ÿvqwÿXRZÿUPTÿÿÿojnÿqm}ÿ()Bÿ,.6ÿilmÿâØáÿ(#'ÿ ÿ31,ÿ731ÿA=;ÿOJEÿUPJÿFA;ÿA>9ÿFDAÿ<:<ÿ*)0ÿ23>ÿ86?ÿ2++ÿÕÈÇÿ¨Ÿ™ÿvphÿid_ÿÿ ÿ -ÿpkoÿÿA;?ÿÿYSWÿÿ%#ÿicgÿÿÿec\ÿ�‰ƒÿ›š“ÿ�{xÿ¦œ˜ÿ?P^ÿ#ÿÿ 1ÿ"ÿ%# ÿ-+4ÿ--8ÿ++6ÿ%%0ÿ !,ÿ&'2ÿÿÿ(ÿ(ÿ[]`ÿ#"(ÿ$"ÿ63.ÿFC>ÿB?:ÿ><9ÿÿ??<ÿCC@ÿ$"$ÿ!ÿ?D@ÿgd_ÿÍÈÃÿêÛàÿ''*ÿ=5+ÿ×ÆÀÿóÛàÿ'#ÿ4//ÿ¸µ´ÿáÕØÿ——šÿKUYÿÿ'()ÿmleÿKOGÿbc\ÿ*+%ÿ_d`ÿQYVÿŠŽ�ÿáÛÙÿ?CRÿ<FTÿºµ°ÿAFLÿ@CDÿËÉÌÿ8AAÿAFFÿJIPÿ14?ÿ(*2ÿ$,.ÿø·ÿ¾¯³ÿÏÆÆÿC?=ÿ;96ÿNHFÿØÐÓÿGGDÿPSMÿIFEÿÓÂÊÿQTYÿ¶¹¾ÿidjÿ¤ž¦ÿ&!%ÿjgfÿ¡œ¢ÿqlpÿwsƒÿ,-Fÿ.08ÿa`_ÿçÚÙÿ>86ÿ654ÿ979ÿ=?Gÿ!,ÿ ÿ#!ÿ2++ÿ502ÿ;79ÿ;:9ÿ336ÿ--6ÿ79Aÿ*(+ÿj]\ÿZOHÿvndÿ†yÿÿÿÿÿÿ\VZÿÿÿÿ'!%ÿ& $ÿ" ÿÿž‘�ÿ3$$ÿ$ÿ'ÿNGAÿ8CNÿ$ÿÿ'ÿ),7ÿ136ÿ$$/ÿ(ÿ!!,ÿ'ÿÿÿÿÿ ÿ%ÿ(-3ÿ<:=ÿ?=:ÿ=;6ÿ=;6ÿ?=8ÿ1/1ÿÿÿÿÿÿÿ‹‡…ÿÐÈÄÿé×Ûÿ)&,ÿ53.ÿÔÇÂÿï×Üÿ.&*ÿ1,,ÿ¶±±ÿéÙÝÿ˜˜›ÿXfiÿœ¤®ÿÿNNKÿ{}zÿWXYÿ+-0ÿ)37ÿ8GLÿƒˆ�ÿÛÕÓÿ@DSÿ9CQÿ‹†�ÿ>CIÿFIJÿËÉÌÿ18>ÿBEJÿ>=Dÿ),7ÿ57?ÿ(02ÿÁ¶µÿ¾¯³ÿÓÑÎÿCC@ÿAGCÿZZWÿÌÊÇÿOQNÿX]Yÿ[]ZÿпÅÿJMRÿ´·¼ÿjekÿœ–žÿ&!%ÿ¦£¢ÿ�˜žÿjeiÿuq�ÿ)*Cÿ24<ÿ‰„ˆÿØÐÞÿ'ÿ9G\ÿ;ÿALeÿ(/Eÿ,ÿ'ÿ!"ÿ-&-ÿ0+1ÿ314ÿ4/3ÿ?AFÿ68@ÿ:8;ÿØÉÉÿ̽·ÿyncÿymhÿÿ`[_ÿQLPÿÿ" ÿ%#ÿNHLÿZTXÿ€z~ÿ0*.ÿÿ715ÿÿÿ"ÿÿÿ.)#ÿ=EOÿ -ÿÿ"ÿ!$/ÿ !(ÿ%ÿ ÿ%ÿ#ÿ""+ÿ$ÿÿÿÿ!ÿ!ÿHIJÿIKIÿ*-.ÿ ÿÿÿÿÿ&ÿ&%+ÿ8:=ÿ!!ÿ:;<ÿ¼¹´ÿçÕÙÿ& (ÿ.20ÿ¶±ÿõÝàÿ*"&ÿ/**ÿ³¬¬ÿØËÊÿ¢�¡ÿWkoÿ›¢®ÿ—™¡ÿ'&,ÿ#ÿ"&.ÿefmÿ±¶ÂÿF]iÿ‚‹‘ÿÛÕÓÿCFRÿ:DRÿ³®©ÿCELÿ;>?ÿ¾¼¿ÿ16<ÿ;=Eÿ@>Gÿ'+3ÿ.08ÿ%-/ÿ�ywÿ»¯²ÿÜÊÆÿÞËÅÿÞÍÇÿÝÉÁÿâÉÂÿл¶ÿØÄÀÿѺµÿßÉËÿSV[ÿ¥¨­ÿWRXÿŠ†Žÿ% $ÿ¢Ÿžÿ›–šÿe`dÿpn~ÿ'(Aÿ35=ÿnsyÿçÔäÿ#+ÿ0:Hÿ 2ÿ!&8ÿ,ÿ ÿÿÿÿ'#%ÿ513ÿC<<ÿ617ÿ107ÿ.(,ÿe][ÿpicÿLI>ÿNKFÿ"ÿÿÿÿÿ#!ÿÿÿÿÿÿÿÿ$!ÿ$!ÿ$!ÿÿÿ ÿ"ÿÿÿÿ#ÿ#ÿÿÿÿ&ÿ&ÿ&ÿ ÿÿÿÿ,-.ÿ.03ÿÿ#%(ÿ&(+ÿ (*ÿ*.0ÿ--0ÿ+/1ÿ)*+ÿ//2ÿ"$ÿCHMÿEJHÿпÅÿ/&-ÿ()*ÿ®¢�ÿõÝàÿ)!%ÿ,')ÿ¼°³ÿÒÑÊÿ³¢­ÿJgrÿr†ŠÿI\dÿnw…ÿRR_ÿT\lÿ>JQÿx’¥ÿNhvÿz€‚ÿÛÓÏÿhgtÿ0;Fÿ ž–ÿ@?Fÿ;ACÿ¾º¼ÿ,/4ÿ9;BÿKIRÿ+.9ÿ%(3ÿ#/3ÿ�||ÿǼÁÿ§“‹ÿ½£–ÿ°–ˆÿÁ¨—ÿȱŸÿͲ¡ÿÁ¥—ÿɲ¦ÿÛÇÃÿZ\_ÿ®°¸ÿXU[ÿuqyÿ'"&ÿ›™–ÿ�‹�ÿ]XZÿkkzÿ),Eÿ44=ÿh]bÿíÙãÿ"!ÿ#ÿ#ÿ)#+ÿÿÿÿ$ "ÿÿÿÿÿ% &ÿ=<Cÿ& $ÿ£™œÿ´®¬ÿ‰†�ÿ,)(ÿÿÿ¯©­ÿÿpjnÿ("&ÿ[UYÿ715ÿ™Ž“ÿd\`ÿ‚|€ÿÿÿ&!#ÿ'"$ÿÿÿÿ3ÿ(5Rÿÿÿÿ ÿ$ÿ'ÿ(ÿ#ÿ 'ÿ&ÿ!ÿÿÿÿÿÿ!#&ÿ #ÿ:<?ÿ:<?ÿÿ79<ÿPKOÿ”‰Žÿkdkÿ‚}ƒÿB@Cÿcacÿ¥£ ÿéÚÛÿ+%)ÿ..+ÿÍÁ¼ÿòÚÝÿ&"ÿ)$&ÿ° ¨ÿÀÀ½ÿº©¹ÿ3L]ÿfu{ÿo„�ÿn†™ÿYxŠÿr�¦ÿo�œÿb�Ÿÿ(<Jÿ‚„‡ÿØÐÌÿNMZÿ9DOÿ\^Uÿ:;Bÿ379ÿrstÿ038ÿ<>EÿA?Hÿ25@ÿ+,7ÿ$.2ÿ»²²ÿÍÀÅÿÀ¬¤ÿ·��ÿ³™‹ÿê™ÿĪ•ÿͯšÿä’ÿÉ°ŸÿàÉÄÿtuvÿ©ª±ÿ_Z^ÿfbjÿ% $ÿ•“�ÿŒˆŠÿe`bÿuu„ÿ-0Iÿ009ÿ¯¨¨ÿéÜçÿÿ&&ÿ ÿ"#ÿ$%ÿ'$*ÿ-*0ÿÿÿÿÿÿÿ=<Cÿ$"ÿB2:ÿ1 &ÿ!ÿ& ÿÿÿMGKÿÿÿÿ*$(ÿÿÿ ÿÿÿÿÿ'"$ÿÿÿÿ*ÿ1ÿ"ÿ&ÿ&ÿ&ÿ#ÿ$ÿ%ÿ)'0ÿ.+1ÿ0-3ÿÿÿÿÿÿÿ"$)ÿ>@Cÿ*,/ÿ*,/ÿ..1ÿTVYÿCEHÿÿÿ43:ÿ1,0ÿKFFÿ©¢œÿëØØÿ*&(ÿ-*%ÿɽ¶ÿëÓÖÿ-%)ÿ2-/ÿ³¤©ÿ|‚zÿ»±»ÿ@Tbÿ“ˆ�ÿ¾½ÊÿBWiÿGr„ÿG}‡ÿ´¿Æÿ`Xlÿ.COÿnyzÿÞÖÒÿIHUÿ-8Cÿ,4*ÿMNUÿ;=@ÿ/23ÿ',1ÿ9;BÿJHQÿ25@ÿ+,7ÿ#'ÿœ�‘ÿ̽Âÿï§ÿ¾¤—ÿ½£•ÿ¿¦•ÿÆ®›ÿÅ«˜ÿĦ–ÿÄ­ ÿßÆÁÿqpoÿ³³¶ÿQLNÿYS[ÿ&!%ÿ�Ž‹ÿˆ„†ÿfacÿffuÿ+.Gÿ22;ÿ¨ £ÿåÛìÿ4,6ÿ-'/ÿ!ÿ*,1ÿ#%,ÿ!(ÿ.)5ÿ ÿÿÿÿ&!#ÿ%#&ÿA@Fÿ'#%ÿÿÿÿÿ ÿÿÿÿ ÿÿ -ÿÿÿ -ÿ ÿ ÿÿÿ# ÿ# ÿÿ#ÿ#ÿ(#)ÿ"ÿ&ÿ&ÿ(ÿ,+2ÿ217ÿ %ÿÿÿÿÿÿÿ"ÿ&%,ÿ&ÿÿ^^aÿ003ÿLLOÿ.*,ÿ !ÿ:BDÿÿÿ%ÿÿc_]ÿĽ·ÿêÚ×ÿ*&(ÿ'!ÿ²¦ŸÿãËÎÿ0(,ÿ0,.ÿ÷³ÿnwpÿ»µ¹ÿ?R\ÿ�‘’ÿÂÄÉÿ7=Mÿ9AUÿz�‡ÿÔÌÊÿhhwÿ<FUÿ<BDÿtlhÿLKXÿ.9Dÿÿ"$)ÿ8:=ÿÿ&+0ÿ9<AÿIHOÿ26>ÿ45@ÿ %*ÿ«¢¢ÿÆ·¼ÿ¬›•ÿª”‹ÿ¨“‡ÿŸ‹}ÿ—ˆ{ÿ—…{ÿ{h`ÿŠ|sÿçÒÍÿcc`ÿ««®ÿJEEÿHEKÿ ÿ‚~ÿiegÿd_cÿ]]lÿ#'=ÿ<=Dÿ•�–ÿäÑçÿ)&,ÿ06@ÿ63?ÿ##,ÿÿÿ;<Gÿ+$,ÿ.,.ÿ?43ÿZRVÿYY\ÿ478ÿ-22ÿ&%$ÿ"ÿ% "ÿ"ÿ% "ÿ,$'ÿ$ÿ)!$ÿ+#&ÿ)$&ÿ# ÿ(#%ÿ&!#ÿ&!!ÿ!ÿ$ÿ$ÿÿ"ÿ'""ÿ$ÿ"ÿ#ÿ!"ÿ!2ÿ)ÿ'ÿ,)/ÿ )ÿ'ÿÿÿÿÿ ÿ$ÿ&ÿ#ÿ ÿ%ÿ33<ÿWTZÿ*(+ÿÿÿ``]ÿxzwÿ<?@ÿÿ %ÿC@Fÿ&'ÿY[^ÿŲ²ÿòÕÑÿ7'/ÿ##&ÿ‰‹‚ÿË·¹ÿ5*/ÿ1/1ÿιÿou…ÿÌÁÀÿ;HYÿ�Ž‘ÿÊÅÅÿ4>Mÿ/;Jÿy~~ÿÛÖÑÿmo~ÿ2BUÿ-;:ÿTRKÿRQ^ÿ2<Jÿÿÿ268ÿ:>@ÿ:?Eÿ=?BÿLNQÿ04<ÿ%+5ÿ!$)ÿkhgÿ»°µÿÓÈÇÿÍÿÿÔÊÆÿÜÒÎÿåÙÕÿèÚ×ÿå×ÔÿêÜÙÿöâÞÿ\^\ÿlnqÿ$! ÿ;9;ÿ ÿFDGÿÿ[Zaÿ0ÿ$'8ÿ48:ÿ‚€‚ÿáÓïÿ+-5ÿHQ_ÿ.0?ÿ(ÿ&*9ÿ!0ÿ#ÿWPZÿiknÿ¾°±ÿĹÀÿeenÿNPXÿFINÿ*%'ÿ%ÿ!ÿ#ÿ#ÿ(!!ÿ!ÿ)""ÿ.''ÿ1**ÿ&ÿ*##ÿ-&&ÿ*%%ÿ'""ÿ-((ÿ+&&ÿ4//ÿ)$$ÿ% ÿ!ÿ!ÿL?>ÿ<5?ÿCgŒÿTl�ÿ -(ÿ ÿÿ!ÿÿ!ÿ&ÿ$ÿ)ÿ#ÿ *ÿ42;ÿ)(/ÿHGNÿ%ÿÿÿ -ÿ ÿÿB8;ÿÿÿÿ65.ÿ!83ÿM_cÿ?AHÿ×ÈÃÿ2'.ÿ$ÿ8B8ÿeYZÿ5/3ÿ846ÿʾµÿ%+;ÿÏÄÃÿ6CTÿ™—šÿÍÈÈÿ@JYÿ9ETÿjssÿspkÿ}Žÿ1@Sÿ4@?ÿGE>ÿVUbÿ",:ÿ>BDÿ9=?ÿ?CEÿ=ACÿ<AGÿ79<ÿ>@Cÿ04<ÿ'-7ÿ!$)ÿ%'%ÿ¢œ ÿæÑÏÿûâÝÿøßÚÿúáÜÿýæáÿúãÞÿøáÜÿùâÝÿôØÚÿmkmÿ&&)ÿ850ÿ“’‘ÿ%#%ÿ" "ÿ!!ÿSRYÿ./@ÿ$'8ÿ6:<ÿOMOÿâÑéÿ43:ÿU\hÿ ,ÿ"ÿ" )ÿ!(ÿ!(ÿ2.7ÿ#ÿÐÁÅÿÙÈÒÿ\[lÿLO`ÿ??Hÿ+#&ÿ+ ÿ,$"ÿ)!ÿ+#!ÿ,&$ÿ/)'ÿ)#!ÿ& ÿ$ÿ-%#ÿ.&$ÿ-%#ÿ/((ÿ4//ÿ#ÿ-((ÿ500ÿÿ-((ÿ$ÿ$"$ÿ‹~yÿE78ÿ&4Uÿ;ÿ*ÿÿ"ÿ*ÿ%ÿ)ÿ#ÿÿ218ÿ%ÿ &ÿÿÿÿ'%(ÿ)'*ÿÿ!"ÿ&$'ÿ!ÿbVRÿò¬ÿcikÿ9:ÿ -$'ÿGLÿd…‘ÿZ}Šÿ£®©ÿ613ÿ-(.ÿ¶º²ÿ̺¼ÿG<Aÿ)')ÿʾµÿDJZÿÕÊÉÿ8EVÿ‹‰ŒÿÈÃÃÿBL[ÿ7CRÿ*65ÿLJEÿƒ…”ÿ$.Bÿ&21ÿA?8ÿON[ÿ%3ÿ046ÿ*.0ÿ/35ÿ'+-ÿ).4ÿ/14ÿ+-0ÿ-19ÿ*0:ÿ!$)ÿ$(&ÿ558ÿȺ»ÿÆ´¶ÿÁ¯±ÿ½«­ÿ­Ÿ ÿ¡•–ÿ¡•–ÿ™�Žÿ“x~ÿJEIÿ646ÿSNHÿnnkÿÿ&%$ÿba`ÿXW^ÿ():ÿ$'8ÿ48:ÿHFHÿáÏãÿ1,0ÿ"#*ÿ2.6ÿ% "ÿÿÿ1,0ÿC?Gÿ(*/ÿÌ¿ÄÿÙÈÒÿXViÿFI[ÿCCNÿ)!%ÿ*ÿ4)(ÿ.#"ÿ+ ÿ0($ÿ,'"ÿ4/*ÿ(#ÿ2*&ÿ2'&ÿ/$#ÿ.#"ÿ)""ÿ*%%ÿÿÿÿÿÿ+&&ÿÿ…zsÿvi\ÿG8Cÿ2):ÿ%(ÿ#ÿ&ÿ%ÿ!ÿ))2ÿ11:ÿ+,-ÿ#"!ÿ!!ÿÿ ÿÿÿ54:ÿÿÿ !ÿ/)-ÿ#$%ÿSJDÿ…vpÿmtzÿW‘§ÿHˆ§ÿ0p�ÿ:fˆÿ*0FÿpZ[ÿ7"'ÿ$!'ÿ¶¯©ÿйºÿaTYÿ/-/ÿÍÁ¸ÿjkvÿÚÑÑÿAKZÿPNQÿÀ¾ÀÿFP_ÿ>JYÿ#"ÿFDAÿ„‚’ÿ$->ÿ,55ÿ%"ÿKJWÿ,5Cÿ9<Aÿ:>@ÿEIKÿ39;ÿ7<Aÿ136ÿÿ16<ÿ$'2ÿ#&+ÿ ÿ034ÿ³®®ÿÕÎÎÿÙÏÒÿ×ÐÐÿàÐÔÿäÒÖÿÁ°¶ÿ²£§ÿïÕØÿÞÓØÿkfhÿtoiÿ,.+ÿ'&%ÿ�zÿkidÿFEKÿ)+:ÿ.ÿ157ÿEFGÿÞÑãÿ( *ÿ ÿ!%ÿ"#ÿÿÿ(#'ÿÿÿ¥žžÿÚÏÖÿCCNÿ<<Kÿ@:Hÿ1*1ÿ' ÿ#ÿ+$$ÿ&ÿ,##ÿ5,,ÿ8//ÿ0''ÿ2++ÿ+$$ÿ' ÿ+$$ÿ+#'ÿÿÿÿÿÿ ÿ+""ÿ#!#ÿrmgÿG=/ÿ¡“�ÿÒÅÐÿb[gÿ%ÿ!,ÿ328ÿ%#&ÿ !ÿÿ# ÿ!ÿ! ÿ!"ÿ&&ÿÿ"ÿ/3;ÿš‘˜ÿœ¡¡ÿ6ONÿE_hÿ:7Dÿ“ƒ‹ÿ¹ª®ÿaZaÿäÝçÿ~�’ÿAI]ÿ.*2ÿ›–šÿÏÀºÿ7,1ÿ+(.ÿ¶©¤ÿ½®¯ÿ}ryÿ(##ÿŹ°ÿ›‘�ÿÈÇÎÿLNUÿÿ�ˆÿCM[ÿ:FUÿ,(ÿLNSÿ�Šœÿ(2Fÿ#%ÿJKLÿ (ÿ(+<ÿ;=Dÿ48:ÿBHJÿ;ACÿ.16ÿ.16ÿ),1ÿ*-2ÿ&+1ÿ(+0ÿ469ÿ$%&ÿ¸­ÿ·£›ÿàÉÄÿ‹yoÿ �…ÿ»«¨ÿc[YÿSKAÿæÔÐÿâÍËÿ–‹Šÿ5::ÿ38=ÿ!ÿ�Š‚ÿ{yqÿ&&)ÿ%(4ÿ+.?ÿSRXÿ……‚ÿØËÝÿ.&0ÿ1,0ÿ#ÿÿ"%ÿ ÿ0-3ÿ11:ÿÿ700ÿãÔÙÿ;8Dÿ??Nÿ>8Fÿ3,3ÿ&ÿ' ÿ-&&ÿ&ÿ6.1ÿ2*-ÿ6.1ÿ"ÿÿ*##ÿ)""ÿ)""ÿ% $ÿ!ÿÿ ÿ(#)ÿ+&*ÿ+#&ÿ-$$ÿ$#"ÿge`ÿfa[ÿ(ÿ²§®ÿsmuÿ&'.ÿ#ÿ"!ÿ ÿÿ! ÿ#$ÿ"#ÿ ÿÿ%#ÿ! ÿ&%,ÿ+/7ÿ¢™™ÿ§©¬ÿ|™¥ÿ\‡Ÿÿ@;UÿiShÿ¯ž©ÿh^aÿÜÏÎÿ�Ž•ÿ;KUÿ7BCÿŽ��ÿÕÆÀÿ>38ÿ'$*ÿ˜“ŽÿŸ”“ÿ–Š�ÿÿƺ³ÿ:0,ÿ¿¾ÅÿACJÿ^\^ÿ46=ÿ<GRÿ<KQÿ)ÿEHBÿ•”›ÿ)/9ÿ\_dÿ %ÿ.6@ÿ"0ÿ=FLÿ4:<ÿ@BEÿÿÿ-05ÿ),1ÿ.16ÿ!&,ÿ"%*ÿ.03ÿ9:;ÿ¾´©ÿ­™‘ÿâËÆÿŒzpÿ˜ˆ~ÿÀ´­ÿslÿ¨•‰ÿç×ÔÿξÂÿE:?ÿ/27ÿAFFÿCA<ÿ��€ÿeg^ÿ*)(ÿ--8ÿwt†ÿF?Gÿ»±´ÿáÔæÿ2*4ÿ% $ÿÿÿ%ÿ#ÿ &ÿ+ÿ'(/ÿe^^ÿßÐÑÿ75>ÿ00?ÿD>LÿB;Bÿ-&&ÿ%ÿ%ÿ"ÿ0*.ÿÿÿÿÿ"ÿ+$$ÿ+$$ÿ611ÿ% ÿ~ruÿaY\ÿ$#ÿ! ÿ+#&ÿ/&&ÿ'&%ÿ]a_ÿ|€~ÿš““ÿ/%(ÿÿÿÿ ÿ" ÿÿ#!ÿÿÿÿTROÿ�ŠŒÿOJNÿ%ÿ=AIÿW\XÿÀÂÅÿÓÑáÿ¼·Éÿ#-ÿICQÿÕÎØÿêÝÜÿêÖØÿ§œ©ÿJBVÿ<#4ÿwnuÿô®ÿK@Eÿ!$ÿlkjÿ0+&ÿ›Ž�ÿ)#'ÿ¸­¦ÿ(ÿihoÿDFMÿ'ÿ7@NÿFO`ÿ?BNÿ -ÿ �ÿ".ÿÿ)$0ÿ$ÿ14@ÿ(/=ÿ$&-ÿÿIILÿÿ"ÿ),1ÿ/27ÿ.16ÿ$)/ÿ#&+ÿ&(+ÿ=>?ÿ¾´©ÿ³Ÿ—ÿæÏÊÿ“�wÿŽ{sÿÁ²­ÿi_[ÿ^RIÿîßÚÿäÓÓÿ×ÈÉÿE@Dÿ9:;ÿ#!ÿa_Zÿ+0.ÿ)-+ÿGIQÿ44Gÿ4/;ÿÒÆÏÿÔÄØÿE>Fÿ# &ÿ!(ÿ77Bÿ9:EÿST_ÿ&&/ÿ((3ÿ(ÿH@CÿÞÏÏÿC?HÿCCRÿ<9Fÿ@;Aÿ$ÿ) ÿ2))ÿ3**ÿÿÿÿÿÿ ÿ%ÿ(!!ÿ0($ÿ‘ˆ‚ÿ×ÈÃÿj^Zÿ'"$ÿ!ÿ( #ÿ1((ÿ$"ÿ^ccÿbfhÿŠ……ÿPHFÿ ÿÿ#ÿ%!ÿ!ÿ& $ÿ*"%ÿOIGÿ‘Ž‰ÿœ—‘ÿ´°¨ÿ611ÿ0+/ÿ~…ÿ48@ÿdfdÿ»¶ºÿÜÖÞÿÔÔÑÿ½Ã¿ÿ«±³ÿÔÑ×ÿìÛÛÿòÜÔÿ¹µ·ÿ?PVÿ$$ÿwxyÿº­¨ÿ]SVÿÿÿ�ŠˆÿE95ÿ#"ÿ¥™”ÿ‚yyÿ/19ÿ24<ÿ-5Eÿ:EVÿ#ÿ%8ÿjdžÿQN�ÿ88qÿJÿ-ÿ/)?ÿ$ÿ"ÿÿÿ!!$ÿ¨¨«ÿ+.3ÿ,.3ÿ69>ÿ,.5ÿ#(.ÿ!&ÿ%'*ÿ313ÿÀ¶¬ÿ²Ÿ—ÿÞÆÃÿ“�wÿ…tnÿ­›Ÿÿljlÿ‚{uÿä×ÖÿãÎÌÿ°ŸŸÿ»²²ÿ'%(ÿ/*.ÿ410ÿ &(ÿ_ffÿ,4>ÿ27Iÿ00;ÿÓËÕÿÕÉâÿGKMÿ'3<ÿ-ÿ00=ÿ*ÿ&ÿ$'ÿÿÿ.'/ÿäÕÙÿG@Jÿ==Lÿ66CÿOJPÿ*'ÿ)!ÿ-#ÿ/#$ÿÿ" ÿ"ÿ*"%ÿ' ÿ)""ÿ+$$ÿ)""ÿ4*&ÿef`ÿàÓÒÿ�oqÿ% ÿ% ÿ,%%ÿ*$"ÿ+'%ÿ__bÿY^cÿÿȼ¸ÿ%ÿ# &ÿ" ÿÿÿhcgÿ(ÿ¯ šÿÁ¿·ÿĸ³ÿÀ²¯ÿ543ÿ#!ÿÿ7:EÿMPJÿÉÃÇÿä×âÿæ×Øÿe_Uÿh`\ÿãÔØÿòßßÿóÝÛÿżÃÿ<AMÿ%$+ÿ>64ÿYSQÿlggÿ!ÿqgcÿ+ ÿ%#ÿ$ÿ“‡ˆÿ107ÿAL]ÿ9=Lÿ<HMÿ 'ÿfc˜ÿ96fÿ,ÿ ÿÿÿ3ÿWW€ÿRRyÿÿ% ÿ.4<ÿCACÿÛÒÒÿ*)0ÿ.-4ÿ68@ÿ+.9ÿ&*2ÿ!$)ÿ+),ÿ:57ÿ¿°ªÿÖýÿíØÖÿž‹ƒÿ…€tÿØÀÏÿ@NWÿ.#ÿvv…ÿÖÇÇÿ803ÿolrÿ54;ÿ502ÿ»³¯ÿ�—�ÿADEÿZ]hÿ38Jÿ/+4ÿ¤�©ÿÆÁÙÿ25:ÿ (ÿÿÿÿÿ#ÿÿÿ*$,ÿÐÄÇÿSLVÿ@@OÿAANÿPKQÿ,"%ÿ+"ÿLA@ÿ7,+ÿXMLÿ—��ÿ4--ÿ$!ÿ&ÿ+$$ÿ+$$ÿ(!!ÿ2($ÿ‰Š„ÿáÔÓÿ‹y{ÿ#ÿ% ÿ+$$ÿ-'%ÿ-)'ÿ``cÿSX]ÿ'"$ÿ›‘�ÿ$ÿÿ#"ÿ˜Œ‡ÿ¦›šÿWPPÿ, ÿ¾²®ÿ�ƒ�ÿ¯¥¨ÿÚÏÔÿ202ÿ%!#ÿ#ÿ69Dÿ>?9ÿÉ¿»ÿâÓÔÿãÖÑÿQOGÿ<86ÿÌÁÆÿçØÜÿõßÝÿÌÃÊÿ8=Iÿ!ÿ2*(ÿ71/ÿB==ÿÿ!ÿ%ÿ ÿ #ÿzrpÿ<>EÿGWgÿ;ESÿ9BBÿ2ÿiV„ÿ ÿÿÿÿÿÿ -ÿ1+Aÿÿ%ÿ?CKÿIGIÿÖÑÑÿ %ÿ.-3ÿ13:ÿ.2:ÿ05;ÿ%(-ÿ0.1ÿ!ÿ‹{rÿÁ­¥ÿéÔÐÿ˜…{ÿqmeÿ˶Ìÿ)7ÿ&(ÿ%5ÿÇ¿½ÿ-(*ÿD?Eÿ-)1ÿ811ÿŸ•‹ÿ…„}ÿ�Š‰ÿffoÿ*->ÿEAIÿĽÇÿÚÃàÿ%#ÿÿ!ÿ!!ÿ$ÿ"(0ÿ-0;ÿ%$*ÿ.-4ÿUQYÿÖÌÏÿB;Eÿ;;JÿSS`ÿSNTÿ0(&ÿ!ÿ, !ÿNE?ÿ¿³¬ÿÜÏÊÿF><ÿ("&ÿ#ÿ)""ÿ%ÿ)""ÿ3)%ÿ‰Š„ÿÞÑÐÿ Ž�ÿ( #ÿ'"ÿ(!!ÿ,&$ÿ0,*ÿ__bÿ]bgÿ% "ÿ°¢™ÿeXSÿ¦žœÿ¦œ˜ÿ÷°ÿž–”ÿ(#%ÿ*"%ÿWHHÿ”’�ÿÞÒÕÿâÓØÿ/.-ÿ$ "ÿ"&ÿ7:Eÿ=@Aÿ¼´²ÿÚËËÿâÞÜÿUZTÿ535ÿ`Y`ÿ£˜�ÿí×ØÿÎÅÌÿ<AMÿ"ÿbZXÿUOMÿÿ#!ÿ!!ÿÿÿÿXMLÿHIPÿFSdÿAHVÿ'0ÿ=+-ÿ«’�ÿvZWÿZ=<ÿ˜unÿ…aWÿ„b_ÿ+ÿ–�ÿ§‘“ÿÿ7)&ÿBDLÿIJKÿÕÒÑÿ!ÿ,-.ÿ?BGÿ05;ÿ,17ÿ$',ÿÿÿˆvlÿÁ«¢ÿêÔÌÿ•€tÿwoeÿÕ½Òÿ*8ÿ,%/ÿ#0=ÿ¤ žÿ,(*ÿ<7=ÿ/(2ÿ@86ÿ ”…ÿ‚ysÿ‰}~ÿ_[cÿ&)5ÿ;:@ÿ¼·½ÿ̼Øÿ)*1ÿ&ÿ$ÿ""-ÿ%*6ÿ<DNÿ ÿ%$*ÿ+*0ÿ96<ÿÿ=9Bÿ;;JÿJJYÿSPVÿ+#!ÿ8,-ÿ*!ÿ+$ÿ—‹‚ÿØÌÅÿYNMÿ*&(ÿ ÿ*##ÿ*##ÿ(!!ÿ0&"ÿ‰Š„ÿÞÑÐÿ¤’”ÿ( #ÿ'"ÿ*##ÿ+%#ÿ/)'ÿmnoÿ`ejÿ&!#ÿ¤‘…ÿÀ­¥ÿÇ»´ÿŹ°ÿÈ»¶ÿª££ÿ(%+ÿ%#&ÿF85ÿ·°ªÿßÐÐÿêÛÜÿ410ÿ$ "ÿ"ÿ7:EÿFNRÿf^aÿÓÇÊÿ{y{ÿz}~ÿu{}ÿhekÿ®£¨ÿóáÞÿØÍÔÿINZÿ!ÿ(" ÿ&ÿ&!!ÿ!ÿÿ !ÿ!!ÿÿF77ÿA;CÿGO_ÿV[gÿLNUÿ - ÿ+ÿ2!'ÿ -ÿ!ÿ'ÿ -ÿ!"ÿ ÿ&'ÿ "ÿ–Š‹ÿDBKÿGHIÿÑÐÏÿ,.1ÿLNLÿÿ %*ÿ<AGÿ).3ÿHCGÿÞÖÙÿ‰xkÿÁ«¢ÿéÓËÿ˜„vÿtiÿ×»Ïÿ.8ÿ,%,ÿ&1<ÿ‘��ÿ)&%ÿ604ÿ)#+ÿG?;ÿ›‹{ÿ‘†ÿ‘ƒ„ÿIDJÿ"%0ÿ##&ÿ®¬®ÿÝÎæÿ'+3ÿ;IXÿ'+3ÿ663ÿB@=ÿ?;9ÿÿ,-'ÿ-3/ÿYa]ÿÕÒÑÿ89@ÿ-0<ÿ:7Dÿidhÿ,"%ÿ.$'ÿ&ÿ&" ÿ=<5ÿ×ËÇÿl[[ÿ&ÿ!ÿ' ÿ/&&ÿ-!"ÿ5('ÿŽŽ‹ÿÞÑÐÿ³¢¢ÿ)$$ÿ$ÿ(##ÿ*%%ÿ80.ÿegeÿbiiÿ"!ÿ™Œ�ÿò²ÿƒ|vÿigbÿåÖÚÿ­¡¢ÿ)&%ÿ% ÿ83-ÿ½´®ÿÔÈÄÿäÜÚÿ854ÿ$ "ÿ $ÿ25@ÿ>EEÿ³³ÿÌ¿¾ÿïäãÿqjvÿGS\ÿ^]cÿ¹«¬ÿéÚÔÿåÐÕÿEERÿ!ÿ$!ÿ&"$ÿ#!ÿ ÿ ÿ!ÿ" ÿÿ5'(ÿKFLÿU`kÿQ[eÿGM]ÿ((7ÿ`]oÿrn”ÿ#"9ÿÿ - -ÿ - ÿ:ÿ,'Qÿ94Vÿ!(ÿ§¥¢ÿYU^ÿBEFÿÖÓÒÿ+-0ÿ8:8ÿ574ÿ25:ÿ01<ÿ(04ÿƺ»ÿçØÝÿ•vÿÉ°«ÿåÌËÿž†wÿ{qgÿ×ÀÓÿ 3?ÿ!#ÿ/5?ÿbfhÿ%'%ÿ1,.ÿ! 'ÿNFDÿˆylÿˆ}vÿ‘‚ƒÿKDKÿ#%,ÿ558ÿ¡œœÿÄÃÐÿÿ#ÿÿ%ÿ>C7ÿ9B5ÿ-:-ÿ#.ÿ"B-ÿi�€ÿÆÅÄÿIDJÿ@>Gÿ5/7ÿ@99ÿ."#ÿ%ÿ+$$ÿ%!ÿ $ÿÈþÿƒppÿ2$%ÿ$ÿ' ÿ3**ÿ-!"ÿ0#"ÿ‡‡„ÿÚÍÌÿ¿®®ÿ)$$ÿ$ÿ-((ÿ0++ÿ6.,ÿegeÿ_ffÿ#"ÿvlaÿj]\ÿŒŠƒÿŒ�‰ÿçØÜÿ°¤¥ÿ/,+ÿ&!!ÿ+*#ÿ­¦ ÿȺ·ÿëàßÿ1.-ÿ#!ÿÿ03>ÿ<CCÿ¿®®ÿ¿°°ÿòåäÿnhvÿIVaÿVW^ÿ²¦©ÿáÕÎÿçÒ×ÿ??Lÿ ")ÿ% "ÿ#!ÿ#!ÿ ÿ ÿ!ÿ" ÿÿ+#!ÿIKNÿFR[ÿZelÿDOZÿ9CNÿ*1?ÿ21Nÿ0'cÿ4*oÿ?6|ÿ[QšÿIÿe_‹ÿA=]ÿ9AKÿ•”“ÿXT]ÿLOPÿÙÖÕÿ027ÿ012ÿIKIÿ029ÿ12=ÿ'/3ÿ÷¸ÿäÕÚÿ~qlÿÀ«©ÿÜÉÉÿ†rnÿwngÿÔ½Ðÿ'3ÿ%'ÿ7@Nÿ9?Gÿ!#&ÿ0,4ÿ!$/ÿLHJÿxjaÿvkdÿ’��ÿF=Dÿ#$+ÿ><?ÿ¶«ªÿ¿ÄÊÿ>H7ÿ6B3ÿ/@0ÿLcPÿ9TCÿ )ÿ>_Mÿ3N=ÿ<ZJÿ˜­¡ÿÙÑÍÿKGOÿ45@ÿ-*6ÿC>@ÿ&ÿ%ÿ' ÿ'#!ÿNOHÿÑÇÃÿœ‰‰ÿ&ÿ"ÿ' ÿ,##ÿ."#ÿ2%$ÿ{{xÿ×ÊÉÿÈ··ÿ(##ÿ% ÿ'""ÿ)$$ÿ.&$ÿ=?=ÿ]ddÿÿ{peÿhYYÿ²«¥ÿ›™”ÿäÕÙÿ·«¬ÿ30/ÿ'""ÿ!"ÿ®©£ÿ­ŸœÿåØ×ÿ3..ÿ%!#ÿ$ (ÿ9<Gÿ9>>ÿÀ­­ÿ§––ÿîßßÿc]kÿ8IVÿCGOÿ« ¥ÿáÔÏÿæÑÖÿ==Jÿ ")ÿ(#%ÿ&"$ÿ%!#ÿ" ÿ" ÿ" ÿ" ÿ" ÿ#ÿQPOÿ<ELÿˆŠ‘ÿ‹‰‹ÿIOQÿ;GLÿ@HRÿxzÿFGNÿ(.8ÿ%3ÿLUUÿyz{ÿÇÁÉÿ9>Jÿ‹‰‹ÿOKTÿBEFÿÉÆÅÿ/07ÿ)),ÿ˜™šÿ<>Fÿ78Cÿ/7;ÿ¾²³ÿâÓØÿwrlÿɾ·ÿßÒÍÿ™�‹ÿš•�ÿÞÇÚÿ5HTÿ& (ÿ:BLÿ.38ÿhijÿB=Aÿ54;ÿRLJÿµ©¢ÿ]XXÿ�„‡ÿ:5;ÿ!(.ÿCEHÿ©¤¤ÿÆÈÏÿ.E2ÿLoWÿu�zÿ(?,ÿ ,+ÿ1:3ÿ7D9ÿ(4=ÿ?BTÿÊÂÅÿçØÒÿ;;Dÿ<@OÿKIYÿFBJÿ.$'ÿ-#&ÿ'ÿ0*(ÿc\VÿÞÐÍÿ©˜˜ÿ&#"ÿ!ÿ' ÿ.%%ÿ."#ÿ1$#ÿDE?ÿ×ÈÈÿÌ»»ÿ(##ÿ% ÿ$ÿ&!!ÿ.''ÿ+)+ÿ:??ÿÿo_Vÿolÿ‘ˆ‚ÿ¤ŸšÿèÙÚÿº®¯ÿ-*)ÿ#ÿ$%ÿ¯©¡ÿ“‡ƒÿâÕÔÿ>99ÿ#!ÿ# &ÿDGRÿDHJÿ¼¬©ÿ“‚‚ÿçØØÿƒ}‹ÿ7HVÿ_bmÿœ”˜ÿÚÎÉÿæÔÖÿ67Bÿ.07ÿ($&ÿ'#%ÿ" ÿ#!ÿ" ÿ" ÿ!ÿ#!ÿ(ÿGCEÿQPVÿÀ¹ÀÿêÙãÿ]Vgÿ=BTÿBI[ÿ}v€ÿµ©²ÿçÝìÿTReÿaapÿŒ‚‹ÿàÓØÿ<?DÿŽ�ŽÿPNWÿBEFÿÎËÊÿ()0ÿ+*0ÿ‰ˆŽÿ34?ÿ.08ÿ.6:ÿĸ¹ÿæÖÚÿÑÁ¸ÿÓ¹¬ÿ×·¯ÿÌ°¬ÿ™�†ÿÙÄ×ÿ#1@ÿ%!)ÿ&+1ÿxxuÿ�˜’ÿ�‹‹ÿ€{{ÿˆ�{ÿg`Zÿ\]dÿ•�”ÿ(*-ÿ7CGÿ;DDÿfkkÿÞÛÏÿ-*)ÿ0.7ÿ8>:ÿ~‹ÿfCŠÿ£{¯ÿE,KÿªŠ½ÿ{X˜ÿÓÂÌÿìÚÐÿJFOÿ>>KÿSR_ÿ=<Cÿ+#!ÿ/#$ÿ0$%ÿ>40ÿrf_ÿ×ÈÃÿ¬��ÿ+#&ÿ ÿ'"ÿ3**ÿ/$#ÿ1% ÿ‰‡€ÿÝËÈÿÒÁÁÿ&!!ÿ$ÿ(##ÿ+&&ÿ(#'ÿ)$(ÿ&!%ÿÿsc`ÿŒ€{ÿzwrÿ§¡ŸÿáÓÐÿÊ¿¾ÿ/,+ÿ% "ÿ,(&ÿĶ§ÿumiÿçÞÞÿ:55ÿ'#%ÿ$"%ÿRU`ÿDGSÿº«¥ÿugdÿéÛÜÿ•‰’ÿ@JXÿ\_jÿ£›žÿŸ˜˜ÿèÛÖÿCCNÿ.1<ÿ*&(ÿ&"$ÿ#!ÿ$ "ÿ" ÿ" ÿ ÿ" ÿÿ).4ÿÊÅËÿ¼´¸ÿÜÓÓÿQUdÿ!)3ÿ@GSÿlnuÿ—ŽŽÿÜÍÒÿNQ]ÿlnuÿwmpÿÝÎÓÿDGRÿ†‹‹ÿa_hÿ>ABÿÆÁÁÿ'&-ÿ+*1ÿ“‘šÿ78Cÿ7:?ÿ&,6ÿ¸«ªÿ͹»ÿ·¢–ÿĨšÿ»ž’ÿÁ¥—ÿ›ŠzÿÔÈ×ÿ..Aÿ!#+ÿ957ÿ�|vÿÚ÷ÿA56ÿ'#%ÿ`^Yÿ„…ÿˆˆ‹ÿ”�“ÿpqrÿJSSÿUZZÿ‡‰Œÿè»ßÿˆN ÿ¦dÑÿÇœÒÿ\HQÿ53ÿG0;ÿ5.(ÿ‰}yÿš‰”ÿÔÈÄÿíÚÔÿSOWÿ77DÿTS`ÿ[Zaÿ*" ÿ+ ÿ/#$ÿ=3/ÿƒwpÿÔÅÀÿĵµÿ+#&ÿ ÿ)!$ÿ4++ÿ1&%ÿ<0+ÿŠˆ�ÿÜÊÇÿÔÃÃÿ.))ÿ&!!ÿ#ÿ*%%ÿ'"&ÿÿ! ÿÿTDAÿ–Š…ÿc`[ÿ©£¡ÿÛÍÊÿÕÊÉÿ1.-ÿ(#%ÿ-)'ÿÅ·¨ÿ^VRÿäÛÛÿ<77ÿ'#%ÿÿ@CNÿ;>Jÿ°¡›ÿ_QNÿäÖ×ÿ­¡ªÿBMXÿSW_ÿ^WWÿ�zzÿä×ÒÿOOZÿ-0;ÿ$ "ÿ%!#ÿ#!ÿ$ "ÿ" ÿ#!ÿ&"$ÿ!ÿ+#!ÿ31,ÿ]NNÿ¨žšÿ×ÏÍÿOSbÿ+3=ÿ@GSÿ\^eÿ�††ÿæ×ÜÿILXÿRT[ÿcY\ÿÚËÐÿ:=Hÿ~ƒƒÿa_hÿILMÿÞÙÙÿ/.5ÿ/.5ÿ”’›ÿ<=Hÿ=@Eÿ.4>ÿ¶©¨ÿÀ¬®ÿª‘Šÿ¢ˆ}ÿª”Œÿ¹Ÿ”ÿŽrÿÊÃÏÿ03>ÿ#&'ÿ�€ÿ“�}ÿÞËÅÿJ<=ÿÿ!"ÿ\^[ÿkomÿtqpÿ~}ÿw|zÿgkiÿ]`aÿæÅÖÿnHiÿܵØÿûâÝÿUHMÿ)",ÿ)&2ÿ55@ÿzsgÿ•�}ÿË¿ºÿäÐÌÿGDJÿ33@ÿ87DÿVU\ÿ)!ÿ2&'ÿ3'(ÿ4*&ÿ‘…~ÿÙÊÅÿŶ¶ÿ+#&ÿ"ÿ% ÿ.%%ÿ+ ÿ6*%ÿ‚€yÿÒÀ½ÿÒÁÁÿ)$$ÿ% ÿ&!!ÿ"ÿÿÿÿÿE52ÿ§›–ÿNKFÿ¦ žÿÝÏÌÿ×ÌËÿ0-,ÿ&!#ÿ2.,ÿĶ§ÿUMIÿâÙÙÿ:55ÿ&"$ÿÿ#&1ÿBEQÿ¦—‘ÿRDAÿáÓÔÿ·¬³ÿ<HQÿV[aÿ™“‘ÿ�‰‰ÿéÜ×ÿFFQÿ8;Fÿ'#%ÿ'#%ÿ%!#ÿ&"$ÿ-)+ÿ®ª¬ÿ#!ÿ($&ÿm`Uÿƒ{kÿž‡{ÿpcXÿÚÒÐÿSWfÿ-5?ÿELXÿZ\cÿ}ttÿéÚßÿEHTÿOQXÿ`VYÿÞÏÔÿDGRÿŽ““ÿtr{ÿEHIÿÉÄÄÿ43:ÿ,+2ÿš˜¡ÿ34?ÿ8;@ÿ$*4ÿ«ž�ÿ®šœÿŽ}wÿpd]ÿB;5ÿ’„{ÿ{h`ÿË¿ÈÿA?Aÿ83.ÿf[Zÿ><9ÿ*,*ÿ646ÿ #ÿ678ÿtxvÿjmrÿ™–•ÿhfcÿpuqÿTVSÿTUOÿèÛÖÿ[QGÿä×ÒÿâÎ×ÿ^RSÿ41%ÿ,(&ÿD;BÿzneÿŽ…wÿɼ»ÿÝÉÅÿA?Aÿ11>ÿDDQÿHGNÿ0*(ÿ*ÿ3'(ÿ7.(ÿ˜�†ÿØÉÄÿÓÂÂÿ*"%ÿ# ÿ&!ÿ-$$ÿ.&$ÿ6-'ÿnicÿÚÈÅÿϾ¾ÿ+&&ÿ% ÿ$ÿ(##ÿÿÿÿÿ0&"ÿ²¥ ÿCA:ÿº°¬ÿÓÇÃÿÜÑÐÿ4//ÿ'"$ÿ842ÿ¿³¤ÿI?;ÿåÙÚÿB=?ÿ&"$ÿ ÿ#&1ÿBCNÿ¨œ—ÿ4($ÿÞÑÐÿƹ¾ÿ<HQÿV]cÿ•�‹ÿ›””ÿëÞÙÿPP[ÿ=@Kÿ&!#ÿ'#%ÿ)%'ÿVRTÿgbdÿSOQÿ#"ÿ+')ÿ*&$ÿGGDÿgX\ÿ„�‡ÿØÐÓÿX`jÿMV]ÿHO[ÿUZ`ÿtkkÿæÙÞÿCFRÿT[aÿF>AÿÛÏÒÿ@FPÿpstÿihoÿGJKÿžšœÿ46;ÿ-,2ÿ¦¢«ÿ69Dÿ/27ÿ.4>ÿŸ’‘ÿ±Ÿ¡ÿk_Zÿ\WQÿhicÿnjbÿ}kgÿò¸ÿÖÌÈÿÑ¿¼ÿva_ÿª¡¡ÿ$#)ÿ?7;ÿ&$!ÿ‹ŽˆÿgljÿQU]ÿqpoÿ~|wÿWYVÿPQKÿSQIÿãÓÊÿgXSÿáÒÒÿåÐËÿl`aÿ1*1ÿ93;ÿ<8Aÿ‹‚{ÿ~unÿ¾²­ÿàÌÄÿMFMÿ;=LÿIKZÿ:6?ÿ0(+ÿ,%%ÿ/*%ÿ/*$ÿ�‹ƒÿÍÁºÿÒÀ½ÿ.%%ÿ$ÿ)""ÿ*##ÿ(!!ÿ'$ÿd[Uÿ³®ÿÌÀ»ÿ-%#ÿ&ÿ$ÿ*##ÿ##ÿ#ÿ !ÿ(!+ÿ$ ÿ½¦¡ÿ{{pÿÀ«§ÿÆÁ¼ÿÛÓÑÿ4--ÿ$!ÿ=53ÿª¤”ÿUIEÿçØÙÿJDHÿ)#'ÿ" ÿ 'ÿ-/4ÿˆ…„ÿ@:2ÿâÔÑÿɸÀÿKTbÿDIUÿ•��ÿ£œœÿæÔÐÿ\Uaÿ:;Fÿ-'+ÿ0*.ÿª¥§ÿ;66ÿ‡{|ÿ›’™ÿ!%ÿ" ÿ#ÿ+-*ÿ7..ÿ ÿÐÅÊÿWaeÿKW^ÿIP\ÿS[_ÿmhhÿÞÓØÿ@COÿ?KTÿ424ÿÍÆÆÿ<AMÿJGFÿ`abÿCHMÿPKOÿ-13ÿ--0ÿª¤¬ÿAEMÿ;@Eÿ)1;ÿZRPÿÐÄÅÿŠ�Žÿ‚ÿŸ�¦ÿV]cÿ.7>ÿ;=Bÿ.''ÿ1((ÿ´§¢ÿ*%'ÿ )ÿLGIÿ‡„yÿ¥¤™ÿglhÿltxÿcv~ÿ†ˆ�ÿ‚‚ÿGEBÿZUPÿØȾÿqb\ÿÝÏÌÿæÒÊÿwjiÿ5-1ÿ?8?ÿC=Eÿg`Zÿngaÿ¬¢žÿÞËÅÿmfnÿCDUÿVWhÿGBNÿ-%(ÿ-&&ÿ+&!ÿ61+ÿlh`ÿɽ¶ÿÔ¿ÿ+""ÿ$ÿ&ÿ-&&ÿ*##ÿ-'%ÿJB>ÿ* ÿË¿»ÿ+""ÿ$ÿ"ÿ+$$ÿ%ÿ#ÿ""ÿ.&)ÿ !ÿβ®ÿsrgÿé¦ÿ¸³®ÿÝÕÓÿ6//ÿ# ÿ?75ÿ•�ÿpd`ÿÚËÌÿe_cÿ)#'ÿ#!ÿ 'ÿ=?DÿEBAÿµ¯§ÿØÊÇÿÑÀÈÿAJXÿTYeÿ�Šˆÿ ™™ÿãÑÍÿwp|ÿFGRÿ(#%ÿ*%'ÿ¬¥¥ÿ”ŒŠÿ‹~}ÿœ‘–ÿ% &ÿ*"%ÿtsÿZ\ZÿĽ½ÿ¶³²ÿ¼®¶ÿMU_ÿBLZÿIN`ÿGNTÿqllÿâ×ÜÿLO[ÿ9ENÿ„‚„ÿÚÓÓÿ9>Jÿ=>?ÿWY\ÿ=?Fÿ('-ÿÿ$$'ÿ»µ½ÿBFNÿAFKÿ19Cÿ‘‰‡ÿßÓÔÿWiwÿ7Mcÿ'<Uÿ0E]ÿH\pÿ!/ÿ"ÿ&%$ÿPEJÿ0'.ÿÿ¥Ÿ—ÿ°¥žÿŽ‡�ÿmomÿnvzÿVhŒÿHQbÿPZKÿLLIÿSNNÿ×È»ÿzlcÿÙÍÆÿåÒÈÿ€roÿ*!!ÿA9=ÿIBIÿjc]ÿgb]ÿOGEÿÓÄ¿ÿa\`ÿ9<GÿcfrÿC@Fÿ.''ÿ+$$ÿ.)$ÿ(#ÿsogÿ½±ªÿÖÄÁÿ+""ÿ!ÿ#ÿ*##ÿ+$$ÿ3**ÿ!ÿ$ÿÌÀÁÿ-$$ÿ%ÿ' ÿ(!!ÿ(ÿ"!ÿ#ÿ)%-ÿÿÊ­©ÿspeÿÌ°­ÿ°¨¤ÿß×Õÿ6//ÿ$!ÿ0(&ÿxrbÿ„xtÿÞÏÐÿlfjÿ("&ÿ& $ÿ$ÿ>@Eÿ<98ÿµ¯§ÿáÓÐÿÕÄÌÿLUcÿDIUÿ„~|ÿŠƒƒÿÖÄÀÿŠƒ�ÿGHSÿ,(*ÿ/((ÿ¯¤£ÿ«�šÿ‡wtÿ¢–—ÿ/)-ÿ+#!ÿª’•ÿQILÿË¿Àÿ¿°°ÿ¸§­ÿXagÿKW`ÿ?FTÿGOSÿRMMÿÜÑÖÿSVbÿCOXÿ„‚„ÿÔÍÍÿ=BNÿ#%ÿ/16ÿOOXÿ&'.ÿ:@Bÿ((+ÿ¾¸ÀÿJNVÿ27<ÿ19Cÿ}usÿÙÍÎÿ4CPÿ';OÿATlÿ1?Vÿabsÿ#&ÿ.%%ÿ(!!ÿ`X\ÿ2*.ÿʾÿ¢—�ÿŠˆƒÿOSQÿ=BBÿs{}ÿ:KYÿa`fÿY\PÿPNGÿc[QÿÒÆ·ÿi]Tÿ×ÈÂÿâÏÅÿ…wtÿ,##ÿ3+.ÿE?Cÿhc^ÿ1-+ÿ%ÿÖÉÄÿ†ƒ‚ÿZ`bÿ�—›ÿbcdÿ+&&ÿ.''ÿ-%!ÿ+&!ÿa]Uÿ£—�ÿÔ¿ÿ) ÿ"ÿ$ÿ+$$ÿ/((ÿ.%%ÿ"ÿOMHÿËÀ¿ÿ-$$ÿ#ÿ+$$ÿ-&&ÿ!ÿUXcÿ $Qÿ70_ÿÿÇ«§ÿrj`ÿÇ­ªÿ”�ŠÿÜÑÐÿ8//ÿ$!ÿ*" ÿ]VHÿvjeÿÛÌÍÿ…}€ÿ("&ÿ ÿ"ÿ>?Fÿ987ÿµ¯§ÿÓÆÁÿØÇÍÿCMXÿEKUÿ~vtÿYTTÿȹ´ÿ‰ƒ‹ÿOR]ÿ%#%ÿ,''ÿ©�™ÿ³¤Ÿÿš‹†ÿ«�žÿ$ÿ-&&ÿ1&+ÿBIIÿž¢ ÿ­«¦ÿbZXÿLXWÿEQVÿAHTÿLTXÿB?>ÿåÙÜÿFIUÿBLVÿkikÿÊÃÃÿ8=Iÿ*17ÿÿHHQÿIKRÿAGIÿ**-ÿ·±¹ÿ<@Hÿ,16ÿ06>ÿ{usÿÚÎÏÿ#%*ÿ!'ÿSVbÿ)$0ÿ"!ÿ" ÿ$"ÿ"'%ÿZYXÿmecÿÝÑÌÿ²¨¤ÿLSSÿ2>=ÿ‰��ÿ^afÿqxlÿ’ˆ~ÿ’†�ÿ~slÿ®¢“ÿÌÇ»ÿ\QJÿ¦’ŽÿáÉÀÿ™ˆˆÿ1),ÿ85;ÿD=Eÿ&!!ÿ ÿ.,.ÿ¿¶°ÿˆƒƒÿ<BDÿfrvÿoqxÿ/**ÿ1&%ÿ+ ÿ$ ÿ[YRÿB93ÿпÿ0(&ÿ"ÿ%ÿ0))ÿ(!!ÿ*##ÿ/)!ÿ�‰{ÿɽ¸ÿ+$$ÿ"ÿ(##ÿ)$$ÿ+")ÿXb_ÿ )Xÿ<<gÿÿ½¨£ÿbRIÿ·ª¥ÿtqlÿÝÌÌÿ>55ÿ#!#ÿ( #ÿ>86ÿ;4.ÿg[\ÿ”‹‹ÿ+$$ÿÿ#ÿ<@Hÿ<:<ÿ§›–ÿǹ°ÿÛÉÍÿHPZÿIP^ÿOGKÿ"!'ÿPE>ÿ�{ÿBBOÿÿ' ÿ¦˜•ÿÑžÿªš—ÿ¶§§ÿ1((ÿ'#%ÿ6<>ÿLPRÿXTVÿ¦žœÿ5:6ÿ"++ÿHQXÿFO]ÿPQ\ÿ‡‰ŒÿãÔØÿRP`ÿ7AKÿ_`aÿ¾»ºÿ69Eÿ(+7ÿ?AIÿFHOÿEHMÿHNPÿ)),ÿ­©±ÿIIRÿ18>ÿ157ÿKIFÿËÂÂÿ% "ÿ"ÿ¹­°ÿ(#%ÿ #ÿ!ÿÿ%()ÿ³¬¦ÿØËÆÿâÖÒÿ»·µÿBGGÿpvrÿRXTÿ9>Cÿã×ÓÿïÜÔÿìÙÑÿóàØÿûçßÿÄ»µÿE;7ÿzliÿÔ¾µÿšŠ‡ÿ-&&ÿ?=@ÿ6/6ÿÿ<;:ÿ”�Žÿ±¥ ÿphlÿ''4ÿBHXÿfdtÿ% ÿ.#"ÿ-"!ÿ%!ÿ%#ÿ ÿÏÂÁÿ-&&ÿÿ"ÿ)""ÿ/((ÿ-&&ÿ0*"ÿ“Œ~ÿÌÀ»ÿ+$$ÿ"ÿ% ÿ-((ÿ+""ÿ_d^ÿ^esÿZZeÿÿ­¨ÿG90ÿ¦�—ÿa_ZÿÞÍÍÿD;;ÿ" "ÿÿ.+*ÿ2.,ÿworÿ¢™™ÿ-&&ÿ!"ÿ'ÿAGQÿGGJÿ›‘�ÿµ©¢ÿÚÈÊÿRZdÿDL`ÿ+ÿ ÿSLFÿe_gÿ)$0ÿ*"&ÿ8)-ÿ¬—•ÿÙÈÂÿ—…‚ÿyjjÿ+""ÿ'#%ÿ/27ÿNQVÿ77:ÿ†�ƒÿ ÿÿKQYÿ@GSÿGHSÿ‰‹ŽÿÛÌÐÿECSÿ7AKÿ"#$ÿ854ÿ,/;ÿ=@LÿBDLÿLNUÿKNSÿBHJÿ%%(ÿ±­µÿAAJÿ/3;ÿ69>ÿIKIÿ�‹�ÿ!ÿ/((ÿ8//ÿB==ÿHFHÿjeeÿ‘‰‡ÿ©�™ÿëÜÖÿÕÈÃÿZPLÿsmkÿhgfÿOTRÿ>FCÿNRPÿDz­ÿøÝÖÿùÞ×ÿþãÜÿýäÝÿÀ²³ÿ+#&ÿ!ÿ­š�ÿ§˜“ÿ0*(ÿA@?ÿ613ÿEKMÿDHFÿ‘ˆ‚ÿšŒ‰ÿŽƒˆÿ,*:ÿDE\ÿqm}ÿ+#&ÿ-"!ÿ0%$ÿÿÿÿÈ¿¿ÿ'"$ÿ"ÿ!ÿ' ÿ+$$ÿ.''ÿ-'ÿ‡€rÿÏþÿ(!!ÿ ÿ&!!ÿ&!!ÿ&$!ÿ\`^ÿgljÿdcbÿ"ÿ½¨£ÿ7-#ÿ�˜’ÿ=;6ÿÞÍÍÿaXXÿ#!#ÿ(#%ÿ63.ÿ€{uÿLD@ÿª¢ ÿ*##ÿ !ÿ"ÿ=DPÿ=>Eÿ�‡…ÿYMIÿàÎÒÿDLVÿ@HXÿ.)/ÿJFHÿ�xrÿ!!,ÿ52>ÿ(#%ÿ1'*ÿ¡‘ŽÿÀ±«ÿ¨–“ÿµ¦¦ÿ,##ÿ&"$ÿ79@ÿNPWÿÿNNQÿ %ÿ@CHÿLPXÿ;AKÿNPXÿjloÿÔÅÉÿ;9Iÿ)3=ÿGHIÿolkÿ%(4ÿ36Bÿ>@Hÿ\^eÿKNSÿ4:<ÿÿžš¢ÿFFOÿ,/;ÿ.07ÿ145ÿKJPÿ«¤¤ÿÛÎÍÿéØØÿëÞÝÿâÔÑÿ¿­©ÿ•„~ÿwd\ÿçÒÍÿíÛ×ÿÓËÇÿÖËÊÿÓÏÍÿ?BCÿoqoÿêÛÖÿùÞ×ÿÿäÝÿÿåÞÿÿåÞÿÿçàÿ¢‘—ÿ#ÿÿŒ{nÿ¤”‹ÿ% ÿ>;:ÿD??ÿ7AEÿDIEÿŽƒ|ÿ��~ÿ©  ÿ?<Hÿ>@UÿXR`ÿ.''ÿ-!"ÿ-"!ÿ*% ÿÿgb]ÿË¿Àÿ*%'ÿ!ÿÿ' ÿ2++ÿ,%%ÿ,( ÿ�|pÿÇ»¶ÿ)""ÿ!ÿ#ÿ.))ÿ((%ÿ`beÿekgÿddgÿ"ÿ®¦ÿ?4-ÿƒ‚{ÿÿÚËÌÿrfgÿ)%'ÿ0($ÿRJ@ÿzqcÿZOHÿ¯¤£ÿ1,,ÿÿ,*3ÿ9CMÿ)*1ÿvvÿ& ÿÖÉÎÿJMXÿEHSÿ‡|{ÿ^XVÿ( ÿLOZÿ:<Dÿÿ+&(ÿ�’‘ÿ²§ ÿ¼ª¦ÿ½®®ÿ,##ÿ&"$ÿ56=ÿVX`ÿ ")ÿ#ÿŒ�”ÿJLSÿ@AHÿfgrÿFITÿnpsÿ¯£¤ÿECSÿ(0:ÿhjmÿ:8;ÿ%(4ÿ&)5ÿ@BJÿVX_ÿCEJÿ7=?ÿ--0ÿiemÿ?@Gÿ01<ÿ57>ÿFJLÿ/16ÿ~rnÿ ‹‰ÿѹ¶ÿub\ÿØÊÒÿXNXÿ(!+ÿ !ÿéÔÒÿáÏËÿE>8ÿNFBÿMMJÿ}|{ÿÜÏÎÿøÙÓÿÿéáÿÿæßÿÿçàÿÿæßÿýäÝÿœ„�ÿ*"ÿA;9ÿ}l^ÿ{kaÿ$#ÿA97ÿB:8ÿ/8>ÿ256ÿ‹‚{ÿylgÿ¾´°ÿ65<ÿORdÿLHXÿ+#&ÿ+!$ÿ/#$ÿ,!ÿ*$ÿxpfÿÒÇÀÿ2(+ÿ ÿ!ÿ/&&ÿ.#"ÿ.%%ÿ'#!ÿkj_ÿ¸¯©ÿ(!!ÿ!ÿ#ÿ,(&ÿ,##ÿbcdÿbkkÿadeÿ ÿº©›ÿ%ÿwxyÿÿĽ½ÿ”†‡ÿ( ÿ&ÿ[QGÿe\Nÿb^Vÿ¹¬«ÿ+*)ÿ&&ÿÿ8AHÿ'&-ÿ0*.ÿ&(&ÿ{sqÿ?;Dÿ5;KÿTU\ÿOQTÿEKSÿLR\ÿ:9@ÿÿ+#&ÿ±§£ÿ¨�–ÿ¸¤œÿ·§¤ÿ-"'ÿ%#ÿ0/5ÿNOVÿ$&.ÿlozÿ]^iÿV_eÿUQYÿ75Eÿ@JYÿ7<<ÿ-+&ÿ?@Kÿ'/?ÿ/6Dÿ16Bÿ-ÿ(ÿDFNÿ<>Cÿ558ÿ<?Dÿ%$*ÿ*'-ÿ?AFÿ48@ÿ68?ÿ8:?ÿ&&)ÿ –‡ÿÅ­ªÿçÐÃÿ£“ÿÓÇÈÿ>7?ÿ%'ÿ)""ÿëÓÖÿÕÃÅÿC?AÿhjmÿS]aÿµ±¯ÿøáÜÿüåàÿÿçÞÿÿåÜÿÿæÝÿÿäÝÿÿèáÿ·� ÿ1!ÿI=9ÿvaUÿmcÿ"!ÿ6.,ÿ?75ÿ$&-ÿ$"$ÿ}yqÿma\ÿ¬ œÿ2.6ÿV[mÿIIXÿ1,.ÿ(!ÿ0$%ÿ3(!ÿ.( ÿme[ÿɾ·ÿ3),ÿ ÿ!ÿ0''ÿ/$#ÿ/&&ÿ!ÿ_^SÿŽ…ÿ' ÿ# ÿÿ*&$ÿ-$$ÿYZ[ÿZccÿilmÿ#ÿ±¥žÿÿ77:ÿC@;ÿ½µ³ÿ£—˜ÿ*"%ÿ)#!ÿULEÿNG;ÿmkdÿƹ¸ÿ.-,ÿ  ÿ)%.ÿPL\ÿ..7ÿÿD?9ÿl`\ÿ839ÿIP^ÿEN\ÿAFLÿBHRÿ>EQÿ@DLÿÿ%ÿ°¤ŸÿœŒƒÿ´ ˜ÿ³£ ÿ)#ÿ$"ÿ65;ÿUW^ÿ+19ÿ^fpÿ_`kÿ]flÿYU]ÿ/-=ÿ8BLÿ9=;ÿ¨©£ÿ$+1ÿ(=ÿ&-Aÿ".ÿ"'ÿ068ÿ9<Aÿÿÿ7:?ÿ*)/ÿ"%ÿ:<Aÿ+/7ÿ24;ÿ/16ÿ77:ÿœ“‚ÿÆ­¨ÿèÐÁÿ¤“|ÿÌ¿¾ÿ;4;ÿ!(ÿ&!'ÿåÐÌÿÏÁ¾ÿZ\_ÿ9=?ÿ€yyÿñàÚÿûâÕÿÿäÙÿÿåáÿÿãßÿÿåÞÿÿåÜÿýäÝÿ¦‘�ÿ."ÿ?82ÿdQEÿvf\ÿÿ@86ÿ0(&ÿ)%-ÿ%#%ÿhh_ÿ[RLÿ¸ª§ÿ0*2ÿNQcÿFHWÿ0+-ÿ+!$ÿ4()ÿ0%ÿ("ÿ�…{ÿÆ»´ÿ.$'ÿÿÿ,##ÿ-"!ÿ,##ÿ&" ÿ:9.ÿ_VPÿ&ÿÿ(##ÿ ÿ-$$ÿSTUÿ^ggÿbefÿ #ÿª™“ÿ8+*ÿZTRÿqkcÿ´ª¦ÿ§›œÿ& $ÿ&#"ÿYRLÿC=3ÿvtoÿ˾½ÿ)('ÿ!!ÿ %ÿ9>Jÿ@BEÿ‚€xÿ˜ŽŠÿ #ÿZ\dÿHO[ÿMWeÿAEMÿCFRÿLVdÿMU_ÿ !"ÿ/)'ÿ©�–ÿ¢Œƒÿ¬–Žÿ£“�ÿ)#ÿ$"ÿ*,1ÿIPVÿKT[ÿKU_ÿPQ\ÿ\ekÿ·³»ÿA?Oÿ)/9ÿ—“›ÿ"%ÿ+5@ÿ&.>ÿ-ÿ! &ÿ…€€ÿNRPÿ5:8ÿÿ98>ÿADIÿ#ÿ528ÿ!#(ÿ(,4ÿ%'.ÿ<>Cÿ>>Aÿ™�{ÿÁ¦Ÿÿä˺ÿ™†nÿÓúÿ–ˆ‰ÿ3-1ÿ'"$ÿçÒÆÿƽ·ÿOW[ÿagiÿáÌÑÿöÞÛÿþçÛÿÿèßÿûÞÝÿÃ¥§ÿüàÜÿÿçÞÿÿæßÿ³¤žÿ&ÿ94.ÿWJ=ÿqcZÿÿ2))ÿ&ÿ(!)ÿÿKLEÿQHAÿȶ³ÿ('ÿaduÿEHTÿ833ÿ' ÿ3'*ÿ3(!ÿ+%ÿne^ÿ¿´­ÿ2))ÿ!ÿÿ+""ÿ1&%ÿ*!!ÿ'!ÿ*( ÿ?82ÿ ÿ ÿ'""ÿ%!ÿ*##ÿOPQÿ]ffÿadeÿ#"ÿ§”Šÿn]Wÿ\PGÿpf[ÿªž™ÿ³¥¦ÿ'"&ÿ$ "ÿID?ÿ2-'ÿsqnÿËÀ¿ÿ,)(ÿ#!ÿ!%ÿ#/6ÿ:<:ÿj]Xÿ# ÿDIUÿCJVÿAISÿCMXÿOR]ÿKP\ÿKUdÿLWbÿ!$%ÿ-(#ÿ§—Žÿº¥™ÿ¥�‡ÿD63ÿ' ÿ& $ÿ..1ÿ<CIÿGPWÿcgoÿ¢¢«ÿT]dÿ.+1ÿ54Aÿ5:Fÿ(ÿ97Gÿ*2Bÿ (ÿ #ÿŒˆ†ÿg[VÿŠŽ†ÿ†‹‡ÿ||ÿ79>ÿNQVÿ"ÿ*'-ÿ68=ÿ#+ÿ-28ÿ35:ÿ??Bÿ‡zgÿ¾£˜ÿÖ»ªÿƒpXÿÅ­¤ÿ¡’�ÿ1**ÿ*##ÿéÍÏÿǺÇÿ49Rÿ??TÿPD]ÿYSgÿ`\lÿkgwÿ{frÿŽv{ÿüâßÿÿèÝÿÿêáÿ£’’ÿ(ÿ80.ÿH>4ÿfZUÿÿ+#&ÿ#!ÿ+%)ÿ" ÿ>;6ÿC70ÿʵ³ÿ.&*ÿMNYÿgdpÿ1)%ÿ/#$ÿ*$ÿ+"ÿ%ÿlc\ÿ³¨¡ÿ6--ÿÿÿ-$$ÿ-"!ÿ-$$ÿ%ÿ!ÿ+*#ÿÿÿ)!$ÿ&ÿ($"ÿ?A?ÿ`iiÿcgiÿ !ÿ ��ÿ`PFÿ9-&ÿ_UKÿ�„ÿµ¨§ÿ&!ÿ&ÿ502ÿ.,.ÿa]_ÿǾ¾ÿ.%%ÿ# ÿ!"ÿ"ÿ67>ÿMQYÿ>DNÿ.2:ÿIOYÿBIUÿEN\ÿ@JUÿFP[ÿ>HSÿIS^ÿ!#(ÿ)!ÿ¨˜Žÿ¸¥›ÿjZWÿ…xwÿ"ÿ$"$ÿ(##ÿ49?ÿBHRÿ°§§ÿ¥  ÿINZÿMKMÿ8:Bÿ!+:ÿ8CTÿ(1Bÿ(ÿ)$(ÿ¡�›ÿXSGÿ§œ‘ÿ‰‰~ÿ][Xÿ×ÑÙÿ9<AÿKNSÿ!#(ÿ-/4ÿ-/4ÿ*.6ÿ+06ÿ8;@ÿ?ADÿk_Pÿ­˜†ÿº¢“ÿcRDÿ³œ�ÿ/#&ÿ !"ÿ&!#ÿìÐÓÿ»®³ÿgryÿGHOÿæØàÿéÙáÿêÚâÿæÖÞÿæÙäÿÜÌÔÿúåáÿÿèÛÿÿæÛÿ£”•ÿ#ÿ/((ÿ@70ÿ`VRÿÿ&!ÿ ÿ$"ÿÿ-+(ÿ#ÿ³­ÿ953ÿBGLÿlprÿ6.,ÿ."#ÿ1%(ÿ3*$ÿ$ÿ1(!ÿ“ˆ�ÿ900ÿ!ÿÿ*!!ÿ0%$ÿ/&&ÿ%ÿÿÿÿÿ&!ÿ(ÿ*&$ÿEGEÿcllÿ`dfÿ %ÿŠxnÿPB9ÿ+ÿE;1ÿuidÿº­¬ÿ)!$ÿ&"ÿ/(/ÿ!ÿÿQKIÿ) ÿ!ÿ !ÿ"ÿ)*1ÿ<@HÿFLVÿ-19ÿZ`jÿ?FRÿIR`ÿMWbÿCMXÿBLWÿQ[fÿ!#(ÿ*" ÿ¤–�ÿJ<3ÿ‰~}ÿÿ$!ÿ! ÿPGGÿBDIÿEKSÿg_]ÿrmmÿ=BNÿ/-/ÿ?AIÿEReÿ,6Eÿ((1ÿQHHÿ´°®ÿd[Tÿ½¬Ÿÿ£�‡ÿWXQÿhmiÿ¿½Àÿ249ÿOQVÿ!#(ÿ027ÿ+-2ÿ!#+ÿ-/6ÿ:<Aÿ669ÿd[Tÿƒsiÿ~neÿ|qjÿ. !ÿ% ÿ#!#ÿ(#%ÿðÖÓÿŸ·ÿW]_ÿ2--ÿùÝÙÿÿáÛÿÿáÛÿÿâÜÿÿæßÿÿæâÿÿêãÿÿéàÿÿåÞÿ ‘•ÿ"ÿ)$&ÿ2+%ÿWMIÿÿ% ÿÿÿÿ$%&ÿÿ½°«ÿ1/,ÿYaeÿ‚‡Œÿ803ÿ4()ÿ/$#ÿ1("ÿÿB92ÿSHAÿ+""ÿ"ÿÿ*!!ÿ*ÿ+#!ÿ%ÿÿÿÿÿ% ÿ+""ÿ+'%ÿ*,*ÿgppÿimoÿ%ÿ|lcÿZNGÿ1&%ÿD;4ÿ\PKÿµ´ÿ,$'ÿ&$ÿ#!ÿ)'$ÿ|uoÿnd`ÿ!ÿÿÿ#ÿÿ@DLÿQWaÿ"&.ÿLR\ÿ?FRÿGP^ÿ=GRÿEOZÿDNYÿIS^ÿ'%.ÿ)ÿXLEÿ„{uÿÿ'#%ÿ#"ÿ!"ÿpaaÿŽ‰�ÿAFLÿ]XSÿ£Ÿ�ÿ<AMÿ/-/ÿ:<DÿEN\ÿ*+2ÿ`ZXÿ¨�œÿ[VPÿÀ³¨ÿ¥’†ÿ�ƒzÿBJFÿS[Wÿprpÿ67>ÿNOVÿ(*/ÿ:<Aÿ,.3ÿ (ÿ !(ÿ;:@ÿ$"%ÿÿB:6ÿPEDÿ!ÿ%!#ÿ" ÿ#!ÿ&"$ÿéÔÐÿ£�›ÿltvÿRMOÿõßÝÿúáàÿûâáÿþåäÿÿéâÿÿéâÿÿêâÿÿëæÿÿëæÿ•ˆ�ÿ!ÿ! ÿ*% ÿJB@ÿÿ$ÿÿ ÿÿ($&ÿSLLÿ´§¦ÿ202ÿahnÿJOUÿ/'+ÿ3('ÿ.$ ÿ/%!ÿÿ.( ÿ?7-ÿÿ)$&ÿÿ+""ÿ1&%ÿ) ÿ( #ÿÿÿÿÿ!ÿ%ÿ*%%ÿ8:8ÿirrÿcgiÿ!ÿnbYÿaUPÿ0''ÿ;7/ÿ7.'ÿǹ¶ÿ1),ÿ% "ÿ;61ÿ‹‚{ÿiYOÿ -ÿ) ÿ*%'ÿ425ÿÿ$%,ÿIMUÿV\fÿDJTÿOT`ÿ:AMÿBKYÿSZfÿCMXÿFQ\ÿNWeÿ"'ÿ,"%ÿukgÿÿ&"$ÿ !ÿ! ÿÿš�ŒÿàØÛÿ>AFÿ`[Vÿ˜”’ÿ5;Cÿ003ÿKOWÿ%ÿ‹‰†ÿ±§£ÿcZZÿª¤œÿš‹~ÿ§˜‹ÿee\ÿ<JIÿ+74ÿOTPÿ@BGÿRUZÿ"ÿ:9?ÿ*,1ÿ#$+ÿ''0ÿCADÿ+')ÿ%!#ÿ922ÿÁ¹¼ÿ*(+ÿ!ÿ! ÿ(##ÿ)$$ÿº««ÿspoÿ]eiÿ/)-ÿöàØÿýãØÿÿèÝÿÿëàÿûäßÿÿëçÿÿêæÿÿíçÿýêäÿ�|†ÿ ÿÿÿ946ÿÿÿÿ#ÿsniÿ´«¥ÿPC>ÿRJHÿ)')ÿDLNÿCHMÿ0+-ÿ*##ÿ&ÿ)""ÿÿ# ÿ%%ÿÿ#"ÿÿ+$$ÿ,$"ÿ'"$ÿ'"&ÿÿÿÿÿ$ "ÿ$ "ÿ*"%ÿ-+-ÿhqqÿ]ddÿ!ÿVOCÿrdaÿ"!ÿ8>:ÿ#ÿÄ·²ÿ/'*ÿ# ÿ}usÿ#ÿ%ÿ"!ÿ$ÿ(!!ÿ!%ÿ!ÿ!!*ÿGHSÿNQ]ÿMScÿFN^ÿEM]ÿ:BRÿ[_nÿOYgÿGVcÿOXfÿ'&-ÿ$#ÿ ÿ$#ÿ&$&ÿÿÿÿº¶´ÿÞÑÖÿEDJÿZRNÿ—‘�ÿ99<ÿopwÿPPYÿehiÿ|ÿ€xtÿ¼«¥ÿŸ”�ÿ—Œ…ÿd\XÿGMIÿ7BCÿ*56ÿ4;;ÿƒ‰…ÿIOQÿ%$*ÿ2/5ÿ!#(ÿ'-/ÿ#$/ÿ:<9ÿäáàÿ+(.ÿ!ÿ¦›šÿ!ÿ"ÿ.+*ÿ£¡™ÿœ™”ÿÖÉÈÿ¹­©ÿá×ÓÿøæãÿûâÛÿÿçÞÿÿçÞÿÿèßÿÿêâÿÿëãÿþêâÿÿëãÿþëãÿ}lvÿÿÿÿ-(*ÿÿÿÿYPJÿ8/)ÿ4.,ÿA<>ÿE@Bÿ" #ÿAIMÿV[aÿ(#%ÿ+$$ÿ&ÿ,%%ÿÿÿÿÿÿÿ&ÿ.&$ÿ&ÿ% "ÿÿÿ% ÿ)$$ÿ&!!ÿ&!!ÿ'"ÿ&$&ÿgppÿcjjÿ!ÿNG;ÿoa^ÿÿ@EEÿÿgb\ÿ&$ÿ ÿÿ"ÿ!"ÿ!$ÿ!ÿ"ÿÿ "*ÿ9;Cÿ?EOÿJQ]ÿBKYÿ:CQÿFO]ÿV_mÿ?LYÿHUbÿIT_ÿMWaÿ76<ÿ(#'ÿ ÿ ÿ�y|ÿ)!$ÿÿÿž˜–ÿ®Ÿ¤ÿCEJÿWRMÿ‘ŠŠÿHBFÿãÕÝÿåÚáÿ‘�˜ÿ\TWÿ¼¬£ÿ¼©�ÿ}{tÿILFÿ?DBÿ9GFÿ.77ÿ9BBÿŽ••ÿ.55ÿ7=?ÿ98>ÿÿ138ÿ5;=ÿ*+6ÿPNKÿÜÕÕÿ%&-ÿÿ700ÿ'!%ÿÿ ÿgjdÿyvqÿàÐÇÿθ¯ÿüäÛÿøÞÕÿüâÙÿÿæÝÿÿçÞÿÿèßÿÿêâÿÿëãÿþêâÿþêâÿÿëãÿn]gÿ!ÿÿÿ ÿÿÿÿ$ÿ(ÿC>>ÿ=<;ÿC=Aÿ!ÿIPVÿNRZÿ604ÿ)""ÿ+$$ÿ*##ÿÿÿÿÿÿ ÿ#ÿ4,*ÿ&ÿ)""ÿ$ÿ(!!ÿ)#!ÿ)#!ÿ)#!ÿ,&$ÿ*"%ÿ.,.ÿbkkÿellÿ #ÿ;4(ÿ†xuÿÿÿ_]XÿZXQÿ#ÿÿ"!ÿ#ÿ ÿ"#ÿ ÿ)""ÿ%!)ÿ$&.ÿ.4<ÿ;CMÿ<FQÿBLWÿJT_ÿDNYÿGQ\ÿ>HVÿAHTÿ^^gÿ‘“˜ÿA?Bÿ"!ÿ)$(ÿ% $ÿOCFÿ(ÿÿÿÜÔÒÿðßåÿCEJÿec^ÿ‚€‚ÿ`Z^ÿèÖÚÿéÝÞÿØÒÚÿîàáÿ½®¡ÿŠ‚xÿMOMÿ8AAÿ8GGÿ/9=ÿEJJÿ‰‘Žÿ099ÿALMÿ?GKÿ#"(ÿŸœ¢ÿ35:ÿ,46ÿ12=ÿ]YWÿæØÙÿJAHÿ˜’�ÿ™”�ÿ�Ž�ÿ�‹ˆÿdigÿ]ddÿfe^ÿíÝÓÿöÜÑÿÿßÕÿþãØÿÿæÝÿÿæÝÿÿåÜÿÿèßÿÿëãÿüèàÿúæÞÿþêâÿÿêâÿZISÿ!ÿÿÿÿÿÿÿÿ%#ÿ<77ÿEB=ÿÿÿMS[ÿHKVÿ?9=ÿ' ÿ"ÿ(!!ÿÿÿÿÿÿÿ%ÿ2*(ÿ)!ÿ0(&ÿ*" ÿ,$"ÿ( ÿ/'#ÿ.&"ÿ*"ÿ*##ÿ#!#ÿZccÿcjjÿ%"(ÿ0)ÿ˜Š‡ÿ504ÿupjÿEB7ÿ#ÿ -ÿ"ÿ!ÿ'ÿ!ÿÿ#ÿ%ÿ%!)ÿ46>ÿ4:BÿCKUÿ=GRÿ5?Iÿ@JTÿOYcÿ8BLÿ1;Iÿ>>Mÿ«¡«ÿ¤ž¢ÿ;6:ÿ&!%ÿ! ÿÿRCGÿ2#'ÿ"ÿ -ÿ©ž�ÿãÒØÿ[]bÿ\ZUÿqvvÿa\`ÿäÒÔÿãÙÕÿèàäÿº­¨ÿˆ~pÿLQKÿ:??ÿ?GIÿ!/2ÿQV\ÿˆŒŠÿ6<8ÿCKMÿ:FJÿ:BFÿ$ÿØÕÛÿ68=ÿ.68ÿ/0;ÿ]YWÿé×Ùÿ]KMÿàÑËÿž”‰ÿ_`Yÿ]\UÿX]]ÿVbaÿongÿìßÔÿ÷ßÖÿýÝÕÿûß×ÿüâÙÿÿæÝÿþäÛÿÿçÞÿÿêâÿûçßÿþêâÿýéáÿÿèá \ No newline at end of file diff --git a/Lib/test/test.rawimg.rev b/Lib/test/test.rawimg.rev deleted file mode 100644 index 6565c8ac68..0000000000 --- a/Lib/test/test.rawimg.rev +++ /dev/null @@ -1,82 +0,0 @@ -ÿZISÿ!ÿÿÿÿÿÿÿÿ%#ÿ<77ÿEB=ÿÿÿMS[ÿHKVÿ?9=ÿ' ÿ"ÿ(!!ÿÿÿÿÿÿÿ%ÿ2*(ÿ)!ÿ0(&ÿ*" ÿ,$"ÿ( ÿ/'#ÿ.&"ÿ*"ÿ*##ÿ#!#ÿZccÿcjjÿ%"(ÿ0)ÿ˜Š‡ÿ504ÿupjÿEB7ÿ#ÿ -ÿ"ÿ!ÿ'ÿ!ÿÿ#ÿ%ÿ%!)ÿ46>ÿ4:BÿCKUÿ=GRÿ5?Iÿ@JTÿOYcÿ8BLÿ1;Iÿ>>Mÿ«¡«ÿ¤ž¢ÿ;6:ÿ&!%ÿ! ÿÿRCGÿ2#'ÿ"ÿ -ÿ©ž�ÿãÒØÿ[]bÿ\ZUÿqvvÿa\`ÿäÒÔÿãÙÕÿèàäÿº­¨ÿˆ~pÿLQKÿ:??ÿ?GIÿ!/2ÿQV\ÿˆŒŠÿ6<8ÿCKMÿ:FJÿ:BFÿ$ÿØÕÛÿ68=ÿ.68ÿ/0;ÿ]YWÿé×Ùÿ]KMÿàÑËÿž”‰ÿ_`Yÿ]\UÿX]]ÿVbaÿongÿìßÔÿ÷ßÖÿýÝÕÿûß×ÿüâÙÿÿæÝÿþäÛÿÿçÞÿÿêâÿûçßÿþêâÿýéáÿÿèáÿn]gÿ!ÿÿÿ ÿÿÿÿ$ÿ(ÿC>>ÿ=<;ÿC=Aÿ!ÿIPVÿNRZÿ604ÿ)""ÿ+$$ÿ*##ÿÿÿÿÿÿ ÿ#ÿ4,*ÿ&ÿ)""ÿ$ÿ(!!ÿ)#!ÿ)#!ÿ)#!ÿ,&$ÿ*"%ÿ.,.ÿbkkÿellÿ #ÿ;4(ÿ†xuÿÿÿ_]XÿZXQÿ#ÿÿ"!ÿ#ÿ ÿ"#ÿ ÿ)""ÿ%!)ÿ$&.ÿ.4<ÿ;CMÿ<FQÿBLWÿJT_ÿDNYÿGQ\ÿ>HVÿAHTÿ^^gÿ‘“˜ÿA?Bÿ"!ÿ)$(ÿ% $ÿOCFÿ(ÿÿÿÜÔÒÿðßåÿCEJÿec^ÿ‚€‚ÿ`Z^ÿèÖÚÿéÝÞÿØÒÚÿîàáÿ½®¡ÿŠ‚xÿMOMÿ8AAÿ8GGÿ/9=ÿEJJÿ‰‘Žÿ099ÿALMÿ?GKÿ#"(ÿŸœ¢ÿ35:ÿ,46ÿ12=ÿ]YWÿæØÙÿJAHÿ˜’�ÿ™”�ÿ�Ž�ÿ�‹ˆÿdigÿ]ddÿfe^ÿíÝÓÿöÜÑÿÿßÕÿþãØÿÿæÝÿÿæÝÿÿåÜÿÿèßÿÿëãÿüèàÿúæÞÿþêâÿÿêâÿ}lvÿÿÿÿ-(*ÿÿÿÿYPJÿ8/)ÿ4.,ÿA<>ÿE@Bÿ" #ÿAIMÿV[aÿ(#%ÿ+$$ÿ&ÿ,%%ÿÿÿÿÿÿÿ&ÿ.&$ÿ&ÿ% "ÿÿÿ% ÿ)$$ÿ&!!ÿ&!!ÿ'"ÿ&$&ÿgppÿcjjÿ!ÿNG;ÿoa^ÿÿ@EEÿÿgb\ÿ&$ÿ ÿÿ"ÿ!"ÿ!$ÿ!ÿ"ÿÿ "*ÿ9;Cÿ?EOÿJQ]ÿBKYÿ:CQÿFO]ÿV_mÿ?LYÿHUbÿIT_ÿMWaÿ76<ÿ(#'ÿ ÿ ÿ�y|ÿ)!$ÿÿÿž˜–ÿ®Ÿ¤ÿCEJÿWRMÿ‘ŠŠÿHBFÿãÕÝÿåÚáÿ‘�˜ÿ\TWÿ¼¬£ÿ¼©�ÿ}{tÿILFÿ?DBÿ9GFÿ.77ÿ9BBÿŽ••ÿ.55ÿ7=?ÿ98>ÿÿ138ÿ5;=ÿ*+6ÿPNKÿÜÕÕÿ%&-ÿÿ700ÿ'!%ÿÿ ÿgjdÿyvqÿàÐÇÿθ¯ÿüäÛÿøÞÕÿüâÙÿÿæÝÿÿçÞÿÿèßÿÿêâÿÿëãÿþêâÿþêâÿÿëãÿ�|†ÿ ÿÿÿ946ÿÿÿÿ#ÿsniÿ´«¥ÿPC>ÿRJHÿ)')ÿDLNÿCHMÿ0+-ÿ*##ÿ&ÿ)""ÿÿ# ÿ%%ÿÿ#"ÿÿ+$$ÿ,$"ÿ'"$ÿ'"&ÿÿÿÿÿ$ "ÿ$ "ÿ*"%ÿ-+-ÿhqqÿ]ddÿ!ÿVOCÿrdaÿ"!ÿ8>:ÿ#ÿÄ·²ÿ/'*ÿ# ÿ}usÿ#ÿ%ÿ"!ÿ$ÿ(!!ÿ!%ÿ!ÿ!!*ÿGHSÿNQ]ÿMScÿFN^ÿEM]ÿ:BRÿ[_nÿOYgÿGVcÿOXfÿ'&-ÿ$#ÿ ÿ$#ÿ&$&ÿÿÿÿº¶´ÿÞÑÖÿEDJÿZRNÿ—‘�ÿ99<ÿopwÿPPYÿehiÿ|ÿ€xtÿ¼«¥ÿŸ”�ÿ—Œ…ÿd\XÿGMIÿ7BCÿ*56ÿ4;;ÿƒ‰…ÿIOQÿ%$*ÿ2/5ÿ!#(ÿ'-/ÿ#$/ÿ:<9ÿäáàÿ+(.ÿ!ÿ¦›šÿ!ÿ"ÿ.+*ÿ£¡™ÿœ™”ÿÖÉÈÿ¹­©ÿá×ÓÿøæãÿûâÛÿÿçÞÿÿçÞÿÿèßÿÿêâÿÿëãÿþêâÿÿëãÿþëãÿ•ˆ�ÿ!ÿ! ÿ*% ÿJB@ÿÿ$ÿÿ ÿÿ($&ÿSLLÿ´§¦ÿ202ÿahnÿJOUÿ/'+ÿ3('ÿ.$ ÿ/%!ÿÿ.( ÿ?7-ÿÿ)$&ÿÿ+""ÿ1&%ÿ) ÿ( #ÿÿÿÿÿ!ÿ%ÿ*%%ÿ8:8ÿirrÿcgiÿ!ÿnbYÿaUPÿ0''ÿ;7/ÿ7.'ÿǹ¶ÿ1),ÿ% "ÿ;61ÿ‹‚{ÿiYOÿ -ÿ) ÿ*%'ÿ425ÿÿ$%,ÿIMUÿV\fÿDJTÿOT`ÿ:AMÿBKYÿSZfÿCMXÿFQ\ÿNWeÿ"'ÿ,"%ÿukgÿÿ&"$ÿ !ÿ! ÿÿš�ŒÿàØÛÿ>AFÿ`[Vÿ˜”’ÿ5;Cÿ003ÿKOWÿ%ÿ‹‰†ÿ±§£ÿcZZÿª¤œÿš‹~ÿ§˜‹ÿee\ÿ<JIÿ+74ÿOTPÿ@BGÿRUZÿ"ÿ:9?ÿ*,1ÿ#$+ÿ''0ÿCADÿ+')ÿ%!#ÿ922ÿÁ¹¼ÿ*(+ÿ!ÿ! ÿ(##ÿ)$$ÿº««ÿspoÿ]eiÿ/)-ÿöàØÿýãØÿÿèÝÿÿëàÿûäßÿÿëçÿÿêæÿÿíçÿýêäÿ ‘•ÿ"ÿ)$&ÿ2+%ÿWMIÿÿ% ÿÿÿÿ$%&ÿÿ½°«ÿ1/,ÿYaeÿ‚‡Œÿ803ÿ4()ÿ/$#ÿ1("ÿÿB92ÿSHAÿ+""ÿ"ÿÿ*!!ÿ*ÿ+#!ÿ%ÿÿÿÿÿ% ÿ+""ÿ+'%ÿ*,*ÿgppÿimoÿ%ÿ|lcÿZNGÿ1&%ÿD;4ÿ\PKÿµ´ÿ,$'ÿ&$ÿ#!ÿ)'$ÿ|uoÿnd`ÿ!ÿÿÿ#ÿÿ@DLÿQWaÿ"&.ÿLR\ÿ?FRÿGP^ÿ=GRÿEOZÿDNYÿIS^ÿ'%.ÿ)ÿXLEÿ„{uÿÿ'#%ÿ#"ÿ!"ÿpaaÿŽ‰�ÿAFLÿ]XSÿ£Ÿ�ÿ<AMÿ/-/ÿ:<DÿEN\ÿ*+2ÿ`ZXÿ¨�œÿ[VPÿÀ³¨ÿ¥’†ÿ�ƒzÿBJFÿS[Wÿprpÿ67>ÿNOVÿ(*/ÿ:<Aÿ,.3ÿ (ÿ !(ÿ;:@ÿ$"%ÿÿB:6ÿPEDÿ!ÿ%!#ÿ" ÿ#!ÿ&"$ÿéÔÐÿ£�›ÿltvÿRMOÿõßÝÿúáàÿûâáÿþåäÿÿéâÿÿéâÿÿêâÿÿëæÿÿëæÿ£”•ÿ#ÿ/((ÿ@70ÿ`VRÿÿ&!ÿ ÿ$"ÿÿ-+(ÿ#ÿ³­ÿ953ÿBGLÿlprÿ6.,ÿ."#ÿ1%(ÿ3*$ÿ$ÿ1(!ÿ“ˆ�ÿ900ÿ!ÿÿ*!!ÿ0%$ÿ/&&ÿ%ÿÿÿÿÿ&!ÿ(ÿ*&$ÿEGEÿcllÿ`dfÿ %ÿŠxnÿPB9ÿ+ÿE;1ÿuidÿº­¬ÿ)!$ÿ&"ÿ/(/ÿ!ÿÿQKIÿ) ÿ!ÿ !ÿ"ÿ)*1ÿ<@HÿFLVÿ-19ÿZ`jÿ?FRÿIR`ÿMWbÿCMXÿBLWÿQ[fÿ!#(ÿ*" ÿ¤–�ÿJ<3ÿ‰~}ÿÿ$!ÿ! ÿPGGÿBDIÿEKSÿg_]ÿrmmÿ=BNÿ/-/ÿ?AIÿEReÿ,6Eÿ((1ÿQHHÿ´°®ÿd[Tÿ½¬Ÿÿ£�‡ÿWXQÿhmiÿ¿½Àÿ249ÿOQVÿ!#(ÿ027ÿ+-2ÿ!#+ÿ-/6ÿ:<Aÿ669ÿd[Tÿƒsiÿ~neÿ|qjÿ. !ÿ% ÿ#!#ÿ(#%ÿðÖÓÿŸ·ÿW]_ÿ2--ÿùÝÙÿÿáÛÿÿáÛÿÿâÜÿÿæßÿÿæâÿÿêãÿÿéàÿÿåÞÿ£’’ÿ(ÿ80.ÿH>4ÿfZUÿÿ+#&ÿ#!ÿ+%)ÿ" ÿ>;6ÿC70ÿʵ³ÿ.&*ÿMNYÿgdpÿ1)%ÿ/#$ÿ*$ÿ+"ÿ%ÿlc\ÿ³¨¡ÿ6--ÿÿÿ-$$ÿ-"!ÿ-$$ÿ%ÿ!ÿ+*#ÿÿÿ)!$ÿ&ÿ($"ÿ?A?ÿ`iiÿcgiÿ !ÿ ��ÿ`PFÿ9-&ÿ_UKÿ�„ÿµ¨§ÿ&!ÿ&ÿ502ÿ.,.ÿa]_ÿǾ¾ÿ.%%ÿ# ÿ!"ÿ"ÿ67>ÿMQYÿ>DNÿ.2:ÿIOYÿBIUÿEN\ÿ@JUÿFP[ÿ>HSÿIS^ÿ!#(ÿ)!ÿ¨˜Žÿ¸¥›ÿjZWÿ…xwÿ"ÿ$"$ÿ(##ÿ49?ÿBHRÿ°§§ÿ¥  ÿINZÿMKMÿ8:Bÿ!+:ÿ8CTÿ(1Bÿ(ÿ)$(ÿ¡�›ÿXSGÿ§œ‘ÿ‰‰~ÿ][Xÿ×ÑÙÿ9<AÿKNSÿ!#(ÿ-/4ÿ-/4ÿ*.6ÿ+06ÿ8;@ÿ?ADÿk_Pÿ­˜†ÿº¢“ÿcRDÿ³œ�ÿ/#&ÿ !"ÿ&!#ÿìÐÓÿ»®³ÿgryÿGHOÿæØàÿéÙáÿêÚâÿæÖÞÿæÙäÿÜÌÔÿúåáÿÿèÛÿÿæÛÿ³¤žÿ&ÿ94.ÿWJ=ÿqcZÿÿ2))ÿ&ÿ(!)ÿÿKLEÿQHAÿȶ³ÿ('ÿaduÿEHTÿ833ÿ' ÿ3'*ÿ3(!ÿ+%ÿne^ÿ¿´­ÿ2))ÿ!ÿÿ+""ÿ1&%ÿ*!!ÿ'!ÿ*( ÿ?82ÿ ÿ ÿ'""ÿ%!ÿ*##ÿOPQÿ]ffÿadeÿ#"ÿ§”Šÿn]Wÿ\PGÿpf[ÿªž™ÿ³¥¦ÿ'"&ÿ$ "ÿID?ÿ2-'ÿsqnÿËÀ¿ÿ,)(ÿ#!ÿ!%ÿ#/6ÿ:<:ÿj]Xÿ# ÿDIUÿCJVÿAISÿCMXÿOR]ÿKP\ÿKUdÿLWbÿ!$%ÿ-(#ÿ§—Žÿº¥™ÿ¥�‡ÿD63ÿ' ÿ& $ÿ..1ÿ<CIÿGPWÿcgoÿ¢¢«ÿT]dÿ.+1ÿ54Aÿ5:Fÿ(ÿ97Gÿ*2Bÿ (ÿ #ÿŒˆ†ÿg[VÿŠŽ†ÿ†‹‡ÿ||ÿ79>ÿNQVÿ"ÿ*'-ÿ68=ÿ#+ÿ-28ÿ35:ÿ??Bÿ‡zgÿ¾£˜ÿÖ»ªÿƒpXÿÅ­¤ÿ¡’�ÿ1**ÿ*##ÿéÍÏÿǺÇÿ49Rÿ??TÿPD]ÿYSgÿ`\lÿkgwÿ{frÿŽv{ÿüâßÿÿèÝÿÿêáÿ¦‘�ÿ."ÿ?82ÿdQEÿvf\ÿÿ@86ÿ0(&ÿ)%-ÿ%#%ÿhh_ÿ[RLÿ¸ª§ÿ0*2ÿNQcÿFHWÿ0+-ÿ+!$ÿ4()ÿ0%ÿ("ÿ�…{ÿÆ»´ÿ.$'ÿÿÿ,##ÿ-"!ÿ,##ÿ&" ÿ:9.ÿ_VPÿ&ÿÿ(##ÿ ÿ-$$ÿSTUÿ^ggÿbefÿ #ÿª™“ÿ8+*ÿZTRÿqkcÿ´ª¦ÿ§›œÿ& $ÿ&#"ÿYRLÿC=3ÿvtoÿ˾½ÿ)('ÿ!!ÿ %ÿ9>Jÿ@BEÿ‚€xÿ˜ŽŠÿ #ÿZ\dÿHO[ÿMWeÿAEMÿCFRÿLVdÿMU_ÿ !"ÿ/)'ÿ©�–ÿ¢Œƒÿ¬–Žÿ£“�ÿ)#ÿ$"ÿ*,1ÿIPVÿKT[ÿKU_ÿPQ\ÿ\ekÿ·³»ÿA?Oÿ)/9ÿ—“›ÿ"%ÿ+5@ÿ&.>ÿ-ÿ! &ÿ…€€ÿNRPÿ5:8ÿÿ98>ÿADIÿ#ÿ528ÿ!#(ÿ(,4ÿ%'.ÿ<>Cÿ>>Aÿ™�{ÿÁ¦Ÿÿä˺ÿ™†nÿÓúÿ–ˆ‰ÿ3-1ÿ'"$ÿçÒÆÿƽ·ÿOW[ÿagiÿáÌÑÿöÞÛÿþçÛÿÿèßÿûÞÝÿÃ¥§ÿüàÜÿÿçÞÿÿæßÿ·� ÿ1!ÿI=9ÿvaUÿmcÿ"!ÿ6.,ÿ?75ÿ$&-ÿ$"$ÿ}yqÿma\ÿ¬ œÿ2.6ÿV[mÿIIXÿ1,.ÿ(!ÿ0$%ÿ3(!ÿ.( ÿme[ÿɾ·ÿ3),ÿ ÿ!ÿ0''ÿ/$#ÿ/&&ÿ!ÿ_^SÿŽ…ÿ' ÿ# ÿÿ*&$ÿ-$$ÿYZ[ÿZccÿilmÿ#ÿ±¥žÿÿ77:ÿC@;ÿ½µ³ÿ£—˜ÿ*"%ÿ)#!ÿULEÿNG;ÿmkdÿƹ¸ÿ.-,ÿ  ÿ)%.ÿPL\ÿ..7ÿÿD?9ÿl`\ÿ839ÿIP^ÿEN\ÿAFLÿBHRÿ>EQÿ@DLÿÿ%ÿ°¤ŸÿœŒƒÿ´ ˜ÿ³£ ÿ)#ÿ$"ÿ65;ÿUW^ÿ+19ÿ^fpÿ_`kÿ]flÿYU]ÿ/-=ÿ8BLÿ9=;ÿ¨©£ÿ$+1ÿ(=ÿ&-Aÿ".ÿ"'ÿ068ÿ9<Aÿÿÿ7:?ÿ*)/ÿ"%ÿ:<Aÿ+/7ÿ24;ÿ/16ÿ77:ÿœ“‚ÿÆ­¨ÿèÐÁÿ¤“|ÿÌ¿¾ÿ;4;ÿ!(ÿ&!'ÿåÐÌÿÏÁ¾ÿZ\_ÿ9=?ÿ€yyÿñàÚÿûâÕÿÿäÙÿÿåáÿÿãßÿÿåÞÿÿåÜÿýäÝÿœ„�ÿ*"ÿA;9ÿ}l^ÿ{kaÿ$#ÿA97ÿB:8ÿ/8>ÿ256ÿ‹‚{ÿylgÿ¾´°ÿ65<ÿORdÿLHXÿ+#&ÿ+!$ÿ/#$ÿ,!ÿ*$ÿxpfÿÒÇÀÿ2(+ÿ ÿ!ÿ/&&ÿ.#"ÿ.%%ÿ'#!ÿkj_ÿ¸¯©ÿ(!!ÿ!ÿ#ÿ,(&ÿ,##ÿbcdÿbkkÿadeÿ ÿº©›ÿ%ÿwxyÿÿĽ½ÿ”†‡ÿ( ÿ&ÿ[QGÿe\Nÿb^Vÿ¹¬«ÿ+*)ÿ&&ÿÿ8AHÿ'&-ÿ0*.ÿ&(&ÿ{sqÿ?;Dÿ5;KÿTU\ÿOQTÿEKSÿLR\ÿ:9@ÿÿ+#&ÿ±§£ÿ¨�–ÿ¸¤œÿ·§¤ÿ-"'ÿ%#ÿ0/5ÿNOVÿ$&.ÿlozÿ]^iÿV_eÿUQYÿ75Eÿ@JYÿ7<<ÿ-+&ÿ?@Kÿ'/?ÿ/6Dÿ16Bÿ-ÿ(ÿDFNÿ<>Cÿ558ÿ<?Dÿ%$*ÿ*'-ÿ?AFÿ48@ÿ68?ÿ8:?ÿ&&)ÿ –‡ÿÅ­ªÿçÐÃÿ£“ÿÓÇÈÿ>7?ÿ%'ÿ)""ÿëÓÖÿÕÃÅÿC?AÿhjmÿS]aÿµ±¯ÿøáÜÿüåàÿÿçÞÿÿåÜÿÿæÝÿÿäÝÿÿèáÿ¢‘—ÿ#ÿÿŒ{nÿ¤”‹ÿ% ÿ>;:ÿD??ÿ7AEÿDIEÿŽƒ|ÿ��~ÿ©  ÿ?<Hÿ>@UÿXR`ÿ.''ÿ-!"ÿ-"!ÿ*% ÿÿgb]ÿË¿Àÿ*%'ÿ!ÿÿ' ÿ2++ÿ,%%ÿ,( ÿ�|pÿÇ»¶ÿ)""ÿ!ÿ#ÿ.))ÿ((%ÿ`beÿekgÿddgÿ"ÿ®¦ÿ?4-ÿƒ‚{ÿÿÚËÌÿrfgÿ)%'ÿ0($ÿRJ@ÿzqcÿZOHÿ¯¤£ÿ1,,ÿÿ,*3ÿ9CMÿ)*1ÿvvÿ& ÿÖÉÎÿJMXÿEHSÿ‡|{ÿ^XVÿ( ÿLOZÿ:<Dÿÿ+&(ÿ�’‘ÿ²§ ÿ¼ª¦ÿ½®®ÿ,##ÿ&"$ÿ56=ÿVX`ÿ ")ÿ#ÿŒ�”ÿJLSÿ@AHÿfgrÿFITÿnpsÿ¯£¤ÿECSÿ(0:ÿhjmÿ:8;ÿ%(4ÿ&)5ÿ@BJÿVX_ÿCEJÿ7=?ÿ--0ÿiemÿ?@Gÿ01<ÿ57>ÿFJLÿ/16ÿ~rnÿ ‹‰ÿѹ¶ÿub\ÿØÊÒÿXNXÿ(!+ÿ !ÿéÔÒÿáÏËÿE>8ÿNFBÿMMJÿ}|{ÿÜÏÎÿøÙÓÿÿéáÿÿæßÿÿçàÿÿæßÿýäÝÿÀ²³ÿ+#&ÿ!ÿ­š�ÿ§˜“ÿ0*(ÿA@?ÿ613ÿEKMÿDHFÿ‘ˆ‚ÿšŒ‰ÿŽƒˆÿ,*:ÿDE\ÿqm}ÿ+#&ÿ-"!ÿ0%$ÿÿÿÿÈ¿¿ÿ'"$ÿ"ÿ!ÿ' ÿ+$$ÿ.''ÿ-'ÿ‡€rÿÏþÿ(!!ÿ ÿ&!!ÿ&!!ÿ&$!ÿ\`^ÿgljÿdcbÿ"ÿ½¨£ÿ7-#ÿ�˜’ÿ=;6ÿÞÍÍÿaXXÿ#!#ÿ(#%ÿ63.ÿ€{uÿLD@ÿª¢ ÿ*##ÿ !ÿ"ÿ=DPÿ=>Eÿ�‡…ÿYMIÿàÎÒÿDLVÿ@HXÿ.)/ÿJFHÿ�xrÿ!!,ÿ52>ÿ(#%ÿ1'*ÿ¡‘ŽÿÀ±«ÿ¨–“ÿµ¦¦ÿ,##ÿ&"$ÿ79@ÿNPWÿÿNNQÿ %ÿ@CHÿLPXÿ;AKÿNPXÿjloÿÔÅÉÿ;9Iÿ)3=ÿGHIÿolkÿ%(4ÿ36Bÿ>@Hÿ\^eÿKNSÿ4:<ÿÿžš¢ÿFFOÿ,/;ÿ.07ÿ145ÿKJPÿ«¤¤ÿÛÎÍÿéØØÿëÞÝÿâÔÑÿ¿­©ÿ•„~ÿwd\ÿçÒÍÿíÛ×ÿÓËÇÿÖËÊÿÓÏÍÿ?BCÿoqoÿêÛÖÿùÞ×ÿÿäÝÿÿåÞÿÿåÞÿÿçàÿÄ»µÿE;7ÿzliÿÔ¾µÿšŠ‡ÿ-&&ÿ?=@ÿ6/6ÿÿ<;:ÿ”�Žÿ±¥ ÿphlÿ''4ÿBHXÿfdtÿ% ÿ.#"ÿ-"!ÿ%!ÿ%#ÿ ÿÏÂÁÿ-&&ÿÿ"ÿ)""ÿ/((ÿ-&&ÿ0*"ÿ“Œ~ÿÌÀ»ÿ+$$ÿ"ÿ% ÿ-((ÿ+""ÿ_d^ÿ^esÿZZeÿÿ­¨ÿG90ÿ¦�—ÿa_ZÿÞÍÍÿD;;ÿ" "ÿÿ.+*ÿ2.,ÿworÿ¢™™ÿ-&&ÿ!"ÿ'ÿAGQÿGGJÿ›‘�ÿµ©¢ÿÚÈÊÿRZdÿDL`ÿ+ÿ ÿSLFÿe_gÿ)$0ÿ*"&ÿ8)-ÿ¬—•ÿÙÈÂÿ—…‚ÿyjjÿ+""ÿ'#%ÿ/27ÿNQVÿ77:ÿ†�ƒÿ ÿÿKQYÿ@GSÿGHSÿ‰‹ŽÿÛÌÐÿECSÿ7AKÿ"#$ÿ854ÿ,/;ÿ=@LÿBDLÿLNUÿKNSÿBHJÿ%%(ÿ±­µÿAAJÿ/3;ÿ69>ÿIKIÿ�‹�ÿ!ÿ/((ÿ8//ÿB==ÿHFHÿjeeÿ‘‰‡ÿ©�™ÿëÜÖÿÕÈÃÿZPLÿsmkÿhgfÿOTRÿ>FCÿNRPÿDz­ÿøÝÖÿùÞ×ÿþãÜÿýäÝÿÌÇ»ÿ\QJÿ¦’ŽÿáÉÀÿ™ˆˆÿ1),ÿ85;ÿD=Eÿ&!!ÿ ÿ.,.ÿ¿¶°ÿˆƒƒÿ<BDÿfrvÿoqxÿ/**ÿ1&%ÿ+ ÿ$ ÿ[YRÿB93ÿпÿ0(&ÿ"ÿ%ÿ0))ÿ(!!ÿ*##ÿ/)!ÿ�‰{ÿɽ¸ÿ+$$ÿ"ÿ(##ÿ)$$ÿ+")ÿXb_ÿ )Xÿ<<gÿÿ½¨£ÿbRIÿ·ª¥ÿtqlÿÝÌÌÿ>55ÿ#!#ÿ( #ÿ>86ÿ;4.ÿg[\ÿ”‹‹ÿ+$$ÿÿ#ÿ<@Hÿ<:<ÿ§›–ÿǹ°ÿÛÉÍÿHPZÿIP^ÿOGKÿ"!'ÿPE>ÿ�{ÿBBOÿÿ' ÿ¦˜•ÿÑžÿªš—ÿ¶§§ÿ1((ÿ'#%ÿ6<>ÿLPRÿXTVÿ¦žœÿ5:6ÿ"++ÿHQXÿFO]ÿPQ\ÿ‡‰ŒÿãÔØÿRP`ÿ7AKÿ_`aÿ¾»ºÿ69Eÿ(+7ÿ?AIÿFHOÿEHMÿHNPÿ)),ÿ­©±ÿIIRÿ18>ÿ157ÿKIFÿËÂÂÿ% "ÿ"ÿ¹­°ÿ(#%ÿ #ÿ!ÿÿ%()ÿ³¬¦ÿØËÆÿâÖÒÿ»·µÿBGGÿpvrÿRXTÿ9>Cÿã×ÓÿïÜÔÿìÙÑÿóàØÿûçßÿÒÆ·ÿi]Tÿ×ÈÂÿâÏÅÿ…wtÿ,##ÿ3+.ÿE?Cÿhc^ÿ1-+ÿ%ÿÖÉÄÿ†ƒ‚ÿZ`bÿ�—›ÿbcdÿ+&&ÿ.''ÿ-%!ÿ+&!ÿa]Uÿ£—�ÿÔ¿ÿ) ÿ"ÿ$ÿ+$$ÿ/((ÿ.%%ÿ"ÿOMHÿËÀ¿ÿ-$$ÿ#ÿ+$$ÿ-&&ÿ!ÿUXcÿ $Qÿ70_ÿÿÇ«§ÿrj`ÿÇ­ªÿ”�ŠÿÜÑÐÿ8//ÿ$!ÿ*" ÿ]VHÿvjeÿÛÌÍÿ…}€ÿ("&ÿ ÿ"ÿ>?Fÿ987ÿµ¯§ÿÓÆÁÿØÇÍÿCMXÿEKUÿ~vtÿYTTÿȹ´ÿ‰ƒ‹ÿOR]ÿ%#%ÿ,''ÿ©�™ÿ³¤Ÿÿš‹†ÿ«�žÿ$ÿ-&&ÿ1&+ÿBIIÿž¢ ÿ­«¦ÿbZXÿLXWÿEQVÿAHTÿLTXÿB?>ÿåÙÜÿFIUÿBLVÿkikÿÊÃÃÿ8=Iÿ*17ÿÿHHQÿIKRÿAGIÿ**-ÿ·±¹ÿ<@Hÿ,16ÿ06>ÿ{usÿÚÎÏÿ#%*ÿ!'ÿSVbÿ)$0ÿ"!ÿ" ÿ$"ÿ"'%ÿZYXÿmecÿÝÑÌÿ²¨¤ÿLSSÿ2>=ÿ‰��ÿ^afÿqxlÿ’ˆ~ÿ’†�ÿ~slÿ®¢“ÿ×È»ÿzlcÿÙÍÆÿåÒÈÿ€roÿ*!!ÿA9=ÿIBIÿjc]ÿgb]ÿOGEÿÓÄ¿ÿa\`ÿ9<GÿcfrÿC@Fÿ.''ÿ+$$ÿ.)$ÿ(#ÿsogÿ½±ªÿÖÄÁÿ+""ÿ!ÿ#ÿ*##ÿ+$$ÿ3**ÿ!ÿ$ÿÌÀÁÿ-$$ÿ%ÿ' ÿ(!!ÿ(ÿ"!ÿ#ÿ)%-ÿÿÊ­©ÿspeÿÌ°­ÿ°¨¤ÿß×Õÿ6//ÿ$!ÿ0(&ÿxrbÿ„xtÿÞÏÐÿlfjÿ("&ÿ& $ÿ$ÿ>@Eÿ<98ÿµ¯§ÿáÓÐÿÕÄÌÿLUcÿDIUÿ„~|ÿŠƒƒÿÖÄÀÿŠƒ�ÿGHSÿ,(*ÿ/((ÿ¯¤£ÿ«�šÿ‡wtÿ¢–—ÿ/)-ÿ+#!ÿª’•ÿQILÿË¿Àÿ¿°°ÿ¸§­ÿXagÿKW`ÿ?FTÿGOSÿRMMÿÜÑÖÿSVbÿCOXÿ„‚„ÿÔÍÍÿ=BNÿ#%ÿ/16ÿOOXÿ&'.ÿ:@Bÿ((+ÿ¾¸ÀÿJNVÿ27<ÿ19Cÿ}usÿÙÍÎÿ4CPÿ';OÿATlÿ1?Vÿabsÿ#&ÿ.%%ÿ(!!ÿ`X\ÿ2*.ÿʾÿ¢—�ÿŠˆƒÿOSQÿ=BBÿs{}ÿ:KYÿa`fÿY\PÿPNGÿc[QÿØȾÿqb\ÿÝÏÌÿæÒÊÿwjiÿ5-1ÿ?8?ÿC=Eÿg`Zÿngaÿ¬¢žÿÞËÅÿmfnÿCDUÿVWhÿGBNÿ-%(ÿ-&&ÿ+&!ÿ61+ÿlh`ÿɽ¶ÿÔ¿ÿ+""ÿ$ÿ&ÿ-&&ÿ*##ÿ-'%ÿJB>ÿ* ÿË¿»ÿ+""ÿ$ÿ"ÿ+$$ÿ%ÿ#ÿ""ÿ.&)ÿ !ÿβ®ÿsrgÿé¦ÿ¸³®ÿÝÕÓÿ6//ÿ# ÿ?75ÿ•�ÿpd`ÿÚËÌÿe_cÿ)#'ÿ#!ÿ 'ÿ=?DÿEBAÿµ¯§ÿØÊÇÿÑÀÈÿAJXÿTYeÿ�Šˆÿ ™™ÿãÑÍÿwp|ÿFGRÿ(#%ÿ*%'ÿ¬¥¥ÿ”ŒŠÿ‹~}ÿœ‘–ÿ% &ÿ*"%ÿtsÿZ\ZÿĽ½ÿ¶³²ÿ¼®¶ÿMU_ÿBLZÿIN`ÿGNTÿqllÿâ×ÜÿLO[ÿ9ENÿ„‚„ÿÚÓÓÿ9>Jÿ=>?ÿWY\ÿ=?Fÿ('-ÿÿ$$'ÿ»µ½ÿBFNÿAFKÿ19Cÿ‘‰‡ÿßÓÔÿWiwÿ7Mcÿ'<Uÿ0E]ÿH\pÿ!/ÿ"ÿ&%$ÿPEJÿ0'.ÿÿ¥Ÿ—ÿ°¥žÿŽ‡�ÿmomÿnvzÿVhŒÿHQbÿPZKÿLLIÿSNNÿãÓÊÿgXSÿáÒÒÿåÐËÿl`aÿ1*1ÿ93;ÿ<8Aÿ‹‚{ÿ~unÿ¾²­ÿàÌÄÿMFMÿ;=LÿIKZÿ:6?ÿ0(+ÿ,%%ÿ/*%ÿ/*$ÿ�‹ƒÿÍÁºÿÒÀ½ÿ.%%ÿ$ÿ)""ÿ*##ÿ(!!ÿ'$ÿd[Uÿ³®ÿÌÀ»ÿ-%#ÿ&ÿ$ÿ*##ÿ##ÿ#ÿ !ÿ(!+ÿ$ ÿ½¦¡ÿ{{pÿÀ«§ÿÆÁ¼ÿÛÓÑÿ4--ÿ$!ÿ=53ÿª¤”ÿUIEÿçØÙÿJDHÿ)#'ÿ" ÿ 'ÿ-/4ÿˆ…„ÿ@:2ÿâÔÑÿɸÀÿKTbÿDIUÿ•��ÿ£œœÿæÔÐÿ\Uaÿ:;Fÿ-'+ÿ0*.ÿª¥§ÿ;66ÿ‡{|ÿ›’™ÿ!%ÿ" ÿ#ÿ+-*ÿ7..ÿ ÿÐÅÊÿWaeÿKW^ÿIP\ÿS[_ÿmhhÿÞÓØÿ@COÿ?KTÿ424ÿÍÆÆÿ<AMÿJGFÿ`abÿCHMÿPKOÿ-13ÿ--0ÿª¤¬ÿAEMÿ;@Eÿ)1;ÿZRPÿÐÄÅÿŠ�Žÿ‚ÿŸ�¦ÿV]cÿ.7>ÿ;=Bÿ.''ÿ1((ÿ´§¢ÿ*%'ÿ )ÿLGIÿ‡„yÿ¥¤™ÿglhÿltxÿcv~ÿ†ˆ�ÿ‚‚ÿGEBÿZUPÿèÛÖÿ[QGÿä×ÒÿâÎ×ÿ^RSÿ41%ÿ,(&ÿD;BÿzneÿŽ…wÿɼ»ÿÝÉÅÿA?Aÿ11>ÿDDQÿHGNÿ0*(ÿ*ÿ3'(ÿ7.(ÿ˜�†ÿØÉÄÿÓÂÂÿ*"%ÿ# ÿ&!ÿ-$$ÿ.&$ÿ6-'ÿnicÿÚÈÅÿϾ¾ÿ+&&ÿ% ÿ$ÿ(##ÿÿÿÿÿ0&"ÿ²¥ ÿCA:ÿº°¬ÿÓÇÃÿÜÑÐÿ4//ÿ'"$ÿ842ÿ¿³¤ÿI?;ÿåÙÚÿB=?ÿ&"$ÿ ÿ#&1ÿBCNÿ¨œ—ÿ4($ÿÞÑÐÿƹ¾ÿ<HQÿV]cÿ•�‹ÿ›””ÿëÞÙÿPP[ÿ=@Kÿ&!#ÿ'#%ÿ)%'ÿVRTÿgbdÿSOQÿ#"ÿ+')ÿ*&$ÿGGDÿgX\ÿ„�‡ÿØÐÓÿX`jÿMV]ÿHO[ÿUZ`ÿtkkÿæÙÞÿCFRÿT[aÿF>AÿÛÏÒÿ@FPÿpstÿihoÿGJKÿžšœÿ46;ÿ-,2ÿ¦¢«ÿ69Dÿ/27ÿ.4>ÿŸ’‘ÿ±Ÿ¡ÿk_Zÿ\WQÿhicÿnjbÿ}kgÿò¸ÿÖÌÈÿÑ¿¼ÿva_ÿª¡¡ÿ$#)ÿ?7;ÿ&$!ÿ‹ŽˆÿgljÿQU]ÿqpoÿ~|wÿWYVÿPQKÿSQIÿæÅÖÿnHiÿܵØÿûâÝÿUHMÿ)",ÿ)&2ÿ55@ÿzsgÿ•�}ÿË¿ºÿäÐÌÿGDJÿ33@ÿ87DÿVU\ÿ)!ÿ2&'ÿ3'(ÿ4*&ÿ‘…~ÿÙÊÅÿŶ¶ÿ+#&ÿ"ÿ% ÿ.%%ÿ+ ÿ6*%ÿ‚€yÿÒÀ½ÿÒÁÁÿ)$$ÿ% ÿ&!!ÿ"ÿÿÿÿÿE52ÿ§›–ÿNKFÿ¦ žÿÝÏÌÿ×ÌËÿ0-,ÿ&!#ÿ2.,ÿĶ§ÿUMIÿâÙÙÿ:55ÿ&"$ÿÿ#&1ÿBEQÿ¦—‘ÿRDAÿáÓÔÿ·¬³ÿ<HQÿV[aÿ™“‘ÿ�‰‰ÿéÜ×ÿFFQÿ8;Fÿ'#%ÿ'#%ÿ%!#ÿ&"$ÿ-)+ÿ®ª¬ÿ#!ÿ($&ÿm`Uÿƒ{kÿž‡{ÿpcXÿÚÒÐÿSWfÿ-5?ÿELXÿZ\cÿ}ttÿéÚßÿEHTÿOQXÿ`VYÿÞÏÔÿDGRÿŽ““ÿtr{ÿEHIÿÉÄÄÿ43:ÿ,+2ÿš˜¡ÿ34?ÿ8;@ÿ$*4ÿ«ž�ÿ®šœÿŽ}wÿpd]ÿB;5ÿ’„{ÿ{h`ÿË¿ÈÿA?Aÿ83.ÿf[Zÿ><9ÿ*,*ÿ646ÿ #ÿ678ÿtxvÿjmrÿ™–•ÿhfcÿpuqÿTVSÿTUOÿè»ßÿˆN ÿ¦dÑÿÇœÒÿ\HQÿ53ÿG0;ÿ5.(ÿ‰}yÿš‰”ÿÔÈÄÿíÚÔÿSOWÿ77DÿTS`ÿ[Zaÿ*" ÿ+ ÿ/#$ÿ=3/ÿƒwpÿÔÅÀÿĵµÿ+#&ÿ ÿ)!$ÿ4++ÿ1&%ÿ<0+ÿŠˆ�ÿÜÊÇÿÔÃÃÿ.))ÿ&!!ÿ#ÿ*%%ÿ'"&ÿÿ! ÿÿTDAÿ–Š…ÿc`[ÿ©£¡ÿÛÍÊÿÕÊÉÿ1.-ÿ(#%ÿ-)'ÿÅ·¨ÿ^VRÿäÛÛÿ<77ÿ'#%ÿÿ@CNÿ;>Jÿ°¡›ÿ_QNÿäÖ×ÿ­¡ªÿBMXÿSW_ÿ^WWÿ�zzÿä×ÒÿOOZÿ-0;ÿ$ "ÿ%!#ÿ#!ÿ$ "ÿ" ÿ#!ÿ&"$ÿ!ÿ+#!ÿ31,ÿ]NNÿ¨žšÿ×ÏÍÿOSbÿ+3=ÿ@GSÿ\^eÿ�††ÿæ×ÜÿILXÿRT[ÿcY\ÿÚËÐÿ:=Hÿ~ƒƒÿa_hÿILMÿÞÙÙÿ/.5ÿ/.5ÿ”’›ÿ<=Hÿ=@Eÿ.4>ÿ¶©¨ÿÀ¬®ÿª‘Šÿ¢ˆ}ÿª”Œÿ¹Ÿ”ÿŽrÿÊÃÏÿ03>ÿ#&'ÿ�€ÿ“�}ÿÞËÅÿJ<=ÿÿ!"ÿ\^[ÿkomÿtqpÿ~}ÿw|zÿgkiÿ]`aÿÞÛÏÿ-*)ÿ0.7ÿ8>:ÿ~‹ÿfCŠÿ£{¯ÿE,KÿªŠ½ÿ{X˜ÿÓÂÌÿìÚÐÿJFOÿ>>KÿSR_ÿ=<Cÿ+#!ÿ/#$ÿ0$%ÿ>40ÿrf_ÿ×ÈÃÿ¬��ÿ+#&ÿ ÿ'"ÿ3**ÿ/$#ÿ1% ÿ‰‡€ÿÝËÈÿÒÁÁÿ&!!ÿ$ÿ(##ÿ+&&ÿ(#'ÿ)$(ÿ&!%ÿÿsc`ÿŒ€{ÿzwrÿ§¡ŸÿáÓÐÿÊ¿¾ÿ/,+ÿ% "ÿ,(&ÿĶ§ÿumiÿçÞÞÿ:55ÿ'#%ÿ$"%ÿRU`ÿDGSÿº«¥ÿugdÿéÛÜÿ•‰’ÿ@JXÿ\_jÿ£›žÿŸ˜˜ÿèÛÖÿCCNÿ.1<ÿ*&(ÿ&"$ÿ#!ÿ$ "ÿ" ÿ" ÿ ÿ" ÿÿ).4ÿÊÅËÿ¼´¸ÿÜÓÓÿQUdÿ!)3ÿ@GSÿlnuÿ—ŽŽÿÜÍÒÿNQ]ÿlnuÿwmpÿÝÎÓÿDGRÿ†‹‹ÿa_hÿ>ABÿÆÁÁÿ'&-ÿ+*1ÿ“‘šÿ78Cÿ7:?ÿ&,6ÿ¸«ªÿ͹»ÿ·¢–ÿĨšÿ»ž’ÿÁ¥—ÿ›ŠzÿÔÈ×ÿ..Aÿ!#+ÿ957ÿ�|vÿÚ÷ÿA56ÿ'#%ÿ`^Yÿ„…ÿˆˆ‹ÿ”�“ÿpqrÿJSSÿUZZÿ‡‰ŒÿÆÈÏÿ.E2ÿLoWÿu�zÿ(?,ÿ ,+ÿ1:3ÿ7D9ÿ(4=ÿ?BTÿÊÂÅÿçØÒÿ;;Dÿ<@OÿKIYÿFBJÿ.$'ÿ-#&ÿ'ÿ0*(ÿc\VÿÞÐÍÿ©˜˜ÿ&#"ÿ!ÿ' ÿ.%%ÿ."#ÿ1$#ÿDE?ÿ×ÈÈÿÌ»»ÿ(##ÿ% ÿ$ÿ&!!ÿ.''ÿ+)+ÿ:??ÿÿo_Vÿolÿ‘ˆ‚ÿ¤ŸšÿèÙÚÿº®¯ÿ-*)ÿ#ÿ$%ÿ¯©¡ÿ“‡ƒÿâÕÔÿ>99ÿ#!ÿ# &ÿDGRÿDHJÿ¼¬©ÿ“‚‚ÿçØØÿƒ}‹ÿ7HVÿ_bmÿœ”˜ÿÚÎÉÿæÔÖÿ67Bÿ.07ÿ($&ÿ'#%ÿ" ÿ#!ÿ" ÿ" ÿ!ÿ#!ÿ(ÿGCEÿQPVÿÀ¹ÀÿêÙãÿ]Vgÿ=BTÿBI[ÿ}v€ÿµ©²ÿçÝìÿTReÿaapÿŒ‚‹ÿàÓØÿ<?DÿŽ�ŽÿPNWÿBEFÿÎËÊÿ()0ÿ+*0ÿ‰ˆŽÿ34?ÿ.08ÿ.6:ÿĸ¹ÿæÖÚÿÑÁ¸ÿÓ¹¬ÿ×·¯ÿÌ°¬ÿ™�†ÿÙÄ×ÿ#1@ÿ%!)ÿ&+1ÿxxuÿ�˜’ÿ�‹‹ÿ€{{ÿˆ�{ÿg`Zÿ\]dÿ•�”ÿ(*-ÿ7CGÿ;DDÿfkkÿ¿ÄÊÿ>H7ÿ6B3ÿ/@0ÿLcPÿ9TCÿ )ÿ>_Mÿ3N=ÿ<ZJÿ˜­¡ÿÙÑÍÿKGOÿ45@ÿ-*6ÿC>@ÿ&ÿ%ÿ' ÿ'#!ÿNOHÿÑÇÃÿœ‰‰ÿ&ÿ"ÿ' ÿ,##ÿ."#ÿ2%$ÿ{{xÿ×ÊÉÿÈ··ÿ(##ÿ% ÿ'""ÿ)$$ÿ.&$ÿ=?=ÿ]ddÿÿ{peÿhYYÿ²«¥ÿ›™”ÿäÕÙÿ·«¬ÿ30/ÿ'""ÿ!"ÿ®©£ÿ­ŸœÿåØ×ÿ3..ÿ%!#ÿ$ (ÿ9<Gÿ9>>ÿÀ­­ÿ§––ÿîßßÿc]kÿ8IVÿCGOÿ« ¥ÿáÔÏÿæÑÖÿ==Jÿ ")ÿ(#%ÿ&"$ÿ%!#ÿ" ÿ" ÿ" ÿ" ÿ" ÿ#ÿQPOÿ<ELÿˆŠ‘ÿ‹‰‹ÿIOQÿ;GLÿ@HRÿxzÿFGNÿ(.8ÿ%3ÿLUUÿyz{ÿÇÁÉÿ9>Jÿ‹‰‹ÿOKTÿBEFÿÉÆÅÿ/07ÿ)),ÿ˜™šÿ<>Fÿ78Cÿ/7;ÿ¾²³ÿâÓØÿwrlÿɾ·ÿßÒÍÿ™�‹ÿš•�ÿÞÇÚÿ5HTÿ& (ÿ:BLÿ.38ÿhijÿB=Aÿ54;ÿRLJÿµ©¢ÿ]XXÿ�„‡ÿ:5;ÿ!(.ÿCEHÿ©¤¤ÿÄÃÐÿÿ#ÿÿ%ÿ>C7ÿ9B5ÿ-:-ÿ#.ÿ"B-ÿi�€ÿÆÅÄÿIDJÿ@>Gÿ5/7ÿ@99ÿ."#ÿ%ÿ+$$ÿ%!ÿ $ÿÈþÿƒppÿ2$%ÿ$ÿ' ÿ3**ÿ-!"ÿ0#"ÿ‡‡„ÿÚÍÌÿ¿®®ÿ)$$ÿ$ÿ-((ÿ0++ÿ6.,ÿegeÿ_ffÿ#"ÿvlaÿj]\ÿŒŠƒÿŒ�‰ÿçØÜÿ°¤¥ÿ/,+ÿ&!!ÿ+*#ÿ­¦ ÿȺ·ÿëàßÿ1.-ÿ#!ÿÿ03>ÿ<CCÿ¿®®ÿ¿°°ÿòåäÿnhvÿIVaÿVW^ÿ²¦©ÿáÕÎÿçÒ×ÿ??Lÿ ")ÿ% "ÿ#!ÿ#!ÿ ÿ ÿ!ÿ" ÿÿ+#!ÿIKNÿFR[ÿZelÿDOZÿ9CNÿ*1?ÿ21Nÿ0'cÿ4*oÿ?6|ÿ[QšÿIÿe_‹ÿA=]ÿ9AKÿ•”“ÿXT]ÿLOPÿÙÖÕÿ027ÿ012ÿIKIÿ029ÿ12=ÿ'/3ÿ÷¸ÿäÕÚÿ~qlÿÀ«©ÿÜÉÉÿ†rnÿwngÿÔ½Ðÿ'3ÿ%'ÿ7@Nÿ9?Gÿ!#&ÿ0,4ÿ!$/ÿLHJÿxjaÿvkdÿ’��ÿF=Dÿ#$+ÿ><?ÿ¶«ªÿÝÎæÿ'+3ÿ;IXÿ'+3ÿ663ÿB@=ÿ?;9ÿÿ,-'ÿ-3/ÿYa]ÿÕÒÑÿ89@ÿ-0<ÿ:7Dÿidhÿ,"%ÿ.$'ÿ&ÿ&" ÿ=<5ÿ×ËÇÿl[[ÿ&ÿ!ÿ' ÿ/&&ÿ-!"ÿ5('ÿŽŽ‹ÿÞÑÐÿ³¢¢ÿ)$$ÿ$ÿ(##ÿ*%%ÿ80.ÿegeÿbiiÿ"!ÿ™Œ�ÿò²ÿƒ|vÿigbÿåÖÚÿ­¡¢ÿ)&%ÿ% ÿ83-ÿ½´®ÿÔÈÄÿäÜÚÿ854ÿ$ "ÿ $ÿ25@ÿ>EEÿ³³ÿÌ¿¾ÿïäãÿqjvÿGS\ÿ^]cÿ¹«¬ÿéÚÔÿåÐÕÿEERÿ!ÿ$!ÿ&"$ÿ#!ÿ ÿ ÿ!ÿ" ÿÿ5'(ÿKFLÿU`kÿQ[eÿGM]ÿ((7ÿ`]oÿrn”ÿ#"9ÿÿ - -ÿ - ÿ:ÿ,'Qÿ94Vÿ!(ÿ§¥¢ÿYU^ÿBEFÿÖÓÒÿ+-0ÿ8:8ÿ574ÿ25:ÿ01<ÿ(04ÿƺ»ÿçØÝÿ•vÿÉ°«ÿåÌËÿž†wÿ{qgÿ×ÀÓÿ 3?ÿ!#ÿ/5?ÿbfhÿ%'%ÿ1,.ÿ! 'ÿNFDÿˆylÿˆ}vÿ‘‚ƒÿKDKÿ#%,ÿ558ÿ¡œœÿ̼Øÿ)*1ÿ&ÿ$ÿ""-ÿ%*6ÿ<DNÿ ÿ%$*ÿ+*0ÿ96<ÿÿ=9Bÿ;;JÿJJYÿSPVÿ+#!ÿ8,-ÿ*!ÿ+$ÿ—‹‚ÿØÌÅÿYNMÿ*&(ÿ ÿ*##ÿ*##ÿ(!!ÿ0&"ÿ‰Š„ÿÞÑÐÿ¤’”ÿ( #ÿ'"ÿ*##ÿ+%#ÿ/)'ÿmnoÿ`ejÿ&!#ÿ¤‘…ÿÀ­¥ÿÇ»´ÿŹ°ÿÈ»¶ÿª££ÿ(%+ÿ%#&ÿF85ÿ·°ªÿßÐÐÿêÛÜÿ410ÿ$ "ÿ"ÿ7:EÿFNRÿf^aÿÓÇÊÿ{y{ÿz}~ÿu{}ÿhekÿ®£¨ÿóáÞÿØÍÔÿINZÿ!ÿ(" ÿ&ÿ&!!ÿ!ÿÿ !ÿ!!ÿÿF77ÿA;CÿGO_ÿV[gÿLNUÿ - ÿ+ÿ2!'ÿ -ÿ!ÿ'ÿ -ÿ!"ÿ ÿ&'ÿ "ÿ–Š‹ÿDBKÿGHIÿÑÐÏÿ,.1ÿLNLÿÿ %*ÿ<AGÿ).3ÿHCGÿÞÖÙÿ‰xkÿÁ«¢ÿéÓËÿ˜„vÿtiÿ×»Ïÿ.8ÿ,%,ÿ&1<ÿ‘��ÿ)&%ÿ604ÿ)#+ÿG?;ÿ›‹{ÿ‘†ÿ‘ƒ„ÿIDJÿ"%0ÿ##&ÿ®¬®ÿÚÃàÿ%#ÿÿ!ÿ!!ÿ$ÿ"(0ÿ-0;ÿ%$*ÿ.-4ÿUQYÿÖÌÏÿB;Eÿ;;JÿSS`ÿSNTÿ0(&ÿ!ÿ, !ÿNE?ÿ¿³¬ÿÜÏÊÿF><ÿ("&ÿ#ÿ)""ÿ%ÿ)""ÿ3)%ÿ‰Š„ÿÞÑÐÿ Ž�ÿ( #ÿ'"ÿ(!!ÿ,&$ÿ0,*ÿ__bÿ]bgÿ% "ÿ°¢™ÿeXSÿ¦žœÿ¦œ˜ÿ÷°ÿž–”ÿ(#%ÿ*"%ÿWHHÿ”’�ÿÞÒÕÿâÓØÿ/.-ÿ$ "ÿ"&ÿ7:Eÿ=@Aÿ¼´²ÿÚËËÿâÞÜÿUZTÿ535ÿ`Y`ÿ£˜�ÿí×ØÿÎÅÌÿ<AMÿ"ÿbZXÿUOMÿÿ#!ÿ!!ÿÿÿÿXMLÿHIPÿFSdÿAHVÿ'0ÿ=+-ÿ«’�ÿvZWÿZ=<ÿ˜unÿ…aWÿ„b_ÿ+ÿ–�ÿ§‘“ÿÿ7)&ÿBDLÿIJKÿÕÒÑÿ!ÿ,-.ÿ?BGÿ05;ÿ,17ÿ$',ÿÿÿˆvlÿÁ«¢ÿêÔÌÿ•€tÿwoeÿÕ½Òÿ*8ÿ,%/ÿ#0=ÿ¤ žÿ,(*ÿ<7=ÿ/(2ÿ@86ÿ ”…ÿ‚ysÿ‰}~ÿ_[cÿ&)5ÿ;:@ÿ¼·½ÿÆÁÙÿ25:ÿ (ÿÿÿÿÿ#ÿÿÿ*$,ÿÐÄÇÿSLVÿ@@OÿAANÿPKQÿ,"%ÿ+"ÿLA@ÿ7,+ÿXMLÿ—��ÿ4--ÿ$!ÿ&ÿ+$$ÿ+$$ÿ(!!ÿ2($ÿ‰Š„ÿáÔÓÿ‹y{ÿ#ÿ% ÿ+$$ÿ-'%ÿ-)'ÿ``cÿSX]ÿ'"$ÿ›‘�ÿ$ÿÿ#"ÿ˜Œ‡ÿ¦›šÿWPPÿ, ÿ¾²®ÿ�ƒ�ÿ¯¥¨ÿÚÏÔÿ202ÿ%!#ÿ#ÿ69Dÿ>?9ÿÉ¿»ÿâÓÔÿãÖÑÿQOGÿ<86ÿÌÁÆÿçØÜÿõßÝÿÌÃÊÿ8=Iÿ!ÿ2*(ÿ71/ÿB==ÿÿ!ÿ%ÿ ÿ #ÿzrpÿ<>EÿGWgÿ;ESÿ9BBÿ2ÿiV„ÿ ÿÿÿÿÿÿ -ÿ1+Aÿÿ%ÿ?CKÿIGIÿÖÑÑÿ %ÿ.-3ÿ13:ÿ.2:ÿ05;ÿ%(-ÿ0.1ÿ!ÿ‹{rÿÁ­¥ÿéÔÐÿ˜…{ÿqmeÿ˶Ìÿ)7ÿ&(ÿ%5ÿÇ¿½ÿ-(*ÿD?Eÿ-)1ÿ811ÿŸ•‹ÿ…„}ÿ�Š‰ÿffoÿ*->ÿEAIÿĽÇÿÕÉâÿGKMÿ'3<ÿ-ÿ00=ÿ*ÿ&ÿ$'ÿÿÿ.'/ÿäÕÙÿG@Jÿ==Lÿ66CÿOJPÿ*'ÿ)!ÿ-#ÿ/#$ÿÿ" ÿ"ÿ*"%ÿ' ÿ)""ÿ+$$ÿ)""ÿ4*&ÿef`ÿàÓÒÿ�oqÿ% ÿ% ÿ,%%ÿ*$"ÿ+'%ÿ__bÿY^cÿÿȼ¸ÿ%ÿ# &ÿ" ÿÿÿhcgÿ(ÿ¯ šÿÁ¿·ÿĸ³ÿÀ²¯ÿ543ÿ#!ÿÿ7:EÿMPJÿÉÃÇÿä×âÿæ×Øÿe_Uÿh`\ÿãÔØÿòßßÿóÝÛÿżÃÿ<AMÿ%$+ÿ>64ÿYSQÿlggÿ!ÿqgcÿ+ ÿ%#ÿ$ÿ“‡ˆÿ107ÿAL]ÿ9=Lÿ<HMÿ 'ÿfc˜ÿ96fÿ,ÿ ÿÿÿ3ÿWW€ÿRRyÿÿ% ÿ.4<ÿCACÿÛÒÒÿ*)0ÿ.-4ÿ68@ÿ+.9ÿ&*2ÿ!$)ÿ+),ÿ:57ÿ¿°ªÿÖýÿíØÖÿž‹ƒÿ…€tÿØÀÏÿ@NWÿ.#ÿvv…ÿÖÇÇÿ803ÿolrÿ54;ÿ502ÿ»³¯ÿ�—�ÿADEÿZ]hÿ38Jÿ/+4ÿ¤�©ÿÔÄØÿE>Fÿ# &ÿ!(ÿ77Bÿ9:EÿST_ÿ&&/ÿ((3ÿ(ÿH@CÿÞÏÏÿC?HÿCCRÿ<9Fÿ@;Aÿ$ÿ) ÿ2))ÿ3**ÿÿÿÿÿÿ ÿ%ÿ(!!ÿ0($ÿ‘ˆ‚ÿ×ÈÃÿj^Zÿ'"$ÿ!ÿ( #ÿ1((ÿ$"ÿ^ccÿbfhÿŠ……ÿPHFÿ ÿÿ#ÿ%!ÿ!ÿ& $ÿ*"%ÿOIGÿ‘Ž‰ÿœ—‘ÿ´°¨ÿ611ÿ0+/ÿ~…ÿ48@ÿdfdÿ»¶ºÿÜÖÞÿÔÔÑÿ½Ã¿ÿ«±³ÿÔÑ×ÿìÛÛÿòÜÔÿ¹µ·ÿ?PVÿ$$ÿwxyÿº­¨ÿ]SVÿÿÿ�ŠˆÿE95ÿ#"ÿ¥™”ÿ‚yyÿ/19ÿ24<ÿ-5Eÿ:EVÿ#ÿ%8ÿjdžÿQN�ÿ88qÿJÿ-ÿ/)?ÿ$ÿ"ÿÿÿ!!$ÿ¨¨«ÿ+.3ÿ,.3ÿ69>ÿ,.5ÿ#(.ÿ!&ÿ%'*ÿ313ÿÀ¶¬ÿ²Ÿ—ÿÞÆÃÿ“�wÿ…tnÿ­›Ÿÿljlÿ‚{uÿä×ÖÿãÎÌÿ°ŸŸÿ»²²ÿ'%(ÿ/*.ÿ410ÿ &(ÿ_ffÿ,4>ÿ27Iÿ00;ÿÓËÕÿáÔæÿ2*4ÿ% $ÿÿÿ%ÿ#ÿ &ÿ+ÿ'(/ÿe^^ÿßÐÑÿ75>ÿ00?ÿD>LÿB;Bÿ-&&ÿ%ÿ%ÿ"ÿ0*.ÿÿÿÿÿ"ÿ+$$ÿ+$$ÿ611ÿ% ÿ~ruÿaY\ÿ$#ÿ! ÿ+#&ÿ/&&ÿ'&%ÿ]a_ÿ|€~ÿš““ÿ/%(ÿÿÿÿ ÿ" ÿÿ#!ÿÿÿÿTROÿ�ŠŒÿOJNÿ%ÿ=AIÿW\XÿÀÂÅÿÓÑáÿ¼·Éÿ#-ÿICQÿÕÎØÿêÝÜÿêÖØÿ§œ©ÿJBVÿ<#4ÿwnuÿô®ÿK@Eÿ!$ÿlkjÿ0+&ÿ›Ž�ÿ)#'ÿ¸­¦ÿ(ÿihoÿDFMÿ'ÿ7@NÿFO`ÿ?BNÿ -ÿ �ÿ".ÿÿ)$0ÿ$ÿ14@ÿ(/=ÿ$&-ÿÿIILÿÿ"ÿ),1ÿ/27ÿ.16ÿ$)/ÿ#&+ÿ&(+ÿ=>?ÿ¾´©ÿ³Ÿ—ÿæÏÊÿ“�wÿŽ{sÿÁ²­ÿi_[ÿ^RIÿîßÚÿäÓÓÿ×ÈÉÿE@Dÿ9:;ÿ#!ÿa_Zÿ+0.ÿ)-+ÿGIQÿ44Gÿ4/;ÿÒÆÏÿØËÝÿ.&0ÿ1,0ÿ#ÿÿ"%ÿ ÿ0-3ÿ11:ÿÿ700ÿãÔÙÿ;8Dÿ??Nÿ>8Fÿ3,3ÿ&ÿ' ÿ-&&ÿ&ÿ6.1ÿ2*-ÿ6.1ÿ"ÿÿ*##ÿ)""ÿ)""ÿ% $ÿ!ÿÿ ÿ(#)ÿ+&*ÿ+#&ÿ-$$ÿ$#"ÿge`ÿfa[ÿ(ÿ²§®ÿsmuÿ&'.ÿ#ÿ"!ÿ ÿÿ! ÿ#$ÿ"#ÿ ÿÿ%#ÿ! ÿ&%,ÿ+/7ÿ¢™™ÿ§©¬ÿ|™¥ÿ\‡Ÿÿ@;UÿiShÿ¯ž©ÿh^aÿÜÏÎÿ�Ž•ÿ;KUÿ7BCÿŽ��ÿÕÆÀÿ>38ÿ'$*ÿ˜“ŽÿŸ”“ÿ–Š�ÿÿƺ³ÿ:0,ÿ¿¾ÅÿACJÿ^\^ÿ46=ÿ<GRÿ<KQÿ)ÿEHBÿ•”›ÿ)/9ÿ\_dÿ %ÿ.6@ÿ"0ÿ=FLÿ4:<ÿ@BEÿÿÿ-05ÿ),1ÿ.16ÿ!&,ÿ"%*ÿ.03ÿ9:;ÿ¾´©ÿ­™‘ÿâËÆÿŒzpÿ˜ˆ~ÿÀ´­ÿslÿ¨•‰ÿç×ÔÿξÂÿE:?ÿ/27ÿAFFÿCA<ÿ��€ÿeg^ÿ*)(ÿ--8ÿwt†ÿF?Gÿ»±´ÿÞÑãÿ( *ÿ ÿ!%ÿ"#ÿÿÿ(#'ÿÿÿ¥žžÿÚÏÖÿCCNÿ<<Kÿ@:Hÿ1*1ÿ' ÿ#ÿ+$$ÿ&ÿ,##ÿ5,,ÿ8//ÿ0''ÿ2++ÿ+$$ÿ' ÿ+$$ÿ+#'ÿÿÿÿÿÿ ÿ+""ÿ#!#ÿrmgÿG=/ÿ¡“�ÿÒÅÐÿb[gÿ%ÿ!,ÿ328ÿ%#&ÿ !ÿÿ# ÿ!ÿ! ÿ!"ÿ&&ÿÿ"ÿ/3;ÿš‘˜ÿœ¡¡ÿ6ONÿE_hÿ:7Dÿ“ƒ‹ÿ¹ª®ÿaZaÿäÝçÿ~�’ÿAI]ÿ.*2ÿ›–šÿÏÀºÿ7,1ÿ+(.ÿ¶©¤ÿ½®¯ÿ}ryÿ(##ÿŹ°ÿ›‘�ÿÈÇÎÿLNUÿÿ�ˆÿCM[ÿ:FUÿ,(ÿLNSÿ�Šœÿ(2Fÿ#%ÿJKLÿ (ÿ(+<ÿ;=Dÿ48:ÿBHJÿ;ACÿ.16ÿ.16ÿ),1ÿ*-2ÿ&+1ÿ(+0ÿ469ÿ$%&ÿ¸­ÿ·£›ÿàÉÄÿ‹yoÿ �…ÿ»«¨ÿc[YÿSKAÿæÔÐÿâÍËÿ–‹Šÿ5::ÿ38=ÿ!ÿ�Š‚ÿ{yqÿ&&)ÿ%(4ÿ+.?ÿSRXÿ……‚ÿáÏãÿ1,0ÿ"#*ÿ2.6ÿ% "ÿÿÿ1,0ÿC?Gÿ(*/ÿÌ¿ÄÿÙÈÒÿXViÿFI[ÿCCNÿ)!%ÿ*ÿ4)(ÿ.#"ÿ+ ÿ0($ÿ,'"ÿ4/*ÿ(#ÿ2*&ÿ2'&ÿ/$#ÿ.#"ÿ)""ÿ*%%ÿÿÿÿÿÿ+&&ÿÿ…zsÿvi\ÿG8Cÿ2):ÿ%(ÿ#ÿ&ÿ%ÿ!ÿ))2ÿ11:ÿ+,-ÿ#"!ÿ!!ÿÿ ÿÿÿ54:ÿÿÿ !ÿ/)-ÿ#$%ÿSJDÿ…vpÿmtzÿW‘§ÿHˆ§ÿ0p�ÿ:fˆÿ*0FÿpZ[ÿ7"'ÿ$!'ÿ¶¯©ÿйºÿaTYÿ/-/ÿÍÁ¸ÿjkvÿÚÑÑÿAKZÿPNQÿÀ¾ÀÿFP_ÿ>JYÿ#"ÿFDAÿ„‚’ÿ$->ÿ,55ÿ%"ÿKJWÿ,5Cÿ9<Aÿ:>@ÿEIKÿ39;ÿ7<Aÿ136ÿÿ16<ÿ$'2ÿ#&+ÿ ÿ034ÿ³®®ÿÕÎÎÿÙÏÒÿ×ÐÐÿàÐÔÿäÒÖÿÁ°¶ÿ²£§ÿïÕØÿÞÓØÿkfhÿtoiÿ,.+ÿ'&%ÿ�zÿkidÿFEKÿ)+:ÿ.ÿ157ÿEFGÿâÑéÿ43:ÿU\hÿ ,ÿ"ÿ" )ÿ!(ÿ!(ÿ2.7ÿ#ÿÐÁÅÿÙÈÒÿ\[lÿLO`ÿ??Hÿ+#&ÿ+ ÿ,$"ÿ)!ÿ+#!ÿ,&$ÿ/)'ÿ)#!ÿ& ÿ$ÿ-%#ÿ.&$ÿ-%#ÿ/((ÿ4//ÿ#ÿ-((ÿ500ÿÿ-((ÿ$ÿ$"$ÿ‹~yÿE78ÿ&4Uÿ;ÿ*ÿÿ"ÿ*ÿ%ÿ)ÿ#ÿÿ218ÿ%ÿ &ÿÿÿÿ'%(ÿ)'*ÿÿ!"ÿ&$'ÿ!ÿbVRÿò¬ÿcikÿ9:ÿ -$'ÿGLÿd…‘ÿZ}Šÿ£®©ÿ613ÿ-(.ÿ¶º²ÿ̺¼ÿG<Aÿ)')ÿʾµÿDJZÿÕÊÉÿ8EVÿ‹‰ŒÿÈÃÃÿBL[ÿ7CRÿ*65ÿLJEÿƒ…”ÿ$.Bÿ&21ÿA?8ÿON[ÿ%3ÿ046ÿ*.0ÿ/35ÿ'+-ÿ).4ÿ/14ÿ+-0ÿ-19ÿ*0:ÿ!$)ÿ$(&ÿ558ÿȺ»ÿÆ´¶ÿÁ¯±ÿ½«­ÿ­Ÿ ÿ¡•–ÿ¡•–ÿ™�Žÿ“x~ÿJEIÿ646ÿSNHÿnnkÿÿ&%$ÿba`ÿXW^ÿ():ÿ$'8ÿ48:ÿHFHÿáÓïÿ+-5ÿHQ_ÿ.0?ÿ(ÿ&*9ÿ!0ÿ#ÿWPZÿiknÿ¾°±ÿĹÀÿeenÿNPXÿFINÿ*%'ÿ%ÿ!ÿ#ÿ#ÿ(!!ÿ!ÿ)""ÿ.''ÿ1**ÿ&ÿ*##ÿ-&&ÿ*%%ÿ'""ÿ-((ÿ+&&ÿ4//ÿ)$$ÿ% ÿ!ÿ!ÿL?>ÿ<5?ÿCgŒÿTl�ÿ -(ÿ ÿÿ!ÿÿ!ÿ&ÿ$ÿ)ÿ#ÿ *ÿ42;ÿ)(/ÿHGNÿ%ÿÿÿ -ÿ ÿÿB8;ÿÿÿÿ65.ÿ!83ÿM_cÿ?AHÿ×ÈÃÿ2'.ÿ$ÿ8B8ÿeYZÿ5/3ÿ846ÿʾµÿ%+;ÿÏÄÃÿ6CTÿ™—šÿÍÈÈÿ@JYÿ9ETÿjssÿspkÿ}Žÿ1@Sÿ4@?ÿGE>ÿVUbÿ",:ÿ>BDÿ9=?ÿ?CEÿ=ACÿ<AGÿ79<ÿ>@Cÿ04<ÿ'-7ÿ!$)ÿ%'%ÿ¢œ ÿæÑÏÿûâÝÿøßÚÿúáÜÿýæáÿúãÞÿøáÜÿùâÝÿôØÚÿmkmÿ&&)ÿ850ÿ“’‘ÿ%#%ÿ" "ÿ!!ÿSRYÿ./@ÿ$'8ÿ6:<ÿOMOÿäÑçÿ)&,ÿ06@ÿ63?ÿ##,ÿÿÿ;<Gÿ+$,ÿ.,.ÿ?43ÿZRVÿYY\ÿ478ÿ-22ÿ&%$ÿ"ÿ% "ÿ"ÿ% "ÿ,$'ÿ$ÿ)!$ÿ+#&ÿ)$&ÿ# ÿ(#%ÿ&!#ÿ&!!ÿ!ÿ$ÿ$ÿÿ"ÿ'""ÿ$ÿ"ÿ#ÿ!"ÿ!2ÿ)ÿ'ÿ,)/ÿ )ÿ'ÿÿÿÿÿ ÿ$ÿ&ÿ#ÿ ÿ%ÿ33<ÿWTZÿ*(+ÿÿÿ``]ÿxzwÿ<?@ÿÿ %ÿC@Fÿ&'ÿY[^ÿŲ²ÿòÕÑÿ7'/ÿ##&ÿ‰‹‚ÿË·¹ÿ5*/ÿ1/1ÿιÿou…ÿÌÁÀÿ;HYÿ�Ž‘ÿÊÅÅÿ4>Mÿ/;Jÿy~~ÿÛÖÑÿmo~ÿ2BUÿ-;:ÿTRKÿRQ^ÿ2<Jÿÿÿ268ÿ:>@ÿ:?Eÿ=?BÿLNQÿ04<ÿ%+5ÿ!$)ÿkhgÿ»°µÿÓÈÇÿÍÿÿÔÊÆÿÜÒÎÿåÙÕÿèÚ×ÿå×ÔÿêÜÙÿöâÞÿ\^\ÿlnqÿ$! ÿ;9;ÿ ÿFDGÿÿ[Zaÿ0ÿ$'8ÿ48:ÿ‚€‚ÿåÛìÿ4,6ÿ-'/ÿ!ÿ*,1ÿ#%,ÿ!(ÿ.)5ÿ ÿÿÿÿ&!#ÿ%#&ÿA@Fÿ'#%ÿÿÿÿÿ ÿÿÿÿ ÿÿ -ÿÿÿ -ÿ ÿ ÿÿÿ# ÿ# ÿÿ#ÿ#ÿ(#)ÿ"ÿ&ÿ&ÿ(ÿ,+2ÿ217ÿ %ÿÿÿÿÿÿÿ"ÿ&%,ÿ&ÿÿ^^aÿ003ÿLLOÿ.*,ÿ !ÿ:BDÿÿÿ%ÿÿc_]ÿĽ·ÿêÚ×ÿ*&(ÿ'!ÿ²¦ŸÿãËÎÿ0(,ÿ0,.ÿ÷³ÿnwpÿ»µ¹ÿ?R\ÿ�‘’ÿÂÄÉÿ7=Mÿ9AUÿz�‡ÿÔÌÊÿhhwÿ<FUÿ<BDÿtlhÿLKXÿ.9Dÿÿ"$)ÿ8:=ÿÿ&+0ÿ9<AÿIHOÿ26>ÿ45@ÿ %*ÿ«¢¢ÿÆ·¼ÿ¬›•ÿª”‹ÿ¨“‡ÿŸ‹}ÿ—ˆ{ÿ—…{ÿ{h`ÿŠ|sÿçÒÍÿcc`ÿ««®ÿJEEÿHEKÿ ÿ‚~ÿiegÿd_cÿ]]lÿ#'=ÿ<=Dÿ•�–ÿéÜçÿÿ&&ÿ ÿ"#ÿ$%ÿ'$*ÿ-*0ÿÿÿÿÿÿÿ=<Cÿ$"ÿB2:ÿ1 &ÿ!ÿ& ÿÿÿMGKÿÿÿÿ*$(ÿÿÿ ÿÿÿÿÿ'"$ÿÿÿÿ*ÿ1ÿ"ÿ&ÿ&ÿ&ÿ#ÿ$ÿ%ÿ)'0ÿ.+1ÿ0-3ÿÿÿÿÿÿÿ"$)ÿ>@Cÿ*,/ÿ*,/ÿ..1ÿTVYÿCEHÿÿÿ43:ÿ1,0ÿKFFÿ©¢œÿëØØÿ*&(ÿ-*%ÿɽ¶ÿëÓÖÿ-%)ÿ2-/ÿ³¤©ÿ|‚zÿ»±»ÿ@Tbÿ“ˆ�ÿ¾½ÊÿBWiÿGr„ÿG}‡ÿ´¿Æÿ`Xlÿ.COÿnyzÿÞÖÒÿIHUÿ-8Cÿ,4*ÿMNUÿ;=@ÿ/23ÿ',1ÿ9;BÿJHQÿ25@ÿ+,7ÿ#'ÿœ�‘ÿ̽Âÿï§ÿ¾¤—ÿ½£•ÿ¿¦•ÿÆ®›ÿÅ«˜ÿĦ–ÿÄ­ ÿßÆÁÿqpoÿ³³¶ÿQLNÿYS[ÿ&!%ÿ�Ž‹ÿˆ„†ÿfacÿffuÿ+.Gÿ22;ÿ¨ £ÿíÙãÿ"!ÿ#ÿ#ÿ)#+ÿÿÿÿ$ "ÿÿÿÿÿ% &ÿ=<Cÿ& $ÿ£™œÿ´®¬ÿ‰†�ÿ,)(ÿÿÿ¯©­ÿÿpjnÿ("&ÿ[UYÿ715ÿ™Ž“ÿd\`ÿ‚|€ÿÿÿ&!#ÿ'"$ÿÿÿÿ3ÿ(5Rÿÿÿÿ ÿ$ÿ'ÿ(ÿ#ÿ 'ÿ&ÿ!ÿÿÿÿÿÿ!#&ÿ #ÿ:<?ÿ:<?ÿÿ79<ÿPKOÿ”‰Žÿkdkÿ‚}ƒÿB@Cÿcacÿ¥£ ÿéÚÛÿ+%)ÿ..+ÿÍÁ¼ÿòÚÝÿ&"ÿ)$&ÿ° ¨ÿÀÀ½ÿº©¹ÿ3L]ÿfu{ÿo„�ÿn†™ÿYxŠÿr�¦ÿo�œÿb�Ÿÿ(<Jÿ‚„‡ÿØÐÌÿNMZÿ9DOÿ\^Uÿ:;Bÿ379ÿrstÿ038ÿ<>EÿA?Hÿ25@ÿ+,7ÿ$.2ÿ»²²ÿÍÀÅÿÀ¬¤ÿ·��ÿ³™‹ÿê™ÿĪ•ÿͯšÿä’ÿÉ°ŸÿàÉÄÿtuvÿ©ª±ÿ_Z^ÿfbjÿ% $ÿ•“�ÿŒˆŠÿe`bÿuu„ÿ-0Iÿ009ÿ¯¨¨ÿçÔäÿ#+ÿ0:Hÿ 2ÿ!&8ÿ,ÿ ÿÿÿÿ'#%ÿ513ÿC<<ÿ617ÿ107ÿ.(,ÿe][ÿpicÿLI>ÿNKFÿ"ÿÿÿÿÿ#!ÿÿÿÿÿÿÿÿ$!ÿ$!ÿ$!ÿÿÿ ÿ"ÿÿÿÿ#ÿ#ÿÿÿÿ&ÿ&ÿ&ÿ ÿÿÿÿ,-.ÿ.03ÿÿ#%(ÿ&(+ÿ (*ÿ*.0ÿ--0ÿ+/1ÿ)*+ÿ//2ÿ"$ÿCHMÿEJHÿпÅÿ/&-ÿ()*ÿ®¢�ÿõÝàÿ)!%ÿ,')ÿ¼°³ÿÒÑÊÿ³¢­ÿJgrÿr†ŠÿI\dÿnw…ÿRR_ÿT\lÿ>JQÿx’¥ÿNhvÿz€‚ÿÛÓÏÿhgtÿ0;Fÿ ž–ÿ@?Fÿ;ACÿ¾º¼ÿ,/4ÿ9;BÿKIRÿ+.9ÿ%(3ÿ#/3ÿ�||ÿǼÁÿ§“‹ÿ½£–ÿ°–ˆÿÁ¨—ÿȱŸÿͲ¡ÿÁ¥—ÿɲ¦ÿÛÇÃÿZ\_ÿ®°¸ÿXU[ÿuqyÿ'"&ÿ›™–ÿ�‹�ÿ]XZÿkkzÿ),Eÿ44=ÿh]bÿØÐÞÿ'ÿ9G\ÿ;ÿALeÿ(/Eÿ,ÿ'ÿ!"ÿ-&-ÿ0+1ÿ314ÿ4/3ÿ?AFÿ68@ÿ:8;ÿØÉÉÿ̽·ÿyncÿymhÿÿ`[_ÿQLPÿÿ" ÿ%#ÿNHLÿZTXÿ€z~ÿ0*.ÿÿ715ÿÿÿ"ÿÿÿ.)#ÿ=EOÿ -ÿÿ"ÿ!$/ÿ !(ÿ%ÿ ÿ%ÿ#ÿ""+ÿ$ÿÿÿÿ!ÿ!ÿHIJÿIKIÿ*-.ÿ ÿÿÿÿÿ&ÿ&%+ÿ8:=ÿ!!ÿ:;<ÿ¼¹´ÿçÕÙÿ& (ÿ.20ÿ¶±ÿõÝàÿ*"&ÿ/**ÿ³¬¬ÿØËÊÿ¢�¡ÿWkoÿ›¢®ÿ—™¡ÿ'&,ÿ#ÿ"&.ÿefmÿ±¶ÂÿF]iÿ‚‹‘ÿÛÕÓÿCFRÿ:DRÿ³®©ÿCELÿ;>?ÿ¾¼¿ÿ16<ÿ;=Eÿ@>Gÿ'+3ÿ.08ÿ%-/ÿ�ywÿ»¯²ÿÜÊÆÿÞËÅÿÞÍÇÿÝÉÁÿâÉÂÿл¶ÿØÄÀÿѺµÿßÉËÿSV[ÿ¥¨­ÿWRXÿŠ†Žÿ% $ÿ¢Ÿžÿ›–šÿe`dÿpn~ÿ'(Aÿ35=ÿnsyÿçÚÙÿ>86ÿ654ÿ979ÿ=?Gÿ!,ÿ ÿ#!ÿ2++ÿ502ÿ;79ÿ;:9ÿ336ÿ--6ÿ79Aÿ*(+ÿj]\ÿZOHÿvndÿ†yÿÿÿÿÿÿ\VZÿÿÿÿ'!%ÿ& $ÿ" ÿÿž‘�ÿ3$$ÿ$ÿ'ÿNGAÿ8CNÿ$ÿÿ'ÿ),7ÿ136ÿ$$/ÿ(ÿ!!,ÿ'ÿÿÿÿÿ ÿ%ÿ(-3ÿ<:=ÿ?=:ÿ=;6ÿ=;6ÿ?=8ÿ1/1ÿÿÿÿÿÿÿ‹‡…ÿÐÈÄÿé×Ûÿ)&,ÿ53.ÿÔÇÂÿï×Üÿ.&*ÿ1,,ÿ¶±±ÿéÙÝÿ˜˜›ÿXfiÿœ¤®ÿÿNNKÿ{}zÿWXYÿ+-0ÿ)37ÿ8GLÿƒˆ�ÿÛÕÓÿ@DSÿ9CQÿ‹†�ÿ>CIÿFIJÿËÉÌÿ18>ÿBEJÿ>=Dÿ),7ÿ57?ÿ(02ÿÁ¶µÿ¾¯³ÿÓÑÎÿCC@ÿAGCÿZZWÿÌÊÇÿOQNÿX]Yÿ[]ZÿпÅÿJMRÿ´·¼ÿjekÿœ–žÿ&!%ÿ¦£¢ÿ�˜žÿjeiÿuq�ÿ)*Cÿ24<ÿ‰„ˆÿâØáÿ(#'ÿ ÿ31,ÿ731ÿA=;ÿOJEÿUPJÿFA;ÿA>9ÿFDAÿ<:<ÿ*)0ÿ23>ÿ86?ÿ2++ÿÕÈÇÿ¨Ÿ™ÿvphÿid_ÿÿ ÿ -ÿpkoÿÿA;?ÿÿYSWÿÿ%#ÿicgÿÿÿec\ÿ�‰ƒÿ›š“ÿ�{xÿ¦œ˜ÿ?P^ÿ#ÿÿ 1ÿ"ÿ%# ÿ-+4ÿ--8ÿ++6ÿ%%0ÿ !,ÿ&'2ÿÿÿ(ÿ(ÿ[]`ÿ#"(ÿ$"ÿ63.ÿFC>ÿB?:ÿ><9ÿÿ??<ÿCC@ÿ$"$ÿ!ÿ?D@ÿgd_ÿÍÈÃÿêÛàÿ''*ÿ=5+ÿ×ÆÀÿóÛàÿ'#ÿ4//ÿ¸µ´ÿáÕØÿ——šÿKUYÿÿ'()ÿmleÿKOGÿbc\ÿ*+%ÿ_d`ÿQYVÿŠŽ�ÿáÛÙÿ?CRÿ<FTÿºµ°ÿAFLÿ@CDÿËÉÌÿ8AAÿAFFÿJIPÿ14?ÿ(*2ÿ$,.ÿø·ÿ¾¯³ÿÏÆÆÿC?=ÿ;96ÿNHFÿØÐÓÿGGDÿPSMÿIFEÿÓÂÊÿQTYÿ¶¹¾ÿidjÿ¤ž¦ÿ&!%ÿjgfÿ¡œ¢ÿqlpÿwsƒÿ,-Fÿ.08ÿa`_ÿíÛéÿ""ÿÿÿÿÿÿÿ ÿ2.,ÿJEIÿ;7?ÿKHTÿIIVÿ95>ÿ¹¬«ÿk]^ÿKC?ÿojdÿ_[YÿÿE@Dÿ£ž¢ÿÿ%#ÿICGÿ„~‚ÿoimÿgaeÿgaeÿ€z~ÿÿ/*$ÿ©Ÿ•ÿ��xÿkcYÿq`Zÿ’�ˆÿ@Seÿ!'ÿÿ#!4ÿ !(ÿfa[ÿÿ*ÿ!ÿ)ÿ'*6ÿ-0<ÿ!ÿ ÿ.ÿ!)ÿ‡„ƒÿÿÿ'%(ÿ0.1ÿÿÿ-,+ÿ432ÿBA@ÿ.-,ÿ+-*ÿx}wÿ ž—ÿŽˆ†ÿàÕÚÿÿm\OÿÝÈÃÿíÕÚÿ1)-ÿA<<ÿµ·µÿâØÛÿ†„‡ÿ2:>ÿ$ÿjdhÿhe`ÿQVPÿigbÿDA<ÿc_]ÿ%"!ÿ‰‰ŒÿãÝÛÿ<@Oÿ<FTÿ·²­ÿAFLÿ=@Aÿ ž¡ÿ0:7ÿ@FBÿIHNÿ69Dÿ)*5ÿ"*,ÿŸÿĵ¹ÿÙÍÈÿMD=ÿA;3ÿRG@ÿäÓÓÿ\RHÿgdSÿWJEÿÕÀÆÿDGLÿ�„‰ÿvqwÿXRZÿUPTÿÿÿojnÿqm}ÿ()Bÿ,.6ÿilmÿùØ÷ÿÿ!ÿÿÿÿÿÿ -ÿ504ÿFDGÿPMSÿFGRÿVYdÿLGMÿƵ¯ÿçÒÎÿŒ~ÿÿÿÿÿÿÿ ÿ ÿ ÿÿÿ ÿÿÿ?>3ÿ½´¦ÿÀ²©ÿ¼¶®ÿÇ¿»ÿª›ŽÿH[yÿSPVÿÿ+&Jÿ!ÿXVGÿ&ÿ&ÿÿÿ%,2ÿ"ÿ -ÿ'ÿ AÿFFQÿÀ¹³ÿ&(&ÿÿÿÿÿ%&ÿVSNÿ#!ÿ!#!ÿ$)%ÿ?DBÿ#!ÿSQSÿnliÿŠ‰ˆÿÿ‹xnÿÈ´°ÿÖÇËÿ#!ÿZTRÿý»ÿâÚÝÿ�~„ÿ(*1ÿ !ÿqeaÿ~slÿ:<AÿÿXVNÿ410ÿ:8;ÿmqsÿÙÖÕÿ:?Qÿ1;Iÿº¶ÿ@EKÿ9><ÿÈÃÃÿ'+-ÿ>@CÿFGNÿ(+6ÿ26>ÿ"#ÿùµÿÆ´¶ÿ×ÎÈÿRC=ÿB>6ÿPH>ÿìÔÑÿpaTÿvr]ÿa[SÿÕÃÇÿEHMÿ9=Eÿ639ÿompÿ%!#ÿÿ ÿusvÿ€Œÿ,->ÿ138ÿ°«¯ÿø×èÿÿÿÿÿÿÿÿ97:ÿ?=@ÿJHKÿECFÿ@BIÿCEMÿGBHÿп¹ÿí×Ïÿ„uvÿ ÿÿÿÿ/+-ÿLHJÿ[UYÿLFJÿÿ#!ÿ1,0ÿ@;?ÿÿÿº¯¨ÿű©ÿ ‰„ÿ€lhÿkcfÿ¸¦˜ÿ3Fdÿÿÿ#&Pÿÿ\XIÿ+ÿ(ÿÿ ÿ#,2ÿ%ÿÿ1ÿ":kÿ”—¨ÿ¤››ÿC>BÿÿA<@ÿÿÿJH@ÿ¡ž™ÿÿ,+*ÿ@@=ÿ2/.ÿÿÿÿ(,*ÿiifÿbRIÿ·ª¥ÿº¾ÿ% $ÿg_]ÿŸ—“ÿâÞÜÿqsqÿKOQÿ68=ÿ_ZUÿbVQÿOMPÿXRVÿMMBÿKJIÿÿu~~ÿÝÙÛÿ<@Uÿ*4Cÿ¿·³ÿDIOÿ8=;ÿÏËÉÿ)+2ÿ=>Eÿ@@Iÿ+.9ÿ&,4ÿ$%ÿÁ¶µÿ²¶ÿãÔÎÿu]TÿPF;ÿ[QCÿëÔÏÿl`ÿ‹‚qÿf`XÿÔÂÆÿACJÿ:>FÿEDJÿ~|~ÿ#!ÿÿ" ÿigjÿ#ÿ&ÿLLOÿ²­±ÿÿíàÿ,ÿ"ÿ ÿ!ÿÿÿÿÿ !ÿ/-0ÿ758ÿ9;@ÿ?@GÿVQWÿƹ´ÿîÛÓÿŠ|yÿE6:ÿ)ÿÿÿÿ\XZÿkeiÿ]W[ÿHBFÿ[UYÿUPTÿÿÿ -ÿ�‡…ÿ­¥£ÿ½¸³ÿ¸°¬ÿ¥¤«ÿ±¤ÿRb|ÿ# ÿ#ÿF[‹ÿ#ÿ^SHÿ1ÿ+ÿÿ+ÿ*3:ÿ,ÿ)ÿ=ÿ#Ayÿ£©¿ÿŠ‚†ÿ)!+ÿÿfedÿ""ÿ34.ÿŽ…ÿ¢œšÿÿ*'"ÿˆ€|ÿŒ……ÿÿÿÿÿÿ1&ÿe]YÿXSWÿ425ÿˆ€~ÿUQOÿ€‚ÿ†ˆ…ÿ7<8ÿ ÿccfÿniiÿ°¬®ÿ½º¹ÿwwnÿ;>Cÿ8CDÿ|ˆ…ÿÜØÚÿ9=Rÿ1;Jÿ¾¶²ÿ38>ÿ>CAÿÏËÉÿ24;ÿBCJÿ77@ÿ-0;ÿ%(3ÿ#-1ÿ¼³³ÿ¶«°ÿàÓÆÿˆn`ÿRI;ÿbXMÿñÜ×ÿ�znÿœ�~ÿic[ÿÔÄÈÿ8:Aÿ8<Dÿ>=Cÿ�Ž�ÿ ÿ^Z\ÿ402ÿmknÿ&&1ÿ!#2ÿ336ÿ¯ª°ÿÿîÖÿÇ›sÿ>ÿÿÿÿÿÿÿÿÿÿÿÿÿ¾²®ÿèÕÍÿj]Xÿ%ÿJ@<ÿJEEÿÿÿÿQKOÿ5/3ÿ& $ÿ937ÿÿÿÿÿÿÿ:DAÿQVPÿ27CÿìÛÎÿ5CXÿ'#!ÿ&ÿ4Z�ÿ*ÿS@8ÿ)Fÿ.ÿÿ1ÿ%0ÿ 9ÿ9ÿ#7dÿ =wÿ­±Æÿ’��ÿ-/4ÿÿproÿ45/ÿHF?ÿË»¸ÿ¯¥¨ÿ)+)ÿ@;5ÿ»³¯ÿ‰„„ÿ}~ÿ)-/ÿ!ÿ!ÿ'"$ÿHC=ÿÿÿ)'*ÿ†~|ÿ/-0ÿÿÿ*.,ÿgfeÿ012ÿ %ÿ9>Dÿ536ÿ-,+ÿ@CUÿ1AJÿ‚��ÿÝÙÛÿ04Iÿ6@Oÿ¿·³ÿ5:@ÿ<A?ÿÍÉÇÿ/18ÿ67>ÿ>>Gÿ'*5ÿ%%2ÿ"(ÿ‡‚„ÿµ®µÿÞÓÈÿ†qeÿSRGÿ-,%ÿßÐËÿŽymÿ©˜ˆÿhd\ÿÒÂÆÿ?AHÿ6:BÿCBHÿ˜–˜ÿ" ÿ•‘“ÿ—“•ÿjhkÿ%%0ÿ!#2ÿ447ÿ­¨®ÿÿòéÿÙ£jÿÀ—mÿ}\8ÿÿÿÿ%ÿ4.Bÿ -ÿÿÿ -ÿÿ+('ÿÅ»·ÿðÖÍÿ«¢›ÿkecÿ#ÿ% $ÿÿÿÿ - -ÿ"ÿÿ#$ÿ*ÿ4$!ÿ8#!ÿ.ÿ'ÿ"ÿ" ÿuywÿCECÿÖÑÓÿZk{ÿ&*ÿ$ÿ&N†ÿ+ÿrbRÿ4^ÿss|ÿVUNÿ"0Gÿ\blÿ)0Fÿ Lÿ"<{ÿ(:tÿ¸µÇÿ]c_ÿ789ÿÿtvmÿRPMÿg_[ÿѼÿº¯®ÿJHJÿˆ…„ÿˆƒ‡ÿJLQÿ,16ÿ-05ÿ%)+ÿ)+.ÿ!#&ÿÿÿÿÿ‹„„ÿ336ÿ149ÿ+/1ÿÿÿ ÿ&0ÿ ,3ÿ½·»ÿèÛÚÿ|}Žÿ<LVÿqx~ÿßÚÞÿ7=Mÿ6=KÿÇ»·ÿAFLÿ9?;ÿØÒÐÿ23:ÿ25:ÿ+/1ÿ+-4ÿ**3ÿ"ÿ¼´¸ÿ„x{ÿãÎÉÿ‘}uÿ>5/ÿFD?ÿòáÔÿŸ‡xÿ¬šŒÿƒwnÿßÐÔÿA@Gÿ]fmÿ@CHÿ›™›ÿÿš–˜ÿ§£¥ÿpkoÿ""1ÿ%(:ÿ//8ÿ®¦ªÿüðëÿݧmÿÊ rÿÆ—]ÿ®�zÿ9"3ÿ5ÿ+$Bÿ(!3ÿÿÿ ÿÿÿ)%#ÿνÿóÜ×ÿ?=:ÿ979ÿaZZÿ685ÿÿ'%"ÿ/**ÿ˜Œ…ÿ¦–�ÿÓ½´ÿïÓËÿåÏÆÿðØÏÿíÑÉÿìÖÍÿòÖÓÿâÉÈÿ² �ÿ¸¦£ÿF:6ÿÖÎØÿ4GYÿ4N\ÿ;>Iÿ8V‚ÿ"ÿ±š}ÿ%;bÿCELÿ:??ÿ1Tÿ 4ÿ 2Nÿ8mÿ'L�ÿ,@zÿ»¹Éÿ‚Š†ÿ$ "ÿÿwznÿvtqÿµ«§ÿ×Ǿÿ¾±°ÿ`[_ÿRMOÿ°ª®ÿˆŠ�ÿ!&+ÿ$ÿÿ-13ÿ268ÿ'+-ÿ%&'ÿÿÿ™”–ÿ87=ÿFKQÿ/4:ÿÿ $"ÿ!$ÿ!.;ÿ0@Pÿ9;Cÿ©¢¢ÿ ¢±ÿMWfÿ{{~ÿæàÞÿ’™§ÿ6?Mÿø·ÿ8=Cÿ9><ÿÌÈÆÿ79Aÿ:?Dÿ!!ÿ05;ÿ ÿ#(ÿ,*-ÿ)!$ÿçÓÏÿíØÓÿëÙÕÿòäáÿúäÜÿöÝÖÿñÜ×ÿÞÌÈÿé×ÙÿICKÿ|…Œÿ˜› ÿ¥£¥ÿJFHÿ¤ ¢ÿ¢ž ÿyswÿ''4ÿ#(:ÿ,,7ÿ­¥¨ÿýðëÿá«qÿΣsÿÝ£^ÿÚ§kÿ­…kÿ(ÿÿ ÿÿ63.ÿ94/ÿ1)'ÿÿ0+&ÿ˽ºÿíÛØÿ9>>ÿ!'ÿ %ÿ17/ÿGKBÿ34.ÿÿ)%'ÿ' ÿ�|ÿØþÿîØÏÿ÷ÝÔÿûß×ÿóÝÔÿøÞÕÿôÞÕÿòâØÿõâØÿáÏËÿØÅËÿ<DTÿ-AUÿ;EZÿ'Alÿ .ÿŸ“„ÿ 1Uÿ[]dÿ$ÿ3Zÿ#0Iÿ,Mÿ'V�ÿ,Y™ÿ1M†ÿ¾¾Íÿ®°­ÿ@8;ÿÿ�„xÿ€~{ÿƼ¸ÿÕÆÁÿº®±ÿ�y}ÿƽ½ÿɽ¾ÿD@Bÿÿ!ÿ#')ÿÿÿÿÿ ÿ1/1ÿ957ÿ617ÿ89@ÿ79@ÿ"ÿ&//ÿ"!'ÿ*7ÿ->Vÿ1>Qÿ%*/ÿ(7ÿEOdÿ–•›ÿ®©¤ÿw~Šÿ0:Hÿ²­­ÿ9?IÿABCÿÑÍÏÿ04<ÿ5=Aÿ$$ÿ,39ÿ -2ÿ1=Aÿ ÿÿßÐËÿòÝØÿõÛØÿùÜÛÿ÷ÛÝÿöÝÞÿðÙÚÿïÚØÿïÙ×ÿšŽ‘ÿ„†�ÿ¨«°ÿ ›Ÿÿfaeÿ¬§«ÿ¦¡¥ÿsnpÿÿ &6ÿ..7ÿ¡�ŸÿÿõëÿÙ¥lÿͦ|ÿÚ¤aÿÊ¡`ÿÅ•^ÿ½”cÿ -�ÿ :ÿ0*Fÿ*)0ÿ<<9ÿOJEÿ94.ÿ=51ÿÔÄÁÿíÙÕÿ6;9ÿ#(-ÿ$$'ÿ-22ÿÿ131ÿ?>=ÿ-22ÿ"&(ÿ'),ÿÿlfdÿÄ·²ÿîÖÓÿñ×ÔÿöÝØÿóÞÙÿñÞØÿøßÚÿîÛÓÿùÜØÿâÓÓÿRJNÿ$ÿ,7Hÿ",ÿkb[ÿ ,Iÿ)$$ÿ')&ÿ3=Rÿ''4ÿ-Fÿ=hœÿ3X™ÿ-KƒÿÄÆÕÿžž›ÿÿÿ‚…yÿ‡…‚ÿÉ¿»ÿÖÈÅÿ¼¯´ÿj`cÿÑÅÁÿ̽¸ÿmgeÿ&(+ÿ"'-ÿ69>ÿ&*,ÿJNPÿ;?AÿGLLÿ;>?ÿ !"ÿÿÖÊÍÿƼ¿ÿÿÿ16;ÿ*$(ÿ"ÿ.?Mÿ1?Xÿ9CMÿ=Pbÿ0D`ÿ&3Fÿÿ:GXÿ.9Dÿÿ+0<ÿ,,/ÿaadÿ,4>ÿ7AEÿ ,+ÿ,5;ÿ$16ÿ+7;ÿ&,.ÿ-+-ÿçØÓÿïÚÕÿòÝÙÿõßÝÿøáâÿöàÞÿöáÝÿøáÜÿÿçàÿæÕÕÿrqxÿ­¯´ÿ™”šÿqlrÿ°«±ÿ¨£©ÿ‚}ÿZ\dÿ&4ÿ018ÿ‹Œ�ÿÿòéÿߨnÿÄ™mÿݦfÿÇ›iÿΚhÿÃ�[ÿ¿’iÿ@7ÿ1"Aÿ -ÿÿ™‰€ÿ��|ÿNK@ÿÖÉÄÿñÛÜÿ478ÿ %ÿÿ,02ÿÿ!%'ÿ##ÿ051ÿDICÿ22/ÿÿ('.ÿÿnelÿÝÎÒÿôÞÜÿùßÜÿøÜØÿÿàÜÿøÜØÿøÞÕÿ÷ßÖÿñØÙÿñ×ÔÿnZVÿ1("ÿ-'ÿ,(*ÿ-$ÿ*!ÿ50+ÿ("ÿ(ÿL‚ÿ(F�ÿ&Mˆÿ½ÂÈÿ–”�ÿ$ ÿÿ�‰ÿ‡„ÿËÂÂÿÝÄÅÿ¼µµÿÈÂÀÿÑÄ¿ÿÙÄ¿ÿYLKÿ(,.ÿ"''ÿ"#ÿÿ$$ÿ/66ÿÿÿÿ72,ÿÎÁ¼ÿÁ¹µÿ9;2ÿ{„wÿ��ˆÿ. ÿÿ -ÿ/@Nÿ5EUÿ7Kaÿ2Gcÿ.C_ÿ1F^ÿ1BYÿ4<Fÿÿÿ:7=ÿÿÿ/7;ÿ)-ÿ!*1ÿ#14ÿ#01ÿ025ÿ+%)ÿçÓÏÿòÛÖÿïÚÕÿ÷âÝÿ÷âÞÿúåáÿõàÛÿ÷âÝÿýâÛÿϹºÿhbjÿ©«°ÿ‘�•ÿ~{�ÿ¸µ»ÿ§¥¨ÿmgkÿzwƒÿ#$5ÿ()0ÿ)')ÿÿôîÿמdÿΠsÿÖ�[ÿÍ�jÿÊ™dÿÌ›fÿÍœgÿ¶�^ÿ`??ÿ#ÿ!ÿVPHÿjdhÿ?@9ÿÓÇÀÿçÓÕÿ8:=ÿ#ÿÿ-13ÿ68;ÿ'-/ÿ)13ÿ-22ÿÿ575ÿEDCÿ./0ÿÿ ÿ*,/ÿSNTÿÏÄÉÿëØØÿôÝØÿ÷ÜÕÿ÷ÝÒÿöÜÓÿùÝÚÿð×ÒÿïØÓÿêÕÑÿ¦”‘ÿyqtÿ3.4ÿ-/7ÿnt~ÿmorÿ /ÿL…ÿ!<‰ÿ$LŠÿ¾¿Êÿ|wwÿ#!ÿÿš’ˆÿ‡‚}ÿÐÆÉÿßÉËÿ›�›ÿÉÅÃÿÔÄÁÿÙÊÅÿ;36ÿÿÿ%#&ÿ!ÿ!#&ÿ)-/ÿ(*1ÿNQVÿÿ‘‰‡ÿÓÀÀÿн½ÿ¤˜”ÿLC=ÿCD=ÿSWNÿŠ„|ÿœ‹…ÿicaÿZZ]ÿ<DNÿ7DUÿ7G[ÿ1BYÿ:I\ÿ3<Cÿ*02ÿ!')ÿ6:<ÿÿ''*ÿ28:ÿ3?Cÿ+28ÿ.:>ÿ,78ÿ!#ÿ(,.ÿÚÒÕÿÛÒÒÿáØØÿÞÕÕÿèÙÚÿçÕ×ÿèÖØÿçÕ×ÿôããÿÔÉÎÿxsÿ°­¹ÿzv~ÿ€}ƒÿ³±´ÿ­«­ÿ‚|€ÿ„‹ÿ'&7ÿ%%.ÿljlÿÿñëÿÅŒRÿÀ’eÿÏ–Tÿ“]ÿÉ™bÿȘaÿÅ•^ÿÊ—VÿÈ™iÿ`E ÿ&ÿ" ÿ!(ÿOOLÿÏüÿçÖÖÿ/35ÿ ÿ"ÿ#')ÿ ÿ#)+ÿ08:ÿ(//ÿÿ+./ÿÿ;<6ÿFICÿ)00ÿ#'ÿ#/ÿ#&1ÿ639ÿÑÈÈÿèÖÒÿíÚÔÿößÚÿøßÚÿòÜÔÿóÜ×ÿ÷ÛØÿö××ÿìÔÑÿƱ¯ÿ%ÿ/)1ÿfhoÿ)ÿ!W‘ÿ$;ˆÿ#Lˆÿ½½Ìÿ_X_ÿhWgÿ"'ÿ¢š�ÿ�‹†ÿÝÓÖÿÙÉÍÿ:AAÿÅÂÁÿÞËËÿɽ¾ÿ:76ÿÿ!ÿ'"&ÿ$ "ÿÿÿ #ÿÿÿqgjÿ‹ƒ†ÿž™™ÿtpnÿ«¨£ÿμ¸ÿ.( ÿ/2%ÿǽ®ÿŸ�|ÿ›Ž}ÿ‘ˆ�ÿ]\[ÿNQVÿ9AKÿ5?Jÿ9>Dÿ)1.ÿ/73ÿ>C?ÿ<>;ÿ#"!ÿ.33ÿ'/1ÿ).3ÿ!#ÿ!')ÿ')ÿ+89ÿbdgÿrpsÿmknÿhfiÿ`dfÿX^`ÿTZ\ÿPVXÿQRSÿONUÿffuÿ¯©·ÿxt}ÿˆ…‹ÿ†„‡ÿ©§©ÿŠ„ˆÿz†ÿ%$5ÿ88AÿlnqÿÿôîÿÔ›aÿÌžqÿ¾…Cÿ“]ÿ¿�VÿÄ•[ÿÀ‘Wÿ¿‘Wÿ¿ŒWÿÁ‘Rÿ’lEÿ- -ÿ\SSÿ``WÿÒÇÀÿÝÎÏÿ+13ÿ-28ÿ>@Eÿ%)+ÿ&(+ÿ-35ÿ"*,ÿ$,.ÿÿ,02ÿÿ)+0ÿÿ439ÿ!"ÿ ÿ#+-ÿ&.2ÿ+06ÿ846ÿÔÉÎÿàÏ×ÿé×ÔÿíÙÑÿñÚÕÿñÙÖÿóÚÙÿøÜÙÿó×ÓÿáÉÆÿøãßÿ£™•ÿ63@ÿ%TŽÿ3�ÿ+SŠÿÁÂÍÿWPWÿ'#ÿtxzÿŸ—�ÿ‡‚}ÿÝÓÖÿÞÉÎÿÿ™—™ÿÎÀÁÿØÇÇÿfYTÿÏÉÁÿ('&ÿEB=ÿ‚{uÿ><5ÿ[ZSÿA<7ÿ ÿ -ÿª¢ ÿÎÃÂÿļ¸ÿPNGÿ@D;ÿZTLÿ¶ª¥ÿJC=ÿ,-&ÿ·°¤ÿ‚xjÿ•‹€ÿ”‰~ÿaYOÿ/-*ÿ8;@ÿacfÿbe_ÿSTMÿ21*ÿLJCÿ.,)ÿ242ÿ#**ÿÿ ÿÿ!$ÿ-/2ÿ—�‰ÿ¡”�ÿ£–‘ÿ›Ž‰ÿ•Œ†ÿ‘ˆ‚ÿŒƒ}ÿŒƒ}ÿ„}wÿ*&(ÿaajÿ¶²»ÿ2.6ÿŽ‹‘ÿÿÿ…ƒÿzu�ÿ*):ÿ))2ÿLQVÿÿðãÿÌ�mÿÊšgÿËœeÿÔZÿÆ”[ÿÂ�WÿÁ�XÿÀ“WÿÀ�\ÿÁŒVÿ¾�Sÿ©}KÿF/ÿacaÿÌÅÅÿÝÑÍÿ''ÿÿ$ÿ "ÿÿ'),ÿÿ'+-ÿÿ)+.ÿÿ(*/ÿÿ %ÿ"$ÿ#((ÿ,11ÿ28:ÿ+05ÿ=CKÿ¡¢­ÿ(=Zÿ]f�ÿÙÌßÿðÙÚÿõÕËÿðÙÚÿðÚØÿñÙÖÿîÜØÿïàÛÿíáØÿãØ×ÿ]e…ÿ>Q—ÿ-L|ÿ½ÃÓÿPDGÿNLUÿ(/ÿŸ™�ÿ~uoÿåÙÜÿìÓÒÿRONÿB=?ÿØÉÉÿæÑÌÿš�„ÿËÁ·ÿ*(!ÿ¿¹¯ÿŽ…~ÿwrlÿƾ´ÿ^^Qÿ€zrÿ" ÿ±ª¤ÿàÎËÿ„yxÿ¨£�ÿµ±©ÿ20(ÿ65.ÿ½¼µÿ¤Ÿšÿ#$ÿ™•�ÿqe\ÿunbÿkfZÿythÿ ÿ"ÿÿ>=6ÿ03-ÿMSOÿgegÿbb_ÿFKEÿ)..ÿ"))ÿ*-2ÿÿÿš’•ÿ ˜›ÿ£›žÿ®¦©ÿ³ªªÿ»²²ÿ¼µµÿÄ¿¿ÿÄνÿ[`ZÿXY`ÿ«³¯ÿ+-0ÿ–’šÿ1,0ÿ624ÿwuwÿ‰‰”ÿ$"2ÿ%ÿ-35ÿÿïâÿ¼’jÿ¹�aÿ­‰\ÿ®ƒUÿ·‹_ÿ´‰Yÿ´‹Wÿ·‹Yÿ¼Ž[ÿ·ŠTÿ·‹Sÿ½‰Wÿ©€Vÿ‘y^ÿØÊ»ÿäÑËÿ,-.ÿÿÿÿÿ(*-ÿÿ'),ÿÿ&(+ÿÿ%'*ÿÿ!#ÿ"$ÿ%'ÿ!')ÿ#)+ÿ)/1ÿ,;:ÿ ")ÿ .Gÿ:Ilÿ)9eÿS_„ÿÎÈÖÿßÍÉÿéÐËÿðÔÑÿõÙÖÿõÙÖÿòÖÙÿôÖÔÿëÔÏÿãÛßÿ��žÿÏÇËÿN<8ÿ217ÿ")ÿž˜ŽÿukgÿåÙÜÿðØÕÿ}xxÿÊÂÅÿÙÈÈÿÞÊÆÿŠ…ÿÏÇÃÿwurÿÊƾÿ~wqÿŽŠˆÿÈ¿¸ÿoofÿ¿·³ÿ# ÿ»±­ÿÞÎËÿwuÿONGÿ:6.ÿÁº´ÿ}{tÿ10)ÿ³®¨ÿMLEÿxvnÿ�yoÿwrfÿ~zkÿ{tfÿlf\ÿÿPLJÿSKGÿ!ÿ ÿ.)-ÿ<<9ÿPSMÿ478ÿ#!ÿ"ÿÿÿÿÿÿÿÿÿÿÿPDYÿE>Hÿ`^Yÿ¹§±ÿ.#(ÿž›šÿŸ ¡ÿ#&'ÿ(,*ÿ‰‰’ÿ'%5ÿ'(/ÿ486ÿðæïÿB.&ÿ7+$ÿ4+%ÿ<-'ÿE60ÿ8+ ÿD8)ÿN=0ÿUB6ÿYH8ÿk[Hÿv\NÿƒgLÿƒnQÿ…|uÿáÏÌÿÊÆÈÿ79>ÿ#)+ÿ#+-ÿ,24ÿ'-/ÿ%+-ÿ"(*ÿ "ÿ#)+ÿÿ#%(ÿÿ!#ÿ!#ÿ#%ÿ')ÿ"*,ÿ%-/ÿ)=.ÿho{ÿ'#3ÿ&-ÿ )Aÿ%3Jÿ!2ÿ=8>ÿC?=ÿpljÿ¦žœÿ˾½ÿÕÊÉÿæ×Ñÿí×ÏÿîÓÒÿíØÖÿéÖÌÿÙÉ¿ÿ'$#ÿ(+0ÿ —�ÿXSUÿäÛÛÿìÔÑÿzuuÿÑÉÌÿØÇÇÿÙÆÆÿ# ÿ¿º¼ÿNNQÿƒ�|ÿš–”ÿ›™›ÿËÇÅÿvwqÿÁ¸¸ÿ*&(ÿº±«ÿàÐÍÿ°¨¦ÿÁÀ¹ÿhd\ÿ<71ÿª¨¡ÿSNHÿ64-ÿÀ»µÿ2.&ÿÁ¾³ÿzwkÿ{yjÿyiÿ|vfÿ<:3ÿ495ÿÿ $"ÿÿ" "ÿ(&(ÿ'&%ÿ(&!ÿ750ÿÿ$ ÿJGFÿÿÿÿÿÿÿÿÿ=B>ÿ#'6ÿ\^sÿ�‘Œÿlc]ÿJEEÿ‘”•ÿ3<<ÿFKIÿ‘‘šÿ,ÿ()0ÿ��ˆÿôêôÿWFFÿ%!)ÿ%ÿÿÿÿ ÿ!ÿÿÿÿ !ÿÿÿ2(+ÿÚÎÊÿIRRÿ5=Aÿ5=?ÿ1<=ÿ/79ÿ*24ÿ'/1ÿ')ÿ#%ÿ!#ÿ!#ÿ $&ÿ!ÿÿ!#ÿ%&ÿ)*ÿ!,-ÿ!,-ÿ.5)ÿ7Ieÿ)ÿÿ",Nÿ+4Eÿ " ÿ#ÿ!&ÿ"%&ÿ#&'ÿ(--ÿ053ÿ256ÿ439ÿ<8Aÿ>69ÿXSNÿ†~zÿ´¨«ÿÁ¼¾ÿ¦›”ÿGDJÿäÝÝÿòÛÖÿyttÿÚÒÕÿÙÈÈÿл¹ÿ‚zvÿĸ¹ÿ&!#ÿÂÁÀÿPNQÿ46;ÿ¿½¿ÿ_]_ÿ¼±¸ÿ+')ÿ»²¬ÿÞÎËÿaYWÿ65.ÿÉŽÿgf_ÿ?:4ÿú´ÿ970ÿ®¢�ÿlf^ÿ::/ÿttgÿigXÿ€{iÿwo[ÿtpaÿ.)$ÿ ÿÿÿÿÿÿ ÿ71!ÿ;7!ÿ44!ÿ64,ÿÿ$"$ÿ$"$ÿ!!ÿÿÿÿ!$ÿ -0ÿ7.cÿ´£ÙÿE8kÿQLdÿ%ÿ>AFÿ ÿ-1/ÿ��¦ÿ{y‰ÿ*+2ÿÄ¿ºÿÿòíÿ„rhÿÿÿ^]VÿIGDÿÿÿ"ÿ ÿÿÿÿ)-+ÿ«¦¦ÿßÐËÿ²««ÿ046ÿ*24ÿ+89ÿ*63ÿ/<=ÿ*6;ÿ+37ÿ)22ÿ)54ÿ$0/ÿ$0/ÿ*24ÿ*24ÿ (*ÿ#$ÿ"$ÿ &(ÿ(.0ÿ&,.ÿ,,#ÿ;]ÿ.ÿÿ7pÿ'3Rÿ'%(ÿÿ$#ÿÿ$#"ÿ(&)ÿ##ÿ$ÿ##,ÿ# ÿ(ÿ(#'ÿ&%+ÿ,(0ÿ3,3ÿ.)-ÿ758ÿÕÌÌÿèÖÓÿŽ��ÿ™”˜ÿÔÅÅÿǸ³ÿ®¤ ÿƾ¼ÿ^YYÿ̾ÿ�ŠˆÿGHIÿÇÅÀÿ2*(ÿÌÄÈÿ$$'ÿ¸°¬ÿØÊÇÿÎÁÀÿ„}wÿ"$ÿÊƾÿH<5ÿ¬¬£ÿ¬¬£ÿ0/(ÿ«¬¥ÿ7;3ÿ�’‰ÿ??4ÿDE8ÿqqdÿfgZÿ‘‹ƒÿØÅ¿ÿÞ¿ÿ©‘Žÿ'ÿ) ÿ -ÿ ÿ++ÿ25ÿ14ÿ/3ÿ.0-ÿ234ÿ123ÿ123ÿ*)(ÿÿÿNLOÿ;ÿ¡œ¶ÿfa\ÿ§¢ºÿ?ÿ#"?ÿ[[nÿ382ÿ9=5ÿ %ÿ+(4ÿedjÿÈÂÀÿþïðÿÆ´°ÿ><Eÿ$(0ÿÿÿÿÿ¢�Ÿÿ¯§ªÿÿÿ%**ÿ575ÿµ°«ÿÜÍÈÿàÑÑÿ�††ÿjeeÿ]\[ÿIOKÿ+67ÿ.:?ÿ.6:ÿ*33ÿ*65ÿ&21ÿ".-ÿ&12ÿ"-.ÿ"-.ÿ#./ÿ ÿ#%ÿ%'ÿ (*ÿ/1(ÿ$@[ÿ /ÿ!ÿ ;qÿ$-Kÿÿ#"ÿÿ970ÿJH@ÿLGGÿ.ÿ-Qÿ7cÿ)@jÿ)DÿZTXÿ(%+ÿ 'ÿÿ$"$ÿ(&#ÿæÜØÿïÜÜÿCCFÿkfjÿØÉÉÿ¿²­ÿ·­©ÿľ¼ÿQNMÿÓÊÄÿ½³¯ÿ¨¥¤ÿÊÅ¿ÿ±¥¡ÿļÀÿ--0ÿ·¯­ÿÞÐÍÿ3('ÿ¡œ–ÿTTKÿjj_ÿÀ¶¬ÿ6;/ÿ�¢–ÿA?8ÿ»º³ÿA?8ÿ®©£ÿTTKÿ;>2ÿVYMÿRUIÿNMBÿ×ǾÿôÕÏÿêÏÈÿÖ¿ºÿ©—“ÿH??ÿÿÿÿÿ0-,ÿÿÿ'#%ÿÿÿ-((ÿNIKÿ›•™ÿ ?ÿ§¢Ìÿ¶³¿ÿ®£Øÿ<ÿ ?ÿ)&Cÿbcnÿ:;<ÿ&&)ÿ$#*ÿ,,/ÿÒÊÈÿÿó÷ÿμ¹ÿ)ÿ+ÿLIHÿÿÿÿÿ "ÿÿÿGLLÿ=?=ÿ¿ºµÿìÝØÿðÝ×ÿн·ÿè×ÑÿàÑËÿ«ª£ÿ9@@ÿ/;?ÿ(02ÿ,55ÿ)54ÿ(43ÿ'32ÿ$/0ÿ#./ÿ#./ÿ"-.ÿ&12ÿ+67ÿ*56ÿ'23ÿ,6-ÿ5EYÿ'ÿ!$ÿ-H~ÿ*4Oÿ##&ÿ,(*ÿ/-&ÿXWLÿcbWÿ\XVÿ -'ÿ &Qÿ:|ÿD‚ÿ'9_ÿ²­³ÿ+&(ÿ#ÿ$ÿœœ“ÿ1/(ÿîâÝÿñÛÜÿ97:ÿÊÄÈÿßÌÌÿ¹¬§ÿÁ·³ÿÀº¸ÿRONÿÚÑËÿ¼´°ÿº³³ÿÌýÿÖÈÅÿÎÆÊÿ%%(ÿÌÄÂÿÚÌÉÿ[SQÿ981ÿÁ½µÿ"'ÿ€}rÿ9<0ÿ·¼°ÿ]XRÿ¥ž˜ÿ˜�‰ÿymhÿDD;ÿRUIÿJMAÿEH<ÿaaVÿƸ¯ÿïÓÌÿàÇÀÿåÊ¿ÿð×ÐÿÒÃÃÿ ÿÿÿ%"!ÿ/-*ÿÿ513ÿC?Aÿÿ&!!ÿXSSÿuprÿ‹…‰ÿÿ;ÿ,ZÿAÿ2ÿ-ÿ:ÿ'%Fÿ20@ÿ&%+ÿ''*ÿ()*ÿØÊËÿÿòòÿͼ¶ÿ &ÿ!ÿCA>ÿ%$#ÿÿÿŒ~ÿšŒ�ÿ!ÿ !ÿ:??ÿ575ÿ¿ºµÿðáÜÿíßÜÿãÕÒÿÚÊÇÿáÑÎÿ²«¥ÿ?A?ÿ/:;ÿ.:9ÿ-98ÿ-98ÿ.:9ÿ/;:ÿ-89ÿ.9:ÿ4?@ÿ2=>ÿ.;<ÿ/<=ÿ&34ÿ -.ÿ.$ÿ!%4ÿ*)ÿ08:ÿ%=tÿ(3Lÿ !ÿ)&%ÿ))&ÿJMGÿ:>6ÿ678ÿ!0ÿ;gÿ<€ÿ@ÿ*=gÿŸ›£ÿC87ÿ'%(ÿ+& ÿŸ�–ÿ3.)ÿëÜÝÿïØÙÿ+&*ÿÏÇËÿäÎÏÿ¼¯ªÿÉ¿»ÿ·±¯ÿNKJÿÛÒÌÿ´¬¨ÿÉÀÀÿÖÇÂÿÐÀ½ÿÍÅÉÿ((+ÿÉÁ¿ÿÓÅÂÿÁ½»ÿ9=5ÿ¡˜‘ÿ+2&ÿ´¬¢ÿC=3ÿŽ�‚ÿ ž—ÿ][Tÿ¬§¡ÿB;5ÿ__VÿIL@ÿ`cWÿUXLÿIL@ÿ÷®ÿÔ¹²ÿ¬–Žÿ¿¦ŸÿáÈÃÿÚÁÀÿÓ½¿ÿÿÿ_]Zÿ&$ÿ;?=ÿ,/0ÿ;>?ÿ7:;ÿ9=;ÿ^`^ÿ_`aÿKKNÿÿÿÿ*ÿ-ÿ-ÿ1ÿ7ÿ95Kÿ329ÿDFDÿCECÿÑÈÈÿÿöòÿÁ´³ÿ$ÿÿÿ$ÿ!ÿÿ4)(ÿC87ÿÿÿDFDÿ084ÿùµÿñÜÚÿçÛ×ÿáÕÑÿÝÐËÿÙÍÆÿž—‘ÿ# ÿÿÿ"#ÿ ÿ #ÿ""%ÿ%)+ÿ%+-ÿ&,.ÿ*02ÿ,02ÿ28:ÿ%23ÿ&12ÿ*/-ÿ*1ÿ%0)ÿ%'.ÿ$?uÿ)1Kÿ$"$ÿ'()ÿGGDÿTUOÿRUOÿ&(+ÿ$@ÿCoÿ2|ÿ&G�ÿ#>mÿ¸§§ÿ0/5ÿ+&!ÿ31.ÿ ›•ÿ4,(ÿëÜÝÿïÙÚÿ,)(ÿÖÍÍÿÛÌÌÿ{soÿ×ÆÆÿ°««ÿJJMÿÛÓÑÿº¯®ÿÊ¿¾ÿŸ·ÿƼ¸ÿÉ¿Èÿ,(*ÿÀ¼ºÿztrÿ±¬§ÿ=82ÿŠ�zÿNLEÿe^XÿŒ†~ÿDA6ÿ¡ ™ÿ./(ÿª©¢ÿ,+$ÿ^`Wÿ@D;ÿCG>ÿAE<ÿX_Sÿ¥ž’ÿɯ¦ÿŪŸÿʲ©ÿʲ©ÿÇ°¤ÿʳ§ÿ;/+ÿ>:<ÿ ÿ-*)ÿHICÿJKEÿRSMÿRSMÿLHFÿKFFÿÿÿÿÿÿÿ*ÿ+ÿ/ÿ4ÿ!<ÿ,ÿÿ%$#ÿˆƒ‡ÿÿóïÿ·«®ÿÿÿuppÿ=88ÿÿÿ&ÿÿÿÿJIHÿ4<8ÿû¹ÿêÛÛÿàÑÒÿâÐÔÿÙÈÈÿÓÃÀÿŸš”ÿÿÿÿÿÿÿÿÿÿÿÿÿÿ -.ÿ#+-ÿ(+,ÿ*/ÿ%+'ÿ,.6ÿ$Awÿ%+Eÿ#!ÿ$&$ÿ?=6ÿQQHÿ]^Wÿÿ$DÿDnÿ3zÿ(I’ÿ;kÿ»¦¢ÿ $,ÿ% ÿKKHÿ¡œ–ÿ:0,ÿåÖÖÿðÚÛÿ641ÿØÐÎÿÞÏÏÿš–”ÿÞÏÐÿ¥¡£ÿJLOÿÐÉÉÿ¬¦¤ÿÔÎÌÿÀº¸ÿļ¸ÿ½³¼ÿ2--ÿ20-ÿHFHÿ››˜ÿ˜–‘ÿ=;4ÿ©¥£ÿ3/-ÿ¯¬§ÿ@>7ÿœš•ÿ9:4ÿuvpÿ'("ÿEIAÿ6:2ÿDH@ÿBF>ÿFLDÿTPHÿÊ·¯ÿʲ©ÿɱ¨ÿé ÿ¼¡–ÿÕ¸¬ÿ¿¬¢ÿC73ÿÿGBHÿÿÿ%!#ÿB>@ÿ?75ÿ£ššÿÿÿÿÿ - ÿ%ÿ3ÿ2ÿ/ÿ(ÿ4ÿ&#0ÿ42-ÿ42+ÿPUSÿÿðìÿ±¥¨ÿ!ÿÿ% ÿuppÿÿÿª££ÿ²««ÿÿÿÿ!)&ÿ±®­ÿÁ¼¼ÿw|�ÿIQUÿCKMÿBKKÿJOIÿÿÿÿÿÿÿÿÿÿÿÿÿ!ÿ -.ÿ"*,ÿ#)+ÿ%,ÿ#%#ÿ%&1ÿ&B{ÿ$>ÿ'#!ÿ560ÿGE=ÿVVKÿMOFÿ!#!ÿ,Iÿ Kuÿ 6}ÿ&G�ÿ9iÿ±œ˜ÿ!ÿ&!ÿSSPÿœ—‘ÿ@62ÿîßßÿïÙÚÿ0.+ÿÙÑÏÿßÐÐÿ{yvÿÛÍÎÿŸ�ŸÿEIKÿÓÐÏÿ­«¨ÿÕÓÐÿ¼º·ÿ£ž™ÿ©Ÿ¨ÿ4//ÿÿ58=ÿ##ÿÿ8:7ÿ3/1ÿÿpmlÿFDAÿ('&ÿ464ÿ¢¤¢ÿ#%#ÿ_a^ÿJLIÿAC@ÿ?A>ÿY[XÿNNKÿa\Wÿ™�ˆÿ·¥¡ÿÈ´°ÿѸ³ÿѵ®ÿÍ´§ÿTC=ÿ#!ÿUOWÿxrzÿxq{ÿ~w�ÿ®§±ÿ¨ŸŸÿ¯¦¦ÿÿÿ ÿ ÿ#"3ÿ.ÿ-ÿ"ÿ%ÿ ÿ ÿ410ÿ?>3ÿKH<ÿ86/ÿÿñíÿªž¡ÿ!$ÿÿ…€€ÿ¶±±ÿÿÿÿ+$$ÿÿÿhbfÿÿš�žÿ:=>ÿ.??ÿ1BBÿ4FDÿ:LHÿJSLÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿ"/0ÿ"$ÿ"*.ÿ'ÿ" ÿ)ÿ!:uÿ$&Aÿ*% ÿQQFÿ;;.ÿXYLÿ14(ÿ ÿ/LÿJtÿ 6}ÿ*K”ÿ"?oÿį«ÿ ÿ&!ÿttqÿ¨£�ÿI?;ÿêÛÛÿòÜÝÿ" ÿŸ—•ÿÖÇÇÿ¹¹¶ÿÛÏÐÿ˜™šÿV\^ÿÏÈÈÿº²°ÿÚÒÐÿº¸ÿ»³¯ÿ¥›¤ÿRMMÿ" ÿ$ÿÿÿÿ -ÿÿÿ+)+ÿ++.ÿ ÿÿÿ$%&ÿ567ÿ>?@ÿKLMÿ(&)ÿÿ,11ÿfhfÿPTRÿ<>;ÿWRMÿl`[ÿslÿrjhÿÿPJNÿ!"ÿ -ÿ,&.ÿlfnÿ\SSÿ­¤¤ÿÿÿÿÿ"+ÿÿÿÿ¢��ÿ¦žœÿJHAÿFD=ÿNICÿRLDÿwsÿÿúúÿ¼±°ÿ'""ÿ$ "ÿ$ÿ�Š‰ÿ -ÿÿ²¨¤ÿ·«§ÿÿÿÿ $"ÿ––“ÿ_bcÿ4BAÿ8FEÿ:IEÿ>MHÿCOFÿÿÿÿÿÿÿÿÿÿÿÿÿ!!ÿ&21ÿ"))ÿ%,,ÿ,ÿÿ!ÿ!;tÿ8ÿ'&%ÿ+-*ÿ4;4ÿ589ÿ/3+ÿ160ÿ1Sÿ+V„ÿDŽÿ.M•ÿ8Qtÿ«˜˜ÿ"ÿÿ|{tÿ¢š–ÿ`TWÿå×ØÿëÜÝÿ.*(ÿÀÁ»ÿ°©£ÿ¨¡¡ÿÜÍÑÿ†‹‹ÿajjÿÕÔÍÿ½ºµÿßÙ×ÿËľÿ¼·²ÿ�ˆŠÿ`]\ÿ321ÿÿÿÿÿÿÿÿ&$&ÿ!ÿÿÿÿÿÿÿÿÿ.ÿ - ÿ"ÿ%-ÿ'-5ÿ6;9ÿTVSÿURMÿTPNÿÿQNTÿ.+1ÿ"#ÿ.%,ÿnioÿMDDÿ®¥¥ÿÿÿ -ÿÿ¬§§ÿ|xzÿ868ÿ00-ÿ––�ÿ¡œ–ÿLJCÿÿ#!#ÿ(##ÿ·µ¸ÿÿôñÿ¡–•ÿÿÿ743ÿ¶³²ÿÿÿÿÿ ÿ"ÿwpwÿ$ ÿŠ�‰ÿy~|ÿ5A@ÿ9BBÿ9C@ÿ;FAÿBNEÿÿÿÿÿÿÿÿÿÿÿÿÿ !ÿ".-ÿ ''ÿ,41ÿ$ÿÿ  ÿ2kÿ5ÿ@?>ÿ@B@ÿ+0*ÿ"ÿ64-ÿ796ÿ6Yÿ)W„ÿF�ÿ+J’ÿ9Roÿ±Ÿ¡ÿÿ& ÿŠ‹~ÿ¥Ÿ—ÿhZ[ÿêÙÙÿèØÜÿ946ÿyyvÿÕÉÄÿ¥žžÿØÌÏÿ�’’ÿ|ƒƒÿÈÆ¿ÿ½¸³ÿà××ÿÊÁ»ÿ¿·µÿŠ……ÿqnmÿ.-,ÿÿÿÿÿ -ÿÿÿ$"$ÿÿÿÿÿÿÿÿÿ+ÿ%Eÿ1ÿ-ÿXIbÿdiuÿdiiÿVXUÿ…ƒ~ÿQMKÿÿRNVÿ~„ÿxÿ€w~ÿ¶±·ÿ…||ÿ¦��ÿÿÿ!ÿÿ­§¥ÿ†�…ÿ;9<ÿ/.-ÿ††}ÿ�š•ÿIE=ÿÿÿ4-'ÿ¾¸¼ÿÿôðÿ}vvÿ!ÿÿˆ„‚ÿª§¦ÿÿÿtihÿnfdÿÿÿ/'*ÿ ÿ6=3ÿ:B>ÿ&--ÿ#&'ÿÿ).*ÿFPGÿÿÿÿÿÿÿÿÿÿÿÿÿ!"ÿ#/.ÿÿ+30ÿ%ÿÿ)ÿ1hÿ/3HÿHFCÿ$$!ÿ-+#ÿ:03ÿ93+ÿ?=:ÿ$@bÿ,W…ÿF‘ÿ*K“ÿD_wÿ·¥©ÿÿ"ÿ��~ÿ£ ”ÿxpnÿÁµ¸ÿÒËÕÿ&ÿ8;<ÿµ¨£ÿ©¤¤ÿÙÏÒÿ}‚‚ÿ›žŸÿÊÅÀÿº´²ÿÜÒÕÿȾºÿÎÆÄÿ~yyÿ‰†…ÿÿÿÿÿÿÿÿ?@Aÿ ÿ'%(ÿ%#&ÿ !ÿÿÿÿ -ÿÿ%=ÿ!Qÿ@ÿ4ÿ/ 9ÿinzÿdiiÿhjgÿ‰‡‚ÿRNLÿ$#ÿ<8@ÿFEKÿ -ÿ:18ÿŒ‡�ÿcZZÿ¢™™ÿÿÿÿÿª¤¢ÿ4/3ÿÿ'&%ÿvÿ}zuÿ?60ÿ+&!ÿÿVLAÿËÁÄÿÿöðÿUOSÿ5:Fÿ(%+ÿ$ ÿ±®­ÿÿÿaVUÿcYUÿÿÿ*ÿ()"ÿ•”‰ÿ‡ˆ‚ÿ%,,ÿ&&ÿ&#ÿ*2.ÿJVMÿÿÿÿÿÿÿÿÿÿÿÿÿ"#ÿ'32ÿ ÿ-52ÿ ÿÿ!,ÿ0eÿ!3ÿ!ÿ,*%ÿ<:+ÿ'"ÿJG<ÿ‚ˆ„ÿ#Bdÿ,W…ÿ@‹ÿ-N–ÿIg}ÿÀ®²ÿ$ÿ#ÿ���ÿžœ•ÿŒŽ“ÿ™¤«ÿ—£²ÿGXeÿ:FJÿŽ†‚ÿ¨¥¤ÿÝÕØÿ“˜˜ÿ©ª«ÿÁ¿¼ÿº¹¸ÿØÓ×ÿº¶´ÿÉÂÂÿsnnÿ…‚�ÿ/.-ÿÿÿÿÿ -ÿX[\ÿQTUÿ"%&ÿ !ÿ$"%ÿÿÿÿÿÿÿ&>ÿ#QÿBÿ <ÿ.:ÿafrÿY^^ÿkmjÿ•“ŽÿQMKÿÿ,(0ÿ#ÿ2+2ÿ:18ÿ~yÿTKKÿ©  ÿÿÿÿÿ¥Ÿ�ÿÿÿÿ��xÿ™–‘ÿ<86ÿ&"$ÿÿSMCÿÀ½¼ÿÿõòÿ@:>ÿ#ÿÿxzwÿ¼µµÿÿÿ&ÿÿÿ"ÿ‹††ÿ*+$ÿ�”�ÿƒ�|ÿ/74ÿ(-+ÿÿ-3/ÿSYQÿÿÿÿÿÿÿÿÿÿÿÿÿ"''ÿ,55ÿ ÿ57?ÿÿÿ'ÿ$6nÿ/ÿ&*"ÿ-0*ÿ6-&ÿ;66ÿmpqÿFOOÿ0QcÿP†ÿ;sÿ8Ozÿ\hwÿº²¶ÿ"#ÿ ÿ��†ÿ¢Ÿ”ÿS`kÿKlƒÿGk€ÿ!BXÿ!6Bÿ)+)ÿŸ¡žÿÃÆÇÿ„‰ŽÿÃÄÅÿ¿¼»ÿZ]^ÿ¾ÃÃÿ>ABÿÍÉËÿaY\ÿ—�’ÿÿ%%(ÿÿÿÿÿ!ÿ##&ÿ((+ÿÿÿÿÿÿÿÿ!ÿ0ÿ!KÿAÿ;ÿfOyÿsp}ÿ*56ÿ +ÿ}zyÿGDCÿÿ-(,ÿGBHÿE;DÿC4?ÿ„|†ÿaSTÿ¡™�ÿÿÿÿÿ—‘�ÿ - ÿÿÿef`ÿkifÿ567ÿ!ÿÿTRJÿ½º¹ÿÿø÷ÿLDHÿ%$*ÿ ÿ/40ÿ¿¶¶ÿÿ$$'ÿ³«©ÿºµ·ÿÿÿÿ#ÿ¡–�ÿ€~yÿ4<8ÿ9?;ÿ-3/ÿ5;7ÿ]`Zÿÿÿÿÿÿÿÿÿÿÿÿÿ!((ÿ1::ÿÿ--8ÿ#+!ÿ#"ÿ%-ÿ-eÿ65Fÿ782ÿ?A>ÿ382ÿ™¥¤ÿ™¥©ÿnuuÿOecÿ3Yyÿt|�ÿˆ€~ÿ†��ÿ¬¦ªÿÿÿ�Žˆÿ�˜ŒÿHYfÿGmˆÿ¯ÏåÿtŽ£ÿDT^ÿ„„�ÿ™š”ÿ'-/ÿ05:ÿ°®°ÿÿÁÿdiiÿ\hgÿt{{ÿ„‰‰ÿ‘�‘ÿ¨ £ÿÿÿÿÿÿÿÿ ÿ!ÿ"ÿÿÿÿ -ÿÿÿÿ6ÿ#Pÿ%Jÿ7ÿeO|ÿ~y…ÿÿ'ÿÿURQÿ($&ÿ0+/ÿ'#%ÿ"ÿ2%*ÿypwÿA65ÿ`VYÿÿÿÿÿ•��ÿÿÿÿ]^Xÿžž›ÿ123ÿÿÿKJCÿ‡„ƒÿÿø÷ÿC;?ÿ$ÿÿ%%"ÿ±¥¦ÿÿÿÿÿÿÿ’��ÿEIAÿ¢—�ÿ}xÿ\e^ÿfmeÿ`g_ÿah`ÿdh`ÿÿÿÿÿÿÿÿÿÿÿÿÿ&--ÿ4==ÿÿ30<ÿ!(ÿÿ ÿ)aÿ'ÿ'!ÿÿ4KJÿ…¡¤ÿdx|ÿMVVÿRihÿ3Xwÿqr}ÿ—€mÿ…wnÿ¨ žÿ!"ÿÿ�Š…ÿ¨¡•ÿ‘¢¯ÿ%Oiÿ³ÏäÿµÊÜÿ'ÿŠ…ÿƒ€{ÿ"$ÿY[`ÿ¿»½ÿ½¹»ÿ,11ÿ4@?ÿ4==ÿLXWÿ$'(ÿ”Œ�ÿÿÿÿÿÿÿ!ÿ!ÿCCFÿ**-ÿ #ÿ**-ÿÿÿÿ ÿÿ!<ÿ%Tÿ'Jÿ25NÿbTzÿ€~‡ÿ -ÿÿ - ÿPMLÿÿ ÿCBHÿVTVÿc\\ÿ¦¢ªÿnovÿÿÿ1%!ÿÿÿ©£¡ÿÿÿ -ÿbc]ÿ››˜ÿ==:ÿÿÿ-.(ÿÿÿúùÿ+#'ÿÿÿywtÿ¦—˜ÿÿ)-/ÿ»µ³ÿœ—™ÿÿÿÿEIAÿ¨�–ÿ…ƒ~ÿeofÿ…�ƒÿltjÿgoeÿimeÿÿÿÿÿÿÿÿÿÿÿÿÿ(//ÿ2;;ÿÿ50<ÿ"&ÿ ÿ)0ÿ!6lÿ$ÿ"ÿ!-4ÿŠ¤§ÿ‚�¤ÿ]tyÿFROÿQjoÿ-U|ÿty‹ÿ‘€rÿs`Vÿž’�ÿ!"#ÿÿ’Š†ÿ§�’ÿ™ª·ÿv¢¼ÿ˜ÄØÿ©Íâÿ*;Hÿˆƒƒÿ�˜“ÿ!ÿKJPÿÅÀÂÿ®¦©ÿ:8:ÿ8;<ÿKNOÿ>CCÿÿ‚~€ÿÿÿÿÿÿÿÿÿ==@ÿ"ÿÿ"ÿÿÿÿÿÿ"=ÿ"*Vÿ6ÿ!ÿTLgÿ@>Gÿ+'/ÿ!ÿƒ�~ÿRONÿÿ'"&ÿ -$ÿ#1ÿ25@ÿgmƒÿv� ÿ$6ÿÿ8-&ÿ#ÿÿ­§¥ÿ+(.ÿ#ÿÿbc]ÿÿ31,ÿÿÿ)-+ÿÿùíîÿ'"ÿÿÿÿšŽ‘ÿ(%+ÿ()*ÿ1)'ÿ*%'ÿÿ" "ÿ~yyÿ[VPÿ£š“ÿ”’�ÿnunÿ‘–�ÿz}wÿnunÿrsmÿÿÿÿÿÿÿÿÿÿ  ÿÿÿ'30ÿ497ÿÿ8>@ÿ!ÿÿFN^ÿ$-\ÿ&ÿ ÿ&43ÿ†›�ÿs‰‹ÿawuÿ[d]ÿ^upÿ.Ozÿx|~ÿœ‡‚ÿgZMÿŠ‚~ÿ !ÿ/1/ÿ‡Ž‚ÿ©•�ÿPXbÿd”©ÿy¨Àÿ›Íèÿ[|“ÿ¼·½ÿ‚vwÿ !ÿ;>?ÿÏÉÇÿ¨¡¡ÿ1/1ÿ//2ÿ*)/ÿ\XVÿÿCBHÿ ÿ"ÿ "ÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿ#Cÿ0ÿÿÿ)%.ÿ'$*ÿ0-3ÿ.,/ÿ1/1ÿ&$&ÿÿB=?ÿ"%>ÿJQgÿ,ÿ#3MÿJVuÿ ÿ!ÿa\JÿC>9ÿÿ¢�Ÿÿ*$,ÿÿÿILFÿPOHÿ¬¢žÿÿÿ(&)ÿ0.0ÿÿóòÿ( #ÿ$!'ÿ!ÿ?A>ÿtinÿ -ÿ%&'ÿ5*)ÿ'!%ÿÿÿ[VVÿg`Zÿ š’ÿ¥£žÿ€…�ÿœ�—ÿ’�‹ÿvysÿxxuÿÿÿÿÿÿÿÿÿÿ#!#ÿÿÿ'62ÿ8<:ÿÿ/;8ÿ%"!ÿ60&ÿ&,<ÿ'Pÿ#ÿ"ÿT[[ÿTggÿtŠ‰ÿ{Žˆÿ`jaÿYpkÿ.K{ÿw|zÿ™ƒ�ÿuk`ÿvpnÿ*+,ÿ02/ÿ�Žƒÿjb`ÿ '2ÿq¨Àÿƒ±Íÿb–·ÿy¢Àÿ³³¼ÿnbcÿ$"$ÿ.20ÿÏÉÇÿŸššÿ,*,ÿ¦¦©ÿ*,1ÿ±­«ÿÿbcjÿ'$1ÿ<9Eÿ!")ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ#Aÿ - -ÿ ÿ(#%ÿÿÿ$"%ÿ !ÿÿ" "ÿjfhÿ&!#ÿÿ#ÿÿ%0ÿ&:ÿ9=Eÿ'"ÿ5/'ÿlkjÿ -ÿ¤¢Ÿÿ50+ÿ!ÿÿ>C?ÿLJEÿŹµÿGLJÿ./0ÿÿÿÿôñÿ94:ÿ$ÿ&!%ÿ)+(ÿ}rwÿÿŠ‹Œÿ²§¦ÿpjnÿÿÿÿwpjÿ›•�ÿ¸¶±ÿ½½ºÿÁ¾¹ÿ©¡�ÿœš•ÿœš—ÿ%"!ÿ ÿÿÿÿÿÿÿÿ  ÿÿÿ*95ÿ7;9ÿÿ.62ÿ'"&ÿ'&ÿ$)5ÿ&Kÿ!ÿ?;9ÿ„‰Žÿ—¬®ÿ�–˜ÿx†…ÿemiÿ]toÿ$Aqÿy~|ÿ•}ÿwmbÿHB@ÿ)*+ÿ#%"ÿŸ�‹ÿ#'ÿ6_rÿ[�¨ÿe“¯ÿ]‘²ÿP}›ÿª°ºÿ_UXÿ,*,ÿÿÐÊÈÿ ››ÿÿ°°³ÿBDIÿ²°³ÿÿsuxÿÿ"$ÿ%)+ÿÿÿÿÿÿÿÿÿÿÿÿÿ -ÿÿ&<ÿ%ÿÿ% $ÿÿÿ,*-ÿÿÿÿMIKÿ)$&ÿÿÿÿ!"ÿÿ ÿ,)(ÿÿdZmÿ*ÿŒ€•ÿ�v}ÿE<<ÿ!ÿ<@>ÿ020ÿÏÄÃÿ053ÿGHIÿ ÿÿÿøóÿA=FÿSXjÿÿ$$!ÿodiÿÿÿ(ÿÿÿÿ�ŠŠÿxrÿ�—�ÿ­«¦ÿÒÐÍÿØÐÌÿ×ËÇÿ­¨£ÿ«©¦ÿÿÿÿÿÿÿÿÿÿÿ987ÿ$#"ÿ)84ÿ597ÿÿ/40ÿ%"(ÿÿ"ÿ;ÿ!ÿ[YVÿ‹˜�ÿ‰£¦ÿ…™�ÿemoÿXb_ÿWolÿ%Brÿx}{ÿ‹usÿoeZÿOIGÿ$%&ÿ#%"ÿ�”�ÿ]lqÿ.Eÿ+Cÿ}¥ºÿ›Ëçÿ¡Ìäÿ¼ÀÂÿPGGÿ)')ÿ`dbÿÎÈÆÿ™””ÿÿ»»¾ÿJLQÿ¸·¾ÿÿ`cdÿÿ!ÿ&!!ÿÿÿÿ" #ÿÿÿÿÿÿÿÿÿ - ÿÿ3;Kÿÿÿÿÿÿ$"%ÿÿÿÿÿÿÿ -ÿ ÿÿÿÿÿ~igÿ}brÿH.IÿS=WÿB6?ÿ�‚�ÿVQQÿ9;>ÿ-/4ÿÎÂÃÿ.31ÿLMNÿÿÿÿùúÿ'&-ÿ*/;ÿ54:ÿ(" ÿWQUÿ!ÿ–‘“ÿ´¬ªÿ>9=ÿÿÿÿ€~wÿ•“‹ÿ¼ºµÿ×ÑÏÿÛÐÏÿ×ÌËÿ·¶ÿ­©§ÿ$! ÿÿÿÿÿÿÿÿÿÿÿ#!ÿ/74ÿ8=;ÿ!ÿ48:ÿ!&ÿÿÿ,ÿ"#ÿCXRÿy�—ÿ–±¼ÿ|˜ ÿ^xƒÿCWeÿHeqÿ2Gdÿy{yÿ–„vÿpeZÿKGEÿBEFÿ162ÿŽ�ˆÿzwvÿ&ÿAZqÿ�°Âÿ™ÅÙÿŒ·Éÿª¹¹ÿ854ÿ9>>ÿdigÿÍÉÇÿ�ŠŠÿÿŽŽ‘ÿachÿ¦¤§ÿÿ034ÿ%"!ÿ’†�ÿd_Yÿÿÿÿÿÿÿÿÿÿÿÿÿ - ÿÿPOUÿHGMÿÿÿ -ÿÿÿÿÿ ÿÿÿFBJÿ?=Fÿ::Eÿÿ2)0ÿ@5:ÿ‰~ƒÿXGQÿi]lÿdZkÿwn{ÿohoÿ£ž ÿ�—•ÿJGBÿUSUÿÖÊËÿ[SQÿJCCÿÿÿÿôôÿ,')ÿ %ÿ!ÿ.&$ÿLFJÿ# &ÿ&!ÿ*" ÿÿÿÿvsrÿƒ‚{ÿ˜˜�ÿ¼ºµÿØÐÎÿÞÓÒÿÙÎÍÿź¹ÿª¦¤ÿGDCÿÿÿÿÿÿÿÿÿÿÿ#!ÿ164ÿ386ÿ" ÿ861ÿ$"ÿ"ÿÿ(ÿ07Uÿ1Uÿ 6\ÿ/Twÿ;j�ÿ-Z‚ÿEoÿ,Uyÿ.Hoÿ|ƒ‰ÿž��ÿl`WÿEA?ÿ.12ÿ*/+ÿ_cZÿ�zÿ]fmÿY|“ÿož¶ÿŸÁÛÿƒ¥¹ÿ¡¦«ÿ3,,ÿ456ÿUZXÿ~€}ÿlkjÿ),-ÿ ¤¦ÿ^chÿÂÀÃÿÿÿÿ#!ÿ¸¯©ÿ‹||ÿÿÿÿÿÿÿÿÿÿÿÿÿÿIGJÿÿÿÿÿ !ÿ" #ÿ#!$ÿÿDBEÿÿÿÿÿÿ'#+ÿ1.4ÿ839ÿNHPÿaZdÿÿÿ ÿB=Aÿ­¨ªÿ²ª¨ÿ{ojÿleeÿ‹‚‚ÿpggÿleeÿ\WWÿC>Bÿÿðìÿ;44ÿ)*+ÿMGEÿ5-+ÿ604ÿÿYQTÿc[Yÿ'"&ÿ"ÿ&$&ÿ632ÿ�Ž‡ÿ˜˜�ÿĽÿÙÑÏÿ×ÌËÿÚÏÎÿź¹ÿª¦¤ÿOLKÿÿÿÿÿÿÿÿÿÿÿ"&$ÿ8=;ÿ053ÿ#(&ÿ597ÿ)ÿ 2ÿ 7ÿ2ÿ+<jÿ9vÿ)K}ÿ'P�ÿ>lžÿ,ZŒÿ2[ŒÿEh�ÿNf�ÿLT^ÿ—�‚ÿwkbÿ820ÿ?@AÿHHEÿjneÿjnfÿuƒ†ÿ;]qÿ}¯Äÿ Çàÿx¢²ÿu„„ÿ„{{ÿC?Aÿ# ÿ-3/ÿCHFÿuzzÿ¸ÀÂÿ#ÿ½»¾ÿÿÿÿÿ·©¦ÿ›€†ÿÿÿÿÿÿÿÿÿÿÿÿÿÿ!ÿÿ -ÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ202ÿÿ¡œœÿ�„ƒÿh\Wÿf]]ÿ`\^ÿ^Z\ÿJFHÿQMOÿRPSÿÿòóÿ*%)ÿ ")ÿB>@ÿC;9ÿ5/3ÿÿ“‹Žÿš’�ÿ*%)ÿÿÿ)&%ÿ�Ž‡ÿ••ŒÿĽÿÖÎÌÿÕÊÉÿÚÏÎÿÍÂÁÿ¡�›ÿ'$#ÿÿÿÿÿÿÿÿÿ#!#ÿÿ$(&ÿ9><ÿ/42ÿ$)'ÿ;;8ÿ#-ÿ6F`ÿCOjÿ5:Sÿ0:Nÿ=O]ÿ,<Lÿ',>ÿ+2@ÿ:DOÿ^bjÿhgfÿngoÿ€ysÿ„zoÿsd^ÿŸ—•ÿOMOÿIGDÿÿÿ#%(ÿ>JSÿ-2ÿObnÿŽ¨µÿ%%ÿ% ÿ<?@ÿHMKÿVVSÿMLKÿLMNÿ²´·ÿ ÿ´¯³ÿÿ"#ÿÿ!ÿ¹µ³ÿXSWÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿ73;ÿ2.7ÿ"ÿÿÿÿÿÿ -ÿ !ÿÿÿÿÿÿÿÿÿÿÿÿÿQORÿÿnopÿfdaÿ…€zÿTSRÿLPRÿEIKÿHHKÿJHKÿGEHÿÿøûÿ"%ÿÿÿ<64ÿ ÿ#!ÿ.ÿ'ÿ"ÿÿÿ@ABÿˆ†ƒÿ›•�ÿǽÿÖÏÏÿÝÔÔÿÛÑÍÿÑÅÁÿž——ÿÿÿÿÿÿÿÿÿÿ0.0ÿÿ%*&ÿ275ÿ388ÿ$*&ÿ<80ÿ($ÿolgÿb\Tÿuqÿlc\ÿmh\ÿpj`ÿujcÿrf]ÿsf[ÿj\SÿRNLÿRNPÿ]XSÿmd]ÿj^aÿE:?ÿÿ.*,ÿÿÿ$#"ÿÿ4%ÿ'ÿWRTÿ{sqÿ% ÿ%$*ÿ&*,ÿ #ÿ(&)ÿÿhgmÿ %ÿœž¡ÿÿÿÿ#ÿÄÁÀÿhgmÿ# &ÿÿÿÿÿ+,-ÿÿ $ÿÿÿ536ÿ - ÿÿ1.4ÿ84<ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ -ÿÿ84<ÿ+(.ÿ'),ÿrvtÿRTRÿJMNÿDHJÿDFIÿCEHÿFFIÿFHKÿûóöÿ'"(ÿ! &ÿŽ‰‰ÿuomÿ*%)ÿÿ½·µÿ½µ±ÿÿÿÿÿ’��ÿž•ŽÿÊÅÀÿÖÏÏÿÝÔÔÿÜÒÎÿÒÆÁÿ ——ÿÿÿÿÿÿÿÿÿÿÿÿ$)#ÿ5:8ÿ.33ÿ&,(ÿ45/ÿ,)$ÿKF@ÿIC;ÿcYUÿYQMÿJE@ÿ961ÿ0,.ÿ$"%ÿÿÿÿÿ,%ÿ€vlÿg[\ÿb\Zÿifaÿ@=<ÿÿÿ42/ÿ'ÿJ3'ÿ9%ÿʽ¼ÿƒyuÿ ÿ,*,ÿ3::ÿHKLÿ)*+ÿabcÿ}~ÿÿ³µ¸ÿ ÿÿÿ)&!ÿ½¸¸ÿ`Zbÿÿ27<ÿ8:?ÿ"ÿ(*/ÿ@ABÿÿ'#+ÿÿ - -ÿ203ÿÿÿ"ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿ,*-ÿ-+.ÿRPSÿIJKÿEHIÿDGHÿCFGÿ?ADÿ>@CÿACFÿBDGÿ@BEÿøðóÿGBHÿ+*0ÿÿogeÿ$#ÿ "%ÿ ÿ!ÿÿÿÿ.,.ÿ�ˆˆÿž•ŽÿÏÊÅÿÒËËÿ×ÎÎÿÜÒÎÿÖÊÅÿ ——ÿ$!ÿÿÿÿÿÿÿÿÿÿÿ',&ÿ7<:ÿ*//ÿ%+'ÿ/1.ÿ(&#ÿ<94ÿD?9ÿG?=ÿÿ#ÿÿ3*$ÿD<8ÿRMMÿh_YÿfZQÿqf[ÿzm`ÿ…whÿyqgÿfcXÿlk`ÿ530ÿ !ÿ" "ÿ($"ÿ-ÿF+ÿ8!ÿÔÆÃÿ”ŒŠÿÿ]_\ÿalgÿZ`\ÿ_eaÿiokÿ]c_ÿ=C?ÿJOOÿÿÿÿ74/ÿLGGÿ "ÿÿ49>ÿ\^cÿYV\ÿ027ÿPQRÿÿ $ÿÿÿÿÿ !ÿÿ$!'ÿÿ!ÿÿÿÿÿÿÿÿÿÿÿÿÿÿ $ÿÿ#'ÿ567ÿSUSÿegeÿJLJÿJLOÿDFIÿACFÿ>@CÿBDGÿ?ADÿ;=@ÿ>@Cÿ99<ÿúòõÿ4/5ÿ$#)ÿojjÿ–’�ÿÿ-(,ÿ •”ÿ‹{ÿÿÿÿÿ•��ÿž•ŽÿÏÊÅÿÖÏÏÿØÏÏÿÔÊÆÿØÌÇÿ�””ÿÿÿÿÿÿÿÿÿÿÿÿ',&ÿ9><ÿ*//ÿ&,(ÿ54-ÿ/*$ÿKE=ÿ[SIÿsjÿMA8ÿE;1ÿME;ÿpcVÿ!ÿ/+-ÿOD=ÿreXÿ}pcÿ}rgÿ†{pÿph^ÿebWÿrphÿ624ÿÿÿ-("ÿ:(ÿbB,ÿH/ÿ¾¯ªÿia_ÿ1-/ÿcgiÿalmÿY_aÿTZ\ÿ7=?ÿ;ACÿ,24ÿOSUÿÿ - -ÿ !ÿ<94ÿ�ˆˆÿ!#ÿ# &ÿ16;ÿ^`eÿÿ ÿJKLÿ #ÿ ÿ&$'ÿ!"ÿÿHFIÿJHKÿÿQNTÿ"ÿ -ÿÿÿÿÿÿÿÿ!ÿÿÿÿÿ%#%ÿ%#%ÿGEGÿusuÿ__bÿNPUÿJLQÿCEJÿACHÿ>@Eÿ<>Cÿ;=Bÿ136ÿ136ÿ469ÿ/14ÿÿÿôõÿ/'*ÿÿ{~ÿ“”•ÿÿ ÿiegÿmlrÿÿ&'(ÿÿ,(*ÿ�‹‹ÿ˜”ŒÿÎÍÆÿÔÑÐÿÑÌÌÿÖÐÎÿÊÀ¼ÿ¦š�ÿÿÿÿÿÿÿÿ -ÿ!ÿÿ ÿ(-'ÿ<A;ÿ+0,ÿ+0,ÿ/+)ÿA<6ÿWQGÿh^PÿbPFÿP@6ÿE:/ÿ]SHÿ_RMÿÿÿnicÿlbXÿ{naÿyk\ÿ„wjÿc\Vÿ`\Tÿqlfÿÿÿÿ ÿTA9ÿaC-ÿT7%ÿ�}uÿ�‡…ÿ+$+ÿ`_eÿPTVÿPSTÿLMNÿ ÿ#!$ÿEA?ÿRVMÿ&(%ÿ#ÿÿMF@ÿXPNÿÿÿ(04ÿVX]ÿÿÿDFIÿÿ(ÿDFKÿ-+4ÿ"ÿNLNÿOLRÿÿXVYÿÿÿ ÿÿÿ!ÿÿÿÿ!ÿÿ !ÿ ÿRPSÿoqtÿUY[ÿMQSÿJNPÿCHMÿ?DIÿ>CHÿ?DIÿ@AHÿCBIÿBAHÿBAHÿ=?Dÿ=ACÿ:>@ÿ6:<ÿÿüú÷ÿ+('ÿÿÿ--0ÿÿÿÿ$ÿÿÿ)&!ÿ ÿ�Ž�ÿž˜�ÿÓÎÉÿÓËÉÿÕËÇÿÓÊÄÿËŽÿ£—˜ÿÿÿÿÿÿÿÿÿÿÿ$'!ÿ ÿ@C=ÿ%'$ÿÿÿIG@ÿVSHÿi_Qÿxf\ÿXH>ÿE8-ÿRG<ÿbSSÿÿÿrldÿe[Qÿm`SÿjZJÿsf[ÿUPKÿig`ÿZXQÿÿÿÿÿE61ÿ[>,ÿJ0ÿ–†}ÿ†ÿ$$ÿ)&,ÿbhjÿ|€ÿ‰Š‹ÿÿÿ{wuÿoqhÿbdaÿ ÿÿE@;ÿOIGÿÿÿ"&ÿ9;@ÿÿÿGILÿÿ%ÿPRWÿ61=ÿ#ÿa_aÿXU[ÿÿXVYÿÿ ÿ;:@ÿÿÿÿÿ ÿ*$(ÿJDHÿRPRÿtrtÿ\Z\ÿXVXÿKMRÿGJOÿFINÿBEJÿ?BGÿ;>Cÿ8;@ÿ36;ÿ.05ÿ.-3ÿ.-3ÿ.-3ÿ+-0ÿ+-0ÿ.03ÿ+-0ÿ  ÿóõòÿ<><ÿ!!ÿ�ŠŽÿOMPÿÿÿÿ#ÿÿ !ÿÿÿ�‘‹ÿ¢›•ÿÕÏÍÿÖËÊÿÕÉÅÿÓÊÄÿÍÇ¿ÿž’“ÿÿÿÿÿÿÿÿ%& ÿ25/ÿ@C=ÿBE?ÿ22/ÿ..+ÿ! ÿÿ ÿDB;ÿDA6ÿ\RDÿzk^ÿSD7ÿB3&ÿSB5ÿZKKÿÿ#%(ÿRMGÿmbWÿeXKÿk^Qÿe\UÿRMQÿNKJÿjhcÿÿÿÿÿ*ÿX=,ÿM8&ÿh_Xÿnjlÿ!ÿ &ÿS[_ÿaegÿ‰ˆ‡ÿÿÿ‚€ƒÿ�~ÿccfÿÿÿNLGÿÿÿÿ $ÿTV[ÿÿ "'ÿYZ[ÿÿ('.ÿddgÿ409ÿ#ÿgegÿa^dÿÿWUXÿÿ#!$ÿecfÿ!ÿÿGJUÿ ÿd__ÿ‚}}ÿ]XXÿNLOÿJJMÿOORÿFFIÿ@BGÿBDIÿ>@Eÿ=?Dÿ>@Eÿ9;@ÿ>@Eÿ=?Dÿ==@ÿ??Bÿ>>Aÿ??Bÿ>>Aÿ<<?ÿ336ÿ #ÿÿöòðÿ?::ÿ-+-ÿ''*ÿš˜›ÿÿÿÿÿÿÿÿÿš•�ÿ™”ŽÿÖÙÚÿÏÓÕÿÐÐÓÿÍÈÊÿË¿ÀÿbVWÿGBBÿ�ÿb_^ÿSSPÿBB?ÿ330ÿ..+ÿ8;5ÿ463ÿ+-+ÿ##&ÿÿÿ ÿÿ ÿEC<ÿVSHÿmcUÿ€rcÿseVÿn\Nÿo[Mÿ]NOÿ[W_ÿ(+0ÿEB=ÿg[RÿfYLÿ[PEÿJFDÿ#'ÿÿUURÿÿÿÿÿÿH.!ÿJ8*ÿRSLÿFEKÿ 'ÿ!ÿ^gmÿbglÿhgfÿ ÿ&ÿBDLÿ8:=ÿ-,3ÿÿÿ<A=ÿ -ÿÿÿÿEGLÿÿÿLNLÿÿ# &ÿfdfÿ,(1ÿ#ÿhfhÿ]Z`ÿ# &ÿFDGÿ!"ÿ$"%ÿPJHÿE?=ÿFDGÿÿbdiÿPOUÿLKQÿIHNÿIKPÿFHMÿ?AFÿ@BGÿMLRÿ54:ÿ0/5ÿ-,2ÿ+*0ÿ+*0ÿ*)/ÿ)(.ÿ''*ÿ)*+ÿ)*+ÿ)*+ÿ+),ÿ)'*ÿ*(+ÿÿÿüô÷ÿ'"$ÿÿÿ’�“ÿÿÿÿÿÿÿÿD<8ÿ—‘‡ÿ™˜‘ÿÁÄÅÿ´¹¾ÿ¯³µÿ¶´·ÿÁ¹½ÿeceÿgjkÿ]`aÿ367ÿ$))ÿ!&&ÿ #$ÿ#$%ÿ" "ÿÿÿÿÿÿÿ -ÿ"!ÿ?9=ÿ,&$ÿ^WKÿkaVÿ]O@ÿ|dUÿ~dYÿ-"ÿ(#)ÿ735ÿ>;6ÿeZOÿaWIÿWLEÿ<64ÿÿÿ<?Dÿ=<Bÿ!ÿ!ÿ -ÿ&"+ÿ-"'ÿ%"ÿZ\SÿSQTÿ$ÿ"ÿY\]ÿW\VÿZ\Yÿÿÿ^b`ÿoqoÿddgÿÿ!ÿ?A?ÿ)),ÿÿ!ÿ?=?ÿ ÿÿÿ106ÿÿÿjihÿ"+ÿ )ÿPKOÿLFDÿ*"ÿ( ÿOJEÿhe`ÿ‰…‡ÿXVYÿIGJÿÿILQÿFINÿ<?Dÿ@CHÿ>AFÿBEJÿEHMÿ@CHÿADIÿ?@Gÿ:;Bÿ<=Dÿ9;@ÿ;=@ÿ=?Bÿ/14ÿ+,-ÿ,*,ÿ)')ÿ)')ÿ(&(ÿ(&(ÿ(&(ÿÿÿøðóÿ)$&ÿÿÿ|w{ÿÿÿÿÿÿÿ&!%ÿKECÿ�‹…ÿ‹‰„ÿ"ÿbglÿRXZÿJNPÿ77:ÿ+-0ÿ(*-ÿ$&)ÿÿÿÿÿ -ÿÿÿÿÿÿÿÿÿÿ>8@ÿÿ'#ÿJE9ÿ^RCÿlYGÿu`Tÿ)!%ÿ2-3ÿD@BÿB@=ÿUPJÿQLFÿGBBÿ:59ÿ#ÿÿSX^ÿSRYÿONTÿWV]ÿÿ;8Dÿ3/8ÿ[Y[ÿ[\VÿXVYÿ#ÿÿ[\]ÿ_c[ÿ`b`ÿÿÿ_a_ÿ`b_ÿ^^aÿÿÿEDCÿ647ÿÿ ÿkffÿmhnÿÿ"ÿolrÿ ÿ#!$ÿWUWÿ& $ÿ,$(ÿRMMÿ[VVÿ€{{ÿ…€‚ÿD@Bÿ424ÿ$$'ÿ$ÿ ÿÿ""%ÿ(&)ÿ+),ÿ203ÿ247ÿ79<ÿ9;>ÿ:<?ÿ9;@ÿ8:?ÿ68=ÿ57<ÿ247ÿ,.1ÿ(*-ÿ'),ÿ*(*ÿ(&(ÿ(&(ÿ(&(ÿ'%'ÿ'%'ÿ&$&ÿ(&(ÿÿÿöùÿ ÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿ %ÿ #ÿ(,.ÿ!ÿÿÿÿÿÿÿÿphlÿÿÿÿÿÿÿÿÿÿOKSÿ728ÿ# ÿ=;3ÿWPDÿZPAÿ^WKÿÿÿ869ÿ<;:ÿ>ABÿQSXÿQRYÿ,-4ÿ#ÿÿaflÿhgnÿmlrÿonuÿÿ$ÿ][dÿffiÿghiÿ[Z`ÿÿ ÿccfÿhjhÿefgÿÿÿVWXÿ_a^ÿVVYÿÿÿ@?>ÿ'%(ÿÿ"%ÿgcaÿa\`ÿ ÿ! &ÿGEGÿÿ(&(ÿ^\^ÿzupÿ©¡�ÿwrtÿ[X^ÿTU\ÿNNWÿDFNÿ=CKÿ8;@ÿ9<Aÿ/27ÿ),1ÿ+),ÿ/*.ÿ-(,ÿ-(,ÿ+),ÿ((+ÿ&&)ÿ&&)ÿ&&)ÿ%%(ÿ((+ÿ''*ÿ''*ÿ$$'ÿ$$'ÿ%%(ÿ(&(ÿ'%'ÿ%#%ÿ%#%ÿ%#%ÿ%#%ÿ(&(ÿ" "ÿ-)+ÿüðóÿÿ1),ÿ,')ÿÿÿÿÿÿÿÿÿÿÿÿÿ ÿÿÿÿÿÿÿÿÿ -ÿÿ ÿÿÿÿÿÿÿÿÿÿÿÿ!ÿÿJFDÿUPJÿ#"!ÿÿÿ-,2ÿSTUÿMPUÿVY^ÿ^]cÿ0-3ÿ ÿÿ^ciÿbahÿbagÿcbiÿÿ ÿ^_fÿ`ahÿ`ahÿTV[ÿ!ÿÿedjÿedjÿ_^dÿ ÿ#ÿMMPÿ130ÿ''*ÿ!ÿÿA@?ÿ-+.ÿ $ÿ'$*ÿ@=8ÿB>@ÿ!$ÿ"ÿde_ÿ‚ƒ}ÿ–•”ÿgehÿUY[ÿUX]ÿNPWÿJJSÿHGNÿFGNÿEGNÿAFLÿ>CHÿ@EJÿ>CHÿ=BGÿ>@Cÿ>>Aÿ447ÿ//2ÿ,*-ÿ+),ÿ*(+ÿ*(+ÿ+)+ÿ(&(ÿ)')ÿ(&(ÿ)'*ÿ&$'ÿ%#&ÿ%#&ÿ&$&ÿ$"$ÿ$"$ÿ$"$ÿ$"$ÿ$"$ÿ" "ÿ&$&ÿÿûòòÿ& ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ4*9ÿÿÿÿÿÿÿ -ÿ - -ÿÿ"ÿÿÿÿÿÿ -ÿÿ -ÿÿÿÿÿÿÿ-((ÿEA?ÿ=:9ÿÿÿ)&,ÿRQPÿMQOÿQSPÿRSMÿ'$#ÿ %ÿ"ÿ[][ÿcbaÿ][Xÿgceÿÿ!ÿZZcÿbcjÿhipÿEEPÿÿ!ÿ__hÿddoÿbbmÿÿ$ÿabiÿ^`hÿa_hÿ#ÿ#ÿ>@>ÿ:8:ÿÿ(%+ÿZUPÿ`[Vÿvrpÿda`ÿVX[ÿWY\ÿZ\aÿQSXÿLQWÿJNVÿEIQÿHJQÿEGNÿEFMÿCELÿEGNÿBEJÿ<?Dÿ=@EÿADIÿ=@Eÿ>@Gÿ<>Eÿ<>Eÿ8:?ÿ:9?ÿ,+1ÿ)(.ÿ.,.ÿ*(*ÿ*(*ÿ'%'ÿ)')ÿ%#%ÿ(&(ÿ%#%ÿ&"$ÿ'#%ÿ" ÿ%!#ÿ&!%ÿ#"ÿ726ÿ$#ÿÿúññÿ ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ!ÿÿÿÿÿÿÿÿÿÿÿÿÿÿ# ÿ'$#ÿ!ÿÿÿ !ÿKKHÿMOLÿNRJÿNOHÿÿ!ÿÿVVSÿZZWÿ\YTÿYUWÿÿ ÿ`_eÿ]^_ÿabcÿ=<Cÿÿ"ÿabiÿbbkÿaalÿ ÿ"#*ÿNPUÿSUZÿWRXÿ'#ÿ%$#ÿ[[Xÿ]^Xÿkjiÿ•“•ÿ„€‚ÿYVUÿXX[ÿSUZÿPRYÿNPWÿKMTÿIKRÿKMTÿGIPÿBDKÿDFMÿDFMÿCELÿACJÿACJÿ>AFÿ@CHÿ@CHÿADIÿ<>Eÿ=?Fÿ=?Fÿ>@Gÿ=?Dÿ<>Cÿ=?Dÿ8:?ÿ203ÿ*(*ÿ+)+ÿ(&(ÿ(&(ÿ)')ÿ'%'ÿ$"$ÿ'#%ÿ($&ÿ)%'ÿ)%'ÿ% $ÿÿÿÿÿÿõúÿ/%.ÿG>Kÿ!"ÿÿÿÿÿÿÿÿÿÿÿ - ÿvrtÿIDJÿÿÿÿÿÿÿÿÿ - ÿÿ"ÿÿÿÿÿÿÿÿÿÿÿ!ÿÿ!!ÿ1/1ÿ?=?ÿLJLÿÿÿ%#&ÿQQNÿQSQÿORLÿRROÿÿ#&ÿÿYYVÿUURÿVSNÿXTVÿ ÿÿXWVÿYZTÿXYRÿ%#%ÿ!ÿ ÿ\[aÿ]\bÿa`fÿÿ$$'ÿWXYÿPPMÿWQOÿ^VTÿVRPÿz}wÿ`c]ÿWYWÿVWXÿLQVÿKOWÿJPZÿGJVÿNPXÿJLSÿGIPÿGIPÿEGNÿFHOÿGIPÿDFMÿ>@Gÿ@BIÿ;=DÿCELÿ@CHÿADIÿJMRÿ>AFÿ?AHÿ?AHÿ>@GÿBDKÿ>@Eÿ>@Eÿ?AFÿ>@Eÿ::=ÿ225ÿ--0ÿ''*ÿ+)+ÿ(&(ÿ*(*ÿ#!#ÿ%!#ÿ)%'ÿ" ÿ.*,ÿÿÿÿÿÿùîõÿ>4>ÿ&+ÿ!ÿÿÿÿÿÿÿÿÿÿÿÿÿÿ,'-ÿ!ÿÿÿÿÿÿA?BÿIGJÿÿ#ÿÿÿÿÿ ÿ"!ÿ$#ÿ(#'ÿÿÿ$ÿKOQÿMORÿPPSÿQQTÿTTWÿÿÿ/-0ÿiifÿUVWÿQSQÿQPOÿÿ#(ÿÿXXUÿXXUÿ[XSÿTPRÿ ÿ!ÿXVXÿ[ZSÿ[YTÿ%"!ÿ!%ÿÿ_]`ÿGEGÿ-+-ÿ" "ÿ('&ÿRSMÿy~xÿ‘‘ŽÿojlÿWWZÿRTWÿQSVÿPRWÿNOVÿIPVÿHOUÿDHPÿEFQÿFHPÿGIPÿFHOÿDFMÿACJÿDFMÿACJÿ@BIÿ@BIÿACJÿDFMÿACJÿ>AFÿBEJÿADIÿDGLÿACJÿACJÿ=?Fÿ@BIÿ@BGÿ>@Eÿ?AFÿ>@Eÿ9;@ÿ=?Dÿ<>Cÿ:<Aÿ=;>ÿ757ÿ202ÿ0.0ÿ-)+ÿ&"$ÿÿÿÿ -ÿÿÿÿÿùøÿ!ÿ)#ÿÿÿÿÿ"ÿÿÿÿÿÿÿÿÿÿÿ!ÿÿÿ:76ÿ<:=ÿEDJÿIILÿOORÿ!ÿ#&ÿ"$ÿIFLÿGDJÿDBEÿ97:ÿDBEÿNLOÿQORÿÿÿ)%-ÿTV[ÿUW\ÿUW\ÿ\^cÿ\^cÿÿÿ"!(ÿYX^ÿUX]ÿX\^ÿY[^ÿÿ $ÿÿQSQÿ\ZUÿWVOÿSQSÿÿ"ÿHFHÿ=>8ÿIJDÿ)'*ÿ"&ÿ$#)ÿZ[\ÿ[YVÿ^XVÿ�||ÿ�~}ÿ^_`ÿPTVÿTW\ÿSUZÿRT[ÿNPWÿKMTÿFHOÿCELÿDIOÿHIPÿHGNÿFGNÿJOUÿIJQÿHGNÿCELÿIKRÿHIPÿFGNÿCDKÿBDLÿ@BJÿCELÿFINÿEHMÿDGLÿ@CHÿDGLÿACHÿCBHÿ?>DÿCBHÿACHÿ9<Aÿ;@Eÿ@?Eÿ>@Eÿ:<Aÿ:<Aÿ:<Aÿ;;>ÿ?=@ÿÿ%#&ÿÿ425ÿÿ'%(ÿÿÿÿÿ \ No newline at end of file diff --git a/Lib/test/test.rgb b/Lib/test/test.rgb deleted file mode 100644 index 5fe29940723e2cdbe17ae007549a3b5ac6746771..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcwPel00001 literal 43554 zcwX$hcXV6#l`eX4nPd`Liv&*Z1qZzo06`F)1VDgb@4a`b_uh-uo7H9YZplTGWfe<S zv1IjT*|OvkJDFte+*HT0(=_Y){h&BAS+izl-Sysmf84hose?m+#5sHKZ<p`;odYR8 zRw$qhXf`wi9{>9FZTg{nsBiMrKCx!pP~Sk`sELy%bahRF{{OH44}QJy1cEY~At>uJ z2vT-JkP7S(@Em;%L3lj`5l<nAYJwp8QwU-^Ac*@Mf`o1e5`PXs>OlySe*r<-kr1Q< zd&4LQGX55V%o8BU@(l#pra_SXFA$V78-iTmT<(Ps<oN*v<t>At{1+g|w;F;1N(c(R z1VLdOf+AZXsE~!A=q?C~t0Ac900bos5LA2=f=X-<RC*j_COA;VTM$&04?)%EA*ePC zL3LLks38tPjW-~uxdeh*?m<vn6$G_^070D%5Y+WC1ogB*Q12HI)ZYU^1OEg;LqiZW z{3{3=H5P(Ke+5BfCqvM<KS9uhnGiJbe?rjY`4BYqdk{43MF^Ua2|+VgLC|bq>l|R~ zJYeg5VCzC)>msmU0`@Ngo0kEbm+yn1l^O_IbqIpim>_8Fs}Qu_0YNXFgrJQc2-<WC zg0|#B&{pt#yAy(52K$|E2-*eqdw`F7!Ta_DpAP`v59uK2@LmWS(Fid51cI{L0Y)JH za4WzF;D!Nw@Q)yf1o%+EM+W%F0v~yRqwtRqB=rM~{uzQa03R*DM?VZO`ZWZZ#sQ3e z4?)%`03+bD1NfW+e0Bk!bAitu;IsEf0Hc)<<j)2et%INt3NYFXK?O9xXa@wvM1T?S zH34i)9)X~g1z_|#1eN6gjNXKx$~=J4IS8r=0*o#}P<<3&^d1B?6$6a!Ku~K1!03Gl z>Zk)40bjaX07gHCpuR4E(a#`gZ~$NgY#uopVDu#fjhP5A`U3=wpAInk7YLd(7lNkz zH-OP%2%7#wfYAyFnw14G0=CWtw$1~#E&#SJ+zvsD!F~y_c`2}Y8L)W;z-J|h?`ja| zH6XXvfw->+xwQe{u<<kmZ3Z}P0Xen}Jl_s**#Y)D!G1T`?>PoR`@sA51Dp;5-w*AF zpd%8%2-Hayz$F{tqXIa=0525e9tP@&0QiyM_cZX40X}k|j`*K|8tMfY{dZ79AQv?t z7j<B-|0SrQF#x0Aff@om*ZN0LL%?ST@YxA`b_1VtfzNrsXYX=QLm)T(Ye5ac0Hckd zhDd-B@Hxr@jP`&U0=_1It;HZ0Qy>>hK`xe^05t@1u<{J3AwR(A9Z*9B0Hdp*h7tgy zTcC!@07ef$4b=dQfDc_D$GSle=moa-{S?$tAHWFY)-cGek-q^oG#+5|HK?Jf03%TI z6G6>`l7gmynx6)0embc6nIiy3Yd{SFTjv5>=L1_809zLUd=`WKi@@fkz~<$^<`n>^ zRUp2rL2j)DxwQ`D)=QvXHh}us<OLW3oVJ1-+XkM$3~<>2_PfA-H`wnr1B}4?4uJO` z1il}Z0Y;#Xpm|`M|J^qCyKT<jz5e&V|M%P9emD0&`Mdw@z5mrQ|Eul)?)(1V+UEW* z{LTN$_P68A`467|`*Y0wyKUZgul;TRU)l7(%hvzXw*ScQ|0l7S`=9Lp{onjo82$av z|2u5@kB;|$()J(a_<!~HppQPUjalFQ{P*#m{@v?y|J^qK7k@%!mc=QKAW;%0a8_Vw zjPwLkrPY#7Q<{qV;uX~_Z*6I9?dhR-Lwj3$JELK%>MCjkb<!I%>5Q%Q^|NMo*0(md zG}Km<R#cXk*Hx95R#%pnl%`6{%Sw}_$z&{<EXasw6s!nEa2=UT8ZZP?pb8xN^`8+2 z#bJUbFc?KKC4vw%Lgo2l#T69G7R3tl3QH?sR9oNB(B7`XrN+kA7L3Jfn(M1@x+s*= z^Kwg5<E%LywGDN(m1W6zad9G1kxIl%iW9L|VZ1n*h$f<ip~7e&5{_g9R``R6j5#qa ztb`RR1p@v0Tgk{U1gqvbg2D-KdQQSvUm#vw!O3cHko;JA6~!29>*`utF<RYJ*Vsgg zL{)1;4b3Nm#YVNJxut#n{PxP)n(FeBq9|~+C{>({7AK3Mg^_4cJQj%+M8na7e19aA z;alMkV_L#Z=usF|APNk6_D#qvkr;|o1WF(nBk)#%!3CZxOz|>{)0`m5dWO|hRoB!u zFr1^mp{jy2Fm-h`)uPl`Q!8nO&V*I1E1R}@RC7apLw$W+WmRQmMOmsWRa^`nfHkG5 zR8esvUKEeSq6MKmr^Bp4F;s;E2r%fa-?&){RViT%Q6eaU5vZOc5SF3C37iI5!7!X4 zBdAbOQCU@sVAi4fno5GjG8(T`5_ElYlbWO2;$~4_GiTj!0|-JzWks?mnRXuppb$J1 z#AAtQG+bC1DTw&Pp@2WvVKb^>M41UIlnNE}?9U;cK;alclNd<=02qtJVm!wd6w^FM zvVy4A7$}k}DFX%&lzphKs*07##>SRfhG}eR(MoIwh=8Gb`ns_V)m4?{#mQK_C{YwE zh!sR4;2~599twhyNGKf24+eZe5CN+W2PsD=Fpz}L{$eXpQy5BMV57(plTri-1dgL< z7N=%$6^vsfLoyOC<%CNaPFG%4TEXhL`s(s}QK+x2)=FYmcR#CdDyyiioZ8mVSl`fG z-&j*wSzb|DmMD&uCX1_!lF39#96%7vb(qWslPv2+3yBa4SV2Jl_>DHiVk#w~N^kHF zC&Vx^T?;DJ3m8SB*-BW25=w+&1bZ-rU~*MWbv4NnO?5T31liEsBr|kNYbUO0tgNc9 zp54;~Qlv6fSqf?)SzHt;4926evW$X_kr)U^#OJi?jXHxQX?YWxjVQ7}6+HXao{(tZ zCXS~e$edD4(Ikvv2$D&09EqR=PO&J#bLj{Wl(wp>qMDQGrn>q@hH7kT)Ur%#TNj~e zsBCDjpV8S+Us{q%l&2CP=Mu3{#2<|mq(b3vs4xT|NE?ujfYzwCQ78$jfP@zRj%R7& z`{+sp$8eYu2o($?8R$<jTB2!=0#G0XBXEo$b2KX@OH)Z&;%gde8#uAAqbJI%henPP zO?AzUvfS7>v~fXQOLJ30ZFOyBNm*Gs`;*DycoDEA8VkEX_zgzAMyu27H3Y68fd7ks zN1!<JedWq*7=g1841tx|$_&*i7$$L&Az-C4I~&QM-WN4IjPfNF)fFT`g50k|sgCyU z0Ks*4cM)=BUA3TTX&-)RUVUR-b!AyeS#hkWC?1U#M58g_ek2?U`y2+NPN&zZWsO!V zA~5hi8(RDqkzvU1WAo7rVktthpdF~-4CJRM&N84Qr}Gjac!87k5>ARGW##28&(t@! zHj#8^TUQWgy1?nx<uwg@ZA;t8jf<K<@|Bkqmm~^fpx_Ha0QNvI7zzf0Ugvk->kUSu zmLwFU0)-ZTB~lm&{_jBWF_g(?Pz;1YsYKKQ2GTM8O@Oh08^ZZCXQ>29Eo;>+U5$Ob z)H6J;l9L9<j^;E&gM+dh@(Je3`f;5ttzC@`^;K1%|Cgs?@#1(Q9uJ3eY&MfgZ`2yJ z8m$P9;Zew-0WJQDfe{e=-+|yGN|gx#!B%ExW-3`irOH-jW@Tn65l{h!0w0X(s;X*g zG%VZJ-O_`R%{@bLobBlChMDfp4u+3-S#4d*gs#S>)|#sF;#8stoH(4$`%uW2Z#GyA z2CZJ!$!eLGB;KhIK>JzzOve!41^?F=>88`cS7m1^K^w*p6hs115hO)f<3XG>R+m*( z>qV}mr)_|uo4W_&82$Y8UF}^08}jjn=FTa-p#H1C>`cbv(Rg7XSP%>a0$!iR_&4u$ zdbL(3=P5Lx`Rx2XVKFkG-+&ayNs^!t4E%(E^oMZ)M>62Ifi(!v3aVI2qFHBMU3-s9 z6ov)|h6J&HaIi(<hlhJbxzb^h_^?f5@<uf3j@cUqTiP0GGRjw!CR1Pr7UVgtmJIV^ zgVA8pXXw7KnXgvp6iR64m#9%sfN+Bhhe7;RBUDP2@;LwqgD5ky-_FX;f(ew%E~-?k z5KC=kQ=63}d%C*1akQhWtDYu$d)o=R%%!Kvh?&&{L%h(paARLnV`VBMv8gB;2U9TQ zwwsI~?R0vbUL(tz@2lsF!1*j_=fChd78cB+bmv6~5;Q~%R6b~fnV5*d8LAI}H7b&n zRH-@{%$}OE`gR9Pw0C#+kVJcDXDvha^>t8eS&p8e3ap|&QYZ<%3pNeZ)s?4`MRAb& zp<oD{-eNX^#5V#HwA#OU4?~;&3`ReRGi3Vo7=zGS*(RZA2C^6?N2Ozb4aA<U@iMMh zK?%d=`wAPI+_Erg%!J9DrgvzlGmXFiOE<PRv3$tDYr8r{T>`MAaXTipw>FfQL<;h9 zEVc~Gd~=3znE}|K*BcD_?`h{76l#ST+Vlq!j2#f(=Y5|+QBkxADpiJZaTYoVgXrG` z(WgqBqQA1T0Yg3hf|_b8L-r4h8iSH8{e#Uo)id0WAq`#i7#Y^$LQg9x##vqK<UJD_ z>&lCw{(#eBG=az)GIYzd2GH<8+tYqep087g3L~`hTal+If~B6feUTt|-oOA`lrTb% zBS83Xg78xnd2+C!xt%7xflyVIMIgEcM~}ssw*G+@lI|Jo!_oSVdYp>rY4t!CE2aIP zab#*sZFwx{&9@uPcB|F=cjy0C|E<tBzt=I$OfcfWnYGcyi`1i<D}4^DQ2^al1xgQ2 z=K>mGnEYs>R_iJZriu#lWud*PwoQn6Tk4x+p{=Ep6FNG&cs82Hiv44F^#oDVpfQxy z&s<RG)@wvUYqYrX0wK_SgMqvptHqRISg6<Q6b3MOzxh%_QBzf*y&|*}U$IOWXe`gO znsh9v!AzwpJ39;f%kmO(yt=7VvPL46rG>c+*$5^-?zK0y))QoFPd7nzb+;3E%#G6h zgBUZ4mg+<eFkoK9so`mrT4!{)^Zfz8&ztAAnbKG+)M_;#12O2EKN&e@7EV(nDd<Yp zt`NGbQ+Z~C1~efm-FQIugMT4TpK2d9+31WF)>S2Z0#Q>_(LnlLEiH{S)zZ;P(jA@c zBoX(J+{n=sJC>6hbe8Itd5dFijljTagW2iK%lGAbJ-JScLH}<NprAkfQA3e0@dN?p zF6n)7-L-d4oxadFvMbN1(`eN^l^(<@DX1x_kJL4(jk%tR;<%d^Vug}~oAq2xtw!Be z53;{=>;Nx?Eu0h<dCtRggJxqzjA!GWFE*v<s`3~h#bwE2FpwgVLbugoG-enS9GE@3 zzg82(TKajzLj&u!Ts?d8&9gnjogSl3)`$#_W@K&2<nnb5T@}5(yzKHfH<WsCG8|x- z%nbFS)+&<9Xgx`h-Q#-+rof0%K`^KsBt0Z>B}Hm6)wj4lftD5n{vA(7V-bJQ9}MSM zKpkf26bxtqfBF|ag|8Pt<3%wlwt4I2H(!72a^FCkOCyQ0nj>*Q!(esT(mt|n)*P!L zFVxr75TJ=bkY}@XR&8?)Lp3!tQ&judUXl$PDK5-WL=M9atHsJvlc8d8Sz|F)Toj0e z3geN2urHAB58BOt^B)Hp=(C!(69h?PpcL1v{`kX3w=Ojl&TX#@JIuK*vyOz7I2B0N z_0*S_RdhIl)ur*6o~dRr7O*i>X^CDMJ*r>Sl?Gh`6NEW|D`l8cM%SMs4|eJjYHc!@ z-~nSUuPiG{RQqzB4u{=l$}lgqn9K?ml)#m*d}jR?1VKrJ!<mg6o<4eT<6?c`{EnJJ zm(B07$`mp}NkwaVCiJzolsA|QTbe411hS69aDuXVYvK%*G4KY>#C#SUE67&iR06}x zNwL?!^f!w!L7fW6u-=N2WJ$81uoQG+6Q}@vhH0Tu5ArWv0)Gfw_1j32VlkQ&wrzcU z|H0kc-HEx~X#>1&GY~;4OpMo$o;PvK*tQl!e4xK2CDV00C>kM|sxA`2JQ(DdLa&v? z1DPnPij!z5E%#f5!8W-_(p1Kau<kS)E(%A=avfH)*<{pb7#Et2CXfOY^z5sEw7L?^ z0fCfoZpFsCx2|2i_>zjD5R_7h_F&j<7F3Mi6Kl`Y<(3GBL_<kcT~(?FK{-mW=o&{! zx{iSt33lO}et}BBJg;fN^(~}rAYUHn#Tx}pza-T09kUxN%BqVK#qn4?0z_e9L195S zO@PR>1QeE+p%{?DA}Orfe*gB(Ti4fT(?r?;U2Zh)w29eFVL|oCn5(da(w22Mwzrm* z3<6q)@Ii0KFd?+`Ema}&=J()8DNt}?y;9u_>w6tcU%Rr7m3kOF#R3CLQx!#^0>cqM zXoi4{h5{}y2Y>+jeLz}M0R)jufgD)7_ru2@KDxUTr5KXpaji2_=(I^HF&1l`QBzpc z%*)lI`$qOvmk(n&jhh<F2FLJXP1iD%STMJTM9Xo|%xV#_2{H7#g@G=lftUMOJR$Zj zXe$Q>L<+%3&JP9u%>Wwu=8t-kbubj6VJJylwf5%C>sK#q!C4>)X$%o)i41BmGLo!n z4Os&<IN4iOlWHmHtWu&Rn`7Z-&(&Cl=dGaG$%9=Y>rZg3F2XXUgtj3lceUV6f*1kn zo>Ur=)stEqt1EyqiAMan8Lov6hfCp5h|o8GG2j%)AC$vMov?b#z1z2MUE2&(2;lz+ z%yW7%swe0~O-Fyyo2Y^5Q7xU#{gnfaSxT7pgd9uea=O8}%Tavl_+AQ+6k~+ikK@Hk zwmOIDs8iOnoR0tlZG<LPIia~82=jPh$nSA{-#Xu+uqt@y>whtmO#1XZiW&JeJ0Csz z@X_skBt^0`Ai*4?VIx|MFRmY&))=qurpXC?qlYKf4K*VeCd6A(o0e#d-LsYv%*?Uf zG!d_0Fgl+?6WMH~N9bxq8hOD_qBsScQfdE75=Dh!zt{CW+d{M1rZ5BdpM7Iu=We9M zfeExhX<D)Jy$5&ho!`OpB!Q7IBGJ6wZ?PCXiOM36Jy`}LJ&j$h!}YcO6pm2&R_)}) z=Dzyc@)4SFnO5c^<t*!N<C$W{P~ujXR})PFp(HWji6C*3STm`mrn0O!nf^}3q7g+P zy$bTRo|?0P;QB^kdepFD!`+8>9$eZ+kT8xCs!WCwtpyH;IZ)MJ8S&LrE0sgtV@6JG zZ5@Rxl~h4AZ}y9tj@p{CA4moD297AI#BoO>i5KBqk(n(mRn@cT2ppmDY=WYBu5x@+ zRXI3w3{+r2xFDqP{Z#=|GhZUOq0z98wXEH8?}LYrZyn?rpn-8^7EAJmfZ1#>Xc+9S zjJI`Q$}yv6PG8j1IiAO0v9_yr?HY4uWo79<0HUDd$+AX<Fw`?>4CP{0p}YcZ<Z%^E zN({nqtSD5Ett(4KLHb9cg@wVOPvLpK4wP#gUdvfF%mg}DSiAb#{rm4--#{=J7!3%* zu&gd%H&`{n;$d%&zaFy&8+!)EwKoj91xC$V_*XjYL!-M|!%=q~u9VzMWu3o|5=&)K zujYzNh*~vh3kc1Ul*9p+r`0AVcY_|51nk`7$yc~R4L<wIE)TD#3>)VX6vMCGc<cWC zTX!~KK#$<0N=4DMC1kg_P4SwE1^##sWsdcYn=o^*dz_P^42DAc>s{7?Q60^}0%r}9 z$>%R+L{BHelyIa*po@~KayC<iWaBuDFa#j<vK*h-QCS*~0)Fmtc@#Nd5<UBiTQhbO zZ{59uqd9Kl&ijv_eDGuk&HZZx^!X-TuDzsXZdtr+oMf+<FnjiraeWg!EMxU`C*K*$ z>FH{!&GTC-RGDI6l_cl1<5WsybrPFQp;dwsCsBsNaGpjPCLMu}@>H}S6!7QdxE1#F zAozXKLHEg8j=}}nwsiHi+xPBW+bl6)(9sA?v$W1<*V|-weh_9Ujkm0+s-<&qps~{- zsnwuQy}O)j9cb+u*%7Y5VZxqJGohZ=ylPBC5-cH+dP1To458Cqm7rKsL+SHs`cf6e zMbShoqKGO2(6cWKP4s}E7I}msEK4`ux_$5cTbl(61tCx=Nt(0-?B*O@emD#aFa^pw zn)^pj9p5w3#fuu=EWNjq?ikhCH?}8Qfn=lZ1dZjl*E_4S0h^^z9+p%fn^oB;0@S?< zWHqZ2Jaq%5rA5(5tRSd}DDt6ae@d8zu^Lg7Fj}y!+Ij!|k3N08Tf_Zp1oU|(t=$la zB^a4^#i|GU$In<iy?<1$s5V%OydP}f+q#-NhT4KDRW_biDw6KjCPyVK5;%j4m<Hu( z8Wc26VmN3=sEEnAAOflM3SHQ*2mu3L`-4HZY_yR&b)4Y{Y}M*Z_dmFIc{7V)IK={v z&M>mqWw2`^{<^YAj!pYL>ZUNNwYe+6Qg%kqou5oue5K}|xyTuj;-oX(d?2j07t&@l z(?uX^z$OV2XiW~sSkUNchN4BQt)`?nnTSP;6bVHfq<~snHdc$DK1C21vTEbC`yagj z-e!<~C_$@KBt;p0E=#VlDB4sN_gK_8PB7XjEv@}QnsBl%?S<)-$yZ|Po&%o($Jd={ zCi8r(sQ{H#nGRIRV#+K8RVlLxWj3Bg0F|YJIg_~(2=t<YNK_G16hhCQ>7~_^P2`0O zpjNT<J8wPy?9=ym3&g($K$C0Jxh*BdJx!^6hlV5>!7^{4dnm$FZhb2M)<V(ZN*cRn zt4=aFYrN3OIK6@)Lg<kZP8=3U1o(hsFaVQM(FmCMxL~nX15N_kQGudR5dj8hImRtW z0sspuT)67O{SWS5-b|sW65|kpa?rY5ug<{^)Q)d$?d)l5sVS|jY3mBp77A0d0$w{_ zG+AULJ6gMk<#_7SXq~`goR!z0geQw|2Y3Mol9!?ha6}4lKAOUafXy<gx;#~!R1_;p zKn@Bx>tQ&703xVh$;K=9KX`a;GXcX{2&2LX8)?e(n!K7(t&@8Ohll(7Tg%HEd)s}q z2}5LBOI1(gG$v7p4+uLcn&B@Gh%}W=SQu7?x?VtSZk&MAE3K#s$;tu>iz0~3Y`4KU zrM4_t6ju}}l3*05F(DwzHoY2AMV4;A{`j*`9`0oEe~p0F>CyxYW4q^$8a;0Ego(q| z)or7P<ARMLG=f{-FjK45i3Vy=e3_s*`Rbrd5HM-xL<G;x#B;nfL(o8M5h$)wfjvV} zD#UBnPpD4CV$uIr1pVaqMq?!3MXz3K<XP>DD=*x+dGGRe8BG@shLJL(3pn*&Yv*uH zd0S~HQZd{=cH-FfjTJGDHq<!BoYIPslA4n8)8a{9X4#VsEQY8E5h#2VMiGCWTEH^M z#Y%}(F&Wq@AiXh`sAk4>&8V)<C;{I8<SVT@<hP?M)@vzRw|e81d$;ai*`Wa{Fs+ht zi86%TM!#HC;qz4lEY4W>z`*nwy_?Gt45>|7yANx{a9Mq6*_+JkteO^1)nM7mER+Kx zN|mirx@;7loq;XR<gqOB`|v6h#j+~cvAy$ZDgpXQP=G)A)+822bBUL>nF!XnX5-bz zAAWpyk3M~6=C9ss^6eTw<B8@vf)>5m*FHFA-lB=SDvAYG4&fE6S#2O$Usig8e3KV= z>1-no1N|hV7f@9Qoaf|dID=T6EfPvP16_lpm)(?A!kGTWwWaZ-BBe+`zxb8g95=hU z+9sV^=X`O^h5NVfo!wu8V9&!3hKI)Q(&ZVQdCuV}v*+(zxpM8Q_66OJf_Pv5lJQr+ zII(DEfoLz9aYcTI<yrXPlJwdZ2ptL|IEqOGK!KqtgvUTH{vNrC<|)!izr3)at-Up= zs8G~Eo4$0L5>^LM)uQG!uGL$vJiK%N+`-Ze)x&iBQI^yNa}D_dfgpkWlFCudErb2F zt42B_$uVOVw!MCR@1mJu*_E7eNqC#)X!6LsY#`vX;PgT&=r&At=7?;Pz?BS4W@l%> zs}YQXVF&l}qSm(7<|0Lzq7tOP-&mIGp__X2jLx%W%hjhJeSGbe3JgcS3xL||kaLL_ zM*Pss8}%WJGhSZ0d8#*@93GzRpS^q9<V8`&8l8LwyTH;sc6vLi0=)y6u7WWH<q?%q z1%w;Sp){Pnz@S0^F?I@j)(rM{wx<+TifZW5*G4U;N$Dh!71#+g*POcd{@t_tqbN?& z1W6DKC%HXhj-VC{b#<*%S1lMjeeAON4PmFbdB*6M-umS1QH!T>_OSKf;JYAP^pRN@ zfngcwf#+Z|DO`mhlB^-)n2N-Cvpc`Cm*K>MR}K&NEg0xiG=Lub=xe>m>xx7kOm%wV zf-UDBJi2%8U<}v`1{a1=jO_8MJ!%$F<>h#4hnwSd$%Sh>3v%o|bNgrQynNuGCAWFr zNX!17ODcqxUZ15xVK_r|K>2(vGl66&l{^@*g>aTK3zu!KWOJ5^3?6=E>~{u)phw?Y zc*#~O>r5QUPFc9+{F5I)z4l51Cy4JNAmq3>uSUR8halShR^DQpwR2S5X6l&V)--n4 z!aXi`-JDUz-R)NpB`=>@LEz~{%>(H*WrQxqlrSu+Wg-S(foXk?x4cV*vW2gnm^o_2 zxKWB$MHG7U7pvbV)=4kD62xeF>WWkM@85pwkVt}_{oDXSa{C3Jj%O`$_2%=t7xs<s zoj#>GUgTUlMK}J+)0=1Ap@Hkm>2-sLaJMwS2>{OHe>DKfV(ZE<M5$s(_(uqpDvFa1 z-@>X<BWI4?y|J+Fc2!h?0W$jN&pNwXUB#?Bmain4IWL`i_~6dzBNDDu5zisu<h-Ed zmB5fyH?BFpWm-dDV&<a0MBKAxD%JePwbN&FLqj*0ldF67BQEul4vs(>Btv;1J6oxI zfvQNr%FHYh%l?59D-8Owjk$9YZOvl_cWzG9+^UH_zb5$TTfHgQ(7<ncGn7U1^ERIU z=#!7Gys80e^t%WMb}#D|Xca+3r*E3o9!)x@ZyHxpn6r8YTQGm?%2&Mky?58JtGf;& z4(<A0hM_nt13sVv)tJdtCQ&$BNfW9c!gNvCr*cM?H4gPo9lLKws_t=1N<k}Fz(k6M zF=>bfRD~s%PgryC?w#xV4q_CAk{}NWJWuV;V;lxn?U(9z9NaOsW7LG16Ppt{^{Vml z=(+#?vnvT>_j?<dcdFjudtpYxF-qnE{OPskETKdI#XxCEa2$feL4P2SfeFP8;rUe| z_q#de3O20={uFG4HN7axDRF%Hw9Q8!Jh*-M2%roqEE|SV)GK@QIk#E>L$+zlzOAFX z#}>|>+*hpCZWv`VAGm$zQbON*V*~Ye>1n11<s>v47a3)?5>;hqzd-rnY($Bx0hWN< zW{>!XESeeWwgo*4s{HmVuCnKsrJj9TP=jj55{LmO=rwb9y!!r=k6t}WF*IlyD2C(t z8e=YH*K#PqwyapTxUaE6J8i|-3XQy@O;FC>zUO?UvGd+m=IzuOs*{v-AaH69R>3%; zQf0C(7=x9h24G3jZ00}w5MhNmvy(N2tLpQu_iUvKE-grY=hJ8nQ@ND~$B-mEyz2P5 zvpY6!mUsqbP(a2-g3HaPojM`6M9N?N+LpybW5>^$-5oKjSLi1ke*MJubBz}K#&-T> z@kwqPsWB5U!H{4IsM6Or_<)wyAheYyuo4}h7HU>B;G<0&X9u{D<6T#=LQpW!M_;=M z$vlBracCIE;c*+^y711PZQIl=P*7l`U_8m^`&o}#XVfwNWydxx89k|B&fL+3Chc0e zW7SLRX1`HqB5!SH--x|IPlnY-Gz(2%R#s(YWber&bvP+12@``M#p&rT;JguOhUZNQ z@Db<L+@yk0kkIyT^9h}CHog4BID{sqZa;J3@{yNc)`~1bBN@b5krGUKq)o5auxNPE z=K0h5+BDNQPE8u+U6iM#udVWx4h#BVH~&WA33?*NYf%KJiS&I28LB<mjDT`ln6dz# zUuL9nAWuk((95ixAD04-`;Nr(g`vk^$$B<42GJX}6jk56e&_tnD<)1xfQ}?Eki9ZR zJAJfQ(giAIwq;=1(yoy+XUy*$W3eynbY8l9`qKFxjpO<@%aNR;#BfgB2uLRZh5-3J zc#ldb5MIzSv{vHOgR&rV4qu$p4`=N%vv@duD&+t<n3ja1#1;%?>P!+s)OT*%w|K|e z>C?b8&qhH4p%Tq_0<2%{u;>}SWnlU0;c+Fi7LFWecCPN$A3nZm@5yep^X4|wLCdRT zk0u}RNfioa0G94US(Kdlf{YPro)P<{Y?9RKf@=H7%)JhljHb?(+MnMb^XyxLMhZ_- zYIF4{(=xF8z`U2&PnibNRt5MVhRY1A_mXz4N5^C8+S*AoJDY4%w@#j7a;zC1F@9n9 z^pj&Ww)?v*2TjMBZhb%kv=>Nl(0M=~QnGBO(m+xgky8)r5E7&Le0}by5&Lr`JXCru zVN+1)#mV2O!3bDqHtF@GdV1wctH!LII%c#oeWjA3X+p#(M;;krRqd@h#<gR`<hF4$ z<}4_iBiR?M>OOMmpI^E#RSI9<ljF44Q%Ov%W<d(Vgh)J}MP$?gV>Xk^o}**Kp#e+T zWDZN^W4kO2R+QYy&<dl%0d4xVpklbyTBA`5i_`13t)IMU_T-7G4D=#UUj)kIv@4$u z2}HS-;oaMpP3@grG3&+V1!B(Xjg1=)-<@@OiWs`N$8I+^(uF_7X&lJkY?MO*{Za0Q zWjtG@)mSZd4IR{0@viz2RBH&?p}~mKioG1A&?#)tlRxWmp4(<H<d`t^oR)nX#;lt$ zW&%o4I0*zHE)tC1je8}&NJERdB@??^+HKQb9#}5eUp!LTJAHf0`2~Xi{^1<Esg;ZV zh!ZJg`qmo(u>TBrH^!+{gi-IX<>>fAbqbYJFGyWca<7TTiYt#%q{09q@a)fef}gYn zv!C2b@o>SWIsFTV`}zouAsL<p6osVhek#BTj!_!keQ5vmim|g+OsHQab4%8rKL6yW z$%QXTl~<1V0u@ny9t|`aK#q&3S+xoWGB8;0kp>cWX-+w*)8s@J?)Kn14nJU%(KgaT z;0kj(2mT_fxT%{F>#5BM0~haDICj;fv7<491frA%QNT%HfJ28HJ*Z&azhhGMaNYEI zo$J-i@*S`2y?WQba0{QhbkOTBk8*P;pkq-Sr-K3|WMzRuP@7n?G^D5JSKw+`&K*5p zgIfjskb!}Fm>d#OSf5vc8D^&+#EfshOmam0@Z!G3qXvcu;QDtFAPi14S1oc9u9lWB zXe+9+PFgo{rzEUDv~|jsBc`Q0_>ya{`Mf0|dI9<O2B4rDlWLr-jhLB*)wDj7bq-7s zIIqmTY8KFL#>HSD2|)z@7}gN#gAA`iICfRR+G*{59i5#dOW-sI^fX0K)*uz&DXL2^ zaH;*X>IbLJ9zABKT3EdC^`W1As-HVk(|O_ToN%zgum&YKgdruV$SPX_tInnawW;zM zFJk<NQbI`9x4trkfF&B;LlD_*TYMY~asU|cCqIvC4^RvcbJVKh&9nPP4-5{b?@=Nd z6j6e12n=u-l(3PI=#o9t>W3O9%$vGf;Fj;%TXFvuw|Jhq<?XXMkzk{Kr3$5$B*ybm zlW2movPY;Stv<JQjuOr+!<fR_*1cm<SWBb(RN0w5+k*_Husw$$Dqz~<K(68}vp&9e zZfk#MS1(E7e~SR2bE7Va{t?6IN%!L3vTE1(&5I99!m7jTv?os?%NO!Z7cW@c?o!PL z3jaF;P&5m{Xx7<1FB4N%Qew2e=inHe$`P0&D3aa1J;*U22WV*PACo50@fM{&a+-xH zX3cc3-=5bD^ed8qeU5-~Bn>{oE2*u0Mb40O|B=Z()7Q?K{|d`5UD?0%=lj~{Z?OB` zxI8p4bJ@Cm7|tQIiV`I?%Yr_xVmy_pyjhEBJyWH#YZ=qj+$Nxw;Z>l^HEwqaoFb}N z2yOjS4Cwo}2+h$`cs3<(niB}S{GB)$=NZTX70{I*0|TsPN^8ya7I+UFnB3PiYu@~W zIJ<gF)9CxFYZq;^=Dv1uXmIATHM<dnRuWk_#|spdotc#d^Rkwzm`>7EwZ<%y+Hs!x zEI`xOz)Gxrr;}xXG+hL3{kBxg+b>d@ljj%}FYKA;&bQ{a0aE_A2;fo<Y?Wm}@Z^PE zTeps>a7|je<QT)R+L27WJ}I_ntKRX(yS=TG7OguBy8XWyfFMc~$Qrb7j*{l;3=X~8 zIlZ7$h2qpkAbZ<(=CGWiMDZfD^Q(|dPd!EB0!gWtXjaW~n;Cl*`TYJQ6hkwpkM+4? zn5Oh&>}r$FGrpo{$;25`-;((y8%8di*H~!Wd42V@x7*(>yxqE<GO##}NIEmilj*x` zBu7bsfBI~Xd3qGLBxB(vwL1V?BGzP)cxQi}gn|g1g`R!mW2qUZNJPL9c8Phz{5-4R zY61`-aC##M5*U!jV}eI8Ijo*>6;+k~iop{cyJlDCsF8&p^PcyXT|M9SZo$o_HH4Nz z2q2FP6oV<VvXnF{acsr7TyaJWH5B^Yvud`&n2K2U0!;J|d01FctvCm&Ai|K-&eNEV z#<>-y9SiLS%31>;_-h0xicnjaT%4mcl+Nn$k1ldBjJNfiT3ofarX(Rr#$E3&diP@U zJE6N>o2kDy06|~|qj9ExqDh#YAgzgbbWztHAe-6EnHbqOGM7dbwTcVSmM?3H%>1ha zRab{GoO;;;i%zzc(FB@7WT2nn6d^ldr-)ekT%^{_1s3%#Ua@KR2@N}c<4Z?R^raT; zf3oH1`7<BAd1cIeD<@!7c59tZ(()jOU?Nmi81PMKA6{L8J7lMKZpm&?RQL`8C#S9R zXb4aQ=b<fssPJjU*D$QUiC|gdhNTvr&RI`^VTOJII0fJ&Y8RZVA|;0;n0)HQ(!z#F z`M_%ewf5!J`}Z{#EjjSvmRByGee~9qF$-)o3*%WWwOU@ysFc~+s7~fYzQ29+OJ%Tu zGv`b%*-hXux(h+5`J23IQc;!;z_)d|2F-Db?&@JUlVRhFT7fsENF2$)zd+FRZM1^^ z1#31#P`qRb=u-=13u`UDM9XV;uH3pg;ah$9vzLxsKKJC@&54WcBn^|9ja6z<!=;Hi z$^o%u>uMUgv5K(pPT!o`BP@wf2SBmR-x|<SiW<cwfWQ<<wcsGj4)$W4iE@Rkdd8IC zXgq`Z0_Yi>!qhgxp+$^?$*3f|%)ai$>t33Agl6Y#7<1-BU0~n-_ZRHCbmGHvSEn!L zSQ;g9Wr1kWNg#uiaIh-k&Yv+fu%J|ql&HL`nzyn9N$qtp+9{JApa=>SSD`ImPoc9G z9iqvhevHwJ!9uH!vsJQaIs!0ALjsZPgbOG699NOX>~IAm4Mim#2WVpL?s2DX^Zvv8 z?=RSS?alY!d2jlX^bH;umK_naG7l@WGqbfo-iTv{hF>ffyz$JO7n`@zC`|0Ple)Px zJUUuYs<;dwm`y2{zQS{p#?YLd@c48xWh`PSEQ9<4eI5Z`R+@oGqU=eH)t4XESa?(H zG@@R$Z`$SeS?{SMPiJqxb?(y}_vS1UfSx4KtT3<FiYN|P8OtEJeW-VES+yomr1Guo z*_*EQSKPFI?(DExP}D1K17WriXI&>yULZyFRB_p?NMWQPj?#b-k{C|l6e(HtIT}<P znH!3j)K*W^qP6SC?xDpwn_HfK>X~wN=l%5yFP{A9?Nf_KTLh3QpaW_I4v2e1g`49! z*6zteb#qFn`bBf+oSwCV;w0+8;(&Gb#vp<z^q>l!eZ7gG-6vt1f+>2OX3d;}!e~)B zl3t(#svx~oDBARHjKZ8kxX{76^F0kksp?%kvtn2C(<kofH+SAyzwo^?A6-7Zc#M@L zQ9M(nQnNrCWoKt0f|ekPhlUy#mSN>{rcFIQYX?Cy#G(25wk6x*BngJ$8R$3P?xFd- zw{U^S2y`mDe0pwvzP}Kru;&ZQ=?HLY(Sooq&{QO12J=8L(&qf*xNiA@!C(Ay{`3zI zJXtmC#)U6#U0goiM&l@%jsVY6z;-1<3M#s>x3_+A6<s}d?!31aAN(G>?A0ZH`;r~S zG_7ze-T{p84YgWWmWl2^1az4CrJjO#JXwUXC`FSPU<eo~<rpm%N}A-=n%wzjN6n(u z8z*fMh)J6oo_uC_d*7aiD~9i$`ske#%Ug2<j-Wu~bP`8Ak04_c)z;knnzC}THb=IM zjUB*n6gf1*YhAS|%E$^C1mM|Uj;lps`3uU!M+pkkZ0as7DlV%)an<wNx=|XzC8yEC zF_>S_S^Zv@C#ODER<%Wq&fHe}(Wj=%NA}!ZG5o=~r&mueZF8m(P%2d#o=&e$s9+kf za@y*zudYPP&75{9b^t*#vky)4I5xeU;w50fDKH7n>ouBH+1QEG0xO7{I^14gD5_!* zk|NOO5ny#{EufeZtv9=K?K!L&w|S4!{H(p5KmVoe(i?|AUDEa8h0kxFU)AYKBLEbU zE^WZ`R!nD-TD_;Xu9m8@scmD*UL&zA^w=z~W7D2eUIvWtH1zD(do<j<<4OwG5OhDg zGZZe2B};K2%7nBu1nNL^Xl#1XIJrP9vXvUR(n+&7j6Etc<9GN!`Hb6m{jCSv+Hbt^ z;LPj$%Qy`~f{>wRo5+y5yhxdm$?325m$i%<<jU2sZA{I6f~0vfMN>OoE(oSCRZRp{ zxRa;n9nZpXAeXw?9l>y6QE3f^-~@}PP#7cv4`=|#b3UE6%HQM`?I}-5_;pg6v@iV0 zr{d=8XYX%qy>a6Gb0@c#iGV|rnM#$>%;1RD6E4+}IfJ#K>duM7REo{i_1EkNZAv9% zqvVdA$yhPyLsJ0+uSoRbw_uVpQ`jK3&1cJT`%);*QarE%Woe97(`rObOBz#^zcGg= zg&&#JS5e)h!^OY&O1<mx*-y6A-#_>9mA4O6t9g`Q!4x)|DO9D&4V4&hOMhjcVbt6S ze5ItcjB0(ACbD5QjuCqgri#h|8<-0{`_*BI7snCszN2ZlUp+s+uB@b(z!3&ZL%?#3 zWV4tpa?Z?<<Or4&NyU?AuN~SVF_r6_pMPw=|6t0!T_yJqKRCVhu$>6XWL^$AszB%7 zE4LR%LX9O2OZU8S^0h-jsbR*<`Nwx1BuG(o*{o{7%^fa9Kw*cTeR+Uk#Bo^mzN3Ic z8(%v=tE!}=0#hnUI1K?PM!{+_YPGsTjqHinSICwUPa^+iN~+oH`TVKv;e+XScN9N3 z`sm!wU3S_l(>^;sI;QvR*LIag3tGxsR~>ls%&9k{bj5`6QxEMrh=Go#CI}@qVnj|z zkyLm91jl(sJDF0wa)Lm3>G<WT#nHkPfxtAHzIPfJz=&#@mbE%TpPQ&JlQ8i|I`%lG zt9d!{o8LN~em?V)UGYb+et3T05jUI5<6aj%uE+o)(2*(#H<fp7J$>Wh!@IR|-Lz?Q zUOW6c4FtbT(+Gts-C;mUz0kAYzDCmHyeK7r)|2#}{p9@*Zd}^H0cDD&r9M!Hf(^)f zy=Q7%(s+^$bZpFw^&|IM=;S8L<4<z#-QVzFU&YP+cg~zSZ?z`3taI<P9?IM39;YsF zMnbXV>qidn-gIoQi%Vjh9Le1V1OZEFT~52f?XUuETmwD({ZW`0=Y??r1#LU<_9qV? z+<12z10%SK00SLNMJ|2Enb}rg7IeX?c1ja-75fir#FCdCk3V)lxWDQCp3<8K@0~k; z(&{MMzR7>Uek`=jH^orwOBR(@o<4E>$euID@~A?DkwSUfa7=}afGLuMY1yf8D(V0P zr!iu35GQpEgQeW>{^E<DK7F)Hz!1P(KqgQGMv1b4(^@oISre{mBeSR<82GnEZOI<r z&%g9M`SG?NA4oko_Q9pA7o5)I_AS99uGb?k=TFwhJ+Z=~+FQ47zI*<|i%~v72-?E% zK88SvOhA+vOwhT(EU1K@eRWbp5Q2ak@>nkBKK1cO4{yJ>PT)9Ml(lB7&FS>HoYowp zZE}gm7^|o-N5;-tGx|`jWZP)?>|?{-J7eEFTK4d@cTS(VVLCVAkaI@7agJxJVXvma z9}3j0Ke+42k^P6v0nr$Zmz5P2r9Y|0^Cq+19k4K<6~72Q`@@?&NB|BodTF}Id-l^$ zK74R@vq&;(PE;Gs7Kg*@%(0ss`f!fgkf^IOXrj(U=#X8Pv)%IPQ{&w`6W=?Udi46m zGv_ZF&QCh#onP9%q+qxGh`BSCh<EIK{go3Z-Z*LZai-#uni??WFgQzzAu5caNmii& z%JA8@mj#&9NSHe+&@somzx(e$`RwUV87Bl_0H{8b#R(n+tyW{y=o7Wox@__XI{A#l z?Aq=A<!?bA&iv?&)F<a|U3>4Q<<gAf!R6(BD`R_XuUOh6(SpVUH?Q5gb^Vq<Bv_NF z>gv)G3L^m1Nq=BU;yHy@u@pe?mQD)EI5TGzEroMWefsJ9*Y6z&`}4itd|$pV5()&} zHjUfpn^Y=kbqSBxF)(lLz`i_#xXJk0Q`7DHue|+w>dxUyS1#N%U%c{m?mFFG*MiNp zdvfa|4W*ISPORSb?xl+;(<}rXVZXn<tDIz%CaX0kuOvSPWWfz!z<Gfw(4gepl>`&c zJNJ{%KfLwuXo1g{pYQW~^TR=Zz-6^*P2QkO)EUb{d6GX632yglbvtaIKG9vj_xi=- zCGQ`*bp6sb!{uuif?J%&f~$769P)RR_B58BKD+7QjmsBMwoMbZhkU`#&Jtxdn!ckB z&UF?k;%NiEy({8TEl#i8CW*e>i(mfwA3y%diLl*fwc6}fo7-u#>qJgs99n~5G^TtW zLQwLiT~WPxm+P0mHQ)c)`J1Q9KY8=!;|F&QHy>Tj-(!9=x_WopvBHkx&bs1vKR9;r zCm%mzgbtnG;?K)(?<hghYzlA<B;S>ez(eTSAI}=iNt&X0HAj^OPd)kQ^uycxB4KB) z+vRlF?KWqg$7OBOYvxqwOuEvBdVSTb1sx|1GWC+-vrm0D?i@OKru_CBCof#PWw>&) zD(4h4!SP1*mSuzf;(|c^>vt|)eDJP-<B|z>6_8TRgk_|^xxi`l6-CS@g(*#ne}A48 ziW!2yX#y_|pZn~y3m-jvCE|DF0t@Umn>ELi>-5BVDe0CC)`spzT<44BzpCSem+e3O zB=72-W2etmJbd%yyEop`UcFP}y`Y~RIN!K)&FENNS+eWQqwBXmdKXusYAccx#-*BZ zi#b%FDJ8CTX!Q!C;ue75p1_u}6vc`xnFwC|)t3+c`HQ3Zc7w%eNPp}@tuveSmRuzm zNwUS>*wdOhLdEM(n0d|1IluW`{;ki?UcOZQ@%eLi9^cd6`M4$jvU*<r>9zw~rpKyN z@virN`^C?{d|$*!tsT#e(z?dUD`3)+mS=jWP7fH-6EF?mh&$3BAlvl{Nttqw-gvmA zucag}>~rPjSe-VTUDWDLh8DXpzC=({j!42*)iWGxH0xQ7{N&T3;hV1>IbU}5_5Bz3 zTyng6SHG#G<CuMu_oR1UiL<P@@SXcN&b<`INfNWbj20&iC0oOHE<Oo_qhkU_lfs@( z!r#6bFyI7&>^Owtro1=q0s~qrJU)-h<Fw^~Oyp&)Atyp`ek;W@dC3H2&5IaowIZ$7 zefnv%|K^ET-zmR!^1!tN=dG_lFuYtl{FZ-j_+0o%ZK$cP?D~iIFK!MifyA>Sl#Eh_ z;*BrtJ-JWC>w5e;Sz$>-@IT)RX@G^;-q$Hy3;MtpYlhp3&FPO_>C`&48gvLwv};C4 zqK1}*{8TC6C`O^#An+Q)Km9g3^2x>1SF0XfIDG5)RqN>=yY|!$U-IlIc)Q@WT0n-& zKl=I?kB=k~j3OL3rzcr!`S$EXZ@q?!#%`ZZ0}OZ{kkUbdsgKbNIs#}h^TFFkJ??y0 z(4XgY+wE?*Nux11Y;v2899L}+WJYb2H5S332P)O-z4K`8mTM<>pKp3+Y4Ih)4gIm} zm!>lB<nG&NIN)05_VzX}ym)anDQ1sg!ECX*T`mJgR`}m)Jr@p-apr2>ieaG6pM5m} z#oH1jkd=T_TMs@s>UMfP0gua>>u@-o29Sj|i^Y#%c`iWCSy{(2vd95gEXLeBkJoIt zc4q%OO;?sDubHlD-neynw&uOSv19gQ{`KMb_<<GIuB;=u%xp8LD2L1GG$ME@`Eu7@ zM&05K3I;{5;tHsOML61C%(7~ZK@sE8&rdi^W|Q4yHX1b=lSw3LAoeZnKX9C0&uavY zLFQzc1uwa5c_04s>a8DKf9<{YJ8Kiyop&^6p4?lczLh+7%yBetZ8$c*f8CQGAJH3O zl^M)4n=>cJgpuXgp8i9u+~Ud?&5Aydgg^Vb$f#v#UX%oumMF}8tGXZ@%y;J)wX&>} z1X%|<x3SMimd8a|r_)<qp8SIR@)<|p*^v6|@uUxLoSkx3zEtJE*m1^q>~@3gLWlcJ z$BuUUK;uwLmxh6HjKN1_NE<AeMkA33u5t7{9oefb;_U~Q0YY*PdiIMViDT1ORtcQo zY0_}7Iv5P(IqiB`k~BOgX@N4#Ev6`o8&Gqt&YGL+@_K6K96rB2_Sq+s-oNqoj5E^Z za?gdf<N6c#nsTr8`_AR<?e|R@m^pTwk;zg5jSc7Ix!pLBpqLVoGHv_3rBs2Kvtv4- zWEX)tZ_qLv#V{;GQ6fV-KQ7MA1q47Zq@T0tn}8+BmZzfCW|0@vvcchW2SSZY-n@J; z@w2a{fBf{pf~&eKmF|lj=gn{bxXW{MApCCrYomOVhUQJ3WD^k;0%%~K-|Znl1PB-r zevtQOyowDm)*UlJE4~W)fKH>;J4B<y<4u;AR!zQhBV@L^?N*c8Oc+pE1`)8^X1c5e zDQ74+{PKmH5AVPK_|8Syv9|7$hm-GIe@{4HHEYB6Yva!tj@~_Zwl!x@(t1jFa^&z( zzbjXz=F|qQ<iPkM1du!eN4bz^;>x!8#z65li^2i;z)$|kW;R<rW^b@C+0r^NX4d`p z@{MMv)oc)rm{ui8vfgA3j+J#rm*fqP+WF3{k3M?z<nc|7d2`JtA56Y^{XOwq`TR{= zuTMRrJO1GCrQW>5<?gp_?@XOOeTpw1)39QOZgVazCX`A{i6SbxP~X0;C%z$2vW^9_ zU`_f?);xD0?v0h#HI1CIaN**g+{%+>i(ady<!m{dp%_7}H4f@IQHuwo;||{b@SlGD zn_vHrr+UNg#-IIa#=|F1<%{JDw{5>Y<+ADA7jIl147^g~x#YY&W9Hmh0e7~@s115U z9;ZpcFaa`BMF!>89ivj~Tt(}6Fbmc~zx?TNS8H8IQ$tfrZB0Xc``fo|fUS{M%mP%b z370i`qdCWCOpNMV^!VoOhmRjW{owxRJ8ygQjH?Ge{czf~8}H41cfvd4m!9cADZF}n za>DlJB;(=un6dpM`&)%nf?}-sWnM{*(=5w<k6Ot!C7X^Lw(ZfI*5`sz;DLVi+x2Uf zEnKl|#fsI-S1g-1{nkS(hSQh{HZlfWk4S2*-e~u$ZN>Q=H|{?8;OW!Hk3aZi&GkTz zddtYCPo`bDaclAQ$?r{FesSz+@%X)|<(_jh9j}#6nLc60q<*fngkg+<nmn1yBGdnA zK?c5(j)mF}$=i49EX%YY0N(Wa#MxJ0JN@RHr_Y~0ec{NuCqJ_wFpe0MdP;|CRSYdi zve6=nK4Z<j&;Q4l-+c4c*T4M7RrkxC#Lme-|8n-Nr$1hPf9kC{t8a|GD8K#VxfQ<4 zvvW?CO`AV;&dgClWsM}-0+nuofkBP^^%7uZyz{JW=Puc>Os~)@+|aXs96iw2+|tn4 z&{|(pLUvudtEV+;&O%!S8~uN=@t#pprs>)!e0}!*zHxdfp>oxmW96JPMOBe=4w91~ z=7^#qD2h3wwmD(W8AU+^LCI0j)(%e3OwUaBq@L~BYoC|iXRmdBoW&o0P&`*X_kCaY zb-nNN+)6%y(`t)8`byT$_me%7<D=tm$Hy8Dt{L*DDt9iJ8jN#x_txJ-uGLoEPFyTJ z)3frc7Fu!VFt9zRFsq!0vJCS0vOKRstO14lj~r{cc=OKF)~x(%s>3SXihUYJ6ziEB z{Oa)0efxIp+`DtzuC>ad7XuU<f(2rp6p(TyEEuKLCY9%uy|i~?WMXn+>gx~VC5bWZ z;W2dcvWcO1d-uT3XY_-H#ZTt0hA+NZb^3-%|M)n*zofc!DFAWp+T@bLXoXnL<?lIk z<lGE^H~E>j<a=bAWn0idFi^{cp!Zczd*}0KZEeq<wD<~or@<gV#G_agU(BXM01%UD zr1q0^?!;gI{+GY}^rt`n_)V@u-kJ~x9IyTEk4a(U-yiOgJl(OPbMAWd#@F>1?r03H zXRzi)%PLpF0N<gCEi3eiQ3+3Y_{8a}w;nz2=*Z5vBt4)utk{AF0)g^?&3`Ib<jGCT z{v!RSB=4-`^tL{&$t#uWWeQNkSMkj#EY}zeZ^niPMn)$lhC1KxckS4)^>sS7di&bZ zH&FAlmnqLk`!ap9@yq{x;`x2QHRi0HJTq^7ZM?))ninhah&2)j7U7yLJ9lr{RJV5R z3VPln!)|WS#tjyx6{ImteB@Ze-d+25@7}h%N|>Dg@{L;K64P3VOr+vSL$wenRj72` zePhi2Pfm?>f77f@(I!7n;H^AZH`EOrY<rp6O@-CivTVV#PPIRd3s1S|kzZfgv?Wt+ zEh<S-N6B;&0N^9a?fVYw*w(ml<65%drlN^8d)+cI!$XNo2!?x~Jb&8J_VnqqJ@TCV z!D*@7!L%F{=g3%MmJZ=zq|`M0^$$P(^wVE|`Rj*YP8$eN`YfGVdVKTrJAU(<@zOrp zTj$7jhkkkSO-F(&>u!|nUfuqE1xiyvVX`Jhp~3h<E+jvA^7N7YySHttmlWL9?BE17 ztd=kUVgf$@A*m!Kx3FMtS_RC8>6pi(dd8E&Qi~E$3Je|<rBs`{28SmnhsVap2Cj+J z3&gt{8+-H0s9l>zU%Q|6JTZU>i83lh$eXvRx%%{dn7F!T?S|~M=%{do)@enwYAq%f zo6D9|SCr=GWF)69ySKJ!b4%kUeV{vVQNZV)w(U8vxB1ZigUw!n2#RkX)$&CYAT}uh z1>Y8_Vl;uaYjpDc`>Cn7W5YN2;&N8HHKsKq9X;GM)a`!W(`p2SC@c^FJa*Z}=7kp? z)0)<uI~sEm-A;$v=y9Noxj-n&RJ^dVw0Le7qZ3P8mNwL%uV0M^ngXkt5WHyXd*0pk z;#F5Zi6ZfRpOjnx6JjcwC*@gvV!jA74E*lLfBf?EU;p`!KXwwz(jWxKTJy@GQ@f@o zEHB=5TSOp*i})~)yQt~d(o1g?%9qEF?9Pod>&;@N!-gp+F@QkQ!o~B;^D|Ns65~s+ zt!&)XvUMH70H_N1{HNk2+4G7^%jP;UD5BilHe$y_TB}m4VT^=|3oBE)$Hzwohb9My z26ivi8EY3S8@6nHwF2QauI=tQ(*Ep)0Thx5sZ^(NH@CI!v)kj=G!*2<rDkX5cr;?0 zP-5|z941ULGB`dm$%OHnH|rkMZoGYEeUmXzF$3Ul$4-3pRr8UfJDovDLb2=RkVV8% zo8)Q@&ls*`0kXJ`@#!h%XKZ|A-y(%_=>j;$7V~sPXy~50&hD>XbiC4Xc^HVvC5fCZ zZLNnq;pz2FMOoqD{;)`!in8!1lT%|cBC<gSz{JSt$T!_ft}I`B<I<XSB*TRBm=KJ; z8GZe#_x0U;07{$Z9QtGe_;Ld!mb3I;1xqMN?)$^v{`t>;{Od1&{{6XCT6y(+kcZ$; z)?h)0H}}6k(mgz3WqcQii0L@??xFrOF`neDM=P>yMx)xIl^_NVrO`?iGCn=|_QSj1 zefr&}zYVXvzIy$wD|Pi01Ay6qAFAh<R+MK~7~L#j{Tf%tl!*W|0t!=mlxzi5H8?dj zJ~hse&~O?GNkD;AK-cYR?Ai`P>()JgafhkiXa$7{aRVUa${yd*tY`#6L~*GFMR{{G zeL}!40<ChjPOTUBjgCye`|x)9?ZbK3_iuP~p>m_15kz9f7F=jPcjWM{JrK$gZrKps z{niL^Rcr#&M{0N!x8%*c_fua_y?Z}Cmc<AQ98sY_j4$^2KE7Z}{qv4H&pSF|WE3jE z4Lm+y^X!4Oeml$(xxCSSk1x!|;}|)7qgbL=X^5e>lOI2R_w~n*4+<}Bueo!!Yz5Bn z0L6sheaH06H|<Yd>RCYZ_PEiXbg)1ciilL<8UZb=p8ngve)+Foe);E5KUJ&cGPy)g zivXHzJ%ICeZtj_W+%+(fNuv-KQid|t<;^p5%}#}AmQrtIe5G2)VOjWGC4gX<O8V*N zKmYTe|MB;K{%2o#%kJ9y=jX4Ud0oKlz#ppC6y(n>3b6Q8X0Jm1Y{V?5G(5FkL(9P8 zn?u9n6XTOZ<3n+Hge*G}CzEu(qs<#fj_?Gl>K?tgUG(gJ2}7N-1b2)Rg<e19iL5jl zn-N=>?}IYJ`8H*-!z;BKtP1(i$i(!=chgf}kF30Xc=3&vb;UZS47Ue-{`=W;XHM?l zH;X3`+oE*(jtMJ`YXn+{h7|Kk?~RU4zkB!o?bJ||(1;ewaIu||muEzG9%FMG8lHAt z%YV^YMpI@<oHNFO0Iwc%1O^;*Iz0*DTCU$LP{|5(Zkb+flu5@Yr{910`oo7$Ba5!> ztGaZ0Z4Mcz4&26sVB+=Us~4>htdiK`&Gz9R4Hz!xsGV|@0;)Rx^wU57`qM9e`q#%K zKqjh$#gvxf*|qYHV*tNybNA@uc>}%kNz_0_S^ZWR8toK-Y6(Z7HrrKXutfn#Wd$-L zEW@Rw{L`O*{`)Wg_{T5*_5I>2&5N#IsLO(wBy3_ruxQEL%1REG%~vQXHu-SeK@rL@ z1&@N)Jn0)A8y*=MAMfc&NzJNK)Tb8XS&^~Zn>W3_V&$!@x&Q3O+SVswTtv*c7dEUm z8eJ|_Ng2};mB!*DXSPOMiS+c@+_+iehPgfC<8P<mO^%Q4-hTaf$)&Rk0YjiM@HnH0 zE}cGozCjrJn^3Jz%$2sjbs&&2TE{2gb?xKR@0kdE{Mh#*-0gM4d)2w1RwYZzjD2$5 z#Hz1-+<A3XYpaVbptw8{3sUOUX0uR<NE{9c9lyV&)^f!e_F8AhwQ@Vi>7RZ(^>&(R z>N_@FI#O`{WOWG1FyU7Lpa1j2o9W3bG%tu}Fsp^Co*&I3Snbz}#MJijKmGIbUw`@A z&wu|gZj)On?r}JqE5t%5nfl397k|V0&XI>3I=jQ?@UT!8FBnvt4JM<AL;<;)0KEsU zu29`Hy9ZQyp$t~@*zbS-`@jDAkH7r+&xh+ToG86~Zb>lA0658nVE*FV)mnX+77*|S zBCK`HV$Ra@QAxx0+dZ9q-LHqbzB+9f&&-LeL)R9@I8$_S^S7_=-h^_i7oC4{Jum+1 zPALv)O>znZ4%ibdLKL?qcuw6Yt$lYs_MXSq=?+J%FfGUXhDJV2jgECqL~lEBHsaKY z6*>zOf(uLt&Yw8A3*|D#QNR!75znXW#w?SFkZe29I@CAL7?JK1=PYmhagH?Tu+{5S z!x~eJ>%mqyboJ6pFK=YWUffDTfZ8A>MZ$ed=t6N&;j*4Om0t68v-7^)(PefbdI2Uu zhQ=qp{dRh)cg)jp<h1X^u_Y88C<{Cr@cI9qe${!^3`%JcBZdL-o4-2E1qKnNJalg8 z&)@y!$3Oo3@#cNss7_}!K{p5w)2U!CC3{qd^HwasGxj7u>3Sm~;>$G@0Yc3tpOOnB zh|1h@BDUuHJ%)CZxz}hBs6s)R_|uPn`1wEn@zc8>BG()`8+GQ?Dr)8#)fJ`}%$slG z2tgu@&*ih()V<e7irBayh&u~{aK@PP1rWT#GgKqNH%XJ`u8H$k`C@98zRWYT=f`G0 zz8Y1(Inkh(D#)36Q1wg}apyoP?W4&ZX|?ZSqwmF7`z;o=PK(~J>0YLE4zJu+J?x(! zafEy5>;kogA)<>+FF1WLM>sn;STTzgI%^L7X!KMGA7;(w&YBrEhGQZ=fUfcmRFeES zs8F{gRaK~hY?eDkrjX?cdC#v!G;EAftHe@_0|3H$txg#lA|z$^-mZ;VIcc{)@;L{! zddBGkw^zPds}KLM`S6N<SE;9&ec*H@N;BT@+zb)5tp$QveBI2I)DY>5zg()s2!5z2 z1cfk(&ZMAFV3}t$OTZxoi-9F+XpZ=|D1ATI$Xc3IHt;a2u`x;}C&Wmo5Q3VtYAKHe zi{RGZt+6e7Z#2Ago5wX8sZ=6-T>s5(hwta(mp8t5=emyY51(I%5)6Q=0iQ>g{9kMy zi!*ajfy3hSuD;F?*}Pm9FJ6lq*&H5UBy=Zu-ee%;c8STS0Msh8xp+nAPMu(Z(s}=a zSbwd4of1KCJBuY*qY|=YB^n~!AWe<h`8G2Cmdp9l<nZe?bp4&K5<k&1zcHsXA}rz% zymx=4O2bqE1K>|bKsGBVBsh3x)KMtw=14BnP1zxwXeF!-4q>tR{O~m6TMx#`61v19 z0YJbaqy5HqC4aHr_vozDdaJ%x4hd0@AegF^b3zrRYS^KbdEC1ubgp|AcemQ;kPv9y z)uBa6vi?<vil4hJVF$q7d&>zdP&ZSC|Mk)#nt6}%>&Pn>|H<#>5m8Zmjv!G_nrCji z3fY!K%^&qtkWQEk@C9rk5QM>3_Q*L4brC(+#I8qM){2E76~PY{Z&HQ^Ny=1!Sub~~ z>!wwPr+V9KrGepg{^mRHHYLm7?`SC>bQ(N|(ESJJ5eNf-se-R(qc8yQcw9tfa{1G5 z53REB=LB=IDzbf<DJ&qk;q<M`m(Hw#uqG@*EoDnBGO>Nt(@j!NF{D^`n2WAy5D7S3 z7L=K;uZ>^VV1i34u0E*tgf~nkMcs6`yRA_!t5$vMdS|{hcC5NKyUQK!*#+iks@0l6 zL*Vs*O+P{+0m%P?^)o2fTV06{-mWol=geVcl%$8HCIs<kZ9aSd`k5PrFh5(E%oBwG zS}t4YZmB~;OHf_IQ8u-{LBM6P*ko?9W_@B^qfJ;;arxm2ho^DeZoO;r^yoZB6)nGY zX{b6fV`}xzq7IAAzC)CyswA;M?MxZ|mka_BaOMQH(r9+3b^d9qSIi0J<y7WIWT&#h zknLAm@1K31goXO}b3+9o90_}N5O#X2m|co$cbwu%8n;1w4vVKQ$<Q^XuHR(j6;)qv zU12q?nKG-NXdQi;Fr%En9^d`CF{$vUokuH%O(w@Kc&=_fi7)`J1$_P;Psn_O5U#}) z?Td_!c+j_;NePZTDl;ksQ91dc7h3AeOAi$bL<vBolor4m0#sLCI1(ms2?VZYp2V&Q z<_jdHk!PRaxqGJ;CE8OH6Vk#Wf!epJo?G$OZjCq6tRwE+eUoDK^yM$g=#273)gk~q z4<iHP18)R;9utJj4hfnaYP3gq!n|Qm$CmN9p)6@cs&6(Rv$E%0yRoIJ=$wzwC3zV< zCRbz}j>vNGh=XI}0TIVIQkQZLTPUkYy7&;zJNRx%yeTU!HYqkrR6F6)-HWvMNF6SP z48MDGIM<grTveC<+~Wve0|~)09yc&%CJBGxF$Ba8<(ZvPUYEz;|6@HY;_{R+*)c3k z?GmsazBsYI^1hZAg0XW1fPjNB`;G29;}N+9!l;u1nM)HY0O^Xtd(Vlo;~y7A8}bU{ zGh(Cp%cgCTr{ShPvE3yl`Oltzvn(O|59^vrhus!$Ee4?#JT?R1X29ovve`U_g?O`c z{^X?M*lTZUXKv{8SaZGv`JqrKpgq@e_0f)1X;2j6CrJUIL0ObL@fHcN`5Y(?L5MIU zxuOxMzTSf*J({jpBL!7%UYyFhWF#^2ZnUjk?uj!vuse6V>;}g`N^bJYSg&~@CIXjl zb1=Pt$$|0U;5i{dp&`Ffg~$3c{dWe}@p+*vPRMWnkAOW#IEU}Jee>?qBiRWM38wJ? zE=$IlB@p-?(EMNyn@ol<aX6M(wFO#v`z4UlI$0|bmMpP_q^V7dMxEA&UPrss<(C@J z2e;pN91+6>i?iD!?ArN=K(u6?oJqn<0iXZHK>!w;$DOVBCHT@}IzMd_GJ7K61kZ+r zESLp4TiYJLycm%zkcu)uh|eNIzZ87wYa>ApCxl4D5ZnnRS8oNHx<;|A_KzEAcu}o| zo1wGJpRlN(yUbmb!$)hl?VV#uVF`a+xV&J*Yc?z(KzP}D8Ka7?2h{z5e!=|*CxpY3 zMLJW`9GB)gi!(Xlr+ApZZhlEgtq9-0GBc~Ogc9lKY=Hz38*B)y5N`xPS`CV%8kbD6 z;^3x9AijN4ZoBh#vjZ>BPbjqIBHP}^r(B6~pEQQWh3jSaA9UHZuAzuzZ)ePw6<H~K zuzGD6LqzifKELG!g)q&4B~W;c5s~`Kxt@91A+BRA$WvQUP_UXOIliGNe|s{Yk01ph z5C@c~SfPBRp2s5;LO`Z<%jIj2HI9gKx<<sdd*k&MVR1=XnL7{NGVSu+^tp~%d=X}e z<iVZS;a2}pQgKw9zkX3tf`B(~zWBfG`H$$FAOWAvhc!{w=t%Q}%IF1oT<>W<5m~>W ztZY4~Y}r}4XpalwV{j>l0YJ%FEH1Q}!>3dLDA$E4q$^MC_*yuB`bV|<&c{s}U|xA* zMR*ah<r|yrp4)yx<%%?j(T<LZSa;I5Ic4c1;Tx7`qyoT#MKhADBH;4}3Y4j>-YBct zZBsd%(wEKUc>*YSfzZiMXJKVRUe3n7D-X@ZKs5^MOa_%q1BqxlpN13;i&<!M;gBn@ z{cDM|?Q2YVd;D-FBrfsi5cz4lCX!OF$AtH~eF;vD;@+)JyTLaU9_xLT`DETXqV&|l zjXtId@|Y^XV71mBmEd-STf|y}wCni7VxDkTCD+PM4uXofV9}PtHAfRdg&-f3%B2KC zv4XfjE{bYBP8;a-ph$Re*IP>8`4&>%89A8BqpRYJq{W##-g<m@e4cK%FH$Fw-M`l9 zG)MINlYP%q9uyx#%8phoku%OHKj8C68q^xy@u@zy&nD5BG$R+5R{(IxLclG|<Pa4A zP_paD_H#}qMtnlf0DwtWC{L7);Raurg8_g;&a&6Pr|e^YrF8c{9E|2r^P>wTd5K#; zIBgHzt{#&+N=@VKPx?I8xN(0%<WS<>iZkTAlZ#f!m>ehw_&j0Inf)>tk!s9lgTXD$ zi6~wr<cdW6ED=vc;PC8SI8We?!#R}EprmCK$QSTnLTk4e3??-s1OS1kq2sMg@q9`m zyD@#F;;Jxub*9P~vwbKzaYJNOuOlkl=+xY~^~U8%e;JpV^&;tU<uT&av5F0zK-<g- zj!Bc==tKmNRAsbi<z_lJzIq*F5P0k~9*c*-qS?D~KHu*NWwT^j96&^zpx`;70=dO* zwc3?4cVM`}&0S-p_T?BUyD@R7^b99%ZH8RyZyX8tZ1O~Qo4j_JQFZs)fXAQpDls?r zY3#j{1IXz^C5t4CAgK@d{K;W3+d(0w(Oa!rxluANYxyRS$7tLfPykXS%08yWsW_8> z#TBb(0I-5WLpfa9=Cs?LYEU3z8b?$A4`TiBpB3u6KOD+98X8xVE)|<LzIB<K9KIfP zm_w|mpFJ7!xU+iWGqU@mZqGYPp8IOvGI5|La7)1FcT|qG#4DpvIiufwE^GI_qH=Ct z0td!oGHMkpJ!1@@5G<b0LX|WD6POeSM2ugEid4WL1cId0j@WKb(5f3>lakA?PA<55 zQidt!Kd;z5l$6vG<9urK`n4wIikqD;UOsz%x9v_(_LYns__4#qweCQB;HrSn{Tx3S zqXa|(QmR(EO{VVF>iO*Km=F;Zk+ND6q~<ca5hV7`3J$^%5mzKYg{;sJ7C$mt4gmr# z2O=zp^}z_NxjT(YF86#@d8(NN$kMyHO(VYWt6s-rgWVxj$yZ%_)$_W$`%%Zk?z9U@ zo8aRI@~i1U{mg;N@lbQHn-+=?xk{^Z8Z6_zt5yl}6S*i6m$hESG4e$y#8TK9&CDdk zuK+k)Hj5n*DG>>HJON0WM3%>&NX7HNOO&_9Po*C@NP%d{4PV_`kL8xf`b2GYQ3_(i zqp5fAra$(N54=x4o4%Deb);k=#WbVpfRo=!BQz!%^S=dz)@C%yvWpx(h|B15gv;WG zviYH3AlpJh0F(;>7zT)-FUT&K(aH)fNJ}Lum0GI7V<TS3C0~6_h;O~RvUqE8Lta(l z+2wV8OMM4?p2xbdB(qk#=2_E$#)HRC9z55ccRza-d0>0iYA+Ll!hn;*fCVOnYz~`; zscmW%om&wZ4TJ{I4go@gSaX8e!CydQLEPZb*`dKRQ#5#hP{<AnX3JGVf~FO6r9_EF zL_H<Nr=}6=`oO8OO*t!)a-#N>uOBM29&@@MDy@+UTDj)&-qQyz+_-u6=F6Pxsf*C& zri@A%Qw6yJCqH2-A;Mz|`65d1F{l+K3uEF?K4XnAMsRSMHNU{eLPTHA3E^>=jOXxY z0EC2cWC}h;!V<YutOPyYekFbN?_$~G!CO&_Bde2A94q5izb#jta9N+o%+XQ;+wk&y z>-A?{ub*|l&AOVgj5@M2w^GaiC=dAj4T51(0T)7<ka9^6e)RGNS`>1HUrlD}_vWt; z3BmB0Q6@>C5P)%t#wZfub9p>Ii8-AjTl|j7jh><tZ^hEb(<phN^+9gUuI8=hjvkNN z+?y4j8fIQ<@<zCfnwu}q>}qP>e|XRFj^#Jz&ck<YEv%0WG|xDr37$xVg@gjIfXCs& zHn{ofCNXbz3ws`#s@{>aW_A#Q3TB6Z`rtXiES^xr1p!`AP;f{n2HR``bM%(twXTBG zlZ4{gB#57AYl&G_ziH*JUE6K-{juS5t;Qu<hf^<8+-$r2RrAG**Unt;UUo675Z>FE zzf8sSf(tY47y!gP9)yF8K_Tqq>DyamAnTfNA)Re(F0Kn@lN2<Y6GG42HW7l50EPrJ zw|`g&XtA)23HvJR!ivuRAXU8nnG|1dd#Ej4P@TDWK_Oi?9%s(6Xcwz&ZjBUw^t$cd zt@e)B?cHB5ZOJPo_HQd$Hq(r*1+;t;kPt>lR9qoDGzjpZ7Lo%CgwZ^<fEMtA1e{O- zE)wx1YV-@T55ozSS}Wji*g~P$qg1LhBSM81mG9^{P23$7D_d4SD%|<1qJDE{Rs8C~ zRF5RprB#O|x{TEB=jRXZ-+$!LffLUb+>Og7nl=?J^9Nc3PY1M21v4E5!X=^n(BL4h z4b;GFVJO$n3g+OP&@VY5!8}yJ7YG3E7s5V)P((@P3>k;8LU5N%rbzS73DwGcr^ZQ1 z>kuJ7Q+Fe!u{C}1+NT+wRihCmU7TGbvqtD;*sj)VXHK8Hdg<Ji&V{#Pl93(t1*Hmx zicbWz{2(M@6sP2j;$?G1c05dtkRl*fz!gbEAdAU+fMRS!2xkU>2mr+j6_@exY!>Q} zNE9g^E?1|HZux^m-u(x;=GK}=uDwsf{Qledit2Zfa#^fZNtvTGQsL3w_9v}RJ708k zykB%HF_YZYSXwG&09**T_D6#fQOjsOEMk~|^bvd>PdJCi<p%MB`P^A^f<pN)%-9hz zN|Ln3NPGcwiv$8xMv4lw@iHVFga~f#y)ha({zj&_weUgCp6=Mx&97FZhL>lAhluS0 zl{?<ylAL<HziIQ@nwtD2uk){ZqoLZeqAGh}c;JD6mbWrWC?g=TVCE(P=E6eRT+VM9 z;{B2}iyiu#-+md)1woz&!~|ae8>MRK3vM@u#T5|(&RkWD1P)`Q11GO_l0?q+(6W0g z?j-H*u)8<(mixl0qRm3wB9Pi540__!y(9bfHZ?YsuNf@5<n;>ImE`483={4O`06{I z9F$;)0s?sgl5kTzE{DaaRDOscR4Du+_$^1oFfb;fK>!fRG%zCo_*^bP0$c`w0<iGe zqR^s_-%F^Q->6jW)sLLJo*T`phs$lYr7?<N)Wjyuks2L*sq^y13&#&0tl9dh=u%V! zTvt(?i!p*^Kcfd^E~gBF{4#|$Eytw6ArwL>2q#IV^&%n&Vgo1yicpQ1Qi>@61Q|La zF_^GrNrQ#CD_jD?N6o!Cpd{-aDAf-d+A?>)h>fZps7<v*&y9kFCYLuX(WV!d-Ff-6 z^UcWE@Wi{EMX(k23ky`HKucg<z~=$dpv71$8!po&Wg0aE05eO75DW(~<bMDNL=eIS z#jx<#yJteC4U4oX^lV=KY9|+Vk=Zv#D6Hw8MEQK#vxprp9M;;=1!2~tL>s_2IGoNn zofI#>-qrqUaAI<7>f_vM#0-S<vLK34#p?q;e=AlQu+UJeRN>6Z)X7PdKnWQxmWnZ& zBoQ1JpcIZ`2rmef!61h_(+!{*0O^t-LH<e`8}#rqU;J#uw)E)LZx-}gcfHanSG}FD zk*6eS_-u{EVvkV~NadrU*TYla{qDQp|0Aagw?aNaHi$F5fZ2gR>+_tnS%qa)-)O7O zh@)my7Q(D5fiRLlX;O*9BFN#~ww;DSM1+vI7?W6)aRkH)`jTf2;sz<SMG@@^+?1s? z+_AQ&9PY|YSyH(p+36^>ggd<+zs+Maiis0_)00yl-c3zU&KIk86DX4DGBG(2AMkld zo~QyO2rHrT`h${$NaFtw0OHh_Rk2uXb`YES@*F@z`$19gtlxx~SOTuzl;`fEps-A( z?uoR+bFeGQyJX=ym&=<f3$uINZnH}#$El+OAK!oY{+kaU$16$w9t?((loXQ#v5Yg4 zMkoX%5R_i=q@yIxCn1>bNF!o}nv}>Tlw7J469^Pz^Q6q;a(SUVKmhS!oj3vlL+AXK z8wT<?1|-%wrV*J+^rlxtpP~7+%RFz%TD8ufhC0kM6QLa{3L#E?|M{2y_|O0N<zIiB zPnz~JJCLlv8FR|)zz>#k87ih}BlcpjDnEi`ssO<$1QcL6Mk_&D#it>Bl_}LKflvt{ z#snsUgdl*Huuuv~x?E|YVs>wB(JF2}c8l+1b*F7>&rZ^N_l2oV*;<22FW2c*W{a3K zJ-U12%83I9cGN~1A}V=!{#?sU6+|#qpv{4VFa#;UXI<IxP7KBoj1*(Ah#-mo0f5#T zbs(e900GDgRfCX7Bp|3@2p6W^tT5yLhP7AK^uvcX>Pgfq@0Ru$k0Gi-p>f6$I)zrM zP|MXSoYp_QeeKfm{rk7C^y=cO`9wjwc%}+`j5X7x!XgwwG{XLgoEWE6Dicd(N->Gc z8NH>$<a$t!<4s<YQA8ZZDezbt2nInBB@ShJMqzsqI14P!I&F~O?e&Xag^!q;y26Z- zn2k8;ju)yVN=mGh$|VS{@9KQkdgbKF=Dksd<Z1y~m_g4}0kZ?&s3Zn76j1q<9fK9w zaRf-C5ROVflEhGy;D!hUJQ7%v<FU|8QX(3Q96=x$;8_GbL{5Y+Tz&rh&PHE0MYTN4 zRNh}ckd@e$mx;RfIP^fe$L)%?x(ytgMhfe$z8UNv9=&^he7w9uN~|u9wkQIPf&PFK zeT<KQ=kR4t$<wa1NDl%r+fP$UOhVz<41h0q<0NNwg-HxDU706V%TS2%gKQm(4U6%p z<x6)rE-Y1Lp~$rdDe`BP1JQ9$5~8s1I=LQ=(%T%7W}7zDK#{Qa>YKj){=w^~M}|rl zD9CjcUMax%0$;$14{B6Hut2qk?w!c+dBhT(LaLJKXpKgx5KBbdFMx3=(6HREA!ddm zi`7yLfgllA&t*eOEV*HRdW6a%S!l%X_7^B$&zp27wD}xdUp+1(qGe`_S8G%Ut8q-I zx-~K}_Vu^VZvOdQ<x&~7q0%Q71gdAIB7P%*2#j%oAotj4Ty%sQ7U2*kQ&Li#(V(oE z_XR=}D^u?3FC%0ol35&pQ4&C{hfc<ohc{g<__QZibNHcJapu}8?E3aMshq~_R66;n zkBFgd;g%?m!JyWtRc7+ak&Xoo7c$-bJzFhypl*>^=M2nXnDE#D%vfxW0OPTb^?7U- z$^RDs7W4&slFLJp`S!gpvIU3+14S?>5<z^ScK6BnJmbcTS<@RLB?sDMbj#Jn*n{0K z<5(MFeX_W%8Y~)?+D#E|wOS^ZN)5#Q)7`7KU&@Xie%)j-fm>IRv?4Gmup!{aI~qn% zAw&!LXD2;2mzu()q)cy8X{3}?%4Q2iB3Ozo_MaRq<bzrQ2C*-Ymn0}s9zJUDTJ}CD z__o%qIMQd7-fdk=zc|tr!&&FC05LmhC<>&lx-hGP2_#AD@aOlwZaVR(DEa%32lQHG zR}D!>1Ctp5pQlwS3?g8yMWC7pkMn6En1q<p1-MKR;7r0ZAIH)BY|+(a3MTqYr(`Gs zgJs6%%V&?LmbVnV*`Mm!)n=0H*t=bLOZFmau01Ic3OiyhCS0l*n^yqp)drbFYi-%x zxv=(1)t2GsPNUDZelBg=6zC7U9q_q_lnJ?zK(1z~hD}bBYzBZrq7cjgfQ5VkMlzIG zQUIKvPl*7=KY@UN1&Ih{b4&APYx1$VeLJGVc6Ms<z5BNEAF7^sat!`xal}4l9&A8; zmM|_~B~z1x%5uB8XLaN4CHu#oSTsKO_A;@2X`plFY5BN94GB>|rREyHu{s@El9H1K zjR6HEVle@V09q=Q<7K7v%_U6gF%1!8<N<+@(o^Tx<hUxXl}~NA8h4C1s6)pOfSs17 z?zuXf4f5_6=Li)%yUxYu%Ebx<RhXY#`MB*++qw&%-guR6&-N0Dd_|xy@KM0$?{&C< zsRL4~oIBuf#)Od|$b6K=NPiqx!^?6om?Vk3+PyR&6oD{+aE1K%ZE-|o#)}W#^2G6} z@s>2*va4Qv9=V-5Cs+_m#pTBdLKJ)z?y}28F<ew_G$^G~XUoA?E0$czj+`9o4!43? z3TfhuFX#)nI4prfc%TRZ>AC%SmBTs%K*9<N37G)^EY6%c&rTMs-%AL;5WErbfl#g> zX=@bd&Urp?Pvm(sJ$f_@tG?|5E2TTID`2?~a>a+u3gG^4T&Po${74oc)2PKH?YMos zZ$r(^yrlO-T`mifr;<m`49M+d+OdY<@R{TSsgn0bRd|@3AW#*b%@v?C#Zy~=BT^-m zyXLSG;zKYBVLTC#vNImCr?(9~#v(_4|NHY%wiWHsNR{e{_&!|`E;Ra_LBBy~i-l?$ zX8;JrN(GLQ_9wT#-@D^k#oRxAJLWZG1yZqp=Bn8slLJ1I4)f+IwX~-%BFX2T$$PF4 z5^?w-g4eZYF|0sCMdb}X5hOw&obYeieL<~ka1}p%H}Le<*xTWIY51xOX^^l{kM3J# zwt3Sq)3IHPqU25-<%0Mnt=6GekP_|XgY7G-k5?@l?LB^zR;cJwM<f%1k$}$~4j3|8 zQb-zd^*KFetB3&*%I5Pz831%+*IZNx(`Zp?Lj)ts0U?Y=?l^c|Ev+?`-W?rozcKK3 z>P`Z_@=CHuwABnYuTtyu-Z?;VoJklW4(5jPkP8ZhSwSO|`tI@04NH&As~LN9{3an$ zlchQ%V@`VlJ`Z~_#Ar@t07Sg=FieDtHQJe})<T$|RlCRLQ3$QZ=N4{FfEf>qkdpY_ zM{gTc>vYABriNQD4gc}y2Tt~ihq)lI%Zr_@Q)=Xv|3l16H1PyV7MCYPE=Xkt83q#C zwwv$vHe9Ky`}Ujbk0_-M&XZ{v07Hx(h_%V>5|ZKxl@n1ho&<{7XCBN@6N;l`{@@}Q zW@K_<5&u3&!n1j0g2VT2UDG0vH|pib@zk90_ix){rMkp2s0hOFMq_SFEOn?<2J!*z z`c)uo^9-tVF0)1~GhS>R-MF+b9cy^0U2N4{+vP2fVsfA*;B$Ah7F00?IXILWaoG(~ zAmfBsBBtaS0Fu(71pq+cRNh?fV-Ob2W)*=ap5DKygSeK2_OY?N{NeZ0kKMQ-xeO?S zAz-sA#vbw8B16!ZK^%U1(i~Xl9u&(>3JEUOUvD38THh82EPtu0(y4A849_(MN@otS zjQA;*3KZZxzT#WI-4HJk%asBYl~9Z|(3O0>fgofOX<nwNi@;Dezns4ItfNhj35~Jc z-+o_G{>{&SePJUUnN`RlDFN<PyUn(LFE#UoAS7e}5DL#*iNYWy5vk?r=#R%5#$Af# zqoxIV{i9v(EG<)pX97M?SZIjP0Wp9hdzls=mq?&4Y0P#x69^o^>xXJU7$>NrTzoqK zpqmdTh^}t9Fs#9_aPy<#0l%ShYWh_qLM!cD0SICXy=BQ^ntDLU;ei0h4T_>82MDdj zVwJ1G#b^6#N_vg7zE$E?tDDwtS>Ona415`|>6so5;f8*}{dqRt5#w@4qmWw`yHgI$ z0HC)HuMz?{CC<-4cLQ8-+mQtL=Ek#qDnw{@J{=m3H$5AF-)<L3)ONOjq3y+vbZ;0Z z?Mv3|pkU6wOW7iie*lteHF{bhs<|@UF#oO?B%abvv3h^~)>3((JFqq2bEifWDh%a_ zL?M#?WS2WZCXF#>9Ms{YR7z{Md}x}vcq-3NrjFnO?9jP%*^>>|CN%_PaCCqCCehaW z>F>QJp~e`-M+g{RZSz~r!U}fi%&_@cYChqN9EBBXg^ExiP0xNfw5W$mLNDdva?|mK z?WK}H@5~L4uQ8qg!Btj?F0;=Ym7hZL5a;DrHWEZZl&J6Dg`o&8DJ(;qlaC&{zK<Xx zc8-k8QPS(a*)x@*&;M$?Hx|u^W&dhqV-kwfRPqh!w(9h}kac^%AY-Bj5QX1rlmYyz zQ@u+|22D!)F^OGcXjoEPqz`n>>_EFHI7lF*Rk%E{*J@3UquH?cR-XeEG62L|2X?>^ zLdx<A;ZqsMj@~<fp%HrqhZHbqaoz5Dm!-`-H1@(R%!+42kN^N;Ba<Tl>7Fe6vVub1 zhTZ=z4v!iH<zad?CEzZ<G`xO6tAtRUppCR?->S9QV#b)<3-~-q@DN0Z$_Yj4XqYuQ zS%t{ro=*8_OiYNiTi%_ZDO#q=%O$RtoIBTkjFzPDd-qX^qelDV$&ab}{L??av55*( z1;0K^$cXT{Df^}6S%(_xr3cQljA4-@BAHVq!$qRTXTRUSVuUBd&d6*^*NM6<c_c%{ zkC|SeW;}=?4wk5Fys)UuG(?VobuVIR0K*WpzJDKvVi>hx9@cR7_Vv4`rKJ91|C9<v zy-5YHYHHV3UU)a0g)qAWK?ou+dh*Irzl5lnYs@H*LYtx^`_wUj#IN;FRG#WtUeRZg z*>(~-skLTZeUvJYoH@kuSONj4BwT<?3_P<nDgl#$cvEj2DP#bUTL<>cFtE6~1lfJ% z(St{)3Cwi8|E(GpSmNfsT(!2Q<n)KvaRSCp0wSjLjn??=xGz}9EG7j7zvT(GhDG!% z;zWd7;Tc_dX{dhbBL$(}MXE4o)25B#L?9M;IpA}zm?cCBTPPtlLw0LaveYDz9vsh< zz!C|q+VbuUO-ZE6`T69TwwEuuF4BbW-uvI{aM0*09jaNqto-U<$0PYOk1|9s0{Yzk zw3t~^4I82O2#<shg!>0%F?`r2j(E3)se*N5A{n_`Y!Lg8?A{%TG60wz_+Fc#)!NO$ zlrnd~WeYDSC<xZS%w`k<iBe7dr<it3C`u}j4L6q;PM#uQ`PGg|9g4fWx1M~nJg4aL z@JJGZ;0Oppu!xSSEXg%4*k^_W97|#veQK_6P-W6tY`RC&%P;k;C>wHO&T>LQg;y=# z7%gMW>Cu4CZ={h@gUcE!*A@(#RmNfzhfrHjHUz>XLhl&(6@aR&0@!wQP1)#4#$(;? zn$p7}z4zABZ|5cFUYhLp3K&Z-5&@uq^5tj8(z(@W(5&C^DIIb))jK4&81-t^!|`?3 zdp9j=(+c&alnnN*T3g42KtBUunzB-cFsD!^&m1wyEfq2aN!rJ%NQ6?#^*i3(663VQ zR8ojGw{NWY?uwW&wGMx4!eNc$dGDVW`R6|P;X5yH=D8W;E<k;BYNDUcUyKFK63Wcb z`OL6UsY$O<(Vd_6cYk-RW(-D@g@hW3Yi!&djWO$=4EWs7hxlBhUM`fc?}+jn%@~M7 zq9+Rp0G6O=eeYEqqNTEuQnVmv<CdwjQUp73?>*Bf9G<J!zg=E1x8==PjF>U^zeWIw z%dX0bbH)`dSaUeCDK~m=Zo-IB6KS?<?@v~>bXS-4YpFOtsZ&N36mJNZGOGOI3=au~ zgeT0R2;2E0+@Un1LZ%0`FT@!D2)6n4uK*NfrC?R=)}7;LWQgS4!><((SIYqSt~@RM z+{mC4g`xkB02ZB867Nx~DTyJGoo9FNONk%VsG}L1dv9dXrS8SmtrX;PVlq5pUgZWm z9%!36K+yqWT*zUTV`xQZq)YEo5K;o}+Ni-Ptz5Nv@~Ie?s|+Q1*z$SXwtc#;B&Aon z{-9>euI=g5pQ|I&ZhrXWgbD1wBOs0RWrdq18kNqO%`0)6_h-aRs8o?EHP!xYZQInQ z6~ipTXhu{>%*y3^d|03(@NU4%S4OQW!NZNUN1c2f?=rXm5Jn=}w*UZ)Vff1Kdl(~3 zaC<RWl6iLD#APKaJbiRbfzf`)l>_f9)8fzejYf$H9Q!x;8aF;>cT-|a(z-a4HnpZZ zswu_y!YDiJ^H^_<SKWKvv~x0rjxo)1Tcb{8Y_=)_BN#F8vLhnQRg@ymi_5w);MYqW zj1t7+U;es0O4Pjib$QZRELfO%sd?lQLx3&E#}x={n^`_L(tl!jz>YHA>fgX?!UXTu zE%E+{)qVw$y84-8OSHFBC2n?@j5miCKN;M)|78Rmrme8+Vp=ll^)%B6ndP5449Xbu zmkzD%&_uLO?jZ?^iW@k})W1xjsTu2{2}-Q6=R!5*H;;UKPfH<JuY9K^aI?AX{GW<U zo=YFTx5G3^{2O`=OSCmMMOs}eeY7ZM)k||zd|0<qe8^^0KKZz!`+f7_cY4yIC=b&o z-O1f$K>|H9Vz5t>zFH>Ln(Zks2E*esqbL%j(_SA!fti>(yB=W-!&6cxm{wJHc=DPU z1W#@pHX~$GR7>4>Q`-DP-J@Yfl7JDI`8$y}t?iq#l<f64|5&oHX*_&Ky6=@rwZmz$ zJea(H`P$`8V=l3J*`B7Fnylh|a(`fWU}eDPF7JY!PMIZK7xsMI>WU1*F;J4ze+UB^ z8H{`XUjSmKAa6nA@rkPvkZ9RFVuoOU#O1p2wGoB;-V7U6%x54F1R%hZ@L(b>EOL3v zbW%axkaJg@w?`~#)Ts>jN1r{ocYS+@8j-F%)Ks$}KX;eJ^WOkE6*0?bSZ$=8uRd9A z(LRNoQWd>xVHilEP=}B8(gaQ_q!wtwy4`1f_fU@E*Y<vNFk&$L@!n4xjd@2Wzc(mo zib(+!VUjYj?f1F%u(fwSr4(%Y+O{Jh><um5qE#q5z8@GG>usLE2y*3DyVf_B<?N@8 zOdl>~LLfF;nzmkxZavi7A0M6PL2yEq*Zvh_!X+5IzU$e{m1Bw~!2FuU$NQg1QSyAn zJ3T?<C!Z~z+LJNw*rCxl8;v6<41+LF*K>cUSev|T$6)TVg+obA<zdg{>cbwV;o_qM zhxZ&@J?54gm)|oGnd_SNE=~^2nmO0c2xdpEr$)9l<N2h|kz`}aPFLFX6()ovII+3s zR{$7}2#VIPI63rG2Ge)vztdxAs{c~i+bvOfM-IL9s7dtKr<P!l;>GQuRI$H$$LqxE z`EUG9dG2SVWVgv8yY%4Hg=1&8b}2CZnsz-lx1n+8q8R`)Cl}-@)4I~r-itLue~fY@ z+oejCWAWH!DNJdV>MhfQBu-0dF$pc%w)*^sS4u+GvFwwD!jr-uF8g7>E9dm_-+2@g z1|rIM7_Ru$<Ecc%RdsMGu4=_}_@)9!Cneo$G?MpU-|Kkv?8vYJF>jxAQ~C9c`xZt8 zrp^pNd4FPHFi~rzSMBQ<P7lv7fMHy@u<Z^B;8H@m;bprR0SS^13*8ObCtr2T3F<=9 zTO$F+MIDJ7yO@!ezIrgriZZGRMsSFcafe?Q+LKE*O=V=~^hazgkDbu#k3@JK7p`ty zyKUd%J_oga?F&1IX3t-^c6DII%<-8=am7a?_$tNPEnSoG#^fx<`)gOcxPu81DXD6F z^(z3BE#ii6%|HG6l>!srOM7d?gdWGq#L<(n>FKM-;#DvL&0NO@Fm>FqzGSU`?xwMr zl*}Ic#=Mvbg<_B0rE9soyK&#~b?sVm-G&|;2b#NJQSF+*%9#U1ziT}AGDq*%Z#g{t zW3n+Nn-M<tjl&&MSgcdqwoVNzNK8Tr5K+p3qL#NKYFhqc?zc7ya9OYCeS0M=dG3a9 z<K;60a!`zMUfSFXWARc~&d%>6lZqxSwFQyyl*)ZJyW(!!#Zwm_?0BWZw(orxB|>s4 zm#$k8SQeNY@OiXid^%R9ah0uo*c;^v&w(hKtbK8pgkS<9R<%CEVFVDeIRecA-?82v z874a)Iibge>crjd;aiCXySI!b`UnPq^fE%GR@P+nmpU_wmcCEP$Q(}ETNBw~(VTR; zbYC4^k*lxC?{X`$%n}1;TE2LH(W1cQnKu<LBJO;QKuP_Q?N9r|wZ>G0q$CZm?qZA` zh9&FUeg(h{4&msJM4#yEl_QF~Ok7bO={*=ebU7k>@0KZ_bw)XhFG6^J&E}%PbbU<D z(#eR#v_Ajd#StA^=^>p}a_sQhVrzZ*Q>QlDCes1NmGcjjE(=VXnM3q__0;E7u~@%) zf6upmttm~c(du?jypW=VLTacR9265ID&la3-t%$irpHvIrX%&Eg%n_6=aN3$v!ylf z`oU+SD1ww<#pwAPk1d=`mV2|-{@{(ze;2-Eskd7vJFGR~m#*$u7`CUT$89QgNDQ!H z>AdFhh5svs34niaESVs~N>)62;dUg((GX2<>Uhp@JC0LDFP@N$91jg)bI}u)%kBM2 zTyw@c>BJ#*+(EqmNn%mczKQH;jG$7A6Hzf9p0jyqUT$`N<-4Q;_h7=(1<^;XnoHqE z$L^C^iA9BF_q!hFofKP<#(B95R-^?+2Sze9lsNV#Nlja;8y<H%)!}{#NGY~=KSx0j zC*>7gzXF&O6dX#PbzgruphR`IoD+6bNP3Ra0}mo{ckO$Z;6gAWsW2X-NPotL{`|D~ ztjY;rwxiFtq&(`dL3YZl(d{{&mtHZi@@DVTf|HmL-%*via82g_N@OY^``eFmb+Yi) zJG!Uc>hK7aL~A@WJ|w|Nxx!FA*(W7%n#JPqR5v{jho*Ft>1pJ5VI+)&UC_Pjw59Do z@`nUFNr}_Sk};{oUsgY!5gU=Z^m|W=@2zWLh5wjNe$Jp&9KTVSQ(nEceRN>?Mchd? zl_f5!O%F_%8HDvJd9bHIZFSdFU+IXA$#O~w0^j(sm4Fy#fl{wN!e$N)i4ZA#a^d;M z19C*W&pQ!8!IZ9EGtgF;y8UQ>flsP9Z&=ezz(R=vdQ~zvC$D@wK1J6V>nn_n*QzeZ zdaVgBcGR6Ka)eRzDM}o<s=0h+?e=wnVKZ~6hB5~G^CenS-Ljj#K6|u*CM1%kXKlX% zz_V{LzW^9t#7FRRHJ6?Z$szrj$nkJY1S%UW!}n7ncOD&1wNjF^hMGNq2#_m;FACBV zvdf1&(V9-TzaS!7EkEORsgpXkulp+3Xs77&1njRrQ?+z?V;!S~m<sr&?8A3eYO}4W z_Q}_=)<}y=rc~~HJ*dFN5}GQ0-YX|@38OS=sI{i8^Q{iIUrhZJB}QR+qw8aLbol<$ z-{)B5s*BdmM-UW~8sYx*=*Z;x?_5sZYg<&lCqXX1=(dWp`nRq-o~E!W)VC#Y%;vLY zRYjZX0{wwm0iU1b^uDT4JH1&2$6i#YmdDWyndRSoib4>H5f0HK6cFMN7ZnSxmYusg zq=fbB@_UOYgbH_`f7z8$(%AfZO%g$!-MaPwNi4}~y?Hk;D?g=bDm$)zD9V}RlMATU zxM<Jj;T1)xxeJvj9;E;e9@{W~^|nH$0s`Y0HB{I)I8Sb}=a-%8DGg5#BS=zR-unDk z08|+KbOr!dC?t`ai(77uC_&@S;+{MV0G(miUbRJKZfzb|=*Nh&+iG{i=+d0lTUS$K z;^L~t;=Of44o9Yw;^B9EKJ%8LiddUB2Z0DLB{+U|^Md8&iCKX$GXTaHO@F^a@AQ;a zUw${=ljfJprG~2RVJTCB5_y!QM~b6T0z(z>n<ee{rwy2M|H8=<F$UYccg6?YDZ5U5 zv%*J9F7InPN=Vjab=-X%8y4wb^fAU<KWVn7+i4d5D9o+i{XX4DsUo-lnV^EsUf(gl zIxQlB0l-wjqoU5P1&BQ|H`n_#-@n*L;W$us@fj)-VYoyDJ;NDyAQE75ZcE9PGb2ib zEL_?@kHm4W>3n~0QR<qFZ99`C^y$M(56Y4KF>Tkcl;x)+$Bq_e)W41+3>k_rX<M4j zv*b-ed{x>Kl0b44Pj+og3|pI7n!w}$!vkGauLl<+=CGnde@Bk3)J5T9Y{89={{hf8 z0{}oc1aM{H^$TN4h+e$1uM~xaF7vgaj?~E7jU5{!X!^`oD-MXUJ&{kZpD#%F#m5e$ z#n-(K!_@JVi@qOcG%tJYv8Ff+MFf%|d48}lIjkl+KPNCQFgxJ$*y@Sz)=S)x^UC6f z3d}_wg;YT=X&q&}r$nkn@LooK&@{>si(W11z5d>St5(*(tD;H3VY~BTBqqFm>*!X$ zOnL3n=2J@P#l)Vc_cNlM{-mj7PyMhRP{xxM`bm^Vy>>!Jxzz=jg3i~xI<+<4zQj_H z$q-Rdz~_4@&tELX6rQ<Ku%oW<NHIwvNb0VqFaY2*A&Pj4i*OPwO3Z`K=U?2~uSDR8 zlGp1=5cL_)KYN{#x-{i>Q!YU@AK!EgBBhZh&Sj*hrDQm!QqwBiBaQsTq)7RL2!mru zpM)w@AxwMCDC#|vY~NK{Rl6auDsV3&$#c8<R$x+RksR#an18T{WV%}J!RP-C0E}&$ z0l?0{RiaDtuIwC8LTK8&-nFQJ?=)TOd>I?PJmta0B#ip%Ow(5)l8iicDJvr}BE>lo z8B@`2SBFGI`z1GAYQwTO1d_)1Y?R6@8Mu(_*j2EyaZ})uz*7OA2P?)tHpsNzay2o! zDQjn;R3VoZoE{dVxKyb?<9p<oRF0&=M)2k0m;0tnxFmP^+XfouJIr^6#y#HJ%&sl* zgskP(;Y+w&9d_(WVT{)u6ZV}itn!sf5*!ifmfW++R5g>BC|Qi6IGQzo`euw~%iKkK z_5{|>JQ#WuwWF<3X7wVV;`+w$<trrw1SV;pl0s07U`Wk<9Kdk#|5MU+e@9uS?L>CZ z`Of~ZK+3eY_cDDleJ0a;&!kO~NiRb}fB=FZ2m&j;h#(z|1PDbe3y7kC;wrj;N;L=x zNr2FHzjD5_`?(uezBle4Fz3GJdanDrultAhc^Wf0urGYD`?7%`jH>K95+OqNZSP;H zZHO|CrAZil^W64+mU5)4_88@v`t16FrfBmSzbTxIrxYKg9j3qq9D1K3Fe!KFt81r% zb1J;oZ(PkE$iJ62ezEM0Z&q`LQVdaixWY4MHcz8yjpYLSD*$fI*$Du63ulK9r;pCQ zY`{>nzHS{UmAS0DKmI0_3S$069st_$<*t5~u%{~aS><KPvNbnS?xs&Ha(5_{;EsgN zhVTVccAS6!5&O=iTc?BbGmanb-p(J+f0Q?VIeTbir`GJFQPug?_KsO<t(>g$e6PVN z4a=)v|3;3poIHct!Lu!=UmSE0tizVuDu-oud;i5dp>PsUE%QLkp{qwf)H23c=8ypo z1yZZ-r%jFLjI1-@4{^uCT5a?ag@4SVpols#F#3t7CvCa^Uw_H}-~92s@l&SGQ>$o~ z5w>pZ?bc^rL~#s(i$13%0M63*l1~KXuz17V_M*d@?X_2IIK(UF>=f4avdD)0e{O4% zqk)`;R=#;*c^6KZs;nzeaZP#o#_!9cq}~>bRhCECQxTgZya8d=rJ?p!J8yjvo8FQ3 zrjFnGA^&dvpr8R;_qnxnsT#7qesCHSYJ&)2!<1b3HvoS9XTJhyYp<0ax9n}aVnd~J z)vTQ~2nU0kk9=JlgMnBhiF4b(eys~9bY-SxNO4&(wC=LkO&HWJUm_8rj=M`N(RGjj zAke;M@7=FcGjbJy^dAR@^6%$A$Q%EY|K%IIlujdP-}*rh<LRJON{T|iQzAI0R%*6f z7Lut_-q=tJTnHX&9`fO^O83%!B?h~LyHEX?_93G3c8)i{b9?(jIipUPR)UkGuHc$G zeiLq1lzL)O5A}gtZ4AGTsm-2H*XAS7Zr0A7mUJX8{`8OhU-JKzxBmn!eSHh-EQtq} zuUT!)zCvT9L|ky5gk&hmAal-Pz$ENeLstvfN4#OYk|8M7JXfy}!BhU%!q=)Y>d+j8 zgW@+H+j58?UDZe#70N_2v%U$JhNtU2q4sh+vOj4v8BzzX3=Cd9vLt)uhl_u{;+-|| zDSiG>{&3#-9|>UB4&J4WhE}g%!TV<rI3)v%geg1$fO+)`48Sn5sk;?EtlVL{lEH|Q zMZWz6AoV#`#lMY(xWEETM=+Z|*mj7(Eh$+7^`_jZ?k_DRp>EdbYDieYT>-U5A35;t zz|f83e`vdQ=hCI`JhSf%J$RV^Q0RjFpUJV~{TjE?@7ug<qrx{^uGGM=>}v+c7{QZP zeaE7c=o{Hw8-CWbw{)nPV2!WFj`FCqv~*L=u+OE6EW-?}_U+FOpHk4Kgd_pGVzxxr z4I3AnMU^<RQ9ZaXpipU}$L>6NHhTWemmdA~`mO8ESx^7*o9B7s+mWJ~>rkuH?_a#6 zH&odqR7H#HKVx7CDyPt%4{;FYsP<eAI;31Ax}0N3S8J$G0hPqH^WkqZ<%_D|S|7-6 z?mhG_L6$ag#MbiAoQk;z%B?eOdPAf!;?&Ft+8r_D%rzfouVv)ewM%ACWYM?RNA3;h z-<#-w%|Owjt*FiE4zF0&Yj>p?OyIxeJOxewU>AQf0f23p-Uhv^Uk+aCpxDUl<N<}4 z_ww`6Z{nfF88m5^(Qou0eV4$E864gabLYZ6eO^tMndLkgf2p$Fr8PygbJl&_^5+Bw z-1yEBh%f%`_LH$k`C~!{{Is8tu0KFId?w$<O-G!Lj7q8G!Q3StLl~VxvFxJYg~I%7 zZ^JJ*R{%fG;WX)&Yv0p?3JbTCz7_GWYG7klSibj<pPp6FhAI?XA8~aAX1?cVr&%f5 zRpm7)JDnOsK)s~*>b!vri#{3gC*rT%{pmN)1^JI}z%32UgvsnMF3P=cZ_5ZNM+SC$ zCWj|(#>N_tU@%M*ZPVL<-M~W8*;TMCn5a6&(QrtqqG$V}*^2V43#9wD?K!{@hAP#| zo$WRL8ao|z`aDWD;WhhsWx(Zha;uJhvGi*vgWvknJ)`-(yTe0w2lEH>NAkx1AhUH( zM=VyeVR`pSLpnqVvxn@t$jYQb945Nn!$6oNTBo<cN1z4bvnx@!EZgu7j}*IUo}Fv6 zRhC85775Y6_dq|62*G1kLt~jCVwbzrMk5Rb90n)JxXorOz3uq-TP~Uq{Q4KpuKEu~ z9zJ>~u%G`p@25Sy`;|qc+oRU4TX@cxjLGF{1;5~$4#m_e6*K)K79$jjmX>Dp4E2)a zPg_~KuD#`BIW09a8hVk_P?7Xc@c+T#k4`HoO@i#Muc|b;OiCxC)`Bvh-C(D9r`~9$ zd%t|tcilm8&u)6Bm7n_Q=idtI@5L;Yt(d}~Bxh&$7-wWu7=@vArxh^B5HwJ}6h&nu zS=Ty)*eA2vPVAsCzpd>f1**!Lq?W9uAsb7V#US{t6+3zf+}2>}nciJr8ng9jOWi8Q z?1mwynsS?LM(gs!pD#XVW0}k68l4M&ym@=%-q64Oe=kznJOfghXnbLFuc|JrfJv5Z zKgY?W3`s)`uc5GvCTm-}p@U+R>(q9fhy|yAtdvqQ736FxNhJayzYl;9tnclEVMDdH zqp71(=_x%TXO%c^v;#6LhuGD6t!azE{&_uuegAp3bm8#mgNOGg%;!Pg|DD!`=P$*L zPLh0O#yh&Iu$I-7sAhaqf?^uA8f)Ch5D2fVsqKV6Kuq4VeLPp0nDLbg<x;9*U$;5z zcY7Qzh<bm|$rBuDtduu2*4L=bmct}WLy*QIm6>?lD%Yt^d%k*n;Ia*)AAVPBdG&wB zfBSFo!#aOfYNVA^W2|4-TCF5GShnaS1IYvxqN)@E5;C$f*FkLI)2)a0ka(<Q)>#Il zBK`$yiMG1-c)G0-XSS`__&R}WtLhrF(?3aCc2h2gl72O1h8<zT%<5HM_oBDX%sjJ3 zOMZ2_uJh`hJNE|r?+V^8B%sZ>xvZnu%u>X(^ijSnB*$0^f9(@eDkgBj&8rX@0g@HD zc4()(V*1hDD3LCG@f<4y9iCS=LfK@sKTuVPaeLQq+XBOiR7GW3`w6Fd3t~{g=&NZf zVD>>eLcus3n+{!C`Ne7_e(h{^?()#1$3q8&{F6VHH-1RvY@080X*g<H-A9^4KqJ>{ z*bQH)5JaI=(AGv8VNqpyLkoJ;Ts!+@KTX$o=U?J5)Z$vc1Fa3k-QHLnRUg^^P9I0| z;b=6KJ?-YU<8oSty_PUYEpFH#{3W|%=jRW0Uf)*2Jo+lxJo5Kno{xX=^9zFh_sLYH zwIUAU0KfYLGq0iq<uRz?xNr)B`5>qcfN+E;>uAT<RtM{L9-?t4GxI!)QATS9t*j~+ z@@88LMQq%;sstsq;p$n(+O+Nf8}zWm%Bq#CmO83%WvSe3_2hOO%^cXk6W?7-SJdaa zUz)S%-oM@F0IZL+7H|+IjfFmh+d?G}!&2=hIZ%w#7{;1~9E1_6jy8B}eX3*MK^*ld zXMe^)klJ1kha=&5I#pRsvfB@CGD4`zo67C4m+P$(lMY2!*KJ(4*ir^DW<qChzTEdo z&+#{S;>sC|(^sC&b<7{lf1Lj`Z~O#psh%y-(JT}#`<iX`o0*al`ONb=43TSjhIgVU zL-EP_W}<&)w&&;xh79ZGUQ!71w003buiKl9Mq`+=|I9%jL#yn;*8LSKgF$BDL3Dj? z?aIZb1i%{+Wr=guxmzo~d|S&uxu|!hYMQ1m+W6}MyaB27l?61$p+?OKzNUvFNl=n~ zTM3FujD)2`5kx|`v$GRh7NDa``!PhPYCK1wIPR!PSZgY?m38F}EVOZV^-BOrIMe;T zwQ-NN!o#w=gPWIRZoA7_z20ba`BE#l`1aB`as9-?<nYMo(1RNzFWeEzgBnL|0Rd64 z&2)-Rv~dK8!>xyvvLX^EVVEzFVi4)>%)uK{%E~_+hCz*@{u~7(kg3e4ONJAXRH&T5 zb{wo-0N{ir)Zd$kTIF6XMD8u$v!?E<Jwd3|DvizExMP2M4}oFdzdI*1aQnwww=X{w z=pW15)yJAc9e|vW;|}kiRq>ow&C99o6GjA_q#U9!xd`TH*4fmG_BL4>Uq40D237M# z6@dZ9xI-28_+0@<7~>9q)b$!pvU<<^2g7kQW@aJo?M(lg`X4M&Oqk|!vvd0KGp#4o zDE*gDa>21DPshgY{&Rx<H$hgDo{GUZ$cm4b#O5dnmK0;lG_VX4*58RYGBAYncXv=T zEr7P|9THb#g<%xNaBZl{(v@y%$y9f+=!TM4CSzzYTwXsTp$@nEwV`(_-da`G`I)7P zHR<F=x22-9y$eGL>iX$M<?TCn?%o@{FKj?VdE;B9tf^`$EQ4io;DjOAqrxd3VpnTG zF-FmFk!*?xM(AL78?wNI*gB7601FpHQ4ofBS4`U!NLR;Wbp*c6zGN~227S@S86KrO zZDd35*S)hTGvlnjjL<0wwcS`Zcjjyq!iZZR)hh=_Mn=cRp5{Nvf0*~TK0@tklF=v$ zD~SshPq$H}Eg`jAEEvLT)RY7)256S|w>F_`Q*!^jGaRi3CzlBZ1aS6%vep@ndp%_s ze;~3(LSiY8KR2gT?er_yvXgCR`>Lm%*CjEH98+42Z7Y^6R#61|-(Obi{_!8r^L~00 zrm1it3JN&`IHqV{U&0Z1fzFL1QVho6sUlG!Dsa&=i)sy0`shhU=!aQN5}A~MW6i2; zx*=U#)1ZR=^Q07xH*biQ?~SW{SzTsN>hQ{!1Jyl_Dz&?WWnGlS=tBq;BfsB0KRGx& z@?g^F3xe-%mXY#!AtVurDe3#_=2aS&WJQ(`4v8>?fF~DBnGE5KqGtx&ouF;0QzQg2 z^V%d55iIsq)9FAem`s#YP;8L^2W(yw$h_rN+7t5Hy;UdPSP`k4V@mRN6^dDLnbi+r zFoNIM`(pgw$mqi-PoBQ;EbpgYoYPf<6bu6-d{$et+^kn?VNbanhj~H&MdIQjN-pPf zoyg)^tuK2)K@;5KnHVGiMXoYD<_wnlePM>n`~hYNtY@RUzR#|<`uV2Ab)OyF<SFkl zCRnQiMr|bQNnsRD&`<ih(|`Nt_%9QgX9I$wuHPd7Afsc4bTcdE42l(^%BeJfQz%gc z7Zt)VWuDWC)ub3T^PvLQE=v9mWel*QvZJCYUel4uwlh?2Dv6=c`a6NDH@qd))XKiv zJxkVQ!}?UP7I$jp8XrgKK9vh(lE-FsDhCDzhwnWa6K0;Ua;}zul;`)LSOSo-e$BKb z!;(}nYbqqAIE|uHM8BU5!jyGRPS#S%m{cDN*0{W8DoW|3R6HB0a7Sz7Wz{e~U4+A+ zXv2WJZmUg`MAr1z9$2@dJz}cxR6-Vo5IPx5_c05j0)U=&ZutJ=XAhn|&Ht<5`Tuwm z!}v(Cuv)`x`AJ=KL|vj%11cxL!E!Cfion7mjN;9mt-#D?jm>mXOWD?SLL9Fbli?~~ z(&{Pq1`@bp9zdfQv}@SWw8Nl@%GQ0*dURKRyIr1ir2#8XFkU%j`J9I_mOC@IUj6rf zJ%2tv>DSb=5{5xzu?&Pd4?03zBCaG5Tm(p_;Gkf-ba7FE3>TK}*=?A&8M8|M$Rl%$ z0Spn6DPLaS+EAaKnQQG3enZfpwCLomNMe)yrJBygFCN_RS|;o@+FmQ;4Xj#i8CJo& zK%C#X_3I<o@82035<F-0h5LEqi^YIUUnr3wGmm*AOe`c9$`_zi0W3sa9G^O6iUdV* z`Rq0z*#<e_(+oOK1VNx6J}gvLo``!IYpOCd0wAPJT=3ylUwX5pCpB&9f@53PXX74& zZB3F?6H3xP!h*Y{p#1Hf-yHv8Z1mBi$4{S4NdIpePzbSzL713(GL`0hUJXxk5`q#D zuw20~qT(WuBzfhudbny1ZYKVuCSD;Z!P_wj7EHtgersJam}E#)uxCJgX2@T=-7+iH zzVy{k-`d_5H1YZsVM>QFg!O?OJA@&szCE`-9{EX#o6CO5f1dwK-uT4zHM~e7i*O2u zhln>*BtjL5iVKUR2#Mf@5|qR+obKtuYz;EMG>f1j7$-ph;l0WFnzH&CH7$+Jb_PKf zlTzun1CjXJz~IP^>b|`%20Q_i=S_pt0hmjT(VI$%h7v<<voF4P=jQFfU&+rO%@^qJ zE*2HCMIuQ`t+Kn&a2+84m?D-<Ef6C#f=(4p06@r|E+E(}^2=ICq(FwiQb3H`{AE#Z zvN2X!QEemuU?C<J?|93fUhBE}<EDytjx37#f)fBr&BY})dEzE5)(CCgHUImM9t@3+ z{YroS)BI<7CtiUi5~V~2)|mBfKklw#<+MU11B*oft)eLrKyft9(79GPF$-`3IT{w@ zld$tRfLfdpk2O%`429z+7DbnFAh7RUZ}sNT{fC>gpMLsE*lAH&HmXb(iPpfU?ouKX zBY|@Zhrj)KV%ZW7KsbWDw{l342r85a`g7RaSXHeaCy9x7aHhZ@kKoX6umO@%P46by zdE%l>87L_K*E{f4cA@JVYqC`pxg8#iB?FKYy!J5Cu)N{Np&v)yUJ!Q&OCuXC@hH3B zYAmh39eRD!hSj;YhU-^v4h#<7y?1|j=!Ma|-g?Q@B0v}}AmXr>0;#k{s9sPwwcz(4 zs1T}SlZXKtS4{7Q^a~2b^%-#D<9SGeW3=8Ih*c!YLZOB&PKZRkQjzS&J%8(~wYLVZ z4ZpiQ=?+>Vn=P>*zQ>@~)eN}b*t&6DXIuM3<*~7ckDomrd*Nwb?@X*viWbXcB<n5p z!r_FGlk*eeD?kZ7&5`UR?y7=UwX~zQl@f7dEg{1R6h}FVRN3sFh%e}HH*9v}9F=5Y z`0jsu+m|;zelqZ%XV=EfX0?Bf#_c5DDp6?b$09p+ZradR-|^SKKNmcI`Op9SmHU(B z2q+V(6-~ShFM;c-N>KotS|lx)3cxHvqc}+5FhR6-vCt}gmq}bOaX<Vd_)na}Q<)A| zw8p~mWBaWX3IrKo^4@`#%K1$<Zaz5N6Lp4l*|p|)BtYINHQTCh$1km^sjP3#-MDr0 zhued9hDPs=z95ACutX{mxGoSOCQp&5JZcfj7fcmRnJk5QjKxWm5fUoa+J$p#H9a2S zcQOEkWB`mAt<j(}Qsc2X-ri@#K(UvQ{BGa1`r7%~Yqy7wFDY{d)m7{5(SQfOX*OzV zeu!S(+LWztnR)Nt;JwkY2aldUng~0O^Tum2;V_FuB8am4L0LTHWN@~)P*P9`Q94e; zD_FIP=ZV@@O0&Z-&o5+Qj1eXnMd|h4QiCgL);f+Iu+bQp*5Q+n+^@^dZhmn8@tM^z ts}n0*ZS-2L$beC$u76TLysxo7Q#I=^|M#!)pP&CCIR7vC{}K-1{{fpg_ND*; diff --git a/Lib/test/test_audioop.py b/Lib/test/test_audioop.py deleted file mode 100644 index 3acf1bf070..0000000000 --- a/Lib/test/test_audioop.py +++ /dev/null @@ -1,202 +0,0 @@ -# Test audioop. -import audioop - -def gendata1(): - return '\0\1\2' - -def gendata2(): - if audioop.getsample('\0\1', 2, 0) == 1: - return '\0\0\0\1\0\2' - else: - return '\0\0\1\0\2\0' - -def gendata4(): - if audioop.getsample('\0\0\0\1', 4, 0) == 1: - return '\0\0\0\0\0\0\0\1\0\0\0\2' - else: - return '\0\0\0\0\1\0\0\0\2\0\0\0' - -def testmax(data): - if audioop.max(data[0], 1) <> 2 or \ - audioop.max(data[1], 2) <> 2 or \ - audioop.max(data[2], 4) <> 2: - return 0 - return 1 - -def testmaxpp(data): - if audioop.maxpp(data[0], 1) <> 0 or \ - audioop.maxpp(data[1], 2) <> 0 or \ - audioop.maxpp(data[2], 4) <> 0: - return 0 - return 1 - -def testavg(data): - if audioop.avg(data[0], 1) <> 1 or \ - audioop.avg(data[1], 2) <> 1 or \ - audioop.avg(data[2], 4) <> 1: - return 0 - return 1 - -def testavgpp(data): - if audioop.avgpp(data[0], 1) <> 0 or \ - audioop.avgpp(data[1], 2) <> 0 or \ - audioop.avgpp(data[2], 4) <> 0: - return 0 - return 1 - -def testrms(data): - if audioop.rms(data[0], 1) <> 1 or \ - audioop.rms(data[1], 2) <> 1 or \ - audioop.rms(data[2], 4) <> 1: - return 0 - return 1 - -def testcross(data): - if audioop.cross(data[0], 1) <> 0 or \ - audioop.cross(data[1], 2) <> 0 or \ - audioop.cross(data[2], 4) <> 0: - return 0 - return 1 - -def testadd(data): - data2 = [] - for d in data: - str = '' - for s in d: - str = str + chr(ord(s)*2) - data2.append(str) - if audioop.add(data[0], data[0], 1) <> data2[0] or \ - audioop.add(data[1], data[1], 2) <> data2[1] or \ - audioop.add(data[2], data[2], 4) <> data2[2]: - return 0 - return 1 - -def testbias(data): - # Note: this test assumes that avg() works - d1 = audioop.bias(data[0], 1, 100) - d2 = audioop.bias(data[1], 2, 100) - d4 = audioop.bias(data[2], 4, 100) - if audioop.avg(d1, 1) <> 101 or \ - audioop.avg(d2, 2) <> 101 or \ - audioop.avg(d4, 4) <> 101: - return 0 - return 1 - -def testlin2lin(data): - # too simple: we test only the size - for d1 in data: - for d2 in data: - got = len(d1)/3 - wtd = len(d2)/3 - if len(audioop.lin2lin(d1, got, wtd)) <> len(d2): - return 0 - return 1 - -def testadpcm2lin(data): - # Very cursory test - if audioop.adpcm2lin('\0\0', 1, None) <> ('\0\0\0\0', (0,0)): - return 0 - return 1 - -def testlin2adpcm(data): - # Very cursory test - if audioop.lin2adpcm('\0\0\0\0', 1, None) <> ('\0\0', (0,0)): - return 0 - return 1 - -def testlin2ulaw(data): - if audioop.lin2ulaw(data[0], 1) <> '\377\347\333' or \ - audioop.lin2ulaw(data[1], 2) <> '\377\377\377' or \ - audioop.lin2ulaw(data[2], 4) <> '\377\377\377': - return 0 - return 1 - -def testulaw2lin(data): - # Cursory - d = audioop.lin2ulaw(data[0], 1) - if audioop.ulaw2lin(d, 1) <> data[0]: - return 0 - return 1 - -def testmul(data): - data2 = [] - for d in data: - str = '' - for s in d: - str = str + chr(ord(s)*2) - data2.append(str) - if audioop.mul(data[0], 1, 2) <> data2[0] or \ - audioop.mul(data[1],2, 2) <> data2[1] or \ - audioop.mul(data[2], 4, 2) <> data2[2]: - return 0 - return 1 - -def testreverse(data): - if audioop.reverse(data[0], 1) <> '\2\1\0': - return 0 - return 1 - -def testtomono(data): - data2 = '' - for d in data[0]: - data2 = data2 + d + d - if audioop.tomono(data2, 1, 0.5, 0.5) <> data[0]: - return 0 - return 1 - -def testtostereo(data): - data2 = '' - for d in data[0]: - data2 = data2 + d + d - if audioop.tostereo(data[0], 1, 1, 1) <> data2: - return 0 - return 1 - -def testfindfactor(data): - if audioop.findfactor(data[1], data[1]) <> 1.0: - return 0 - return 1 - -def testfindfit(data): - if audioop.findfit(data[1], data[1]) <> (0, 1.0): - return 0 - return 1 - -def testfindmax(data): - if audioop.findmax(data[1], 1) <> 2: - return 0 - return 1 - -def testgetsample(data): - for i in range(3): - if audioop.getsample(data[0], 1, i) <> i or \ - audioop.getsample(data[1], 2, i) <> i or \ - audioop.getsample(data[2], 4, i) <> i: - return 0 - return 1 - -def testone(name, data): - try: - func = eval('test'+name) - except NameError: - print 'No test found for audioop.'+name+'()' - return - try: - rv = func(data) - except 'xx': - print 'Test FAILED for audioop.'+name+'() (with an exception)' - return - if not rv: - print 'Test FAILED for audioop.'+name+'()' - -def testall(): - data = [gendata1(), gendata2(), gendata4()] - names = dir(audioop) - # We know there is a routine 'add' - routines = [] - for n in names: - if type(eval('audioop.'+n)) == type(audioop.add): - routines.append(n) - for n in routines: - testone(n, data) -testall() diff --git a/Lib/test/test_b1.py b/Lib/test/test_b1.py deleted file mode 100644 index 903cc56c18..0000000000 --- a/Lib/test/test_b1.py +++ /dev/null @@ -1,273 +0,0 @@ -# Python test set -- part 4a, built-in functions a-m - -from test_support import * - -print '__import__' -__import__('sys') -__import__('strop') -__import__('string') -try: __import__('spamspam') -except ImportError: pass -else: raise TestFailed, "__import__('spamspam') should fail" - -print 'abs' -if abs(0) <> 0: raise TestFailed, 'abs(0)' -if abs(1234) <> 1234: raise TestFailed, 'abs(1234)' -if abs(-1234) <> 1234: raise TestFailed, 'abs(-1234)' -# -if abs(0.0) <> 0.0: raise TestFailed, 'abs(0.0)' -if abs(3.14) <> 3.14: raise TestFailed, 'abs(3.14)' -if abs(-3.14) <> 3.14: raise TestFailed, 'abs(-3.14)' -# -if abs(0L) <> 0L: raise TestFailed, 'abs(0L)' -if abs(1234L) <> 1234L: raise TestFailed, 'abs(1234L)' -if abs(-1234L) <> 1234L: raise TestFailed, 'abs(-1234L)' - -print 'apply' -def f0(*args): - if args != (): raise TestFailed, 'f0 called with ' + `args` -def f1(a1): - if a1 != 1: raise TestFailed, 'f1 called with ' + `a1` -def f2(a1, a2): - if a1 != 1 or a2 != 2: - raise TestFailed, 'f2 called with ' + `a1, a2` -def f3(a1, a2, a3): - if a1 != 1 or a2 != 2 or a3 != 3: - raise TestFailed, 'f3 called with ' + `a1, a2, a3` -apply(f0, ()) -apply(f1, (1,)) -apply(f2, (1, 2)) -apply(f3, (1, 2, 3)) - -print 'callable' -if not callable(len):raise TestFailed, 'callable(len)' -def f(): pass -if not callable(f): raise TestFailed, 'callable(f)' -class C: - def meth(self): pass -if not callable(C): raise TestFailed, 'callable(C)' -x = C() -if not callable(x.meth): raise TestFailed, 'callable(x.meth)' -if callable(x): raise TestFailed, 'callable(x)' -class D(C): - def __call__(self): pass -y = D() -if not callable(y): raise TestFailed, 'callable(y)' - -print 'chr' -if chr(32) <> ' ': raise TestFailed, 'chr(32)' -if chr(65) <> 'A': raise TestFailed, 'chr(65)' -if chr(97) <> 'a': raise TestFailed, 'chr(97)' - -print 'cmp' -if cmp(-1, 1) <> -1: raise TestFailed, 'cmp(-1, 1)' -if cmp(1, -1) <> 1: raise TestFailed, 'cmp(1, -1)' -if cmp(1, 1) <> 0: raise TestFailed, 'cmp(1, 1)' - -print 'coerce' -if fcmp(coerce(1, 1.1), (1.0, 1.1)): raise TestFailed, 'coerce(1, 1.1)' -if coerce(1, 1L) <> (1L, 1L): raise TestFailed, 'coerce(1, 1L)' -if fcmp(coerce(1L, 1.1), (1.0, 1.1)): raise TestFailed, 'coerce(1L, 1.1)' - -print 'compile' -compile('print 1\n', '', 'exec') - -print 'delattr' -import sys -sys.spam = 1 -delattr(sys, 'spam') - -print 'dir' -x = 1 -if 'x' not in dir(): raise TestFailed, 'dir()' -import sys -if 'modules' not in dir(sys): raise TestFailed, 'dir(sys)' - -print 'divmod' -if divmod(12, 7) <> (1, 5): raise TestFailed, 'divmod(12, 7)' -if divmod(-12, 7) <> (-2, 2): raise TestFailed, 'divmod(-12, 7)' -if divmod(12, -7) <> (-2, -2): raise TestFailed, 'divmod(12, -7)' -if divmod(-12, -7) <> (1, -5): raise TestFailed, 'divmod(-12, -7)' -# -if divmod(12L, 7L) <> (1L, 5L): raise TestFailed, 'divmod(12L, 7L)' -if divmod(-12L, 7L) <> (-2L, 2L): raise TestFailed, 'divmod(-12L, 7L)' -if divmod(12L, -7L) <> (-2L, -2L): raise TestFailed, 'divmod(12L, -7L)' -if divmod(-12L, -7L) <> (1L, -5L): raise TestFailed, 'divmod(-12L, -7L)' -# -if divmod(12, 7L) <> (1, 5L): raise TestFailed, 'divmod(12, 7L)' -if divmod(-12, 7L) <> (-2, 2L): raise TestFailed, 'divmod(-12, 7L)' -if divmod(12L, -7) <> (-2L, -2): raise TestFailed, 'divmod(12L, -7)' -if divmod(-12L, -7) <> (1L, -5): raise TestFailed, 'divmod(-12L, -7)' -# -if fcmp(divmod(3.25, 1.0), (3.0, 0.25)): - raise TestFailed, 'divmod(3.25, 1.0)' -if fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)): - raise TestFailed, 'divmod(-3.25, 1.0)' -if fcmp(divmod(3.25, -1.0), (-4.0, -0.75)): - raise TestFailed, 'divmod(3.25, -1.0)' -if fcmp(divmod(-3.25, -1.0), (3.0, -0.25)): - raise TestFailed, 'divmod(-3.25, -1.0)' - -print 'eval' -if eval('1+1') <> 2: raise TestFailed, 'eval(\'1+1\')' -if eval(' 1+1\n') <> 2: raise TestFailed, 'eval(\' 1+1\\n\')' -globals = {'a': 1, 'b': 2} -locals = {'b': 200, 'c': 300} -if eval('a', globals) <> 1: raise TestFailed, "eval(1)" -if eval('a', globals, locals) <> 1: raise TestFailed, "eval(2)" -if eval('b', globals, locals) <> 200: raise TestFailed, "eval(3)" -if eval('c', globals, locals) <> 300: raise TestFailed, "eval(4)" - -print 'execfile' -z = 0 -f = open(TESTFN, 'w') -f.write('z = z+1\n') -f.write('z = z*2\n') -f.close() -execfile(TESTFN) -if z <> 2: raise TestFailed, "execfile(1)" -globals['z'] = 0 -execfile(TESTFN, globals) -if globals['z'] <> 2: raise TestFailed, "execfile(1)" -locals['z'] = 0 -execfile(TESTFN, globals, locals) -if locals['z'] <> 2: raise TestFailed, "execfile(1)" -unlink(TESTFN) - -print 'filter' -if filter(lambda c: 'a' <= c <= 'z', 'Hello World') <> 'elloorld': - raise TestFailed, 'filter (filter a string)' -if filter(None, [1, 'hello', [], [3], '', None, 9, 0]) <> [1, 'hello', [3], 9]: - raise TestFailed, 'filter (remove false values)' -if filter(lambda x: x > 0, [1, -3, 9, 0, 2]) <> [1, 9, 2]: - raise TestFailed, 'filter (keep positives)' -class Squares: - def __init__(self, max): - self.max = max - self.sofar = [] - def __len__(self): return len(self.sofar) - def __getitem__(self, i): - if not 0 <= i < self.max: raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(n*n) - n = n+1 - return self.sofar[i] -if filter(None, Squares(10)) != [1, 4, 9, 16, 25, 36, 49, 64, 81]: - raise TestFailed, 'filter(None, Squares(10))' -if filter(lambda x: x%2, Squares(10)) != [1, 9, 25, 49, 81]: - raise TestFailed, 'filter(oddp, Squares(10))' - -print 'float' -if float(3.14) <> 3.14: raise TestFailed, 'float(3.14)' -if float(314) <> 314.0: raise TestFailed, 'float(314)' -if float(314L) <> 314.0: raise TestFailed, 'float(314L)' - -print 'getattr' -import sys -if getattr(sys, 'stdout') is not sys.stdout: raise TestFailed, 'getattr' - -print 'hasattr' -import sys -if not hasattr(sys, 'stdout'): raise TestFailed, 'hasattr' - -print 'hash' -hash(None) -if not hash(1) == hash(1L) == hash(1.0): raise TestFailed, 'numeric hash()' -hash('spam') -hash((0,1,2,3)) -def f(): pass - -print 'hex' -if hex(16) != '0x10': raise TestFailed, 'hex(16)' -if hex(16L) != '0x10L': raise TestFailed, 'hex(16L)' -if hex(-16) != '-0x10': raise TestFailed, 'hex(-16)' -if hex(-16L) != '-0x10L': raise TestFailed, 'hex(-16L)' - -print 'id' -id(None) -id(1) -id(1L) -id(1.0) -id('spam') -id((0,1,2,3)) -id([0,1,2,3]) -id({'spam': 1, 'eggs': 2, 'ham': 3}) - -# Test input() later, together with raw_input - -print 'int' -if int(314) <> 314: raise TestFailed, 'int(314)' -if int(3.14) <> 3: raise TestFailed, 'int(3.14)' -if int(314L) <> 314: raise TestFailed, 'int(314L)' - -print 'len' -if len('123') <> 3: raise TestFailed, 'len(\'123\')' -if len(()) <> 0: raise TestFailed, 'len(())' -if len((1, 2, 3, 4)) <> 4: raise TestFailed, 'len((1, 2, 3, 4))' -if len([1, 2, 3, 4]) <> 4: raise TestFailed, 'len([1, 2, 3, 4])' -if len({}) <> 0: raise TestFailed, 'len({})' -if len({'a':1, 'b': 2}) <> 2: raise TestFailed, 'len({\'a\':1, \'b\': 2})' - -print 'long' -if long(314) <> 314L: raise TestFailed, 'long(314)' -if long(3.14) <> 3L: raise TestFailed, 'long(3.14)' -if long(314L) <> 314L: raise TestFailed, 'long(314L)' - -print 'map' -if map(None, 'hello world') <> ['h','e','l','l','o',' ','w','o','r','l','d']: - raise TestFailed, 'map(None, \'hello world\')' -if map(None, 'abcd', 'efg') <> \ - [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)]: - raise TestFailed, 'map(None, \'abcd\', \'efg\')' -if map(None, range(10)) <> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: - raise TestFailed, 'map(None, range(10))' -if map(lambda x: x*x, range(1,4)) <> [1, 4, 9]: - raise TestFailed, 'map(lambda x: x*x, range(1,4))' -try: - from math import sqrt -except ImportError: - def sqrt(x): - return pow(x, 0.5) -if map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]) <> [[4.0, 2.0], [9.0, 3.0]]: - raise TestFailed, 'map(lambda x: map(sqrt,x), [[16, 4], [81, 9]])' -if map(lambda x, y: x+y, [1,3,2], [9,1,4]) <> [10, 4, 6]: - raise TestFailed, 'map(lambda x,y: x+y, [1,3,2], [9,1,4])' -def plus(*v): - accu = 0 - for i in v: accu = accu + i - return accu -if map(plus, [1, 3, 7]) <> [1, 3, 7]: - raise TestFailed, 'map(plus, [1, 3, 7])' -if map(plus, [1, 3, 7], [4, 9, 2]) <> [1+4, 3+9, 7+2]: - raise TestFailed, 'map(plus, [1, 3, 7], [4, 9, 2])' -if map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]) <> [1+4+1, 3+9+1, 7+2+0]: - raise TestFailed, 'map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])' -if map(None, Squares(10)) != [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]: - raise TestFailed, 'map(None, Squares(10))' -if map(int, Squares(10)) != [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]: - raise TestFailed, 'map(int, Squares(10))' -if map(None, Squares(3), Squares(2)) != [(0,0), (1,1), (4,None)]: - raise TestFailed, 'map(None: x, Squares(3), Squares(2))' -if map(max, Squares(3), Squares(2)) != [0, 1, 4]: - raise TestFailed, 'map(None: x, Squares(3), Squares(2))' - -print 'max' -if max('123123') <> '3': raise TestFailed, 'max(\'123123\')' -if max(1, 2, 3) <> 3: raise TestFailed, 'max(1, 2, 3)' -if max((1, 2, 3, 1, 2, 3)) <> 3: raise TestFailed, 'max((1, 2, 3, 1, 2, 3))' -if max([1, 2, 3, 1, 2, 3]) <> 3: raise TestFailed, 'max([1, 2, 3, 1, 2, 3])' -# -if max(1, 2L, 3.0) <> 3.0: raise TestFailed, 'max(1, 2L, 3.0)' -if max(1L, 2.0, 3) <> 3: raise TestFailed, 'max(1L, 2.0, 3)' -if max(1.0, 2, 3L) <> 3L: raise TestFailed, 'max(1.0, 2, 3L)' - -print 'min' -if min('123123') <> '1': raise TestFailed, 'min(\'123123\')' -if min(1, 2, 3) <> 1: raise TestFailed, 'min(1, 2, 3)' -if min((1, 2, 3, 1, 2, 3)) <> 1: raise TestFailed, 'min((1, 2, 3, 1, 2, 3))' -if min([1, 2, 3, 1, 2, 3]) <> 1: raise TestFailed, 'min([1, 2, 3, 1, 2, 3])' -# -if min(1, 2L, 3.0) <> 1: raise TestFailed, 'min(1, 2L, 3.0)' -if min(1L, 2.0, 3) <> 1L: raise TestFailed, 'min(1L, 2.0, 3)' -if min(1.0, 2, 3L) <> 1.0: raise TestFailed, 'min(1.0, 2, 3L)' diff --git a/Lib/test/test_b2.py b/Lib/test/test_b2.py deleted file mode 100644 index 62d17b9ba5..0000000000 --- a/Lib/test/test_b2.py +++ /dev/null @@ -1,260 +0,0 @@ -# Python test set -- part 4b, built-in functions n-z - -from test_support import * - -print 'oct' -if oct(100) != '0144': raise TestFailed, 'oct(100)' -if oct(100L) != '0144L': raise TestFailed, 'oct(100L)' -if oct(-100) != '-0144': raise TestFailed, 'oct(-100)' -if oct(-100L) != '-0144L': raise TestFailed, 'oct(-100L)' - -print 'open' -# NB the first 4 lines are also used to test input and raw_input, below -fp = open(TESTFN, 'w') -try: - fp.write('1+1\n') - fp.write('1+1\n') - fp.write('The quick brown fox jumps over the lazy dog') - fp.write('.\n') - fp.write('Dear John\n') - fp.write('XXX'*100) - fp.write('YYY'*100) -finally: - fp.close() -# -fp = open(TESTFN, 'r') -try: - if fp.readline(4) <> '1+1\n': raise TestFailed, 'readline(4) # exact' - if fp.readline(4) <> '1+1\n': raise TestFailed, 'readline(4) # exact' - if fp.readline() <> 'The quick brown fox jumps over the lazy dog.\n': - raise TestFailed, 'readline() # default' - if fp.readline(4) <> 'Dear': raise TestFailed, 'readline(4) # short' - if fp.readline(100) <> ' John\n': raise TestFailed, 'readline(100)' - if fp.read(300) <> 'XXX'*100: raise TestFailed, 'read(300)' - if fp.read(1000) <> 'YYY'*100: raise TestFailed, 'read(1000) # truncate' -finally: - fp.close() - -print 'ord' -if ord(' ') <> 32: raise TestFailed, 'ord(\' \')' -if ord('A') <> 65: raise TestFailed, 'ord(\'A\')' -if ord('a') <> 97: raise TestFailed, 'ord(\'a\')' - -print 'pow' -if pow(0,0) <> 1: raise TestFailed, 'pow(0,0)' -if pow(0,1) <> 0: raise TestFailed, 'pow(0,1)' -if pow(1,0) <> 1: raise TestFailed, 'pow(1,0)' -if pow(1,1) <> 1: raise TestFailed, 'pow(1,1)' -# -if pow(2,0) <> 1: raise TestFailed, 'pow(2,0)' -if pow(2,10) <> 1024: raise TestFailed, 'pow(2,10)' -if pow(2,20) <> 1024*1024: raise TestFailed, 'pow(2,20)' -if pow(2,30) <> 1024*1024*1024: raise TestFailed, 'pow(2,30)' -# -if pow(-2,0) <> 1: raise TestFailed, 'pow(-2,0)' -if pow(-2,1) <> -2: raise TestFailed, 'pow(-2,1)' -if pow(-2,2) <> 4: raise TestFailed, 'pow(-2,2)' -if pow(-2,3) <> -8: raise TestFailed, 'pow(-2,3)' -# -if pow(0L,0) <> 1: raise TestFailed, 'pow(0L,0)' -if pow(0L,1) <> 0: raise TestFailed, 'pow(0L,1)' -if pow(1L,0) <> 1: raise TestFailed, 'pow(1L,0)' -if pow(1L,1) <> 1: raise TestFailed, 'pow(1L,1)' -# -if pow(2L,0) <> 1: raise TestFailed, 'pow(2L,0)' -if pow(2L,10) <> 1024: raise TestFailed, 'pow(2L,10)' -if pow(2L,20) <> 1024*1024: raise TestFailed, 'pow(2L,20)' -if pow(2L,30) <> 1024*1024*1024: raise TestFailed, 'pow(2L,30)' -# -if pow(-2L,0) <> 1: raise TestFailed, 'pow(-2L,0)' -if pow(-2L,1) <> -2: raise TestFailed, 'pow(-2L,1)' -if pow(-2L,2) <> 4: raise TestFailed, 'pow(-2L,2)' -if pow(-2L,3) <> -8: raise TestFailed, 'pow(-2L,3)' -# -if fcmp(pow(0.,0), 1.): raise TestFailed, 'pow(0.,0)' -if fcmp(pow(0.,1), 0.): raise TestFailed, 'pow(0.,1)' -if fcmp(pow(1.,0), 1.): raise TestFailed, 'pow(1.,0)' -if fcmp(pow(1.,1), 1.): raise TestFailed, 'pow(1.,1)' -# -if fcmp(pow(2.,0), 1.): raise TestFailed, 'pow(2.,0)' -if fcmp(pow(2.,10), 1024.): raise TestFailed, 'pow(2.,10)' -if fcmp(pow(2.,20), 1024.*1024.): raise TestFailed, 'pow(2.,20)' -if fcmp(pow(2.,30), 1024.*1024.*1024.): raise TestFailed, 'pow(2.,30)' -# -# XXX These don't work -- negative float to the float power... -#if fcmp(pow(-2.,0), 1.): raise TestFailed, 'pow(-2.,0)' -#if fcmp(pow(-2.,1), -2.): raise TestFailed, 'pow(-2.,1)' -#if fcmp(pow(-2.,2), 4.): raise TestFailed, 'pow(-2.,2)' -#if fcmp(pow(-2.,3), -8.): raise TestFailed, 'pow(-2.,3)' -# -for x in 2, 2L, 2.0: - for y in 10, 10L, 10.0: - for z in 1000, 1000L, 1000.0: - if fcmp(pow(x, y, z), 24.0): - raise TestFailed, 'pow(%s, %s, %s)' % (x, y, z) - -print 'range' -if range(3) <> [0, 1, 2]: raise TestFailed, 'range(3)' -if range(1, 5) <> [1, 2, 3, 4]: raise TestFailed, 'range(1, 5)' -if range(0) <> []: raise TestFailed, 'range(0)' -if range(-3) <> []: raise TestFailed, 'range(-3)' -if range(1, 10, 3) <> [1, 4, 7]: raise TestFailed, 'range(1, 10, 3)' -if range(5, -5, -3) <> [5, 2, -1, -4]: raise TestFailed, 'range(5, -5, -3)' - -print 'input and raw_input' -import sys -fp = open(TESTFN, 'r') -savestdin = sys.stdin -try: - sys.stdin = fp - if input() <> 2: raise TestFailed, 'input()' - if input('testing\n') <> 2: raise TestFailed, 'input()' - if raw_input() <> 'The quick brown fox jumps over the lazy dog.': - raise TestFailed, 'raw_input()' - if raw_input('testing\n') <> 'Dear John': - raise TestFailed, 'raw_input(\'testing\\n\')' -finally: - sys.stdin = savestdin - fp.close() - -print 'reduce' -if reduce(lambda x, y: x+y, ['a', 'b', 'c'], '') <> 'abc': - raise TestFailed, 'reduce(): implode a string' -if reduce(lambda x, y: x+y, - [['a', 'c'], [], ['d', 'w']], []) <> ['a','c','d','w']: - raise TestFailed, 'reduce(): append' -if reduce(lambda x, y: x*y, range(2,8), 1) <> 5040: - raise TestFailed, 'reduce(): compute 7!' -if reduce(lambda x, y: x*y, range(2,21), 1L) <> 2432902008176640000L: - raise TestFailed, 'reduce(): compute 20!, use long' -class Squares: - def __init__(self, max): - self.max = max - self.sofar = [] - def __len__(self): return len(self.sofar) - def __getitem__(self, i): - if not 0 <= i < self.max: raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(n*n) - n = n+1 - return self.sofar[i] -if reduce(lambda x, y: x+y, Squares(10)) != 285: - raise TestFailed, 'reduce(<+>, Squares(10))' -if reduce(lambda x, y: x+y, Squares(10), 0) != 285: - raise TestFailed, 'reduce(<+>, Squares(10), 0)' -if reduce(lambda x, y: x+y, Squares(0), 0) != 0: - raise TestFailed, 'reduce(<+>, Squares(0), 0)' - - -print 'reload' -import marshal -reload(marshal) -import string -reload(string) -import sys -try: reload(sys) -except ImportError: pass -else: raise TestFailed, 'reload(sys) should fail' - -print 'repr' -if repr('') <> '\'\'': raise TestFailed, 'repr(\'\')' -if repr(0) <> '0': raise TestFailed, 'repr(0)' -if repr(0L) <> '0L': raise TestFailed, 'repr(0L)' -if repr(()) <> '()': raise TestFailed, 'repr(())' -if repr([]) <> '[]': raise TestFailed, 'repr([])' -if repr({}) <> '{}': raise TestFailed, 'repr({})' - -print 'round' -if round(0.0) <> 0.0: raise TestFailed, 'round(0.0)' -if round(1.0) <> 1.0: raise TestFailed, 'round(1.0)' -if round(10.0) <> 10.0: raise TestFailed, 'round(10.0)' -if round(1000000000.0) <> 1000000000.0: - raise TestFailed, 'round(1000000000.0)' -if round(1e20) <> 1e20: raise TestFailed, 'round(1e20)' - -if round(-1.0) <> -1.0: raise TestFailed, 'round(-1.0)' -if round(-10.0) <> -10.0: raise TestFailed, 'round(-10.0)' -if round(-1000000000.0) <> -1000000000.0: - raise TestFailed, 'round(-1000000000.0)' -if round(-1e20) <> -1e20: raise TestFailed, 'round(-1e20)' - -if round(0.1) <> 0.0: raise TestFailed, 'round(0.0)' -if round(1.1) <> 1.0: raise TestFailed, 'round(1.0)' -if round(10.1) <> 10.0: raise TestFailed, 'round(10.0)' -if round(1000000000.1) <> 1000000000.0: - raise TestFailed, 'round(1000000000.0)' - -if round(-1.1) <> -1.0: raise TestFailed, 'round(-1.0)' -if round(-10.1) <> -10.0: raise TestFailed, 'round(-10.0)' -if round(-1000000000.1) <> -1000000000.0: - raise TestFailed, 'round(-1000000000.0)' - -if round(0.9) <> 1.0: raise TestFailed, 'round(0.9)' -if round(9.9) <> 10.0: raise TestFailed, 'round(9.9)' -if round(999999999.9) <> 1000000000.0: - raise TestFailed, 'round(999999999.9)' - -if round(-0.9) <> -1.0: raise TestFailed, 'round(-0.9)' -if round(-9.9) <> -10.0: raise TestFailed, 'round(-9.9)' -if round(-999999999.9) <> -1000000000.0: - raise TestFailed, 'round(-999999999.9)' - -print 'setattr' -import sys -setattr(sys, 'spam', 1) -if sys.spam != 1: raise TestFailed, 'setattr(sys, \'spam\', 1)' - -print 'str' -if str('') <> '': raise TestFailed, 'str(\'\')' -if str(0) <> '0': raise TestFailed, 'str(0)' -if str(0L) <> '0L': raise TestFailed, 'str(0L)' -if str(()) <> '()': raise TestFailed, 'str(())' -if str([]) <> '[]': raise TestFailed, 'str([])' -if str({}) <> '{}': raise TestFailed, 'str({})' - -print 'tuple' -if tuple(()) <> (): raise TestFailed, 'tuple(())' -if tuple((0, 1, 2, 3)) <> (0, 1, 2, 3): raise TestFailed, 'tuple((0, 1, 2, 3))' -if tuple([]) <> (): raise TestFailed, 'tuple([])' -if tuple([0, 1, 2, 3]) <> (0, 1, 2, 3): raise TestFailed, 'tuple([0, 1, 2, 3])' -if tuple('') <> (): raise TestFailed, 'tuple('')' -if tuple('spam') <> ('s', 'p', 'a', 'm'): raise TestFailed, "tuple('spam')" - -print 'type' -if type('') <> type('123') or type('') == type(()): - raise TestFailed, 'type()' - -print 'vars' -a = b = None -a = vars().keys() -b = dir() -a.sort() -b.sort() -if a <> b: raise TestFailed, 'vars()' -import sys -a = vars(sys).keys() -b = dir(sys) -a.sort() -b.sort() -if a <> b: raise TestFailed, 'vars(sys)' -def f0(): - if vars() != {}: raise TestFailed, 'vars() in f0()' -f0() -def f2(): - f0() - a = 1 - b = 2 - if vars() != {'a': a, 'b': b}: raise TestFailed, 'vars() in f2()' -f2() - -print 'xrange' -if tuple(xrange(10)) <> tuple(range(10)): raise TestFailed, 'xrange(10)' -if tuple(xrange(5,10)) <> tuple(range(5,10)): raise TestFailed, 'xrange(5,10)' -if tuple(xrange(0,10,2)) <> tuple(range(0,10,2)): - raise TestFailed, 'xrange(0,10,2)' - - -# Epilogue -- unlink the temp file - -unlink(TESTFN) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py deleted file mode 100644 index 33fef8d1b7..0000000000 --- a/Lib/test/test_builtin.py +++ /dev/null @@ -1,13 +0,0 @@ -# Python test set -- part 4, built-in functions - -from test_support import * - -print '4. Built-in functions' - -print 'test_b1' -unload('test_b1') -import test_b1 - -print 'test_b2' -unload('test_b2') -import test_b2 diff --git a/Lib/test/test_exceptions.py b/Lib/test/test_exceptions.py deleted file mode 100644 index 4fbee3e76a..0000000000 --- a/Lib/test/test_exceptions.py +++ /dev/null @@ -1,92 +0,0 @@ -# Python test set -- part 5, built-in exceptions - -from test_support import * - -print '5. Built-in exceptions' -# XXX This is not really enough, each *operation* should be tested! - -def r(name): print name - -r(AttributeError) -import sys -try: x = sys.undefined_attribute -except AttributeError: pass - -r(EOFError) -import sys -fp = open(TESTFN, 'w') -fp.close() -fp = open(TESTFN, 'r') -savestdin = sys.stdin -try: - try: - sys.stdin = fp - x = raw_input() - except EOFError: - pass -finally: - sys.stdin = savestdin - fp.close() - -r(IOError) -try: open('this file does not exist', 'r') -except IOError: pass - -r(ImportError) -try: import undefined_module -except ImportError: pass - -r(IndexError) -x = [] -try: a = x[10] -except IndexError: pass - -r(KeyError) -x = {} -try: a = x['key'] -except KeyError: pass - -r(KeyboardInterrupt) -print '(not testable in a script)' - -r(MemoryError) -print '(not safe to test)' - -r(NameError) -try: x = undefined_variable -except NameError: pass - -r(OverflowError) -x = 1 -try: - while 1: x = x+x -except OverflowError: pass - -r(RuntimeError) -print '(not used any more?)' - -r(SyntaxError) -try: exec '/\n' -except SyntaxError: pass - -r(SystemError) -print '(hard to reproduce)' - -r(SystemExit) -import sys -try: sys.exit(0) -except SystemExit: pass - -r(TypeError) -try: [] + () -except TypeError: pass - -r(ValueError) -try: x = chr(10000) -except ValueError: pass - -r(ZeroDivisionError) -try: x = 1/0 -except ZeroDivisionError: pass - -unlink(TESTFN) diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py deleted file mode 100644 index b9607ac18b..0000000000 --- a/Lib/test/test_grammar.py +++ /dev/null @@ -1,513 +0,0 @@ -# Python test set -- part 1, grammar. -# This just tests whether the parser accepts them all. - -from test_support import * - -print '1. Parser' - -print '1.1 Tokens' - -print '1.1.1 Backslashes' - -# Backslash means line continuation: -x = 1 \ -+ 1 -if x <> 2: raise TestFailed, 'backslash for line continuation' - -# Backslash does not means continuation in comments :\ -x = 0 -if x <> 0: raise TestFailed, 'backslash ending comment' - -print '1.1.2 Numeric literals' - -print '1.1.2.1 Plain integers' -if 0xff <> 255: raise TestFailed, 'hex int' -if 0377 <> 255: raise TestFailed, 'octal int' -if 2147483647 != 017777777777: raise TestFailed, 'large positive int' -try: - from sys import maxint -except ImportError: - maxint = 2147483647 -if maxint == 2147483647: - if -2147483647-1 != 020000000000: raise TestFailed, 'max negative int' - # XXX -2147483648 - if 037777777777 != -1: raise TestFailed, 'oct -1' - if 0xffffffff != -1: raise TestFailed, 'hex -1' - for s in '2147483648', '040000000000', '0x100000000': - try: - x = eval(s) - except OverflowError: - continue -## raise TestFailed, \ - print \ - 'No OverflowError on huge integer literal ' + `s` -elif eval('maxint == 9223372036854775807'): - if eval('-9223372036854775807-1 != 01000000000000000000000'): - raise TestFailed, 'max negative int' - if eval('01777777777777777777777') != -1: raise TestFailed, 'oct -1' - if eval('0xffffffffffffffff') != -1: raise TestFailed, 'hex -1' - for s in '9223372036854775808', '02000000000000000000000', \ - '0x10000000000000000': - try: - x = eval(s) - except OverflowError: - continue - raise TestFailed, \ - 'No OverflowError on huge integer literal ' + `s` -else: - print 'Weird maxint value', maxint - -print '1.1.2.2 Long integers' -x = 0L -x = 0l -x = 0xffffffffffffffffL -x = 0xffffffffffffffffl -x = 077777777777777777L -x = 077777777777777777l -x = 123456789012345678901234567890L -x = 123456789012345678901234567890l - -print '1.1.2.3 Floating point' -x = 3.14 -x = 314. -x = 0.314 -# XXX x = 000.314 -x = .314 -x = 3e14 -x = 3E14 -x = 3e-14 -x = 3e+14 -x = 3.e14 -x = .3e14 -x = 3.1e4 - -print '1.1.3 String literals' - -def assert(s): - if not s: raise TestFailed, 'see traceback' - -x = ''; y = ""; assert(len(x) == 0 and x == y) -x = '\''; y = "'"; assert(len(x) == 1 and x == y and ord(x) == 39) -x = '"'; y = "\""; assert(len(x) == 1 and x == y and ord(x) == 34) -x = "doesn't \"shrink\" does it" -y = 'doesn\'t "shrink" does it' -assert(len(x) == 24 and x == y) -x = "does \"shrink\" doesn't it" -y = 'does "shrink" doesn\'t it' -assert(len(x) == 24 and x == y) -x = """ -The "quick" -brown fox -jumps over -the 'lazy' dog. -""" -y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' -assert(x == y) -y = ''' -The "quick" -brown fox -jumps over -the 'lazy' dog. -'''; assert(x == y) -y = "\n\ -The \"quick\"\n\ -brown fox\n\ -jumps over\n\ -the 'lazy' dog.\n\ -"; assert(x == y) -y = '\n\ -The \"quick\"\n\ -brown fox\n\ -jumps over\n\ -the \'lazy\' dog.\n\ -'; assert(x == y) - - -print '1.2 Grammar' - -print 'single_input' # NEWLINE | simple_stmt | compound_stmt NEWLINE -# XXX can't test in a script -- this rule is only used when interactive - -print 'file_input' # (NEWLINE | stmt)* ENDMARKER -# Being tested as this very moment this very module - -print 'expr_input' # testlist NEWLINE -# XXX Hard to test -- used only in calls to input() - -print 'eval_input' # testlist ENDMARKER -x = eval('1, 0 or 1') - -print 'funcdef' -### 'def' NAME parameters ':' suite -### parameters: '(' [varargslist] ')' -### varargslist: (fpdef ['=' test] ',')* '*' NAME -### | fpdef ['=' test] (',' fpdef ['=' test])* [','] -### fpdef: NAME | '(' fplist ')' -### fplist: fpdef (',' fpdef)* [','] -def f1(): pass -def f2(one_argument): pass -def f3(two, arguments): pass -def f4(two, (compound, (argument, list))): pass -def a1(one_arg,): pass -def a2(two, args,): pass -def v0(*rest): pass -def v1(a, *rest): pass -def v2(a, b, *rest): pass -def v3(a, (b, c), *rest): pass -def d01(a=1): pass -d01() -d01(1) -def d11(a, b=1): pass -d11(1) -d11(1, 2) -def d21(a, b, c=1): pass -d21(1, 2) -d21(1, 2, 3) -def d02(a=1, b=2): pass -d02() -d02(1) -d02(1, 2) -def d12(a, b=1, c=2): pass -d12(1) -d12(1, 2) -d12(1, 2, 3) -def d22(a, b, c=1, d=2): pass -d22(1, 2) -d22(1, 2, 3) -d22(1, 2, 3, 4) -def d01v(a=1, *rest): pass -d01v() -d01v(1) -d01v(1, 2) -def d11v(a, b=1, *rest): pass -d11v(1) -d11v(1, 2) -d11v(1, 2, 3) -def d21v(a, b, c=1, *rest): pass -d21v(1, 2) -d21v(1, 2, 3) -d21v(1, 2, 3, 4) -def d02v(a=1, b=2, *rest): pass -d02v() -d02v(1) -d02v(1, 2) -d02v(1, 2, 3) -def d12v(a, b=1, c=2, *rest): pass -d12v(1) -d12v(1, 2) -d12v(1, 2, 3) -d12v(1, 2, 3, 4) -def d22v(a, b, c=1, d=2, *rest): pass -d22v(1, 2) -d22v(1, 2, 3) -d22v(1, 2, 3, 4) -d22v(1, 2, 3, 4, 5) - -### stmt: simple_stmt | compound_stmt -# Tested below - -### simple_stmt: small_stmt (';' small_stmt)* [';'] -print 'simple_stmt' -x = 1; pass; del x - -### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt -# Tested below - -print 'expr_stmt' # (exprlist '=')* exprlist -1 -1, 2, 3 -x = 1 -x = 1, 2, 3 -x = y = z = 1, 2, 3 -x, y, z = 1, 2, 3 -abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4) -# NB these variables are deleted below - -print 'print_stmt' # 'print' (test ',')* [test] -print 1, 2, 3 -print 1, 2, 3, -print -print 0 or 1, 0 or 1, -print 0 or 1 - -print 'del_stmt' # 'del' exprlist -del abc -del x, y, (z, xyz) - -print 'pass_stmt' # 'pass' -pass - -print 'flow_stmt' # break_stmt | continue_stmt | return_stmt | raise_stmt -# Tested below - -print 'break_stmt' # 'break' -while 1: break - -print 'continue_stmt' # 'continue' -i = 1 -while i: i = 0; continue - -print 'return_stmt' # 'return' [testlist] -def g1(): return -def g2(): return 1 -g1() -x = g2() - -print 'raise_stmt' # 'raise' test [',' test] -try: raise RuntimeError, 'just testing' -except RuntimeError: pass -try: raise KeyboardInterrupt -except KeyboardInterrupt: pass - -print 'import_stmt' # 'import' NAME (',' NAME)* | 'from' NAME 'import' ('*' | NAME (',' NAME)*) -import sys -import time, sys -from time import time -from sys import * -from sys import path, argv - -print 'global_stmt' # 'global' NAME (',' NAME)* -def f(): - global a - global a, b - global one, two, three, four, five, six, seven, eight, nine, ten - -print 'exec_stmt' # 'exec' expr ['in' expr [',' expr]] -def f(): - z = None - del z - exec 'z=1+1\n' - if z <> 2: raise TestFailed, 'exec \'z=1+1\'\\n' - del z - exec 'z=1+1' - if z <> 2: raise TestFailed, 'exec \'z=1+1\'' -f() -g = {} -exec 'z = 1' in g -if g.has_key('__builtins__'): del g['__builtins__'] -if g <> {'z': 1}: raise TestFailed, 'exec \'z = 1\' in g' -g = {} -l = {} -exec 'global a; a = 1; b = 2' in g, l -if g.has_key('__builtins__'): del g['__builtins__'] -if l.has_key('__builtins__'): del l['__builtins__'] -if (g, l) <> ({'a':1}, {'b':2}): raise TestFailed, 'exec ... in g, l' - - -### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef -# Tested below - -print 'if_stmt' # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] -if 1: pass -if 1: pass -else: pass -if 0: pass -elif 0: pass -if 0: pass -elif 0: pass -elif 0: pass -elif 0: pass -else: pass - -print 'while_stmt' # 'while' test ':' suite ['else' ':' suite] -while 0: pass -while 0: pass -else: pass - -print 'for_stmt' # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] -for i in 1, 2, 3: pass -for i, j, k in (): pass -else: pass -class Squares: - def __init__(self, max): - self.max = max - self.sofar = [] - def __len__(self): return len(self.sofar) - def __getitem__(self, i): - if not 0 <= i < self.max: raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(n*n) - n = n+1 - return self.sofar[i] -n = 0 -for x in Squares(10): n = n+x -if n != 285: raise TestFailed, 'for over growing sequence' - -print 'try_stmt' -### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] -### | 'try' ':' suite 'finally' ':' suite -### except_clause: 'except' [expr [',' expr]] -try: - 1/0 -except ZeroDivisionError: - pass -else: - pass -try: 1/0 -except EOFError: pass -except TypeError, msg: pass -except RuntimeError, msg: pass -except: pass -else: pass -try: 1/0 -except (EOFError, TypeError, ZeroDivisionError): pass -try: 1/0 -except (EOFError, TypeError, ZeroDivisionError), msg: pass -try: pass -finally: pass - -print 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT -if 1: pass -if 1: - pass -if 1: - # - # - # - pass - pass - # - pass - # - -print 'test' -### and_test ('or' and_test)* -### and_test: not_test ('and' not_test)* -### not_test: 'not' not_test | comparison -if not 1: pass -if 1 and 1: pass -if 1 or 1: pass -if not not not 1: pass -if not 1 and 1 and 1: pass -if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass - -print 'comparison' -### comparison: expr (comp_op expr)* -### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' -if 1: pass -x = (1 == 1) -if 1 == 1: pass -if 1 != 1: pass -if 1 <> 1: pass -if 1 < 1: pass -if 1 > 1: pass -if 1 <= 1: pass -if 1 >= 1: pass -if 1 is 1: pass -if 1 is not 1: pass -if 1 in (): pass -if 1 not in (): pass -if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass - -print 'binary mask ops' -x = 1 & 1 -x = 1 ^ 1 -x = 1 | 1 - -print 'shift ops' -x = 1 << 1 -x = 1 >> 1 -x = 1 << 1 >> 1 - -print 'additive ops' -x = 1 -x = 1 + 1 -x = 1 - 1 - 1 -x = 1 - 1 + 1 - 1 + 1 - -print 'multiplicative ops' -x = 1 * 1 -x = 1 / 1 -x = 1 % 1 -x = 1 / 1 * 1 % 1 - -print 'unary ops' -x = +1 -x = -1 -x = ~1 -x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 -x = -1*1/1 + 1*1 - ---1*1 - -print 'selectors' -### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME -### subscript: expr | [expr] ':' [expr] -f1() -f2(1) -f2(1,) -f3(1, 2) -f3(1, 2,) -f4(1, (2, (3, 4))) -v0() -v0(1) -v0(1,) -v0(1,2) -v0(1,2,3,4,5,6,7,8,9,0) -v1(1) -v1(1,) -v1(1,2) -v1(1,2,3) -v1(1,2,3,4,5,6,7,8,9,0) -v2(1,2) -v2(1,2,3) -v2(1,2,3,4) -v2(1,2,3,4,5,6,7,8,9,0) -v3(1,(2,3)) -v3(1,(2,3),4) -v3(1,(2,3),4,5,6,7,8,9,0) -import sys, time -c = sys.path[0] -x = time.time() -x = sys.modules['time'].time() -a = '01234' -c = a[0] -c = a[-1] -s = a[0:5] -s = a[:5] -s = a[0:] -s = a[:] -s = a[-5:] -s = a[:-1] -s = a[-4:-3] - -print 'atoms' -### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING -### dictmaker: test ':' test (',' test ':' test)* [','] - -x = (1) -x = (1 or 2 or 3) -x = (1 or 2 or 3, 2, 3) - -x = [] -x = [1] -x = [1 or 2 or 3] -x = [1 or 2 or 3, 2, 3] -x = [] - -x = {} -x = {'one': 1} -x = {'one': 1,} -x = {'one' or 'two': 1 or 2} -x = {'one': 1, 'two': 2} -x = {'one': 1, 'two': 2,} -x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} - -x = `x` -x = `1 or 2 or 3` -x = x -x = 'x' -x = 123 - -### exprlist: expr (',' expr)* [','] -### testlist: test (',' test)* [','] -# These have been exercised enough above - -print 'classdef' # 'class' NAME ['(' testlist ')'] ':' suite -class B: pass -class C1(B): pass -class C2(B): pass -class D(C1, C2, B): pass -class C: - def meth1(self): pass - def meth2(self, arg): pass - def meth3(self, a1, a2): pass diff --git a/Lib/test/test_md5.py b/Lib/test/test_md5.py deleted file mode 100644 index 43f12ca6bf..0000000000 --- a/Lib/test/test_md5.py +++ /dev/null @@ -1,24 +0,0 @@ -# Testing md5 module - -import string -from md5 import md5 - -def hexstr(s): - h = string.hexdigits - r = '' - for c in s: - i = ord(c) - r = r + h[(i >> 4) & 0xF] + h[i & 0xF] - return r - -def md5test(s): - return 'MD5 ("' + s + '") = ' + hexstr(md5(s).digest()) - -print 'MD5 test suite:' -print md5test('') -print md5test('a') -print md5test('abc') -print md5test('message digest') -print md5test('abcdefghijklmnopqrstuvwxyz') -print md5test('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') -print md5test('12345678901234567890123456789012345678901234567890123456789012345678901234567890') diff --git a/Lib/test/test_opcodes.py b/Lib/test/test_opcodes.py deleted file mode 100644 index b1e944b4d2..0000000000 --- a/Lib/test/test_opcodes.py +++ /dev/null @@ -1,59 +0,0 @@ -# Python test set -- part 2, opcodes - -from test_support import * - - -print '2. Opcodes' -print 'XXX Not yet fully implemented' - -print '2.1 try inside for loop' -n = 0 -for i in range(10): - n = n+i - try: 1/0 - except NameError: pass - except ZeroDivisionError: pass - except TypeError: pass - try: pass - except: pass - try: pass - finally: pass - n = n+i -if n <> 90: - raise TestFailed, 'try inside for' - - -print '2.2 raise class exceptions' - -class AClass: pass -class BClass(AClass): pass -class CClass: pass - -try: raise AClass() -except: pass - -try: raise AClass() -except AClass: pass - -try: raise BClass() -except AClass: pass - -try: raise BClass() -except CClass: raise TestFailed -except: pass - -a = AClass() -b = BClass() - -try: raise AClass, b -except BClass, v: raise TestFailed -except AClass, v: - if v != b: raise TestFailed - - -try: raise b -except AClass, v: - if v != b: raise TestFailed - -try: raise BClass, a -except TypeError: pass diff --git a/Lib/test/test_operations.py b/Lib/test/test_operations.py deleted file mode 100644 index 1a75065190..0000000000 --- a/Lib/test/test_operations.py +++ /dev/null @@ -1,5 +0,0 @@ -# Python test set -- part 3, built-in operations. - - -print '3. Operations' -print 'XXX Not yet implemented' diff --git a/Lib/test/test_pow.py b/Lib/test/test_pow.py deleted file mode 100644 index 03f7314894..0000000000 --- a/Lib/test/test_pow.py +++ /dev/null @@ -1,92 +0,0 @@ -import sys - -def powtest(type): - if (type!=float): - print " Testing 2-argument pow() function..." - for i in range(-1000, 1000): - if (pow(type(i),0)!=1): - raise ValueError, 'pow('+str(i)+',0) != 1' - if (pow(type(i),1)!=type(i)): - raise ValueError, 'pow('+str(i)+',1) != '+str(i) - if (pow(type(0),1)!=type(0)): - raise ValueError, 'pow(0,'+str(i)+') != 0' - if (pow(type(1),1)!=type(1)): - raise ValueError, 'pow(1,'+str(i)+') != 1' - - for i in range(-100, 100): - if (pow(type(i),3)!=i*i*i): - raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) - - pow2=1 - for i in range(0,31): - if (pow(2,i)!=pow2): - raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) - if (i!=30): pow2=pow2*2 - - print " Testing 3-argument pow() function..." - il, ih = -20, 20 - jl, jh = -5, 5 - kl, kh = -10, 10 - if (type==float): - il=1 - elif (type==int): - jl=0 - elif (type==long): - jl,jh = 0, 15 - for i in range(il, ih+1): - for j in range(jl,jh+1): - for k in range(kl, kh+1): - if (k!=0): - if (pow(type(i),j,k)!=pow(type(i),j)% type(k) ): - raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ - "," +str(k)+ ") != pow(" +str(i)+ "," + \ - str(j)+ ") % " +str(k) - - -print 'Testing integer mode...' -powtest(int) -print 'Testing long integer mode...' -powtest(long) -print 'Testing floating point mode...' -powtest(float) - -# Other tests-- not very systematic - -print 'The number in both columns should match.' -print pow(3,3) % 8, pow(3,3,8) -print pow(3,3) % -8, pow(3,3,-8) -print pow(3,2) % -2, pow(3,2,-2) -print pow(-3,3) % 8, pow(-3,3,8) -print pow(-3,3) % -8, pow(-3,3,-8) -print pow(5,2) % -8, pow(5,2,-8) -print - -print pow(3L,3L) % 8, pow(3L,3L,8) -print pow(3L,3L) % -8, pow(3L,3L,-8) -print pow(3L,2) % -2, pow(3L,2,-2) -print pow(-3L,3L) % 8, pow(-3L,3L,8) -print pow(-3L,3L) % -8, pow(-3L,3L,-8) -print pow(5L,2) % -8, pow(5L,2,-8) -print - -print pow(3.0,3.0) % 8, pow(3.0,3.0,8) -print pow(3.0,3.0) % -8, pow(3.0,3.0,-8) -print pow(3.0,2) % -2, pow(3.0,2,-2) -print pow(5.0,2) % -8, pow(5.0,2,-8) -print - -for i in range(-10, 11): - for j in range(0, 6): - for k in range(-7, 11): - if (j>=0 and k!=0): - o=pow(i,j) % k - n=pow(i,j,k) - if (o!=n): print 'Integer mismatch:', i,j,k - if (j>=0 and k<>0): - o=pow(long(i),j) % k - n=pow(long(i),j,k) - if (o!=n): print 'Long mismatch:', i,j,k - if (i>=0 and k<>0): - o=pow(float(i),j) % k - n=pow(float(i),j,k) - if (o!=n): print 'Float mismatch:', i,j,k diff --git a/Lib/test/test_rgbimg.py b/Lib/test/test_rgbimg.py deleted file mode 100644 index cdadc660dd..0000000000 --- a/Lib/test/test_rgbimg.py +++ /dev/null @@ -1,49 +0,0 @@ -# Testing rgbimg module - -import rgbimg, os - -error = 'test_rgbimg.error' - -print 'RGBimg test suite:' - -def findfile(file): - if os.path.isabs(file): return file - import sys - for dn in sys.path: - fn = os.path.join(dn, file) - if os.path.exists(fn): return fn - return file - -def testimg(rgb_file, raw_file): - rgb_file = findfile(rgb_file) - raw_file = findfile(raw_file) - width, height = rgbimg.sizeofimage(rgb_file) - rgb = rgbimg.longimagedata(rgb_file) - if len(rgb) != width * height * 4: - raise error, 'bad image length' - raw = open(raw_file, 'r').read() - if rgb != raw: - raise error, 'images don\'t match for '+rgb_file+' and '+raw_file - for depth in [1, 3, 4]: - rgbimg.longstoimage(rgb, width, height, depth, '@.rgb') - os.unlink('@.rgb') - -ttob = rgbimg.ttob(0) -if ttob != 0: - raise error, 'ttob should start out as zero' - -testimg('test.rgb', 'test.rawimg') - -ttob = rgbimg.ttob(1) -if ttob != 0: - raise error, 'ttob should be zero' - -testimg('test.rgb', 'test.rawimg.rev') - -ttob = rgbimg.ttob(0) -if ttob != 1: - raise error, 'ttob should be one' - -ttob = rgbimg.ttob(0) -if ttob != 0: - raise error, 'ttob should be zero' diff --git a/Lib/test/test_select.py b/Lib/test/test_select.py deleted file mode 100644 index f1853087f2..0000000000 --- a/Lib/test/test_select.py +++ /dev/null @@ -1,23 +0,0 @@ -# Testing select module - -def test(): - import select - import os - cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do date; sleep 3; done' - p = os.popen(cmd, 'r') - for tout in (0, 1, 2, 4, 8, 16) + (None,)*10: - print 'timeout =', tout - rfd, wfd, xfd = select.select([p], [], [], tout) - print rfd, wfd, xfd - if (rfd, wfd, xfd) == ([], [], []): - continue - if (rfd, wfd, xfd) == ([p], [], []): - line = p.readline() - print `line` - if not line: - print 'EOF' - break - continue - print 'Heh?' - -test() diff --git a/Lib/test/test_signal.py b/Lib/test/test_signal.py deleted file mode 100644 index bfcf517ac9..0000000000 --- a/Lib/test/test_signal.py +++ /dev/null @@ -1,50 +0,0 @@ -# Test the signal module - -import signal -import os - - -pid = os.getpid() - -# Shell script that will send us asynchronous signals -script = """ -( - set -x - sleep 2 - kill -5 %(pid)d - sleep 2 - kill -2 %(pid)d - sleep 2 - kill -3 %(pid)d -) & -""" % vars() - -def handlerA(*args): - print "handlerA", args - -HandlerBCalled = "HandlerBCalled" # Exception - -def handlerB(*args): - print "handlerB", args - raise HandlerBCalled, args - -signal.alarm(20) # Entire test lasts at most 20 sec. -signal.signal(5, handlerA) -signal.signal(2, handlerB) -signal.signal(3, signal.SIG_IGN) -signal.signal(signal.SIGALRM, signal.default_int_handler) - -os.system(script) - -print "starting pause() loop..." - -try: - while 1: - print "call pause()..." - try: - signal.pause() - print "pause() returned" - except HandlerBCalled: - print "HandlerBCalled exception caught" -except KeyboardInterrupt: - print "KeyboardInterrupt (assume the alarm() went off)" diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py deleted file mode 100644 index 7a766642b6..0000000000 --- a/Lib/test/test_support.py +++ /dev/null @@ -1,41 +0,0 @@ -# Python test set -- supporting definitions. - -TestFailed = 'test_support -- test failed' # Exception - -def unload(name): - import sys - try: - del sys.modules[name] - except KeyError: - pass - -def forget(modname): - unload(modname) - import sys, os - for dirname in sys.path: - try: - os.unlink(os.path.join(dirname, modname + '.pyc')) - except os.error: - pass - -FUZZ = 1e-6 - -def fcmp(x, y): # fuzzy comparison function - if type(x) == type(0.0) or type(y) == type(0.0): - try: - x, y = coerce(x, y) - fuzz = (abs(x) + abs(y)) * FUZZ - if abs(x-y) <= fuzz: - return 0 - except: - pass - elif type(x) == type(y) and type(x) in (type(()), type([])): - for i in range(min(len(x), len(y))): - outcome = fcmp(x[i], y[i]) - if outcome <> 0: - return outcome - return cmp(len(x), len(y)) - return cmp(x, y) - -TESTFN = '@test' # Filename used for testing -from os import unlink diff --git a/Lib/test/test_thread.py b/Lib/test/test_thread.py deleted file mode 100644 index 4e0eb70395..0000000000 --- a/Lib/test/test_thread.py +++ /dev/null @@ -1,106 +0,0 @@ -# Very rudimentary test of thread module - -# Create a bunch of threads, let each do some work, wait until all are done - -import whrandom -import thread -import time - -mutex = thread.allocate_lock() -whmutex = thread.allocate_lock() # for calls to whrandom -running = 0 -done = thread.allocate_lock() -done.acquire() - -numtasks = 10 - -def task(ident): - global running - whmutex.acquire() - delay = whrandom.random() * numtasks - whmutex.release() - print 'task', ident, 'will run for', delay, 'sec' - time.sleep(delay) - print 'task', ident, 'done' - mutex.acquire() - running = running - 1 - if running == 0: - done.release() - mutex.release() - -next_ident = 0 -def newtask(): - global next_ident, running - mutex.acquire() - next_ident = next_ident + 1 - print 'creating task', next_ident - thread.start_new_thread(task, (next_ident,)) - running = running + 1 - mutex.release() - -for i in range(numtasks): - newtask() - -print 'waiting for all tasks to complete' -done.acquire() -print 'all tasks done' - -class barrier: - def __init__(self, n): - self.n = n - self.waiting = 0 - self.checkin = thread.allocate_lock() - self.checkout = thread.allocate_lock() - self.checkout.acquire() - - def enter(self): - checkin, checkout = self.checkin, self.checkout - - checkin.acquire() - self.waiting = self.waiting + 1 - if self.waiting == self.n: - self.waiting = self.n - 1 - checkout.release() - return - checkin.release() - - checkout.acquire() - self.waiting = self.waiting - 1 - if self.waiting == 0: - checkin.release() - return - checkout.release() - -numtrips = 3 -def task2(ident): - global running - for i in range(numtrips): - if ident == 0: - # give it a good chance to enter the next - # barrier before the others are all out - # of the current one - delay = 0.001 - else: - whmutex.acquire() - delay = whrandom.random() * numtasks - whmutex.release() - print 'task', ident, 'will run for', delay, 'sec' - time.sleep(delay) - print 'task', ident, 'entering barrier', i - bar.enter() - print 'task', ident, 'leaving barrier', i - mutex.acquire() - running = running - 1 - if running == 0: - done.release() - mutex.release() - -print '\n*** Barrier Test ***' -if done.acquire(0): - raise ValueError, "'done' should have remained acquired" -bar = barrier(numtasks) -running = numtasks -for i in range(numtasks): - thread.start_new_thread(task2, (i,)) -done.acquire() -print 'all tasks done' diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py deleted file mode 100644 index 51c76dc6d9..0000000000 --- a/Lib/test/test_types.py +++ /dev/null @@ -1,182 +0,0 @@ -# Python test set -- part 6, built-in types - -from test_support import * - -print '6. Built-in types' - -print '6.1 Truth value testing' -if None: raise TestFailed, 'None is true instead of false' -if 0: raise TestFailed, '0 is true instead of false' -if 0L: raise TestFailed, '0L is true instead of false' -if 0.0: raise TestFailed, '0.0 is true instead of false' -if '': raise TestFailed, '\'\' is true instead of false' -if (): raise TestFailed, '() is true instead of false' -if []: raise TestFailed, '[] is true instead of false' -if {}: raise TestFailed, '{} is true instead of false' -if not 1: raise TestFailed, '1 is false instead of true' -if not 1L: raise TestFailed, '1L is false instead of true' -if not 1.0: raise TestFailed, '1.0 is false instead of true' -if not 'x': raise TestFailed, '\'x\' is false instead of true' -if not (1, 1): raise TestFailed, '(1, 1) is false instead of true' -if not [1]: raise TestFailed, '[1] is false instead of true' -if not {'x': 1}: raise TestFailed, '{\'x\': 1} is false instead of true' -def f(): pass -class C: pass -import sys -x = C() -if not f: raise TestFailed, 'f is false instead of true' -if not C: raise TestFailed, 'C is false instead of true' -if not sys: raise TestFailed, 'sys is false instead of true' -if not x: raise TestFailed, 'x is false instead of true' - -print '6.2 Boolean operations' -if 0 or 0: raise TestFailed, '0 or 0 is true instead of false' -if 1 and 1: pass -else: raise TestFailed, '1 and 1 is false instead of false' -if not 1: raise TestFailed, 'not 1 is true instead of false' - -print '6.3 Comparisons' -if 0 < 1 <= 1 == 1 >= 1 > 0 <> 1: pass -else: raise TestFailed, 'int comparisons failed' -if 0L < 1L <= 1L == 1L >= 1L > 0L <> 1L: pass -else: raise TestFailed, 'long int comparisons failed' -if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 <> 1.0: pass -else: raise TestFailed, 'float comparisons failed' -if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass -else: raise TestFailed, 'string comparisons failed' -if 0 in [0] and 0 not in [1]: pass -else: raise TestFailed, 'membership test failed' -if None is None and [] is not []: pass -else: raise TestFailed, 'identity test failed' - -print '6.4 Numeric types (mostly conversions)' -if 0 <> 0L or 0 <> 0.0 or 0L <> 0.0: raise TestFailed, 'mixed comparisons' -if 1 <> 1L or 1 <> 1.0 or 1L <> 1.0: raise TestFailed, 'mixed comparisons' -if -1 <> -1L or -1 <> -1.0 or -1L <> -1.0: - raise TestFailed, 'int/long/float value not equal' -if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass -else: raise TestFailed, 'int() does not round properly' -if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass -else: raise TestFailed, 'long() does not round properly' -if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass -else: raise TestFailed, 'float() does not work properly' -print '6.4.1 32-bit integers' -if 12 + 24 <> 36: raise TestFailed, 'int op' -if 12 + (-24) <> -12: raise TestFailed, 'int op' -if (-12) + 24 <> 12: raise TestFailed, 'int op' -if (-12) + (-24) <> -36: raise TestFailed, 'int op' -if not 12 < 24: raise TestFailed, 'int op' -if not -24 < -12: raise TestFailed, 'int op' -# Test for a particular bug in integer multiply -xsize, ysize, zsize = 238, 356, 4 -if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912): - raise TestFailed, 'int mul commutativity' -print '6.4.2 Long integers' -if 12L + 24L <> 36L: raise TestFailed, 'long op' -if 12L + (-24L) <> -12L: raise TestFailed, 'long op' -if (-12L) + 24L <> 12L: raise TestFailed, 'long op' -if (-12L) + (-24L) <> -36L: raise TestFailed, 'long op' -if not 12L < 24L: raise TestFailed, 'long op' -if not -24L < -12L: raise TestFailed, 'long op' -print '6.4.3 Floating point numbers' -if 12.0 + 24.0 <> 36.0: raise TestFailed, 'float op' -if 12.0 + (-24.0) <> -12.0: raise TestFailed, 'float op' -if (-12.0) + 24.0 <> 12.0: raise TestFailed, 'float op' -if (-12.0) + (-24.0) <> -36.0: raise TestFailed, 'float op' -if not 12.0 < 24.0: raise TestFailed, 'float op' -if not -24.0 < -12.0: raise TestFailed, 'float op' - -print '6.5 Sequence types' - -print '6.5.1 Strings' -if len('') <> 0: raise TestFailed, 'len(\'\')' -if len('a') <> 1: raise TestFailed, 'len(\'a\')' -if len('abcdef') <> 6: raise TestFailed, 'len(\'abcdef\')' -if 'xyz' + 'abcde' <> 'xyzabcde': raise TestFailed, 'string concatenation' -if 'xyz'*3 <> 'xyzxyzxyz': raise TestFailed, 'string repetition *3' -if 0*'abcde' <> '': raise TestFailed, 'string repetition 0*' -if min('abc') <> 'a' or max('abc') <> 'c': raise TestFailed, 'min/max string' -if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass -else: raise TestFailed, 'in/not in string' -x = 'x'*103 -if '%s!'%x != x+'!': raise TestFailed, 'nasty string formatting bug' - -print '6.5.2 Tuples' -if len(()) <> 0: raise TestFailed, 'len(())' -if len((1,)) <> 1: raise TestFailed, 'len((1,))' -if len((1,2,3,4,5,6)) <> 6: raise TestFailed, 'len((1,2,3,4,5,6))' -if (1,2)+(3,4) <> (1,2,3,4): raise TestFailed, 'tuple concatenation' -if (1,2)*3 <> (1,2,1,2,1,2): raise TestFailed, 'tuple repetition *3' -if 0*(1,2,3) <> (): raise TestFailed, 'tuple repetition 0*' -if min((1,2)) <> 1 or max((1,2)) <> 2: raise TestFailed, 'min/max tuple' -if 0 in (0,1,2) and 1 in (0,1,2) and 2 in (0,1,2) and 3 not in (0,1,2): pass -else: raise TestFailed, 'in/not in tuple' - -print '6.5.3 Lists' -if len([]) <> 0: raise TestFailed, 'len([])' -if len([1,]) <> 1: raise TestFailed, 'len([1,])' -if len([1,2,3,4,5,6]) <> 6: raise TestFailed, 'len([1,2,3,4,5,6])' -if [1,2]+[3,4] <> [1,2,3,4]: raise TestFailed, 'list concatenation' -if [1,2]*3 <> [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3' -if 0*[1,2,3] <> []: raise TestFailed, 'list repetition 0*' -if min([1,2]) <> 1 or max([1,2]) <> 2: raise TestFailed, 'min/max list' -if 0 in [0,1,2] and 1 in [0,1,2] and 2 in [0,1,2] and 3 not in [0,1,2]: pass -else: raise TestFailed, 'in/not in list' - -print '6.5.3a Additional list operations' -a = [0,1,2,3,4] -a[0] = 5 -a[1] = 6 -a[2] = 7 -if a <> [5,6,7,3,4]: raise TestFailed, 'list item assignment [0], [1], [2]' -a[-2] = 8 -a[-1] = 9 -if a <> [5,6,7,8,9]: raise TestFailed, 'list item assignment [-2], [-1]' -a[:2] = [0,4] -a[-3:] = [] -a[1:1] = [1,2,3] -if a <> [0,1,2,3,4]: raise TestFailed, 'list slice assignment' -del a[1:4] -if a <> [0,4]: raise TestFailed, 'list slice deletion' -del a[0] -if a <> [4]: raise TestFailed, 'list item deletion [0]' -del a[-1] -if a <> []: raise TestFailed, 'list item deletion [-1]' -a.append(0) -a.append(1) -a.append(2) -if a <> [0,1,2]: raise TestFailed, 'list append' -a.insert(0, -2) -a.insert(1, -1) -a.insert(2,0) -if a <> [-2,-1,0,0,1,2]: raise TestFailed, 'list insert' -if a.count(0) <> 2: raise TestFailed, ' list count' -if a.index(0) <> 2: raise TestFailed, 'list index' -a.remove(0) -if a <> [-2,-1,0,1,2]: raise TestFailed, 'list remove' -a.reverse() -if a <> [2,1,0,-1,-2]: raise TestFailed, 'list reverse' -a.sort() -if a <> [-2,-1,0,1,2]: raise TestFailed, 'list sort' -def revcmp(a, b): return cmp(b, a) -a.sort(revcmp) -if a <> [2,1,0,-1,-2]: raise TestFailed, 'list sort with cmp func' - -print '6.6 Mappings == Dictionaries' -d = {} -if d.keys() <> []: raise TestFailed, '{}.keys()' -if d.has_key('a') <> 0: raise TestFailed, '{}.has_key(\'a\')' -if len(d) <> 0: raise TestFailed, 'len({})' -d = {'a': 1, 'b': 2} -if len(d) <> 2: raise TestFailed, 'len(dict)' -k = d.keys() -k.sort() -if k <> ['a', 'b']: raise TestFailed, 'dict keys()' -if d.has_key('a') and d.has_key('b') and not d.has_key('c'): pass -else: raise TestFailed, 'dict keys()' -if d['a'] <> 1 or d['b'] <> 2: raise TestFailed, 'dict item' -d['c'] = 3 -d['a'] = 4 -if d['c'] <> 3 or d['a'] <> 4: raise TestFailed, 'dict item assignment' -del d['b'] -if d <> {'a': 4, 'c': 3}: raise TestFailed, 'dict item deletion' diff --git a/Lib/test/testall.out b/Lib/test/testall.out deleted file mode 100644 index e69df95d14..0000000000 --- a/Lib/test/testall.out +++ /dev/null @@ -1,141 +0,0 @@ -test_grammar -1. Parser -1.1 Tokens -1.1.1 Backslashes -1.1.2 Numeric literals -1.1.2.1 Plain integers -1.1.2.2 Long integers -1.1.2.3 Floating point -1.1.3 String literals -1.2 Grammar -single_input -file_input -expr_input -eval_input -funcdef -simple_stmt -expr_stmt -print_stmt -1 2 3 -1 2 3 -1 1 1 -del_stmt -pass_stmt -flow_stmt -break_stmt -continue_stmt -return_stmt -raise_stmt -import_stmt -global_stmt -exec_stmt -if_stmt -while_stmt -for_stmt -try_stmt -suite -test -comparison -binary mask ops -shift ops -additive ops -multiplicative ops -unary ops -selectors -atoms -classdef -test_opcodes -2. Opcodes -XXX Not yet fully implemented -2.1 try inside for loop -2.2 raise class exceptions -test_operations -3. Operations -XXX Not yet implemented -test_builtin -4. Built-in functions -test_b1 -__import__ -abs -apply -callable -chr -cmp -coerce -compile -delattr -dir -divmod -eval -execfile -filter -float -getattr -hasattr -hash -hex -id -int -len -long -map -max -min -test_b2 -oct -open -ord -pow -range -input and raw_input -testing -testing -reduce -reload -repr -round -setattr -str -tuple -type -vars -xrange -test_exceptions -5. Built-in exceptions -AttributeError -EOFError -IOError -ImportError -IndexError -KeyError -KeyboardInterrupt -(not testable in a script) -MemoryError -(not safe to test) -NameError -OverflowError -RuntimeError -(not used any more?) -SyntaxError -SystemError -(hard to reproduce) -SystemExit -TypeError -ValueError -ZeroDivisionError -test_types -6. Built-in types -6.1 Truth value testing -6.2 Boolean operations -6.3 Comparisons -6.4 Numeric types (mostly conversions) -6.4.1 32-bit integers -6.4.2 Long integers -6.4.3 Floating point numbers -6.5 Sequence types -6.5.1 Strings -6.5.2 Tuples -6.5.3 Lists -6.5.3a Additional list operations -6.6 Mappings == Dictionaries -Passed all tests. diff --git a/Lib/test/testall.py b/Lib/test/testall.py deleted file mode 100644 index 92e7b9fe3f..0000000000 --- a/Lib/test/testall.py +++ /dev/null @@ -1,32 +0,0 @@ -# testall.py -- a regression test for the Python interpreter. -# To run the tests, execute "import testall" in a clean interpreter. -# It is a good idea to do this whenever you build a new interpreter. -# Remember to add new tests when new features are added! - -from test_support import * - -print 'test_grammar' -forget('test_grammar') -import test_grammar - -print 'test_opcodes' -unload('test_opcodes') -import test_opcodes - -print 'test_operations' -unload('test_operations') -import test_operations - -print 'test_builtin' -unload('test_builtin') -import test_builtin - -print 'test_exceptions' -unload('test_exceptions') -import test_exceptions - -print 'test_types' -unload('test_types') -import test_types - -print 'Passed all tests.' diff --git a/Lib/tkinter/Canvas.py b/Lib/tkinter/Canvas.py deleted file mode 100755 index 1e4a5c8694..0000000000 --- a/Lib/tkinter/Canvas.py +++ /dev/null @@ -1,190 +0,0 @@ -# This module exports classes for the various canvas item types - -from Tkinter import Canvas - -StringType = type('') -DictionaryType = type({}) - -def _flatten(tuple): - res = () - for item in tuple: - if type(item) in (TupleType, ListType): - res = res + _flatten(item) - elif item is not None: - res = res + (item,) - return res - -class CanvasItem: - def __init__(self, canvas, itemType, *args, **kw): - self.canvas = canvas - self.id = canvas._create(itemType, args, kw) - if not hasattr(canvas, 'items'): - canvas.items = {} - canvas.items[self.id] = self - def __str__(self): - return str(self.id) - def __repr__(self): - return '<%s, id=%d>' % (self.__class__.__name__, self.id) - def delete(self): - del self.canvas.items[self.id] - self.canvas.delete(self.id) - def __getitem__(self, key): - v = self.canvas.tk.split(self.canvas.tk.call( - self.canvas._w, 'itemconfigure', - self.id, '-' + key)) - return v[4] - def __setitem__(self, key, value): - self.canvas.itemconfig(self.id, {key: value}) - def keys(self): - if not hasattr(self, '_keys'): - self._keys = map(lambda x, tk=self.canvas.tk: - tk.splitlist(x)[0][1:], - self.canvas.tk.splitlist( - self.canvas._do( - 'itemconfigure', - (self.id,)))) - return self._keys - def has_key(self, key): - return key in self.keys() - def addtag(self, tag, option='withtag'): - self.canvas.addtag(tag, option, self.id) - def bbox(self): - x1, y1, x2, y2 = self.canvas.bbox(self.id) - return (x1, y1), (x2, y2) - def bind(self, sequence=None, command=None): - return self.canvas.bind(self.id, sequence, command) - def config(self, cnf=None): - return self.canvas.itemconfig(self.id, cnf) - def coords(self, pts = ()): - flat = () - for x, y in pts: flat = flat + (x, y) - return apply(self.canvas.coords, (self.id,) + flat) - def dchars(self, first, last=None): - self.canvas.dchars(self.id, first, last) - def dtag(self, ttd): - self.canvas.dtag(self.id, ttd) - def focus(self): - self.canvas.focus(self.id) - def gettags(self): - return self.canvas.gettags(self.id) - def icursor(self): - self.canvas.icursor(self.id) - def index(self): - return self.canvas.index(self.id) - def insert(self, beforethis, string): - self.canvas.insert(self.id, beforethis, string) - def lower(self, belowthis=None): - self.canvas.lower(self.id, belowthis) - def move(self, xamount, yamount): - self.canvas.move(self.id, xamount, yamount) - def tkraise(self, abovethis=None): - self.canvas.tkraise(self.id, abovethis) - raise_ = tkraise # BW compat - def scale(self, xorigin, yorigin, xscale, yscale): - self.canvas.scale(self.id, xorigin, yorigin, xscale, yscale) - def type(self): - return self.canvas.type(self.id) - -class Arc(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'arc', args) - -class Bitmap(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'bitmap', args) - -class ImageItem(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'image', args) - -class Line(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'line', args) - -class Oval(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'oval', args) - -class Polygon(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'polygon', args) - -class Rectangle(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'rectangle', args) - -# XXX "Text" is taken by the Text widget... -class CanvasText(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'text', args) - -class Window(CanvasItem): - def __init__(self, canvas, *args): - CanvasItem.__init__(self, canvas, 'window', args) - -class Group: - def __init__(self, canvas, tag=None): - if not tag: - tag = 'Group%d' % id(self) - self.tag = self.id = tag - self.canvas = canvas - self.canvas.dtag(self.tag) - def str(self): - return self.tag - def _do(self, cmd, *args): - return self.canvas._do(cmd, (self.tag,) + _flatten(args)) - def addtag_above(self, tagOrId): - self._do('addtag', 'above', tagOrId) - def addtag_all(self): - self._do('addtag', 'all') - def addtag_below(self, tagOrId): - self._do('addtag', 'below', tagOrId) - def addtag_closest(self, x, y, halo=None, start=None): - self._do('addtag', 'closest', x, y, halo, start) - def addtag_enclosed(self, x1, y1, x2, y2): - self._do('addtag', 'enclosed', x1, y1, x2, y2) - def addtag_overlapping(self, x1, y1, x2, y2): - self._do('addtag', 'overlapping', x1, y1, x2, y2) - def addtag_withtag(self, tagOrId): - self._do('addtag', 'withtag', tagOrId) - def bbox(self): - return self._getints(self._do('bbox')) - def bind(self, sequence=None, command=None): # XXX args? - return self._do('bind', sequence, command) - def coords(self, *pts): - return self._do('coords', pts) - def dchars(self, first, last=None): - self._do('dchars', first, last) - def delete(self): - self._do('delete') - def dtag(self, tagToDelete=None): - self._do('dtag', tagToDelete) - def focus(self): - self._do('focus') - def gettags(self): - return self.canvas.tk.splitlist(self._do('gettags', self.tag)) - def icursor(self, index): - return self._do('icursor') - def index(self, index): - return self.canvas.tk.getint(self._do('index', index)) - def insert(self, beforeThis, string): - self._do('insert', beforeThis, string) - def config(self, cnf=None): - return self.canvas.itemconfigure(self.tag, cnf) - def lower(self, belowThis=None): - self._do('lower', belowThis) - def move(self, xAmount, yAmount): - self._do('move', xAmount, yAmount) - def tkraise(self, aboveThis=None): - self._do('raise', aboveThis) - lift = tkraise - def scale(self, xOrigin, yOrigin, xScale, yScale): - self._do('scale', xOrigin, yOrigin, xScale, yScale) - def select_adjust(self, index): - self.canvas._do('select', ('adjust', self.tag, index)) - def select_from(self, index): - self.canvas._do('select', ('from', self.tag, index)) - def select_to(self, index): - self.canvas._do('select', ('to', self.tag, index)) - def type(self): - return self._do('type') diff --git a/Lib/tkinter/Dialog.py b/Lib/tkinter/Dialog.py deleted file mode 100755 index 67e7dc90ec..0000000000 --- a/Lib/tkinter/Dialog.py +++ /dev/null @@ -1,49 +0,0 @@ -# Dialog.py -- Tkinter interface to the tk_dialog script. - -from Tkinter import * -from Tkinter import _cnfmerge - -if TkVersion <= 3.6: - DIALOG_ICON = 'warning' -else: - DIALOG_ICON = 'questhead' - - -class Dialog(Widget): - def __init__(self, master=None, cnf={}, **kw): - cnf = _cnfmerge((cnf, kw)) - self.widgetName = '__dialog__' - Widget._setup(self, master, cnf) - self.num = self.tk.getint( - apply(self.tk.call, - ('tk_dialog', self._w, - cnf['title'], cnf['text'], - cnf['bitmap'], cnf['default']) - + cnf['strings'])) - try: Widget.destroy(self) - except TclError: pass - def destroy(self): pass - -def _test(): - d = Dialog(None, {'title': 'File Modified', - 'text': - 'File "Python.h" has been modified' - ' since the last time it was saved.' - ' Do you want to save it before' - ' exiting the application.', - 'bitmap': DIALOG_ICON, - 'default': 0, - 'strings': ('Save File', - 'Discard Changes', - 'Return to Editor')}) - print d.num - - -if __name__ == '__main__': - t = Button(None, {'text': 'Test', - 'command': _test, - Pack: {}}) - q = Button(None, {'text': 'Quit', - 'command': t.quit, - Pack: {}}) - t.mainloop() diff --git a/Lib/tkinter/FileDialog.py b/Lib/tkinter/FileDialog.py deleted file mode 100755 index 76271af5d5..0000000000 --- a/Lib/tkinter/FileDialog.py +++ /dev/null @@ -1,267 +0,0 @@ -"""File selection dialog classes. - -Classes: - -- FileDialog -- LoadFileDialog -- SaveFileDialog - -""" - -from Tkinter import * -from Dialog import Dialog - -ANCHOR = 'anchor' - -import os -import fnmatch - - -dialogstates = {} - - -class FileDialog: - - """Standard file selection dialog -- no checks on selected file. - - Usage: - - d = FileDialog(master) - file = d.go(dir_or_file, pattern, default, key) - if file is None: ...canceled... - else: ...open file... - - All arguments to go() are optional. - - The 'key' argument specifies a key in the global dictionary - 'dialogstates', which keeps track of the values for the directory - and pattern arguments, overriding the values passed in (it does - not keep track of the default argument!). If no key is specified, - the dialog keeps no memory of previous state. Note that memory is - kept even when the dialog is cancelled. (All this emulates the - behavior of the Macintosh file selection dialogs.) - - """ - - title = "File Selection Dialog" - - def __init__(self, master, title=None): - if title is None: title = self.title - self.master = master - self.directory = None - - self.top = Toplevel(master) - self.top.title(title) - self.top.iconname(title) - - self.botframe = Frame(self.top) - self.botframe.pack(side=BOTTOM, fill=X) - - self.selection = Entry(self.top) - self.selection.pack(side=BOTTOM, fill=X) - self.selection.bind('<Return>', self.ok_event) - - self.filter = Entry(self.top) - self.filter.pack(side=TOP, fill=X) - self.filter.bind('<Return>', self.filter_command) - - self.midframe = Frame(self.top) - self.midframe.pack(expand=YES, fill=BOTH) - - self.filesbar = Scrollbar(self.midframe) - self.filesbar.pack(side=RIGHT, fill=Y) - self.files = Listbox(self.midframe, exportselection=0, - yscrollcommand=(self.filesbar, 'set')) - self.files.pack(side=RIGHT, expand=YES, fill=BOTH) - self.files.bind('<ButtonRelease-1>', self.files_select_event) - self.files.bind('<Double-ButtonRelease-1>', self.files_double_event) - self.filesbar.config(command=(self.files, 'yview')) - - self.dirsbar = Scrollbar(self.midframe) - self.dirsbar.pack(side=LEFT, fill=Y) - self.dirs = Listbox(self.midframe, exportselection=0, - yscrollcommand=(self.dirsbar, 'set')) - self.dirs.pack(side=LEFT, expand=YES, fill=BOTH) - self.dirsbar.config(command=(self.dirs, 'yview')) - self.dirs.bind('<ButtonRelease-1>', self.dirs_select_event) - self.dirs.bind('<Double-ButtonRelease-1>', self.dirs_double_event) - - self.ok_button = Button(self.botframe, - text="OK", - command=self.ok_command) - self.ok_button.pack(side=LEFT) - self.filter_button = Button(self.botframe, - text="Filter", - command=self.filter_command) - self.filter_button.pack(side=LEFT, expand=YES) - self.cancel_button = Button(self.botframe, - text="Cancel", - command=self.cancel_command) - self.cancel_button.pack(side=RIGHT) - - self.top.protocol('WM_DELETE_WINDOW', self.cancel_command) - # XXX Are the following okay for a general audience? - self.top.bind('<Alt-w>', self.cancel_command) - self.top.bind('<Alt-W>', self.cancel_command) - - def go(self, dir_or_file=os.curdir, pattern="*", default="", key=None): - if key and dialogstates.has_key(key): - self.directory, pattern = dialogstates[key] - else: - dir_or_file = os.path.expanduser(dir_or_file) - if os.path.isdir(dir_or_file): - self.directory = dir_or_file - else: - self.directory, default = os.path.split(dir_or_file) - self.set_filter(self.directory, pattern) - self.set_selection(default) - self.filter_command() - self.selection.focus_set() - self.top.grab_set() - self.how = None - self.master.mainloop() # Exited by self.quit(how) - if key: dialogstates[key] = self.get_filter() - self.top.destroy() - return self.how - - def quit(self, how=None): - self.how = how - self.master.quit() # Exit mainloop() - - def dirs_double_event(self, event): - self.filter_command() - - def dirs_select_event(self, event): - dir, pat = self.get_filter() - subdir = self.dirs.get(ANCHOR) - dir = os.path.normpath(os.path.join(self.directory, subdir)) - self.set_filter(dir, pat) - - def files_double_event(self, event): - self.ok_command() - - def files_select_event(self, event): - file = self.files.get(ANCHOR) - self.set_selection(file) - - def ok_event(self, event): - self.ok_command() - - def ok_command(self): - self.quit(self.get_selection()) - - def filter_command(self, event=None): - dir, pat = self.get_filter() - try: - names = os.listdir(dir) - except os.error: - self.master.bell() - return - self.directory = dir - self.set_filter(dir, pat) - names.sort() - subdirs = [os.pardir] - matchingfiles = [] - for name in names: - fullname = os.path.join(dir, name) - if os.path.isdir(fullname): - subdirs.append(name) - elif fnmatch.fnmatch(name, pat): - matchingfiles.append(name) - self.dirs.delete(0, END) - for name in subdirs: - self.dirs.insert(END, name) - self.files.delete(0, END) - for name in matchingfiles: - self.files.insert(END, name) - head, tail = os.path.split(self.get_selection()) - if tail == os.curdir: tail = '' - self.set_selection(tail) - - def get_filter(self): - filter = self.filter.get() - filter = os.path.expanduser(filter) - if filter[-1:] == os.sep or os.path.isdir(filter): - filter = os.path.join(filter, "*") - return os.path.split(filter) - - def get_selection(self): - file = self.selection.get() - file = os.path.expanduser(file) - return file - - def cancel_command(self, event=None): - self.quit() - - def set_filter(self, dir, pat): - if not os.path.isabs(dir): - try: - pwd = os.getcwd() - except os.error: - pwd = None - if pwd: - dir = os.path.join(pwd, dir) - dir = os.path.normpath(dir) - self.filter.delete(0, END) - self.filter.insert(END, os.path.join(dir or os.curdir, pat or "*")) - - def set_selection(self, file): - self.selection.delete(0, END) - self.selection.insert(END, os.path.join(self.directory, file)) - - -class LoadFileDialog(FileDialog): - - """File selection dialog which checks that the file exists.""" - - title = "Load File Selection Dialog" - - def ok_command(self): - file = self.get_selection() - if not os.path.isfile(file): - self.master.bell() - else: - self.quit(file) - - -class SaveFileDialog(FileDialog): - - """File selection dialog which checks that the file may be created.""" - - title = "Save File Selection Dialog" - - def ok_command(self): - file = self.get_selection() - if os.path.exists(file): - if os.path.isdir(file): - self.master.bell() - return - d = Dialog(self.top, - title="Overwrite Existing File Question", - text="Overwrite existing file %s?" % `file`, - bitmap='questhead', - default=1, - strings=("Yes", "Cancel")) - if d.num != 0: - return - else: - head, tail = os.path.split(file) - if not os.path.isdir(head): - self.master.bell() - return - self.quit(file) - - -def test(): - """Simple test program.""" - root = Tk() - root.withdraw() - fd = LoadFileDialog(root) - loadfile = fd.go(key="test") - fd = SaveFileDialog(root) - savefile = fd.go(key="test") - print loadfile, savefile - - -if __name__ == '__main__': - test() diff --git a/Lib/tkinter/README b/Lib/tkinter/README deleted file mode 100755 index 2ff9f33995..0000000000 --- a/Lib/tkinter/README +++ /dev/null @@ -1,27 +0,0 @@ -Tommy Burnette <tnb2d@server.cs.virginia.edu> has created an -"official" version of Tkinter.py for Tk 4.0b3. I have placed it on -ftp.cwi.nl in ftp/python/src/tk4inter.shar. Note that this (probably) -isn't compatible with Tk 3.6, and explicitly tests for the Tk version -number (tkintermodule.c *is* compatible with both versions of Tk). -The shar file also contains a slightly modified version of Dialog.py. - -Here are Tommy's notes: - -> Here is an implementation of Tkinter.py that works with -> tk4.0b3. I've used it on sunos4, solaris and Irix5.2 for a few weeks -> and it all seems to work okay. It is an almalgam of patches put in by -> Steven Reiz <sreiz@aie.nl>, Guido vanRossum <guido@cnri.reston.va.us> -> and myself. I can say now that probably not all of the widgets have -> been updated, and the ones that have been updated have not been -> completely updated (i.e. some new commands on Text widgets and such -> are not in yet). So please post patches as you make them and if you -> have an "insurmountable" problems post those too and I'll see if I can -> help. I've also included versions of tributton.c and studbutton.c -> that I've updated for Tk4.0b3 (in case you use those- I know I LOVE -> tributtons!). Enjoy! - -I placed the *Button.c files in a separate shar file in -ftp/python/contrib/tk4buttons.shar. - ---Guido van Rossum, CWI, Amsterdam <mailto:guido@CNRI.Reston.VA.US> -<http://www.python.org/~guido/> diff --git a/Lib/tkinter/ScrolledText.py b/Lib/tkinter/ScrolledText.py deleted file mode 100755 index 0261d907aa..0000000000 --- a/Lib/tkinter/ScrolledText.py +++ /dev/null @@ -1,37 +0,0 @@ -# A ScrolledText widget feels like a text widget but also has a -# vertical scroll bar on its right. (Later, options may be added to -# add a horizontal bar as well, to make the bars disappear -# automatically when not needed, to move them to the other side of the -# window, etc.) -# -# Configuration options are passed to the Text widget. -# A Frame widget is inserted between the master and the text, to hold -# the Scrollbar widget. -# Most methods calls are inherited from the Text widget; Pack methods -# are redirected to the Frame widget however. - -from Tkinter import * -from Tkinter import _cnfmerge - -class ScrolledText(Text): - def __init__(self, master=None, cnf={}): - cnf = _cnfmerge(cnf) - fcnf = {} - vcnf = {'name': 'vbar', - Pack: {'side': 'right', 'fill': 'y'},} - for k in cnf.keys(): - if type(k) == ClassType or k == 'name': - fcnf[k] = cnf[k] - del cnf[k] - self.frame = Frame(master, fcnf) - self.vbar = Scrollbar(self.frame, vcnf) - cnf[Pack] = {'side': 'left', 'fill': 'both', 'expand': 'yes'} - cnf['name'] = 'text' - Text.__init__(self, self.frame, cnf) - self['yscrollcommand'] = (self.vbar, 'set') - self.vbar['command'] = (self, 'yview') - - # Copy Pack methods of self.frame -- hack! - for m in Pack.__dict__.keys(): - if m[0] != '_' and m != 'config': - setattr(self, m, getattr(self.frame, m)) diff --git a/Lib/tkinter/Tkconstants.py b/Lib/tkinter/Tkconstants.py deleted file mode 100755 index dd4fb0ef32..0000000000 --- a/Lib/tkinter/Tkconstants.py +++ /dev/null @@ -1,76 +0,0 @@ -# Symbolic constants for Tk - -# Booleans -NO=FALSE=OFF=0 -YES=TRUE=ON=1 - -# -anchor -N='n' -S='s' -W='w' -E='e' -NW='nw' -SW='sw' -NE='ne' -SE='se' -CENTER='center' - -# -fill -NONE='none' -X='x' -Y='y' -BOTH='both' - -# -side -LEFT='left' -TOP='top' -RIGHT='right' -BOTTOM='bottom' - -# -relief -RAISED='raised' -SUNKEN='sunken' -FLAT='flat' -RIDGE='ridge' -GROOVE='groove' - -# -orient -HORIZONTAL='horizontal' -VERTICAL='vertical' - -# -tabs -NUMERIC='numeric' - -# -wrap -CHAR='char' -WORD='word' - -# -align -BASELINE='baseline' - -# Special tags, marks and insert positions -SEL='sel' -SEL_FIRST='sel.first' -SEL_LAST='sel.last' -END='end' -INSERT='insert' -CURRENT='current' -ANCHOR='anchor' - -# Text widget and button states -NORMAL='normal' -DISABLED='disabled' -ACTIVE='active' - -# Menu item types -CASCADE='cascade' -CHECKBUTTON='checkbutton' -COMMAND='command' -RADIOBUTTON='radiobutton' -SEPARATOR='separator' - -# Selection modes for list boxes -SINGLE='single' -BROWSE='browse' -MULTIPLE='multiple' -EXTENDED='extended' diff --git a/Lib/tkinter/Tkinter.py b/Lib/tkinter/Tkinter.py deleted file mode 100755 index d033823f88..0000000000 --- a/Lib/tkinter/Tkinter.py +++ /dev/null @@ -1,1569 +0,0 @@ -# Tkinter.py -- Tk/Tcl widget wrappers - -__version__ = "$Revision$" - -try: - # See if modern _tkinter is present - import _tkinter - tkinter = _tkinter # b/w compat -except ImportError: - # No modern _tkinter -- try oldfashioned tkinter - import tkinter - if hasattr(tkinter, "__path__"): - import sys, os - # Append standard platform specific directory - p = tkinter.__path__ - for dir in sys.path: - if (dir not in p and - os.path.basename(dir) == sys.platform): - p.append(dir) - del sys, os, p, dir - from tkinter import tkinter -TclError = tkinter.TclError -from types import * -from Tkconstants import * -import string; _string = string; del string - -TkVersion = _string.atof(tkinter.TK_VERSION) -TclVersion = _string.atof(tkinter.TCL_VERSION) - -###################################################################### -# Since the values of file event masks changed from Tk 4.0 to Tk 4.1, -# they are defined here (and not in Tkconstants): -###################################################################### -if TkVersion >= 4.1: - READABLE = 2 - WRITABLE = 4 - EXCEPTION = 8 -else: - READABLE = 1 - WRITABLE = 2 - EXCEPTION = 4 - - -def _flatten(tuple): - res = () - for item in tuple: - if type(item) in (TupleType, ListType): - res = res + _flatten(item) - elif item is not None: - res = res + (item,) - return res - -def _cnfmerge(cnfs): - if type(cnfs) is DictionaryType: - return cnfs - elif type(cnfs) in (NoneType, StringType): - - return cnfs - else: - cnf = {} - for c in _flatten(cnfs): - for k, v in c.items(): - cnf[k] = v - return cnf - -class Event: - pass - -_default_root = None - -def _tkerror(err): - pass - -def _exit(code='0'): - raise SystemExit, code - -_varnum = 0 -class Variable: - def __init__(self, master=None): - global _default_root - global _varnum - if master: - self._tk = master.tk - else: - self._tk = _default_root.tk - self._name = 'PY_VAR' + `_varnum` - _varnum = _varnum + 1 - def __del__(self): - self._tk.globalunsetvar(self._name) - def __str__(self): - return self._name - def set(self, value): - return self._tk.globalsetvar(self._name, value) - -class StringVar(Variable): - def __init__(self, master=None): - Variable.__init__(self, master) - def get(self): - return self._tk.globalgetvar(self._name) - -class IntVar(Variable): - def __init__(self, master=None): - Variable.__init__(self, master) - def get(self): - return self._tk.getint(self._tk.globalgetvar(self._name)) - -class DoubleVar(Variable): - def __init__(self, master=None): - Variable.__init__(self, master) - def get(self): - return self._tk.getdouble(self._tk.globalgetvar(self._name)) - -class BooleanVar(Variable): - def __init__(self, master=None): - Variable.__init__(self, master) - def get(self): - return self._tk.getboolean(self._tk.globalgetvar(self._name)) - -def mainloop(n=0): - _default_root.tk.mainloop(n) - -def getint(s): - return _default_root.tk.getint(s) - -def getdouble(s): - return _default_root.tk.getdouble(s) - -def getboolean(s): - return _default_root.tk.getboolean(s) - -class Misc: - def tk_strictMotif(self, boolean=None): - return self.tk.getboolean(self.tk.call( - 'set', 'tk_strictMotif', boolean)) - def tk_menuBar(self, *args): - apply(self.tk.call, ('tk_menuBar', self._w) + args) - def wait_variable(self, name='PY_VAR'): - self.tk.call('tkwait', 'variable', name) - waitvar = wait_variable # XXX b/w compat - def wait_window(self, window=None): - if window == None: - window = self - self.tk.call('tkwait', 'window', window._w) - def wait_visibility(self, window=None): - if window == None: - window = self - self.tk.call('tkwait', 'visibility', window._w) - def setvar(self, name='PY_VAR', value='1'): - self.tk.setvar(name, value) - def getvar(self, name='PY_VAR'): - return self.tk.getvar(name) - def getint(self, s): - return self.tk.getint(s) - def getdouble(self, s): - return self.tk.getdouble(s) - def getboolean(self, s): - return self.tk.getboolean(s) - def focus_set(self): - self.tk.call('focus', self._w) - focus = focus_set # XXX b/w compat? - def focus_default_set(self): - self.tk.call('focus', 'default', self._w) - def focus_default_none(self): - self.tk.call('focus', 'default', 'none') - focus_default = focus_default_set - def focus_none(self): - self.tk.call('focus', 'none') - def focus_get(self): - name = self.tk.call('focus') - if name == 'none': return None - return self._nametowidget(name) - def tk_focusNext(self): - name = self.tk.call('tk_focusNext', self._w) - if not name: return None - return self._nametowidget(name) - def tk_focusPrev(self): - name = self.tk.call('tk_focusPrev', self._w) - if not name: return None - return self._nametowidget(name) - def after(self, ms, func=None, *args): - if not func: - # I'd rather use time.sleep(ms*0.001) - self.tk.call('after', ms) - else: - # XXX Disgusting hack to clean up after calling func - tmp = [] - def callit(func=func, args=args, tk=self.tk, tmp=tmp): - try: - apply(func, args) - finally: - tk.deletecommand(tmp[0]) - name = self._register(callit) - tmp.append(name) - return self.tk.call('after', ms, name) - def after_idle(self, func, *args): - return apply(self.after, ('idle', func) + args) - def after_cancel(self, id): - self.tk.call('after', 'cancel', id) - def bell(self, displayof=None): - if displayof: - self.tk.call('bell', '-displayof', displayof) - else: - self.tk.call('bell', '-displayof', self._w) - # XXX grab current w/o window argument - def grab_current(self): - name = self.tk.call('grab', 'current', self._w) - if not name: return None - return self._nametowidget(name) - def grab_release(self): - self.tk.call('grab', 'release', self._w) - def grab_set(self): - self.tk.call('grab', 'set', self._w) - def grab_set_global(self): - self.tk.call('grab', 'set', '-global', self._w) - def grab_status(self): - status = self.tk.call('grab', 'status', self._w) - if status == 'none': status = None - return status - def lower(self, belowThis=None): - self.tk.call('lower', self._w, belowThis) - def option_add(self, pattern, value, priority = None): - self.tk.call('option', 'add', pattern, value, priority) - def option_clear(self): - self.tk.call('option', 'clear') - def option_get(self, name, className): - return self.tk.call('option', 'get', self._w, name, className) - def option_readfile(self, fileName, priority = None): - self.tk.call('option', 'readfile', fileName, priority) - def selection_clear(self): - self.tk.call('selection', 'clear', self._w) - def selection_get(self, type=None): - return self.tk.call('selection', 'get', type) - def selection_handle(self, func, type=None, format=None): - name = self._register(func) - self.tk.call('selection', 'handle', self._w, - name, type, format) - def selection_own(self, func=None): - name = self._register(func) - self.tk.call('selection', 'own', self._w, name) - def selection_own_get(self): - return self._nametowidget(self.tk.call('selection', 'own')) - def send(self, interp, cmd, *args): - return apply(self.tk.call, ('send', interp, cmd) + args) - def lower(self, belowThis=None): - self.tk.call('lift', self._w, belowThis) - def tkraise(self, aboveThis=None): - self.tk.call('raise', self._w, aboveThis) - lift = tkraise - def colormodel(self, value=None): - return self.tk.call('tk', 'colormodel', self._w, value) - def winfo_atom(self, name): - return self.tk.getint(self.tk.call('winfo', 'atom', name)) - def winfo_atomname(self, id): - return self.tk.call('winfo', 'atomname', id) - def winfo_cells(self): - return self.tk.getint( - self.tk.call('winfo', 'cells', self._w)) - def winfo_children(self): - return map(self._nametowidget, - self.tk.splitlist(self.tk.call( - 'winfo', 'children', self._w))) - def winfo_class(self): - return self.tk.call('winfo', 'class', self._w) - def winfo_containing(self, rootX, rootY): - return self.tk.call('winfo', 'containing', rootX, rootY) - def winfo_depth(self): - return self.tk.getint(self.tk.call('winfo', 'depth', self._w)) - def winfo_exists(self): - return self.tk.getint( - self.tk.call('winfo', 'exists', self._w)) - def winfo_fpixels(self, number): - return self.tk.getdouble(self.tk.call( - 'winfo', 'fpixels', self._w, number)) - def winfo_geometry(self): - return self.tk.call('winfo', 'geometry', self._w) - def winfo_height(self): - return self.tk.getint( - self.tk.call('winfo', 'height', self._w)) - def winfo_id(self): - return self.tk.getint( - self.tk.call('winfo', 'id', self._w)) - def winfo_interps(self): - return self.tk.splitlist( - self.tk.call('winfo', 'interps')) - def winfo_ismapped(self): - return self.tk.getint( - self.tk.call('winfo', 'ismapped', self._w)) - def winfo_name(self): - return self.tk.call('winfo', 'name', self._w) - def winfo_parent(self): - return self.tk.call('winfo', 'parent', self._w) - def winfo_pathname(self, id): - return self.tk.call('winfo', 'pathname', id) - def winfo_pixels(self, number): - return self.tk.getint( - self.tk.call('winfo', 'pixels', self._w, number)) - def winfo_reqheight(self): - return self.tk.getint( - self.tk.call('winfo', 'reqheight', self._w)) - def winfo_reqwidth(self): - return self.tk.getint( - self.tk.call('winfo', 'reqwidth', self._w)) - def winfo_rgb(self, color): - return self._getints( - self.tk.call('winfo', 'rgb', self._w, color)) - def winfo_rootx(self): - return self.tk.getint( - self.tk.call('winfo', 'rootx', self._w)) - def winfo_rooty(self): - return self.tk.getint( - self.tk.call('winfo', 'rooty', self._w)) - def winfo_screen(self): - return self.tk.call('winfo', 'screen', self._w) - def winfo_screencells(self): - return self.tk.getint( - self.tk.call('winfo', 'screencells', self._w)) - def winfo_screendepth(self): - return self.tk.getint( - self.tk.call('winfo', 'screendepth', self._w)) - def winfo_screenheight(self): - return self.tk.getint( - self.tk.call('winfo', 'screenheight', self._w)) - def winfo_screenmmheight(self): - return self.tk.getint( - self.tk.call('winfo', 'screenmmheight', self._w)) - def winfo_screenmmwidth(self): - return self.tk.getint( - self.tk.call('winfo', 'screenmmwidth', self._w)) - def winfo_screenvisual(self): - return self.tk.call('winfo', 'screenvisual', self._w) - def winfo_screenwidth(self): - return self.tk.getint( - self.tk.call('winfo', 'screenwidth', self._w)) - def winfo_toplevel(self): - return self._nametowidget(self.tk.call( - 'winfo', 'toplevel', self._w)) - def winfo_visual(self): - return self.tk.call('winfo', 'visual', self._w) - def winfo_vrootheight(self): - return self.tk.getint( - self.tk.call('winfo', 'vrootheight', self._w)) - def winfo_vrootwidth(self): - return self.tk.getint( - self.tk.call('winfo', 'vrootwidth', self._w)) - def winfo_vrootx(self): - return self.tk.getint( - self.tk.call('winfo', 'vrootx', self._w)) - def winfo_vrooty(self): - return self.tk.getint( - self.tk.call('winfo', 'vrooty', self._w)) - def winfo_width(self): - return self.tk.getint( - self.tk.call('winfo', 'width', self._w)) - def winfo_x(self): - return self.tk.getint( - self.tk.call('winfo', 'x', self._w)) - def winfo_y(self): - return self.tk.getint( - self.tk.call('winfo', 'y', self._w)) - def update(self): - self.tk.call('update') - def update_idletasks(self): - self.tk.call('update', 'idletasks') - def bindtags(self, tagList=None): - if tagList is None: - return self.tk.splitlist( - self.tk.call('bindtags', self._w)) - else: - self.tk.call('bindtags', self._w, tagList) - def _bind(self, what, sequence, func, add): - if func: - cmd = ("%sset _tkinter_break [%s %s]\n" - 'if {"$_tkinter_break" == "break"} break\n') \ - % (add and '+' or '', - self._register(func, self._substitute), - _string.join(self._subst_format)) - apply(self.tk.call, what + (sequence, cmd)) - elif func == '': - apply(self.tk.call, what + (sequence, func)) - else: - return apply(self.tk.call, what + (sequence,)) - def bind(self, sequence=None, func=None, add=None): - return self._bind(('bind', self._w), sequence, func, add) - def unbind(self, sequence): - self.tk.call('bind', self._w, sequence, '') - def bind_all(self, sequence=None, func=None, add=None): - return self._bind(('bind', 'all'), sequence, func, add) - def unbind_all(self, sequence): - self.tk.call('bind', 'all' , sequence, '') - def bind_class(self, className, sequence=None, func=None, add=None): - self._bind(('bind', className), sequence, func, add) - def unbind_class(self, className, sequence): - self.tk.call('bind', className , sequence, '') - def mainloop(self, n=0): - self.tk.mainloop(n) - def quit(self): - self.tk.quit() - def _getints(self, string): - if not string: return None - return tuple(map(self.tk.getint, self.tk.splitlist(string))) - def _getdoubles(self, string): - if not string: return None - return tuple(map(self.tk.getdouble, self.tk.splitlist(string))) - def _getboolean(self, string): - if string: - return self.tk.getboolean(string) - def _options(self, cnf, kw = None): - if kw: - cnf = _cnfmerge((cnf, kw)) - else: - cnf = _cnfmerge(cnf) - res = () - for k, v in cnf.items(): - if k[-1] == '_': k = k[:-1] - if callable(v): - v = self._register(v) - res = res + ('-'+k, v) - return res - def _nametowidget(self, name): - w = self - if name[0] == '.': - w = w._root() - name = name[1:] - find = _string.find - while name: - i = find(name, '.') - if i >= 0: - name, tail = name[:i], name[i+1:] - else: - tail = '' - w = w.children[name] - name = tail - return w - def _register(self, func, subst=None): - f = CallWrapper(func, subst, self).__call__ - name = `id(f)` - try: - func = func.im_func - except AttributeError: - pass - try: - name = name + func.__name__ - except AttributeError: - pass - self.tk.createcommand(name, f) - return name - register = _register - def _root(self): - w = self - while w.master: w = w.master - return w - _subst_format = ('%#', '%b', '%f', '%h', '%k', - '%s', '%t', '%w', '%x', '%y', - '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y') - def _substitute(self, *args): - tk = self.tk - if len(args) != len(self._subst_format): return args - nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y = args - # Missing: (a, c, d, m, o, v, B, R) - e = Event() - e.serial = tk.getint(nsign) - e.num = tk.getint(b) - try: e.focus = tk.getboolean(f) - except TclError: pass - e.height = tk.getint(h) - e.keycode = tk.getint(k) - # For Visibility events, event state is a string and - # not an integer: - try: - e.state = tk.getint(s) - except TclError: - e.state = s - e.time = tk.getint(t) - e.width = tk.getint(w) - e.x = tk.getint(x) - e.y = tk.getint(y) - e.char = A - try: e.send_event = tk.getboolean(E) - except TclError: pass - e.keysym = K - e.keysym_num = tk.getint(N) - e.type = T - e.widget = self._nametowidget(W) - e.x_root = tk.getint(X) - e.y_root = tk.getint(Y) - return (e,) - def _report_exception(self): - import sys - exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback - root = self._root() - root.report_callback_exception(exc, val, tb) - -class CallWrapper: - def __init__(self, func, subst, widget): - self.func = func - self.subst = subst - self.widget = widget - def __call__(self, *args): - try: - if self.subst: - args = apply(self.subst, args) - return apply(self.func, args) - except SystemExit, msg: - raise SystemExit, msg - except: - self.widget._report_exception() - -class Wm: - def aspect(self, - minNumer=None, minDenom=None, - maxNumer=None, maxDenom=None): - return self._getints( - self.tk.call('wm', 'aspect', self._w, - minNumer, minDenom, - maxNumer, maxDenom)) - def client(self, name=None): - return self.tk.call('wm', 'client', self._w, name) - def command(self, value=None): - return self.tk.call('wm', 'command', self._w, value) - def deiconify(self): - return self.tk.call('wm', 'deiconify', self._w) - def focusmodel(self, model=None): - return self.tk.call('wm', 'focusmodel', self._w, model) - def frame(self): - return self.tk.call('wm', 'frame', self._w) - def geometry(self, newGeometry=None): - return self.tk.call('wm', 'geometry', self._w, newGeometry) - def grid(self, - baseWidht=None, baseHeight=None, - widthInc=None, heightInc=None): - return self._getints(self.tk.call( - 'wm', 'grid', self._w, - baseWidht, baseHeight, widthInc, heightInc)) - def group(self, pathName=None): - return self.tk.call('wm', 'group', self._w, pathName) - def iconbitmap(self, bitmap=None): - return self.tk.call('wm', 'iconbitmap', self._w, bitmap) - def iconify(self): - return self.tk.call('wm', 'iconify', self._w) - def iconmask(self, bitmap=None): - return self.tk.call('wm', 'iconmask', self._w, bitmap) - def iconname(self, newName=None): - return self.tk.call('wm', 'iconname', self._w, newName) - def iconposition(self, x=None, y=None): - return self._getints(self.tk.call( - 'wm', 'iconposition', self._w, x, y)) - def iconwindow(self, pathName=None): - return self.tk.call('wm', 'iconwindow', self._w, pathName) - def maxsize(self, width=None, height=None): - return self._getints(self.tk.call( - 'wm', 'maxsize', self._w, width, height)) - def minsize(self, width=None, height=None): - return self._getints(self.tk.call( - 'wm', 'minsize', self._w, width, height)) - def overrideredirect(self, boolean=None): - return self._getboolean(self.tk.call( - 'wm', 'overrideredirect', self._w, boolean)) - def positionfrom(self, who=None): - return self.tk.call('wm', 'positionfrom', self._w, who) - def protocol(self, name=None, func=None): - if callable(func): - command = self._register(func) - else: - command = func - return self.tk.call( - 'wm', 'protocol', self._w, name, command) - def resizable(self, width=None, height=None): - return self.tk.call('wm', 'resizable', self._w, width, height) - def sizefrom(self, who=None): - return self.tk.call('wm', 'sizefrom', self._w, who) - def state(self): - return self.tk.call('wm', 'state', self._w) - def title(self, string=None): - return self.tk.call('wm', 'title', self._w, string) - def transient(self, master=None): - return self.tk.call('wm', 'transient', self._w, master) - def withdraw(self): - return self.tk.call('wm', 'withdraw', self._w) - -class Tk(Misc, Wm): - _w = '.' - def __init__(self, screenName=None, baseName=None, className='Tk'): - global _default_root - self.master = None - self.children = {} - if baseName is None: - import sys, os - baseName = os.path.basename(sys.argv[0]) - if baseName[-3:] == '.py': baseName = baseName[:-3] - self.tk = tkinter.create(screenName, baseName, className) - try: - # Disable event scanning except for Command-Period - import MacOS - MacOS.EnableAppswitch(0) - except ImportError: - pass - else: - # Work around nasty MacTk bug - self.update() - # Version sanity checks - tk_version = self.tk.getvar('tk_version') - if tk_version != tkinter.TK_VERSION: - raise RuntimeError, \ - "tk.h version (%s) doesn't match libtk.a version (%s)" \ - % (tkinter.TK_VERSION, tk_version) - tcl_version = self.tk.getvar('tcl_version') - if tcl_version != tkinter.TCL_VERSION: - raise RuntimeError, \ - "tcl.h version (%s) doesn't match libtcl.a version (%s)" \ - % (tkinter.TCL_VERSION, tcl_version) - if TkVersion < 4.0: - raise RuntimeError, \ - "Tk 4.0 or higher is required; found Tk %s" \ - % str(TkVersion) - self.tk.createcommand('tkerror', _tkerror) - self.tk.createcommand('exit', _exit) - self.readprofile(baseName, className) - if not _default_root: - _default_root = self - def destroy(self): - for c in self.children.values(): c.destroy() - self.tk.call('destroy', self._w) - def __str__(self): - return self._w - def readprofile(self, baseName, className): - import os - if os.environ.has_key('HOME'): home = os.environ['HOME'] - else: home = os.curdir - class_tcl = os.path.join(home, '.%s.tcl' % className) - class_py = os.path.join(home, '.%s.py' % className) - base_tcl = os.path.join(home, '.%s.tcl' % baseName) - base_py = os.path.join(home, '.%s.py' % baseName) - dir = {'self': self} - exec 'from Tkinter import *' in dir - if os.path.isfile(class_tcl): - print 'source', `class_tcl` - self.tk.call('source', class_tcl) - if os.path.isfile(class_py): - print 'execfile', `class_py` - execfile(class_py, dir) - if os.path.isfile(base_tcl): - print 'source', `base_tcl` - self.tk.call('source', base_tcl) - if os.path.isfile(base_py): - print 'execfile', `base_py` - execfile(base_py, dir) - def report_callback_exception(self, exc, val, tb): - import traceback - print "Exception in Tkinter callback" - traceback.print_exception(exc, val, tb) - -class Pack: - def config(self, cnf={}, **kw): - apply(self.tk.call, - ('pack', 'configure', self._w) - + self._options(cnf, kw)) - configure = config - pack = config - def __setitem__(self, key, value): - Pack.config({key: value}) - def forget(self): - self.tk.call('pack', 'forget', self._w) - pack_forget = forget - def info(self): - words = self.tk.splitlist( - self.tk.call('pack', 'info', self._w)) - dict = {} - for i in range(0, len(words), 2): - key = words[i][1:] - value = words[i+1] - if value[:1] == '.': - value = self._nametowidget(value) - dict[key] = value - return dict - pack_info = info - _noarg_ = ['_noarg_'] - def propagate(self, flag=_noarg_): - if flag is Pack._noarg_: - return self._getboolean(self.tk.call( - 'pack', 'propagate', self._w)) - else: - self.tk.call('pack', 'propagate', self._w, flag) - pack_propagate = propagate - def slaves(self): - return map(self._nametowidget, - self.tk.splitlist( - self.tk.call('pack', 'slaves', self._w))) - pack_slaves = slaves - -class Place: - def config(self, cnf={}, **kw): - for k in ['in_']: - if kw.has_key(k): - kw[k[:-1]] = kw[k] - del kw[k] - apply(self.tk.call, - ('place', 'configure', self._w) - + self._options(cnf, kw)) - configure = config - place = config - def __setitem__(self, key, value): - Place.config({key: value}) - def forget(self): - self.tk.call('place', 'forget', self._w) - place_forget = forget - def info(self): - words = self.tk.splitlist( - self.tk.call('place', 'info', self._w)) - dict = {} - for i in range(0, len(words), 2): - key = words[i][1:] - value = words[i+1] - if value[:1] == '.': - value = self._nametowidget(value) - dict[key] = value - return dict - place_info = info - def slaves(self): - return map(self._nametowidget, - self.tk.splitlist( - self.tk.call( - 'place', 'slaves', self._w))) - place_slaves = slaves - -class Grid: - # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu) - def config(self, cnf={}, **kw): - apply(self.tk.call, - ('grid', 'configure', self._w) - + self._options(cnf, kw)) - grid = config - def __setitem__(self, key, value): - Grid.config({key: value}) - def bbox(self, column, row): - return self._getints( - self.tk.call( - 'grid', 'bbox', self._w, column, row)) or None - grid_bbox = bbox - def columnconfigure(self, index, cnf={}, **kw): - if type(cnf) is not DictionaryType and not kw: - options = self._options({cnf: None}) - else: - options = self._options(cnf, kw) - res = apply(self.tk.call, - ('grid', 'columnconfigure', self._w, index) - + options) - if options == ('-minsize', None): - return self.tk.getint(res) or None - elif options == ('-weight', None): - return self.tk.getdouble(res) or None - def forget(self): - self.tk.call('grid', 'forget', self._w) - grid_forget = forget - def info(self): - words = self.tk.splitlist( - self.tk.call('grid', 'info', self._w)) - dict = {} - for i in range(0, len(words), 2): - key = words[i][1:] - value = words[i+1] - if value[:1] == '.': - value = self._nametowidget(value) - dict[key] = value - return dict - grid_info = info - def location(self, x, y): - return self._getints( - self.tk.call( - 'grid', 'location', self._w, x, y)) or None - _noarg_ = ['_noarg_'] - def propagate(self, flag=_noarg_): - if flag is Grid._noarg_: - return self._getboolean(self.tk.call( - 'grid', 'propagate', self._w)) - else: - self.tk.call('grid', 'propagate', self._w, flag) - grid_propagate = propagate - def rowconfigure(self, index, cnf={}, **kw): - if type(cnf) is not DictionaryType and not kw: - options = self._options({cnf: None}) - else: - options = self._options(cnf, kw) - res = apply(self.tk.call, - ('grid', 'rowconfigure', self._w, index) - + options) - if options == ('-minsize', None): - return self.tk.getint(res) or None - elif options == ('-weight', None): - return self.tk.getdouble(res) or None - def size(self): - return self._getints( - self.tk.call('grid', 'size', self._w)) or None - def slaves(self, *args): - return map(self._nametowidget, - self.tk.splitlist( - apply(self.tk.call, - ('grid', 'slaves', self._w) + args))) - grid_slaves = slaves - -class Widget(Misc, Pack, Place, Grid): - def _setup(self, master, cnf): - global _default_root - if not master: - if not _default_root: - _default_root = Tk() - master = _default_root - if not _default_root: - _default_root = master - self.master = master - self.tk = master.tk - if cnf.has_key('name'): - name = cnf['name'] - del cnf['name'] - else: - name = `id(self)` - self._name = name - if master._w=='.': - self._w = '.' + name - else: - self._w = master._w + '.' + name - self.children = {} - if self.master.children.has_key(self._name): - self.master.children[self._name].destroy() - self.master.children[self._name] = self - def __init__(self, master, widgetName, cnf={}, kw={}, extra=()): - if kw: - cnf = _cnfmerge((cnf, kw)) - self.widgetName = widgetName - Widget._setup(self, master, cnf) - apply(self.tk.call, - (widgetName, self._w) + extra + self._options(cnf)) - def config(self, cnf=None, **kw): - # XXX ought to generalize this so tag_config etc. can use it - if kw: - cnf = _cnfmerge((cnf, kw)) - elif cnf: - cnf = _cnfmerge(cnf) - if cnf is None: - cnf = {} - for x in self.tk.split( - self.tk.call(self._w, 'configure')): - cnf[x[0][1:]] = (x[0][1:],) + x[1:] - return cnf - if type(cnf) is StringType: - x = self.tk.split(self.tk.call( - self._w, 'configure', '-'+cnf)) - return (x[0][1:],) + x[1:] - for k in cnf.keys(): - if type(k) is ClassType: - k.config(self, cnf[k]) - del cnf[k] - apply(self.tk.call, (self._w, 'configure') - + self._options(cnf)) - configure = config - def cget(self, key): - return self.tk.call(self._w, 'cget', '-' + key) - __getitem__ = cget - def __setitem__(self, key, value): - Widget.config(self, {key: value}) - def keys(self): - return map(lambda x: x[0][1:], - self.tk.split(self.tk.call(self._w, 'configure'))) - def __str__(self): - return self._w - def destroy(self): - for c in self.children.values(): c.destroy() - if self.master.children.has_key(self._name): - del self.master.children[self._name] - self.tk.call('destroy', self._w) - def _do(self, name, args=()): - return apply(self.tk.call, (self._w, name) + args) - -class Toplevel(Widget, Wm): - def __init__(self, master=None, cnf={}, **kw): - if kw: - cnf = _cnfmerge((cnf, kw)) - extra = () - for wmkey in ['screen', 'class_', 'class', 'visual', - 'colormap']: - if cnf.has_key(wmkey): - val = cnf[wmkey] - # TBD: a hack needed because some keys - # are not valid as keyword arguments - if wmkey[-1] == '_': opt = '-'+wmkey[:-1] - else: opt = '-'+wmkey - extra = extra + (opt, val) - del cnf[wmkey] - Widget.__init__(self, master, 'toplevel', cnf, {}, extra) - root = self._root() - self.iconname(root.iconname()) - self.title(root.title()) - -class Button(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'button', cnf, kw) - def tkButtonEnter(self, *dummy): - self.tk.call('tkButtonEnter', self._w) - def tkButtonLeave(self, *dummy): - self.tk.call('tkButtonLeave', self._w) - def tkButtonDown(self, *dummy): - self.tk.call('tkButtonDown', self._w) - def tkButtonUp(self, *dummy): - self.tk.call('tkButtonUp', self._w) - def tkButtonInvoke(self, *dummy): - self.tk.call('tkButtonInvoke', self._w) - def flash(self): - self.tk.call(self._w, 'flash') - def invoke(self): - self.tk.call(self._w, 'invoke') - -# Indices: -# XXX I don't like these -- take them away -def AtEnd(): - return 'end' -def AtInsert(*args): - s = 'insert' - for a in args: - if a: s = s + (' ' + a) - return s -def AtSelFirst(): - return 'sel.first' -def AtSelLast(): - return 'sel.last' -def At(x, y=None): - if y is None: - return '@' + `x` - else: - return '@' + `x` + ',' + `y` - -class Canvas(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'canvas', cnf, kw) - def addtag(self, *args): - self._do('addtag', args) - def addtag_above(self, tagOrId): - self.addtag('above', tagOrId) - def addtag_all(self): - self.addtag('all') - def addtag_below(self, tagOrId): - self.addtag('below', tagOrId) - def addtag_closest(self, x, y, halo=None, start=None): - self.addtag('closest', x, y, halo, start) - def addtag_enclosed(self, x1, y1, x2, y2): - self.addtag('enclosed', x1, y1, x2, y2) - def addtag_overlapping(self, x1, y1, x2, y2): - self.addtag('overlapping', x1, y1, x2, y2) - def addtag_withtag(self, tagOrId): - self.addtag('withtag', tagOrId) - def bbox(self, *args): - return self._getints(self._do('bbox', args)) or None - def tag_unbind(self, tagOrId, sequence): - self.tk.call(self._w, 'bind', tagOrId, sequence, '') - def tag_bind(self, tagOrId, sequence=None, func=None, add=None): - return self._bind((self._w, 'tag', 'bind', tagOrId), - sequence, func, add) - def canvasx(self, screenx, gridspacing=None): - return self.tk.getdouble(self.tk.call( - self._w, 'canvasx', screenx, gridspacing)) - def canvasy(self, screeny, gridspacing=None): - return self.tk.getdouble(self.tk.call( - self._w, 'canvasy', screeny, gridspacing)) - def coords(self, *args): - return self._do('coords', args) - def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={}) - args = _flatten(args) - cnf = args[-1] - if type(cnf) in (DictionaryType, TupleType): - args = args[:-1] - else: - cnf = {} - return self.tk.getint(apply( - self.tk.call, - (self._w, 'create', itemType) - + args + self._options(cnf, kw))) - def create_arc(self, *args, **kw): - return self._create('arc', args, kw) - def create_bitmap(self, *args, **kw): - return self._create('bitmap', args, kw) - def create_image(self, *args, **kw): - return self._create('image', args, kw) - def create_line(self, *args, **kw): - return self._create('line', args, kw) - def create_oval(self, *args, **kw): - return self._create('oval', args, kw) - def create_polygon(self, *args, **kw): - return self._create('polygon', args, kw) - def create_rectangle(self, *args, **kw): - return self._create('rectangle', args, kw) - def create_text(self, *args, **kw): - return self._create('text', args, kw) - def create_window(self, *args, **kw): - return self._create('window', args, kw) - def dchars(self, *args): - self._do('dchars', args) - def delete(self, *args): - self._do('delete', args) - def dtag(self, *args): - self._do('dtag', args) - def find(self, *args): - return self._getints(self._do('find', args)) or () - def find_above(self, tagOrId): - return self.find('above', tagOrId) - def find_all(self): - return self.find('all') - def find_below(self, tagOrId): - return self.find('below', tagOrId) - def find_closest(self, x, y, halo=None, start=None): - return self.find('closest', x, y, halo, start) - def find_enclosed(self, x1, y1, x2, y2): - return self.find('enclosed', x1, y1, x2, y2) - def find_overlapping(self, x1, y1, x2, y2): - return self.find('overlapping', x1, y1, x2, y2) - def find_withtag(self, tagOrId): - return self.find('withtag', tagOrId) - def focus(self, *args): - return self._do('focus', args) - def gettags(self, *args): - return self.tk.splitlist(self._do('gettags', args)) - def icursor(self, *args): - self._do('icursor', args) - def index(self, *args): - return self.tk.getint(self._do('index', args)) - def insert(self, *args): - self._do('insert', args) - def itemcget(self, tagOrId, option): - return self._do('itemcget', (tagOrId, '-'+option)) - def itemconfig(self, tagOrId, cnf=None, **kw): - if cnf is None and not kw: - cnf = {} - for x in self.tk.split( - self._do('itemconfigure', (tagOrId))): - cnf[x[0][1:]] = (x[0][1:],) + x[1:] - return cnf - if type(cnf) == StringType and not kw: - x = self.tk.split(self._do('itemconfigure', - (tagOrId, '-'+cnf,))) - return (x[0][1:],) + x[1:] - self._do('itemconfigure', (tagOrId,) - + self._options(cnf, kw)) - itemconfigure = itemconfig - def lower(self, *args): - self._do('lower', args) - def move(self, *args): - self._do('move', args) - def postscript(self, cnf={}, **kw): - return self._do('postscript', self._options(cnf, kw)) - def tkraise(self, *args): - self._do('raise', args) - lift = tkraise - def scale(self, *args): - self._do('scale', args) - def scan_mark(self, x, y): - self.tk.call(self._w, 'scan', 'mark', x, y) - def scan_dragto(self, x, y): - self.tk.call(self._w, 'scan', 'dragto', x, y) - def select_adjust(self, tagOrId, index): - self.tk.call(self._w, 'select', 'adjust', tagOrId, index) - def select_clear(self): - self.tk.call(self._w, 'select', 'clear') - def select_from(self, tagOrId, index): - self.tk.call(self._w, 'select', 'set', tagOrId, index) - def select_item(self): - self.tk.call(self._w, 'select', 'item') - def select_to(self, tagOrId, index): - self.tk.call(self._w, 'select', 'to', tagOrId, index) - def type(self, tagOrId): - return self.tk.call(self._w, 'type', tagOrId) or None - def xview(self, *args): - if not args: - return self._getdoubles(self.tk.call(self._w, 'xview')) - apply(self.tk.call, (self._w, 'xview')+args) - def yview(self, *args): - if not args: - return self._getdoubles(self.tk.call(self._w, 'yview')) - apply(self.tk.call, (self._w, 'yview')+args) - -class Checkbutton(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'checkbutton', cnf, kw) - def deselect(self): - self.tk.call(self._w, 'deselect') - def flash(self): - self.tk.call(self._w, 'flash') - def invoke(self): - self.tk.call(self._w, 'invoke') - def select(self): - self.tk.call(self._w, 'select') - def toggle(self): - self.tk.call(self._w, 'toggle') - -class Entry(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'entry', cnf, kw) - def delete(self, first, last=None): - self.tk.call(self._w, 'delete', first, last) - def get(self): - return self.tk.call(self._w, 'get') - def icursor(self, index): - self.tk.call(self._w, 'icursor', index) - def index(self, index): - return self.tk.getint(self.tk.call( - self._w, 'index', index)) - def insert(self, index, string): - self.tk.call(self._w, 'insert', index, string) - def scan_mark(self, x): - self.tk.call(self._w, 'scan', 'mark', x) - def scan_dragto(self, x): - self.tk.call(self._w, 'scan', 'dragto', x) - def selection_adjust(self, index): - self.tk.call(self._w, 'selection', 'adjust', index) - select_adjust = selection_adjust - def selection_clear(self): - self.tk.call(self._w, 'selection', 'clear') - select_clear = selection_clear - def selection_from(self, index): - self.tk.call(self._w, 'selection', 'set', index) - select_from = selection_from - def selection_present(self): - return self.tk.getboolean( - self.tk.call(self._w, 'selection', 'present')) - select_present = selection_present - def selection_range(self, start, end): - self.tk.call(self._w, 'selection', 'range', start, end) - select_range = selection_range - def selection_to(self, index): - self.tk.call(self._w, 'selection', 'to', index) - select_to = selection_to - def xview(self, index): - self.tk.call(self._w, 'xview', index) - def xview_moveto(self, fraction): - self.tk.call(self._w, 'xview', 'moveto', fraction) - def xview_scroll(self, number, what): - self.tk.call(self._w, 'xview', 'scroll', number, what) - -class Frame(Widget): - def __init__(self, master=None, cnf={}, **kw): - cnf = _cnfmerge((cnf, kw)) - extra = () - if cnf.has_key('class'): - extra = ('-class', cnf['class']) - del cnf['class'] - Widget.__init__(self, master, 'frame', cnf, {}, extra) - -class Label(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'label', cnf, kw) - -class Listbox(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'listbox', cnf, kw) - def activate(self, index): - self.tk.call(self._w, 'activate', index) - def bbox(self, *args): - return self._getints(self._do('bbox', args)) or None - def curselection(self): - # XXX Ought to apply self._getints()... - return self.tk.splitlist(self.tk.call( - self._w, 'curselection')) - def delete(self, first, last=None): - self.tk.call(self._w, 'delete', first, last) - def get(self, first, last=None): - if last: - return self.tk.splitlist(self.tk.call( - self._w, 'get', first, last)) - else: - return self.tk.call(self._w, 'get', first) - def insert(self, index, *elements): - apply(self.tk.call, - (self._w, 'insert', index) + elements) - def nearest(self, y): - return self.tk.getint(self.tk.call( - self._w, 'nearest', y)) - def scan_mark(self, x, y): - self.tk.call(self._w, 'scan', 'mark', x, y) - def scan_dragto(self, x, y): - self.tk.call(self._w, 'scan', 'dragto', x, y) - def see(self, index): - self.tk.call(self._w, 'see', index) - def index(self, index): - i = self.tk.call(self._w, 'index', index) - if i == 'none': return None - return self.tk.getint(i) - def select_adjust(self, index): - self.tk.call(self._w, 'select', 'adjust', index) - def select_anchor(self, index): - self.tk.call(self._w, 'selection', 'anchor', index) - def select_clear(self, first, last=None): - self.tk.call(self._w, - 'selection', 'clear', first, last) - def select_includes(self, index): - return self.tk.getboolean(self.tk.call( - self._w, 'selection', 'includes', index)) - def select_set(self, first, last=None): - self.tk.call(self._w, 'selection', 'set', first, last) - def size(self): - return self.tk.getint(self.tk.call(self._w, 'size')) - def xview(self, *what): - if not what: - return self._getdoubles(self.tk.call(self._w, 'xview')) - apply(self.tk.call, (self._w, 'xview')+what) - def yview(self, *what): - if not what: - return self._getdoubles(self.tk.call(self._w, 'yview')) - apply(self.tk.call, (self._w, 'yview')+what) - -class Menu(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'menu', cnf, kw) - def tk_bindForTraversal(self): - self.tk.call('tk_bindForTraversal', self._w) - def tk_mbPost(self): - self.tk.call('tk_mbPost', self._w) - def tk_mbUnpost(self): - self.tk.call('tk_mbUnpost') - def tk_traverseToMenu(self, char): - self.tk.call('tk_traverseToMenu', self._w, char) - def tk_traverseWithinMenu(self, char): - self.tk.call('tk_traverseWithinMenu', self._w, char) - def tk_getMenuButtons(self): - return self.tk.call('tk_getMenuButtons', self._w) - def tk_nextMenu(self, count): - self.tk.call('tk_nextMenu', count) - def tk_nextMenuEntry(self, count): - self.tk.call('tk_nextMenuEntry', count) - def tk_invokeMenu(self): - self.tk.call('tk_invokeMenu', self._w) - def tk_firstMenu(self): - self.tk.call('tk_firstMenu', self._w) - def tk_mbButtonDown(self): - self.tk.call('tk_mbButtonDown', self._w) - def tk_popup(self, x, y, entry=""): - self.tk.call('tk_popup', self._w, x, y, entry) - def activate(self, index): - self.tk.call(self._w, 'activate', index) - def add(self, itemType, cnf={}, **kw): - apply(self.tk.call, (self._w, 'add', itemType) - + self._options(cnf, kw)) - def add_cascade(self, cnf={}, **kw): - self.add('cascade', cnf or kw) - def add_checkbutton(self, cnf={}, **kw): - self.add('checkbutton', cnf or kw) - def add_command(self, cnf={}, **kw): - self.add('command', cnf or kw) - def add_radiobutton(self, cnf={}, **kw): - self.add('radiobutton', cnf or kw) - def add_separator(self, cnf={}, **kw): - self.add('separator', cnf or kw) - def delete(self, index1, index2=None): - self.tk.call(self._w, 'delete', index1, index2) - def entryconfig(self, index, cnf=None, **kw): - if cnf is None and not kw: - cnf = {} - for x in self.tk.split(apply(self.tk.call, - (self._w, 'entryconfigure', index))): - cnf[x[0][1:]] = (x[0][1:],) + x[1:] - return cnf - if type(cnf) == StringType and not kw: - x = self.tk.split(apply(self.tk.call, - (self._w, 'entryconfigure', index, '-'+cnf))) - return (x[0][1:],) + x[1:] - apply(self.tk.call, (self._w, 'entryconfigure', index) - + self._options(cnf, kw)) - entryconfigure = entryconfig - def index(self, index): - i = self.tk.call(self._w, 'index', index) - if i == 'none': return None - return self.tk.getint(i) - def invoke(self, index): - return self.tk.call(self._w, 'invoke', index) - def post(self, x, y): - self.tk.call(self._w, 'post', x, y) - def unpost(self): - self.tk.call(self._w, 'unpost') - def yposition(self, index): - return self.tk.getint(self.tk.call( - self._w, 'yposition', index)) - -class Menubutton(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'menubutton', cnf, kw) - -class Message(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'message', cnf, kw) - -class Radiobutton(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'radiobutton', cnf, kw) - def deselect(self): - self.tk.call(self._w, 'deselect') - def flash(self): - self.tk.call(self._w, 'flash') - def invoke(self): - self.tk.call(self._w, 'invoke') - def select(self): - self.tk.call(self._w, 'select') - -class Scale(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'scale', cnf, kw) - def get(self): - return self.tk.getint(self.tk.call(self._w, 'get')) - def set(self, value): - self.tk.call(self._w, 'set', value) - -class Scrollbar(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'scrollbar', cnf, kw) - def activate(self, index): - self.tk.call(self._w, 'activate', index) - def delta(self, deltax, deltay): - return self.getdouble(self.tk.call( - self._w, 'delta', deltax, deltay)) - def fraction(self, x, y): - return self.getdouble(self.tk.call( - self._w, 'fraction', x, y)) - def identify(self, x, y): - return self.tk.call(self._w, 'identify', x, y) - def get(self): - return self._getdoubles(self.tk.call(self._w, 'get')) - def set(self, *args): - apply(self.tk.call, (self._w, 'set')+args) - -class Text(Widget): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'text', cnf, kw) - self.bind('<Delete>', self.bspace) - def bbox(self, *args): - return self._getints(self._do('bbox', args)) or None - def bspace(self, *args): - self.delete('insert') - def tk_textSelectTo(self, index): - self.tk.call('tk_textSelectTo', self._w, index) - def tk_textBackspace(self): - self.tk.call('tk_textBackspace', self._w) - def tk_textIndexCloser(self, a, b, c): - self.tk.call('tk_textIndexCloser', self._w, a, b, c) - def tk_textResetAnchor(self, index): - self.tk.call('tk_textResetAnchor', self._w, index) - def compare(self, index1, op, index2): - return self.tk.getboolean(self.tk.call( - self._w, 'compare', index1, op, index2)) - def debug(self, boolean=None): - return self.tk.getboolean(self.tk.call( - self._w, 'debug', boolean)) - def delete(self, index1, index2=None): - self.tk.call(self._w, 'delete', index1, index2) - def dlineinfo(self, index): - return self._getints(self.tk.call(self._w, 'dlineinfo', index)) - def get(self, index1, index2=None): - return self.tk.call(self._w, 'get', index1, index2) - def index(self, index): - return self.tk.call(self._w, 'index', index) - def insert(self, index, chars, *args): - apply(self.tk.call, (self._w, 'insert', index, chars)+args) - def mark_gravity(self, markName, direction=None): - return apply(self.tk.call, - (self._w, 'mark', 'gravity', markName, direction)) - def mark_names(self): - return self.tk.splitlist(self.tk.call( - self._w, 'mark', 'names')) - def mark_set(self, markName, index): - self.tk.call(self._w, 'mark', 'set', markName, index) - def mark_unset(self, *markNames): - apply(self.tk.call, (self._w, 'mark', 'unset') + markNames) - def scan_mark(self, x, y): - self.tk.call(self._w, 'scan', 'mark', x, y) - def scan_dragto(self, x, y): - self.tk.call(self._w, 'scan', 'dragto', x, y) - def search(self, pattern, index, stopindex=None, - forwards=None, backwards=None, exact=None, - regexp=None, nocase=None, count=None): - args = [self._w, 'search'] - if forwards: args.append('-forwards') - if backwards: args.append('-backwards') - if exact: args.append('-exact') - if regexp: args.append('-regexp') - if nocase: args.append('-nocase') - if count: args.append('-count'); args.append(count) - if pattern[0] == '-': args.append('--') - args.append(pattern) - args.append(index) - if stopindex: args.append(stopindex) - return apply(self.tk.call, tuple(args)) - def see(self, index): - self.tk.call(self._w, 'see', index) - def tag_add(self, tagName, index1, index2=None): - self.tk.call( - self._w, 'tag', 'add', tagName, index1, index2) - def tag_unbind(self, tagName, sequence): - self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '') - def tag_bind(self, tagName, sequence, func, add=None): - return self._bind((self._w, 'tag', 'bind', tagName), - sequence, func, add) - def tag_cget(self, tagName, option): - return self.tk.call(self._w, 'tag', 'cget', tagName, option) - def tag_config(self, tagName, cnf={}, **kw): - if type(cnf) == StringType: - x = self.tk.split(self.tk.call( - self._w, 'tag', 'configure', tagName, '-'+cnf)) - return (x[0][1:],) + x[1:] - apply(self.tk.call, - (self._w, 'tag', 'configure', tagName) - + self._options(cnf, kw)) - tag_configure = tag_config - def tag_delete(self, *tagNames): - apply(self.tk.call, (self._w, 'tag', 'delete') + tagNames) - def tag_lower(self, tagName, belowThis=None): - self.tk.call(self._w, 'tag', 'lower', tagName, belowThis) - def tag_names(self, index=None): - return self.tk.splitlist( - self.tk.call(self._w, 'tag', 'names', index)) - def tag_nextrange(self, tagName, index1, index2=None): - return self.tk.splitlist(self.tk.call( - self._w, 'tag', 'nextrange', tagName, index1, index2)) - def tag_raise(self, tagName, aboveThis=None): - self.tk.call( - self._w, 'tag', 'raise', tagName, aboveThis) - def tag_ranges(self, tagName): - return self.tk.splitlist(self.tk.call( - self._w, 'tag', 'ranges', tagName)) - def tag_remove(self, tagName, index1, index2=None): - self.tk.call( - self._w, 'tag', 'remove', tagName, index1, index2) - def window_cget(self, index, option): - return self.tk.call(self._w, 'window', 'cget', index, option) - def window_config(self, index, cnf={}, **kw): - if type(cnf) == StringType: - x = self.tk.split(self.tk.call( - self._w, 'window', 'configure', - index, '-'+cnf)) - return (x[0][1:],) + x[1:] - apply(self.tk.call, - (self._w, 'window', 'configure', index) - + self._options(cnf, kw)) - window_configure = window_config - def window_create(self, index, cnf={}, **kw): - apply(self.tk.call, - (self._w, 'window', 'create', index) - + self._options(cnf, kw)) - def window_names(self): - return self.tk.splitlist( - self.tk.call(self._w, 'window', 'names')) - def xview(self, *what): - if not what: - return self._getdoubles(self.tk.call(self._w, 'xview')) - apply(self.tk.call, (self._w, 'xview')+what) - def yview(self, *what): - if not what: - return self._getdoubles(self.tk.call(self._w, 'yview')) - apply(self.tk.call, (self._w, 'yview')+what) - def yview_pickplace(self, *what): - apply(self.tk.call, (self._w, 'yview', '-pickplace')+what) - -class OptionMenu(Widget): - def __init__(self, master, variable, value, *values): - self.widgetName = 'tk_optionMenu' - Widget._setup(self, master, {}) - self.menuname = apply( - self.tk.call, - (self.widgetName, self._w, variable, value) + values) - -class Image: - def __init__(self, imgtype, name=None, cnf={}, **kw): - self.name = None - master = _default_root - if not master: raise RuntimeError, 'Too early to create image' - self.tk = master.tk - if not name: name = `id(self)` - if kw and cnf: cnf = _cnfmerge((cnf, kw)) - elif kw: cnf = kw - options = () - for k, v in cnf.items(): - if callable(v): - v = self._register(v) - options = options + ('-'+k, v) - apply(self.tk.call, - ('image', 'create', imgtype, name,) + options) - self.name = name - def __str__(self): return self.name - def __del__(self): - if self.name: - self.tk.call('image', 'delete', self.name) - def __setitem__(self, key, value): - self.tk.call(self.name, 'configure', '-'+key, value) - def __getitem__(self, key): - return self.tk.call(self.name, 'configure', '-'+key) - def height(self): - return self.tk.getint( - self.tk.call('image', 'height', self.name)) - def type(self): - return self.tk.call('image', 'type', self.name) - def width(self): - return self.tk.getint( - self.tk.call('image', 'width', self.name)) - -class PhotoImage(Image): - def __init__(self, name=None, cnf={}, **kw): - apply(Image.__init__, (self, 'photo', name, cnf), kw) - def blank(self): - self.tk.call(self.name, 'blank') - def cget(self, option): - return self.tk.call(self.name, 'cget', '-' + option) - # XXX config - def __getitem__(self, key): - return self.tk.call(self.name, 'cget', '-' + key) - def copy(self): - destImage = PhotoImage() - self.tk.call(destImage, 'copy', self.name) - return destImage - def zoom(self,x,y=''): - destImage = PhotoImage() - if y=='': y=x - self.tk.call(destImage, 'copy', self.name, '-zoom',x,y) - return destImage - def subsample(self,x,y=''): - destImage = PhotoImage() - if y=='': y=x - self.tk.call(destImage, 'copy', self.name, '-subsample',x,y) - return destImage - def get(self, x, y): - return self.tk.call(self.name, 'get', x, y) - def put(self, data, to=None): - args = (self.name, 'put', data) - if to: - args = args + to - apply(self.tk.call, args) - # XXX read - def write(self, filename, format=None, from_coords=None): - args = (self.name, 'write', filename) - if format: - args = args + ('-format', format) - if from_coords: - args = args + ('-from',) + tuple(from_coords) - apply(self.tk.call, args) - -class BitmapImage(Image): - def __init__(self, name=None, cnf={}, **kw): - apply(Image.__init__, (self, 'bitmap', name, cnf), kw) - -def image_names(): return _default_root.tk.call('image', 'names') -def image_types(): return _default_root.tk.call('image', 'types') - -###################################################################### -# Extensions: - -class Studbutton(Button): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'studbutton', cnf, kw) - self.bind('<Any-Enter>', self.tkButtonEnter) - self.bind('<Any-Leave>', self.tkButtonLeave) - self.bind('<1>', self.tkButtonDown) - self.bind('<ButtonRelease-1>', self.tkButtonUp) - -class Tributton(Button): - def __init__(self, master=None, cnf={}, **kw): - Widget.__init__(self, master, 'tributton', cnf, kw) - self.bind('<Any-Enter>', self.tkButtonEnter) - self.bind('<Any-Leave>', self.tkButtonLeave) - self.bind('<1>', self.tkButtonDown) - self.bind('<ButtonRelease-1>', self.tkButtonUp) - self['fg'] = self['bg'] - self['activebackground'] = self['bg'] - - -# Emacs cruft -# Local Variables: -# py-indent-offset: 8 -# End: diff --git a/Lib/toaiff.py b/Lib/toaiff.py deleted file mode 100644 index 0001be022f..0000000000 --- a/Lib/toaiff.py +++ /dev/null @@ -1,101 +0,0 @@ -# Convert "arbitrary" sound files to AIFF files (Apple and SGI's audio format). -# Input may be compressed. -# Uncompressed file type may be AIFF, WAV, VOC, 8SVX, NeXT/Sun, and others. -# An exception is raised if the file is not of a recognized type. -# Returned filename is either the input filename or a temporary filename; -# in the latter case the caller must ensure that it is removed. -# Other temporary files used are removed by the function. - -import os -import tempfile -import pipes -import whatsound - -table = {} - -t = pipes.Template() -t.append('sox -t au - -t aiff -r 8000 -', '--') -table['au'] = t - -# XXX The following is actually sub-optimal. -# XXX The HCOM sampling rate can be 22k, 22k/2, 22k/3 or 22k/4. -# XXX We must force the output sampling rate else the SGI won't play -# XXX files sampled at 5.5k or 7.333k; however this means that files -# XXX sampled at 11k are unnecessarily expanded. -# XXX Similar comments apply to some other file types. -t = pipes.Template() -t.append('sox -t hcom - -t aiff -r 22050 -', '--') -table['hcom'] = t - -t = pipes.Template() -t.append('sox -t voc - -t aiff -r 11025 -', '--') -table['voc'] = t - -t = pipes.Template() -t.append('sox -t wav - -t aiff -', '--') -table['wav'] = t - -t = pipes.Template() -t.append('sox -t 8svx - -t aiff -r 16000 -', '--') -table['8svx'] = t - -t = pipes.Template() -t.append('sox -t sndt - -t aiff -r 16000 -', '--') -table['sndt'] = t - -t = pipes.Template() -t.append('sox -t sndr - -t aiff -r 16000 -', '--') -table['sndr'] = t - -uncompress = pipes.Template() -uncompress.append('uncompress', '--') - - -error = 'toaiff.error' # Exception - -def toaiff(filename): - temps = [] - ret = None - try: - ret = _toaiff(filename, temps) - finally: - for temp in temps[:]: - if temp <> ret: - try: - os.unlink(temp) - except os.error: - pass - temps.remove(temp) - return ret - -def _toaiff(filename, temps): - if filename[-2:] == '.Z': - fname = tempfile.mktemp() - temps.append(fname) - sts = uncompress.copy(filename, fname) - if sts: - raise error, filename + ': uncomress failed' - else: - fname = filename - try: - ftype = whatsound.whathdr(fname) - if ftype: - ftype = ftype[0] # All we're interested in - except IOError: - if type(msg) == type(()) and len(msg) == 2 and \ - type(msg[0]) == type(0) and type(msg[1]) == type(''): - msg = msg[1] - if type(msg) <> type(''): - msg = `msg` - raise error, filename + ': ' + msg - if ftype == 'aiff': - return fname - if ftype == None or not table.has_key(ftype): - raise error, \ - filename + ': unsupported audio file type ' + `ftype` - temp = tempfile.mktemp() - temps.append(temp) - sts = table[ftype].copy(fname, temp) - if sts: - raise error, filename + ': conversion to aiff failed' - return temp diff --git a/Lib/token.py b/Lib/token.py deleted file mode 100755 index 75ac39a981..0000000000 --- a/Lib/token.py +++ /dev/null @@ -1,50 +0,0 @@ -# Tokens (from "token.h") - -ENDMARKER = 0 -NAME = 1 -NUMBER = 2 -STRING = 3 -NEWLINE = 4 -INDENT = 5 -DEDENT = 6 -LPAR = 7 -RPAR = 8 -LSQB = 9 -RSQB = 10 -COLON = 11 -COMMA = 12 -SEMI = 13 -PLUS = 14 -MINUS = 15 -STAR = 16 -SLASH = 17 -VBAR = 18 -AMPER = 19 -LESS = 20 -GREATER = 21 -EQUAL = 22 -DOT = 23 -PERCENT = 24 -BACKQUOTE = 25 -LBRACE = 26 -RBRACE = 27 -EQEQUAL = 28 -NOTEQUAL = 29 -LESSEQUAL = 30 -GREATEREQUAL = 31 -TILDE = 32 -CIRCUMFLEX = 33 -LEFTSHIFT = 34 -RIGHTSHIFT = 35 -OP = 36 -ERRORTOKEN = 37 - -names = dir() -tok_name = {} -for name in names: - number = eval(name) - tok_name[number] = name - -N_TOKENS = 38 # Number of tokens including ERRORTOKEN - -NT_OFFSET = 256 # Start of non-terminal symbols diff --git a/Lib/tokenize.py b/Lib/tokenize.py deleted file mode 100644 index 8f16115410..0000000000 --- a/Lib/tokenize.py +++ /dev/null @@ -1,63 +0,0 @@ -# This module compiles a regular expression that recognizes Python tokens. -# It is designed to match the working of the Python tokenizer exactly. -# It takes care of everything except indentation; -# note that un-escaped newlines are tokens, too. -# tokenprog.regs[3] gives the location of the token without whitespace -# It also defines various subexpressions, but doesn't compile them. -# See the function test() below for an example of how to use. - -import regex - -# Note: to get a quoted backslash in a regexp, it must be quadrupled. - -Ignore = '[ \t]*\(\\\\\n[ \t]*\)*\(#.*\)?' - -Name = '[a-zA-Z_][a-zA-Z0-9_]*' - -Hexnumber = '0[xX][0-9a-fA-F]*[lL]?' -Octnumber = '0[0-7]*[lL]?' -Decnumber = '[1-9][0-9]*[lL]?' -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 - -String = '\'\(\\\\.\|[^\\\n\']\)*\'' + '\|' + '"\(\\\\.\|[^\\\n"]\)*"' -# Note: this module *recognizes* double quotes, but for backward -# compatibility, it doesn't *use* them! - -Operator = '~\|\+\|-\|\*\|/\|%\|\^\|&\||\|<<\|>>\|==\|<=\|<>\|!=\|>=\|=\|<\|>' -Bracket = '[][(){}]' -Special = '[:;.,`\n]' -Funny = Operator + '\|' + Bracket + '\|' + Special - -PlainToken = Name + '\|' + Number + '\|' + String + '\|' + Funny - -Token = Ignore + '\(' + PlainToken + '\)' - -try: - save_syntax = regex.set_syntax(0) # Use default syntax - tokenprog = regex.compile(Token) -finally: - if save_syntax != 0: - dummy = regex.set_syntax(save_syntax) # Restore original syntax - - -def test(file): - f = open(file, 'r') - while 1: - line = f.readline() - if not line: break - i, n = 0, len(line) - while i < n: - j = tokenprog.match(line, i) - if j < 0: - print 'No token at', `line[i:i+20]` + '...' - i = i+1 - else: - i = i+j - a, b = tokenprog.regs[3] - if a < b: - print 'Token:', `line[a:b]` diff --git a/Lib/traceback.py b/Lib/traceback.py deleted file mode 100644 index 8d2dfdc379..0000000000 --- a/Lib/traceback.py +++ /dev/null @@ -1,125 +0,0 @@ -# Format and print Python stack traces - -import linecache -import string -import sys -import types - -def _print(file, str='', terminator='\n'): - file.write(str+terminator) - - -def print_tb(tb, limit=None, file=None): - if not file: - file = sys.stderr - if limit is None: - if hasattr(sys, 'tracebacklimit'): - limit = sys.tracebacklimit - n = 0 - while tb is not None and (limit is None or n < limit): - f = tb.tb_frame - lineno = tb.tb_lineno - co = f.f_code - filename = co.co_filename - name = co.co_name - _print(file, - ' File "%s", line %d, in %s' % (filename,lineno,name)) - line = linecache.getline(filename, lineno) - if line: _print(file, ' ' + string.strip(line)) - tb = tb.tb_next - n = n+1 - -def format_tb(tb, limit = None): - list = [] - for filename, lineno, name, line in extract_tb(tb, limit): - item = ' File "%s", line %d, in %s\n' % (filename,lineno,name) - if line: - item = item + ' %s\n' % string.strip(line) - list.append(item) - return list - -def extract_tb(tb, limit = None): - if limit is None: - if hasattr(sys, 'tracebacklimit'): - limit = sys.tracebacklimit - list = [] - n = 0 - while tb is not None and (limit is None or n < limit): - f = tb.tb_frame - lineno = tb.tb_lineno - co = f.f_code - filename = co.co_filename - name = co.co_name - line = linecache.getline(filename, lineno) - if line: line = string.strip(line) - else: line = None - list.append(filename, lineno, name, line) - tb = tb.tb_next - n = n+1 - return list - - -def print_exception(etype, value, tb, limit=None, file=None): - if not file: - file = sys.stderr - if tb: - _print(file, 'Traceback (innermost last):') - print_tb(tb, limit, file) - lines = format_exception_only(etype, value) - for line in lines[:-1]: - _print(file, line, ' ') - _print(file, lines[-1], '') - -def format_exception(etype, value, tb, limit = None): - if tb: - list = ['Traceback (innermost last):\n'] - list = list + format_tb(tb, limit) - list = list + format_exception_only(etype, value) - return list - -def format_exception_only(etype, value): - list = [] - if type(etype) == types.ClassType: - stype = etype.__name__ - else: - stype = etype - if value is None: - list.append(str(stype) + '\n') - else: - if etype is SyntaxError: - try: - msg, (filename, lineno, offset, line) = value - except: - pass - else: - if not filename: filename = "<string>" - list.append(' File "%s", line %d\n' % - (filename, lineno)) - i = 0 - while i < len(line) and \ - line[i] in string.whitespace: - i = i+1 - list.append(' %s\n' % string.strip(line)) - s = ' ' - for c in line[i:offset-1]: - if c in string.whitespace: - s = s + c - else: - s = s + ' ' - list.append('%s^\n' % s) - value = msg - list.append('%s: %s\n' % (str(stype), str(value))) - return list - - -def print_exc(limit=None, file=None): - if not file: - file = sys.stderr - print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, - limit, file) - -def print_last(limit=None, file=None): - if not file: - file = sys.stderr - print_exception(sys.last_type, sys.last_value, sys.last_traceback, - limit, file) diff --git a/Lib/tty.py b/Lib/tty.py deleted file mode 100644 index 86530cf46d..0000000000 --- a/Lib/tty.py +++ /dev/null @@ -1,35 +0,0 @@ -# tty.py -- Terminal utilities. -# Author: Steen Lumholt. - -from TERMIOS import * -from termios import * - -# Indexes for termios list. -IFLAG = 0 -OFLAG = 1 -CFLAG = 2 -LFLAG = 3 -ISPEED = 4 -OSPEED = 5 -CC = 6 - -# Put terminal into a raw mode. -def setraw(fd, when=TCSAFLUSH): - mode = tcgetattr(fd) - mode[IFLAG] = mode[IFLAG] & ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON) - mode[OFLAG] = mode[OFLAG] & ~(OPOST) - mode[CFLAG] = mode[CFLAG] & ~(CSIZE | PARENB) - mode[CFLAG] = mode[CFLAG] | CS8 - mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON | IEXTEN | ISIG) - mode[CC][VMIN] = 1 - mode[CC][VTIME] = 0 - tcsetattr(fd, when, mode) - -# Put terminal into a cbreak mode. -def setcbreak(fd, when=TCSAFLUSH): - mode = tcgetattr(fd) - mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON) - mode[CC][VMIN] = 1 - mode[CC][VTIME] = 0 - tcsetattr(fd, when, mode) - diff --git a/Lib/types.py b/Lib/types.py deleted file mode 100644 index b6841735ce..0000000000 --- a/Lib/types.py +++ /dev/null @@ -1,50 +0,0 @@ -# Define names for all type symbols known in the standard interpreter. -# Types that are part of optional modules (e.g. array) are not listed. - -import sys - -NoneType = type(None) -TypeType = type(NoneType) - -IntType = type(0) -LongType = type(0L) -FloatType = type(0.0) -try: - ComplexType = type(complex(0,1)) -except NameError: - pass - -StringType = type('') - -TupleType = type(()) -ListType = type([]) -DictType = DictionaryType = type({}) - -def _f(): pass -FunctionType = type(_f) -LambdaType = type(lambda: None) # Same as FunctionType -CodeType = type(_f.func_code) - -class _C: - def _m(self): pass -ClassType = type(_C) -UnboundMethodType = type(_C._m) # Same as MethodType -_x = _C() -InstanceType = type(_x) -MethodType = type(_x._m) - -BuiltinFunctionType = type(len) -BuiltinMethodType = type([].append) # Same as BuiltinFunctionType - -ModuleType = type(sys) - -FileType = type(sys.stdin) # XXX what if it was assigned to? -XRangeType = type(xrange(0)) - -try: - raise TypeError -except TypeError: - TracebackType = type(sys.exc_traceback) - FrameType = type(sys.exc_traceback.tb_frame) - -del sys, _f, _C, _x # Not for export diff --git a/Lib/tzparse.py b/Lib/tzparse.py deleted file mode 100644 index ef325e9ff0..0000000000 --- a/Lib/tzparse.py +++ /dev/null @@ -1,80 +0,0 @@ -# Parse a timezone specification. -# XXX Unfinished. -# XXX Only the typical form "XXXhhYYY;ddd/hh,ddd/hh" is currently supported. - -tzpat = '^\([A-Z][A-Z][A-Z]\)\([-+]?[0-9]+\)\([A-Z][A-Z][A-Z]\);' + \ - '\([0-9]+\)/\([0-9]+\),\([0-9]+\)/\([0-9]+\)$' - -tzprog = None - -def tzparse(tzstr): - global tzprog - if tzprog == None: - import regex - tzprog = regex.compile(tzpat) - if tzprog.match(tzstr) < 0: - raise ValueError, 'not the TZ syntax I understand' - regs = tzprog.regs - subs = [] - for i in range(1, 8): - a, b = regs[i] - subs.append(tzstr[a:b]) - for i in (1, 3, 4, 5, 6): - subs[i] = eval(subs[i]) - [tzname, delta, dstname, daystart, hourstart, dayend, hourend] = subs - return (tzname, delta, dstname, daystart, hourstart, dayend, hourend) - -def tzlocaltime(secs, params): - import time - (tzname, delta, dstname, daystart, hourstart, dayend, hourend) = params - year, month, days, hours, mins, secs, yday, wday, isdst = \ - time.gmtime(secs - delta*3600) - if (daystart, hourstart) <= (yday+1, hours) < (dayend, hourend): - tzname = dstname - hours = hours + 1 - return year, month, days, hours, mins, secs, yday, wday, tzname - -def tzset(): - global tzparams, timezone, altzone, daylight, tzname - import os - tzstr = os.environ['TZ'] - tzparams = tzparse(tzstr) - timezone = tzparams[1] * 3600 - altzone = timezone - 3600 - daylight = 1 - tzname = tzparams[0], tzparams[2] - -def isdst(secs): - import time - (tzname, delta, dstname, daystart, hourstart, dayend, hourend) = \ - tzparams - year, month, days, hours, mins, secs, yday, wday, isdst = \ - time.gmtime(secs - delta*3600) - return (daystart, hourstart) <= (yday+1, hours) < (dayend, hourend) - -tzset() - -def localtime(secs): - return tzlocaltime(secs, tzparams) - -def test(): - from time import asctime, gmtime - import time, sys - now = time.time() - x = localtime(now) - tm = x[:-1] + (0,) - print 'now =', now, '=', asctime(tm), x[-1] - now = now - now % (24*3600) - if sys.argv[1:]: now = now + eval(sys.argv[1]) - x = gmtime(now) - tm = x[:-1] + (0,) - print 'gmtime =', now, '=', asctime(tm), 'yday =', x[-2] - jan1 = now - x[-2]*24*3600 - x = localtime(jan1) - tm = x[:-1] + (0,) - print 'jan1 =', jan1, '=', asctime(tm), x[-1] - for d in range(85, 95) + range(265, 275): - t = jan1 + d*24*3600 - x = localtime(t) - tm = x[:-1] + (0,) - print 'd =', d, 't =', t, '=', asctime(tm), x[-1] diff --git a/Lib/urllib.py b/Lib/urllib.py deleted file mode 100644 index 82a39f2fad..0000000000 --- a/Lib/urllib.py +++ /dev/null @@ -1,715 +0,0 @@ -# Open an arbitrary URL -# -# See the following document for a tentative description of URLs: -# Uniform Resource Locators Tim Berners-Lee -# INTERNET DRAFT CERN -# IETF URL Working Group 14 July 1993 -# draft-ietf-uri-url-01.txt -# -# The object returned by URLopener().open(file) will differ per -# protocol. All you know is that is has methods read(), readline(), -# readlines(), fileno(), close() and info(). The read*(), fileno() -# and close() methods work like those of open files. -# The info() method returns an mimetools.Message object which can be -# used to query various info about the object, if available. -# (mimetools.Message objects are queried with the getheader() method.) - -import string -import socket -import regex -import os - - -__version__ = '1.3' - -# Helper for non-unix systems -if os.name == 'mac': - from macurl2path import url2pathname, pathname2url -else: - def url2pathname(pathname): - return pathname - def pathname2url(pathname): - return pathname - -# This really consists of two pieces: -# (1) a class which handles opening of all sorts of URLs -# (plus assorted utilities etc.) -# (2) a set of functions for parsing URLs -# XXX Should these be separated out into different modules? - - -# Shortcut for basic usage -_urlopener = None -def urlopen(url): - global _urlopener - if not _urlopener: - _urlopener = FancyURLopener() - return _urlopener.open(url) -def urlretrieve(url): - global _urlopener - if not _urlopener: - _urlopener = FancyURLopener() - return _urlopener.retrieve(url) -def urlcleanup(): - if _urlopener: - _urlopener.cleanup() - - -# Class to open URLs. -# This is a class rather than just a subroutine because we may need -# more than one set of global protocol-specific options. -# Note -- this is a base class for those who don't want the -# automatic handling of errors type 302 (relocated) and 401 -# (authorization needed). -ftpcache = {} -class URLopener: - - # Constructor - def __init__(self, proxies=None): - if proxies is None: - proxies = getproxies() - self.proxies = proxies - server_version = "Python-urllib/%s" % __version__ - self.addheaders = [('User-agent', server_version)] - self.tempcache = None - # Undocumented feature: if you assign {} to tempcache, - # it is used to cache files retrieved with - # self.retrieve(). This is not enabled by default - # since it does not work for changing documents (and I - # haven't got the logic to check expiration headers - # yet). - self.ftpcache = ftpcache - # Undocumented feature: you can use a different - # ftp cache by assigning to the .ftpcache member; - # in case you want logically independent URL openers - - def __del__(self): - self.close() - - def close(self): - self.cleanup() - - def cleanup(self): - import os - if self.tempcache: - for url in self.tempcache.keys(): - try: - os.unlink(self.tempcache[url][0]) - except os.error: - pass - del self.tempcache[url] - - # Add a header to be used by the HTTP interface only - # e.g. u.addheader('Accept', 'sound/basic') - def addheader(self, *args): - self.addheaders.append(args) - - # External interface - # Use URLopener().open(file) instead of open(file, 'r') - def open(self, fullurl): - fullurl = unwrap(fullurl) - type, url = splittype(fullurl) - if not type: type = 'file' - if self.proxies.has_key(type): - proxy = self.proxies[type] - type, proxy = splittype(proxy) - host, selector = splithost(proxy) - url = (host, fullurl) # Signal special case to open_*() - name = 'open_' + type - if '-' in name: - import regsub - name = regsub.gsub('-', '_', name) - if not hasattr(self, name): - return self.open_unknown(fullurl) - try: - return getattr(self, name)(url) - except socket.error, msg: - raise IOError, ('socket error', msg) - - # Overridable interface to open unknown URL type - def open_unknown(self, fullurl): - type, url = splittype(fullurl) - raise IOError, ('url error', 'unknown url type', type) - - # External interface - # retrieve(url) returns (filename, None) for a local object - # or (tempfilename, headers) for a remote object - def retrieve(self, url): - if self.tempcache and self.tempcache.has_key(url): - return self.tempcache[url] - url1 = unwrap(url) - if self.tempcache and self.tempcache.has_key(url1): - self.tempcache[url] = self.tempcache[url1] - return self.tempcache[url1] - type, url1 = splittype(url1) - if not type or type == 'file': - try: - fp = self.open_local_file(url1) - del fp - return url2pathname(splithost(url1)[1]), None - except IOError, msg: - pass - fp = self.open(url) - headers = fp.info() - import tempfile - tfn = tempfile.mktemp() - result = tfn, headers - if self.tempcache is not None: - self.tempcache[url] = result - tfp = open(tfn, 'w') - bs = 1024*8 - block = fp.read(bs) - while block: - tfp.write(block) - block = fp.read(bs) - del fp - del tfp - return result - - # Each method named open_<type> knows how to open that type of URL - - # Use HTTP protocol - def open_http(self, url): - import httplib - if type(url) is type(""): - host, selector = splithost(url) - else: - host, selector = url - print "proxy via http:", host, selector - if not host: raise IOError, ('http error', 'no host given') - i = string.find(host, '@') - if i >= 0: - user_passwd, host = host[:i], host[i+1:] - else: - user_passwd = None - if user_passwd: - import base64 - auth = string.strip(base64.encodestring(user_passwd)) - else: - auth = None - h = httplib.HTTP(host) - h.putrequest('GET', selector) - if auth: h.putheader('Authorization: Basic %s' % auth) - for args in self.addheaders: apply(h.putheader, args) - h.endheaders() - errcode, errmsg, headers = h.getreply() - fp = h.getfile() - if errcode == 200: - return addinfo(fp, headers) - else: - return self.http_error(url, - fp, errcode, errmsg, headers) - - # Handle http errors. - # Derived class can override this, or provide specific handlers - # named http_error_DDD where DDD is the 3-digit error code - def http_error(self, url, fp, errcode, errmsg, headers): - # First check if there's a specific handler for this error - name = 'http_error_%d' % errcode - if hasattr(self, name): - method = getattr(self, name) - result = method(url, fp, errcode, errmsg, headers) - if result: return result - return self.http_error_default( - url, fp, errcode, errmsg, headers) - - # Default http error handler: close the connection and raises IOError - def http_error_default(self, url, fp, errcode, errmsg, headers): - void = fp.read() - fp.close() - raise IOError, ('http error', errcode, errmsg, headers) - - # Use Gopher protocol - def open_gopher(self, url): - import gopherlib - host, selector = splithost(url) - if not host: raise IOError, ('gopher error', 'no host given') - type, selector = splitgophertype(selector) - selector, query = splitquery(selector) - selector = unquote(selector) - if query: - query = unquote(query) - fp = gopherlib.send_query(selector, query, host) - else: - fp = gopherlib.send_selector(selector, host) - return addinfo(fp, noheaders()) - - # Use local file or FTP depending on form of URL - def open_file(self, url): - if url[:2] == '//': - return self.open_ftp(url) - else: - return self.open_local_file(url) - - # Use local file - def open_local_file(self, url): - host, file = splithost(url) - if not host: return addinfo(open(url2pathname(file), 'r'), noheaders()) - host, port = splitport(host) - if not port and socket.gethostbyname(host) in ( - localhost(), thishost()): - file = unquote(file) - return addinfo(open(url2pathname(file), 'r'), noheaders()) - raise IOError, ('local file error', 'not on local host') - - # Use FTP protocol - def open_ftp(self, url): - host, path = splithost(url) - if not host: raise IOError, ('ftp error', 'no host given') - host, port = splitport(host) - user, host = splituser(host) - if user: user, passwd = splitpasswd(user) - else: passwd = None - host = socket.gethostbyname(host) - if not port: - import ftplib - port = ftplib.FTP_PORT - path, attrs = splitattr(path) - dirs = string.splitfields(path, '/') - dirs, file = dirs[:-1], dirs[-1] - if dirs and not dirs[0]: dirs = dirs[1:] - key = (user, host, port, string.joinfields(dirs, '/')) - try: - if not self.ftpcache.has_key(key): - self.ftpcache[key] = \ - ftpwrapper(user, passwd, - host, port, dirs) - if not file: type = 'D' - else: type = 'I' - for attr in attrs: - attr, value = splitvalue(attr) - if string.lower(attr) == 'type' and \ - value in ('a', 'A', 'i', 'I', 'd', 'D'): - type = string.upper(value) - return addinfo(self.ftpcache[key].retrfile(file, type), - noheaders()) - except ftperrors(), msg: - raise IOError, ('ftp error', msg) - - -# Derived class with handlers for errors we can handle (perhaps) -class FancyURLopener(URLopener): - - def __init__(self, *args): - apply(URLopener.__init__, (self,) + args) - self.auth_cache = {} - - # Default error handling -- don't raise an exception - def http_error_default(self, url, fp, errcode, errmsg, headers): - return addinfo(fp, headers) - - # Error 302 -- relocated - def http_error_302(self, url, fp, errcode, errmsg, headers): - # XXX The server can force infinite recursion here! - if headers.has_key('location'): - newurl = headers['location'] - elif headers.has_key('uri'): - newurl = headers['uri'] - else: - return - void = fp.read() - fp.close() - return self.open(newurl) - - # Error 401 -- authentication required - # See this URL for a description of the basic authentication scheme: - # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt - def http_error_401(self, url, fp, errcode, errmsg, headers): - if headers.has_key('www-authenticate'): - stuff = headers['www-authenticate'] - p = regex.compile( - '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"') - if p.match(stuff) >= 0: - scheme, realm = p.group(1, 2) - if string.lower(scheme) == 'basic': - return self.retry_http_basic_auth( - url, realm) - - def retry_http_basic_auth(self, url, realm): - host, selector = splithost(url) - i = string.find(host, '@') + 1 - host = host[i:] - user, passwd = self.get_user_passwd(host, realm, i) - if not (user or passwd): return None - host = user + ':' + passwd + '@' + host - newurl = '//' + host + selector - return self.open_http(newurl) - - def get_user_passwd(self, host, realm, clear_cache = 0): - key = realm + '@' + string.lower(host) - if self.auth_cache.has_key(key): - if clear_cache: - del self.auth_cache[key] - else: - return self.auth_cache[key] - user, passwd = self.prompt_user_passwd(host, realm) - if user or passwd: self.auth_cache[key] = (user, passwd) - return user, passwd - - def prompt_user_passwd(self, host, realm): - # Override this in a GUI environment! - try: - user = raw_input("Enter username for %s at %s: " % - (realm, host)) - self.echo_off() - try: - passwd = raw_input( - "Enter password for %s in %s at %s: " % - (user, realm, host)) - finally: - self.echo_on() - return user, passwd - except KeyboardInterrupt: - return None, None - - def echo_off(self): - import os - os.system("stty -echo") - - def echo_on(self): - import os - print - os.system("stty echo") - - -# Utility functions - -# Return the IP address of the magic hostname 'localhost' -_localhost = None -def localhost(): - global _localhost - if not _localhost: - _localhost = socket.gethostbyname('localhost') - return _localhost - -# Return the IP address of the current host -_thishost = None -def thishost(): - global _thishost - if not _thishost: - _thishost = socket.gethostbyname(socket.gethostname()) - return _thishost - -# Return the set of errors raised by the FTP class -_ftperrors = None -def ftperrors(): - global _ftperrors - if not _ftperrors: - import ftplib - _ftperrors = (ftplib.error_reply, - ftplib.error_temp, - ftplib.error_perm, - ftplib.error_proto) - return _ftperrors - -# Return an empty mimetools.Message object -_noheaders = None -def noheaders(): - global _noheaders - if not _noheaders: - import mimetools - import StringIO - _noheaders = mimetools.Message(StringIO.StringIO(), 0) - _noheaders.fp.close() # Recycle file descriptor - return _noheaders - - -# Utility classes - -# Class used by open_ftp() for cache of open FTP connections -class ftpwrapper: - def __init__(self, user, passwd, host, port, dirs): - self.user = unquote(user or '') - self.passwd = unquote(passwd or '') - self.host = host - self.port = port - self.dirs = [] - for dir in dirs: - self.dirs.append(unquote(dir)) - self.init() - def init(self): - import ftplib - self.ftp = ftplib.FTP() - self.ftp.connect(self.host, self.port) - self.ftp.login(self.user, self.passwd) - for dir in self.dirs: - self.ftp.cwd(dir) - def retrfile(self, file, type): - import ftplib - if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1 - else: cmd = 'TYPE ' + type; isdir = 0 - try: - self.ftp.voidcmd(cmd) - except ftplib.all_errors: - self.init() - self.ftp.voidcmd(cmd) - conn = None - if file and not isdir: - try: - cmd = 'RETR ' + file - conn = self.ftp.transfercmd(cmd) - except ftplib.error_perm, reason: - if reason[:3] != '550': - raise IOError, ('ftp error', reason) - if not conn: - # Try a directory listing - if file: cmd = 'LIST ' + file - else: cmd = 'LIST' - conn = self.ftp.transfercmd(cmd) - return addclosehook(conn.makefile('rb'), self.ftp.voidresp) - -# Base class for addinfo and addclosehook -class addbase: - def __init__(self, fp): - self.fp = fp - self.read = self.fp.read - self.readline = self.fp.readline - self.readlines = self.fp.readlines - self.fileno = self.fp.fileno - def __repr__(self): - return '<%s at %s whose fp = %s>' % ( - self.__class__.__name__, `id(self)`, `self.fp`) - def close(self): - self.read = None - self.readline = None - self.readlines = None - self.fileno = None - if self.fp: self.fp.close() - self.fp = None - -# Class to add a close hook to an open file -class addclosehook(addbase): - def __init__(self, fp, closehook, *hookargs): - addbase.__init__(self, fp) - self.closehook = closehook - self.hookargs = hookargs - def close(self): - if self.closehook: - apply(self.closehook, self.hookargs) - self.closehook = None - self.hookargs = None - addbase.close(self) - -# class to add an info() method to an open file -class addinfo(addbase): - def __init__(self, fp, headers): - addbase.__init__(self, fp) - self.headers = headers - def info(self): - return self.headers - - -# Utility to combine a URL with a base URL to form a new URL - -def basejoin(base, url): - type, path = splittype(url) - if type: - # if url is complete (i.e., it contains a type), return it - return url - host, path = splithost(path) - type, basepath = splittype(base) # inherit type from base - if host: - # if url contains host, just inherit type - if type: return type + '://' + host + path - else: - # no type inherited, so url must have started with // - # just return it - return url - host, basepath = splithost(basepath) # inherit host - basepath, basetag = splittag(basepath) # remove extraneuous cruft - basepath, basequery = splitquery(basepath) # idem - if path[:1] != '/': - # non-absolute path name - if path[:1] in ('#', '?'): - # path is just a tag or query, attach to basepath - i = len(basepath) - else: - # else replace last component - i = string.rfind(basepath, '/') - if i < 0: - # basepath not absolute - if host: - # host present, make absolute - basepath = '/' - else: - # else keep non-absolute - basepath = '' - else: - # remove last file component - basepath = basepath[:i+1] - path = basepath + path - if type and host: return type + '://' + host + path - elif type: return type + ':' + path - elif host: return '//' + host + path # don't know what this means - else: return path - - -# Utilities to parse URLs (most of these return None for missing parts): -# unwrap('<URL:type://host/path>') --> 'type://host/path' -# splittype('type:opaquestring') --> 'type', 'opaquestring' -# splithost('//host[:port]/path') --> 'host[:port]', '/path' -# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]' -# splitpasswd('user:passwd') -> 'user', 'passwd' -# splitport('host:port') --> 'host', 'port' -# splitquery('/path?query') --> '/path', 'query' -# splittag('/path#tag') --> '/path', 'tag' -# splitattr('/path;attr1=value1;attr2=value2;...') -> -# '/path', ['attr1=value1', 'attr2=value2', ...] -# splitvalue('attr=value') --> 'attr', 'value' -# splitgophertype('/Xselector') --> 'X', 'selector' -# unquote('abc%20def') -> 'abc def' -# quote('abc def') -> 'abc%20def') - -def unwrap(url): - url = string.strip(url) - if url[:1] == '<' and url[-1:] == '>': - url = string.strip(url[1:-1]) - if url[:4] == 'URL:': url = string.strip(url[4:]) - return url - -_typeprog = regex.compile('^\([^/:]+\):\(.*\)$') -def splittype(url): - if _typeprog.match(url) >= 0: return _typeprog.group(1, 2) - return None, url - -_hostprog = regex.compile('^//\([^/]+\)\(.*\)$') -def splithost(url): - if _hostprog.match(url) >= 0: return _hostprog.group(1, 2) - return None, url - -_userprog = regex.compile('^\([^@]*\)@\(.*\)$') -def splituser(host): - if _userprog.match(host) >= 0: return _userprog.group(1, 2) - return None, host - -_passwdprog = regex.compile('^\([^:]*\):\(.*\)$') -def splitpasswd(user): - if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2) - return user, None - -_portprog = regex.compile('^\(.*\):\([0-9]+\)$') -def splitport(host): - if _portprog.match(host) >= 0: return _portprog.group(1, 2) - return host, None - -_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$') -def splitquery(url): - if _queryprog.match(url) >= 0: return _queryprog.group(1, 2) - return url, None - -_tagprog = regex.compile('^\(.*\)#\([^#]*\)$') -def splittag(url): - if _tagprog.match(url) >= 0: return _tagprog.group(1, 2) - return url, None - -def splitattr(url): - words = string.splitfields(url, ';') - return words[0], words[1:] - -_valueprog = regex.compile('^\([^=]*\)=\(.*\)$') -def splitvalue(attr): - if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2) - return attr, None - -def splitgophertype(selector): - if selector[:1] == '/' and selector[1:2]: - return selector[1], selector[2:] - return None, selector - -_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]') -def unquote(s): - i = 0 - n = len(s) - res = '' - while 0 <= i < n: - j = _quoteprog.search(s, i) - if j < 0: - res = res + s[i:] - break - res = res + (s[i:j] + chr(string.atoi(s[j+1:j+3], 16))) - i = j+3 - return res - -always_safe = string.letters + string.digits + '_,.-' -def quote(s, safe = '/'): - safe = always_safe + safe - res = '' - for c in s: - if c in safe: - res = res + c - else: - res = res + '%%%02x' % ord(c) - return res - - -# Proxy handling -def getproxies(): - """Return a dictionary of protocol scheme -> proxy server URL mappings. - - Scan the environment for variables named <scheme>_proxy; - this seems to be the standard convention. If you need a - different way, you can pass a proxies dictionary to the - [Fancy]URLopener constructor. - - """ - proxies = {} - for name, value in os.environ.items(): - if value and name[-6:] == '_proxy': - proxies[name[:-6]] = value - return proxies - - -# Test and time quote() and unquote() -def test1(): - import time - s = '' - for i in range(256): s = s + chr(i) - s = s*4 - t0 = time.time() - qs = quote(s) - uqs = unquote(qs) - t1 = time.time() - if uqs != s: - print 'Wrong!' - print `s` - print `qs` - print `uqs` - print round(t1 - t0, 3), 'sec' - - -# Test program -def test(): - import sys - import regsub - args = sys.argv[1:] - if not args: - args = [ - '/etc/passwd', - 'file:/etc/passwd', - 'file://localhost/etc/passwd', - 'ftp://ftp.cwi.nl/etc/passwd', - 'gopher://gopher.cwi.nl/11/', - 'http://www.cwi.nl/index.html', - ] - try: - for url in args: - print '-'*10, url, '-'*10 - fn, h = urlretrieve(url) - print fn, h - if h: - print '======' - for k in h.keys(): print k + ':', h[k] - print '======' - fp = open(fn, 'r') - data = fp.read() - del fp - print regsub.gsub('\r', '', data) - fn, h = None, None - print '-'*40 - finally: - urlcleanup() - -# Run test program when run as a script -if __name__ == '__main__': -## test1() - test() diff --git a/Lib/urlopen.py b/Lib/urlopen.py deleted file mode 100755 index c43b7f4f69..0000000000 --- a/Lib/urlopen.py +++ /dev/null @@ -1,410 +0,0 @@ -# Open an arbitrary URL -# -# See the following document for a tentative description of URLs: -# Uniform Resource Locators Tim Berners-Lee -# INTERNET DRAFT CERN -# IETF URL Working Group 14 July 1993 -# draft-ietf-uri-url-01.txt -# -# The object returned by URLopener().open(file) will differ per -# protocol. All you know is that is has methods read(), readline(), -# readlines(), fileno(), close() and info(). The read*(), fileno() -# and close() methods work like those of open files. -# The info() method returns an rfc822.Message object which can be -# used to query various info about the object, if available. -# (rfc822.Message objects are queried with the getheader() method.) - -import socket -import regex - - -# This really consists of two pieces: -# (1) a class which handles opening of all sorts of URLs -# (plus assorted utilities etc.) -# (2) a set of functions for parsing URLs -# XXX Should these be separated out into different modules? - - -# Shortcut for basic usage -_urlopener = None -def urlopen(url): - global _urlopener - if not _urlopener: - _urlopener = URLopener() - return _urlopener.open(url) -def urlretrieve(url): - global _urlopener - if not _urlopener: - _urlopener = URLopener() - return _urlopener.retrieve(url) -def urlcleanup(): - if _urlopener: - _urlopener.cleanup() - - -# Class to open URLs. -# This is a class rather than just a subroutine because we may need -# more than one set of global protocol-specific options. -ftpcache = {} -class URLopener: - - # Constructor - def __init__(self): - self.addheaders = [] - self.tempcache = {} - self.ftpcache = ftpcache - # Undocumented feature: you can use a different - # ftp cache by assigning to the .ftpcache member; - # in case you want logically independent URL openers - - def __del__(self): - self.close() - - def close(self): - self.cleanup() - - def cleanup(self): - import os - for url in self.tempcache.keys(): - try: - os.unlink(self.tempcache[url][0]) - except os.error: - pass - del self.tempcache[url] - - # Add a header to be used by the HTTP interface only - # e.g. u.addheader('Accept', 'sound/basic') - def addheader(self, *args): - self.addheaders.append(args) - - # External interface - # Use URLopener().open(file) instead of open(file, 'r') - def open(self, url): - type, url = splittype(unwrap(url)) - if not type: type = 'file' - name = 'open_' + type - if '-' in name: - import regsub - name = regsub.gsub('-', '_', name) - if not hasattr(self, name): - raise IOError, ('url error', 'unknown url type', type) - try: - return getattr(self, name)(url) - except socket.error, msg: - raise IOError, ('socket error', msg) - - # External interface - # retrieve(url) returns (filename, None) for a local object - # or (tempfilename, headers) for a remote object - def retrieve(self, url): - if self.tempcache.has_key(url): - return self.tempcache[url] - url1 = unwrap(url) - if self.tempcache.has_key(url1): - self.tempcache[url] = self.tempcache[url1] - return self.tempcache[url1] - type, url1 = splittype(url1) - if not type or type == 'file': - try: - fp = self.open_local_file(url1) - del fp - return splithost(url1)[1], None - except IOError, msg: - pass - fp = self.open(url) - headers = fp.info() - import tempfile - tfn = tempfile.mktemp() - self.tempcache[url] = result = tfn, headers - tfp = open(tfn, 'w') - bs = 1024*8 - block = fp.read(bs) - while block: - tfp.write(block) - block = fp.read(bs) - del fp - del tfp - return result - - # Each method named open_<type> knows how to open that type of URL - - # Use HTTP protocol - def open_http(self, url): - import httplib - host, selector = splithost(url) - h = httplib.HTTP(host) - h.putrequest('GET', selector) - for args in self.addheaders: apply(h.putheader, args) - errcode, errmsg, headers = h.getreply() - if errcode == 200: return addinfo(h.getfile(), headers) - else: raise IOError, ('http error', errcode, errmsg, headers) - - # Use Gopher protocol - def open_gopher(self, url): - import gopherlib - host, selector = splithost(url) - type, selector = splitgophertype(selector) - selector, query = splitquery(selector) - if query: fp = gopherlib.send_query(selector, query, host) - else: fp = gopherlib.send_selector(selector, host) - return addinfo(fp, noheaders()) - - # Use local file or FTP depending on form of URL - def open_file(self, url): - try: - return self.open_local_file(url) - except IOError: - return self.open_ftp(url) - - # Use local file - def open_local_file(self, url): - host, file = splithost(url) - if not host: return addinfo(open(file, 'r'), noheaders()) - host, port = splitport(host) - if not port and socket.gethostbyname(host) in ( - localhost(), thishost()): - return addinfo(open(file, 'r'), noheaders()) - raise IOError, ('local file error', 'not on local host') - - # Use FTP protocol - def open_ftp(self, url): - host, file = splithost(url) - if not host: raise IOError, ('ftp error', 'no host given') - host, port = splitport(host) - host = socket.gethostbyname(host) - if not port: - import ftplib - port = ftplib.FTP_PORT - key = (host, port) - try: - if not self.ftpcache.has_key(key): - self.ftpcache[key] = ftpwrapper(host, port) - return addinfo(self.ftpcache[key].retrfile(file), - noheaders()) - except ftperrors(), msg: - raise IOError, ('ftp error', msg) - - -# Utility functions - -# Return the IP address of the magic hostname 'localhost' -_localhost = None -def localhost(): - global _localhost - if not _localhost: - _localhost = socket.gethostbyname('localhost') - return _localhost - -# Return the IP address of the current host -_thishost = None -def thishost(): - global _thishost - if not _thishost: - _thishost = socket.gethostbyname(socket.gethostname()) - return _thishost - -# Return the set of errors raised by the FTP class -_ftperrors = None -def ftperrors(): - global _ftperrors - if not _ftperrors: - import ftplib - _ftperrors = (ftplib.error_reply, - ftplib.error_temp, - ftplib.error_perm, - ftplib.error_proto) - return _ftperrors - -# Return an empty rfc822.Message object -_noheaders = None -def noheaders(): - global _noheaders - if not _noheaders: - import rfc822 - _noheaders = rfc822.Message(open('/dev/null', 'r')) - _noheaders.fp.close() # Recycle file descriptor - return _noheaders - - -# Utility classes - -# Class used by open_ftp() for cache of open FTP connections -class ftpwrapper: - def __init__(self, host, port): - self.host = host - self.port = port - self.init() - def init(self): - import ftplib - self.ftp = ftplib.FTP() - self.ftp.connect(self.host, self.port) - self.ftp.login() - def retrfile(self, file): - import ftplib - try: - self.ftp.voidcmd('TYPE I') - except ftplib.all_errors: - self.init() - self.ftp.voidcmd('TYPE I') - conn = None - if file: - try: - cmd = 'RETR ' + file - conn = self.ftp.transfercmd(cmd) - except ftplib.error_perm, reason: - if reason[:3] != '550': - raise IOError, ('ftp error', reason) - if not conn: - # Try a directory listing - if file: cmd = 'LIST ' + file - else: cmd = 'LIST' - conn = self.ftp.transfercmd(cmd) - return addclosehook(conn.makefile('r'), self.ftp.voidresp) - -# Base class for addinfo and addclosehook -class addbase: - def __init__(self, fp): - self.fp = fp - self.read = self.fp.read - self.readline = self.fp.readline - self.readlines = self.fp.readlines - self.fileno = self.fp.fileno - def __repr__(self): - return '<%s at %s whose fp = %s>' % ( - self.__class__.__name__, `id(self)`, `self.fp`) - def __del__(self): - self.close() - def close(self): - self.read = None - self.readline = None - self.readlines = None - self.fileno = None - self.fp = None - -# Class to add a close hook to an open file -class addclosehook(addbase): - def __init__(self, fp, closehook, *hookargs): - addbase.__init__(self, fp) - self.closehook = closehook - self.hookargs = hookargs - def close(self): - if self.closehook: - apply(self.closehook, self.hookargs) - self.closehook = None - self.hookargs = None - addbase.close(self) - -# class to add an info() method to an open file -class addinfo(addbase): - def __init__(self, fp, headers): - addbase.__init__(self, fp) - self.headers = headers - def info(self): - return self.headers - - -# Utility to combine a URL with a base URL to form a new URL - -def basejoin(base, url): - type, path = splittype(url) - if type: return url - host, path = splithost(path) - basetype, basepath = splittype(base) - basehost, basepath = splithost(basepath) - basepath, basetag = splittag(basepath) - basepath, basequery = splitquery(basepath) - type = basetype or 'file' - if path[:1] != '/': - import string - i = string.rfind(basepath, '/') - if i < 0: basepath = '/' - else: basepath = basepath[:i+1] - path = basepath + path - if not host: host = basehost - if host: return type + '://' + host + path - else: return type + ':' + path - - -# Utilities to parse URLs: -# unwrap('<URL:type//host/path>') --> 'type//host/path' -# splittype('type:opaquestring') --> 'type', 'opaquestring' -# splithost('//host[:port]/path') --> 'host[:port]', '/path' -# splitport('host:port') --> 'host', 'port' -# splitquery('/path?query') --> '/path', 'query' -# splittag('/path#tag') --> '/path', 'tag' -# splitgophertype('/Xselector') --> 'X', 'selector' - -def unwrap(url): - import string - url = string.strip(url) - if url[:1] == '<' and url[-1:] == '>': - url = string.strip(url[1:-1]) - if url[:4] == 'URL:': url = string.strip(url[4:]) - return url - -_typeprog = regex.compile('^\([^/:]+\):\(.*\)$') -def splittype(url): - if _typeprog.match(url) >= 0: return _typeprog.group(1, 2) - return None, url - -_hostprog = regex.compile('^//\([^/]+\)\(.*\)$') -def splithost(url): - if _hostprog.match(url) >= 0: return _hostprog.group(1, 2) - return None, url - -_portprog = regex.compile('^\(.*\):\([0-9]+\)$') -def splitport(host): - if _portprog.match(host) >= 0: return _portprog.group(1, 2) - return host, None - -_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$') -def splitquery(url): - if _queryprog.match(url) >= 0: return _queryprog.group(1, 2) - return url, None - -_tagprog = regex.compile('^\(.*\)#\([^#]*\)$') -def splittag(url): - if _tagprog.match(url) >= 0: return _tagprog.group(1, 2) - return url, None - -def splitgophertype(selector): - if selector[:1] == '/' and selector[1:2]: - return selector[1], selector[2:] - return None, selector - - -# Test program -def test(): - import sys - import regsub - args = sys.argv[1:] - if not args: - args = [ - '/etc/passwd', - 'file:/etc/passwd', - 'file://localhost/etc/passwd', - 'ftp://ftp.cwi.nl/etc/passwd', - 'gopher://gopher.cwi.nl/11/', - 'http://www.cwi.nl/index.html', - ] - try: - for url in args: - print '-'*10, url, '-'*10 - fn, h = urlretrieve(url) - print fn, h - if h: - print '======' - for k in h.keys(): print k + ':', h[k] - print '======' - fp = open(fn, 'r') - data = fp.read() - del fp - print regsub.gsub('\r', '', data) - fn, h = None, None - print '-'*40 - finally: - urlcleanup() - -# Run test program when run as a script -if __name__ == '__main__': - test() diff --git a/Lib/urlparse.py b/Lib/urlparse.py deleted file mode 100644 index 571ef0eb0c..0000000000 --- a/Lib/urlparse.py +++ /dev/null @@ -1,218 +0,0 @@ -# Parse (absolute and relative) URLs. See RFC 1808: "Relative Uniform -# Resource Locators", by R. Fielding, UC Irvine, June 1995. - -# Standard/builtin Python modules -import string -from string import joinfields, splitfields, find, rfind - -# A classification of schemes ('' means apply by default) -uses_relative = ['ftp', 'http', 'gopher', 'nntp', 'wais', 'file', - 'prospero', ''] -uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', 'wais', - 'prospero', ''] -non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', 'telnet', 'wais'] -uses_params = ['ftp', 'hdl', 'prospero', 'http', ''] -uses_query = ['http', 'wais', ''] -uses_fragment = ['ftp', 'hdl', 'http', 'gopher', 'news', 'nntp', 'wais', - 'file', 'prospero', ''] - -# Characters valid in scheme names -scheme_chars = string.letters + string.digits + '+-.' - -_parse_cache = {} - -def clear_cache(): - global _parse_cache - _parse_cache = {} - - -# Parse a URL into 6 components: -# <scheme>://<netloc>/<path>;<params>?<query>#<fragment> -# Return a 6-tuple: (scheme, netloc, path, params, query, fragment). -# Note that we don't break the components up in smaller bits -# (e.g. netloc is a single string) and we don't expand % escapes. -def urlparse(url, scheme = '', allow_framents = 1): - key = url, scheme, allow_framents - if _parse_cache.has_key(key): - return _parse_cache[key] - netloc = path = params = query = fragment = '' - i = string.find(url, ':') - if i > 0: - for c in url[:i]: - if c not in scheme_chars: - break - else: - scheme, url = string.lower(url[:i]), url[i+1:] - if scheme in uses_netloc: - if url[:2] == '//': - i = string.find(url, '/', 2) - if i < 0: - i = len(url) - netloc, url = url[2:i], url[i:] - if allow_framents and scheme in uses_fragment: - i = string.rfind(url, '#') - if i >= 0: - url, fragment = url[:i], url[i+1:] - if scheme in uses_query: - i = string.find(url, '?') - if i >= 0: - url, query = url[:i], url[i+1:] - if scheme in uses_params: - i = string.find(url, ';') - if i >= 0: - url, params = url[:i], url[i+1:] - tuple = scheme, netloc, url, params, query, fragment - _parse_cache[key] = tuple - return tuple - -# Put a parsed URL back together again. This may result in a slightly -# different, but equivalent URL, if the URL that was parsed originally -# had redundant delimiters, e.g. a ? with an empty query (the draft -# states that these are equivalent). -def urlunparse((scheme, netloc, url, params, query, fragment)): - if netloc: - if url[:1] != '/': url = '/' + url - url = '//' + netloc + url - if scheme: - url = scheme + ':' + url - if params: - url = url + ';' + params - if query: - url = url + '?' + query - if fragment: - url = url + '#' + fragment - return url - -# Join a base URL and a possibly relative URL to form an absolute -# interpretation of the latter. -def urljoin(base, url, allow_framents = 1): - if not base: - return url - bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ - urlparse(base, '', allow_framents) - scheme, netloc, path, params, query, fragment = \ - urlparse(url, bscheme, allow_framents) - # XXX Unofficial hack: default netloc to bnetloc even if - # schemes differ - if scheme != bscheme and not netloc and \ - scheme in uses_relative and bscheme in uses_relative and \ - scheme in uses_netloc and bscheme in uses_netloc: - netloc = bnetloc - # Strip the port number - i = find(netloc, '@') - if i < 0: i = 0 - i = find(netloc, ':', i) - if i >= 0: - netloc = netloc[:i] - if scheme != bscheme or scheme not in uses_relative: - return urlunparse((scheme, netloc, path, - params, query, fragment)) - if scheme in uses_netloc: - if netloc: - return urlunparse((scheme, netloc, path, - params, query, fragment)) - netloc = bnetloc - if path[:1] == '/': - return urlunparse((scheme, netloc, path, - params, query, fragment)) - if not path: - return urlunparse((scheme, netloc, bpath, - params, query or bquery, fragment)) - i = rfind(bpath, '/') - if i >= 0: - path = bpath[:i] + '/' + path - segments = splitfields(path, '/') - if segments[-1] == '.': - segments[-1] = '' - while '.' in segments: - segments.remove('.') - while 1: - i = 1 - n = len(segments) - 1 - while i < n: - if segments[i] == '..' and segments[i-1]: - del segments[i-1:i+1] - break - i = i+1 - else: - break - if len(segments) >= 2 and segments[-1] == '..': - segments[-2:] = [''] - return urlunparse((scheme, netloc, joinfields(segments, '/'), - params, query, fragment)) - -def urldefrag(url): - """Removes any existing fragment from URL. - - Returns a tuple of the defragmented URL and the fragment. If - the URL contained no fragments, the second element is the - empty string. - """ - s, n, p, a, q, frag = urlparse(url) - defrag = urlunparse((s, n, p, a, q, '')) - return defrag, frag - - -test_input = """ - http://a/b/c/d - - g:h = <URL:g:h> - http:g = <URL:http://a/b/c/g> - http: = <URL:http://a/b/c/d> - g = <URL:http://a/b/c/g> - ./g = <URL:http://a/b/c/g> - g/ = <URL:http://a/b/c/g/> - /g = <URL:http://a/g> - //g = <URL:http://g> - ?y = <URL:http://a/b/c/d?y> - g?y = <URL:http://a/b/c/g?y> - g?y/./x = <URL:http://a/b/c/g?y/./x> - . = <URL:http://a/b/c/> - ./ = <URL:http://a/b/c/> - .. = <URL:http://a/b/> - ../ = <URL:http://a/b/> - ../g = <URL:http://a/b/g> - ../.. = <URL:http://a/> - ../../g = <URL:http://a/g> - ../../../g = <URL:http://a/../g> - ./../g = <URL:http://a/b/g> - ./g/. = <URL:http://a/b/c/g/> - /./g = <URL:http://a/./g> - g/./h = <URL:http://a/b/c/g/h> - g/../h = <URL:http://a/b/c/h> - http:g = <URL:http://a/b/c/g> - http: = <URL:http://a/b/c/d> -""" - -def test(): - import sys - base = '' - if sys.argv[1:]: - fn = sys.argv[1] - if fn == '-': - fp = sys.stdin - else: - fp = open(fn) - else: - import StringIO - fp = StringIO.StringIO(test_input) - while 1: - line = fp.readline() - if not line: break - words = string.split(line) - if not words: - continue - url = words[0] - parts = urlparse(url) - print '%-10s : %s' % (url, parts) - abs = urljoin(base, url) - if not base: - base = abs - wrapped = '<URL:%s>' % abs - print '%-10s = %s' % (url, wrapped) - if len(words) == 3 and words[1] == '=': - if wrapped != words[2]: - print 'EXPECTED', words[2], '!!!!!!!!!!' - -if __name__ == '__main__': - test() diff --git a/Lib/util.py b/Lib/util.py deleted file mode 100644 index 6cb1433426..0000000000 --- a/Lib/util.py +++ /dev/null @@ -1,25 +0,0 @@ -# Module 'util' -- some useful functions that don't fit elsewhere - -# NB: These are now built-in functions, but this module is provided -# for compatibility. Don't use in new programs unless you need backward -# compatibility (i.e. need to run with old interpreters). - - -# Remove an item from a list. -# No complaints if it isn't in the list at all. -# If it occurs more than once, remove the first occurrence. -# -def remove(item, list): - if item in list: list.remove(item) - - -# Return a string containing a file's contents. -# -def readfile(fn): - return readopenfile(open(fn, 'r')) - - -# Read an open file until EOF. -# -def readopenfile(fp): - return fp.read() diff --git a/Lib/uu.py b/Lib/uu.py deleted file mode 100755 index 5644803176..0000000000 --- a/Lib/uu.py +++ /dev/null @@ -1,169 +0,0 @@ -# uu.py -# Copyright 1994 by Lance Ellinghouse -# Cathedral City, California Republic, United States of America. -# All Rights Reserved -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose and without fee 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, and that the name of Lance Ellinghouse -# not be used in advertising or publicity pertaining to distribution -# of the software without specific, written prior permission. -# LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO -# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -# FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM 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. -# -# Modified by Jack Jansen, CWI, July 1995: -# - Use binascii module to do the actual line-by-line conversion -# between ascii and binary. This results in a 1000-fold speedup. The C -# version is still 5 times faster, though. -# - Arguments more compliant with python standard -# -# This file implements the UUencode and UUdecode functions. - -# encode(in_file, out_file [,name, mode]) -# decode(in_file [, out_file, mode]) - -import binascii -import os -import string - -Error = 'uu.Error' - -def encode(in_file, out_file, name=None, mode=None): - """Uuencode file""" - # - # If in_file is a pathname open it and change defaults - # - if in_file == '-': - in_file = sys.stdin - elif type(in_file) == type(''): - if name == None: - name = os.path.basename(in_file) - if mode == None: - try: - mode = os.stat(in_file)[0] - except AttributeError: - pass - in_file = open(in_file, 'rb') - # - # Open out_file if it is a pathname - # - if out_file == '-': - out_file = sys.stdout - elif type(out_file) == type(''): - out_file = open(out_file, 'w') - # - # Set defaults for name and mode - # - if name == None: - name = '-' - if mode == None: - mode = 0666 - # - # Write the data - # - out_file.write('begin %o %s\n' % ((mode&0777),name)) - str = in_file.read(45) - while len(str) > 0: - out_file.write(binascii.b2a_uu(str)) - str = in_file.read(45) - out_file.write(' \nend\n') - - -def decode(in_file, out_file=None, mode=None): - """Decode uuencoded file""" - # - # Open the input file, if needed. - # - if in_file == '-': - in_file = sys.stdin - elif type(in_file) == type(''): - in_file = open(in_file) - # - # Read the header line, and fill in optional args if needed - # - hdr = in_file.readline() - if not hdr: - raise Error, 'Empty input file' - hdrfields = string.split(hdr) - if len(hdrfields) <> 3 or hdrfields[0] <> 'begin': - raise Error, ('Incorrect uu header line', hdr) - if out_file == None: - out_file = hdrfields[2] - if mode == None: - mode = string.atoi(hdrfields[1]) - # - # Open the output file - # - if out_file == '-': - out_file = sys.stdout - elif type(out_file) == type(''): - fp = open(out_file, 'wb') - try: - os.path.chmod(out_file, mode) - except AttributeError: - pass - out_file = fp - # - # Main decoding loop - # - str = in_file.readline() - while str and str != 'end\n': - out_file.write(binascii.a2b_uu(str)) - str = in_file.readline() - if not str: - raise Error, 'Truncated input file' - -def test(): - """uuencode/uudecode main program""" - import sys - import getopt - - dopt = 0 - topt = 0 - input = sys.stdin - output = sys.stdout - ok = 1 - try: - optlist, args = getopt.getopt(sys.argv[1:], 'dt') - except getopt.error: - ok = 0 - if not ok or len(args) > 2: - print 'Usage:', sys.argv[0], '[-d] [-t] [input [output]]' - print ' -d: Decode (in stead of encode)' - print ' -t: data is text, encoded format unix-compatible text' - sys.exit(1) - - for o, a in optlist: - if o == '-d': dopt = 1 - if o == '-t': topt = 1 - - if len(args) > 0: - input = args[0] - if len(args) > 1: - output = args[1] - - if dopt: - if topt: - if type(output) == type(''): - output = open(output, 'w') - else: - print sys.argv[0], ': cannot do -t to stdout' - sys.exit(1) - decode(input, output) - else: - if topt: - if type(input) == type(''): - input = open(input, 'r') - else: - print sys.argv[0], ': cannot do -t from stdin' - sys.exit(1) - encode(input, output) - -if __name__ == '__main__': - test() diff --git a/Lib/wave.py b/Lib/wave.py deleted file mode 100644 index 5d1a1c1629..0000000000 --- a/Lib/wave.py +++ /dev/null @@ -1,559 +0,0 @@ -# Stuff to parse WAVE files. -# -# Usage. -# -# Reading WAVE files: -# f = wave.open(file, 'r') -# where file is either the name of a file or an open file pointer. -# The open file pointer must have methods read(), seek(), and close(). -# When the setpos() and rewind() methods are not used, the seek() -# method is not necessary. -# -# This returns an instance of a class with the following public methods: -# getnchannels() -- returns number of audio channels (1 for -# mono, 2 for stereo) -# getsampwidth() -- returns sample width in bytes -# getframerate() -- returns sampling frequency -# getnframes() -- returns number of audio frames -# getcomptype() -- returns compression type ('NONE' for AIFF files) -# getcompname() -- returns human-readable version of -# compression type ('not compressed' for AIFF files) -# getparams() -- returns a tuple consisting of all of the -# above in the above order -# getmarkers() -- returns None (for compatibility with the -# aifc module) -# getmark(id) -- raises an error since the mark does not -# exist (for compatibility with the aifc module) -# readframes(n) -- returns at most n frames of audio -# rewind() -- rewind to the beginning of the audio stream -# setpos(pos) -- seek to the specified position -# tell() -- return the current position -# close() -- close the instance (make it unusable) -# The position returned by tell() and the position given to setpos() -# are compatible and have nothing to do with the actual postion in the -# file. -# The close() method is called automatically when the class instance -# is destroyed. -# -# Writing WAVE files: -# f = wave.open(file, 'w') -# where file is either the name of a file or an open file pointer. -# The open file pointer must have methods write(), tell(), seek(), and -# close(). -# -# This returns an instance of a class with the following public methods: -# setnchannels(n) -- set the number of channels -# setsampwidth(n) -- set the sample width -# setframerate(n) -- set the frame rate -# setnframes(n) -- set the number of frames -# setcomptype(type, name) -# -- set the compression type and the -# human-readable compression type -# setparams(nchannels, sampwidth, framerate, nframes, comptype, compname) -# -- set all parameters at once -# tell() -- return current position in output file -# writeframesraw(data) -# -- write audio frames without pathing up the -# file header -# writeframes(data) -# -- write audio frames and patch up the file header -# close() -- patch up the file header and close the -# output file -# You should set the parameters before the first writeframesraw or -# writeframes. The total number of frames does not need to be set, -# but when it is set to the correct value, the header does not have to -# be patched up. -# It is best to first set all parameters, perhaps possibly the -# compression type, and then write audio frames using writeframesraw. -# When all frames have been written, either call writeframes('') or -# close() to patch up the sizes in the header. -# The close() method is called automatically when the class instance -# is destroyed. - -import __builtin__ - -Error = 'wave.Error' - -WAVE_FORMAT_PCM = 0x0001 - -_array_fmts = None, 'b', 'h', None, 'l' - -def _read_long(file): - x = 0L - for i in range(4): - byte = file.read(1) - if byte == '': - raise EOFError - x = x + (ord(byte) << (8 * i)) - if x >= 0x80000000L: - x = x - 0x100000000L - return int(x) - -def _read_ulong(file): - x = 0L - for i in range(4): - byte = file.read(1) - if byte == '': - raise EOFError - x = x + (ord(byte) << (8 * i)) - return x - -def _read_short(file): - x = 0 - for i in range(2): - byte = file.read(1) - if byte == '': - raise EOFError - x = x + (ord(byte) << (8 * i)) - if x >= 0x8000: - x = x - 0x10000 - return x - -def _write_short(f, x): - d, m = divmod(x, 256) - f.write(chr(m)) - f.write(chr(d)) - -def _write_long(f, x): - if x < 0: - x = x + 0x100000000L - for i in range(4): - d, m = divmod(x, 256) - f.write(chr(int(m))) - x = d - -class Chunk: - def __init__(self, file): - self.file = file - self.chunkname = self.file.read(4) - if len(self.chunkname) < 4: - raise EOFError - self.chunksize = _read_long(self.file) - self.size_read = 0 - self.offset = self.file.tell() - - def rewind(self): - self.file.seek(self.offset, 0) - self.size_read = 0 - - def setpos(self, pos): - if pos < 0 or pos > self.chunksize: - raise RuntimeError - self.file.seek(self.offset + pos, 0) - self.size_read = pos - - def read(self, length): - if self.size_read >= self.chunksize: - return '' - if length > self.chunksize - self.size_read: - length = self.chunksize - self.size_read - data = self.file.read(length) - self.size_read = self.size_read + len(data) - return data - - def skip(self): - try: - self.file.seek(self.chunksize - self.size_read, 1) - except RuntimeError: - while self.size_read < self.chunksize: - dummy = self.read(8192) - if not dummy: - raise EOFError - -class Wave_read: - # Variables used in this class: - # - # These variables are available to the user though appropriate - # methods of this class: - # _file -- the open file with methods read(), close(), and seek() - # set through the __init__() method - # _nchannels -- the number of audio channels - # available through the getnchannels() method - # _nframes -- the number of audio frames - # available through the getnframes() method - # _sampwidth -- the number of bytes per audio sample - # available through the getsampwidth() method - # _framerate -- the sampling frequency - # available through the getframerate() method - # _comptype -- the AIFF-C compression type ('NONE' if AIFF) - # available through the getcomptype() method - # _compname -- the human-readable AIFF-C compression type - # available through the getcomptype() method - # _soundpos -- the position in the audio stream - # available through the tell() method, set through the - # setpos() method - # - # These variables are used internally only: - # _fmt_chunk_read -- 1 iff the FMT chunk has been read - # _data_seek_needed -- 1 iff positioned correctly in audio - # file for readframes() - # _data_chunk -- instantiation of a chunk class for the DATA chunk - # _framesize -- size of one frame in the file - - access _file, _nchannels, _nframes, _sampwidth, _framerate, \ - _comptype, _compname, _soundpos, \ - _fmt_chunk_read, _data_seek_needed, \ - _data_chunk, _framesize: private - - def initfp(self, file): - self._file = file - self._convert = None - self._soundpos = 0 - form = self._file.read(4) - if form != 'RIFF': - raise Error, 'file does not start with RIFF id' - formlength = _read_long(self._file) - if formlength <= 0: - raise Error, 'invalid FORM chunk data size' - formdata = self._file.read(4) - formlength = formlength - 4 - if formdata != 'WAVE': - raise Error, 'not a WAVE file' - self._fmt_chunk_read = 0 - while formlength > 0: - self._data_seek_needed = 1 - chunk = Chunk(self._file) - if chunk.chunkname == 'fmt ': - self._read_fmt_chunk(chunk) - self._fmt_chunk_read = 1 - elif chunk.chunkname == 'data': - if not self._fmt_chunk_read: - raise Error, 'data chunk before fmt chunk' - self._data_chunk = chunk - self._nframes = chunk.chunksize / self._framesize - self._data_seek_needed = 0 - formlength = formlength - 8 - chunk.chunksize - if formlength > 0: - chunk.skip() - if not self._fmt_chunk_read or not self._data_chunk: - raise Error, 'fmt chunk and/or data chunk missing' - - def __init__(self, f): - if type(f) == type(''): - f = __builtin__.open(f, 'r') - # else, assume it is an open file object already - self.initfp(f) - - def __del__(self): - if self._file: - self.close() - - # - # User visible methods. - # - def getfp(self): - return self._file - - def rewind(self): - self._data_seek_needed = 1 - self._soundpos = 0 - - def close(self): - self._file = None - - def tell(self): - return self._soundpos - - def getnchannels(self): - return self._nchannels - - def getnframes(self): - return self._nframes - - def getsampwidth(self): - return self._sampwidth - - def getframerate(self): - return self._framerate - - def getcomptype(self): - return self._comptype - - def getcompname(self): - return self._compname - - def getparams(self): - return self.getnchannels(), self.getsampwidth(), \ - self.getframerate(), self.getnframes(), \ - self.getcomptype(), self.getcompname() - - def getmarkers(self): - return None - - def getmark(self, id): - raise Error, 'no marks' - - def setpos(self, pos): - if pos < 0 or pos > self._nframes: - raise Error, 'position not in range' - self._soundpos = pos - self._data_seek_needed = 1 - - def readframes(self, nframes): - if self._data_seek_needed: - self._data_chunk.rewind() - pos = self._soundpos * self._framesize - if pos: - self._data_chunk.setpos(pos) - self._data_seek_needed = 0 - if nframes == 0: - return '' - if self._sampwidth > 1: - # unfortunately the fromfile() method does not take - # something that only looks like a file object, so - # we have to reach into the innards of the chunk object - import array - data = array.array(_array_fmts[self._sampwidth]) - nitems = nframes * self._nchannels - if nitems * self._sampwidth > self._data_chunk.chunksize - self._data_chunk.size_read: - nitems = (self._data_chunk.chunksize - self._data_chunk.size_read) / self._sampwidth - data.fromfile(self._data_chunk.file, nitems) - self._data_chunk.size_read = self._data_chunk.size_read + nitems * self._sampwidth - data.byteswap() - data = data.tostring() - else: - data = self._data_chunk.read(nframes * self._framesize) - if self._convert and data: - data = self._convert(data) - self._soundpos = self._soundpos + len(data) / (self._nchannels * self._sampwidth) - return data - - # - # Internal methods. - # - access *: private - - def _read_fmt_chunk(self, chunk): - wFormatTag = _read_short(chunk) - self._nchannels = _read_short(chunk) - self._framerate = _read_long(chunk) - dwAvgBytesPerSec = _read_long(chunk) - wBlockAlign = _read_short(chunk) - if wFormatTag == WAVE_FORMAT_PCM: - self._sampwidth = (_read_short(chunk) + 7) / 8 - else: - raise Error, 'unknown format' - self._framesize = self._nchannels * self._sampwidth - self._comptype = 'NONE' - self._compname = 'not compressed' - -class Wave_write: - # Variables used in this class: - # - # These variables are user settable through appropriate methods - # of this class: - # _file -- the open file with methods write(), close(), tell(), seek() - # set through the __init__() method - # _comptype -- the AIFF-C compression type ('NONE' in AIFF) - # set through the setcomptype() or setparams() method - # _compname -- the human-readable AIFF-C compression type - # set through the setcomptype() or setparams() method - # _nchannels -- the number of audio channels - # set through the setnchannels() or setparams() method - # _sampwidth -- the number of bytes per audio sample - # set through the setsampwidth() or setparams() method - # _framerate -- the sampling frequency - # set through the setframerate() or setparams() method - # _nframes -- the number of audio frames written to the header - # set through the setnframes() or setparams() method - # - # These variables are used internally only: - # _datalength -- the size of the audio samples written to the header - # _nframeswritten -- the number of frames actually written - # _datawritten -- the size of the audio samples actually written - - access _file, _comptype, _compname, _nchannels, _sampwidth, \ - _framerate, _nframes, _nframeswritten, \ - _datalength, _datawritten: private - - def __init__(self, f): - if type(f) == type(''): - f = __builtin__.open(f, 'w') - self.initfp(f) - - def initfp(self, file): - self._file = file - self._convert = None - self._nchannels = 0 - self._sampwidth = 0 - self._framerate = 0 - self._nframes = 0 - self._nframeswritten = 0 - self._datawritten = 0 - self._datalength = 0 - - def __del__(self): - if self._file: - self.close() - - # - # User visible methods. - # - def setnchannels(self, nchannels): - if self._datawritten: - raise Error, 'cannot change parameters after starting to write' - if nchannels < 1: - raise Error, 'bad # of channels' - self._nchannels = nchannels - - def getnchannels(self): - if not self._nchannels: - raise Error, 'number of channels not set' - return self._nchannels - - def setsampwidth(self, sampwidth): - if self._datawritten: - raise Error, 'cannot change parameters after starting to write' - if sampwidth < 1 or sampwidth > 4: - raise Error, 'bad sample width' - self._sampwidth = sampwidth - - def getsampwidth(self): - if not self._sampwidth: - raise Error, 'sample width not set' - return self._sampwidth - - def setframerate(self, framerate): - if self._datawritten: - raise Error, 'cannot change parameters after starting to write' - if framerate <= 0: - raise Error, 'bad frame rate' - self._framerate = framerate - - def getframerate(self): - if not self._framerate: - raise Error, 'frame rate not set' - return self._framerate - - def setnframes(self, nframes): - if self._datawritten: - raise Error, 'cannot change parameters after starting to write' - self._nframes = nframes - - def getnframes(self): - return self._nframeswritten - - def setcomptype(self, comptype, compname): - if self._datawritten: - raise Error, 'cannot change parameters after starting to write' - if comptype not in ('NONE',): - raise Error, 'unsupported compression type' - self._comptype = comptype - self._compname = compname - - def getcomptype(self): - return self._comptype - - def getcompname(self): - return self._compname - - def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)): - if self._datawritten: - raise Error, 'cannot change parameters after starting to write' - self.setnchannels(nchannels) - self.setsampwidth(sampwidth) - self.setframerate(framerate) - self.setnframes(nframes) - self.setcomptype(comptype, compname) - - def getparams(self): - if not self._nchannels or not self._sampwidth or not self._framerate: - raise Error, 'not all parameters set' - return self._nchannels, self._sampwidth, self._framerate, \ - self._nframes, self._comptype, self._compname - - def setmark(self, id, pos, name): - raise Error, 'setmark() not supported' - - def getmark(self, id): - raise Error, 'no marks' - - def getmarkers(self): - return None - - def tell(self): - return self._nframeswritten - - def writeframesraw(self, data): - self._ensure_header_written(len(data)) - nframes = len(data) / (self._sampwidth * self._nchannels) - if self._convert: - data = self._convert(data) - if self._sampwidth > 1: - import array - data = array.array(_array_fmts[self._sampwidth], data) - data.byteswap() - data.tofile(self._file) - self._datawritten = self._datawritten + len(data) * self._sampwidth - else: - self._file.write(data) - self._datawritten = self._datawritten + len(data) - self._nframeswritten = self._nframeswritten + nframes - - def writeframes(self, data): - self.writeframesraw(data) - if self._datalength != self._datawritten: - self._patchheader() - - def close(self): - self._ensure_header_written(0) - if self._datalength != self._datawritten: - self._patchheader() - self._file.flush() - self._file = None - - # - # Internal methods. - # - access *: private - - def _ensure_header_written(self, datasize): - if not self._datawritten: - if not self._nchannels: - raise Error, '# channels not specified' - if not self._sampwidth: - raise Error, 'sample width not specified' - if not self._framerate: - raise Error, 'sampling rate not specified' - self._write_header(datasize) - - def _write_header(self, initlength): - self._file.write('RIFF') - if not self._nframes: - self._nframes = initlength / (self._nchannels * self._sampwidth) - self._datalength = self._nframes * self._nchannels * self._sampwidth - self._form_length_pos = self._file.tell() - _write_long(self._file, 36 + self._datalength) - self._file.write('WAVE') - self._file.write('fmt ') - _write_long(self._file, 16) - _write_short(self._file, WAVE_FORMAT_PCM) - _write_short(self._file, self._nchannels) - _write_long(self._file, self._framerate) - _write_long(self._file, self._nchannels * self._framerate * self._sampwidth) - _write_short(self._file, self._nchannels * self._sampwidth) - _write_short(self._file, self._sampwidth * 8) - self._file.write('data') - self._data_length_pos = self._file.tell() - _write_long(self._file, self._datalength) - - def _patchheader(self): - if self._datawritten == self._datalength: - return - curpos = self._file.tell() - self._file.seek(self._form_length_pos, 0) - _write_long(36 + self._datawritten) - self._file.seek(self._data_length_pos, 0) - _write_long(self._file, self._datawritten) - self._file.seek(curpos, 0) - self._datalength = self._datawritten - -def open(f, mode): - if mode == 'r': - return Wave_read(f) - elif mode == 'w': - return Wave_write(f) - else: - raise Error, "mode must be 'r' or 'w'" - -openfp = open # B/W compatibility diff --git a/Lib/whatsound.py b/Lib/whatsound.py deleted file mode 100644 index b7b349c5ba..0000000000 --- a/Lib/whatsound.py +++ /dev/null @@ -1,270 +0,0 @@ -# This module contains several routines that help recognizing sound -# files. -# -# Function whathdr() recognizes various types of sound file headers. -# It understands almost all headers that SOX can decode. -# -# The return tuple contains the following items, in this order: -# - file type (as SOX understands it) -# - sampling rate (0 if unknown or hard to decode) -# - number of channels (0 if unknown or hard to decode) -# - number of frames in the file (-1 if unknown or hard to decode) -# - number of bits/sample, or 'U' for U-LAW, or 'A' for A-LAW -# -# If the file doesn't have a recognizable type, it returns None. -# If the file can't be opened, IOError is raised. -# -# To compute the total time, divide the number of frames by the -# sampling rate (a frame contains a sample for each channel). -# -# Function whatraw() calls the "whatsound" program and interprets its -# output. You'll have to guess the sampling rate by listening though! -# -# Function what() calls whathdr() and if it doesn't recognize the file -# then calls whatraw(). -# -# Finally, the function test() is a simple main program that calls -# what() for all files mentioned on the argument list. For directory -# arguments it calls what() for all files in that directory. Default -# argument is "." (testing all files in the current directory). The -# option -r tells it to recurse down directories found inside -# explicitly given directories. -# -# The file structure is top-down except that the test program and its -# subroutine come last. - - -#------------------------------------------------------# -# Guess the type of any sound file, raw or with header # -#------------------------------------------------------# - -def what(filename): - res = whathdr(filename) - if not res: - res = whatraw(filename) - return res - - -#-----------------------------# -# Guess the type of raw sound # -#-----------------------------# - -def whatraw(filename): - # Assume it's always 1 channel, byte-sized samples - # Don't assume anything about the rate - import os - from stat import ST_SIZE - # XXX "whatsound" should be part of the distribution somehow... - cmd = 'whatsound ' + filename + ' 2>/dev/null' - cmd = 'PATH=$PATH:/ufs/guido/bin/sgi\n' + cmd - pipe = os.popen(cmd, 'r') - data = pipe.read() - sts = pipe.close() - if sts: - return None - if data[:13] == '-t raw -b -s ': - type = 'sb' - sample_size = 8 - elif data[:13] == '-t raw -b -u ': - type = 'ub' - sample_size = 8 - elif data[:13] == '-t raw -b -U ': - type = 'ul' - sample_size = 'U' - else: - return None - try: - frame_count = os.stat(filename)[ST_SIZE] - except IOError: - frame_count = -1 - return type, 0, 1, frame_count, sample_size - - -#-------------------------# -# Recognize sound headers # -#-------------------------# - -def whathdr(filename): - f = open(filename, 'r') - h = f.read(512) - for tf in tests: - res = tf(h, f) - if res: - return res - return None - - -#-----------------------------------# -# Subroutines per sound header type # -#-----------------------------------# - -tests = [] - -def test_aifc(h, f): - import aifc - if h[:4] <> 'FORM': - return None - if h[8:12] == 'AIFC': - fmt = 'aifc' - elif h[8:12] == 'AIFF': - fmt = 'aiff' - else: - return None - f.seek(0) - try: - a = aifc.openfp(f, 'r') - except (EOFError, aifc.Error): - return None - return (fmt, a.getframerate(), a.getnchannels(), \ - a.getnframes(), 8*a.getsampwidth()) - -tests.append(test_aifc) - - -def test_au(h, f): - if h[:4] == '.snd': - f = get_long_be - elif h[:4] in ('\0ds.', 'dns.'): - f = get_long_le - else: - return None - type = 'au' - hdr_size = f(h[4:8]) - data_size = f(h[8:12]) - encoding = f(h[12:16]) - rate = f(h[16:20]) - nchannels = f(h[20:24]) - sample_size = 1 # default - if encoding == 1: - sample_bits = 'U' - elif encoding == 2: - sample_bits = 8 - elif encoding == 3: - sample_bits = 16 - sample_size = 2 - else: - sample_bits = '?' - frame_size = sample_size * nchannels - return type, rate, nchannels, data_size/frame_size, sample_bits - -tests.append(test_au) - - -def test_hcom(h, f): - if h[65:69] <> 'FSSD' or h[128:132] <> 'HCOM': - return None - divisor = get_long_be(h[128+16:128+20]) - return 'hcom', 22050/divisor, 1, -1, 8 - -tests.append(test_hcom) - - -def test_voc(h, f): - if h[:20] <> 'Creative Voice File\032': - return None - sbseek = get_short_le(h[20:22]) - rate = 0 - if 0 <= sbseek < 500 and h[sbseek] == '\1': - ratecode = ord(h[sbseek+4]) - rate = int(1000000.0 / (256 - ratecode)) - return 'voc', rate, 1, -1, 8 - -tests.append(test_voc) - - -def test_wav(h, f): - # 'RIFF' <len> 'WAVE' 'fmt ' <len> - if h[:4] <> 'RIFF' or h[8:12] <> 'WAVE' or h[12:16] <> 'fmt ': - return None - style = get_short_le(h[20:22]) - nchannels = get_short_le(h[22:24]) - rate = get_long_le(h[24:28]) - sample_bits = get_short_le(h[34:36]) - return 'wav', rate, nchannels, -1, sample_bits - -tests.append(test_wav) - - -def test_8svx(h, f): - if h[:4] <> 'FORM' or h[8:12] <> '8SVX': - return None - # Should decode it to get #channels -- assume always 1 - return '8svx', 0, 1, 0, 8 - -tests.append(test_8svx) - - -def test_sndt(h, f): - if h[:5] == 'SOUND': - nsamples = get_long_le(h[8:12]) - rate = get_short_le(h[20:22]) - return 'sndt', rate, 1, nsamples, 8 - -tests.append(test_sndt) - - -def test_sndr(h, f): - if h[:2] == '\0\0': - rate = get_short_le(h[2:4]) - if 4000 <= rate <= 25000: - return 'sndr', rate, 1, -1, 8 - -tests.append(test_sndr) - - -#---------------------------------------------# -# Subroutines to extract numbers from strings # -#---------------------------------------------# - -def get_long_be(s): - return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3]) - -def get_long_le(s): - return (ord(s[3])<<24) | (ord(s[2])<<16) | (ord(s[1])<<8) | ord(s[0]) - -def get_short_be(s): - return (ord(s[0])<<8) | ord(s[1]) - -def get_short_le(s): - return (ord(s[1])<<8) | ord(s[0]) - - -#--------------------# -# Small test program # -#--------------------# - -def test(): - import sys - recursive = 0 - if sys.argv[1:] and sys.argv[1] == '-r': - del sys.argv[1:2] - recursive = 1 - try: - if sys.argv[1:]: - testall(sys.argv[1:], recursive, 1) - else: - testall(['.'], recursive, 1) - except KeyboardInterrupt: - sys.stderr.write('\n[Interrupted]\n') - sys.exit(1) - -def testall(list, recursive, toplevel): - import sys - import os - for filename in list: - if os.path.isdir(filename): - print filename + '/:', - if recursive or toplevel: - print 'recursing down:' - import glob - names = glob.glob(os.path.join(filename, '*')) - testall(names, recursive, 0) - else: - print '*** directory (use -r) ***' - else: - print filename + ':', - sys.stdout.flush() - try: - print what(filename) - except IOError: - print '*** not found ***' diff --git a/Lib/whrandom.py b/Lib/whrandom.py deleted file mode 100644 index 8ed39c923c..0000000000 --- a/Lib/whrandom.py +++ /dev/null @@ -1,98 +0,0 @@ -# WICHMANN-HILL RANDOM NUMBER GENERATOR -# -# Wichmann, B. A. & Hill, I. D. (1982) -# Algorithm AS 183: -# An efficient and portable pseudo-random number generator -# Applied Statistics 31 (1982) 188-190 -# -# see also: -# Correction to Algorithm AS 183 -# Applied Statistics 33 (1984) 123 -# -# McLeod, A. I. (1985) -# A remark on Algorithm AS 183 -# Applied Statistics 34 (1985),198-200 -# -# -# USE: -# whrandom.random() yields double precision random numbers -# uniformly distributed between 0 and 1. -# -# whrandom.seed(x, y, z) must be called before whrandom.random() -# to seed the generator -# -# There is also an interface to create multiple independent -# random generators, and to choose from other ranges. - - -# Translated by Guido van Rossum from C source provided by -# Adrian Baddeley. - - -class whrandom: - # - # Initialize an instance. - # Without arguments, initialize from current time. - # With arguments (x, y, z), initialize from them. - # - def __init__(self, x = 0, y = 0, z = 0): - self.seed(x, y, z) - # - # Set the seed from (x, y, z). - # These must be integers in the range [0, 256). - # - def seed(self, x = 0, y = 0, z = 0): - if not type(x) == type(y) == type(z) == type(0): - raise TypeError, 'seeds must be integers' - if not 0 <= x < 256 and 0 <= y < 256 and 0 <= z < 256: - raise ValueError, 'seeds must be in range(0, 256)' - if 0 == x == y == z: - # Initialize from current time - import time - t = int(time.time() % 0x80000000) - t, x = divmod(t, 256) - t, y = divmod(t, 256) - t, z = divmod(t, 256) - self._seed = (x, y, z) - # - # Get the next random number in the range [0.0, 1.0). - # - def random(self): - x, y, z = self._seed - # - x1, x2 = divmod(x, 177) - y1, y2 = divmod(y, 176) - z1, z2 = divmod(z, 178) - # - x = (171 * x2 - 2 * x1) % 30269 - y = (172 * y2 - 35 * y1) % 30307 - z = (170 * z2 - 63 * z1) % 30323 - # - self._seed = x, y, z - # - return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0 - # - # Get a random number in the range [a, b). - # - def uniform(self, a, b): - return a + (b-a) * self.random() - # - # Get a random integer in the range [a, b] including both end points. - # - def randint(self, a, b): - return a + int(self.random() * (b+1-a)) - # - # Choose a random element from a non-empty sequence. - # - def choice(self, seq): - return seq[int(self.random() * len(seq))] - - -# Initialize from the current time -# -_inst = whrandom() -seed = _inst.seed -random = _inst.random -uniform = _inst.uniform -randint = _inst.randint -choice = _inst.choice diff --git a/Lib/zmod.py b/Lib/zmod.py deleted file mode 100644 index 4f03626390..0000000000 --- a/Lib/zmod.py +++ /dev/null @@ -1,94 +0,0 @@ -# module 'zmod' - -# Compute properties of mathematical "fields" formed by taking -# Z/n (the whole numbers modulo some whole number n) and an -# irreducible polynomial (i.e., a polynomial with only complex zeros), -# e.g., Z/5 and X**2 + 2. -# -# The field is formed by taking all possible linear combinations of -# a set of d base vectors (where d is the degree of the polynomial). -# -# Note that this procedure doesn't yield a field for all combinations -# of n and p: it may well be that some numbers have more than one -# inverse and others have none. This is what we check. -# -# Remember that a field is a ring where each element has an inverse. -# A ring has commutative addition and multiplication, a zero and a one: -# 0*x = x*0 = 0, 0+x = x+0 = x, 1*x = x*1 = x. Also, the distributive -# property holds: a*(b+c) = a*b + b*c. -# (XXX I forget if this is an axiom or follows from the rules.) - -import poly - - -# Example N and polynomial - -N = 5 -P = poly.plus(poly.one(0, 2), poly.one(2, 1)) # 2 + x**2 - - -# Return x modulo y. Returns >= 0 even if x < 0. - -def mod(x, y): - return divmod(x, y)[1] - - -# Normalize a polynomial modulo n and modulo p. - -def norm(a, n, p): - a = poly.modulo(a, p) - a = a[:] - for i in range(len(a)): a[i] = mod(a[i], n) - a = poly.normalize(a) - return a - - -# Make a list of all n^d elements of the proposed field. - -def make_all(mat): - all = [] - for row in mat: - for a in row: - all.append(a) - return all - -def make_elements(n, d): - if d == 0: return [poly.one(0, 0)] - sub = make_elements(n, d-1) - all = [] - for a in sub: - for i in range(n): - all.append(poly.plus(a, poly.one(d-1, i))) - return all - -def make_inv(all, n, p): - x = poly.one(1, 1) - inv = [] - for a in all: - inv.append(norm(poly.times(a, x), n, p)) - return inv - -def checkfield(n, p): - all = make_elements(n, len(p)-1) - inv = make_inv(all, n, p) - all1 = all[:] - inv1 = inv[:] - all1.sort() - inv1.sort() - if all1 == inv1: print 'BINGO!' - else: - print 'Sorry:', n, p - print all - print inv - -def rj(s, width): - if type(s) <> type(''): s = `s` - n = len(s) - if n >= width: return s - return ' '*(width - n) + s - -def lj(s, width): - if type(s) <> type(''): s = `s` - n = len(s) - if n >= width: return s - return s + ' '*(width - n) diff --git a/Mac/MPW/buildall b/Mac/MPW/buildall deleted file mode 100644 index 5b1794ae72..0000000000 --- a/Mac/MPW/buildall +++ /dev/null @@ -1,29 +0,0 @@ -Set Defines "-d MPW -d HAVE_CONFIG_H" -Set Includes "-i :: -i ::Include -i ::Mac" -Set SymOptions "-sym off" -Set ModelOptions "-model far" -Set OtherOptions "-warnings off" -Set LinkOptions "{SymOptions} {ModelOptions}" -Set COptions "{OtherOptions} {SymOptions} {ModelOptions} {Defines} {Includes}" -# For compiling code resources; Restrictions apply -Set ResCOptions "{SymOptions} -model near -b {Defines} {Includes} " - -Export ResCOptions -Export COptions -Export LinkOptions - -# modules with the source in a single sub directory -Date -Directory {Python} -for MODULE in Parser Mac Modules Objects Python - Directory :{MODULE}: - Echo "### `Directory`: make {1}" - make {1} > makefile.out - makefile.out - Directory :: -end - -Echo "### `Directory`: make {1}" -make {1} > makefile.out -makefile.out - diff --git a/Mac/Unsupported/mactcp/dnrglue.c b/Mac/Unsupported/mactcp/dnrglue.c deleted file mode 100644 index 5474b73ced..0000000000 --- a/Mac/Unsupported/mactcp/dnrglue.c +++ /dev/null @@ -1,301 +0,0 @@ -/* DNR.c - DNR library for MPW - - (c) Copyright 1988 by Apple Computer. All rights reserved - - Modifications by Jim Matthews, Dartmouth College, 5/91 - Again modified for use with python by Jack Jansen, CWI, October 1994. - -*/ - -#include <Traps.h> -#include <OSUtils.h> -#include <Errors.h> -#include <Files.h> -#include <Resources.h> -#include <Memory.h> -#include <Traps.h> -#include <GestaltEqu.h> -#include <Folders.h> -#include <ToolUtils.h> -#include <MacTCPCommonTypes.h> -#include "AddressXlation.h" - -TrapType GetTrapType(unsigned long theTrap); -Boolean TrapAvailable(unsigned long trap); -void GetSystemFolder(short *vRefNumP, long *dirIDP); -void GetCPanelFolder(short *vRefNumP, long *dirIDP); -short SearchFolderForDNRP(long targetType, long targetCreator, short vRefNum, long dirID); -short OpenOurRF(void); - -#define OPENRESOLVER 1L -#define CLOSERESOLVER 2L -#define STRTOADDR 3L -#define ADDRTOSTR 4L -#define ENUMCACHE 5L -#define ADDRTONAME 6L -#define HINFO 7L -#define MXINFO 8L - -Handle codeHndl = nil; - -OSErrProcPtr dnr = nil; - -TrapType GetTrapType(theTrap) -unsigned long theTrap; -{ - if (BitAnd(theTrap, 0x0800) > 0) - return(ToolTrap); - else - return(OSTrap); - } - -Boolean TrapAvailable(trap) -unsigned long trap; -{ -TrapType trapType = ToolTrap; -unsigned long numToolBoxTraps; - - if (NGetTrapAddress(_InitGraf, ToolTrap) == NGetTrapAddress(0xAA6E, ToolTrap)) - numToolBoxTraps = 0x200; - else - numToolBoxTraps = 0x400; - - trapType = GetTrapType(trap); - if (trapType == ToolTrap) { - trap = BitAnd(trap, 0x07FF); - if (trap >= numToolBoxTraps) - trap = _Unimplemented; - } - return(NGetTrapAddress(trap, trapType) != NGetTrapAddress(_Unimplemented, ToolTrap)); - -} - -void GetSystemFolder(short *vRefNumP, long *dirIDP) -{ - SysEnvRec info; - long wdProcID; - - SysEnvirons(1, &info); - if (GetWDInfo(info.sysVRefNum, vRefNumP, dirIDP, &wdProcID) != noErr) { - *vRefNumP = 0; - *dirIDP = 0; - } - } - -void GetCPanelFolder(short *vRefNumP, long *dirIDP) -{ - Boolean hasFolderMgr = false; - long feature; - - if (Gestalt(gestaltFindFolderAttr, &feature) == noErr) hasFolderMgr = true; - if (!hasFolderMgr) { - GetSystemFolder(vRefNumP, dirIDP); - return; - } - else { - if (FindFolder(kOnSystemDisk, kControlPanelFolderType, kDontCreateFolder, vRefNumP, dirIDP) != noErr) { - *vRefNumP = 0; - *dirIDP = 0; - } - } - } - -/* SearchFolderForDNRP is called to search a folder for files that might - contain the 'dnrp' resource */ -short SearchFolderForDNRP(long targetType, long targetCreator, short vRefNum, long dirID) -{ - HParamBlockRec fi; - Str255 filename; - short refnum; - - fi.fileParam.ioCompletion = nil; - fi.fileParam.ioNamePtr = filename; - fi.fileParam.ioVRefNum = vRefNum; - fi.fileParam.ioDirID = dirID; - fi.fileParam.ioFDirIndex = 1; - - while (PBHGetFInfo(&fi, false) == noErr) { - /* scan system folder for driver resource files of specific type & creator */ - if (fi.fileParam.ioFlFndrInfo.fdType == targetType && - fi.fileParam.ioFlFndrInfo.fdCreator == targetCreator) { - /* found the MacTCP driver file? */ - refnum = HOpenResFile(vRefNum, dirID, filename, fsRdPerm); - if (GetIndResource('dnrp', 1) == NULL) - CloseResFile(refnum); - else - return refnum; - } - /* check next file in system folder */ - fi.fileParam.ioFDirIndex++; - fi.fileParam.ioDirID = dirID; /* PBHGetFInfo() clobbers ioDirID */ - } - return(-1); - } - -/* OpenOurRF is called to open the MacTCP driver resources */ - -short OpenOurRF() -{ - short refnum; - short vRefNum; - long dirID; - - /* first search Control Panels for MacTCP 1.1 */ - GetCPanelFolder(&vRefNum, &dirID); - refnum = SearchFolderForDNRP('cdev', 'ztcp', vRefNum, dirID); - if (refnum != -1) return(refnum); - - /* next search System Folder for MacTCP 1.0.x */ - GetSystemFolder(&vRefNum, &dirID); - refnum = SearchFolderForDNRP('cdev', 'mtcp', vRefNum, dirID); - if (refnum != -1) return(refnum); - - /* finally, search Control Panels for MacTCP 1.0.x */ - GetCPanelFolder(&vRefNum, &dirID); - refnum = SearchFolderForDNRP('cdev', 'mtcp', vRefNum, dirID); - if (refnum != -1) return(refnum); - - return -1; - } - - -OSErr OpenResolver(fileName) -char *fileName; -{ - short refnum; - OSErr rc; - - if (dnr != nil) - /* resolver already loaded in */ - return(noErr); - - /* open the MacTCP driver to get DNR resources. Search for it based on - creator & type rather than simply file name */ - refnum = OpenOurRF(); - - /* ignore failures since the resource may have been installed in the - System file if running on a Mac 512Ke */ - - /* load in the DNR resource package */ - codeHndl = GetIndResource('dnrp', 1); - if (codeHndl == nil) { - /* can't open DNR */ - return(ResError()); - } - - DetachResource(codeHndl); - if (refnum != -1) { - CloseWD(refnum); - CloseResFile(refnum); - } - - /* lock the DNR resource since it cannot be reloated while opened */ - HLock(codeHndl); - dnr = (OSErrProcPtr) *codeHndl; - - /* call open resolver */ - rc = (*dnr)(OPENRESOLVER, fileName); - if (rc != noErr) { - /* problem with open resolver, flush it */ - HUnlock(codeHndl); - DisposHandle(codeHndl); - dnr = nil; - } - return(rc); - } - - -OSErr CloseResolver() -{ - if (dnr == nil) - /* resolver not loaded error */ - return(notOpenErr); - - /* call close resolver */ - (void) (*dnr)(CLOSERESOLVER); - - /* release the DNR resource package */ - HUnlock(codeHndl); - DisposHandle(codeHndl); - dnr = nil; - return(noErr); - } - -OSErr StrToAddr(hostName, rtnStruct, resultproc, userDataPtr) -char *hostName; -struct hostInfo *rtnStruct; -ResultProcPtr resultproc; -char *userDataPtr; -{ - if (dnr == nil) - /* resolver not loaded error */ - return(notOpenErr); - - return((*dnr)(STRTOADDR, hostName, rtnStruct, resultproc, userDataPtr)); - } - -OSErr AddrToStr(addr, addrStr) -unsigned long addr; -char *addrStr; -{ - if (dnr == nil) - /* resolver not loaded error */ - return(notOpenErr); - - (*dnr)(ADDRTOSTR, addr, addrStr); - return(noErr); - } - -OSErr EnumCache(resultproc, userDataPtr) -EnumResultProcPtr resultproc; -char *userDataPtr; -{ - if (dnr == nil) - /* resolver not loaded error */ - return(notOpenErr); - - return((*dnr)(ENUMCACHE, resultproc, userDataPtr)); - } - - -OSErr AddrToName(addr, rtnStruct, resultproc, userDataPtr) -unsigned long addr; -struct hostInfo *rtnStruct; -ResultProcPtr resultproc; -char *userDataPtr; -{ - if (dnr == nil) - /* resolver not loaded error */ - return(notOpenErr); - - return((*dnr)(ADDRTONAME, addr, rtnStruct, resultproc, userDataPtr)); - } - - -extern OSErr HInfo(hostName, returnRecPtr, resultProc, userDataPtr) -char *hostName; -struct returnRec *returnRecPtr; -ResultProc2Ptr resultProc; -char *userDataPtr; -{ - if (dnr == nil) - /* resolver not loaded error */ - return(notOpenErr); - - return((*dnr)(HINFO, hostName, returnRecPtr, resultProc, userDataPtr)); - - } - -extern OSErr MXInfo(hostName, returnRecPtr, resultProc, userDataPtr) -char *hostName; -struct returnRec *returnRecPtr; -ResultProc2Ptr resultProc; -char *userDataPtr; -{ - if (dnr == nil) - /* resolver not loaded error */ - return(notOpenErr); - - return((*dnr)(MXINFO, hostName, returnRecPtr, resultProc, userDataPtr)); - - } \ No newline at end of file diff --git a/Mac/errno_unix.h b/Mac/errno_unix.h deleted file mode 100644 index 00fbe5a0f8..0000000000 --- a/Mac/errno_unix.h +++ /dev/null @@ -1,18 +0,0 @@ - -#define ENOTDIR (-120) -#define EACCES (-54) -#define EEXIST (-48) -#define EBUSY (-47) -#define EROFS (-44) -#define ENOENT (-43) -#define ENFILE (-42) -#define EIO (-36) -#define ENOSPC (-34) - -#define ESRCH 3 -#define EINTR 4 -#define EBADF 9 -#define ENODEV 19 -#define EINVAL 22 -#define EMFILE 24 - diff --git a/Mac/fopenRF.c b/Mac/fopenRF.c deleted file mode 100644 index 04f192e434..0000000000 --- a/Mac/fopenRF.c +++ /dev/null @@ -1,336 +0,0 @@ - -/* - * fopen.c - * - * Copyright (c) 1991 Symantec Corporation. All rights reserved. - * - */ - -#include <MacHeaders> - -#include "stdio.h" -#include "errno.h" -#include "string.h" -#include "ansi_private.h" - -extern long _ftype, _fcreator; - -#define fcbVPtr(fcb) (* (VCB **) (fcb + 20)) -#define fcbDirID(fcb) (* (long *) (fcb + 58)) -#define fcbCName(fcb) (fcb + 62) - -static void setfiletype(StringPtr, int); -static void stdio_exit(void); -static int fileio(FILE *, int); -static int close(FILE *); -static void replace(unsigned char *, size_t, int, int); - -FILE *freopenRF(); -FILE *__openRF(); - -FILE * -fopenRF(const char *filename, const char *mode) -{ - return(freopenRF(filename, mode, __getfile())); -} - - -FILE * -freopenRF(const char *filename, const char *mode, FILE *fp) -{ - int omode, oflag; - - /* interpret "rwa" */ - - if (mode[0] == 'r') { - omode = fsRdPerm; - oflag = 0; - } - else if (mode[0] == 'w') { - omode = fsWrPerm; - oflag = F_CREAT+F_TRUNC; - } - else if (mode[0] == 'a') { - omode = fsWrPerm; - oflag = F_CREAT+F_APPEND; - } - else { - errno = EINVAL; - return(NULL); - } - - /* interpret "b+" */ - - if (mode[1] == 'b') { - oflag |= F_BINARY; - if (mode[2] == '+') - omode = fsRdWrPerm; - } - else if (mode[1] == '+') { - omode = fsRdWrPerm; - if (mode[2] == 'b') - oflag |= F_BINARY; - } - - /* open the file */ - - return(__openRF(filename, omode, oflag, fp)); -} - - -FILE * -__openRF(const char *filename, int omode, int oflag, FILE *fp) -{ - IOParam pb; - char pname[FILENAME_MAX]; - - if (fp == NULL) - return(NULL); - fclose(fp); - - /* set up pb */ - - pb.ioNamePtr = __c2p(filename, pname); - pb.ioVRefNum = 0; - pb.ioVersNum = 0; - pb.ioPermssn = omode; - pb.ioMisc = 0; - - /* create file */ - - if (oflag & F_CREAT) { - PBCreateSync((ParmBlkPtr)&pb); - if (pb.ioResult == noErr) - oflag &= ~F_TRUNC; - else if (pb.ioResult == dupFNErr && !(oflag & F_EXCL)) - oflag &= ~F_CREAT; - else { - errno = pb.ioResult; - return(NULL); - } - } - - /* open file */ - - PBOpenRFSync((ParmBlkPtr)&pb); - if (pb.ioResult) { - errno = pb.ioResult; - if (oflag & F_CREAT) - PBDeleteSync((ParmBlkPtr)&pb); - return(NULL); - } - fp->refnum = pb.ioRefNum; - - /* get/set file length */ - - if (oflag & F_TRUNC) - PBSetEOFSync((ParmBlkPtr)&pb); - else if (!(oflag & F_CREAT)) - PBGetEOFSync((ParmBlkPtr)&pb); - fp->len = (fpos_t) pb.ioMisc; - - /* initialize rest of FILE structure */ - - if (oflag & F_APPEND) { - fp->append = 1; - fp->pos = fp->len; - } - if (oflag & F_BINARY) - fp->binary = 1; - setvbuf(fp, NULL, _IOFBF, BUFSIZ); - fp->proc = fileio; - - /* set file type */ - - if (oflag & (F_CREAT|F_TRUNC)) - setfiletype(pb.ioNamePtr, oflag); - - /* done */ - - __atexit_stdio(stdio_exit); - return(fp); -} - - -/* - * setfiletype - set type/creator of new file - * - */ - -static void -setfiletype(StringPtr name, int oflag) -{ - FileParam pb; - - pb.ioNamePtr = name; - pb.ioVRefNum = 0; - pb.ioFVersNum = 0; - pb.ioFDirIndex = 0; - if (PBGetFInfoSync((ParmBlkPtr)&pb) == noErr) { - if (oflag & F_BINARY) - pb.ioFlFndrInfo.fdType = _ftype; - else - pb.ioFlFndrInfo.fdType = 'TEXT'; - pb.ioFlFndrInfo.fdCreator = _fcreator; - PBSetFInfoSync((ParmBlkPtr)&pb); - } -} - - -/* - * stdio_exit - stdio shutdown routine - * - */ - -static void -stdio_exit(void) -{ - register FILE *fp; - int n; - - for (fp = &__file[0], n = FOPEN_MAX; n--; fp++) - fclose(fp); -} - - -/* - * fileio - I/O handler proc for files and devices - * - */ - -static int -fileio(FILE *fp, int i) -{ - IOParam pb; - - pb.ioRefNum = fp->refnum; - switch (i) { - - /* read */ - - case 0: - pb.ioBuffer = (Ptr) fp->ptr; - pb.ioReqCount = fp->cnt; - pb.ioPosMode = fp->refnum > 0 ? fsFromStart : fsAtMark; - pb.ioPosOffset = fp->pos - fp->cnt; - PBReadSync((ParmBlkPtr)&pb); - if (pb.ioResult == eofErr) { - fp->pos = pb.ioPosOffset; - if (fp->cnt = pb.ioActCount) - pb.ioResult = 0; - else { - fp->eof = 1; - return(EOF); - } - } - if (!pb.ioResult && !fp->binary) - replace(fp->ptr, fp->cnt, '\r', '\n'); - break; - - /* write */ - - case 1: - pb.ioBuffer = (Ptr) fp->ptr; - pb.ioReqCount = fp->cnt; - pb.ioPosMode = fp->refnum > 0 ? fsFromStart : fsAtMark; - if ((pb.ioPosOffset = fp->pos - fp->cnt) > fp->len) { - pb.ioMisc = (Ptr) pb.ioPosOffset; - if (PBSetEOFSync((ParmBlkPtr)&pb) != noErr) - break; - } - if (!fp->binary) - replace(fp->ptr, fp->cnt, '\n', '\r'); - PBWriteSync((ParmBlkPtr)&pb); - if (!pb.ioResult && pb.ioPosOffset > fp->len) - fp->len = pb.ioPosOffset; - break; - - /* close */ - - case 2: - pb.ioResult = close(fp); - break; - } - - /* done */ - - if (pb.ioResult) { - if (i < 2) { - fp->pos -= fp->cnt; - fp->cnt = 0; - } - fp->err = 1; - errno = pb.ioResult; - return(EOF); - } - return(0); -} - - -static int -close(FILE *fp) -{ - HFileParam pb; - Str255 buf; - register char *fcb = FCBSPtr + fp->refnum; - VCB *vcb = fcbVPtr(fcb); - register char *s; - enum { none, MFS, HFS } del = none; - - pb.ioVRefNum = vcb->vcbVRefNum; - if (fp->remove) { - pb.ioNamePtr = buf; - pb.ioFVersNum = 0; - - /* close temporary file - HFS */ - - if (vcb->vcbSigWord == 0x4244) { - pb.ioDirID = fcbDirID(fcb); - s = fcbCName(fcb); - memcpy(buf, s, Length(s) + 1); - del = HFS; - } - - /* close temporary file - MFS */ - - else if (vcb->vcbSigWord == 0xD2D7) { - for (pb.ioFDirIndex = 1; PBGetFInfoSync((ParmBlkPtr)&pb) == noErr; pb.ioFDirIndex++) { - if (pb.ioFRefNum == fp->refnum) { - del = MFS; - break; - } - } - } - } - - /* close file and flush volume buffer */ - - pb.ioFRefNum = fp->refnum; - if (PBCloseSync((ParmBlkPtr)&pb) == noErr) { - if (del == MFS) - PBDeleteSync((ParmBlkPtr)&pb); - else if (del == HFS) - PBHDeleteSync((HParmBlkPtr)&pb); - pb.ioNamePtr = 0; - PBFlushVolSync((ParmBlkPtr)&pb); - } - return(pb.ioResult); -} - - -/* - * replace - routine for doing CR/LF conversion - * - */ - -static void -replace(register unsigned char *s, register size_t n, register int c1, register int c2) -{ -#pragma options(honor_register) - register unsigned char *t; - - for (; n && (t = memchr(s, c1, n)); s = t) { - *t++ = c2; - n -= t - s; - } -} diff --git a/Mac/mkapplet.py b/Mac/mkapplet.py deleted file mode 100644 index 99486d4878..0000000000 --- a/Mac/mkapplet.py +++ /dev/null @@ -1,257 +0,0 @@ -"""Create an applet from a Python script. - -This puts up a dialog asking for a Python source file ('TEXT'). -The output is a file with the same name but its ".py" suffix dropped. -It is created by copying an applet template and then adding a 'PYC ' -resource named __main__ containing the compiled, marshalled script. -""" - -import sys -sys.stdout = sys.stderr - -import string -import os -import marshal -import imp -import macfs -import MacOS -from Res import * - -# .pyc file (and 'PYC ' resource magic number) -MAGIC = imp.get_magic() - -# Template file (searched on sys.path) -TEMPLATE = "PythonApplet" - -# Specification of our resource -RESTYPE = 'PYC ' -RESNAME = '__main__' - -# A resource with this name sets the "owner" (creator) of the destination -OWNERNAME = "owner resource" - -# OpenResFile mode parameters -READ = 1 -WRITE = 2 - -def main(): - - # Find the template - # (there's no point in proceeding if we can't find it) - - for p in sys.path: - template = os.path.join(p, TEMPLATE) - try: - tmpl = open(template, "rb") - tmpl.close() - break - except IOError: - continue - else: - die("Template %s not found" % `template`) - return - - # Ask for source text if not specified in sys.argv[1:] - - if not sys.argv[1:]: - srcfss, ok = macfs.StandardGetFile('TEXT') - if not ok: - return - filename = srcfss.as_pathname() - tp, tf = os.path.split(filename) - if tf[-3:] == '.py': - tf = tf[:-3] - else: - tf = tf + '.applet' - dstfss, ok = macfs.StandardPutFile('Save application as:', tf) - if not ok: return - process(template, filename, dstfss.as_pathname()) - else: - - # Loop over all files to be processed - for filename in sys.argv[1:]: - process(template, filename, '') - -undefs = ('????', ' ', '\0\0\0\0', 'BINA') - -def process(template, filename, output): - - print "Processing", `filename`, "..." - - # Read the source and compile it - # (there's no point overwriting the destination if it has a syntax error) - - fp = open(filename) - text = fp.read() - fp.close() - try: - code = compile(text, filename, "exec") - except (SyntaxError, EOFError): - die("Syntax error in script %s" % `filename`) - return - - # Set the destination file name - - if string.lower(filename[-3:]) == ".py": - destname = filename[:-3] - rsrcname = destname + '.rsrc' - else: - destname = filename + ".applet" - rsrcname = filename + '.rsrc' - - if output: - destname = output - # Copy the data from the template (creating the file as well) - - tmpl = open(template, "rb") - dest = open(destname, "wb") - data = tmpl.read() - if data: - dest.write(data) - dest.close() - tmpl.close() - - # Copy the creator of the template to the destination - # unless it already got one. Set type to APPL - - tctor, ttype = MacOS.GetCreatorAndType(template) - ctor, type = MacOS.GetCreatorAndType(destname) - if type in undefs: type = 'APPL' - if ctor in undefs: ctor = tctor - - # Open the output resource fork - - try: - output = FSpOpenResFile(destname, WRITE) - except MacOS.Error: - print "Creating resource fork..." - CreateResFile(destname) - output = FSpOpenResFile(destname, WRITE) - - # Copy the resources from the template - - input = FSpOpenResFile(template, READ) - newctor = copyres(input, output) - CloseResFile(input) - if newctor: ctor = newctor - - # Copy the resources from the target specific resource template, if any - - try: - input = FSpOpenResFile(rsrcname, READ) - except MacOS.Error: - pass - else: - newctor = copyres(input, output) - CloseResFile(input) - if newctor: ctor = newctor - - # Now set the creator and type of the destination - - MacOS.SetCreatorAndType(destname, ctor, type) - - # Make sure we're manipulating the output resource file now - - UseResFile(output) - - # Delete any existing 'PYC 'resource named __main__ - - try: - res = Get1NamedResource(RESTYPE, RESNAME) - res.RmveResource() - except Error: - pass - - # Create the raw data for the resource from the code object - - data = marshal.dumps(code) - del code - data = (MAGIC + '\0\0\0\0') + data - - # Create the resource and write it - - id = 0 - while id < 128: - id = Unique1ID(RESTYPE) - res = Resource(data) - res.AddResource(RESTYPE, id, RESNAME) - res.WriteResource() - res.ReleaseResource() - - # Close the output file - - CloseResFile(output) - - # Give positive feedback - - message("Applet %s created." % `destname`) - - -# Copy resources between two resource file descriptors. -# Exception: don't copy a __main__ resource. -# If a resource's name is "owner resource", its type is returned -# (so the caller can use it to set the destination's creator) - -def copyres(input, output): - ctor = None - UseResFile(input) - ntypes = Count1Types() - for itype in range(1, 1+ntypes): - type = Get1IndType(itype) - nresources = Count1Resources(type) - for ires in range(1, 1+nresources): - res = Get1IndResource(type, ires) - id, type, name = res.GetResInfo() - lcname = string.lower(name) - if (type, lcname) == (RESTYPE, RESNAME): - continue # Don't copy __main__ from template - if lcname == OWNERNAME: ctor = type - size = res.SizeResource() - attrs = res.GetResAttrs() - print id, type, name, size, hex(attrs) - res.LoadResource() - res.DetachResource() - UseResFile(output) - try: - res2 = Get1Resource(type, id) - except MacOS.Error: - res2 = None - if res2: - print "Overwriting..." - res2.RmveResource() - res.AddResource(type, id, name) - res.WriteResource() - attrs = attrs | res.GetResAttrs() - print "New attrs =", hex(attrs) - res.SetResAttrs(attrs) - UseResFile(input) - return ctor - - -# Show a message and exit - -def die(str): - message(str) - sys.exit(1) - - -# Show a message - -def message(str, id = 256): - from Dlg import * - d = GetNewDialog(id, -1) - if not d: - print "Error:", `str` - print "DLOG id =", id, "not found." - return - tp, h, rect = d.GetDItem(2) - SetIText(h, str) - while 1: - n = ModalDialog(None) - if n == 1: break - del d - - -if __name__ == '__main__': - main() - diff --git a/Mac/mwerks/mwerks_applet_config.h b/Mac/mwerks/mwerks_applet_config.h deleted file mode 100644 index 269cb4f097..0000000000 --- a/Mac/mwerks/mwerks_applet_config.h +++ /dev/null @@ -1,4 +0,0 @@ -#define HAVE_CONFIG_H -#define USE_STDWIN -#define BUILD_APPLET_TEMPLATE -#define USE_MAC_SHARED_LIBRARY diff --git a/Mac/mwerks/mwerks_config.h b/Mac/mwerks/mwerks_config.h deleted file mode 100644 index e2697a7639..0000000000 --- a/Mac/mwerks/mwerks_config.h +++ /dev/null @@ -1,2 +0,0 @@ -#define HAVE_CONFIG_H -#define USE_STDWIN \ No newline at end of file diff --git a/Mac/mwerks/mwerks_shlib_config.h b/Mac/mwerks/mwerks_shlib_config.h deleted file mode 100644 index 5f060adc45..0000000000 --- a/Mac/mwerks/mwerks_shlib_config.h +++ /dev/null @@ -1,3 +0,0 @@ -#define HAVE_CONFIG_H -#define USE_STDWIN -#define USE_MAC_SHARED_LIBRARY diff --git a/Mac/mwerksglue.c b/Mac/mwerksglue.c deleted file mode 100644 index 37e3a81728..0000000000 --- a/Mac/mwerksglue.c +++ /dev/null @@ -1,43 +0,0 @@ -/* -** Glue code for MetroWerks CodeWarrior, which misses -** unix-like routines for file-access. -*/ - -#ifdef __MWERKS__ -#include <Types.h> -#include <Files.h> -#include <Strings.h> - -#include <stdio.h> -#include <errno.h> - -int -fileno(fp) - FILE *fp; -{ - if (fp==stdin) return 0; - else if (fp==stdout) return 1; - else if (fp==stderr) return 2; - else return 3; -} - -int -isatty(fd) - int fd; -{ - return (fd >= 0 && fd <= 2); -} - -int -unlink(old) - char *old; -{ - OSErr err; - - if ((err=FSDelete(c2pstr(old), 0)) == noErr) - return 0; - errno= err; - return -1; -} - -#endif /* __MWERKS__ */ \ No newline at end of file diff --git a/Makefile.in b/Makefile.in deleted file mode 100644 index ead811808c..0000000000 --- a/Makefile.in +++ /dev/null @@ -1,379 +0,0 @@ -######################################################################## -# Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -# The Netherlands. -# -# All Rights Reserved -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -# Centrum or CWI not be used in advertising or publicity pertaining to -# distribution of the software without specific, written prior permission. -# -# STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -# FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. -######################################################################## - -# Top-level Makefile for Python -# -# As distributed, this file is called Makefile.in; it is processed -# into the real Makefile by running the script ./configure, which -# replaces things like @spam@ with values appropriate for your system. -# This means that if you edit Makefile, your changes get lost the next -# time you run the configure script. Ideally, you can do: -# -# ./configure -# make -# make test -# make install -# -# The top-level Makefile invokes make recursively in a number of -# subdirectories (see the SUBDIRS variable below). If you want to, -# you can invoke make in individual subdirectories. However, the -# sub-Makefiles are also generated by configure, and the quickest way -# to make sure they are up to date is by running make (or "make -# Makefiles") at the top level. This is particularly important for -# Modules/Makefile, which has to be regenerated every time you edit -# Modules/Setup. The python executable is built in the Modules -# directory and then moved to the top-level directory. The recursive -# makes pass three options to subordinate makes: OPT (a quick way to -# change some compiler options; it defaults to -O), prefix and -# exec_prefix (the installation paths). -# -# If recursive makes fail, try invoking make as "make MAKE=make". -# -# See also the section "Build instructions" in the README file. - -# Substitutions by configure -srcdir= @srcdir@ -VPATH= @srcdir@ -RANLIB= @RANLIB@ - -# Machine-dependent subdirectories -MACHDEP= @MACHDEP@ - -# Install prefix for architecture-independent files -prefix= @prefix@ - -# Install prefix for architecture-dependent files -exec_prefix= @exec_prefix@ - -# Expanded directories -MANDIR=$(prefix)/man -BINDIR=$(exec_prefix)/bin -LIBDIR=$(exec_prefix)/lib -INCLUDEDIR=$(prefix)/include -SCRIPTDIR=$(prefix)/lib - -# Symbols used for using shared libraries -SO= @SO@ -LDSHARED= @LDSHARED@ -CCSHARED= @CCSHARED@ -LINKFORSHARED= @LINKFORSHARED@ -DESTSHARED= $(SCRIPTDIR)/python/$(MACHDEP) - -# Shell used by make (some versions default to the login shell, which is bad) -SHELL= /bin/sh - -# Portable install script (configure doesn't always guess right) -INSTALL= @srcdir@/install-sh -c -INSTALL_PROGRAM=${INSTALL} -INSTALL_DATA= ${INSTALL} -m 644 - -# --with-PACKAGE options for configure script -# e.g. --with-readline --with-svr5 --with-solaris --with-thread -# (see README for an explanation) -WITH= - -# Compiler options passed to subordinate makes -OPT= @OPT@ - -# Subdirectories where to run make recursively -SUBDIRS= Parser Objects Python Modules - -# Other subdirectories -SUBDIRSTOO= Include Lib Doc Misc Demo readline Grammar - -# Files and directories to be distributed -CONFIGFILES= configure configure.in acconfig.h config.h.in Makefile.in -DISTFILES= README ChangeLog $(CONFIGFILES) -DISTDIRS= $(SUBDIRS) $(SUBDIRSTOO) Ext-dummy -DIST= $(DISTFILES) $(DISTDIRS) - -# Default target -all: python - -# Build the interpreter -python: Makefiles - for i in $(SUBDIRS); do \ - (echo $$i; cd $$i; \ - $(MAKE) OPT="$(OPT)" \ - prefix="$(prefix)" \ - exec_prefix="$(exec_prefix)" \ - all); \ - done - -# Test the interpreter (twice, once without .pyc files, once with) -TESTPATH= $(srcdir)/Lib:$(srcdir)/Lib/test:./Modules -test: python - -rm -f $(srcdir)/Lib/test/*.pyc - PYTHONPATH=$(TESTPATH) ./python -c 'import autotest' - PYTHONPATH=$(TESTPATH) ./python -c 'import autotest' - -# Install everything -install: bininstall libinstall maninstall inclinstall \ - libainstall sharedinstall - -# Install the interpreter -bininstall: python - for i in $(BINDIR); \ - do \ - if test ! -d $$i; then \ - echo "Creating directory $$i"; \ - mkdir $$i; \ - chmod 755 $$i; \ - else true; \ - fi; \ - done - $(INSTALL_PROGRAM) python $(BINDIR)/python - -# Install the library. -# If your system does not support "cp -r", try "copy -r" or perhaps -# something like find Lib -print | cpio -pacvdmu $(LIBDEST) -LIBDEST= $(SCRIPTDIR)/python -libinstall: python - for i in $(SCRIPTDIR) $(LIBDEST); \ - do \ - if test ! -d $$i; then \ - echo "Creating directory $$i"; \ - mkdir $$i; \ - chmod 755 $$i; \ - else true; \ - fi; \ - done - cp -r $(srcdir)/Lib/* $(LIBDEST) - PYTHONPATH=$(LIBDEST) \ - ./python $(LIBDEST)/compileall.py $(LIBDEST) - $(MAKE) \ - OPT="$(OPT)" \ - SO="$(SO)" \ - LDSHARED="$(LDSHARED)" \ - CCSHARED="$(CCSHARED)" \ - LINKFORSHARED="$(LINKFORSHARED)" \ - DESTSHARED="$(DESTSHARED)" \ - sharedinstall - -# Install the manual page -maninstall: - for i in $(MANDIR) $(MANDIR)/man1; \ - do \ - if test ! -d $$i; then \ - echo "Creating directory $$i"; \ - mkdir $$i; \ - chmod 755 $$i; \ - else true; \ - fi; \ - done - $(INSTALL_DATA) $(srcdir)/Misc/python.man \ - $(MANDIR)/man1/python.1 - -# Install the include files -INCLUDEPY= $(INCLUDEDIR)/Py -inclinstall: - for i in $(INCLUDEDIR) $(INCLUDEPY); \ - do \ - if test ! -d $$i; then \ - echo "Creating directory $$i"; \ - mkdir $$i; \ - chmod 755 $$i; \ - else true; \ - fi; \ - done - $(INSTALL_DATA) $(srcdir)/Include/*.h $(INCLUDEPY) - -# Install the lib*.a files and miscellaneous stuff needed by extensions -LIBP= $(LIBDIR)/python -LIBPL= $(LIBP)/lib -libainstall: all - for i in $(LIBDIR) $(LIBP) $(LIBPL); \ - do \ - if test ! -d $$i; then \ - echo "Creating directory $$i"; \ - mkdir $$i; \ - chmod 755 $$i; \ - else true; \ - fi; \ - done - for i in $(SUBDIRS); do \ - echo $$i; \ - $(INSTALL_DATA) $$i/lib$$i.a $(LIBPL)/lib$$i.a; \ - $(RANLIB) $(LIBPL)/lib$$i.a; \ - done - $(INSTALL_DATA) Modules/config.c $(LIBPL)/config.c - $(INSTALL_DATA) $(srcdir)/Modules/getpath.c $(LIBPL)/getpath.c - $(INSTALL_DATA) $(srcdir)/Modules/config.c.in $(LIBPL)/config.c.in - $(INSTALL_DATA) Modules/Makefile $(LIBPL)/Makefile - $(INSTALL_DATA) Modules/Setup $(LIBPL)/Setup - $(INSTALL_DATA) $(srcdir)/Modules/makesetup $(LIBPL)/makesetup - $(INSTALL_DATA) config.h $(LIBPL)/config.h - $(INSTALL_DATA) $(srcdir)/Python/frozenmain.c $(LIBPL)/frozenmain.c - $(INSTALL_DATA) Modules/main.o $(LIBPL)/main.o - -# Install the dynamically loadable modules -sharedinstall: - cd Modules; $(MAKE) \ - OPT="$(OPT)" \ - SO="$(SO)" \ - LDSHARED="$(LDSHARED)" \ - CCSHARED="$(CCSHARED)" \ - LINKFORSHARED="$(LINKFORSHARED)" \ - DESTSHARED="$(DESTSHARED)" \ - sharedinstall - -# Build the sub-Makefiles -Makefiles: config.status Modules/Makefile.pre - (cd Modules; $(MAKE) -f Makefile.pre Makefile) - for i in . $(SUBDIRS); do \ - (echo $$i; cd $$i; $(MAKE) Makefile); \ - done - -# Build the intermediate Makefile in Modules -Modules/Makefile.pre: config.status - $(SHELL) config.status - -# Build the toplevel Makefile -Makefile: Makefile.in config.status - CONFIG_FILES=Makefile CONFIG_HEADERS= $(SHELL) config.status - -# Run the configure script. If config.status already exists, -# call it with the --recheck argument, which reruns configure with the -# same options as it was run last time; otherwise run the configure -# script with options taken from the $(WITH) variable -config.status: $(srcdir)/configure - if test -f config.status; \ - then $(SHELL) config.status --recheck; \ - $(SHELL) config.status; \ - else $(SHELL) $(srcdir)/configure $(WITH); \ - fi - -.PRECIOUS: config.status python - -# Rerun configure with the same options as it was run last time, -# provided the config.status script exists -recheck: - $(SHELL) config.status --recheck - $(SHELL) config.status - -# Rebuild the configure script from configure.in; also rebuild config.h.in -autoconf: - (cd $(srcdir); autoconf; autoheader) - -# Create a tags file for vi -tags:: - ctags -w -t Include/*.h - for i in $(SUBDIRS); do ctags -w -t -a $$i/*.[ch]; done - sort tags -o tags - -# Create a tags file for GNU Emacs -TAGS:: - etags Include/*.h - for i in $(SUBDIRS); do etags -a $$i/*.[ch]; done - -# Add dependencies to sub-Makefiles -depend: - for i in $(SUBDIRS); do \ - (echo $$i; cd $$i; $(MAKE) depend); \ - done - -# Sanitation targets -- clean leaves libraries, executables and tags -# files, which clobber removes those as well - -localclean: - -rm -f core *~ [@,#]* *.old *.orig *.rej - -clean: localclean - -for i in $(SUBDIRS); do \ - (echo $$i; cd $$i; \ - if test -f Makefile; \ - then $(MAKE) clean; \ - else $(MAKE) -f Makefile.*in clean; \ - fi); \ - done - -localclobber: localclean - -rm -f tags TAGS python - -rm -f config.log config.cache config.h Makefile - -clobber: localclobber - -for i in $(SUBDIRS); do \ - (echo $$i; cd $$i; \ - if test -f Makefile; \ - then $(MAKE) clobber; \ - else $(MAKE) -f $(srcdir)/Makefile.in clobber; \ - fi); \ - done - -# Make things extra clean, before making a distribution -distclean: clobber - -$(MAKE) -f $(srcdir)/Makefile.in \ - SUBDIRS="$(SUBDIRSTOO)" clobber - -rm -f config.status config.log config.cache config.h Makefile - -rm -f Modules/Makefile - -for i in $(SUBDIRS) $(SUBDIRSTOO); do \ - for f in $$i/*.in; do \ - f=`basename "$$f" .in`; \ - if test "$$f" != "*"; then \ - echo rm -f "$$i/$$f"; \ - rm -f "$$i/$$f"; \ - fi; \ - done; \ - done - -# Check for smelly exported symbols (not starting with Py/_Py) -smelly: all - for i in $(SUBDIRS); do \ - echo --- $$i ---; \ - nm -p $$i/lib$$i.a | \ - sed -n "/ [TDB] /s/.* //p" | grep -v "^_*Py" | sort -u; \ - done - -# Find files with funny names -find: - find $(DISTDIRS) -type d \ - -o -name '*.[chs]' \ - -o -name '*.py' \ - -o -name '*.doc' \ - -o -name '*.sty' \ - -o -name '*.bib' \ - -o -name '*.dat' \ - -o -name '*.el' \ - -o -name '*.fd' \ - -o -name '*.in' \ - -o -name '*.tex' \ - -o -name '*,[vpt]' \ - -o -name 'Setup' \ - -o -name 'Setup.*' \ - -o -name README \ - -o -name Makefile \ - -o -name ChangeLog \ - -o -name RCS \ - -o -name Repository \ - -o -name Entries \ - -o -name Tag \ - -o -name tags \ - -o -name TAGS \ - -o -name .cvsignore \ - -o -name MANIFEST \ - -o -print - -# Build a distribution tar file (run make distclean first) -# (This leaves the RCS and CVS directories in :-( ) -tar: - tar cf - $(DIST) | gzip --best >dist.tar.gz diff --git a/Misc/ACKS b/Misc/ACKS deleted file mode 100644 index 42531e18cc..0000000000 --- a/Misc/ACKS +++ /dev/null @@ -1,132 +0,0 @@ -Acknowledgements ----------------- - -This list is not complete and not in any useful order, but I would -like to thank everybody who contributed in any way, with code, hints, -bug reports, ideas, moral support, endorsement, or even complaints.... -Without you I would've stopped working on Python long ago! - - --Guido - -Mark Anacker -Stig Bakken -Ulf Bartelt -Anthony Baxter -Donald Beaudry -Andy Bensky -Eric Beser -Stephen Bevan -Jurjen Bos -Peter Bosch -Eric Bouck -Monty Brandenberg -Terrence Brannon -Dave Brennan -Erik de Bueger -Jan-Hein B"uhrman -Dick Bulterman -Tommy Burnette -Mike Carlton -David Chaum -Steve Clift -Matt Conway -Tom Culliton -John Cugini -Eric Daniel -Jonathan Dasteel -John DeGood -Roger Dev -Fred Drake -Lance Ellinghaus -David Ely -Stoffel Erasmus -Stefan Esser -Paul Everitt -Niels Ferguson -Robin Friedrich -Jim Fulton -Peter Funk -Dag Gruneau -Michael Guravage -Paul ten Hagen -Jun Hamano -Mark Hammond -Barry Hantman -Lynda Hardman -Rycharde Hawkes -Ivan Herman -Kevan Heydon -David Hobley -Chris Hoffman -Philip Homburg -Ken Howard -John Interrante -Jack Jansen -Bill Janssen -Drew Jenkins -Simon Johnston -Lou Kates -Steve Kirsch -Bob Kras -Andrew Kuchling -Soren Larsen -William Lewis -Robert van Liere -Anne Lord -Mark Lutz -Jim Lynch -Tim MacKenzie -Steve Majewski -Ken Manheimer -Roger Masse -Graham Matthews -Michael McLay -Lambert Meertens -Steven Miale -Doug Moen -Skip Montanaro -Sape Mullender -Sjoerd Mullender -George Neville-Neil -Randy Pausch -Marcel van der Peijl -Steven Pemberton -Tim Peters -Adrian Phillips -Amrit Prem -John Redford -Steven Reiz -Timothy Roscoe -Jim Roskind -Kevin Samborn -Michael Scharf -Gregor Schmid -Nick Seidenman -Fred Sells -Denis Severson -Michael Shiplett -Joel Shprentz -Eric Siegerman -Paul Sijben -George Sipe -Dirk Soede -Per Spilling -Jim St. Pierre -Quentin Stafford-Fraser -Richard Stoakley -Casper Stoel -Ken Stox -Tracy Tims -R Lindsay Todd -Bennett Todd -John Tromp -Jaap Vermeulen -Frank Visser -Richard Walker -Barry Warsaw -Steve Waterbury -Bob Watson -Rickard Westman -Dik Winter -hajime@jsk.t.u-tokyo.ac.jp -tim@prl.philips.nl diff --git a/Misc/AIX-NOTES b/Misc/AIX-NOTES deleted file mode 100644 index 97c09449dd..0000000000 --- a/Misc/AIX-NOTES +++ /dev/null @@ -1,61 +0,0 @@ -[Excerpt from an email describing how to build Python on AIX.] - - -Subject: Re: Python 1.0.0 BETA 5 -- also for Macintosh! -From: se@MI.Uni-Koeln.DE (Stefan Esser) -To: Guido.van.Rossum@cwi.nl -Date: Fri, 7 Jan 1994 17:40:43 +0100 - -[...] - -The following are [...] Instructions -to get a clean compile using gcc and xlc -under AIX 3.2.4. - -Since I wanted to make sure that Python compiles -using both compilers and several sets of options -(ANSI and traditional C, optimize on/off) I didn't -try to include bash readline or other optional -modules. - -'make test' succeeded using Python compiled with -the AIX C-compiler invoked as 'cc' and with options -'-o -qMEMMAX=4000' and compiled with 'gcc' and -options '-O -Wall'. - -There were some problems trying to compile python -using 'gcc -ansi' (because of _AIX no longer being -defined), but I didn't have time to look into this. - - - -Regards, - -Stefan Esser - - - - -REQUIRED: ---------- - -1) AIX compilers don't like the LANG env - varaiable set to european locales. - This makes the compiler generate floating - point constants using "," as the decimal - seperator, which the assembler doesnt't - understand (or was it the other way around, - with the assembler expecting "," in float - numbers ???). - Anyway: "LANG=C; export LANG" solves the - problem, as does "LANG=C $(MAKE) ..." in - the master Makefile. - -OPTIONAL: ---------- - -2) The xlc compiler considers "Python/ceval.c" - too complex to optimize, except when invoked - with "-qMEMMAX=4000". - -[...] diff --git a/Misc/BLURB b/Misc/BLURB deleted file mode 100644 index 53cf55b15e..0000000000 --- a/Misc/BLURB +++ /dev/null @@ -1,45 +0,0 @@ -What is Python? ---------------- - -Python is an interpreted, interactive, object-oriented programming -language. It incorporates modules, exceptions, dynamic typing, very -high level dynamic data types, and classes. Python combines -remarkable power with very clear syntax. It has interfaces to many -system calls and libraries, as well as to various window systems, and -is extensible in C or C++. It is also usable as an extension language -for applications that need a programmable interface. Finally, Python -is portable: it runs on many brands of UNIX, on the Mac, and on -MS-DOS. - -As a short example of what Python looks like, here's a script to -print prime numbers (not blazingly fast, but readable!). When this -file is made executable, it is callable directly from the UNIX shell -(if your system supports #! in scripts and the python interpreter is -installed at the indicated place). - -#!/usr/local/bin/python - -# Print prime numbers in a given range - -def main(): - import sys - min, max = 2, 0x7fffffff - if sys.argv[1:]: - min = int(eval(sys.argv[1])) - if sys.argv[2:]: - max = int(eval(sys.argv[2])) - primes(min, max) - -def primes(min, max): - if 2 >= min: print 2 - primes = [2] - i = 3 - while i <= max: - for p in primes: - if i%p == 0 or p*p > i: break - if i%p <> 0: - primes.append(i) - if i >= min: print i - i = i+2 - -main() diff --git a/Misc/BLURB.LUTZ b/Misc/BLURB.LUTZ deleted file mode 100644 index e508207521..0000000000 --- a/Misc/BLURB.LUTZ +++ /dev/null @@ -1,122 +0,0 @@ -Newsgroups: comp.lang.perl,comp.lang.tcl -From: lutz@xvt.com (Mark Lutz) -Subject: Python (was Re: Has anyone done a tk addition to perl?) -Organization: XVT Software Inc. -Date: Thu, 14 Oct 1993 17:10:37 GMT -X-Disclaimer: The views expressed in this message are those of an - individual at XVT Software Inc., and do not necessarily - reflect those of the company. - - -I've gotten a number of requests for information about Python, -since my post here earlier this week. Since this appears to be -of general interest, and since there's no python news group yet, -I'm posting a description here. I'm not the best authority on -the language, but here's my take on it. - -[TCL/Perl zealots: this is informational only; I'm not trying to -'convert' anybody, and don't have time for a language war :-) -There is a paper comparing TCL/Perl/Python/Emacs-Lisp, which is -referenced in the comp.lang.misc faq, I beleive.] - - -What is Python?... - -Python is a relatively new very-high-level language developed -in Amsterdam. Python is a simple, procedural language, with -features taken from ABC, Icon, Modula-3, and C/C++. - -It's central goal is to provide the best of both worlds: -the dynamic nature of scripting languages like Perl/TCL/REXX, -but also support for general programming found in the more -traditional languages like Icon, C, Modula,... - -As such, it can function as a scripting/extension language, -as a rapid prototyping language, and as a serious software -development language. Python is suitable for fast development -of large programs, but also does well at throw-away shell coding. - -Python resembles other scripting languages a number of ways: - - dynamic, interpretive, interactive nature - - no explicit compile or link steps needed - - no type declarations (it's dynamically typed) - - high-level operators ('in', concatenation, etc) - - automatic memory allocation/deallocation (no 'pointers') - - high level objects: lists, tuples, strings, associative arrays - - programs can construct and execute program code using strings - - very fast edit/compile/run cycle; no static linking - - well-defined interface to and from C functions and data - - well-defined ways to add C modules to the system and language - -Python's features that make it useful for serious programming: - - it's object-oriented; it has a simplified subset of - C++'s 'class' facility, made more useful by python's - dynamic typing; the language is object-oriented from - the ground up (rather than being an add-on, as in C++) - - - it supports modules (imported packages, as in Modula-3); - modules replace C's 'include' files and linking, and allow - for multiple-module systems, code sharing, etc.; - - - it has a good exception handling system (a 'try' statement, - and a 'raise' statement, with user-defined exceptions); - - - it's orthogonal; everything is a first-class object in the - language (functions, modules, classes, class instance methods...) - and can be assigned/passed and used generically; - - - it's fairly run-time secure; it does many run-time checks - like index-out-of-bounds, etc., that C usually doesn't; - - - it has general data structuring support; Python lists are - heterogeneous, variable length, nestable, support slicing, - concatenation, etc., and come into existance and are reclaimed - automatically; strings and dictionaries are similarly general; - - - it's got a symbolic debugger and profiler (written in python, - of course..), and an interactive command-line interface; - as in Lisp, you can enter code and test functions in isolation, - from the interactive command line (even linked C functions); - - - it has a large library of built-in modules; it has support - for sockets, regular expressions, posix bindings, etc. - - - it supports dynamic loading of C modules on many platforms; - - - it has a _readable_ syntax; python code looks like normal - programming languages; tcl and perl can be very unreadable - (IMHO; what was that joke about Perl looking the same after - rot13..); python's syntax is simple, and statement based; - - -Of course, Python isn't perfect, but it's a good compromise betweem -scripting languages and traditional ones, and so is widely applicable. -'Perfect' languages aren't always useful for real-world tasks (Prolog, -for example), and languages at either extreme are not useful in the other -domain (C is poor for shell coding and prototyping, and awk is useless -for large systems design; Python does both well). - -For example, I've used Python successfully for a 4K line expert system -shell project; it would have been at least twice as large in C, and would -have been very difficult in TCL or Perl. - -Python uses an indentation-based syntax which may seem unusual at first -to C coders, but after using it I have found it to be _very_ handy, since -there's less to type. [I now forget to type '}' in my C code, and am -busy calculating how much time I wasted typing all those '}', 'END', etc., -just to pander to 'brain-dead' C/Pascal compilers :-)]. - -Python's currently at release 0.9.9. It seems suprisingly stable. -The first 'official' 1.0 release is due out by the end of this year. -Python runs on most popular machines/systems (mac, dos, unix, etc.) -It's public domain and distributable, and can be had via ftp. The -distribution includes examples, tutorials, and documentation. The -latest ftp address I have (I got it on a cd-rom): - pub/python/* at ftp.cwi.nl - pub/? at wuarchive.wustl.edu (in america) - -There's a python mailing list maintained by the language's creator. -Mail 'python-list-request@cwi.nl' to get on it. - -Mark Lutz -lutz@xvt.com diff --git a/Misc/COPYRIGHT b/Misc/COPYRIGHT deleted file mode 100644 index 4d6bc3063c..0000000000 --- a/Misc/COPYRIGHT +++ /dev/null @@ -1,20 +0,0 @@ -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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/Misc/FAQ b/Misc/FAQ deleted file mode 100644 index 72a85c4edd..0000000000 --- a/Misc/FAQ +++ /dev/null @@ -1,2158 +0,0 @@ -Subject: FAQ: Python -- an object-oriented language -Newsgroups: comp.lang.python,comp.answers,news.answers -Followup-to: comp.lang.python -From: guido@cwi.nl (Guido van Rossum) -Reply-to: guido@cnri.reston.va.us (Guido van Rossum) -Expires: Wed, 1 Nov 1995 00:00:00 GMT -Supersedes: <DFMAv8.3Hp@cwi.nl> -Approved: news-answers-request@MIT.Edu - -Archive-name: python-faq/part1 -Submitted-by: Guido van Rossum <guido@cwi.nl> -Version: 1.29 -Last-modified: 11 October 1995 - -This article contains answers to Frequently Asked Questions about -Python (an object-oriented interpreted programming language -- see -the answer to question 1.1 for a short overview). - -Copyright 1993-1995 Guido van Rossum. Unchanged electronic -redistribution of this FAQ is allowed. Printed redistribution only -with permission of the author. No warranties. - -Author's address: - Guido van Rossum - C.N.R.I. - 1895 Preston White Drive - Reston, VA 22091 - U.S.A. -Email: <guido@python.org>, <guido@cnri.reston.va.us>, <guido@cwi.nl> - -The latest version of this FAQ is available by anonymous ftp from -<URL:ftp://ftp.python.org/pub/doc/FAQ>. It will also be posted -regularly to the newsgroups comp.answers <URL:news:comp.answers> and -comp.lang.python <URL:news:comp.lang.python>. - -Many FAQs, including this one, are available by anonymous ftp -<URL:ftp://rtfm.mit.edu/pub/usenet/news.answers/>. The name under -which a FAQ is archived appears in the Archive-name line at the top of -the article. This FAQ is archived as python-faq/part1 -<URL:ftp://rtfm.mit.edu/pub/usenet/news.answers/python-faq/part1>. - -There's a mail server on that machine which will send you files from -the archive by e-mail if you have no ftp access. You send a e-mail -message to <mail-server@rtfm.mit.edu> containing the single word help -in the message body to receive instructions. - -This FAQ is divided in the following chapters: - - 1. General information and availability - 2. Python in the real world - 3. Building Python and Other Known Bugs - 4. Programming in Python - 5. Extending Python - 6. Python's design - 7. Using Python on non-UNIX platforms - -To find the start of a particular chapter, search for the chapter number -followed by a dot and a space at the beginning of a line (e.g. to -find chapter 4 in vi, type /^4\. /). - -Here's an overview of the questions per chapter: - - 1. General information and availability - 1.1. Q. What is Python? - 1.2. Q. Why is it called Python? - 1.3. Q. How do I obtain a copy of the Python source? - 1.4. Q. How do I get documentation on Python? - 1.5. Q. Are there other ftp sites that mirror the Python distribution? - 1.6. Q. Is there a newsgroup or mailing list devoted to Python? - 1.7. Q. Is there a WWW page devoted to Python? - 1.8. Q. Is the Python documentation available on the WWW? - 1.9. Q. Is there a book on Python, or will there be one out soon? - 1.10. Q. Are there any published articles about Python that I can quote? - 1.11. Q. Are there short introductory papers or talks on Python? - 1.12. Q. How does the Python version numbering scheme work? - 1.13. Q. How do I get a beta test version of Python? - 1.14. Q. Are there copyright restrictions on the use of Python? - 1.15. Q. Why was Python created in the first place? - 1.16. Q. What happened to Tim Peters (the author of python-mode.el, and many - entertaining and enlightening pieces of Python email)? - - 2. Python in the real world - 2.1. Q. How many people are using Python? - 2.2. Q. Have any significant projects been done in Python? - 2.3. Q. Are there any commercial projects going on using Python? - 2.4. Q. How stable is Python? - 2.5. Q. When will the next version be released? - 2.6. Q. What new developments are expected for Python in the future? - 2.7. Q. Is it reasonable to propose incompatible changes to Python? - 2.8. Q. What is the future of Python? - 2.9. Q. What is the PSA, anyway? - 2.10. Q. How do I join the PSA? - 2.11. Q. What are the benefits of joining the PSA? - - 3. Building Python and Other Known Bugs - 3.1. Q. Is there a test set? - 3.2. Q. When running the test set, I get complaints about floating point - operations, but when playing with floating point operations I cannot - find anything wrong with them. - 3.3. Q. Link errors after rerunning the configure script. - 3.4. Q. The python interpreter complains about options passed to a - script (after the script name). - 3.5. Q. When building on the SGI, make tries to run python to create - glmodule.c, but python hasn't been built or installed yet. - 3.6. Q. Python built with gcc for the DEC Alpha doesn't work. - 3.7. Q. I use VPATH but some targets are built in the source directory. - 3.8. Q. Trouble building or linking with the GNU readline library. - 3.9. Q. Trouble building Python on Linux. - 3.10. Q. Trouble with prototypes on Ultrix. - 3.11. Q. Trouble with posix.listdir on NeXTSTEP 3.2. - 3.12. Q. Other trouble building Python on platform X. - 3.13. Q. How to configure dynamic loading on Lixux. - 3.14. Q. Under Solaris 2.x, using GCC, how do I use shared libraries? - 3.15. Q. Errors when linking with a shared library containing C++ code. - 3.16. Q. Tk menus or radiobuttons don't work properly in Python 1.2. - 3.17. Q. I built with _tkintermodule.c enabled but get "Tkinter not found". - 3.18. Q. I built with Tk 4.0 but Tkinter complains about the Tk version. - 3.19. Q. Tk doesn't work right on DEC Alpha. - - 4. Programming in Python - 4.1. Q. Is there a source code level debugger with breakpoints, step, - etc.? - 4.2. Q. Can I create an object class with some methods implemented in - C and others in Python (e.g. through inheritance)? (Also phrased as: - Can I use a built-in type as base class?) - 4.3. Q. Is there a curses/termcap package for Python? - 4.4. Q. Is there an equivalent to C's onexit() in Python? - 4.5. Q. When I define a function nested inside another function, the - nested function seemingly can't access the local variables of the - outer function. What is going on? How do I pass local data to a - nested function? - 4.6. Q. How do I iterate over a sequence in reverse order? - 4.7. Q. My program is too slow. How do I speed it up? - 4.8. Q. When I have imported a module, then edit it, and import it - again (into the same Python process), the changes don't seem to take - place. What is going on? - 4.9. Q. How do I find the current module name? - 4.10. Q. I have a module in which I want to execute some extra code - when it is run as a script. How do I find out whether I am running as - a script? - 4.11. Q. I try to run a program from the Demo directory but it fails - with ImportError: No module named ...; what gives? - 4.12. Q. I have successfully built Python with STDWIN but it can't - find some modules (e.g. stdwinevents). - 4.13. Q. What GUI toolkits exist for Python? - 4.14. Q. Are there any interfaces to database packages in Python? - 4.15. Q. Is it possible to write obfuscated one-liners in Python? - 4.16. Q. Is there an equivalent of C's "?:" ternary operator? - 4.17. Q. My class defines __del__ but it is not called when I delete the - object. - 4.18. Q. How do I change the shell environment for programs called - using os.popen() or os.system()? Changing os.environ doesn't work. - 4.19. Q. What is a class? - 4.20. Q. What is a method? - 4.21. Q. What is self? - 4.22. Q. What is a unbound method? - 4.23. Q. How do I call a method defined in a base class from a derived - class that overrides it? - 4.24. Q. How do I call a method from a base class without using the - name of the base class? - 4.25. Q. How can I organize my code to make it easier to change the base - class? - 4.26. Q. How can I find the methods or attributes of an object? - 4.27. Q. I can't seem to use os.read() on a pipe created with os.popen(). - 4.28. Q. How can I create a stand-alone binary from a Python script? - 4.29. Q. What WWW tools are there for Python? - 4.30. Q. How do I run a subprocess with pipes connected to both input - and output? - 4.31. Q. How do I call a function if I have the arguments in a tuple? - 4.32. Q. How do I enable font-lock-mode for Python in Emacs? - 4.33. Q. Is there an inverse to the format operator (a la C's scanf())? - - 5. Extending Python - 5.1. Q. Can I create my own functions in C? - 5.2. Q. Can I create my own functions in C++? - 5.3. Q. How can I execute arbitrary Python statements from C? - 5.4. Q. How can I evaluate an arbitrary Python expression from C? - 5.5. Q. How do I extract C values from a Python object? - 5.6. Q. How do I use mkvalue() to create a tuple of arbitrary length? - 5.7. Q. What happened to mktuple(), featured in an example in the - Extensions manual? - 5.8. Q. How do I call an object's method from C? - 5.9. Q. How do I catch the output from print_error()? - 5.10. Q. How do I access a module written in Python from C? - 5.11. Q. How do I interface to C++ objects from Python? - - 6. Python's design - 6.1. Q. Why isn't there a generic copying operation for objects in Python? - 6.2. Q. Why isn't there a generic way to implement persistent objects - in Python? (Persistent == automatically saved to and restored from - disk.) - 6.3. Q. Why isn't there a switch or case statement in Python? - 6.4. Q. Why does Python use indentation for grouping of statements? - 6.5. Q. Why are Python strings immutable? - 6.6. Q. Why don't strings have methods like index() or sort(), like - lists? - 6.7. Q. Why does Python use methods for some functionality - (e.g. list.index()) but functions for other (e.g. len(list))? - 6.8. Q. Why can't I derive a class from built-in types (e.g. lists or - files)? - 6.9. Q. Why must 'self' be declared and used explicitly in method - definitions and calls? - 6.10. Q. Can't you emulate threads in the interpreter instead of - relying on an OS-specific thread implementation? - 6.11. Q. Why can't lambda forms contain statements? - 6.12. Q. Why is there no more efficient way of iterating over a dictionary - than first constructing the list of keys()? - 6.13. Q. Can Python be compiled to machine code, C or some other language? - 6.14. Q. Why doesn't Python use proper garbage collection? - - 7. Using Python on non-UNIX platforms - 7.1. Q. Is there a Mac version of Python? - 7.2. Q. Is there a DOS version of Python? - 7.3. Q. Is there a Windows 3.1(1) version of Python? - 7.4. Q. Is there a Windows NT version of Python? - 7.5. Q. Is there a Windows 95 version of Python? - 7.6. Q. Is there an OS/2 version of Python? - 7.7. Q. Is there a VMS version of Python? - 7.8. Q. What about IBM mainframes, or other non-UNIX platforms? - 7.9. Q. Where are the source or Makefiles for the non-UNIX versions? - 7.10. Q. What is the status and support for the non-UNIX versions? - 7.11. Q. I have a PC version but it appears to be only a binary. - Where's the library? - 7.12. Q. Where's the documentation for the Mac or PC version? - 7.13. Q. The Mac (PC) version doesn't seem to have any facilities for - creating or editing programs apart from entering it interactively, and - there seems to be no way to save code that was entered interactively. - How do I create a Python program on the Mac (PC)? - -To find a particular question, search for the question number followed -by a dot, a space, and a Q at the beginning of a line (e.g. to find -question 4.2 in vi, type /^4\.2\. Q/). - - -1. General information and availability - ======================================= - -1.1. Q. What is Python? - -A. Python is an interpreted, interactive, object-oriented programming -language. It incorporates modules, exceptions, dynamic typing, very -high level dynamic data types, and classes. Python combines -remarkable power with very clear syntax. It has interfaces to many -system calls and libraries, as well as to various window systems, and -is extensible in C or C++. It is also usable as an extension language -for applications that need a programmable interface. Finally, Python -is portable: it runs on many brands of UNIX, on the Mac, and on PCs -under MS-DOS, Windows, Windows NT, and OS/2. - -To find out more, the best thing to do is to start reading the -tutorial from the documentation set (see a few questions further -down). - -1.2. Q. Why is it called Python? - -A. Apart from being a computer scientist, I'm also a fan of "Monty -Python's Flying Circus" (a BBC comedy series from the seventies, in -the -- unlikely -- case you didn't know). It occurred to me one day -that I needed a name that was short, unique, and slightly mysterious. -And I happened to be reading some scripts from the series at the -time... So then I decided to call my language Python. But Python is -not a joke. And don't you associate it with dangerous reptiles -either! (If you need an icon, use an image of the 16-ton weight from -the TV series or of a can of SPAM :-) - -1.3. Q. How do I obtain a copy of the Python source? - -A. The latest complete Python source distribution is always available -by anonymous ftp, e.g. -<URL:ftp://ftp.python.org/pub/python/src/python1.2.tar.gz>. It is a -gzipped tar file containing the complete C source, LaTeX -documentation, Python library modules, example programs, and several -useful pieces of freely distributable software. This will compile and -run out of the box on most UNIX platforms. (See section 7 for -non-UNIX information.) - -Occasionally a set of patches is issued which has to be applied using -the patch program. These patches are placed in the same directory, -e.g. <URL:ftp://ftp.python.org/pub/python/src/patch1.1.1>. (At the time -of writing, no patches exist for 1.2.) - -An index of said ftp directory can be found in the file INDEX. An -HTML version of the index can be found in the file index.html, -<URL:ftp://ftp.python.org/pub/python/index.html>. - -1.4. Q. How do I get documentation on Python? - -A. The LaTeX source for the documentation is part of the source -distribution. If you don't have LaTeX, the latest Python -documentation set is always available by anonymous ftp, e.g. -<URL:ftp://ftp.python.org/pub/python/doc/postscript.tar.gz>. It is a -gzipped tar file containing PostScript files of the reference manual, -the library manual, and the tutorial. Note that the library manual is -the most important one of the set, as much of Python's power stems -from the standard or built-in types, functions and modules, all of -which are described here. PostScript for a high-level description of -Python is in the file nluug-paper.ps (a separate file on the ftp -site). - -1.5. Q. Are there other ftp sites that mirror the Python distribution? - -A. The following anonymous ftp sites keep mirrors of the Python -distribution: - -USA: - - <URL:ftp://ftp.python.org/pub/python/> - <URL:ftp://gatekeeper.dec.com/pub/plan/python/> - <URL:ftp://ftp.uu.net/languages/python/> - <URL:ftp://ftp.wustl.edu/graphics/graphics/sgi-stuff/python/> - <URL:ftp://ftp.sterling.com/programming/languages/python/> - <URL:ftp://uiarchive.cso.uiuc.edu/pub/lang/python/> - <URL:ftp://ftp.pht.com/mirrors/python/python/> - -Europe: - - <URL:ftp://ftp.cwi.nl/pub/python/> - <URL:ftp://ftp.funet.fi/pub/languages/python/> - <URL:ftp://ftp.sunet.se/pub/lang/python/> - <URL:ftp://unix.hensa.ac.uk/mirrors/uunet/languages/python/> - <URL:ftp://ftp.ibp.fr/pub/python/> - <URL:ftp://ftp.switch.ch/software/sources/python/> - <URL:ftp://ftp.informatik.tu-muenchen.de/pub/comp/programming/languages/python/> - -Australia: - - <URL:ftp://ftp.dstc.edu.au/pub/python/> - -Or try archie on the string "python". - -1.6. Q. Is there a newsgroup or mailing list devoted to Python? - -A. There is a newsgroup, comp.lang.python <URL:news:comp.lang.python>, -and a mailing list. The newsgroup and mailing list are gatewayed into -each other -- if you can read news it's unnecessary to subscribe to -the mailing list. Send e-mail to <python-list-request@cwi.nl> to -(un)subscribe to the mailing list. Hypermail archives of (nearly) -everything posted to the mailing list (and thus the newsgroup) are -available on our WWW server, -<URL:http://www.cwi.nl/~guido/hypermail/index.html>. The raw archives -are also available by ftp, e.g. -<URL:ftp://ftp.python.org/pub/python/mail/mailinglist.gz>. The -uncompressed versions of these files can be read with the standard -UNIX Mail program ("Mail -f file") or with nn ("nn file"). To read -them using MH, you could use "inc -file file". (The archival service -has stopped archiving new articles around the end of April 1995. I -hope to revive it on the PSA server www.python.org sometime in the -future.) - -1.7. Q. Is there a WWW page devoted to Python? - -A. Yes, <URL:http://www.python.org/> is the official Python home page. -At the time of writing, this page is not yet completely operational; -you may have a look at the old Python home page: -<URL:http://www.cwi.nl/~guido/Python.html> or at the U.S. copy: -<URL:http://www.python.org/~guido/Python.html>. - -1.8. Q. Is the Python documentation available on the WWW? - -A. Yes, see <URL:http://www.python.org/> (Python's home page). It -contains pointers to hypertext versions of the whole documentation set -(as hypertext, not just PostScript). - -If you wish to browse this collection of HTML files on your own -machine, it is available bundled up by anonymous ftp, -e.g. <URL:ftp://ftp.python.org/pub/python/doc/html.tar.gz>. - -An Emacs-INFO set containing the library manual is also available by -ftp, e.g. <URL:ftp://ftp.python.org/pub/python/doc/lib-info.tar.gz>. - -1.9. Q. Is there a book on Python, or will there be one out soon? - -A. Mark Lutz is writing a Python book for O'Reilly and Associates, to -be published early 1996. See the outline (in PostScript): -<URL:http://www.python.org/workshops/1995-05/outlinep.eps>. - -1.10. Q. Are there any published articles about Python that I can quote? - -A. So far the only refereed and published article that describes -Python in some detail is: - - Guido van Rossum and Jelke de Boer, "Interactively Testing Remote - Servers Using the Python Programming Language", CWI Quarterly, Volume - 4, Issue 4 (December 1991), Amsterdam, pp 283-303. - -LaTeX source for this paper is available as part of the Python source -distribution. - -See also the next section (supposedly Aaron Watters' paper has been -refereed). - -1.11. Q. Are there short introductory papers or talks on Python? - -A. A recent, very entertaining introduction to Python is the tutorial by -Aaron Watters in UnixWorld Online: - - Aaron R. Watters: "The What, Why, Who, and Where of Python", - <URL:http://www.wcmh.com/uworld/archives/95/tutorial/005.html> - -An olded paper is: - - Guido van Rossum, "An Introduction to Python for UNIX/C - Programmers", in the proceedings of the NLUUG najaarsconferentie - 1993 (dutch UNIX users group meeting November 1993). - -PostScript for this paper and for the slides used for the accompanying -presentation is available by ftp as -<URL:ftp://ftp.python.org/pub/python/doc/nluug-paper.ps> and -<URL:ftp://ftp.python.org/pub/python/doc/nluug-slides.ps>, respectively. - -Slides for a talk on Python that I gave at the Usenix Symposium on -Very High Level Languages in Santa Fe, NM, USA in October 1994 are -available as <URL:ftp://ftp.python.org/pub/python/doc/vhll-slides.ps>. - -1.12. Q. How does the Python version numbering scheme work? - -A. Python versions are numbered A.B.C or A.B. A is the major version -number -- it is only incremented for major changes in functionality or -source structure. B is the minor version number, incremented for less -earth-shattering changes to a release. C is the patchlevel -- it is -incremented for each new patch release. Not all releases have patch -releases. Note that in the past, patches have added significant -changes; in fact the changeover from 0.9.9 to 1.0.0 was the first time -that either A or B changed! - -Beta versions have an additional suffix of "-beta-N" for some small -number N. Note that (for instance) all versions labeled 1.2-beta-N -*precede* the actual release of 1.2. 1.3b1 is short for 1.3-beta-1. - -1.13. Q. How do I get a beta test version of Python? - -A. If there are any beta releases, they are published in the normal -source directory (e.g. <URL:ftp://ftp.python.org/pub/python/src/>). - -1.14. Q. Are there copyright restrictions on the use of Python? - -A. Hardly. You can do anything you want with the source, as long as -you leave the copyrights in, and display those copyrights in any -documentation about Python that you produce. Also, don't use the -author's institute's name in publicity without prior written -permission, and don't hold them responsible for anything (read the -actual copyright for a precise legal wording). - -In particular, if you honor the copyright rules, it's OK to use Python -for commercial use, to sell copies of Python in source or binary form, -or to sell products that enhance Python or incorporate Python (or part -of it) in some form. I would still like to know about all commercial -use of Python! - -1.15. Q. Why was Python created in the first place? - -A. Here's a *very* brief summary of what got me started: - -- I had extensive experience with implementing an interpreted language -in the ABC group at CWI, and from working with this group I had -learned a lot about language design. This is the origin of many -Python features, including the use of indentation for statement -grouping and the inclusion of very-high-level data types (although the -details are all different in Python). - -- I had a number of gripes about the ABC language, but also liked many -of its features. It was impossible to extend the ABC language (or its -implementation) to remedy my complaints -- in fact its lack of -extensibility was one of its biggest problems. - -- I had some experience with using Modula-2+ and talked with the -designers of Modula-3 (and read the M3 report). M3 is the origin of -the syntax and semantics used for exceptions, and some other Python -features. - -- I was working in the Amoeba distributed operating system group at -CWI. We needed a better way to do system administration than by -writing either C programs or Bourne shell scripts, since Amoeba had -its own system call interface which wasn't easily accessible from the -Bourne shell. My experience with error handling in Amoeba made me -acutely aware of the importance of exceptions as a programming -language feature. - -- It occurred to me that a scripting language with a syntax like ABC -but with access to the Amoeba system calls would fill the need. I -realized that it would be foolish to write an Amoeba-specific -language, so I decided that I needed a language that was generally -extensible. - -- During the 1989 Christmas holidays, I had a lot of time on my hand, -so I decided to give it a try. During the next year, while still -mostly working on it in my own time, Python was used in the Amoeba -project with increasing success, and the feedback from colleagues made -me add many early improvements. - -- In February 1991, after just over a year of development, I decided -to post to USENET. The rest is in the Misc/HISTORY file. - -1.16. Q. What happened to Tim Peters (the author of python-mode.el, and many -entertaining and enlightening pieces of Python email)? - -A. He worked at KSR (Kendall Square Research, a start-up building a -new kind of massively parallel processor). When KSR folded down a -couple of years ago, Tim lost his email access. He hasn't surfaced -on the net since then. - - Missing-him-too-ly yours... - -PS: support for Python's Emacs mode (Misc/python-mode.el in the -distribution) has been taken up by Barry Warsaw. Questions about it -should be mailed to <python-mode@python.org>. - - -2. Python in the real world -=========================== - -2.1. Q. How many people are using Python? - -A. I don't know, but the maximum number of simultaneous subscriptions -to the Python mailing list before it was gatewayed into the newsgroup -was about 180 (several of which were local redistribution lists). I -believe that many active Python users don't bother to subscribe to the -list, and now that there's a newsgroup the mailing list subscription -is even less meaningful. I see new names on the newsgroup all the -time and my best guess is that there are currently at least several -thousands of users. - -Another statistic is the number of accesses to the Python WWW server. -Have a look at <URL:http://www.python.org/stats/>. - -2.2. Q. Have any significant projects been done in Python? - -A. Here at CWI (the home of Python), we have written a 20,000 line -authoring environment for transportable hypermedia presentations, a -5,000 line multimedia teleconferencing tool, as well as many many -smaller programs. - -The University of Virginia uses Python to control a virtual reality -engine. Contact: Matt Conway <conway@virginia.edu>. - -The ILU project at Xerox PARC can generate Python glue for ILU -interfaces. See <URL:ftp://ftp.parc.xerox.com/pub/ilu/ilu.html>. - -The University of California, Irvine uses a student administration -system called TELE-Vision written entirely in Python. Contact: Ray -Price <rlprice@uci.edu>. - -See also the next question. - -If you have done a significant project in Python that you'd like to be -included in the list above, send me email! - -2.3. Q. Are there any commercial projects going on using Python? - -A. Several companies have revealed to me that they are planning or -considering use of Python in a future product. - -Sunrise Software has a product out using Python -- they use Python -for a GUI management application and an SNMP network management -application. Contact: <info@sunrise.com>. - -Infoseek uses Python to implement their commercial WWW information -retrieval service <URL:http://www.infoseek.com/>. Contact: -<info@infoseek.com>. - -Paul Everitt of Connecting Minds is planning a Lotus Notes gateway. -Contact: <Paul.Everitt@cminds.com>. Or see their WWW server -<URL:http://www.cminds.com/>. - -KaPRE in Boulder, CO is using Python for on-site customization of C++ -applications, rapid-prototyping/development, -language-based-components, and possibly more. This is pretty solid: -Python's being shipped with their tool-set now, to beta sites. -Contact: <lutz@KaPRE.COM> (Mark Lutz). - -Individuals at many other companies are using Python for internal -development or for as yet unannounced products (witness their -contributions to the Python mailing list or newsgroup). - -SGI has advertised in the Python list looking for Python programmers -for a project involving interactive television. - -See also the workshop minutes at -<URL:http://www.python.org/workshops/> -- in general the WWW server is -more up to date than the FAQ for these issues. - -Python has also been elected as an extension language by MADE, a -consortium supported by the European Committee's ESPRIT program and -consisting of Bull, CWI and some other European companies. Contact: -Ivan Herman <ivan@cwi.nl>. - -If you'd like to be included in the list above, send me email! - -2.4. Q. How stable is Python? - -A. Very stable. While the current version number would suggest it is -in the early stages of development, in fact new, stable releases -(numbered 0.9.x through 1.3) have been coming out roughly every 3 to -6 months for the past four years. - -2.5. Q. When will the next version be released? - -A. Version 1.3 is being released on 13 October 1995. It is too early -to predict when the next release will be necessary, but you can expect -something awesome within half a year! - -2.6. Q. What new developments are expected for Python in the future? - -A. See my Work-In-Progress web page, currently at -<URL:http://www.python.org:~guido/WIP.html>, and the pages for the -Second Python Workshop (best reached via the Python home page, -<URL:http://www.python.org/>). Also follow the newsgroup discussions! - -2.7. Q. Is it reasonable to propose incompatible changes to Python? - -A. In general, no. There are already millions of lines of Python code -around the world, so any changes in the language that invalidates more -than a very small fraction of existing programs has to be frowned -upon. Even if you can provide a conversion program, there still is -the problem of updating all documentation. Providing a gradual -upgrade path is the only way if a feature has to be changed. - -2.8. Q. What is the future of Python? - -A. If I knew, I'd be rich :-) - -Seriously, the formation of the PSA (Pyton Software Activity, see -<URL:http://www.python.org/psa/>) ensures some kind of support even in -the (unlikely! event that I'd be hit by a bus (actually, here in the -US, a car accident would be more likely :-), were to join a nunnery, -or would be head-hunted. A large number of Python users have become -experts at Python programming as well as maintenance of the -implementation, and would easily fill the vacuum created by my -disappearance. - -In the mean time, I have no plans to disappear -- rather, I am -committed to improving Python, and my current benefactor, CNRI (see -<URL:http://www.cnri.reston.va.us>) is just as committed to continue -its support of Python and the PSA. In fact, we have great plans for -Python -- we just can't tell yet! - -2.9. Q. What is the PSA, anyway? - -A. The Python Software Activity <URL:http://www.python.org/psa/> was -created by a number of Python aficionados who want Python to be more -than the product and responsibility of a single individual. It has -found a home at CNRI <URL:http://www.cnri.reston.va.us>. Anybody who -wishes Python well should join the PSA. - -2.10. Q. How do I join the PSA? - -A. The full scoop is available on the web, see -<URL:http://www.python.org/psa/Joining.html>. Summary: send a check -of at least $50 to CNRI/PSA, 1895 Preston White Drive, Suite 100, in -Reston, VA 22091. Full-time students pay $25. Companies can join for -a mere $500. - -2.11. Q. What are the benefits of joining the PSA? - -A. Like National Public Radio, if not enough people join, Python will -wither. Your name will be mentioned on the PSA's web server. -Workshops organized by the PSA <URL:http://www.python.org/workshops/> -are only accessible to PSA members (you can join at the door). The -PSA is working on additional benefits, such as reduced prices for -books and software, and early access to beta versions of Python. - - -3. Building Python and Other Known Bugs -======================================= - -3.1. Q. Is there a test set? - -A. Yes, simply do "import testall" (or "import autotest" if you aren't -interested in the output). The standard modules whose name begins -with "test" together comprise the test. The test set doesn't test -*all* features of Python but it goes a long way to confirm that a new -port is actually working. The Makefile contains an entry "make test" -which runs the autotest module. NOTE: if "make test" fails, run the -tests manually ("import testall") to see what goes wrong before -reporting the error. - -3.2. Q. When running the test set, I get complaints about floating point -operations, but when playing with floating point operations I cannot -find anything wrong with them. - -A. The test set makes occasional unwarranted assumptions about the -semantics of C floating point operations. Until someone donates a -better floating point test set, you will have to comment out the -offending floating point tests and execute similar tests manually. - -3.3. Q. Link errors after rerunning the configure script. - -A. It is generally necessary to run "make clean" after a configuration -change. - -3.4. Q. The python interpreter complains about options passed to a -script (after the script name). - -A. You are probably linking with GNU getopt, e.g. through -liberty. -Don't. The reason for the complaint is that GNU getopt, unlike System -V getopt and other getopt implementations, doesn't consider a -non-option to be the end of the option list. A quick (and compatible) -fix for scripts is to add "--" to the interpreter, like this: - - #! /usr/local/bin/python -- - -You can also use this interactively: - - python -- script.py [options] - -Note that a working getopt implementation is provided in the Python -distribution (in Python/getopt.c) but not automatically used. - -3.5. Q. When building on the SGI, make tries to run python to create -glmodule.c, but python hasn't been built or installed yet. - -A. Comment out the line mentioning glmodule.c in Setup and build a -python without gl first; install it or make sure it is in your $PATH, -then edit the Setup file again to turn on the gl module, and make -again. You don't need to do "make clean"; you do need to run "make -Makefile" in the Modules subdirectory (or just run "make" at the -toplevel). - -3.6. Q. Python built with gcc for the DEC Alpha doesn't work. - -People have reported problems with gcc 2.5.8 up to 2.6.3. The DEC -OSF/1 cc compiler does not have these problems so it's likely a gcc -bug. The latest news is that this has been fixed in Python 1.2 by a -source change (I gave up waiting for a fixed gcc). - -3.7. Q. I use VPATH but some targets are built in the source directory. - -A. On some systems (e.g. Sun), if the target already exists in the -source directory, it is created there instead of in the build -directory. This is usually because you have previously built without -VPATH. Try running "make clobber" in the source directory. - -3.8. Q. Trouble building or linking with the GNU readline library. - -A. Consider using readline 2.0. Some hints: - -- You can use the GNU readline library to improve the interactive user -interface: this gives you line editing and command history when -calling python interactively. You need to configure and build the GNU -readline library before running the configure script. Its sources are -no longer distributed with Python; you can ftp them from any GNU -mirror site, or from its home site -<URL:ftp://slc2.ins.cwru.edu/pub/dist/readline-2.0.tar.gz> (or a -higher version number -- using version 1.x is not recommended). Pass -the Python configure script the option --with-readline=DIRECTORY where -DIRECTORY is the absolute pathname of the directory where you've built -the readline library. Some hints on building and using the readline -library: - -- On SGI IRIX 5, you may have to add the following -to rldefs.h: - - #ifndef sigmask - #define sigmask(sig) (1L << ((sig)-1)) - #endif - -- On most systems, you will have to add #include "rldefs.h" to the -top of several source files, and if you use the VPATH feature, you -will have to add dependencies of the form foo.o: foo.c to the -Makefile for several values of foo. - -- The readline library requires use of the termcap library. A -known problem with this is that it contains entry points which -cause conflicts with the STDWIN and SGI GL libraries. The STDWIN -conflict can be solved (and will be, in the next release of -STDWIN) by adding a line saying '#define werase w_erase' to the -stdwin.h file (in the STDWIN distribution, subdirectory H). The -GL conflict has been solved in the Python configure script by a -hack that forces use of the static version of the termcap library. - -- Check the newsgroup gnu.bash.bug <URL:news:gnu.bash.bug> for -specific problems with the readline library (I don't read this group -but I've been told that it is the place for readline bugs). - -3.9. Q. Trouble building Python on Linux. - -A. If you're building Python 1.2, Slackware 2.2 has a buggy bash -(version 1.14.3) which breaks a sed script that is used to build -Modules/Makefile. Replace /bin/sh with /bin/ash in both makesetup and -Makefile.pre.in. - -In 1.1 and 1.1.1, there's a bug in the reference counting logic of -ternary pow() which is only tripped by very picky mallocs, like the -GNU malloc on Linux. This has been fixed in 1.2. To continue the -tests in 1.1(.1), just disable the tests of pow() with three arguments -from Lib/test/test_b2.py. - -Apart from this, Python builds and runs fine on most Linux versions -(if you run into trouble on an old Linux version, consider upgrading). - -3.10. Q. Trouble with prototypes on Ultrix. - -A. Ultrix cc seems broken -- use gcc, or edit config.h to #undef -HAVE_PROTOTYPES. - -3.11. Q. Trouble with posix.listdir on NeXTSTEP 3.2. - -A. (This often manifests itself as a weird error from the -compileall.py script run by "make libinstall".) - -Don't use gcc, use the Next C compiler (cc). Even though it is -derived from (an old version of) gcc, its interpretation of the -"-posix" switch is different; in this particular case, cc is right and -gcc is wrong. - -3.12. Q. Other trouble building Python on platform X. - -A. Please email the details to <guido@cwi.nl> and I'll look into it. -Please provide as many details as possible. In particular, if you -don't tell me what type of computer and what operating system (and -version) you are using it will be difficult for me to figure out what -is the matter. If you get a specific error message, please email it -to me too. - -3.13. Q. How to configure dynamic loading on Lixux. - -A. There are two answers, depending on whether you are using the new -ELF object format or not. - -For ELF, this seems to be the procedure (thanks to Martin von Loewis): - -Compile Python to an ELF binary. - -In addition, you have to use the following flags: - - - when linking python: -rdynamic -ldl - - when compiling an object that goes into a shared module: -fPIC - - when linking a shared module: -shared -ldl - -Furthermore, it appears that some Python releases did not understand -that Linux has dynamic linking. Python 1.2 did it right, but you -should check wether the generated config.h indicates the use of -ldl -(i.e. dlopen, dlsym). Finally, you can load a shared module by saying -'use foo'. Make sure the module is in your PYTHONPATH. - -For pre-ELF systems (thanks to Andrew Kuchling): - -Pre-ELF Linux requires that you use the GNU DLD library. The stages -of using dynamic libraries on Linux are: - - 1) Get dld 3.2.5 from a Linux site. Be careful here; the most - recent GNU version is 3.2.3, and doesn't support Linux; be sure to - get it from a Linux mirror, not a GNU mirror (3.2.4 should also - work). Compile it and install the library libdld.a somewhere; I - used /usr/local/lib. - - Suitable URLs for the dld distribution are currently: - <URL:ftp://sunsite.unc.edu/pub/Linux/libs/dld-3.2.5.src.tar.gz> and - <URL:ftp://tsx-11.mit.edu/pub/linux/sources/libs/dld-3.2.5.src.tar.gz>. - There's also a binary distribution of it: - <URL:ftp://sunsite.unc.edu/pub/Linux/libs/dld-3.2.5.bin.tar.gz>. - - 2) Get Jack Jansen's DL library; its location is given in the - _Extending Python_ manual as <URL:ftp://ftp.cwi.nl/pub/dynload/>. - Compile it and install libdl.a wherever you put libdld.a. - - 3) Run Python's configure script, giving it the --with-dl-dld option, - which requires a parameter giving the directory where you put the - libraries. - - 4) Recompile Python. - -3.14. Q. Under Solaris 2.x, using GCC, how do I use shared libraries? - -A. Use the linker in /usr/ucb/ld, not the GNU linker. The latter -cannot create shared libraries. - -3.15. Q. Errors when linking with a shared library containing C++ code. - -A. Link the main Python binary with C++. Change the definition of -LINKCC in Modules/Makefile to be your C++ compiler. You may have to -edit config.c slightly to make it compilable with C++. - -3.16. Q. Tk menus or radiobuttons don't work properly in Python 1.2. - -A. There's a bug in Tkinter.py; remove ClassType and InstanceType from -the definition of CallableTypes near the top of Lib/tkinter/Tkinter.py. - -3.17. Q. I built with _tkintermodule.c enabled but get "Tkinter not found". - -A. Tkinter.py (note: upper case T) lives in a subdirectory of Lib, -Lib/tkinter. If you are using the default module search path, you -probably didn't enable the line in the Modules/Setup file defining -TKPATH; if you use the environment variable PYTHONPATH, you'll have to -add the proper tkinter subdirectory. - -3.18. Q. I built with Tk 4.0 but Tkinter complains about the Tk version. - -A. Several things could cause this. You most likely have a Tk 3.6 -installation that wasn't completely eradicated by the Tk 4.0 -installation (which tends to add "4.0" to its installed files). You -may have the Tk 3.6 support library installed in the place where the -Tk 4.0 support files should be (default /usr/local/lib/tk/); you may -have compiled Python with the old tk.h header file (yes, this actually -compiles!); you may actually have linked with Tk 3.6 even though Tk -4.0 is also around. Similar for Tcl 7.4 vs. Tcl 7.3. - -3.19. Q. Tk doesn't work right on DEC Alpha. - -A. You probably compiled either Tcl, Tk or Python with gcc. Don't. -For this platform, which has 64-bit integers, gcc is known to generate -broken code. The standard cc (which comes bundled with the OS!) -works. If you still prefer gcc, at least try recompiling with cc -before reporting problems to the newsgroup or the author; if this -fixes the problem, report the bug to the gcc developers instead. (As -far as we know, there are no problem with gcc on other platforms -- -the instabilities seem to be restricted to the DEC Alpha.) See also -question 3.6. - - -4. Programming in Python -======================== - -4.1. Q. Is there a source code level debugger with breakpoints, step, -etc.? - -A. Yes. Check out module pdb; pdb.help() prints the documentation (or -you can read it as Lib/pdb.doc). If you use the STDWIN option, -there's also a windowing interface, wdb. You can write your own -debugger by using the code for pdb or wdb as an example. - -4.2. Q. Can I create an object class with some methods implemented in -C and others in Python (e.g. through inheritance)? (Also phrased as: -Can I use a built-in type as base class?) - -A. No, but you can easily create a Python class which serves as a -wrapper around a built-in object, e.g. (for dictionaries): - - # A user-defined class behaving almost identical - # to a built-in dictionary. - class UserDict: - def __init__(self): self.data = {} - def __repr__(self): return repr(self.data) - def __cmp__(self, dict): - if type(dict) == type(self.data): - return cmp(self.data, dict) - else: - return cmp(self.data, dict.data) - def __len__(self): return len(self.data) - def __getitem__(self, key): return self.data[key] - def __setitem__(self, key, item): self.data[key] = item - def __delitem__(self, key): del self.data[key] - def keys(self): return self.data.keys() - def items(self): return self.data.items() - def values(self): return self.data.values() - def has_key(self, key): return self.data.has_key(key) - -4.3. Q. Is there a curses/termcap package for Python? - -A. Yes -- Lance Ellinghaus has written a module that interfaces to -System V's "ncurses". If you know a little curses and some Python, -it's straightforward to use. It is part of the standard Python -distribution, but not configured by default -- you must enable it by -editing Modules/Setup. It requires a System V curses implementation. - -You could also consider using the "alfa" (== character cell) version -of STDWIN. (Standard Window System Interface, a portable windowing -system interface by myself <URL:ftp://ftp.cwi.nl/pub/stdwin/>.) This -will also prepare your program for porting to windowing environments -such as X11 or the Macintosh. - -4.4. Q. Is there an equivalent to C's onexit() in Python? - -A. Yes, if you import sys and assign a function to sys.exitfunc, it -will be called when your program exits, is killed by an unhandled -exception, or (on UNIX) receives a SIGHUP or SIGTERM signal. - -4.5. Q. When I define a function nested inside another function, the -nested function seemingly can't access the local variables of the -outer function. What is going on? How do I pass local data to a -nested function? - -A. Python does not have arbitrarily nested scopes. When you need to -create a function that needs to access some data which you have -available locally, create a new class to hold the data and return a -method of an instance of that class, e.g.: - - class MultiplierClass: - def __init__(self, factor): - self.factor = factor - def multiplier(self, argument): - return argument * self.factor - - def generate_multiplier(factor): - return MultiplierClass(factor).multiplier - - twice = generate_multiplier(2) - print twice(10) - # Output: 20 - -An alternative solution uses default arguments, e.g.: - - def generate_multiplier(factor): - def multiplier(arg, fact = factor): - return arg*fact - return multiplier - - twice = generate_multiplier(2) - print twice(10) - # Output: 20 - -4.6. Q. How do I iterate over a sequence in reverse order? - -A. If it is a list, the fastest solution is - - list.reverse() - try: - for x in list: - "do something with x" - finally: - list.reverse() - -This has the disadvantage that while you are in the loop, the list -is temporarily reversed. If you don't like this, you can make a copy. -This appears expensive but is actually faster than other solutions: - - rev = list[:] - rev.reverse() - for x in rev: - <do something with x> - -If it isn't a list, a more general but slower solution is: - - i = len(list) - while i > 0: - i = i-1 - x = list[i] - <do something with x> - -A more elegant solution, is to define a class which acts as a sequence -and yields the elements in reverse order (solution due to Steve -Majewski): - - class Rev: - def __init__(self, seq): - self.forw = seq - def __len__(self): - return len(self.forw) - def __getitem__(self, i): - return self.forw[-(i + 1)] - -You can now simply write: - - for x in Rev(list): - <do something with x> - -Unfortunately, this solution is slowest of all, due to the method -call overhead... - -4.7. Q. My program is too slow. How do I speed it up? - -A. That's a tough one, in general. There are many tricks to speed up -Python code; I would consider rewriting parts in C only as a last -resort. One thing to notice is that function and (especially) method -calls are rather expensive; if you have designed a purely OO interface -with lots of tiny functions that don't do much more than get or set an -instance variable or call another method, you may consider using a -more direct way, e.g. directly accessing instance variables. Also see -the standard module "profile" (described in the file -"python/lib/profile.doc") which makes it possible to find out where -your program is spending most of its time (if you have some patience --- the profiling itself can slow your program down by an order of -magnitude). - -4.8. Q. When I have imported a module, then edit it, and import it -again (into the same Python process), the changes don't seem to take -place. What is going on? - -A. For reasons of efficiency as well as consistency, Python only reads -the module file on the first time a module is imported. (Otherwise a -program consisting of many modules, each of which imports the same -basic module, would read the basic module over and over again.) To -force rereading of a changed module, do this: - - import modname - reload(modname) - -Warning: this technique is not 100% fool-proof. In particular, -modules containing statements like - - from modname import some_objects - -will continue to work with the old version of the imported objects. - -4.9. Q. How do I find the current module name? - -A. A module can find out its own module name by looking at the -(predefined) global variable __name__. If this has the value -'__main__' you are running as a script. - -4.10. Q. I have a module in which I want to execute some extra code -when it is run as a script. How do I find out whether I am running as -a script? - -A. See the previous question. E.g. if you put the following on the -last line of your module, main() is called only when your module is -running as a script: - - if __name__ == '__main__': main() - -4.11. Q. I try to run a program from the Demo directory but it fails -with ImportError: No module named ...; what gives? - -A. This is probably an optional module (written in C!) which hasn't -been configured on your system. This especially happens with modules -like "Tkinter", "stdwin", "gl", "Xt" or "Xm". For Tkinter, STDWIN and -many other modules, see Modules/Setup.in for info on how to add these -modules to your Python, if it is possible at all. Sometimes you will -have to ftp and build another package first (e.g. STDWIN). Sometimes -the module only works on specific platforms (e.g. gl only works on SGI -machines). - -NOTE: if the complaint is about "Tkinter" (upper case T) and you have -already configured module "_tkinter" (lower case t and underscore), -the solution is *not* to rename tkinter to Tkinter or vice versa. -There is probably something wrong with your module search path. Check -out the value of sys.path. - -For X-related modules (Xt and Xm) you will have to do more work: they -are currently not part of the standard Python distribution. You will -have to ftp the Extensions tar file, e.g. -<URL:ftp://ftp.python.org/pub/python/src/extensions.tar.gz> and follow -the instructions there. - -See also the next question. - -4.12. Q. I have successfully built Python with STDWIN but it can't -find some modules (e.g. stdwinevents). - -A. There's a subdirectory of the library directory named 'stdwin' -which should be in the default module search path. There's a line in -Modules/Setup(.in) that you have to enable for this purpose -- -unfortunately in the latest release it's not near the other -STDWIN-related lines so it's easy to miss it. - -4.13. Q. What GUI toolkits exist for Python? - -A. Depending on what platform(s) you are aiming at, there are several. - -- There's a neat object-oriented interface to the Tcl/Tk widget set, -called Tkinter. As of python 1.1, it is part of the standard Python -distribution -- all you need to do is enable it in Modules/Setup -(provided you have already installed Tk and Tcl). This is probably -the easiest to install and use, and the most complete widget set. It -is also very likely that in the future the standard Python GUI API -will be based on or at least look very much like the Tkinter -interface. For more info about Tk, including pointers to the source, -see the Tcl/Tk home page <URL:http://www.sunlabs.com/research/tcl/>. - -- The standard Python distribution comes with an interface to STDWIN, -a platform-independent low-level windowing interface. You have to ftp -the source for STDWIN separately, -e.g. <URL:ftp://ftp.cwi.nl/pub/stdwin/> or gatekeeper.dec.com in -pub/misc/stdwin <URL:ftp://gatekeeper.dec.com/pub/misc/stdwin/>. -STDWIN runs under X11 or the Mac; a Windows port has been attempted -but I can't seem to get it working. Note that STDWIN is really not -powerful enough to implement a modern GUI (no widgets, etc.) and that -I don't have the time to maintain or extend it, so you may be better -off using Tkinter or the Motif interface, unless you require -portability to the Mac (which is also offered by SUIT, by the way -- -see below). - -- For SGI IRIX only, there's an interface to the complete GL (Graphics -Library -- low level but very good 3D capabilities) as well as to -FORMS (a buttons-and-sliders-etc package built on top of GL by Mark -Overmars -- ftp'able from <URL:ftp://ftp.cs.ruu.nl/pub/SGI/FORMS/>). - -- There's an interface to X11, including the Athena and Motif widget -sets (and a few individual widgets, like Mosaic's HTML widget and -SGI's GL widget) in the Extensions set, which is separately ftp'able -<URL:ftp://ftp.python.org/pub/python/src/extensions.tar.gz>. - -- There's an interface to SUIT, the U of Virginia's Simple User -Interface Toolkit; it can be ftp'ed from -<URL:ftp://uvacs.cs.virginia.edu/pub/suit/python/SUIT_python.tar.Z>. -A PC binary of Python 1.0.2 compiled with DJGPP and with SUIT support -built-in has been made available by Antonio Costa -<URL:ftp://asterix.inescn.pt/pub/PC/python/pyt102su.exe> (a -self-extracting archive). Note that the UVa people themselves have -expressed doubts about SUIT, and are planning to build a Python GUI -API based upon Tk (though not necessarily on Tkinter); see -<URL:http://server.cs.virginia.edu/~tnb2d/IT/IT.html>. - -- There's an interface to WAFE, a Tcl interface to the X11 Motif and -Athena widget sets. Last I heard about it it was included in the WAFE -1.0 prerelease -<URL:ftp://ftp.wu-wien.ac.at/pub/src/X11/wafe/wafe-1.0.tar.gz-prerelease>. - -- The NT port by Mark Hammond (see question 7.4) includes an interface -to the Microsoft Foundation Classes and a Python programming -environment using it that's written mostly in Python. See -<URL:ftp://ftp.python.org/pub/python/nt/>. - -- There's an interface to wxWindows. wxWindows is a portable GUI -class library written in C++. It supports XView, Motif, MS-Windows as -targets. There is some support for Macs and CURSES as well. wxWindows -preserves the look and feel of the underlying graphics toolkit. See -the wxPython WWW page at -<URL:http://www.aiai.ed.ac.uk/~jacs/wx/wxpython/wxpython.html>. - -- There's an object-oriented GUI based on the Microsoft Foundation -Classes model called WPY. Programs written in WPY run unchanged and -with native look and feel on NT, Windows 3.1 (using win32s) and on -Unix (using Tk). Source and binaries for NT and Linux are available -in <URL:ftp://ftp.python.org/pub/python/wpy>. - -- Python has been mentioned on the "Futurism" subpage of the Fresco -home page <URL:http://www.faslab.com/fresco/HomePage.html>. "Pesto" -is a Python interface to the CORBA dynamic invocation interface, and -thus Fresco. A Pesto prototype is running and is currently being -packaged up for inclusion in the Fresco snapshot. See also the Pesto -web pages: <URL:http://www.faslab.com/fresco/pesto/Index.html>. - -4.14. Q. Are there any interfaces to database packages in Python? - -A. There's an interface to SYBASE by John Redford -<jredford@lehman.com>. - -There's an interface to metalbase by Lance Ellinghaus -<lance@markv.com>; it is part of the separate Extensions distribution -<URL:ftp://ftp.python.org/pub/python/src/extensions.tar.gz>. - -Anthony Baxter <anthony.baxter@aaii.oz.au> has written an interface to -mSQL (mini-SQL). -<URL:ftp://ftp.python.org/pub/python/contrib/PymSQL.tar.gz>. - -Tom Culliton <culliton@clark.net> has written an Oracle module. -See <URL:ftp://ftp.clark.net/pub/culliton/oramod.tgz>. - -4.15. Q. Is it possible to write obfuscated one-liners in Python? - -A. Yes. See the following three examples, due to Ulf Bartelt: - - # Primes < 1000 - print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0, - map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000))) - - # First 10 Fibonacci numbers - print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f), - range(10)) - - # Mandelbrot set - print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y, - Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM, - Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro, - i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y - >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr( - 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy - ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24) - # \___ ___/ \___ ___/ | | |__ lines on screen - # V V | |______ columns on screen - # | | |__________ maximum of "iterations" - # | |_________________ range on y axis - # |____________________________ range on x axis - -Don't try this at home, kids! - -4.16. Q. Is there an equivalent of C's "?:" ternary operator? - -A. Not directly. In many cases you can mimic a?b:c with "a and b or -c", but there's a flaw: if b is zero (or empty, or None -- anything -that tests false) then c will be selected instead. In many cases you -can prove by looking at the code that this can't happen (e.g. because -b is a constant or has a type that can never be false), but in general -this can be a problem. - -Steve Majewski (or was it Tim Peters?) suggested the following -solution: (a and [b] or [c])[0]. Because [b] is a singleton list it -is never false, so the wrong path is never taken; then applying [0] to -the whole thing gets the b or c that you really wanted. Ugly, but it -gets you there in the rare cases where it is really inconvenient to -rewrite your code using 'if'. - -4.17. Q. My class defines __del__ but it is not called when I delete the -object. - -A. There are several possible reasons for this. - -- The del statement does not necessarily call __del__ -- it simply -decrements the object's reference count, and if this reaches zero -__del__ is called. - -- If your data structures contain circular links (e.g. a tree where -each child has a parent pointer and each parent has a list of -children) the reference counts will never go back to zero. You'll -have to define an explicit close() method which removes those -pointers. Please don't ever call __del__ directly -- __del__ should -call close() and close() should make sure that it can be called more -than once for the same object. - -- If the object has ever been a local variable (or argument, which is -really the same thing) to a function that caught an expression in an -except clause, chances are that a reference to the object still exists -in that function's stack frame as contained in the stack trace. -Normally, deleting (better: assigning None to) sys.exc_traceback will -take care of this. If you a stack was printed for an unhandled -exception in an interactive interpreter, delete sys.last_traceback -instead. - -- There is code that deletes all objects when the interpreter exits, -but if your Python has been configured to support threads, it is not -called (because other threads may still be active). You can define -your own cleanup function using sys.exitfunc (see question 4.4). - -- Finally, there are some obscure bugs if your __del__ method does -complicated things such as updating dictionaries or lists or -references globals. I hope to have fixed these in release 1.2. - -4.18. Q. How do I change the shell environment for programs called -using os.popen() or os.system()? Changing os.environ doesn't work. - -A. Modifying the environment passed to subshells was left out of the -interpreter because there seemed to be no well-established portable -way to do it (in particular, some systems, have putenv(), others have -setenv(), and some have none at all). - -However if all you want is to pass environment variables to the -commands run by os.system() or os.popen(), there's a simple solution: -prefix the command string with a couple of variable assignments and -export statements. The following would be universal for popen: - - import os - from commands import mkarg # nifty routine to add shell quoting - def epopen(cmd, mode, env = {}): - # env is a dictionary of environment variables - prefix = '' - for key, value in env.items(): - prefix = prefix + '%s=%s\n' % (key, mkarg(value)[1:]) - prefix = prefix + 'export %s\n' % key - return os.popen(prefix + cmd, mode) - -4.19. Q. What is a class? - -A. A class is the particular object type that is created by executing -a class statement. Class objects are used as templates, to create -class instance objects, which embody both the data structure and -program routines specific to a datatype. - -4.20. Q. What is a method? - -A. A method is a function that you normally call as -x.name(arguments...) for some object x. The term is used for methods -of classes and class instances as well as for methods of built-in -objects. (The latter have a completely different implementation and -only share the way their calls look in Python code.) Methods of -classes (and class instances) are defined as functions inside the -class definition. - -4.21. Q. What is self? - -A. Self is merely a conventional name for the first argument of a -method -- i.e. a function defined inside a class definition. A method -defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for -some instance x of the class in which the definition occurs; -the called method will think it is called as meth(x, a, b, c). - -4.22. Q. What is a unbound method? - -A. An unbound method is a method defined in a class that is not yet -bound to an instance. You get an unbound method if you ask for a -class attribute that happens to be a function. You get a bound method -if you ask for an instance attribute. A bound method knows which -instance it belongs to and calling it supplies the instance automatically; -an unbound method only knows which class it wants for its first -argument (a derived class is also OK). Calling an unbound method -doesn't "magically" derive the first argument from the context -- you -have to provide it explicitly. - -4.23. Q. How do I call a method defined in a base class from a derived -class that overrides it? - -A. If your class definition starts with "class Derived(Base): ..." -then you can call method meth defined in Base (or one of Base's base -classes) as Base.meth(self, arguments...). Here, Base.meth is an -unbound method (see previous question). - -4.24. Q. How do I call a method from a base class without using the -name of the base class? - -A. DON'T DO THIS. REALLY. I MEAN IT. It appears that you could call -self.__class__.__bases__[0].meth(self, arguments...) but this fails when -a doubly-derived method is derived from your class: for its instances, -self.__class__.__bases__[0] is your class, not its base class -- so -(assuming you are doing this from within Derived.meth) you would start -a recursive call. - -4.25. Q. How can I organize my code to make it easier to change the base -class? - -A. You could define an alias for the base class, assign the real base -class to it before your class definition, and use the alias throughout -your class. Then all you have to change is the value assigned to the -alias. Incidentally, this trick is also handy if you want to decide -dynamically (e.g. depending on availability of resources) which base -class to use. Example: - -BaseAlias = <real base class> -class Derived(BaseAlias): - def meth(self): - BaseAlias.meth(self) - ... - -4.26. Q. How can I find the methods or attributes of an object? - -A. This depends on the object type. - -For an instance x of a user-defined class, instance attributes are -found in the dictionary x.__dict__, and methods and attributes defined -by its class are found in x.__class__.__bases__[i].__dict__ (for i in -range(len(x.__class__.__bases__))). You'll have to walk the tree of -base classes to find *all* class methods and attributes. - -Many, but not all built-in types define a list of their method names -in x.__methods__, and if they have data attributes, their names may be -found in x.__members__. However this is only a convention. - -For more information, read the source of the standard (but -undocumented) module newdir. - -4.27. Q. I can't seem to use os.read() on a pipe created with os.popen(). - -A. os.read() is a low-level function which takes a file descriptor (a -small integer). os.popen() creates a high-level file object -- the -same type used for sys.std{in,out,err} and returned by the builtin -open() function. Thus, to read n bytes from a pipe p created with -os.popen(), you need to use p.read(n). - -4.28. Q. How can I create a stand-alone binary from a Python script? - -The demo script "Demo/scripts/freeze.py" does what you want. (It's -actually not a demo but a support tool -- there is some extra code in -the interpreter to accommodate it.) It requires that you have the -Python build tree handy, complete with all the lib*.a files. - -This works by scanning your source recursively for import statements -(both forms) and looking for the modules on the standard Python path -as well as in the source directory (for built-in modules). It then -"compiles" the modules written in Python to C code (array initializers -that can be turned into code objects using the marshal module) and -creates a custom-made config file that only contains those built-in -modules which are actually used in the program. It then compiles the -generated C code and links it with the rest of the Python interpreter -to form a self-contained binary which acts exactly like your script. - -Hint: the freeze program only works if your script's filename ends in -".py". - -4.29. Q. What WWW tools are there for Python? - -A. There's a whole lot in the 1.2 release; see the section on -"Internet and WWW" in the Library Reference Manual. Highlights: a CGI -parser, a url retriever, an html parser. - -Steve Miale <smiale@cs.indiana.edu> has written a modular WWW browser -called Dancer. An alpha version can be FTP'ed from -<URL:ftp://ftp.cs.indiana.edu/pub/smiale/dancer.tar.gz>. (There are a -few articles about Dancer in the (hyper)mail archive -<URL:http://www.cwi.nl/~guido/hypermail/python-1994q3/index.html>.) - -4.30. Q. How do I run a subprocess with pipes connected to both input -and output? - -A. This is really a UNIX question. Also, in general, it is unwise to -do so, because you can easily cause a deadlock where the parent -process is blocked waiting for output from the child, while the child -is blocked waiting for input from the child. This can be caused -because the parent expects the child to output more text than it does, -or it can be caused by data being stuck in stdio buffers due to lack -of flushing. The Python parent can of course explicitly flush the data -it sends to the child before it reads any output, but if the child is -a naive C program it can easily have been written to never explicitly -flush its output, even if it is interactive, since flushing is -normally automatic. - -In many cases, all you really need is to run some data through a -command and get the result back. Unless the data is infinite in size, -the easiest (and often the most efficient!) way to do this is to write -it to a temporary file and run the command with that temporary file as -input. The standard module tempfile exports a function mktemp() which -generates unique temporary file names. - -If after reading all of the above you still want to connect two pipes -to a subprocess's standard input and output, here's a simple solution, -due to Jack Jansen: - - import os - import sys - import string - - MAXFD = 100 # Max number of file descriptors in this system - - def popen2(cmd): - cmd = string.split(cmd) - p2cread, p2cwrite = os.pipe() - c2pread, c2pwrite = os.pipe() - pid = os.fork() - if pid == 0: - # Child - os.close(0) - os.close(1) - if os.dup(p2cread) <> 0: - sys.stderr.write('popen2: bad read dup\n') - if os.dup(c2pwrite) <> 1: - sys.stderr.write('popen2: bad write dup\n') - for i in range(3, MAXFD): - try: - os.close(i) - except: - pass - try: - os.execv(cmd[0], cmd) - finally: - os._exit(1) - os.close(p2cread) - tochild = os.fdopen(p2cwrite, 'w') - os.close(c2pwrite) - fromchild = os.fdopen(c2pread, 'r') - return fromchild, tochild - -Note that many interactive programs (e.g. vi) don't work well with -pipes substituted for standard input and output. You will have to use -pseudo ttys ("ptys") instead of pipes. There is some undocumented -code to use these in the library module pty.py -- I'm afraid you're on -your own here. - -A different answer is a Python interface to Don Libes' "expect" -library. A prerelease of this is available on the Python ftp mirror -sites in the contrib subdirectory as expy-0.3.tar.gz, e.g. -<URL:ftp://ftp.python.org/pub/python/contrib/expy-0.3.tar.gz>. - -4.31. Q. How do I call a function if I have the arguments in a tuple? - -A. Use the built-in function apply(). For instance, - - func(1, 2, 3) - -is equivalent to - - args = (1, 2, 3) - apply(func, args) - -Note that func(args) is not the same -- it calls func() with exactly -one argument, the tuple args, instead of three arguments, the integers -1, 2 and 3. - -4.32. Q. How do I enable font-lock-mode for Python in Emacs? - -A. Assuming you're already using python-mode and font-lock-mode -separately, all you need to do is put this in your .emacs file: - - (defun my-python-mode-hook () - (setq font-lock-keywords python-font-lock-keywords) - (font-lock-mode 1)) - (add-hook 'python-mode-hook 'my-python-mode-hook) - -4.33. Q. Is there an inverse to the format operator (a la C's scanf())? - -A. Not as such. - -For simple input parsing, the easiest approach is usually to split -the line into whitespace-delimited words using string.split(), and to -convert decimal strings to numeric values using string.atoi(), -string.atol() or string.atof(). (Python's atoi() is 32-bit and its -atol() is arbitrary precision.) If you want to use another delimiter -than whitespace, use string.splitfield() (possibly combining it with -string.strip() which removes surrounding whitespace from a string). - -For more complicated input parsing, regular expressions (see module -regex) are better suited and more powerful than C's scanf(). - - -5. Extending Python -=================== - -5.1. Q. Can I create my own functions in C? - -A. Yes, you can create built-in modules containing functions, -variables, exceptions and even new types in C. This is explained in -the document "Extending and Embedding the Python Interpreter" (the -LaTeX file Doc/ext.tex). Also read the chapter on dynamic loading. - -5.2. Q. Can I create my own functions in C++? - -A. Yes, using the C-compatibility features found in C++. Basically -you place extern "C" { ... } around the Python include files and put -extern "C" before each function that is going to be called by the -Python interpreter. Global or static C++ objects with constructors -are probably not a good idea. - -5.3. Q. How can I execute arbitrary Python statements from C? - -A. The highest-level function to do this is run_command() which takes -a single string argument which is executed in the context of module -__main__ and returns 0 for success and -1 when an exception occurred -(including SyntaxError). If you want more control, use run_string(); -see the source for run_command() in Python/pythonrun.c. - -5.4. Q. How can I evaluate an arbitrary Python expression from C? - -A. Call the function run_string() from the previous question with the -start symbol eval_input; it then parses an expression, evaluates it -and returns its value. See exec_eval() in Python/bltinmodule.c. - -5.5. Q. How do I extract C values from a Python object? - -A. That depends on the object's type. If it's a tuple, -gettuplesize(o) returns its length and gettupleitem(o, i) returns its -i'th item; similar for lists with getlistsize(o) and getlistitem(o, -i). For strings, getstringsize(o) returns its length and -getstringvalue(o) a pointer to its value (note that Python strings may -contain null bytes so strlen() is not safe). To test which type an -object is, first make sure it isn't NULL, and then use -is_stringobject(o), is_tupleobject(o), is_listobject(o) etc. - -5.6. Q. How do I use mkvalue() to create a tuple of arbitrary length? - -A. You can't. Use t = newtupleobject(n) instead, and fill it with -objects using settupleitem(t, i, o) -- note that this "eats" a -reference count of o. Similar for lists with newlistobject(n) and -setlistitem(l, i, o). Note that you *must* set all the tuple items to -some value before you pass the tuple to Python code -- -newtupleobject(n) initializes them to NULL, which isn't a valid Python -value. - -5.7. Q. What happened to mktuple(), featured in an example in the -Extensions manual? - -A. It's a typo, I meant newtupleobject() (see previous question). - -5.8. Q. How do I call an object's method from C? - -A. Here's a function (untested) that might become part of the next -release in some form. It uses <stdarg.h> to allow passing the -argument list on to vmkvalue(): - - object *call_method(object *inst, char *methodname, char *format, ...) - { - object *method; - object *args; - object *result; - va_list va; - method = getattr(inst, methodname); - if (method == NULL) return NULL; - va_start(va, format); - args = vmkvalue(format, va); - va_end(va); - if (args == NULL) { - DECREF(method); - return NULL; - } - result = call_object(method, args); - DECREF(method); - DECREF(args); - return result; - } - -This works for any instance that has methods -- whether built-in or -user-defined. You are responsible for eventually DECREF'ing the -return value. - -To call, e.g., a file object's "seek" method with arguments 10, 0 -(assuming the file object pointer is "f"): - - res = call_method(f, "seek", "(OO)", 10, 0); - if (res == NULL) { - ... an exception occurred ... - } - else { - DECREF(res); - } - -Note that since call_object() *always* wants a tuple for the argument -list, to call a function without arguments, pass "()" for the format, -and to call a function with one argument, surround the argument in -parentheses, e.g. "(i)". - -5.9. Q. How do I catch the output from print_error()? - -A. (Due to Mark Hammond): - -* in Python code, define an object that supports the "write()" method. -FWIW, there seems to be a small problem that requires the 'softspace' -attribute to be defined too (fixed in 1.2). - -* redirect sys.stdout and sys.stderr to this object. - -* call print_error, or just allow the standard traceback mechanism to -work. - -Then, the output will go wherever your write() method sends it. - -5.10. Q. How do I access a module written in Python from C? - -A. You can get a pointer to the module object as follows: - - module = import_module("<modulename>"); - -If the module hasn't been imported yet (i.e. it is not yet present in -sys.modules), this initializes the module; otherwise it simply returns -the value of sys.modules["<modulename>"]. Note that it doesn't enter -the module into any namespace -- it only ensures it has been -initialized and is stored in sys.modules. - -You can then access the module's attributes (i.e. any name defined in -the module) as follows: - - attr = getattr(module, "<attrname>"); - -Calling setattr(), to assign to variables in the module, also works. - -5.11. Q. How do I interface to C++ objects from Python? - -A. Depending on your requirements, there are many approaches. Begin -by reading the "Extending and Embedding" document (Doc/ext.tex, see -also <URL:http://www.python.org/doc/>). Realize that for the Python -run-time system, there isn't a whole lot of difference between C and -C++ -- so the strategy to build a new Python type around a C structure -(pointer) type will also work for C++ objects. - -Automatic generation of interfaces between Python and C++ is still at -the horizon -- parsing C++ header files requires an almost complete -C++ parser, and many features aren't easily translated from C++ to -Python: certain forms of operator oveloading, function overloading -(best approached by a varargs function which explicitly type-checks -its arguments), and reference arguments are just a number of features -that are hard to translate correctly if at all. - -The hardest problem is to transparently translate the C++ class -hierarchy to Python, so that Python programs derive classes from C++ -classes. Given suitable constraints, this may be possible, but it -would require more space than I have in this FAQ to explain how. -In any case, you can get quite a bit done without this, using just the -existing classes from Python. - -If this all seems rather daunting, that may be because it is -- C++ -isn't exactly a baby to handle without gloves! However, people have -accomplished amazing feats of interfacing between Python and C++, and -a detailed question posted to the Python list is likely to elicit some -interesting and useful responses. - - -6. Python's design -================== - -6.1. Q. Why isn't there a generic copying operation for objects in Python? - -A. Historically, there wasn't. However, starting in Python 1.2, -there's a library module "copy" which supports both shallow and deep -copying of most common Python objects (though not things like open -files, sockets or windows), including an extensible mechanism to copy -class instances. - -6.2. Q. Why isn't there a generic way to implement persistent objects -in Python? (Persistent == automatically saved to and restored from -disk.) - -A. Like the previous question, historically, there wasn't. The -library module "pickle" now solves this in a very general way (though -you still can't store things like open files, sockests or windows), -and the library module "shelve" uses pickle and (g)dbm to create -presistent mappings containing arbitrary Python objects. There are -some problems with shelve when using gdbm which will be solved in -Python 1.3. - -6.3. Q. Why isn't there a switch or case statement in Python? - -A. You can do this easily enough with a sequence of -if... elif... elif... else. There have been some proposals for switch -statement syntax, but there is no consensus (yet) on whether and how -to do range tests. - -6.4. Q. Why does Python use indentation for grouping of statements? - -A. Basically I believe that using indentation for grouping is -extremely elegant and contributes a lot to the clarity of the average -Python program. Most people learn to love this feature after a while. -Some arguments for it: - -- Since there are no begin/end brackets there cannot be a disagreement -between grouping perceived by the parser and the human reader. I -remember long ago seeing a C fragment like this: - - if (x <= y) - x++; - y--; - z++; - -and staring a long time at it wondering why y was being decremented -even for x > y... (And I wasn't a C newbie then either.) - -- Since there are no begin/end brackets, Python is much less prone to -coding-style conflicts. In C there are loads of different ways to -place the braces (including the choice whether to place braces around -single statements in certain cases, for consistency). If you're used -to reading (and writing) code that uses one style, you will feel at -least slightly uneasy when reading (or being required to write) -another style. - -- Many coding styles place begin/end brackets on a line by themself. -This makes programs considerably longer and wastes valuable screen -space, making it harder to get a good overview over a program. -Ideally, a function should fit on one basic tty screen (say, 20 -lines). 20 lines of Python are worth a LOT more than 20 lines of C. -This is not solely due to the lack of begin/end brackets (the lack of -declarations also helps, and the powerful operations of course), but -it certainly helps! - -6.5. Q. Why are Python strings immutable? - -A. There are two advantages. One is performance: knowing that a -string is immutable makes it easy to lay it out at construction time --- fixed and unchanging storage requirements. (This is also one of -the reasons for the distinction between tuples and lists.) The -other is that strings in Python are considered as "elemental" as -numbers. No amount of activity will change the value 8 to anything -else, and in Python, no amount of activity will change the string -"eight" to anything else. (Adapted from Jim Roskind) - -6.6. Q. Why don't strings have methods like index() or sort(), like -lists? - -A. Good question. Strings currently don't have methods at all -(likewise tuples and numbers). Long ago, it seemed unnecessary to -implement any of these functions in C, so a standard library module -"string" written in Python was created that performs string related -operations. Since then, the cry for performance has moved most of -them into the built-in module strop (this is imported by module -string, which is still the preferred interface, without loss of -performance except during initialization). Some of these functions -(e.g. index()) could easily be implemented as string methods instead, -but others (e.g. sort()) can't, since their interface prescribes that -they modify the object, while strings are immutable (see the previous -question). - -6.7. Q. Why does Python use methods for some functionality -(e.g. list.index()) but functions for other (e.g. len(list))? - -A. Functions are used for those operations that are generic for a -group of types and which should work even for objects that don't have -methods at all (e.g. numbers, strings, tuples). Also, implementing -len(), max(), min() as a built-in function is actually less code than -implementing them as methods for each type. One can quibble about -individual cases but it's really too late to change such things -fundamentally now. - -6.8. Q. Why can't I derive a class from built-in types (e.g. lists or -files)? - -A. This is caused by the relatively late addition of (user-defined) -classes to the language -- the implementation framework doesn't easily -allow it. See the answer to question 4.2 for a work-around. This -*may* be fixed in the (distant) future. - -6.9. Q. Why must 'self' be declared and used explicitly in method -definitions and calls? - -A. By asking this question you reveal your C++ background. :-) -When I added classes, this was (again) the simplest way of -implementing methods without too many changes to the interpreter. I -borrowed the idea from Modula-3. It turns out to be very useful, for -a variety of reasons. - -First, it makes it more obvious that you are using a method or -instance attribute instead of a local variable. Reading "self.x" or -"self.meth()" makes it absolutely clear that an instance variable or -method is used even if you don't know the class definition by heart. -In C++, you can sort of tell by the lack of a local variable -declaration (assuming globals are rare or easily recognizable) -- but -in Python, there are no local variable declarations, so you'd have to -look up the class definition to be sure. - -Second, it means that no special syntax is necessary if you want to -explicitly reference or call the method from a particular class. In -C++, if you want to use a method from base class that is overridden in -a derived class, you have to use the :: operator -- in Python you can -write baseclass.methodname(self, <argument list>). This is -particularly useful for __init__() methods, and in general in cases -where a derived class method wants to extend the base class method of -the same name and thus has to call the base class method somehow. - -Lastly, for instance variables, it solves a syntactic problem with -assignment: since local variables in Python are (by definition!) those -variables to which a value assigned in a function body (and that -aren't explicitly declared global), there has to be some way to tell -the interpreter that an assignment was meant to assign to an instance -variable instead of to a local variable, and it should preferably be -syntactic (for efficiency reasons). C++ does this through -declarations, but Python doesn't have declarations and it would be a -pity having to introduce them just for this purpose. Using the -explicit "self.var" solves this nicely. Similarly, for using instance -variables, having to write "self.var" means that references to -unqualified names inside a method don't have to search the instance's -directories. - -6.10. Q. Can't you emulate threads in the interpreter instead of -relying on an OS-specific thread implementation? - -A. Unfortunately, the interpreter pushes at least one C stack frame -for each Python stack frame. Also, extensions can call back into -Python at almost random moments. Therefore a complete threads -implementation requires thread support for C. - -6.11. Q. Why can't lambda forms contain statements? - -A. Python lambda forms cannot contain statements because Python's -syntactic framework can't handle statements nested inside expressions. - -However, in Python, this is not a serious problem. Unlike lambda -forms in other languages, where they add functionality, Python lambdas -are only a shorthand notation if you're too lazy to define a function. - -Functions are already first class objects in Python, and can be -declared in a local scope. Therefore the only advantage of using a -lambda form instead of a locally-defined function is that you'll have -to invent a name for the function -- but that's just a local variable -to which the function object (which is exactly the same type of object -that a lambda form yields) is assigned! - -6.12. Q. Why is there no more efficient way of iterating over a dictionary -than first constructing the list of keys()? - -A. Have you tried it? I bet it's fast enough for your purposes! In -most cases such a list takes only a few percent of the space occupied -by the dictionary -- it needs only 4 bytes (the size of a pointer) per -key -- a dictionary costs 8 bytes per key plus between 30 and 70 -percent hash table overhead, plus the space for the keys and values -- -by necessity all keys are unique objects and a string object (the most -common key type) costs at least 18 bytes plus the length of the -string. Add to that the values contained in the dictionary, and you -see that 4 bytes more per item really isn't that much more memory... - -A call to dict.keys() makes one fast scan over the dictionary -(internally, the iteration function does exist) copying the pointers -to the key objects into a pre-allocated list object of the right size. -The iteration time isn't lost (since you'll have to iterate anyway -- -unless in the majority of cases your loop terminates very prematurely -(which I doubt since you're getting the keys in random order). - -I don't expose the dictionary iteration operation to Python -programmers because the dictionary shouldn't be modified during the -entire iteration -- if it is, there's a very small chance that the -dictionary is reorganized because the hash table becomes too full, and -then the iteration may miss some items and see others twice. Exactly -because this only occurs rarely, it would lead to hidden bugs in -programs: it's easy never to have it happen during test runs if you -only insert or delete a few items per iteration -- but your users will -surely hit upon it sooner or later. - -6.13. Q. Can Python be compiled to machine code, C or some other language? - -A. Not easily. Python's high level data types, dynamic typing of -objects and run-time invocation of the interpreter (using eval() or -exec) together mean that a "compiled" Python program would probably -consist mostly of calls into the Python run-time system, even for -seemingly simple operations like "x+1". Thus, the performance gain -would probably be minimal. - -Internally, Python source code is always translated into a "virtual -machine code" or "byte code" representation before it is interpreted -(by the "Python virtual machine" or "bytecode interpreter"). In order -to avoid the overhead of parsing and translating modules that rarely -change over and over again, this byte code is written on a file whose -name ends in ".pyc" whenever a module is parsed (from a file whose -name ends in ".py"). When the corresponding .py file is changed, it -is parsed and translated again and the .pyc file is rewritten. There -is no performance difference once the .pyc file has been loaded (the -bytecode read from the .pyc file is exactly the same as the bytecode -created by direct translation). The only difference is that loading -code from a .pyc file is faster than parsing and translating a .py -file, so the presence of precompiled .pyc files will generally improve -start-up time of Python scripts. If desired, the Lib/compileall.py -module/script can be used to force creation of valid .pyc files for a -given set of modules. - -If you are looking for a way to translate Python programs in order to -distribute them in binary form, without the need to distribute the -interpreter and library as well, have a look at the freeze.py script -in the Tools/freeze directory. This creates a single binary file -incorporating your program, the Python interpreter, and those parts of -the Python library that are needed by your program. Of course, the -resulting binary will only run on the same type of platform as that -used to create it. - -Hints for proper usage of freeze.py: - -- the script must be in a file whose name ends in .py - -- you must have installed Python fully: - - make install - make libinstall - make inclinstall - make libainstall - -6.14. Q. Why doesn't Python use proper garbage collection? - -A. It's looking less and less likely that Python will ever get -"automatic" garbage collection (GC). For one thing, unless this were -added to C as a standard feature, it's a portability pain in the ass. -And yes, I know about the Xerox library. It has bits of assembler -code for *most* *common* platforms. Not for all. And although it is -mostly transparent, it isn't completely transparent (when I once -linked Python with it, it dumped core). - -"Proper" GC also becomes a problem when Python gets embedded into -other applications. While in a stand-alone Python it may be fine to -replace the standard malloc() and free() with versions provided by the -GC library, an application embedding Python may want to have its *own* -substitute for malloc() and free(), and may not want Python's. Right -now, Python works with anything that implements malloc() and free() -properly. - -Besides, the predictability of destructor calls in Python is kind of -attractive. With GC, the following code (which is fine in current -Python) will run out of file descriptors long before it runs out of -memory: - - for file in <very long list of files>: - f = open(file) - c = file.read(1) - -Using the current reference counting and destructor scheme, each new -assignment to f closes the previous file. Using GC, this is not -guaranteed. Sure, you can think of ways to fix this. But it's not -off-the-shelf technology. - - -7. Using Python on non-UNIX platforms -===================================== - -7.1. Q. Is there a Mac version of Python? - -A. Yes, see the "mac" subdirectory of the distribution sites, -e.g. <URL:ftp://ftp.python.org/pub/python/mac/>. - -7.2. Q. Is there a DOS version of Python? - -A. Yes, see the "pc" subdirectory of the distribution sites, -e.g. <URL:ftp://ftp.python.org/pub/python/pc/>. - -7.3. Q. Is there a Windows 3.1(1) version of Python? - -A. Yes, also see the "pc" subdirectory of the distribution sites, -e.g. <URL:ftp://ftp.python.org/pub/python/pc/>. You may also be able -to run either of the Windows NT versions (see next question) if you -have Microsoft's "win32s". - -7.4. Q. Is there a Windows NT version of Python? - -A. There are two, both sporting DLL support for dynamic loading of -Python modules, and extensions to access the Win32 GUI API. - -Mark Hammond <MHammond@cmutual.com.au> maintains an NT port which -includes an interface to the Microsoft Foundation Classes and a Python -programming environment using it that's written mostly in Python. See -<URL:ftp://ftp.python.org/pub/python/nt/>. - -Jim Ahlstrom's WPY portable GUI runs on Windows NT and is modeled -after the Microsoft Foundation Classes. Source and binaries are -available in <URL:ftp://ftp.python.org/pub/python/wpy>. - -Sam Rushing <rushing@squirl.oau.org> once announced he knows how to -build Python for the Windows NT on the DEC Alpha AXP. - -Note that currently there is no unified compilation environment for -all NT platforms -- hopefully Microsoft will fix this with the release -of Visual C++ 2.0. - -7.5. Q. Is there a Windows 95 version of Python? - -A. The Windows NT versions might work, otherwise the Windows 3.1(1) -version should work (isn't Windows 95 supposed to be backwards -compatible?). - -7.6. Q. Is there an OS/2 version of Python? - -A. Yes, also see the "pc" subdirectory of the distribution sites, -e.g. <URL:ftp://ftp.python.org/pub/python/pc/>. - -7.7. Q. Is there a VMS version of Python? - -A. Donn Cave <donn@cac.washington.edu> did a partial port. The -results of his efforts are on public display in -<<URL:ftp://ftp.python.org/pub/python/contrib/vms.tar.gz/>. Someone -else is working on a more complete port, for details watch the list. - -7.8. Q. What about IBM mainframes, or other non-UNIX platforms? - -A. I haven't heard about these, except I remember hearing about an -OS/9 port and a port to Vxworks (both operating systems for embedded -systems). If you're interested in any of this, go directly to the -newsgroup and ask there, you may find exactly what you need. For -example, a port to MPE/iX 5.0 on HP3000 computers was just announced, -see <URL:http://www.allegro.com/software/>. - -7.9. Q. Where are the source or Makefiles for the non-UNIX versions? - -A. The standard sources can (almost) be used. Additional sources can -be found in the platform-specific subdirectories of the distribution. - -7.10. Q. What is the status and support for the non-UNIX versions? - -A. I don't have access to most of these platforms, so in general I am -dependent on material submitted by volunteers(*). However I strive to -integrate all changes needed to get it to compile on a particular -platform back into the standard sources, so porting of the next -version to the various non-UNIX platforms should be easy. - -(*) For the Macintosh, that volunteer is me, with help from Jack -Jansen <jack@cwi.nl>. - -7.11. Q. I have a PC version but it appears to be only a binary. -Where's the library? - -A. You still need to copy the files from the distribution directory -"python/Lib" to your system. If you don't have the full distribution, -you can get the file lib<version>.tar.gz from most ftp sites carrying -Python; this is a subset of the distribution containing just those -files, e.g. <URL:ftp://ftp.python.org/pub/python/src/lib1.1.tar.gz>. - -Once you have installed the library, you need to point sys.path to it. -Assuming the library is in C:\misc\python\lib, the following commands -will point your Python interpreter to it (note the doubled backslashes --- you can also use single forward slashes instead): - - >>> import sys - >>> sys.path.insert(0, 'C:\\misc\\python\\lib') - >>> - -For a more permanent effect, set the environment variable PYTHONPATH, -as follows (talking to a DOS prompt): - - C> SET PYTHONPATH=C:\misc\python\lib - -7.12. Q. Where's the documentation for the Mac or PC version? - -A. The documentation for the Unix version also applies to the Mac and -PC versions. Where applicable, differences are indicated in the text. - -7.13. Q. The Mac (PC) version doesn't seem to have any facilities for -creating or editing programs apart from entering it interactively, and -there seems to be no way to save code that was entered interactively. -How do I create a Python program on the Mac (PC)? - -A. Use an external editor. On the Mac, BBEdit seems to be a popular -no-frills text editor. I work like this: start the interpreter; edit -a module file using BBedit; import and test it in the interpreter; -edit again in BBedit; then use the built-in function reload() to -re-read the imported module; etc. - -Regarding the same question for the PC, Kurt Wm. Hemr writes: "While -anyone with a pulse could certainly figure out how to do the same on -MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows. -Not only can you easily resave and "reload()" from Python after making -changes, but since WinNot auto-copies to the clipboard any text you -select, you can simply select the entire procedure (function) which -you changed in WinNot, switch to QWPython, and shift-ins to reenter -the changed program unit." diff --git a/Misc/Fixcprt.py b/Misc/Fixcprt.py deleted file mode 100755 index fa28aaa087..0000000000 --- a/Misc/Fixcprt.py +++ /dev/null @@ -1,75 +0,0 @@ -#! /usr/local/bin/python - -import regex -import regsub -import glob -import sys -import os -import stat -import getopt - -oldcprt = """\ -Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum, -Amsterdam, The Netherlands.""" -newcprt = """\ -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands.""" - -oldprog = regex.compile(oldcprt) -newprog = regex.compile(newcprt) - -HEADSIZE = 1024 - -def main(): - opts, args = getopt.getopt(sys.argv[1:], 'y:') - agelimit = 0L - for opt, arg in opts: - if opt == '-y': - agelimit = os.stat(arg)[stat.ST_MTIME] - if not args: - args = glob.glob('*.[ch]') - for file in args: - try: - age = os.stat(file)[stat.ST_MTIME] - except os.error, msg: - print file, ': stat failed :', msg - continue - if age <= agelimit: - print file, ': too old, skipped' - continue - try: - f = open(file, 'r') - except IOError, msg: - print file, ': open failed :', msg - continue - head = f.read(HEADSIZE) - if oldprog.search(head) < 0: - if newprog.search(head) < 0: - print file, ': NO COPYRIGHT FOUND' - else: - print file, ': (new copyright already there)' - f.close() - continue - newhead = regsub.sub(oldcprt, newcprt, head) - data = newhead + f.read() - f.close() - try: - f = open(file + '.new', 'w') - except IOError, msg: - print file, ': creat failed :', msg - continue - f.write(data) - f.close() - try: - os.rename(file, file + '~') - except IOError, msg: - print file, ': rename to backup failed :', msg - continue - try: - os.rename(file + '.new', file) - except IOError, msg: - print file, ': rename from .new failed :', msg - continue - print file, ': copyright changed.' - -main() diff --git a/Misc/HISTORY b/Misc/HISTORY deleted file mode 100644 index 8046c2864c..0000000000 --- a/Misc/HISTORY +++ /dev/null @@ -1,2360 +0,0 @@ -Python history --------------- - -This file contains the release messages for previous Python releases -(slightly edited to adapt them to the format of this file). As you -read on you go back to the dark ages of Python's history. - - -=================================== -==> Release 1.2 (13 April 1995) <== -=================================== - -- Changes to Misc/python-mode.el: - - Wrapping and indentation within triple quote strings should work - properly now. - - `Standard' bug reporting mechanism (use C-c C-b) - - py-mark-block was moved to C-c C-m - - C-c C-v shows you the python-mode version - - a basic python-font-lock-keywords has been added for Emacs 19 - font-lock colorizations. - - proper interaction with pending-del and del-sel modes. - - New py-electric-colon (:) command for improved outdenting. Also - py-indent-line (TAB) should handle outdented lines better. - - New commands py-outdent-left (C-c C-l) and py-indent-right (C-c C-r) - -- The Library Reference has been restructured, and many new and -existing modules are now documented, in particular the debugger and -the profiler, as well as the persistency and the WWW/Internet support -modules. - -- All known bugs have been fixed. For example the pow(2,2,3L) bug on -Linux has been fixed. Also the re-entrancy problems with __del__ have -been fixed. - -- All known memory leaks have been fixed. - -- Phase 2 of the Great Renaming has been executed. The header files -now use the new names (PyObject instead of object, etc.). The linker -also sees the new names. Most source files still use the old names, -by virtue of the rename2.h header file. If you include Python.h, you -only see the new names. Dynamically linked modules have to be -recompiled. (Phase 3, fixing the rest of the sources, will be -executed gradually with the release later versions.) - -- The hooks for implementing "safe-python" (better called "restricted -execution") are in place. Specifically, the import statement is -implemented by calling the built-in function __import__, and the -built-in names used in a particular scope are taken from the -dictionary __builtins__ in that scope's global dictionary. See also -the new (unsupported, undocumented) module rexec.py. - -- The import statement now supports the syntax "import a.b.c" and -"from a.b.c import name". No officially supported implementation -exists, but one can be prototyped by replacing the built-in __import__ -function. A proposal by Ken Manheimer is provided as newimp.py. - -- All machinery used by the import statement (or the built-in -__import__ function) is now exposed through the new built-in module -"imp" (see the library reference manual). All dynamic loading -machinery is moved to the new file importdl.c. - -- Persistent storage is supported through the use of the modules -"pickle" and "shelve" (implemented in Python). There's also a "copy" -module implementing deepcopy and normal (shallow) copy operations. -See the library reference manual. - -- Documentation strings for many objects types are accessible through -the __doc__ attribute. Modules, classes and functions support special -syntax to initialize the __doc__ attribute: if the first statement -consists of just a string literal, that string literal becomes the -value of the __doc__ attribute. The default __doc__ attribute is -None. Documentation strings are also supported for built-in -functions, types and modules; however this feature hasn't been widely -used yet. See the 'new' module for an example. (Basically, the type -object's tp_doc field contains the doc string for the type, and the -4th member of the methodlist structure contains the doc string for the -method.) - -- The __coerce__ and __cmp__ methods for user-defined classes once -again work as expected. As an example, there's a new standard class -Complex in the library. - -- The functions posix.popen() and posix.fdopen() now have an optional -third argument to specify the buffer size, and default their second -(mode) argument to 'r' -- in analogy to the builtin open() function. -The same applies to posixfile.open() and the socket method makefile(). - -- The thread.exit_thread() function now raises SystemExit so that -'finally' clauses are honored and a memory leak is plugged. - -- Improved X11 and Motif support, by Sjoerd Mullender. This extension -is being maintained and distributed separately. - -- Improved support for the Apple Macintosh, in part by Jack Jansen, -e.g. interfaces to (a few) resource mananger functions, get/set file -type and creator, gestalt, sound manager, speech manager, MacTCP, comm -toolbox, and the think C console library. This is being maintained -and distributed separately. - -- Improved version for Windows NT, by Mark Hammond. This is being -maintained and distributed separately. - -- Used autoconf 2.0 to generate the configure script. Adapted -configure.in to use the new features in autoconf 2.0. - -- It now builds on the NeXT without intervention, even on the 3.3 -Sparc pre-release. - -- Characters passed to isspace() and friends are masked to nonnegative -values. - -- Correctly compute pow(-3.0, 3). - -- Fix portability problems with getopt (configure now checks for a -non-GNU getopt). - -- Don't add frozenmain.o to libPython.a. - -- Exceptions can now be classes. ALl built-in exceptions are still -string objects, but this will change in the future. - -- The socket module exports a long list of socket related symbols. -(More built-in modules will export their symbolic constants instead of -relying on a separately generated Python module.) - -- When a module object is deleted, it clears out its own dictionary. -This fixes a circularity in the references between functions and -their global dictionary. - -- Changed the error handling by [new]getargs() e.g. for "O&". - -- Dynamic loading of modules using shared libraries is supported for -several new platforms. - -- Support "O&", "[...]" and "{...}" in mkvalue(). - -- Extension to findmethod(): findmethodinchain() (where a chain is a -linked list of methodlist arrays). The calling interface for -findmethod() has changed: it now gets a pointer to the (static!) -methodlist structure rather than just to the function name -- this -saves copying flags etc. into the (short-lived) method object. - -- The callable() function is now public. - -- Object types can define a few new operations by setting function -pointers in the type object structure: tp_call defines how an object -is called, and tp_str defines how an object's str() is computed. - - -=================================== -==> Release 1.1.1 (10 Nov 1994) <== -=================================== - -This is a pure bugfix release again. See the ChangeLog file for details. - -One exception: a few new features were added to tkinter. - - -================================= -==> Release 1.1 (11 Oct 1994) <== -================================= - -This release adds several new features, improved configuration and -portability, and fixes more bugs than I can list here (including some -memory leaks). - -The source compiles and runs out of the box on more platforms than -ever -- including Windows NT. Makefiles or projects for a variety of -non-UNIX platforms are provided. - -APOLOGY: some new features are badly documented or not at all. I had -the choice -- postpone the new release indefinitely, or release it -now, with working code but some undocumented areas. The problem with -postponing the release is that people continue to suffer from existing -bugs, and send me patches based on the previous release -- which I -can't apply directly because my own source has changed. Also, some -new modules (like signal) have been ready for release for quite some -time, and people are anxiously waiting for them. In the case of -signal, the interface is simple enough to figure out without -documentation (if you're anxious enough :-). In this case it was not -simple to release the module on its own, since it relies on many small -patches elsewhere in the source. - -For most new Python modules, the source code contains comments that -explain how to use them. Documentation for the Tk interface, written -by Matt Conway, is available as tkinter-doc.tar.gz from the Python -home and mirror ftp sites (see Misc/FAQ for ftp addresses). For the -new operator overloading facilities, have a look at Demo/classes: -Complex.py and Rat.py show how to implement a numeric type without and -with __coerce__ method. Also have a look at the end of the Tutorial -document (Doc/tut.tex). If you're still confused: use the newsgroup -or mailing list. - - -New language features: - - - More flexible operator overloading for user-defined classes - (INCOMPATIBLE WITH PREVIOUS VERSIONS!) See end of tutorial. - - - Classes can define methods named __getattr__, __setattr__ and - __delattr__ to trap attribute accesses. See end of tutorial. - - - Classes can define method __call__ so instances can be called - directly. See end of tutorial. - - -New support facilities: - - - The Makefiles (for the base interpreter as well as for extensions) - now support creating dynamically loadable modules if the platform - supports shared libraries. - - - Passing the interpreter a .pyc file as script argument will execute - the code in that file. (On the Mac such files can be double-clicked!) - - - New Freeze script, to create independently distributable "binaries" - of Python programs -- look in Demo/freeze - - - Improved h2py script (in Demo/scripts) follows #includes and - supports macros with one argument - - - New module compileall generates .pyc files for all modules in a - directory (tree) without also executing them - - - Threads should work on more platforms - - -New built-in modules: - - - tkinter (support for Tcl's Tk widget set) is now part of the base - distribution - - - signal allows catching or ignoring UNIX signals (unfortunately still - undocumented -- any taker?) - - - termios provides portable access to POSIX tty settings - - - curses provides an interface to the System V curses library - - - syslog provides an interface to the (BSD?) syslog daemon - - - 'new' provides interfaces to create new built-in object types - (e.g. modules and functions) - - - sybase provides an interface to SYBASE database - - -New/obsolete built-in methods: - - - callable(x) tests whether x can be called - - - sockets now have a setblocking() method - - - sockets no longer have an allowbroadcast() method - - - socket methods send() and sendto() return byte count - - -New standard library modules: - - - types.py defines standard names for built-in types, e.g. StringType - - - urlparse.py parses URLs according to the latest Internet draft - - - uu.py does uuencode/uudecode (not the fastest in the world, but - quicker than installing uuencode on a non-UNIX machine :-) - - - New, faster and more powerful profile module.py - - - mhlib.py provides interface to MH folders and messages - - -New facilities for extension writers (unfortunately still -undocumented): - - - newgetargs() supports optional arguments and improved error messages - - - O!, O& O? formats for getargs allow more versatile type checking of - non-standard types - - - can register pending asynchronous callback, to be called the next - time the Python VM begins a new instruction (Py_AddPendingCall) - - - can register cleanup routines to be called when Python exits - (Py_AtExit) - - - makesetup script understands C++ files in Setup file (use file.C - or file.cc) - - - Make variable OPT is passed on to sub-Makefiles - - - An init<module>() routine may signal an error by not entering - the module in the module table and raising an exception instead - - - For long module names, instead of foobarbletchmodule.c you can - use foobarbletch.c - - - getintvalue() and getfloatvalue() try to convert any object - instead of requiring an "intobject" or "floatobject" - - - All the [new]getargs() formats that retrieve an integer value - will now also work if a float is passed - - - C function listtuple() converts list to tuple, fast - - - You should now call sigcheck() instead of intrcheck(); - sigcheck() also sets an exception when it returns nonzero - - -==================================== -==> Release 1.0.3 (14 July 1994) <== -==================================== - -This release consists entirely of bug fixes to the C sources; see the -head of ../ChangeLog for a complete list. Most important bugs fixed: - -- Sometimes the format operator (string%expr) would drop the last -character of the format string - -- Tokenizer looped when last line did not end in \n - -- Bug when triple-quoted string ended in quote plus newline - -- Typo in socketmodule (listen) (== instead of =) - -- typing vars() at the >>> prompt would cause recursive output - - -================================== -==> Release 1.0.2 (4 May 1994) <== -================================== - -Overview of the most visible changes. Bug fixes are not listed. See -also ChangeLog. - -Tokens ------- - -* String literals follow Standard C rules: they may be continued on -the next line using a backslash; adjacent literals are concatenated -at compile time. - -* A new kind of string literals, surrounded by triple quotes (""" or -'''), can be continued on the next line without a backslash. - -Syntax ------- - -* Function arguments may have a default value, e.g. def f(a, b=1); -defaults are evaluated at function definition time. This also applies -to lambda. - -* The try-except statement has an optional else clause, which is -executed when no exception occurs in the try clause. - -Interpreter ------------ - -* The result of a statement-level expression is no longer printed, -except_ for expressions entered interactively. Consequently, the -k -command line option is gone. - -* The result of the last printed interactive expression is assigned to -the variable '_'. - -* Access to implicit global variables has been speeded up by removing -an always-failing dictionary lookup in the dictionary of local -variables (mod suggested by Steve Makewski and Tim Peters). - -* There is a new command line option, -u, to force stdout and stderr -to be unbuffered. - -* Incorporated Steve Majewski's mods to import.c for dynamic loading -under AIX. - -* Fewer chances of dumping core when trying to reload or re-import -static built-in, dynamically loaded built-in, or frozen modules. - -* Loops over sequences now don't ask for the sequence's length when -they start, but try to access items 0, 1, 2, and so on until they hit -an IndexError. This makes it possible to create classes that generate -infinite or indefinite sequences a la Steve Majewski. This affects -for loops, the (not) in operator, and the built-in functions filter(), -map(), max(), min(), reduce(). - -Changed Built-in operations ---------------------------- - -* The '%' operator on strings (printf-style formatting) supports a new -feature (adapted from a patch by Donald Beaudry) to allow -'%(<key>)<format>' % {...} to take values from a dictionary by name -instead of from a tuple by position (see also the new function -vars()). - -* The '%s' formatting operator is changed to accept any type and -convert it to a string using str(). - -* Dictionaries with more than 20,000 entries can now be created -(thanks to Steve Kirsch). - -New Built-in Functions ----------------------- - -* vars() returns a dictionary containing the local variables; vars(m) -returns a dictionary containing the variables of module m. Note: -dir(x) is now equivalent to vars(x).keys(). - -Changed Built-in Functions --------------------------- - -* open() has an optional third argument to specify the buffer size: 0 -for unbuffered, 1 for line buffered, >1 for explicit buffer size, <0 -for default. - -* open()'s second argument is now optional; it defaults to "r". - -* apply() now checks that its second argument is indeed a tuple. - -New Built-in Modules --------------------- - -Changed Built-in Modules ------------------------- - -The thread module no longer supports exit_prog(). - -New Python Modules ------------------- - -* Module addpack contains a standard interface to modify sys.path to -find optional packages (groups of related modules). - -* Module urllib contains a number of functions to access -World-Wide-Web files specified by their URL. - -* Module httplib implements the client side of the HTTP protocol used -by World-Wide-Web servers. - -* Module gopherlib implements the client side of the Gopher protocol. - -* Module mailbox (by Jack Jansen) contains a parser for UNIX and MMDF -style mailbox files. - -* Module random contains various random distributions, e.g. gauss(). - -* Module lockfile locks and unlocks open files using fcntl (inspired -by a similar module by Andy Bensky). - -* Module ntpath (by Jaap Vermeulen) implements path operations for -Windows/NT. - -* Module test_thread (in Lib/test) contains a small test set for the -thread module. - -Changed Python Modules ----------------------- - -* The string module's expandvars() function is now documented and is -implemented in Python (using regular expressions) instead of forking -off a shell process. - -* Module rfc822 now supports accessing the header fields using the -mapping/dictionary interface, e.g. h['subject']. - -* Module pdb now makes it possible to set a break on a function -(syntax: break <expression>, where <expression> yields a function -object). - -Changed Demos -------------- - -* The Demo/scripts/freeze.py script is working again (thanks to Jaap -Vermeulen). - -New Demos ---------- - -* Demo/threads/Generator.py is a proposed interface for restartable -functions a la Tim Peters. - -* Demo/scripts/newslist.py, by Quentin Stafford-Fraser, generates a -directory full of HTML pages which between them contain links to all -the newsgroups available on your server. - -* Demo/dns contains a DNS (Domain Name Server) client. - -* Demo/lutz contains miscellaneous demos by Mark Lutz (e.g. psh.py, a -nice enhanced Python shell!!!). - -* Demo/turing contains a Turing machine by Amrit Prem. - -Documentation -------------- - -* Documented new language features mentioned above (but not all new -modules). - -* Added a chapter to the Tutorial describing recent additions to -Python. - -* Clarified some sentences in the reference manual, -e.g. break/continue, local/global scope, slice assignment. - -Source Structure ----------------- - -* Moved Include/tokenizer.h to Parser/tokenizer.h. - -* Added Python/getopt.c for systems that don't have it. - -Emacs mode ----------- - -* Indentation of continuated lines is done more intelligently; -consequently the variable py-continuation-offset is gone. - -======================================== -==> Release 1.0.1 (15 February 1994) <== -======================================== - -* Many portability fixes should make it painless to build Python on -several new platforms, e.g. NeXT, SEQUENT, WATCOM, DOS, and Windows. - -* Fixed test for <stdarg.h> -- this broke on some platforms. - -* Fixed test for shared library dynalic loading -- this broke on SunOS -4.x using the GNU loader. - -* Changed order and number of SVR4 networking libraries (it is now --lsocket -linet -lnsl, if these libraries exist). - -* Installing the build intermediate stages with "make libainstall" now -also installs config.c.in, Setup and makesetup, which are used by the -new Extensions mechanism. - -* Improved README file contains more hints and new troubleshooting -section. - -* The built-in module strop now defines fast versions of three more -functions of the standard string module: atoi(), atol() and atof(). -The strop versions of atoi() and atol() support an optional second -argument to specify the base (default 10). NOTE: you don't have to -explicitly import strop to use the faster versions -- the string -module contains code to let versions from stop override the default -versions. - -* There is now a working Lib/dospath.py for those who use Python under -DOS (or Windows). Thanks, Jaap! - -* There is now a working Modules/dosmodule.c for DOS (or Windows) -system calls. - -* Lib.os.py has been reorganized (making it ready for more operating -systems). - -* Lib/ospath.py is now obsolete (use os.path instead). - -* Many fixes to the tutorial to make it match Python 1.0. Thanks, -Tim! - -* Fixed Doc/Makefile, Doc/README and various scripts there. - -* Added missing description of fdopen to Doc/libposix.tex. - -* Made cleanup() global, for the benefit of embedded applications. - -* Added parsing of addresses and dates to Lib/rfc822.py. - -* Small fixes to Lib/aifc.py, Lib/sunau.py, Lib/tzparse.py to make -them usable at all. - -* New module Lib/wave.py reads RIFF (*.wav) audio files. - -* Module Lib/filewin.py moved to Lib/stdwin/filewin.py where it -belongs. - -* New options and comments for Modules/makesetup (used by new -Extension mechanism). - -* Misc/HYPE contains text of announcement of 1.0.0 in comp.lang.misc -and elsewhere. - -* Fixed coredump in filter(None, 'abcdefg'). - - -======================================= -==> Release 1.0.0 (26 January 1994) <== -======================================= - -As is traditional, so many things have changed that I can't pretend to -be complete in these release notes, but I'll try anyway :-) - -Note that the very last section is labeled "remaining bugs". - - -Source organization and build process -------------------------------------- - -* The sources have finally been split: instead of a single src -subdirectory there are now separate directories Include, Parser, -Grammar, Objects, Python and Modules. Other directories also start -with a capital letter: Misc, Doc, Lib, Demo. - -* A few extensions (notably Amoeba and X support) have been moved to a -separate subtree Extensions, which is no longer in the core -distribution, but separately ftp'able as extensions.tar.Z. (The -distribution contains a placeholder Ext-dummy with a description of -the Extensions subtree as well as the most recent versions of the -scripts used there.) - -* A few large specialized demos (SGI video and www) have been -moved to a separate subdirectory Demo2, which is no longer in the core -distribution, but separately ftp'able as demo2.tar.Z. - -* Parts of the standard library have been moved to subdirectories: -there are now standard subdirectories stdwin, test, sgi and sun4. - -* The configuration process has radically changed: I now use GNU -autoconf. This makes it much easier to build on new Unix flavors, as -well as fully supporting VPATH (if your Make has it). The scripts -Configure.py and Addmodule.sh are no longer needed. Many source files -have been adapted in order to work with the symbols that the configure -script generated by autoconf defines (or not); the resulting source is -much more portable to different C compilers and operating systems, -even non Unix systems (a Mac port was done in an afternoon). See the -toplevel README file for a description of the new build process. - -* GNU readline (a slightly newer version) is now a subdirectory of the -Python toplevel. It is still not automatically configured (being -totally autoconf-unaware :-). One problem has been solved: typing -Control-C to a readline prompt will now work. The distribution no -longer contains a "super-level" directory (above the python toplevel -directory), and dl, dl-dld and GNU dld are no longer part of the -Python distribution (you can still ftp them from -ftp.cwi.nl:/pub/dynload). - -* The DOS functions have been taken out of posixmodule.c and moved -into a separate file dosmodule.c. - -* There's now a separate file version.c which contains nothing but -the version number. - -* The actual main program is now contained in config.c (unless NO_MAIN -is defined); pythonmain.c now contains a function realmain() which is -called from config.c's main(). - -* All files needed to use the built-in module md5 are now contained in -the distribution. The module has been cleaned up considerably. - - -Documentation -------------- - -* The library manual has been split into many more small latex files, -so it is easier to edit Doc/lib.tex file to create a custom library -manual, describing only those modules supported on your system. (This -is not automated though.) - -* A fourth manual has been added, titled "Extending and Embedding the -Python Interpreter" (Doc/ext.tex), which collects information about -the interpreter which was previously spread over several files in the -misc subdirectory. - -* The entire documentation is now also available on-line for those who -have a WWW browser (e.g. NCSA Mosaic). Point your browser to the URL -"http://www.cwi.nl/~guido/Python.html". - - -Syntax ------- - -* Strings may now be enclosed in double quotes as well as in single -quotes. There is no difference in interpretation. The repr() of -string objects will use double quotes if the string contains a single -quote and no double quotes. Thanks to Amrit Prem for these changes! - -* There is a new keyword 'exec'. This replaces the exec() built-in -function. If a function contains an exec statement, local variable -optimization is not performed for that particular function, thus -making assignment to local variables in exec statements less -confusing. (As a consequence, os.exec and python.exec have been -renamed to execv.) - -* There is a new keyword 'lambda'. An expression of the form - - lambda <parameters> : <expression> - -yields an anonymous function. This is really only syntactic sugar; -you can just as well define a local function using - - def some_temporary_name(<parameters>): return <expression> - -Lambda expressions are particularly useful in combination with map(), -filter() and reduce(), described below. Thanks to Amrit Prem for -submitting this code (as well as map(), filter(), reduce() and -xrange())! - - -Built-in functions ------------------- - -* The built-in module containing the built-in functions is called -__builtin__ instead of builtin. - -* New built-in functions map(), filter() and reduce() perform standard -functional programming operations (though not lazily): - -- map(f, seq) returns a new sequence whose items are the items from -seq with f() applied to them. - -- filter(f, seq) returns a subsequence of seq consisting of those -items for which f() is true. - -- reduce(f, seq, initial) returns a value computed as follows: - acc = initial - for item in seq: acc = f(acc, item) - return acc - -* New function xrange() creates a "range object". Its arguments are -the same as those of range(), and when used in a for loop a range -objects also behaves identical. The advantage of xrange() over -range() is that its representation (if the range contains many -elements) is much more compact than that of range(). The disadvantage -is that the result cannot be used to initialize a list object or for -the "Python idiom" [RED, GREEN, BLUE] = range(3). On some modern -architectures, benchmarks have shown that "for i in range(...): ..." -actually executes *faster* than "for i in xrange(...): ...", but on -memory starved machines like PCs running DOS range(100000) may be just -too big to be represented at all... - -* Built-in function exec() has been replaced by the exec statement -- -see above. - - -The interpreter ---------------- - -* Syntax errors are now not printed to stderr by the parser, but -rather the offending line and other relevant information are packed up -in the SyntaxError exception argument. When the main loop catches a -SyntaxError exception it will print the error in the same format as -previously, but at the proper position in the stack traceback. - -* You can now set a maximum to the number of traceback entries -printed by assigning to sys.tracebacklimit. The default is 1000. - -* The version number in .pyc files has changed yet again. - -* It is now possible to have a .pyc file without a corresponding .py -file. (Warning: this may break existing installations if you have an -old .pyc file lingering around somewhere on your module search path -without a corresponding .py file, when there is a .py file for a -module of the same name further down the path -- the new interpreter -will find the first .pyc file and complain about it, while the old -interpreter would ignore it and use the .py file further down.) - -* The list sys.builtin_module_names is now sorted and also contains -the names of a few hardwired built-in modules (sys, __main__ and -__builtin__). - -* A module can now find its own name by accessing the global variable -__name__. Assigning to this variable essentially renames the module -(it should also be stored under a different key in sys.modules). -A neat hack follows from this: a module that wants to execute a main -program when called as a script no longer needs to compare -sys.argv[0]; it can simply do "if __name__ == '__main__': main()". - -* When an object is printed by the print statement, its implementation -of str() is used. This means that classes can define __str__(self) to -direct how their instances are printed. This is different from -__repr__(self), which should define an unambigous string -representation of the instance. (If __str__() is not defined, it -defaults to __repr__().) - -* Functions and code objects can now be compared meaningfully. - -* On systems supporting SunOS or SVR4 style shared libraries, dynamic -loading of modules using shared libraries is automatically configured. -Thanks to Bill Jansen and Denis Severson for contributing this change! - - -Built-in objects ----------------- - -* File objects have acquired a new method writelines() which is the -reverse of readlines(). (It does not actually write lines, just a -list of strings, but the symmetry makes the choice of name OK.) - - -Built-in modules ----------------- - -* Socket objects no longer support the avail() method. Use the select -module instead, or use this function to replace it: - - def avail(f): - import select - return f in select.select([f], [], [], 0)[0] - -* Initialization of stdwin is done differently. It actually modifies -sys.argv (taking out the options the X version of stdwin recognizes) -the first time it is imported. - -* A new built-in module parser provides a rudimentary interface to the -python parser. Corresponding standard library modules token and symbol -defines the numeric values of tokens and non-terminal symbols. - -* The posix module has aquired new functions setuid(), setgid(), -execve(), and exec() has been renamed to execv(). - -* The array module is extended with 8-byte object swaps, the 'i' -format character, and a reverse() method. The read() and write() -methods are renamed to fromfile() and tofile(). - -* The rotor module has freed of portability bugs. This introduces a -backward compatibility problem: strings encoded with the old rotor -module can't be decoded by the new version. - -* For select.select(), a timeout (4th) argument of None means the same -as leaving the timeout argument out. - -* Module strop (and hence standard library module string) has aquired -a new function: rindex(). Thanks to Amrit Prem! - -* Module regex defines a new function symcomp() which uses an extended -regular expression syntax: parenthesized subexpressions may be labeled -using the form "\(<labelname>...\)", and the group() method can return -sub-expressions by name. Thanks to Tracy Tims for these changes! - -* Multiple threads are now supported on Solaris 2. Thanks to Sjoerd -Mullender! - - -Standard library modules ------------------------- - -* The library is now split in several subdirectories: all stuff using -stdwin is in Lib/stdwin, all SGI specific (or SGI Indigo or GL) stuff -is in Lib/sgi, all Sun Sparc specific stuff is in Lib/sun4, and all -test modules are in Lib/test. The default module search path will -include all relevant subdirectories by default. - -* Module os now knows about trying to import dos. It defines -functions execl(), execle(), execlp() and execvp(). - -* New module dospath (should be attacked by a DOS hacker though). - -* All modules defining classes now define __init__() constructors -instead of init() methods. THIS IS AN INCOMPATIBLE CHANGE! - -* Some minor changes and bugfixes module ftplib (mostly Steve -Majewski's suggestions); the debug() method is renamed to -set_debuglevel(). - -* Some new test modules (not run automatically by testall though): -test_audioop, test_md5, test_rgbimg, test_select. - -* Module string now defines rindex() and rfind() in analogy of index() -and find(). It also defines atof() and atol() (and corresponding -exceptions) in analogy to atoi(). - -* Added help() functions to modules profile and pdb. - -* The wdb debugger (now in Lib/stdwin) now shows class or instance -variables on a double click. Thanks to Sjoerd Mullender! - -* The (undocumented) module lambda has gone -- you couldn't import it -any more, and it was basically more a demo than a library module... - - -Multimedia extensions ---------------------- - -* The optional built-in modules audioop and imageop are now standard -parts of the interpreter. Thanks to Sjoerd Mullender and Jack Jansen -for contributing this code! - -* There's a new operation in audioop: minmax(). - -* There's a new built-in module called rgbimg which supports portable -efficient reading of SGI RCG image files. Thanks also to Paul -Haeberli for the original code! (Who will contribute a GIF reader?) - -* The module aifc is gone -- you should now always use aifc, which has -received a facelift. - -* There's a new module sunau., for reading Sun (and NeXT) audio files. - -* There's a new module audiodev which provides a uniform interface to -(SGI Indigo and Sun Sparc) audio hardware. - -* There's a new module sndhdr which recognizes various sound files by -looking in their header and checking for various magic words. - - -Optimizations -------------- - -* Most optimizations below can be configured by compile-time flags. -Thanks to Sjoerd Mullender for submitting these optimizations! - -* Small integers (default -1..99) are shared -- i.e. if two different -functions compute the same value it is possible (but not -guaranteed!!!) that they return the same *object*. Python programs -can detect this but should *never* rely on it. - -* Empty tuples (which all compare equal) are shared in the same -manner. - -* Tuples of size up to 20 (default) are put in separate free lists -when deallocated. - -* There is a compile-time option to cache a string's hash function, -but this appeared to have a negligeable effect, and as it costs 4 -bytes per string it is disabled by default. - - -Embedding Python ----------------- - -* The initialization interface has been simplified somewhat. You now -only call "initall()" to initialize the interpreter. - -* The previously announced renaming of externally visible identifiers -has not been carried out. It will happen in a later release. Sorry. - - -Miscellaneous bugs that have been fixed ---------------------------------------- - -* All known portability bugs. - -* Version 0.9.9 dumped core in <listobject>.sort() which has been -fixed. Thanks to Jaap Vermeulen for fixing this and posting the fix -on the mailing list while I was away! - -* Core dump on a format string ending in '%', e.g. in the expression -'%' % None. - -* The array module yielded a bogus result for concatenation (a+b would -yield a+a). - -* Some serious memory leaks in strop.split() and strop.splitfields(). - -* Several problems with the nis module. - -* Subtle problem when copying a class method from another class -through assignment (the method could not be called). - - -Remaining bugs --------------- - -* One problem with 64-bit machines remains -- since .pyc files are -portable and use only 4 bytes to represent an integer object, 64-bit -integer literals are silently truncated when written into a .pyc file. -Work-around: use eval('123456789101112'). - -* The freeze script doesn't work any more. A new and more portable -one can probably be cooked up using tricks from Extensions/mkext.py. - -* The dos support hasn't been tested yet. (Really Soon Now we should -have a PC with a working C compiler!) - - -=================================== -==> Release 0.9.9 (29 Jul 1993) <== -=================================== - -I *believe* these are the main user-visible changes in this release, -but there may be others. SGI users may scan the {src,lib}/ChangeLog -files for improvements of some SGI specific modules, e.g. aifc and -cl. Developers of extension modules should also read src/ChangeLog. - - -Naming of C symbols used by the Python interpreter --------------------------------------------------- - -* This is the last release using the current naming conventions. New -naming conventions are explained in the file misc/NAMING. -Summarizing, all externally visible symbols get (at least) a "Py" -prefix, and most functions are renamed to the standard form -PyModule_FunctionName. - -* Writers of extensions are urged to start using the new naming -conventions. The next release will use the new naming conventions -throughout (it will also have a different source directory -structure). - -* As a result of the preliminary work for the great renaming, many -functions that were accidentally global have been made static. - - -BETA X11 support ----------------- - -* There are now modules interfacing to the X11 Toolkit Intrinsics, the -Athena widgets, and the Motif 1.1 widget set. These are not yet -documented except through the examples and README file in the demo/x11 -directory. It is expected that this interface will be replaced by a -more powerful and correct one in the future, which may or may not be -backward compatible. In other words, this part of the code is at most -BETA level software! (Note: the rest of Python is rock solid as ever!) - -* I understand that the above may be a bit of a disappointment, -however my current schedule does not allow me to change this situation -before putting the release out of the door. By releasing it -undocumented and buggy, at least some of the (working!) demo programs, -like itr (my Internet Talk Radio browser) become available to a larger -audience. - -* There are also modules interfacing to SGI's "Glx" widget (a GL -window wrapped in a widget) and to NCSA's "HTML" widget (which can -format HyperText Markup Language, the document format used by the -World Wide Web). - -* I've experienced some problems when building the X11 support. In -particular, the Xm and Xaw widget sets don't go together, and it -appears that using X11R5 is better than using X11R4. Also the threads -module and its link time options may spoil things. My own strategy is -to build two Python binaries: one for use with X11 and one without -it, which can contain a richer set of built-in modules. Don't even -*think* of loading the X11 modules dynamically... - - -Environmental changes ---------------------- - -* Compiled files (*.pyc files) created by this Python version are -incompatible with those created by the previous version. Both -versions detect this and silently create a correct version, but it -means that it is not a good idea to use the same library directory for -an old and a new interpreter, since they will start to "fight" over -the *.pyc files... - -* When a stack trace is printed, the exception is printed last instead -of first. This means that if the beginning of the stack trace -scrolled out of your window you can still see what exception caused -it. - -* Sometimes interrupting a Python operation does not work because it -hangs in a blocking system call. You can now kill the interpreter by -interrupting it three times. The second time you interrupt it, a -message will be printed telling you that the third interrupt will kill -the interpreter. The "sys.exitfunc" feature still makes limited -clean-up possible in this case. - - -Changes to the command line interface -------------------------------------- - -* The python usage message is now much more informative. - -* New option -i enters interactive mode after executing a script -- -useful for debugging. - -* New option -k raises an exception when an expression statement -yields a value other than None. - -* For each option there is now also a corresponding environment -variable. - - -Using Python as an embedded language ------------------------------------- - -* The distribution now contains (some) documentation on the use of -Python as an "embedded language" in other applications, as well as a -simple example. See the file misc/EMBEDDING and the directory embed/. - - -Speed improvements ------------------- - -* Function local variables are now generally stored in an array and -accessed using an integer indexing operation, instead of through a -dictionary lookup. (This compensates the somewhat slower dictionary -lookup caused by the generalization of the dictionary module.) - - -Changes to the syntax ---------------------- - -* Continuation lines can now *sometimes* be written without a -backslash: if the continuation is contained within nesting (), [] or -{} brackets the \ may be omitted. There's a much improved -python-mode.el in the misc directory which knows about this as well. - -* You can no longer use an empty set of parentheses to define a class -without base classes. That is, you no longer write this: - - class Foo(): # syntax error - ... - -You must write this instead: - - class Foo: - ... - -This was already the preferred syntax in release 0.9.8 but many -people seemed not to have picked it up. There's a Python script that -fixes old code: demo/scripts/classfix.py. - -* There's a new reserved word: "access". The syntax and semantics are -still subject of of research and debate (as well as undocumented), but -the parser knows about the keyword so you must not use it as a -variable, function, or attribute name. - - -Changes to the semantics of the language proper ------------------------------------------------ - -* The following compatibility hack is removed: if a function was -defined with two or more arguments, and called with a single argument -that was a tuple with just as many arguments, the items of this tuple -would be used as the arguments. This is no longer supported. - - -Changes to the semantics of classes and instances -------------------------------------------------- - -* Class variables are now also accessible as instance variables for -reading (assignment creates an instance variable which overrides the -class variable of the same name though). - -* If a class attribute is a user-defined function, a new kind of -object is returned: an "unbound method". This contains a pointer to -the class and can only be called with a first argument which is a -member of that class (or a derived class). - -* If a class defines a method __init__(self, arg1, ...) then this -method is called when a class instance is created by the classname() -construct. Arguments passed to classname() are passed to the -__init__() method. The __init__() methods of base classes are not -automatically called; the derived __init__() method must call these if -necessary (this was done so the derived __init__() method can choose -the call order and arguments for the base __init__() methods). - -* If a class defines a method __del__(self) then this method is called -when an instance of the class is about to be destroyed. This makes it -possible to implement clean-up of external resources attached to the -instance. As with __init__(), the __del__() methods of base classes -are not automatically called. If __del__ manages to store a reference -to the object somewhere, its destruction is postponed; when the object -is again about to be destroyed its __del__() method will be called -again. - -* Classes may define a method __hash__(self) to allow their instances -to be used as dictionary keys. This must return a 32-bit integer. - - -Minor improvements ------------------- - -* Function and class objects now know their name (the name given in -the 'def' or 'class' statement that created them). - -* Class instances now know their class name. - - -Additions to built-in operations --------------------------------- - -* The % operator with a string left argument implements formatting -similar to sprintf() in C. The right argument is either a single -value or a tuple of values. All features of Standard C sprintf() are -supported except %p. - -* Dictionaries now support almost any key type, instead of just -strings. (The key type must be an immutable type or must be a class -instance where the class defines a method __hash__(), in order to -avoid losing track of keys whose value may change.) - -* Built-in methods are now compared properly: when comparing x.meth1 -and y.meth2, if x is equal to y and the methods are defined by the -same function, x.meth1 compares equal to y.meth2. - - -Additions to built-in functions -------------------------------- - -* str(x) returns a string version of its argument. If the argument is -a string it is returned unchanged, otherwise it returns `x`. - -* repr(x) returns the same as `x`. (Some users found it easier to -have this as a function.) - -* round(x) returns the floating point number x rounded to an whole -number, represented as a floating point number. round(x, n) returns x -rounded to n digits. - -* hasattr(x, name) returns true when x has an attribute with the given -name. - -* hash(x) returns a hash code (32-bit integer) of an arbitrary -immutable object's value. - -* id(x) returns a unique identifier (32-bit integer) of an arbitrary -object. - -* compile() compiles a string to a Python code object. - -* exec() and eval() now support execution of code objects. - - -Changes to the documented part of the library (standard modules) ----------------------------------------------------------------- - -* os.path.normpath() (a.k.a. posixpath.normpath()) has been fixed so -the border case '/foo/..' returns '/' instead of ''. - -* A new function string.find() is added with similar semantics to -string.index(); however when it does not find the given substring it -returns -1 instead of raising string.index_error. - - -Changes to built-in modules ---------------------------- - -* New optional module 'array' implements operations on sequences of -integers or floating point numbers of a particular size. This is -useful to manipulate large numerical arrays or to read and write -binary files consisting of numerical data. - -* Regular expression objects created by module regex now support a new -method named group(), which returns one or more \(...\) groups by number. -The number of groups is increased from 10 to 100. - -* Function compile() in module regex now supports an optional mapping -argument; a variable casefold is added to the module which can be used -as a standard uppercase to lowercase mapping. - -* Module time now supports many routines that are defined in the -Standard C time interface (<time.h>): gmtime(), localtime(), -asctime(), ctime(), mktime(), as well as these variables (taken from -System V): timezone, altzone, daylight and tzname. (The corresponding -functions in the undocumented module calendar have been removed; the -undocumented and unfinished module tzparse is now obsolete and will -disappear in a future release.) - -* Module strop (the fast built-in version of standard module string) -now uses C's definition of whitespace instead of fixing it to space, -tab and newline; in practice this usually means that vertical tab, -form feed and return are now also considered whitespace. It exports -the string of characters that are considered whitespace as well as the -characters that are considered lowercase or uppercase. - -* Module sys now defines the variable builtin_module_names, a list of -names of modules built into the current interpreter (including not -yet imported, but excluding two special modules that always have to be -defined -- sys and builtin). - -* Objects created by module sunaudiodev now also support flush() and -close() methods. - -* Socket objects created by module socket now support an optional -flags argument for their methods sendto() and recvfrom(). - -* Module marshal now supports dumping to and loading from strings, -through the functions dumps() and loads(). - -* Module stdwin now supports some new functionality. You may have to -ftp the latest version: ftp.cwi.nl:/pub/stdwin/stdwinforviews.tar.Z.) - - -Bugs fixed ----------- - -* Fixed comparison of negative long integers. - -* The tokenizer no longer botches input lines longer than BUFSIZ. - -* Fixed several severe memory leaks in module select. - -* Fixed memory leaks in modules socket and sv. - -* Fixed memory leak in divmod() for long integers. - -* Problems with definition of floatsleep() on Suns fixed. - -* Many portability bugs fixed (and undoubtedly new ones added :-). - - -Changes to the build procedure ------------------------------- - -* The Makefile supports some new targets: "make default" and "make -all". Both are by normally equivalent to "make python". - -* The Makefile no longer uses $> since it's not supported by all -versions of Make. - -* The header files now all contain #ifdef constructs designed to make -it safe to include the same header file twice, as well as support for -inclusion from C++ programs (automatic extern "C" { ... } added). - - -Freezing Python scripts ------------------------ - -* There is now some support for "freezing" a Python script as a -stand-alone executable binary file. See the script -demo/scripts/freeze.py. It will require some site-specific tailoring -of the script to get this working, but is quite worthwhile if you write -Python code for other who may not have built and installed Python. - - -MS-DOS ------- - -* A new MS-DOS port has been done, using MSC 6.0 (I believe). Thanks, -Marcel van der Peijl! This requires fewer compatibility hacks in -posixmodule.c. The executable is not yet available but will be soon -(check the mailing list). - -* The default PYTHONPATH has changed. - - -Changes for developers of extension modules -------------------------------------------- - -* Read src/ChangeLog for full details. - - -SGI specific changes --------------------- - -* Read src/ChangeLog for full details. - - -================================== -==> Release 0.9.8 (9 Jan 1993) <== -================================== - -I claim no completeness here, but I've tried my best to scan the log -files throughout my source tree for interesting bits of news. A more -complete account of the changes is to be found in the various -ChangeLog files. See also "News for release 0.9.7beta" below if you're -still using release 0.9.6, and the file HISTORY if you have an even -older release. - - --Guido - - -Changes to the language proper ------------------------------- - -There's only one big change: the conformance checking for function -argument lists (of user-defined functions only) is stricter. Earlier, -you could get away with the following: - - (a) define a function of one argument and call it with any - number of arguments; if the actual argument count wasn't - one, the function would receive a tuple containing the - arguments arguments (an empty tuple if there were none). - - (b) define a function of two arguments, and call it with more - than two arguments; if there were more than two arguments, - the second argument would be passed as a tuple containing - the second and further actual arguments. - -(Note that an argument (formal or actual) that is a tuple is counted as -one; these rules don't apply inside such tuples, only at the top level -of the argument list.) - -Case (a) was needed to accommodate variable-length argument lists; -there is now an explicit "varargs" feature (precede the last argument -with a '*'). Case (b) was needed for compatibility with old class -definitions: up to release 0.9.4 a method with more than one argument -had to be declared as "def meth(self, (arg1, arg2, ...)): ...". -Version 0.9.6 provide better ways to handle both casees, bot provided -backward compatibility; version 0.9.8 retracts the compatibility hacks -since they also cause confusing behavior if a function is called with -the wrong number of arguments. - -There's a script that helps converting classes that still rely on (b), -provided their methods' first argument is called "self": -demo/scripts/methfix.py. - -If this change breaks lots of code you have developed locally, try -#defining COMPAT_HACKS in ceval.c. - -(There's a third compatibility hack, which is the reverse of (a): if a -function is defined with two or more arguments, and called with a -single argument that is a tuple with just as many arguments, the items -of this tuple will be used as the arguments. Although this can (and -should!) be done using the built-in function apply() instead, it isn't -withdrawn yet.) - - -One minor change: comparing instance methods works like expected, so -that if x is an instance of a user-defined class and has a method m, -then (x.m==x.m) yields 1. - - -The following was already present in 0.9.7beta, but not explicitly -mentioned in the NEWS file: user-defined classes can now define types -that behave in almost allrespects like numbers. See -demo/classes/Rat.py for a simple example. - - -Changes to the build process ----------------------------- - -The Configure.py script and the Makefile has been made somewhat more -bullet-proof, after reports of (minor) trouble on certain platforms. - -There is now a script to patch Makefile and config.c to add a new -optional built-in module: Addmodule.sh. Read the script before using! - -Useing Addmodule.sh, all optional modules can now be configured at -compile time using Configure.py, so there are no modules left that -require dynamic loading. - -The Makefile has been fixed to make it easier to use with the VPATH -feature of some Make versions (e.g. SunOS). - - -Changes affecting portability ------------------------------ - -Several minor portability problems have been solved, e.g. "malloc.h" -has been renamed to "mymalloc.h", "strdup.c" is no longer used, and -the system now tolerates malloc(0) returning 0. - -For dynamic loading on the SGI, Jack Jansen's dl 1.6 is now -distributed with Python. This solves several minor problems, in -particular scripts invoked using #! can now use dynamic loading. - - -Changes to the interpreter interface ------------------------------------- - -On popular demand, there's finally a "profile" feature for interactive -use of the interpreter. If the environment variable $PYTHONSTARTUP is -set to the name of an existing file, Python statements in this file -are executed when the interpreter is started in interactive mode. - -There is a new clean-up mechanism, complementing try...finally: if you -assign a function object to sys.exitfunc, it will be called when -Python exits or receives a SIGTERM or SIGHUP signal. - -The interpreter is now generally assumed to live in -/usr/local/bin/python (as opposed to /usr/local/python). The script -demo/scripts/fixps.py will update old scripts in place (you can easily -modify it to do other similar changes). - -Most I/O that uses sys.stdin/stdout/stderr will now use any object -assigned to those names as long as the object supports readline() or -write() methods. - -The parser stack has been increased to 500 to accommodate more -complicated expressions (7 levels used to be the practical maximum, -it's now about 38). - -The limit on the size of the *run-time* stack has completely been -removed -- this means that tuple or list displays can contain any -number of elements (formerly more than 50 would crash the -interpreter). - - -Changes to existing built-in functions and methods --------------------------------------------------- - -The built-in functions int(), long(), float(), oct() and hex() now -also apply to class instalces that define corresponding methods -(__int__ etc.). - - -New built-in functions ----------------------- - -The new functions str() and repr() convert any object to a string. -The function repr(x) is in all respects equivalent to `x` -- some -people prefer a function for this. The function str(x) does the same -except if x is already a string -- then it returns x unchanged -(repr(x) adds quotes and escapes "funny" characters as octal escapes). - -The new function cmp(x, y) returns -1 if x<y, 0 if x==y, 1 if x>y. - - -Changes to general built-in modules ------------------------------------ - -The time module's functions are more general: time() returns a -floating point number and sleep() accepts one. Their accuracies -depends on the precision of the system clock. Millisleep is no longer -needed (although it still exists for now), but millitimer is still -needed since on some systems wall clock time is only available with -seconds precision, while a source of more precise time exists that -isn't synchronized with the wall clock. (On UNIX systems that support -the BSD gettimeofday() function, time.time() is as time.millitimer().) - -The string representation of a file object now includes an address: -'<file 'filename', mode 'r' at #######>' where ###### is a hex number -(the object's address) to make it unique. - -New functions added to posix: nice(), setpgrp(), and if your system -supports them: setsid(), setpgid(), tcgetpgrp(), tcsetpgrp(). - -Improvements to the socket module: socket objects have new methods -getpeername() and getsockname(), and the {get,set}sockopt methods can -now get/set any kind of option using strings built with the new struct -module. And there's a new function fromfd() which creates a socket -object given a file descriptor (useful for servers started by inetd, -which have a socket connected to stdin and stdout). - - -Changes to SGI-specific built-in modules ----------------------------------------- - -The FORMS library interface (fl) now requires FORMS 2.1a. Some new -functions have been added and some bugs have been fixed. - -Additions to al (audio library interface): added getname(), -getdefault() and getminmax(). - -The gl modules doesn't call "foreground()" when initialized (this -caused some problems) like it dit in 0.9.7beta (but not before). -There's a new gl function 'gversion() which returns a version string. - -The interface to sv (Indigo video interface) has totally changed. -(Sorry, still no documentation, but see the examples in -demo/sgi/{sv,video}.) - - -Changes to standard library modules ------------------------------------ - -Most functions in module string are now much faster: they're actually -implemented in C. The module containing the C versions is called -"strop" but you should still import "string" since strop doesn't -provide all the interfaces defined in string (and strop may be renamed -to string when it is complete in a future release). - -string.index() now accepts an optional third argument giving an index -where to start searching in the first argument, so you can find second -and further occurrences (this is similar to the regular expression -functions in regex). - -The definition of what string.splitfields(anything, '') should return -is changed for the last time: it returns a singleton list containing -its whole first argument unchanged. This is compatible with -regsub.split() which also ignores empty delimiter matches. - -posixpath, macpath: added dirname() and normpath() (and basename() to -macpath). - -The mainloop module (for use with stdwin) can now demultiplex input -from other sources, as long as they can be polled with select(). - - -New built-in modules --------------------- - -Module struct defines functions to pack/unpack values to/from strings -representing binary values in native byte order. - -Module strop implements C versions of many functions from string (see -above). - -Optional module fcntl defines interfaces to fcntl() and ioctl() -- -UNIX only. (Not yet properly documented -- see however src/fcntl.doc.) - -Optional module mpz defines an interface to an altaernative long -integer implementation, the GNU MPZ library. - -Optional module md5 uses the GNU MPZ library to calculate MD5 -signatures of strings. - -There are also optional new modules specific to SGI machines: imageop -defines some simple operations to images represented as strings; sv -interfaces to the Indigo video board; cl interfaces to the (yet -unreleased) compression library. - - -New standard library modules ----------------------------- - -(Unfortunately the following modules are not all documented; read the -sources to find out more about them!) - -autotest: run testall without showing any output unless it differs -from the expected output - -bisect: use bisection to insert or find an item in a sorted list - -colorsys: defines conversions between various color systems (e.g. RGB -<-> YUV) - -nntplib: a client interface to NNTP servers - -pipes: utility to construct pipeline from templates, e.g. for -conversion from one file format to another using several utilities. - -regsub: contains three functions that are more or less compatible with -awk functions of the same name: sub() and gsub() do string -substitution, split() splits a string using a regular expression to -define how separators are define. - -test_types: test operations on the built-in types of Python - -toaiff: convert various audio file formats to AIFF format - -tzparse: parse the TZ environment parameter (this may be less general -than it could be, let me know if you fix it). - -(Note that the obsolete module "path" no longer exists.) - - -New SGI-specific library modules --------------------------------- - -CL: constants for use with the built-in compression library interface (cl) - -Queue: a multi-producer, multi-consumer queue class implemented for -use with the built-in thread module - -SOCKET: constants for use with built-in module socket, e.g. to set/get -socket options. This is SGI-specific because the constants to be -passed are system-dependent. You can generate a version for your own -system by running the script demo/scripts/h2py.py with -/usr/include/sys/socket.h as input. - -cddb: interface to the database used the the CD player - -torgb: convert various image file types to rgb format (requires pbmplus) - - -New demos ---------- - -There's an experimental interface to define Sun RPC clients and -servers in demo/rpc. - -There's a collection of interfaces to WWW, WAIS and Gopher (both -Python classes and program providing a user interface) in demo/www. -This includes a program texi2html.py which converts texinfo files to -HTML files (the format used hy WWW). - -The ibrowse demo has moved from demo/stdwin/ibrowse to demo/ibrowse. - -For SGI systems, there's a whole collection of programs and classes -that make use of the Indigo video board in demo/sgi/{sv,video}. This -represents a significant amount of work that we're giving away! - -There are demos "rsa" and "md5test" that exercise the mpz and md5 -modules, respectively. The rsa demo is a complete implementation of -the RSA public-key cryptosystem! - -A bunch of games and examples submitted by Stoffel Erasmus have been -included in demo/stoffel. - -There are miscellaneous new files in some existing demo -subdirectories: classes/bitvec.py, scripts/{fixps,methfix}.py, -sgi/al/cmpaf.py, sockets/{mcast,gopher}.py. - -There are also many minor changes to existing files, but I'm too lazy -to run a diff and note the differences -- you can do this yourself if -you save the old distribution's demos. One highlight: the -stdwin/python.py demo is much improved! - - -Changes to the documentation ----------------------------- - -The LaTeX source for the library uses different macros to enable it to -be converted to texinfo, and from there to INFO or HTML format so it -can be browsed as a hypertext. The net result is that you can now -read the Python library documentation in Emacs info mode! - - -Changes to the source code that affect C extension writers ----------------------------------------------------------- - -The function strdup() no longer exists (it was used only in one places -and is somewhat of a a portability problem sice some systems have the -same function in their C library. - -The functions NEW() and RENEW() allocate one spare byte to guard -against a NULL return from malloc(0) being taken for an error, but -this should not be relied upon. - - -========================= -==> Release 0.9.7beta <== -========================= - - -Changes to the language proper ------------------------------- - -User-defined classes can now implement operations invoked through -special syntax, such as x[i] or `x` by defining methods named -__getitem__(self, i) or __repr__(self), etc. - - -Changes to the build process ----------------------------- - -Instead of extensive manual editing of the Makefile to select -compile-time options, you can now run a Configure.py script. -The Makefile as distributed builds a minimal interpreter sufficient to -run Configure.py. See also misc/BUILD - -The Makefile now includes more "utility" targets, e.g. install and -tags/TAGS - -Using the provided strtod.c and strtol.c are now separate options, as -on the Sun the provided strtod.c dumps core :-( - -The regex module is now an option chosen by the Makefile, since some -(old) C compilers choke on regexpr.c - - -Changes affecting portability ------------------------------ - -You need STDWIN version 0.9.7 (released 30 June 1992) for the stdwin -interface - -Dynamic loading is now supported for Sun (and other non-COFF systems) -throug dld-3.2.3, as well as for SGI (a new version of Jack Jansen's -DL is out, 1.4) - -The system-dependent code for the use of the select() system call is -moved to one file: myselect.h - -Thanks to Jaap Vermeulen, the code should now port cleanly to the -SEQUENT - - -Changes to the interpreter interface ------------------------------------- - -The interpretation of $PYTHONPATH in the environment is different: it -is inserted in front of the default path instead of overriding it - - -Changes to existing built-in functions and methods --------------------------------------------------- - -List objects now support an optional argument to their sort() method, -which is a comparison function similar to qsort(3) in C - -File objects now have a method fileno(), used by the new select module -(see below) - - -New built-in function ---------------------- - -coerce(x, y): take two numbers and return a tuple containing them -both converted to a common type - - -Changes to built-in modules ---------------------------- - -sys: fixed core dumps in settrace() and setprofile() - -socket: added socket methods setsockopt() and getsockopt(); and -fileno(), used by the new select module (see below) - -stdwin: added fileno() == connectionnumber(), in support of new module -select (see below) - -posix: added get{eg,eu,g,u}id(); waitpid() is now a separate function. - -gl: added qgetfd() - -fl: added several new functions, fixed several obscure bugs, adapted -to FORMS 2.1 - - -Changes to standard modules ---------------------------- - -posixpath: changed implementation of ismount() - -string: atoi() no longer mistakes leading zero for octal number - -... - - -New built-in modules --------------------- - -Modules marked "dynamic only" are not configured at compile time but -can be loaded dynamically. You need to turn on the DL or DLD option in -the Makefile for support dynamic loading of modules (this requires -external code). - -select: interfaces to the BSD select() system call - -dbm: interfaces to the (new) dbm library (dynamic only) - -nis: interfaces to some NIS functions (aka yellow pages) - -thread: limited form of multiple threads (sgi only) - -audioop: operations useful for audio programs, e.g. u-LAW and ADPCM -coding (dynamic only) - -cd: interface to Indigo SCSI CDROM player audio library (sgi only) - -jpeg: read files in JPEG format (dynamic only, sgi only; needs -external code) - -imgfile: read SGI image files (dynamic only, sgi only) - -sunaudiodev: interface to sun's /dev/audio (dynamic only, sun only) - -sv: interface to Indigo video library (sgi only) - -pc: a minimal set of MS-DOS interfaces (MS-DOS only) - -rotor: encryption, by Lance Ellinghouse (dynamic only) - - -New standard modules --------------------- - -Not all these modules are documented. Read the source: -lib/<modulename>.py. Sometimes a file lib/<modulename>.doc contains -additional documentation. - -imghdr: recognizes image file headers - -sndhdr: recognizes sound file headers - -profile: print run-time statistics of Python code - -readcd, cdplayer: companion modules for built-in module cd (sgi only) - -emacs: interface to Emacs using py-connect.el (see below). - -SOCKET: symbolic constant definitions for socket options - -SUNAUDIODEV: symbolic constant definitions for sunaudiodef (sun only) - -SV: symbolic constat definitions for sv (sgi only) - -CD: symbolic constat definitions for cd (sgi only) - - -New demos ---------- - -scripts/pp.py: execute Python as a filter with a Perl-like command -line interface - -classes/: examples using the new class features - -threads/: examples using the new thread module - -sgi/cd/: examples using the new cd module - - -Changes to the documentation ----------------------------- - -The last-minute syntax changes of release 0.9.6 are now reflected -everywhere in the manuals - -The reference manual has a new section (3.2) on implementing new kinds -of numbers, sequences or mappings with user classes - -Classes are now treated extensively in the tutorial (chapter 9) - -Slightly restructured the system-dependent chapters of the library -manual - -The file misc/EXTENDING incorporates documentation for mkvalue() and -a new section on error handling - -The files misc/CLASSES and misc/ERRORS are no longer necessary - -The doc/Makefile now creates PostScript files automatically - - -Miscellaneous changes ---------------------- - -Incorporated Tim Peters' changes to python-mode.el, it's now version -1.06 - -A python/Emacs bridge (provided by Terrence M. Brannon) lets a Python -program running in an Emacs buffer execute Emacs lisp code. The -necessary Python code is in lib/emacs.py. The Emacs code is -misc/py-connect.el (it needs some external Emacs lisp code) - - -Changes to the source code that affect C extension writers ----------------------------------------------------------- - -New service function mkvalue() to construct a Python object from C -values according to a "format" string a la getargs() - -Most functions from pythonmain.c moved to new pythonrun.c which is -in libpython.a. This should make embedded versions of Python easier - -ceval.h is split in eval.h (which needs compile.h and only declares -eval_code) and ceval.h (which doesn't need compile.hand declares the -rest) - -ceval.h defines macros BGN_SAVE / END_SAVE for use with threads (to -improve the parallellism of multi-threaded programs by letting other -Python code run when a blocking system call or something similar is -made) - -In structmember.[ch], new member types BYTE, CHAR and unsigned -variants have been added - -New file xxmodule.c is a template for new extension modules. - - -================================== -==> RELEASE 0.9.6 (6 Apr 1992) <== -================================== - -Misc news in 0.9.6: -- Restructured the misc subdirectory -- Reference manual completed, library manual much extended (with indexes!) -- the GNU Readline library is now distributed standard with Python -- the script "../demo/scripts/classfix.py" fixes Python modules using old - class syntax -- Emacs python-mode.el (was python.el) vastly improved (thanks, Tim!) -- Because of the GNU copyleft business I am not using the GNU regular - expression implementation but a free re-implementation by Tatu Ylonen - that recently appeared in comp.sources.misc (Bravo, Tatu!) - -New features in 0.9.6: -- stricter try stmt syntax: cannot mix except and finally clauses on 1 try -- New module 'os' supplants modules 'mac' and 'posix' for most cases; - module 'path' is replaced by 'os.path' -- os.path.split() return value differs from that of old path.split() -- sys.exc_type, sys.exc_value, sys.exc_traceback are set to the exception - currently being handled -- sys.last_type, sys.last_value, sys.last_traceback remember last unhandled - exception -- New function string.expandtabs() expands tabs in a string -- Added times() interface to posix (user & sys time of process & children) -- Added uname() interface to posix (returns OS type, hostname, etc.) -- New built-in function execfile() is like exec() but from a file -- Functions exec() and eval() are less picky about whitespace/newlines -- New built-in functions getattr() and setattr() access arbitrary attributes -- More generic argument handling in built-in functions (see "./EXTENDING") -- Dynamic loading of modules written in C or C++ (see "./DYNLOAD") -- Division and modulo for long and plain integers with negative operands - have changed; a/b is now floor(float(a)/float(b)) and a%b is defined - as a-(a/b)*b. So now the outcome of divmod(a,b) is the same as - (a/b, a%b) for integers. For floats, % is also changed, but of course - / is unchanged, and divmod(x,y) does not yield (x/y, x%y)... -- A function with explicit variable-length argument list can be declared - like this: def f(*args): ...; or even like this: def f(a, b, *rest): ... -- Code tracing and profiling features have been added, and two source - code debuggers are provided in the library (pdb.py, tty-oriented, - and wdb, window-oriented); you can now step through Python programs! - See sys.settrace() and sys.setprofile(), and "../lib/pdb.doc" -- '==' is now the only equality operator; "../demo/scripts/eqfix.py" is - a script that fixes old Python modules -- Plain integer right shift now uses sign extension -- Long integer shift/mask operations now simulate 2's complement - to give more useful results for negative operands -- Changed/added range checks for long/plain integer shifts -- Options found after "-c command" are now passed to the command in sys.argv - (note subtle incompatiblity with "python -c command -- -options"!) -- Module stdwin is better protected against touching objects after they've - been closed; menus can now also be closed explicitly -- Stdwin now uses its own exception (stdwin.error) - -New features in 0.9.5 (released as Macintosh application only, 2 Jan 1992): -- dictionary objects can now be compared properly; e.g., {}=={} is true -- new exception SystemExit causes termination if not caught; - it is raised by sys.exit() so that 'finally' clauses can clean up, - and it may even be caught. It does work interactively! -- new module "regex" implements GNU Emacs style regular expressions; - module "regexp" is rewritten in Python for backward compatibility -- formal parameter lists may contain trailing commas - -Bugs fixed in 0.9.6: -- assigning to or deleting a list item with a negative index dumped core -- divmod(-10L,5L) returned (-3L, 5L) instead of (-2L, 0L) - -Bugs fixed in 0.9.5: -- masking operations involving negative long integers gave wrong results - - -=================================== -==> RELEASE 0.9.4 (24 Dec 1991) <== -=================================== - -- new function argument handling (see below) -- built-in apply(func, args) means func(args[0], args[1], ...) -- new, more refined exceptions -- new exception string values (NameError = 'NameError' etc.) -- better checking for math exceptions -- for sequences (string/tuple/list), x[-i] is now equivalent to x[len(x)-i] -- fixed list assignment bug: "a[1:1] = a" now works correctly -- new class syntax, without extraneous parentheses -- new 'global' statement to assign global variables from within a function - - -New class syntax ----------------- - -You can now declare a base class as follows: - - class B: # Was: class B(): - def some_method(self): ... - ... - -and a derived class thusly: - - class D(B): # Was: class D() = B(): - def another_method(self, arg): ... - -Multiple inheritance looks like this: - - class M(B, D): # Was: class M() = B(), D(): - def this_or_that_method(self, arg): ... - -The old syntax is still accepted by Python 0.9.4, but will disappear -in Python 1.0 (to be posted to comp.sources). - - -New 'global' statement ----------------------- - -Every now and then you have a global variable in a module that you -want to change from within a function in that module -- say, a count -of calls to a function, or an option flag, etc. Until now this was -not directly possible. While several kludges are known that -circumvent the problem, and often the need for a global variable can -be avoided by rewriting the module as a class, this does not always -lead to clearer code. - -The 'global' statement solves this dilemma. Its occurrence in a -function body means that, for the duration of that function, the -names listed there refer to global variables. For instance: - - total = 0.0 - count = 0 - - def add_to_total(amount): - global total, count - total = total + amount - count = count + 1 - -'global' must be repeated in each function where it is needed. The -names listed in a 'global' statement must not be used in the function -before the statement is reached. - -Remember that you don't need to use 'global' if you only want to *use* -a global variable in a function; nor do you need ot for assignments to -parts of global variables (e.g., list or dictionary items or -attributes of class instances). This has not changed; in fact -assignment to part of a global variable was the standard workaround. - - -New exceptions --------------- - -Several new exceptions have been defined, to distinguish more clearly -between different types of errors. - -name meaning was - -AttributeError reference to non-existing attribute NameError -IOError unexpected I/O error RuntimeError -ImportError import of non-existing module or name NameError -IndexError invalid string, tuple or list index RuntimeError -KeyError key not in dictionary RuntimeError -OverflowError numeric overflow RuntimeError -SyntaxError invalid syntax RuntimeError -ValueError invalid argument value RuntimeError -ZeroDivisionError division by zero RuntimeError - -The string value of each exception is now its name -- this makes it -easier to experimentally find out which operations raise which -exceptions; e.g.: - - >>> KeyboardInterrupt - 'KeyboardInterrupt' - >>> - - -New argument passing semantics ------------------------------- - -Off-line discussions with Steve Majewski and Daniel LaLiberte have -convinced me that Python's parameter mechanism could be changed in a -way that made both of them happy (I hope), kept me happy, fixed a -number of outstanding problems, and, given some backward compatibility -provisions, would only break a very small amount of existing code -- -probably all mine anyway. In fact I suspect that most Python users -will hardly notice the difference. And yet it has cost me at least -one sleepless night to decide to make the change... - -Philosophically, the change is quite radical (to me, anyway): a -function is no longer called with either zero or one argument, which -is a tuple if there appear to be more arguments. Every function now -has an argument list containing 0, 1 or more arguments. This list is -always implemented as a tuple, and it is a (run-time) error if a -function is called with a different number of arguments than expected. - -What's the difference? you may ask. The answer is, very little unless -you want to write variadic functions -- functions that may be called -with a variable number of arguments. Formerly, you could write a -function that accepted one or more arguments with little trouble, but -writing a function that could be called with either 0 or 1 argument -(or more) was next to impossible. This is now a piece of cake: you -can simply declare an argument that receives the entire argument -tuple, and check its length -- it will be of size 0 if there are no -arguments. - -Another anomaly of the old system was the way multi-argument methods -(in classes) had to be declared, e.g.: - - class Point(): - def init(self, (x, y, color)): ... - def setcolor(self, color): ... - dev moveto(self, (x, y)): ... - def draw(self): ... - -Using the new scheme there is no need to enclose the method arguments -in an extra set of parentheses, so the above class could become: - - class Point: - def init(self, x, y, color): ... - def setcolor(self, color): ... - dev moveto(self, x, y): ... - def draw(self): ... - -That is, the equivalence rule between methods and functions has -changed so that now p.moveto(x,y) is equivalent to Point.moveto(p,x,y) -while formerly it was equivalent to Point.moveto(p,(x,y)). - -A special backward compatibility rule makes that the old version also -still works: whenever a function with exactly two arguments (at the top -level) is called with more than two arguments, the second and further -arguments are packed into a tuple and passed as the second argument. -This rule is invoked independently of whether the function is actually a -method, so there is a slight chance that some erroneous calls of -functions expecting two arguments with more than that number of -arguments go undetected at first -- when the function tries to use the -second argument it may find it is a tuple instead of what was expected. -Note that this rule will be removed from future versions of the -language; it is a backward compatibility provision *only*. - -Two other rules and a new built-in function handle conversion between -tuples and argument lists: - -Rule (a): when a function with more than one argument is called with a -single argument that is a tuple of the right size, the tuple's items -are used as arguments. - -Rule (b): when a function with exactly one argument receives no -arguments or more than one, that one argument will receive a tuple -containing the arguments (the tuple will be empty if there were no -arguments). - - -A new built-in function, apply(), was added to support functions that -need to call other functions with a constructed argument list. The call - - apply(function, tuple) - -is equivalent to - - function(tuple[0], tuple[1], ..., tuple[len(tuple)-1]) - - -While no new argument syntax was added in this phase, it would now be -quite sensible to add explicit syntax to Python for default argument -values (as in C++ or Modula-3), or a "rest" argument to receive the -remaining arguments of a variable-length argument list. - - -======================================================== -==> Release 0.9.3 (never made available outside CWI) <== -======================================================== - -- string sys.version shows current version (also printed on interactive entry) -- more detailed exceptions, e.g., IOError, ZeroDivisionError, etc. -- 'global' statement to declare module-global variables assigned in functions. -- new class declaration syntax: class C(Base1, Base2, ...): suite - (the old syntax is still accepted -- be sure to convert your classes now!) -- C shifting and masking operators: << >> ~ & ^ | (for ints and longs). -- C comparison operators: == != (the old = and <> remain valid). -- floating point numbers may now start with a period (e.g., .14). -- definition of integer division tightened (always truncates towards zero). -- new builtins hex(x), oct(x) return hex/octal string from (long) integer. -- new list method l.count(x) returns the number of occurrences of x in l. -- new SGI module: al (Indigo and 4D/35 audio library). -- the FORMS interface (modules fl and FL) now uses FORMS 2.0 -- module gl: added lrect{read,write}, rectzoom and pixmode; - added (non-GL) functions (un)packrect. -- new socket method: s.allowbroadcast(flag). -- many objects support __dict__, __methods__ or __members__. -- dir() lists anything that has __dict__. -- class attributes are no longer read-only. -- classes support __bases__, instances support __class__ (and __dict__). -- divmod() now also works for floats. -- fixed obscure bug in eval('1 '). - - -=================================== -==> Release 0.9.2 (Autumn 1991) <== -=================================== - -Highlights ----------- - -- tutorial now (almost) complete; library reference reorganized -- new syntax: continue statement; semicolons; dictionary constructors; - restrictions on blank lines in source files removed -- dramatically improved module load time through precompiled modules -- arbitrary precision integers: compute 2 to the power 1000 and more... -- arithmetic operators now accept mixed type operands, e.g., 3.14/4 -- more operations on list: remove, index, reverse; repetition -- improved/new file operations: readlines, seek, tell, flush, ... -- process management added to the posix module: fork/exec/wait/kill etc. -- BSD socket operations (with example servers and clients!) -- many new STDWIN features (color, fonts, polygons, ...) -- new SGI modules: font manager and FORMS library interface - - -Extended list of changes in 0.9.2 ---------------------------------- - -Here is a summary of the most important user-visible changes in 0.9.2, -in somewhat arbitrary order. Changes in later versions are listed in -the "highlights" section above. - - -1. Changes to the interpreter proper - -- Simple statements can now be separated by semicolons. - If you write "if t: s1; s2", both s1 and s2 are executed - conditionally. -- The 'continue' statement was added, with semantics as in C. -- Dictionary displays are now allowed on input: {key: value, ...}. -- Blank lines and lines bearing only a comment no longer need to - be indented properly. (A completely empty line still ends a multi- - line statement interactively.) -- Mixed arithmetic is supported, 1 compares equal to 1.0, etc. -- Option "-c command" to execute statements from the command line -- Compiled versions of modules are cached in ".pyc" files, giving a - dramatic improvement of start-up time -- Other, smaller speed improvements, e.g., extracting characters from - strings, looking up single-character keys, and looking up global - variables -- Interrupting a print operation raises KeyboardInterrupt instead of - only cancelling the print operation -- Fixed various portability problems (it now passes gcc with only - warnings -- more Standard C compatibility will be provided in later - versions) -- Source is prepared for porting to MS-DOS -- Numeric constants are now checked for overflow (this requires - standard-conforming strtol() and strtod() functions; a correct - strtol() implementation is provided, but the strtod() provided - relies on atof() for everything, including error checking - - -2. Changes to the built-in types, functions and modules - -- New module socket: interface to BSD socket primitives -- New modules pwd and grp: access the UNIX password and group databases -- (SGI only:) New module "fm" interfaces to the SGI IRIX Font Manager -- (SGI only:) New module "fl" interfaces to Mark Overmars' FORMS library -- New numeric type: long integer, for unlimited precision - - integer constants suffixed with 'L' or 'l' are long integers - - new built-in function long(x) converts int or float to long - - int() and float() now also convert from long integers -- New built-in function: - - pow(x, y) returns x to the power y -- New operation and methods for lists: - - l*n returns a new list consisting of n concatenated copies of l - - l.remove(x) removes the first occurrence of the value x from l - - l.index(x) returns the index of the first occurrence of x in l - - l.reverse() reverses l in place -- New operation for tuples: - - t*n returns a tuple consisting of n concatenated copies of t -- Improved file handling: - - f.readline() no longer restricts the line length, is faster, - and isn't confused by null bytes; same for raw_input() - - f.read() without arguments reads the entire (rest of the) file - - mixing of print and sys.stdout.write() has different effect -- New methods for files: - - f.readlines() returns a list containing the lines of the file, - as read with f.readline() - - f.flush(), f.tell(), f.seek() call their stdio counterparts - - f.isatty() tests for "tty-ness" -- New posix functions: - - _exit(), exec(), fork(), getpid(), getppid(), kill(), wait() - - popen() returns a file object connected to a pipe - - utime() replaces utimes() (the latter is not a POSIX name) -- New stdwin features, including: - - font handling - - color drawing - - scroll bars made optional - - polygons - - filled and xor shapes - - text editing objects now have a 'settext' method - - -3. Changes to the standard library - -- Name change: the functions path.cat and macpath.cat are now called - path.join and macpath.join -- Added new modules: formatter, mutex, persist, sched, mainloop -- Added some modules and functionality to the "widget set" (which is - still under development, so please bear with me): - DirList, FormSplit, TextEdit, WindowSched -- Fixed module testall to work non-interactively -- Module string: - - added functions join() and joinfields() - - fixed center() to work correct and make it "transitive" -- Obsolete modules were removed: util, minmax -- Some modules were moved to the demo directory - - -4. Changes to the demonstration programs - -- Added new useful scipts: byteyears, eptags, fact, from, lfact, - objgraph, pdeps, pi, primes, ptags, which -- Added a bunch of socket demos -- Doubled the speed of ptags -- Added new stdwin demos: microedit, miniedit -- Added a windowing interface to the Python interpreter: python (most - useful on the Mac) -- Added a browser for Emacs info files: demo/stdwin/ibrowse - (yes, I plan to put all STDWIN and Python documentation in texinfo - form in the future) - - -5. Other changes to the distribution - -- An Emacs Lisp file "python.el" is provided to facilitate editing - Python programs in GNU Emacs (slightly improved since posted to - gnu.emacs.sources) -- Some info on writing an extension in C is provided -- Some info on building Python on non-UNIX platforms is provided - - -===================================== -==> Release 0.9.1 (February 1991) <== -===================================== - -- Micro changes only -- Added file "patchlevel.h" - - -===================================== -==> Release 0.9.0 (February 1991) <== -===================================== - -Original posting to alt.sources. diff --git a/Misc/HPUX-NOTES b/Misc/HPUX-NOTES deleted file mode 100644 index 33ce4d49a1..0000000000 --- a/Misc/HPUX-NOTES +++ /dev/null @@ -1,21 +0,0 @@ -Subject: Dynamic Linking under HP-UX -From: "C. Derek Fields" <derek@gamekeeper.bellcore.com> -Date: Thu, 08 Sep 94 14:14:07 -0400 - -There are two important points. First, the python executable must be -linked with the -E option to explicitly export all symbols. This -works with the vanilla interpreter, but I am not sure how friendly it -will be when I try to embed the interpreter in a larger application. -It may be necessary to hand tune the exports using the -e option. -Anyway, the additional flag to $(CC) is "-Wl,-E", which passes the -E -flag to the compiler. My link line (from an actual run) looks like -this: - -cc config.o -Wl,-E libModules.a ../Python/libPython.a ../Objects/libObjects.a ../Parser/libParser.a -lm -ldld -o python - -Second, the dynamic module must be compiled with the +z option to make -it position independent and then linked into a shared library: - -ld -b -o <modName>module.sl <object list> - -The -b tells the linker to produce a shared library. diff --git a/Misc/HYPE b/Misc/HYPE deleted file mode 100644 index ff39f4990b..0000000000 --- a/Misc/HYPE +++ /dev/null @@ -1,70 +0,0 @@ -Newsgroups: comp.lang.misc,comp.lang.c,comp.lang.c++,comp.lang.perl,comp.lang.tcl -Followup-to: comp.lang.misc -Subject: Python 1.0.0 is out! - ---> Tired of decyphering the Perl code you wrote last week? - ---> Frustrated with Bourne shell syntax? - ---> Spent too much time staring at core dumps lately? - -Maybe you should try Python, the next generation object-oriented -scripting and prototyping language, with a *readable* syntax. Python -has been used by hundreds of happy users all over the world during the -past three years, and is now ready for prime time. - -Python is an interpreted language, and has the usual advantages of -such languages, such as run-time checks (e.g. bounds checking), -execution of dynamically generated code, automatic memory allocation, -high level operations on strings, lists and dictionaries (associative -arrays), and a fast edit-compile-run cycle. Additionally, it features -modules, classes, exceptions, and dynamic linking of extensions -written in C or C++. It has arbitrary precision integers. - -Python can be run interactively, and there is an extensive Emacs -editing mode which includes the capability to execute regions of code. -For the truly desperate there is a source level debugger (written in -Python, of course :-). - -Python comes with a large library of standard modules and classes, as -well as an extensive set of demo programs. It has interfaces to most -Unix system calls and library functions, and there exist extensions -that interface to window systems and graphics libraries like X and -SGI's GL. - -Python's source (in C) and documentation (in LaTeX and PostScript) are -freely available on the Internet. It builds without intervention on -most Unix platforms: error-free builds have been confirmed for SGI -IRIX 4 and 5, Sun SunOS 4 and Solaris 2, HP-UX, DEC Ultrix and OSF/1, -IBM AIX, and SCO ODT 3.0. A Macintosh binary is also available -- a -DOS binary is in the works. - -If you have a WWW viewer (e.g. Mosaic), you can see all Python -documentation on-line: point your viewer at the URL -http://www.cwi.nl/~guido/Python.html. - -The source and documentation are available by anonymous ftp from the -following sites -- please pick the one closest to you: - -Site IP address Directory - -ftp.cwi.nl 192.16.184.180 /pub/python -gatekeeper.dec.com 16.1.0.2 /pub/plan/python/cwi -ftp.uu.net 192.48.96.9 /languages/python -ftp.fu-berlin.de 130.133.4.50 /pub/unix/languages/python - -The file is called python1.0.0.tar.Z (some mirror sites convert it to -a .gz file or split it up in separate parts). See the INDEX file for -other goodies: FAQ, NEWS, PostScript, Emacs info, Mac binary, etc. -(Please don't ask me to mail it to you -- at 1.76 Megabytes it is -unwieldy at least...) - -There's a mailing list; write to <python-list@cwi.nl> to subscribe (no -LISTSERV commands please). A FAQ list is regularly posted to -comp.lang.misc. A newsgroup may be created in the near future. - -[Excuse the hype -- Python really is a neat language, if I may say so. -Please direct all followups to comp.lang.misc only.] - ---Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl> -URL: <http://www.cwi.nl/cwi/people/Guido.van.Rossum.html> diff --git a/Misc/Makefile b/Misc/Makefile deleted file mode 100644 index 9df7110976..0000000000 --- a/Misc/Makefile +++ /dev/null @@ -1,10 +0,0 @@ -all: - @echo Nothing to make in this directory. - -clean: - find . '(' -name '*.pyc' -o -name core -o -name '*~' \ - -o -name '[@,#]*' -o -name '*.old' \ - -o -name '*.orig' -o -name '*.rej' ')' \ - -print -exec rm -f {} ';' - -clobber: clean diff --git a/Misc/NEWS b/Misc/NEWS deleted file mode 100644 index 7df75dbb14..0000000000 --- a/Misc/NEWS +++ /dev/null @@ -1,153 +0,0 @@ -===================================== -==> Release 1.3 (13 October 1995) <== -===================================== - -Major change -============ - -Two words: Keyword Arguments. See the first section of Chapter 12 of -the Tutorial. - -(The rest of this file is textually the same as the remaining sections -of that chapter.) - - -Changes to the WWW and Internet tools -===================================== - -The "htmllib" module has been rewritten in an incompatible fashion. -The new version is considerably more complete (HTML 2.0 except forms, -but including all ISO-8859-1 entity definitions), and easy to use. -Small changes to "sgmllib" have also been made, to better match the -tokenization of HTML as recognized by other web tools. - -A new module "formatter" has been added, for use with the new -"htmllib" module. - -The "urllib"and "httplib" modules have been changed somewhat to allow -overriding unknown URL types and to support authentication. They now -use "mimetools.Message" instead of "rfc822.Message" to parse headers. -The "endrequest()" method has been removed from the HTTP class since -it breaks the interaction with some servers. - -The "rfc822.Message" class has been changed to allow a flag to be -passed in that says that the file is unseekable. - -The "ftplib" module has been fixed to be (hopefully) more robust on -Linux. - -Several new operations that are optionally supported by servers have -been added to "nntplib": "xover", "xgtitle", "xpath" and "date". - -Other Language Changes -====================== - -The "raise" statement now takes an optional argument which specifies -the traceback to be used when printing the exception's stack trace. -This must be a traceback object, such as found in "sys.exc_traceback". -When omitted or given as "None", the old behavior (to generate a stack -trace entry for the current stack frame) is used. - -The tokenizer is now more tolerant of alien whitespace. Control-L in -the leading whitespace of a line resets the column number to zero, -while Control-R just before the end of the line is ignored. - -Changes to Built-in Operations -============================== - -For file objects, "f.read(0)" and "f.readline(0)" now return an empty -string rather than reading an unlimited number of bytes. For the -latter, omit the argument altogether or pass a negative value. - -A new system variable, "sys.platform", has been added. It specifies -the current platform, e.g. "sunos5" or "linux1". - -The built-in functions "input()" and "raw_input()" now use the GNU -readline library when it has been configured (formerly, only -interactive input to the interpreter itself was read using GNU -readline). The GNU readline library provides elaborate line editing -and history. The Python debugger ("pdb") is the first beneficiary of -this change. - -Two new built-in functions, "globals()" and "locals()", provide access -to dictionaries containming current global and local variables, -respectively. (These augment rather than replace "vars()", which -returns the current local variables when called without an argument, -and a module's global variables when called with an argument of type -module.) - -The built-in function "compile()" now takes a third possible value for -the kind of code to be compiled: specifying "'single'" generates code -for a single interactive statement, which prints the output of -expression statements that evaluate to something else than "None". - -Library Changes -=============== - -There are new module "ni" and "ihooks" that support importing modules -with hierarchical names such as "A.B.C". This is enabled by writing -"import ni; ni.ni()" at the very top of the main program. These -modules are amply documented in the Python source. - -The module "rexec" has been rewritten (incompatibly) to define a class -and to use "ihooks". - -The "string.split()" and "string.splitfields()" functions are now the -same function (the presence or absence of the second argument -determines which operation is invoked); similar for "string.join()" -and "string.joinfields()". - -The "Tkinter" module and its helper "Dialog" have been revamped to use -keyword arguments. Tk 4.0 is now the standard. A new module -"FileDialog" has been added which implements standard file selection -dialogs. - -The optional built-in modules "dbm" and "gdbm" are more coordinated ---- their "open()" functions now take the same values for their "flag" -argument, and the "flag" and "mode" argument have default values (to -open the database for reading only, and to create the database with -mode "0666" minuse the umask, respectively). The memory leaks have -finally been fixed. - -A new dbm-like module, "bsddb", has been added, which uses the BSD DB -package's hash method. - -A portable (though slow) dbm-clone, implemented in Python, has been -added for systems where none of the above is provided. It is aptly -dubbed "dumbdbm". - -The module "anydbm" provides a unified interface to "bsddb", "gdbm", -"dbm", and "dumbdbm", choosing the first one available. - -A new extension module, "binascii", provides a variety of operations -for conversion of text-encoded binary data. - -There are three new or rewritten companion modules implemented in -Python that can encode and decode the most common such formats: "uu" -(uuencode), "base64" and "binhex". - -A module to handle the MIME encoding quoted-printable has also been -added: "quopri". - -The parser module (which provides an interface to the Python parser's -abstract syntax trees) has been rewritten (incompatibly) by Fred -Drake. It now lets you change the parse tree and compile the result! - -The \code{syslog} module has been upgraded and documented. - -Other Changes -============= - -The dynamic module loader recognizes the fact that different filenames -point to the same shared library and loads the library only once, so -you can have a single shared library that defines multiple modules. -(SunOS / SVR4 style shared libraries only.) - -Jim Fulton's ``abstract object interface'' has been incorporated into -the run-time API. For more detailes, read the files -"Include/abstract.h" and "Objects/abstract.c". - -The Macintosh version is much more robust now. - -Numerous things I have forgotten or that are so obscure no-one will -notice them anyway :-) diff --git a/Misc/QuickRef-1.1.1.ps b/Misc/QuickRef-1.1.1.ps deleted file mode 100644 index 39ff862cfe..0000000000 --- a/Misc/QuickRef-1.1.1.ps +++ /dev/null @@ -1,6639 +0,0 @@ -%!PS-Adobe-3.0 -%%BoundingBox: (atend) -%%Pages: (atend) -%%PageOrder: (atend) -%%DocumentFonts: (atend) -%%Creator: Frame 4.0 -%%DocumentData: Clean7Bit -%%EndComments -%%BeginProlog -% -% Frame ps_prolog 4.0, for use with Frame 4.0 products -% This ps_prolog file is Copyright (c) 1986-1993 Frame Technology -% Corporation. All rights reserved. This ps_prolog file may be -% freely copied and distributed in conjunction with documents created -% using FrameMaker, FrameBuilder and FrameViewer as long as this -% copyright notice is preserved. -% -% Frame products normally print colors as their true color on a color printer -% or as shades of gray, based on luminance, on a black-and white printer. The -% following flag, if set to True, forces all non-white colors to print as pure -% black. This has no effect on bitmap images. -/FMPrintAllColorsAsBlack false def -% -% Frame products can either set their own line screens or use a printer's -% default settings. Three flags below control this separately for no -% separations, spot separations and process separations. If a flag -% is true, then the default printer settings will not be changed. If it is -% false, Frame products will use their own settings from a table based on -% the printer's resolution. -/FMUseDefaultNoSeparationScreen true def -/FMUseDefaultSpotSeparationScreen true def -/FMUseDefaultProcessSeparationScreen false def -% -% For any given PostScript printer resolution, Frame products have two sets of -% screen angles and frequencies for printing process separations, which are -% recomended by Adobe. The following variable chooses the higher frequencies -% when set to true or the lower frequencies when set to false. This is only -% effective if the appropriate FMUseDefault...SeparationScreen flag is false. -/FMUseHighFrequencyScreens true def -% -% PostScript Level 2 printers contain an "Accurate Screens" feature which can -% improve process separation rendering at the expense of compute time. This -% flag is ignored by PostScript Level 1 printers. -/FMUseAcccurateScreens true def -% -% The following PostScript procedure defines the spot function that Frame -% products will use for process separations. You may un-comment-out one of -% the alternative functions below, or use your own. -% -% Dot function -/FMSpotFunction {abs exch abs 2 copy add 1 gt - {1 sub dup mul exch 1 sub dup mul add 1 sub } - {dup mul exch dup mul add 1 exch sub }ifelse } def -% -% Line function -% /FMSpotFunction { pop } def -% -% Elipse function -% /FMSpotFunction { dup 5 mul 8 div mul exch dup mul exch add -% sqrt 1 exch sub } def -% -% -/FMversion (4.0) def -/FMLevel1 /languagelevel where {pop languagelevel} {1} ifelse 2 lt def -/FMPColor - FMLevel1 { - false - /colorimage where {pop pop true} if - } { - true - } ifelse -def -/FrameDict 400 dict def -systemdict /errordict known not {/errordict 10 dict def - errordict /rangecheck {stop} put} if -% The readline in PS 23.0 doesn't recognize cr's as nl's on AppleTalk -FrameDict /tmprangecheck errordict /rangecheck get put -errordict /rangecheck {FrameDict /bug true put} put -FrameDict /bug false put -mark -% Some PS machines read past the CR, so keep the following 3 lines together! -currentfile 5 string readline -00 -0000000000 -cleartomark -errordict /rangecheck FrameDict /tmprangecheck get put -FrameDict /bug get { - /readline { - /gstring exch def - /gfile exch def - /gindex 0 def - { - gfile read pop - dup 10 eq {exit} if - dup 13 eq {exit} if - gstring exch gindex exch put - /gindex gindex 1 add def - } loop - pop - gstring 0 gindex getinterval true - } bind def - } if -/FMshowpage /showpage load def -/FMquit /quit load def -/FMFAILURE { - dup = flush - FMshowpage - /Helvetica findfont 12 scalefont setfont - 72 200 moveto - show FMshowpage - FMquit - } def -/FMVERSION { - FMversion ne { - (Frame product version does not match ps_prolog!) FMFAILURE - } if - } def -/FMBADEPSF { - (PostScript Lang. Ref. Man., 2nd Ed., H.2.4 says EPS must not call X ) - dup dup (X) search pop exch pop exch pop length - 4 -1 roll - putinterval - FMFAILURE - } def -/FMLOCAL { - FrameDict begin - 0 def - end - } def -/concatprocs - { - /proc2 exch cvlit def/proc1 exch cvlit def/newproc proc1 length proc2 length add array def - newproc 0 proc1 putinterval newproc proc1 length proc2 putinterval newproc cvx -}def -FrameDict begin -/FMnone 0 def -/FMcyan 1 def -/FMmagenta 2 def -/FMyellow 3 def -/FMblack 4 def -/FMcustom 5 def -/FrameNegative false def -/FrameSepIs FMnone def -/FrameSepBlack 0 def -/FrameSepYellow 0 def -/FrameSepMagenta 0 def -/FrameSepCyan 0 def -/FrameSepRed 1 def -/FrameSepGreen 1 def -/FrameSepBlue 1 def -/FrameCurGray 1 def -/FrameCurPat null def -/FrameCurColors [ 0 0 0 1 0 0 0 ] def -/FrameColorEpsilon .001 def -/eqepsilon { - sub dup 0 lt {neg} if - FrameColorEpsilon le -} bind def -/FrameCmpColorsCMYK { - 2 copy 0 get exch 0 get eqepsilon { - 2 copy 1 get exch 1 get eqepsilon { - 2 copy 2 get exch 2 get eqepsilon { - 3 get exch 3 get eqepsilon - } {pop pop false} ifelse - }{pop pop false} ifelse - } {pop pop false} ifelse -} bind def -/FrameCmpColorsRGB { - 2 copy 4 get exch 0 get eqepsilon { - 2 copy 5 get exch 1 get eqepsilon { - 6 get exch 2 get eqepsilon - }{pop pop false} ifelse - } {pop pop false} ifelse -} bind def -/RGBtoCMYK { - 1 exch sub - 3 1 roll - 1 exch sub - 3 1 roll - 1 exch sub - 3 1 roll - 3 copy - 2 copy - le { pop } { exch pop } ifelse - 2 copy - le { pop } { exch pop } ifelse - dup dup dup - 6 1 roll - 4 1 roll - 7 1 roll - sub - 6 1 roll - sub - 5 1 roll - sub - 4 1 roll -} bind def -/CMYKtoRGB { - dup dup 4 -1 roll add - 5 1 roll 3 -1 roll add - 4 1 roll add - 1 exch sub dup 0 lt {pop 0} if 3 1 roll - 1 exch sub dup 0 lt {pop 0} if exch - 1 exch sub dup 0 lt {pop 0} if exch -} bind def -/FrameSepInit { - 1.0 RealSetgray -} bind def -/FrameSetSepColor { - /FrameSepBlue exch def - /FrameSepGreen exch def - /FrameSepRed exch def - /FrameSepBlack exch def - /FrameSepYellow exch def - /FrameSepMagenta exch def - /FrameSepCyan exch def - /FrameSepIs FMcustom def - setCurrentScreen -} bind def -/FrameSetCyan { - /FrameSepBlue 1.0 def - /FrameSepGreen 1.0 def - /FrameSepRed 0.0 def - /FrameSepBlack 0.0 def - /FrameSepYellow 0.0 def - /FrameSepMagenta 0.0 def - /FrameSepCyan 1.0 def - /FrameSepIs FMcyan def - setCurrentScreen -} bind def - -/FrameSetMagenta { - /FrameSepBlue 1.0 def - /FrameSepGreen 0.0 def - /FrameSepRed 1.0 def - /FrameSepBlack 0.0 def - /FrameSepYellow 0.0 def - /FrameSepMagenta 1.0 def - /FrameSepCyan 0.0 def - /FrameSepIs FMmagenta def - setCurrentScreen -} bind def - -/FrameSetYellow { - /FrameSepBlue 0.0 def - /FrameSepGreen 1.0 def - /FrameSepRed 1.0 def - /FrameSepBlack 0.0 def - /FrameSepYellow 1.0 def - /FrameSepMagenta 0.0 def - /FrameSepCyan 0.0 def - /FrameSepIs FMyellow def - setCurrentScreen -} bind def - -/FrameSetBlack { - /FrameSepBlue 0.0 def - /FrameSepGreen 0.0 def - /FrameSepRed 0.0 def - /FrameSepBlack 1.0 def - /FrameSepYellow 0.0 def - /FrameSepMagenta 0.0 def - /FrameSepCyan 0.0 def - /FrameSepIs FMblack def - setCurrentScreen -} bind def - -/FrameNoSep { - /FrameSepIs FMnone def - setCurrentScreen -} bind def -/FrameSetSepColors { - FrameDict begin - [ exch 1 add 1 roll ] - /FrameSepColors - exch def end - } bind def -/FrameColorInSepListCMYK { - FrameSepColors { - exch dup 3 -1 roll - FrameCmpColorsCMYK - { pop true exit } if - } forall - dup true ne {pop false} if - } bind def -/FrameColorInSepListRGB { - FrameSepColors { - exch dup 3 -1 roll - FrameCmpColorsRGB - { pop true exit } if - } forall - dup true ne {pop false} if - } bind def -/RealSetgray /setgray load def -/RealSetrgbcolor /setrgbcolor load def -/RealSethsbcolor /sethsbcolor load def -end -/setgray { - FrameDict begin - FrameSepIs FMnone eq - { RealSetgray } - { - FrameSepIs FMblack eq - { RealSetgray } - { FrameSepIs FMcustom eq - FrameSepRed 0 eq and - FrameSepGreen 0 eq and - FrameSepBlue 0 eq and { - RealSetgray - } { - 1 RealSetgray pop - } ifelse - } ifelse - } ifelse - end -} bind def -/setrgbcolor { - FrameDict begin - FrameSepIs FMnone eq - { RealSetrgbcolor } - { - 3 copy [ 4 1 roll ] - FrameColorInSepListRGB - { - FrameSepBlue eq exch - FrameSepGreen eq and exch - FrameSepRed eq and - { 0 } { 1 } ifelse - } - { - FMPColor { - RealSetrgbcolor - currentcmykcolor - } { - RGBtoCMYK - } ifelse - FrameSepIs FMblack eq - {1.0 exch sub 4 1 roll pop pop pop} { - FrameSepIs FMyellow eq - {pop 1.0 exch sub 3 1 roll pop pop} { - FrameSepIs FMmagenta eq - {pop pop 1.0 exch sub exch pop } { - FrameSepIs FMcyan eq - {pop pop pop 1.0 exch sub } - {pop pop pop pop 1} ifelse } ifelse } ifelse } ifelse - } ifelse - RealSetgray - } - ifelse - end -} bind def -/sethsbcolor { - FrameDict begin - FrameSepIs FMnone eq - { RealSethsbcolor } - { - RealSethsbcolor - currentrgbcolor - setrgbcolor - } - ifelse - end -} bind def -FrameDict begin -/setcmykcolor where { - pop /RealSetcmykcolor /setcmykcolor load def -} { - /RealSetcmykcolor { - 4 1 roll - 3 { 3 index add 0 max 1 min 1 exch sub 3 1 roll} repeat - setrgbcolor pop - } bind def -} ifelse -userdict /setcmykcolor { - FrameDict begin - FrameSepIs FMnone eq - { RealSetcmykcolor } - { - 4 copy [ 5 1 roll ] - FrameColorInSepListCMYK - { - FrameSepBlack eq exch - FrameSepYellow eq and exch - FrameSepMagenta eq and exch - FrameSepCyan eq and - { 0 } { 1 } ifelse - } - { - FrameSepIs FMblack eq - {1.0 exch sub 4 1 roll pop pop pop} { - FrameSepIs FMyellow eq - {pop 1.0 exch sub 3 1 roll pop pop} { - FrameSepIs FMmagenta eq - {pop pop 1.0 exch sub exch pop } { - FrameSepIs FMcyan eq - {pop pop pop 1.0 exch sub } - {pop pop pop pop 1} ifelse } ifelse } ifelse } ifelse - } ifelse - RealSetgray - } - ifelse - end - } bind put -FMLevel1 not { - - /patProcDict 5 dict dup begin - <0f1e3c78f0e1c387> { 3 setlinewidth -1 -1 moveto 9 9 lineto stroke - 4 -4 moveto 12 4 lineto stroke - -4 4 moveto 4 12 lineto stroke} bind def - <0f87c3e1f0783c1e> { 3 setlinewidth -1 9 moveto 9 -1 lineto stroke - -4 4 moveto 4 -4 lineto stroke - 4 12 moveto 12 4 lineto stroke} bind def - <8142241818244281> { 1 setlinewidth -1 9 moveto 9 -1 lineto stroke - -1 -1 moveto 9 9 lineto stroke } bind def - <03060c183060c081> { 1 setlinewidth -1 -1 moveto 9 9 lineto stroke - 4 -4 moveto 12 4 lineto stroke - -4 4 moveto 4 12 lineto stroke} bind def - <8040201008040201> { 1 setlinewidth -1 9 moveto 9 -1 lineto stroke - -4 4 moveto 4 -4 lineto stroke - 4 12 moveto 12 4 lineto stroke} bind def - end def - /patDict 15 dict dup begin - /PatternType 1 def - /PaintType 2 def - /TilingType 3 def - /BBox [ 0 0 8 8 ] def - /XStep 8 def - /YStep 8 def - /PaintProc { - begin - patProcDict bstring known { - patProcDict bstring get exec - } { - 8 8 true [1 0 0 -1 0 8] bstring imagemask - } ifelse - end - } bind def - end def -} if -/combineColor { - FrameSepIs FMnone eq - { - graymode FMLevel1 or not { - - [/Pattern [/DeviceCMYK]] setcolorspace - FrameCurColors 0 4 getinterval aload pop FrameCurPat setcolor - } { - FrameCurColors 3 get 1.0 ge { - FrameCurGray RealSetgray - } { - FMPColor graymode and { - 0 1 3 { - FrameCurColors exch get - 1 FrameCurGray sub mul - } for - RealSetcmykcolor - } { - 4 1 6 { - FrameCurColors exch get - graymode { - 1 exch sub 1 FrameCurGray sub mul 1 exch sub - } { - 1.0 lt {FrameCurGray} {1} ifelse - } ifelse - } for - RealSetrgbcolor - } ifelse - } ifelse - } ifelse - } { - FrameCurColors 0 4 getinterval aload - FrameColorInSepListCMYK { - FrameSepBlack eq exch - FrameSepYellow eq and exch - FrameSepMagenta eq and exch - FrameSepCyan eq and - FrameSepIs FMcustom eq and - { FrameCurGray } { 1 } ifelse - } { - FrameSepIs FMblack eq - {FrameCurGray 1.0 exch sub mul 1.0 exch sub 4 1 roll pop pop pop} { - FrameSepIs FMyellow eq - {pop FrameCurGray 1.0 exch sub mul 1.0 exch sub 3 1 roll pop pop} { - FrameSepIs FMmagenta eq - {pop pop FrameCurGray 1.0 exch sub mul 1.0 exch sub exch pop } { - FrameSepIs FMcyan eq - {pop pop pop FrameCurGray 1.0 exch sub mul 1.0 exch sub } - {pop pop pop pop 1} ifelse } ifelse } ifelse } ifelse - } ifelse - graymode FMLevel1 or not { - - [/Pattern [/DeviceGray]] setcolorspace - FrameCurPat setcolor - } { - graymode not FMLevel1 and { - - dup 1 lt {pop FrameCurGray} if - } if - RealSetgray - } ifelse - } ifelse -} bind def -/savematrix { - orgmatrix currentmatrix pop - } bind def -/restorematrix { - orgmatrix setmatrix - } bind def -/dmatrix matrix def -/dpi 72 0 dmatrix defaultmatrix dtransform - dup mul exch dup mul add sqrt def - -/freq dpi dup 72 div round dup 0 eq {pop 1} if 8 mul div def -/sangle 1 0 dmatrix defaultmatrix dtransform exch atan def -/dpiranges [ 2540 2400 1693 1270 1200 635 600 0 ] def -/CMLowFreqs [ 100.402 94.8683 89.2289 100.402 94.8683 66.9349 63.2456 47.4342 ] def -/YLowFreqs [ 95.25 90.0 84.65 95.25 90.0 70.5556 66.6667 50.0 ] def -/KLowFreqs [ 89.8026 84.8528 79.8088 89.8026 84.8528 74.8355 70.7107 53.033 ] def -/CLowAngles [ 71.5651 71.5651 71.5651 71.5651 71.5651 71.5651 71.5651 71.5651 ] def -/MLowAngles [ 18.4349 18.4349 18.4349 18.4349 18.4349 18.4349 18.4349 18.4349 ] def -/YLowTDot [ true true false true true false false false ] def -/CMHighFreqs [ 133.87 126.491 133.843 108.503 102.523 100.402 94.8683 63.2456 ] def -/YHighFreqs [ 127.0 120.0 126.975 115.455 109.091 95.25 90.0 60.0 ] def -/KHighFreqs [ 119.737 113.137 119.713 128.289 121.218 89.8026 84.8528 63.6395 ] def -/CHighAngles [ 71.5651 71.5651 71.5651 70.0169 70.0169 71.5651 71.5651 71.5651 ] def -/MHighAngles [ 18.4349 18.4349 18.4349 19.9831 19.9831 18.4349 18.4349 18.4349 ] def -/YHighTDot [ false false true false false true true false ] def -/PatFreq [ 10.5833 10.0 9.4055 10.5833 10.0 10.5833 10.0 9.375 ] def -/screenIndex { - 0 1 dpiranges length 1 sub { dup dpiranges exch get 1 sub dpi le {exit} {pop} ifelse } for -} bind def -/getCyanScreen { - FMUseHighFrequencyScreens { CHighAngles CMHighFreqs} {CLowAngles CMLowFreqs} ifelse - screenIndex dup 3 1 roll get 3 1 roll get /FMSpotFunction load -} bind def -/getMagentaScreen { - FMUseHighFrequencyScreens { MHighAngles CMHighFreqs } {MLowAngles CMLowFreqs} ifelse - screenIndex dup 3 1 roll get 3 1 roll get /FMSpotFunction load -} bind def -/getYellowScreen { - FMUseHighFrequencyScreens { YHighTDot YHighFreqs} { YLowTDot YLowFreqs } ifelse - screenIndex dup 3 1 roll get 3 1 roll get { 3 div - {2 { 1 add 2 div 3 mul dup floor sub 2 mul 1 sub exch} repeat - FMSpotFunction } } {/FMSpotFunction load } ifelse - 0.0 exch -} bind def -/getBlackScreen { - FMUseHighFrequencyScreens { KHighFreqs } { KLowFreqs } ifelse - screenIndex get 45.0 /FMSpotFunction load -} bind def -/getSpotScreen { - getBlackScreen -} bind def -/getCompositeScreen { - getBlackScreen -} bind def -/FMSetScreen - FMLevel1 { /setscreen load - }{ { - 8 dict begin - /HalftoneType 1 def - /SpotFunction exch def - /Angle exch def - /Frequency exch def - /AccurateScreens FMUseAcccurateScreens def - currentdict end sethalftone - } bind } ifelse -def -/setDefaultScreen { - FMPColor { - orgrxfer cvx orggxfer cvx orgbxfer cvx orgxfer cvx setcolortransfer - } - { - orgxfer cvx settransfer - } ifelse - orgfreq organgle orgproc cvx setscreen -} bind def -/setCurrentScreen { - FrameSepIs FMnone eq { - FMUseDefaultNoSeparationScreen { - setDefaultScreen - } { - getCompositeScreen FMSetScreen - } ifelse - } { - FrameSepIs FMcustom eq { - FMUseDefaultSpotSeparationScreen { - setDefaultScreen - } { - getSpotScreen FMSetScreen - } ifelse - } { - FMUseDefaultProcessSeparationScreen { - setDefaultScreen - } { - FrameSepIs FMcyan eq { - getCyanScreen FMSetScreen - } { - FrameSepIs FMmagenta eq { - getMagentaScreen FMSetScreen - } { - FrameSepIs FMyellow eq { - getYellowScreen FMSetScreen - } { - getBlackScreen FMSetScreen - } ifelse - } ifelse - } ifelse - } ifelse - } ifelse - } ifelse -} bind def -end - /gstring FMLOCAL - /gfile FMLOCAL - /gindex FMLOCAL - /orgrxfer FMLOCAL - /orggxfer FMLOCAL - /orgbxfer FMLOCAL - /orgxfer FMLOCAL - /orgproc FMLOCAL - /orgrproc FMLOCAL - /orggproc FMLOCAL - /orgbproc FMLOCAL - /organgle FMLOCAL - /orgrangle FMLOCAL - /orggangle FMLOCAL - /orgbangle FMLOCAL - /orgfreq FMLOCAL - /orgrfreq FMLOCAL - /orggfreq FMLOCAL - /orgbfreq FMLOCAL - /yscale FMLOCAL - /xscale FMLOCAL - /edown FMLOCAL - /manualfeed FMLOCAL - /paperheight FMLOCAL - /paperwidth FMLOCAL -/FMDOCUMENT { - array /FMfonts exch def - /#copies exch def - FrameDict begin - 0 ne /manualfeed exch def - /paperheight exch def - /paperwidth exch def - 0 ne /FrameNegative exch def - 0 ne /edown exch def - /yscale exch def - /xscale exch def - FMLevel1 { - manualfeed {setmanualfeed} if - /FMdicttop countdictstack 1 add def - /FMoptop count def - setpapername - manualfeed {true} {papersize} ifelse - {manualpapersize} {false} ifelse - {desperatepapersize} {false} ifelse - { (Can't select requested paper size for Frame print job!) FMFAILURE } if - count -1 FMoptop {pop pop} for - countdictstack -1 FMdicttop {pop end} for - } - {{1 dict dup /PageSize [paperwidth paperheight]put setpagedevice}stopped - { (Can't select requested paper size for Frame print job!) FMFAILURE } if - {1 dict dup /ManualFeed manualfeed put setpagedevice } stopped pop } - ifelse - - FMPColor { - currentcolorscreen - cvlit /orgproc exch def - /organgle exch def - /orgfreq exch def - cvlit /orgbproc exch def - /orgbangle exch def - /orgbfreq exch def - cvlit /orggproc exch def - /orggangle exch def - /orggfreq exch def - cvlit /orgrproc exch def - /orgrangle exch def - /orgrfreq exch def - currentcolortransfer - FrameNegative { - 1 1 4 { - pop { 1 exch sub } concatprocs 4 1 roll - } for - 4 copy - setcolortransfer - } if - cvlit /orgxfer exch def - cvlit /orgbxfer exch def - cvlit /orggxfer exch def - cvlit /orgrxfer exch def - } { - currentscreen - cvlit /orgproc exch def - /organgle exch def - /orgfreq exch def - - currenttransfer - FrameNegative { - { 1 exch sub } concatprocs - dup settransfer - } if - cvlit /orgxfer exch def - } ifelse - end -} def -/pagesave FMLOCAL -/orgmatrix FMLOCAL -/landscape FMLOCAL -/pwid FMLOCAL -/FMBEGINPAGE { - FrameDict begin - /pagesave save def - 3.86 setmiterlimit - /landscape exch 0 ne def - landscape { - 90 rotate 0 exch dup /pwid exch def neg translate pop - }{ - pop /pwid exch def - } ifelse - edown { [-1 0 0 1 pwid 0] concat } if - 0 0 moveto paperwidth 0 lineto paperwidth paperheight lineto - 0 paperheight lineto 0 0 lineto 1 setgray fill - xscale yscale scale - /orgmatrix matrix def - gsave -} def -/FMENDPAGE { - grestore - pagesave restore - end - showpage - } def -/FMFONTDEFINE { - FrameDict begin - findfont - ReEncode - 1 index exch - definefont - FMfonts 3 1 roll - put - end - } def -/FMFILLS { - FrameDict begin dup - array /fillvals exch def - dict /patCache exch def - end - } def -/FMFILL { - FrameDict begin - fillvals 3 1 roll put - end - } def -/FMNORMALIZEGRAPHICS { - newpath - 0.0 0.0 moveto - 1 setlinewidth - 0 setlinecap - 0 0 0 sethsbcolor - 0 setgray - } bind def - /fx FMLOCAL - /fy FMLOCAL - /fh FMLOCAL - /fw FMLOCAL - /llx FMLOCAL - /lly FMLOCAL - /urx FMLOCAL - /ury FMLOCAL -/FMBEGINEPSF { - end - /FMEPSF save def - /showpage {} def -% See Adobe's "PostScript Language Reference Manual, 2nd Edition", page 714. -% "...the following operators MUST NOT be used in an EPS file:" (emphasis ours) - /banddevice {(banddevice) FMBADEPSF} def - /clear {(clear) FMBADEPSF} def - /cleardictstack {(cleardictstack) FMBADEPSF} def - /copypage {(copypage) FMBADEPSF} def - /erasepage {(erasepage) FMBADEPSF} def - /exitserver {(exitserver) FMBADEPSF} def - /framedevice {(framedevice) FMBADEPSF} def - /grestoreall {(grestoreall) FMBADEPSF} def - /initclip {(initclip) FMBADEPSF} def - /initgraphics {(initgraphics) FMBADEPSF} def - /initmatrix {(initmatrix) FMBADEPSF} def - /quit {(quit) FMBADEPSF} def - /renderbands {(renderbands) FMBADEPSF} def - /setglobal {(setglobal) FMBADEPSF} def - /setpagedevice {(setpagedevice) FMBADEPSF} def - /setshared {(setshared) FMBADEPSF} def - /startjob {(startjob) FMBADEPSF} def - /lettertray {(lettertray) FMBADEPSF} def - /letter {(letter) FMBADEPSF} def - /lettersmall {(lettersmall) FMBADEPSF} def - /11x17tray {(11x17tray) FMBADEPSF} def - /11x17 {(11x17) FMBADEPSF} def - /ledgertray {(ledgertray) FMBADEPSF} def - /ledger {(ledger) FMBADEPSF} def - /legaltray {(legaltray) FMBADEPSF} def - /legal {(legal) FMBADEPSF} def - /statementtray {(statementtray) FMBADEPSF} def - /statement {(statement) FMBADEPSF} def - /executivetray {(executivetray) FMBADEPSF} def - /executive {(executive) FMBADEPSF} def - /a3tray {(a3tray) FMBADEPSF} def - /a3 {(a3) FMBADEPSF} def - /a4tray {(a4tray) FMBADEPSF} def - /a4 {(a4) FMBADEPSF} def - /a4small {(a4small) FMBADEPSF} def - /b4tray {(b4tray) FMBADEPSF} def - /b4 {(b4) FMBADEPSF} def - /b5tray {(b5tray) FMBADEPSF} def - /b5 {(b5) FMBADEPSF} def - FMNORMALIZEGRAPHICS - [/fy /fx /fh /fw /ury /urx /lly /llx] {exch def} forall - fx fw 2 div add fy fh 2 div add translate - rotate - fw 2 div neg fh 2 div neg translate - fw urx llx sub div fh ury lly sub div scale - llx neg lly neg translate - /FMdicttop countdictstack 1 add def - /FMoptop count def - } bind def -/FMENDEPSF { - count -1 FMoptop {pop pop} for - countdictstack -1 FMdicttop {pop end} for - FMEPSF restore - FrameDict begin - } bind def -FrameDict begin -/setmanualfeed { -%%BeginFeature *ManualFeed True - statusdict /manualfeed true put -%%EndFeature - } bind def -/max {2 copy lt {exch} if pop} bind def -/min {2 copy gt {exch} if pop} bind def -/inch {72 mul} def -/pagedimen { - paperheight sub abs 16 lt exch - paperwidth sub abs 16 lt and - {/papername exch def} {pop} ifelse - } bind def - /papersizedict FMLOCAL -/setpapername { - /papersizedict 14 dict def - papersizedict begin - /papername /unknown def - /Letter 8.5 inch 11.0 inch pagedimen - /LetterSmall 7.68 inch 10.16 inch pagedimen - /Tabloid 11.0 inch 17.0 inch pagedimen - /Ledger 17.0 inch 11.0 inch pagedimen - /Legal 8.5 inch 14.0 inch pagedimen - /Statement 5.5 inch 8.5 inch pagedimen - /Executive 7.5 inch 10.0 inch pagedimen - /A3 11.69 inch 16.5 inch pagedimen - /A4 8.26 inch 11.69 inch pagedimen - /A4Small 7.47 inch 10.85 inch pagedimen - /B4 10.125 inch 14.33 inch pagedimen - /B5 7.16 inch 10.125 inch pagedimen - end - } bind def -/papersize { - papersizedict begin - /Letter {lettertray letter} def - /LetterSmall {lettertray lettersmall} def - /Tabloid {11x17tray 11x17} def - /Ledger {ledgertray ledger} def - /Legal {legaltray legal} def - /Statement {statementtray statement} def - /Executive {executivetray executive} def - /A3 {a3tray a3} def - /A4 {a4tray a4} def - /A4Small {a4tray a4small} def - /B4 {b4tray b4} def - /B5 {b5tray b5} def - /unknown {unknown} def - papersizedict dup papername known {papername} {/unknown} ifelse get - end - statusdict begin stopped end - } bind def -/manualpapersize { - papersizedict begin - /Letter {letter} def - /LetterSmall {lettersmall} def - /Tabloid {11x17} def - /Ledger {ledger} def - /Legal {legal} def - /Statement {statement} def - /Executive {executive} def - /A3 {a3} def - /A4 {a4} def - /A4Small {a4small} def - /B4 {b4} def - /B5 {b5} def - /unknown {unknown} def - papersizedict dup papername known {papername} {/unknown} ifelse get - end - stopped - } bind def -/desperatepapersize { - statusdict /setpageparams known - { - paperwidth paperheight 0 1 - statusdict begin - {setpageparams} stopped - end - } {true} ifelse - } bind def -/DiacriticEncoding [ -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/.notdef /.notdef /.notdef /.notdef /space /exclam /quotedbl -/numbersign /dollar /percent /ampersand /quotesingle /parenleft -/parenright /asterisk /plus /comma /hyphen /period /slash /zero /one -/two /three /four /five /six /seven /eight /nine /colon /semicolon -/less /equal /greater /question /at /A /B /C /D /E /F /G /H /I /J /K -/L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /backslash -/bracketright /asciicircum /underscore /grave /a /b /c /d /e /f /g /h -/i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /braceleft /bar -/braceright /asciitilde /.notdef /Adieresis /Aring /Ccedilla /Eacute -/Ntilde /Odieresis /Udieresis /aacute /agrave /acircumflex /adieresis -/atilde /aring /ccedilla /eacute /egrave /ecircumflex /edieresis -/iacute /igrave /icircumflex /idieresis /ntilde /oacute /ograve -/ocircumflex /odieresis /otilde /uacute /ugrave /ucircumflex -/udieresis /dagger /.notdef /cent /sterling /section /bullet -/paragraph /germandbls /registered /copyright /trademark /acute -/dieresis /.notdef /AE /Oslash /.notdef /.notdef /.notdef /.notdef -/yen /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef -/ordfeminine /ordmasculine /.notdef /ae /oslash /questiondown -/exclamdown /logicalnot /.notdef /florin /.notdef /.notdef -/guillemotleft /guillemotright /ellipsis /.notdef /Agrave /Atilde -/Otilde /OE /oe /endash /emdash /quotedblleft /quotedblright -/quoteleft /quoteright /.notdef /.notdef /ydieresis /Ydieresis -/fraction /currency /guilsinglleft /guilsinglright /fi /fl /daggerdbl -/periodcentered /quotesinglbase /quotedblbase /perthousand -/Acircumflex /Ecircumflex /Aacute /Edieresis /Egrave /Iacute -/Icircumflex /Idieresis /Igrave /Oacute /Ocircumflex /.notdef /Ograve -/Uacute /Ucircumflex /Ugrave /dotlessi /circumflex /tilde /macron -/breve /dotaccent /ring /cedilla /hungarumlaut /ogonek /caron -] def -/ReEncode { - dup - length - dict begin - { - 1 index /FID ne - {def} - {pop pop} ifelse - } forall - 0 eq {/Encoding DiacriticEncoding def} if - currentdict - end - } bind def -FMPColor - - { - /BEGINBITMAPCOLOR { - BITMAPCOLOR} def - /BEGINBITMAPCOLORc { - BITMAPCOLORc} def - /BEGINBITMAPTRUECOLOR { - BITMAPTRUECOLOR } def - /BEGINBITMAPTRUECOLORc { - BITMAPTRUECOLORc } def - } - - { - /BEGINBITMAPCOLOR { - BITMAPGRAY} def - /BEGINBITMAPCOLORc { - BITMAPGRAYc} def - /BEGINBITMAPTRUECOLOR { - BITMAPTRUEGRAY } def - /BEGINBITMAPTRUECOLORc { - BITMAPTRUEGRAYc } def - } -ifelse -/K { - FMPrintAllColorsAsBlack { - dup 1 eq 2 index 1 eq and 3 index 1 eq and not - {7 {pop} repeat 0 0 0 1 0 0 0} if - } if - FrameCurColors astore - pop combineColor -} bind def -/graymode true def - /bwidth FMLOCAL - /bpside FMLOCAL - /bstring FMLOCAL - /onbits FMLOCAL - /offbits FMLOCAL - /xindex FMLOCAL - /yindex FMLOCAL - /x FMLOCAL - /y FMLOCAL -/setPatternMode { - FMLevel1 { - /bwidth exch def - /bpside exch def - /bstring exch def - /onbits 0 def /offbits 0 def - freq sangle landscape {90 add} if - {/y exch def - /x exch def - /xindex x 1 add 2 div bpside mul cvi def - /yindex y 1 add 2 div bpside mul cvi def - bstring yindex bwidth mul xindex 8 idiv add get - 1 7 xindex 8 mod sub bitshift and 0 ne FrameNegative {not} if - {/onbits onbits 1 add def 1} - {/offbits offbits 1 add def 0} - ifelse - } - setscreen - offbits offbits onbits add div FrameNegative {1.0 exch sub} if - /FrameCurGray exch def - } { - pop pop - dup patCache exch known { - patCache exch get - } { - dup - patDict /bstring 3 -1 roll put - patDict - 9 PatFreq screenIndex get div dup matrix scale - makepattern - dup - patCache 4 -1 roll 3 -1 roll put - } ifelse - /FrameCurGray 0 def - /FrameCurPat exch def - } ifelse - /graymode false def - combineColor -} bind def -/setGrayScaleMode { - graymode not { - /graymode true def - FMLevel1 { - setCurrentScreen - } if - } if - /FrameCurGray exch def - combineColor -} bind def -/normalize { - transform round exch round exch itransform - } bind def -/dnormalize { - dtransform round exch round exch idtransform - } bind def -/lnormalize { - 0 dtransform exch cvi 2 idiv 2 mul 1 add exch idtransform pop - } bind def -/H { - lnormalize setlinewidth - } bind def -/Z { - setlinecap - } bind def - -/PFill { - graymode FMLevel1 or not { - gsave 1 setgray eofill grestore - } if -} bind def -/PStroke { - graymode FMLevel1 or not { - gsave 1 setgray stroke grestore - } if - stroke -} bind def - /fillvals FMLOCAL -/X { - fillvals exch get - dup type /stringtype eq - {8 1 setPatternMode} - {setGrayScaleMode} - ifelse - } bind def -/V { - PFill gsave eofill grestore - } bind def -/Vclip { - clip - } bind def -/Vstrk { - currentlinewidth exch setlinewidth PStroke setlinewidth - } bind def -/N { - PStroke - } bind def -/Nclip { - strokepath clip newpath - } bind def -/Nstrk { - currentlinewidth exch setlinewidth PStroke setlinewidth - } bind def -/M {newpath moveto} bind def -/E {lineto} bind def -/D {curveto} bind def -/O {closepath} bind def - /n FMLOCAL -/L { - /n exch def - newpath - normalize - moveto - 2 1 n {pop normalize lineto} for - } bind def -/Y { - L - closepath - } bind def - /x1 FMLOCAL - /x2 FMLOCAL - /y1 FMLOCAL - /y2 FMLOCAL -/R { - /y2 exch def - /x2 exch def - /y1 exch def - /x1 exch def - x1 y1 - x2 y1 - x2 y2 - x1 y2 - 4 Y - } bind def - /rad FMLOCAL -/rarc - {rad - arcto - } bind def -/RR { - /rad exch def - normalize - /y2 exch def - /x2 exch def - normalize - /y1 exch def - /x1 exch def - mark - newpath - { - x1 y1 rad add moveto - x1 y2 x2 y2 rarc - x2 y2 x2 y1 rarc - x2 y1 x1 y1 rarc - x1 y1 x1 y2 rarc - closepath - } stopped {x1 y1 x2 y2 R} if - cleartomark - } bind def -/RRR { - /rad exch def - normalize /y4 exch def /x4 exch def - normalize /y3 exch def /x3 exch def - normalize /y2 exch def /x2 exch def - normalize /y1 exch def /x1 exch def - newpath - normalize moveto - mark - { - x2 y2 x3 y3 rarc - x3 y3 x4 y4 rarc - x4 y4 x1 y1 rarc - x1 y1 x2 y2 rarc - closepath - } stopped - {x1 y1 x2 y2 x3 y3 x4 y4 newpath moveto lineto lineto lineto closepath} if - cleartomark - } bind def -/C { - grestore - gsave - R - clip - setCurrentScreen -} bind def -/CP { - grestore - gsave - Y - clip - setCurrentScreen -} bind def - /FMpointsize FMLOCAL -/F { - FMfonts exch get - FMpointsize scalefont - setfont - } bind def -/Q { - /FMpointsize exch def - F - } bind def -/T { - moveto show - } bind def -/RF { - rotate - 0 ne {-1 1 scale} if - } bind def -/TF { - gsave - moveto - RF - show - grestore - } bind def -/P { - moveto - 0 32 3 2 roll widthshow - } bind def -/PF { - gsave - moveto - RF - 0 32 3 2 roll widthshow - grestore - } bind def -/S { - moveto - 0 exch ashow - } bind def -/SF { - gsave - moveto - RF - 0 exch ashow - grestore - } bind def -/B { - moveto - 0 32 4 2 roll 0 exch awidthshow - } bind def -/BF { - gsave - moveto - RF - 0 32 4 2 roll 0 exch awidthshow - grestore - } bind def -/G { - gsave - newpath - normalize translate 0.0 0.0 moveto - dnormalize scale - 0.0 0.0 1.0 5 3 roll arc - closepath - PFill fill - grestore - } bind def -/Gstrk { - savematrix - newpath - 2 index 2 div add exch 3 index 2 div sub exch - normalize 2 index 2 div sub exch 3 index 2 div add exch - translate - scale - 0.0 0.0 1.0 5 3 roll arc - restorematrix - currentlinewidth exch setlinewidth PStroke setlinewidth - } bind def -/Gclip { - newpath - savematrix - normalize translate 0.0 0.0 moveto - dnormalize scale - 0.0 0.0 1.0 5 3 roll arc - closepath - clip newpath - restorematrix - } bind def -/GG { - gsave - newpath - normalize translate 0.0 0.0 moveto - rotate - dnormalize scale - 0.0 0.0 1.0 5 3 roll arc - closepath - PFill - fill - grestore - } bind def -/GGclip { - savematrix - newpath - normalize translate 0.0 0.0 moveto - rotate - dnormalize scale - 0.0 0.0 1.0 5 3 roll arc - closepath - clip newpath - restorematrix - } bind def -/GGstrk { - savematrix - newpath - normalize translate 0.0 0.0 moveto - rotate - dnormalize scale - 0.0 0.0 1.0 5 3 roll arc - closepath - restorematrix - currentlinewidth exch setlinewidth PStroke setlinewidth - } bind def -/A { - gsave - savematrix - newpath - 2 index 2 div add exch 3 index 2 div sub exch - normalize 2 index 2 div sub exch 3 index 2 div add exch - translate - scale - 0.0 0.0 1.0 5 3 roll arc - restorematrix - PStroke - grestore - } bind def -/Aclip { - newpath - savematrix - normalize translate 0.0 0.0 moveto - dnormalize scale - 0.0 0.0 1.0 5 3 roll arc - closepath - strokepath clip newpath - restorematrix -} bind def -/Astrk { - Gstrk -} bind def -/AA { - gsave - savematrix - newpath - - 3 index 2 div add exch 4 index 2 div sub exch - - normalize 3 index 2 div sub exch 4 index 2 div add exch - translate - rotate - scale - 0.0 0.0 1.0 5 3 roll arc - restorematrix - PStroke - grestore - } bind def -/AAclip { - savematrix - newpath - normalize translate 0.0 0.0 moveto - rotate - dnormalize scale - 0.0 0.0 1.0 5 3 roll arc - closepath - strokepath clip newpath - restorematrix -} bind def -/AAstrk { - GGstrk -} bind def - /x FMLOCAL - /y FMLOCAL - /w FMLOCAL - /h FMLOCAL - /xx FMLOCAL - /yy FMLOCAL - /ww FMLOCAL - /hh FMLOCAL - /FMsaveobject FMLOCAL - /FMoptop FMLOCAL - /FMdicttop FMLOCAL -/BEGINPRINTCODE { - /FMdicttop countdictstack 1 add def - /FMoptop count 7 sub def - /FMsaveobject save def - userdict begin - /showpage {} def - FMNORMALIZEGRAPHICS - 3 index neg 3 index neg translate - } bind def -/ENDPRINTCODE { - count -1 FMoptop {pop pop} for - countdictstack -1 FMdicttop {pop end} for - FMsaveobject restore - } bind def -/gn { - 0 - { 46 mul - cf read pop - 32 sub - dup 46 lt {exit} if - 46 sub add - } loop - add - } bind def - /str FMLOCAL -/cfs { - /str sl string def - 0 1 sl 1 sub {str exch val put} for - str def - } bind def -/ic [ - 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0223 - 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0223 - 0 - {0 hx} {1 hx} {2 hx} {3 hx} {4 hx} {5 hx} {6 hx} {7 hx} {8 hx} {9 hx} - {10 hx} {11 hx} {12 hx} {13 hx} {14 hx} {15 hx} {16 hx} {17 hx} {18 hx} - {19 hx} {gn hx} {0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} - {13} {14} {15} {16} {17} {18} {19} {gn} {0 wh} {1 wh} {2 wh} {3 wh} - {4 wh} {5 wh} {6 wh} {7 wh} {8 wh} {9 wh} {10 wh} {11 wh} {12 wh} - {13 wh} {14 wh} {gn wh} {0 bl} {1 bl} {2 bl} {3 bl} {4 bl} {5 bl} {6 bl} - {7 bl} {8 bl} {9 bl} {10 bl} {11 bl} {12 bl} {13 bl} {14 bl} {gn bl} - {0 fl} {1 fl} {2 fl} {3 fl} {4 fl} {5 fl} {6 fl} {7 fl} {8 fl} {9 fl} - {10 fl} {11 fl} {12 fl} {13 fl} {14 fl} {gn fl} - ] def - /sl FMLOCAL - /val FMLOCAL - /ws FMLOCAL - /im FMLOCAL - /bs FMLOCAL - /cs FMLOCAL - /len FMLOCAL - /pos FMLOCAL -/ms { - /sl exch def - /val 255 def - /ws cfs - /im cfs - /val 0 def - /bs cfs - /cs cfs - } bind def -400 ms -/ip { - is - 0 - cf cs readline pop - { ic exch get exec - add - } forall - pop - - } bind def -/rip { - - - bis ris copy pop - is - 0 - cf cs readline pop - { ic exch get exec - add - } forall - pop pop - ris gis copy pop - dup is exch - - cf cs readline pop - { ic exch get exec - add - } forall - pop pop - gis bis copy pop - dup add is exch - - cf cs readline pop - { ic exch get exec - add - } forall - pop - - } bind def -/wh { - /len exch def - /pos exch def - ws 0 len getinterval im pos len getinterval copy pop - pos len - } bind def -/bl { - /len exch def - /pos exch def - bs 0 len getinterval im pos len getinterval copy pop - pos len - } bind def -/s1 1 string def -/fl { - /len exch def - /pos exch def - /val cf s1 readhexstring pop 0 get def - pos 1 pos len add 1 sub {im exch val put} for - pos len - } bind def -/hx { - 3 copy getinterval - cf exch readhexstring pop pop - } bind def - /h FMLOCAL - /w FMLOCAL - /d FMLOCAL - /lb FMLOCAL - /bitmapsave FMLOCAL - /is FMLOCAL - /cf FMLOCAL -/wbytes { - dup dup - 24 eq { pop pop 3 mul } - { 8 eq {pop} {1 eq {7 add 8 idiv} {3 add 4 idiv} ifelse} ifelse } ifelse - } bind def -/BEGINBITMAPBWc { - 1 {} COMMONBITMAPc - } bind def -/BEGINBITMAPGRAYc { - 8 {} COMMONBITMAPc - } bind def -/BEGINBITMAP2BITc { - 2 {} COMMONBITMAPc - } bind def -/COMMONBITMAPc { - - /r exch def - /d exch def - gsave - - 3 index 2 div add exch - 4 index 2 div add exch - translate - rotate - 1 index 2 div neg - 1 index 2 div neg - translate - scale - /h exch def /w exch def - /lb w d wbytes def - sl lb lt {lb ms} if - /bitmapsave save def - r - /is im 0 lb getinterval def - ws 0 lb getinterval is copy pop - /cf currentfile def - w h d [w 0 0 h neg 0 h] - {ip} image - bitmapsave restore - grestore - } bind def -/BEGINBITMAPBW { - 1 {} COMMONBITMAP - } bind def -/BEGINBITMAPGRAY { - 8 {} COMMONBITMAP - } bind def -/BEGINBITMAP2BIT { - 2 {} COMMONBITMAP - } bind def -/COMMONBITMAP { - /r exch def - /d exch def - gsave - - 3 index 2 div add exch - 4 index 2 div add exch - translate - rotate - 1 index 2 div neg - 1 index 2 div neg - translate - scale - /h exch def /w exch def - /bitmapsave save def - r - /is w d wbytes string def - /cf currentfile def - w h d [w 0 0 h neg 0 h] - {cf is readhexstring pop} image - bitmapsave restore - grestore - } bind def -/ngrayt 256 array def -/nredt 256 array def -/nbluet 256 array def -/ngreent 256 array def - /gryt FMLOCAL - /blut FMLOCAL - /grnt FMLOCAL - /redt FMLOCAL - /indx FMLOCAL - /cynu FMLOCAL - /magu FMLOCAL - /yelu FMLOCAL - /k FMLOCAL - /u FMLOCAL -FMLevel1 { -/colorsetup { - currentcolortransfer - /gryt exch def - /blut exch def - /grnt exch def - /redt exch def - 0 1 255 { - /indx exch def - /cynu 1 red indx get 255 div sub def - /magu 1 green indx get 255 div sub def - /yelu 1 blue indx get 255 div sub def - /k cynu magu min yelu min def - /u k currentundercolorremoval exec def -% /u 0 def - nredt indx 1 0 cynu u sub max sub redt exec put - ngreent indx 1 0 magu u sub max sub grnt exec put - nbluet indx 1 0 yelu u sub max sub blut exec put - ngrayt indx 1 k currentblackgeneration exec sub gryt exec put - } for - {255 mul cvi nredt exch get} - {255 mul cvi ngreent exch get} - {255 mul cvi nbluet exch get} - {255 mul cvi ngrayt exch get} - setcolortransfer - {pop 0} setundercolorremoval - {} setblackgeneration - } bind def -} -{ -/colorSetup2 { - [ /Indexed /DeviceRGB 255 - {dup red exch get 255 div - exch dup green exch get 255 div - exch blue exch get 255 div} - ] setcolorspace -} bind def -} ifelse - /tran FMLOCAL -/fakecolorsetup { - /tran 256 string def - 0 1 255 {/indx exch def - tran indx - red indx get 77 mul - green indx get 151 mul - blue indx get 28 mul - add add 256 idiv put} for - currenttransfer - {255 mul cvi tran exch get 255.0 div} - exch concatprocs settransfer -} bind def -/BITMAPCOLOR { - /d 8 def - gsave - - 3 index 2 div add exch - 4 index 2 div add exch - translate - rotate - 1 index 2 div neg - 1 index 2 div neg - translate - scale - /h exch def /w exch def - /bitmapsave save def - FMLevel1 { - colorsetup - /is w d wbytes string def - /cf currentfile def - w h d [w 0 0 h neg 0 h] - {cf is readhexstring pop} {is} {is} true 3 colorimage - } { - colorSetup2 - /is w d wbytes string def - /cf currentfile def - 7 dict dup begin - /ImageType 1 def - /Width w def - /Height h def - /ImageMatrix [w 0 0 h neg 0 h] def - /DataSource {cf is readhexstring pop} bind def - /BitsPerComponent d def - /Decode [0 255] def - end image - } ifelse - bitmapsave restore - grestore - } bind def -/BITMAPCOLORc { - /d 8 def - gsave - - 3 index 2 div add exch - 4 index 2 div add exch - translate - rotate - 1 index 2 div neg - 1 index 2 div neg - translate - scale - /h exch def /w exch def - /lb w d wbytes def - sl lb lt {lb ms} if - /bitmapsave save def - FMLevel1 { - colorsetup - /is im 0 lb getinterval def - ws 0 lb getinterval is copy pop - /cf currentfile def - w h d [w 0 0 h neg 0 h] - {ip} {is} {is} true 3 colorimage - } { - colorSetup2 - /is im 0 lb getinterval def - ws 0 lb getinterval is copy pop - /cf currentfile def - 7 dict dup begin - /ImageType 1 def - /Width w def - /Height h def - /ImageMatrix [w 0 0 h neg 0 h] def - /DataSource {ip} bind def - /BitsPerComponent d def - /Decode [0 255] def - end image - } ifelse - bitmapsave restore - grestore - } bind def -/BITMAPTRUECOLORc { - /d 24 def - gsave - - 3 index 2 div add exch - 4 index 2 div add exch - translate - rotate - 1 index 2 div neg - 1 index 2 div neg - translate - scale - /h exch def /w exch def - /lb w d wbytes def - sl lb lt {lb ms} if - /bitmapsave save def - - /is im 0 lb getinterval def - /ris im 0 w getinterval def - /gis im w w getinterval def - /bis im w 2 mul w getinterval def - - ws 0 lb getinterval is copy pop - /cf currentfile def - w h 8 [w 0 0 h neg 0 h] - {w rip pop ris} {gis} {bis} true 3 colorimage - bitmapsave restore - grestore - } bind def -/BITMAPTRUECOLOR { - gsave - - 3 index 2 div add exch - 4 index 2 div add exch - translate - rotate - 1 index 2 div neg - 1 index 2 div neg - translate - scale - /h exch def /w exch def - /bitmapsave save def - /is w string def - /gis w string def - /bis w string def - /cf currentfile def - w h 8 [w 0 0 h neg 0 h] - { cf is readhexstring pop } - { cf gis readhexstring pop } - { cf bis readhexstring pop } - true 3 colorimage - bitmapsave restore - grestore - } bind def -/BITMAPTRUEGRAYc { - /d 24 def - gsave - - 3 index 2 div add exch - 4 index 2 div add exch - translate - rotate - 1 index 2 div neg - 1 index 2 div neg - translate - scale - /h exch def /w exch def - /lb w d wbytes def - sl lb lt {lb ms} if - /bitmapsave save def - - /is im 0 lb getinterval def - /ris im 0 w getinterval def - /gis im w w getinterval def - /bis im w 2 mul w getinterval def - ws 0 lb getinterval is copy pop - /cf currentfile def - w h 8 [w 0 0 h neg 0 h] - {w rip pop ris gis bis w gray} image - bitmapsave restore - grestore - } bind def -/ww FMLOCAL -/r FMLOCAL -/g FMLOCAL -/b FMLOCAL -/i FMLOCAL -/gray { - /ww exch def - /b exch def - /g exch def - /r exch def - 0 1 ww 1 sub { /i exch def r i get .299 mul g i get .587 mul - b i get .114 mul add add r i 3 -1 roll floor cvi put } for - r - } bind def -/BITMAPTRUEGRAY { - gsave - - 3 index 2 div add exch - 4 index 2 div add exch - translate - rotate - 1 index 2 div neg - 1 index 2 div neg - translate - scale - /h exch def /w exch def - /bitmapsave save def - /is w string def - /gis w string def - /bis w string def - /cf currentfile def - w h 8 [w 0 0 h neg 0 h] - { cf is readhexstring pop - cf gis readhexstring pop - cf bis readhexstring pop w gray} image - bitmapsave restore - grestore - } bind def -/BITMAPGRAY { - 8 {fakecolorsetup} COMMONBITMAP - } bind def -/BITMAPGRAYc { - 8 {fakecolorsetup} COMMONBITMAPc - } bind def -/ENDBITMAP { - } bind def -end - /ALDsave FMLOCAL - /ALDmatrix matrix def ALDmatrix currentmatrix pop -/StartALD { - /ALDsave save def - savematrix - ALDmatrix setmatrix - } bind def -/InALD { - restorematrix - } bind def -/DoneALD { - ALDsave restore - } bind def -/I { setdash } bind def -/J { [] 0 setdash } bind def -%%EndProlog -%%BeginSetup -(4.0) FMVERSION -1 1 0 0 595.28 841.89 0 1 7 FMDOCUMENT -0 0 /Times-Bold FMFONTDEFINE -1 0 /Times-Roman FMFONTDEFINE -2 0 /Courier FMFONTDEFINE -3 0 /Times-Italic FMFONTDEFINE -4 1 /ZapfDingbats FMFONTDEFINE -32 FMFILLS -0 0 FMFILL -1 0.1 FMFILL -2 0.3 FMFILL -3 0.5 FMFILL -4 0.7 FMFILL -5 0.9 FMFILL -6 0.97 FMFILL -7 1 FMFILL -8 <0f1e3c78f0e1c387> FMFILL -9 <0f87c3e1f0783c1e> FMFILL -10 <cccccccccccccccc> FMFILL -11 <ffff0000ffff0000> FMFILL -12 <8142241818244281> FMFILL -13 <03060c183060c081> FMFILL -14 <8040201008040201> FMFILL -16 1 FMFILL -17 0.9 FMFILL -18 0.7 FMFILL -19 0.5 FMFILL -20 0.3 FMFILL -21 0.1 FMFILL -22 0.03 FMFILL -23 0 FMFILL -24 <f0e1c3870f1e3c78> FMFILL -25 <f0783c1e0f87c3e1> FMFILL -26 <3333333333333333> FMFILL -27 <0000ffff0000ffff> FMFILL -28 <7ebddbe7e7dbbd7e> FMFILL -29 <fcf9f3e7cf9f3f7e> FMFILL -30 <7fbfdfeff7fbfdfe> FMFILL -%%EndSetup -%%Page: "1" 1 -%%BeginPaperSize: A4 -%%EndPaperSize -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -J -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 18 Q -0 X -0 0 0 1 0 0 0 K -(A Python Quick Refer) 56.69 773.2 T -(ence) 227.85 773.2 T -1 12 Q -(Postscript version v1.1.1, by Anthony Baxter) 56.69 748.2 T -(,) 272.87 748.2 T -2 F -(<anthony@aaii.oz.au>) 56.69 734.2 T -(Based on:) 56.69 720.2 T -(ASCII v1.0; 1994/09/27) 56.69 706.2 T -1 F -(Author: Chris Hof) 56.69 692.2 T -(fmann,) 144.47 692.2 T -2 F -(choffman@vicorp.com) 56.69 678.2 T -1 F -(Based on) 56.69 664.2 T -(\245) 56.69 650.2 T -(Python Bestiary) 70.87 650.2 T -(,) 147.09 650.2 T -(by Ken Manheimer) 85.04 636.2 T -(,) 177.87 636.2 T -2 F -(\050ken.manheimer@nist.gov\051) 85.04 622.2 T -1 F -(\245) 56.69 608.2 T -(Python manuals,) 70.87 608.2 T -(by Guido van Rossum,) 85.04 594.2 T -2 F -(\050guido@cwi.nl\051) 85.04 580.2 T -1 F -(\245) 56.69 566.2 T -(python-mode.el,) 70.87 566.2 T -(by T) 85.04 552.2 T -(im Peters,) 106.95 552.2 T -2 F -(\050tim@ksr.com\051) 85.04 538.2 T -0 14 Q -(Invocation Options) 308.98 775.86 T -2 12 Q -(python) 308.98 756.2 T -([-diuv]) 355.18 756.2 T -([-c) 408.58 756.2 T -(command |) 433.18 756.2 T -(script | - ] [args]) 308.98 742.2 T -(-d) 308.98 728.2 T -1 F -(T) 337.32 728.2 T -(urn on parser debugging output \050for) 344.23 728.2 T -(wizards only) 337.32 714.2 T -(, depending on compilation) 398.2 714.2 T -(options\051.) 337.32 700.2 T -(-i) 308.98 686.2 T --0.35 (When a script is passed as \336rst ar) 337.32 686.2 P --0.35 (gument) 494.27 686.2 P --0.09 (or the -c option is used, enter interactive) 337.32 672.2 P -(mode after executing the script or the) 337.32 658.2 T -(command. It does not read the) 337.32 644.2 T -($) 337.32 630.2 T -2 F -(PYTHONSTARTUP) 343.32 630.2 T -1 F -( \336le. This can be) 436.92 630.2 T -(useful to inspect global variables or a) 337.32 616.2 T --0.29 (stack trace when a script raises an excep-) 337.32 602.2 P -(tion.) 337.32 588.2 T -2 F -(-u) 308.98 574.2 T -1 F -(Force stdout and stderr to be totally) 337.32 574.2 T -(unbuf) 337.32 560.2 T -(fered.) 365.1 560.2 T -2 F -(-v) 308.98 546.2 T -1 F -(Print a message each time a module is) 337.32 546.2 T -(initialized, showing the place \050\336lename) 337.32 532.2 T -(or built-in module\051 from which it is) 337.32 518.2 T -(loaded.) 337.32 504.2 T -(-c) 308.98 490.2 T -2 F -(command) 321.3 490.2 T -1 F -(Specify the command to execute) 337.32 476.2 T -3 F -(\050see) 496.96 476.2 T --0.01 (next section\051) 337.32 462.2 P -1 F --0.01 (. This terminates the option) 398.3 462.2 P -(list \050following options are passed as) 337.32 448.2 T -(ar) 337.32 434.2 T -(guments to the command\051.) 346.43 434.2 T -2 F -(-) 308.98 420.2 T -1 F -(anything afterward is passed as options) 337.32 420.2 T -(to python script or command, not inter-) 337.32 406.2 T -(preted as an option to interpreter itself.) 337.32 392.2 T -(script) 308.98 378.2 T -(is the name of a python \336le to execute) 338.64 378.2 T -2 F -(args) 308.98 364.2 T -1 F -(are passed to script or command \050in) 340.78 364.2 T -2 F -(sys.argv) 337.32 350.2 T -1 F -(\051) 394.92 350.2 T -(If no script or command, Python enters inter-) 308.98 336.2 T -(active mode. Uses \322) 308.98 322.2 T -2 F -(readline) 404.95 322.2 T -1 F -(\323 package for) 462.55 322.2 T -(input, if available.) 308.98 308.2 T -0 14 Q -(Envir) 561.26 775.86 T -(onment V) 595.24 775.86 T -(ariables) 652.67 775.86 T -2 12 Q -(PYTHONPATH) 561.26 756.2 T -1 F -(Augments the default search path for module) 561.26 742.2 T -(\336les. The format is the same as the shell\325) 561.26 728.2 T -(s) 756.91 728.2 T -($) 561.26 714.2 T -2 F -(PATH) 567.26 714.2 T -1 F -(: one or more directory pathnames sep-) 596.06 714.2 T -(arated by colons.) 561.26 700.2 T -2 F -(PYTHONSTARTUP) 561.26 686.2 T -1 F -(If this is the name of a readable \336le, the) 561.26 672.2 T -(Python commands in that \336le are executed) 561.26 658.2 T -(before the \336rst prompt is displayed in interac-) 561.26 644.2 T -(tive mode.) 561.26 630.2 T -2 F -(PYTHONDEBUG) 561.26 616.2 T -1 F -(If non-empty) 561.26 602.2 T -(, same as) 623.47 602.2 T -2 F -(-d) 670.12 602.2 T -1 F -( option) 684.52 602.2 T -2 F -(PYTHONINSPECT) 561.26 588.2 T -1 F -(If non-empty) 561.26 574.2 T -(, same as) 623.47 574.2 T -2 F -(-i) 670.12 574.2 T -1 F -( option) 684.52 574.2 T -2 F -(PYTHONUNBUFFERED) 561.26 560.2 T -1 F -(If non-empty) 561.26 546.2 T -(, same as) 623.47 546.2 T -2 F -(-u) 670.12 546.2 T -1 F -( option) 684.52 546.2 T -2 F -(PYTHONVERBOSE) 561.26 532.2 T -1 F -(If non-empty) 561.26 518.2 T -(, same as) 623.47 518.2 T -2 F -(-v) 670.12 518.2 T -1 F -( option) 684.52 518.2 T -0 14 Q -(T) 561.26 488.86 T -(erms used in this document) 569.31 488.86 T -1 12 Q -(sequence\320 a string, list or tuple) 561.26 469.2 T -(suite\320 a series of statements, possibly sepa-) 561.26 455.2 T --0.29 (rated by newlines. Must all be at same indenta-) 561.26 441.2 P -(tion level, except for suites inside compound) 561.26 427.2 T -(statements) 561.26 413.2 T -2 F -(<x>) 561.26 399.2 T -1 F -(\320 in a syntax diagram: not literally the) 582.86 399.2 T -(string \322x\323 but some token referred to as \322x\323) 561.26 385.2 T -2 F -([xxx]) 561.26 371.2 T -1 F -(\320 in a syntax diagram means \322xxx\323 is) 597.26 371.2 T -(optional) 561.26 357.2 T -(x) 561.26 343.2 T -4 F -(\325) 570.26 343.2 T -1 F -( y\320 means the value of <x> is <y>) 580.32 343.2 T -(x) 561.26 329.2 T -4 F -(\326) 570.26 329.2 T -1 F -( y\320 means \322x is equivalent to y\323) 582.45 329.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "1" 1 -%%Page: "2" 2 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 14 Q -0 X -0 0 0 1 0 0 0 K -(Notable lexical entities) 56.69 775.86 T -108.69 745.01 56.69 745.01 2 L -V -1.14 H -0 Z -N -0 12 Q -(Keywords) 56.69 746.2 T -2 F -(and elif from lambda return) 56.69 725.2 T --1.08 (break else global not try class) 56.69 711.2 P -(except if or while continue) 56.69 697.2 T --1.08 (exec import pass def f) 56.69 683.2 P --1.08 (inally in) 210.78 683.2 P -(print del or is raise) 56.69 669.2 T -126.35 640.01 56.69 640.01 2 L -V -N -0 F -(Illegitimate T) 56.69 641.2 T -266.61 640.01 125.25 640.01 2 L -V -N -(okens \050only valid in strings\051) 125.25 641.2 T -2 F -(@ $ ?) 56.69 620.2 T -1 F -(A statement must all be on a single line. T) 56.69 606.2 T -(o) 258.51 606.2 T -(break a statement over multiple lines use \322) 56.69 592.2 T -2 F -(\134) 260.99 592.2 T -1 F -(\323,) 268.19 592.2 T -(as with the C preprocessor) 56.69 578.2 T -(.) 183.34 578.2 T -3 F -(Exception: can always br) 56.69 564.2 T -(eak when inside any) 178.57 564.2 T -2 F -(\050\051) 56.69 550.2 T -1 F -(,) 71.09 550.2 T -2 F -([]) 77.09 550.2 T -3 F -(, or) 91.49 550.2 T -2 F -({}) 111.16 550.2 T -3 F -( pair) 125.56 550.2 T -1 F -(.) 147.9 550.2 T -(More than one statement can appear on a line) 56.69 536.2 T -(if they are separated with semicolons \050\322) 56.69 522.2 T -2 F -(;) 247.31 522.2 T -1 F -(\323\051) 254.51 522.2 T -(Comments start with \322) 56.69 508.2 T -2 F -(#) 165.03 508.2 T -1 F -(\323 and continue to end) 172.23 508.2 T -(of line.) 56.69 494.2 T -113.36 465.01 56.69 465.01 2 L -V -N -0 F -(Identi\336ers:) 56.69 466.2 T -2 F -(\050letter|\323_\323\051\050letter|digit|\323_\323\051*) 56.69 445.2 T -97.36 416.01 56.69 416.01 2 L -V -N -0 F -(Strings:) 56.69 417.2 T -2 F -(\322a string\323 \324another string\325) 56.69 396.2 T --1.62 (\324\325\325a string containing embedded) 56.69 382.2 P -(newlines, and quote \050\324\051 marks,) 56.69 368.2 T -(can be delimited with triple) 56.69 354.2 T -(quotes.\325\325\325) 56.69 340.2 T -422.98 776.01 308.98 776.01 2 L -V -N -0 F -(String Literal Escapes) 308.98 777.2 T -1 F -( \134newline) 308.98 756.2 T -(Ignored \050escape newline\051) 379.84 756.2 T -2 F -(\134\134) 308.98 742.2 T -1 F -(Literal backslash \050\134\051) 379.84 742.2 T -2 F -(\134e) 308.98 728.2 T -1 F -( Escape \050ESC\051) 379.84 728.2 T -2 F -(\134v) 308.98 714.2 T -1 F -(V) 379.84 714.2 T -(ertical T) 387.17 714.2 T -(ab \050VT\051) 426.65 714.2 T -2 F -(\134\325) 308.98 700.2 T -1 F -(Single quote \050\324\051) 379.84 700.2 T -2 F -(\134f) 308.98 686.2 T -1 F -(Formfeed \050FF\051) 379.84 686.2 T -2 F -(\1340OO) 308.98 672.2 T -1 F -(\050zero\051 char with value 0) 379.84 672.2 T -2 F -(\134\323) 308.98 658.2 T -1 F -(Double quote \050\322\051) 379.84 658.2 T -2 F -(\134n) 308.98 644.2 T -1 F -(Linefeed \050LF\051) 379.84 644.2 T -2 F -(\134) 308.98 630.2 T -1 F -(octal value OO) 316.18 630.2 T -2 F -(\134a) 308.98 616.2 T -1 F -(Bell \050BEL\051) 379.84 616.2 T -2 F -(\134r) 308.98 602.2 T -1 F -(Carriage Return \050CR\051) 379.84 602.2 T -2 F -(\134xXX) 308.98 588.2 T -1 F -(char with hex value) 379.84 588.2 T -2 F -(XX) 477.15 588.2 T -1 F -(\134b) 308.98 574.2 T -(Backspace \050BS\051) 379.84 574.2 T -(\134t) 308.98 560.2 T -(Horizontal T) 379.84 560.2 T -(ab \050T) 440.66 560.2 T -(AB\051) 465.35 560.2 T -(\134<any other char> is left as-is) 308.98 546.2 T -2 F -(NULL) 308.98 532.2 T -1 F -( byte \050) 337.78 532.2 T -2 F -(\134000) 368.44 532.2 T -1 F -(\051 is) 397.24 532.2 T -430.57 530.89 415.24 530.89 2 L -V -0.59 H -N -(not) 415.24 532.2 T -( an end-of-string) 430.57 532.2 T -(marker;) 308.98 518.2 T -2 F -(NULL) 349.3 518.2 T -1 F -(\325) 376.99 518.2 T -(s may be imbedded in strings) 380.33 518.2 T -(Strings \050and tuples\051 are immutable: they can-) 308.98 504.2 T -(not be modi\336ed.) 308.98 490.2 T -373.3 461.01 308.98 461.01 2 L -V -1.14 H -N -0 F -(Other types:) 308.98 462.2 T -1 F -(long integer \050unlimited precision\051:) 308.98 441.2 T -2 F -(1234567890L) 340.16 427.2 T -1 F -(octal integer:) 308.98 413.2 T -2 F -(0177, 017777777777777L) 340.16 399.2 T -1 F -(hex integer:) 308.98 385.2 T -2 F -(0xFF, 0xFFFFFFFFFFFFL) 340.16 371.2 T -1 F -(\337oat:) 308.98 357.2 T -2 F -(3.14e-10) 340.16 343.2 T -1 F -(tuple of length 0, 1, 2, etc:) 308.98 329.2 T -2 F -(\050\051 \0501,\051 \0501,2\051) 340.16 315.2 T -3 F -(\050par) 561.26 777.2 T -(entheses ar) 581.48 777.2 T -(e optional if len > 0\051) 635.36 777.2 T -1 F -(list of length 0, 1, 2, etc:) 561.26 763.2 T -2 F -([] [1] [1,2]) 592.44 749.2 T -1 F -(dictionary of length 0, 1, 2, etc:) 561.26 735.2 T -2 F --0.23 ({} {1 : \324one\325} {1 : \324one\325,) 592.44 721.2 P -(\324next\325: \3242nd\325}) 561.26 707.2 T -3 F -(\050Indexing is 0-based. Negative indices \050usu-) 561.26 693.2 T -(ally\051 mean count backwar) 561.26 679.2 T -(ds fr) 685.8 679.2 T -(om end of) 707.02 679.2 T -(sequence.\051) 561.26 665.2 T -1 F -( Sequence slicing) 561.26 651.2 T --0.79 ([starting-at-index : but-less-than-index]) 595.28 637.2 P -3 F -(\050Start defaults to \3240\325; End defaults to) 561.26 623.2 T -(\324sequence-length\325.\051) 561.26 609.2 T -2 F -(a = \0500,1,2,3,4,5,6,7\051) 561.26 595.2 T -(a[3]) 561.26 581.2 T -4 F -(\325) 597.26 581.2 T -2 F -(3) 610.65 581.2 T -(a[-1]) 561.26 567.2 T -4 F -(\325) 604.46 567.2 T -2 F -(7) 617.85 567.2 T -(a[2:4]) 561.26 553.2 T -4 F -(\325) 611.66 553.2 T -2 F -(\0502, 3\051) 621.72 553.2 T -(a[1:]) 561.26 539.2 T -4 F -(\325) 604.46 539.2 T -2 F -(\0501, 2, 3, 4, 5, 6, 7\051) 617.85 539.2 T -(a[:3]) 561.26 525.2 T -4 F -(\325) 604.46 525.2 T -2 F -(\0500, 1, 2\051) 614.52 525.2 T -(a[:]) 561.26 511.2 T -4 F -(\325) 597.26 511.2 T -2 F -(\0500,1,2,3,4,5,6,7\051) 607.32 511.2 T -3 F -( \050makes a) 729.72 511.2 T -(copy of the sequence.\051) 561.26 497.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "2" 2 -%%Page: "3" 3 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 14 Q -0 X -0 0 0 1 0 0 0 K -(Basic T) 56.69 775.86 T -(ypes and Their Operations) 100.39 775.86 T -272.69 745.01 56.69 745.01 2 L -V -1.14 H -0 Z -N -0 12 Q -(Comparisions \050de\336ned between any types\051) 56.69 746.2 T -2 F -(<) 56.69 725.2 T -1 F -(strictly less than) 127.56 725.2 T -2 F -(<=) 56.69 711.2 T -1 F -(less than or equal) 127.56 711.2 T -2 F -(>) 56.69 697.2 T -1 F -(strictly greater than) 127.56 697.2 T -2 F -(>=) 56.69 683.2 T -1 F -(greater than or equal) 127.56 683.2 T -2 F -(==) 56.69 669.2 T -1 F -(equal) 127.56 669.2 T -2 F -(!=) 56.69 655.2 T -1 F -(not equal \050 \322) 127.56 655.2 T -2 F -(<>) 187.21 655.2 T -1 F -(\323 is also) 201.61 655.2 T -(allowed\051) 127.56 641.2 T -2 F -(is) 56.69 627.2 T -1 F -(object identity) 127.56 627.2 T -3 F -(\050ar) 199.56 627.2 T -(e) 213.78 627.2 T -256.1 626.05 222.11 626.05 2 L -V -0.58 H -N -(objects) 222.11 627.2 T -(identical, not values\051) 127.56 613.2 T -2 F -(is not) 56.69 599.2 T -1 F -(negated object identity) 127.56 599.2 T -2 F -(X < Y < Z < W) 56.69 585.2 T -1 F -(has expected meaning,) 157.49 585.2 T -(unlike) 127.56 571.2 T -2 F -( C) 157.56 571.2 T -207.7 542.01 56.69 542.01 2 L -V -1.14 H -N -0 F -(Boolean values and operators) 56.69 543.2 T -1 F -(False values:) 56.69 522.2 T -2 F -(None) 127.56 522.2 T -1 F -(, numeric zeros, empty) 156.36 522.2 T -(sequences and mappings) 127.56 508.2 T -(T) 56.69 494.2 T -(rue values:) 63.6 494.2 T -(all other values) 127.56 494.2 T -2 F -(not) 56.69 480.2 T -(X) 81.29 480.2 T -1 F -(:) 88.49 480.2 T -(if) 127.56 480.2 T -2 F -(X) 137.89 480.2 T -1 F -( is false then 1, else 0) 145.09 480.2 T -2 F -(X) 56.69 466.2 T -(or) 66.89 466.2 T -(Y) 84.29 466.2 T -1 F -(:) 90.39 466.2 T -(if) 127.56 466.2 T -2 F -(X) 137.89 466.2 T -1 F -( is false then) 145.09 466.2 T -2 F -(Y) 208.41 466.2 T -1 F -(, else) 214.07 466.2 T -2 F -(X) 241.73 466.2 T -(X) 56.69 452.2 T -(and) 66.89 452.2 T -(Y) 91.49 452.2 T -1 F -(if) 101.69 452.2 T -2 F -(X) 112.03 452.2 T -1 F -( is false then) 119.22 452.2 T -2 F -(X) 182.55 452.2 T -1 F -(, else) 189.75 452.2 T -2 F -(Y) 217.41 452.2 T -3 F -(\050\324) 56.69 438.2 T -2 F -(or) 64.68 438.2 T -3 F -(\325, \324) 79.53 438.2 T -2 F -(and) 93.52 438.2 T -3 F -(\325 evaluate second ar) 115.12 438.2 T -(g only if nec-) 212.32 438.2 T -(essary to determine outcome\051) 56.69 424.2 T -69.35 395.01 56.69 395.01 2 L -V -N -0 F -(Pr) 56.69 396.2 T -252.45 395.01 69.14 395.01 2 L -V -N -(ede\336ned object of special type:None) 69.14 396.2 T -2 F -(None) 56.69 375.2 T -1 F -( is used as default return value on func-) 85.49 375.2 T -(tions. Input that evaluates to) 56.69 361.2 T -2 F -(None) 195.35 361.2 T -1 F -( does not) 224.15 361.2 T -(print when running Python interactively) 56.69 347.2 T -383.29 776.01 308.98 776.01 2 L -V -N -0 F -(Numeric types) 308.98 777.2 T -1 F -(Floats, integers and long integers. Floats are) 308.98 756.2 T -(implemented with C doubles. Integers are) 308.98 742.2 T --0.58 (implemented with C longs. Long integers have) 308.98 728.2 P -(unlimited size \050only limit is system resources\051) 308.98 714.2 T -468.3 685.01 308.98 685.01 2 L -V -N -0 F -(Operators on all numeric types) 308.98 686.2 T -2 F -(abs\050x\051) 308.98 665.2 T -1 F -(absolute value of x) 379.84 665.2 T -2 F -(int\050x\051) 308.98 651.2 T -1 F -(x converted to integer) 379.84 651.2 T -2 F -(long\050x\051) 308.98 637.2 T -1 F -(x converted to long integer) 379.84 637.2 T -2 F -(f) 308.98 623.2 T -(loat\050x\051) 316.18 623.2 T -1 F -(x converted to \337oating point) 379.84 623.2 T -2 F -(-x) 308.98 609.2 T -1 F -(x negated) 379.84 609.2 T -2 F -(+x) 308.98 595.2 T -1 F -(x unchanged) 379.84 595.2 T -2 F -(x+y) 308.98 581.2 T -1 F -(sum of x and y) 379.84 581.2 T -2 F -(x-y) 308.98 567.2 T -1 F -(dif) 379.84 567.2 T -(ference of x and y) 392.96 567.2 T -2 F -(x*y) 308.98 553.2 T -1 F -(product of x and y) 379.84 553.2 T -2 F -(x/y) 308.98 539.2 T -1 F -(quotient of x and y) 379.84 539.2 T -2 F -(x%y) 308.98 525.2 T -1 F -(remainder of x / y) 379.84 525.2 T -2 F -(pow\050x,y\051) 308.98 511.2 T -1 F -(x to the power y) 379.84 511.2 T -2 F -(divmod\050x,y\051) 308.98 497.2 T -1 F -(the tuple \050) 388.18 497.2 T -2 F -(x/y,x%y) 436.84 497.2 T -1 F -(\051) 487.24 497.2 T -526.97 468.01 308.98 468.01 2 L -V -N -0 F -(Bit operators on integers and long integers) 308.98 469.2 T -2 F -(~x) 308.98 448.2 T -1 F -(the bits of x inverted) 379.84 448.2 T -2 F -(x^y) 308.98 434.2 T -1 F -(bitwise exclusive or of x and y) 379.84 434.2 T -2 F -(x&y) 308.98 420.2 T -1 F -(bitwise and of x and y) 379.84 420.2 T -2 F -(x|y) 308.98 406.2 T -1 F -(bitwise or of x and y) 379.84 406.2 T -2 F -(x<<n) 308.98 392.2 T -1 F -(x shifted left by n bits) 379.84 392.2 T -2 F -(x>>n) 308.98 378.2 T -1 F -(x shifted right by n bits) 379.84 378.2 T -409.96 349.01 308.98 349.01 2 L -V -N -0 F -(Numeric exceptions) 308.98 350.2 T -2 F -(TypeError) 308.98 329.2 T -1 F -(: raised on application of) 373.78 329.2 T -(arithemetic opertion to non-number) 308.98 315.2 T -2 F --2.18 (Overf) 561.26 777.2 P --2.18 (lowError) 597.26 777.2 P -1 F --0.91 (: numeric bounds exceeded) 654.86 777.2 P -2 F -(ZeroDivisionError) 561.26 763.2 T -1 F -(: raised when zero) 683.66 763.2 T -(second ar) 561.26 749.2 T -(gument of div or modulo op) 606.69 749.2 T -756.92 720.01 561.26 720.01 2 L -V -N -0 F -(Operators on all sequence types \050lists,) 561.26 721.2 T -636.6 703.01 561.26 703.01 2 L -V -N -(tuples, strings\051) 561.26 704.2 T -2 F -(len\050s\051) 561.26 683.2 T -1 F -(length of s) 632.13 683.2 T -2 F -(min\050s\051) 561.26 669.2 T -1 F -(smallest item of s) 632.13 669.2 T -2 F -(max\050s\051) 561.26 655.2 T -1 F -(lar) 632.13 655.2 T -(gest item of s) 644.57 655.2 T -2 F -(x in s) 561.26 641.2 T -1 F -(1 if an item of s is equal to x,) 632.13 641.2 T -(else 0) 632.13 627.2 T -2 F -(x not in s) 561.26 613.2 T -1 F -(0 if an item of s is equal to x,) 633.26 613.2 T -(else 1) 632.13 599.2 T -2 F -(s+t) 561.26 585.2 T -1 F -(the concatenation of s and t) 632.13 585.2 T -2 F -(s*n, n*s) 561.26 571.2 T -1 F -(n copies of s concatenated) 632.13 571.2 T -2 F -(s[i]) 561.26 557.2 T -1 F -(i\325) 632.13 557.2 T -(th item of s, origin 0) 639.24 557.2 T -2 F -(s[i:j]) 561.26 543.2 T -1 F -(slice of s from i to j) 632.13 543.2 T -3 F -(\050slice fr) 729.12 543.2 T -(om) 765.67 543.2 T -(index) 632.13 529.2 T -2 F -(i) 661.12 529.2 T -3 F -( up to but not including) 668.32 529.2 T -(index) 632.13 515.2 T -2 F -(j) 661.12 515.2 T -3 F -(.) 668.32 515.2 T -2 F -(i) 674.32 515.2 T -3 F -( defaults to) 681.52 515.2 T -2 F -(0) 737.86 515.2 T -3 F -(,) 745.06 515.2 T -2 F -(j) 751.06 515.2 T -3 F -( to) 758.26 515.2 T -2 F -(len\050s\051) 632.13 501.2 T -3 F -(.Negative goes fr) 675.33 501.2 T -(om) 756.54 501.2 T -(right-end of sequence\051) 632.13 487.2 T -762.25 458.01 561.26 458.01 2 L -V -N -0 F -( Operators on mutable sequences \050lists\051) 561.26 459.2 T -2 F -(s[i]=x) 561.26 438.2 T -1 F -(item) 632.13 438.2 T -2 F -(i) 656.46 438.2 T -1 F -( of) 663.66 438.2 T -2 F -(s) 679.66 438.2 T -1 F -( is replaced by) 686.86 438.2 T -2 F -(x) 759.51 438.2 T -(s[i:j]=t) 561.26 424.2 T -1 F -(slice of) 632.13 424.2 T -2 F -(s) 670.12 424.2 T -1 F -( from) 677.32 424.2 T -2 F -(i) 706.65 424.2 T -1 F -( to) 713.85 424.2 T -2 F -(j) 729.18 424.2 T -1 F -( is) 736.38 424.2 T -(replaced by) 632.13 410.2 T -2 F -(t) 690.77 410.2 T -(del s[i:j]) 561.26 396.2 T -1 F -(delete slice \050) 633.26 396.2 T -3 F -(same as) 693.91 396.2 T -2 F -(s[i:j]=[]) 632.13 382.2 T -1 F -(\051) 696.93 382.2 T -2 F -(s.append\050x\051) 561.26 368.2 T -1 F -(add) 640.46 368.2 T -2 F -(x) 660.79 368.2 T -1 F -( to end of) 667.99 368.2 T -2 F -(s) 716.65 368.2 T -(s.count\050x\051) 561.26 354.2 T -1 F -(return number of) 633.26 354.2 T -2 F -(i) 717.57 354.2 T -1 F -(\325) 724.77 354.2 T -(s for which) 728.11 354.2 T -2 F -(s[i] == x) 632.13 340.2 T -(s.index\050x\051) 561.26 326.2 T -1 F -(return smallest) 633.26 326.2 T -2 F -(i) 707.25 326.2 T -1 F -( such that) 714.45 326.2 T -2 F -(s[i] == x1\051) 632.13 312.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "3" 3 -%%Page: "4" 4 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -2 12 Q -0 X -0 0 0 1 0 0 0 K -(s.insert\050i, x\051) 56.69 777.2 T -1 F -(item) 157.49 777.2 T -2 F -(i) 181.83 777.2 T -1 F -( becomes) 189.03 777.2 T -2 F -(x) 237.02 777.2 T -1 F -(, old) 244.22 777.2 T -(item) 127.56 763.2 T -2 F -(i) 151.9 763.2 T -1 F -( is now at) 159.1 763.2 T -2 F -(i+1) 208.43 763.2 T -1 F -(, etc.) 230.03 763.2 T -2 F -(s.remove\050x\051) 56.69 749.2 T -1 F -(same as) 155.9 749.2 T -2 F -(del) 196.56 749.2 T -(s[s.index\050x\051]) 127.56 735.2 T -(s.reverse\050\051) 56.69 721.2 T -1 F --0.63 (reverses the items of) 155.9 721.2 P -2 F --1.51 (s) 255.36 721.2 P -1 F --0.63 ( \050in) 262.56 721.2 P -(place\051) 127.56 707.2 T -2 F -(s.sort\050\051) 56.69 693.2 T -1 F -(sorts the list \050in place\051) 127.56 693.2 T -3 F -(\050Optional parameter: function) 127.56 679.2 T --0.22 (of two ar) 127.56 665.2 P --0.22 (guments r) 170.01 665.2 P --0.22 (eturning) 217.01 665.2 P -2 F --0.54 (-1) 260.45 665.2 P -3 F --0.22 (,) 274.85 665.2 P -2 F -(0) 127.56 651.2 T -3 F -( or) 134.76 651.2 T -2 F -(1) 151.43 651.2 T -3 F -( depending on whether) 158.63 651.2 T -(ar) 127.56 637.2 T -(g1 is) 137.78 637.2 T -2 F -(>) 163.79 637.2 T -3 F -(,) 170.99 637.2 T -2 F -(==) 176.99 637.2 T -3 F -(,) 191.39 637.2 T -2 F -(<) 197.39 637.2 T -3 F -( ar) 204.59 637.2 T -(g2\051) 217.81 637.2 T -2 F -(IndexError) 56.69 623.2 T -1 F -( is raised on out-of-range) 128.69 623.2 T -(sequence subscript) 56.69 609.2 T -253.71 580.01 56.69 580.01 2 L -V -1.14 H -0 Z -N -0 F -(Operations on mappings \050dictionaries\051) 56.69 581.2 T -2 F -(len\050a\051) 56.69 560.2 T -1 F -(the number of items in) 127.56 560.2 T -2 F -(a) 239.22 560.2 T -(a[k]) 56.69 546.2 T -1 F -(the item of a with key) 127.56 546.2 T -2 F -(k) 235.55 546.2 T -(a[k] = x) 56.69 532.2 T -1 F -(set) 127.56 532.2 T -2 F -(a[k]) 143.89 532.2 T -1 F -( to) 172.69 532.2 T -2 F -(x) 188.03 532.2 T -(del a[k]) 56.69 518.2 T -1 F -(remove) 127.56 518.2 T -2 F -(a[k]) 166.55 518.2 T -1 F -( from) 195.35 518.2 T -2 F -(a) 224.68 518.2 T -(a.items\050\051) 56.69 504.2 T -1 F -(a copy of) 127.56 504.2 T -2 F -(a) 175.21 504.2 T -1 F -(\325) 182.41 504.2 T -(s list of \050key) 185.75 504.2 T -(, item\051) 244.63 504.2 T -(pairs) 127.56 490.2 T -2 F -(a.keys\050\051) 56.69 476.2 T -1 F -(a copy of) 127.56 476.2 T -2 F -(a) 175.21 476.2 T -1 F -(\325) 182.41 476.2 T -(s list of keys) 185.75 476.2 T -2 F -(a.values\050\051) 56.69 462.2 T -1 F -(a copy of) 128.69 462.2 T -2 F -(a) 176.35 462.2 T -1 F -(\325) 183.54 462.2 T -(s list of values) 186.88 462.2 T -2 F -(a.has_key\050k\051) 56.69 448.2 T -(1) 143.09 448.2 T -1 F -( if) 150.29 448.2 T -2 F -(a) 163.62 448.2 T -1 F -( has a key) 170.82 448.2 T -2 F -(k) 221.48 448.2 T -1 F -(, else) 228.68 448.2 T -2 F -(0) 256.34 448.2 T -(TypeError) 56.69 420.2 T -1 F -( is raised if key not acceptable.) 121.49 420.2 T -2 F --1.24 (KeyError) 56.69 406.2 P -1 F --0.51 ( is raised if attempt is made to read) 114.29 406.2 P -(with non-existent key) 56.69 392.2 T -221.98 363.01 56.69 363.01 2 L -V -N -0 F -(Format operator for strings \050%\051) 56.69 364.2 T -1 F -(Uses sprintf codes, supports:) 56.69 343.2 T -2 F -(%) 197.68 343.2 T -1 F -(,) 204.88 343.2 T -2 F -(c) 210.88 343.2 T -1 F -(,) 218.08 343.2 T -2 F -(s) 224.08 343.2 T -1 F -(,) 231.28 343.2 T -2 F -(i) 237.28 343.2 T -1 F -(,) 244.48 343.2 T -2 F -(d) 250.48 343.2 T -1 F -(,) 257.68 343.2 T -2 F -(u) 263.68 343.2 T -1 F -(,) 270.88 343.2 T -2 F -(o) 56.69 329.2 T -1 F -(,) 63.89 329.2 T -2 F -(x) 69.89 329.2 T -1 F -(,) 77.09 329.2 T -2 F -(X) 83.09 329.2 T -1 F -(,) 90.29 329.2 T -2 F -(e) 96.29 329.2 T -1 F -(,) 103.49 329.2 T -2 F -(E) 109.49 329.2 T -1 F -(,) 116.69 329.2 T -2 F -(f) 122.69 329.2 T -1 F -(,) 129.89 329.2 T -2 F -(g) 135.89 329.2 T -1 F -(,) 143.09 329.2 T -2 F -(G) 149.09 329.2 T -1 F -(.) 156.29 329.2 T --0.34 (W) 56.69 315.2 P --0.34 (idth and precision may be a) 67.54 315.2 P -2 F --0.82 (*) 200.8 315.2 P -1 F --0.34 ( to specify that) 208 315.2 P -(an integer ar) 308.98 777.2 T -(gument speci\336es the actual width) 368.74 777.2 T --0.29 (or precision. The \337ag characters) 308.98 763.2 P -2 F --0.7 (-) 464.81 763.2 P -1 F --0.29 (,) 472.01 763.2 P -2 F --0.7 (+) 477.72 763.2 P -1 F --0.29 (, blank,) 484.92 763.2 P -2 F --0.7 (#) 523 763.2 P -1 F -(and) 308.98 749.2 T -2 F -(0) 329.3 749.2 T -1 F -( are understood.) 336.5 749.2 T -2 F -(%s) 308.98 735.2 T -1 F -( will convert any type ar) 323.38 735.2 T -(gument to string) 440.14 735.2 T -(\050uses) 308.98 721.2 T -2 F -(str\050\051) 336.64 721.2 T -1 F -( function\051) 372.64 721.2 T -2 F -(a=\324%s has %03d quote types\325%) 308.98 707.2 T -(\050\324Python\325,2\051) 308.98 693.2 T -(a) 308.98 679.2 T -4 F -(\325) 316.18 679.2 T -1 F -(\324) 326.23 679.2 T -2 F -(Python has 002 quote types) 330.23 679.2 T -1 F -(.\325) 517.43 679.2 T -(Right-hand-side can be a mapping:) 308.98 665.2 T -2 F --1.08 (a = \324%\050lang\051s has %\050c\05103d quote) 308.98 651.2 P -(types.\325 % {\324c\325:2,) 308.98 637.2 T -(\324lang\325:\325Python}) 308.98 623.2 T -3 F -(\050) 308.98 609.2 T -2 F -(vars\050\051) 312.97 609.2 T -3 F -( function very handy to use on right-) 356.17 609.2 T -(hand-side.\051) 308.98 595.2 T -370.63 566.01 308.98 566.01 2 L -V -N -0 F -(File Objects) 308.98 567.2 T -1 F -(Created with built-in function) 308.98 546.2 T -2 F -(open\050\051) 454.97 546.2 T -1 F -( ; may) 498.17 546.2 T -(be created by other modules\325) 308.98 532.2 T -(s functions as) 447.61 532.2 T -(well. Operators:) 308.98 518.2 T -2 F -(f.close\050x\051) 308.98 504.2 T -1 F -(close \336le) 380.98 504.2 T -2 F -(f.f) 308.98 490.2 T -(lush\050x\051) 330.58 490.2 T -1 F -(\337ush \336le\325) 380.98 490.2 T -(s internal buf) 425.99 490.2 T -(fer) 489.1 490.2 T -(.) 501.76 490.2 T -2 F -(f.isatty\050\0511) 308.98 476.2 T -1 F -( if \336le is connected to a tty-) 388.18 476.2 T -(like dev) 379.84 462.2 T -(, else) 417.39 462.2 T -2 F -(0) 445.05 462.2 T -(f.read\050[size]\051) 308.98 448.2 T -1 F -(read at most most) 379.84 434.2 T -2 F -(<size>) 467.84 434.2 T -1 F -(bytes from \336le and return as a) 379.84 420.2 T -(string object. If) 379.84 406.2 T -2 F -(<size>) 456.5 406.2 T -1 F -( omit-) 499.7 406.2 T -(ted, read to) 379.84 392.2 T -2 F -(EOF) 436.49 392.2 T -1 F -(.) 457.13 392.2 T -2 F -(f.readline\050\051) 308.98 378.2 T -1 F -(read one entire line from \336le) 379.84 364.2 T -2 F -(f.readlines\050\051) 308.98 350.2 T -1 F -(read until) 379.84 336.2 T -2 F -(EOF) 428.5 336.2 T -1 F -( with) 450.1 336.2 T -2 F -(read-) 477.44 336.2 T --0.58 (line\050\051) 379.84 322.2 P -1 F --0.24 ( and return list of lines) 423.04 322.2 P -(read.) 379.84 308.2 T -2 F -(f.seek\050offset, whence=0\051) 561.26 777.2 T -1 F -(set \336le\325) 632.13 763.2 T -(s position, like stdio\325) 667.13 763.2 T -(s) 767.15 763.2 T -2 F -(fseek\050\051) 632.13 749.2 T -1 F -(.) 682.53 749.2 T -2 F -(whence == 0) 632.13 735.2 T -1 F -( then use abso-) 711.33 735.2 T -(lute indexing) 632.13 721.2 T -2 F -(whence == 1) 632.13 707.2 T -1 F -( then of) 711.33 707.2 T -(fset rel-) 747.77 707.2 T -(ative to current pos) 632.13 693.2 T -2 F -(whence == 2) 632.13 679.2 T -1 F -( then of) 711.33 679.2 T -(fset rel-) 747.77 679.2 T -(ative to \336le end) 632.13 665.2 T -2 F -(f.tell\050\051) 561.26 651.2 T -1 F -(return \336le\325) 632.13 651.2 T -(s current position) 682.45 651.2 T -2 F -(f.write\050str\051) 561.26 637.2 T -1 F -(W) 632.13 623.2 T -(rite string to \336le.) 642.97 623.2 T -2 F -(EOFError) 561.26 609.2 T -1 F -( \321 End-of-\336le hit when reading) 618.86 609.2 T -(\050may be raised many times, e.g. if) 561.26 595.2 T -2 F -(<f>) 727.23 595.2 T -1 F -( is a) 748.83 595.2 T -(tty\051.) 561.26 581.2 T -2 F -(IOError) 561.26 567.2 T -1 F -( \321 Other I/O-related I/O operation) 611.66 567.2 T -(failure) 561.26 553.2 T -0 14 Q -(Advanced T) 561.26 523.86 T -(ypes) 632.95 523.86 T -3 12 Q -(See manuals for mor) 561.26 504.2 T -(e details) 660.48 504.2 T -1 F -(Module Objects) 561.26 490.2 T -(Class Objects) 561.26 476.2 T -(T) 561.26 462.2 T -(ype Objects) 567.75 462.2 T -(Callable types:) 561.26 448.2 T -(User) 595.28 434.2 T -(-de\336ned \050written in Python\051:) 617.69 434.2 T -(User) 623.62 420.2 T -(-de\336ned Function Objects) 646.04 420.2 T -(User) 623.62 406.2 T -(-de\336ned Method Objects) 646.04 406.2 T -(Built-in \050written in C\051:) 595.28 392.2 T -(Built-in Function Objects) 623.62 378.2 T -(Built-in Method Objects) 623.62 364.2 T -(Internal T) 561.26 350.2 T -(ypes:) 608.07 350.2 T -(Code Objects) 595.28 336.2 T -(Frame Objects) 595.28 322.2 T -(T) 595.28 308.2 T -(raceback Objects) 602.19 308.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "4" 4 -%%Page: "5" 5 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 14 Q -0 X -0 0 0 1 0 0 0 K -(Statements) 56.69 775.86 T -2 12 Q -(pass) 56.69 756.2 T -1 F -(Null statement) 127.56 756.2 T -2 F -(=) 56.69 742.2 T -1 F -(assignment operator) 127.56 742.2 T -(. Can) 223.88 742.2 T -(unpack tuples,) 127.56 728.2 T -2 F --1.78 (f) 127.56 714.2 P --1.78 (irst,second = a[0:2]) 134.76 714.2 P -(del) 56.69 700.2 T -1 F -(Unbind name from object, or) 127.56 700.2 T -(attributes from objects, etc.) 127.56 686.2 T -2 F -(print [<c1> [,<c2>]* [,]) 56.69 672.2 T -1 F -(W) 127.56 658.2 T -(rites to) 138.41 658.2 T -2 F -(sys.stdout) 174.41 658.2 T -1 F -(. Puts) 246.41 658.2 T --0.92 (spaces between ar) 127.56 644.2 P --0.92 (guments. Puts) 212.13 644.2 P --0.38 (newline at end unless statement) 127.56 630.2 P -(ends with comma. Print is not) 127.56 616.2 T -(required when running interac-) 127.56 602.2 T -(tively) 127.56 588.2 T -(, simply typing an expres-) 154.12 588.2 T -(sion will print its value, unless) 127.56 574.2 T -(the value is) 127.56 560.2 T -2 F -(None) 185.22 560.2 T -1 F -(.) 214.02 560.2 T -2 F -(exec<x>[in <glob> [,<loc>]]) 56.69 546.2 T -1 F -(executes) 127.56 532.2 T -2 F -(<x>) 171.88 532.2 T -1 F -( in namespace) 193.48 532.2 T -(provided. Defaults to current) 127.56 518.2 T -(namespace.) 127.56 504.2 T -2 F -(<glob>) 186.2 504.2 T -1 F -( is a dic-) 229.4 504.2 T --0.19 (tionary containing global name-) 127.56 490.2 P -(space,) 127.56 476.2 T -2 F -(<loc>) 160.21 476.2 T -1 F -( contains local) 196.21 476.2 T -(namespace.) 127.56 462.2 T -2 F -(<x>) 186.2 462.2 T -1 F -( can be a) 207.8 462.2 T -(string, \336le object or a function) 127.56 448.2 T -(object.) 127.56 434.2 T -0 14 Q -(Contr) 56.69 404.86 T -(ol Flow) 92.21 404.86 T -2 12 Q -(if <condition>: <suite>) 56.69 385.2 T -([elif <condition>: <suite>]*) 56.69 371.2 T -([else: suite]) 56.69 357.2 T -1 F -(usual) 127.56 343.2 T -2 F -(if/else_if/else) 155.89 343.2 T -1 F -(statement) 127.56 329.2 T -2 F -(while <condition>: <suite>) 56.69 315.2 T -([else: <suite>]) 379.84 777.2 T -1 F -(usual while statement.) 379.84 763.2 T -2 F -(else) 489.83 763.2 T -1 F -(suite is executed after loop) 379.84 749.2 T -(exits, unless the loop is exited) 379.84 735.2 T -(with) 379.84 721.2 T -2 F -(break) 404.18 721.2 T -(for <target> in <condition-) 308.98 707.2 T -(list>: <suite>) 379.84 693.2 T -([else: <suite>]) 379.84 679.2 T -1 F -(iterates over sequence) 379.84 665.2 T -2 F -(<con-) 488.8 665.2 T -(dition-list>) 379.84 651.2 T -1 F -( assigning) 466.24 651.2 T -(each element to) 379.84 637.2 T -2 F -(<target>) 458.15 637.2 T -1 F -(.) 515.75 637.2 T -2 F -(else) 379.84 623.2 T -1 F -( suite executed at end) 408.64 623.2 T -(unless loop exited with \322break\323) 379.84 609.2 T -2 F -(break) 308.98 595.2 T -1 F -( immediately exit) 379.84 595.2 T -2 F -(for) 466.84 595.2 T -1 F -( or) 488.44 595.2 T -2 F -(while) 379.84 581.2 T -1 F -( loop) 415.84 581.2 T -2 F -(continue) 308.98 567.2 T -1 F -(immediately do next iteration) 379.84 567.2 T -(of) 379.84 553.2 T -2 F -(for) 392.84 553.2 T -1 F -( or) 414.44 553.2 T -2 F -(while) 430.43 553.2 T -1 F -( loop) 466.43 553.2 T -2 F -(return [<result>]) 308.98 539.2 T -1 F -(return from function \050or) 379.84 525.2 T -(method\051 and return) 379.84 511.2 T -2 F -(<result>) 379.84 497.2 T -1 F -(. If no result given,) 437.44 497.2 T -(then returns) 379.84 483.2 T -2 F -(None) 439.83 483.2 T -1 F -(.) 468.63 483.2 T -0 14 Q -(Exception Statements) 308.98 453.86 T -2 12 Q -(try: <suite1>) 308.98 434.2 T -([except [<exception> [,) 308.98 420.2 T -(<value>]: <suite2>]+) 379.84 406.2 T -([else: <suite3>]) 308.98 392.2 T -1 F -(statements in) 379.84 378.2 T -2 F -(<suite1>) 445.84 378.2 T -1 F -( are) 503.44 378.2 T -(executed. If an exception) 379.84 364.2 T -(occurs, look in) 379.84 350.2 T -2 F -(except) 453.83 350.2 T -1 F -(clauses for matching) 379.84 336.2 T -2 F -(<excep-) 482.15 336.2 T -(tion>) 379.84 322.2 T -1 F -(. If matches or bare) 415.84 322.2 T -2 F -(except) 379.84 308.2 T -1 F -( execute suite of that) 423.04 308.2 T --0.18 (clause. If no exception happens) 632.13 777.2 P -(suite in) 632.13 763.2 T -2 F -(else) 670.13 763.2 T -1 F -( clause is exe-) 698.93 763.2 T -(cuted after) 632.13 749.2 T -2 F -(<suite1>) 686.1 749.2 T -1 F -(. If) 743.7 749.2 T -2 F -(<exception>) 632.13 735.2 T -1 F -( has a value, it) 711.33 735.2 T -(is put in) 632.13 721.2 T -2 F -(<value>) 673.8 721.2 T -1 F -(.) 724.2 721.2 T -2 F -(<excep-) 730.2 721.2 T -(tion>) 632.13 707.2 T -1 F -( can also be tuple of) 668.13 707.2 T -(exceptions, e.g.) 632.13 693.2 T -2 F -(except) 709.78 693.2 T -(\050KeyError, NameEr-) 632.13 679.2 T -(ror\051, val: print val) 632.13 665.2 T -(try: <suite1>) 561.26 651.2 T -(f) 561.26 637.2 T -(inally: <suite2>) 568.46 637.2 T -1 F -(statements in) 632.13 623.2 T -2 F -(<suite1>) 698.13 623.2 T -1 F -( are) 755.73 623.2 T -(executed. If no exception, exe-) 632.13 609.2 T -(cute) 632.13 595.2 T -2 F -(<suite2>) 655.12 595.2 T -1 F -( \050even if) 712.72 595.2 T -2 F -(<suite1>) 632.13 581.2 T -1 F -( is exited with a) 689.73 581.2 T -2 F -(return) 632.13 567.2 T -1 F -(,) 675.33 567.2 T -2 F -(break) 681.33 567.2 T -1 F -( or) 717.33 567.2 T -2 F -(con-) 733.32 567.2 T -(tinue) 632.13 553.2 T -1 F -( statement\051. If an excep-) 668.13 553.2 T -(tion did occur) 632.13 539.2 T -(, executes) 698.31 539.2 T -2 F -(<suite2>) 632.13 525.2 T -1 F -( and them immedi-) 689.73 525.2 T -(ately reraises exception.) 632.13 511.2 T -2 F -(raise <exception> [,<value>]) 561.26 497.2 T -1 F -(raises) 632.13 483.2 T -2 F -(<exception>) 662.45 483.2 T -1 F -( with) 741.65 483.2 T -(optional parameter) 632.13 469.2 T -2 F -(<value>) 725.44 469.2 T -1 F -(.) 775.84 469.2 T -(An exception is simply a string \050object\051. Cre-) 561.26 441.2 T -(ate a new one simply by creating a new string:) 561.26 427.2 T -2 F -(my_exception = \324it went wrong\325) 561.26 413.2 T -(try: if bad:) 561.26 399.2 T -(raise my_exception, bad) 595.28 385.2 T -(except my_exception, value:) 561.26 371.2 T -(print \324Oops\325, value) 595.28 357.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "5" 5 -%%Page: "6" 6 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 14 Q -0 X -0 0 0 1 0 0 0 K -(Name Space Statements) 56.69 775.86 T -1 12 Q -(import <module_id1> [, <module_id2>]*) 56.69 756.2 T -(imports modules. Members of) 127.56 742.2 T -(module must be) 127.56 728.2 T -( referred to by) 207.23 728.2 T -(qualifying with module name:) 127.56 714.2 T -(\322import sys; print sys.ar) 127.56 700.2 T -(gv:) 242.68 700.2 T -2 F -(from <module_id> import <id1>) 56.69 686.2 T -([, <id2>]*) 127.56 672.2 T -1 F -(imports names from module) 127.56 658.2 T -2 F -(<module_id>) 127.56 644.2 T -1 F -(. Names) 206.76 644.2 T -( are) 249.08 644.2 T -(not quali\336ed:) 127.56 630.2 T -2 F -(from sys import argv) 127.56 616.2 T -(print argv\323) 127.56 602.2 T -(from <module_id> import *) 56.69 588.2 T -1 F -(imports all names in module) 127.56 574.2 T -2 F -(<module_id>) 127.56 560.2 T -1 F -(, except those) 206.76 560.2 T -(starting with) 127.56 546.2 T -2 F -(_) 190.9 546.2 T -(global <id1> [,<id2>]*) 56.69 532.2 T -1 F -(ids are from global scope \050usu-) 127.56 518.2 T -(ally meaning from module\051) 127.56 504.2 T -(rather than local \050usually mean-) 127.56 490.2 T -(ing only in function\051.) 127.56 476.2 T -(In a function with no \322global\323) 127.56 462.2 T -(statements, assume) 127.56 448.2 T -2 F -(a) 222.55 448.2 T -1 F -( is name) 229.75 448.2 T -(that hasn\325) 127.56 434.2 T -(t been used in fcn or) 174.34 434.2 T -(module so far) 127.56 420.2 T -(.) 192.89 420.2 T -(T) 127.56 406.2 T -(ry to read from) 134.47 406.2 T -2 F -(a) 209.78 406.2 T -4 F -(\325) 216.98 406.2 T -2 F -(NameEr-) 227.04 406.2 T -(ror) 127.56 392.2 T -1 F -(.) 148.5 392.2 T -(T) 127.56 378.2 T -(ry to write to) 134.47 378.2 T -2 F -(a) 199.8 378.2 T -4 F -(\325) 207 378.2 T -1 F -(creates) 217.05 378.2 T -2 F -(a) 253.37 378.2 T -1 F -(local to fcn. If) 127.56 364.2 T -2 F -(a) 198.54 364.2 T -1 F -( not de\336ned in) 205.74 364.2 T -(fcn, but is in module, then:) 127.56 350.2 T -(T) 127.56 336.2 T -(ry to read from) 134.47 336.2 T -2 F -(a) 209.78 336.2 T -1 F -(, gets value) 216.98 336.2 T -(from module.) 127.56 322.2 T -(T) 127.56 308.2 T -(ry to write to) 134.47 308.2 T -2 F -(a) 199.8 308.2 T -1 F -(, changes) 207 308.2 T -2 F -(a) 254.65 308.2 T -1 F -( in) 261.85 308.2 T -(module) 379.84 777.2 T -0 14 Q -(Function De\336nition) 308.98 747.86 T -2 12 Q --2.15 (def <func_id> \050[<param_list>]\051:) 308.98 728.2 P -(<suite>) 379.84 714.2 T -1 F -(creates a function object and) 379.84 700.2 T -(assigns it name) 379.84 686.2 T -2 F -(<func_id>) 456.17 686.2 T -1 F -(.) 520.97 686.2 T -2 F --1.22 (<param_list>) 308.98 672.2 P -4 F --0.57 (\325) 401.35 672.2 P -2 F --1.22 ([<id> [, <id>]*]) 414.18 672.2 P -([<id>=<v>) 379.84 658.2 T -([,<id>=<v>]*]) 379.84 644.2 T -([,*<id>]) 379.84 630.2 T -1 F -(Parameters with \322) 379.84 616.2 T -2 F -(=) 465.82 616.2 T -1 F -(\323 have) 473.02 616.2 T -(default values \050) 379.84 602.2 T -2 F -(<v>) 453.82 602.2 T -1 F -( is evalu-) 475.42 602.2 T -(ated when function de\336ned\051. If) 379.84 588.2 T -(list ends with \322) 379.84 574.2 T -2 F -(*<id>) 452.18 574.2 T -1 F -(\323 then) 488.18 574.2 T -2 F -(<id>) 379.84 560.2 T -1 F -( is assigned a tuple of all) 408.64 560.2 T -(remaining ar) 379.84 546.2 T -(gs passed to func-) 440.61 546.2 T -(tion.) 379.84 532.2 T -3 F -(\050allows varar) 401.51 532.2 T -(g functions\051) 466.07 532.2 T -1 F -(.) 523.07 532.2 T -0 14 Q -(Class De\336nition) 308.98 502.86 T -2 12 Q -(class <class_id>) 308.98 483.2 T -([\050<super_class1>) 379.84 469.2 T -([,<super_class2>]*\051]:) 379.84 455.2 T -( <suite>) 379.84 441.2 T -1 F -(Creates a class object and assigns it name) 308.98 427.2 T -2 F -(<class_id>) 308.98 413.2 T -1 F -(.) 380.98 413.2 T -2 F -(<suite>) 386.98 413.2 T -1 F -( may contain) 437.38 413.2 T -(\322) 308.98 399.2 T -2 F -(def) 314.3 399.2 T -1 F -(\323s of class methods and assignments to) 335.9 399.2 T -(class attributes) 308.98 385.2 T -(E.g.) 308.98 371.2 T -2 F -(class my_cl \050cl1, cl_lst[3]\051:) 308.98 357.2 T -1 F -(Creates a class object inheriting from both) 308.98 343.2 T -2 F -(cl1) 308.98 329.2 T -1 F -( and whatever class object) 330.58 329.2 T -2 F -(cl_lst[3]) 459.54 329.2 T -1 F --0.38 (evaluates to. Assigns new class object to name) 308.98 315.2 P -2 F -(my_class) 561.26 777.2 T -1 F -(.) 618.86 777.2 T -(First ar) 561.26 763.2 T -(g to class methods is always instance) 595.38 763.2 T -(object. By convention this is called \322) 561.26 749.2 T -2 F -(self) 738.25 749.2 T -1 F -(\323.) 767.05 749.2 T -(Special method) 561.26 735.2 T -2 F -(__init__\050\051) 638.59 735.2 T -1 F -( called when) 710.59 735.2 T -(instance created. Create instance by \322calling\323) 561.26 721.2 T -(class object, possibly with ar) 561.26 707.2 T -(gs. In current) 699.37 707.2 T --0.55 (implementation, you can\325) 561.26 693.2 P --0.55 (t subclass of) 682.94 693.2 P --0.55 (f built-in) 740.96 693.2 P -(classes.) 561.26 679.2 T -3 F -(E.g.) 561.26 665.2 T -2 F -(class c \050c_parent\051:) 561.26 651.2 T -(def __init__\050self, name\051:) 575.43 637.2 T -(self.name = name) 589.61 623.2 T -(def print_name\050self\051:) 589.61 609.2 T -(print \322I\325m\323,\134) 603.78 595.2 T -(self.name) 603.78 581.2 T -(def call_parent\050self\051:) 589.61 567.2 T -(c_parent.print_name\050self\051) 603.78 553.2 T -(instance = c\050\324tom\325\051) 561.26 539.2 T -(print instance.name) 561.26 525.2 T -(\324tom\325) 561.26 511.2 T -(instance.print_name\050\051) 561.26 497.2 T -(\322I\325m tom\323) 561.26 483.2 T -1 F --0.05 (Call parent\325) 561.26 469.2 P --0.05 (s super class by accessing parent\325) 617.54 469.2 P --0.05 (s) 777.58 469.2 P -(method directly and passing \322) 561.26 455.2 T -2 F -(self) 704.58 455.2 T -1 F -(\323 explic-) 733.38 455.2 T -(itly \050see \322) 561.26 441.2 T -2 F -(call_parent) 607.92 441.2 T -1 F -(\323 in example) 687.12 441.2 T -(above\051.) 561.26 427.2 T -(Many other special methods available for) 561.26 413.2 T -(implementing arithmetic operators, sequence,) 561.26 399.2 T -(mapping indexing, etc.) 561.26 385.2 T -0 14 Q -(Others) 561.26 355.86 T -2 12 Q -(lambda [<param_list>]: <condi-) 561.26 336.2 T -(tion>) 632.13 322.2 T -1 F -(Create an anonymous function.) 632.13 308.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "6" 6 -%%Page: "7" 7 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -2 12 Q -0 X -0 0 0 1 0 0 0 K -(<condition>) 127.56 777.2 T -1 F -( must be an) 206.76 777.2 T -(expression not a statement) 127.56 763.2 T -(\050e.g., not \322) 127.56 749.2 T -2 F -(if xx:) 178.55 749.2 T -1 F -(...\323,) 221.75 749.2 T -(\322) 127.56 735.2 T -2 F -(print xxx) 132.89 735.2 T -1 F -(\323, etc.\051 and thus) 197.69 735.2 T -(can\325) 127.56 721.2 T -(t contain newlines. Used) 147.99 721.2 T -(mostly for) 127.56 707.2 T -2 F -(f) 180.23 707.2 T -(ilter\050\051) 187.43 707.2 T -1 F -(,) 237.83 707.2 T -2 F -(map\050\051) 127.56 693.2 T -1 F -(,) 163.56 693.2 T -2 F -(reduce\050\051) 169.56 693.2 T -1 F -( functions.) 227.16 693.2 T -0 14 Q -(Built-In Functions) 56.69 663.86 T -2 12 Q -(abs\050x\051) 56.69 644.2 T -1 F -(Return the absolute value of a) 127.56 644.2 T -(number) 127.56 630.2 T -2 F -(apply\050f,args\051) 56.69 616.2 T -1 F -(Call func/method) 127.56 602.2 T -2 F -(<f>) 214.22 602.2 T -1 F -( with) 235.82 602.2 T -(ar) 127.56 588.2 T -(gs) 136.67 588.2 T -2 F -(<args>) 150.34 588.2 T -(chr\050i\051) 56.69 574.2 T -1 F -(Return one-character string) 127.56 574.2 T -(whose ASCII code is integer) 127.56 560.2 T -2 F -(i) 268.54 560.2 T -(cmp\050x,y\051) 56.69 546.2 T -1 F -(Return neg, zero, pos if) 127.56 546.2 T -2 F -(x) 243.2 546.2 T -(<) 253.4 546.2 T -1 F -(,) 260.6 546.2 T -2 F -(==) 127.56 532.2 T -1 F -(,) 141.96 532.2 T -2 F -(>) 147.96 532.2 T -1 F -( to) 155.16 532.2 T -2 F -(y) 170.49 532.2 T -(coerce\050x,y\051) 56.69 518.2 T -1 F -(Return a tuple of the two) 127.56 504.2 T -(numeric ar) 127.56 490.2 T -(guments converted) 178.99 490.2 T -(to a common type.) 127.56 476.2 T -2 F --2.15 (compile\050string, f) 56.69 462.2 P --2.15 (ilename, kind\051) 176.94 462.2 P -1 F -(Compile) 127.56 448.2 T -2 F -(<string>) 171.9 448.2 T -1 F -( into a) 229.5 448.2 T -(code object.) 127.56 434.2 T -2 F -(<f) 188.54 434.2 T -(ilename>) 202.94 434.2 T -1 F -( is) 260.54 434.2 T -(used for error reporting, can be) 127.56 420.2 T -(any string.) 127.56 406.2 T -2 F -(<kind>) 181.22 406.2 T -1 F -( is either) 224.42 406.2 T -(\324) 127.56 392.2 T -2 F -(eval) 131.55 392.2 T -1 F -(\325 if) 160.35 392.2 T -2 F -(<string>) 177.68 392.2 T -1 F -( is a sin-) 235.28 392.2 T -(gle stmt, else it should be) 127.56 378.2 T -(\324) 127.56 364.2 T -2 F -(exec) 131.55 364.2 T -1 F -(\325.) 160.35 364.2 T -2 F -(dir\050[object]\051) 56.69 350.2 T -1 F -(If no ar) 127.56 336.2 T -(gs, return the list of) 162.66 336.2 T -(names in current local symbol) 127.56 322.2 T -(table. W) 127.56 308.2 T -(ith a module, class or) 167.74 308.2 T -(class instance object as ar) 379.84 777.2 T -(g,) 502.93 777.2 T -(return list of names in its attr) 379.84 763.2 T -(dict.) 379.84 749.2 T -2 F -(divmod\050a,b\051) 308.98 735.2 T -1 F -(Returns tuple of) 379.84 721.2 T -2 F -(\050a/b, a%b\051) 460.17 721.2 T -(eval\050s, globals, locals\051) 308.98 707.2 T -1 F -(Eval string) 379.84 693.2 T -2 F -(<s>) 435.17 693.2 T -1 F -( in \050optional\051) 456.77 693.2 T -2 F -(<globals>) 379.84 679.2 T -1 F -(,) 444.64 679.2 T -2 F -(<locals>) 450.64 679.2 T -1 F -(.) 508.24 679.2 T -2 F -(<s>) 379.84 665.2 T -1 F -( must have no) 401.44 665.2 T -2 F -(NULL) 471.44 665.2 T -1 F -(\325) 499.13 665.2 T -(s or) 502.47 665.2 T -(newlines.) 379.84 651.2 T -2 F -(<s>) 428.5 651.2 T -1 F -( can also be a) 450.1 651.2 T -(code object. E.g.:) 379.84 637.2 T -2 F -(x = 1;) 466.49 637.2 T -(incr_x = eval\050\324x +) 379.84 623.2 T -(1\325\051) 379.84 609.2 T -(f) 308.98 595.2 T -(ilter\050function, list\051) 316.18 595.2 T -1 F -(Construct a list from those ele-) 379.84 581.2 T -(ments of) 379.84 567.2 T -2 F -(<list>) 424.51 567.2 T -1 F -( for which) 467.71 567.2 T -2 F -(<function>) 379.84 553.2 T -1 F -( returns true.) 451.84 553.2 T -2 F -(<function>) 379.84 539.2 T -1 F -( takes one) 451.84 539.2 T -(parameter) 379.84 525.2 T -(.) 427.16 525.2 T -2 F -(f) 308.98 511.2 T -(loat\050x\051) 316.18 511.2 T -1 F -(Convert a number to \337oating) 379.84 511.2 T -(point.) 379.84 497.2 T -2 F -(getattr\050object, name\051) 308.98 483.2 T -1 F -(Get attr called) 379.84 469.2 T -2 F -(<name>) 450.82 469.2 T -1 F -( from) 494.02 469.2 T -2 F -(<object>) 379.84 455.2 T -1 F -(.) 437.44 455.2 T -2 F -(getattr\050x, \324foobar\325\051) 379.84 441.2 T -4 F -(\326) 379.84 427.2 T -2 F -(x.foobar) 395.37 427.2 T -(hasattr\050object, name\051) 308.98 413.2 T -1 F -(Returns true if) 379.84 399.2 T -2 F -(<object>) 452.17 399.2 T -1 F -( has) 509.77 399.2 T -(attr called) 379.84 385.2 T -2 F -(<name>) 430.49 385.2 T -1 F -(.) 473.69 385.2 T -2 F -(hash\050object\051) 308.98 371.2 T -1 F -(Return the hash value of the) 379.84 357.2 T -(object \050if it has one\051) 379.84 343.2 T -2 F -(hex\050x\051) 308.98 329.2 T -1 F --0.11 (Convert a number to a hexadec-) 379.84 329.2 P -(imal string.) 379.84 315.2 T -2 F -(id\050object\051) 561.26 777.2 T -1 F -(Return a unique \324identity\325 inte-) 632.13 763.2 T -(ger for an object.) 632.13 749.2 T -2 F -(input\050[prompt]\051) 561.26 735.2 T -1 F -(Prints prompt, if given. Reads) 632.13 721.2 T -(input and evaluates it.) 632.13 707.2 T -2 F -(int\050x\051) 561.26 693.2 T -1 F -(Convert a number to a plain) 632.13 693.2 T -(integer) 632.13 679.2 T -(.) 664.79 679.2 T -2 F -(len\050s\051) 561.26 665.2 T -1 F -(Return the length \050the number) 632.13 665.2 T -(of items\051 of an object.) 632.13 651.2 T -2 F -(long\050x\051) 561.26 637.2 T -1 F -(Convert a number to a long) 632.13 637.2 T -(integer) 632.13 623.2 T -(.) 664.79 623.2 T -2 F -(map\050function, list, ...\051) 561.26 609.2 T -1 F -(Apply) 632.13 595.2 T -2 F -(<function>) 665.13 595.2 T -1 F -( to every) 737.13 595.2 T -(item of) 632.13 581.2 T -2 F -(<list>) 669.46 581.2 T -1 F -( and return a) 712.66 581.2 T -(list of the results. If additional) 632.13 567.2 T -(ar) 632.13 553.2 T -(guments are passed,) 641.23 553.2 T -2 F -(<func-) 740.55 553.2 T -(tion>) 632.13 539.2 T -1 F -( must take that many) 668.13 539.2 T -(ar) 632.13 525.2 T -(guments and it is given to) 641.23 525.2 T -2 F -(<function>) 632.13 511.2 T -1 F -( on each call.) 704.13 511.2 T -2 F -(max\050s\051) 561.26 497.2 T -1 F -(Return the lar) 632.13 497.2 T -(gest item of a) 697.9 497.2 T -(non-empty sequence.) 632.13 483.2 T -2 F -(min\050s\051) 561.26 469.2 T -1 F -(Return the smallest item of a) 632.13 469.2 T -(non-empty sequence.) 632.13 455.2 T -2 F -(oct\050x\051) 561.26 441.2 T -1 F -(Convert a number to an octal) 632.13 441.2 T -(string.) 632.13 427.2 T -2 F -(open\050f) 561.26 413.2 T -(ilename, mode=\325r\325, buf-) 604.46 413.2 T -(size=<implementation) 632.13 399.2 T -(dependent>) 632.13 385.2 T -1 F -(Return a new \336le object. First) 632.13 371.2 T -(two ar) 632.13 357.2 T -(gs are same as those for) 662.23 357.2 T -(C\325) 632.13 343.2 T -(s \322stdio open\323 function.) 643.47 343.2 T -2 F -(<bufsize>) 632.13 329.2 T -1 F -( is) 696.93 329.2 T -2 F -(0) 710.93 329.2 T -1 F -( for unbuf) 718.13 329.2 T -(f-) 765.9 329.2 T -(ered,) 632.13 315.2 T -2 F -(1) 658.78 315.2 T -1 F -( for line-buf) 665.98 315.2 T -(fered, nega-) 723.75 315.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "7" 7 -%%Page: "8" 8 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -1 12 Q -0 X -0 0 0 1 0 0 0 K -(tive for sys-default, all else, of) 127.56 777.2 T -(\050about\051 given size.) 127.56 763.2 T -2 F -(ord\050c\051) 56.69 749.2 T -1 F -(Return integer) 127.56 749.2 T -2 F -(ASCII) 199.55 749.2 T -1 F -( value of) 235.55 749.2 T -2 F -(<c>) 127.56 735.2 T -1 F -( \050a string of len) 149.16 735.2 T -2 F -(1) 225.48 735.2 T -1 F -(\051.) 232.68 735.2 T -2 F -(pow\050x, y\051) 56.69 721.2 T -1 F -(Return) 127.56 721.2 T -2 F -(x) 163.22 721.2 T -1 F -( to power) 170.42 721.2 T -2 F -(y) 218.75 721.2 T -1 F -(.) 225.17 721.2 T -2 F -(range\050start, end, step\051) 56.69 707.2 T -1 F -(return list of ints from) 127.56 693.2 T -2 F -(>=) 236.55 693.2 T -1 F -( start) 250.96 693.2 T --0.18 (and) 127.56 679.2 P -2 F --0.43 (<) 147.71 679.2 P -1 F --0.18 ( end. W) 154.91 679.2 P --0.18 (ith 1 ar) 191.73 679.2 P --0.18 (g, list from) 225.16 679.2 P -(0 to) 127.56 665.2 T -2 F -(<arg>-1.) 148.9 665.2 T -1 F -( W) 206.49 665.2 T -(ith 2 ar) 220.34 665.2 T -(gs,) 254.12 665.2 T -(list from) 127.56 651.2 T -2 F -(<start>) 171.56 651.2 T -1 F -( to) 221.96 651.2 T -2 F -(<end>-) 237.3 651.2 T -(1) 127.56 637.2 T -1 F -(W) 141.96 637.2 T -(ith 3 ar) 152.81 637.2 T -(gs, list from) 186.59 637.2 T -2 F -(<start>) 127.56 623.2 T -1 F -( up to) 177.96 623.2 T -2 F -(<end>) 208.29 623.2 T -1 F -( by) 244.29 623.2 T -2 F -(<step>) 127.56 609.2 T -(raw_input\050[prompt]\051) 56.69 595.2 T -1 F --0.21 (Print prompt if given, then read) 127.56 581.2 P -(string from std input.) 127.56 567.2 T -2 F -(reduce\050f, list [, init]\051) 56.69 553.2 T -1 F -(Apply the binary function) 127.56 539.2 T -2 F -(<f>) 254.88 539.2 T -1 F --0.52 (to the items of) 127.56 525.2 P -2 F --1.24 (<list>) 197.49 525.2 P -1 F --0.52 ( so as to) 240.69 525.2 P -(reduce the list to a single value.) 127.56 511.2 T -(If) 127.56 497.2 T -2 F -(<init>) 138.55 497.2 T -1 F -( given, it is \322pre-) 181.75 497.2 T -(pended\323 to) 127.56 483.2 T -2 F -(<list>) 182.88 483.2 T -1 F -(.) 226.08 483.2 T -2 F -(reload\050module\051) 56.69 469.2 T -1 F -(Re-parse and re-initialize an) 127.56 455.2 T -(already imported module. Use-) 127.56 441.2 T -(ful in interactive mode, if you) 127.56 427.2 T -(want to reload a module after) 127.56 413.2 T --0.05 (\336xing it. If module was synacti-) 127.56 399.2 P --0.17 (cally correct but had an error in) 127.56 385.2 P -(initialization, must import it) 127.56 371.2 T -(one more time before calling) 127.56 357.2 T -2 F -(reload) 127.56 343.2 T -1 F -(\050\051.) 170.76 343.2 T -2 F -(repr\050object\051) 56.69 329.2 T -1 F -(Return a string containing a) 127.56 315.2 T -(printable representation of an) 379.84 777.2 T -(object. Equivalent to `object`) 379.84 763.2 T -(\050using backquotes\051.) 379.84 749.2 T -2 F -(round\050x,n=0\051) 308.98 735.2 T -1 F -(Return the \337oating point value) 379.84 721.2 T -(x rounded to n digits) 379.84 707.2 T -(after the) 482.18 707.2 T -(decimal point.) 379.84 693.2 T -2 F -(setattr\050object, name, value\051) 308.98 679.2 T -1 F -(This is the counterpart of) 379.84 665.2 T -2 F -(getattr) 379.84 651.2 T -1 F -(\050\051.) 430.24 651.2 T -2 F -(setattr\050o,) 444.23 651.2 T -(\324foobar\325, 3\051) 379.84 637.2 T -4 F -(\326) 469.24 637.2 T -2 F -(o.foo-) 484.77 637.2 T -(bar = 3) 379.84 623.2 T -(str\050object\051) 308.98 609.2 T -1 F -(Return a string containing a) 379.84 595.2 T -(nicely printable representation) 379.84 581.2 T -(of an object.) 379.84 567.2 T -2 F -(type\050object\051) 308.98 553.2 T -1 F -(Return type of an object.) 379.84 539.2 T -(E.g.,) 308.98 525.2 T -2 F -(if type\050x\051 == type\050\324\325\051:) 323.15 511.2 T -(print \324It is a string\325) 337.32 497.2 T -(vars\050[object]\051) 308.98 483.2 T -1 F -(W) 379.84 469.2 T -(ithout ar) 390.69 469.2 T -(guments, return a) 430.81 469.2 T --0.06 (dictionary corresponding to the) 379.84 455.2 P -(current local symbol table.) 379.84 441.2 T -(W) 379.84 427.2 T -(ith a module, class or class) 390.69 427.2 T -(instance object as ar) 379.84 413.2 T -(gument) 476.6 413.2 T --0.18 (returns a dictionary correspond-) 379.84 399.2 P --0.54 (ing to the object\325) 379.84 385.2 P --0.54 (s symbol table.) 459.21 385.2 P -(Useful with \322) 379.84 371.2 T -2 F -(%) 444.5 371.2 T -1 F -(\323 formatting) 451.7 371.2 T -(operator) 379.84 357.2 T -(. Don\325) 419.17 357.2 T -(t simply type) 449.61 357.2 T -2 F --0.06 (vars\050\051) 379.84 343.2 P -1 F --0.03 ( at interactive prompt!) 423.04 343.2 P -(\050But) 379.84 329.2 T -2 F -(print vars\050\051) 404.18 329.2 T -1 F -( is \336ne.\051) 490.58 329.2 T -2 F -(xrange\050start, end, step\051) 308.98 315.2 T -1 F -(Like) 632.13 777.2 T -2 F -(range\050\051) 657.12 777.2 T -1 F -(, but doesn\325) 707.52 777.2 T -(t) 763.63 777.2 T -(actually store entire list all at) 632.13 763.2 T --0.36 (once. Good to use in) 632.13 749.2 P -2 F --0.86 (for) 732.31 749.2 P -1 F --0.36 ( loops) 753.91 749.2 P -(when there is a big range and) 632.13 735.2 T -(little memory) 632.13 721.2 T -(.) 696.35 721.2 T -0 14 Q -(Built-In Exceptions) 561.26 691.86 T -2 12 Q -(AttributeError) 561.26 672.2 T -1 F -(On attribute reference or) 632.13 658.2 T -(assignment failure) 632.13 644.2 T -2 F -(EOFError) 561.26 630.2 T -1 F -(Immediate end-of-\336le hit by) 632.13 616.2 T -(input\050\051 or raw_input\050\051) 632.13 602.2 T -2 F -(IOError) 561.26 588.2 T -1 F -(I/O-related I/O operation fail-) 632.13 574.2 T -(ure) 632.13 560.2 T -2 F -(ImportError) 561.26 546.2 T -1 F -(On failure of `import\325 to \336nd) 632.13 532.2 T -(module or name) 632.13 518.2 T -2 F -(IndexError) 561.26 504.2 T -1 F -(On out-of-range sequence sub-) 632.13 490.2 T -(script) 632.13 476.2 T -2 F -(KeyError) 561.26 462.2 T -1 F -(On reference to a non-existent) 632.13 448.2 T -(mapping \050dict\051 key) 632.13 434.2 T -2 F -(KeyboardInterrupt) 561.26 420.2 T -1 F -(On user entry of the interrupt) 632.13 406.2 T -(key \050often `Control-C\325\051) 632.13 392.2 T -2 F -(MemoryError) 561.26 378.2 T -1 F -(On recoverable memory) 632.13 364.2 T -(exhaustion) 632.13 350.2 T -2 F -(NameError) 561.26 336.2 T -1 F -(On failure to \336nd a local or glo-) 632.13 322.2 T -(bal \050unquali\336ed\051 name) 632.13 308.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "8" 8 -%%Page: "9" 9 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -2 12 Q -0 X -0 0 0 1 0 0 0 K -(Overf) 56.69 777.2 T -(lowError) 92.69 777.2 T -1 F -(On excessively lar) 127.56 763.2 T -(ge arithme-) 215.99 763.2 T -(tic operation) 127.56 749.2 T -2 F -(RuntimeError) 56.69 735.2 T -1 F -(Obsolete catch-all; de\336ne a) 127.56 721.2 T -(suitable error instead) 127.56 707.2 T -2 F -(SyntaxError) 56.69 693.2 T -1 F -(On parser encountering a syn-) 127.56 679.2 T -(tax error) 127.56 665.2 T -2 F -(SystemError) 56.69 651.2 T -1 F -(On non-fatal interpreter error -) 127.56 637.2 T -(bug - report it) 127.56 623.2 T -2 F -(SystemExit) 56.69 609.2 T -1 F -(On `sys.exit\050\051\325) 127.56 595.2 T -2 F -(TypeError) 56.69 581.2 T -1 F -(On passing inappropriate type) 127.56 567.2 T -(to built-in op or func) 127.56 553.2 T -2 F -(ValueError) 56.69 539.2 T -1 F -(On ar) 127.56 525.2 T -(g error not covered by) 154.33 525.2 T -(T) 127.56 511.2 T -(ypeError or more precise) 134.05 511.2 T -2 F -(ZeroDivisionError) 56.69 497.2 T -1 F -(On division or modulo opera-) 127.56 483.2 T -(tion with 0 as 2nd ar) 127.56 469.2 T -(g) 225.67 469.2 T -0 14 Q -(Special Methods For User) 56.69 439.86 T -(-De\336ned) 211.32 439.86 T -(Classes) 56.69 422.86 T -3 12 Q -(E.g) 56.69 403.2 T -1 F -(.) 73.03 403.2 T -2 F -(class x:) 56.69 389.2 T -(def __init__\050self, v\051:) 70.87 375.2 T -(self.value = v def) 85.04 361.2 T -(__add__\050self, r\051:) 70.87 347.2 T -(return self.value + r) 85.04 333.2 T -(a = x\0503\051) 56.69 319.2 T -3 F -(\050like calling) 323.15 777.2 T -2 F -(x.__init__\050a,3\051\051) 383.81 777.2 T -(a + 4) 308.98 763.2 T -3 F -(\050equivalent to) 323.15 749.2 T -2 F -( a.__add__\0504\051\051) 389.47 749.2 T -456.97 720.01 308.98 720.01 2 L -V -1.14 H -0 Z -N -0 F -(Special methods for any type) 308.98 721.2 T -3 F -(\050s: self, o: other\051) 308.98 700.2 T -2 F -( __init__\050s, args\051) 308.98 686.2 T -1 F -(object instantiation) 379.84 672.2 T -2 F -(__del__\050s\051) 308.98 658.2 T -1 F -(called on object demise) 379.84 644.2 T -2 F -(__repr__\050s\051) 308.98 630.2 T -(repr) 379.84 616.2 T -1 F -(\050\051 and `...` conversions) 408.64 616.2 T -2 F -(__str__\050s\051) 308.98 602.2 T -(str) 379.84 588.2 T -1 F -(\050\051 and \324) 401.44 588.2 T -2 F -(print) 436.76 588.2 T -1 F -(\325 statement) 472.76 588.2 T -2 F -(__cmp__\050s, o\051) 308.98 574.2 T -1 F -(implements) 379.84 560.2 T -2 F -(<) 438.85 560.2 T -1 F -(,) 446.05 560.2 T -2 F -(==) 452.05 560.2 T -1 F -(,) 466.45 560.2 T -2 F -(>) 472.45 560.2 T -1 F -(,) 479.65 560.2 T -2 F -(<=) 485.65 560.2 T -1 F -(,) 500.05 560.2 T -2 F -(<>) 506.05 560.2 T -1 F -(,) 520.45 560.2 T -2 F -(!=) 379.84 546.2 T -1 F -(,) 394.24 546.2 T -2 F -(>=) 400.24 546.2 T -1 F -(,) 414.64 546.2 T -2 F -(is) 420.64 546.2 T -1 F -( [) 435.04 546.2 T -2 F -(not) 442.04 546.2 T -1 F -(]) 463.64 546.2 T -2 F -(__hash__\050s\051) 308.98 532.2 T -(hash) 379.84 518.2 T -1 F -(\050\051 and dict operations) 408.64 518.2 T -508.3 489.01 308.98 489.01 2 L -V -N -0 F -(Numeric operations vs special methods) 308.98 490.2 T -3 F -(\050s: self, o: other\051) 308.98 469.2 T -2 F -(s+o = __add__\050s,o\051) 308.98 455.2 T -(s-o = __sub__\050s,o\051) 308.98 441.2 T -(s*o = __mul__\050s,o\051) 308.98 427.2 T -(s/o = __div__\050s,o\051) 308.98 413.2 T -(s%o = __mod__\050s,o\051) 308.98 399.2 T -(divmod\050s,o\051 = __divmod__\050s,o\051) 308.98 385.2 T -(pow\050s,o\051 = __pow__\050s,o\051) 308.98 371.2 T -(s&o = __and__\050s,o\051) 308.98 357.2 T -(s^o = __xor__\050s,o\051) 308.98 343.2 T -(s|o = __or__\050s,o\051) 308.98 329.2 T -(s<<o = __lshift__\050s,o\051) 308.98 315.2 T -(s>>o = __rshift__\050s,o\051) 561.26 777.2 T -(nonzero\050s\051 = __nonzero__\050s\051) 561.26 763.2 T -3 F -(\050used in boolean testing\051) 632.13 749.2 T -2 F -(-s = __neg__\050s\051) 561.26 735.2 T -(+s = __pos__\050s\051) 561.26 721.2 T -(abs\050s\051 = __abs__\050s\051) 561.26 707.2 T -(~s = __invert__\050s\051) 561.26 693.2 T -3 F -(\050bitwise\051) 698.06 693.2 T -2 F -(int\050s\051 = __int__\050s\051) 561.26 679.2 T -(long\050s\051 = __long__\050s\051) 561.26 665.2 T -(f) 561.26 651.2 T -(loat\050s\051 = __f) 568.46 651.2 T -(loat__\050s\051) 662.06 651.2 T -(oct\050s\051 = __oct__\050s\051) 561.26 637.2 T -(hex\050s\051 = __hex__\050s\051) 561.26 623.2 T -(coerce\050s,o\051 = __coerce__\050s,o\051) 561.26 609.2 T -782.95 580.01 561.26 580.01 2 L -V -N -0 F -(All seqs and maps, general operations plus:) 561.26 581.2 T -3 F -(\050s: self, i: index or key\051) 561.26 560.2 T -2 F -( len\050s\051 = __len__\050s\051) 561.26 546.2 T -1 F -(length of object,) 632.13 532.2 T -2 F -(>= 0.) 713.45 532.2 T -1 F -(Length 0 == false) 632.13 518.2 T -2 F -(s[i] = __getitem__\050s,i\051) 561.26 504.2 T -1 F -(Element at index/key) 632.13 490.2 T -2 F -(i) 737.11 490.2 T -1 F -(, origin) 744.31 490.2 T -2 F -(0) 632.13 476.2 T -735.6 447.01 561.26 447.01 2 L -V -N -0 F -(Sequences, general methods, plus:) 561.26 448.2 T -2 F -(s[i]=v) 561.26 427.2 T -4 F -(\325) 611.66 427.2 T -2 F -(__setitem__\050s,i,v\051) 625.05 427.2 T -(del s[i]) 561.26 413.2 T -4 F -(\325) 626.06 413.2 T -2 F -(__delitem__\050s,i\051) 639.45 413.2 T -(s[i:j]) 561.26 399.2 T -4 F -(\325) 611.66 399.2 T -2 F -(__getslice__\050s,i,j\051) 621.72 399.2 T -(s[i:j]=seq) 561.26 385.2 T -4 F -(\325) 640.46 385.2 T -2 F -(__setslice__\050s,i,j,seq\051) 561.26 371.2 T -(del s[i:j]) 561.26 357.2 T -4 F -(\325) 640.46 357.2 T -2 F -(__delslice__\050s,i,j\051==s[i:j]=[]) 561.26 343.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "9" 9 -%%Page: "10" 10 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -229.71 776.01 56.69 776.01 2 L -0 X -0 0 0 1 0 0 0 K -V -1.14 H -0 Z -N -0 12 Q -(Mappings, general methods, plus:) 56.69 777.2 T -2 F -(hash\050s\051) 56.69 756.2 T -4 F -(\325) 114.29 756.2 T -2 F -( __hash__\050s\051) 124.35 756.2 T -1 F -(hash value for dictionary refer-) 127.56 742.2 T -(ences) 127.56 728.2 T -2 F -(s[k]=v) 56.69 714.2 T -4 F -(\325) 107.09 714.2 T -2 F -(__setitem__\050s,k,v\051) 120.49 714.2 T -(del s[k]) 56.69 700.2 T -4 F -(\325) 121.49 700.2 T -2 F -(__delitem__\050s,k\051) 134.88 700.2 T -257.66 671.01 56.69 671.01 2 L -V -N -0 F -(Special informative state attributes for) 56.69 672.2 T -116.35 654.01 56.69 654.01 2 L -V -N -(some types:) 56.69 655.2 T -2 F -(X.__dict__) 56.69 634.2 T -1 F --0.12 (dict used to store object\325) 127.56 620.2 P --0.12 (s write-) 244.42 620.2 P -(able attributes) 127.56 606.2 T -2 F -(X.__methods__) 56.69 592.2 T -1 F -(list of X\325) 127.56 578.2 T -(s methods; on many) 170.23 578.2 T -(built-in types.) 127.56 564.2 T -2 F -(X.__members__) 56.69 550.2 T -1 F -(lists of X\325) 127.56 536.2 T -(s data attributes) 174.9 536.2 T -2 F -(X.__class__) 56.69 522.2 T -1 F -(class to which X belongs) 127.56 508.2 T -2 F -(X.__bases__) 56.69 494.2 T -1 F -(tuple of X base classes) 127.56 480.2 T -2 F -(M.__name__) 56.69 466.2 T -1 F --0.22 (r/o attr) 127.56 452.2 P --0.22 (, module\325) 159.19 452.2 P --0.22 (s name as string) 204.3 452.2 P -0 14 Q -(Important Modules) 56.69 422.86 T -72.03 392.01 56.69 392.01 2 L -V -N -0 12 Q -(sys) 56.69 393.2 T -1 F -(V) 56.69 372.2 T -(ariables:) 64.03 372.2 T -2 F -(argv) 56.69 358.2 T -1 F -(The list of command line ar) 127.56 358.2 T -(gu-) 260.33 358.2 T --0.65 (ments passed to a Python script.) 127.56 344.2 P -(sys.ar) 127.56 330.2 T -(gv[0] is the script name.) 155 330.2 T -2 F -(builtin_module_names) 56.69 316.2 T -1 F -(A list of strings giving the) 379.84 777.2 T --0.26 (names of all modules written in) 379.84 763.2 P -(C that are linked into this inter-) 379.84 749.2 T -(preter) 379.84 735.2 T -(.) 407.17 735.2 T -2 F -(exc_type) 308.98 721.2 T -(exc_value) 308.98 707.2 T -(exc_traceback) 308.98 693.2 T -1 F -(Set when in an exception han-) 379.84 679.2 T -(dler) 379.84 665.2 T -(. Are last exception, last) 397.84 665.2 T -(exception value, and traceback) 379.84 651.2 T --0.24 (object of call stack when excep-) 379.84 637.2 P -(tion occured.) 379.84 623.2 T -2 F -(exitfunc) 308.98 609.2 T -1 F -(User can set to a parameterless) 379.84 609.2 T -(fcn. It will get called before) 379.84 595.2 T -(interpreter exits.) 379.84 581.2 T -2 F -(last_type) 308.98 567.2 T -(last_value) 308.98 553.2 T -(last_traceback) 308.98 539.2 T -1 F --0.15 (Set only when an exception not) 379.84 525.2 P -(handled and interpreter prints) 379.84 511.2 T -(an error) 379.84 497.2 T -(. Used by debuggers.) 416.83 497.2 T -2 F -(modules) 308.98 483.2 T -1 F -(List of modules that have) 379.84 483.2 T -(already been loaded.) 379.84 469.2 T -2 F -(path) 308.98 455.2 T -1 F -( Search path for external mod-) 379.84 455.2 T -(ules. Can be modi\336ed by pro-) 379.84 441.2 T -(gram.) 379.84 427.2 T -2 F -(ps1) 308.98 413.2 T -(ps2) 308.98 399.2 T -1 F -(prompts to use in interactive) 379.84 399.2 T -(mode.) 379.84 385.2 T -2 F -(stdin stdout) 308.98 371.2 T -(stderr) 308.98 357.2 T -1 F -(File objects used for I/O. User) 379.84 357.2 T --0.15 (can redirect by assigning a new) 379.84 343.2 P -(\336le object to them \050or any) 379.84 329.2 T -(object with a method \322write\050\051\323) 379.84 315.2 T -(taking string ar) 632.13 777.2 T -(gument\051.) 704.57 777.2 T -2 F -(tracebacklimit) 561.26 763.2 T -1 F -(Maximum levels of tb info) 632.13 749.2 T -(printed on error) 632.13 735.2 T -(.) 706.78 735.2 T -(Functions:) 561.26 721.2 T -2 F -(exit\050n\051) 561.26 707.2 T -1 F -(Exit with status <n>. Raises) 632.13 707.2 T -(SystemExit exception. \050Hence) 632.13 693.2 T -(can be caught and ignored by) 632.13 679.2 T -(program\051) 632.13 665.2 T -2 F -(settrace\050func\051) 561.26 651.2 T -1 F -(Sets a trace function: called) 632.13 637.2 T -(before each line of code is) 632.13 623.2 T -(exited.) 632.13 609.2 T -2 F -(setprof) 561.26 595.2 T -(ile\050func\051) 611.66 595.2 T -1 F -(Sets a pro\336le function for per-) 632.13 581.2 T -(formance pro\336ling.) 632.13 567.2 T -571.93 538.01 561.26 538.01 2 L -V -N -0 F -(os) 561.26 539.2 T -1 F -(synonym for whatever O/S-speci\336c module is) 561.26 518.2 T -(proper for current environment. Uses) 561.26 504.2 T -2 F -(posix) 742.54 504.2 T -1 F -(whenever possible.) 561.26 490.2 T -(V) 561.26 476.2 T -(ariables) 568.59 476.2 T -2 F -(name) 561.26 462.2 T -1 F -(name of O/S-speci\336c module) 632.13 462.2 T -(\050e.g.) 632.13 448.2 T -2 F -(posix) 656.45 448.2 T -1 F -( or) 692.45 448.2 T -2 F -(mac) 708.45 448.2 T -1 F -(\051) 730.05 448.2 T -2 F -(path) 561.26 434.2 T -1 F -(O/S-speci\336c module for path) 632.13 434.2 T -(manipulations. On Unix,) 632.13 420.2 T -2 F -(os.path.split\050\051) 632.13 406.2 T -4 F -(\326) 743.13 406.2 T -2 F -(posixpath.split\050\051) 632.13 392.2 T -(curdir) 561.26 378.2 T -1 F -(string used to represent current) 632.13 378.2 T -(directory \050\324.\325\051) 632.13 364.2 T -2 F -(pardir) 561.26 350.2 T -1 F -(string used to represent parent) 632.13 350.2 T -(directory \050\324..\325\051) 632.13 336.2 T -2 F -(sep) 561.26 322.2 T -1 F -(string used to separate directo-) 632.13 322.2 T -(ries \050\324/\325\051) 632.13 308.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "10" 10 -%%Page: "11" 11 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -83.37 776.01 56.69 776.01 2 L -0 X -0 0 0 1 0 0 0 K -V -1.14 H -0 Z -N -0 12 Q -(posix) 56.69 777.2 T -1 F -(V) 56.69 756.2 T -(ariables:) 64.03 756.2 T -(environ) 56.69 742.2 T -(dictionary of environment vari-) 127.56 742.2 T -(ables,) 127.56 728.2 T -(E.g..) 56.69 714.2 T -2 F -(posix.environ[\324HOME\325]) 82.03 714.2 T -(error) 56.69 700.2 T -1 F -(exception raised on POSIX-) 127.56 700.2 T -(related error) 127.56 686.2 T -(. Corresponding) 185.87 686.2 T -(value is tuple of errno code and) 127.56 672.2 T -(perror\050\051 string.) 127.56 658.2 T -(Some Functions \050see doc for more\051:) 56.69 644.2 T -2 F -(chdir\050path\051) 56.69 630.2 T -1 F -(Go to) 127.56 616.2 T -2 F -(<path>) 157.56 616.2 T -1 F -(.) 200.76 616.2 T -2 F -(close\050fd\051) 56.69 602.2 T -1 F -(Close \336le descriptor) 127.56 602.2 T -2 F -(<fd>) 227.22 602.2 T -1 F -(.) 256.02 602.2 T -2 F -(_exit\050n\051) 56.69 588.2 T -1 F -(Immediate exit, with no clean-) 127.56 588.2 T -(ups, no) 127.56 574.2 T -2 F -(SystemExit) 165.23 574.2 T -1 F -(, etc.) 237.23 574.2 T -(Should use this to exit a child) 127.56 560.2 T -(process.) 127.56 546.2 T -2 F -(exec\050p, args\051) 56.69 532.2 T -1 F --0.79 (\322Become\323 executable) 127.56 518.2 P -2 F --1.89 (<p>) 233.27 518.2 P -1 F --0.79 ( with) 254.87 518.2 P -(ar) 127.56 504.2 T -(gs) 136.67 504.2 T -2 F -(<args>) 150.34 504.2 T -(fork\050\051) 56.69 490.2 T -1 F -(Like C\325) 127.56 490.2 T -(s) 163.9 490.2 T -2 F -(fork) 171.56 490.2 T -1 F -(\050\051. Returns 0 to) 200.36 490.2 T -(child, child pid to parent.) 127.56 476.2 T -2 F -(kill\050pid, signal\051) 56.69 462.2 T -1 F -(Like C\325) 127.56 448.2 T -(s kill) 163.9 448.2 T -2 F -(listdir\050path\051) 56.69 434.2 T -1 F -(List names of entries in direc-) 127.56 420.2 T -(tory <path>.) 127.56 406.2 T -2 F -(open\050f) 56.69 392.2 T -(ile, f) 99.89 392.2 T -(lags, mode\051) 143.09 392.2 T -1 F -(Like C\325) 127.56 378.2 T -(s) 163.9 378.2 T -2 F -(open) 171.56 378.2 T -1 F -(\050\051. Returns \336le) 200.36 378.2 T -(descriptor) 127.56 364.2 T -(.) 174.89 364.2 T -2 F -(pipe) 56.69 350.2 T -1 F -(\050\051) 85.49 350.2 T -(Creates pipe. Returns pair of) 127.56 350.2 T -(\336le descriptors \050r) 127.56 336.2 T -(, w\051.) 209.06 336.2 T -2 F -(popen\050command, mode\051) 56.69 322.2 T -1 F -(Open a pipe to or from) 127.56 308.2 T -2 F -(<com-) 240.2 308.2 T -(mand>) 379.84 777.2 T -1 F -(. Result is a \336le object) 415.84 777.2 T --0.13 (to read to or write from, as indi-) 379.84 763.2 P -(cated by) 379.84 749.2 T -2 F -(<mode>) 423.16 749.2 T -1 F -( being \324r) 466.36 749.2 T -(\325 or) 507.46 749.2 T -(\324w\325.) 379.84 735.2 T -2 F -(read\050fd, n\051) 308.98 721.2 T -1 F -(Read <n> bytes from <fd> and) 379.84 707.2 T -(return as string.) 379.84 693.2 T -2 F -(stat\050path\051) 308.98 679.2 T -1 F -(Returns) 379.84 665.2 T -2 F -(st_mode,) 420.17 665.2 T -(st_ino, st_dev,) 379.84 651.2 T -(st_nlink, st_uid,) 379.84 637.2 T -(st_gid, st_size,) 379.84 623.2 T -(st_atime, st_mtime,) 379.84 609.2 T -(st_ctime) 379.84 595.2 T -1 F -(.) 437.44 595.2 T -2 F -(system\050command\051) 308.98 581.2 T -1 F -(Execute string) 379.84 567.2 T -2 F -(<command>) 451.83 567.2 T -1 F -( in) 516.63 567.2 T --0.1 (a subhell. Returns exit status of) 379.84 553.2 P -(subshell.) 379.84 539.2 T -2 F -(unlink\050path\051) 308.98 525.2 T -1 F -(Unlink \050\322delete\323\051 path/\336le.) 379.84 511.2 T -2 F -(wait\050\051) 308.98 497.2 T -1 F -(W) 379.84 497.2 T -(ait for child process comple-) 390.21 497.2 T -(tion. Returns tuple of pid,) 379.84 483.2 T -(exit_status) 379.84 469.2 T -2 F -(waitpid\050pid, options\051) 308.98 455.2 T -1 F -(W) 379.84 441.2 T -(ait for process pid to com-) 390.21 441.2 T -(plete. Returns tuple of pid,) 379.84 427.2 T -(exit_status) 379.84 413.2 T -2 F -(write\050fd, str\051) 308.98 399.2 T -1 F --0.65 (W) 379.84 385.2 P --0.65 (rite) 390.69 385.2 P -2 F --1.56 (<str>) 409.04 385.2 P -1 F --0.65 ( to) 445.04 385.2 P -2 F --1.56 (<fd>) 459.08 385.2 P -1 F --0.65 (. Returns) 487.88 385.2 P -(num bytes written.) 379.84 371.2 T -358.99 342.01 308.98 342.01 2 L -V -N -0 F -(posixpath) 308.98 343.2 T -1 F -(Some Functions \050see doc for more\051:) 308.98 322.2 T -2 F -(exists\050p\051) 308.98 308.2 T -1 F --0.54 (T) 379.84 308.2 P --0.54 (rue if string) 386.75 308.2 P -2 F --1.29 (<p>) 444.13 308.2 P -1 F --0.54 ( is an existing) 465.73 308.2 P -(path) 632.13 777.2 T -2 F -(expanduser\050p\051) 561.26 763.2 T -1 F -(Returns string that is) 632.13 749.2 T -2 F -(<p>) 734.8 749.2 T -1 F -( with) 756.4 749.2 T -(\322~\323 expansion done.) 632.13 735.2 T -2 F -(isabs\050p\051) 561.26 721.2 T -1 F -(T) 632.13 707.2 T -(rue if string) 639.04 707.2 T -2 F -(<p>) 698.03 707.2 T -1 F -( is an abso-) 719.63 707.2 T -(lute path.) 632.13 693.2 T -2 F -(isdir\050p\051) 561.26 679.2 T -1 F --0.04 (T) 632.13 665.2 P --0.04 (rue if string <p> is a directory) 639.04 665.2 P --0.04 (.) 782.2 665.2 P -2 F -(isf) 561.26 651.2 T -(ile\050p\051) 582.86 651.2 T -1 F -(T) 632.13 651.2 T -(rue if string <p> is a regular) 639.04 651.2 T -(\336le.) 632.13 637.2 T -2 F -(islink\050p\051) 561.26 623.2 T -1 F --0.24 (T) 632.13 623.2 P --0.24 (rue if string <p> is a symbolic) 639.04 623.2 P -(link.) 632.13 609.2 T -2 F -(isf) 561.26 595.2 T -(ile\050p\051) 582.86 595.2 T -1 F -(T) 632.13 595.2 T -(rue if string <p> is a regular) 639.04 595.2 T -(\336le.) 632.13 581.2 T -2 F -(ismount\050p\051) 561.26 567.2 T -1 F -(T) 633.26 567.2 T -(rue if string <p> is a mount) 640.17 567.2 T -(point.) 632.13 553.2 T -2 F -(split\050p\051) 561.26 539.2 T -1 F -(Splits into \050head, tail\051 where) 632.13 539.2 T -2 F -(<tail>) 632.13 525.2 T -1 F -( is last pathname com-) 675.33 525.2 T -(ponent and) 632.13 511.2 T -2 F -(<head>) 688.12 511.2 T -1 F -( is every-) 731.32 511.2 T -(thing leading up to that.) 632.13 497.2 T -2 F -(splitext\050p\051) 561.26 483.2 T -1 F -(Splits into) 632.13 469.2 T -2 F -(\050root, ext\051) 684.15 469.2 T -1 F -(where last comp of) 632.13 455.2 T -2 F -(<root>) 726.77 455.2 T -1 F --0.52 (contains no periods and) 632.13 441.2 P -2 F --1.24 (<ext>) 746.71 441.2 P -1 F --0.23 (is empty or starts with a period.) 632.13 427.2 P -2 F -(walk\050p, visit, arg\051) 561.26 413.2 T -1 F -(Calls the function) 632.13 399.2 T -2 F -(<visit>) 720.46 399.2 T -1 F -(with ar) 632.13 385.2 T -(guments) 665.57 385.2 T -2 F -( \050<arg>,) 706.24 385.2 T --2.03 (<dirname>, <names>\051) 632.13 371.2 P -1 F --0.85 ( for) 766.9 371.2 P -(each directory in the directory) 632.13 357.2 T -(tree rooted at) 632.13 343.2 T -2 F -(<p>) 698.44 343.2 T -1 F -( The ar) 720.04 343.2 T -(gu-) 753.81 343.2 T --0.93 (ment) 632.13 329.2 P -2 F --2.23 (<dirname>) 658.2 329.2 P -1 F --0.93 ( speci\336es the) 723 329.2 P -(visited directory) 632.13 315.2 T -(, the ar) 709.67 315.2 T -(gument) 742.44 315.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "11" 11 -%%Page: "12" 12 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -2 12 Q -0 X -0 0 0 1 0 0 0 K -(<names>) 127.56 777.2 T -1 F -( lists the \336les in the) 177.96 777.2 T -(directory) 127.56 763.2 T -(. The) 170.1 763.2 T -2 F -(<visit>) 197.76 763.2 T -1 F -( func-) 248.16 763.2 T -(tion may modify) 127.56 749.2 T -2 F -(<names>) 210.56 749.2 T -1 F -( to) 260.96 749.2 T -(in\337uence the set of directories) 127.56 735.2 T -(visited below) 127.56 721.2 T -2 F -(<dirname>) 194.89 721.2 T -1 F -(,) 259.69 721.2 T -(e.g., to avoid visiting certain) 127.56 707.2 T -(parts of the tree.) 127.56 693.2 T -83.36 664.01 56.69 664.01 2 L -V -1.14 H -0 Z -N -0 F -(math) 56.69 665.2 T -1 F -(V) 56.69 644.2 T -(ariables:) 64.03 644.2 T -2 F -(pi e) 107.68 644.2 T -1 F --0.5 (Functions \050see ordinary C man pages for info\051:) 56.69 630.2 P -2 F -(acos\050x\051) 56.69 616.2 T -(asin\050x\051) 147.4 616.2 T -(atan\050x\051) 205 616.2 T -(atan2\050x,y\051) 56.69 602.2 T -(ceil\050x\051) 147.4 602.2 T -(cos\050x\051) 205 602.2 T -(cosh\050x\051) 56.69 588.2 T -(exp\050x\051) 147.4 588.2 T -(fabs\050x\051) 204.09 588.2 T -(f) 56.69 574.2 T -(loor\050x\051) 63.89 574.2 T -(fmod\050x,y\051) 147.4 574.2 T -(ldexp\050x,y\051) 56.69 560.2 T -(log\050x\051) 147.4 560.2 T -(log10\050x\051) 204.09 560.2 T -(pow\050x,y\051) 56.69 546.2 T -(sin\050x\051) 147.4 546.2 T -(sinh\050x\051) 204.09 546.2 T -(sqrt\050x\051) 56.69 532.2 T -(tan\050x\051) 147.4 532.2 T -(tanh\050x\051.) 204.09 532.2 T -(frexp\050x\051 -) 56.69 518.2 T -3 F -(Differ) 135.89 518.2 T -(ent than C:) 164.12 518.2 T -2 F -(\050f) 56.69 504.2 T -(loat,int\051=frexp\050f) 71.09 504.2 T -(loat\051) 193.49 504.2 T -(modf\050x\051 -) 56.69 490.2 T -3 F -(Differ) 128.69 490.2 T -(ent than C:) 156.92 490.2 T -2 F -(\050f) 56.69 476.2 T -(loat,f) 71.09 476.2 T -(loat\051=modf\050f) 114.29 476.2 T -(loat\051) 200.69 476.2 T -86.69 447.01 56.69 447.01 2 L -V -N -0 F -(string) 56.69 448.2 T -1 F -(Some V) 56.69 427.2 T -(ariables:) 94.36 427.2 T -2 F -(digits) 56.69 413.2 T -1 F -(The string \3240123456789\325) 127.56 413.2 T -2 F -(uppercase) 56.69 399.2 T -(lowercase) 56.69 385.2 T -(whitespace) 56.69 371.2 T -1 F -(Strings containing the appropri-) 127.56 357.2 T -(ate characters) 127.56 343.2 T -2 F -(index_error) 56.69 329.2 T -1 F --0.51 (Exception raised by) 127.56 315.2 P -2 F --1.23 (index) 224.33 315.2 P -1 F --0.51 (\050\051 if) 260.33 315.2 P -2 F -(substr) 379.84 777.2 T -1 F -( not found.) 423.04 777.2 T -(Some Functions:) 308.98 763.2 T -2 F -(index\050s, sub, i=0\051) 308.98 749.2 T -1 F --0.2 (Return the lowest index in) 379.84 735.2 P -2 F --0.48 (<s>) 508.51 735.2 P -1 F --0.31 (not smaller than) 379.84 721.2 P -2 F --0.74 (<i>) 459.25 721.2 P -1 F --0.31 ( where the) 480.85 721.2 P -(substring) 379.84 707.2 T -2 F -(<sub>) 426.85 707.2 T -1 F -( is found.) 462.85 707.2 T -2 F -(lower\050s\051) 308.98 693.2 T -1 F -(Return a string that is) 379.84 693.2 T -2 F -(<s>) 486.17 693.2 T -1 F -( in) 507.77 693.2 T -(lowercase) 379.84 679.2 T -2 F -(splitf) 308.98 665.2 T -(ields\050s, sep\051) 352.18 665.2 T -1 F -(Returns a list containing the) 379.84 651.2 T -(\336elds of the string) 379.84 637.2 T -2 F -(<s>) 469.84 637.2 T -1 F -(, using) 491.44 637.2 T -(the string) 379.84 623.2 T -2 F -(<sep>) 427.84 623.2 T -1 F -( as a separa-) 463.84 623.2 T -(tor) 379.84 609.2 T -(.) 392.51 609.2 T -2 F -(joinf) 308.98 595.2 T -(ields\050words, sep\051) 344.98 595.2 T -1 F -(Concatenate a list or tuple of) 379.84 581.2 T -(words with intervening separa-) 379.84 567.2 T -(tors.) 379.84 553.2 T -2 F -(strip\050s\051) 308.98 539.2 T -1 F -(Return a string that is) 379.84 539.2 T -2 F -(<s>) 486.17 539.2 T -1 F -(without leading and trailing) 379.84 525.2 T -(whitespace.) 379.84 511.2 T -2 F -(upper\050s\051) 308.98 497.2 T -1 F -(Return a string that is) 379.84 497.2 T -2 F -(<s>) 486.17 497.2 T -1 F -( in) 507.77 497.2 T -(uppercase) 379.84 483.2 T -314.3 454.01 308.98 454.01 2 L -V -N -0 F -(r) 308.98 455.2 T -336.74 454.01 314.09 454.01 2 L -V -N -(egex) 314.09 455.2 T -3 F -(Patterns ar) 308.98 434.2 T -(e speci\336ed as strings. Default syn-) 362.87 434.2 T -(tax is emacs-style.) 308.98 420.2 T -1 F -(V) 308.98 406.2 T -(ariables:) 316.31 406.2 T -2 F -(error) 308.98 392.2 T -1 F -(Exception when pattern string) 379.84 392.2 T -(isn\325) 379.84 378.2 T -(t valid regexp.) 397.63 378.2 T -(Functions:) 308.98 364.2 T -2 F -(match\050pattern, string\051) 308.98 350.2 T -1 F -(Return how many characters at) 379.84 336.2 T -(the beginning of) 379.84 322.2 T -2 F -(<string>) 461.5 322.2 T -1 F --0.78 (match regexp) 379.84 308.2 P -2 F --1.87 (<pattern>) 446.27 308.2 P -1 F --0.78 (.) 511.07 308.2 P -2 F --1.87 (-1) 516.29 308.2 P -1 F -(if none.) 632.13 777.2 T -2 F -(search\050pattern, string\051) 561.26 763.2 T -1 F -(Return the \336rst position in) 632.13 749.2 T -2 F -(<string>) 632.13 735.2 T -1 F -( that matches) 689.73 735.2 T -(regexp) 632.13 721.2 T -2 F -(<pattern>) 667.78 721.2 T -1 F -(. Return) 732.58 721.2 T -2 F -(-) 632.13 707.2 T -(1) 639.33 707.2 T -1 F -( if none.) 646.53 707.2 T -2 F -(compile\050pattern [,translate]\051) 561.26 693.2 T -1 F -( Create regexp object that has) 632.13 679.2 T -(methods match\050\051 and search\050\051) 632.13 665.2 T -(working as above. Also) 632.13 651.2 T -2 F -(group\050i1, [,i2]*\051) 632.13 637.2 T -3 F -(E.g.) 561.26 623.2 T -2 F -(p= \134) 561.26 609.2 T -(compile\050\324id\134\050[a-) 561.26 595.2 T -(z]\134\051\134\050[a-) 676.46 595.2 T -(z]\134\051\325\051) 741.26 595.2 T -(p.match\050\324idab\325\051 ==> 4) 561.26 581.2 T -(p.group\0501, 2\051 ==> \050\324a\325,\324b\325\051) 561.26 567.2 T -(set_sytax\050f) 561.26 553.2 T -(lag\051) 640.46 553.2 T -1 F -(Set syntax \337ags for future calls) 632.13 539.2 T -(to) 632.13 525.2 T -2 F -(match) 644.46 525.2 T -1 F -(\050\051,) 680.46 525.2 T -2 F -(search) 694.45 525.2 T -1 F -(\050\051 and) 737.65 525.2 T -2 F -(compile) 632.13 511.2 T -1 F -(\050\051. Returns current) 682.53 511.2 T -(value. Flags in module) 632.13 497.2 T -2 F -(regex_syntax) 632.13 483.2 T -1 F -(.) 718.53 483.2 T -2 F -(symcomp\050pattern [,translate]\051) 561.26 469.2 T -1 F --0.65 (Like compile but with symbolic) 632.13 455.2 P -(group names. Names in angle) 632.13 441.2 T -(brackets. Access through) 632.13 427.2 T -(group method.) 632.13 413.2 T -3 F -(E.g.) 561.26 399.2 T -2 F -(p = \134) 561.26 385.2 T -(symcomp\050\324id\134\050<l1>[a-) 561.26 371.2 T -(z]\134\051\134\050<l2>[) 705.26 371.2 T -(a-z]\134\051\325\051) 561.26 357.2 T -(p.match\050\324idab\325\051 ==> 4) 561.26 343.2 T -(p.group\050\324l1\325\051 ==> \324a\325) 561.26 329.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "12" 12 -%%Page: "13" 13 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -62.02 776.01 56.69 776.01 2 L -0 X -0 0 0 1 0 0 0 K -V -1.14 H -0 Z -N -0 12 Q -(r) 56.69 777.2 T -123.8 776.01 61.81 776.01 2 L -V -N -(egex_syntax) 61.81 777.2 T -3 F -(Flags for) 56.69 756.2 T -2 F -(regex.set_syntax) 104.03 756.2 T -1 F -(\050\051.) 219.23 756.2 T -3 F -(BitOr the \337ags you want together and pass to) 56.69 742.2 T -(function.) 56.69 728.2 T -1 F -(V) 56.69 714.2 T -(ariables:) 64.03 714.2 T -2 F -(RE_NO_BK_PARENS) 56.69 700.2 T -1 F --0.27 (if set, \050 means grouping, \134\050 is lit-) 127.56 686.2 P -(eral \322\050\322) 127.56 672.2 T -(if not, vice versa) 127.56 658.2 T -2 F -(RE_NO_BK_VBAR) 56.69 644.2 T -1 F -(if set, | means or) 127.56 630.2 T -(, \134| is literal \322|\323) 205.8 630.2 T -(if not, vice versa) 127.56 616.2 T -2 F -(RE_BK_PLUS_QM) 56.69 602.2 T -1 F -(if set, + or ? are operator) 127.56 588.2 T -(, \134+, \134?) 245.47 588.2 T -(are literal) 127.56 574.2 T -(if not, vice versa) 127.56 560.2 T -2 F -(RE_TIGHT_VBAR) 56.69 546.2 T -1 F -(-- if set, | binds tighter) 155.9 546.2 T -(than ^ or $) 127.56 532.2 T -(if not, vice versa) 127.56 518.2 T -2 F -(RE_NEWLINE_OR) 56.69 504.2 T -1 F -(if set, \134n is an OR operator) 127.56 490.2 T -(if not, it is a normal char) 127.56 476.2 T -2 F -(RE_CONTEXT_INDEP_OPS) 56.69 462.2 T -1 F -(if not set, special chars always) 127.56 448.2 T -(have special meaning) 127.56 434.2 T -( if set, depends on context:) 127.56 420.2 T -2 F --0.53 (^) 56.69 406.2 P -1 F --0.22 ( - only special at the beginning, or after \050 or) 63.89 406.2 P -2 F --0.53 (|) 273.43 406.2 P -($) 56.69 392.2 T -1 F -( - only special at the end, or before) 63.89 392.2 T -2 F -(\051) 233.85 392.2 T -1 F -( or) 241.05 392.2 T -2 F -(|) 257.05 392.2 T -(*,) 56.69 378.2 T -(+,) 74.09 378.2 T -(?) 91.49 378.2 T -1 F -( - only special when not after the) 98.69 378.2 T -(beginning,) 56.69 364.2 T -2 F -(\050) 110.69 364.2 T -1 F -(, or) 117.89 364.2 T -2 F -(|) 136.89 364.2 T -(RE_SYNTAX_AWK =) 56.69 350.2 T -(\050RE_NO_BK_PARENS |) 127.56 336.2 T -(RE_NO_BK_VBAR |) 127.56 322.2 T -(RE_CONTEXT_INDEP_OPS\051) 127.56 308.2 T -(RE_SYNTAX_EGREP =) 308.98 777.2 T -(\050RE_SYNTAX_AWK |) 379.84 763.2 T -(RE_NEWLINE_OR\051) 379.84 749.2 T --2.15 (RE_SYNTAX_GREP = \050RE_BK_PLUS_QM) 308.98 735.2 P -(| RE_NEWLINE_OR\051) 379.84 721.2 T -(RE_SYNTAX_EMACS = 0) 308.98 707.2 T -314.3 678.01 308.98 678.01 2 L -V -N -0 F -(r) 308.98 679.2 T -352.43 678.01 314.09 678.01 2 L -V -N -(eg_sub) 314.09 679.2 T -1 F -(Functions:) 308.98 658.2 T -2 F -(sub\050pattern, rep, str\051) 308.98 644.2 T -1 F -(Replace 1st occur of) 379.84 630.2 T -2 F -(<pat-) 481.15 630.2 T -(tern>) 379.84 616.2 T -1 F -( in) 415.84 616.2 T -2 F -(<str>) 431.18 616.2 T -1 F -( by) 467.18 616.2 T -2 F -(<rep>) 485.18 616.2 T -1 F -(and return this.) 379.84 602.2 T -2 F -(gsub\050pattern, rep, str\051) 308.98 588.2 T -1 F -(Replace) 379.84 574.2 T -433.49 572.89 421.49 572.89 2 L -V -0.59 H -N -(all) 421.49 574.2 T -( occurances of) 433.49 574.2 T -2 F -(<pattern>) 379.84 560.2 T -1 F -( in) 444.64 560.2 T -2 F -(<str>) 459.98 560.2 T -1 F -( by) 495.98 560.2 T -2 F -(<rep>) 379.84 546.2 T -1 F -( and return this.) 415.84 546.2 T -2 F -(split\050str, pattern\051) 308.98 532.2 T -1 F -(Split) 379.84 518.2 T -2 F -(<str>) 405.52 518.2 T -1 F -( into \336elds seper-) 441.52 518.2 T -(ated by delimiters matching) 379.84 504.2 T -2 F -(<pattern>) 379.84 490.2 T -1 F -( and return as list) 444.64 490.2 T -(of strings.) 379.84 476.2 T -0 14 Q -(Other Modules In Base Distribution) 308.98 446.86 T -352.99 416.01 308.98 416.01 2 L -V -1.14 H -N -0 12 Q -(Built-ins) 308.98 417.2 T -1 F -( sys) 308.98 396.2 T -(Interpreter state vars and func-) 379.84 396.2 T -(tions) 379.84 382.2 T -2 F -(__built-in__) 308.98 368.2 T -1 F -(Access to all built-in python) 379.84 354.2 T -(identi\336ers) 379.84 340.2 T -2 F -(__main__) 308.98 326.2 T -1 F -(Scope of the interpreters main) 379.84 326.2 T -(program, script or stdin) 379.84 312.2 T -2 F -(array) 561.26 777.2 T -1 F -(Obj ef) 632.13 777.2 T -(\336ciently representing) 662.23 777.2 T -(arrays of basic values) 632.13 763.2 T -2 F -(math) 561.26 749.2 T -1 F -(Math functions of C standard) 632.13 749.2 T -2 F -(time) 561.26 735.2 T -1 F -(T) 632.13 735.2 T -(ime-related functions) 639.04 735.2 T -2 F -(regex) 561.26 721.2 T -1 F -(Regular expression matching) 632.13 721.2 T -(operations) 632.13 707.2 T -2 F -(marshal) 561.26 693.2 T -1 F -(Read and write some python) 632.13 693.2 T -(values in binary format) 632.13 679.2 T -2 F -(struct) 561.26 665.2 T -1 F -(Convert between python val-) 632.13 665.2 T -(ues and C structs) 632.13 651.2 T -609.27 622.01 561.26 622.01 2 L -V -N -0 F -(Standard) 561.26 623.2 T -2 F -(getopt) 561.26 602.2 T -1 F --0.06 (Parse cmd line ar) 632.13 602.2 P --0.06 (gs in sys.ar) 714.71 602.2 P --0.06 (gv) 768.04 602.2 P --0.06 (.) 779.26 602.2 P -(A la UNIX \324getopt\325.) 632.13 588.2 T -2 F -(os) 561.26 574.2 T -1 F --0.7 (A more portable interface to OS) 632.13 574.2 P -(dependent functionality) 632.13 560.2 T -2 F -(rand) 561.26 546.2 T -1 F -(Pseudo-random generator) 632.13 546.2 T -(, like) 755.28 546.2 T -(C rand\050\051) 632.13 532.2 T -2 F -(regsub) 561.26 518.2 T -1 F -(Functions useful for working) 632.13 518.2 T -(with regular expressions) 632.13 504.2 T -2 F -(string) 561.26 490.2 T -1 F -(Useful string and characters) 632.13 490.2 T -(functions and exceptions) 632.13 476.2 T -2 F -(whrandom) 561.26 462.2 T -1 F -(W) 632.13 462.2 T -(ichmann-Hill pseudo-ran-) 642.97 462.2 T -(dom number generator) 632.13 448.2 T -585.93 419.01 561.26 419.01 2 L -V -N -0 F -(Unix) 561.26 420.2 T -2 F -(dbm) 561.26 399.2 T -1 F -(Interface to Unix ndbm data-) 632.13 399.2 T -(base library) 632.13 385.2 T -2 F -(grp) 561.26 371.2 T -1 F -(Interface to Unix group data-) 632.13 371.2 T -(base) 632.13 357.2 T -2 F -(posix) 561.26 343.2 T -1 F -(OS functionality standardized) 632.13 343.2 T -(by C and) 632.13 329.2 T -2 F -(POSIX) 678.46 329.2 T -1 F -( standards) 714.46 329.2 T -2 F -(posixpath) 561.26 315.2 T -(POSIX) 632.13 315.2 T -1 F -( pathname functions) 668.13 315.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "13" 13 -%%Page: "14" 14 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -2 12 Q -0 X -0 0 0 1 0 0 0 K -(pwd) 56.69 777.2 T -1 F -(Access to the Unix password) 127.56 777.2 T -(database) 127.56 763.2 T -2 F -(select) 56.69 749.2 T -1 F --0.52 (Access to Unix select multiplex) 127.56 749.2 P -(\336le synchronization) 127.56 735.2 T -2 F -(socket) 56.69 721.2 T -1 F --0.25 (Access to BSD socket interface) 127.56 721.2 P -2 F -(thread) 56.69 707.2 T -1 F -(Low-level primitives for work-) 127.56 707.2 T -(ing with process threads) 127.56 693.2 T -116.69 664.01 56.69 664.01 2 L -V -1.14 H -0 Z -N -0 F -(Multimedia) 56.69 665.2 T -2 F -(audioop) 56.69 644.2 T -1 F -(Useful operations on sound) 127.56 644.2 T -(fragments) 127.56 630.2 T -2 F -(imageop) 56.69 616.2 T -1 F -(Useful operations on images) 127.56 616.2 T -2 F -(jpeg) 56.69 602.2 T -1 F -(Access to jpeg image compres-) 127.56 602.2 T -(sor and decompressor) 127.56 588.2 T -2 F -(rgbimg) 56.69 574.2 T -1 F -(Access SGI imglib image \336les) 127.56 574.2 T -191.03 545.01 56.69 545.01 2 L -V -N -0 F -(Cryptographic Extensions) 56.69 546.2 T -2 F -(md5) 56.69 525.2 T -1 F -(Interface to RSA) 127.56 525.2 T -(\325) 207.54 525.2 T -(s MD5 mes-) 210.88 525.2 T -(sage digest algorithm) 127.56 511.2 T -2 F -(mpz) 56.69 497.2 T -1 F -(Interface to int part of GNU) 127.56 497.2 T -(multiple precision library) 127.56 483.2 T -2 F -(rotor) 56.69 469.2 T -1 F -(Implementation of a rotor) 127.56 469.2 T -(-) 250.97 469.2 T -(based encryption algorithm) 127.56 455.2 T -173.72 426.01 56.69 426.01 2 L -V -N -0 F -(Stdwin \321 Standard W) 56.69 427.2 T -244.51 426.01 173.5 426.01 2 L -V -N -(indow System) 173.5 427.2 T -1 F -(stdwin) 56.69 406.2 T --0.26 (Standard W) 127.56 406.2 P --0.26 (indow System inter-) 183.81 406.2 P -(face) 127.56 392.2 T -(stdwinevents) 56.69 378.2 T -(Stdwin event, command, and) 127.56 378.2 T -(selection constants) 127.56 364.2 T -(rect) 56.69 350.2 T -(Rectangle manipulation opera-) 127.56 350.2 T -(tions) 127.56 336.2 T -398.3 776.01 308.98 776.01 2 L -V -N -0 F -(SGI IRIX \0504 & 5\051) 308.98 777.2 T -1 F -(al) 308.98 756.2 T -(SGI audio facilities) 379.84 756.2 T -(AL) 308.98 742.2 T -(al constants) 379.84 742.2 T -(\337) 308.98 728.2 T -(Interface to FORMS library) 379.84 728.2 T -(FL) 308.98 714.2 T -(\337 constants) 379.84 714.2 T -(\337p) 308.98 700.2 T -(Functions for form designer) 379.84 700.2 T -(fm) 308.98 686.2 T -(Access to font manager library) 379.84 686.2 T -(gl) 308.98 672.2 T -(Access to graphics library) 379.84 672.2 T -(GL) 308.98 658.2 T -(Constants for gl) 379.84 658.2 T -(DEVICE) 308.98 644.2 T -(More constants for gl) 379.84 644.2 T -(img\336le) 308.98 630.2 T -(Imglib image \336le interface) 379.84 630.2 T -348.98 601.01 308.98 601.01 2 L -V -N -0 F -(SUNOS) 308.98 602.2 T -1 F -(sunaudiodev) 308.98 581.2 T -(Access to sun audio interface) 379.84 581.2 T -0 14 Q -(W) 308.98 551.86 T -(orkspace exploration and idiom) 322.21 551.86 T -(hints) 308.98 534.86 T -1 12 Q -(dir\050<module>\051) 308.98 515.2 T --0.57 (list functions, variables in) 408.19 515.2 P -(<module>) 379.84 501.2 T -(dir\050\051) 308.98 487.2 T -(get object keys, defaults) 408.19 487.2 T -(to local name space) 379.84 473.2 T -(X.__methods__) 308.98 459.2 T --0.62 (list of methods supported by X) 385.31 459.2 P -(\050if any\051) 379.84 445.2 T -(X.__members__) 308.98 431.2 T -(List of X\325) 388.63 431.2 T -(s data attributes) 435.3 431.2 T -(if __name__ == \324__main__\325: main\050\051) 308.98 417.2 T -(invoke main if running as script) 379.84 403.2 T -(map\050None, lst1, lst2, ...\051) 308.98 389.2 T -(mer) 379.84 375.2 T -(ge lists) 398.29 375.2 T -(b = a[:]) 308.98 361.2 T -(create copy of seq structure) 379.84 361.2 T -(_) 308.98 347.2 T -(in interactive mode, is last) 379.84 347.2 T -(value printed) 379.84 333.2 T -(vars\050\051) 308.98 319.2 T -(DO NOT type at interactive) 379.84 319.2 T -(prompt! Y) 632.13 777.2 T -(ou get in\336nite loop) 681.25 777.2 T -(\050C-c will exit\051.) 632.13 763.2 T -0 14 Q -(Python Mode for Emacs) 561.26 733.86 T -1 12 Q -(T) 561.26 714.2 T -(ype C-c ? when in python-mode for exten-) 567.75 714.2 T -(sive help.) 561.26 700.2 T -607.93 671.01 561.26 671.01 2 L -V -N -0 F -(INDENT) 561.26 672.2 T -615.7 671.01 607.04 671.01 2 L -V -N -(A) 607.04 672.2 T -645.49 671.01 614.82 671.01 2 L -V -N -(TION) 614.82 672.2 T -1 F -(Primarily for entering new code:) 561.26 651.2 T -(T) 561.26 637.2 T -(AB) 567.63 637.2 T -(indent line appropriately) 632.13 637.2 T -(LFD) 561.26 623.2 T -(insert newline, then indent) 632.13 623.2 T -(DEL) 561.26 609.2 T -(reduce indentation, or delete) 632.13 609.2 T -(single character) 632.13 595.2 T -(Primarily for reindenting existing code:) 561.26 581.2 T -(C-c :) 561.26 567.2 T -(guess py-indent-of) 632.13 567.2 T -(fset from) 721.56 567.2 T -(\336le content; change locally) 632.13 553.2 T -(C-u C-c :) 561.26 539.2 T -(ditto, but change globally) 632.13 539.2 T -(C-c T) 561.26 525.2 T -(AB) 587.96 525.2 T -(reindent region to match its) 632.13 525.2 T -(context) 632.13 511.2 T -(C-c <) 561.26 497.2 T -(shift region left by py-indent-) 632.13 497.2 T -(of) 632.13 483.2 T -(fset) 641.91 483.2 T -(C-c >) 561.26 469.2 T -(shift region right by py-indent-) 632.13 469.2 T -(of) 632.13 455.2 T -(fset) 641.91 455.2 T -703.9 412.01 561.26 412.01 2 L -V -N -0 F -(MARKING & MANIPULA) 561.26 413.2 T -736.69 412.01 703.02 412.01 2 L -V -N -(TING) 703.02 413.2 T -673.94 395.01 561.26 395.01 2 L -V -N -(REGIONS OF CODE) 561.26 396.2 T -1 F -(C-c C-b) 561.26 375.2 T -(mark block of lines) 632.13 375.2 T -(M-C-h) 561.26 361.2 T -(mark smallest enclosing def) 632.13 361.2 T -(C-u M-C-h) 561.26 347.2 T -(mark smallest enclosing class) 632.13 347.2 T -(C-c #) 561.26 333.2 T -(comment out region of code) 632.13 333.2 T -(C-u C-c #) 561.26 319.2 T -(uncomment region of code) 632.13 319.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "14" 14 -%%Page: "15" 15 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -149.69 776.01 56.69 776.01 2 L -0 X -0 0 0 1 0 0 0 K -V -1.14 H -0 Z -N -0 12 Q -(MOVING POINT) 56.69 777.2 T -1 F -(C-c C-p) 56.69 756.2 T -(move to statement preceding) 127.56 756.2 T -(point) 127.56 742.2 T -(C-c C-n) 56.69 728.2 T -(move to statement following) 127.56 728.2 T -(point) 127.56 714.2 T -(C-c C-u) 56.69 700.2 T -(move up to start of current) 127.56 700.2 T -(block) 127.56 686.2 T -(M-C-a) 56.69 672.2 T -(move to start of def) 127.56 672.2 T -(C-u M-C-a) 56.69 658.2 T -(move to start of class) 127.56 658.2 T -(M-C-e) 56.69 644.2 T -(move to end of def) 127.56 644.2 T -(C-u M-C-e) 56.69 630.2 T -(move to end of class) 127.56 630.2 T -221.37 601.01 56.69 601.01 2 L -V -N -0 F -(EXECUTING PYTHON CODE) 56.69 602.2 T -1 F -(C-c C-c) 56.69 581.2 T -(sends the entire buf) 127.56 581.2 T -(fer to the) 220.99 581.2 T -(Python interpreter) 127.56 567.2 T -(C-c |) 56.69 553.2 T -(sends the current region) 127.56 553.2 T -(C-c !) 56.69 539.2 T -(starts a Python interpreter win-) 127.56 539.2 T -(dow; this will be used by) 127.56 525.2 T --0.23 (subse-) 250.9 525.2 S -(quent C-c C-c or C-c |) 127.56 511.2 T -(commands) 127.56 497.2 T -0 14 Q -(The Python Debugger) 56.69 467.86 T -106.68 437.01 56.69 437.01 2 L -V -N -0 12 Q -(Accessing) 56.69 438.2 T -2 F -(import pdb) 56.69 417.2 T -3 F -(\050it\325) 56.69 403.2 T -(s a module written in Python\051) 69.81 403.2 T -1 F -(Functions) 56.69 389.2 T -2 F -(run\050string\051) 56.69 375.2 T -1 F -(interpret string in the debugger) 127.56 361.2 T -2 F --2.15 (runctx\050string, globals, locals\051) 56.69 347.2 P -1 F -( interpret string using globals) 127.56 333.2 T -(and locals for namespace) 127.56 319.2 T -2 F -(runcall\050fun, arg1, arg2, ...\051) 308.98 777.2 T -1 F -(run function object) 379.84 763.2 T -2 F -(<fun>) 474.16 763.2 T -1 F -(with ar) 379.84 749.2 T -(gs given.) 413.29 749.2 T -2 F -(pm\050\051) 308.98 735.2 T -1 F -(run postmortem on last excep-) 379.84 735.2 T -(tion \050like debugging a core \336le\051) 379.84 721.2 T -2 F -(post_mortem\050t\051) 308.98 707.2 T -1 F -(run postmortem on traceback) 379.84 693.2 T -(object) 379.84 679.2 T -2 F -(<t>) 412.17 679.2 T -1 F -(De\336nes class \322) 308.98 665.2 T -2 F -(Pdb) 380.29 665.2 T -1 F -(\323) 401.89 665.2 T -(use) 379.84 651.2 T -2 F -(Pdb) 398.84 651.2 T -1 F -( to create reusable) 420.44 651.2 T -(debugger objects. Object pre-) 379.84 637.2 T -(serves state \050i.e. break points\051) 379.84 623.2 T -(between calls.) 379.84 609.2 T -2 F -(Pdb) 308.98 595.2 T -1 F -( de\336nes methods) 330.58 595.2 T -2 F -(run\050string\051) 308.98 581.2 T -1 F -( interpret string in the debugger) 379.84 567.2 T -2 F --2.15 (runctx\050string, globals, locals\051) 308.98 553.2 P -1 F -(interpret string using globals) 379.84 539.2 T -(and locals for namespace) 379.84 525.2 T -2 F -(runcall\050fun, arg1, arg2, ...\051) 308.98 511.2 T -1 F -(run function object with ar) 379.84 497.2 T -(gs) 507.61 497.2 T -(runs until a breakpoint hit,) 379.84 483.2 T --0.59 (exception, or end of program. If) 379.84 469.2 P -(an exception occurs, variable) 379.84 455.2 T -2 F -(__exception__) 379.84 441.2 T -1 F -( holds) 473.44 441.2 T -(\050exception,value\051.) 379.84 427.2 T -367.64 398.01 308.98 398.01 2 L -V -N -0 F -(Commands) 308.98 399.2 T -2 F -(h, help) 308.98 378.2 T -1 F -(brief reminder of commands) 379.84 378.2 T -2 F -(b, break [<arg>]) 308.98 364.2 T -1 F --0.65 (if) 379.84 350.2 P -2 F --1.56 (<arg>) 389.52 350.2 P -1 F --0.65 ( numeric, break at line) 425.52 350.2 P -2 F -(<arg>) 379.84 336.2 T -1 F -( in current \336le) 415.84 336.2 T -(if) 379.84 322.2 T -2 F -(<arg>) 390.17 322.2 T -1 F -( is function object,) 426.17 322.2 T -(break on entry to fcn) 379.84 308.2 T -2 F -(<arg>) 482.81 308.2 T -1 F -(if no ar) 632.13 777.2 T -(g, list breakpoints) 666.57 777.2 T -2 F -(cl, clear [<arg>]) 561.26 763.2 T -1 F -(if) 632.13 749.2 T -2 F -(<arg>) 642.46 749.2 T -1 F -( numeric, clear break-) 678.46 749.2 T -(point at) 632.13 735.2 T -2 F -(<arg>) 671.46 735.2 T -1 F -( in current \336le) 707.46 735.2 T -(if no ar) 632.13 721.2 T -(g, clear all breakpoints) 666.57 721.2 T -(after con\336rmation) 632.13 707.2 T -2 F -(w, where) 561.26 693.2 T -1 F -(print current call stack) 632.13 693.2 T -2 F -(u, up) 561.26 679.2 T -1 F -(move up one stack frame \050to) 632.13 679.2 T -(top-level caller\051) 632.13 665.2 T -2 F -(d, down) 561.26 651.2 T -1 F -(move down one stack frame) 632.13 651.2 T -2 F -(s, step) 561.26 637.2 T -1 F -(advance one line in the pro-) 632.13 637.2 T -(gram, stepping into calls) 632.13 623.2 T -2 F -(n, next) 561.26 609.2 T -1 F -(advance one line, stepping) 632.13 609.2 T -(over calls) 632.13 595.2 T -2 F -(r, return) 561.26 581.2 T -1 F --1.01 (continue execution until current) 633.26 581.2 P -(function returns \050the return) 632.13 567.2 T -(value is saved in variable) 632.13 553.2 T -2 F -(__return__) 632.13 539.2 T -1 F -(, which can be) 704.13 539.2 T -(printed or manipulated from) 632.13 525.2 T -(debugger\051) 632.13 511.2 T -2 F -(c, continue) 561.26 497.2 T -1 F -(continue until next breakpoint) 632.13 483.2 T -2 F -(a, args) 561.26 469.2 T -1 F -(print ar) 632.13 469.2 T -(gs to current function) 666.9 469.2 T -2 F -(rv, retval) 561.26 455.2 T -1 F -(prints return value from last) 632.13 441.2 T -(function that returned) 632.13 427.2 T -2 F -(p, print <arg>) 561.26 413.2 T -1 F -(prints value of) 632.13 399.2 T -2 F -(<arg>) 704.45 399.2 T -1 F -( in cur-) 740.45 399.2 T -(rent stack frame) 632.13 385.2 T -2 F -(l, list [<f) 561.26 371.2 T -(irst> [, <last>]]) 640.46 371.2 T -1 F --0.04 (List source code for the current) 632.13 357.2 P -(\336le. W) 632.13 343.2 T -(ithout ar) 664.31 343.2 T -(guments, list 1) 704.43 343.2 T -(1) 774.33 343.2 T -(lines around the current line or) 632.13 329.2 T -(continue the previous listing.) 632.13 315.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "15" 15 -%%Page: "16" 16 -595.28 841.89 1 FMBEGINPAGE -[0 0 0 1 0 0 0] -[ 0 0 0 0 1 1 1] -[ 0 1 1 0 1 0 0] -[ 1 0 1 0 0 1 0] -[ 1 1 0 0 0 0 1] -[ 1 0 0 0 0 1 1] -[ 0 1 0 0 1 0 1] -[ 0 0 1 0 1 1 0] - 8 FrameSetSepColors -FrameNoSep -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -0 0 0 1 0 0 0 K -1 12 Q -0 X -0 0 0 1 0 0 0 K --0.46 (W) 127.56 777.2 P --0.46 (ith one ar) 138.41 777.2 P --0.46 (gument, list 1) 182.59 777.2 P --0.46 (1 lines) 246.89 777.2 P -(starting at that line. W) 127.56 763.2 T -(ith two) 234.07 763.2 T --0.14 (ar) 127.56 749.2 P --0.14 (guments, list the given range;) 136.67 749.2 P -(if the second ar) 127.56 735.2 T -(gument is less) 200.99 735.2 T -(than the \336rst, it is a count.) 127.56 721.2 T -2 F -(whatis <arg>) 56.69 707.2 T -1 F -(prints type of) 127.56 693.2 T -2 F -(<arg>) 194.55 693.2 T -(!) 56.69 679.2 T -1 F --0.56 (executes rest of line as a Python) 127.56 679.2 P -(statement in the current stack) 127.56 665.2 T -(frame) 127.56 651.2 T -2 F -(q quit) 56.69 637.2 T -1 F --0.73 (immediately stop execution and) 127.56 637.2 P -(leave debugger) 127.56 623.2 T -2 F -(<return>) 56.69 609.2 T -1 F -(executes last command again) 127.56 609.2 T -(Any input debugger doesn\325) 56.69 595.2 T -(t recognize as a) 187.46 595.2 T --0.34 (command is assumed to be a Python statement) 56.69 581.2 P -(to execute in the current stack frame, same as) 56.69 567.2 T -(the exclamation mark \050\322) 56.69 553.2 T -2 F -(!) 173 553.2 T -1 F -(\323\051 command does.) 180.2 553.2 T -102.03 524.01 56.69 524.01 2 L -V -1.14 H -0 Z -N -0 F -(Example) 56.69 525.2 T -2 F -(\0501394\051 python) 56.69 504.2 T -(Python 1.0.3 \050Sep 26 1994\051) 56.69 490.2 T -(>>> import rm) 56.69 476.2 T -(>>> rm.run\050\051) 56.69 462.2 T -(Traceback \050innermost last\051:) 56.69 448.2 T -(File \322<stdin>\323, line 1) 70.87 434.2 T -(File \322./rm.py\323, line 7) 70.87 420.2 T -(x = div\0503\051) 85.04 406.2 T -(File \322./rm.py\323, line 2) 70.87 392.2 T -(return a / r) 85.04 378.2 T -(ZeroDivisionError: integer) 56.69 364.2 T -(division or modulo) 56.69 350.2 T -(>>> import pdb) 56.69 336.2 T -(>>> pdb.pm\050\051) 56.69 322.2 T -(> ./rm.py\0502\051div: return a / r) 56.69 308.2 T -(\050Pdb\051 list) 308.98 777.2 T -(1 def div\050a\051:) 323.15 763.2 T -(2 -> return a / r) 323.15 749.2 T -(3) 323.15 735.2 T -(4 def run\050\051:) 323.15 721.2 T -(5 global r) 323.15 707.2 T -(6 r = 0) 323.15 693.2 T -(7 x = div\0503\051) 323.15 679.2 T -(8 print x) 323.15 665.2 T -([EOF]) 308.98 651.2 T -(\050Pdb\051 print r) 308.98 637.2 T -(0) 308.98 623.2 T -(\050Pdb\051 q) 308.98 609.2 T -(>>> pdb.runcall\050rm.run\051 etc.) 308.98 595.2 T -344.99 566.01 308.98 566.01 2 L -V -N -0 F -(Quirks) 308.98 567.2 T -1 F -(Breakpoints are stored as \336lename, line) 308.98 546.2 T -(number tuples. If a module is reloaded after) 308.98 532.2 T -(editing, any remembered breakpoints are) 308.98 518.2 T -(likely to be wrong.) 308.98 504.2 T -(Always single-steps through top-most stack) 308.98 490.2 T -(frame. That is, \322c\323 acts like \322n\323.) 308.98 476.2 T -0 0 0 1 0 0 0 K -FMENDPAGE -%%EndPage: "16" 16 -%%Trailer -%%BoundingBox: 0 0 595.28 841.89 -%%PageOrder: Ascend -%%Pages: 16 -%%DocumentFonts: Times-Bold -%%+ Times-Roman -%%+ Courier -%%+ Times-Italic -%%+ ZapfDingbats -%%EOF diff --git a/Misc/README b/Misc/README deleted file mode 100644 index 57253a7f44..0000000000 --- a/Misc/README +++ /dev/null @@ -1,33 +0,0 @@ -Python Misc subdirectory -======================== - -This directory contains files that wouldn't fit in elsewhere, in -particular the UNIX manual page, an Emacs mode for Python source code, -and a list of Frequently Asked Questions (and their answers). - -Files found here ----------------- - -ACKS Acknowledgements -AIX-NOTES Notes for building Python on AIX -BLURB A quick description of Python for newcomers -BLURB.LUTZ A testimonial from a converted Tcl/Perl hacker :-) -COPYRIGHT The Python copyright notice -FAQ Frequently Asked Questions about Python (and answers) -Fixcprt.py Fix the copyright message (a yearly chore :-) -HISTORY News from previous releases -- oldest last -HPUX-NOTES Notes about dynamic loading under HP-UX -HYPE More hype about Python -Makefile Used for administrative chores like cleaning up -NEWS News for this release -README The file you're reading now -RFD Request For Discussion about a Python newsgroup -cheatsheet Quick summary of Python by Ken Manheimer -dlMakefile Generic Makefile for dynamically loadable modules by Ken M. -fixfuncptrs.sh Shell script to fix function pointer initializers -indent.pro GNU indent profile approximating my C style (by Steen Lumholt) -python-mode.el Emacs mode for editing Python programs (thanks, Tim!) -pyimenu.el Support for Emacs with python-mode.el (by Perry Stoll) -python.man UNIX man page for the python interpreter -renumber.py Script to renumber the sections in the FAQ -setuid-prog.c C helper program for set-uid Python scripts diff --git a/Misc/RFD b/Misc/RFD deleted file mode 100644 index fd278c4fa5..0000000000 --- a/Misc/RFD +++ /dev/null @@ -1,114 +0,0 @@ -To: python-list -Subject: comp.lang.python RFD again -From: Guido.van.Rossum@cwi.nl - -I've followed the recent discussion and trimmed the blurb RFD down a bit -(and added the word "object-oriented" to the blurb). - -I don't think it's too early to *try* to create the newsgroup -- -whether we will succeed may depend on how many Python supporters there -are outside the mailing list. - -I'm personally not worried about moderation, and anyway I haven't -heard from any volunteers for moderation (and I won't volunteer -myself) so I suggest that we'll continue to ask for one unmoderated -newsgroup. - -My next action will be to post an updated FAQ (which will hint at the -upcoming RFD) to comp.lang.misc; then finalize the 1.0.0 release and -put it on the ftp site. I'll also try to get it into -comp.sources.unix or .misc. And all this before the end of January! - ---Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl> -URL: <http://www.cwi.nl/cwi/people/Guido.van.Rossum.html> - -====================================================================== - -These are the steps required (in case you don't know about the -newsgroup creation process): - -First, we need to draw up an RFD (Request For Discussion). This is a -document that tells what the purpose of the group is, and gives a case -for its creation. We post this to relevant groups (comp.lang.misc, -the mailing list, news.groups, etc.) Discussion is held on -news.groups. - -Then, after a few weeks, we run the official CFV (Call For Votes). -The votes are then collected over a period of weeks. We need 100 more -yes votes than no votes, and a 2/3 majority, to get the group. - -There are some restrictions on the vote taker: [s]he cannot actively -campaign for/against the group during the vote process. So the main -benefit to Steve instead of me running the vote is that I will be free -to campaign for its creation! - -The following is our current draft for the RFD. - -====================================================================== - -Request For Discussion: comp.lang.python - - -Purpose -------- - -The newsgroup will be for discussion on the Python computer language. -Possible topics include requests for information, general programming, -development, and bug reports. The group will be unmoderated. - - -What is Python? ---------------- - -Python is a relatively new very-high-level language developed in -Amsterdam. Python is a simple, object-oriented procedural language, -with features taken from ABC, Icon, Modula-3, and C/C++. - -Its central goal is to provide the best of both worlds: the dynamic -nature of scripting languages like Perl/TCL/REXX, but also support for -general programming found in the more traditional languages like Icon, -C, Modula,... - -Python may be FTP'd from the following sites: - - ftp.cwi.nl in directory /pub/python (its "home site", also has a FAQ) - ftp.uu.net in directory /languages/python - gatekeeper.dec.com in directory /pub/plan/python/cwi - - -Rationale ---------- - -Currently there is a mailing list with over 130 subscribers. -The activity of this list is high, and to make handling the -traffic more reasonable, a newsgroup is being proposed. We -also feel that comp.lang.misc would not be a suitable forum -for this volume of discussion on a particular language. - - -Charter -------- - -Comp.lang.python is an unmoderated newsgroup which will serve -as a forum for discussing the Python computer language. The -group will serve both those who just program in Python and -those who work on developing the language. Topics that -may be discussed include: - - - announcements of new versions of the language and - applications written in Python. - - - discussion on the internals of the Python language. - - - general information about the language. - - - discussion on programming in Python. - - -Discussion ----------- - -Any objections to this RFD will be considered and, if determined -to be appropriate, will be incorporated. The discussion period -will be for a period of 21 days after which the first CFV will be -issued. diff --git a/Misc/cheatsheet b/Misc/cheatsheet deleted file mode 100644 index 204b51bc9e..0000000000 --- a/Misc/cheatsheet +++ /dev/null @@ -1,541 +0,0 @@ - A Python Bestiary - Itemizing Python Objects and Nuances - - $Revision$ $Date$ ken.manheimer@nist.gov - - Notable lexical entities - ======================== - - Keywords - - access and break class - continue def del elif - else except exec finally - for from global if - import in is lambda - not or pass print - raise return try while - - String Literal Escapes - - \newline Ignored (escape newline) - \\ Backslash (\) \e Escape (ESC) \v Vertical Tab (VT) - \' Single quote (') \f Formfeed (FF) \0XX char with - \" Double quote (") \n Linefeed (LF) octal value XX - \a Bell (BEL) \r Carriage Return (CR) \xXX char with - \b Backspace (BS) \t Horizontal Tab (TAB) hex value XX - - Illegitimate Tokens (only valid in strings): @ $ ? - - Operating environment (Unix) - - Shell environment vars: - - PYTHONPATH: dirs to be prepended to module search path; a la shell PATH - PYTHONSTARTUP: names path of file to be loaded on interactive startup - - Internal (module sys) vars ('import sys' to refer to them): - - argv - list of command and arguments passed to python script - builtin_module_names - list of names of modules compiled in to python - ( exc_* values are set only during handling of a raised exception) - exc_type - type of exception being handled - exc_value - exception's parameter ('raise's 2nd arg) - exc_traceback - exception's traceback obj - exit(N) - exit from python with status N, by raising SystemExit - exitfunc - function hook, to be called on exit if set - last_type - type of last unhandled exception - last_value - value of last unhandled exception - last_traceback - traceback of last unhandled exception - modules - list of modules already loaded - path - list of strings specifying module-load search path - ps1='>>>' - string specifying primary prompt, iff interactive - ps2='...' - string specifying secondary prompt, iff interactive - settrace - system trace function, used by debuggers, etc - setprofile - system profile function - stdin - standard input file object - stdout - standard output file object - stderr - standard error file object - tracebacklimit=1000 - maximum number of traceback levels to print - - - Objects - behaviors, special attributes, operations, statements, etc - ==================================================================== - - General object aspects - - Boolean values and operators - - False values: None, numeric zeros, empty sequences and mappings - True values: all other values - - not X: if X is false then 1, else 0 - ( 'or', 'and' evaluate second arg only if necessary to determine outcome) - X or Y: if X is false then Y, else X - X and Y: if X is false then X, else Y - - Special methods for any type (s: self) - - id(obj) unique identifier for object (currently, its address) - __init__(s, args) object instantiation - see Classes, below - __del__(s) object demise - __repr__(s) repr() and `...` conversions - __str__(s) str() and 'print' statement - __cmp__(s) implements <, ==, >, <=, <>, !=, >=, is [not] - __hash__(s) hash() and dictionary operations - - Special informative state attributes for some types: - - X.__dict__ dict used to store object's writeable attributes - X.__methods__ list of X's methods; on many built-in types. - X.__members__ lists of X's data attributes - X.__class__ class to which X belongs - X.__bases__ tuple of X base classes - - General Name Space behavior and binding - - Name space search order: local, global, builtin - - "global" name space = file = module - "local" name space = function or method - - Code Block scopes (ns = name space, cb = containing block) - - ( global ns generally is containing module, unless overriden by args) - - Code block type Local ns Notes - --------------- -------- ----- - Module same as global ns - Script same as global ns global ns is __main__ - Interactive cmd same as global ns global ns is __main__ - Class def new ns - Function body new ns - 'exec' string local ns of cb (or args) - 'eval' string local ns of caller (or args) - 'execfile' file local ns of caller (or args) - 'input' expr local ns of caller - - Binding operations and exceptions: - - ~ SyntaxError: on attempt to bind to literals or other non-bindables - ~ NameError: on attempt to evaluate unbound atom - - ( for object attribute functions, obj: object, nm: string, val: any value) - getattr(obj, nm) get value of obj.nm - hasattr(obj, nm) true if obj has nm attribute - setattr(obj, nm, val) set obj.nm to val - - assignment statement: targ1, targ2, ,,, = obj1, obj2, ,,, - deletion statement: del obj1, obj2, ... - for loop target identifiers, 'except' clauses (see Statements, below) - formal params (see Callables, below) - import statement (see Modules objects, below) - class and func defs (see Callables, below) - - Name space linkage - - global statement: global var, ... # Interpret 'var's as globals - X access statement: access ... # control inst and class vars access - - @ Built-in Exceptions - - AttributeError On attribute reference or assignment failure - EOFError Immediate end-of-file hit by input() or raw_input() - IOError I/O-related I/O operation failure - ImportError On failure of `import' to find module or name - IndexError On out-of-range sequence subscript - KeyError On reference to a non-existent mapping (dict) key - KeyboardInterrupt On user entry of the interrupt key (often `Control-C') - MemoryError On recoverable memory exhaustion - NameError On failure to find a local or global (unqualified) name - OverflowError On excessively large arithmetic operation - RuntimeError Obsolete catch-all; define a suitable error instead - SyntaxError On parser encountering a syntax error - SystemError On non-fatal interpreter error - bug - report it - SystemExit On `sys.exit()' - TypeError On passing inappropriate type to built-in op or func - ValueError On arg error not covered by TypeError or more precise - ZeroDivisionError On division or modulo operation with 0 as 2nd arg - - **** Numbers **** - - @ Integers: 'C' long, >= 32 bits precision; OverflowError if bounds exceeded - @ Long Integers: unlimited precision - '2147483648L' - @ Floating point: machine double-precision floating point - '2147483648.0' - - Numeric operations vs special methods (s = self, o = other) - - s+o = __add__(s,o) s-o = __sub__(s,o) - s*o = __mul__(s,o) s/o = __div__(s,o) - s%o = __mod__(s,o) divmod(s,o) = __divmod__(s,o) - pow(s,o) = __pow__(s,o) - s&o = __and__(s,o) - s^o = __xor__(s,o) s|o = __xor__(s,o) - s<<o = __lshift__(s,o) s>>o = __rshift__(s,o) - nonzero(s) = __nonzero__(s) coerce(s,o) = __coerce__(s,o) - -s = __neg__(s) +s = __pos__(s) - abs(s) = __abs__(s) ~s = __invert__(s) (bitwise) - int(s) = __int__(s) long(s) = __long__(s) - float(s) = __float__(s) - oct(s) = __oct__(s) hex(s) = __hex__(s) - - Numeric functions: - - range(start=0,end,step=1) create arithmetic progression list - round(x, n=0) round floating point x to n decimal places - xrange(start=0,end,step=1) create virtual arithmetic progressions tuple - - Numeric exceptions: - - ~ TypeError: raised on application of arithemetic opertion to non-number - ~ OverflowError: numeric bounds exceeded - ~ ZeroDivisionError: raised when zero second argument of div or modulo op - - **** Collections - Sequences and Mappings **** - - Collections general operations vs methods (s: self, i: index or key) - - len(s) = __len__(s) length of object, >= 0. Length 0 == false - s[i] = __getitem__(s,i) Element at index/key i, origin 0 - - Sequences - - @ String (immutable sequence): 'string contents' - - 'this is a string' - "and so is this" - ''' and this begins a 'multi-line' string with embedded quotes... - and this is the end of that string.''' - - `expr` = __repr__(expr), converts arbitrary expr to string - chr(int) string of ascii letter at ordinate in (0 <= int < 256) - ord(string) ascii ordinate of string (string must be length 1) - string % arg format operator, a la C sprintf - arg for single directive can be any (suitable) type - arg for multiple directives must be tuple or dict - dict (mapping) arg uses parenthesized directives that are keys into it - supports %, c, s, i, d, u, o, x, X, e, E, f, g, G directives - * can be width and precision; directs use of corresponding (int) args - * can not be used with dict args - flag characters -, +, blank, #, and 0 understood. - %s conversion takes any python object, converts using `str()' - ANSI directives %p and %n not supported - %s conversions do *not* take \000 as end of string - - @ Tuples (immutable sequence): (oneelem, another, etc) - - parens may be left off all but empty tuples - singletons represented by affixing a comma to an expr - empty tuple represented using empty parens - - @ Lists (mutable sequence): [oneelem, another, etc] - - assignment - must be 1-1 map of items in target and object sequences - deletion - similar rules as for assignment - - List special methods: see mutable sequence ops vs methods, below - - Sequences general ops vs methods (s: self, i,j: indices, v: val) - - All collections general methods, plus: - s[i:j] __getslice__(s,i,j), all s[k] s.t. i <= k < j - min(s) smallest item of s - max(s) largest item of s - v [not] in s 1 if v [not] equal to an item in s, else 0 - s + seq concatenation of s and seq - s * num num copies of s concatenated, also, `num * s' - - Immutable sequence ops vs methods (s: self, i,j: indices, v: val) - - All collections and sequences general methods, plus: - s[i:j] __getslice__(s,i,j), all s[k] s.t. i <= k < j - ( For s[i:j], len(self) is intrinsically added to i, j < 0) - ( Complex elems of immutable seqs may be mutable, see dictionaries, below) - - Mutable sequence ops vs methods (s: self, i,j: indices, v: val) - - All sequences' general methods, plus: - ( for non-slice refs, i < 0 intrinsically has len(s) added) - ( For slice refs, len(s) *is not* intrinsically added to i, j < 0) - ( for assignment/deletion, index refs must point to existing items - s[i]=v = __setitem__(s,i,v) - del s[i] = __delitem__(s,i) - s[i:j] = __getslice__(s,i,j) - s[i:j]=seq = __setslice__(s,i,j,seq) - del s[i:j] = __delslice__(s,i,j) == s[i:j] = [] - s.append(seq) == `s[len(seq):len(seq)] = seq' (but faster) - s.count(v) number of i's for which `s[i] == v' - s.index(v) first i such that `s[i] == v', or IndexError if none - s.insert(i, v) == `s[i:i] = [v]' - s.remove(v) == `del s[s.index(v)]', or IndexError if v not in s - s.reverse() reverse the items of s in place - s.sort() permute s items so s[i] <= s[j], for i < j - - Mappings - - @ Dictionaries: {key1: val1, key2: val2, ...} - - built-in types as keys must be unalterable: obj & all contents immutable - User-defined classes as keys must have __hash__() and __cmp__() methods - ~ TypeError is raised if key not acceptable - ~ KeyError is raised if reference made using non-existent key - key types may vary (contrary to ref man) - - Dictionaries ops vs methods (s: self, k: key, v: val) - - all collections general ops, plus: - hash(s) = __hash__(s) - hash value for dictionary references - s[k]=v = __setitem__(s,k,v) - del s[k] = __delitem__(s,k) - s.items() = a list copy of s's (key, item) pairs - s.keys() = a list copy of s's keys - s.values() = a list copy of s's values - s.has_keys(k) = 1 if s has key k, else 0 - ( s.items, .keys, and .values yield random but mutually consistent order) - - **** Callables **** - - @ User defined functions: 'def name (param-list): suite' - - suite is not evaluated at statement execution, but at function invocation - function parameters, comma separated on param-list: - func_code: special attr, code object representing compiled function body - func_globals: special attr, ref to global dict of funcs definition module - func(arg-list) invocation - - @ User defined methods: like functions, with extra implicit arg - - Same as functions, but passed class instance as additional first argument - im_self: special attr, method's class instance object - im_func: special attr, function object - mthd(args) invocation, same as mthd.im_func(mthd.im_self, args) - - @ Classes: 'class name[ (inheritance)]: suite' - - inheritance list is evaluated, if any, to identify base classes for name - suite is executed in new local name space, which goes to the class object - class name is bound in encompassing local name space - container for dictionary containing class's ns dictionary - __dict__: ro attr, class ns as dictionary object - __bases__: ro attr, class' base classes in tuple - __init__(self, args..): implements object instantiation - __del__(self): implements impending object deletion - - @ Class instances - - __dict__: ro attr, class' attribute dictionary - __class__: ro attr, instance's class object - - Callables special method vs ops (f: function) - - apply(f, args-tuple) call f with args-tuple as arg list - compile(str, flnm, kind) compile string into exectuable code object - eval(str, glbls=, lcls=) evaluate string as expression (cond_list) - filter(f, seq) => seq of seq elems for which f is true - map(f, lst, [lst2, ...]) => list of f applied to succesive lsts elems - reduce(f, lst, initlzr) => value of f applied to elems and cume result - - @ **** Null object: `None' **** - - @ **** Type objects, print as: <type 'int'> **** - ( '<...>' form is only for printing - cannot be entered that way, - - accessed via built-in func 'type()' - ( equal only when identical (same id()), - so can't just use the string name, must use object with the same str val) - - @ **** Modules **** - - functions and methods in a module share module's ("global") namespace - function uses "global" statement to instantiate var in global context - Modules use "import" to incorp other module's names - see Name Spaces - - Special attrs, methods, and operations - - __dict__: attr, module's ns as dictionary; can modify vals but not sruct - __name__: ro attr, module's name as string - import Instantiate module or module components within another - reload(amod) Reread an imported module - - @ **** Files **** - - wrapper around a C stdio file pointer - sys.stdin, sys.stdout, sys.stderr are standard io-stream file objects - - File operations: - - open(nm, mode='r', bufsize=sysdef) return new file object - close() A closed file cannot be read or written anymore. - flush() Flush the internal buffer, like stdio's `fflush()'. - isatty() 1 if file connected to a tty(-like) device, else 0. - read(SIZE) Read up to SIZE bytes frm file, less on EOF or no data - readline() Read one entire line from the file. - readlines() `readline()' til EOF and return list of lines read. - seek(OFFSET,WHENCE) Set file's current position, like stdio's `fseek()' - tell() Return file's current position, like stdio's `ftell()'. - write(STR) Write a string to the file. There is no return value. - - File functions: - - input(prompt='') like raw input but accept '\' line continuations - print exp, exp2, ... Write values to stdout - raw_input(prompt='') prompt then read single line of input - - **** Internal types **** - - @ Code objects - represent exectuable code - function obj sans context - @ Frame objects - represent executable frames - may occur in traceback objs - @ Traceback objects - stack trace of an exception - - Control statements - ================== - - * Calls and Evaluation * - - ( See also Callables, in Objects section above, for ops and methods.) - - exec: exec expr [ in expr2 [, expr3]] # Dynamic execution of python code - return: return [expr] # Leave current func call with expr value - - * Conditionals and Loops * - ( See also Boolean values, above) - - break: break # Terminate nearest enclosing loop - continue: continue # Continue next cycle of enclosing loop - if: if cond: suite [\n elif cond: suite \n ...] [\n else: suite] - for: for targs in conds: suite [ \n else: suite ] - while: while cond: suite [ \n else : suite ] - - * Exceptions * - - raise: raise expr [, expr2] # Raise exception expr, passing expr2 if any - try... # Handle exceptions: - try: suite [\n except [cond [, targ]]: suite \n ... \n] [else: suite] - try: suite \n finally: suite # Specify a 'cleanup' handler - ( two 'try' forms cannot be mixed together) - - System modules - ============== - @ * Built-ins * - - sys Interpreter state (see Operating Environment, above) - __builtin__ Access to all built-in python identifiers - __main__ Scope of the interpreters main program, script or stdin - array Obj efficiently representing arrays of basic values - math Math functions of C standard - time Time-related functions - regex Regular expression matching operations - marshal Read and write some python values in binary format - strop Miscellaneous string operations - struct Convert between python values and C structs - - @ * Standard * - - getopt Parse cmd line args in sys.argv. A la UNIX 'getopt'. - os Portable interface to OS dependent functionality - pdb text-oriented debugger - rand Pseudo-random generator, like C rand() - regsub Functions useful for working with regular expressions - string Useful string and characters functions and exceptions - wdb window-oriented debugger - whrandom Wichmann-Hill pseudo-random number generator - - @ * Miscellaneous * - - dis Python disassembler - glob Filename globbing (a la unix shell) - grep File string search - posixpath Common operations on POSIX pathnames - profile Python code profiler - repr `...` repr operator with presentation constraints - string All of builtin 'strop', plus - tb Traceback browser and printer - tempfile Produce a temporary-file name - util Miscellaneous functions that don't belong elsewhere - - @ * Unix * - - dbm Dict/file-like interface to Unix ndbm database library - grp Interface to Unix group database - posix Standardized UNIX OS functionality - see 'os', above - posixpath POSIX pathname functions - see 'os', above - pwd Access to the Unix password database - select Access to Unix select multiplex file synchronization - socket Access to BSD socket interface - thread Low-level primitives for working with process threads - - @ * Multimedia * - - audioop Useful operations on sound fragments - imageop Useful operations on images - jpeg Access to jpeg image compressor and decompressor - rgbimg Access SGI imglib image files - - @ * Cryptographic Extensions * - - md5 Interface to RSA's MD5 message digest algorithm - mpz Interface to int part of GNU multiple precision library - rotor Implementation of a rotor-based encryption algorithm - - @ * Stdwin * Standard Window System - - stdwin Standard Window System interface - stdwinevents Stdwin event, command, and selection constants - rect Rectangle manipulation operations - - @ * SGI IRIX * (4 & 5) - - al SGI audio facilities - AL al constants - fl Interface to FORMS library - FL fl constants - flp Functions for form designer - fm Access to font manager library - gl Access to graphics library - GL Constants for gl - DEVICE More constants for gl - imgfile Imglib image file interface - - @ * Suns * - - sunaudiodev Access to sun audio interface - - @ * Contrib * - - syslog - - metalbase - - Idioms and hints - ================ - - Invoke main if running as script: if __name__ == '__main__': main() - - General object-type miscellany - What type is someobj; eg, a list: if type(someobj) == type([]): - Convert number to hex or octal string: hex(122) => '0x7a' - Convert string to number: eval('0x7a') => 122 - - Sequence Slice conceptualization: - +---+---+---+---+---+ Indices point ~between~ chars: - | s | t | u | f | f | - first char's left edge = 0, - +---+---+---+---+---+ - nth char's right edge = n. - 0 1 2 3 4 5 (Note that -0 == 0, so it does - -5 -4 -3 -2 -1 not count from right.) - - Sequences miscellany: - Create merge of lists: map(None, lst1, lst2, ...) - It's faster to list.append(elem) than to list[len(list):] = [elem] - Copy structure of seq a to b: b = a[:] - - Comma (tuple vs expression grouping) nuances: - to specify a tuple of one element: ('element',) - to specify a tuple containing 1 tuple: (('contained', 'tuple'),) - "TypeError: call of non-function" often means a list missing a comma - - Namespace and object surveillance: - get dictful object keys/key-vals: dir(), vars() - Current context globals: eval(__name__ + '.__dict__') - Current context locals: vars() - Methods supported by X (some objs): X.__methods__ - X's data attributes (some objs): X.__members__ diff --git a/Misc/dlMakefile b/Misc/dlMakefile deleted file mode 100755 index 0a69f2de98..0000000000 --- a/Misc/dlMakefile +++ /dev/null @@ -1,58 +0,0 @@ -# Makefile to do general-coverage creation of dynamic-load libraries -# from python C-module sources. - -# $Id$ -# Created by Ken Manheimer, Jul-1994. ken.manheimer@nist.gov, 301 975-3539 - -# To configure for your site, select the appropriate SOURCES and macro -# def and assign the right path to the prefix macro. - -ARCH= sun4 -prefix= /depot/sundry -DESTLIB= $(prefix)/lib/python/$(ARCH) - -### For Sun Make; tested in v 1.0, under both SunOS 4.1.3 and SunOS 5.3: -#SOURCES:sh= echo *.c -### For Gnu Make; works at least for v 3.59: -SOURCES= $(wildcard *.c) - -# To configure for a new module: -# - put the module in the current directory -# - if it doesn't require any special compile or load options, that's it. -# - if it does require special compile or load options, create a macro -# composed of the (full) module name, sans suffix, plus 'CFLAGS' or -# 'LDFLAGS', depending on the compile phase in question. -metalbasemoduleCFLAGS= -I$(prefix)/include/mbase51 -DNO_TIMEB -DNO_USHORT -DNO_ENCRYPT -metalbasemoduleLDFLAGS= -L/depot/sundry/plat/lib -lmb -cursesmoduleCFLAGS= -I/usr/5include -cursesmoduleLDFLAGS= -L/usr/5lib -lcurses -ltermcap - -OBJS= $(SOURCES:.c=.so) - -CC= gcc -OPT= -g -O -DEFS= -DHAVE_CONFIG_H -INCLDIR= $(prefix)/include/python -CFLAGS= $(OPT) -I$(INCLDIR) -I.. $(DEFS) -LD= ld - -all: $(OBJS) - -%.o: %.c - $(CC) -c $(CFLAGS) $(CPPFLAGS) $($*CFLAGS) -o $@ $< - -%.so: %.o - $(LD) $(LDFLAGS) -o $@ $< $($*LDFLAGS) $(LOADLIBES) - -PHONY: echo # For testing derivation of $(OBJS). -echo: - @echo "(Set SOURCES def if you don't see a '.so' for each '.c' between the brackets)" - @echo :$(OBJS): - -PHONY : install -install: $(OBJS) - ls $(OBJS) | cpio -pm $(DESTLIB) - -PHONY : clean -clean: - rm -f *.o *.so diff --git a/Misc/faq2html.py b/Misc/faq2html.py deleted file mode 100755 index 2ea3810ae4..0000000000 --- a/Misc/faq2html.py +++ /dev/null @@ -1,193 +0,0 @@ -#! /usr/local/bin/python - -# Convert the Python FAQ to HTML - -import string -import regex -import regsub -import sys -import os - -FAQ = 'FAQ' - -chapterprog = regex.compile('^\([1-9][0-9]*\)\. ') -questionprog = regex.compile('^\([1-9][0-9]*\)\.\([1-9][0-9]*\)\. ') -newquestionprog = regex.compile('^Q\. ') -blankprog = regex.compile('^[ \t]*$') -indentedorblankprog = regex.compile('^\([ \t]+\|[ \t]*$\)') -underlineprog = regex.compile('^==*$') -eightblanksprog = regex.compile('^\( \| *\t\)') -mailheaderprog = regex.compile('^\(Subject\|Newsgroups\|Followup-To\|From\|Reply-To\|Approved\|Archive-name\|Version\|Last-modified\): +') -urlprog = regex.compile('<URL:\([^>]*\)>') -ampprog = regex.compile('&') -aprog = regex.compile('^A\. +') -qprog = regex.compile('>Q\. +') -qrefprog = regex.compile('question +\([0-9]\.[0-9]+\)') -versionprog = regex.compile('^Version: ') -emailprog = regex.compile('<\([^>@:]+@[^>@:]+\)>') - -def main(): - print 'Reading lines...' - lines = open(FAQ, 'r').readlines() - print 'Renumbering in memory...' - oldlines = lines[:] - after_blank = 1 - chapter = 0 - question = 0 - chapters = ['<OL>'] - questions = ['<OL>'] - for i in range(len(lines)): - line = lines[i] - if after_blank: - n = chapterprog.match(line) - if n >= 0: - chapter = chapter + 1 - if chapter != 1: - questions.append('</UL>\n') - question = 0 - lines[i] = '<H2>' + line[n:-1] + '</H2>\n' - chapters.append('<LI> ' + line[n:]) - questions.append('<LI> ' + line[n:]) - questions.append('<UL>\n') - afterblank = 0 - continue - n = underlineprog.match(line) - if n >= 0: - lines[i] = '' - continue - n = questionprog.match(line) - if n < 0: n = newquestionprog.match(line) - 3 - if n >= 0: - question = question + 1 - number = '%d.%d'%(chapter, question) - lines[i] = '<A NAME="' + number + '"><H3>' + line[n:] - questions.append('<LI><A HREF="#' + \ - number + '">' + line[n:]) - # Add up to 4 continuations of the question - n = len(number) - for j in range(i+1, i+5): - if blankprog.match(lines[j]) >= 0: - lines[j-1] = lines[j-1] + '</H3></A>' - questions[-1] = \ - questions[-1][:-1] + '</A>\n' - break - questions.append(' '*(n+2) + lines[j]) - afterblank = 0 - continue - afterblank = (blankprog.match(line) >= 0) - print 'Inserting list of chapters...' - chapters.append('</OL>\n') - for i in range(len(lines)): - line = lines[i] - if regex.match( - '^This FAQ is divided in the following chapters', - line) >= 0: - i = i+1 - while 1: - line = lines[i] - if indentedorblankprog.match(line) < 0: - break - del lines[i] - lines[i:i] = chapters - break - else: - print '*** Can\'t find header for list of chapters' - print '*** Chapters found:' - for line in chapters: print line, - print 'Inserting list of questions...' - questions.append('</UL></OL>\n') - for i in range(len(lines)): - line = lines[i] - if regex.match('^Here.s an overview of the questions', - line) >= 0: - i = i+1 - while 1: - line = lines[i] - if indentedorblankprog.match(line) < 0: - break - del lines[i] - lines[i:i] = questions - break - else: - print '*** Can\'t find header for list of questions' - print '*** Questions found:' - for line in questions: print line, - # final cleanup - print "Final cleanup..." - doingpre = 0 - for i in range(len(lines)): - # set lines indented by >= 8 spaces using PRE - # blank lines either terminate PRE or separate paragraphs - n = eightblanksprog.match(lines[i]) - if n < 0: n = mailheaderprog.match(lines[i]) - if n >= 0: - if versionprog.match(lines[i]) > 0: - version = string.split(lines[i])[1] - if doingpre == 0: - lines[i] = '<PRE>\n' + lines[i] - doingpre = 1 - continue - n = blankprog.match(lines[i]) - if n >= 0: - # print '*** ', lines[i-1], doingpre - if doingpre == 1: - lines[i] = '</PRE><P>\n' - doingpre = 0 - else: - lines[i] = '<P>\n' - continue - - # & -> &amp; - n = ampprog.search(lines[i]) - if n >= 0: - lines[i] = regsub.gsub(ampprog, '&amp;', lines[i]) - # no continue - there might be other changes to the line... - - # zap all the 'Q.' and 'A.' leaders - what happened to the - # last couple? - n = qprog.search(lines[i]) - if n >= 0: - lines[i] = regsub.sub(qprog, '>', lines[i]) - # no continue - there might be other changes to the line... - - n = aprog.search(lines[i]) - if n >= 0: - lines[i] = regsub.sub(aprog, '', lines[i]) - # no continue - there might be other changes to the line... - - # patch up hard refs to questions - n = qrefprog.search(lines[i]) - if n >= 0: - lines[i] = regsub.sub(qrefprog, - '<A HREF="#\\1">question \\1</A>', lines[i]) - # no continue - there might be other changes to the line... - - # make <URL:...> into actual links - n = urlprog.search(lines[i]) - if n >= 0: - lines[i] = regsub.gsub(urlprog, '<A HREF="\\1">\\1</A>', lines[i]) - # no continue - there might be other changes to the line... - - # make <user@host.domain> into <mailto:...> links - n = emailprog.search(lines[i]) - if n >= 0: - lines[i] = regsub.gsub(emailprog, - '<A HREF="mailto:\\1">\\1</A>', lines[i]) - # no continue - there might be other changes to the line... - - lines[0:0] = ['<HTML><HEAD><TITLE>Python Frequently Asked Questions v', - version, - '</TITLE>\n', - '</HEAD><body>\n', - '(This file was generated using\n', - '<A HREF="faq2html.py">faq2html.py</A>.)<P>\n'] - lines.append('<P></BODY></HTML>\n') - - print 'Writing html file...' - f = open(FAQ + '.html', 'w') - for line in lines: - f.write(line) - f.close() - print 'Done.' - -main() diff --git a/Misc/fixfuncptrs.sh b/Misc/fixfuncptrs.sh deleted file mode 100755 index f05809efc8..0000000000 --- a/Misc/fixfuncptrs.sh +++ /dev/null @@ -1,47 +0,0 @@ -prog=' -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_dealloc\*/\)$|\1(destructor)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_print\*/\)$|\1(printfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_getattr\*/\)$|\1(getattrfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_setattr\*/\)$|\1(setattrfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_compare\*/\)$|\1(cmpfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_repr\*/\)$|\1(reprfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_hash\*/\)$|\1(hashfunc)\2 \3| - -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_length\*/\)$|\1(inquiry)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_concat\*/\)$|\1(binaryfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_repeat\*/\)$|\1(intargfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_item\*/\)$|\1(intargfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_slice\*/\)$|\1(intintargfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_ass_item\*/\)$|\1(intobjargproc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_ass_slice\*/\)$|\1(intintobjargproc)\2 \3| - -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*mp_length\*/\)$|\1(inquiry)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*mp_subscript\*/\)$|\1(binaryfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*mp_ass_subscript\*/\)$|\1(objobjargproc)\2 \3| - -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_nonzero*\*/\)$|\1(inquiry)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_coerce*\*/\)$|\1(coercion)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_negative*\*/\)$|\1(unaryfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_positive*\*/\)$|\1(unaryfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_absolute*\*/\)$|\1(unaryfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_invert*\*/\)$|\1(unaryfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_int*\*/\)$|\1(unaryfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_long*\*/\)$|\1(unaryfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_float*\*/\)$|\1(unaryfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_oct*\*/\)$|\1(unaryfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_hex*\*/\)$|\1(unaryfunc)\2 \3| -s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_[a-z]*\*/\)$|\1(binaryfunc)\2 \3| - -' -for file -do - sed -e "$prog" $file >$file.new || break - if cmp -s $file $file.new - then - echo $file unchanged; rm $file.new - else - echo $file UPDATED - mv $file $file~ - mv $file.new $file - fi -done diff --git a/Misc/indent.pro b/Misc/indent.pro deleted file mode 100644 index 3efac89b74..0000000000 --- a/Misc/indent.pro +++ /dev/null @@ -1,15 +0,0 @@ --sob --nbad --bap --br --nce --ncs --npcs --i8 --ip8 --c25 --T PyObject - - - - diff --git a/Misc/pyimenu.el b/Misc/pyimenu.el deleted file mode 100755 index 738de7d825..0000000000 --- a/Misc/pyimenu.el +++ /dev/null @@ -1,305 +0,0 @@ -;;; PYIMENU.EL --- - -;; Copyright (C) 1995 Perry A. Stoll - -;; Author: Perry A. Stoll <stoll@atr-sw.atr.co.jp> -;; Created: 12 May 1995 -;; Version: 1.0 -;; Keywords: tools python imenu - -;; This program is free software; you can redistribute it and/or modify -;; it under the terms of the GNU General Public License as published by -;; the Free Software Foundation; either version 2, or (at your option) -;; any later version. - -;; This program is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;; GNU General Public License for more details. - -;; A copy of the GNU General Public License can be obtained from the -;; Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, -;; USA. - -;;;; COMMENTS - -;; I use the imenu package a lot for looking at Lisp and C/C++ -;; code. When I started using Python, I was dismayed that I couldn't -;; use it to look at Python source. So here's a rough go at it. - -;;;; USAGE - -;; This program is used in conjunction with the imenu package. When -;; you call imenu in python-mode in a python buffer, a list of -;; functions and classes is built. The top level menu has a list of -;; all functions and classes defined at the top indentation -;; level. Classes which have methods defined in them have a submenu -;; which contains all definitions contained in them. Selecting any -;; item will bring you to that point in the file. - -;;;; INSTALLATION - -;; You know the routine: -;; 1) Save this file as pyimenu.el, -;; 2) Place that file somewhere in your emacs load path (maybe ~/emacs -;; or ~/emacs/lisp), -;; 3) Byte compile it (M-x byte-compile-file), -;; 4) Add the following (between "cut here" and "end here") to your -;; ~/.emacs file, -;; 5) Reboot. (joke: DON'T do that, although you'll probably have to -;; either reload your ~/.emacs file or start a new emacs) - -;;--------------cut here------------------------------------------- -;;;; Load the pyimenu index function -;;(autoload 'imenu "imenu" nil t) -;;(autoload 'imenu-example--create-python-index "pyimenu") -;;;; Add the index creation function to the python-mode-hook -;;(add-hook 'python-mode-hook -;; (function -;; (lambda () -;; (setq imenu-create-index-function -;; (function imenu-example--create-python-index))))) -;;----------------end here-------------------------------------------- -;; -;; That is all you need. Of course, the following provides a more -;; useful interface. i.e. this is how I have it set up ;-) -;; -;;----------------optionally cut here---------------------------------- -;;(autoload 'imenu-add-to-menubar "imenu" nil t) -;;(defun my-imenu-install-hook () -;; (imenu-add-to-menubar (format "%s-%s" "IM" mode-name))) -;;(add-hook 'python-mode-hook (function my-imenu-install-hook)) -;;;; Bind imenu to some convenient (?) mouse key. This really lets you -;;;; fly around the buffer. Here it is set to Meta-Shift-Mouse3Click. -;;(global-set-key [M-S-down-mouse-3] (function imenu)) -;;-----------------optionaly end here----------------------------------- - -;;;; CAVEATS/NOTES - -;; 0) I'm not a professional elisp programmer and it shows in the code -;; below. If anyone there has suggestions/changes, I'd love to -;; hear them. I've tried the code out on a bunch of python files -;; from the python-1.1.1 Demo distribution and it worked with -;; them - your mileage may very. -;; -;; 1) You must have the imenu package to use this file. This file -;; works with imenu version 1.11 (the version included with emacs -;; 19.28) and imenu version 1.14; if you have a later version, this -;; may not work with it. -;; -;; 2) This setup assumes you also have python-mode.el, so that it can -;; use the python-mode-hook. It comes with the python distribution. -;; -;; 3) I don't have the Python 1.2 distribution yet, so again, this may -;; not work with that. -;; - -(require 'imenu) - -;;; -;;; VARIABLES: customizable in your .emacs file. -;;; - -(defvar imenu-example--python-show-method-args-p nil - "*When using imenu package with python-mode, whether the arguments of -the function/methods should be printed in the imenu buffer in addition -to the function/method name. If non-nil, args are printed.") - -;;; -;;; VARIABLES: internal use. -;;; -(defvar imenu-example--python-class-regexp - (concat ; <<classes>> - "\\(" ; - "^[ \t]*" ; newline and maybe whitespace - "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name - ; possibly multiple superclasses - "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)" - "[ \t]*:" ; and the final : - "\\)" ; >>classes<< - ) - "Regexp for Python classes for use with the imenu package." -) - -(defvar imenu-example--python-method-regexp - (concat ; <<methods and functions>> - "\\(" ; - "^[ \t]*" ; new line and maybe whitespace - "\\(def[ \t]+" ; function definitions start with def - "\\([a-zA-Z0-9_]+\\)" ; name is here - ; function arguments... - "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))" - "\\)" ; end of def - "[ \t]*:" ; and then the : - "\\)" ; >>methods and functions<< - ) - "Regexp for Python methods/functions for use with the imenu package." - ) - -(defvar imenu-example--python-method-no-arg-parens '(2 8) - "Indicies into the parenthesis list of the regular expression for -python for use with imenu. Using these values will result in smaller -imenu lists, as arguments to functions are not listed. - -See the variable imenu-example--python-show-method-args-p to for -information") - -(defvar imenu-example--python-method-arg-parens '(2 7) - "Indicies into the parenthesis list of the regular expression for -python for use with imenu. Using these values will result in large -imenu lists, as arguments to functions are listed. - -See the variable imenu-example--python-show-method-args-p to for -information") - -;; Note that in this format, this variable can still be used with the -;; imenu--generic-function. Otherwise, there is no real reason to have -;; it. -(defvar imenu-example--generic-python-expression - (cons - (concat - imenu-example--python-class-regexp - "\\|" ; or... - imenu-example--python-method-regexp - ) - imenu-example--python-method-no-arg-parens) - "Generic Python expression which may be used directly with imenu by -setting the variable imenu-generic-expression to this value. Also, see -the function \\[imenu-example--create-python-index] for an alternate -way of finding the index.") - -;; These next two variables are used when searching for the python -;; class/definitions. Just saving some time in accessing the -;; generic-python-expression, really. -(defvar imenu-example--python-generic-regexp) -(defvar imenu-example--python-generic-parens) - -;;; -;;; CODE: -;;; - -;; Note: -;; At first, I tried using some of the functions supplied by -;; python-mode to navigate through functions and classes, but after a -;; while, I decided dump it. This file is relatively self contained -;; and I liked it that. - -;;;###autoload -(defun imenu-example--create-python-index () - "Interface function for imenu package to find all python classes and -functions/methods. Calls function -\\[imenu-example--create-python-index-engine]. See that function for -the details of how this works." - (setq imenu-example--python-generic-regexp - (car imenu-example--generic-python-expression)) - (setq imenu-example--python-generic-parens - (if imenu-example--python-show-method-args-p - imenu-example--python-method-arg-parens - imenu-example--python-method-no-arg-parens)) - (goto-char (point-min)) - (imenu-example--create-python-index-engine nil)) - -(defun imenu-example--create-python-index-engine (&optional start-indent) -"Function for finding all definitions (classes, methods, or functions) -in a python file for the imenu package. - -Retuns a possibly nested alist of the form \(INDEX-NAME - INDEX-POSITION). The second element of the alist may be an alist, -producing a nested list as in \(INDEX-NAME . INDEX-ALIST). - -This function should not be called directly, as it calls itself -recursively and requires some setup. Rather this is the engine for the -function \\[imenu-example--create-python-index]. - -It works recursively by looking for all definitions at the current -indention level. When it finds one, it adds it to the alist. If it -finds a definition at a greater indentation level, it removes the -previous definition from the alist. In it's place it adds all -definitions found at the next indentation level. When it finds a -definition that is less indented then the current level, it retuns the -alist it has created thus far. - - The optional argument START-INDENT indicates the starting indentation -at which to continue looking for python classes, methods, or -functions. If this is not supplied, the function uses the indentation -of the first definition found. " - (let ((index-alist '()) - (sub-method-alist '()) - looking-p - def-name prev-name - cur-indent def-pos - (class-paren (first imenu-example--python-generic-parens)) - (def-paren (second imenu-example--python-generic-parens))) - (setq looking-p - (re-search-forward imenu-example--python-generic-regexp - (point-max) t)) - (while looking-p - (save-excursion - ;; used to set def-name to this value but generic-extract-name is - ;; new to imenu-1.14. this way it still works with imenu-1.11 - ;;(imenu--generic-extract-name imenu-example--python-generic-parens)) - (let ((cur-paren (if (match-beginning class-paren) - class-paren def-paren))) - (setq def-name - (buffer-substring (match-beginning cur-paren) - (match-end cur-paren)))) - (beginning-of-line) - (setq cur-indent (current-indentation))) - - ;; HACK: want to go to the correct definition location. Assuming - ;; here that there are only two..which is true for python. - (setq def-pos - (or (match-beginning class-paren) - (match-beginning def-paren))) - - ; if we don't have a starting indent level, take this one - (or start-indent - (setq start-indent cur-indent)) - - ; if we don't have class name yet, take this one - (or prev-name - (setq prev-name def-name)) - - ;; what level is the next definition on? - ;; must be same, deeper or shallower indentation - (cond - - ;; at the same indent level, add it to the list... - ((= start-indent cur-indent) - (push (cons def-name def-pos) index-alist)) - - ;; deeper indented expression, recur... - ((< start-indent cur-indent) - - ;; the point is currently on the expression we're supposed to - ;; start on, so go back to the last expression. The recursive - ;; call will find this place again and add it to the correct - ;; list - (re-search-backward imenu-example--python-generic-regexp - (point-min) 'move) - (setq sub-method-alist (imenu-example--create-python-index-engine - cur-indent)) - - (if sub-method-alist - ;; we put the last element on the index-alist on the start - ;; of the submethod alist so the user can still get to it. - (let ((save-elmt (pop index-alist))) - (push (cons (imenu-create-submenu-name prev-name) - (cons save-elmt sub-method-alist)) - index-alist)))) - - ;; found less indented expression, we're done. - (t - (setq looking-p nil) - (re-search-backward imenu-example--python-generic-regexp - (point-min) t))) - (setq prev-name def-name) - (and looking-p - (setq looking-p - (re-search-forward imenu-example--python-generic-regexp - (point-max) 'move)))) - (nreverse index-alist))) - -(provide 'pyimenu) - -;;; PyImenu.EL ends here diff --git a/Misc/python-mode-old.el b/Misc/python-mode-old.el deleted file mode 100644 index 0782bdcae1..0000000000 --- a/Misc/python-mode-old.el +++ /dev/null @@ -1,2056 +0,0 @@ -;;; python-mode.el --- Major mode for editing Python programs - -;; Copyright (C) 1992,1993,1994 Tim Peters - -;; Author: 1995 Barry A. Warsaw -;; 1992-1994 Tim Peters -;; Maintainer: python-mode@python.org -;; Created: Feb 1992 -;; Version: 2.30 -;; Last Modified: 1995/09/19 20:01:42 -;; Keywords: python editing language major-mode - -;; This software is provided as-is, without express or implied -;; warranty. Permission to use, copy, modify, distribute or sell this -;; software, without fee, for any purpose and by any individual or -;; organization, is hereby granted, provided that the above copyright -;; notice and this paragraph appear in all copies. - -;;; Commentary: -;; -;; This is a major mode for editing Python programs. It was developed -;; by Tim Peters <tim@ksr.com> after an original idea by Michael -;; A. Guravage. Tim doesn't appear to be on the 'net any longer so I -;; have undertaken maintenance of the mode. - -;; At some point this mode will undergo a rewrite to bring it more in -;; line with GNU Emacs Lisp coding standards. But all in all, the -;; mode works exceedingly well. - -;; The following statements, placed in your .emacs file or -;; site-init.el, will cause this file to be autoloaded, and -;; python-mode invoked, when visiting .py files (assuming this file is -;; in your load-path): -;; -;; (autoload 'python-mode "python-mode" "Python editing mode." t) -;; (setq auto-mode-alist -;; (cons '("\\.py$" . python-mode) auto-mode-alist)) - -;; Here's a brief list of recent additions/improvements: -;; -;; - Wrapping and indentation within triple quote strings should work -;; properly now. -;; - `Standard' bug reporting mechanism (use C-c C-b) -;; - py-mark-block was moved to C-c C-m -;; - C-c C-v shows you the python-mode version -;; - a basic python-font-lock-keywords has been added for Emacs 19 -;; font-lock colorizations. -;; - proper interaction with pending-del and del-sel modes. -;; - New py-electric-colon (:) command for improved outdenting. Also -;; py-indent-line (TAB) should handle outdented lines better. -;; - New commands py-outdent-left (C-c C-l) and py-indent-right (C-c C-r) - -;; Here's a brief to do list: -;; -;; - Better integration with gud-mode for debugging. -;; - Rewrite according to GNU Emacs Lisp standards. -;; - py-delete-char should obey numeric arguments. -;; - even better support for outdenting. Guido suggests outdents of -;; at least one level after a return, raise, break, or continue -;; statement. -;; - de-electrify colon inside literals (e.g. comments and strings) - -;; If you can think of more things you'd like to see, drop me a line. -;; If you want to report bugs, use py-submit-bug-report (C-c C-b). -;; -;; Note that I only test things on XEmacs (currently 19.11). If you -;; port stuff to FSF Emacs 19, or Emacs 18, please send me your -;; patches. - -;; LCD Archive Entry: -;; python-mode|Barry A. Warsaw|python-mode@python.org -;; |Major mode for editing Python programs -;; |1995/09/19 20:01:42|2.30| - -;;; Code: - - -;; user definable variables -;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv - -(defvar py-python-command "python" - "*Shell command used to start Python interpreter.") - -(defvar py-indent-offset 8 ; argue with Guido <grin> - "*Indentation increment. -Note that `\\[py-guess-indent-offset]' can usually guess a good value -when you're editing someone else's Python code.") - -(defvar py-align-multiline-strings-p t - "*Flag describing how multiline triple quoted strings are aligned. -When this flag is non-nil, continuation lines are lined up under the -preceding line's indentation. When this flag is nil, continuation -lines are aligned to column zero.") - -(defvar py-block-comment-prefix "##" - "*String used by `py-comment-region' to comment out a block of code. -This should follow the convention for non-indenting comment lines so -that the indentation commands won't get confused (i.e., the string -should be of the form `#x...' where `x' is not a blank or a tab, and -`...' is arbitrary).") - -(defvar py-scroll-process-buffer t - "*Scroll Python process buffer as output arrives. -If nil, the Python process buffer acts, with respect to scrolling, like -Shell-mode buffers normally act. This is surprisingly complicated and -so won't be explained here; in fact, you can't get the whole story -without studying the Emacs C code. - -If non-nil, the behavior is different in two respects (which are -slightly inaccurate in the interest of brevity): - - - If the buffer is in a window, and you left point at its end, the - window will scroll as new output arrives, and point will move to the - buffer's end, even if the window is not the selected window (that - being the one the cursor is in). The usual behavior for shell-mode - windows is not to scroll, and to leave point where it was, if the - buffer is in a window other than the selected window. - - - If the buffer is not visible in any window, and you left point at - its end, the buffer will be popped into a window as soon as more - output arrives. This is handy if you have a long-running - computation and don't want to tie up screen area waiting for the - output. The usual behavior for a shell-mode buffer is to stay - invisible until you explicitly visit it. - -Note the `and if you left point at its end' clauses in both of the -above: you can `turn off' the special behaviors while output is in -progress, by visiting the Python buffer and moving point to anywhere -besides the end. Then the buffer won't scroll, point will remain where -you leave it, and if you hide the buffer it will stay hidden until you -visit it again. You can enable and disable the special behaviors as -often as you like, while output is in progress, by (respectively) moving -point to, or away from, the end of the buffer. - -Warning: If you expect a large amount of output, you'll probably be -happier setting this option to nil. - -Obscure: `End of buffer' above should really say `at or beyond the -process mark', but if you know what that means you didn't need to be -told <grin>.") - -(defvar py-temp-directory - (let ((ok '(lambda (x) - (and x - (setq x (expand-file-name x)) ; always true - (file-directory-p x) - (file-writable-p x) - x)))) - (or (funcall ok (getenv "TMPDIR")) - (funcall ok "/usr/tmp") - (funcall ok "/tmp") - (funcall ok ".") - (error - "Couldn't find a usable temp directory -- set py-temp-directory"))) - "*Directory used for temp files created by a *Python* process. -By default, the first directory from this list that exists and that you -can write into: the value (if any) of the environment variable TMPDIR, -/usr/tmp, /tmp, or the current directory.") - -(defvar py-beep-if-tab-change t - "*Ring the bell if tab-width is changed. -If a comment of the form - - \t# vi:set tabsize=<number>: - -is found before the first code line when the file is entered, and the -current value of (the general Emacs variable) `tab-width' does not -equal <number>, `tab-width' is set to <number>, a message saying so is -displayed in the echo area, and if `py-beep-if-tab-change' is non-nil -the Emacs bell is also rung as a warning.") - -;; These were the previous font-lock keywords, but I think I now -;; prefer the ones from XEmacs 19.12's font-lock.el. I've merged the -;; two into the new definition below. -;; -;;(defvar python-font-lock-keywords -;; (list -;; (cons -;; (concat -;; "\\<\\(" -;; (mapconcat -;; 'identity -;; '("access" "and" "break" "continue" -;; "del" "elif" "else" "except" -;; "exec" "finally" "for" "from" -;; "global" "if" "import" "in" -;; "is" "lambda" "not" "or" -;; "pass" "print" "raise" "return" -;; "try" "while" "def" "class" -;; ) -;; "\\|") -;; "\\)\\>") -;; 1) -;; ;; functions -;; '("\\bdef\\s +\\(\\sw+\\)(" 1 font-lock-function-name-face) -;; ;; classes -;; '("\\bclass\\s +\\(\\sw+\\)[(:]" 1 font-lock-function-name-face) -;; ) -;; "*Additional keywords to highlight `python-mode' buffers.") - -;; These are taken from XEmacs 19.12's font-lock.el file, but have the -;; more complete list of keywords from the previous definition in -;; python-mode.el. There are a few other minor stylistic changes as -;; well. -;; -(defvar python-font-lock-keywords - (list - (cons (concat - "\\b\\(" - (mapconcat - 'identity - '("access" "and" "break" "continue" - "del" "elif" "else:" "except" - "except:" "exec" "finally:" "for" - "from" "global" "if" "import" - "in" "is" "lambda" "not" - "or" "pass" "print" "raise" - "return" "try:" "while" - ) - "\\|") - "\\)[ \n\t(]") - 1) - ;; classes - '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)" - 1 font-lock-type-face) - ;; functions - '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)" - 1 font-lock-function-name-face) - ) - "*Additional expressions to highlight in Python mode.") - -;; R Lindsay Todd <toddr@rpi.edu> suggests these changes to the -;; original keywords, which wouldn't be necessary if we go with the -;; XEmacs defaults, but which I agree makes sense without them. -;; -;; functions -;; '("\\bdef\\s +\\(\\sw+\\)\\s *(" 1 font-lock-function-name-face) -;; classes -;; '("\\bclass\\s +\\(\\sw+\\)\\s *[(:]" 1 font-lock-type-face) - - - -;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT - -;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This -;; seems to be the standard way of checking this. -;; BAW - This is *not* the right solution. When at all possible, -;; instead of testing for the version of Emacs, use feature tests. - -(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version)) -(setq py-this-is-emacs-19-p - (and - (not py-this-is-lucid-emacs-p) - (string-match "^19\\." emacs-version))) - -;; have to bind py-file-queue before installing the kill-emacs hook -(defvar py-file-queue nil - "Queue of Python temp files awaiting execution. -Currently-active file is at the head of the list.") - -;; define a mode-specific abbrev table for those who use such things -(defvar python-mode-abbrev-table nil - "Abbrev table in use in `python-mode' buffers.") -(define-abbrev-table 'python-mode-abbrev-table nil) - -(defvar python-mode-hook nil - "*Hook called by `python-mode'.") - -;; in previous version of python-mode.el, the hook was incorrectly -;; called py-mode-hook, and was not defvar'd. deprecate its use. -(and (fboundp 'make-obsolete-variable) - (make-obsolete-variable 'py-mode-hook 'python-mode-hook)) - -(defvar py-mode-map () - "Keymap used in `python-mode' buffers.") - -(if py-mode-map - () - (setq py-mode-map (make-sparse-keymap)) - - ;; shadow global bindings for newline-and-indent w/ the py- version. - ;; BAW - this is extremely bad form, but I'm not going to change it - ;; for now. - (mapcar (function (lambda (key) - (define-key - py-mode-map key 'py-newline-and-indent))) - (where-is-internal 'newline-and-indent)) - - ;; BAW - you could do it this way, but its not considered proper - ;; major-mode form. - (mapcar (function - (lambda (x) - (define-key py-mode-map (car x) (cdr x)))) - '((":" . py-electric-colon) - ("\C-c\C-c" . py-execute-buffer) - ("\C-c|" . py-execute-region) - ("\C-c!" . py-shell) - ("\177" . py-delete-char) - ("\n" . py-newline-and-indent) - ("\C-c:" . py-guess-indent-offset) - ("\C-c\t" . py-indent-region) - ("\C-c\C-l" . py-outdent-left) - ("\C-c\C-r" . py-indent-right) - ("\C-c<" . py-shift-region-left) - ("\C-c>" . py-shift-region-right) - ("\C-c\C-n" . py-next-statement) - ("\C-c\C-p" . py-previous-statement) - ("\C-c\C-u" . py-goto-block-up) - ("\C-c\C-m" . py-mark-block) - ("\C-c#" . py-comment-region) - ("\C-c?" . py-describe-mode) - ("\C-c\C-hm" . py-describe-mode) - ("\e\C-a" . beginning-of-python-def-or-class) - ("\e\C-e" . end-of-python-def-or-class) - ( "\e\C-h" . mark-python-def-or-class))) - ;; should do all keybindings this way - (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report) - (define-key py-mode-map "\C-c\C-v" 'py-version) - ) - -(defvar py-mode-syntax-table nil - "Syntax table used in `python-mode' buffers.") - -(if py-mode-syntax-table - () - (setq py-mode-syntax-table (make-syntax-table)) - ;; BAW - again, blech. - (mapcar (function - (lambda (x) (modify-syntax-entry - (car x) (cdr x) py-mode-syntax-table))) - '(( ?\( . "()" ) ( ?\) . ")(" ) - ( ?\[ . "(]" ) ( ?\] . ")[" ) - ( ?\{ . "(}" ) ( ?\} . "){" ) - ;; fix operator symbols misassigned in the std table - ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." ) - ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." ) - ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." ) - ( ?\> . "." ) ( ?\| . "." ) - ( ?\_ . "w" ) ; underscore is legit in names - ( ?\' . "\"") ; single quote is string quote - ( ?\" . "\"" ) ; double quote is string quote too - ( ?\` . "$") ; backquote is open and close paren - ( ?\# . "<") ; hash starts comment - ( ?\n . ">")))) ; newline ends comment - -(defconst py-stringlit-re - (concat - "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted - "\\|" ; or - "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted - "Regexp matching a Python string literal.") - -;; this is tricky because a trailing backslash does not mean -;; continuation if it's in a comment -(defconst py-continued-re - (concat - "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*" - "\\\\$") - "Regexp matching Python lines that are continued via backslash.") - -(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)" - "Regexp matching blank or comment lines.") - -(defconst py-outdent-re - (concat "\\(" (mapconcat 'identity - '("else:" - "except\\(\\s +.*\\)?:" - "finally:" - "elif\\s +.*:") - "\\|") - "\\)") - "Regexp matching clauses to be outdented one level.") - -(defconst py-no-outdent-re - (concat "\\(" (mapconcat 'identity - '("try:" - "except\\(\\s +.*\\)?:" - "while\\s +.*:" - "for\\s +.*:" - "if\\s +.*:" - "elif\\s +.*:") - "\\|") - "\\)") - "Regexp matching lines to not outdent after.") - - -;;;###autoload -(defun python-mode () - "Major mode for editing Python files. -To submit a problem report, enter `\\[py-submit-bug-report]' from a -`python-mode' buffer. Do `\\[py-describe-mode]' for detailed -documentation. To see what version of `python-mode' you are running, -enter `\\[py-version]'. - -This mode knows about Python indentation, tokens, comments and -continuation lines. Paragraphs are separated by blank lines only. - -COMMANDS -\\{py-mode-map} -VARIABLES - -py-indent-offset\tindentation increment -py-block-comment-prefix\tcomment string used by py-comment-region -py-python-command\tshell command to invoke Python interpreter -py-scroll-process-buffer\talways scroll Python process buffer -py-temp-directory\tdirectory used for temp files (if needed) -py-beep-if-tab-change\tring the bell if tab-width is changed" - (interactive) - (kill-all-local-variables) - (set-syntax-table py-mode-syntax-table) - (setq major-mode 'python-mode - mode-name "Python" - local-abbrev-table python-mode-abbrev-table) - (use-local-map py-mode-map) - ;; Emacs 19 requires this - (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p) - (setq comment-multi-line nil)) - ;; BAW -- style... - (mapcar (function (lambda (x) - (make-local-variable (car x)) - (set (car x) (cdr x)))) - '((paragraph-separate . "^[ \t]*$") - (paragraph-start . "^[ \t]*$") - (require-final-newline . t) - (comment-start . "# ") - (comment-start-skip . "# *") - (comment-column . 40) - (indent-region-function . py-indent-region) - (indent-line-function . py-indent-line))) - ;; hack to allow overriding the tabsize in the file (see tokenizer.c) - ;; - ;; not sure where the magic comment has to be; to save time - ;; searching for a rarity, we give up if it's not found prior to the - ;; first executable statement. - ;; - ;; BAW - on first glance, this seems like complete hackery. Why was - ;; this necessary, and is it still necessary? - (let ((case-fold-search nil) - (start (point)) - new-tab-width) - (if (re-search-forward - "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):" - (prog2 (py-next-statement 1) (point) (goto-char 1)) - t) - (progn - (setq new-tab-width - (string-to-int - (buffer-substring (match-beginning 1) (match-end 1)))) - (if (= tab-width new-tab-width) - nil - (setq tab-width new-tab-width) - (message "Caution: tab-width changed to %d" new-tab-width) - (if py-beep-if-tab-change (beep))))) - (goto-char start)) - - ;; run the mode hook. py-mode-hook use is deprecated - (if python-mode-hook - (run-hooks 'python-mode-hook) - (run-hooks 'py-mode-hook))) - - -;; electric characters -(defun py-outdent-p () - ;; returns non-nil if the current line should outdent one level - (save-excursion - (and (progn (back-to-indentation) - (looking-at py-outdent-re)) - (progn (backward-to-indentation 1) - (while (or (looking-at py-blank-or-comment-re) - (bobp)) - (backward-to-indentation 1)) - (not (looking-at py-no-outdent-re))) - ))) - - -(defun py-electric-colon (arg) - "Insert a colon. -In certain cases the line is outdented appropriately. If a numeric -argument is provided, that many colons are inserted non-electrically. -Electric behavior is inhibited inside a string or comment." - (interactive "P") - (self-insert-command (prefix-numeric-value arg)) - ;; are we in a string or comment? - (if (save-excursion - (let ((pps (parse-partial-sexp (save-excursion - (beginning-of-python-def-or-class) - (point)) - (point)))) - (not (or (nth 3 pps) (nth 4 pps))))) - (save-excursion - (let ((here (point)) - (outdent 0) - (indent (py-compute-indentation))) - (if (and (not arg) - (py-outdent-p) - (= indent (save-excursion - (forward-line -1) - (py-compute-indentation))) - ) - (setq outdent py-indent-offset)) - ;; Don't indent, only outdent. This assumes that any lines that - ;; are already outdented relative to py-compute-indentation were - ;; put there on purpose. Its highly annoying to have `:' indent - ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is - ;; there a better way to determine this??? - (if (< (current-indentation) indent) nil - (goto-char here) - (beginning-of-line) - (delete-horizontal-space) - (indent-to (- indent outdent)) - ))))) - -(defun py-indent-right (arg) - "Indent the line by one `py-indent-offset' level. -With numeric arg, indent by that many levels. You cannot indent -farther right than the distance the line would be indented by -\\[py-indent-line]." - (interactive "p") - (let ((col (current-indentation)) - (want (* arg py-indent-offset)) - (indent (py-compute-indentation)) - (pos (- (point-max) (point))) - (bol (save-excursion (beginning-of-line) (point)))) - (if (<= (+ col want) indent) - (progn - (beginning-of-line) - (delete-horizontal-space) - (indent-to (+ col want)) - (if (> (- (point-max) pos) (point)) - (goto-char (- (point-max) pos))) - )))) - -(defun py-outdent-left (arg) - "Outdent the line by one `py-indent-offset' level. -With numeric arg, outdent by that many levels. You cannot outdent -farther left than column zero." - (interactive "p") - (let ((col (current-indentation)) - (want (* arg py-indent-offset)) - (pos (- (point-max) (point))) - (bol (save-excursion (beginning-of-line) (point)))) - (if (<= 0 (- col want)) - (progn - (beginning-of-line) - (delete-horizontal-space) - (indent-to (- col want)) - (if (> (- (point-max) pos) (point)) - (goto-char (- (point-max) pos))) - )))) - - -;;; Functions that execute Python commands in a subprocess -(defun py-shell () - "Start an interactive Python interpreter in another window. -This is like Shell mode, except that Python is running in the window -instead of a shell. See the `Interactive Shell' and `Shell Mode' -sections of the Emacs manual for details, especially for the key -bindings active in the `*Python*' buffer. - -See the docs for variable `py-scroll-buffer' for info on scrolling -behavior in the process window. - -Warning: Don't use an interactive Python if you change sys.ps1 or -sys.ps2 from their default values, or if you're running code that -prints `>>> ' or `... ' at the start of a line. `python-mode' can't -distinguish your output from Python's output, and assumes that `>>> ' -at the start of a line is a prompt from Python. Similarly, the Emacs -Shell mode code assumes that both `>>> ' and `... ' at the start of a -line are Python prompts. Bad things can happen if you fool either -mode. - -Warning: If you do any editing *in* the process buffer *while* the -buffer is accepting output from Python, do NOT attempt to `undo' the -changes. Some of the output (nowhere near the parts you changed!) may -be lost if you do. This appears to be an Emacs bug, an unfortunate -interaction between undo and process filters; the same problem exists in -non-Python process buffers using the default (Emacs-supplied) process -filter." - ;; BAW - should undo be disabled in the python process buffer, if - ;; this bug still exists? - (interactive) - (if py-this-is-emacs-19-p - (progn - (require 'comint) - (switch-to-buffer-other-window - (make-comint "Python" py-python-command))) - (progn - (require 'shell) - (switch-to-buffer-other-window - (apply (if (boundp 'make-shell) 'make-shell 'make-comint) - "Python" py-python-command nil)))) - (make-local-variable 'shell-prompt-pattern) - (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ") - (set-process-filter (get-buffer-process (current-buffer)) - 'py-process-filter) - (set-syntax-table py-mode-syntax-table)) - -(defun py-execute-region (start end) - "Send the region between START and END to a Python interpreter. -If there is a *Python* process it is used. - -Hint: If you want to execute part of a Python file several times -\(e.g., perhaps you're developing a function and want to flesh it out -a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to -the region of interest, and send the code to a *Python* process via -`\\[py-execute-buffer]' instead. - -Following are subtleties to note when using a *Python* process: - -If a *Python* process is used, the region is copied into a temporary -file (in directory `py-temp-directory'), and an `execfile' command is -sent to Python naming that file. If you send regions faster than -Python can execute them, `python-mode' will save them into distinct -temp files, and execute the next one in the queue the next time it -sees a `>>> ' prompt from Python. Each time this happens, the process -buffer is popped into a window (if it's not already in some window) so -you can see it, and a comment of the form - - \t## working on region in file <name> ... - -is inserted at the end. - -Caution: No more than 26 regions can be pending at any given time. -This limit is (indirectly) inherited from libc's mktemp(3). -`python-mode' does not try to protect you from exceeding the limit. -It's extremely unlikely that you'll get anywhere close to the limit in -practice, unless you're trying to be a jerk <grin>. - -See the `\\[py-shell]' docs for additional warnings." - (interactive "r") - (or (< start end) (error "Region is empty")) - (let ((pyproc (get-process "Python")) - fname) - (if (null pyproc) - (shell-command-on-region start end py-python-command) - ;; else feed it thru a temp file - (setq fname (py-make-temp-name)) - (write-region start end fname nil 'no-msg) - (setq py-file-queue (append py-file-queue (list fname))) - (if (cdr py-file-queue) - (message "File %s queued for execution" fname) - ;; else - (py-execute-file pyproc fname))))) - -(defun py-execute-file (pyproc fname) - (py-append-to-process-buffer - pyproc - (format "## working on region in file %s ...\n" fname)) - (process-send-string pyproc (format "execfile('%s')\n" fname))) - -(defun py-process-filter (pyproc string) - (let ((curbuf (current-buffer)) - (pbuf (process-buffer pyproc)) - (pmark (process-mark pyproc)) - file-finished) - - ;; make sure we switch to a different buffer at least once. if we - ;; *don't* do this, then if the process buffer is in the selected - ;; window, and point is before the end, and lots of output is - ;; coming at a fast pace, then (a) simple cursor-movement commands - ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time - ;; to have a visible effect (the window just doesn't get updated, - ;; sometimes for minutes(!)), and (b) it takes about 5x longer to - ;; get all the process output (until the next python prompt). - ;; - ;; #b makes no sense to me at all. #a almost makes sense: unless - ;; we actually change buffers, set_buffer_internal in buffer.c - ;; doesn't set windows_or_buffers_changed to 1, & that in turn - ;; seems to make the Emacs command loop reluctant to update the - ;; display. Perhaps the default process filter in process.c's - ;; read_process_output has update_mode_lines++ for a similar - ;; reason? beats me ... - - ;; BAW - we want to check to see if this still applies - (if (eq curbuf pbuf) ; mysterious ugly hack - (set-buffer (get-buffer-create "*scratch*"))) - - (set-buffer pbuf) - (let* ((start (point)) - (goback (< start pmark)) - (goend (and (not goback) (= start (point-max)))) - (buffer-read-only nil)) - (goto-char pmark) - (insert string) - (move-marker pmark (point)) - (setq file-finished - (and py-file-queue - (equal ">>> " - (buffer-substring - (prog2 (beginning-of-line) (point) - (goto-char pmark)) - (point))))) - (if goback (goto-char start) - ;; else - (if py-scroll-process-buffer - (let* ((pop-up-windows t) - (pwin (display-buffer pbuf))) - (set-window-point pwin (point))))) - (set-buffer curbuf) - (if file-finished - (progn - (py-delete-file-silently (car py-file-queue)) - (setq py-file-queue (cdr py-file-queue)) - (if py-file-queue - (py-execute-file pyproc (car py-file-queue))))) - (and goend - (progn (set-buffer pbuf) - (goto-char (point-max)))) - ))) - -(defun py-execute-buffer () - "Send the contents of the buffer to a Python interpreter. -If there is a *Python* process buffer it is used. If a clipping -restriction is in effect, only the accessible portion of the buffer is -sent. A trailing newline will be supplied if needed. - -See the `\\[py-execute-region]' docs for an account of some subtleties." - (interactive) - (py-execute-region (point-min) (point-max))) - - - -;; Functions for Python style indentation -(defun py-delete-char () - "Reduce indentation or delete character. -If point is at the leftmost column, deletes the preceding newline. - -Else if point is at the leftmost non-blank character of a line that is -neither a continuation line nor a non-indenting comment line, or if -point is at the end of a blank line, reduces the indentation to match -that of the line that opened the current block of code. The line that -opened the block is displayed in the echo area to help you keep track -of where you are. - -Else the preceding character is deleted, converting a tab to spaces if -needed so that only a single column position is deleted." - (interactive "*") - (if (or (/= (current-indentation) (current-column)) - (bolp) - (py-continuation-line-p) - (looking-at "#[^ \t\n]")) ; non-indenting # - (backward-delete-char-untabify 1) - ;; else indent the same as the colon line that opened the block - - ;; force non-blank so py-goto-block-up doesn't ignore it - (insert-char ?* 1) - (backward-char) - (let ((base-indent 0) ; indentation of base line - (base-text "") ; and text of base line - (base-found-p nil)) - (condition-case nil ; in case no enclosing block - (save-excursion - (py-goto-block-up 'no-mark) - (setq base-indent (current-indentation) - base-text (py-suck-up-leading-text) - base-found-p t)) - (error nil)) - (delete-char 1) ; toss the dummy character - (delete-horizontal-space) - (indent-to base-indent) - (if base-found-p - (message "Closes block: %s" base-text))))) - -;; required for pending-del and delsel modes -(put 'py-delete-char 'delete-selection 'supersede) -(put 'py-delete-char 'pending-delete 'supersede) - -(defun py-indent-line () - "Fix the indentation of the current line according to Python rules." - (interactive) - (let* ((ci (current-indentation)) - (move-to-indentation-p (<= (current-column) ci)) - (need (py-compute-indentation))) - ;; see if we need to outdent - (if (py-outdent-p) - (setq need (- need py-indent-offset))) - (if (/= ci need) - (save-excursion - (beginning-of-line) - (delete-horizontal-space) - (indent-to need))) - (if move-to-indentation-p (back-to-indentation)))) - -(defun py-newline-and-indent () - "Strives to act like the Emacs `newline-and-indent'. -This is just `strives to' because correct indentation can't be computed -from scratch for Python code. In general, deletes the whitespace before -point, inserts a newline, and takes an educated guess as to how you want -the new line indented." - (interactive) - (let ((ci (current-indentation))) - (if (< ci (current-column)) ; if point beyond indentation - (newline-and-indent) - ;; else try to act like newline-and-indent "normally" acts - (beginning-of-line) - (insert-char ?\n 1) - (move-to-column ci)))) - -(defun py-compute-indentation () - (save-excursion - (let ((pps (parse-partial-sexp (save-excursion - (beginning-of-python-def-or-class) - (point)) - (point)))) - (beginning-of-line) - (cond - ;; are we inside a string or comment? - ((or (nth 3 pps) (nth 4 pps)) - (save-excursion - (if (not py-align-multiline-strings-p) 0 - ;; skip back over blank & non-indenting comment lines - ;; note: will skip a blank or non-indenting comment line - ;; that happens to be a continuation line too - (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move) - (back-to-indentation) - (current-column)))) - ;; are we on a continuation line? - ((py-continuation-line-p) - (let ((startpos (point)) - (open-bracket-pos (py-nesting-level)) - endpos searching found) - (if open-bracket-pos - (progn - ;; align with first item in list; else a normal - ;; indent beyond the line with the open bracket - (goto-char (1+ open-bracket-pos)) ; just beyond bracket - ;; is the first list item on the same line? - (skip-chars-forward " \t") - (if (null (memq (following-char) '(?\n ?# ?\\))) - ; yes, so line up with it - (current-column) - ;; first list item on another line, or doesn't exist yet - (forward-line 1) - (while (and (< (point) startpos) - (looking-at "[ \t]*[#\n\\\\]")) ; skip noise - (forward-line 1)) - (if (< (point) startpos) - ;; again mimic the first list item - (current-indentation) - ;; else they're about to enter the first item - (goto-char open-bracket-pos) - (+ (current-indentation) py-indent-offset)))) - - ;; else on backslash continuation line - (forward-line -1) - (if (py-continuation-line-p) ; on at least 3rd line in block - (current-indentation) ; so just continue the pattern - ;; else started on 2nd line in block, so indent more. - ;; if base line is an assignment with a start on a RHS, - ;; indent to 2 beyond the leftmost "="; else skip first - ;; chunk of non-whitespace characters on base line, + 1 more - ;; column - (end-of-line) - (setq endpos (point) searching t) - (back-to-indentation) - (setq startpos (point)) - ;; look at all "=" from left to right, stopping at first - ;; one not nested in a list or string - (while searching - (skip-chars-forward "^=" endpos) - (if (= (point) endpos) - (setq searching nil) - (forward-char 1) - (setq state (parse-partial-sexp startpos (point))) - (if (and (zerop (car state)) ; not in a bracket - (null (nth 3 state))) ; & not in a string - (progn - (setq searching nil) ; done searching in any case - (setq found - (not (or - (eq (following-char) ?=) - (memq (char-after (- (point) 2)) - '(?< ?> ?!))))))))) - (if (or (not found) ; not an assignment - (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash> - (progn - (goto-char startpos) - (skip-chars-forward "^ \t\n"))) - (1+ (current-column)))))) - - ;; not on a continuation line - - ;; if at start of restriction, or on a non-indenting comment - ;; line, assume they intended whatever's there - ((or (bobp) (looking-at "[ \t]*#[^ \t\n]")) - (current-indentation)) - - ;; else indentation based on that of the statement that - ;; precedes us; use the first line of that statement to - ;; establish the base, in case the user forced a non-std - ;; indentation for the continuation lines (if any) - (t - ;; skip back over blank & non-indenting comment lines note: - ;; will skip a blank or non-indenting comment line that - ;; happens to be a continuation line too - (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move) - ;; if we landed inside a string, go to the beginning of that - ;; string. this handles triple quoted, multi-line spanning - ;; strings. - (py-goto-initial-line) - (if (py-statement-opens-block-p) - (+ (current-indentation) py-indent-offset) - (current-indentation))))))) - -(defun py-guess-indent-offset (&optional global) - "Guess a good value for, and change, `py-indent-offset'. -By default (without a prefix arg), makes a buffer-local copy of -`py-indent-offset' with the new value. This will not affect any other -Python buffers. With a prefix arg, changes the global value of -`py-indent-offset'. This affects all Python buffers (that don't have -their own buffer-local copy), both those currently existing and those -created later in the Emacs session. - -Some people use a different value for `py-indent-offset' than you use. -There's no excuse for such foolishness, but sometimes you have to deal -with their ugly code anyway. This function examines the file and sets -`py-indent-offset' to what it thinks it was when they created the -mess. - -Specifically, it searches forward from the statement containing point, -looking for a line that opens a block of code. `py-indent-offset' is -set to the difference in indentation between that line and the Python -statement following it. If the search doesn't succeed going forward, -it's tried again going backward." - (interactive "P") ; raw prefix arg - (let (new-value - (start (point)) - restart - (found nil) - colon-indent) - (py-goto-initial-line) - (while (not (or found (eobp))) - (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move) - (progn - (setq restart (point)) - (py-goto-initial-line) - (if (py-statement-opens-block-p) - (setq found t) - (goto-char restart))))) - (if found - () - (goto-char start) - (py-goto-initial-line) - (while (not (or found (bobp))) - (setq found - (and - (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move) - (or (py-goto-initial-line) t) ; always true -- side effect - (py-statement-opens-block-p))))) - (setq colon-indent (current-indentation) - found (and found (zerop (py-next-statement 1))) - new-value (- (current-indentation) colon-indent)) - (goto-char start) - (if found - (progn - (funcall (if global 'kill-local-variable 'make-local-variable) - 'py-indent-offset) - (setq py-indent-offset new-value) - (message "%s value of py-indent-offset set to %d" - (if global "Global" "Local") - py-indent-offset)) - (error "Sorry, couldn't guess a value for py-indent-offset")))) - -(defun py-shift-region (start end count) - (save-excursion - (goto-char end) (beginning-of-line) (setq end (point)) - (goto-char start) (beginning-of-line) (setq start (point)) - (indent-rigidly start end count))) - -(defun py-shift-region-left (start end &optional count) - "Shift region of Python code to the left. -The lines from the line containing the start of the current region up -to (but not including) the line containing the end of the region are -shifted to the left, by `py-indent-offset' columns. - -If a prefix argument is given, the region is instead shifted by that -many columns." - (interactive "*r\nP") ; region; raw prefix arg - (py-shift-region start end - (- (prefix-numeric-value - (or count py-indent-offset))))) - -(defun py-shift-region-right (start end &optional count) - "Shift region of Python code to the right. -The lines from the line containing the start of the current region up -to (but not including) the line containing the end of the region are -shifted to the right, by `py-indent-offset' columns. - -If a prefix argument is given, the region is instead shifted by that -many columns." - (interactive "*r\nP") ; region; raw prefix arg - (py-shift-region start end (prefix-numeric-value - (or count py-indent-offset)))) - -(defun py-indent-region (start end &optional indent-offset) - "Reindent a region of Python code. -The lines from the line containing the start of the current region up -to (but not including) the line containing the end of the region are -reindented. If the first line of the region has a non-whitespace -character in the first column, the first line is left alone and the -rest of the region is reindented with respect to it. Else the entire -region is reindented with respect to the (closest code or -indenting-comment) statement immediately preceding the region. - -This is useful when code blocks are moved or yanked, when enclosing -control structures are introduced or removed, or to reformat code -using a new value for the indentation offset. - -If a numeric prefix argument is given, it will be used as the value of -the indentation offset. Else the value of `py-indent-offset' will be -used. - -Warning: The region must be consistently indented before this function -is called! This function does not compute proper indentation from -scratch (that's impossible in Python), it merely adjusts the existing -indentation to be correct in context. - -Warning: This function really has no idea what to do with -non-indenting comment lines, and shifts them as if they were indenting -comment lines. Fixing this appears to require telepathy. - -Special cases: whitespace is deleted from blank lines; continuation -lines are shifted by the same amount their initial line was shifted, -in order to preserve their relative indentation with respect to their -initial line; and comment lines beginning in column 1 are ignored." - (interactive "*r\nP") ; region; raw prefix arg - (save-excursion - (goto-char end) (beginning-of-line) (setq end (point-marker)) - (goto-char start) (beginning-of-line) - (let ((py-indent-offset (prefix-numeric-value - (or indent-offset py-indent-offset))) - (indents '(-1)) ; stack of active indent levels - (target-column 0) ; column to which to indent - (base-shifted-by 0) ; amount last base line was shifted - (indent-base (if (looking-at "[ \t\n]") - (py-compute-indentation) - 0)) - ci) - (while (< (point) end) - (setq ci (current-indentation)) - ;; figure out appropriate target column - (cond - ((or (eq (following-char) ?#) ; comment in column 1 - (looking-at "[ \t]*$")) ; entirely blank - (setq target-column 0)) - ((py-continuation-line-p) ; shift relative to base line - (setq target-column (+ ci base-shifted-by))) - (t ; new base line - (if (> ci (car indents)) ; going deeper; push it - (setq indents (cons ci indents)) - ;; else we should have seen this indent before - (setq indents (memq ci indents)) ; pop deeper indents - (if (null indents) - (error "Bad indentation in region, at line %d" - (save-restriction - (widen) - (1+ (count-lines 1 (point))))))) - (setq target-column (+ indent-base - (* py-indent-offset - (- (length indents) 2)))) - (setq base-shifted-by (- target-column ci)))) - ;; shift as needed - (if (/= ci target-column) - (progn - (delete-horizontal-space) - (indent-to target-column))) - (forward-line 1)))) - (set-marker end nil)) - - -;; Functions for moving point -(defun py-previous-statement (count) - "Go to the start of previous Python statement. -If the statement at point is the i'th Python statement, goes to the -start of statement i-COUNT. If there is no such statement, goes to the -first statement. Returns count of statements left to move. -`Statements' do not include blank, comment, or continuation lines." - (interactive "p") ; numeric prefix arg - (if (< count 0) (py-next-statement (- count)) - (py-goto-initial-line) - (let (start) - (while (and - (setq start (point)) ; always true -- side effect - (> count 0) - (zerop (forward-line -1)) - (py-goto-statement-at-or-above)) - (setq count (1- count))) - (if (> count 0) (goto-char start))) - count)) - -(defun py-next-statement (count) - "Go to the start of next Python statement. -If the statement at point is the i'th Python statement, goes to the -start of statement i+COUNT. If there is no such statement, goes to the -last statement. Returns count of statements left to move. `Statements' -do not include blank, comment, or continuation lines." - (interactive "p") ; numeric prefix arg - (if (< count 0) (py-previous-statement (- count)) - (beginning-of-line) - (let (start) - (while (and - (setq start (point)) ; always true -- side effect - (> count 0) - (py-goto-statement-below)) - (setq count (1- count))) - (if (> count 0) (goto-char start))) - count)) - -(defun py-goto-block-up (&optional nomark) - "Move up to start of current block. -Go to the statement that starts the smallest enclosing block; roughly -speaking, this will be the closest preceding statement that ends with a -colon and is indented less than the statement you started on. If -successful, also sets the mark to the starting point. - -`\\[py-mark-block]' can be used afterward to mark the whole code -block, if desired. - -If called from a program, the mark will not be set if optional argument -NOMARK is not nil." - (interactive) - (let ((start (point)) - (found nil) - initial-indent) - (py-goto-initial-line) - ;; if on blank or non-indenting comment line, use the preceding stmt - (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)") - (progn - (py-goto-statement-at-or-above) - (setq found (py-statement-opens-block-p)))) - ;; search back for colon line indented less - (setq initial-indent (current-indentation)) - (if (zerop initial-indent) - ;; force fast exit - (goto-char (point-min))) - (while (not (or found (bobp))) - (setq found - (and - (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move) - (or (py-goto-initial-line) t) ; always true -- side effect - (< (current-indentation) initial-indent) - (py-statement-opens-block-p)))) - (if found - (progn - (or nomark (push-mark start)) - (back-to-indentation)) - (goto-char start) - (error "Enclosing block not found")))) - -(defun beginning-of-python-def-or-class (&optional class) - "Move point to start of def (or class, with prefix arg). - -Searches back for the closest preceding `def'. If you supply a prefix -arg, looks for a `class' instead. The docs assume the `def' case; -just substitute `class' for `def' for the other case. - -If point is in a def statement already, and after the `d', simply -moves point to the start of the statement. - -Else (point is not in a def statement, or at or before the `d' of a -def statement), searches for the closest preceding def statement, and -leaves point at its start. If no such statement can be found, leaves -point at the start of the buffer. - -Returns t iff a def statement is found by these rules. - -Note that doing this command repeatedly will take you closer to the -start of the buffer each time. - -If you want to mark the current def/class, see -`\\[mark-python-def-or-class]'." - (interactive "P") ; raw prefix arg - (let ((at-or-before-p (<= (current-column) (current-indentation))) - (start-of-line (progn (beginning-of-line) (point))) - (start-of-stmt (progn (py-goto-initial-line) (point)))) - (if (or (/= start-of-stmt start-of-line) - (not at-or-before-p)) - (end-of-line)) ; OK to match on this line - (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>") - nil 'move))) - -(defun end-of-python-def-or-class (&optional class) - "Move point beyond end of def (or class, with prefix arg) body. - -By default, looks for an appropriate `def'. If you supply a prefix arg, -looks for a `class' instead. The docs assume the `def' case; just -substitute `class' for `def' for the other case. - -If point is in a def statement already, this is the def we use. - -Else if the def found by `\\[beginning-of-python-def-or-class]' -contains the statement you started on, that's the def we use. - -Else we search forward for the closest following def, and use that. - -If a def can be found by these rules, point is moved to the start of -the line immediately following the def block, and the position of the -start of the def is returned. - -Else point is moved to the end of the buffer, and nil is returned. - -Note that doing this command repeatedly will take you closer to the -end of the buffer each time. - -If you want to mark the current def/class, see -`\\[mark-python-def-or-class]'." - (interactive "P") ; raw prefix arg - (let ((start (progn (py-goto-initial-line) (point))) - (which (if class "class" "def")) - (state 'not-found)) - ;; move point to start of appropriate def/class - (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one - (setq state 'at-beginning) - ;; else see if beginning-of-python-def-or-class hits container - (if (and (beginning-of-python-def-or-class class) - (progn (py-goto-beyond-block) - (> (point) start))) - (setq state 'at-end) - ;; else search forward - (goto-char start) - (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move) - (progn (setq state 'at-beginning) - (beginning-of-line))))) - (cond - ((eq state 'at-beginning) (py-goto-beyond-block) t) - ((eq state 'at-end) t) - ((eq state 'not-found) nil) - (t (error "internal error in end-of-python-def-or-class"))))) - - -;; Functions for marking regions -(defun py-mark-block (&optional extend just-move) - "Mark following block of lines. With prefix arg, mark structure. -Easier to use than explain. It sets the region to an `interesting' -block of succeeding lines. If point is on a blank line, it goes down to -the next non-blank line. That will be the start of the region. The end -of the region depends on the kind of line at the start: - - - If a comment, the region will include all succeeding comment lines up - to (but not including) the next non-comment line (if any). - - - Else if a prefix arg is given, and the line begins one of these - structures: - - if elif else try except finally for while def class - - the region will be set to the body of the structure, including - following blocks that `belong' to it, but excluding trailing blank - and comment lines. E.g., if on a `try' statement, the `try' block - and all (if any) of the following `except' and `finally' blocks - that belong to the `try' structure will be in the region. Ditto - for if/elif/else, for/else and while/else structures, and (a bit - degenerate, since they're always one-block structures) def and - class blocks. - - - Else if no prefix argument is given, and the line begins a Python - block (see list above), and the block is not a `one-liner' (i.e., - the statement ends with a colon, not with code), the region will - include all succeeding lines up to (but not including) the next - code statement (if any) that's indented no more than the starting - line, except that trailing blank and comment lines are excluded. - E.g., if the starting line begins a multi-statement `def' - structure, the region will be set to the full function definition, - but without any trailing `noise' lines. - - - Else the region will include all succeeding lines up to (but not - including) the next blank line, or code or indenting-comment line - indented strictly less than the starting line. Trailing indenting - comment lines are included in this case, but not trailing blank - lines. - -A msg identifying the location of the mark is displayed in the echo -area; or do `\\[exchange-point-and-mark]' to flip down to the end. - -If called from a program, optional argument EXTEND plays the role of -the prefix arg, and if optional argument JUST-MOVE is not nil, just -moves to the end of the block (& does not set mark or display a msg)." - (interactive "P") ; raw prefix arg - (py-goto-initial-line) - ;; skip over blank lines - (while (and - (looking-at "[ \t]*$") ; while blank line - (not (eobp))) ; & somewhere to go - (forward-line 1)) - (if (eobp) - (error "Hit end of buffer without finding a non-blank stmt")) - (let ((initial-pos (point)) - (initial-indent (current-indentation)) - last-pos ; position of last stmt in region - (followers - '((if elif else) (elif elif else) (else) - (try except finally) (except except) (finally) - (for else) (while else) - (def) (class) ) ) - first-symbol next-symbol) - - (cond - ;; if comment line, suck up the following comment lines - ((looking-at "[ \t]*#") - (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment - (re-search-backward "^[ \t]*#") ; and back to last comment in block - (setq last-pos (point))) - - ;; else if line is a block line and EXTEND given, suck up - ;; the whole structure - ((and extend - (setq first-symbol (py-suck-up-first-keyword) ) - (assq first-symbol followers)) - (while (and - (or (py-goto-beyond-block) t) ; side effect - (forward-line -1) ; side effect - (setq last-pos (point)) ; side effect - (py-goto-statement-below) - (= (current-indentation) initial-indent) - (setq next-symbol (py-suck-up-first-keyword)) - (memq next-symbol (cdr (assq first-symbol followers)))) - (setq first-symbol next-symbol))) - - ;; else if line *opens* a block, search for next stmt indented <= - ((py-statement-opens-block-p) - (while (and - (setq last-pos (point)) ; always true -- side effect - (py-goto-statement-below) - (> (current-indentation) initial-indent)) - nil)) - - ;; else plain code line; stop at next blank line, or stmt or - ;; indenting comment line indented < - (t - (while (and - (setq last-pos (point)) ; always true -- side effect - (or (py-goto-beyond-final-line) t) - (not (looking-at "[ \t]*$")) ; stop at blank line - (or - (>= (current-indentation) initial-indent) - (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting # - nil))) - - ;; skip to end of last stmt - (goto-char last-pos) - (py-goto-beyond-final-line) - - ;; set mark & display - (if just-move - () ; just return - (push-mark (point) 'no-msg) - (forward-line -1) - (message "Mark set after: %s" (py-suck-up-leading-text)) - (goto-char initial-pos)))) - -(defun mark-python-def-or-class (&optional class) - "Set region to body of def (or class, with prefix arg) enclosing point. -Pushes the current mark, then point, on the mark ring (all language -modes do this, but although it's handy it's never documented ...). - -In most Emacs language modes, this function bears at least a -hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and -`\\[beginning-of-python-def-or-class]'. - -And in earlier versions of Python mode, all 3 were tightly connected. -Turned out that was more confusing than useful: the `goto start' and -`goto end' commands are usually used to search through a file, and -people expect them to act a lot like `search backward' and `search -forward' string-search commands. But because Python `def' and `class' -can nest to arbitrary levels, finding the smallest def containing -point cannot be done via a simple backward search: the def containing -point may not be the closest preceding def, or even the closest -preceding def that's indented less. The fancy algorithm required is -appropriate for the usual uses of this `mark' command, but not for the -`goto' variations. - -So the def marked by this command may not be the one either of the -`goto' commands find: If point is on a blank or non-indenting comment -line, moves back to start of the closest preceding code statement or -indenting comment line. If this is a `def' statement, that's the def -we use. Else searches for the smallest enclosing `def' block and uses -that. Else signals an error. - -When an enclosing def is found: The mark is left immediately beyond -the last line of the def block. Point is left at the start of the -def, except that: if the def is preceded by a number of comment lines -followed by (at most) one optional blank line, point is left at the -start of the comments; else if the def is preceded by a blank line, -point is left at its start. - -The intent is to mark the containing def/class and its associated -documentation, to make moving and duplicating functions and classes -pleasant." - (interactive "P") ; raw prefix arg - (let ((start (point)) - (which (if class "class" "def"))) - (push-mark start) - (if (not (py-go-up-tree-to-keyword which)) - (progn (goto-char start) - (error "Enclosing %s not found" which)) - ;; else enclosing def/class found - (setq start (point)) - (py-goto-beyond-block) - (push-mark (point)) - (goto-char start) - (if (zerop (forward-line -1)) ; if there is a preceding line - (progn - (if (looking-at "[ \t]*$") ; it's blank - (setq start (point)) ; so reset start point - (goto-char start)) ; else try again - (if (zerop (forward-line -1)) - (if (looking-at "[ \t]*#") ; a comment - ;; look back for non-comment line - ;; tricky: note that the regexp matches a blank - ;; line, cuz \n is in the 2nd character class - (and - (re-search-backward "^[ \t]*[^ \t#]" nil 'move) - (forward-line 1)) - ;; no comment, so go back - (goto-char start)))))))) - -(defun py-comment-region (start end &optional uncomment-p) - "Comment out region of code; with prefix arg, uncomment region. -The lines from the line containing the start of the current region up -to (but not including) the line containing the end of the region are -commented out, by inserting the string `py-block-comment-prefix' at -the start of each line. With a prefix arg, removes -`py-block-comment-prefix' from the start of each line instead." - (interactive "*r\nP") ; region; raw prefix arg - (goto-char end) (beginning-of-line) (setq end (point)) - (goto-char start) (beginning-of-line) (setq start (point)) - (let ((prefix-len (length py-block-comment-prefix)) ) - (save-excursion - (save-restriction - (narrow-to-region start end) - (while (not (eobp)) - (if uncomment-p - (and (string= py-block-comment-prefix - (buffer-substring - (point) (+ (point) prefix-len))) - (delete-char prefix-len)) - (insert py-block-comment-prefix)) - (forward-line 1)))))) - - -;; Documentation functions - -;; dump the long form of the mode blurb; does the usual doc escapes, -;; plus lines of the form ^[vc]:name$ to suck variable & command docs -;; out of the right places, along with the keys they're on & current -;; values -(defun py-dump-help-string (str) - (with-output-to-temp-buffer "*Help*" - (let ((locals (buffer-local-variables)) - funckind funcname func funcdoc - (start 0) mstart end - keys ) - (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start) - (setq mstart (match-beginning 0) end (match-end 0) - funckind (substring str (match-beginning 1) (match-end 1)) - funcname (substring str (match-beginning 2) (match-end 2)) - func (intern funcname)) - (princ (substitute-command-keys (substring str start mstart))) - (cond - ((equal funckind "c") ; command - (setq funcdoc (documentation func) - keys (concat - "Key(s): " - (mapconcat 'key-description - (where-is-internal func py-mode-map) - ", ")))) - ((equal funckind "v") ; variable - (setq funcdoc (substitute-command-keys - (get func 'variable-documentation)) - keys (if (assq func locals) - (concat - "Local/Global values: " - (prin1-to-string (symbol-value func)) - " / " - (prin1-to-string (default-value func))) - (concat - "Value: " - (prin1-to-string (symbol-value func)))))) - (t ; unexpected - (error "Error in py-dump-help-string, tag `%s'" funckind))) - (princ (format "\n-> %s:\t%s\t%s\n\n" - (if (equal funckind "c") "Command" "Variable") - funcname keys)) - (princ funcdoc) - (terpri) - (setq start end)) - (princ (substitute-command-keys (substring str start)))) - (print-help-return-message))) - -(defun py-describe-mode () - "Dump long form of Python-mode docs." - (interactive) - (py-dump-help-string "Major mode for editing Python files. -Knows about Python indentation, tokens, comments and continuation lines. -Paragraphs are separated by blank lines only. - -Major sections below begin with the string `@'; specific function and -variable docs begin with `->'. - -@EXECUTING PYTHON CODE - -\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter -\\[py-execute-region]\tsends the current region -\\[py-shell]\tstarts a Python interpreter window; this will be used by -\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands -%c:py-execute-buffer -%c:py-execute-region -%c:py-shell - -@VARIABLES - -py-indent-offset\tindentation increment -py-block-comment-prefix\tcomment string used by py-comment-region - -py-python-command\tshell command to invoke Python interpreter -py-scroll-process-buffer\talways scroll Python process buffer -py-temp-directory\tdirectory used for temp files (if needed) - -py-beep-if-tab-change\tring the bell if tab-width is changed -%v:py-indent-offset -%v:py-block-comment-prefix -%v:py-python-command -%v:py-scroll-process-buffer -%v:py-temp-directory -%v:py-beep-if-tab-change - -@KINDS OF LINES - -Each physical line in the file is either a `continuation line' (the -preceding line ends with a backslash that's not part of a comment, or -the paren/bracket/brace nesting level at the start of the line is -non-zero, or both) or an `initial line' (everything else). - -An initial line is in turn a `blank line' (contains nothing except -possibly blanks or tabs), a `comment line' (leftmost non-blank -character is `#'), or a `code line' (everything else). - -Comment Lines - -Although all comment lines are treated alike by Python, Python mode -recognizes two kinds that act differently with respect to indentation. - -An `indenting comment line' is a comment line with a blank, tab or -nothing after the initial `#'. The indentation commands (see below) -treat these exactly as if they were code lines: a line following an -indenting comment line will be indented like the comment line. All -other comment lines (those with a non-whitespace character immediately -following the initial `#') are `non-indenting comment lines', and -their indentation is ignored by the indentation commands. - -Indenting comment lines are by far the usual case, and should be used -whenever possible. Non-indenting comment lines are useful in cases -like these: - -\ta = b # a very wordy single-line comment that ends up being -\t #... continued onto another line - -\tif a == b: -##\t\tprint 'panic!' # old code we've `commented out' -\t\treturn a - -Since the `#...' and `##' comment lines have a non-whitespace -character following the initial `#', Python mode ignores them when -computing the proper indentation for the next line. - -Continuation Lines and Statements - -The Python-mode commands generally work on statements instead of on -individual lines, where a `statement' is a comment or blank line, or a -code line and all of its following continuation lines (if any) -considered as a single logical unit. The commands in this mode -generally (when it makes sense) automatically move to the start of the -statement containing point, even if point happens to be in the middle -of some continuation line. - - -@INDENTATION - -Primarily for entering new code: -\t\\[indent-for-tab-command]\t indent line appropriately -\t\\[py-newline-and-indent]\t insert newline, then indent -\t\\[py-delete-char]\t reduce indentation, or delete single character - -Primarily for reindenting existing code: -\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally -\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally - -\t\\[py-indent-region]\t reindent region to match its context -\t\\[py-shift-region-left]\t shift region left by py-indent-offset -\t\\[py-shift-region-right]\t shift region right by py-indent-offset - -Unlike most programming languages, Python uses indentation, and only -indentation, to specify block structure. Hence the indentation supplied -automatically by Python-mode is just an educated guess: only you know -the block structure you intend, so only you can supply correct -indentation. - -The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on -the indentation of preceding statements. E.g., assuming -py-indent-offset is 4, after you enter -\tif a > 0: \\[py-newline-and-indent] -the cursor will be moved to the position of the `_' (_ is not a -character in the file, it's just used here to indicate the location of -the cursor): -\tif a > 0: -\t _ -If you then enter `c = d' \\[py-newline-and-indent], the cursor will move -to -\tif a > 0: -\t c = d -\t _ -Python-mode cannot know whether that's what you intended, or whether -\tif a > 0: -\t c = d -\t_ -was your intent. In general, Python-mode either reproduces the -indentation of the (closest code or indenting-comment) preceding -statement, or adds an extra py-indent-offset blanks if the preceding -statement has `:' as its last significant (non-whitespace and non- -comment) character. If the suggested indentation is too much, use -\\[py-delete-char] to reduce it. - -Continuation lines are given extra indentation. If you don't like the -suggested indentation, change it to something you do like, and Python- -mode will strive to indent later lines of the statement in the same way. - -If a line is a continuation line by virtue of being in an unclosed -paren/bracket/brace structure (`list', for short), the suggested -indentation depends on whether the current line contains the first item -in the list. If it does, it's indented py-indent-offset columns beyond -the indentation of the line containing the open bracket. If you don't -like that, change it by hand. The remaining items in the list will mimic -whatever indentation you give to the first item. - -If a line is a continuation line because the line preceding it ends with -a backslash, the third and following lines of the statement inherit their -indentation from the line preceding them. The indentation of the second -line in the statement depends on the form of the first (base) line: if -the base line is an assignment statement with anything more interesting -than the backslash following the leftmost assigning `=', the second line -is indented two columns beyond that `='. Else it's indented to two -columns beyond the leftmost solid chunk of non-whitespace characters on -the base line. - -Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command] -repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block -structure you intend. -%c:indent-for-tab-command -%c:py-newline-and-indent -%c:py-delete-char - - -The next function may be handy when editing code you didn't write: -%c:py-guess-indent-offset - - -The remaining `indent' functions apply to a region of Python code. They -assume the block structure (equals indentation, in Python) of the region -is correct, and alter the indentation in various ways while preserving -the block structure: -%c:py-indent-region -%c:py-shift-region-left -%c:py-shift-region-right - -@MARKING & MANIPULATING REGIONS OF CODE - -\\[py-mark-block]\t mark block of lines -\\[mark-python-def-or-class]\t mark smallest enclosing def -\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class -\\[py-comment-region]\t comment out region of code -\\[universal-argument] \\[py-comment-region]\t uncomment region of code -%c:py-mark-block -%c:mark-python-def-or-class -%c:py-comment-region - -@MOVING POINT - -\\[py-previous-statement]\t move to statement preceding point -\\[py-next-statement]\t move to statement following point -\\[py-goto-block-up]\t move up to start of current block -\\[beginning-of-python-def-or-class]\t move to start of def -\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class -\\[end-of-python-def-or-class]\t move to end of def -\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class - -The first two move to one statement beyond the statement that contains -point. A numeric prefix argument tells them to move that many -statements instead. Blank lines, comment lines, and continuation lines -do not count as `statements' for these commands. So, e.g., you can go -to the first code statement in a file by entering -\t\\[beginning-of-buffer]\t to move to the top of the file -\t\\[py-next-statement]\t to skip over initial comments and blank lines -Or do `\\[py-previous-statement]' with a huge prefix argument. -%c:py-previous-statement -%c:py-next-statement -%c:py-goto-block-up -%c:beginning-of-python-def-or-class -%c:end-of-python-def-or-class - -@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE - -`\\[indent-new-comment-line]' is handy for entering a multi-line comment. - -`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the -overall class and def structure of a module. - -`\\[back-to-indentation]' moves point to a line's first non-blank character. - -`\\[indent-relative]' is handy for creating odd indentation. - -@OTHER EMACS HINTS - -If you don't like the default value of a variable, change its value to -whatever you do like by putting a `setq' line in your .emacs file. -E.g., to set the indentation increment to 4, put this line in your -.emacs: -\t(setq py-indent-offset 4) -To see the value of a variable, do `\\[describe-variable]' and enter the variable -name at the prompt. - -When entering a key sequence like `C-c C-n', it is not necessary to -release the CONTROL key after doing the `C-c' part -- it suffices to -press the CONTROL key, press and release `c' (while still holding down -CONTROL), press and release `n' (while still holding down CONTROL), & -then release CONTROL. - -Entering Python mode calls with no arguments the value of the variable -`python-mode-hook', if that value exists and is not nil; for backward -compatibility it also tries `py-mode-hook'; see the `Hooks' section of -the Elisp manual for details. - -Obscure: When python-mode is first loaded, it looks for all bindings -to newline-and-indent in the global keymap, and shadows them with -local bindings to py-newline-and-indent.")) - - -;; Helper functions -(defvar py-parse-state-re - (concat - "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>" - "\\|" - "^[^ #\t\n]")) - -;; returns the parse state at point (see parse-partial-sexp docs) -(defun py-parse-state () - (save-excursion - (let ((here (point)) ) - ;; back up to the first preceding line (if any; else start of - ;; buffer) that begins with a popular Python keyword, or a non- - ;; whitespace and non-comment character. These are good places - ;; to start parsing to see whether where we started is at a - ;; non-zero nesting level. It may be slow for people who write - ;; huge code blocks or huge lists ... tough beans. - (re-search-backward py-parse-state-re nil 'move) - (beginning-of-line) - (parse-partial-sexp (point) here)))) - -;; if point is at a non-zero nesting level, returns the number of the -;; character that opens the smallest enclosing unclosed list; else -;; returns nil. -(defun py-nesting-level () - (let ((status (py-parse-state)) ) - (if (zerop (car status)) - nil ; not in a nest - (car (cdr status))))) ; char# of open bracket - -;; t iff preceding line ends with backslash that's not in a comment -(defun py-backslash-continuation-line-p () - (save-excursion - (beginning-of-line) - (and - ;; use a cheap test first to avoid the regexp if possible - ;; use 'eq' because char-after may return nil - (eq (char-after (- (point) 2)) ?\\ ) - ;; make sure; since eq test passed, there is a preceding line - (forward-line -1) ; always true -- side effect - (looking-at py-continued-re)))) - -;; t iff current line is a continuation line -(defun py-continuation-line-p () - (save-excursion - (beginning-of-line) - (or (py-backslash-continuation-line-p) - (py-nesting-level)))) - -;; go to initial line of current statement; usually this is the line -;; we're on, but if we're on the 2nd or following lines of a -;; continuation block, we need to go up to the first line of the -;; block. -;; -;; Tricky: We want to avoid quadratic-time behavior for long continued -;; blocks, whether of the backslash or open-bracket varieties, or a -;; mix of the two. The following manages to do that in the usual -;; cases. -(defun py-goto-initial-line () - (let ( open-bracket-pos ) - (while (py-continuation-line-p) - (beginning-of-line) - (if (py-backslash-continuation-line-p) - (while (py-backslash-continuation-line-p) - (forward-line -1)) - ;; else zip out of nested brackets/braces/parens - (while (setq open-bracket-pos (py-nesting-level)) - (goto-char open-bracket-pos))))) - (beginning-of-line)) - -;; go to point right beyond final line of current statement; usually -;; this is the start of the next line, but if this is a multi-line -;; statement we need to skip over the continuation lines. Tricky: -;; Again we need to be clever to avoid quadratic time behavior. -(defun py-goto-beyond-final-line () - (forward-line 1) - (let (state) - (while (and (py-continuation-line-p) - (not (eobp))) - ;; skip over the backslash flavor - (while (and (py-backslash-continuation-line-p) - (not (eobp))) - (forward-line 1)) - ;; if in nest, zip to the end of the nest - (setq state (py-parse-state)) - (if (and (not (zerop (car state))) - (not (eobp))) - (progn - ;; BUG ALERT: I could swear, from reading the docs, that - ;; the 3rd argument should be plain 0 - (parse-partial-sexp (point) (point-max) (- 0 (car state)) - nil state) - (forward-line 1)))))) - -;; t iff statement opens a block == iff it ends with a colon that's -;; not in a comment. point should be at the start of a statement -(defun py-statement-opens-block-p () - (save-excursion - (let ((start (point)) - (finish (progn (py-goto-beyond-final-line) (1- (point)))) - (searching t) - (answer nil) - state) - (goto-char start) - (while searching - ;; look for a colon with nothing after it except whitespace, and - ;; maybe a comment - (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$" - finish t) - (if (eq (point) finish) ; note: no `else' clause; just - ; keep searching if we're not at - ; the end yet - ;; sure looks like it opens a block -- but it might - ;; be in a comment - (progn - (setq searching nil) ; search is done either way - (setq state (parse-partial-sexp start - (match-beginning 0))) - (setq answer (not (nth 4 state))))) - ;; search failed: couldn't find another interesting colon - (setq searching nil))) - answer))) - -;; go to point right beyond final line of block begun by the current -;; line. This is the same as where py-goto-beyond-final-line goes -;; unless we're on colon line, in which case we go to the end of the -;; block. assumes point is at bolp -(defun py-goto-beyond-block () - (if (py-statement-opens-block-p) - (py-mark-block nil 'just-move) - (py-goto-beyond-final-line))) - -;; go to start of first statement (not blank or comment or -;; continuation line) at or preceding point. returns t if there is -;; one, else nil -(defun py-goto-statement-at-or-above () - (py-goto-initial-line) - (if (looking-at py-blank-or-comment-re) - ;; skip back over blank & comment lines - ;; note: will skip a blank or comment line that happens to be - ;; a continuation line too - (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t) - (progn (py-goto-initial-line) t) - nil) - t)) - -;; go to start of first statement (not blank or comment or -;; continuation line) following the statement containing point returns -;; t if there is one, else nil -(defun py-goto-statement-below () - (beginning-of-line) - (let ((start (point))) - (py-goto-beyond-final-line) - (while (and - (looking-at py-blank-or-comment-re) - (not (eobp))) - (forward-line 1)) - (if (eobp) - (progn (goto-char start) nil) - t))) - -;; go to start of statement, at or preceding point, starting with -;; keyword KEY. Skips blank lines and non-indenting comments upward -;; first. If that statement starts with KEY, done, else go back to -;; first enclosing block starting with KEY. If successful, leaves -;; point at the start of the KEY line & returns t. Else leaves point -;; at an undefined place & returns nil. -(defun py-go-up-tree-to-keyword (key) - ;; skip blanks and non-indenting # - (py-goto-initial-line) - (while (and - (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)") - (zerop (forward-line -1))) ; go back - nil) - (py-goto-initial-line) - (let* ((re (concat "[ \t]*" key "\\b")) - (case-fold-search nil) ; let* so looking-at sees this - (found (looking-at re)) - (dead nil)) - (while (not (or found dead)) - (condition-case nil ; in case no enclosing block - (py-goto-block-up 'no-mark) - (error (setq dead t))) - (or dead (setq found (looking-at re)))) - (beginning-of-line) - found)) - -;; return string in buffer from start of indentation to end of line; -;; prefix "..." if leading whitespace was skipped -(defun py-suck-up-leading-text () - (save-excursion - (back-to-indentation) - (concat - (if (bolp) "" "...") - (buffer-substring (point) (progn (end-of-line) (point)))))) - -;; assuming point at bolp, return first keyword ([a-z]+) on the line, -;; as a Lisp symbol; return nil if none -(defun py-suck-up-first-keyword () - (let ((case-fold-search nil)) - (if (looking-at "[ \t]*\\([a-z]+\\)\\b") - (intern (buffer-substring (match-beginning 1) (match-end 1))) - nil))) - -(defun py-make-temp-name () - (make-temp-name - (concat (file-name-as-directory py-temp-directory) "python"))) - -(defun py-delete-file-silently (fname) - (condition-case nil - (delete-file fname) - (error nil))) - -(defun py-kill-emacs-hook () - ;; delete our temp files - (while py-file-queue - (py-delete-file-silently (car py-file-queue)) - (setq py-file-queue (cdr py-file-queue))) - (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)) - ;; run the hook we inherited, if any - (and py-inherited-kill-emacs-hook - (funcall py-inherited-kill-emacs-hook)))) - -;; make PROCESS's buffer visible, append STRING to it, and force -;; display; also make shell-mode believe the user typed this string, -;; so that kill-output-from-shell and show-output-from-shell work -;; "right" -(defun py-append-to-process-buffer (process string) - (let ((cbuf (current-buffer)) - (pbuf (process-buffer process)) - (py-scroll-process-buffer t)) - (set-buffer pbuf) - (goto-char (point-max)) - (move-marker (process-mark process) (point)) - (if (not (or py-this-is-emacs-19-p - py-this-is-lucid-emacs-p)) - (move-marker last-input-start (point))) ; muck w/ shell-mode - (funcall (process-filter process) process string) - (if (not (or py-this-is-emacs-19-p - py-this-is-lucid-emacs-p)) - (move-marker last-input-end (point))) ; muck w/ shell-mode - (set-buffer cbuf)) - (sit-for 0)) - -(defun py-keep-region-active () - ;; do whatever is necessary to keep the region active in XEmacs. - ;; Ignore byte-compiler warnings you might see. Also note that - ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't - ;; require us to take explicit action. - (and (boundp 'zmacs-region-stays) - (setq zmacs-region-stays t))) - - -(defconst py-version "2.30" - "`python-mode' version number.") -(defconst py-help-address "python-mode@python.org" - "Address accepting submission of bug reports.") - -(defun py-version () - "Echo the current version of `python-mode' in the minibuffer." - (interactive) - (message "Using `python-mode' version %s" py-version) - (py-keep-region-active)) - -;; only works under Emacs 19 -;(eval-when-compile -; (require 'reporter)) - -(defun py-submit-bug-report (enhancement-p) - "Submit via mail a bug report on `python-mode'. -With \\[universal-argument] just submit an enhancement request." - (interactive - (list (not (y-or-n-p - "Is this a bug report? (hit `n' to send other comments) ")))) - (let ((reporter-prompt-for-summary-p (if enhancement-p - "(Very) brief summary: " - t))) - (require 'reporter) - (reporter-submit-bug-report - py-help-address ;address - (concat "python-mode " py-version) ;pkgname - ;; varlist - (if enhancement-p nil - '(py-python-command - py-indent-offset - py-block-comment-prefix - py-scroll-process-buffer - py-temp-directory - py-beep-if-tab-change)) - nil ;pre-hooks - nil ;post-hooks - "Dear Barry,") ;salutation - (if enhancement-p nil - (set-mark (point)) - (insert -"Please replace this text with a sufficiently large code sample\n\ -and an exact recipe so that I can reproduce your problem. Failure\n\ -to do so may mean a greater delay in fixing your bug.\n\n") - (exchange-point-and-mark) - (py-keep-region-active)))) - - -;; arrange to kill temp files when Emacs exists -(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p) - (add-hook 'kill-emacs-hook 'py-kill-emacs-hook) - ;; have to trust that other people are as respectful of our hook - ;; fiddling as we are of theirs - (if (boundp 'py-inherited-kill-emacs-hook) - ;; we were loaded before -- trust others not to have screwed us - ;; in the meantime (no choice, really) - nil - ;; else arrange for our hook to run theirs - (setq py-inherited-kill-emacs-hook kill-emacs-hook) - (setq kill-emacs-hook 'py-kill-emacs-hook))) - - - -(provide 'python-mode) -;;; python-mode.el ends here diff --git a/Misc/python-mode.el b/Misc/python-mode.el deleted file mode 100644 index 8e4e199e3c..0000000000 --- a/Misc/python-mode.el +++ /dev/null @@ -1,2075 +0,0 @@ -;;; python-mode.el --- Major mode for editing Python programs - -;; Copyright (C) 1992,1993,1994 Tim Peters - -;; Author: 1995-1996 Barry A. Warsaw -;; 1992-1994 Tim Peters -;; Maintainer: python-mode@python.org -;; Created: Feb 1992 -;; Version: $Revision$ -;; Last Modified: $Date$ -;; Keywords: python languages oop - -;; This software is provided as-is, without express or implied -;; warranty. Permission to use, copy, modify, distribute or sell this -;; software, without fee, for any purpose and by any individual or -;; organization, is hereby granted, provided that the above copyright -;; notice and this paragraph appear in all copies. - -;;; Commentary: -;; -;; This is a major mode for editing Python programs. It was developed -;; by Tim Peters <tim@ksr.com> after an original idea by Michael -;; A. Guravage. Tim doesn't appear to be on the 'net any longer so I -;; (Barry) have undertaken maintenance of the mode. - -;; At some point this mode will undergo a rewrite to bring it more in -;; line with GNU Emacs Lisp coding standards. But all in all, the -;; mode works exceedingly well, and I've simply been tweeking it as I -;; go along. Ain't it wonderful that Python has a much more sane -;; syntax than C? (or <shudder> C++?! :-). - -;; The following statements, placed in your .emacs file or -;; site-init.el, will cause this file to be autoloaded, and -;; python-mode invoked, when visiting .py files (assuming this file is -;; in your load-path): -;; -;; (autoload 'python-mode "python-mode" "Python editing mode." t) -;; (setq auto-mode-alist -;; (cons '("\\.py$" . python-mode) auto-mode-alist)) - -;; Here's a brief list of recent additions/improvements: -;; -;; - Wrapping and indentation within triple quote strings should work -;; properly now. -;; - `Standard' bug reporting mechanism (use C-c C-b) -;; - py-mark-block was moved to C-c C-m -;; - C-c C-v shows you the python-mode version -;; - a basic python-font-lock-keywords has been added for Emacs 19 -;; font-lock colorizations. -;; - proper interaction with pending-del and del-sel modes. -;; - New py-electric-colon (:) command for improved outdenting. Also -;; py-indent-line (TAB) should handle outdented lines better. -;; - New commands py-outdent-left (C-c C-l) and py-indent-right (C-c C-r) - -;; Here's a brief to do list: -;; -;; - Better integration with gud-mode for debugging. -;; - Rewrite according to GNU Emacs Lisp standards. -;; - py-delete-char should obey numeric arguments. -;; - even better support for outdenting. Guido suggests outdents of -;; at least one level after a return, raise, break, or continue -;; statement. -;; - de-electrify colon inside literals (e.g. comments and strings) - -;; If you can think of more things you'd like to see, drop me a line. -;; If you want to report bugs, use py-submit-bug-report (C-c C-b). -;; -;; Note that I only test things on XEmacs. If you port stuff to FSF -;; Emacs 19, or Emacs 18, please send me your patches. Byte compiler -;; complaints can probably be safely ignored. - -;; LCD Archive Entry: -;; python-mode|Barry A. Warsaw|python-mode@python.org -;; |Major mode for editing Python programs -;; |$Date$|$Revision$| - -;;; Code: - - -;; user definable variables -;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv - -(defvar py-python-command "python" - "*Shell command used to start Python interpreter.") - -(defvar py-indent-offset 4 - "*Indentation increment. -Note that `\\[py-guess-indent-offset]' can usually guess a good value -when you're editing someone else's Python code.") - -(defvar py-align-multiline-strings-p t - "*Flag describing how multiline triple quoted strings are aligned. -When this flag is non-nil, continuation lines are lined up under the -preceding line's indentation. When this flag is nil, continuation -lines are aligned to column zero.") - -(defvar py-block-comment-prefix "##" - "*String used by \\[comment-region] to comment out a block of code. -This should follow the convention for non-indenting comment lines so -that the indentation commands won't get confused (i.e., the string -should be of the form `#x...' where `x' is not a blank or a tab, and -`...' is arbitrary).") - -(defvar py-honor-comment-indentation t - "*Controls how comment lines influence subsequent indentation. - -When nil, all comment lines are skipped for indentation purposes, and -in Emacs 19, a faster algorithm is used. - -When t, lines that begin with a single `#' are a hint to subsequent -line indentation. If the previous line is such a comment line (as -opposed to one that starts with `py-block-comment-prefix'), then it's -indentation is used as a hint for this line's indentation. Lines that -begin with `py-block-comment-prefix' are ignored for indentation -purposes. - -When not nil or t, comment lines that begin with a `#' are used as -indentation hints, unless the comment character is in column zero.") - -(defvar py-scroll-process-buffer t - "*Scroll Python process buffer as output arrives. -If nil, the Python process buffer acts, with respect to scrolling, like -Shell-mode buffers normally act. This is surprisingly complicated and -so won't be explained here; in fact, you can't get the whole story -without studying the Emacs C code. - -If non-nil, the behavior is different in two respects (which are -slightly inaccurate in the interest of brevity): - - - If the buffer is in a window, and you left point at its end, the - window will scroll as new output arrives, and point will move to the - buffer's end, even if the window is not the selected window (that - being the one the cursor is in). The usual behavior for shell-mode - windows is not to scroll, and to leave point where it was, if the - buffer is in a window other than the selected window. - - - If the buffer is not visible in any window, and you left point at - its end, the buffer will be popped into a window as soon as more - output arrives. This is handy if you have a long-running - computation and don't want to tie up screen area waiting for the - output. The usual behavior for a shell-mode buffer is to stay - invisible until you explicitly visit it. - -Note the `and if you left point at its end' clauses in both of the -above: you can `turn off' the special behaviors while output is in -progress, by visiting the Python buffer and moving point to anywhere -besides the end. Then the buffer won't scroll, point will remain where -you leave it, and if you hide the buffer it will stay hidden until you -visit it again. You can enable and disable the special behaviors as -often as you like, while output is in progress, by (respectively) moving -point to, or away from, the end of the buffer. - -Warning: If you expect a large amount of output, you'll probably be -happier setting this option to nil. - -Obscure: `End of buffer' above should really say `at or beyond the -process mark', but if you know what that means you didn't need to be -told <grin>.") - -(defvar py-temp-directory - (let ((ok '(lambda (x) - (and x - (setq x (expand-file-name x)) ; always true - (file-directory-p x) - (file-writable-p x) - x)))) - (or (funcall ok (getenv "TMPDIR")) - (funcall ok "/usr/tmp") - (funcall ok "/tmp") - (funcall ok ".") - (error - "Couldn't find a usable temp directory -- set py-temp-directory"))) - "*Directory used for temp files created by a *Python* process. -By default, the first directory from this list that exists and that you -can write into: the value (if any) of the environment variable TMPDIR, -/usr/tmp, /tmp, or the current directory.") - -(defvar py-beep-if-tab-change t - "*Ring the bell if tab-width is changed. -If a comment of the form - - \t# vi:set tabsize=<number>: - -is found before the first code line when the file is entered, and the -current value of (the general Emacs variable) `tab-width' does not -equal <number>, `tab-width' is set to <number>, a message saying so is -displayed in the echo area, and if `py-beep-if-tab-change' is non-nil -the Emacs bell is also rung as a warning.") - -(defconst python-font-lock-keywords - (let* ((keywords '("access" "and" "break" "continue" - "del" "elif" "else:" "except" - "except:" "exec" "finally:" "for" - "from" "global" "if" "import" - "in" "is" "lambda" "not" - "or" "pass" "print" "raise" - "return" "try:" "while" - )) - (kwregex (mapconcat 'identity keywords "\\|"))) - (list - ;; keywords not at beginning of line - (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1) - ;; keywords at beginning of line. i don't think regexps are - ;; powerful enough to handle these two cases in one regexp. - ;; prove me wrong! - (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1) - ;; classes - '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)" - 1 font-lock-type-face) - ;; functions - '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)" - 1 font-lock-function-name-face) - )) - "Additional expressions to highlight in Python mode.") - - -;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT - -(make-variable-buffer-local 'py-indent-offset) - -;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This -;; seems to be the standard way of checking this. -;; BAW - This is *not* the right solution. When at all possible, -;; instead of testing for the version of Emacs, use feature tests. - -(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version)) -(setq py-this-is-emacs-19-p - (and - (not py-this-is-lucid-emacs-p) - (string-match "^19\\." emacs-version))) - -;; have to bind py-file-queue before installing the kill-emacs hook -(defvar py-file-queue nil - "Queue of Python temp files awaiting execution. -Currently-active file is at the head of the list.") - -;; define a mode-specific abbrev table for those who use such things -(defvar python-mode-abbrev-table nil - "Abbrev table in use in `python-mode' buffers.") -(define-abbrev-table 'python-mode-abbrev-table nil) - -(defvar python-mode-hook nil - "*Hook called by `python-mode'.") - -;; in previous version of python-mode.el, the hook was incorrectly -;; called py-mode-hook, and was not defvar'd. deprecate its use. -(and (fboundp 'make-obsolete-variable) - (make-obsolete-variable 'py-mode-hook 'python-mode-hook)) - -(defvar py-mode-map () - "Keymap used in `python-mode' buffers.") - -(if py-mode-map - () - (setq py-mode-map (make-sparse-keymap)) - - ;; shadow global bindings for newline-and-indent w/ the py- version. - ;; BAW - this is extremely bad form, but I'm not going to change it - ;; for now. - (mapcar (function (lambda (key) - (define-key - py-mode-map key 'py-newline-and-indent))) - (where-is-internal 'newline-and-indent)) - - ;; BAW - you could do it this way, but its not considered proper - ;; major-mode form. - (mapcar (function - (lambda (x) - (define-key py-mode-map (car x) (cdr x)))) - '((":" . py-electric-colon) - ("\C-c\C-c" . py-execute-buffer) - ("\C-c|" . py-execute-region) - ("\C-c!" . py-shell) - ("\177" . py-delete-char) - ("\n" . py-newline-and-indent) - ("\C-c:" . py-guess-indent-offset) - ("\C-c\t" . py-indent-region) - ("\C-c\C-l" . py-outdent-left) - ("\C-c\C-r" . py-indent-right) - ("\C-c<" . py-shift-region-left) - ("\C-c>" . py-shift-region-right) - ("\C-c\C-n" . py-next-statement) - ("\C-c\C-p" . py-previous-statement) - ("\C-c\C-u" . py-goto-block-up) - ("\C-c\C-m" . py-mark-block) - ("\C-c#" . comment-region) - ("\C-c?" . py-describe-mode) - ("\C-c\C-hm" . py-describe-mode) - ("\e\C-a" . beginning-of-python-def-or-class) - ("\e\C-e" . end-of-python-def-or-class) - ( "\e\C-h" . mark-python-def-or-class))) - ;; should do all keybindings this way - (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report) - (define-key py-mode-map "\C-c\C-v" 'py-version) - ) - -(defvar py-mode-syntax-table nil - "Syntax table used in `python-mode' buffers.") - -(if py-mode-syntax-table - () - (setq py-mode-syntax-table (make-syntax-table)) - ;; BAW - again, blech. - (mapcar (function - (lambda (x) (modify-syntax-entry - (car x) (cdr x) py-mode-syntax-table))) - '(( ?\( . "()" ) ( ?\) . ")(" ) - ( ?\[ . "(]" ) ( ?\] . ")[" ) - ( ?\{ . "(}" ) ( ?\} . "){" ) - ;; fix operator symbols misassigned in the std table - ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." ) - ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." ) - ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." ) - ( ?\> . "." ) ( ?\| . "." ) - ( ?\_ . "_" ) ; underscore is legit in symbols, but not words - ( ?\' . "\"") ; single quote is string quote - ( ?\" . "\"" ) ; double quote is string quote too - ( ?\` . "$") ; backquote is open and close paren - ( ?\# . "<") ; hash starts comment - ( ?\n . ">")))) ; newline ends comment - -(defconst py-stringlit-re - (concat - "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted - "\\|" ; or - "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted - "Regexp matching a Python string literal.") - -;; this is tricky because a trailing backslash does not mean -;; continuation if it's in a comment -(defconst py-continued-re - (concat - "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*" - "\\\\$") - "Regexp matching Python lines that are continued via backslash.") - -(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)" - "Regexp matching blank or comment lines.") - -(defconst py-outdent-re - (concat "\\(" (mapconcat 'identity - '("else:" - "except\\(\\s +.*\\)?:" - "finally:" - "elif\\s +.*:") - "\\|") - "\\)") - "Regexp matching clauses to be outdented one level.") - -(defconst py-no-outdent-re - (concat "\\(" (mapconcat 'identity - '("try:" - "except\\(\\s +.*\\)?:" - "while\\s +.*:" - "for\\s +.*:" - "if\\s +.*:" - "elif\\s +.*:") - "\\|") - "\\)") - "Regexp matching lines to not outdent after.") - - -;;;###autoload -(defun python-mode () - "Major mode for editing Python files. -To submit a problem report, enter `\\[py-submit-bug-report]' from a -`python-mode' buffer. Do `\\[py-describe-mode]' for detailed -documentation. To see what version of `python-mode' you are running, -enter `\\[py-version]'. - -This mode knows about Python indentation, tokens, comments and -continuation lines. Paragraphs are separated by blank lines only. - -COMMANDS -\\{py-mode-map} -VARIABLES - -py-indent-offset\tindentation increment -py-block-comment-prefix\tcomment string used by py-comment-region -py-python-command\tshell command to invoke Python interpreter -py-scroll-process-buffer\talways scroll Python process buffer -py-temp-directory\tdirectory used for temp files (if needed) -py-beep-if-tab-change\tring the bell if tab-width is changed" - (interactive) - (kill-all-local-variables) - (set-syntax-table py-mode-syntax-table) - (setq major-mode 'python-mode - mode-name "Python" - local-abbrev-table python-mode-abbrev-table) - (use-local-map py-mode-map) - ;; Emacs 19 requires this - (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p) - (setq comment-multi-line nil)) - ;; BAW -- style... - (mapcar (function (lambda (x) - (make-local-variable (car x)) - (set (car x) (cdr x)))) - '((paragraph-separate . "^[ \t]*$") - (paragraph-start . "^[ \t]*$") - (require-final-newline . t) - (comment-start . "## ") - (comment-start-skip . "# *") - (comment-column . 40) - (indent-region-function . py-indent-region) - (indent-line-function . py-indent-line))) - ;; hack to allow overriding the tabsize in the file (see tokenizer.c) - ;; - ;; not sure where the magic comment has to be; to save time - ;; searching for a rarity, we give up if it's not found prior to the - ;; first executable statement. - ;; - ;; BAW - on first glance, this seems like complete hackery. Why was - ;; this necessary, and is it still necessary? - (let ((case-fold-search nil) - (start (point)) - new-tab-width) - (if (re-search-forward - "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):" - (prog2 (py-next-statement 1) (point) (goto-char 1)) - t) - (progn - (setq new-tab-width - (string-to-int - (buffer-substring (match-beginning 1) (match-end 1)))) - (if (= tab-width new-tab-width) - nil - (setq tab-width new-tab-width) - (message "Caution: tab-width changed to %d" new-tab-width) - (if py-beep-if-tab-change (beep))))) - (goto-char start)) - - ;; run the mode hook. py-mode-hook use is deprecated - (if python-mode-hook - (run-hooks 'python-mode-hook) - (run-hooks 'py-mode-hook))) - - -(defun py-keep-region-active () - ;; Do whatever is necessary to keep the region active in - ;; XEmacs 19. This is unnecessary, but no-op in Emacs 19, so just - ;; ignore byte-compiler warnings you might see. - (and (boundp 'zmacs-region-stays) - (setq zmacs-region-stays t))) - -;; electric characters -(defun py-outdent-p () - ;; returns non-nil if the current line should outdent one level - (save-excursion - (and (progn (back-to-indentation) - (looking-at py-outdent-re)) - (progn (backward-to-indentation 1) - (while (or (looking-at py-blank-or-comment-re) - (bobp)) - (backward-to-indentation 1)) - (not (looking-at py-no-outdent-re))) - ))) - - -(defun py-electric-colon (arg) - "Insert a colon. -In certain cases the line is outdented appropriately. If a numeric -argument is provided, that many colons are inserted non-electrically. -Electric behavior is inhibited inside a string or comment." - (interactive "P") - (self-insert-command (prefix-numeric-value arg)) - ;; are we in a string or comment? - (if (save-excursion - (let ((pps (parse-partial-sexp (save-excursion - (beginning-of-python-def-or-class) - (point)) - (point)))) - (not (or (nth 3 pps) (nth 4 pps))))) - (save-excursion - (let ((here (point)) - (outdent 0) - (indent (py-compute-indentation))) - (if (and (not arg) - (py-outdent-p) - (= indent (save-excursion - (forward-line -1) - (py-compute-indentation))) - ) - (setq outdent py-indent-offset)) - ;; Don't indent, only outdent. This assumes that any lines that - ;; are already outdented relative to py-compute-indentation were - ;; put there on purpose. Its highly annoying to have `:' indent - ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is - ;; there a better way to determine this??? - (if (< (current-indentation) indent) nil - (goto-char here) - (beginning-of-line) - (delete-horizontal-space) - (indent-to (- indent outdent)) - ))))) - -(defun py-indent-right (start end arg) - "Indent lines in the region by one `py-indent-offset' level. -With numeric arg, indent by that many levels. You cannot indent -farther right than the distance the line would be indented by -\\[py-indent-line]. With no active region, indent only the -current line." - (interactive - (let ((p (point)) - (m (mark)) - (arg (prefix-numeric-value current-prefix-arg))) - (if m - (list (min p m) (max p m) arg) - (list p m arg)))) - (let* ((dir (= (point) start)) - (pos (if dir (point) - (- (point-max) (point)))) - (end (save-excursion - (goto-char (or end (1+ start))) - (and (not (bolp)) - (forward-line 1)) - (set-marker (make-marker) (point)))) - col want indent) - (goto-char start) - (beginning-of-line) - (unwind-protect - (while (< (point) end) - (setq col (current-indentation) - want (* arg py-indent-offset) - indent (py-compute-indentation)) - (if (<= (+ col want) indent) - (progn - (beginning-of-line) - (delete-horizontal-space) - (indent-to (+ col want)))) - (forward-line 1)) - (set-marker end nil)) - (goto-char (if dir pos - (- (point-max) pos))) - (py-keep-region-active))) - -(defun py-outdent-left (start end arg) - "Outdent lines in the region by one `py-indent-offset' level. -With numeric arg, outdent by that many levels. You cannot outdent -farther left than column zero. With no active region, outdent only -the current line." - (interactive - (let ((p (point)) - (m (mark)) - (arg (prefix-numeric-value current-prefix-arg))) - (if m - (list (min p m) (max p m) arg) - (list p m arg)))) - (let* ((dir (= (point) start)) - (pos (if dir (point) - (- (point-max) (point)))) - (end (save-excursion - (goto-char (or end (1+ start))) - (and (not (bolp)) - (forward-line 1)) - (set-marker (make-marker) (point)))) - col want) - (goto-char start) - (beginning-of-line) - (unwind-protect - (while (< (point) end) - (setq col (current-indentation) - want (* arg py-indent-offset)) - (if (<= 0 (- col want)) - (progn - (beginning-of-line) - (delete-horizontal-space) - (indent-to (- col want)))) - (forward-line 1)) - (set-marker end nil)) - (goto-char (if dir pos - (- (point-max) pos))) - (py-keep-region-active))) - - -;;; Functions that execute Python commands in a subprocess -(defun py-shell () - "Start an interactive Python interpreter in another window. -This is like Shell mode, except that Python is running in the window -instead of a shell. See the `Interactive Shell' and `Shell Mode' -sections of the Emacs manual for details, especially for the key -bindings active in the `*Python*' buffer. - -See the docs for variable `py-scroll-buffer' for info on scrolling -behavior in the process window. - -Warning: Don't use an interactive Python if you change sys.ps1 or -sys.ps2 from their default values, or if you're running code that -prints `>>> ' or `... ' at the start of a line. `python-mode' can't -distinguish your output from Python's output, and assumes that `>>> ' -at the start of a line is a prompt from Python. Similarly, the Emacs -Shell mode code assumes that both `>>> ' and `... ' at the start of a -line are Python prompts. Bad things can happen if you fool either -mode. - -Warning: If you do any editing *in* the process buffer *while* the -buffer is accepting output from Python, do NOT attempt to `undo' the -changes. Some of the output (nowhere near the parts you changed!) may -be lost if you do. This appears to be an Emacs bug, an unfortunate -interaction between undo and process filters; the same problem exists in -non-Python process buffers using the default (Emacs-supplied) process -filter." - ;; BAW - should undo be disabled in the python process buffer, if - ;; this bug still exists? - (interactive) - (if py-this-is-emacs-19-p - (progn - (require 'comint) - (switch-to-buffer-other-window - (make-comint "Python" py-python-command))) - (progn - (require 'shell) - (switch-to-buffer-other-window - (apply (if (fboundp 'make-shell) 'make-shell 'make-comint) - "Python" py-python-command nil)))) - (make-local-variable 'shell-prompt-pattern) - (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ") - (set-process-filter (get-buffer-process (current-buffer)) - 'py-process-filter) - (set-syntax-table py-mode-syntax-table)) - -(defun py-execute-region (start end) - "Send the region between START and END to a Python interpreter. -If there is a *Python* process it is used. - -Hint: If you want to execute part of a Python file several times -\(e.g., perhaps you're developing a function and want to flesh it out -a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to -the region of interest, and send the code to a *Python* process via -`\\[py-execute-buffer]' instead. - -Following are subtleties to note when using a *Python* process: - -If a *Python* process is used, the region is copied into a temporary -file (in directory `py-temp-directory'), and an `execfile' command is -sent to Python naming that file. If you send regions faster than -Python can execute them, `python-mode' will save them into distinct -temp files, and execute the next one in the queue the next time it -sees a `>>> ' prompt from Python. Each time this happens, the process -buffer is popped into a window (if it's not already in some window) so -you can see it, and a comment of the form - - \t## working on region in file <name> ... - -is inserted at the end. - -Caution: No more than 26 regions can be pending at any given time. -This limit is (indirectly) inherited from libc's mktemp(3). -`python-mode' does not try to protect you from exceeding the limit. -It's extremely unlikely that you'll get anywhere close to the limit in -practice, unless you're trying to be a jerk <grin>. - -See the `\\[py-shell]' docs for additional warnings." - (interactive "r") - (or (< start end) (error "Region is empty")) - (let ((pyproc (get-process "Python")) - fname) - (if (null pyproc) - (shell-command-on-region start end py-python-command) - ;; else feed it thru a temp file - (setq fname (py-make-temp-name)) - (write-region start end fname nil 'no-msg) - (setq py-file-queue (append py-file-queue (list fname))) - (if (cdr py-file-queue) - (message "File %s queued for execution" fname) - ;; else - (py-execute-file pyproc fname))))) - -(defun py-execute-file (pyproc fname) - (py-append-to-process-buffer - pyproc - (format "## working on region in file %s ...\n" fname)) - (process-send-string pyproc (format "execfile('%s')\n" fname))) - -(defun py-process-filter (pyproc string) - (let ((curbuf (current-buffer)) - (pbuf (process-buffer pyproc)) - (pmark (process-mark pyproc)) - file-finished) - - ;; make sure we switch to a different buffer at least once. if we - ;; *don't* do this, then if the process buffer is in the selected - ;; window, and point is before the end, and lots of output is - ;; coming at a fast pace, then (a) simple cursor-movement commands - ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time - ;; to have a visible effect (the window just doesn't get updated, - ;; sometimes for minutes(!)), and (b) it takes about 5x longer to - ;; get all the process output (until the next python prompt). - ;; - ;; #b makes no sense to me at all. #a almost makes sense: unless - ;; we actually change buffers, set_buffer_internal in buffer.c - ;; doesn't set windows_or_buffers_changed to 1, & that in turn - ;; seems to make the Emacs command loop reluctant to update the - ;; display. Perhaps the default process filter in process.c's - ;; read_process_output has update_mode_lines++ for a similar - ;; reason? beats me ... - - ;; BAW - we want to check to see if this still applies - (if (eq curbuf pbuf) ; mysterious ugly hack - (set-buffer (get-buffer-create "*scratch*"))) - - (set-buffer pbuf) - (let* ((start (point)) - (goback (< start pmark)) - (goend (and (not goback) (= start (point-max)))) - (buffer-read-only nil)) - (goto-char pmark) - (insert string) - (move-marker pmark (point)) - (setq file-finished - (and py-file-queue - (equal ">>> " - (buffer-substring - (prog2 (beginning-of-line) (point) - (goto-char pmark)) - (point))))) - (if goback (goto-char start) - ;; else - (if py-scroll-process-buffer - (let* ((pop-up-windows t) - (pwin (display-buffer pbuf))) - (set-window-point pwin (point))))) - (set-buffer curbuf) - (if file-finished - (progn - (py-delete-file-silently (car py-file-queue)) - (setq py-file-queue (cdr py-file-queue)) - (if py-file-queue - (py-execute-file pyproc (car py-file-queue))))) - (and goend - (progn (set-buffer pbuf) - (goto-char (point-max)))) - ))) - -(defun py-execute-buffer () - "Send the contents of the buffer to a Python interpreter. -If there is a *Python* process buffer it is used. If a clipping -restriction is in effect, only the accessible portion of the buffer is -sent. A trailing newline will be supplied if needed. - -See the `\\[py-execute-region]' docs for an account of some subtleties." - (interactive) - (py-execute-region (point-min) (point-max))) - - - -;; Functions for Python style indentation -(defun py-delete-char () - "Reduce indentation or delete character. -If point is at the leftmost column, deletes the preceding newline. - -Else if point is at the leftmost non-blank character of a line that is -neither a continuation line nor a non-indenting comment line, or if -point is at the end of a blank line, reduces the indentation to match -that of the line that opened the current block of code. The line that -opened the block is displayed in the echo area to help you keep track -of where you are. - -Else the preceding character is deleted, converting a tab to spaces if -needed so that only a single column position is deleted." - (interactive "*") - (if (or (/= (current-indentation) (current-column)) - (bolp) - (py-continuation-line-p) - (looking-at "#[^ \t\n]")) ; non-indenting # - (backward-delete-char-untabify 1) - ;; else indent the same as the colon line that opened the block - - ;; force non-blank so py-goto-block-up doesn't ignore it - (insert-char ?* 1) - (backward-char) - (let ((base-indent 0) ; indentation of base line - (base-text "") ; and text of base line - (base-found-p nil)) - (condition-case nil ; in case no enclosing block - (save-excursion - (py-goto-block-up 'no-mark) - (setq base-indent (current-indentation) - base-text (py-suck-up-leading-text) - base-found-p t)) - (error nil)) - (delete-char 1) ; toss the dummy character - (delete-horizontal-space) - (indent-to base-indent) - (if base-found-p - (message "Closes block: %s" base-text))))) - -;; required for pending-del and delsel modes -(put 'py-delete-char 'delete-selection 'supersede) -(put 'py-delete-char 'pending-delete 'supersede) - -(defun py-indent-line () - "Fix the indentation of the current line according to Python rules." - (interactive) - (let* ((ci (current-indentation)) - (move-to-indentation-p (<= (current-column) ci)) - (need (py-compute-indentation))) - ;; see if we need to outdent - (if (py-outdent-p) - (setq need (- need py-indent-offset))) - (if (/= ci need) - (save-excursion - (beginning-of-line) - (delete-horizontal-space) - (indent-to need))) - (if move-to-indentation-p (back-to-indentation)))) - -(defun py-newline-and-indent () - "Strives to act like the Emacs `newline-and-indent'. -This is just `strives to' because correct indentation can't be computed -from scratch for Python code. In general, deletes the whitespace before -point, inserts a newline, and takes an educated guess as to how you want -the new line indented." - (interactive) - (let ((ci (current-indentation))) - (if (< ci (current-column)) ; if point beyond indentation - (newline-and-indent) - ;; else try to act like newline-and-indent "normally" acts - (beginning-of-line) - (insert-char ?\n 1) - (move-to-column ci)))) - -(defun py-compute-indentation () - (save-excursion - (let ((pps (parse-partial-sexp (save-excursion - (beginning-of-python-def-or-class) - (point)) - (point)))) - (beginning-of-line) - (cond - ;; are we inside a string or comment? - ((or (nth 3 pps) (nth 4 pps)) - (save-excursion - (if (not py-align-multiline-strings-p) 0 - ;; skip back over blank & non-indenting comment lines - ;; note: will skip a blank or non-indenting comment line - ;; that happens to be a continuation line too - (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move) - (back-to-indentation) - (current-column)))) - ;; are we on a continuation line? - ((py-continuation-line-p) - (let ((startpos (point)) - (open-bracket-pos (py-nesting-level)) - endpos searching found) - (if open-bracket-pos - (progn - ;; align with first item in list; else a normal - ;; indent beyond the line with the open bracket - (goto-char (1+ open-bracket-pos)) ; just beyond bracket - ;; is the first list item on the same line? - (skip-chars-forward " \t") - (if (null (memq (following-char) '(?\n ?# ?\\))) - ; yes, so line up with it - (current-column) - ;; first list item on another line, or doesn't exist yet - (forward-line 1) - (while (and (< (point) startpos) - (looking-at "[ \t]*[#\n\\\\]")) ; skip noise - (forward-line 1)) - (if (< (point) startpos) - ;; again mimic the first list item - (current-indentation) - ;; else they're about to enter the first item - (goto-char open-bracket-pos) - (+ (current-indentation) py-indent-offset)))) - - ;; else on backslash continuation line - (forward-line -1) - (if (py-continuation-line-p) ; on at least 3rd line in block - (current-indentation) ; so just continue the pattern - ;; else started on 2nd line in block, so indent more. - ;; if base line is an assignment with a start on a RHS, - ;; indent to 2 beyond the leftmost "="; else skip first - ;; chunk of non-whitespace characters on base line, + 1 more - ;; column - (end-of-line) - (setq endpos (point) searching t) - (back-to-indentation) - (setq startpos (point)) - ;; look at all "=" from left to right, stopping at first - ;; one not nested in a list or string - (while searching - (skip-chars-forward "^=" endpos) - (if (= (point) endpos) - (setq searching nil) - (forward-char 1) - (setq state (parse-partial-sexp startpos (point))) - (if (and (zerop (car state)) ; not in a bracket - (null (nth 3 state))) ; & not in a string - (progn - (setq searching nil) ; done searching in any case - (setq found - (not (or - (eq (following-char) ?=) - (memq (char-after (- (point) 2)) - '(?< ?> ?!))))))))) - (if (or (not found) ; not an assignment - (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash> - (progn - (goto-char startpos) - (skip-chars-forward "^ \t\n"))) - (1+ (current-column)))))) - - ;; not on a continuation line - - ;; if at start of restriction, or on a non-indenting comment - ;; line, assume they intended whatever's there - ((or (bobp) (looking-at "[ \t]*#[^ \t\n]")) - (current-indentation)) - - ;; else indentation based on that of the statement that - ;; precedes us; use the first line of that statement to - ;; establish the base, in case the user forced a non-std - ;; indentation for the continuation lines (if any) - (t - ;; skip back over blank & non-indenting comment lines note: - ;; will skip a blank or non-indenting comment line that - ;; happens to be a continuation line too. use fast Emacs 19 - ;; function if it's there. - (if (and (eq py-honor-comment-indentation nil) - (fboundp 'forward-comment)) - (forward-comment (- (point-max))) - (let (done) - (while (not done) - (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" - nil 'move) - (setq done (or (eq py-honor-comment-indentation t) - (bobp) - (/= (following-char) ?#) - (not (zerop (current-column))))) - ))) - ;; if we landed inside a string, go to the beginning of that - ;; string. this handles triple quoted, multi-line spanning - ;; strings. - (py-goto-initial-line) - (if (py-statement-opens-block-p) - (+ (current-indentation) py-indent-offset) - (current-indentation))))))) - -(defun py-guess-indent-offset (&optional global) - "Guess a good value for, and change, `py-indent-offset'. -By default (without a prefix arg), makes a buffer-local copy of -`py-indent-offset' with the new value. This will not affect any other -Python buffers. With a prefix arg, changes the global value of -`py-indent-offset'. This affects all Python buffers (that don't have -their own buffer-local copy), both those currently existing and those -created later in the Emacs session. - -Some people use a different value for `py-indent-offset' than you use. -There's no excuse for such foolishness, but sometimes you have to deal -with their ugly code anyway. This function examines the file and sets -`py-indent-offset' to what it thinks it was when they created the -mess. - -Specifically, it searches forward from the statement containing point, -looking for a line that opens a block of code. `py-indent-offset' is -set to the difference in indentation between that line and the Python -statement following it. If the search doesn't succeed going forward, -it's tried again going backward." - (interactive "P") ; raw prefix arg - (let (new-value - (start (point)) - restart - (found nil) - colon-indent) - (py-goto-initial-line) - (while (not (or found (eobp))) - (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move) - (progn - (setq restart (point)) - (py-goto-initial-line) - (if (py-statement-opens-block-p) - (setq found t) - (goto-char restart))))) - (if found - () - (goto-char start) - (py-goto-initial-line) - (while (not (or found (bobp))) - (setq found - (and - (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move) - (or (py-goto-initial-line) t) ; always true -- side effect - (py-statement-opens-block-p))))) - (setq colon-indent (current-indentation) - found (and found (zerop (py-next-statement 1))) - new-value (- (current-indentation) colon-indent)) - (goto-char start) - (if found - (progn - (funcall (if global 'kill-local-variable 'make-local-variable) - 'py-indent-offset) - (setq py-indent-offset new-value) - (message "%s value of py-indent-offset set to %d" - (if global "Global" "Local") - py-indent-offset)) - (error "Sorry, couldn't guess a value for py-indent-offset")))) - -(defun py-shift-region (start end count) - (save-excursion - (goto-char end) (beginning-of-line) (setq end (point)) - (goto-char start) (beginning-of-line) (setq start (point)) - (indent-rigidly start end count))) - -(defun py-shift-region-left (start end &optional count) - "Shift region of Python code to the left. -The lines from the line containing the start of the current region up -to (but not including) the line containing the end of the region are -shifted to the left, by `py-indent-offset' columns. - -If a prefix argument is given, the region is instead shifted by that -many columns." - (interactive "*r\nP") ; region; raw prefix arg - (py-shift-region start end - (- (prefix-numeric-value - (or count py-indent-offset))))) - -(defun py-shift-region-right (start end &optional count) - "Shift region of Python code to the right. -The lines from the line containing the start of the current region up -to (but not including) the line containing the end of the region are -shifted to the right, by `py-indent-offset' columns. - -If a prefix argument is given, the region is instead shifted by that -many columns." - (interactive "*r\nP") ; region; raw prefix arg - (py-shift-region start end (prefix-numeric-value - (or count py-indent-offset)))) - -(defun py-indent-region (start end &optional indent-offset) - "Reindent a region of Python code. - -The lines from the line containing the start of the current region up -to (but not including) the line containing the end of the region are -reindented. If the first line of the region has a non-whitespace -character in the first column, the first line is left alone and the -rest of the region is reindented with respect to it. Else the entire -region is reindented with respect to the (closest code or indenting -comment) statement immediately preceding the region. - -This is useful when code blocks are moved or yanked, when enclosing -control structures are introduced or removed, or to reformat code -using a new value for the indentation offset. - -If a numeric prefix argument is given, it will be used as the value of -the indentation offset. Else the value of `py-indent-offset' will be -used. - -Warning: The region must be consistently indented before this function -is called! This function does not compute proper indentation from -scratch (that's impossible in Python), it merely adjusts the existing -indentation to be correct in context. - -Warning: This function really has no idea what to do with -non-indenting comment lines, and shifts them as if they were indenting -comment lines. Fixing this appears to require telepathy. - -Special cases: whitespace is deleted from blank lines; continuation -lines are shifted by the same amount their initial line was shifted, -in order to preserve their relative indentation with respect to their -initial line; and comment lines beginning in column 1 are ignored." - (interactive "*r\nP") ; region; raw prefix arg - (save-excursion - (goto-char end) (beginning-of-line) (setq end (point-marker)) - (goto-char start) (beginning-of-line) - (let ((py-indent-offset (prefix-numeric-value - (or indent-offset py-indent-offset))) - (indents '(-1)) ; stack of active indent levels - (target-column 0) ; column to which to indent - (base-shifted-by 0) ; amount last base line was shifted - (indent-base (if (looking-at "[ \t\n]") - (py-compute-indentation) - 0)) - ci) - (while (< (point) end) - (setq ci (current-indentation)) - ;; figure out appropriate target column - (cond - ((or (eq (following-char) ?#) ; comment in column 1 - (looking-at "[ \t]*$")) ; entirely blank - (setq target-column 0)) - ((py-continuation-line-p) ; shift relative to base line - (setq target-column (+ ci base-shifted-by))) - (t ; new base line - (if (> ci (car indents)) ; going deeper; push it - (setq indents (cons ci indents)) - ;; else we should have seen this indent before - (setq indents (memq ci indents)) ; pop deeper indents - (if (null indents) - (error "Bad indentation in region, at line %d" - (save-restriction - (widen) - (1+ (count-lines 1 (point))))))) - (setq target-column (+ indent-base - (* py-indent-offset - (- (length indents) 2)))) - (setq base-shifted-by (- target-column ci)))) - ;; shift as needed - (if (/= ci target-column) - (progn - (delete-horizontal-space) - (indent-to target-column))) - (forward-line 1)))) - (set-marker end nil)) - - -;; Functions for moving point -(defun py-previous-statement (count) - "Go to the start of previous Python statement. -If the statement at point is the i'th Python statement, goes to the -start of statement i-COUNT. If there is no such statement, goes to the -first statement. Returns count of statements left to move. -`Statements' do not include blank, comment, or continuation lines." - (interactive "p") ; numeric prefix arg - (if (< count 0) (py-next-statement (- count)) - (py-goto-initial-line) - (let (start) - (while (and - (setq start (point)) ; always true -- side effect - (> count 0) - (zerop (forward-line -1)) - (py-goto-statement-at-or-above)) - (setq count (1- count))) - (if (> count 0) (goto-char start))) - count)) - -(defun py-next-statement (count) - "Go to the start of next Python statement. -If the statement at point is the i'th Python statement, goes to the -start of statement i+COUNT. If there is no such statement, goes to the -last statement. Returns count of statements left to move. `Statements' -do not include blank, comment, or continuation lines." - (interactive "p") ; numeric prefix arg - (if (< count 0) (py-previous-statement (- count)) - (beginning-of-line) - (let (start) - (while (and - (setq start (point)) ; always true -- side effect - (> count 0) - (py-goto-statement-below)) - (setq count (1- count))) - (if (> count 0) (goto-char start))) - count)) - -(defun py-goto-block-up (&optional nomark) - "Move up to start of current block. -Go to the statement that starts the smallest enclosing block; roughly -speaking, this will be the closest preceding statement that ends with a -colon and is indented less than the statement you started on. If -successful, also sets the mark to the starting point. - -`\\[py-mark-block]' can be used afterward to mark the whole code -block, if desired. - -If called from a program, the mark will not be set if optional argument -NOMARK is not nil." - (interactive) - (let ((start (point)) - (found nil) - initial-indent) - (py-goto-initial-line) - ;; if on blank or non-indenting comment line, use the preceding stmt - (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)") - (progn - (py-goto-statement-at-or-above) - (setq found (py-statement-opens-block-p)))) - ;; search back for colon line indented less - (setq initial-indent (current-indentation)) - (if (zerop initial-indent) - ;; force fast exit - (goto-char (point-min))) - (while (not (or found (bobp))) - (setq found - (and - (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move) - (or (py-goto-initial-line) t) ; always true -- side effect - (< (current-indentation) initial-indent) - (py-statement-opens-block-p)))) - (if found - (progn - (or nomark (push-mark start)) - (back-to-indentation)) - (goto-char start) - (error "Enclosing block not found")))) - -(defun beginning-of-python-def-or-class (&optional class) - "Move point to start of def (or class, with prefix arg). - -Searches back for the closest preceding `def'. If you supply a prefix -arg, looks for a `class' instead. The docs assume the `def' case; -just substitute `class' for `def' for the other case. - -If point is in a def statement already, and after the `d', simply -moves point to the start of the statement. - -Else (point is not in a def statement, or at or before the `d' of a -def statement), searches for the closest preceding def statement, and -leaves point at its start. If no such statement can be found, leaves -point at the start of the buffer. - -Returns t iff a def statement is found by these rules. - -Note that doing this command repeatedly will take you closer to the -start of the buffer each time. - -If you want to mark the current def/class, see -`\\[mark-python-def-or-class]'." - (interactive "P") ; raw prefix arg - (let ((at-or-before-p (<= (current-column) (current-indentation))) - (start-of-line (progn (beginning-of-line) (point))) - (start-of-stmt (progn (py-goto-initial-line) (point)))) - (if (or (/= start-of-stmt start-of-line) - (not at-or-before-p)) - (end-of-line)) ; OK to match on this line - (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>") - nil 'move))) - -(defun end-of-python-def-or-class (&optional class) - "Move point beyond end of def (or class, with prefix arg) body. - -By default, looks for an appropriate `def'. If you supply a prefix arg, -looks for a `class' instead. The docs assume the `def' case; just -substitute `class' for `def' for the other case. - -If point is in a def statement already, this is the def we use. - -Else if the def found by `\\[beginning-of-python-def-or-class]' -contains the statement you started on, that's the def we use. - -Else we search forward for the closest following def, and use that. - -If a def can be found by these rules, point is moved to the start of -the line immediately following the def block, and the position of the -start of the def is returned. - -Else point is moved to the end of the buffer, and nil is returned. - -Note that doing this command repeatedly will take you closer to the -end of the buffer each time. - -If you want to mark the current def/class, see -`\\[mark-python-def-or-class]'." - (interactive "P") ; raw prefix arg - (let ((start (progn (py-goto-initial-line) (point))) - (which (if class "class" "def")) - (state 'not-found)) - ;; move point to start of appropriate def/class - (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one - (setq state 'at-beginning) - ;; else see if beginning-of-python-def-or-class hits container - (if (and (beginning-of-python-def-or-class class) - (progn (py-goto-beyond-block) - (> (point) start))) - (setq state 'at-end) - ;; else search forward - (goto-char start) - (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move) - (progn (setq state 'at-beginning) - (beginning-of-line))))) - (cond - ((eq state 'at-beginning) (py-goto-beyond-block) t) - ((eq state 'at-end) t) - ((eq state 'not-found) nil) - (t (error "internal error in end-of-python-def-or-class"))))) - - -;; Functions for marking regions -(defun py-mark-block (&optional extend just-move) - "Mark following block of lines. With prefix arg, mark structure. -Easier to use than explain. It sets the region to an `interesting' -block of succeeding lines. If point is on a blank line, it goes down to -the next non-blank line. That will be the start of the region. The end -of the region depends on the kind of line at the start: - - - If a comment, the region will include all succeeding comment lines up - to (but not including) the next non-comment line (if any). - - - Else if a prefix arg is given, and the line begins one of these - structures: - - if elif else try except finally for while def class - - the region will be set to the body of the structure, including - following blocks that `belong' to it, but excluding trailing blank - and comment lines. E.g., if on a `try' statement, the `try' block - and all (if any) of the following `except' and `finally' blocks - that belong to the `try' structure will be in the region. Ditto - for if/elif/else, for/else and while/else structures, and (a bit - degenerate, since they're always one-block structures) def and - class blocks. - - - Else if no prefix argument is given, and the line begins a Python - block (see list above), and the block is not a `one-liner' (i.e., - the statement ends with a colon, not with code), the region will - include all succeeding lines up to (but not including) the next - code statement (if any) that's indented no more than the starting - line, except that trailing blank and comment lines are excluded. - E.g., if the starting line begins a multi-statement `def' - structure, the region will be set to the full function definition, - but without any trailing `noise' lines. - - - Else the region will include all succeeding lines up to (but not - including) the next blank line, or code or indenting-comment line - indented strictly less than the starting line. Trailing indenting - comment lines are included in this case, but not trailing blank - lines. - -A msg identifying the location of the mark is displayed in the echo -area; or do `\\[exchange-point-and-mark]' to flip down to the end. - -If called from a program, optional argument EXTEND plays the role of -the prefix arg, and if optional argument JUST-MOVE is not nil, just -moves to the end of the block (& does not set mark or display a msg)." - (interactive "P") ; raw prefix arg - (py-goto-initial-line) - ;; skip over blank lines - (while (and - (looking-at "[ \t]*$") ; while blank line - (not (eobp))) ; & somewhere to go - (forward-line 1)) - (if (eobp) - (error "Hit end of buffer without finding a non-blank stmt")) - (let ((initial-pos (point)) - (initial-indent (current-indentation)) - last-pos ; position of last stmt in region - (followers - '((if elif else) (elif elif else) (else) - (try except finally) (except except) (finally) - (for else) (while else) - (def) (class) ) ) - first-symbol next-symbol) - - (cond - ;; if comment line, suck up the following comment lines - ((looking-at "[ \t]*#") - (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment - (re-search-backward "^[ \t]*#") ; and back to last comment in block - (setq last-pos (point))) - - ;; else if line is a block line and EXTEND given, suck up - ;; the whole structure - ((and extend - (setq first-symbol (py-suck-up-first-keyword) ) - (assq first-symbol followers)) - (while (and - (or (py-goto-beyond-block) t) ; side effect - (forward-line -1) ; side effect - (setq last-pos (point)) ; side effect - (py-goto-statement-below) - (= (current-indentation) initial-indent) - (setq next-symbol (py-suck-up-first-keyword)) - (memq next-symbol (cdr (assq first-symbol followers)))) - (setq first-symbol next-symbol))) - - ;; else if line *opens* a block, search for next stmt indented <= - ((py-statement-opens-block-p) - (while (and - (setq last-pos (point)) ; always true -- side effect - (py-goto-statement-below) - (> (current-indentation) initial-indent)) - nil)) - - ;; else plain code line; stop at next blank line, or stmt or - ;; indenting comment line indented < - (t - (while (and - (setq last-pos (point)) ; always true -- side effect - (or (py-goto-beyond-final-line) t) - (not (looking-at "[ \t]*$")) ; stop at blank line - (or - (>= (current-indentation) initial-indent) - (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting # - nil))) - - ;; skip to end of last stmt - (goto-char last-pos) - (py-goto-beyond-final-line) - - ;; set mark & display - (if just-move - () ; just return - (push-mark (point) 'no-msg) - (forward-line -1) - (message "Mark set after: %s" (py-suck-up-leading-text)) - (goto-char initial-pos)))) - -(defun mark-python-def-or-class (&optional class) - "Set region to body of def (or class, with prefix arg) enclosing point. -Pushes the current mark, then point, on the mark ring (all language -modes do this, but although it's handy it's never documented ...). - -In most Emacs language modes, this function bears at least a -hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and -`\\[beginning-of-python-def-or-class]'. - -And in earlier versions of Python mode, all 3 were tightly connected. -Turned out that was more confusing than useful: the `goto start' and -`goto end' commands are usually used to search through a file, and -people expect them to act a lot like `search backward' and `search -forward' string-search commands. But because Python `def' and `class' -can nest to arbitrary levels, finding the smallest def containing -point cannot be done via a simple backward search: the def containing -point may not be the closest preceding def, or even the closest -preceding def that's indented less. The fancy algorithm required is -appropriate for the usual uses of this `mark' command, but not for the -`goto' variations. - -So the def marked by this command may not be the one either of the -`goto' commands find: If point is on a blank or non-indenting comment -line, moves back to start of the closest preceding code statement or -indenting comment line. If this is a `def' statement, that's the def -we use. Else searches for the smallest enclosing `def' block and uses -that. Else signals an error. - -When an enclosing def is found: The mark is left immediately beyond -the last line of the def block. Point is left at the start of the -def, except that: if the def is preceded by a number of comment lines -followed by (at most) one optional blank line, point is left at the -start of the comments; else if the def is preceded by a blank line, -point is left at its start. - -The intent is to mark the containing def/class and its associated -documentation, to make moving and duplicating functions and classes -pleasant." - (interactive "P") ; raw prefix arg - (let ((start (point)) - (which (if class "class" "def"))) - (push-mark start) - (if (not (py-go-up-tree-to-keyword which)) - (progn (goto-char start) - (error "Enclosing %s not found" which)) - ;; else enclosing def/class found - (setq start (point)) - (py-goto-beyond-block) - (push-mark (point)) - (goto-char start) - (if (zerop (forward-line -1)) ; if there is a preceding line - (progn - (if (looking-at "[ \t]*$") ; it's blank - (setq start (point)) ; so reset start point - (goto-char start)) ; else try again - (if (zerop (forward-line -1)) - (if (looking-at "[ \t]*#") ; a comment - ;; look back for non-comment line - ;; tricky: note that the regexp matches a blank - ;; line, cuz \n is in the 2nd character class - (and - (re-search-backward "^[ \t]*[^ \t#]" nil 'move) - (forward-line 1)) - ;; no comment, so go back - (goto-char start)))))))) - - -;; Documentation functions - -;; dump the long form of the mode blurb; does the usual doc escapes, -;; plus lines of the form ^[vc]:name$ to suck variable & command docs -;; out of the right places, along with the keys they're on & current -;; values -(defun py-dump-help-string (str) - (with-output-to-temp-buffer "*Help*" - (let ((locals (buffer-local-variables)) - funckind funcname func funcdoc - (start 0) mstart end - keys ) - (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start) - (setq mstart (match-beginning 0) end (match-end 0) - funckind (substring str (match-beginning 1) (match-end 1)) - funcname (substring str (match-beginning 2) (match-end 2)) - func (intern funcname)) - (princ (substitute-command-keys (substring str start mstart))) - (cond - ((equal funckind "c") ; command - (setq funcdoc (documentation func) - keys (concat - "Key(s): " - (mapconcat 'key-description - (where-is-internal func py-mode-map) - ", ")))) - ((equal funckind "v") ; variable - (setq funcdoc (substitute-command-keys - (get func 'variable-documentation)) - keys (if (assq func locals) - (concat - "Local/Global values: " - (prin1-to-string (symbol-value func)) - " / " - (prin1-to-string (default-value func))) - (concat - "Value: " - (prin1-to-string (symbol-value func)))))) - (t ; unexpected - (error "Error in py-dump-help-string, tag `%s'" funckind))) - (princ (format "\n-> %s:\t%s\t%s\n\n" - (if (equal funckind "c") "Command" "Variable") - funcname keys)) - (princ funcdoc) - (terpri) - (setq start end)) - (princ (substitute-command-keys (substring str start)))) - (print-help-return-message))) - -(defun py-describe-mode () - "Dump long form of Python-mode docs." - (interactive) - (py-dump-help-string "Major mode for editing Python files. -Knows about Python indentation, tokens, comments and continuation lines. -Paragraphs are separated by blank lines only. - -Major sections below begin with the string `@'; specific function and -variable docs begin with `->'. - -@EXECUTING PYTHON CODE - -\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter -\\[py-execute-region]\tsends the current region -\\[py-shell]\tstarts a Python interpreter window; this will be used by -\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands -%c:py-execute-buffer -%c:py-execute-region -%c:py-shell - -@VARIABLES - -py-indent-offset\tindentation increment -py-block-comment-prefix\tcomment string used by py-comment-region - -py-python-command\tshell command to invoke Python interpreter -py-scroll-process-buffer\talways scroll Python process buffer -py-temp-directory\tdirectory used for temp files (if needed) - -py-beep-if-tab-change\tring the bell if tab-width is changed -%v:py-indent-offset -%v:py-block-comment-prefix -%v:py-python-command -%v:py-scroll-process-buffer -%v:py-temp-directory -%v:py-beep-if-tab-change - -@KINDS OF LINES - -Each physical line in the file is either a `continuation line' (the -preceding line ends with a backslash that's not part of a comment, or -the paren/bracket/brace nesting level at the start of the line is -non-zero, or both) or an `initial line' (everything else). - -An initial line is in turn a `blank line' (contains nothing except -possibly blanks or tabs), a `comment line' (leftmost non-blank -character is `#'), or a `code line' (everything else). - -Comment Lines - -Although all comment lines are treated alike by Python, Python mode -recognizes two kinds that act differently with respect to indentation. - -An `indenting comment line' is a comment line with a blank, tab or -nothing after the initial `#'. The indentation commands (see below) -treat these exactly as if they were code lines: a line following an -indenting comment line will be indented like the comment line. All -other comment lines (those with a non-whitespace character immediately -following the initial `#') are `non-indenting comment lines', and -their indentation is ignored by the indentation commands. - -Indenting comment lines are by far the usual case, and should be used -whenever possible. Non-indenting comment lines are useful in cases -like these: - -\ta = b # a very wordy single-line comment that ends up being -\t #... continued onto another line - -\tif a == b: -##\t\tprint 'panic!' # old code we've `commented out' -\t\treturn a - -Since the `#...' and `##' comment lines have a non-whitespace -character following the initial `#', Python mode ignores them when -computing the proper indentation for the next line. - -Continuation Lines and Statements - -The Python-mode commands generally work on statements instead of on -individual lines, where a `statement' is a comment or blank line, or a -code line and all of its following continuation lines (if any) -considered as a single logical unit. The commands in this mode -generally (when it makes sense) automatically move to the start of the -statement containing point, even if point happens to be in the middle -of some continuation line. - - -@INDENTATION - -Primarily for entering new code: -\t\\[indent-for-tab-command]\t indent line appropriately -\t\\[py-newline-and-indent]\t insert newline, then indent -\t\\[py-delete-char]\t reduce indentation, or delete single character - -Primarily for reindenting existing code: -\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally -\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally - -\t\\[py-indent-region]\t reindent region to match its context -\t\\[py-shift-region-left]\t shift region left by py-indent-offset -\t\\[py-shift-region-right]\t shift region right by py-indent-offset - -Unlike most programming languages, Python uses indentation, and only -indentation, to specify block structure. Hence the indentation supplied -automatically by Python-mode is just an educated guess: only you know -the block structure you intend, so only you can supply correct -indentation. - -The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on -the indentation of preceding statements. E.g., assuming -py-indent-offset is 4, after you enter -\tif a > 0: \\[py-newline-and-indent] -the cursor will be moved to the position of the `_' (_ is not a -character in the file, it's just used here to indicate the location of -the cursor): -\tif a > 0: -\t _ -If you then enter `c = d' \\[py-newline-and-indent], the cursor will move -to -\tif a > 0: -\t c = d -\t _ -Python-mode cannot know whether that's what you intended, or whether -\tif a > 0: -\t c = d -\t_ -was your intent. In general, Python-mode either reproduces the -indentation of the (closest code or indenting-comment) preceding -statement, or adds an extra py-indent-offset blanks if the preceding -statement has `:' as its last significant (non-whitespace and non- -comment) character. If the suggested indentation is too much, use -\\[py-delete-char] to reduce it. - -Continuation lines are given extra indentation. If you don't like the -suggested indentation, change it to something you do like, and Python- -mode will strive to indent later lines of the statement in the same way. - -If a line is a continuation line by virtue of being in an unclosed -paren/bracket/brace structure (`list', for short), the suggested -indentation depends on whether the current line contains the first item -in the list. If it does, it's indented py-indent-offset columns beyond -the indentation of the line containing the open bracket. If you don't -like that, change it by hand. The remaining items in the list will mimic -whatever indentation you give to the first item. - -If a line is a continuation line because the line preceding it ends with -a backslash, the third and following lines of the statement inherit their -indentation from the line preceding them. The indentation of the second -line in the statement depends on the form of the first (base) line: if -the base line is an assignment statement with anything more interesting -than the backslash following the leftmost assigning `=', the second line -is indented two columns beyond that `='. Else it's indented to two -columns beyond the leftmost solid chunk of non-whitespace characters on -the base line. - -Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command] -repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block -structure you intend. -%c:indent-for-tab-command -%c:py-newline-and-indent -%c:py-delete-char - - -The next function may be handy when editing code you didn't write: -%c:py-guess-indent-offset - - -The remaining `indent' functions apply to a region of Python code. They -assume the block structure (equals indentation, in Python) of the region -is correct, and alter the indentation in various ways while preserving -the block structure: -%c:py-indent-region -%c:py-shift-region-left -%c:py-shift-region-right - -@MARKING & MANIPULATING REGIONS OF CODE - -\\[py-mark-block]\t mark block of lines -\\[mark-python-def-or-class]\t mark smallest enclosing def -\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class -\\[py-comment-region]\t comment out region of code -\\[universal-argument] \\[py-comment-region]\t uncomment region of code -%c:py-mark-block -%c:mark-python-def-or-class -%c:py-comment-region - -@MOVING POINT - -\\[py-previous-statement]\t move to statement preceding point -\\[py-next-statement]\t move to statement following point -\\[py-goto-block-up]\t move up to start of current block -\\[beginning-of-python-def-or-class]\t move to start of def -\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class -\\[end-of-python-def-or-class]\t move to end of def -\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class - -The first two move to one statement beyond the statement that contains -point. A numeric prefix argument tells them to move that many -statements instead. Blank lines, comment lines, and continuation lines -do not count as `statements' for these commands. So, e.g., you can go -to the first code statement in a file by entering -\t\\[beginning-of-buffer]\t to move to the top of the file -\t\\[py-next-statement]\t to skip over initial comments and blank lines -Or do `\\[py-previous-statement]' with a huge prefix argument. -%c:py-previous-statement -%c:py-next-statement -%c:py-goto-block-up -%c:beginning-of-python-def-or-class -%c:end-of-python-def-or-class - -@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE - -`\\[indent-new-comment-line]' is handy for entering a multi-line comment. - -`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the -overall class and def structure of a module. - -`\\[back-to-indentation]' moves point to a line's first non-blank character. - -`\\[indent-relative]' is handy for creating odd indentation. - -@OTHER EMACS HINTS - -If you don't like the default value of a variable, change its value to -whatever you do like by putting a `setq' line in your .emacs file. -E.g., to set the indentation increment to 4, put this line in your -.emacs: -\t(setq py-indent-offset 4) -To see the value of a variable, do `\\[describe-variable]' and enter the variable -name at the prompt. - -When entering a key sequence like `C-c C-n', it is not necessary to -release the CONTROL key after doing the `C-c' part -- it suffices to -press the CONTROL key, press and release `c' (while still holding down -CONTROL), press and release `n' (while still holding down CONTROL), & -then release CONTROL. - -Entering Python mode calls with no arguments the value of the variable -`python-mode-hook', if that value exists and is not nil; for backward -compatibility it also tries `py-mode-hook'; see the `Hooks' section of -the Elisp manual for details. - -Obscure: When python-mode is first loaded, it looks for all bindings -to newline-and-indent in the global keymap, and shadows them with -local bindings to py-newline-and-indent.")) - - -;; Helper functions -(defvar py-parse-state-re - (concat - "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>" - "\\|" - "^[^ #\t\n]")) - -;; returns the parse state at point (see parse-partial-sexp docs) -(defun py-parse-state () - (save-excursion - (let ((here (point)) - pps done) - (while (not done) - ;; back up to the first preceding line (if any; else start of - ;; buffer) that begins with a popular Python keyword, or a - ;; non- whitespace and non-comment character. These are good - ;; places to start parsing to see whether where we started is - ;; at a non-zero nesting level. It may be slow for people who - ;; write huge code blocks or huge lists ... tough beans. - (re-search-backward py-parse-state-re nil 'move) - (beginning-of-line) - (save-excursion - (setq pps (parse-partial-sexp (point) here))) - ;; make sure we don't land inside a triple-quoted string - (setq done (or (not (nth 3 pps)) (bobp)))) - pps))) - -;; if point is at a non-zero nesting level, returns the number of the -;; character that opens the smallest enclosing unclosed list; else -;; returns nil. -(defun py-nesting-level () - (let ((status (py-parse-state)) ) - (if (zerop (car status)) - nil ; not in a nest - (car (cdr status))))) ; char# of open bracket - -;; t iff preceding line ends with backslash that's not in a comment -(defun py-backslash-continuation-line-p () - (save-excursion - (beginning-of-line) - (and - ;; use a cheap test first to avoid the regexp if possible - ;; use 'eq' because char-after may return nil - (eq (char-after (- (point) 2)) ?\\ ) - ;; make sure; since eq test passed, there is a preceding line - (forward-line -1) ; always true -- side effect - (looking-at py-continued-re)))) - -;; t iff current line is a continuation line -(defun py-continuation-line-p () - (save-excursion - (beginning-of-line) - (or (py-backslash-continuation-line-p) - (py-nesting-level)))) - -;; go to initial line of current statement; usually this is the line -;; we're on, but if we're on the 2nd or following lines of a -;; continuation block, we need to go up to the first line of the -;; block. -;; -;; Tricky: We want to avoid quadratic-time behavior for long continued -;; blocks, whether of the backslash or open-bracket varieties, or a -;; mix of the two. The following manages to do that in the usual -;; cases. -(defun py-goto-initial-line () - (let ( open-bracket-pos ) - (while (py-continuation-line-p) - (beginning-of-line) - (if (py-backslash-continuation-line-p) - (while (py-backslash-continuation-line-p) - (forward-line -1)) - ;; else zip out of nested brackets/braces/parens - (while (setq open-bracket-pos (py-nesting-level)) - (goto-char open-bracket-pos))))) - (beginning-of-line)) - -;; go to point right beyond final line of current statement; usually -;; this is the start of the next line, but if this is a multi-line -;; statement we need to skip over the continuation lines. Tricky: -;; Again we need to be clever to avoid quadratic time behavior. -(defun py-goto-beyond-final-line () - (forward-line 1) - (let (state) - (while (and (py-continuation-line-p) - (not (eobp))) - ;; skip over the backslash flavor - (while (and (py-backslash-continuation-line-p) - (not (eobp))) - (forward-line 1)) - ;; if in nest, zip to the end of the nest - (setq state (py-parse-state)) - (if (and (not (zerop (car state))) - (not (eobp))) - (progn - ;; BUG ALERT: I could swear, from reading the docs, that - ;; the 3rd argument should be plain 0 - (parse-partial-sexp (point) (point-max) (- 0 (car state)) - nil state) - (forward-line 1)))))) - -;; t iff statement opens a block == iff it ends with a colon that's -;; not in a comment. point should be at the start of a statement -(defun py-statement-opens-block-p () - (save-excursion - (let ((start (point)) - (finish (progn (py-goto-beyond-final-line) (1- (point)))) - (searching t) - (answer nil) - state) - (goto-char start) - (while searching - ;; look for a colon with nothing after it except whitespace, and - ;; maybe a comment - (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$" - finish t) - (if (eq (point) finish) ; note: no `else' clause; just - ; keep searching if we're not at - ; the end yet - ;; sure looks like it opens a block -- but it might - ;; be in a comment - (progn - (setq searching nil) ; search is done either way - (setq state (parse-partial-sexp start - (match-beginning 0))) - (setq answer (not (nth 4 state))))) - ;; search failed: couldn't find another interesting colon - (setq searching nil))) - answer))) - -;; go to point right beyond final line of block begun by the current -;; line. This is the same as where py-goto-beyond-final-line goes -;; unless we're on colon line, in which case we go to the end of the -;; block. assumes point is at bolp -(defun py-goto-beyond-block () - (if (py-statement-opens-block-p) - (py-mark-block nil 'just-move) - (py-goto-beyond-final-line))) - -;; go to start of first statement (not blank or comment or -;; continuation line) at or preceding point. returns t if there is -;; one, else nil -(defun py-goto-statement-at-or-above () - (py-goto-initial-line) - (if (looking-at py-blank-or-comment-re) - ;; skip back over blank & comment lines - ;; note: will skip a blank or comment line that happens to be - ;; a continuation line too - (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t) - (progn (py-goto-initial-line) t) - nil) - t)) - -;; go to start of first statement (not blank or comment or -;; continuation line) following the statement containing point returns -;; t if there is one, else nil -(defun py-goto-statement-below () - (beginning-of-line) - (let ((start (point))) - (py-goto-beyond-final-line) - (while (and - (looking-at py-blank-or-comment-re) - (not (eobp))) - (forward-line 1)) - (if (eobp) - (progn (goto-char start) nil) - t))) - -;; go to start of statement, at or preceding point, starting with -;; keyword KEY. Skips blank lines and non-indenting comments upward -;; first. If that statement starts with KEY, done, else go back to -;; first enclosing block starting with KEY. If successful, leaves -;; point at the start of the KEY line & returns t. Else leaves point -;; at an undefined place & returns nil. -(defun py-go-up-tree-to-keyword (key) - ;; skip blanks and non-indenting # - (py-goto-initial-line) - (while (and - (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)") - (zerop (forward-line -1))) ; go back - nil) - (py-goto-initial-line) - (let* ((re (concat "[ \t]*" key "\\b")) - (case-fold-search nil) ; let* so looking-at sees this - (found (looking-at re)) - (dead nil)) - (while (not (or found dead)) - (condition-case nil ; in case no enclosing block - (py-goto-block-up 'no-mark) - (error (setq dead t))) - (or dead (setq found (looking-at re)))) - (beginning-of-line) - found)) - -;; return string in buffer from start of indentation to end of line; -;; prefix "..." if leading whitespace was skipped -(defun py-suck-up-leading-text () - (save-excursion - (back-to-indentation) - (concat - (if (bolp) "" "...") - (buffer-substring (point) (progn (end-of-line) (point)))))) - -;; assuming point at bolp, return first keyword ([a-z]+) on the line, -;; as a Lisp symbol; return nil if none -(defun py-suck-up-first-keyword () - (let ((case-fold-search nil)) - (if (looking-at "[ \t]*\\([a-z]+\\)\\b") - (intern (buffer-substring (match-beginning 1) (match-end 1))) - nil))) - -(defun py-make-temp-name () - (make-temp-name - (concat (file-name-as-directory py-temp-directory) "python"))) - -(defun py-delete-file-silently (fname) - (condition-case nil - (delete-file fname) - (error nil))) - -(defun py-kill-emacs-hook () - ;; delete our temp files - (while py-file-queue - (py-delete-file-silently (car py-file-queue)) - (setq py-file-queue (cdr py-file-queue))) - (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)) - ;; run the hook we inherited, if any - (and py-inherited-kill-emacs-hook - (funcall py-inherited-kill-emacs-hook)))) - -;; make PROCESS's buffer visible, append STRING to it, and force -;; display; also make shell-mode believe the user typed this string, -;; so that kill-output-from-shell and show-output-from-shell work -;; "right" -(defun py-append-to-process-buffer (process string) - (let ((cbuf (current-buffer)) - (pbuf (process-buffer process)) - (py-scroll-process-buffer t)) - (set-buffer pbuf) - (goto-char (point-max)) - (move-marker (process-mark process) (point)) - (if (not (or py-this-is-emacs-19-p - py-this-is-lucid-emacs-p)) - (move-marker last-input-start (point))) ; muck w/ shell-mode - (funcall (process-filter process) process string) - (if (not (or py-this-is-emacs-19-p - py-this-is-lucid-emacs-p)) - (move-marker last-input-end (point))) ; muck w/ shell-mode - (set-buffer cbuf)) - (sit-for 0)) - -(defun py-keep-region-active () - ;; do whatever is necessary to keep the region active in XEmacs. - ;; Ignore byte-compiler warnings you might see. Also note that - ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't - ;; require us to take explicit action. - (and (boundp 'zmacs-region-stays) - (setq zmacs-region-stays t))) - - -(defconst py-version "$Revision$" - "`python-mode' version number.") -(defconst py-help-address "python-mode@python.org" - "Address accepting submission of bug reports.") - -(defun py-version () - "Echo the current version of `python-mode' in the minibuffer." - (interactive) - (message "Using `python-mode' version %s" py-version) - (py-keep-region-active)) - -;; only works under Emacs 19 -;(eval-when-compile -; (require 'reporter)) - -(defun py-submit-bug-report (enhancement-p) - "Submit via mail a bug report on `python-mode'. -With \\[universal-argument] just submit an enhancement request." - (interactive - (list (not (y-or-n-p - "Is this a bug report? (hit `n' to send other comments) ")))) - (let ((reporter-prompt-for-summary-p (if enhancement-p - "(Very) brief summary: " - t))) - (require 'reporter) - (reporter-submit-bug-report - py-help-address ;address - (concat "python-mode " py-version) ;pkgname - ;; varlist - (if enhancement-p nil - '(py-python-command - py-indent-offset - py-block-comment-prefix - py-scroll-process-buffer - py-temp-directory - py-beep-if-tab-change)) - nil ;pre-hooks - nil ;post-hooks - "Dear Barry,") ;salutation - (if enhancement-p nil - (set-mark (point)) - (insert -"Please replace this text with a sufficiently large code sample\n\ -and an exact recipe so that I can reproduce your problem. Failure\n\ -to do so may mean a greater delay in fixing your bug.\n\n") - (exchange-point-and-mark) - (py-keep-region-active)))) - - -;; arrange to kill temp files when Emacs exists -(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p) - (add-hook 'kill-emacs-hook 'py-kill-emacs-hook) - ;; have to trust that other people are as respectful of our hook - ;; fiddling as we are of theirs - (if (boundp 'py-inherited-kill-emacs-hook) - ;; we were loaded before -- trust others not to have screwed us - ;; in the meantime (no choice, really) - nil - ;; else arrange for our hook to run theirs - (setq py-inherited-kill-emacs-hook kill-emacs-hook) - (setq kill-emacs-hook 'py-kill-emacs-hook))) - - - -(provide 'python-mode) -;;; python-mode.el ends here diff --git a/Misc/python.gif b/Misc/python.gif deleted file mode 100644 index 4c94b3d459a82050bb8ac509425b97fdb31f2ffb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcwPel00001 literal 7380 zcwPb294q5TNk%v~Ve|mg0Pz3-00010RaL60s{jB0EC2ui0Q3OU00091oR6u??GK}z zwAzca-n{z{hT=$;=82~2%C_zc$MQ_q_KoNI&iDTR69|Vxpz)|83IfXj;0cXNpG>6n zT4@HhOd;1f4NJk>BKCY;0=NQ0d+-HE<$$J|I#&nKd>^=7=C;?gMz=NK^|t3GgeW)o z*XQvjd7-9P)OZ(Gr3nCc&=@+m$8=bkQH4rjCs0>9xH<MTbXpqfMMkH|xLWZk>g(XN zNNj4b1w}l!#=FGm73K<63r8#*QAUZaaE(m0lsonK1Sd))D8>}kNLR<r5RMFwK&&Y3 zUO1(Mh};$}MhLZav$oMw^@-j9aQ&u<c{rwsp=1!-u!F;C(ZT+9&$vws_XVOzT7?9T z+=r10L1l^zuIi`?TdQ{Y)||`(@TQz0Qe?eKrqNfzY25w*&DZ6hxdUAGH9DEJ4ip1Z zz7^^>&zD9j!agRIl@!rbc~r+av52p!KcZzXifx89Zlz+bgn{V?3tSyS$_{m87A~;U zMa`oAbBMD_EMzhH6g%q@&7r)z5Fw7}Wno0Zb^=WX#2M6Om4Sm!JB3Emx|jOGYA&>r z(?Y8x1O0oK2+*4~=DMUD=f<)lY8}sX`IIoI@lUq~y{$5`ODSc|&}B+w4(6MGHMufH zirNY=sgcvrA`(aC?|@(3IiH+0S1)UztU;9i(4H0PPW~Jzw{lt;&b`)9ey8BplPgN8 z;>;q|EOc9R_Zd^34j}dSOfX2e64ruuG+|kLb!GThPtwsx*jl>*g4azhz5@hvXU&${ zE0*O32urpwa*7!~y;6&A+-=8QOccF%5)kWTm{3+nsN@@q5mK`hB#tz+)fizZ7A0LY zZr5FYF8Yw6m;NBZm10T=$c`p0$tPNvg>~|bYYwKP6O!fZ@YjHX{KvytKamm5k)gx_ zCX1Gh<OyS{H8hGkavDg=4&x<<m3KctrrSw4l0lUjlXAsfh_`IhR6wJ78qO=c;ZRCl z3QPqAhauv@j+oRTniDhQ)ahHW+%dW;uK5tT{^AV+$%^WpK~zU5Ma8fhr#?C{2x61P znh2z>nBk&e4VPqyfPxjm+R2Q6w!=w+i%Qs2Z<)0R)oi^&D@G`cyeh*-!7y2zA6K0x zR%UI9lqyueie*imCW%SsLhf7`MneLL1t<&MQu0)PG4jR*Q?H7mr&LJlA_|=~VR+1s z#0}?^Jf_GB!;&!CO68`m(sBTmwb<mMbQ~giv40P1DcErj9lEe?)`Z6bUk(;_mCo7# zW0D=_oV>?gN-Jzix<{L6?v!M+fs`T`X_oN`COcQoGBKVNwi{!yJ0UfDm4@7l7|Iyi zK06lc<0d<07EQP;n1UNd;?xS{I*0WBRV}NXDRGIf8GS{YSsee!W>k29dfT$jCcze3 zDV=KrY$@5zv&W;J_Y<55Ql}1xiW#`?Ub%bit1kXP*CYyc@l4fp{PwU{KQ_IEJn_V$ z*IU<z-6YUgyl-8RaGm2iWW%<iFgc7EtrX+WwXwAK*!OuIBuFkVZEoNL9V2H)9Gi93 zbdJzmf=<BbE_YB8dHx^^-6Ump^%GE?hPN%CRfkEOz|MU*<eTrA?0>n)UJ3NqypL>+ zbu=IfLCSy`&_s|FLW59XvQw-hU4;l*;u7qB<q*2LOmSOFRRDW-y}cpN51=5`!+-^e z`5}!YiJMoe7$uw^bx?f?3S9oA@Nt;*knjS)SlhA=)wUZHhKGpB1a5e8K|<t)bJ|eQ z%0l-Vvc<7tv#AWsaAz9EsX+v?;#s&rQ#>Bz1};|N4`}d%u*?PNMrAsO45P%NmHAF{ zu#q4*#8Hs#oF^F~7)m+FsIDHo@H~a;q84f)J(ZZqkQ8#-zizdqz>G#fGAs!6e5O3g zy(2WM`G5e`vzF!Yz-u1s4fxO#ze$BnMi>l9UydR_%(-uu(?sEJ;w2nrI46rfoJ5m| z0~4t2U`gY94qZSbu~u~_8Hs3|NytE&jJ!}V(%5CiKv<RF<d8Rtnw$tbfEz;91Axq{ z(;1EEz1l4hS5R_TF8*qHOk+snFmoJ;L1V_IRVK_kV9F*THPD#TEy@UL+9XSubfuOt zE+b&%i?t->Quf_357paDFi?Uepjqig%WRA#nsuiu8DUP%dszcTqy^9MbZGEYhb8;c zroa*KcBJv%O!alkpgd-10kZ(jB2lhD_J9p(qS8>H0TN;Y1)RNFXRa=DowwYJI9&u< zFc!Fre%d6I`g(>`GEkhHInR7#>YET5LMIC{>_W>R#HiRgCoQn?lyqZHT8oyWl)Z&1 zj<tzF6mg_5Ho$y2Tc%hy;8PFSgBFii;IbGS2$SW?Q|qc^xWq=Eca7tdej$ru4uw^$ z2nsHdxkE7}{s2IKsg$oA;Gs94va_>RX<0&}?qL%tFUi4ENay&Ifp!B8#smja<F%Mh zVeth`B4>-I1QTpLqzlM2SF{!IXERtk4`f~kYlT|j1hZ4S4=qI^YnqUJf+eptS_hLX zED1-DL*J44Cld24mkhTU52rO3NaiACZmXe<^ghR_u0h8omsB5Yr8G<-YB8#I65Mj# zlA*R;>}kK_UNmAY5OLA39zF_zE@61I1H>9$#+$_Iy_O`uLX?+ya=u-{?NJA#F~g$B zpfSux0iYWlMZQSbL)`-|%4`uo6Y$WI1X*lD4r`gZC>mFG<~Z3KZbafFzARogoM`m~ zPUx!sq8)3KLk5wYuIK<Ei6y`rY$F*dT-KO3DF;*wXpi06{0$B^PsxwcERI&ClmveU zk)tM(Am-tYbQEkg#k>y~ql-IL>f#+EgBsmLHp6li_{3?8A_JP@8iq(9a&nC&foXz9 z`yB?#DUP3UJ$(){#4#u!gHG3QEe*!JNDq&=&H1*$FSImHF7^42u^i-BaauTQvJ`d$ z+;}SvZ_|N^_Q(2!tw$2EfrdmWjQ6zT=W#>GFjY!p$@c1&;`uqO%ag25pQq0Z%7rWq zm>EMbhc-6GqI`|)P^9VVu9@5lJMG+bj~K}=i&3;-%)Z?lmvJ(^VJ*zI8rID&4$1yP z`4k=Ges>nzG_GYYo1cO<%mgo2MjWasH`5K0d~Z~b{0bE>p>8AM+%t>!A<V94dQ+q* zapG&e5GxDvIk}biX%q=(rB6-nCQd_~B+smommA}Uqqv<d|BIae)9u0O2GMK>tVlx~ zR}JG(OUbnZx%S9AdXC~0kWr;R<Z&T8Q7DoJW+!Y~1Ij}|v2*gqMNP1jnMHEcuFP|e z#x~W~G7{VC2!M{hXs!+;C9dby9@$Ngi51*?GSP^yaS)pccadyEb_=7LZ1Q7$bUX$V zT>%lR|C+-FFgdgGF8UtaeQ30Gl%3&)H%NZVukUGjFRckzODz0c&j8bIJ^qo4jU$<U zp$~>>30ycH0p({aIQVu6b|s0jC^1DWYIiw36c9q?e6o>uQD#vyr4v`CKQl&0R>d)h zmIS}11T2AaIe`$^LJ2A(KeIz?&B0Di2ObUrbFp?om{%3VrzgHgE_kyvy<t_UMgw2= zHP3_+ujOcdv^S<jN)W{ll;t=>!!4+1NhSzI{`G^?GK6^YRK?RIFep+oa6eSU4tIfL zsxe6ml~$KTI0~dDiDed?1ceGyK~+XuOQ8%jf+xp<3)mKBJ9ut!pdkssVHoobR$@I| z#daaLc(i6ZF>@&ghdt9I5-9R^<Wf;>(lhIke@PHu?ZtDW;A9Lk{v)tZNAWjNivcn! zlz468RFp(CjHoIN10gvBcKOjTL$Qa$^k?mZcv412d!z-h^in9XRc|sVP(@DDGlbiw zilMk{M=>9bI6`LtCGGc$@**Q5!%4$2VPP_Y^6)~O_h^s-izI?2idPX*G)>r1AnFl) zd4NFTB^gnLABx8lXaNw2!W^B^J^IrMkT5geI8`jQc++JI)dUvw)P+2<9vxzV1Yt&! zU~^-139&LsPc%6I7H=&`E280lo?%QBLTkA~a5d;{=)q(%7d@TwNh>lM#UXC7GZt~^ z3*?w@eq<ERW|8^wZ;fV#JRwjHkr`+7TO1TJmUkornRkNzB6MBj6!mak1tc;GVHEyT zbD1SM1*k+8m2$G=bZ$g21F=+!1|P8{kA^l$@PlQ2XA8c<F$al8`%{TeLT0Q*Fa;zm zRVj&TH({Li2gLPB|HB53m^`1-K@Qdl*>o{f#yA=ngq$LIWzm)&!*2>nLjz=SQ0Qci zqHl9IT-ii*26cPXvw7A-AxO4%R~KmNXa-&QPWVK7<}r7`0}M)oa-xGU|5i7g_cTob zj$5%VwB$u`<9+*>j8Hcsi-C~|5^5LWI~;*Qci0CC!c6a^l%8cebV)1W^E7*7Dm=Lj z1lUIwVLc(@N(;3bZUTTR$A#EgM3jSKJfaVcsRRD@fMVU2o~krguGVZ_vTw4qo-)QI z7&lKz1PiECC4!(R|9C=Cpik3wS&PP6>b4y1B$2G>R(`WTcC%cN!FkySE~V08rpF(l z5(xt$OL$fyIAu@Z)Ob^~Nvrt-4GLAZ_e81ZBFO@pMY2L)7H8mT2b)A6Wn)c2g(y5F ziY}N??pQV*NmG*0pmZWw5#)rWRWKInE$rhArITpbd15*VEtw!1uv04gusjR}n?3VJ z?nwi*Ba-mbgJ@GSA*Mj^5)lMbC9H%(0%9+ow{)f^R|7Z;)MlK_VqQ35rdkMW(A9rS zG8u?eGJL9tRC9*d0UdQVit!j{ReCg>rT#exfEiPHQ}Q&ZFVK-!<6*-wEJeVERiQ** zfqm9zD|CT=&gp>yRHaPecQ;ck#n~53iE`hC1xPw2;Q^eWSP>94W1*&NGyxn2BOm&P z7$O)#BN&|sszGuJriJ+@lB8zhfflh)owiYPv6y)`(uF!zXe|*%4mg-zd6q!eLtWaX zbETp<HAnqXjZ)&IK$botlr@}HUFl^wF>_RpFi^p<aT&;b2Gg2mb5iN#3<N7rk!Xd+ z$tk9aFhMy~A2Oy(5v5pJl?eNOGjePsQ!1JYd=!OjqMEFJ5nPOj5Eocc5UN$m<ZdmB zlz3w>LaGspDtK$sc*12S(nLW`{x*5pXFvCoTI+{H329+8)rp#RihISPT4)kC#Cy2l zKnAFeo^cumd1@s#vP?*lpv8c5g-V}gW?Dv&0(TivL7eqzkvt|!_XR&36*8uTo!hb{ zWuY7tr&%iJr!JVY)ev+*CtYL*Y5F1uTt*!w=OL*|4#K1ZVR%hm!&$v>4iB+-IRu^- zL#qR3mSa{MVAV_LrK$?)a|<X`F)_KUiachtTaUzOmV!Q3(Rl<aW)K@Ie`92<2z6+t z6dkl4I29|2)_vY6aM3Efw5m2KnVNVJcz{c3mJ)!5a%DN%qcA0dwG$sQHVi`ti%Um> zPLxC9)Ez3>xmTnkGn9A!T$6>ZV`y6WDoM6?I{On>f?rHGeibq#3d>~Tx>!u-CWD5& z7on&1P^OZnJ-fAA%_O@R^or<ogl-rw_J~<$LVZtT9gGCA7paXS`gpT6YM6^`1p6=( z;Ya>ag(6IRpBe%?lQMB>8thWE0X9Awx^jM3S(|pAOa>+!H(nnhTP#$QIN=}SY6!rW zSZDiK%f!MTU@fRrl4vC@Wtdr=tFi#5zy--~NPH)};InuTLmO2=r<WdDXT8)lh%7`K zP22&YMS1=<Jccko7FUm(2X(3VOOc0e{fUJQ=r?-gOet)N0N9@8yQLRd12Cvw74{oC zRKA)KoaOes`QiRFC9A6_+{Z3RDU>qF->V8?(^xci4Raf{CjeJ4gDlX~K`W704z?EP ztI2vZB6b+cbu2;8`=psC$m7Vc+~#>=3Lk(}$|m5#?=oIoXBg5lTQ&-emb|voq;0MO ztH0+dPur+E(Go%fY=I|2yTisB@WiRosawi7-LZB;^-idnJ$kXMr<Vu!wT82G&DvCc z8)s;%HHZ|GEjQ)@;#^2JCtoWiNkgI$V7sIUrx%@g8@r$v8*I%pxXW8dB~GSLX$;1` z(He;?uzi&h`-qKYgm>w18W-g|PpLoIOOke$bzln7v0O5x^JDY)RCy_1mrz2tTwd|z z&=eDhlKv*B&HB!l)FKScM5?mNogC3^x{ANoM!EBt<k7w^@KPZKCEZ5HM?@n9jZwmQ zUzA3V@dcOe(<$|ns`EUfh8xH=VO3ILGmzWQX~@bt(r!#hsTd6#kkw%P;WL^vld5!S zJQ_LcY}VHtK21fEssukr>XI=4tAOiehshC@6<*Qo9YlSSFgB!^Kxlj7CS*+3Y`tyQ zTuY54x9X@%`53gr+(}~09-c=}C`lwo{57HzM69(xiyJO`GBt}tOF|USW^D)qR?<NC zV=jaaYZcXtQx1pb9@4^>^U<uUYB*^tixMNpg25w{mCQN}YlAJLA*8B@w@I!97qX?= z{vg0q`J+T-nP28T+MrFZJn6X-g`)kTRs$D*WT9SJjJYvqWLDQ&p_7l!t2_h+s)T0P zkE>MZrim$fQq#+JZS;rkay5pOEx4IzoalrK?kV~KT@=fHV!3b2=Ugw)Oe;yBqa8A; z8@zqIoQeG!r6J5XU6|D6Mmq{4@>bi7VjD9|3P$xBAtq6voZeJQ9cSuUJxIwb1}R+S zkl_u+k@*>Cd&|+_LZ0<rV5MmFri7;`bms^$CkcWWLp8xTl5r;}HLzD&Q%$#!Vw(6? zRD@_r1|=yb$X}37{6XK~2BNzobD&~An3IsZLS`VC#)2|Ccfp)3po9%Wf|ct2iA=K@ zAr^&^sZR=96R3ot#x*OBQ;afMI2XLSemsKNX4}in-%_yUGhhsL8ZurSF}?G8zIj18 z#T>NR;X9fWk&zrW0?${xFCtoQ!JDZ{@jFe}g_-Ostpm@d$E7I)QCNq$JaQZ=Bf**O zKtnlNmb>EFsz;(X>`=%Ua?;#_YS_HN&x~%g<WvmTnsrXtxOyv^J5hy=O*s#saE2&S z7%DOR#CHzuGq=>`(Jqo?<$;U-*0QWSI5-hVEqHe472>7rZxv$@fGIb39oZLMJ!0(B z^Rn~E&>@<a7jayy-Y(hc<3Yo4dZVg2f)o^g0fb>AeHrPkkd#pp9Vq@Rs8~)KOx2M` zv`05EDLVh%5a9q>GrZ>1-w1#7GH*0><a$zQeOd8X0cYF0f!u-#wIy7=Ht^dAw?#dx z<jxoLUbPi_q|I_hI7`Jp4?f*@oG|D&#p7$>iR|6j6ai=SKN$gh>3;N9C=q+|D&2xb z`>n}I#6%hkX88#uc}_ZhF9W%pd2I$~e0}Z%!SoMc8p)F`jq$vKJ4-(pAae)u>x`R^ zcOpltERsL<S-@dnr`~lx0fAIEm4|L99(Q0KJmWnTxev+d-GPx))#sh?i6n6r(0F>4 z#a5mHgym3fepd?!H;e0$H?%V<J0nm{XE;tPC2s_?2m+E<l>RJTRGIGp{4%_^ZjO0@ zs?gB)N4_4zakWMLUeYYLyQ2^oKxi&8@|cm_c~1a{Mld3$0UGHDaIs)>-GDKMQ9e(x zqGd1@<NGw_DUSn~@Lb>d-v5C?Auyzwoh~g<vNY_48c~%|f{2tr6$fewH72rF*U2J+ zSz@u;2<ddc;c=(Pvvzf{5saKu#NAdb9ug3gmTWlk@-9{?6f5dT4sB9uVmt@|`8GK_ zc^(-&vKBKwHn}z?APHp}W)>Sxz(Pc?s2*D?TI=rAT=fhJH9d)o-(K`!>AJEQH<t<@ z3I$zBIx<v+yHJp>!%iHzQT19hN?VN6)qhY(o8O^f{+^j-j-p+Eg9|s@UnrNol(E$4 z4mopZP^en5j$y+G%plUD_hKF%dxH)PlIGxugNP#raxtK9O)PUXNR$v5Ow}-lFFSpt z#|)CWig@^ytF~d9MsGMrs3IlF8XYda%#F;52xe1GcxpwZr!xW{cS&vtbifl_3XKp& zXka6<h)NmlXr#zG(f~)7PT>w|2bFEaG{LIMAqxV>ScD`d=mWI(oLC89+jT|4!Ud&P zg5pLVay8VUnMvjGv5U|KxLASPI$A-KOvcfq9##!iW28XVby`Z6O(dekx_pgbl^|zx zD_zyJRn1G;%wjyjF<<h_jRKh2&w1Rgofbs?G_0<8OU>Inkc=CZlTabdM9XMk=b*TF z2r^W{=FXtU4>X;+N|s8{Y0iiS{!ZUNufVP!$Hb5>BWT2;WhJi$K|{Xyz^kpc0)aV2 zlb-4kYra0Zpa2pH_h}8mQ34bNyrA~M?!nn2r0X^;kb{r6-J~&%Cwac3Cy-gD<B*ph zOBAIjC{m$l#plL5PRG>lc#1~I2FbAzN-S#7ypQlJNIM%KAdiWj7CI713CT3>inreQ zqQ)3vvxdiQSV=MiN$7Bgvs{8{@2oDx9P=u8zEMO*-h={U0a*kA1R^qUkTb7w;5q7r zlSI*ImOh_5&n|a(grTjca!_wai~#;y)WJ+93=Xf(im1aMwzP=C6ij8)6f7OF_(erI zQrWQ*5wf8GC^mhZ3bY7m=ximB?&E4ZTH`9{PdM`shDN=Hk>U%ns=0EHa_X6|(QPW5 zlv0t-I%`m9o#Kzo>OveN2~S+ILIqPaBnu>ax7dsg?ZQ)vTa{|$z&&;&vz5%$!oq@> zUi%V?jKPi*?TC+bNY4aY=q#m?1t8cJ;ilaEQ>EAN!GxF#56f5uZvk0@6_|^Nw>n@( zkV+Qdm>W5=X>TioFJz3_wkjHn6c%166RC|mn#J+d;WVtM%xB4xx-|od&`RfMXLhaU zO+^1|vAP_(WQ<EHRm*I#tNs%nZxKV>J++uJdd}f2gP*j*Lna~GLYih!B78j#GPxG+ zm#|uxETKiF7eRKg^E+bDdYp!BK$%KqPc#>AsBsXPyqF=dK0%zL893TJ@V@eaHIHCp z<uG)(HU_w{!}wGDVVb&a6!G1He>c3<ySnbX&!nk(G~aJu=VZ!~nx+hgh<lbDrH$7c z%tV`4JytQIhfC<J!>}(lhaBBq0@Kh2+9I9|Uh`1oHD|i~rWi3hYwxrty>}(cRS7a4 zG*nlGC~QR`e8ULn_IJ7)NM&p%amoQ{g26@Y;C;danFF~LLEMQ5UL}N}I@%{c4K6_k z`?!bj1lJA`j_@v9{(GHMRJg(e2Cspw5ZnR}Hba<f4P9ZFm-%#<MAV@TaRQ1M9fUZ- z6o_L)CuB(b$W*QsicN1E*^M@$D8&!G31_mwB4T`qKI19wi#t$R7>D>JAgLvQ7u+Ht zq$UYK0k4gh>z5VbSPUYKP9m9l%}3;MiMbqdhqCB_V*+W%{$Z{b&~Xj2m|!q+u!dVZ zL=gNMm6=G!u@u|*)R<V{LSb0K7P`@$@zPSCQIf1oM}$tU*dqn-C`WcVQ{s|l$+*4b z>Us~tWu9VrE`S&?hgl3J|IWj+Aj+p73WAY>3^PY1K9iRE=uSB>MT$vP3v!joTCS7` zJ#Gr{5bC7Kre$bhht}kBleRgaJJ%_}Q?d&dCL)o2#?UYYtuddH!G_QJsT91Jz#lMR z)y>XXrGh4GR#%%Ay0{S_dD_!16Rnm0Mkcp+%q2(~1f@rD7pBlP(?wdM9!h7Uhw`b> zqy&X&OhLNRUrOktH;tA`BY4I}`V=}7#3$TnT2rFRXL*54UKV@0R5KnZa#1A1Rk<it zV~QlITJ`D$IrUYswrgJKgO~`9I@U}DkWp%Nt1)c(R=KWYnsc?QAgg*;z3!E-eZ6S` G0028JT|Wl^ diff --git a/Misc/python.man b/Misc/python.man deleted file mode 100644 index 4e7d46a767..0000000000 --- a/Misc/python.man +++ /dev/null @@ -1,243 +0,0 @@ -.TH PYTHON "4 January 1995" -.SH NAME -python \- an interpreted, interactive, object-oriented programming language -.SH SYNOPSIS -.B python -[ -.I X11-options -] -[ -.B \-d -] -[ -.B \-i -] -[ -.B \-s -] -[ -.B \-u -] -[ -.B \-v -] -[ -.B \-c -.I command -| -.I script -| -\- -] -[ -.I arguments -] -.SH DESCRIPTION -Python is an interpreted, interactive, object-oriented programming -language that combines remarkable power with very clear syntax. -For an introduction to programming in Python you are referred to the -Python Tutorial. -The Python Library Reference documents built-in and standard types, -constants, functions and modules. -Finally, the Python Reference Manual describes the syntax and -semantics of the core language in (perhaps too) much detail. -.PP -Python's basic power can be extended with your own modules written in -C or C++. -On some (most?) systems such modules may be dynamically loaded. -Python is also adaptable as an extension language for existing -applications. -See the internal documentation for hints. -.SH COMMAND LINE OPTIONS -.TP -.B \-d -Turn on parser debugging output (for wizards only, depending on -compilation options). -.TP -.B \-i -When a script is passed as first argument or the \fB\-c\fP option is -used, enter interactive mode after executing the script or the -command. It does not read the $PYTHONSTARTUP file. This can be -useful to inspect global variables or a stack trace when a script -raises an exception. -.TP -.B \-s -Suppresses the automatic printing of expressions entered in -interactive mode (useful when input is actually generated e.g. by -Emacs). -.TP -.B \-u -Force stdout and stderr to be totally unbuffered. -.TP -.B \-v -Print a message each time a module is initialized, showing the place -(filename or built-in module) from which it is loaded. -.TP -.BI "\-c " command -Specify the command to execute (see next section). -This terminates the option list (following options are passed as -arguments to the command). -.PP -When the interpreter is configured to contain the -.I stdwin -built-in module for use with the X window system, additional command -line options common to most X applications are recognized (by STDWIN), -e.g. -.B \-display -.I displayname -and -.B \-geometry -.I widthxheight+x+y. -The complete set of options is described in the STDWIN documentation. -.SH INTERPRETER INTERFACE -The interpreter interface resembles that of the UNIX shell: when -called with standard input connected to a tty device, it prompts for -commands and executes them until an EOF is read; when called with a -file name argument or with a file as standard input, it reads and -executes a -.I script -from that file; -when called with -.B \-c -.I command, -it executes the Python statement(s) given as -.I command. -Here -.I command -may contain multiple statements separated by newlines. -Leading whitespace is significant in Python statements! -In non-interactive mode, the entire input is parsed befored it is -executed. -.PP -If available, the script name and additional arguments thereafter are -passed to the script in the Python variable -.I sys.argv , -which is a list of strings (you must first -.I import sys -to be able to access it). -If no script name is given, -.I sys.argv -is empty; if -.B \-c -is used, -.I sys.argv[0] -contains the string -.I '-c'. -Note that options interpreter by the Python interpreter or by STDWIN -are not placed in -.I sys.argv. -.PP -In interactive mode, the primary prompt is `>>>'; the second prompt -(which appears when a command is not complete) is `...'. -The prompts can be changed by assignment to -.I sys.ps1 -or -.I sys.ps2. -The interpreter quits when it reads an EOF at a prompt. -When an unhandled exception occurs, a stack trace is printed and -control returns to the primary prompt; in non-interactive mode, the -interpreter exits after printing the stack trace. -The interrupt signal raises the -.I Keyboard\%Interrupt -exception; other UNIX signals are not caught (except that SIGPIPE is -sometimes ignored, in favor of the -.I IOError -exception). Error messages are written to stderr. -.SH FILES AND DIRECTORIES -These are subject to difference depending on local installation -conventions: -.IP /usr/local/bin/python -Recommended location of the interpreter. -.IP /usr/local/lib/python -Recommended location of the directory containing the standard modules. -.SH ENVIRONMENT VARIABLES -.IP PYTHONPATH -Augments the default search path for module files. -The format is the same as the shell's $PATH: one or more directory -pathnames separated by colons. -Non-existant directories are silently ignored. -The default search path is installation dependent, but always begins -with `.', (for example, -.I .:/usr/local/lib/python ). -The default search path is appended to $PYTHONPATH. -The search path can be manipulated from within a Python program as the -variable -.I sys.path . -.IP PYTHONSTARTUP -If this is the name of a readable file, the Python commands in that -file are executed before the first prompt is displayed in interactive -mode. -The file is executed in the same name space where interactive commands -are executed so that objects defined or imported in it can be used -without qualification in the interactive session. -You can also change the prompts -.I sys.ps1 -and -.I sys.ps2 -in this file. -.IP PYTHONDEBUG -If this is set to a non-empty string it is equivalent to specifying -the \fB\-d\fP option. -.IP PYTHONINSPECT -If this is set to a non-empty string it is equivalent to specifying -the \fB\-i\fP option. -.IP PYTHONSUPPRESS -If this is set to a non-empty string it is equivalent to specifying -the \fB\-s\fP option. -.IP PYTHONUNBUFFERED -If this is set to a non-empty string it is equivalent to specifying -the \fB\-u\fP option. -.IP PYTHONVERBOSE -If this is set to a non-empty string it is equivalent to specifying -the \fB\-v\fP option. -.SH SEE ALSO -Python Tutorial -.br -Python Library Reference -.br -Python Reference Manual -.br -STDWIN under X11 -.SH BUGS AND CAVEATS -The first time -.I stdwin -is imported, it initializes the STDWIN library. -If this initialization fails, e.g. because the display connection -fails, the interpreter aborts immediately. -.SH AUTHOR -.nf -Guido van Rossum -CWI (Centrum voor Wiskunde en Informatica) -P.O. Box 4079 -1009 AB Amsterdam -The Netherlands -.PP -E-mail: Guido.van.Rossum@cwi.nl -.fi -.SH MAILING LIST -There is a mailing list devoted to Python programming, bugs and -design. -To subscribe, send mail containing your real name and e-mail address -in Internet form to -.I python-list-request@cwi.nl. -.SH COPYRIGHT -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. -.IP " " -All Rights Reserved -.PP -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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/Misc/renumber.py b/Misc/renumber.py deleted file mode 100755 index f2299b66f2..0000000000 --- a/Misc/renumber.py +++ /dev/null @@ -1,110 +0,0 @@ -#! /usr/local/bin/python - -# Renumber the Python FAQ - -import string -import regex -import sys -import os - -FAQ = 'FAQ' - -chapterprog = regex.compile('^\([1-9][0-9]*\)\. ') -questionprog = regex.compile('^\([1-9][0-9]*\)\.\([1-9][0-9]*\)\. ') -newquestionprog = regex.compile('^Q\. ') -blankprog = regex.compile('^[ \t]*$') -indentedorblankprog = regex.compile('^\([ \t]+\|[ \t]*$\)') - -def main(): - print 'Reading lines...' - lines = open(FAQ, 'r').readlines() - print 'Renumbering in memory...' - oldlines = lines[:] - after_blank = 1 - chapter = 0 - question = 0 - chapters = ['\n'] - questions = [] - for i in range(len(lines)): - line = lines[i] - if after_blank: - n = chapterprog.match(line) - if n >= 0: - chapter = chapter + 1 - question = 0 - line = `chapter` + '. ' + line[n:] - lines[i] = line - chapters.append(' ' + line) - questions.append('\n') - questions.append(' ' + line) - afterblank = 0 - continue - n = questionprog.match(line) - if n < 0: n = newquestionprog.match(line) - 3 - if n >= 0: - question = question + 1 - number = '%d.%d. '%(chapter, question) - line = number + line[n:] - lines[i] = line - questions.append(' ' + line) - # Add up to 4 continuations of the question - n = len(number) - for j in range(i+1, i+5): - if blankprog.match(lines[j]) >= 0: - break - questions.append(' '*(n+2) + lines[j]) - afterblank = 0 - continue - afterblank = (blankprog.match(line) >= 0) - print 'Inserting list of chapters...' - chapters.append('\n') - for i in range(len(lines)): - line = lines[i] - if regex.match( - '^This FAQ is divided in the following chapters', - line) >= 0: - i = i+1 - while 1: - line = lines[i] - if indentedorblankprog.match(line) < 0: - break - del lines[i] - lines[i:i] = chapters - break - else: - print '*** Can\'t find header for list of chapters' - print '*** Chapters found:' - for line in chapters: print line, - print 'Inserting list of questions...' - questions.append('\n') - for i in range(len(lines)): - line = lines[i] - if regex.match('^Here.s an overview of the questions', - line) >= 0: - i = i+1 - while 1: - line = lines[i] - if indentedorblankprog.match(line) < 0: - break - del lines[i] - lines[i:i] = questions - break - else: - print '*** Can\'t find header for list of questions' - print '*** Questions found:' - for line in questions: print line, - if lines == oldlines: - print 'No changes.' - return - print 'Writing new file...' - f = open(FAQ + '.new', 'w') - for line in lines: - f.write(line) - f.close() - print 'Making backup...' - os.rename(FAQ, FAQ + '~') - print 'Moving new file...' - os.rename(FAQ + '.new', FAQ) - print 'Done.' - -main() diff --git a/Misc/setuid-prog.c b/Misc/setuid-prog.c deleted file mode 100644 index 6f25493cca..0000000000 --- a/Misc/setuid-prog.c +++ /dev/null @@ -1,172 +0,0 @@ -/* - Template for a setuid program that calls a script. - - The script should be in an unwritable directory and should itself - be unwritable. In fact all parent directories up to the root - should be unwritable. The script must not be setuid, that's what - this program is for. - - This is a template program. You need to fill in the name of the - script that must be executed. This is done by changing the - definition of FULL_PATH below. - - There are also some rules that should be adhered to when writing - the script itself. - - The first and most important rule is to never, ever trust that the - user of the program will behave properly. Program defensively. - Check your arguments for reasonableness. If the user is allowed to - create files, check the names of the files. If the program depends - on argv[0] for the action it should perform, check it. - - Assuming the script is a Bourne shell script, the first line of the - script should be - #!/bin/sh - - The - is important, don't omit it. If you're using esh, the first - line should be - #!/usr/local/bin/esh -f - and for ksh, the first line should be - #!/usr/local/bin/ksh -p - The script should then set the variable IFS to the string - consisting of <space>, <tab>, and <newline>. After this (*not* - before!), the PATH variable should be set to a reasonable value and - exported. Do not expect the PATH to have a reasonable value, so do - not trust the old value of PATH. You should then set the umask of - the program by calling - umask 077 # or 022 if you want the files to be readable - If you plan to change directories, you should either unset CDPATH - or set it to a good value. Setting CDPATH to just ``.'' (dot) is a - good idea. - If, for some reason, you want to use csh, the first line should be - #!/bin/csh -fb - You should then set the path variable to something reasonable, - without trusting the inherited path. Here too, you should set the - umask using the command - umask 077 # or 022 if you want the files to be readable -*/ - -#include <unistd.h> -#include <stdlib.h> -#include <stdio.h> -#include <sys/types.h> -#include <sys/stat.h> - -/* CONFIGURATION SECTION */ - -#ifndef FULL_PATH /* so that this can be specified from the Makefile */ -#define FULL_PATH "/full/path/of/script" -#endif -#ifndef UMASK -#define UMASK 077 -#endif - -/* END OF CONFIGURATION SECTION */ - -#if defined(__STDC__) && defined(__sgi) -#define environ _environ -#endif - -/* don't change def_IFS */ -char def_IFS[] = "IFS= \t\n"; -/* you may want to change def_PATH, but you should really change it in */ -/* your script */ -#ifdef __sgi -char def_PATH[] = "PATH=/usr/bsd:/usr/bin:/bin:/usr/local/bin:/usr/sbin"; -#else -char def_PATH[] = "PATH=/usr/ucb:/usr/bin:/bin:/usr/local/bin"; -#endif -/* don't change def_CDPATH */ -char def_CDPATH[] = "CDPATH=."; -/* don't change def_ENV */ -char def_ENV[] = "ENV=:"; - -/* - This function changes all environment variables that start with LD_ - into variables that start with XD_. This is important since we - don't want the script that is executed to use any funny shared - libraries. - - The other changes to the environment are, strictly speaking, not - needed here. They can safely be done in the script. They are done - here because we don't trust the script writer (just like the script - writer shouldn't trust the user of the script). - If IFS is set in the environment, set it to space,tab,newline. - If CDPATH is set in the environment, set it to ``.''. - Set PATH to a reasonable default. -*/ -void -clean_environ(void) -{ - char **p; - extern char **environ; - - for (p = environ; *p; p++) { - if (strncmp(*p, "LD_", 3) == 0) - **p = 'X'; - else if (strncmp(*p, "_RLD", 4) == 0) - **p = 'X'; - else if (strncmp(*p, "IFS=", 4) == 0) - *p = def_IFS; - else if (strncmp(*p, "CDPATH=", 7) == 0) - *p = def_CDPATH; - else if (strncmp(*p, "ENV=", 4) == 0) - *p = def_ENV; - } - putenv(def_PATH); -} - -int -main(int argc, char **argv) -{ - struct stat statb; - gid_t egid = getegid(); - uid_t euid = geteuid(); - - /* - Sanity check #1. - This check should be made compile-time, but that's not possible. - If you're sure that you specified a full path name for FULL_PATH, - you can omit this check. - */ - if (FULL_PATH[0] != '/') { - fprintf(stderr, "%s: %s is not a full path name\n", argv[0], - FULL_PATH); - fprintf(stderr, "Tell this program's maintainer that s\\he "); - fprintf(stderr, "fouled up some simple rules\n"); - fprintf(stderr, "pretty badly.\n"); - exit(1); - } - - /* - Sanity check #2. - Check that the owner of the script is equal to either the - effective uid or the super user. - */ - if (stat(FULL_PATH, &statb) < 0) { - perror("stat"); - exit(1); - } - if (statb.st_uid != 0 && statb.st_uid != euid) { - fprintf(stderr, "%s: %s has the wrong owner\n", argv[0], - FULL_PATH); - fprintf(stderr, "Tell this program's maintainer that the "); - fprintf(stderr, "script should be owned by him/herself or the\n"); - fprintf(stderr, "superuser.\n"); - exit(1); - } - - if (setregid(egid, egid) < 0) - perror("setregid"); - if (setreuid(euid, euid) < 0) - perror("setreuid"); - - clean_environ(); - - umask(UMASK); - - while (**argv == '-') /* don't let argv[0] start with '-' */ - (*argv)++; - execv(FULL_PATH, argv); - fprintf(stderr, "%s: could not execute the script\n", argv[0]); - exit(1); -} diff --git a/Modules/Makefile.pre.in b/Modules/Makefile.pre.in deleted file mode 100644 index 69eb540f8e..0000000000 --- a/Modules/Makefile.pre.in +++ /dev/null @@ -1,181 +0,0 @@ -# META-NOTE: this note is different from the note in the other Makefiles! -# NOTE: Makefile.pre.in is converted into Makefile.pre by the configure -# script in the toplevel directory or by ../config.status. -# Makefile.pre is converted into Makefile by running the makesetup -# script in the source directory. Once Makefile exists, it can be -# brought up to date by running "make Makefile". (The makesetup also -# creates config.c from config.c.in in the source directory.) - -# === Variables set by makesetup === - -MODOBJS= _MODOBJS_ -MODLIBS= _MODLIBS_ - -# === Variables set by configure === - -srcdir= @srcdir@ -VPATH= @srcdir@ - -CC= @CC@ -RANLIB= @RANLIB@ -AR= @AR@ - -OPT= @OPT@ - -DEFS= @DEFS@ -LIBS= @LIBS@ -LIBM= @LIBM@ -LIBC= @LIBC@ - -# Machine-dependent subdirectories -MACHDEP= @MACHDEP@ - -# Install prefix for architecture-independent files -prefix= @prefix@ - -# Install prefix for architecture-dependent files -exec_prefix= @exec_prefix@ - -# Symbols used for using shared libraries -SO= @SO@ -LDSHARED= @LDSHARED@ -CCSHARED= @CCSHARED@ -LINKFORSHARED= @LINKFORSHARED@ -DESTSHARED= $(exec_prefix)/lib/python/$(MACHDEP) - -# Portable install script (configure doesn't always guess right) -INSTALL= @srcdir@/../install-sh -c -INSTALL_PROGRAM=${INSTALL} -INSTALL_DATA= ${INSTALL} -m 644 - -# === Variables that are customizable by hand or by inclusion in Setup === - -LINKCC= $(CC) -INCLDIR= $(srcdir)/../Include -CFLAGS= $(OPT) -I$(INCLDIR) -I.. $(DEFS) - -MKDEP= mkdep -SHELL= /bin/sh - -MAKESETUP= $(srcdir)/makesetup - -# (The makesetup script inserts all variable definitions found -# found in the Setup file just below the following line. -# This means that the Setup file can override any of the definitions -# given before this point, but not any given below. -# The script insert the definitions in reverse order, -# for the benefits of independent extensions.) -# === Definitions added by makesetup === - -# === Fixed definitions === - -OBJS= $(MODOBJS) - -ADDOBJS= main.o config.o getpath.o - -LIB= libModules.a - -MYLIBS= $(LIB) \ - ../Python/libPython.a \ - ../Objects/libObjects.a \ - ../Parser/libParser.a - -SYSLIBS= $(LIBM) $(LIBC) - - -# === Rules === - -all: $(LIB) ../python sharedmods - -$(LIB): $& $(OBJS) Makefile - -rm -f $(LIB) - $(AR) cr $(LIB) $(OBJS) - $(RANLIB) $(LIB) - -../python: $(MYLIBS) $(ADDOBJS) Makefile - $(LINKCC) $(OPT) $(LINKFORSHARED) $(ADDOBJS) \ - $(MYLIBS) $(MODLIBS) $(LIBS) $(SYSLIBS) -o python - mv python ../python - -clean: - -rm -f *.o python core *~ [@,#]* *.old *.orig *.rej - -clobber: clean - -rm -f *.a tags TAGS config.c glmodule.c Makefile.pre - -rm -f *.so so_locations - -getpath.o: getpath.c Makefile - $(CC) -c $(CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \ - $(srcdir)/getpath.c - -config.c Makefile: Makefile.pre config.c.in $(MAKESETUP) Setup - $(SHELL) $(MAKESETUP) Setup - -Setup: - cp $(srcdir)/Setup.in Setup - -Makefile.pre: Makefile.pre.in ../config.status - (cd ..; CONFIG_FILES=Modules/Makefile.pre CONFIG_HEADERS= \ - $(SHELL) config.status) - -depend: - $(MKDEP) $(CFLAGS) `echo $(OBJS) | tr ' ' '\012' | \ - sed 's|\(.*\)\.o|$(srcdir)/\1.c|'` - -.PRECIOUS: ../python - -glmodule.c: $(srcdir)/cgen.py $(srcdir)/cstubs - python $(srcdir)/cgen.py <$(srcdir)/cstubs >glmodule.c - -almodule.o: almodule.c -arraymodule.o: arraymodule.c -audioop.o: audioop.c -cdmodule.o: cdmodule.c -clmodule.o: clmodule.c -dbmmodule.o: dbmmodule.c -fcntlmodule.o: fcntlmodule.c -flmodule.o: flmodule.c -fmmodule.o: fmmodule.c -glmodule.o: glmodule.c -imageop.o: imageop.c -imgfile.o: imgfile.c -main.o: main.c -mathmodule.o: mathmodule.c -md5c.o: md5c.c -md5module.o: md5module.c -mpzmodule.o: mpzmodule.c -nismodule.o: nismodule.c -parsermodule.o: parsermodule.c -posixmodule.o: posixmodule.c -pwdmodule.o: pwdmodule.c -regexmodule.o: regexmodule.c -regexpr.o: regexpr.c -rgbimgmodule.o: rgbimgmodule.c -rotormodule.o: rotormodule.c -selectmodule.o: selectmodule.c -sgimodule.o: sgimodule.c -socketmodule.o: socketmodule.c -stdwinmodule.o: stdwinmodule.c -stropmodule.o: stropmodule.c -structmodule.o: structmodule.c -sunaudiodev.o: sunaudiodev.c -svmodule.o: svmodule.c -threadmodule.o: threadmodule.c -timemodule.o: timemodule.c -timingmodule.o: timingmodule.c -xxmodule.o: xxmodule.c -yuvconvert.o: yuvconvert.c - -# Rules to build and install all shared modules -sharedmods: $(SHAREDMODS) -sharedinstall: $(DESTSHARED) $(SHAREDMODS) - -for i in X $(SHAREDMODS); do \ - if test $$i != X; \ - then $(INSTALL_DATA) $$i $(DESTSHARED)/$$i; \ - fi; \ - done - -$(DESTSHARED): - mkdir $(DESTSHARED); chmod 755 $(DESTSHARED) - -# Stuff is appended here by makesetup and make depend diff --git a/Modules/Setup.in b/Modules/Setup.in deleted file mode 100644 index f6755678f9..0000000000 --- a/Modules/Setup.in +++ /dev/null @@ -1,319 +0,0 @@ -# The file Setup is used by the makesetup script to construct the files -# Makefile and config.c, from Makefile.pre and config.c.in, -# respectively. The file Setup itself is initially copied from -# Setup.in; once it exists it will not be overwritten, so you can edit -# Setup to your heart's content. Note that Makefile.pre is created -# from Makefile.pre.in by the toplevel configure script. - -# (VPATH notes: Setup and Makefile.pre are in the build directory, as -# are Makefile and config.c; the *.in files are in the source -# directory.) - -# Each line in this file describes one or more optional modules. -# Comment out lines to suppress modules. -# Lines have the following structure: -# -# <module> ... [<sourcefile> ...] [<cpparg> ...] [<library> ...] -# -# <sourcefile> is anything ending in .c (.C, .cc, .c++ are C++ files) -# <cpparg> is anything starting with -I, -D, -U or -C -# <library> is anything ending in .a or beginning with -l or -L -# <module> is anything else but should be a valid Python -# identifier (letters, digits, underscores, beginning with non-digit) -# -# Lines can also have the form -# -# <name> = <value> -# -# which defines a Make variable definition inserted into Makefile.in -# -# Finally, if a line has the literal form -# -# *noconfig* -# -# (that is including the '*' and '*' !) then the following modules will -# not be included in the config.c file, nor in the list of objects to be -# added to the library archive, and their linker options won't be added -# to the linker options, but rules to create their .o files and their -# shared libraries will still be added to the Makefile, and their -# names will be collected in the Make variable SHAREDMODS. This is -# used to build modules as shared libraries. (They must be installed -# using "make sharedinstall".) - -# NOTE: As a standard policy, as many modules as can be supported by a -# platform should be present. The distribution comes with all modules -# enabled that are supported by most platforms and don't require you -# to ftp sources from elsewhere. - - -# Some special rules to define PYTHONPATH. -# Edit the definitions below to indicate which options you are using. -# Don't add any whitespace or comments! - -# Don't edit this (usually) -DESTLIB=$(prefix)/lib/python - -# Site specific path insertions -- should begin with : if non-empty -SITEPATH= - -# Standard path -- don't edit -DESTPATH=:$(DESTLIB) - -# Standard enabled (tests are always available) -TESTPATH=:$(DESTLIB)/test - -# Path for machine- or system-dependent modules (and shared libraries) -MACHDEPPATH=:$(DESTLIB)/$(MACHDEP) - -COREPYTHONPATH=.$(SITEPATH)$(DESTPATH)$(TESTPATH)$(MACHDEPPATH)$(STDWINPATH)$(TKPATH) -PYTHONPATH=$(COREPYTHONPATH) - - -# The modules listed here can't be built as shared libraries for -# various reasons; therefore they are listed here instead of in the -# normal order. - -# Some modules that are normally always on: - -posix posixmodule.c # posix (UNIX) system calls -signal signalmodule.c # signal(2) - -# The SGI specific GL module: - -#gl glmodule.c -lgl -lX11 # Graphics Library -- SGI only - -# Thread module -- works on selected systems only, e.g. SGI IRIX and -# on SunOS 5.x (SOLARIS) only. -# Note that you must have configured (and built!) Python with the -# --with-thread option passed to the configure script for this to work: - -#thread threadmodule.c - -# Uncommenting the following line tells makesetup that all following -# modules are to be built as shared libraries (see above for more -# detail): - -#*noconfig* - - -# Modules that should always be present (non UNIX dependent): - -array arraymodule.c # array objects -cmath cmathmodule.c # complex math library functions -math mathmodule.c -lm # math library functions, e.g. sin() -regex regexmodule.c regexpr.c # Regular expressions, GNU Emacs style -strop stropmodule.c # fast string operations implemented in C -struct structmodule.c # binary structure packing/unpacking -time timemodule.c # time operations and variables - - -# Modules with some UNIX dependencies -- on by default: -# (If you have a really backward UNIX, select and socket may not be -# supported...) - -fcntl fcntlmodule.c # fcntl(2) and ioctl(2) -pwd pwdmodule.c # pwd(3) -grp grpmodule.c # grp(3) -crypt cryptmodule.c # -lcrypt # crypt(3); needs -lcrypt on some systems -select selectmodule.c # select(2); not on ancient System V -socket socketmodule.c # socket(2); not on ancient System V - - -# Some more UNIX dependent modules -- off by default, since these -# are not supported by all UNIX systems: - -#dbm dbmmodule.c # dbm(3) may require -lndbm or similar -#nis nismodule.c # Sun yellow pages -- not everywhere -#termios termios.c # Steen Lumholt's termios module - - -# Multimedia modules -- on by default. -# These represent audio samples or images as strings: - -audioop audioop.c # Operations on audio samples -imageop imageop.c # Operations on images -rgbimg rgbimgmodule.c # Read SGI RGB image files (but coded portably) - - -# The stdwin module provides a simple, portable (between X11 and Mac) -# windowing interface. You need to ftp the STDWIN library, e.g. from -# ftp://ftp.cwi.nl/pub/stdwin. (If you get it elsewhere, be sure to -# get version 1.0 or higher!) The STDWIN variable must point to the -# STDWIN toplevel directory. - -# Uncomment and edit as needed: -#STDWIN=/ufs/guido/src/stdwin - -# Uncomment these lines: -#STDWINPATH=:$(DESTLIB)/stdwin -#LIBTEXTEDIT=$(STDWIN)/$(MACHDEP)/Packs/textedit/libtextedit.a -#LIBX11STDWIN=$(STDWIN)/$(MACHDEP)/Ports/x11/libstdwin.a -#stdwin stdwinmodule.c -I$(STDWIN)/H $(LIBTEXTEDIT) $(LIBX11STDWIN) -lX11 - -# Use this instead of the last two lines above for alphanumeric stdwin: -#LIBALFASTDWIN=$(STDWIN)/$(MACHDEP)/Ports/alfa/libstdwin.a -#stdwin stdwinmodule.c -I$(STDWIN)/H $(LIBTEXTEDIT) $(LIBALFASTDWIN) -ltermcap - - -# The md5 module implements the RSA Data Security, Inc. MD5 -# Message-Digest Algorithm, described in RFC 1321. The necessary files -# md5c.c and md5.h are included here. - -md5 md5module.c md5c.c - - -# The mpz module interfaces to the GNU Multiple Precision library. -# You need to ftp the GNU MP library. -# The GMP variable must point to the GMP source directory. -# This was originally written and tested against GMP 1.2. I have -# compiled it against GMP 1.3.2 (the latest I believe) and it seems to -# work OK, but I haven't tested it thoroughly (lacking knowledge about -# it). - -# A compatible MP library unencombered by the GPL also exists. It was -# posted to comp.sources.misc in volume 40 and is widely available from -# FTP archive sites. One URL for it is: -# ftp://gatekeeper.dec.com/.b/usenet/comp.sources.misc/volume40/fgmp/part01.Z - -#GMP=/ufs/guido/src/gmp -#mpz mpzmodule.c -I$(GMP) $(GMP)/libgmp.a - - -# SGI IRIX specific modules -- off by default. - -# These module work on any SGI machine: - -# *** gl must be enabled higher up in this file *** -#fm fmmodule.c -lfm -lgl # Font Manager -#sgi sgimodule.c # sgi.nap() and a few more - -# This module requires the header file -# /usr/people/4Dgifts/iristools/include/izoom.h: - -#imgfile imgfile.c -limage -lgutil -lm # Image Processing Utilities - - -# These modules require the Multimedia Development Option (I think): - -#al almodule.c -laudio # Audio Library -#cd cdmodule.c -lcdaudio -lds -lmediad # CD Audio Library -#cl clmodule.c -lcl -lawareaudio # Compression Library -#sv svmodule.c yuvconvert.c -lsvideo -lXext -lX11 # Starter Video - - -# The FORMS library, by Mark Overmars, implements user interface -# components such as dialogs and buttons using SGI's GL and FM -# libraries. You must ftp the FORMS library separately from -# ftp://ftp.cs.ruu.nl/pub/SGI/FORMS. It was tested with FORMS 2.2a. -# The FORMS variable must point to the FORMS subdirectory of the forms -# toplevel directory: - -#FORMS=/ufs/guido/src/forms/FORMS -#fl flmodule.c -I$(FORMS) $(FORMS)/libforms.a -lfm -lgl - - -# SunOS specific modules -- off by default: - -#sunaudiodev sunaudiodev.c - - -# George Neville-Neil's timing module: - -#timing timingmodule.c - - -# Steen Lumholt's tkinter module. -# -# For use with plain Tk, use the first line. -# -# For use with extended Tk (i.e. if you have added extra widgets to -# the Tk library, such as the common "studButton" and "triButton" -# extensions), edit tkappinit.c, add appropriate -DWITH_... and -# libraries/objects to the second line, and use that. -# -# In all cases also enable the last line (TKPATH). -# -# See the section "The Tk interface" in ../README for more info. - -# *** Use ONE of the following two lines, see previous comments *** -#_tkinter _tkinter.c -I/usr/local/include -L/usr/local/lib -ltk4.0 -ltcl7.4 -lX11 -#_tkinter _tkinter.c tkappinit.c -DWITH_APPINIT -I/usr/local/include -L/usr/local/lib -ltk -ltcl -lX11 - -# *** ALWAYS use this line as well *** -#TKPATH=:$(DESTLIB)/tkinter - - -# Lance Ellinghaus's modules: - -rotor rotormodule.c # enigma-inspired encryption -#syslog syslogmodule.c # syslog daemon interface - - -# Lance's curses module. This requires the System V version of -# curses, sometimes known as ncurses (e.g. on Linux, link with -# -lncurses instead of -lcurses; on SunOS 4.1.3, insert -I/usr/5include -# -L/usr/5lib before -lcurses). - -#curses cursesmodule.c -lcurses -ltermcap - - - -# Tommy Burnette's 'new' module (creates new empty objects of certain kinds): - -#new newmodule.c - - -# John Redford's sybase module (requires sybase): -# (Unfortunately this code is orphaned. Read the source for documentation.) - -#sybase sybasemodule.c - - -# Generic (SunOS / SVR4) dynamic loading module. -# This is not needed for dynamic loading of Python modules -- -# it is a highly experimental and dangerous device for calling -# *arbitrary* C functions in *arbitrary* shared libraries: - -#dl dlmodule.c - - -# Anthony Baxter's gdbm module (derived from Jack's dbm module) -# GNU dbm(3) will require -lgdbm: - -#gdbm gdbmmodule.c -I/usr/local/include -L/usr/local/lib -lgdbm - - -# Berkeley DB interface. -# -# This requires the Berkeley DB code, see -# ftp://ftp.cs.berkeley.edu/pub/4bsd/db.1.85.tar.gz -# -# Edit the variables DB and DBPORT to point to the db top directory -# and the subdirectory of PORT where you built it. - -#DB=/depot/sundry/src/db.1.85/ -#DBPORT=$(DB)/PORT/sunos.5.2 -#bsddb bsddbmodule.o -I$(DB)/include -I$(DBPORT) $(DBPORT)/libdb.a - - - -# Andy Bensky's "environment" module (contains putenv()) -#environment environment.c - -# David Wayne Williams' soundex module -#soundex soundex.c - -# Objective-C (incomplete!!!) -#objc.c - -# Helper module for various ascii-encoders -binascii binascii.c - -# Fred Drake's interface to the Python parser. -# (Not enabled by default because it is big and doesn't compile with -# cc on SunOS 4.1.3) -#parser parsermodule.c - - -# Example -- included for reference only: -# xx xxmodule.c diff --git a/Modules/_cursesmodule.c b/Modules/_cursesmodule.c deleted file mode 100644 index 25a18a5a62..0000000000 --- a/Modules/_cursesmodule.c +++ /dev/null @@ -1,1584 +0,0 @@ -/*********************************************************** -Copyright 1994 by Lance Ellinghouse, -Cathedral City, California Republic, United States of America. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the name of Lance Ellinghouse -not be used in advertising or publicity pertaining to distribution -of the software without specific, written prior permission. - -LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE 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. - -******************************************************************/ - -/****************************************************************** -This is a curses implementation. I have tried to be as complete -as possible. If there are functions you need that are not included, -please let me know and/or send me some diffs. - -There are 3 basic types exported by this module: - 1) Screen - This is not currently used - 2) Window - This is the basic type. This is equivalent to "WINDOW *". - 3) Pad - This is similar to Window, but works with Pads as defined - in curses. - -Most of the routines can be looked up using the curses man page. - -Here is a list of the currently supported methods and attributes -in the curses module: - -Return Value Func/Attr Description --------------------------------------------------------------------------- -StringObject version A string representing the current - version of this module. -WindowObject initscr() This initializes the screen for use -None endwin() Closes down the screen and returns - things as they were before calling - initscr() -True/FalseObject isendwin() Has endwin() been called? -None doupdate() Updates screen -WindowObject newwin(nlines,ncols,begin_y,begin_x) - newwin(begin_y,begin_x) - newwin() creates and returns - a new window. -None beep() Beep the screen if possible -None flash() Flash the screen if possible -None ungetch(int) Push the int back so next getch() - will return it. - Note: argument is an INT, not a CHAR -None flushinp() Flush all input buffers -None cbreak() Enter cbreak mode -None nocbreak() Leave cbreak mode -None echo() Enter echo mode -None noecho() Leave echo mode -None nl() Enter nl mode -None nonl() Leave nl mode -None raw() Enter raw mode -None noraw() Leave raw mode -None intrflush(int) Set or reset interruptable flush - mode, int=1 if set, 0 if notset. -None meta(int) Allow 8 bit or 7 bit chars. - int=1 is 8 bit, int=0 is 7 bit -StringObject keyname(int) return the text representation - of a KEY_ value. (see below) - -Here is a list of the currently supported methods and attributes -in the WindowObject: - -Return Value Func/Attr Description --------------------------------------------------------------------------- -None refresh() Do refresh -None nooutrefresh() Mark for refresh but wait -None mvwin(new_y,new_x) Move Window -None move(new_y,new_x) Move Cursor -WindowObject subwin(nlines,ncols,begin_y,begin_x) - subwin(begin_y,begin_x) -None addch(y,x,ch,attr) - addch(y,x,ch) - addch(ch,attr) - addch(ch) -None insch(y,x,ch,attr) - insch(y,x,ch) - insch(ch,attr) - insch(ch) -None delch(y,x) - delch() -None echochar(ch,attr) - echochar(ch) -None addstr(y,x,str,attr) - addstr(y,x,str) - addstr(str,attr) - addstr(str) -None attron(attr) -None attroff(attr) -None attrset(sttr) -None standend() -None standout() -None border(ls,rs,ts,bs,tl,tr,bl,br) (accepts 0-8 INT args) -None box(vertch,horch) vertch and horch are INTS - box() -None hline(y,x,ch,n) - hline(ch,n) -None vline(y,x,ch,n) - vline(ch,n) -None erase() -None deleteln() -None insertln() -(y,x) getyx() -(y,x) getbegyx() -(y,x) getmaxyx() -None clear() -None clrtobot() -None clrtoeol() -None scroll() -None touchwin() -None touchline(start,count) -IntObject getch(y,x) - getch() -StringObject getstr(y,x) - getstr() -IntObject inch(y,x) - inch() -None clearok(int) int=0 or int=1 -None idlok(int) int=0 or int=1 -None leaveok(int) int=0 or int=1 -None scrollok(int) int=0 or int=1 -None setscrreg(top,bottom) -None keypad(int) int=0 or int=1 -None nodelay(int) int=0 or int=1 -None notimeout(int) int=0 or int=1 -******************************************************************/ - - -/* curses module */ - -#include "Python.h" - -#ifdef HAVE_NCURSES_H -/* Now let's hope there aren't systems that have a broken ncurses.h */ -#include <ncurses.h> -#else -#include <curses.h> -#endif - -typedef struct { - PyObject_HEAD - SCREEN *scr; -} PyCursesScreenObject; - -typedef struct { - PyObject_HEAD - WINDOW *win; - WINDOW *parent; -} PyCursesWindowObject; - -typedef struct { - PyObject_HEAD - WINDOW *pad; -} PyCursesPadObject; - -staticforward PyTypeObject PyCursesScreen_Type; -staticforward PyTypeObject PyCursesWindow_Type; -staticforward PyTypeObject PyCursesPad_Type; - -#define PyCursesScreen_Check(v) ((v)->ob_type == &PyCursesScreen_Type) -#define PyCursesWindow_Check(v) ((v)->ob_type == &PyCursesWindow_Type) -#define PyCursesPad_Check(v) ((v)->ob_type == &PyCursesPad_Type) - -/* Defines */ -static PyObject *PyCursesError; /* For exception curses.error */ - -/* Catch-all error messages */ -static char *catchall_ERR = "curses function returned ERR"; -static char *catchall_NULL = "curses function returned NULL"; - -/* Tells whether initscr() has been called to initialise curses */ -static int initialised = FALSE; - -#define ARG_COUNT(X) \ - (((X) == NULL) ? 0 : (PyTuple_Check(X) ? PyTuple_Size(X) : 1)) - -/****************************************************************** - -Change Log: - -Version 1.2: 95/02/23 (Steve Clift) - Fixed several potential core-dumping bugs. - Reworked arg parsing where variable arg lists are used. - Generate exceptions when ERR or NULL is returned by curses functions. - Changed return types to match SysV Curses manual descriptions. - Added keypad() to window method list. - Added border(), hline() and vline() window methods. - -Version 1.1: 94/08/31: - Minor fixes given by Guido. - Changed 'ncurses' to 'curses' - Changed '__version__' to 'version' - Added PyErr_Clear() where needed - Moved ACS_* attribute initialization to PyCurses_InitScr() to fix - crash on SGI - -Version 1.0: 94/08/30: - This is the first release of this software. - Released to the Internet via python-list@cwi.nl - -******************************************************************/ - -char *PyCursesVersion = "1.2"; - -/* - * Check the return code from a curses function and return None - * or raise an exception as appropriate. - */ - -static PyObject * -PyCursesCheckERR(code, fname) - int code; - char *fname; -{ - char buf[100]; - - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - if (fname == NULL) { - PyErr_SetString(PyCursesError, catchall_ERR); - } else { - strcpy(buf, fname); - strcat(buf, "() returned ERR"); - PyErr_SetString(PyCursesError, buf); - } - return NULL; - } -} - - -static int -PyCursesInitialised() -{ - if (initialised == TRUE) - return 1; - else { - PyErr_SetString(PyCursesError, "must call initscr() first"); - return 0; - } -} - - -/* ------------- SCREEN routines --------------- */ - -#ifdef NOT_YET -static PyObject * -PyCursesScreen_New(arg) - PyObject * arg; -{ - char *term_type; - PyFileObject *in_fo; - PyFileObject *out_fo; - PyCursesScreenObject *xp; - xp = PyObject_NEW(PyCursesScreenObject, &PyCursesScreen_Type); - if (xp == NULL) - return NULL; - return (PyObject *)xp; -} -#endif - - -/* ------------- WINDOW routines --------------- */ - -static PyObject * -PyCursesWindow_New(win) - WINDOW *win; -{ - PyCursesWindowObject *wo; - - wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); - if (wo == NULL) - return NULL; - wo->win = win; - wo->parent = (WINDOW *)NULL; - return (PyObject *)wo; -} - -static void -PyCursesWindow_Dealloc(wo) - PyCursesWindowObject *wo; -{ - if (wo->win != stdscr) - delwin(wo->win); - PyMem_DEL(wo); -} - -static PyObject * -PyCursesWindow_Refresh(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg)) - return NULL; - return PyCursesCheckERR(wrefresh(self->win), "wrefresh"); -} - -static PyObject * -PyCursesWindow_NoOutRefresh(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg)) - return NULL; - return PyCursesCheckERR(wnoutrefresh(self->win), "wnoutrefresh"); -} - -static PyObject * -PyCursesWindow_MoveWin(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int x, y; - if (!PyArg_Parse(arg,"(ii);y,x", &y, &x)) - return NULL; - return PyCursesCheckERR(mvwin(self->win,y,x), "mvwin"); -} - -static PyObject * -PyCursesWindow_Move(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int x, y; - if (!PyArg_Parse(arg,"(ii);y,x", &y, &x)) - return NULL; - return PyCursesCheckERR(wmove(self->win,y,x), "wmove"); -} - -static PyObject * -PyCursesWindow_SubWin(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - WINDOW *win; - PyCursesWindowObject *rtn_win; - int nlines, ncols, begin_y, begin_x; - - nlines = 0; - ncols = 0; - switch (ARG_COUNT(arg)) { - case 2: - if (!PyArg_Parse(arg,"(ii);begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_Parse(arg, "(iiii);nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); - return NULL; - } - win = subwin(self->win,nlines,ncols,begin_y,begin_x); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - rtn_win = (PyCursesWindowObject *)PyCursesWindow_New(win); - rtn_win->parent = self->win; - return (PyObject *)rtn_win; -} - -static PyObject * -PyCursesWindow_AddCh(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int rtn; - int x, y; - int ch; - int attr, attr_old; - int use_xy = FALSE, use_attr = FALSE; - - switch (ARG_COUNT(arg)) { - case 1: - if (!PyArg_Parse(arg, "i;ch", &ch)) - return NULL; - break; - case 2: - if (!PyArg_Parse(arg,"(ii);ch,attr", &ch, &attr)) - return NULL; - use_attr = TRUE; - break; - case 3: - if (!PyArg_Parse(arg,"(iii);y,x,ch", &y, &x, &ch)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_Parse(arg,"(iiii);y,x,ch,attr", &y, &x, &ch, &attr)) - return NULL; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddch(self->win,y,x,ch); - else - rtn = waddch(self->win,ch); - if (use_attr == TRUE) - wattrset(self->win,attr_old); - - return PyCursesCheckERR(rtn, "[mv]waddch"); -} - -static PyObject * -PyCursesWindow_InsCh(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int rtn; - int x, y; - int ch; - int attr, attr_old; - int use_xy = TRUE, use_attr = FALSE; - - switch (ARG_COUNT(arg)) { - case 1: - if (!PyArg_Parse(arg, "i;ch", &ch)) - return NULL; - break; - case 2: - if (!PyArg_Parse(arg,"(ii);ch,attr", &ch, &attr)) - return NULL; - use_attr = TRUE; - break; - case 3: - if (!PyArg_Parse(arg,"(iii);y,x,ch", &y, &x, &ch)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_Parse(arg,"(iiii);y,x,ch,attr", &y, &x, &ch, &attr)) - return NULL; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insch requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsch(self->win,y,x,ch); - else - rtn = winsch(self->win,ch); - if (use_attr == TRUE) - wattrset(self->win,attr_old); - - return PyCursesCheckERR(rtn, "[mv]winsch"); -} - -static PyObject * -PyCursesWindow_DelCh(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int rtn; - int x, y; - - switch (ARG_COUNT(arg)) { - case 0: - rtn = wdelch(self->win); - break; - case 2: - if (!PyArg_Parse(arg,"(ii);y,x", &y, &x)) - return NULL; - rtn = mvwdelch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); - return NULL; - } - - return PyCursesCheckERR(rtn, "[mv]wdelch"); -} - -static PyObject * -PyCursesWindow_EchoChar(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int rtn; - int ch; - int attr, attr_old; - - switch (ARG_COUNT(arg)) { - case 1: - if (!PyArg_Parse(arg,"i;ch", &ch)) - return NULL; - rtn = wechochar(self->win,ch); - break; - case 2: - if (!PyArg_Parse(arg,"(ii);ch,attr", &ch, &attr)) - return NULL; - attr_old = getattrs(self->win); - wattrset(self->win,attr); - rtn = wechochar(self->win,ch); - wattrset(self->win,attr_old); - break; - default: - PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); - return NULL; - } - - return PyCursesCheckERR(rtn, "wechochar"); -} - -static PyObject * -PyCursesWindow_AddStr(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int rtn; - int x, y; - char *str; - int attr, attr_old; - int use_xy = FALSE, use_attr = FALSE; - - switch (ARG_COUNT(arg)) { - case 1: - if (!PyArg_Parse(arg,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_Parse(arg,"(si);str,attr", &str, &attr)) - return NULL; - use_attr = TRUE; - break; - case 3: - if (!PyArg_Parse(arg,"(iis);y,x,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_Parse(arg,"(iisi);y,x,str,attr", &y, &x, &str, &attr)) - return NULL; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddstr(self->win,y,x,str); - else - rtn = waddstr(self->win,str); - if (use_attr == TRUE) - wattrset(self->win,attr_old); - - return PyCursesCheckERR(rtn, "[mv]waddstr"); -} - -static PyObject * -PyCursesWindow_AttrOn(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int ch; - if (!PyArg_Parse(arg,"i;attr", &ch)) - return NULL; - wattron(self->win,ch); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_AttrOff(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int ch; - if (!PyArg_Parse(arg,"i;attr", &ch)) - return NULL; - wattroff(self->win,ch); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_AttrSet(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int ch; - if (!PyArg_Parse(arg,"i;attr", &ch)) - return NULL; - wattrset(self->win,ch); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_StandEnd(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg)) - return NULL; - wstandend(self->win); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_StandOut(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg)) - return NULL; - wstandout(self->win); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_Border(self, args) - PyCursesWindowObject *self; - PyObject *args; -{ - int ls, rs, ts, bs, tl, tr, bl, br; - ls = rs = ts = bs = tl = tr = bl = br = 0; - if (!PyArg_ParseTuple(args,"|iiiiiiii;ls,rs,ts,bs,tl,tr,bl,br", - &ls, &rs, &ts, &bs, &tl, &tr, &bl, &br)) - return NULL; - wborder(self->win, ls, rs, ts, bs, tl, tr, bl, br); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_Box(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int ch1=0,ch2=0; - if (!PyArg_NoArgs(arg)) { - PyErr_Clear(); - if (!PyArg_Parse(arg,"(ii);vertch,horch", &ch1, &ch2)) - return NULL; - } - box(self->win,ch1,ch2); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_Hline(self, args) - PyCursesWindowObject *self; - PyObject *args; -{ - int ch, n, x, y, code = OK; - switch (ARG_COUNT(args)) { - case 2: - if (!PyArg_Parse(args, "(ii);ch,n", &ch, &n)) - return NULL; - break; - case 4: - if (!PyArg_Parse(args, "(iiii);y,x,ch,n", &y, &x, &ch, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "hline requires 2 or 4 arguments"); - return NULL; - } - if (code != ERR) - whline(self->win, ch, n); - return PyCursesCheckERR(code, "wmove"); -} - -static PyObject * -PyCursesWindow_Vline(self, args) - PyCursesWindowObject *self; - PyObject *args; -{ - int ch, n, x, y, code = OK; - switch (ARG_COUNT(args)) { - case 2: - if (!PyArg_Parse(args, "(ii);ch,n", &ch, &n)) - return NULL; - break; - case 4: - if (!PyArg_Parse(args, "(iiii);y,x,ch,n", &y, &x, &ch, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "vline requires 2 or 4 arguments"); - return NULL; - } - if (code != ERR) - wvline(self->win, ch, n); - return PyCursesCheckERR(code, "wmove"); -} - -static PyObject * -PyCursesWindow_Erase(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg)) - return NULL; - werase(self->win); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_DeleteLine(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg)) - return NULL; - return PyCursesCheckERR(wdeleteln(self->win), "wdeleteln"); -} - -static PyObject * -PyCursesWindow_InsertLine(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg)) - return NULL; - return PyCursesCheckERR(winsertln(self->win), "winsertln"); -} - -static PyObject * -PyCursesWindow_GetYX(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int x, y; - if (!PyArg_NoArgs(arg)) - return NULL; - getyx(self->win,y,x); - return Py_BuildValue("(ii)", y, x); -} - -static PyObject * -PyCursesWindow_GetBegYX(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int x, y; - if (!PyArg_NoArgs(arg)) - return NULL; - getbegyx(self->win,y,x); - return Py_BuildValue("(ii)", y, x); -} - -static PyObject * -PyCursesWindow_GetMaxYX(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int x, y; - if (!PyArg_NoArgs(arg)) - return NULL; - getmaxyx(self->win,y,x); - return Py_BuildValue("(ii)", y, x); -} - -static PyObject * -PyCursesWindow_Clear(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg)) - return NULL; - wclear(self->win); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_ClearToBottom(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg)) - return NULL; - wclrtobot(self->win); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_ClearToEOL(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg)) - return NULL; - wclrtoeol(self->win); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_Scroll(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg)) - return NULL; - return PyCursesCheckERR(scroll(self->win), "scroll"); -} - -static PyObject * -PyCursesWindow_TouchWin(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg)) - return NULL; - return PyCursesCheckERR(touchwin(self->win), "touchwin"); -} - -static PyObject * -PyCursesWindow_TouchLine(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int st, cnt; - if (!PyArg_Parse(arg,"(ii);start,count",&st,&cnt)) - return NULL; - return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); -} - -static PyObject * -PyCursesWindow_GetCh(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int x, y; - int rtn; - - switch (ARG_COUNT(arg)) { - case 0: - rtn = wgetch(self->win); - break; - case 2: - if (!PyArg_Parse(arg,"(ii);y,x",&y,&x)) - return NULL; - rtn = mvwgetch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); - return NULL; - } - - return PyInt_FromLong((long) rtn); -} - -static PyObject * -PyCursesWindow_GetStr(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int x, y; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (ARG_COUNT(arg)) { - case 0: - rtn2 = wgetstr(self->win,rtn); - break; - case 2: - if (!PyArg_Parse(arg,"(ii);y,x",&y,&x)) - return NULL; - rtn2 = mvwgetstr(self->win,y,x,rtn); - break; - default: - PyErr_SetString(PyExc_TypeError, "getstr requires 0 or 2 arguments"); - return NULL; - } - - if (rtn2 == ERR) - rtn[0] = 0; - return PyString_FromString(rtn); -} - -static PyObject * -PyCursesWindow_InCh(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int x, y, rtn; - - switch (ARG_COUNT(arg)) { - case 0: - rtn = winch(self->win); - break; - case 2: - if (!PyArg_Parse(arg,"(ii);y,x",&y,&x)) - return NULL; - rtn = mvwinch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); - return NULL; - } - - return PyInt_FromLong((long) rtn); -} - -static PyObject * -PyCursesWindow_ClearOk(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int val; - if (!PyArg_Parse(arg,"i;True(1) or False(0)",&val)) - return NULL; - clearok(self->win,val); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_IdlOk(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int val; - if (!PyArg_Parse(arg,"i;True(1) or False(0)",&val)) - return NULL; - idlok(self->win,val); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_LeaveOk(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int val; - if (!PyArg_Parse(arg,"i;True(1) or False(0)",&val)) - return NULL; - leaveok(self->win,val); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_ScrollOk(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int val; - if (!PyArg_Parse(arg,"i;True(1) or False(0)",&val)) - return NULL; - scrollok(self->win,val); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_SetScrollRegion(self,arg) - PyCursesWindowObject *self; - PyObject * arg; -{ - int x, y; - if (!PyArg_Parse(arg,"(ii);top, bottom",&y,&x)) - return NULL; - return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); -} - -static PyObject * -PyCursesWindow_KeyPad(self,arg) - PyCursesWindowObject * self; - PyObject * arg; -{ - int ch; - if (!PyArg_Parse(arg,"i;True(1), False(0)",&ch)) - return NULL; - keypad(self->win,ch); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_NoDelay(self,arg) - PyCursesWindowObject * self; - PyObject * arg; -{ - int ch; - if (!PyArg_Parse(arg,"i;True(1), False(0)",&ch)) - return NULL; - nodelay(self->win,ch); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCursesWindow_NoTimeout(self,arg) - PyCursesWindowObject * self; - PyObject * arg; -{ - int ch; - if (!PyArg_Parse(arg,"i;True(1), False(0)",&ch)) - return NULL; - notimeout(self->win,ch); - Py_INCREF(Py_None); - return Py_None; -} - -static PyMethodDef PyCursesWindow_Methods[] = { - {"refresh", (PyCFunction)PyCursesWindow_Refresh}, - {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh}, - {"mvwin", (PyCFunction)PyCursesWindow_MoveWin}, - {"move", (PyCFunction)PyCursesWindow_Move}, - {"subwin", (PyCFunction)PyCursesWindow_SubWin}, - {"addch", (PyCFunction)PyCursesWindow_AddCh}, - {"insch", (PyCFunction)PyCursesWindow_InsCh}, - {"delch", (PyCFunction)PyCursesWindow_DelCh}, - {"echochar", (PyCFunction)PyCursesWindow_EchoChar}, - {"addstr", (PyCFunction)PyCursesWindow_AddStr}, - {"attron", (PyCFunction)PyCursesWindow_AttrOn}, - {"attroff", (PyCFunction)PyCursesWindow_AttrOff}, - {"attrset", (PyCFunction)PyCursesWindow_AttrSet}, - {"standend", (PyCFunction)PyCursesWindow_StandEnd}, - {"standout", (PyCFunction)PyCursesWindow_StandOut}, - {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, - {"box", (PyCFunction)PyCursesWindow_Box}, - {"hline", (PyCFunction)PyCursesWindow_Hline}, - {"vline", (PyCFunction)PyCursesWindow_Vline}, - {"erase", (PyCFunction)PyCursesWindow_Erase}, - {"deleteln", (PyCFunction)PyCursesWindow_DeleteLine}, - {"insertln", (PyCFunction)PyCursesWindow_InsertLine}, - {"getyx", (PyCFunction)PyCursesWindow_GetYX}, - {"getbegyx", (PyCFunction)PyCursesWindow_GetBegYX}, - {"getmaxyx", (PyCFunction)PyCursesWindow_GetMaxYX}, - {"clear", (PyCFunction)PyCursesWindow_Clear}, - {"clrtobot", (PyCFunction)PyCursesWindow_ClearToBottom}, - {"clrtoeol", (PyCFunction)PyCursesWindow_ClearToEOL}, - {"scroll", (PyCFunction)PyCursesWindow_Scroll}, - {"touchwin", (PyCFunction)PyCursesWindow_TouchWin}, - {"touchline", (PyCFunction)PyCursesWindow_TouchLine}, - {"getch", (PyCFunction)PyCursesWindow_GetCh}, - {"getstr", (PyCFunction)PyCursesWindow_GetStr}, - {"inch", (PyCFunction)PyCursesWindow_InCh}, - {"clearok", (PyCFunction)PyCursesWindow_ClearOk}, - {"idlok", (PyCFunction)PyCursesWindow_IdlOk}, - {"leaveok", (PyCFunction)PyCursesWindow_LeaveOk}, - {"scrollok", (PyCFunction)PyCursesWindow_ScrollOk}, - {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion}, - {"keypad", (PyCFunction)PyCursesWindow_KeyPad}, - {"nodelay", (PyCFunction)PyCursesWindow_NoDelay}, - {"notimeout", (PyCFunction)PyCursesWindow_NoTimeout}, - {NULL, NULL} /* sentinel */ -}; - -static PyObject * -PyCursesWindow_GetAttr(self, name) - PyCursesWindowObject *self; - char *name; -{ - return Py_FindMethod(PyCursesWindow_Methods, (PyObject *)self, name); -} - - -/* --------------- PAD routines ---------------- */ - -#ifdef NOT_YET -static PyObject * -PyCursesPad_New(pad) - WINDOW *pad; -{ - PyCursesPadObject *po; - po = PyObject_NEW(PyCursesPadObject, &PyCursesPad_Type); - if (po == NULL) - return NULL; - po->pad = pad; - return (PyObject *)po; -} -#endif - - -/* -------------------------------------------------------*/ - -static PyTypeObject PyCursesScreen_Type = { - PyObject_HEAD_INIT(&PyType_Type) - 0, /*ob_size*/ - "curses screen", /*tp_name*/ - sizeof(PyCursesScreenObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)0 /*PyCursesScreen_Dealloc*/, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ -}; - -static PyTypeObject PyCursesWindow_Type = { - PyObject_HEAD_INIT(&PyType_Type) - 0, /*ob_size*/ - "curses window", /*tp_name*/ - sizeof(PyCursesWindowObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)PyCursesWindow_GetAttr, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ -}; - -static PyTypeObject PyCursesPad_Type = { - PyObject_HEAD_INIT(&PyType_Type) - 0, /*ob_size*/ - "curses pad", /*tp_name*/ - sizeof(PyCursesPadObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)0 /*PyCursesPad_Dealloc*/, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ -}; - - -/* -------------------------------------------------------*/ - -static PyObject *ModDict; - -static PyObject * -PyCurses_InitScr(self, args) - PyObject * self; - PyObject * args; -{ - WINDOW *win; - if (!PyArg_NoArgs(args)) - return NULL; - if (initialised == TRUE) { - wrefresh(stdscr); - return (PyObject *)PyCursesWindow_New(stdscr); - } - - win = initscr(); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - initialised = TRUE; - -/* This was moved from initcurses() because core dumped on SGI */ -/* Also, they are probably not defined until you've called initscr() */ -#define SetDictInt(string,ch) \ - PyDict_SetItemString(ModDict,string,PyInt_FromLong((long) (ch))); - - /* Here are some graphic symbols you can use */ - SetDictInt("ACS_ULCORNER",(ACS_ULCORNER)); - SetDictInt("ACS_ULCORNER",(ACS_ULCORNER)); - SetDictInt("ACS_LLCORNER",(ACS_LLCORNER)); - SetDictInt("ACS_URCORNER",(ACS_URCORNER)); - SetDictInt("ACS_LRCORNER",(ACS_LRCORNER)); - SetDictInt("ACS_RTEE", (ACS_RTEE)); - SetDictInt("ACS_LTEE", (ACS_LTEE)); - SetDictInt("ACS_BTEE", (ACS_BTEE)); - SetDictInt("ACS_TTEE", (ACS_TTEE)); - SetDictInt("ACS_HLINE", (ACS_HLINE)); - SetDictInt("ACS_VLINE", (ACS_VLINE)); - SetDictInt("ACS_PLUS", (ACS_PLUS)); - SetDictInt("ACS_S1", (ACS_S1)); - SetDictInt("ACS_S9", (ACS_S9)); - SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); - SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); - SetDictInt("ACS_DEGREE", (ACS_DEGREE)); - SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); - SetDictInt("ACS_BULLET", (ACS_BULLET)); - SetDictInt("ACS_LARROW", (ACS_RARROW)); - SetDictInt("ACS_DARROW", (ACS_DARROW)); - SetDictInt("ACS_UARROW", (ACS_UARROW)); - SetDictInt("ACS_BOARD", (ACS_BOARD)); - SetDictInt("ACS_LANTERN", (ACS_LANTERN)); - SetDictInt("ACS_BLOCK", (ACS_BLOCK)); - - return (PyObject *)PyCursesWindow_New(win); -} - -static PyObject * -PyCurses_EndWin(self, args) - PyObject * self; - PyObject * args; -{ - if (!PyArg_NoArgs(args) || !PyCursesInitialised()) - return NULL; - return PyCursesCheckERR(endwin(), "endwin"); -} - -static PyObject * -PyCurses_IsEndWin(self, args) - PyObject * self; - PyObject * args; -{ - if (!PyArg_NoArgs(args)) - return NULL; - if (isendwin() == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } - Py_INCREF(Py_True); - return Py_True; -} - -static PyObject * -PyCurses_DoUpdate(self,arg) - PyObject * self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg) || !PyCursesInitialised()) - return NULL; - return PyCursesCheckERR(doupdate(), "doupdate"); -} - -static PyObject * -PyCurses_NewWindow(self,arg) - PyObject * self; - PyObject * arg; -{ - WINDOW *win; - int nlines, ncols, begin_y, begin_x; - - if (!PyCursesInitialised()) - return NULL; - nlines = ncols = 0; - switch (ARG_COUNT(arg)) { - case 2: - if (!PyArg_Parse(arg,"(ii);begin)_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_Parse(arg, "(iiii);nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); - return NULL; - } - - win = newwin(nlines,ncols,begin_y,begin_x); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return (PyObject *)PyCursesWindow_New(win); -} - -static PyObject * -PyCurses_Beep(self,arg) - PyObject * self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg) || !PyCursesInitialised()) - return NULL; - beep(); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCurses_Flash(self,arg) - PyObject * self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg) || !PyCursesInitialised()) - return NULL; - flash(); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCurses_UngetCh(self,arg) - PyObject * self; - PyObject * arg; -{ - int ch; - if (!PyArg_Parse(arg,"i;integer",&ch) || !PyCursesInitialised()) - return NULL; - return PyCursesCheckERR(ungetch(ch), "ungetch"); -} - -static PyObject * -PyCurses_FlushInp(self,arg) - PyObject * self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg) || !PyCursesInitialised()) - return NULL; - flushinp(); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCurses_CBreak(self,arg) - PyObject * self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg) || !PyCursesInitialised()) - return NULL; - return PyCursesCheckERR(cbreak(), "cbreak"); -} - -static PyObject * -PyCurses_NoCBreak(self,arg) - PyObject * self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg) || !PyCursesInitialised()) - return NULL; - return PyCursesCheckERR(nocbreak(), "nocbreak"); -} - -static PyObject * -PyCurses_Echo(self,arg) - PyObject * self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg) || !PyCursesInitialised()) - return NULL; - return PyCursesCheckERR(echo(), "echo"); -} - -static PyObject * -PyCurses_NoEcho(self,arg) - PyObject * self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg) || !PyCursesInitialised()) - return NULL; - return PyCursesCheckERR(noecho(), "noecho"); -} - -static PyObject * -PyCurses_Nl(self,arg) - PyObject * self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg) || !PyCursesInitialised()) - return NULL; - return PyCursesCheckERR(nl(), "nl"); -} - -static PyObject * -PyCurses_NoNl(self,arg) - PyObject * self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg) || !PyCursesInitialised()) - return NULL; - return PyCursesCheckERR(nonl(), "nonl"); -} - -static PyObject * -PyCurses_Raw(self,arg) - PyObject * self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg) || !PyCursesInitialised()) - return NULL; - return PyCursesCheckERR(raw(), "raw"); -} - -static PyObject * -PyCurses_NoRaw(self,arg) - PyObject * self; - PyObject * arg; -{ - if (!PyArg_NoArgs(arg) || !PyCursesInitialised()) - return NULL; - return PyCursesCheckERR(noraw(), "noraw"); -} - -static PyObject * -PyCurses_IntrFlush(self,arg) - PyObject * self; - PyObject * arg; -{ - int ch; - if (!PyArg_Parse(arg,"i;True(1), False(0)",&ch)) - return NULL; - return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); -} - -static PyObject * -PyCurses_Meta(self,arg) - PyObject * self; - PyObject * arg; -{ - int ch; - if (!PyArg_Parse(arg,"i;True(1), False(0)",&ch) || !PyCursesInitialised()) - return NULL; - return PyCursesCheckERR(meta(stdscr, ch), "meta"); -} - -static PyObject * -PyCurses_KeyName(self,arg) - PyObject * self; - PyObject * arg; -{ - char *knp; - int ch; - if (!PyArg_Parse(arg,"i",&ch)) - return NULL; - knp = keyname(ch); - return PyString_FromString((knp == NULL) ? "" : knp); -} - -#ifdef NOT_YET -static PyObject * -PyCurses_NewTerm(self, args) - PyObject * self; - PyObject * args; -{ -} - -static PyObject * -PyCurses_SetTerm(self, args) - PyObject * self; - PyObject * args; -{ -} -#endif - -/* List of functions defined in the module */ - -static PyMethodDef PyCurses_methods[] = { - {"initscr", (PyCFunction)PyCurses_InitScr}, - {"endwin", (PyCFunction)PyCurses_EndWin}, - {"isendwin", (PyCFunction)PyCurses_IsEndWin}, - {"doupdate", (PyCFunction)PyCurses_DoUpdate}, - {"newwin", (PyCFunction)PyCurses_NewWindow}, - {"beep", (PyCFunction)PyCurses_Beep}, - {"flash", (PyCFunction)PyCurses_Flash}, - {"ungetch", (PyCFunction)PyCurses_UngetCh}, - {"flushinp", (PyCFunction)PyCurses_FlushInp}, - {"cbreak", (PyCFunction)PyCurses_CBreak}, - {"nocbreak", (PyCFunction)PyCurses_NoCBreak}, - {"echo", (PyCFunction)PyCurses_Echo}, - {"noecho", (PyCFunction)PyCurses_NoEcho}, - {"nl", (PyCFunction)PyCurses_Nl}, - {"nonl", (PyCFunction)PyCurses_NoNl}, - {"raw", (PyCFunction)PyCurses_Raw}, - {"noraw", (PyCFunction)PyCurses_NoRaw}, - {"intrflush", (PyCFunction)PyCurses_IntrFlush}, - {"meta", (PyCFunction)PyCurses_Meta}, - {"keyname", (PyCFunction)PyCurses_KeyName}, -#ifdef NOT_YET - {"newterm", (PyCFunction)PyCurses_NewTerm}, - {"set_term", (PyCFunction)PyCurses_SetTerm}, -#endif - {NULL, NULL} /* sentinel */ -}; - -/* Initialization function for the module */ - -void -initcurses() -{ - PyObject *m, *d, *v; - - /* Create the module and add the functions */ - m = Py_InitModule("curses", PyCurses_methods); - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - ModDict = d; /* For PyCurses_InitScr */ - - /* For exception curses.error */ - PyCursesError = PyString_FromString("curses.error"); - PyDict_SetItemString(d, "error", PyCursesError); - - /* Make the version available */ - v = PyString_FromString(PyCursesVersion); - PyDict_SetItemString(d, "version", v); - PyDict_SetItemString(d, "__version__", v); - Py_DECREF(v); - - /* Here are some attributes you can add to chars to print */ - SetDictInt("A_NORMAL", A_NORMAL); - SetDictInt("A_STANDOUT", A_STANDOUT); - SetDictInt("A_UNDERLINE", A_UNDERLINE); - SetDictInt("A_REVERSE", A_REVERSE); - SetDictInt("A_BLINK", A_BLINK); - SetDictInt("A_DIM", A_DIM); - SetDictInt("A_BOLD", A_BOLD); - SetDictInt("A_ALTCHARSET", A_ALTCHARSET); - - /* Now set everything up for KEY_ variables */ - { - int key; - char *key_n; - char *key_n2; - for (key=KEY_MIN;key < KEY_MAX; key++) { - key_n = (char *)keyname(key); - if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) - continue; - if (strncmp(key_n,"KEY_F(",6)==0) { - char *p1, *p2; - key_n2 = malloc(strlen(key_n)+1); - p1 = key_n; - p2 = key_n2; - while (*p1) { - if (*p1 != '(' && *p1 != ')') { - *p2 = *p1; - p2++; - } - p1++; - } - *p2 = (char)0; - } else - key_n2 = key_n; - PyDict_SetItemString(d,key_n2,PyInt_FromLong((long) key)); - if (key_n2 != key_n) - free(key_n2); - } - SetDictInt("KEY_MIN", KEY_MIN); - SetDictInt("KEY_MAX", KEY_MAX); - } - - /* Check for errors */ - if (PyErr_Occurred()) - Py_FatalError("can't initialize module curses"); -} diff --git a/Modules/_tkinter.c b/Modules/_tkinter.c deleted file mode 100644 index 8df8c4a3aa..0000000000 --- a/Modules/_tkinter.c +++ /dev/null @@ -1,1407 +0,0 @@ -/* _tkinter.c -- Interface to libtk.a and libtcl.a. - Copyright (C) 1994 Steen Lumholt */ - -#include "Python.h" - -#include <tcl.h> -#include <tk.h> - -extern char *getprogramname (); - -/* Internal declarations from tkInt.h. */ -#if (TK_MAJOR_VERSION*1000 + TK_MINOR_VERSION) >= 4001 -extern int Tk_GetNumMainWindows(); -#else -extern int tk_NumMainWindows; -#define Tk_GetNumMainWindows() (tk_NumMainWindows) -#define NEED_TKCREATEMAINWINDOW 1 -#endif - -#if TK_MAJOR_VERSION < 4 -extern struct { Tk_Window win; } *tkMainWindowList; -#endif - -#ifdef macintosh - -/* -** Additional cruft needed by Tcl/Tk on the Mac. -** Unfortunately this changes with each beta. -** This is for beta 2 of Tcl 7.5 and Tk 4.1. -*/ - -#include <Events.h> /* For EventRecord */ - -typedef int (*TclMacConvertEventPtr) Py_PROTO((EventRecord *eventPtr)); -void TclMacSetEventProc Py_PROTO((TclMacConvertEventPtr procPtr)); -int TkMacConvertEvent Py_PROTO((EventRecord *eventPtr)); - -staticforward int PyMacConvertEvent Py_PROTO((EventRecord *eventPtr)); - -#endif /* macintosh */ - -/**** Tkapp Object Declaration ****/ - -staticforward PyTypeObject Tkapp_Type; - -typedef struct - { - PyObject_HEAD - Tcl_Interp *interp; -#ifdef NEED_TKCREATEMAINWINDOW - Tk_Window tkwin; -#endif - } -TkappObject; - -#define Tkapp_Check(v) ((v)->ob_type == &Tkapp_Type) -#ifdef NEED_TKCREATEMAINWINDOW -#define Tkapp_Tkwin(v) (((TkappObject *) (v))->tkwin) -#endif -#define Tkapp_Interp(v) (((TkappObject *) (v))->interp) -#define Tkapp_Result(v) (((TkappObject *) (v))->interp->result) - -#define DEBUG_REFCNT(v) (printf ("DEBUG: id=%p, refcnt=%i\n", \ - (void *) v, ((PyObject *) v)->ob_refcnt)) - -/**** Error Handling ****/ - -static PyObject *Tkinter_TclError; -static int quitMainLoop = 0; -static int errorInCmd = 0; -static PyObject *excInCmd; -static PyObject *valInCmd; -static PyObject *trbInCmd; - -static PyObject * -Tkinter_Error (v) - PyObject *v; -{ - PyErr_SetString (Tkinter_TclError, Tkapp_Result (v)); - return NULL; -} - -int -PythonCmd_Error (interp) - Tcl_Interp *interp; -{ - errorInCmd = 1; - PyErr_Fetch (&excInCmd, &valInCmd, &trbInCmd); - return TCL_ERROR; -} - -/**** Utils ****/ - -static char * -AsString (value, tmp) - PyObject *value; - PyObject *tmp; -{ - if (PyString_Check (value)) - return PyString_AsString (value); - else - { - PyObject *v; - - v = PyObject_Str (value); - PyList_Append (tmp, v); - Py_DECREF (v); - return PyString_AsString (v); - } -} - -#define ARGSZ 64 - -static char * -Merge (args) - PyObject *args; -{ - PyObject *tmp; - char *argvStore[ARGSZ]; - char **argv; - int fvStore[ARGSZ]; - int *fv; - int argc; - char *res; - int i; - - tmp = PyList_New (0); - argv = argvStore; - fv = fvStore; - - if (!PyTuple_Check (args)) - { - argc = 1; - fv[0] = 0; - argv[0] = AsString (args, tmp); - } - else - { - PyObject *v; - - if (PyTuple_Size (args) > ARGSZ) - { - argv = (char **) malloc (PyTuple_Size (args) * sizeof (char *)); - fv = (int *) malloc (PyTuple_Size (args) * sizeof (int)); - if (argv == NULL || fv == NULL) - PyErr_NoMemory (); - } - - argc = PyTuple_Size (args); - for (i = 0; i < argc; i++) - { - v = PyTuple_GetItem (args, i); - if (PyTuple_Check (v)) - { - fv[i] = 1; - argv[i] = Merge (v); - } - else if (v == Py_None) - { - argc = i; - break; - } - else - { - fv[i] = 0; - argv[i] = AsString (v, tmp); - } - } - } - - res = Tcl_Merge (argc, argv); - - Py_DECREF (tmp); - for (i = 0; i < argc; i++) - if (fv[i]) free (argv[i]); - if (argv != argvStore) - free (argv); - if (fv != fvStore) - free (fv); - - return res; -} - -static PyObject * -Split (self, list) - PyObject *self; - char *list; -{ - int argc; - char **argv; - PyObject *v; - - if (list == NULL) - { - Py_INCREF (Py_None); - return Py_None; - } - - if (Tcl_SplitList (Tkapp_Interp (self), list, &argc, &argv) == TCL_ERROR) - return Tkinter_Error (self); - - if (argc == 0) - v = PyString_FromString (""); - else if (argc == 1) - v = PyString_FromString (argv[0]); - else - { - int i; - - v = PyTuple_New (argc); - for (i = 0; i < argc; i++) - PyTuple_SetItem (v, i, Split (self, argv[i])); - } - - free (argv); - return v; -} - -/**** Tkapp Object ****/ - -#ifndef WITH_APPINIT -int -Tcl_AppInit (interp) - Tcl_Interp *interp; -{ - Tk_Window main; - - main = Tk_MainWindow(interp); - if (Tcl_Init (interp) == TCL_ERROR) { - fprintf(stderr, "Tcl_Init error: %s\n", interp->result); - return TCL_ERROR; - } - if (Tk_Init (interp) == TCL_ERROR) { - fprintf(stderr, "Tk_Init error: %s\n", interp->result); - return TCL_ERROR; - } - return TCL_OK; -} - -char * -TkDefaultAppName() -{ - return "Python"; -} - -#endif /* !WITH_APPINIT */ - -/* Initialize the Tk application; see the `main' function in - `tkMain.c'. */ -static TkappObject * -Tkapp_New (screenName, baseName, className, interactive) - char *screenName; - char *baseName; - char *className; - int interactive; -{ - TkappObject *v; - - v = PyObject_NEW (TkappObject, &Tkapp_Type); - if (v == NULL) - return NULL; - - v->interp = Tcl_CreateInterp (); - -#ifdef NEED_TKCREATEMAINWINDOW - v->tkwin = Tk_CreateMainWindow (v->interp, screenName, - baseName, className); - if (v->tkwin == NULL) - return (TkappObject *) Tkinter_Error ((PyObject *) v); - - Tk_GeometryRequest (v->tkwin, 200, 200); -#endif - - if (screenName != NULL) - Tcl_SetVar2 (v->interp, "env", "DISPLAY", screenName, TCL_GLOBAL_ONLY); - - if (interactive) - Tcl_SetVar (v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY); - else - Tcl_SetVar (v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY); - - if (Tcl_AppInit (v->interp) != TCL_OK) - { - PyErr_SetString (Tkinter_TclError, "Tcl_AppInit failed"); /* XXX */ - return NULL; - } - - return v; -} - -/** Tcl Eval **/ - -static PyObject * -Tkapp_Call (self, args) - PyObject *self; - PyObject *args; -{ - char *cmd; - - cmd = Merge (args); - if (Tcl_Eval (Tkapp_Interp (self), cmd) == TCL_ERROR) - { - free (cmd); - return Tkinter_Error (self); - } - - free (cmd); - return PyString_FromString (Tkapp_Result (self)); -} - -static PyObject * -Tkapp_GlobalCall (self, args) - PyObject *self; - PyObject *args; -{ - char *cmd; - - cmd = Merge (args); - if (Tcl_GlobalEval (Tkapp_Interp (self), cmd) == TCL_ERROR) - { - free (cmd); - return Tkinter_Error (self); - } - - free (cmd); - return PyString_FromString (Tkapp_Result (self)); -} - -static PyObject * -Tkapp_Eval (self, args) - PyObject *self; - PyObject *args; -{ - char *script; - - if (!PyArg_Parse (args, "s", &script)) - return NULL; - - if (Tcl_Eval (Tkapp_Interp (self), script) == TCL_ERROR) - return Tkinter_Error (self); - - return PyString_FromString (Tkapp_Result (self)); -} - -static PyObject * -Tkapp_GlobalEval (self, args) - PyObject *self; - PyObject *args; -{ - char *script; - - if (!PyArg_Parse (args, "s", &script)) - return NULL; - - if (Tcl_GlobalEval (Tkapp_Interp (self), script) == TCL_ERROR) - return Tkinter_Error (self); - - return PyString_FromString (Tkapp_Result (self)); -} - -static PyObject * -Tkapp_EvalFile (self, args) - PyObject *self; - PyObject *args; -{ - char *fileName; - - if (!PyArg_Parse (args, "s", &fileName)) - return NULL; - - if (Tcl_EvalFile (Tkapp_Interp (self), fileName) == TCL_ERROR) - return Tkinter_Error (self); - - return PyString_FromString (Tkapp_Result (self)); -} - -static PyObject * -Tkapp_Record (self, args) - PyObject *self; - PyObject *args; -{ - char *script; - - if (!PyArg_Parse (args, "s", &script)) - return NULL; - - if (Tcl_RecordAndEval (Tkapp_Interp (self), - script, TCL_NO_EVAL) == TCL_ERROR) - return Tkinter_Error (self); - - return PyString_FromString (Tkapp_Result (self)); -} - -static PyObject * -Tkapp_AddErrorInfo (self, args) - PyObject *self; - PyObject *args; -{ - char *msg; - - if (!PyArg_Parse (args, "s", &msg)) - return NULL; - Tcl_AddErrorInfo (Tkapp_Interp (self), msg); - - Py_INCREF(Py_None); - return Py_None; -} - -/** Tcl Variable **/ - -static PyObject * -SetVar (self, args, flags) - PyObject *self; - PyObject *args; - int flags; -{ - char *name1, *name2, *ok; - PyObject *newValue; - PyObject *tmp; - - tmp = PyList_New (0); - - if (PyArg_Parse (args, "(sO)", &name1, &newValue)) - ok = Tcl_SetVar (Tkapp_Interp (self), name1, - AsString (newValue, tmp), flags); /* XXX Merge? */ - else if (PyArg_Parse (args, "(ssO)", &name1, &name2, &newValue)) - ok = Tcl_SetVar2 (Tkapp_Interp (self), name1, name2, - AsString (newValue, tmp), flags); - else - { - Py_DECREF (tmp); - return NULL; - } - Py_DECREF (tmp); - - if (!ok) - return Tkinter_Error (self); - - Py_INCREF (Py_None); - return Py_None; -} - -static PyObject * -Tkapp_SetVar (self, args) - PyObject *self; - PyObject *args; -{ - return SetVar (self, args, TCL_LEAVE_ERR_MSG); -} - -static PyObject * -Tkapp_GlobalSetVar (self, args) - PyObject *self; - PyObject *args; -{ - return SetVar (self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); -} - -static PyObject * -GetVar (self, args, flags) - PyObject *self; - PyObject *args; - int flags; -{ - char *name1, *name2, *s; - - if (PyArg_Parse (args, "s", &name1)) - s = Tcl_GetVar (Tkapp_Interp (self), name1, flags); - else if (PyArg_Parse (args, "(ss)", &name1, &name2)) - s = Tcl_GetVar2 (Tkapp_Interp (self), name1, name2, flags); - else - return NULL; - - if (s == NULL) - return Tkinter_Error (self); - - return PyString_FromString (s); -} - -static PyObject * -Tkapp_GetVar (self, args) - PyObject *self; - PyObject *args; -{ - return GetVar (self, args, TCL_LEAVE_ERR_MSG); -} - -static PyObject * -Tkapp_GlobalGetVar (self, args) - PyObject *self; - PyObject *args; -{ - return GetVar (self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); -} - -static PyObject * -UnsetVar (self, args, flags) - PyObject *self; - PyObject *args; - int flags; -{ - char *name1, *name2; - int code; - - if (PyArg_Parse (args, "s", &name1)) - code = Tcl_UnsetVar (Tkapp_Interp (self), name1, flags); - else if (PyArg_Parse (args, "(ss)", &name1, &name2)) - code = Tcl_UnsetVar2 (Tkapp_Interp (self), name1, name2, flags); - else - return NULL; - - if (code == TCL_ERROR) - return Tkinter_Error (self); - - Py_INCREF (Py_None); - return Py_None; -} - -static PyObject * -Tkapp_UnsetVar (self, args) - PyObject *self; - PyObject *args; -{ - return UnsetVar (self, args, TCL_LEAVE_ERR_MSG); -} - -static PyObject * -Tkapp_GlobalUnsetVar (self, args) - PyObject *self; - PyObject *args; -{ - return UnsetVar (self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); -} - -/** Tcl to Python **/ - -static PyObject * -Tkapp_GetInt (self, args) - PyObject *self; - PyObject *args; -{ - char *s; - int v; - - if (!PyArg_Parse (args, "s", &s)) - return NULL; - if (Tcl_GetInt (Tkapp_Interp (self), s, &v) == TCL_ERROR) - return Tkinter_Error (self); - return Py_BuildValue ("i", v); -} - -static PyObject * -Tkapp_GetDouble (self, args) - PyObject *self; - PyObject *args; -{ - char *s; - double v; - - if (!PyArg_Parse (args, "s", &s)) - return NULL; - if (Tcl_GetDouble (Tkapp_Interp (self), s, &v) == TCL_ERROR) - return Tkinter_Error (self); - return Py_BuildValue ("d", v); -} - -static PyObject * -Tkapp_GetBoolean (self, args) - PyObject *self; - PyObject *args; -{ - char *s; - int v; - - if (!PyArg_Parse (args, "s", &s)) - return NULL; - if (Tcl_GetBoolean (Tkapp_Interp (self), s, &v) == TCL_ERROR) - return Tkinter_Error (self); - return Py_BuildValue ("i", v); -} - -static PyObject * -Tkapp_ExprString (self, args) - PyObject *self; - PyObject *args; -{ - char *s; - - if (!PyArg_Parse (args, "s", &s)) - return NULL; - if (Tcl_ExprString (Tkapp_Interp (self), s) == TCL_ERROR) - return Tkinter_Error (self); - return Py_BuildValue ("s", Tkapp_Result (self)); -} - -static PyObject * -Tkapp_ExprLong (self, args) - PyObject *self; - PyObject *args; -{ - char *s; - long v; - - if (!PyArg_Parse (args, "s", &s)) - return NULL; - if (Tcl_ExprLong (Tkapp_Interp (self), s, &v) == TCL_ERROR) - return Tkinter_Error (self); - return Py_BuildValue ("l", v); -} - -static PyObject * -Tkapp_ExprDouble (self, args) - PyObject *self; - PyObject *args; -{ - char *s; - double v; - - if (!PyArg_Parse (args, "s", &s)) - return NULL; - if (Tcl_ExprDouble (Tkapp_Interp (self), s, &v) == TCL_ERROR) - return Tkinter_Error (self); - return Py_BuildValue ("d", v); -} - -static PyObject * -Tkapp_ExprBoolean (self, args) - PyObject *self; - PyObject *args; -{ - char *s; - int v; - - if (!PyArg_Parse (args, "s", &s)) - return NULL; - if (Tcl_ExprBoolean (Tkapp_Interp (self), s, &v) == TCL_ERROR) - return Tkinter_Error (self); - return Py_BuildValue ("i", v); -} - -static PyObject * -Tkapp_SplitList (self, args) - PyObject *self; - PyObject *args; -{ - char *list; - int argc; - char **argv; - PyObject *v; - int i; - - if (!PyArg_Parse (args, "s", &list)) - return NULL; - - if (Tcl_SplitList (Tkapp_Interp (self), list, &argc, &argv) == TCL_ERROR) - return Tkinter_Error (self); - - v = PyTuple_New (argc); - for (i = 0; i < argc; i++) - PyTuple_SetItem (v, i, PyString_FromString (argv[i])); - - free (argv); - return v; -} - -static PyObject * -Tkapp_Split (self, args) - PyObject *self; - PyObject *args; -{ - char *list; - - if (!PyArg_Parse (args, "s", &list)) - return NULL; - return Split (self, list); -} - -static PyObject * -Tkapp_Merge (self, args) - PyObject *self; - PyObject *args; -{ - char *s; - PyObject *v; - - s = Merge (args); - v = PyString_FromString (s); - free (s); - return v; -} - -/** Tcl Command **/ - -/* This is the Tcl command that acts as a wrapper for Python - function or method. */ -static int -PythonCmd (clientData, interp, argc, argv) - ClientData clientData; /* Is (self, func) */ - Tcl_Interp *interp; - int argc; - char *argv[]; -{ - PyObject *self, *func, *arg, *res, *tmp; - int i; - - self = PyTuple_GetItem ((PyObject *) clientData, 0); - func = PyTuple_GetItem ((PyObject *) clientData, 1); - - /* Create argument list (argv1, ..., argvN) */ - arg = PyTuple_New (argc - 1); - for (i = 0; i < (argc - 1); i++) - PyTuple_SetItem (arg, i, PyString_FromString (argv[i + 1])); - - res = PyEval_CallObject (func, arg); - Py_DECREF (arg); - - if (res == NULL) - return PythonCmd_Error (interp); - - tmp = PyList_New (0); - Tcl_SetResult (Tkapp_Interp (self), AsString (res, tmp), TCL_VOLATILE); - Py_DECREF (res); - Py_DECREF (tmp); - - return TCL_OK; -} - -static void -PythonCmdDelete (clientData) - ClientData clientData; /* Is (self, func) */ -{ - Py_DECREF ((PyObject *) clientData); -} - -static PyObject * -Tkapp_CreateCommand (self, args) - PyObject *self; - PyObject *args; -{ - char *cmdName; - PyObject *data; - PyObject *func; - - /* Args is: (cmdName, func) */ - if (!PyTuple_Check (args) - || !(PyTuple_Size (args) == 2) - || !PyString_Check (PyTuple_GetItem (args, 0)) - || !PyCallable_Check (PyTuple_GetItem (args, 1))) - { - PyErr_SetString (PyExc_TypeError, "bad argument list"); - return NULL; - } - - cmdName = PyString_AsString (PyTuple_GetItem (args, 0)); - func = PyTuple_GetItem (args, 1); - - data = PyTuple_New (2); /* ClientData is: (self, func) */ - - Py_INCREF (self); - PyTuple_SetItem (data, 0, self); - - Py_INCREF (func); - PyTuple_SetItem (data, 1, func); - - Tcl_CreateCommand (Tkapp_Interp (self), cmdName, PythonCmd, - (ClientData) data, PythonCmdDelete); - - Py_INCREF (Py_None); - return Py_None; -} - -static PyObject * -Tkapp_DeleteCommand (self, args) - PyObject *self; - PyObject *args; -{ - char *cmdName; - - if (!PyArg_Parse (args, "s", &cmdName)) - return NULL; - if (Tcl_DeleteCommand (Tkapp_Interp (self), cmdName) == -1) - { - PyErr_SetString (Tkinter_TclError, "can't delete Tcl command"); - return NULL; - } - Py_INCREF (Py_None); - return Py_None; -} - -/** File Handler **/ - -static void -FileHandler (clientData, mask) - ClientData clientData; /* Is: (func, file) */ - int mask; -{ - PyObject *func, *file, *arg, *res; - - func = PyTuple_GetItem ((PyObject *) clientData, 0); - file = PyTuple_GetItem ((PyObject *) clientData, 1); - - arg = Py_BuildValue ("(Oi)", file, (long) mask); - res = PyEval_CallObject (func, arg); - Py_DECREF (arg); - if (res == NULL) - { - errorInCmd = 1; - PyErr_Fetch (&excInCmd, &valInCmd, &trbInCmd); - } - Py_XDECREF (res); -} - -static int -GetFileNo (file) - PyObject *file; /* Either an int >= 0 or an object with a - .fileno() method that returns an int >= 0 */ -{ - PyObject *meth, *args, *res; - int id; - if (PyInt_Check(file)) { - id = PyInt_AsLong(file); - if (id < 0) - PyErr_SetString(PyExc_ValueError, "invalid file id"); - return id; - } - meth = PyObject_GetAttrString(file, "fileno"); - if (meth == NULL) - return -1; - args = PyTuple_New(0); - if (args == NULL) - return -1; - res = PyEval_CallObject(meth, args); - Py_DECREF(args); - Py_DECREF(meth); - if (res == NULL) - return -1; - if (PyInt_Check(res)) - id = PyInt_AsLong(res); - else - id = -1; - if (id < 0) - PyErr_SetString(PyExc_ValueError, - "invalid fileno() return value"); - Py_DECREF(res); - return id; -} - -static PyObject * -Tkapp_CreateFileHandler (self, args) - PyObject *self; - PyObject *args; /* Is (file, mask, func) */ -{ - PyObject *file, *func, *data; - int mask, id; -#if (TK_MAJOR_VERSION*1000 + TK_MINOR_VERSION) >= 4001 - Tcl_File tfile; -#endif - - if (!PyArg_Parse (args, "(OiO)", &file, &mask, &func)) - return NULL; - id = GetFileNo (file); - if (id < 0) - return NULL; - if (!PyCallable_Check(func)) - { - PyErr_SetString (PyExc_TypeError, "bad argument list"); - return NULL; - } - - /* ClientData is: (func, file) */ - data = Py_BuildValue ("(OO)", func, file); - -#if (TK_MAJOR_VERSION*1000 + TK_MINOR_VERSION) >= 4001 - tfile = Tcl_GetFile((ClientData)id, TCL_UNIX_FD); - /* Oughtta check for null Tcl_File object... */ - Tcl_CreateFileHandler (tfile, mask, FileHandler, (ClientData) data); -#else - Tk_CreateFileHandler ((ClientData) id, mask, FileHandler, (ClientData) data); -#endif - /* XXX fileHandlerDict */ - - Py_INCREF (Py_None); - return Py_None; -} - -static PyObject * -Tkapp_DeleteFileHandler (self, args) - PyObject *self; - PyObject *args; /* Args: file */ -{ - PyObject *file; - int id; -#if (TK_MAJOR_VERSION*1000 + TK_MINOR_VERSION) >= 4001 - Tcl_File tfile; -#endif - - if (!PyArg_Parse (args, "O", &file)) - return NULL; - id = GetFileNo (file); - if (id < 0) - return NULL; - -#if (TK_MAJOR_VERSION*1000 + TK_MINOR_VERSION) >= 4001 - tfile = Tcl_GetFile((ClientData) id, TCL_UNIX_FD); - /* Oughtta check for null Tcl_File object... */ - Tcl_DeleteFileHandler(tfile); -#else - Tk_DeleteFileHandler ((ClientData) id); -#endif - /* XXX fileHandlerDict */ - Py_INCREF (Py_None); - return Py_None; -} - -/**** Tktt Object (timer token) ****/ - -staticforward PyTypeObject Tktt_Type; - -typedef struct - { - PyObject_HEAD - Tk_TimerToken token; - PyObject *func; - } -TkttObject; - -static PyObject * -Tktt_DeleteTimerHandler (self, args) - PyObject *self; - PyObject *args; -{ - TkttObject *v = (TkttObject *) self; - - if (!PyArg_Parse (args, "")) - return NULL; - if (v->func != NULL) - { - Tk_DeleteTimerHandler (v->token); - PyMem_DEL (v->func); - v->func = NULL; - } - Py_INCREF (Py_None); - return Py_None; -} - -static PyMethodDef Tktt_methods[] = -{ - {"deletetimerhandler", Tktt_DeleteTimerHandler}, - {NULL, NULL} -}; - -static TkttObject * -Tktt_New (token, func) - Tk_TimerToken token; - PyObject *func; -{ - TkttObject *v; - - v = PyObject_NEW (TkttObject, &Tktt_Type); - if (v == NULL) - return NULL; - - v->token = token; - v->func = func; - Py_INCREF (v->func); - return v; -} - -static void -Tktt_Dealloc (self) - PyObject *self; -{ - PyMem_DEL (self); -} - -static int -Tktt_Print (self, fp, flags) - PyObject *self; - FILE *fp; - int flags; -{ - TkttObject *v = (TkttObject *) self; - - fprintf(fp, "<tktimertoken at 0x%x%s>", v, - v->func == NULL ? ", handler deleted" : ""); - return 0; -} - -static PyObject * -Tktt_GetAttr (self, name) - PyObject *self; - char *name; -{ - return Py_FindMethod (Tktt_methods, self, name); -} - -static PyTypeObject Tktt_Type = -{ - PyObject_HEAD_INIT (&PyType_Type) - 0, /*ob_size */ - "tktimertoken", /*tp_name */ - sizeof (TkttObject), /*tp_basicsize */ - 0, /*tp_itemsize */ - Tktt_Dealloc, /*tp_dealloc */ - Tktt_Print, /*tp_print */ - Tktt_GetAttr, /*tp_getattr */ - 0, /*tp_setattr */ - 0, /*tp_compare */ - 0, /*tp_repr */ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash */ -}; - -/** Timer Handler **/ - -static void -TimerHandler (clientData) - ClientData clientData; -{ - PyObject *func = (PyObject *) clientData; - PyObject *arg, *res; - - arg = PyTuple_New (0); - res = PyEval_CallObject (func, arg); - Py_DECREF (arg); - if (res == NULL) - { - errorInCmd = 1; - PyErr_Fetch (&excInCmd, &valInCmd, &trbInCmd); - } - else - Py_DECREF (res); -} - -static PyObject * -Tkapp_CreateTimerHandler (self, args) - PyObject *self; - PyObject *args; /* Is (milliseconds, func) */ -{ - int milliseconds; - PyObject *func; - Tk_TimerToken token; - - if (!PyArg_Parse (args, "(iO)", &milliseconds, &func)) - return NULL; - if (!PyCallable_Check(func)) - { - PyErr_SetString (PyExc_TypeError, "bad argument list"); - return NULL; - } - token = Tk_CreateTimerHandler(milliseconds, TimerHandler, (ClientData) func); - return (PyObject *) Tktt_New (token, func); -} - -/** Event Loop **/ - -static PyObject * -Tkapp_MainLoop (self, args) - PyObject *self; - PyObject *args; -{ - int threshold = 0; - - if (!PyArg_ParseTuple (args, "|i", &threshold)) - return NULL; - - quitMainLoop = 0; - while (Tk_GetNumMainWindows() > threshold && !quitMainLoop && !errorInCmd) - { - if (PyOS_InterruptOccurred ()) - { - PyErr_SetNone (PyExc_KeyboardInterrupt); - return NULL; - } - Tk_DoOneEvent (0); - } - quitMainLoop = 0; - - if (errorInCmd) - { - errorInCmd = 0; - PyErr_Restore (excInCmd, valInCmd, trbInCmd); - excInCmd = valInCmd = trbInCmd = NULL; - return NULL; - } - Py_INCREF (Py_None); - return Py_None; -} - -static PyObject * -Tkapp_DoOneEvent (self, args) - PyObject *self; - PyObject *args; -{ - int flags = TK_ALL_EVENTS; - int rv; - - if (!PyArg_ParseTuple (args, "|i", &flags)) - return NULL; - rv = Tk_DoOneEvent(flags); - return Py_BuildValue ("i", rv); -} - -static PyObject * -Tkapp_Quit (self, args) - PyObject *self; - PyObject *args; -{ - - if (!PyArg_Parse (args, "")) - return NULL; - quitMainLoop = 1; - Py_INCREF (Py_None); - return Py_None; -} - -/**** Tkapp Method List ****/ - -static PyMethodDef Tkapp_methods[] = -{ - {"call", Tkapp_Call}, - {"globalcall", Tkapp_GlobalCall}, - {"eval", Tkapp_Eval}, - {"globaleval", Tkapp_GlobalEval}, - {"evalfile", Tkapp_EvalFile}, - {"record", Tkapp_Record}, - {"adderrorinfo", Tkapp_AddErrorInfo}, - {"setvar", Tkapp_SetVar}, - {"globalsetvar", Tkapp_GlobalSetVar}, - {"getvar", Tkapp_GetVar}, - {"globalgetvar", Tkapp_GlobalGetVar}, - {"unsetvar", Tkapp_UnsetVar}, - {"globalunsetvar", Tkapp_GlobalUnsetVar}, - {"getint", Tkapp_GetInt}, - {"getdouble", Tkapp_GetDouble}, - {"getboolean", Tkapp_GetBoolean}, - {"exprstring", Tkapp_ExprString}, - {"exprlong", Tkapp_ExprLong}, - {"exprdouble", Tkapp_ExprDouble}, - {"exprboolean", Tkapp_ExprBoolean}, - {"splitlist", Tkapp_SplitList}, - {"split", Tkapp_Split}, - {"merge", Tkapp_Merge}, - {"createcommand", Tkapp_CreateCommand}, - {"deletecommand", Tkapp_DeleteCommand}, - {"createfilehandler", Tkapp_CreateFileHandler}, - {"deletefilehandler", Tkapp_DeleteFileHandler}, - {"createtimerhandler", Tkapp_CreateTimerHandler}, - {"mainloop", Tkapp_MainLoop, 1}, - {"dooneevent", Tkapp_DoOneEvent, 1}, - {"quit", Tkapp_Quit}, - {NULL, NULL} -}; - -/**** Tkapp Type Methods ****/ - -static void -Tkapp_Dealloc (self) - PyObject *self; -{ -#ifdef NEED_TKCREATEMAINWINDOW - Tk_DestroyWindow (Tkapp_Tkwin (self)); -#endif - Tcl_DeleteInterp (Tkapp_Interp (self)); - PyMem_DEL (self); -} - -static PyObject * -Tkapp_GetAttr (self, name) - PyObject *self; - char *name; -{ - return Py_FindMethod (Tkapp_methods, self, name); -} - -static PyTypeObject Tkapp_Type = -{ - PyObject_HEAD_INIT (&PyType_Type) - 0, /*ob_size */ - "tkapp", /*tp_name */ - sizeof (TkappObject), /*tp_basicsize */ - 0, /*tp_itemsize */ - Tkapp_Dealloc, /*tp_dealloc */ - 0, /*tp_print */ - Tkapp_GetAttr, /*tp_getattr */ - 0, /*tp_setattr */ - 0, /*tp_compare */ - 0, /*tp_repr */ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash */ -}; - -/**** Tkinter Module ****/ - -static PyObject * -Tkinter_Create (self, args) - PyObject *self; - PyObject *args; -{ - char *screenName = NULL; - char *baseName = NULL; - char *className = NULL; - int interactive = 0; - - baseName = strrchr (getprogramname (), '/'); - if (baseName != NULL) - baseName++; - else - baseName = getprogramname (); - className = "Tk"; - - if (!PyArg_ParseTuple (args, "|zssi", - &screenName, &baseName, &className, &interactive)) - return NULL; - - return (PyObject *) Tkapp_New (screenName, baseName, className, - interactive); -} - -static PyMethodDef moduleMethods[] = -{ - {"create", Tkinter_Create, 1}, - {"createfilehandler", Tkapp_CreateFileHandler, 0}, - {"deletefilehandler", Tkapp_DeleteFileHandler, 0}, - {"createtimerhandler", Tkapp_CreateTimerHandler, 0}, - {"mainloop", Tkapp_MainLoop, 1}, - {"dooneevent", Tkapp_DoOneEvent, 1}, - {"quit", Tkapp_Quit}, - {NULL, NULL} -}; - -#undef WITH_READLINE /* XXX */ -#ifdef WITH_READLINE -static int -EventHook () -{ - if (errorInCmd) /* XXX Reset tty */ - { - errorInCmd = 0; - PyErr_Restore (excInCmd, valInCmd, trbInCmd); - excInCmd = valInCmd = trbInCmd = NULL; - PyErr_Print (); - } - if (Tk_GetNumMainWindows() > 0) - Tk_DoOneEvent (TK_DONT_WAIT); - return 0; -} -#endif /* WITH_READLINE */ - -static void -Tkinter_Cleanup () -{ -/* This segfault with Tk 4.0 beta and seems unnecessary there as well */ -#if TK_MAJOR_VERSION < 4 - /* XXX rl_deprep_terminal is static, damned! */ - while (tkMainWindowList != 0) - Tk_DestroyWindow (tkMainWindowList->win); -#endif -} - -void -init_tkinter () -{ - static inited = 0; - -#ifdef WITH_READLINE - extern int (*rl_event_hook) (); -#endif /* WITH_READLINE */ - PyObject *m, *d, *v; - - m = Py_InitModule ("_tkinter", moduleMethods); - - d = PyModule_GetDict (m); - Tkinter_TclError = Py_BuildValue ("s", "TclError"); - PyDict_SetItemString (d, "TclError", Tkinter_TclError); - - v = Py_BuildValue ("i", TK_READABLE); - PyDict_SetItemString (d, "READABLE", v); - v = Py_BuildValue ("i", TK_WRITABLE); - PyDict_SetItemString (d, "WRITABLE", v); - v = Py_BuildValue ("i", TK_EXCEPTION); - PyDict_SetItemString (d, "EXCEPTION", v); - v = Py_BuildValue ("i", TK_X_EVENTS); - PyDict_SetItemString (d, "X_EVENTS", v); - v = Py_BuildValue ("i", TK_FILE_EVENTS); - PyDict_SetItemString (d, "FILE_EVENTS", v); - v = Py_BuildValue ("i", TK_TIMER_EVENTS); - PyDict_SetItemString (d, "TIMER_EVENTS", v); - v = Py_BuildValue ("i", TK_IDLE_EVENTS); - PyDict_SetItemString (d, "IDLE_EVENTS", v); - v = Py_BuildValue ("i", TK_ALL_EVENTS); - PyDict_SetItemString (d, "ALL_EVENTS", v); - v = Py_BuildValue ("i", TK_DONT_WAIT); - PyDict_SetItemString (d, "DONT_WAIT", v); - v = Py_BuildValue ("s", TK_VERSION); - PyDict_SetItemString (d, "TK_VERSION", v); - v = Py_BuildValue ("s", TCL_VERSION); - PyDict_SetItemString (d, "TCL_VERSION", v); - -#ifdef WITH_READLINE - rl_event_hook = EventHook; -#endif /* WITH_READLINE */ - - if (!inited) - { - inited = 1; - if (Py_AtExit (Tkinter_Cleanup) != 0) - fprintf(stderr, - "Tkinter: warning: cleanup procedure not registered\n"); - } - - if (PyErr_Occurred ()) - Py_FatalError ("can't initialize module _tkinter"); -#ifdef macintosh - TclMacSetEventProc(PyMacConvertEvent); -#if GENERATINGCFM - mac_addlibresources(); -#endif /* GENERATINGCFM */ -#endif /* macintosh */ -} - - -#ifdef macintosh - -/* -** Anyone who embeds Tcl/Tk on the Mac must define panic(). -*/ - -void -panic(char * format, ...) -{ - va_list varg; - - va_start(varg, format); - - vfprintf(stderr, format, varg); - (void) fflush(stderr); - - va_end(varg); - - Py_FatalError("Tcl/Tk panic"); -} - -/* -** Pass events to SIOUX before passing them to Tk. -*/ - -static int -PyMacConvertEvent(eventPtr) - EventRecord *eventPtr; -{ - if (SIOUXHandleOneEvent(eventPtr)) - return 0; /* Nothing happened to the Tcl event queue */ - return TkMacConvertEvent(eventPtr); -} - -#if GENERATINGCFM - -/* -** Additional Mac specific code for dealing with shared libraries. -*/ - -#include <Resources.h> -#include <CodeFragments.h> - -static int loaded_from_shlib = 0; -static FSSpec library_fss; - -/* -** If this module is dynamically loaded the following routine should -** be the init routine. It takes care of adding the shared library to -** the resource-file chain, so that the tk routines can find their -** resources. -*/ -OSErr pascal -init_tkinter_shlib(InitBlockPtr data) -{ - __sinit(); /* Sez Jack */ - if ( data == nil ) return noErr; - if ( data->fragLocator.where == kOnDiskFlat ) { - library_fss = *data->fragLocator.u.onDisk.fileSpec; - loaded_from_shlib = 1; - } else if ( data->fragLocator.where == kOnDiskSegmented ) { - library_fss = *data->fragLocator.u.inSegs.fileSpec; - loaded_from_shlib = 1; - } - return noErr; -} - -/* -** Insert the library resources into the search path. Put them after -** the resources from the application. Again, we ignore errors. -*/ -static -mac_addlibresources() -{ - if ( !loaded_from_shlib ) - return; - (void)FSpOpenResFile(&library_fss, fsRdPerm); -} - -#endif /* GENERATINGCFM */ -#endif /* macintosh */ diff --git a/Modules/almodule.c b/Modules/almodule.c deleted file mode 100644 index 052939ec5f..0000000000 --- a/Modules/almodule.c +++ /dev/null @@ -1,777 +0,0 @@ -/********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* AL module -- interface to Mark Callow's Audio Library (AL). */ - -#include <audio.h> - -/* Check which version audio library we have: */ -#ifdef AL_ERROR_NUMBER -#define AL_405 -/* XXXX 4.0.5 libaudio also allows us to provide better error -** handling (with ALseterrorhandler). We should implement that -** sometime. -*/ - -#endif - -#include "allobjects.h" -#include "import.h" -#include "modsupport.h" -#include "structmember.h" -#include "ceval.h" - - -/* Config objects */ - -typedef struct { - OB_HEAD - ALconfig ob_config; -} configobject; - -staticforward typeobject Configtype; - -#define is_configobject(v) ((v)->ob_type == &Configtype) - -/* Forward */ -static int getconfigarg PROTO((object *, ALconfig *)); -static int getstrstrconfigarg PROTO((object *, char **, char **, ALconfig *)); - -static object * -setConfig (self, args, func) - configobject *self; - object *args; - void (*func)(ALconfig, long); -{ - long par; - - if (!getlongarg (args, &par)) return NULL; - - (*func) (self-> ob_config, par); - - INCREF (None); - return None; -} - -static object * -getConfig (self, args, func) - configobject *self; - object *args; - long (*func)(ALconfig); -{ - long par; - - if (!getnoarg (args)) return NULL; - - par = (*func) (self-> ob_config); - - return newintobject (par); -} - -static object * -al_setqueuesize (self, args) - configobject *self; - object *args; -{ - return (setConfig (self, args, ALsetqueuesize)); -} - -static object * -al_getqueuesize (self, args) - configobject *self; - object *args; -{ - return (getConfig (self, args, ALgetqueuesize)); -} - -static object * -al_setwidth (self, args) - configobject *self; - object *args; -{ - return (setConfig (self, args, ALsetwidth)); -} - -static object * -al_getwidth (self, args) - configobject *self; - object *args; -{ - return (getConfig (self, args, ALgetwidth)); -} - -static object * -al_getchannels (self, args) - configobject *self; - object *args; -{ - return (getConfig (self, args, ALgetchannels)); -} - -static object * -al_setchannels (self, args) - configobject *self; - object *args; -{ - return (setConfig (self, args, ALsetchannels)); -} - -#ifdef AL_405 - -static object * -al_getsampfmt (self, args) - configobject *self; - object *args; -{ - return (getConfig (self, args, ALgetsampfmt)); -} - -static object * -al_setsampfmt (self, args) - configobject *self; - object *args; -{ - return (setConfig (self, args, ALsetsampfmt)); -} - -static object * -al_getfloatmax(self, args) - configobject *self; - object *args; -{ - double arg; - - if ( !getnoarg(args) ) - return 0; - arg = ALgetfloatmax(self->ob_config); - return newfloatobject(arg); -} - -static object * -al_setfloatmax(self, args) - configobject *self; - object *args; -{ - double arg; - - if ( !getargs(args, "d", &arg) ) - return 0; - ALsetfloatmax(self->ob_config, arg); - INCREF(None); - return None; -} -#endif /* AL_405 */ - -static struct methodlist config_methods[] = { - {"getqueuesize", (method)al_getqueuesize}, - {"setqueuesize", (method)al_setqueuesize}, - {"getwidth", (method)al_getwidth}, - {"setwidth", (method)al_setwidth}, - {"getchannels", (method)al_getchannels}, - {"setchannels", (method)al_setchannels}, -#ifdef AL_405 - {"getsampfmt", (method)al_getsampfmt}, - {"setsampfmt", (method)al_setsampfmt}, - {"getfloatmax", (method)al_getfloatmax}, - {"setfloatmax", (method)al_setfloatmax}, -#endif /* AL_405 */ - {NULL, NULL} /* sentinel */ -}; - -static void -config_dealloc(self) - configobject *self; -{ - ALfreeconfig(self->ob_config); - DEL(self); -} - -static object * -config_getattr(self, name) - configobject *self; - char *name; -{ - return findmethod(config_methods, (object *)self, name); -} - -static typeobject Configtype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "config", /*tp_name*/ - sizeof(configobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)config_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)config_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - -static object * -newconfigobject(config) - ALconfig config; -{ - configobject *p; - - p = NEWOBJ(configobject, &Configtype); - if (p == NULL) - return NULL; - p->ob_config = config; - return (object *)p; -} - -/* Port objects */ - -typedef struct { - OB_HEAD - ALport ob_port; -} portobject; - -staticforward typeobject Porttype; - -#define is_portobject(v) ((v)->ob_type == &Porttype) - -static object * -al_closeport (self, args) - portobject *self; - object *args; -{ - if (!getnoarg (args)) return NULL; - - if (self->ob_port != NULL) { - ALcloseport (self-> ob_port); - self->ob_port = NULL; - /* XXX Using a closed port may dump core! */ - } - - INCREF (None); - return None; -} - -static object * -al_getfd (self, args) - portobject *self; - object *args; -{ - int fd; - - if (!getnoarg (args)) return NULL; - - fd = ALgetfd (self-> ob_port); - - return newintobject (fd); -} - -static object * -al_getfilled (self, args) - portobject *self; - object *args; -{ - long count; - - if (!getnoarg (args)) return NULL; - - count = ALgetfilled (self-> ob_port); - - return newintobject (count); -} - -static object * -al_getfillable (self, args) - portobject *self; - object *args; -{ - long count; - - if (!getnoarg (args)) return NULL; - - count = ALgetfillable (self-> ob_port); - - return newintobject (count); -} - -static object * -al_readsamps (self, args) - portobject *self; - object *args; -{ - long count; - object *v; - ALconfig c; - int width; - - if (!getlongarg (args, &count)) return NULL; - - if (count <= 0) - { - err_setstr (RuntimeError, "al.readsamps : arg <= 0"); - return NULL; - } - - c = ALgetconfig(self->ob_port); -#ifdef AL_405 - width = ALgetsampfmt(c); - if ( width == AL_SAMPFMT_FLOAT ) - width = sizeof(float); - else if ( width == AL_SAMPFMT_DOUBLE ) - width = sizeof(double); - else - width = ALgetwidth(c); -#else - width = ALgetwidth(c); -#endif /* AL_405 */ - ALfreeconfig(c); - v = newsizedstringobject ((char *)NULL, width * count); - if (v == NULL) return NULL; - - BGN_SAVE - ALreadsamps (self-> ob_port, (void *) getstringvalue(v), count); - END_SAVE - - return (v); -} - -static object * -al_writesamps (self, args) - portobject *self; - object *args; -{ - long count; - char *buf; - int size, width; - ALconfig c; - - if (!getargs (args, "s#", &buf, &size)) return NULL; - - c = ALgetconfig(self->ob_port); -#ifdef AL_405 - width = ALgetsampfmt(c); - if ( width == AL_SAMPFMT_FLOAT ) - width = sizeof(float); - else if ( width == AL_SAMPFMT_DOUBLE ) - width = sizeof(double); - else - width = ALgetwidth(c); -#else - width = ALgetwidth(c); -#endif /* AL_405 */ - ALfreeconfig(c); - BGN_SAVE - ALwritesamps (self-> ob_port, (void *) buf, (long) size / width); - END_SAVE - - INCREF (None); - return None; -} - -static object * -al_getfillpoint (self, args) - portobject *self; - object *args; -{ - long count; - - if (!getnoarg (args)) return NULL; - - count = ALgetfillpoint (self-> ob_port); - - return newintobject (count); -} - -static object * -al_setfillpoint (self, args) - portobject *self; - object *args; -{ - long count; - - if (!getlongarg (args, &count)) return NULL; - - ALsetfillpoint (self-> ob_port, count); - - INCREF (None); - return (None); -} - -static object * -al_setconfig (self, args) - portobject *self; - object *args; -{ - ALconfig config; - - if (!getconfigarg (args, &config)) return NULL; - - ALsetconfig (self-> ob_port, config); - - INCREF (None); - return (None); -} - -static object * -al_getconfig (self, args) - portobject *self; - object *args; -{ - ALconfig config; - - if (!getnoarg (args)) return NULL; - - config = ALgetconfig (self-> ob_port); - - return newconfigobject (config); -} - -#ifdef AL_405 -static object * -al_getstatus (self, args) - portobject *self; - object *args; -{ - object *list, *v; - long *PVbuffer; - long length; - int i; - - if (!getargs(args, "O", &list)) - return NULL; - if (!is_listobject(list)) { - err_badarg(); - return NULL; - } - length = getlistsize(list); - PVbuffer = NEW(long, length); - if (PVbuffer == NULL) - return err_nomem(); - for (i = 0; i < length; i++) { - v = getlistitem(list, i); - if (!is_intobject(v)) { - DEL(PVbuffer); - err_badarg(); - return NULL; - } - PVbuffer[i] = getintvalue(v); - } - - ALgetstatus(self->ob_port, PVbuffer, length); - - for (i = 0; i < length; i++) - setlistitem(list, i, newintobject(PVbuffer[i])); - - DEL(PVbuffer); - - INCREF(None); - return None; -} -#endif /* AL_405 */ - -static struct methodlist port_methods[] = { - {"closeport", (method)al_closeport}, - {"getfd", (method)al_getfd}, - {"fileno", (method)al_getfd}, - {"getfilled", (method)al_getfilled}, - {"getfillable", (method)al_getfillable}, - {"readsamps", (method)al_readsamps}, - {"writesamps", (method)al_writesamps}, - {"setfillpoint", (method)al_setfillpoint}, - {"getfillpoint", (method)al_getfillpoint}, - {"setconfig", (method)al_setconfig}, - {"getconfig", (method)al_getconfig}, -#ifdef AL_405 - {"getstatus", (method)al_getstatus}, -#endif /* AL_405 */ - {NULL, NULL} /* sentinel */ -}; - -static void -port_dealloc(p) - portobject *p; -{ - if (p->ob_port != NULL) - ALcloseport(p->ob_port); - DEL(p); -} - -static object * -port_getattr(p, name) - portobject *p; - char *name; -{ - return findmethod(port_methods, (object *)p, name); -} - -static typeobject Porttype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "port", /*tp_name*/ - sizeof(portobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)port_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)port_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - -static object * -newportobject(port) - ALport port; -{ - portobject *p; - - p = NEWOBJ(portobject, &Porttype); - if (p == NULL) - return NULL; - p->ob_port = port; - return (object *)p; -} - -/* the module al */ - -static object * -al_openport (self, args) - object *self, *args; -{ - char *name, *dir; - ALport port; - ALconfig config = NULL; - int size; - - if (args == NULL || !is_tupleobject(args)) { - err_badarg (); - return NULL; - } - size = gettuplesize(args); - if (size == 2) { - if (!getargs (args, "(ss)", &name, &dir)) - return NULL; - } - else if (size == 3) { - if (!getstrstrconfigarg (args, &name, &dir, &config)) - return NULL; - } - else { - err_badarg (); - return NULL; - } - - port = ALopenport(name, dir, config); - - if (port == NULL) { - err_errno(RuntimeError); - return NULL; - } - - return newportobject (port); -} - -static object * -al_newconfig (self, args) - object *self, *args; -{ - ALconfig config; - - if (!getnoarg (args)) return NULL; - - config = ALnewconfig (); - if (config == NULL) { - err_errno(RuntimeError); - return NULL; - } - - return newconfigobject (config); -} - -static object * -al_queryparams(self, args) - object *self, *args; -{ - long device; - long length; - long *PVbuffer; - long PVdummy[2]; - object *v; - object *w; - - if (!getlongarg (args, &device)) - return NULL; - length = ALqueryparams(device, PVdummy, 2L); - PVbuffer = NEW(long, length); - if (PVbuffer == NULL) - return err_nomem(); - (void) ALqueryparams(device, PVbuffer, length); - v = newlistobject((int)length); - if (v != NULL) { - int i; - for (i = 0; i < length; i++) - setlistitem(v, i, newintobject(PVbuffer[i])); - } - DEL(PVbuffer); - return v; -} - -static object * -doParams(args, func, modified) - object *args; - void (*func)(long, long *, long); - int modified; -{ - long device; - object *list, *v; - long *PVbuffer; - long length; - int i; - - if (!getargs(args, "(lO)", &device, &list)) - return NULL; - if (!is_listobject(list)) { - err_badarg(); - return NULL; - } - length = getlistsize(list); - PVbuffer = NEW(long, length); - if (PVbuffer == NULL) - return err_nomem(); - for (i = 0; i < length; i++) { - v = getlistitem(list, i); - if (!is_intobject(v)) { - DEL(PVbuffer); - err_badarg(); - return NULL; - } - PVbuffer[i] = getintvalue(v); - } - - (*func)(device, PVbuffer, length); - - if (modified) { - for (i = 0; i < length; i++) - setlistitem(list, i, newintobject(PVbuffer[i])); - } - - DEL(PVbuffer); - - INCREF(None); - return None; -} - -static object * -al_getparams(self, args) - object *self, *args; -{ - return doParams(args, ALgetparams, 1); -} - -static object * -al_setparams(self, args) - object *self, *args; -{ - return doParams(args, ALsetparams, 0); -} - -static object * -al_getname(self, args) - object *self, *args; -{ - long device, descriptor; - char *name; - if (!getargs(args, "(ll)", &device, &descriptor)) - return NULL; - name = ALgetname(device, descriptor); - if (name == NULL) { - err_setstr(ValueError, "al.getname: bad descriptor"); - return NULL; - } - return newstringobject(name); -} - -static object * -al_getdefault(self, args) - object *self, *args; -{ - long device, descriptor, value; - if (!getargs(args, "(ll)", &device, &descriptor)) - return NULL; - value = ALgetdefault(device, descriptor); - return newlongobject(value); -} - -static object * -al_getminmax(self, args) - object *self, *args; -{ - long device, descriptor, min, max; - if (!getargs(args, "(ll)", &device, &descriptor)) - return NULL; - min = -1; - max = -1; - ALgetminmax(device, descriptor, &min, &max); - return mkvalue("ll", min, max); -} - -static struct methodlist al_methods[] = { - {"openport", (method)al_openport}, - {"newconfig", (method)al_newconfig}, - {"queryparams", (method)al_queryparams}, - {"getparams", (method)al_getparams}, - {"setparams", (method)al_setparams}, - {"getname", (method)al_getname}, - {"getdefault", (method)al_getdefault}, - {"getminmax", (method)al_getminmax}, - {NULL, NULL} /* sentinel */ -}; - -void -inital() -{ - initmodule("al", al_methods); -} - -static int -getconfigarg(o, conf) - object *o; - ALconfig *conf; -{ - if (o == NULL || !is_configobject(o)) - return err_badarg (); - - *conf = ((configobject *) o) -> ob_config; - - return 1; -} - -static int -getstrstrconfigarg(v, a, b, c) - object *v; - char **a; - char **b; - ALconfig *c; -{ - object *o; - return getargs(v, "(ssO)", a, b, &o) && getconfigarg(o, c); -} diff --git a/Modules/arraymodule.c b/Modules/arraymodule.c deleted file mode 100644 index d1c73069c5..0000000000 --- a/Modules/arraymodule.c +++ /dev/null @@ -1,1157 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Array object implementation */ - -/* An array is a uniform list -- all items have the same type. - The item type is restricted to simple C types like int or float */ - -#include "allobjects.h" -#include "modsupport.h" -#include "ceval.h" -#ifdef STDC_HEADERS -#include <stddef.h> -#else -#include <sys/types.h> /* For size_t */ -#endif - -struct arrayobject; /* Forward */ - -struct arraydescr { - int typecode; - int itemsize; - object * (*getitem) FPROTO((struct arrayobject *, int)); - int (*setitem) FPROTO((struct arrayobject *, int, object *)); -}; - -typedef struct arrayobject { - OB_VARHEAD - char *ob_item; - struct arraydescr *ob_descr; -} arrayobject; - -staticforward typeobject Arraytype; - -#define is_arrayobject(op) ((op)->ob_type == &Arraytype) - -/* Forward */ -static object *newarrayobject PROTO((int, struct arraydescr *)); -static int getarraysize PROTO((object *)); -static object *getarrayitem PROTO((object *, int)); -static int setarrayitem PROTO((object *, int, object *)); -static int insarrayitem PROTO((object *, int, object *)); -static int addarrayitem PROTO((object *, object *)); - -static object * -c_getitem(ap, i) - arrayobject *ap; - int i; -{ - return newsizedstringobject(&((char *)ap->ob_item)[i], 1); -} - -static int -c_setitem(ap, i, v) - arrayobject *ap; - int i; - object *v; -{ - char x; - if (!getargs(v, "c;array item must be char", &x)) - return -1; - if (i >= 0) - ((char *)ap->ob_item)[i] = x; - return 0; -} - -static object * -b_getitem(ap, i) - arrayobject *ap; - int i; -{ - long x = ((char *)ap->ob_item)[i]; - if (x >= 128) - x -= 256; - return newintobject(x); -} - -static int -b_setitem(ap, i, v) - arrayobject *ap; - int i; - object *v; -{ - char x; - if (!getargs(v, "b;array item must be integer", &x)) - return -1; - if (i >= 0) - ((char *)ap->ob_item)[i] = x; - return 0; -} - -static object * -h_getitem(ap, i) - arrayobject *ap; - int i; -{ - return newintobject((long) ((short *)ap->ob_item)[i]); -} - -static int -h_setitem(ap, i, v) - arrayobject *ap; - int i; - object *v; -{ - short x; - if (!getargs(v, "h;array item must be integer", &x)) - return -1; - if (i >= 0) - ((short *)ap->ob_item)[i] = x; - return 0; -} - -static object * -i_getitem(ap, i) - arrayobject *ap; - int i; -{ - return newintobject((long) ((int *)ap->ob_item)[i]); -} - -static int -i_setitem(ap, i, v) - arrayobject *ap; - int i; - object *v; -{ - int x; - if (!getargs(v, "i;array item must be integer", &x)) - return -1; - if (i >= 0) - ((int *)ap->ob_item)[i] = x; - return 0; -} - -static object * -l_getitem(ap, i) - arrayobject *ap; - int i; -{ - return newintobject(((long *)ap->ob_item)[i]); -} - -static int -l_setitem(ap, i, v) - arrayobject *ap; - int i; - object *v; -{ - long x; - if (!getargs(v, "l;array item must be integer", &x)) - return -1; - if (i >= 0) - ((long *)ap->ob_item)[i] = x; - return 0; -} - -static object * -f_getitem(ap, i) - arrayobject *ap; - int i; -{ - return newfloatobject((double) ((float *)ap->ob_item)[i]); -} - -static int -f_setitem(ap, i, v) - arrayobject *ap; - int i; - object *v; -{ - float x; - if (!getargs(v, "f;array item must be float", &x)) - return -1; - if (i >= 0) - ((float *)ap->ob_item)[i] = x; - return 0; -} - -static object * -d_getitem(ap, i) - arrayobject *ap; - int i; -{ - return newfloatobject(((double *)ap->ob_item)[i]); -} - -static int -d_setitem(ap, i, v) - arrayobject *ap; - int i; - object *v; -{ - double x; - if (!getargs(v, "d;array item must be float", &x)) - return -1; - if (i >= 0) - ((double *)ap->ob_item)[i] = x; - return 0; -} - -/* Description of types */ -static struct arraydescr descriptors[] = { - {'c', sizeof(char), c_getitem, c_setitem}, - {'b', sizeof(char), b_getitem, b_setitem}, - {'h', sizeof(short), h_getitem, h_setitem}, - {'i', sizeof(int), i_getitem, i_setitem}, - {'l', sizeof(long), l_getitem, l_setitem}, - {'f', sizeof(float), f_getitem, f_setitem}, - {'d', sizeof(double), d_getitem, d_setitem}, - {'\0', 0, 0, 0} /* Sentinel */ -}; -/* If we ever allow items larger than double, we must change reverse()! */ - - -static object * -newarrayobject(size, descr) - int size; - struct arraydescr *descr; -{ - arrayobject *op; - size_t nbytes; - if (size < 0) { - err_badcall(); - return NULL; - } - nbytes = size * descr->itemsize; - /* Check for overflow */ - if (nbytes / descr->itemsize != size) { - return err_nomem(); - } - op = NEW(arrayobject, 1); - if (op == NULL) { - return err_nomem(); - } - if (size <= 0) { - op->ob_item = NULL; - } - else { - op->ob_item = NEW(char, nbytes); - if (op->ob_item == NULL) { - DEL(op); - return err_nomem(); - } - } - op->ob_type = &Arraytype; - op->ob_size = size; - op->ob_descr = descr; - NEWREF(op); - return (object *) op; -} - -static int -getarraysize(op) - object *op; -{ - if (!is_arrayobject(op)) { - err_badcall(); - return -1; - } - return ((arrayobject *)op) -> ob_size; -} - -static object * -getarrayitem(op, i) - object *op; - int i; -{ - register arrayobject *ap; - if (!is_arrayobject(op)) { - err_badcall(); - return NULL; - } - ap = (arrayobject *)op; - if (i < 0 || i >= ap->ob_size) { - err_setstr(IndexError, "array index out of range"); - return NULL; - } - return (*ap->ob_descr->getitem)(ap, i); -} - -static int -ins1(self, where, v) - arrayobject *self; - int where; - object *v; -{ - char *items; - if (v == NULL) { - err_badcall(); - return -1; - } - if ((*self->ob_descr->setitem)(self, -1, v) < 0) - return -1; - items = self->ob_item; - RESIZE(items, char, (self->ob_size+1) * self->ob_descr->itemsize); - if (items == NULL) { - err_nomem(); - return -1; - } - if (where < 0) - where = 0; - if (where > self->ob_size) - where = self->ob_size; - memmove(items + (where+1)*self->ob_descr->itemsize, - items + where*self->ob_descr->itemsize, - (self->ob_size-where)*self->ob_descr->itemsize); - self->ob_item = items; - self->ob_size++; - return (*self->ob_descr->setitem)(self, where, v); -} - -static int -insarrayitem(op, where, newitem) - object *op; - int where; - object *newitem; -{ - if (!is_arrayobject(op)) { - err_badcall(); - return -1; - } - return ins1((arrayobject *)op, where, newitem); -} - -static int -addarrayitem(op, newitem) - object *op; - object *newitem; -{ - if (!is_arrayobject(op)) { - err_badcall(); - return -1; - } - return ins1((arrayobject *)op, - (int) ((arrayobject *)op)->ob_size, newitem); -} - -/* Methods */ - -static void -array_dealloc(op) - arrayobject *op; -{ - if (op->ob_item != NULL) - DEL(op->ob_item); - DEL(op); -} - -static int -array_compare(v, w) - arrayobject *v, *w; -{ - int len = (v->ob_size < w->ob_size) ? v->ob_size : w->ob_size; - int i; - for (i = 0; i < len; i++) { - object *ai, *bi; - int cmp; - ai = getarrayitem((object *)v, i); - bi = getarrayitem((object *)w, i); - if (ai && bi) - cmp = cmpobject(ai, bi); - else - cmp = -1; - XDECREF(ai); - XDECREF(bi); - if (cmp != 0) { - err_clear(); /* XXX Can't report errors here */ - return cmp; - } - } - return v->ob_size - w->ob_size; -} - -static int -array_length(a) - arrayobject *a; -{ - return a->ob_size; -} - -static object * -array_item(a, i) - arrayobject *a; - int i; -{ - if (i < 0 || i >= a->ob_size) { - err_setstr(IndexError, "array index out of range"); - return NULL; - } - return getarrayitem((object *)a, i); -} - -static object * -array_slice(a, ilow, ihigh) - arrayobject *a; - int ilow, ihigh; -{ - arrayobject *np; - if (ilow < 0) - ilow = 0; - else if (ilow > a->ob_size) - ilow = a->ob_size; - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > a->ob_size) - ihigh = a->ob_size; - np = (arrayobject *) newarrayobject(ihigh - ilow, a->ob_descr); - if (np == NULL) - return NULL; - memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize, - (ihigh-ilow) * a->ob_descr->itemsize); - return (object *)np; -} - -static object * -array_concat(a, bb) - arrayobject *a; - object *bb; -{ - int size; - arrayobject *np; - if (!is_arrayobject(bb)) { - err_badarg(); - return NULL; - } -#define b ((arrayobject *)bb) - if (a->ob_descr != b->ob_descr) { - err_badarg(); - return NULL; - } - size = a->ob_size + b->ob_size; - np = (arrayobject *) newarrayobject(size, a->ob_descr); - if (np == NULL) { - return NULL; - } - memcpy(np->ob_item, a->ob_item, a->ob_size*a->ob_descr->itemsize); - memcpy(np->ob_item + a->ob_size*a->ob_descr->itemsize, - b->ob_item, b->ob_size*b->ob_descr->itemsize); - return (object *)np; -#undef b -} - -static object * -array_repeat(a, n) - arrayobject *a; - int n; -{ - int i; - int size; - arrayobject *np; - char *p; - int nbytes; - if (n < 0) - n = 0; - size = a->ob_size * n; - np = (arrayobject *) newarrayobject(size, a->ob_descr); - if (np == NULL) - return NULL; - p = np->ob_item; - nbytes = a->ob_size * a->ob_descr->itemsize; - for (i = 0; i < n; i++) { - memcpy(p, a->ob_item, nbytes); - p += nbytes; - } - return (object *) np; -} - -static int -array_ass_slice(a, ilow, ihigh, v) - arrayobject *a; - int ilow, ihigh; - object *v; -{ - char *item; - int n; /* Size of replacement array */ - int d; /* Change in size */ -#define b ((arrayobject *)v) - if (v == NULL) - n = 0; - else if (is_arrayobject(v)) { - n = b->ob_size; - if (a == b) { - /* Special case "a[i:j] = a" -- copy b first */ - int ret; - v = array_slice(b, 0, n); - ret = array_ass_slice(a, ilow, ihigh, v); - DECREF(v); - return ret; - } - if (b->ob_descr != a->ob_descr) { - err_badarg(); - return -1; - } - } - else { - err_badarg(); - return -1; - } - if (ilow < 0) - ilow = 0; - else if (ilow > a->ob_size) - ilow = a->ob_size; - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > a->ob_size) - ihigh = a->ob_size; - item = a->ob_item; - d = n - (ihigh-ilow); - if (d < 0) { /* Delete -d items */ - memmove(item + (ihigh+d)*a->ob_descr->itemsize, - item + ihigh*a->ob_descr->itemsize, - (a->ob_size-ihigh)*a->ob_descr->itemsize); - a->ob_size += d; - RESIZE(item, char, a->ob_size*a->ob_descr->itemsize); - /* Can't fail */ - a->ob_item = item; - } - else if (d > 0) { /* Insert d items */ - RESIZE(item, char, (a->ob_size + d)*a->ob_descr->itemsize); - if (item == NULL) { - err_nomem(); - return -1; - } - memmove(item + (ihigh+d)*a->ob_descr->itemsize, - item + ihigh*a->ob_descr->itemsize, - (a->ob_size-ihigh)*a->ob_descr->itemsize); - a->ob_item = item; - a->ob_size += d; - } - if (n > 0) - memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item, - n*b->ob_descr->itemsize); - return 0; -#undef b -} - -static int -array_ass_item(a, i, v) - arrayobject *a; - int i; - object *v; -{ - if (i < 0 || i >= a->ob_size) { - err_setstr(IndexError, "array assignment index out of range"); - return -1; - } - if (v == NULL) - return array_ass_slice(a, i, i+1, v); - return (*a->ob_descr->setitem)(a, i, v); -} - -static int -setarrayitem(a, i, v) - object *a; - int i; - object *v; -{ - if (!is_arrayobject(a)) { - err_badcall(); - return -1; - } - return array_ass_item((arrayobject *)a, i, v); -} - -static object * -ins(self, where, v) - arrayobject *self; - int where; - object *v; -{ - if (ins1(self, where, v) != 0) - return NULL; - INCREF(None); - return None; -} - -static object * -array_insert(self, args) - arrayobject *self; - object *args; -{ - int i; - object *v; - if (!getargs(args, "(iO)", &i, &v)) - return NULL; - return ins(self, i, v); -} - -static object * -array_append(self, args) - arrayobject *self; - object *args; -{ - object *v; - if (!getargs(args, "O", &v)) - return NULL; - return ins(self, (int) self->ob_size, v); -} - -static object * -array_byteswap(self, args) - arrayobject *self; - object *args; -{ - char *p; - int i; - switch (self->ob_descr->itemsize) { - case 1: - break; - case 2: - for (p = self->ob_item, i = self->ob_size; --i >= 0; p += 2) { - char p0 = p[0]; - p[0] = p[1]; - p[1] = p0; - } - break; - case 4: - for (p = self->ob_item, i = self->ob_size; --i >= 0; p += 4) { - char p0 = p[0]; - char p1 = p[1]; - p[0] = p[3]; - p[1] = p[2]; - p[2] = p1; - p[3] = p0; - } - break; - case 8: - for (p = self->ob_item, i = self->ob_size; --i >= 0; p += 8) { - char p0 = p[0]; - char p1 = p[1]; - char p2 = p[2]; - char p3 = p[3]; - p[0] = p[7]; - p[1] = p[6]; - p[2] = p[5]; - p[3] = p[4]; - p[4] = p3; - p[5] = p2; - p[6] = p1; - p[7] = p0; - } - break; - default: - err_setstr(RuntimeError, - "don't know how to byteswap this array type"); - return NULL; - } - INCREF(None); - return None; -} - -static object * -array_reverse(self, args) - arrayobject *self; - object *args; -{ - register int itemsize = self->ob_descr->itemsize; - register char *p, *q; - char tmp[sizeof(double)]; /* Assume that's the max item size */ - - if (args != NULL) { - err_badarg(); - return NULL; - } - - if (self->ob_size > 1) { - for (p = self->ob_item, - q = self->ob_item + (self->ob_size - 1)*itemsize; - p < q; - p += itemsize, q -= itemsize) { - memmove(tmp, p, itemsize); - memmove(p, q, itemsize); - memmove(q, tmp, itemsize); - } - } - - INCREF(None); - return None; -} - -/* The following routines were adapted from listobject.c but not converted. - To make them work you will have to work! */ - -#if 0 -static object * -array_index(self, args) - arrayobject *self; - object *args; -{ - int i; - - if (args == NULL) { - err_badarg(); - return NULL; - } - for (i = 0; i < self->ob_size; i++) { - if (cmpobject(self->ob_item[i], args) == 0) - return newintobject((long)i); - } - err_setstr(ValueError, "array.index(x): x not in array"); - return NULL; -} -#endif - -#if 0 -static object * -array_count(self, args) - arrayobject *self; - object *args; -{ - int count = 0; - int i; - - if (args == NULL) { - err_badarg(); - return NULL; - } - for (i = 0; i < self->ob_size; i++) { - if (cmpobject(self->ob_item[i], args) == 0) - count++; - } - return newintobject((long)count); -} -#endif - -#if 0 -static object * -array_remove(self, args) - arrayobject *self; - object *args; -{ - int i; - - if (args == NULL) { - err_badarg(); - return NULL; - } - for (i = 0; i < self->ob_size; i++) { - if (cmpobject(self->ob_item[i], args) == 0) { - if (array_ass_slice(self, i, i+1, (object *)NULL) != 0) - return NULL; - INCREF(None); - return None; - } - - } - err_setstr(ValueError, "array.remove(x): x not in array"); - return NULL; -} -#endif - -static object * -array_fromfile(self, args) - arrayobject *self; - object *args; -{ - object *f; - int n; - FILE *fp; - if (!getargs(args, "(Oi)", &f, &n)) - return NULL; - fp = getfilefile(f); - if (fp == NULL) { - err_setstr(TypeError, "arg1 must be open file"); - return NULL; - } - if (n > 0) { - char *item = self->ob_item; - int itemsize = self->ob_descr->itemsize; - int nread; - RESIZE(item, char, (self->ob_size + n) * itemsize); - if (item == NULL) { - err_nomem(); - return NULL; - } - self->ob_item = item; - self->ob_size += n; - nread = fread(item + (self->ob_size - n) * itemsize, - itemsize, n, fp); - if (nread < n) { - self->ob_size -= (n - nread); - RESIZE(item, char, self->ob_size*itemsize); - self->ob_item = item; - err_setstr(EOFError, "not enough items in file"); - return NULL; - } - } - INCREF(None); - return None; -} - -static object * -array_tofile(self, args) - arrayobject *self; - object *args; -{ - object *f; - FILE *fp; - if (!getargs(args, "O", &f)) - return NULL; - fp = getfilefile(f); - if (fp == NULL) { - err_setstr(TypeError, "arg must be open file"); - return NULL; - } - if (self->ob_size > 0) { - if (fwrite(self->ob_item, self->ob_descr->itemsize, - self->ob_size, fp) != self->ob_size) { - err_errno(IOError); - clearerr(fp); - return NULL; - } - } - INCREF(None); - return None; -} - -static object * -array_fromlist(self, args) - arrayobject *self; - object *args; -{ - int n; - object *list; - int itemsize = self->ob_descr->itemsize; - if (!getargs(args, "O", &list)) - return NULL; - if (!is_listobject(list)) { - err_setstr(TypeError, "arg must be list"); - return NULL; - } - n = getlistsize(list); - if (n > 0) { - char *item = self->ob_item; - int i; - RESIZE(item, char, (self->ob_size + n) * itemsize); - if (item == NULL) { - err_nomem(); - return NULL; - } - self->ob_item = item; - self->ob_size += n; - for (i = 0; i < n; i++) { - object *v = getlistitem(list, i); - if ((*self->ob_descr->setitem)(self, - self->ob_size - n + i, v) != 0) { - self->ob_size -= n; - RESIZE(item, char, self->ob_size * itemsize); - self->ob_item = item; - return NULL; - } - } - } - INCREF(None); - return None; -} - -static object * -array_tolist(self, args) - arrayobject *self; - object *args; -{ - object *list = newlistobject(self->ob_size); - int i; - if (list == NULL) - return NULL; - for (i = 0; i < self->ob_size; i++) { - object *v = getarrayitem((object *)self, i); - if (v == NULL) { - DECREF(list); - return NULL; - } - setlistitem(list, i, v); - } - return list; -} - -static object * -array_fromstring(self, args) - arrayobject *self; - object *args; -{ - char *str; - int n; - int itemsize = self->ob_descr->itemsize; - if (!getargs(args, "s#", &str, &n)) - return NULL; - if (n % itemsize != 0) { - err_setstr(ValueError, - "string length not a multiple of item size"); - return NULL; - } - n = n / itemsize; - if (n > 0) { - char *item = self->ob_item; - RESIZE(item, char, (self->ob_size + n) * itemsize); - if (item == NULL) { - err_nomem(); - return NULL; - } - self->ob_item = item; - self->ob_size += n; - memcpy(item + (self->ob_size - n) * itemsize, str, itemsize*n); - } - INCREF(None); - return None; -} - -static object * -array_tostring(self, args) - arrayobject *self; - object *args; -{ - if (!getargs(args, "")) - return NULL; - return newsizedstringobject(self->ob_item, - self->ob_size * self->ob_descr->itemsize); -} - -static struct methodlist array_methods[] = { - {"append", (method)array_append}, - {"byteswap", (method)array_byteswap}, -/* {"count", (method)array_count},*/ - {"fromfile", (method)array_fromfile}, - {"fromlist", (method)array_fromlist}, - {"fromstring", (method)array_fromstring}, -/* {"index", (method)array_index},*/ - {"insert", (method)array_insert}, - {"read", (method)array_fromfile}, -/* {"remove", (method)array_remove},*/ - {"reverse", (method)array_reverse}, -/* {"sort", (method)array_sort},*/ - {"tofile", (method)array_tofile}, - {"tolist", (method)array_tolist}, - {"tostring", (method)array_tostring}, - {"write", (method)array_tofile}, - {NULL, NULL} /* sentinel */ -}; - -static object * -array_getattr(a, name) - arrayobject *a; - char *name; -{ - if (strcmp(name, "typecode") == 0) { - char tc = a->ob_descr->typecode; - return newsizedstringobject(&tc, 1); - } - if (strcmp(name, "itemsize") == 0) { - return newintobject((long)a->ob_descr->itemsize); - } - if (strcmp(name, "__members__") == 0) { - object *list = newlistobject(2); - if (list) { - setlistitem(list, 0, newstringobject("typecode")); - setlistitem(list, 1, newstringobject("itemsize")); - if (err_occurred()) { - DECREF(list); - list = NULL; - } - } - return list; - } - return findmethod(array_methods, (object *)a, name); -} - -static int -array_print(a, fp, flags) - arrayobject *a; - FILE *fp; - int flags; -{ - int ok = 0; - int i, len; - object *v; - len = a->ob_size; - if (len == 0) { - fprintf(fp, "array('%c')", a->ob_descr->typecode); - return ok; - } - if (a->ob_descr->typecode == 'c') { - fprintf(fp, "array('c', "); - v = array_tostring(a, (object *)NULL); - ok = printobject(v, fp, 0); - XDECREF(v); - fprintf(fp, ")"); - return ok; - } - fprintf(fp, "array('%c', [", a->ob_descr->typecode); - for (i = 0; i < len && ok == 0; i++) { - if (i > 0) - fprintf(fp, ", "); - v = (a->ob_descr->getitem)(a, i); - ok = printobject(v, fp, 0); - XDECREF(v); - } - fprintf(fp, "])"); - return ok; -} - -static object * -array_repr(a) - arrayobject *a; -{ - char buf[256]; - object *s, *t, *comma, *v; - int i, len; - len = a->ob_size; - if (len == 0) { - sprintf(buf, "array('%c')", a->ob_descr->typecode); - return newstringobject(buf); - } - if (a->ob_descr->typecode == 'c') { - sprintf(buf, "array('c', "); - s = newstringobject(buf); - v = array_tostring(a, (object *)NULL); - t = reprobject(v); - XDECREF(v); - joinstring_decref(&s, t); - joinstring_decref(&s, newstringobject(")")); - return s; - } - sprintf(buf, "array('%c', [", a->ob_descr->typecode); - s = newstringobject(buf); - comma = newstringobject(", "); - for (i = 0; i < len && !err_occurred(); i++) { - if (i > 0) - joinstring(&s, comma); - v = (a->ob_descr->getitem)(a, i); - t = reprobject(v); - XDECREF(v); - joinstring_decref(&s, t); - } - XDECREF(comma); - joinstring_decref(&s, newstringobject("])")); - return s; -} - -static sequence_methods array_as_sequence = { - (inquiry)array_length, /*sq_length*/ - (binaryfunc)array_concat, /*sq_concat*/ - (intargfunc)array_repeat, /*sq_repeat*/ - (intargfunc)array_item, /*sq_item*/ - (intintargfunc)array_slice, /*sq_slice*/ - (intobjargproc)array_ass_item, /*sq_ass_item*/ - (intintobjargproc)array_ass_slice, /*sq_ass_slice*/ -}; - -statichere typeobject Arraytype = { - OB_HEAD_INIT(&Typetype) - 0, - "array", - sizeof(arrayobject), - 0, - (destructor)array_dealloc, /*tp_dealloc*/ - (printfunc)array_print, /*tp_print*/ - (getattrfunc)array_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)array_compare, /*tp_compare*/ - (reprfunc)array_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - &array_as_sequence, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ -}; - - -static object * -a_array(self, args) - object *self; - object *args; -{ - char c; - object *initial = NULL; - struct arraydescr *descr; - if (!getargs(args, "c", &c)) { - err_clear(); - if (!getargs(args, "(cO)", &c, &initial)) - return NULL; - if (!is_listobject(initial) && !is_stringobject(initial)) { - err_setstr(TypeError, - "array initializer must be list or string"); - return NULL; - } - } - for (descr = descriptors; descr->typecode != '\0'; descr++) { - if (descr->typecode == c) { - object *a; - int len; - if (initial == NULL || !is_listobject(initial)) - len = 0; - else - len = getlistsize(initial); - a = newarrayobject(len, descr); - if (a == NULL) - return NULL; - if (len > 0) { - int i; - for (i = 0; i < len; i++) { - object *v = getlistitem(initial, i); - if (setarrayitem(a, i, v) != 0) { - DECREF(a); - return NULL; - } - } - } - if (initial != NULL && is_stringobject(initial)) { - object *v = - array_fromstring((arrayobject *)a, initial); - if (v == NULL) { - DECREF(a); - return NULL; - } - DECREF(v); - } - return a; - } - } - err_setstr(ValueError, "bad typecode (must be c, b, h, l, f or d)"); - return NULL; -} - -static struct methodlist a_methods[] = { - {"array", a_array}, - {NULL, NULL} /* sentinel */ -}; - -void -initarray() -{ - initmodule("array", a_methods); -} diff --git a/Modules/audioop.c b/Modules/audioop.c deleted file mode 100644 index 899bbc62b1..0000000000 --- a/Modules/audioop.c +++ /dev/null @@ -1,1238 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* audioopmodule - Module to detect peak values in arrays */ - -#include "allobjects.h" -#include "modsupport.h" - -#if defined(__CHAR_UNSIGNED__) -#if defined(signed) -!ERROR!; READ THE SOURCE FILE!; -/* This module currently does not work on systems where only unsigned - characters are available. Take it out of Setup. Sorry. */ -#endif -#endif - -#include "mymath.h" - -/* Code shamelessly stolen from sox, -** (c) Craig Reese, Joe Campbell and Jeff Poskanzer 1989 */ - -#define MINLIN -32768 -#define MAXLIN 32767 -#define LINCLIP(x) do { if ( x < MINLIN ) x = MINLIN ; else if ( x > MAXLIN ) x = MAXLIN; } while ( 0 ) - -static unsigned char st_linear_to_ulaw( /* int sample */ ); - -/* -** This macro converts from ulaw to 16 bit linear, faster. -** -** Jef Poskanzer -** 23 October 1989 -** -** Input: 8 bit ulaw sample -** Output: signed 16 bit linear sample -*/ -#define st_ulaw_to_linear(ulawbyte) ulaw_table[ulawbyte] - -static int ulaw_table[256] = { - -32124, -31100, -30076, -29052, -28028, -27004, -25980, -24956, - -23932, -22908, -21884, -20860, -19836, -18812, -17788, -16764, - -15996, -15484, -14972, -14460, -13948, -13436, -12924, -12412, - -11900, -11388, -10876, -10364, -9852, -9340, -8828, -8316, - -7932, -7676, -7420, -7164, -6908, -6652, -6396, -6140, - -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092, - -3900, -3772, -3644, -3516, -3388, -3260, -3132, -3004, - -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980, - -1884, -1820, -1756, -1692, -1628, -1564, -1500, -1436, - -1372, -1308, -1244, -1180, -1116, -1052, -988, -924, - -876, -844, -812, -780, -748, -716, -684, -652, - -620, -588, -556, -524, -492, -460, -428, -396, - -372, -356, -340, -324, -308, -292, -276, -260, - -244, -228, -212, -196, -180, -164, -148, -132, - -120, -112, -104, -96, -88, -80, -72, -64, - -56, -48, -40, -32, -24, -16, -8, 0, - 32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, - 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, - 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, - 11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316, - 7932, 7676, 7420, 7164, 6908, 6652, 6396, 6140, - 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092, - 3900, 3772, 3644, 3516, 3388, 3260, 3132, 3004, - 2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980, - 1884, 1820, 1756, 1692, 1628, 1564, 1500, 1436, - 1372, 1308, 1244, 1180, 1116, 1052, 988, 924, - 876, 844, 812, 780, 748, 716, 684, 652, - 620, 588, 556, 524, 492, 460, 428, 396, - 372, 356, 340, 324, 308, 292, 276, 260, - 244, 228, 212, 196, 180, 164, 148, 132, - 120, 112, 104, 96, 88, 80, 72, 64, - 56, 48, 40, 32, 24, 16, 8, 0 }; - -#define ZEROTRAP /* turn on the trap as per the MIL-STD */ -#define BIAS 0x84 /* define the add-in bias for 16 bit samples */ -#define CLIP 32635 - -static unsigned char -st_linear_to_ulaw( sample ) -int sample; - { - static int exp_lut[256] = {0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3, - 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, - 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, - 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, - 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, - 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, - 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, - 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7}; - int sign, exponent, mantissa; - unsigned char ulawbyte; - - /* Get the sample into sign-magnitude. */ - sign = (sample >> 8) & 0x80; /* set aside the sign */ - if ( sign != 0 ) sample = -sample; /* get magnitude */ - if ( sample > CLIP ) sample = CLIP; /* clip the magnitude */ - - /* Convert from 16 bit linear to ulaw. */ - sample = sample + BIAS; - exponent = exp_lut[( sample >> 7 ) & 0xFF]; - mantissa = ( sample >> ( exponent + 3 ) ) & 0x0F; - ulawbyte = ~ ( sign | ( exponent << 4 ) | mantissa ); -#ifdef ZEROTRAP - if ( ulawbyte == 0 ) ulawbyte = 0x02; /* optional CCITT trap */ -#endif - - return ulawbyte; - } -/* End of code taken from sox */ - -/* Intel ADPCM step variation table */ -static int indexTable[16] = { - -1, -1, -1, -1, 2, 4, 6, 8, - -1, -1, -1, -1, 2, 4, 6, 8, -}; - -static int stepsizeTable[89] = { - 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, - 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, - 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, - 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, - 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, - 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, - 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, - 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, - 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 -}; - -#define CHARP(cp, i) ((signed char *)(cp+i)) -#define SHORTP(cp, i) ((short *)(cp+i)) -#define LONGP(cp, i) ((long *)(cp+i)) - - - -static object *AudioopError; - -static object * -audioop_getsample(self, args) - object *self; - object *args; -{ - signed char *cp; - int len, size, val; - int i; - - if ( !getargs(args, "(s#ii)", &cp, &len, &size, &i) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - if ( i < 0 || i >= len/size ) { - err_setstr(AudioopError, "Index out of range"); - return 0; - } - if ( size == 1 ) val = (int)*CHARP(cp, i); - else if ( size == 2 ) val = (int)*SHORTP(cp, i*2); - else if ( size == 4 ) val = (int)*LONGP(cp, i*4); - return newintobject(val); -} - -static object * -audioop_max(self, args) - object *self; - object *args; -{ - signed char *cp; - int len, size, val; - int i; - int max = 0; - - if ( !getargs(args, "(s#i)", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - for ( i=0; i<len; i+= size) { - if ( size == 1 ) val = (int)*CHARP(cp, i); - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = (int)*LONGP(cp, i); - if ( val < 0 ) val = (-val); - if ( val > max ) max = val; - } - return newintobject(max); -} - -static object * -audioop_minmax(self, args) - object *self; - object *args; -{ - signed char *cp; - int len, size, val; - int i; - int min = 0x7fffffff, max = -0x7fffffff; - - if (!getargs(args, "(s#i)", &cp, &len, &size)) - return NULL; - if (size != 1 && size != 2 && size != 4) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return NULL; - } - for (i = 0; i < len; i += size) { - if (size == 1) val = (int) *CHARP(cp, i); - else if (size == 2) val = (int) *SHORTP(cp, i); - else if (size == 4) val = (int) *LONGP(cp, i); - if (val > max) max = val; - if (val < min) min = val; - } - return mkvalue("(ii)", min, max); -} - -static object * -audioop_avg(self, args) - object *self; - object *args; -{ - signed char *cp; - int len, size, val; - int i; - float avg = 0.0; - - if ( !getargs(args, "(s#i)", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - for ( i=0; i<len; i+= size) { - if ( size == 1 ) val = (int)*CHARP(cp, i); - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = (int)*LONGP(cp, i); - avg += val; - } - if ( len == 0 ) - val = 0; - else - val = (int)(avg / (float)(len/size)); - return newintobject(val); -} - -static object * -audioop_rms(self, args) - object *self; - object *args; -{ - signed char *cp; - int len, size, val; - int i; - float sum_squares = 0.0; - - if ( !getargs(args, "(s#i)", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - for ( i=0; i<len; i+= size) { - if ( size == 1 ) val = (int)*CHARP(cp, i); - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = (int)*LONGP(cp, i); - sum_squares += (float)val*(float)val; - } - if ( len == 0 ) - val = 0; - else - val = (int)sqrt(sum_squares / (float)(len/size)); - return newintobject(val); -} - -static double _sum2(a, b, len) - short *a; - short *b; - int len; -{ - int i; - double sum = 0.0; - - for( i=0; i<len; i++) { - sum = sum + (double)a[i]*(double)b[i]; - } - return sum; -} - -/* -** Findfit tries to locate a sample within another sample. Its main use -** is in echo-cancellation (to find the feedback of the output signal in -** the input signal). -** The method used is as follows: -** -** let R be the reference signal (length n) and A the input signal (length N) -** with N > n, and let all sums be over i from 0 to n-1. -** -** Now, for each j in {0..N-n} we compute a factor fj so that -fj*R matches A -** as good as possible, i.e. sum( (A[j+i]+fj*R[i])^2 ) is minimal. This -** equation gives fj = sum( A[j+i]R[i] ) / sum(R[i]^2). -** -** Next, we compute the relative distance between the original signal and -** the modified signal and minimize that over j: -** vj = sum( (A[j+i]-fj*R[i])^2 ) / sum( A[j+i]^2 ) => -** vj = ( sum(A[j+i]^2)*sum(R[i]^2) - sum(A[j+i]R[i])^2 ) / sum( A[j+i]^2 ) -** -** In the code variables correspond as follows: -** cp1 A -** cp2 R -** len1 N -** len2 n -** aj_m1 A[j-1] -** aj_lm1 A[j+n-1] -** sum_ri_2 sum(R[i]^2) -** sum_aij_2 sum(A[i+j]^2) -** sum_aij_ri sum(A[i+j]R[i]) -** -** sum_ri is calculated once, sum_aij_2 is updated each step and sum_aij_ri -** is completely recalculated each step. -*/ -static object * -audioop_findfit(self, args) - object *self; - object *args; -{ - short *cp1, *cp2; - int len1, len2; - int j, best_j; - double aj_m1, aj_lm1; - double sum_ri_2, sum_aij_2, sum_aij_ri, result, best_result, factor; - - if ( !getargs(args, "(s#s#)", &cp1, &len1, &cp2, &len2) ) - return 0; - if ( len1 & 1 || len2 & 1 ) { - err_setstr(AudioopError, "Strings should be even-sized"); - return 0; - } - len1 >>= 1; - len2 >>= 1; - - if ( len1 < len2 ) { - err_setstr(AudioopError, "First sample should be longer"); - return 0; - } - sum_ri_2 = _sum2(cp2, cp2, len2); - sum_aij_2 = _sum2(cp1, cp1, len2); - sum_aij_ri = _sum2(cp1, cp2, len2); - - result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2; - - best_result = result; - best_j = 0; - j = 0; - - for ( j=1; j<=len1-len2; j++) { - aj_m1 = (double)cp1[j-1]; - aj_lm1 = (double)cp1[j+len2-1]; - - sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1; - sum_aij_ri = _sum2(cp1+j, cp2, len2); - - result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2; - - if ( result < best_result ) { - best_result = result; - best_j = j; - } - - } - - factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2; - - return mkvalue("(if)", best_j, factor); -} - -/* -** findfactor finds a factor f so that the energy in A-fB is minimal. -** See the comment for findfit for details. -*/ -static object * -audioop_findfactor(self, args) - object *self; - object *args; -{ - short *cp1, *cp2; - int len1, len2; - double sum_ri_2, sum_aij_ri, result; - - if ( !getargs(args, "(s#s#)", &cp1, &len1, &cp2, &len2) ) - return 0; - if ( len1 & 1 || len2 & 1 ) { - err_setstr(AudioopError, "Strings should be even-sized"); - return 0; - } - if ( len1 != len2 ) { - err_setstr(AudioopError, "Samples should be same size"); - return 0; - } - len2 >>= 1; - sum_ri_2 = _sum2(cp2, cp2, len2); - sum_aij_ri = _sum2(cp1, cp2, len2); - - result = sum_aij_ri / sum_ri_2; - - return newfloatobject(result); -} - -/* -** findmax returns the index of the n-sized segment of the input sample -** that contains the most energy. -*/ -static object * -audioop_findmax(self, args) - object *self; - object *args; -{ - short *cp1; - int len1, len2; - int j, best_j; - double aj_m1, aj_lm1; - double result, best_result; - - if ( !getargs(args, "(s#i)", &cp1, &len1, &len2) ) - return 0; - if ( len1 & 1 ) { - err_setstr(AudioopError, "Strings should be even-sized"); - return 0; - } - len1 >>= 1; - - if ( len1 < len2 ) { - err_setstr(AudioopError, "Input sample should be longer"); - return 0; - } - - result = _sum2(cp1, cp1, len2); - - best_result = result; - best_j = 0; - j = 0; - - for ( j=1; j<=len1-len2; j++) { - aj_m1 = (double)cp1[j-1]; - aj_lm1 = (double)cp1[j+len2-1]; - - result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1; - - if ( result > best_result ) { - best_result = result; - best_j = j; - } - - } - - return newintobject(best_j); -} - -static object * -audioop_avgpp(self, args) - object *self; - object *args; -{ - signed char *cp; - int len, size, val, prevval, prevextremevalid = 0, prevextreme; - int i; - float avg = 0.0; - int diff, prevdiff, extremediff, nextreme = 0; - - if ( !getargs(args, "(s#i)", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - /* Compute first delta value ahead. Also automatically makes us - ** skip the first extreme value - */ - if ( size == 1 ) prevval = (int)*CHARP(cp, 0); - else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0); - else if ( size == 4 ) prevval = (int)*LONGP(cp, 0); - if ( size == 1 ) val = (int)*CHARP(cp, size); - else if ( size == 2 ) val = (int)*SHORTP(cp, size); - else if ( size == 4 ) val = (int)*LONGP(cp, size); - prevdiff = val - prevval; - - for ( i=size; i<len; i+= size) { - if ( size == 1 ) val = (int)*CHARP(cp, i); - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = (int)*LONGP(cp, i); - diff = val - prevval; - if ( diff*prevdiff < 0 ) { - /* Derivative changed sign. Compute difference to last extreme - ** value and remember. - */ - if ( prevextremevalid ) { - extremediff = prevval - prevextreme; - if ( extremediff < 0 ) - extremediff = -extremediff; - avg += extremediff; - nextreme++; - } - prevextremevalid = 1; - prevextreme = prevval; - } - prevval = val; - if ( diff != 0 ) - prevdiff = diff; - } - if ( nextreme == 0 ) - val = 0; - else - val = (int)(avg / (float)nextreme); - return newintobject(val); -} - -static object * -audioop_maxpp(self, args) - object *self; - object *args; -{ - signed char *cp; - int len, size, val, prevval, prevextremevalid = 0, prevextreme; - int i; - int max = 0; - int diff, prevdiff, extremediff; - - if ( !getargs(args, "(s#i)", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - /* Compute first delta value ahead. Also automatically makes us - ** skip the first extreme value - */ - if ( size == 1 ) prevval = (int)*CHARP(cp, 0); - else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0); - else if ( size == 4 ) prevval = (int)*LONGP(cp, 0); - if ( size == 1 ) val = (int)*CHARP(cp, size); - else if ( size == 2 ) val = (int)*SHORTP(cp, size); - else if ( size == 4 ) val = (int)*LONGP(cp, size); - prevdiff = val - prevval; - - for ( i=size; i<len; i+= size) { - if ( size == 1 ) val = (int)*CHARP(cp, i); - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = (int)*LONGP(cp, i); - diff = val - prevval; - if ( diff*prevdiff < 0 ) { - /* Derivative changed sign. Compute difference to last extreme - ** value and remember. - */ - if ( prevextremevalid ) { - extremediff = prevval - prevextreme; - if ( extremediff < 0 ) - extremediff = -extremediff; - if ( extremediff > max ) - max = extremediff; - } - prevextremevalid = 1; - prevextreme = prevval; - } - prevval = val; - if ( diff != 0 ) - prevdiff = diff; - } - return newintobject(max); -} - -static object * -audioop_cross(self, args) - object *self; - object *args; -{ - signed char *cp; - int len, size, val; - int i; - int prevval, ncross; - - if ( !getargs(args, "(s#i)", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - ncross = -1; - prevval = 17; /* Anything <> 0,1 */ - for ( i=0; i<len; i+= size) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) >> 7; - else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) >> 15; - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 31; - val = val & 1; - if ( val != prevval ) ncross++; - prevval = val; - } - return newintobject(ncross); -} - -static object * -audioop_mul(self, args) - object *self; - object *args; -{ - signed char *cp, *ncp; - int len, size, val; - double factor, fval, maxval; - object *rv; - int i; - - if ( !getargs(args, "(s#id)", &cp, &len, &size, &factor ) ) - return 0; - - if ( size == 1 ) maxval = (double) 0x7f; - else if ( size == 2 ) maxval = (double) 0x7fff; - else if ( size == 4 ) maxval = (double) 0x7fffffff; - else { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = newsizedstringobject(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)getstringvalue(rv); - - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = (int)*CHARP(cp, i); - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = (int)*LONGP(cp, i); - fval = (double)val*factor; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val = (int)fval; - if ( size == 1 ) *CHARP(ncp, i) = (signed char)val; - else if ( size == 2 ) *SHORTP(ncp, i) = (short)val; - else if ( size == 4 ) *LONGP(ncp, i) = (long)val; - } - return rv; -} - -static object * -audioop_tomono(self, args) - object *self; - object *args; -{ - signed char *cp, *ncp; - int len, size, val1, val2; - double fac1, fac2, fval, maxval; - object *rv; - int i; - - if ( !getargs(args, "(s#idd)", &cp, &len, &size, &fac1, &fac2 ) ) - return 0; - - if ( size == 1 ) maxval = (double) 0x7f; - else if ( size == 2 ) maxval = (double) 0x7fff; - else if ( size == 4 ) maxval = (double) 0x7fffffff; - else { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = newsizedstringobject(NULL, len/2); - if ( rv == 0 ) - return 0; - ncp = (signed char *)getstringvalue(rv); - - - for ( i=0; i < len; i += size*2 ) { - if ( size == 1 ) val1 = (int)*CHARP(cp, i); - else if ( size == 2 ) val1 = (int)*SHORTP(cp, i); - else if ( size == 4 ) val1 = (int)*LONGP(cp, i); - if ( size == 1 ) val2 = (int)*CHARP(cp, i+1); - else if ( size == 2 ) val2 = (int)*SHORTP(cp, i+2); - else if ( size == 4 ) val2 = (int)*LONGP(cp, i+4); - fval = (double)val1*fac1 + (double)val2*fac2; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val1 = (int)fval; - if ( size == 1 ) *CHARP(ncp, i/2) = (signed char)val1; - else if ( size == 2 ) *SHORTP(ncp, i/2) = (short)val1; - else if ( size == 4 ) *LONGP(ncp, i/2)= (long)val1; - } - return rv; -} - -static object * -audioop_tostereo(self, args) - object *self; - object *args; -{ - signed char *cp, *ncp; - int len, size, val1, val2, val; - double fac1, fac2, fval, maxval; - object *rv; - int i; - - if ( !getargs(args, "(s#idd)", &cp, &len, &size, &fac1, &fac2 ) ) - return 0; - - if ( size == 1 ) maxval = (double) 0x7f; - else if ( size == 2 ) maxval = (double) 0x7fff; - else if ( size == 4 ) maxval = (double) 0x7fffffff; - else { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = newsizedstringobject(NULL, len*2); - if ( rv == 0 ) - return 0; - ncp = (signed char *)getstringvalue(rv); - - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = (int)*CHARP(cp, i); - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = (int)*LONGP(cp, i); - - fval = (double)val*fac1; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val1 = (int)fval; - - fval = (double)val*fac2; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val2 = (int)fval; - - if ( size == 1 ) *CHARP(ncp, i*2) = (signed char)val1; - else if ( size == 2 ) *SHORTP(ncp, i*2) = (short)val1; - else if ( size == 4 ) *LONGP(ncp, i*2) = (long)val1; - - if ( size == 1 ) *CHARP(ncp, i*2+1) = (signed char)val2; - else if ( size == 2 ) *SHORTP(ncp, i*2+2) = (short)val2; - else if ( size == 4 ) *LONGP(ncp, i*2+4) = (long)val2; - } - return rv; -} - -static object * -audioop_add(self, args) - object *self; - object *args; -{ - signed char *cp1, *cp2, *ncp; - int len1, len2, size, val1, val2; - object *rv; - int i; - - if ( !getargs(args, "(s#s#i)", - &cp1, &len1, &cp2, &len2, &size ) ) - return 0; - - if ( len1 != len2 ) { - err_setstr(AudioopError, "Lengths should be the same"); - return 0; - } - - if ( size != 1 && size != 2 && size != 4) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = newsizedstringobject(NULL, len1); - if ( rv == 0 ) - return 0; - ncp = (signed char *)getstringvalue(rv); - - - for ( i=0; i < len1; i += size ) { - if ( size == 1 ) val1 = (int)*CHARP(cp1, i); - else if ( size == 2 ) val1 = (int)*SHORTP(cp1, i); - else if ( size == 4 ) val1 = (int)*LONGP(cp1, i); - - if ( size == 1 ) val2 = (int)*CHARP(cp2, i); - else if ( size == 2 ) val2 = (int)*SHORTP(cp2, i); - else if ( size == 4 ) val2 = (int)*LONGP(cp2, i); - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val1+val2); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val1+val2); - else if ( size == 4 ) *LONGP(ncp, i) = (long)(val1+val2); - } - return rv; -} - -static object * -audioop_bias(self, args) - object *self; - object *args; -{ - signed char *cp, *ncp; - int len, size, val; - object *rv; - int i; - int bias; - - if ( !getargs(args, "(s#ii)", - &cp, &len, &size , &bias) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = newsizedstringobject(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)getstringvalue(rv); - - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = (int)*CHARP(cp, i); - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = (int)*LONGP(cp, i); - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val+bias); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val+bias); - else if ( size == 4 ) *LONGP(ncp, i) = (long)(val+bias); - } - return rv; -} - -static object * -audioop_reverse(self, args) - object *self; - object *args; -{ - signed char *cp; - unsigned char *ncp; - int len, size, val; - object *rv; - int i, j; - - if ( !getargs(args, "(s#i)", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4 ) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = newsizedstringobject(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - j = len - i - size; - - if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); - else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val); - else if ( size == 4 ) *LONGP(ncp, j) = (long)(val<<16); - } - return rv; -} - -static object * -audioop_lin2lin(self, args) - object *self; - object *args; -{ - signed char *cp; - unsigned char *ncp; - int len, size, size2, val; - object *rv; - int i, j; - - if ( !getargs(args, "(s#ii)", - &cp, &len, &size, &size2) ) - return 0; - - if ( (size != 1 && size != 2 && size != 4) || - (size2 != 1 && size2 != 2 && size2 != 4)) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = newsizedstringobject(NULL, (len/size)*size2); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - - for ( i=0, j=0; i < len; i += size, j += size2 ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - if ( size2 == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); - else if ( size2 == 2 ) *SHORTP(ncp, j) = (short)(val); - else if ( size2 == 4 ) *LONGP(ncp, j) = (long)(val<<16); - } - return rv; -} - -static object * -audioop_lin2ulaw(self, args) - object *self; - object *args; -{ - signed char *cp; - unsigned char *ncp; - int len, size, val; - object *rv; - int i; - - if ( !getargs(args, "(s#i)", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = newsizedstringobject(NULL, len/size); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - *ncp++ = st_linear_to_ulaw(val); - } - return rv; -} - -static object * -audioop_ulaw2lin(self, args) - object *self; - object *args; -{ - unsigned char *cp; - unsigned char cval; - signed char *ncp; - int len, size, val; - object *rv; - int i; - - if ( !getargs(args, "(s#i)", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = newsizedstringobject(NULL, len*size); - if ( rv == 0 ) - return 0; - ncp = (signed char *)getstringvalue(rv); - - for ( i=0; i < len*size; i += size ) { - cval = *cp++; - val = st_ulaw_to_linear(cval); - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); - else if ( size == 4 ) *LONGP(ncp, i) = (long)(val<<16); - } - return rv; -} - -static object * -audioop_lin2adpcm(self, args) - object *self; - object *args; -{ - signed char *cp; - signed char *ncp; - int len, size, val, step, valpred, delta, index, sign, vpdiff, diff; - object *rv, *state, *str; - int i, outputbuffer, bufferstep; - - if ( !getargs(args, "(s#iO)", - &cp, &len, &size, &state) ) - return 0; - - - if ( size != 1 && size != 2 && size != 4) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - str = newsizedstringobject(NULL, len/(size*2)); - if ( str == 0 ) - return 0; - ncp = (signed char *)getstringvalue(str); - - /* Decode state, should have (value, step) */ - if ( state == None ) { - /* First time, it seems. Set defaults */ - valpred = 0; - step = 7; - index = 0; - } else if ( !getargs(state, "(ii)", &valpred, &index) ) - return 0; - - step = stepsizeTable[index]; - bufferstep = 1; - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - /* Step 1 - compute difference with previous value */ - diff = val - valpred; - sign = (diff < 0) ? 8 : 0; - if ( sign ) diff = (-diff); - - /* Step 2 - Divide and clamp */ - /* Note: - ** This code *approximately* computes: - ** delta = diff*4/step; - ** vpdiff = (delta+0.5)*step/4; - ** but in shift step bits are dropped. The net result of this is - ** that even if you have fast mul/div hardware you cannot put it to - ** good use since the fixup would be too expensive. - */ - delta = 0; - vpdiff = (step >> 3); - - if ( diff >= step ) { - delta = 4; - diff -= step; - vpdiff += step; - } - step >>= 1; - if ( diff >= step ) { - delta |= 2; - diff -= step; - vpdiff += step; - } - step >>= 1; - if ( diff >= step ) { - delta |= 1; - vpdiff += step; - } - - /* Step 3 - Update previous value */ - if ( sign ) - valpred -= vpdiff; - else - valpred += vpdiff; - - /* Step 4 - Clamp previous value to 16 bits */ - if ( valpred > 32767 ) - valpred = 32767; - else if ( valpred < -32768 ) - valpred = -32768; - - /* Step 5 - Assemble value, update index and step values */ - delta |= sign; - - index += indexTable[delta]; - if ( index < 0 ) index = 0; - if ( index > 88 ) index = 88; - step = stepsizeTable[index]; - - /* Step 6 - Output value */ - if ( bufferstep ) { - outputbuffer = (delta << 4) & 0xf0; - } else { - *ncp++ = (delta & 0x0f) | outputbuffer; - } - bufferstep = !bufferstep; - } - rv = mkvalue("(O(ii))", str, valpred, index); - DECREF(str); - return rv; -} - -static object * -audioop_adpcm2lin(self, args) - object *self; - object *args; -{ - signed char *cp; - signed char *ncp; - int len, size, valpred, step, delta, index, sign, vpdiff; - object *rv, *str, *state; - int i, inputbuffer, bufferstep; - - if ( !getargs(args, "(s#iO)", - &cp, &len, &size, &state) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - err_setstr(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - /* Decode state, should have (value, step) */ - if ( state == None ) { - /* First time, it seems. Set defaults */ - valpred = 0; - step = 7; - index = 0; - } else if ( !getargs(state, "(ii)", &valpred, &index) ) - return 0; - - str = newsizedstringobject(NULL, len*size*2); - if ( str == 0 ) - return 0; - ncp = (signed char *)getstringvalue(str); - - step = stepsizeTable[index]; - bufferstep = 0; - - for ( i=0; i < len*size*2; i += size ) { - /* Step 1 - get the delta value and compute next index */ - if ( bufferstep ) { - delta = inputbuffer & 0xf; - } else { - inputbuffer = *cp++; - delta = (inputbuffer >> 4) & 0xf; - } - - bufferstep = !bufferstep; - - /* Step 2 - Find new index value (for later) */ - index += indexTable[delta]; - if ( index < 0 ) index = 0; - if ( index > 88 ) index = 88; - - /* Step 3 - Separate sign and magnitude */ - sign = delta & 8; - delta = delta & 7; - - /* Step 4 - Compute difference and new predicted value */ - /* - ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment - ** in adpcm_coder. - */ - vpdiff = step >> 3; - if ( delta & 4 ) vpdiff += step; - if ( delta & 2 ) vpdiff += step>>1; - if ( delta & 1 ) vpdiff += step>>2; - - if ( sign ) - valpred -= vpdiff; - else - valpred += vpdiff; - - /* Step 5 - clamp output value */ - if ( valpred > 32767 ) - valpred = 32767; - else if ( valpred < -32768 ) - valpred = -32768; - - /* Step 6 - Update step value */ - step = stepsizeTable[index]; - - /* Step 6 - Output value */ - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(valpred >> 8); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(valpred); - else if ( size == 4 ) *LONGP(ncp, i) = (long)(valpred<<16); - } - - rv = mkvalue("(O(ii))", str, valpred, index); - DECREF(str); - return rv; -} - -static struct methodlist audioop_methods[] = { - { "max", audioop_max }, - { "minmax", audioop_minmax }, - { "avg", audioop_avg }, - { "maxpp", audioop_maxpp }, - { "avgpp", audioop_avgpp }, - { "rms", audioop_rms }, - { "findfit", audioop_findfit }, - { "findmax", audioop_findmax }, - { "findfactor", audioop_findfactor }, - { "cross", audioop_cross }, - { "mul", audioop_mul }, - { "add", audioop_add }, - { "bias", audioop_bias }, - { "ulaw2lin", audioop_ulaw2lin }, - { "lin2ulaw", audioop_lin2ulaw }, - { "lin2lin", audioop_lin2lin }, - { "adpcm2lin", audioop_adpcm2lin }, - { "lin2adpcm", audioop_lin2adpcm }, - { "tomono", audioop_tomono }, - { "tostereo", audioop_tostereo }, - { "getsample", audioop_getsample }, - { "reverse", audioop_reverse }, - { 0, 0 } -}; - - -void -initaudioop() -{ - object *m, *d; - m = initmodule("audioop", audioop_methods); - d = getmoduledict(m); - AudioopError = newstringobject("audioop.error"); - if ( AudioopError == NULL || dictinsert(d,"error",AudioopError) ) - fatal("can't define audioop.error"); -} diff --git a/Modules/binascii.c b/Modules/binascii.c deleted file mode 100644 index c74ed3c219..0000000000 --- a/Modules/binascii.c +++ /dev/null @@ -1,743 +0,0 @@ -/*********************************************************** -Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum, -Amsterdam, The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* -** Routines to represent binary data in ASCII and vice-versa -** -** This module currently supports the following encodings: -** uuencode: -** each line encodes 45 bytes (except possibly the last) -** First char encodes (binary) length, rest data -** each char encodes 6 bits, as follows: -** binary: 01234567 abcdefgh ijklmnop -** ascii: 012345 67abcd efghij klmnop -** ASCII encoding method is "excess-space": 000000 is encoded as ' ', etc. -** short binary data is zero-extended (so the bits are always in the -** right place), this does *not* reflect in the length. -** base64: -** Line breaks are insignificant, but lines are at most 76 chars -** each char encodes 6 bits, in similar order as uucode/hqx. Encoding -** is done via a table. -** Short binary data is filled (in ASCII) with '='. -** hqx: -** File starts with introductory text, real data starts and ends -** with colons. -** Data consists of three similar parts: info, datafork, resourcefork. -** Each part is protected (at the end) with a 16-bit crc -** The binary data is run-length encoded, and then ascii-fied: -** binary: 01234567 abcdefgh ijklmnop -** ascii: 012345 67abcd efghij klmnop -** ASCII encoding is table-driven, see the code. -** Short binary data results in the runt ascii-byte being output with -** the bits in the right place. -** -** While I was reading dozens of programs that encode or decode the formats -** here (documentation? hihi:-) I have formulated Jansen's Observation: -** -** Programs that encode binary data in ASCII are written in -** such a style that they are as unreadable as possible. Devices used -** include unnecessary global variables, burying important tables -** in unrelated sourcefiles, putting functions in include files, -** using seemingly-descriptive variable names for different purposes, -** calls to empty subroutines and a host of others. -** -** I have attempted to break with this tradition, but I guess that that -** does make the performance sub-optimal. Oh well, too bad... -** -** Jack Jansen, CWI, July 1995. -*/ - - -#include "Python.h" - -static PyObject *Error; -static PyObject *Incomplete; - -/* -** hqx lookup table, ascii->binary. -*/ - -#define RUNCHAR 0x90 - -#define DONE 0x7F -#define SKIP 0x7E -#define FAIL 0x7D - -static unsigned char table_a2b_hqx[256] = { -/* ^@ ^A ^B ^C ^D ^E ^F ^G */ -/* 0*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, -/* \b \t \n ^K ^L \r ^N ^O */ -/* 1*/ FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL, -/* ^P ^Q ^R ^S ^T ^U ^V ^W */ -/* 2*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, -/* ^X ^Y ^Z ^[ ^\ ^] ^^ ^_ */ -/* 3*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, -/* ! " # $ % & ' */ -/* 4*/ FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, -/* ( ) * + , - . / */ -/* 5*/ 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL, -/* 0 1 2 3 4 5 6 7 */ -/* 6*/ 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL, -/* 8 9 : ; < = > ? */ -/* 7*/ 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL, -/* @ A B C D E F G */ -/* 8*/ 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, -/* H I J K L M N O */ -/* 9*/ 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL, -/* P Q R S T U V W */ -/*10*/ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL, -/* X Y Z [ \ ] ^ _ */ -/*11*/ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL, -/* ` a b c d e f g */ -/*12*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL, -/* h i j k l m n o */ -/*13*/ 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL, -/* p q r s t u v w */ -/*14*/ 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL, -/* x y z { | } ~ ^? */ -/*15*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, -/*16*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, -}; - -static unsigned char table_b2a_hqx[] = - "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr"; - -static char table_a2b_base64[] = { - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */ - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; - -#define BASE64_PAD '=' -#define BASE64_MAXBIN 57 /* Max binary chunk size (76 char line) */ - -static unsigned char table_b2a_base64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - - -static unsigned short crctab_hqx[256] = { - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, -}; - -static char doc_a2b_uu[] = "(ascii) -> bin. Decode a line of uuencoded data"; - -static PyObject * -binascii_a2b_uu(self, args) - PyObject *self; - PyObject *args; -{ - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - int ascii_len, bin_len; - - if ( !PyArg_ParseTuple(args, "s#", &ascii_data, &ascii_len) ) - return NULL; - - /* First byte: binary data length (in bytes) */ - bin_len = (*ascii_data++ - ' ') & 077; - ascii_len--; - - /* Allocate the buffer */ - if ( (rv=PyString_FromStringAndSize(NULL, bin_len)) == NULL ) - return NULL; - bin_data = (unsigned char *)PyString_AsString(rv); - - for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) { - this_ch = *ascii_data; - if ( this_ch == '\n' || this_ch == '\r' || ascii_len <= 0) { - /* - ** Whitespace. Assume some spaces got eaten at - ** end-of-line. (We check this later) - */ - this_ch = 0; - } else { - /* Check the character for legality - ** The 64 in stead of the expected 63 is because there are a few - ** uuencodes out there that use '@' as zero in stead of space. - */ - if ( this_ch < ' ' || this_ch > (' ' + 64)) { - PyErr_SetString(Error, "Illegal char"); - Py_DECREF(rv); - return NULL; - } - this_ch = (this_ch - ' ') & 077; - } - /* - ** Shift it in on the low end, and see if there's - ** a byte ready for output. - */ - leftchar = (leftchar << 6) | (this_ch); - leftbits += 6; - if ( leftbits >= 8 ) { - leftbits -= 8; - *bin_data++ = (leftchar >> leftbits) & 0xff; - leftchar &= ((1 << leftbits) - 1); - bin_len--; - } - } - /* - ** Finally, check that if there's anything left on the line - ** that it's whitespace only. - */ - while( ascii_len-- > 0 ) { - this_ch = *ascii_data++; - if ( this_ch != ' ' && this_ch != '\n' && this_ch != '\r' ) { - PyErr_SetString(Error, "Trailing garbage"); - Py_DECREF(rv); - return NULL; - } - } - return rv; -} - -static char doc_b2a_uu[] = "(bin) -> ascii. Uuencode line of data"; - -static PyObject * -binascii_b2a_uu(self, args) - PyObject *self; - PyObject *args; -{ - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - int bin_len; - - if ( !PyArg_ParseTuple(args, "s#", &bin_data, &bin_len) ) - return NULL; - if ( bin_len > 45 ) { - /* The 45 is a limit that appears in all uuencode's */ - PyErr_SetString(Error, "At most 45 bytes at once"); - return NULL; - } - - /* We're lazy and allocate to much (fixed up later) */ - if ( (rv=PyString_FromStringAndSize(NULL, bin_len*2)) == NULL ) - return NULL; - ascii_data = (unsigned char *)PyString_AsString(rv); - - /* Store the length */ - *ascii_data++ = ' ' + (bin_len & 077); - - for( ; bin_len > 0 || leftbits != 0 ; bin_len--, bin_data++ ) { - /* Shift the data (or padding) into our buffer */ - if ( bin_len > 0 ) /* Data */ - leftchar = (leftchar << 8) | *bin_data; - else /* Padding */ - leftchar <<= 8; - leftbits += 8; - - /* See if there are 6-bit groups ready */ - while ( leftbits >= 6 ) { - this_ch = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - *ascii_data++ = this_ch + ' '; - } - } - *ascii_data++ = '\n'; /* Append a courtesy newline */ - - _PyString_Resize(&rv, (ascii_data - (unsigned char *)PyString_AsString(rv))); - return rv; -} - -static char doc_a2b_base64[] = "(ascii) -> bin. Decode a line of base64 data"; - -static PyObject * -binascii_a2b_base64(self, args) - PyObject *self; - PyObject *args; -{ - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - int npad = 0; - PyObject *rv; - int ascii_len, bin_len; - - if ( !PyArg_ParseTuple(args, "s#", &ascii_data, &ascii_len) ) - return NULL; - - bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */ - - /* Allocate the buffer */ - if ( (rv=PyString_FromStringAndSize(NULL, bin_len)) == NULL ) - return NULL; - bin_data = (unsigned char *)PyString_AsString(rv); - bin_len = 0; - for( ; ascii_len > 0 ; ascii_len--, ascii_data++ ) { - /* Skip some punctuation */ - this_ch = (*ascii_data & 0x7f); - if ( this_ch == '\r' || this_ch == '\n' || this_ch == ' ' ) - continue; - - if ( this_ch == BASE64_PAD ) - npad++; - this_ch = table_a2b_base64[(*ascii_data) & 0x7f]; - if ( this_ch == (unsigned char) -1 ) continue; - /* - ** Shift it in on the low end, and see if there's - ** a byte ready for output. - */ - leftchar = (leftchar << 6) | (this_ch); - leftbits += 6; - if ( leftbits >= 8 ) { - leftbits -= 8; - *bin_data++ = (leftchar >> leftbits) & 0xff; - leftchar &= ((1 << leftbits) - 1); - bin_len++; - } - } - /* Check that no bits are left */ - if ( leftbits ) { - PyErr_SetString(Error, "Incorrect padding"); - Py_DECREF(rv); - return NULL; - } - /* and remove any padding */ - bin_len -= npad; - /* and set string size correctly */ - _PyString_Resize(&rv, bin_len); - return rv; -} - -static char doc_b2a_base64[] = "(bin) -> ascii. Base64-code line of data"; - -static PyObject * -binascii_b2a_base64(self, args) - PyObject *self; - PyObject *args; -{ - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - int bin_len; - - if ( !PyArg_ParseTuple(args, "s#", &bin_data, &bin_len) ) - return NULL; - if ( bin_len > BASE64_MAXBIN ) { - PyErr_SetString(Error, "Too much data for base64 line"); - return NULL; - } - - /* We're lazy and allocate to much (fixed up later) */ - if ( (rv=PyString_FromStringAndSize(NULL, bin_len*2)) == NULL ) - return NULL; - ascii_data = (unsigned char *)PyString_AsString(rv); - - for( ; bin_len > 0 ; bin_len--, bin_data++ ) { - /* Shift the data into our buffer */ - leftchar = (leftchar << 8) | *bin_data; - leftbits += 8; - - /* See if there are 6-bit groups ready */ - while ( leftbits >= 6 ) { - this_ch = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - *ascii_data++ = table_b2a_base64[this_ch]; - } - } - if ( leftbits == 2 ) { - *ascii_data++ = table_b2a_base64[(leftchar&3) << 4]; - *ascii_data++ = BASE64_PAD; - *ascii_data++ = BASE64_PAD; - } else if ( leftbits == 4 ) { - *ascii_data++ = table_b2a_base64[(leftchar&0xf) << 2]; - *ascii_data++ = BASE64_PAD; - } - *ascii_data++ = '\n'; /* Append a courtesy newline */ - - _PyString_Resize(&rv, (ascii_data - (unsigned char *)PyString_AsString(rv))); - return rv; -} - -static char doc_a2b_hqx[] = "ascii -> bin, done. Decode .hqx coding"; - -static PyObject * -binascii_a2b_hqx(self, args) - PyObject *self; - PyObject *args; -{ - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - int len; - int done = 0; - - if ( !PyArg_ParseTuple(args, "s#", &ascii_data, &len) ) - return NULL; - - /* Allocate a string that is too big (fixed later) */ - if ( (rv=PyString_FromStringAndSize(NULL, len)) == NULL ) - return NULL; - bin_data = (unsigned char *)PyString_AsString(rv); - - for( ; len > 0 ; len--, ascii_data++ ) { - /* Get the byte and look it up */ - this_ch = table_a2b_hqx[*ascii_data]; - if ( this_ch == SKIP ) - continue; - if ( this_ch == FAIL ) { - PyErr_SetString(Error, "Illegal char"); - Py_DECREF(rv); - return NULL; - } - if ( this_ch == DONE ) { - /* The terminating colon */ - done = 1; - break; - } - - /* Shift it into the buffer and see if any bytes are ready */ - leftchar = (leftchar << 6) | (this_ch); - leftbits += 6; - if ( leftbits >= 8 ) { - leftbits -= 8; - *bin_data++ = (leftchar >> leftbits) & 0xff; - leftchar &= ((1 << leftbits) - 1); - } - } - - if ( leftbits && !done ) { - PyErr_SetString(Incomplete, - "String has incomplete number of bytes"); - Py_DECREF(rv); - return NULL; - } - _PyString_Resize(&rv, (bin_data - (unsigned char *)PyString_AsString(rv))); - if ( rv ) - return Py_BuildValue("Oi", rv, done); - return NULL; -} - -static char doc_rlecode_hqx[] = "Binhex RLE-code binary data"; - -static PyObject * -binascii_rlecode_hqx(self, args) - PyObject *self; - PyObject *args; -{ - unsigned char *in_data, *out_data; - PyObject *rv; - unsigned char ch; - int in, inend, len; - - if ( !PyArg_ParseTuple(args, "s#", &in_data, &len) ) - return NULL; - - /* Worst case: output is twice as big as input (fixed later) */ - if ( (rv=PyString_FromStringAndSize(NULL, len*2)) == NULL ) - return NULL; - out_data = (unsigned char *)PyString_AsString(rv); - - for( in=0; in<len; in++) { - ch = in_data[in]; - if ( ch == RUNCHAR ) { - /* RUNCHAR. Escape it. */ - *out_data++ = RUNCHAR; - *out_data++ = 0; - } else { - /* Check how many following are the same */ - for(inend=in+1; - inend<len && in_data[inend] == ch && - inend < in+255; - inend++) ; - if ( inend - in > 3 ) { - /* More than 3 in a row. Output RLE. */ - *out_data++ = ch; - *out_data++ = RUNCHAR; - *out_data++ = inend-in; - in = inend-1; - } else { - /* Less than 3. Output the byte itself */ - *out_data++ = ch; - } - } - } - _PyString_Resize(&rv, (out_data - (unsigned char *)PyString_AsString(rv))); - return rv; -} - -static char doc_b2a_hqx[] = "Encode .hqx data"; - -static PyObject * -binascii_b2a_hqx(self, args) - PyObject *self; - PyObject *args; -{ - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - int len; - - if ( !PyArg_ParseTuple(args, "s#", &bin_data, &len) ) - return NULL; - - /* Allocate a buffer that is at least large enough */ - if ( (rv=PyString_FromStringAndSize(NULL, len*2)) == NULL ) - return NULL; - ascii_data = (unsigned char *)PyString_AsString(rv); - - for( ; len > 0 ; len--, bin_data++ ) { - /* Shift into our buffer, and output any 6bits ready */ - leftchar = (leftchar << 8) | *bin_data; - leftbits += 8; - while ( leftbits >= 6 ) { - this_ch = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - *ascii_data++ = table_b2a_hqx[this_ch]; - } - } - /* Output a possible runt byte */ - if ( leftbits ) { - leftchar <<= (6-leftbits); - *ascii_data++ = table_b2a_hqx[leftchar & 0x3f]; - } - _PyString_Resize(&rv, (ascii_data - (unsigned char *)PyString_AsString(rv))); - return rv; -} - -static char doc_rledecode_hqx[] = "Decode hexbin RLE-coded string"; - -static PyObject * -binascii_rledecode_hqx(self, args) - PyObject *self; - PyObject *args; -{ - unsigned char *in_data, *out_data; - unsigned char in_byte, in_repeat; - PyObject *rv; - int in_len, out_len, out_len_left; - - if ( !PyArg_ParseTuple(args, "s#", &in_data, &in_len) ) - return NULL; - - /* Empty string is a special case */ - if ( in_len == 0 ) - return Py_BuildValue("s", ""); - - /* Allocate a buffer of reasonable size. Resized when needed */ - out_len = in_len*2; - if ( (rv=PyString_FromStringAndSize(NULL, out_len)) == NULL ) - return NULL; - out_len_left = out_len; - out_data = (unsigned char *)PyString_AsString(rv); - - /* - ** We need two macros here to get/put bytes and handle - ** end-of-buffer for input and output strings. - */ -#define INBYTE(b) \ - do { \ - if ( --in_len < 0 ) { \ - PyErr_SetString(Incomplete, ""); \ - Py_DECREF(rv); \ - return NULL; \ - } \ - b = *in_data++; \ - } while(0) - -#define OUTBYTE(b) \ - do { \ - if ( --out_len_left < 0 ) { \ - _PyString_Resize(&rv, 2*out_len); \ - if ( rv == NULL ) return NULL; \ - out_data = (unsigned char *)PyString_AsString(rv) + out_len; \ - out_len_left = out_len-1; \ - out_len = out_len * 2; \ - } \ - *out_data++ = b; \ - } while(0) - - /* - ** Handle first byte separately (since we have to get angry - ** in case of an orphaned RLE code). - */ - INBYTE(in_byte); - - if (in_byte == RUNCHAR) { - INBYTE(in_repeat); - if (in_repeat != 0) { - /* Note Error, not Incomplete (which is at the end - ** of the string only). This is a programmer error. - */ - PyErr_SetString(Error, "Orphaned RLE code at start"); - Py_DECREF(rv); - return NULL; - } - OUTBYTE(RUNCHAR); - } else { - OUTBYTE(in_byte); - } - - while( in_len > 0 ) { - INBYTE(in_byte); - - if (in_byte == RUNCHAR) { - INBYTE(in_repeat); - if ( in_repeat == 0 ) { - /* Just an escaped RUNCHAR value */ - OUTBYTE(RUNCHAR); - } else { - /* Pick up value and output a sequence of it */ - in_byte = out_data[-1]; - while ( --in_repeat > 0 ) - OUTBYTE(in_byte); - } - } else { - /* Normal byte */ - OUTBYTE(in_byte); - } - } - _PyString_Resize(&rv, (out_data - (unsigned char *)PyString_AsString(rv))); - return rv; -} - -static char doc_crc_hqx[] = "(data, oldcrc) -> newcrc. Compute hqx CRC incrementally"; - -static PyObject * -binascii_crc_hqx(self, args) - PyObject *self; - PyObject *args; -{ - unsigned char *bin_data; - unsigned int crc; - int len; - - if ( !PyArg_ParseTuple(args, "s#i", &bin_data, &len, &crc) ) - return NULL; - - while(len--) { - crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++]; - } - - return Py_BuildValue("i", crc); -} - -/* List of functions defined in the module */ - -static struct PyMethodDef binascii_module_methods[] = { - {"a2b_uu", binascii_a2b_uu, 1, doc_a2b_uu}, - {"b2a_uu", binascii_b2a_uu, 1, doc_b2a_uu}, - {"a2b_base64", binascii_a2b_base64, 1, - doc_a2b_base64}, - {"b2a_base64", binascii_b2a_base64, 1, - doc_b2a_base64}, - {"a2b_hqx", binascii_a2b_hqx, 1, doc_a2b_hqx}, - {"b2a_hqx", binascii_b2a_hqx, 1, doc_b2a_hqx}, - {"rlecode_hqx", binascii_rlecode_hqx, 1, - doc_rlecode_hqx}, - {"rledecode_hqx", binascii_rledecode_hqx, 1, - doc_rledecode_hqx}, - {"crc_hqx", binascii_crc_hqx, 1, doc_crc_hqx}, - {NULL, NULL} /* sentinel */ -}; - - -/* Initialization function for the module (*must* be called initbinascii) */ -static char doc_binascii[] = "Conversion between binary data and ASCII"; - -void -initbinascii() -{ - PyObject *m, *d, *x; - - /* Create the module and add the functions */ - m = Py_InitModule("binascii", binascii_module_methods); - - d = PyModule_GetDict(m); - x = PyString_FromString(doc_binascii); - PyDict_SetItemString(d, "__doc__", x); - - Error = PyString_FromString("binascii.Error"); - PyDict_SetItemString(d, "Error", Error); - Incomplete = PyString_FromString("binascii.Incomplete"); - PyDict_SetItemString(d, "Incomplete", Incomplete); - - /* Check for errors */ - if (PyErr_Occurred()) - Py_FatalError("can't initialize module binascii"); -} diff --git a/Modules/bsddbmodule.c b/Modules/bsddbmodule.c deleted file mode 100644 index 8cf674e959..0000000000 --- a/Modules/bsddbmodule.c +++ /dev/null @@ -1,676 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Berkeley DB interface. - Author: Michael McLay - Hacked: Guido van Rossum - Btree and Recno additions plus sequence methods: David Ely - - XXX To do: - - provide interface to the B-tree and record libraries too - - provide a way to access the various hash functions - - support more open flags - */ - -#include "allobjects.h" -#include "modsupport.h" - -#include <sys/types.h> -#include <sys/stat.h> -#include <fcntl.h> -#include <db.h> -/* Please don't include internal header files of the Berkeley db package - (it messes up the info required in the Setup file) */ - -typedef struct { - OB_HEAD - DB *di_bsddb; - int di_size; /* -1 means recompute */ -} bsddbobject; - -staticforward typeobject Bsddbtype; - -#define is_bsddbobject(v) ((v)->ob_type == &Bsddbtype) - -static object *BsddbError; - -static object * -newdbhashobject(file, flags, mode, - bsize, ffactor, nelem, cachesize, hash, lorder) - char *file; - int flags; - int mode; - int bsize; - int ffactor; - int nelem; - int cachesize; - int hash; /* XXX ignored */ - int lorder; -{ - bsddbobject *dp; - HASHINFO info; - - if ((dp = NEWOBJ(bsddbobject, &Bsddbtype)) == NULL) - return NULL; - - info.bsize = bsize; - info.ffactor = ffactor; - info.nelem = nelem; - info.cachesize = cachesize; - info.hash = NULL; /* XXX should derive from hash argument */ - info.lorder = lorder; - - if ((dp->di_bsddb = dbopen(file, flags, mode, DB_HASH, &info)) == NULL) { - err_errno(BsddbError); - DECREF(dp); - return NULL; - } - - dp->di_size = -1; - - return (object *)dp; -} - -static object * -newdbbtobject(file, flags, mode, - btflags, cachesize, maxkeypage, minkeypage, psize, lorder) - char *file; - int flags; - int mode; - int btflags; - int cachesize; - int maxkeypage; - int minkeypage; - int psize; - int lorder; -{ - bsddbobject *dp; - BTREEINFO info; - - if ((dp = NEWOBJ(bsddbobject, &Bsddbtype)) == NULL) - return NULL; - - info.flags = btflags; - info.cachesize = cachesize; - info.maxkeypage = maxkeypage; - info.minkeypage = minkeypage; - info.psize = psize; - info.lorder = lorder; - info.compare = 0; /* Use default comparison functions, for now..*/ - info.prefix = 0; - - if ((dp->di_bsddb = dbopen(file, flags, mode, DB_BTREE, &info)) == NULL) { - err_errno(BsddbError); - DECREF(dp); - return NULL; - } - - dp->di_size = -1; - - return (object *)dp; -} - -static object * -newdbrnobject(file, flags, mode, - rnflags, cachesize, psize, lorder, reclen, bval, bfname) - char *file; - int flags; - int mode; - int rnflags; - int cachesize; - int psize; - int lorder; - size_t reclen; - u_char bval; - char *bfname; -{ - bsddbobject *dp; - RECNOINFO info; - - if ((dp = NEWOBJ(bsddbobject, &Bsddbtype)) == NULL) - return NULL; - - info.flags = rnflags; - info.cachesize = cachesize; - info.psize = psize; - info.lorder = lorder; - info.reclen = reclen; - info.bval = bval; - info.bfname = bfname; - - if ((dp->di_bsddb = dbopen(file, flags, mode, DB_RECNO, &info)) == NULL) { - err_errno(BsddbError); - DECREF(dp); - return NULL; - } - - dp->di_size = -1; - - return (object *)dp; -} - - -static void -bsddb_dealloc(dp) - bsddbobject *dp; -{ - if (dp->di_bsddb != NULL) { - if ((dp->di_bsddb->close)(dp->di_bsddb) != 0) - fprintf(stderr, - "Python bsddb: close errno %s in dealloc\n", errno); - } - DEL(dp); -} - -static int -bsddb_length(dp) - bsddbobject *dp; -{ - if (dp->di_size < 0) { - DBT krec, drec; - int status; - int size = 0; - for (status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec,R_FIRST); - status == 0; - status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_NEXT)) - size++; - if (status < 0) { - err_errno(BsddbError); - return -1; - } - dp->di_size = size; - } - return dp->di_size; -} - -static object * -bsddb_subscript(dp, key) - bsddbobject *dp; - object *key; -{ - int status; - object *v; - DBT krec, drec; - char *data; - int size; - - if (!getargs(key, "s#", &data, &size)) - return NULL; - krec.data = data; - krec.size = size; - - status = (dp->di_bsddb->get)(dp->di_bsddb, &krec, &drec, 0); - if (status != 0) { - if (status < 0) - err_errno(BsddbError); - else - err_setval(KeyError, key); - return NULL; - } - - return newsizedstringobject((char *)drec.data, (int)drec.size); -} - -static int -bsddb_ass_sub(dp, key, value) - bsddbobject *dp; - object *key, *value; -{ - int status; - DBT krec, drec; - char *data; - int size; - - if (!getargs(key, "s#", &data, &size)) { - err_setstr(TypeError, "bsddb key type must be string"); - return -1; - } - krec.data = data; - krec.size = size; - dp->di_size = -1; - if (value == NULL) { - status = (dp->di_bsddb->del)(dp->di_bsddb, &krec, 0); - } - else { - if (!getargs(value, "s#", &data, &size)) { - err_setstr(TypeError, "bsddb value type must be string"); - return -1; - } - drec.data = data; - drec.size = size; - status = (dp->di_bsddb->put)(dp->di_bsddb, &krec, &drec, 0); - } - if (status != 0) { - if (status < 0) - err_errno(BsddbError); - else - err_setval(KeyError, key); - return -1; - } - return 0; -} - -static mapping_methods bsddb_as_mapping = { - (inquiry)bsddb_length, /*mp_length*/ - (binaryfunc)bsddb_subscript, /*mp_subscript*/ - (objobjargproc)bsddb_ass_sub, /*mp_ass_subscript*/ -}; - -static object * -bsddb_close(dp, args) - bsddbobject *dp; - object *args; -{ - if (!getnoarg(args)) - return NULL; - if (dp->di_bsddb != NULL) { - if ((dp->di_bsddb->close)(dp->di_bsddb) != 0) { - dp->di_bsddb = NULL; - err_errno(BsddbError); - return NULL; - } - } - dp->di_bsddb = NULL; - INCREF(None); - return None; -} - -static object * -bsddb_keys(dp, args) - bsddbobject *dp; - object *args; -{ - object *list, *item; - DBT krec, drec; - int status; - int err; - - if (!getnoarg(args)) - return NULL; - list = newlistobject(0); - if (list == NULL) - return NULL; - for (status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_FIRST); - status == 0; - status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_NEXT)) { - item = newsizedstringobject((char *)krec.data, (int)krec.size); - if (item == NULL) { - DECREF(list); - return NULL; - } - err = addlistitem(list, item); - DECREF(item); - if (err != 0) { - DECREF(list); - return NULL; - } - } - if (status < 0) { - err_errno(BsddbError); - DECREF(list); - return NULL; - } - if (dp->di_size < 0) - dp->di_size = getlistsize(list); /* We just did the work for this... */ - return list; -} - -static object * -bsddb_has_key(dp, args) - bsddbobject *dp; - object *args; -{ - DBT krec, drec; - int status; - char *data; - int size; - - if (!getargs(args, "s#", &data, &size)) - return NULL; - krec.data = data; - krec.size = size; - - status = (dp->di_bsddb->get)(dp->di_bsddb, &krec, &drec, 0); - if (status < 0) { - err_errno(BsddbError); - return NULL; - } - - return newintobject(status == 0); -} - -static object * -bsddb_set_location(dp, key) - bsddbobject *dp; - object *key; -{ - int status; - object *v; - DBT krec, drec; - char *data; - int size; - - if (!getargs(key, "s#", &data, &size)) - return NULL; - krec.data = data; - krec.size = size; - - status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_CURSOR); - if (status != 0) { - if (status < 0) - err_errno(BsddbError); - else - err_setval(KeyError, key); - return NULL; - } - - return mkvalue("s#s#", krec.data, krec.size, drec.data, drec.size); -} - -static object * -bsddb_seq(dp, args, sequence_request) - bsddbobject *dp; - object *args; - int sequence_request; -{ - int status; - DBT krec, drec; - - if (!getnoarg(args)) - return NULL; - - krec.data = 0; - krec.size = 0; - - status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, sequence_request); - if (status != 0) { - if (status < 0) - err_errno(BsddbError); - else - err_setval(KeyError, args); - return NULL; - } - - return mkvalue("s#s#", krec.data, krec.size, drec.data, drec.size); -} - -static object * -bsddb_next(dp, key) - bsddbobject *dp; - object *key; -{ - return bsddb_seq(dp, key, R_NEXT); -} -static object * -bsddb_previous(dp, key) - bsddbobject *dp; - object *key; -{ - return bsddb_seq(dp, key, R_PREV); -} -static object * -bsddb_first(dp, key) - bsddbobject *dp; - object *key; -{ - return bsddb_seq(dp, key, R_FIRST); -} -static object * -bsddb_last(dp, key) - bsddbobject *dp; - object *key; -{ - return bsddb_seq(dp, key, R_LAST); -} -static object * -bsddb_sync(dp, args) - bsddbobject *dp; - object *args; -{ - int status; - - status = (dp->di_bsddb->sync)(dp->di_bsddb, 0); - if (status != 0) { - err_errno(BsddbError); - return NULL; - } - return newintobject(status = 0); -} -static struct methodlist bsddb_methods[] = { - {"close", (method)bsddb_close}, - {"keys", (method)bsddb_keys}, - {"has_key", (method)bsddb_has_key}, - {"set_location", (method)bsddb_set_location}, - {"next", (method)bsddb_next}, - {"previous", (method)bsddb_previous}, - {"first", (method)bsddb_first}, - {"last", (method)bsddb_last}, - {"sync", (method)bsddb_sync}, - {NULL, NULL} /* sentinel */ -}; - -static object * -bsddb_getattr(dp, name) - object *dp; - char *name; -{ - return findmethod(bsddb_methods, dp, name); -} - -static typeobject Bsddbtype = { - OB_HEAD_INIT(&Typetype) - 0, - "bsddb", - sizeof(bsddbobject), - 0, - (destructor)bsddb_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)bsddb_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - &bsddb_as_mapping, /*tp_as_mapping*/ -}; - -static object * -bsdhashopen(self, args) - object *self; - object *args; -{ - char *file; - char *flag = NULL; - int flags = O_RDONLY; - int mode = 0666; - int bsize = 0; - int ffactor = 0; - int nelem = 0; - int cachesize = 0; - int hash = 0; /* XXX currently ignored */ - int lorder = 0; - - if (!newgetargs(args, "s|siiiiiii", - &file, &flag, &mode, - &bsize, &ffactor, &nelem, &cachesize, &hash, &lorder)) - return NULL; - if (flag != NULL) { - /* XXX need a way to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */ - if (flag[0] == 'r') - flags = O_RDONLY; - else if (flag[0] == 'w') - flags = O_RDWR; - else if (flag[0] == 'c') - flags = O_RDWR|O_CREAT; - else if (flag[0] == 'n') - flags = O_RDWR|O_CREAT|O_TRUNC; - else { - err_setstr(BsddbError, - "Flag should begin with 'r', 'w', 'c' or 'n'"); - return NULL; - } - if (flag[1] == 'l') { -#if defined(O_EXLOCK) && defined(O_SHLOCK) - if (flag[0] == 'r') - flags |= O_SHLOCK; - else - flags |= O_EXLOCK; -#else - err_setstr(BsddbError, "locking not supported on this platform"); - return NULL; -#endif - } - } - return newdbhashobject(file, flags, mode, - bsize, ffactor, nelem, cachesize, hash, lorder); -} - -static object * -bsdbtopen(self, args) - object *self; - object *args; -{ - char *file; - char *flag = NULL; - int flags = O_RDONLY; - int mode = 0666; - int cachesize = 0; - int maxkeypage = 0; - int minkeypage = 0; - int btflags = 0; - unsigned int psize = 0; - int lorder = 0; - - if (!newgetargs(args, "s|siiiiiii", - &file, &flag, &mode, - &btflags, &cachesize, &maxkeypage, &minkeypage, - &psize, &lorder)) - return NULL; - if (flag != NULL) { - /* XXX need a way to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */ - if (flag[0] == 'r') - flags = O_RDONLY; - else if (flag[0] == 'w') - flags = O_RDWR; - else if (flag[0] == 'c') - flags = O_RDWR|O_CREAT; - else if (flag[0] == 'n') - flags = O_RDWR|O_CREAT|O_TRUNC; - else { - err_setstr(BsddbError, - "Flag should begin with 'r', 'w', 'c' or 'n'"); - return NULL; - } - if (flag[1] == 'l') { -#if defined(O_EXLOCK) && defined(O_SHLOCK) - if (flag[0] == 'r') - flags |= O_SHLOCK; - else - flags |= O_EXLOCK; -#else - err_setstr(BsddbError, "locking not supported on this platform"); - return NULL; -#endif - } - } - return newdbbtobject(file, flags, mode, - btflags, cachesize, maxkeypage, minkeypage, - psize, lorder); -} - -static object * -bsdrnopen(self, args) - object *self; - object *args; -{ - char *file; - char *flag = NULL; - int flags = O_RDONLY; - int mode = 0666; - int cachesize = 0; - int rnflags = 0; - unsigned int psize = 0; - int lorder = 0; - size_t reclen = 0; - char *bval = ""; - char *bfname = NULL; - - if (!newgetargs(args, "s|siiiiiiss", - &file, &flag, &mode, - &rnflags, &cachesize, &psize, &lorder, - &reclen, &bval, &bfname)) - return NULL; - if (flag != NULL) { - /* XXX need a way to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */ - if (flag[0] == 'r') - flags = O_RDONLY; - else if (flag[0] == 'w') - flags = O_RDWR; - else if (flag[0] == 'c') - flags = O_RDWR|O_CREAT; - else if (flag[0] == 'n') - flags = O_RDWR|O_CREAT|O_TRUNC; - else { - err_setstr(BsddbError, - "Flag should begin with 'r', 'w', 'c' or 'n'"); - return NULL; - } - if (flag[1] == 'l') { -#if defined(O_EXLOCK) && defined(O_SHLOCK) - if (flag[0] == 'r') - flags |= O_SHLOCK; - else - flags |= O_EXLOCK; -#else - err_setstr(BsddbError, "locking not supported on this platform"); - return NULL; -#endif - } - else if (flag[1] != '\0') { - err_setstr(BsddbError, - "Flag char 2 should be 'l' or absent"); - return NULL; - } - } - return newdbrnobject(file, flags, mode, - rnflags, cachesize, psize, lorder, bval[0], bfname); -} - -static struct methodlist bsddbmodule_methods[] = { - {"hashopen", (method)bsdhashopen, 1}, - {"btopen", (method)bsdbtopen, 1}, - {"rnopen", (method)bsdrnopen, 1}, - {0, 0}, -}; - -void -initbsddb() { - object *m, *d; - - m = initmodule("bsddb", bsddbmodule_methods); - d = getmoduledict(m); - BsddbError = newstringobject("bsddb.error"); - if (BsddbError == NULL || dictinsert(d, "error", BsddbError)) - fatal("can't define bsddb.error"); -} diff --git a/Modules/cdmodule.c b/Modules/cdmodule.c deleted file mode 100644 index 4abef27734..0000000000 --- a/Modules/cdmodule.c +++ /dev/null @@ -1,877 +0,0 @@ -/********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* CD module -- interface to Mark Callow's and Roger Chickering's */ - /* CD Audio Library (CD). */ - -#include <sys/types.h> -#include <cdaudio.h> -/* #include <sigfpe.h> */ -#include "allobjects.h" -#include "import.h" -#include "modsupport.h" -#include "ceval.h" - -#define NCALLBACKS 8 - -typedef struct { - OB_HEAD - CDPLAYER *ob_cdplayer; -} cdplayerobject; - -static object *CdError; /* exception cd.error */ - -static object * -CD_allowremoval(self, args) - cdplayerobject *self; - object *args; -{ - if (!newgetargs(args, "")) - return NULL; - - CDallowremoval(self->ob_cdplayer); - - INCREF(None); - return None; -} - -static object * -CD_preventremoval(self, args) - cdplayerobject *self; - object *args; -{ - if (!newgetargs(args, "")) - return NULL; - - CDpreventremoval(self->ob_cdplayer); - - INCREF(None); - return None; -} - -static object * -CD_bestreadsize(self, args) - cdplayerobject *self; - object *args; -{ - if (!newgetargs(args, "")) - return NULL; - - return newintobject((long) CDbestreadsize(self->ob_cdplayer)); -} - -static object * -CD_close(self, args) - cdplayerobject *self; - object *args; -{ - if (!newgetargs(args, "")) - return NULL; - - if (!CDclose(self->ob_cdplayer)) { - err_errno(CdError); /* XXX - ??? */ - return NULL; - } - self->ob_cdplayer = NULL; - - INCREF(None); - return None; -} - -static object * -CD_eject(self, args) - cdplayerobject *self; - object *args; -{ - CDSTATUS status; - - if (!newgetargs(args, "")) - return NULL; - - if (!CDeject(self->ob_cdplayer)) { - if (CDgetstatus(self->ob_cdplayer, &status) && - status.state == CD_NODISC) - err_setstr(CdError, "no disc in player"); - else - err_setstr(CdError, "eject failed"); - return NULL; - } - - INCREF(None); - return None; -} - -static object * -CD_getstatus(self, args) - cdplayerobject *self; - object *args; -{ - CDSTATUS status; - - if (!newgetargs(args, "")) - return NULL; - - if (!CDgetstatus(self->ob_cdplayer, &status)) { - err_errno(CdError); /* XXX - ??? */ - return NULL; - } - - return mkvalue("(ii(iii)(iii)(iii)iiii)", status.state, - status.track, status.min, status.sec, status.frame, - status.abs_min, status.abs_sec, status.abs_frame, - status.total_min, status.total_sec, status.total_frame, - status.first, status.last, status.scsi_audio, - status.cur_block); -} - -static object * -CD_gettrackinfo(self, args) - cdplayerobject *self; - object *args; -{ - int track; - CDTRACKINFO info; - CDSTATUS status; - - if (!newgetargs(args, "i", &track)) - return NULL; - - if (!CDgettrackinfo(self->ob_cdplayer, track, &info)) { - if (CDgetstatus(self->ob_cdplayer, &status) && - status.state == CD_NODISC) - err_setstr(CdError, "no disc in player"); - else - err_setstr(CdError, "gettrackinfo failed"); - return NULL; - } - - return mkvalue("((iii)(iii))", - info.start_min, info.start_sec, info.start_frame, - info.total_min, info.total_sec, info.total_frame); -} - -static object * -CD_msftoblock(self, args) - cdplayerobject *self; - object *args; -{ - int min, sec, frame; - - if (!newgetargs(args, "iii", &min, &sec, &frame)) - return NULL; - - return newintobject((long) CDmsftoblock(self->ob_cdplayer, - min, sec, frame)); -} - -static object * -CD_play(self, args) - cdplayerobject *self; - object *args; -{ - int start, play; - CDSTATUS status; - - if (!newgetargs(args, "ii", &start, &play)) - return NULL; - - if (!CDplay(self->ob_cdplayer, start, play)) { - if (CDgetstatus(self->ob_cdplayer, &status) && - status.state == CD_NODISC) - err_setstr(CdError, "no disc in player"); - else - err_setstr(CdError, "play failed"); - return NULL; - } - - INCREF(None); - return None; -} - -static object * -CD_playabs(self, args) - cdplayerobject *self; - object *args; -{ - int min, sec, frame, play; - CDSTATUS status; - - if (!newgetargs(args, "iiii", &min, &sec, &frame, &play)) - return NULL; - - if (!CDplayabs(self->ob_cdplayer, min, sec, frame, play)) { - if (CDgetstatus(self->ob_cdplayer, &status) && - status.state == CD_NODISC) - err_setstr(CdError, "no disc in player"); - else - err_setstr(CdError, "playabs failed"); - return NULL; - } - - INCREF(None); - return None; -} - -static object * -CD_playtrack(self, args) - cdplayerobject *self; - object *args; -{ - int start, play; - CDSTATUS status; - - if (!newgetargs(args, "ii", &start, &play)) - return NULL; - - if (!CDplaytrack(self->ob_cdplayer, start, play)) { - if (CDgetstatus(self->ob_cdplayer, &status) && - status.state == CD_NODISC) - err_setstr(CdError, "no disc in player"); - else - err_setstr(CdError, "playtrack failed"); - return NULL; - } - - INCREF(None); - return None; -} - -static object * -CD_playtrackabs(self, args) - cdplayerobject *self; - object *args; -{ - int track, min, sec, frame, play; - CDSTATUS status; - - if (!newgetargs(args, "iiiii", &track, &min, &sec, &frame, &play)) - return NULL; - - if (!CDplaytrackabs(self->ob_cdplayer, track, min, sec, frame, play)) { - if (CDgetstatus(self->ob_cdplayer, &status) && - status.state == CD_NODISC) - err_setstr(CdError, "no disc in player"); - else - err_setstr(CdError, "playtrackabs failed"); - return NULL; - } - - INCREF(None); - return None; -} - -static object * -CD_readda(self, args) - cdplayerobject *self; - object *args; -{ - int numframes, n; - object *result; - - if (!newgetargs(args, "i", &numframes)) - return NULL; - - result = newsizedstringobject(NULL, numframes * sizeof(CDFRAME)); - if (result == NULL) - return NULL; - - n = CDreadda(self->ob_cdplayer, (CDFRAME *) getstringvalue(result), numframes); - if (n == -1) { - DECREF(result); - err_errno(CdError); - return NULL; - } - if (n < numframes) - if (resizestring(&result, n * sizeof(CDFRAME))) - return NULL; - - return result; -} - -static object * -CD_seek(self, args) - cdplayerobject *self; - object *args; -{ - int min, sec, frame; - long block; - - if (!newgetargs(args, "iii", &min, &sec, &frame)) - return NULL; - - block = CDseek(self->ob_cdplayer, min, sec, frame); - if (block == -1) { - err_errno(CdError); - return NULL; - } - - return newintobject(block); -} - -static object * -CD_seektrack(self, args) - cdplayerobject *self; - object *args; -{ - int track; - long block; - - if (!newgetargs(args, "i", &track)) - return NULL; - - block = CDseektrack(self->ob_cdplayer, track); - if (block == -1) { - err_errno(CdError); - return NULL; - } - - return newintobject(block); -} - -static object * -CD_seekblock(self, args) - cdplayerobject *self; - object *args; -{ - unsigned long block; - - if (!newgetargs(args, "l", &block)) - return NULL; - - block = CDseekblock(self->ob_cdplayer, block); - if (block == (unsigned long) -1) { - err_errno(CdError); - return NULL; - } - - return newintobject(block); -} - -static object * -CD_stop(self, args) - cdplayerobject *self; - object *args; -{ - CDSTATUS status; - - if (!newgetargs(args, "")) - return NULL; - - if (!CDstop(self->ob_cdplayer)) { - if (CDgetstatus(self->ob_cdplayer, &status) && - status.state == CD_NODISC) - err_setstr(CdError, "no disc in player"); - else - err_setstr(CdError, "stop failed"); - return NULL; - } - - INCREF(None); - return None; -} - -static object * -CD_togglepause(self, args) - cdplayerobject *self; - object *args; -{ - CDSTATUS status; - - if (!newgetargs(args, "")) - return NULL; - - if (!CDtogglepause(self->ob_cdplayer)) { - if (CDgetstatus(self->ob_cdplayer, &status) && - status.state == CD_NODISC) - err_setstr(CdError, "no disc in player"); - else - err_setstr(CdError, "togglepause failed"); - return NULL; - } - - INCREF(None); - return None; -} - -static struct methodlist cdplayer_methods[] = { - {"allowremoval", (method)CD_allowremoval, 1}, - {"bestreadsize", (method)CD_bestreadsize, 1}, - {"close", (method)CD_close, 1}, - {"eject", (method)CD_eject, 1}, - {"getstatus", (method)CD_getstatus, 1}, - {"gettrackinfo", (method)CD_gettrackinfo, 1}, - {"msftoblock", (method)CD_msftoblock, 1}, - {"play", (method)CD_play, 1}, - {"playabs", (method)CD_playabs, 1}, - {"playtrack", (method)CD_playtrack, 1}, - {"playtrackabs", (method)CD_playtrackabs, 1}, - {"preventremoval", (method)CD_preventremoval, 1}, - {"readda", (method)CD_readda, 1}, - {"seek", (method)CD_seek, 1}, - {"seekblock", (method)CD_seekblock, 1}, - {"seektrack", (method)CD_seektrack, 1}, - {"stop", (method)CD_stop, 1}, - {"togglepause", (method)CD_togglepause, 1}, - {NULL, NULL} /* sentinel */ -}; - -static void -cdplayer_dealloc(self) - cdplayerobject *self; -{ - if (self->ob_cdplayer != NULL) - CDclose(self->ob_cdplayer); - DEL(self); -} - -static object * -cdplayer_getattr(self, name) - cdplayerobject *self; - char *name; -{ - if (self->ob_cdplayer == NULL) { - err_setstr(RuntimeError, "no player active"); - return NULL; - } - return findmethod(cdplayer_methods, (object *)self, name); -} - -typeobject CdPlayertype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "cdplayer", /*tp_name*/ - sizeof(cdplayerobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)cdplayer_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)cdplayer_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - -static object * -newcdplayerobject(cdp) - CDPLAYER *cdp; -{ - cdplayerobject *p; - - p = NEWOBJ(cdplayerobject, &CdPlayertype); - if (p == NULL) - return NULL; - p->ob_cdplayer = cdp; - return (object *) p; -} - -static object * -CD_open(self, args) - object *self, *args; -{ - char *dev, *direction; - CDPLAYER *cdp; - - /* - * Variable number of args. - * First defaults to "None", second defaults to "r". - */ - dev = NULL; - direction = "r"; - if (!newgetargs(args, "|zs", &dev, &direction)) - return NULL; - - cdp = CDopen(dev, direction); - if (cdp == NULL) { - err_errno(CdError); - return NULL; - } - - return newcdplayerobject(cdp); -} - -typedef struct { - OB_HEAD - CDPARSER *ob_cdparser; - struct { - object *ob_cdcallback; - object *ob_cdcallbackarg; - } ob_cdcallbacks[NCALLBACKS]; -} cdparserobject; - -static void -CD_callback(arg, type, data) - void *arg; - CDDATATYPES type; - void *data; -{ - object *result, *args, *v; - char *p; - int i; - cdparserobject *self; - - self = (cdparserobject *) arg; - args = newtupleobject(3); - if (args == NULL) - return; - INCREF(self->ob_cdcallbacks[type].ob_cdcallbackarg); - settupleitem(args, 0, self->ob_cdcallbacks[type].ob_cdcallbackarg); - settupleitem(args, 1, newintobject((long) type)); - switch (type) { - case cd_audio: - v = newsizedstringobject(data, CDDA_DATASIZE); - break; - case cd_pnum: - case cd_index: - v = newintobject(((CDPROGNUM *) data)->value); - break; - case cd_ptime: - case cd_atime: -#define ptr ((struct cdtimecode *) data) - v = mkvalue("(iii)", - ptr->mhi * 10 + ptr->mlo, - ptr->shi * 10 + ptr->slo, - ptr->fhi * 10 + ptr->flo); -#undef ptr - break; - case cd_catalog: - v = newsizedstringobject(NULL, 13); - p = getstringvalue(v); - for (i = 0; i < 13; i++) - *p++ = ((char *) data)[i] + '0'; - break; - case cd_ident: -#define ptr ((struct cdident *) data) - v = newsizedstringobject(NULL, 12); - p = getstringvalue(v); - CDsbtoa(p, ptr->country, 2); - p += 2; - CDsbtoa(p, ptr->owner, 3); - p += 3; - *p++ = ptr->year[0] + '0'; - *p++ = ptr->year[1] + '0'; - *p++ = ptr->serial[0] + '0'; - *p++ = ptr->serial[1] + '0'; - *p++ = ptr->serial[2] + '0'; - *p++ = ptr->serial[3] + '0'; - *p++ = ptr->serial[4] + '0'; -#undef ptr - break; - case cd_control: - v = newintobject((long) *((unchar *) data)); - break; - } - settupleitem(args, 2, v); - if (err_occurred()) { - DECREF(args); - return; - } - - result = call_object(self->ob_cdcallbacks[type].ob_cdcallback, args); - DECREF(args); - XDECREF(result); -} - -static object * -CD_deleteparser(self, args) - cdparserobject *self; - object *args; -{ - int i; - - if (!newgetargs(args, "")) - return NULL; - - CDdeleteparser(self->ob_cdparser); - self->ob_cdparser = NULL; - - /* no sense in keeping the callbacks, so remove them */ - for (i = 0; i < NCALLBACKS; i++) { - XDECREF(self->ob_cdcallbacks[i].ob_cdcallback); - self->ob_cdcallbacks[i].ob_cdcallback = NULL; - XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg); - self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL; - } - - INCREF(None); - return None; -} - -static object * -CD_parseframe(self, args) - cdparserobject *self; - object *args; -{ - char *cdfp; - int length; - CDFRAME *p; - - if (!newgetargs(args, "s#", &cdfp, &length)) - return NULL; - - if (length % sizeof(CDFRAME) != 0) { - err_setstr(TypeError, "bad length"); - return NULL; - } - - p = (CDFRAME *) cdfp; - while (length > 0) { - CDparseframe(self->ob_cdparser, p); - length -= sizeof(CDFRAME); - p++; - if (err_occurred()) - return NULL; - } - - INCREF(None); - return None; -} - -static object * -CD_removecallback(self, args) - cdparserobject *self; - object *args; -{ - int type; - - if (!newgetargs(args, "i", &type)) - return NULL; - - if (type < 0 || type >= NCALLBACKS) { - err_setstr(TypeError, "bad type"); - return NULL; - } - - CDremovecallback(self->ob_cdparser, (CDDATATYPES) type); - - XDECREF(self->ob_cdcallbacks[type].ob_cdcallback); - self->ob_cdcallbacks[type].ob_cdcallback = NULL; - - XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg); - self->ob_cdcallbacks[type].ob_cdcallbackarg = NULL; - - INCREF(None); - return None; -} - -static object * -CD_resetparser(self, args) - cdparserobject *self; - object *args; -{ - if (!newgetargs(args, "")) - return NULL; - - CDresetparser(self->ob_cdparser); - - INCREF(None); - return None; -} - -static object * -CD_addcallback(self, args) - cdparserobject *self; - object *args; -{ - int type; - object *func, *funcarg; - - /* XXX - more work here */ - if (!newgetargs(args, "iOO", &type, &func, &funcarg)) - return NULL; - - if (type < 0 || type >= NCALLBACKS) { - err_setstr(TypeError, "argument out of range"); - return NULL; - } - -#ifdef CDsetcallback - CDaddcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback, (void *) self); -#else - CDsetcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback, (void *) self); -#endif - XDECREF(self->ob_cdcallbacks[type].ob_cdcallback); - INCREF(func); - self->ob_cdcallbacks[type].ob_cdcallback = func; - XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg); - INCREF(funcarg); - self->ob_cdcallbacks[type].ob_cdcallbackarg = funcarg; - -/* - if (type == cd_audio) { - sigfpe_[_UNDERFL].repls = _ZERO; - handle_sigfpes(_ON, _EN_UNDERFL, NULL, _ABORT_ON_ERROR, NULL); - } -*/ - - INCREF(None); - return None; -} - -static struct methodlist cdparser_methods[] = { - {"addcallback", (method)CD_addcallback, 1}, - {"deleteparser", (method)CD_deleteparser, 1}, - {"parseframe", (method)CD_parseframe, 1}, - {"removecallback", (method)CD_removecallback, 1}, - {"resetparser", (method)CD_resetparser, 1}, - {"setcallback", (method)CD_addcallback, 1}, /* backward compatibility */ - {NULL, NULL} /* sentinel */ -}; - -static void -cdparser_dealloc(self) - cdparserobject *self; -{ - int i; - - for (i = 0; i < NCALLBACKS; i++) { - XDECREF(self->ob_cdcallbacks[i].ob_cdcallback); - self->ob_cdcallbacks[i].ob_cdcallback = NULL; - XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg); - self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL; - } - CDdeleteparser(self->ob_cdparser); - DEL(self); -} - -static object * -cdparser_getattr(self, name) - cdparserobject *self; - char *name; -{ - if (self->ob_cdparser == NULL) { - err_setstr(RuntimeError, "no parser active"); - return NULL; - } - - return findmethod(cdparser_methods, (object *)self, name); -} - -typeobject CdParsertype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "cdparser", /*tp_name*/ - sizeof(cdparserobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)cdparser_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)cdparser_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - -static object * -newcdparserobject(cdp) - CDPARSER *cdp; -{ - cdparserobject *p; - int i; - - p = NEWOBJ(cdparserobject, &CdParsertype); - if (p == NULL) - return NULL; - p->ob_cdparser = cdp; - for (i = 0; i < NCALLBACKS; i++) { - p->ob_cdcallbacks[i].ob_cdcallback = NULL; - p->ob_cdcallbacks[i].ob_cdcallbackarg = NULL; - } - return (object *) p; -} - -static object * -CD_createparser(self, args) - object *self, *args; -{ - CDPARSER *cdp; - - if (!newgetargs(args, "")) - return NULL; - cdp = CDcreateparser(); - if (cdp == NULL) { - err_setstr(CdError, "createparser failed"); - return NULL; - } - - return newcdparserobject(cdp); -} - -static object * -CD_msftoframe(self, args) - object *self, *args; -{ - int min, sec, frame; - - if (!newgetargs(args, "iii", &min, &sec, &frame)) - return NULL; - - return newintobject((long) CDmsftoframe(min, sec, frame)); -} - -static struct methodlist CD_methods[] = { - {"open", (method)CD_open, 1}, - {"createparser", (method)CD_createparser, 1}, - {"msftoframe", (method)CD_msftoframe, 1}, - {NULL, NULL} /* Sentinel */ -}; - -void -initcd() -{ - object *m, *d; - - m = initmodule("cd", CD_methods); - d = getmoduledict(m); - - CdError = newstringobject("cd.error"); - dictinsert(d, "error", CdError); - - /* Identifiers for the different types of callbacks from the parser */ - dictinsert(d, "audio", newintobject((long) cd_audio)); - dictinsert(d, "pnum", newintobject((long) cd_pnum)); - dictinsert(d, "index", newintobject((long) cd_index)); - dictinsert(d, "ptime", newintobject((long) cd_ptime)); - dictinsert(d, "atime", newintobject((long) cd_atime)); - dictinsert(d, "catalog", newintobject((long) cd_catalog)); - dictinsert(d, "ident", newintobject((long) cd_ident)); - dictinsert(d, "control", newintobject((long) cd_control)); - - /* Block size information for digital audio data */ - dictinsert(d, "DATASIZE", newintobject((long) CDDA_DATASIZE)); - dictinsert(d, "BLOCKSIZE", newintobject((long) CDDA_BLOCKSIZE)); - - /* Possible states for the cd player */ - dictinsert(d, "ERROR", newintobject((long) CD_ERROR)); - dictinsert(d, "NODISC", newintobject((long) CD_NODISC)); - dictinsert(d, "READY", newintobject((long) CD_READY)); - dictinsert(d, "PLAYING", newintobject((long) CD_PLAYING)); - dictinsert(d, "PAUSED", newintobject((long) CD_PAUSED)); - dictinsert(d, "STILL", newintobject((long) CD_STILL)); -#ifdef CD_CDROM /* only newer versions of the library */ - dictinsert(d, "CDROM", newintobject((long) CD_CDROM)); -#endif - - if (err_occurred()) - fatal("can't initialize module cd"); -} diff --git a/Modules/cgen.py b/Modules/cgen.py deleted file mode 100644 index d358e28dea..0000000000 --- a/Modules/cgen.py +++ /dev/null @@ -1,532 +0,0 @@ -######################################################################## -# Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -# The Netherlands. -# -# All Rights Reserved -# -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -# Centrum or CWI not be used in advertising or publicity pertaining to -# distribution of the software without specific, written prior permission. -# -# STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -# FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. -######################################################################## - -# Python script to parse cstubs file for gl and generate C stubs. -# usage: python cgen.py <cstubs >glmodule.c -# -# NOTE: You must first make a python binary without the "GL" option -# before you can run this, when building Python for the first time. -# See comments in the Makefile. -# -# XXX BUG return arrays generate wrong code -# XXX need to change error returns into gotos to free mallocked arrays - - -import string -import sys - - -# Function to print to stderr -# -def err(*args): - savestdout = sys.stdout - try: - sys.stdout = sys.stderr - for i in args: - print i, - print - finally: - sys.stdout = savestdout - - -# The set of digits that form a number -# -digits = '0123456789' - - -# Function to extract a string of digits from the front of the string. -# Returns the leading string of digits and the remaining string. -# If no number is found, returns '' and the original string. -# -def getnum(s): - n = '' - while s and s[0] in digits: - n = n + s[0] - s = s[1:] - return n, s - - -# Function to check if a string is a number -# -def isnum(s): - if not s: return 0 - for c in s: - if not c in digits: return 0 - return 1 - - -# Allowed function return types -# -return_types = ['void', 'short', 'long'] - - -# Allowed function argument types -# -arg_types = ['char', 'string', 'short', 'u_short', 'float', 'long', 'double'] - - -# Need to classify arguments as follows -# simple input variable -# simple output variable -# input array -# output array -# input giving size of some array -# -# Array dimensions can be specified as follows -# constant -# argN -# constant * argN -# retval -# constant * retval -# -# The dimensions given as constants * something are really -# arrays of points where points are 2- 3- or 4-tuples -# -# We have to consider three lists: -# python input arguments -# C stub arguments (in & out) -# python output arguments (really return values) -# -# There is a mapping from python input arguments to the input arguments -# of the C stub, and a further mapping from C stub arguments to the -# python return values - - -# Exception raised by checkarg() and generate() -# -arg_error = 'bad arg' - - -# Function to check one argument. -# Arguments: the type and the arg "name" (really mode plus subscript). -# Raises arg_error if something's wrong. -# Return type, mode, factor, rest of subscript; factor and rest may be empty. -# -def checkarg(type, arg): - # - # Turn "char *x" into "string x". - # - if type == 'char' and arg[0] == '*': - type = 'string' - arg = arg[1:] - # - # Check that the type is supported. - # - if type not in arg_types: - raise arg_error, ('bad type', type) - if type[:2] == 'u_': - type = 'unsigned ' + type[2:] - # - # Split it in the mode (first character) and the rest. - # - mode, rest = arg[:1], arg[1:] - # - # The mode must be 's' for send (= input) or 'r' for return argument. - # - if mode not in ('r', 's'): - raise arg_error, ('bad arg mode', mode) - # - # Is it a simple argument: if so, we are done. - # - if not rest: - return type, mode, '', '' - # - # Not a simple argument; must be an array. - # The 'rest' must be a subscript enclosed in [ and ]. - # The subscript must be one of the following forms, - # otherwise we don't handle it (where N is a number): - # N - # argN - # retval - # N*argN - # N*retval - # - if rest[:1] <> '[' or rest[-1:] <> ']': - raise arg_error, ('subscript expected', rest) - sub = rest[1:-1] - # - # Is there a leading number? - # - num, sub = getnum(sub) - if num: - # There is a leading number - if not sub: - # The subscript is just a number - return type, mode, num, '' - if sub[:1] == '*': - # There is a factor prefix - sub = sub[1:] - else: - raise arg_error, ('\'*\' expected', sub) - if sub == 'retval': - # size is retval -- must be a reply argument - if mode <> 'r': - raise arg_error, ('non-r mode with [retval]', mode) - elif not isnum(sub) and (sub[:3] <> 'arg' or not isnum(sub[3:])): - raise arg_error, ('bad subscript', sub) - # - return type, mode, num, sub - - -# List of functions for which we have generated stubs -# -functions = [] - - -# Generate the stub for the given function, using the database of argument -# information build by successive calls to checkarg() -# -def generate(type, func, database): - # - # Check that we can handle this case: - # no variable size reply arrays yet - # - n_in_args = 0 - n_out_args = 0 - # - for a_type, a_mode, a_factor, a_sub in database: - if a_mode == 's': - n_in_args = n_in_args + 1 - elif a_mode == 'r': - n_out_args = n_out_args + 1 - else: - # Can't happen - raise arg_error, ('bad a_mode', a_mode) - if (a_mode == 'r' and a_sub) or a_sub == 'retval': - err('Function', func, 'too complicated:', - a_type, a_mode, a_factor, a_sub) - print '/* XXX Too complicated to generate code for */' - return - # - functions.append(func) - # - # Stub header - # - print - print 'static object *' - print 'gl_' + func + '(self, args)' - print '\tobject *self;' - print '\tobject *args;' - print '{' - # - # Declare return value if any - # - if type <> 'void': - print '\t' + type, 'retval;' - # - # Declare arguments - # - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - print '\t' + a_type, - brac = ket = '' - if a_sub and not isnum(a_sub): - if a_factor: - brac = '(' - ket = ')' - print brac + '*', - print 'arg' + `i+1` + ket, - if a_sub and isnum(a_sub): - print '[', a_sub, ']', - if a_factor: - print '[', a_factor, ']', - print ';' - # - # Find input arguments derived from array sizes - # - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode == 's' and a_sub[:3] == 'arg' and isnum(a_sub[3:]): - # Sending a variable-length array - n = eval(a_sub[3:]) - if 1 <= n <= len(database): - b_type, b_mode, b_factor, b_sub = database[n-1] - if b_mode == 's': - database[n-1] = b_type, 'i', a_factor, `i` - n_in_args = n_in_args - 1 - # - # Assign argument positions in the Python argument list - # - in_pos = [] - i_in = 0 - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode == 's': - in_pos.append(i_in) - i_in = i_in + 1 - else: - in_pos.append(-1) - # - # Get input arguments - # - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - if a_type[:9] == 'unsigned ': - xtype = a_type[9:] - else: - xtype = a_type - if a_mode == 'i': - # - # Implicit argument; - # a_factor is divisor if present, - # a_sub indicates which arg (`database index`) - # - j = eval(a_sub) - print '\tif', - print '(!geti' + xtype + 'arraysize(args,', - print `n_in_args` + ',', - print `in_pos[j]` + ',', - if xtype <> a_type: - print '('+xtype+' *)', - print '&arg' + `i+1` + '))' - print '\t\treturn NULL;' - if a_factor: - print '\targ' + `i+1`, - print '= arg' + `i+1`, - print '/', a_factor + ';' - elif a_mode == 's': - if a_sub and not isnum(a_sub): - # Allocate memory for varsize array - print '\tif ((arg' + `i+1`, '=', - if a_factor: - print '('+a_type+'(*)['+a_factor+'])', - print 'NEW(' + a_type, ',', - if a_factor: - print a_factor, '*', - print a_sub, ')) == NULL)' - print '\t\treturn err_nomem();' - print '\tif', - if a_factor or a_sub: # Get a fixed-size array array - print '(!geti' + xtype + 'array(args,', - print `n_in_args` + ',', - print `in_pos[i]` + ',', - if a_factor: print a_factor, - if a_factor and a_sub: print '*', - if a_sub: print a_sub, - print ',', - if (a_sub and a_factor) or xtype <> a_type: - print '('+xtype+' *)', - print 'arg' + `i+1` + '))' - else: # Get a simple variable - print '(!geti' + xtype + 'arg(args,', - print `n_in_args` + ',', - print `in_pos[i]` + ',', - if xtype <> a_type: - print '('+xtype+' *)', - print '&arg' + `i+1` + '))' - print '\t\treturn NULL;' - # - # Begin of function call - # - if type <> 'void': - print '\tretval =', func + '(', - else: - print '\t' + func + '(', - # - # Argument list - # - for i in range(len(database)): - if i > 0: print ',', - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode == 'r' and not a_factor: - print '&', - print 'arg' + `i+1`, - # - # End of function call - # - print ');' - # - # Free varsize arrays - # - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode == 's' and a_sub and not isnum(a_sub): - print '\tDEL(arg' + `i+1` + ');' - # - # Return - # - if n_out_args: - # - # Multiple return values -- construct a tuple - # - if type <> 'void': - n_out_args = n_out_args + 1 - if n_out_args == 1: - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode == 'r': - break - else: - raise arg_error, 'expected r arg not found' - print '\treturn', - print mkobject(a_type, 'arg' + `i+1`) + ';' - else: - print '\t{ object *v = newtupleobject(', - print n_out_args, ');' - print '\t if (v == NULL) return NULL;' - i_out = 0 - if type <> 'void': - print '\t settupleitem(v,', - print `i_out` + ',', - print mkobject(type, 'retval') + ');' - i_out = i_out + 1 - for i in range(len(database)): - a_type, a_mode, a_factor, a_sub = database[i] - if a_mode == 'r': - print '\t settupleitem(v,', - print `i_out` + ',', - s = mkobject(a_type, 'arg' + `i+1`) - print s + ');' - i_out = i_out + 1 - print '\t return v;' - print '\t}' - else: - # - # Simple function return - # Return None or return value - # - if type == 'void': - print '\tINCREF(None);' - print '\treturn None;' - else: - print '\treturn', mkobject(type, 'retval') + ';' - # - # Stub body closing brace - # - print '}' - - -# Subroutine to return a function call to mknew<type>object(<arg>) -# -def mkobject(type, arg): - if type[:9] == 'unsigned ': - type = type[9:] - return 'mknew' + type + 'object((' + type + ') ' + arg + ')' - return 'mknew' + type + 'object(' + arg + ')' - - -defined_archs = [] - -# usage: cgen [ -Dmach ... ] [ file ] -for arg in sys.argv[1:]: - if arg[:2] == '-D': - defined_archs.append(arg[2:]) - else: - # Open optional file argument - sys.stdin = open(arg, 'r') - - -# Input line number -lno = 0 - - -# Input is divided in two parts, separated by a line containing '%%'. -# <part1> -- literally copied to stdout -# <part2> -- stub definitions - -# Variable indicating the current input part. -# -part = 1 - -# Main loop over the input -# -while 1: - try: - line = raw_input() - except EOFError: - break - # - lno = lno+1 - words = string.split(line) - # - if part == 1: - # - # In part 1, copy everything literally - # except look for a line of just '%%' - # - if words == ['%%']: - part = part + 1 - else: - # - # Look for names of manually written - # stubs: a single percent followed by the name - # of the function in Python. - # The stub name is derived by prefixing 'gl_'. - # - if words and words[0][0] == '%': - func = words[0][1:] - if (not func) and words[1:]: - func = words[1] - if func: - functions.append(func) - else: - print line - continue - if not words: - continue # skip empty line - elif words[0] == 'if': - # if XXX rest - # if !XXX rest - if words[1][0] == '!': - if words[1][1:] in defined_archs: - continue - elif words[1] not in defined_archs: - continue - words = words[2:] - if words[0] == '#include': - print line - elif words[0][:1] == '#': - pass # ignore comment - elif words[0] not in return_types: - err('Line', lno, ': bad return type :', words[0]) - elif len(words) < 2: - err('Line', lno, ': no funcname :', line) - else: - if len(words) % 2 <> 0: - err('Line', lno, ': odd argument list :', words[2:]) - else: - database = [] - try: - for i in range(2, len(words), 2): - x = checkarg(words[i], words[i+1]) - database.append(x) - print - print '/*', - for w in words: print w, - print '*/' - generate(words[0], words[1], database) - except arg_error, msg: - err('Line', lno, ':', msg) - - -print -print 'static struct methodlist gl_methods[] = {' -for func in functions: - print '\t{"' + func + '", gl_' + func + '},' -print '\t{NULL, NULL} /* Sentinel */' -print '};' -print -print 'initgl()' -print '{' -print '\tinitmodule("gl", gl_methods);' -print '}' diff --git a/Modules/cgensupport.c b/Modules/cgensupport.c deleted file mode 100644 index 6951467306..0000000000 --- a/Modules/cgensupport.c +++ /dev/null @@ -1,377 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Functions used by cgen output */ - -#include "allobjects.h" -#include "cgensupport.h" - - -/* Functions to extract arguments. - These needs to know the total number of arguments supplied, - since the argument list is a tuple only of there is more than - one argument. */ - -int -getiobjectarg(args, nargs, i, p_arg) - register object *args; - int nargs, i; - object **p_arg; -{ - if (nargs != 1) { - if (args == NULL || !is_tupleobject(args) || - nargs != gettuplesize(args) || - i < 0 || i >= nargs) { - return err_badarg(); - } - else { - args = gettupleitem(args, i); - } - } - if (args == NULL) { - return err_badarg(); - } - *p_arg = args; - return 1; -} - -int -getilongarg(args, nargs, i, p_arg) - register object *args; - int nargs, i; - long *p_arg; -{ - if (nargs != 1) { - if (args == NULL || !is_tupleobject(args) || - nargs != gettuplesize(args) || - i < 0 || i >= nargs) { - return err_badarg(); - } - args = gettupleitem(args, i); - } - if (args == NULL || !is_intobject(args)) { - return err_badarg(); - } - *p_arg = getintvalue(args); - return 1; -} - -int -getishortarg(args, nargs, i, p_arg) - register object *args; - int nargs, i; - short *p_arg; -{ - long x; - if (!getilongarg(args, nargs, i, &x)) - return 0; - *p_arg = x; - return 1; -} - -static int -extractdouble(v, p_arg) - register object *v; - double *p_arg; -{ - if (v == NULL) { - /* Fall through to error return at end of function */ - } - else if (is_floatobject(v)) { - *p_arg = GETFLOATVALUE((floatobject *)v); - return 1; - } - else if (is_intobject(v)) { - *p_arg = GETINTVALUE((intobject *)v); - return 1; - } - else if (is_longobject(v)) { - *p_arg = dgetlongvalue(v); - return 1; - } - return err_badarg(); -} - -static int -extractfloat(v, p_arg) - register object *v; - float *p_arg; -{ - if (v == NULL) { - /* Fall through to error return at end of function */ - } - else if (is_floatobject(v)) { - *p_arg = GETFLOATVALUE((floatobject *)v); - return 1; - } - else if (is_intobject(v)) { - *p_arg = GETINTVALUE((intobject *)v); - return 1; - } - else if (is_longobject(v)) { - *p_arg = dgetlongvalue(v); - return 1; - } - return err_badarg(); -} - -int -getifloatarg(args, nargs, i, p_arg) - register object *args; - int nargs, i; - float *p_arg; -{ - object *v; - float x; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (!extractfloat(v, &x)) - return 0; - *p_arg = x; - return 1; -} - -int -getistringarg(args, nargs, i, p_arg) - object *args; - int nargs, i; - string *p_arg; -{ - object *v; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (!is_stringobject(v)) { - return err_badarg(); - } - *p_arg = getstringvalue(v); - return 1; -} - -int -getichararg(args, nargs, i, p_arg) - object *args; - int nargs, i; - char *p_arg; -{ - string x; - if (!getistringarg(args, nargs, i, &x)) - return 0; - if (x[0] == '\0' || x[1] != '\0') { - /* Not exactly one char */ - return err_badarg(); - } - *p_arg = x[0]; - return 1; -} - -int -getilongarraysize(args, nargs, i, p_arg) - object *args; - int nargs, i; - long *p_arg; -{ - object *v; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - *p_arg = gettuplesize(v); - return 1; - } - if (is_listobject(v)) { - *p_arg = getlistsize(v); - return 1; - } - return err_badarg(); -} - -int -getishortarraysize(args, nargs, i, p_arg) - object *args; - int nargs, i; - short *p_arg; -{ - long x; - if (!getilongarraysize(args, nargs, i, &x)) - return 0; - *p_arg = x; - return 1; -} - -/* XXX The following four are too similar. Should share more code. */ - -int -getilongarray(args, nargs, i, n, p_arg) - object *args; - int nargs, i; - int n; - long *p_arg; /* [n] */ -{ - object *v, *w; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - if (gettuplesize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = gettupleitem(v, i); - if (!is_intobject(w)) { - return err_badarg(); - } - p_arg[i] = getintvalue(w); - } - return 1; - } - else if (is_listobject(v)) { - if (getlistsize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = getlistitem(v, i); - if (!is_intobject(w)) { - return err_badarg(); - } - p_arg[i] = getintvalue(w); - } - return 1; - } - else { - return err_badarg(); - } -} - -int -getishortarray(args, nargs, i, n, p_arg) - object *args; - int nargs, i; - int n; - short *p_arg; /* [n] */ -{ - object *v, *w; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - if (gettuplesize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = gettupleitem(v, i); - if (!is_intobject(w)) { - return err_badarg(); - } - p_arg[i] = getintvalue(w); - } - return 1; - } - else if (is_listobject(v)) { - if (getlistsize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = getlistitem(v, i); - if (!is_intobject(w)) { - return err_badarg(); - } - p_arg[i] = getintvalue(w); - } - return 1; - } - else { - return err_badarg(); - } -} - -int -getidoublearray(args, nargs, i, n, p_arg) - object *args; - int nargs, i; - int n; - double *p_arg; /* [n] */ -{ - object *v, *w; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - if (gettuplesize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = gettupleitem(v, i); - if (!extractdouble(w, &p_arg[i])) - return 0; - } - return 1; - } - else if (is_listobject(v)) { - if (getlistsize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = getlistitem(v, i); - if (!extractdouble(w, &p_arg[i])) - return 0; - } - return 1; - } - else { - return err_badarg(); - } -} - -int -getifloatarray(args, nargs, i, n, p_arg) - object *args; - int nargs, i; - int n; - float *p_arg; /* [n] */ -{ - object *v, *w; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - if (gettuplesize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = gettupleitem(v, i); - if (!extractfloat(w, &p_arg[i])) - return 0; - } - return 1; - } - else if (is_listobject(v)) { - if (getlistsize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = getlistitem(v, i); - if (!extractfloat(w, &p_arg[i])) - return 0; - } - return 1; - } - else { - return err_badarg(); - } -} diff --git a/Modules/cgensupport.h b/Modules/cgensupport.h deleted file mode 100644 index bb7cbbc674..0000000000 --- a/Modules/cgensupport.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef Py_CGENSUPPORT_H -#define Py_CGENSUPPORT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Definitions used by cgen output */ - -typedef char *string; - -#define mknewlongobject(x) PyInt_FromLong(x) -#define mknewshortobject(x) PyInt_FromLong((long)x) -#define mknewfloatobject(x) PyFloat_FromDouble(x) -#define mknewcharobject(ch) Py_BuildValue("c", ch) - -extern int PyArg_GetObject Py_PROTO((PyObject *args, int nargs, int i, PyObject **p_a)); -extern int PyArg_GetLong Py_PROTO((PyObject *args, int nargs, int i, long *p_a)); -extern int PyArg_GetShort Py_PROTO((PyObject *args, int nargs, int i, short *p_a)); -extern int PyArg_GetFloat Py_PROTO((PyObject *args, int nargs, int i, float *p_a)); -extern int PyArg_GetString Py_PROTO((PyObject *args, int nargs, int i, string *p_a)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_CGENSUPPORT_H */ diff --git a/Modules/clmodule.c b/Modules/clmodule.c deleted file mode 100644 index 18fa92e040..0000000000 --- a/Modules/clmodule.c +++ /dev/null @@ -1,1282 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - - -/* Cl objects */ - -#define CLDEBUG - -#include <stdarg.h> -#include <cl.h> -#include "allobjects.h" -#include "modsupport.h" /* For getargs() etc. */ -#include "ceval.h" /* For call_object() */ - -typedef struct { - OB_HEAD - int ob_isCompressor; /* Compressor or Decompressor */ - CL_Handle ob_compressorHdl; - int *ob_paramtypes; - int ob_nparams; -} clobject; - -static object *ClError; /* exception cl.error */ - -static int error_handler_called = 0; - -/* - * We want to use the function prototypes that are available in the C - * compiler on the SGI. Because of that, we need to declare the first - * argument of the compressor and decompressor methods as "object *", - * even though they are really "clobject *". Therefore we cast the - * argument to the proper type using this macro. - */ -#define SELF ((clobject *) self) - -/******************************************************************** - Utility routines. -********************************************************************/ -static void -cl_ErrorHandler(CL_Handle handle, int code, const char *fmt, ...) -{ - va_list ap; - char errbuf[BUFSIZ]; /* hopefully big enough */ - char *p; - - if (err_occurred()) /* don't change existing error */ - return; - error_handler_called = 1; - va_start(ap, fmt); - vsprintf(errbuf, fmt, ap); - va_end(ap); - p = &errbuf[strlen(errbuf) - 1]; /* swat the line feed */ - if (*p == '\n') - *p = 0; - err_setstr(ClError, errbuf); -} - -/* - * This assumes that params are always in the range 0 to some maximum. - */ -static int -param_type_is_float(clobject *self, int param) -{ - int bufferlength; - int ret; - - if (self->ob_paramtypes == NULL) { - error_handler_called = 0; - bufferlength = clQueryParams(self->ob_compressorHdl, 0, 0); - if (error_handler_called) - return -1; - - self->ob_paramtypes = NEW(int, bufferlength); - if (self->ob_paramtypes == NULL) - return -1; - self->ob_nparams = bufferlength / 2; - - (void) clQueryParams(self->ob_compressorHdl, self->ob_paramtypes, bufferlength); - if (error_handler_called) { - DEL(self->ob_paramtypes); - self->ob_paramtypes = NULL; - return -1; - } - } - - if (param < 0 || param >= self->ob_nparams) - return -1; - - if (self->ob_paramtypes[param*2 + 1] == CL_FLOATING_ENUM_VALUE || - self->ob_paramtypes[param*2 + 1] == CL_FLOATING_RANGE_VALUE) - return 1; - else - return 0; -} - -/******************************************************************** - Single image compression/decompression. -********************************************************************/ -static object * -cl_CompressImage(object *self, object *args) -{ - int compressionScheme, width, height, originalFormat; - float compressionRatio; - int frameBufferSize, compressedBufferSize; - char *frameBuffer; - object *compressedBuffer; - - if (!getargs(args, "(iiiifs#)", &compressionScheme, &width, &height, - &originalFormat, &compressionRatio, &frameBuffer, - &frameBufferSize)) - return NULL; - - retry: - compressedBuffer = newsizedstringobject(NULL, frameBufferSize); - if (compressedBuffer == NULL) - return NULL; - - compressedBufferSize = frameBufferSize; - error_handler_called = 0; - if (clCompressImage(compressionScheme, width, height, originalFormat, - compressionRatio, (void *) frameBuffer, - &compressedBufferSize, - (void *) getstringvalue(compressedBuffer)) - == FAILURE) { - DECREF(compressedBuffer); - if (!error_handler_called) - err_setstr(ClError, "clCompressImage failed"); - return NULL; - } - - if (compressedBufferSize > frameBufferSize) { - frameBufferSize = compressedBufferSize; - DECREF(compressedBuffer); - goto retry; - } - - if (compressedBufferSize < frameBufferSize) - if (resizestring(&compressedBuffer, compressedBufferSize)) - return NULL; - - return compressedBuffer; -} - -static object * -cl_DecompressImage(object *self, object *args) -{ - int compressionScheme, width, height, originalFormat; - char *compressedBuffer; - int compressedBufferSize, frameBufferSize; - object *frameBuffer; - - if (!getargs(args, "(iiiis#)", &compressionScheme, &width, &height, - &originalFormat, &compressedBuffer, - &compressedBufferSize)) - return NULL; - - frameBufferSize = width * height * CL_BytesPerPixel(originalFormat); - - frameBuffer = newsizedstringobject(NULL, frameBufferSize); - if (frameBuffer == NULL) - return NULL; - - error_handler_called = 0; - if (clDecompressImage(compressionScheme, width, height, originalFormat, - compressedBufferSize, compressedBuffer, - (void *) getstringvalue(frameBuffer)) == FAILURE) { - DECREF(frameBuffer); - if (!error_handler_called) - err_setstr(ClError, "clDecompressImage failed"); - return NULL; - } - - return frameBuffer; -} - -/******************************************************************** - Sequential compression/decompression. -********************************************************************/ -#define CheckCompressor(self) if ((self)->ob_compressorHdl == NULL) { \ - err_setstr(RuntimeError, "(de)compressor not active"); \ - return NULL; \ - } - -static object * -doClose(clobject *self, object *args, int (*close_func)(CL_Handle)) -{ - CheckCompressor(self); - - if (!getnoarg(args)) - return NULL; - - error_handler_called = 0; - if ((*close_func)(self->ob_compressorHdl) == FAILURE) { - if (!error_handler_called) - err_setstr(ClError, "close failed"); - return NULL; - } - - self->ob_compressorHdl = NULL; - - if (self->ob_paramtypes) - DEL(self->ob_paramtypes); - self->ob_paramtypes = NULL; - - INCREF(None); - return None; -} - -static object * -clm_CloseCompressor(object *self, object *args) -{ - return doClose(SELF, args, clCloseCompressor); -} - -static object * -clm_CloseDecompressor(object *self, object *args) -{ - return doClose(SELF, args, clCloseDecompressor); -} - -static object * -clm_Compress(object *self, object *args) -{ - int numberOfFrames; - int frameBufferSize, compressedBufferSize, size; - char *frameBuffer; - object *data; - - CheckCompressor(SELF); - - if (!getargs(args, "(is#)", &numberOfFrames, &frameBuffer, &frameBufferSize)) - return NULL; - - error_handler_called = 0; - size = clGetParam(SELF->ob_compressorHdl, CL_COMPRESSED_BUFFER_SIZE); - compressedBufferSize = size; - if (error_handler_called) - return NULL; - - data = newsizedstringobject(NULL, size); - if (data == NULL) - return NULL; - - error_handler_called = 0; - if (clCompress(SELF->ob_compressorHdl, numberOfFrames, - (void *) frameBuffer, &compressedBufferSize, - (void *) getstringvalue(data)) == FAILURE) { - DECREF(data); - if (!error_handler_called) - err_setstr(ClError, "compress failed"); - return NULL; - } - - if (compressedBufferSize < size) - if (resizestring(&data, compressedBufferSize)) - return NULL; - - if (compressedBufferSize > size) { - /* we didn't get all "compressed" data */ - DECREF(data); - err_setstr(ClError, "compressed data is more than fitted"); - return NULL; - } - - return data; -} - -static object * -clm_Decompress(object *self, object *args) -{ - object *data; - int numberOfFrames; - char *compressedData; - int compressedDataSize, dataSize; - - CheckCompressor(SELF); - - if (!getargs(args, "(is#)", &numberOfFrames, &compressedData, - &compressedDataSize)) - return NULL; - - error_handler_called = 0; - dataSize = clGetParam(SELF->ob_compressorHdl, CL_FRAME_BUFFER_SIZE); - if (error_handler_called) - return NULL; - - data = newsizedstringobject(NULL, dataSize); - if (data == NULL) - return NULL; - - error_handler_called = 0; - if (clDecompress(SELF->ob_compressorHdl, numberOfFrames, - compressedDataSize, (void *) compressedData, - (void *) getstringvalue(data)) == FAILURE) { - DECREF(data); - if (!error_handler_called) - err_setstr(ClError, "decompress failed"); - return NULL; - } - - return data; -} - -static object * -doParams(clobject *self, object *args, int (*func)(CL_Handle, int *, int), - int modified) -{ - object *list, *v; - int *PVbuffer; - int length; - int i; - float number; - - CheckCompressor(self); - - if (!getargs(args, "O", &list)) - return NULL; - if (!is_listobject(list)) { - err_badarg(); - return NULL; - } - length = getlistsize(list); - PVbuffer = NEW(int, length); - if (PVbuffer == NULL) - return err_nomem(); - for (i = 0; i < length; i++) { - v = getlistitem(list, i); - if (is_floatobject(v)) { - number = getfloatvalue(v); - PVbuffer[i] = CL_TypeIsInt(number); - } else if (is_intobject(v)) { - PVbuffer[i] = getintvalue(v); - if ((i & 1) && - param_type_is_float(self, PVbuffer[i-1]) > 0) { - number = PVbuffer[i]; - PVbuffer[i] = CL_TypeIsInt(number); - } - } else { - DEL(PVbuffer); - err_badarg(); - return NULL; - } - } - - error_handler_called = 0; - (*func)(self->ob_compressorHdl, PVbuffer, length); - if (error_handler_called) { - DEL(PVbuffer); - return NULL; - } - - if (modified) { - for (i = 0; i < length; i++) { - if ((i & 1) && - param_type_is_float(self, PVbuffer[i-1]) > 0) { - number = CL_TypeIsFloat(PVbuffer[i]); - v = newfloatobject(number); - } else - v = newintobject(PVbuffer[i]); - setlistitem(list, i, v); - } - } - - DEL(PVbuffer); - - INCREF(None); - return None; -} - -static object * -clm_GetParams(object *self, object *args) -{ - return doParams(SELF, args, clGetParams, 1); -} - -static object * -clm_SetParams(object *self, object *args) -{ - return doParams(SELF, args, clSetParams, 0); -} - -static object * -do_get(clobject *self, object *args, int (*func)(CL_Handle, int)) -{ - int paramID, value; - float fvalue; - - CheckCompressor(self); - - if (!getargs(args, "i", &paramID)) - return NULL; - - error_handler_called = 0; - value = (*func)(self->ob_compressorHdl, paramID); - if (error_handler_called) - return NULL; - - if (param_type_is_float(self, paramID) > 0) { - fvalue = CL_TypeIsFloat(value); - return newfloatobject(fvalue); - } - - return newintobject(value); -} - -static object * -clm_GetParam(object *self, object *args) -{ - return do_get(SELF, args, clGetParam); -} - -static object * -clm_GetDefault(object *self, object *args) -{ - return do_get(SELF, args, clGetDefault); -} - -static object * -clm_SetParam(object *self, object *args) -{ - int paramID, value; - float fvalue; - - CheckCompressor(SELF); - - if (!getargs(args, "(ii)", &paramID, &value)) { - err_clear(); - if (!getargs(args, "(if)", &paramID, &fvalue)) { - err_clear(); - err_setstr(TypeError, "bad argument list (format '(ii)' or '(if)')"); - return NULL; - } - value = CL_TypeIsInt(fvalue); - } else { - if (param_type_is_float(SELF, paramID) > 0) { - fvalue = value; - value = CL_TypeIsInt(fvalue); - } - } - - error_handler_called = 0; - value = clSetParam(SELF->ob_compressorHdl, paramID, value); - if (error_handler_called) - return NULL; - - if (param_type_is_float(SELF, paramID) > 0) - return newfloatobject(CL_TypeIsFloat(value)); - else - return newintobject(value); -} - -static object * -clm_GetParamID(object *self, object *args) -{ - char *name; - int value; - - CheckCompressor(SELF); - - if (!getargs(args, "s", &name)) - return NULL; - - error_handler_called = 0; - value = clGetParamID(SELF->ob_compressorHdl, name); - if (value == FAILURE) { - if (!error_handler_called) - err_setstr(ClError, "getparamid failed"); - return NULL; - } - - return newintobject(value); -} - -static object * -clm_QueryParams(object *self, object *args) -{ - int bufferlength; - int *PVbuffer; - object *list; - int i; - - CheckCompressor(SELF); - - if (!getnoarg(args)) - return NULL; - - error_handler_called = 0; - bufferlength = clQueryParams(SELF->ob_compressorHdl, 0, 0); - if (error_handler_called) - return NULL; - - PVbuffer = NEW(int, bufferlength); - if (PVbuffer == NULL) - return err_nomem(); - - bufferlength = clQueryParams(SELF->ob_compressorHdl, PVbuffer, - bufferlength); - if (error_handler_called) { - DEL(PVbuffer); - return NULL; - } - - list = newlistobject(bufferlength); - if (list == NULL) { - DEL(PVbuffer); - return NULL; - } - - for (i = 0; i < bufferlength; i++) { - if (i & 1) - setlistitem(list, i, newintobject(PVbuffer[i])); - else if (PVbuffer[i] == 0) { - INCREF(None); - setlistitem(list, i, None); - } else - setlistitem(list, i, newstringobject((char *) PVbuffer[i])); - } - - DEL(PVbuffer); - - return list; -} - -static object * -clm_GetMinMax(object *self, object *args) -{ - int param, min, max; - float fmin, fmax; - - CheckCompressor(SELF); - - if (!getargs(args, "i", &param)) - return NULL; - - clGetMinMax(SELF->ob_compressorHdl, param, &min, &max); - - if (param_type_is_float(SELF, param) > 0) { - fmin = CL_TypeIsFloat(min); - fmax = CL_TypeIsFloat(max); - return mkvalue("(ff)", fmin, fmax); - } - - return mkvalue("(ii)", min, max); -} - -static object * -clm_GetName(object *self, object *args) -{ - int param; - char *name; - - CheckCompressor(SELF); - - if (!getargs(args, "i", &param)) - return NULL; - - error_handler_called = 0; - name = clGetName(SELF->ob_compressorHdl, param); - if (name == NULL || error_handler_called) { - if (!error_handler_called) - err_setstr(ClError, "getname failed"); - return NULL; - } - - return newstringobject(name); -} - -static object * -clm_QuerySchemeFromHandle(object *self, object *args) -{ - CheckCompressor(SELF); - - if (!getnoarg(args)) - return NULL; - - return newintobject(clQuerySchemeFromHandle(SELF->ob_compressorHdl)); -} - -static object * -clm_ReadHeader(object *self, object *args) -{ - char *header; - int headerSize; - - CheckCompressor(SELF); - - if (!getargs(args, "s#", &header, &headerSize)) - return NULL; - - return newintobject(clReadHeader(SELF->ob_compressorHdl, - headerSize, header)); -} - -static struct methodlist compressor_methods[] = { - {"close", clm_CloseCompressor}, /* alias */ - {"CloseCompressor", clm_CloseCompressor}, - {"Compress", clm_Compress}, - {"GetDefault", clm_GetDefault}, - {"GetMinMax", clm_GetMinMax}, - {"GetName", clm_GetName}, - {"GetParam", clm_GetParam}, - {"GetParamID", clm_GetParamID}, - {"GetParams", clm_GetParams}, - {"QueryParams", clm_QueryParams}, - {"QuerySchemeFromHandle",clm_QuerySchemeFromHandle}, - {"SetParam", clm_SetParam}, - {"SetParams", clm_SetParams}, - {NULL, NULL} /* sentinel */ -}; - -static struct methodlist decompressor_methods[] = { - {"close", clm_CloseDecompressor}, /* alias */ - {"CloseDecompressor", clm_CloseDecompressor}, - {"Decompress", clm_Decompress}, - {"GetDefault", clm_GetDefault}, - {"GetMinMax", clm_GetMinMax}, - {"GetName", clm_GetName}, - {"GetParam", clm_GetParam}, - {"GetParamID", clm_GetParamID}, - {"GetParams", clm_GetParams}, - {"ReadHeader", clm_ReadHeader}, - {"QueryParams", clm_QueryParams}, - {"QuerySchemeFromHandle",clm_QuerySchemeFromHandle}, - {"SetParam", clm_SetParam}, - {"SetParams", clm_SetParams}, - {NULL, NULL} /* sentinel */ -}; - -static void -cl_dealloc(object *self) -{ - if (SELF->ob_compressorHdl) { - if (SELF->ob_isCompressor) - clCloseCompressor(SELF->ob_compressorHdl); - else - clCloseDecompressor(SELF->ob_compressorHdl); - } - DEL(self); -} - -static object * -cl_getattr(object *self, char *name) -{ - if (SELF->ob_isCompressor) - return findmethod(compressor_methods, self, name); - else - return findmethod(decompressor_methods, self, name); -} - -static typeobject Cltype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "cl", /*tp_name*/ - sizeof(clobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)cl_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)cl_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ -}; - -static object * -doOpen(object *self, object *args, int (*open_func)(int, CL_Handle *), - int iscompressor) -{ - int scheme; - clobject *new; - - if (!getargs(args, "i", &scheme)) - return NULL; - - new = NEWOBJ(clobject, &Cltype); - if (new == NULL) - return NULL; - - new->ob_compressorHdl = NULL; - new->ob_isCompressor = iscompressor; - new->ob_paramtypes = NULL; - - error_handler_called = 0; - if ((*open_func)(scheme, &new->ob_compressorHdl) == FAILURE) { - DECREF(new); - if (!error_handler_called) - err_setstr(ClError, "Open(De)Compressor failed"); - return NULL; - } - return (object *)new; -} - -static object * -cl_OpenCompressor(object *self, object *args) -{ - return doOpen(self, args, clOpenCompressor, 1); -} - -static object * -cl_OpenDecompressor(object *self, object *args) -{ - return doOpen(self, args, clOpenDecompressor, 0); -} - -static object * -cl_QueryScheme(object *self, object *args) -{ - char *header; - int headerlen; - int scheme; - - if (!getargs(args, "s#", &header, &headerlen)) - return NULL; - - scheme = clQueryScheme(header); - if (scheme < 0) { - err_setstr(ClError, "unknown compression scheme"); - return NULL; - } - - return newintobject(scheme); -} - -static object * -cl_QueryMaxHeaderSize(object *self, object *args) -{ - int scheme; - - if (!getargs(args, "i", &scheme)) - return NULL; - - return newintobject(clQueryMaxHeaderSize(scheme)); -} - -static object * -cl_QueryAlgorithms(object *self, object *args) -{ - int algorithmMediaType; - int bufferlength; - int *PVbuffer; - object *list; - int i; - - if (!getargs(args, "i", &algorithmMediaType)) - return NULL; - - error_handler_called = 0; - bufferlength = clQueryAlgorithms(algorithmMediaType, 0, 0); - if (error_handler_called) - return NULL; - - PVbuffer = NEW(int, bufferlength); - if (PVbuffer == NULL) - return err_nomem(); - - bufferlength = clQueryAlgorithms(algorithmMediaType, PVbuffer, - bufferlength); - if (error_handler_called) { - DEL(PVbuffer); - return NULL; - } - - list = newlistobject(bufferlength); - if (list == NULL) { - DEL(PVbuffer); - return NULL; - } - - for (i = 0; i < bufferlength; i++) { - if (i & 1) - setlistitem(list, i, newintobject(PVbuffer[i])); - else if (PVbuffer[i] == 0) { - INCREF(None); - setlistitem(list, i, None); - } else - setlistitem(list, i, newstringobject((char *) PVbuffer[i])); - } - - DEL(PVbuffer); - - return list; -} - -static object * -cl_QuerySchemeFromName(object *self, object *args) -{ - int algorithmMediaType; - char *name; - int scheme; - - if (!getargs(args, "(is)", &algorithmMediaType, &name)) - return NULL; - - error_handler_called = 0; - scheme = clQuerySchemeFromName(algorithmMediaType, name); - if (error_handler_called) { - err_setstr(ClError, "unknown compression scheme"); - return NULL; - } - - return newintobject(scheme); -} - -static object * -cl_GetAlgorithmName(object *self, object *args) -{ - int scheme; - char *name; - - if (!getargs(args, "i", &scheme)) - return NULL; - - name = clGetAlgorithmName(scheme); - if (name == 0) { - err_setstr(ClError, "unknown compression scheme"); - return NULL; - } - - return newstringobject(name); -} - -static object * -do_set(object *self, object *args, int (*func)(int, int, int)) -{ - int scheme, paramID, value; - float fvalue; - int is_float = 0; - - if (!getargs(args, "(iii)", &scheme, &paramID, &value)) { - err_clear(); - if (!getargs(args, "(iif)", &scheme, &paramID, &fvalue)) { - err_clear(); - err_setstr(TypeError, "bad argument list (format '(iii)' or '(iif)')"); - return NULL; - } - value = CL_TypeIsInt(fvalue); - is_float = 1; - } else { - /* check some parameters which we know to be floats */ - switch (scheme) { - case CL_COMPRESSION_RATIO: - case CL_SPEED: - fvalue = value; - value = CL_TypeIsInt(fvalue); - is_float = 1; - break; - } - } - - error_handler_called = 0; - value = (*func)(scheme, paramID, value); - if (error_handler_called) - return NULL; - - if (is_float) - return newfloatobject(CL_TypeIsFloat(value)); - else - return newintobject(value); -} - -static object * -cl_SetDefault(object *self, object *args) -{ - return do_set(self, args, clSetDefault); -} - -static object * -cl_SetMin(object *self, object *args) -{ - return do_set(self, args, clSetMin); -} - -static object * -cl_SetMax(object *self, object *args) -{ - return do_set(self, args, clSetMax); -} - -#define func(name, type) \ - static object *cl_##name(object *self, object *args) \ - { \ - int x; \ - if (!getargs(args, "i", &x)) return NULL; \ - return new##type##object(CL_##name(x)); \ - } - -#define func2(name, type) \ - static object *cl_##name(object *self, object *args) \ - { \ - int a1, a2; \ - if (!getargs(args, "(ii)", &a1, &a2)) return NULL; \ - return new##type##object(CL_##name(a1, a2)); \ - } - -func(BytesPerSample,int) -func(BytesPerPixel,int) -func(AudioFormatName,string) -func(VideoFormatName,string) -func(AlgorithmNumber,int) -func(AlgorithmType,int) -func2(Algorithm,int) -func(ParamNumber,int) -func(ParamType,int) -func2(ParamID,int) - -#ifdef CLDEBUG -static object * -cvt_type(object *self, object *args) -{ - int number; - float fnumber; - - if (getargs(args, "i", &number)) - return newfloatobject(CL_TypeIsFloat(number)); - else { - err_clear(); - if (getargs(args, "f", &fnumber)) - return newintobject(CL_TypeIsInt(fnumber)); - return NULL; - } -} -#endif - -static struct methodlist cl_methods[] = { - {"CompressImage", cl_CompressImage}, - {"DecompressImage", cl_DecompressImage}, - {"GetAlgorithmName", cl_GetAlgorithmName}, - {"OpenCompressor", cl_OpenCompressor}, - {"OpenDecompressor", cl_OpenDecompressor}, - {"QueryAlgorithms", cl_QueryAlgorithms}, - {"QueryMaxHeaderSize", cl_QueryMaxHeaderSize}, - {"QueryScheme", cl_QueryScheme}, - {"QuerySchemeFromName", cl_QuerySchemeFromName}, - {"SetDefault", cl_SetDefault}, - {"SetMax", cl_SetMax}, - {"SetMin", cl_SetMin}, - {"BytesPerSample", cl_BytesPerSample}, - {"BytesPerPixel", cl_BytesPerPixel}, - {"AudioFormatName", cl_AudioFormatName}, - {"VideoFormatName", cl_VideoFormatName}, - {"AlgorithmNumber", cl_AlgorithmNumber}, - {"AlgorithmType", cl_AlgorithmType}, - {"Algorithm", cl_Algorithm}, - {"ParamNumber", cl_ParamNumber}, - {"ParamType", cl_ParamType}, - {"ParamID", cl_ParamID}, -#ifdef CLDEBUG - {"cvt_type", cvt_type}, -#endif - {NULL, NULL} /* Sentinel */ -}; - -#ifdef CL_JPEG_SOFTWARE -#define IRIX_5_3_LIBRARY -#endif - -void -initcl() -{ - object *m, *d; - - m = initmodule("cl", cl_methods); - d = getmoduledict(m); - - ClError = newstringobject("cl.error"); - (void) dictinsert(d, "error", ClError); - - (void) dictinsert(d, "MAX_NUMBER_OF_ORIGINAL_FORMATS", - newintobject(CL_MAX_NUMBER_OF_ORIGINAL_FORMATS)); - (void) dictinsert(d, "MONO", newintobject(CL_MONO)); - (void) dictinsert(d, "STEREO_INTERLEAVED", - newintobject(CL_STEREO_INTERLEAVED)); - (void) dictinsert(d, "RGB", newintobject(CL_RGB)); - (void) dictinsert(d, "RGBX", newintobject(CL_RGBX)); - (void) dictinsert(d, "RGBA", newintobject(CL_RGBA)); - (void) dictinsert(d, "RGB332", newintobject(CL_RGB332)); - (void) dictinsert(d, "GRAYSCALE", newintobject(CL_GRAYSCALE)); - (void) dictinsert(d, "Y", newintobject(CL_Y)); - (void) dictinsert(d, "YUV", newintobject(CL_YUV)); - (void) dictinsert(d, "YCbCr", newintobject(CL_YCbCr)); - (void) dictinsert(d, "YUV422", newintobject(CL_YUV422)); - (void) dictinsert(d, "YCbCr422", newintobject(CL_YCbCr422)); - (void) dictinsert(d, "YUV422HC", newintobject(CL_YUV422HC)); - (void) dictinsert(d, "YCbCr422HC", newintobject(CL_YCbCr422HC)); - (void) dictinsert(d, "YUV422DC", newintobject(CL_YUV422DC)); - (void) dictinsert(d, "YCbCr422DC", newintobject(CL_YCbCr422DC)); - (void) dictinsert(d, "RGB8", newintobject(CL_RGB8)); - (void) dictinsert(d, "BEST_FIT", newintobject(CL_BEST_FIT)); - (void) dictinsert(d, "MAX_NUMBER_OF_AUDIO_ALGORITHMS", - newintobject(CL_MAX_NUMBER_OF_AUDIO_ALGORITHMS)); - (void) dictinsert(d, "MAX_NUMBER_OF_VIDEO_ALGORITHMS", - newintobject(CL_MAX_NUMBER_OF_VIDEO_ALGORITHMS)); - (void) dictinsert(d, "AUDIO", newintobject(CL_AUDIO)); - (void) dictinsert(d, "VIDEO", newintobject(CL_VIDEO)); - (void) dictinsert(d, "UNKNOWN_SCHEME", - newintobject(CL_UNKNOWN_SCHEME)); - (void) dictinsert(d, "UNCOMPRESSED_AUDIO", - newintobject(CL_UNCOMPRESSED_AUDIO)); - (void) dictinsert(d, "G711_ULAW", newintobject(CL_G711_ULAW)); - (void) dictinsert(d, "ULAW", newintobject(CL_ULAW)); - (void) dictinsert(d, "G711_ALAW", newintobject(CL_G711_ALAW)); - (void) dictinsert(d, "ALAW", newintobject(CL_ALAW)); - (void) dictinsert(d, "AWARE_MPEG_AUDIO", - newintobject(CL_AWARE_MPEG_AUDIO)); - (void) dictinsert(d, "AWARE_MULTIRATE", - newintobject(CL_AWARE_MULTIRATE)); - (void) dictinsert(d, "UNCOMPRESSED", newintobject(CL_UNCOMPRESSED)); - (void) dictinsert(d, "UNCOMPRESSED_VIDEO", - newintobject(CL_UNCOMPRESSED_VIDEO)); - (void) dictinsert(d, "RLE", newintobject(CL_RLE)); - (void) dictinsert(d, "JPEG", newintobject(CL_JPEG)); -#ifdef IRIX_5_3_LIBRARY - (void) dictinsert(d, "JPEG_SOFTWARE", newintobject(CL_JPEG_SOFTWARE)); -#endif - (void) dictinsert(d, "MPEG_VIDEO", newintobject(CL_MPEG_VIDEO)); - (void) dictinsert(d, "MVC1", newintobject(CL_MVC1)); - (void) dictinsert(d, "RTR", newintobject(CL_RTR)); - (void) dictinsert(d, "RTR1", newintobject(CL_RTR1)); - (void) dictinsert(d, "HDCC", newintobject(CL_HDCC)); - (void) dictinsert(d, "MVC2", newintobject(CL_MVC2)); - (void) dictinsert(d, "RLE24", newintobject(CL_RLE24)); - (void) dictinsert(d, "MAX_NUMBER_OF_PARAMS", - newintobject(CL_MAX_NUMBER_OF_PARAMS)); - (void) dictinsert(d, "IMAGE_WIDTH", newintobject(CL_IMAGE_WIDTH)); - (void) dictinsert(d, "IMAGE_HEIGHT", newintobject(CL_IMAGE_HEIGHT)); - (void) dictinsert(d, "ORIGINAL_FORMAT", - newintobject(CL_ORIGINAL_FORMAT)); - (void) dictinsert(d, "INTERNAL_FORMAT", - newintobject(CL_INTERNAL_FORMAT)); - (void) dictinsert(d, "COMPONENTS", newintobject(CL_COMPONENTS)); - (void) dictinsert(d, "BITS_PER_COMPONENT", - newintobject(CL_BITS_PER_COMPONENT)); - (void) dictinsert(d, "FRAME_RATE", newintobject(CL_FRAME_RATE)); - (void) dictinsert(d, "COMPRESSION_RATIO", - newintobject(CL_COMPRESSION_RATIO)); - (void) dictinsert(d, "EXACT_COMPRESSION_RATIO", - newintobject(CL_EXACT_COMPRESSION_RATIO)); - (void) dictinsert(d, "FRAME_BUFFER_SIZE", - newintobject(CL_FRAME_BUFFER_SIZE)); - (void) dictinsert(d, "COMPRESSED_BUFFER_SIZE", - newintobject(CL_COMPRESSED_BUFFER_SIZE)); - (void) dictinsert(d, "BLOCK_SIZE", newintobject(CL_BLOCK_SIZE)); - (void) dictinsert(d, "PREROLL", newintobject(CL_PREROLL)); - (void) dictinsert(d, "FRAME_TYPE", newintobject(CL_FRAME_TYPE)); - (void) dictinsert(d, "ALGORITHM_ID", newintobject(CL_ALGORITHM_ID)); - (void) dictinsert(d, "ALGORITHM_VERSION", - newintobject(CL_ALGORITHM_VERSION)); - (void) dictinsert(d, "ORIENTATION", newintobject(CL_ORIENTATION)); - (void) dictinsert(d, "NUMBER_OF_FRAMES", - newintobject(CL_NUMBER_OF_FRAMES)); - (void) dictinsert(d, "SPEED", newintobject(CL_SPEED)); - (void) dictinsert(d, "LAST_FRAME_INDEX", - newintobject(CL_LAST_FRAME_INDEX)); -#ifdef IRIX_5_3_LIBRARY - (void) dictinsert(d, "ENABLE_IMAGEINFO", - newintobject(CL_ENABLE_IMAGEINFO)); - (void) dictinsert(d, "INTERNAL_IMAGE_WIDTH", - newintobject(CL_INTERNAL_IMAGE_WIDTH)); - (void) dictinsert(d, "INTERNAL_IMAGE_HEIGHT", - newintobject(CL_INTERNAL_IMAGE_HEIGHT)); -#endif - (void) dictinsert(d, "NUMBER_OF_PARAMS", - newintobject(CL_NUMBER_OF_PARAMS)); -#ifdef IRIX_5_3_LIBRARY - (void) dictinsert(d, "MVC2_LUMA_THRESHOLD", - newintobject(CL_MVC2_LUMA_THRESHOLD)); - (void) dictinsert(d, "MVC2_CHROMA_THRESHOLD", - newintobject(CL_MVC2_CHROMA_THRESHOLD)); - (void) dictinsert(d, "MVC2_EDGE_THRESHOLD", - newintobject(CL_MVC2_EDGE_THRESHOLD)); - (void) dictinsert(d, "MVC2_BLENDING", newintobject(CL_MVC2_BLENDING)); - (void) dictinsert(d, "MVC2_BLENDING_OFF", - newintobject(CL_MVC2_BLENDING_OFF)); - (void) dictinsert(d, "MVC2_BLENDING_ON", - newintobject(CL_MVC2_BLENDING_ON)); - (void) dictinsert(d, "JPEG_QUALITY_FACTOR", - newintobject(CL_JPEG_QUALITY_FACTOR)); - (void) dictinsert(d, "JPEG_STREAM_HEADERS", - newintobject(CL_JPEG_STREAM_HEADERS)); - (void) dictinsert(d, "JPEG_QUANTIZATION_TABLES", - newintobject(CL_JPEG_QUANTIZATION_TABLES)); - (void) dictinsert(d, "JPEG_NUM_PARAMS", - newintobject(CL_JPEG_NUM_PARAMS)); - (void) dictinsert(d, "RTR_QUALITY_LEVEL", - newintobject(CL_RTR_QUALITY_LEVEL)); - (void) dictinsert(d, "HDCC_TILE_THRESHOLD", - newintobject(CL_HDCC_TILE_THRESHOLD)); - (void) dictinsert(d, "HDCC_SAMPLES_PER_TILE", - newintobject(CL_HDCC_SAMPLES_PER_TILE)); -#endif - (void) dictinsert(d, "END_OF_SEQUENCE", - newintobject(CL_END_OF_SEQUENCE)); - (void) dictinsert(d, "CHANNEL_POLICY", - newintobject(CL_CHANNEL_POLICY)); - (void) dictinsert(d, "NOISE_MARGIN", newintobject(CL_NOISE_MARGIN)); - (void) dictinsert(d, "BITRATE_POLICY", - newintobject(CL_BITRATE_POLICY)); - (void) dictinsert(d, "BITRATE_TARGET", - newintobject(CL_BITRATE_TARGET)); - (void) dictinsert(d, "LAYER", newintobject(CL_LAYER)); - (void) dictinsert(d, "ENUM_VALUE", newintobject(CL_ENUM_VALUE)); - (void) dictinsert(d, "RANGE_VALUE", newintobject(CL_RANGE_VALUE)); - (void) dictinsert(d, "FLOATING_ENUM_VALUE", - newintobject(CL_FLOATING_ENUM_VALUE)); - (void) dictinsert(d, "FLOATING_RANGE_VALUE", - newintobject(CL_FLOATING_RANGE_VALUE)); - (void) dictinsert(d, "DECOMPRESSOR", newintobject(CL_DECOMPRESSOR)); - (void) dictinsert(d, "COMPRESSOR", newintobject(CL_COMPRESSOR)); - (void) dictinsert(d, "CODEC", newintobject(CL_CODEC)); - (void) dictinsert(d, "NONE", newintobject(CL_NONE)); -#ifdef IRIX_5_3_LIBRARY - (void) dictinsert(d, "BUF_FRAME", newintobject(CL_BUF_FRAME)); - (void) dictinsert(d, "BUF_DATA", newintobject(CL_BUF_DATA)); -#endif -#ifdef CL_FRAME - (void) dictinsert(d, "FRAME", newintobject(CL_FRAME)); - (void) dictinsert(d, "DATA", newintobject(CL_DATA)); -#endif - (void) dictinsert(d, "NONE", newintobject(CL_NONE)); - (void) dictinsert(d, "KEYFRAME", newintobject(CL_KEYFRAME)); - (void) dictinsert(d, "INTRA", newintobject(CL_INTRA)); - (void) dictinsert(d, "PREDICTED", newintobject(CL_PREDICTED)); - (void) dictinsert(d, "BIDIRECTIONAL", newintobject(CL_BIDIRECTIONAL)); - (void) dictinsert(d, "TOP_DOWN", newintobject(CL_TOP_DOWN)); - (void) dictinsert(d, "BOTTOM_UP", newintobject(CL_BOTTOM_UP)); -#ifdef IRIX_5_3_LIBRARY - (void) dictinsert(d, "CONTINUOUS_BLOCK", - newintobject(CL_CONTINUOUS_BLOCK)); - (void) dictinsert(d, "CONTINUOUS_NONBLOCK", - newintobject(CL_CONTINUOUS_NONBLOCK)); - (void) dictinsert(d, "EXTERNAL_DEVICE", - newintobject((long)CL_EXTERNAL_DEVICE)); -#endif - (void) dictinsert(d, "AWCMP_STEREO", newintobject(AWCMP_STEREO)); - (void) dictinsert(d, "AWCMP_JOINT_STEREO", - newintobject(AWCMP_JOINT_STEREO)); - (void) dictinsert(d, "AWCMP_INDEPENDENT", - newintobject(AWCMP_INDEPENDENT)); - (void) dictinsert(d, "AWCMP_FIXED_RATE", - newintobject(AWCMP_FIXED_RATE)); - (void) dictinsert(d, "AWCMP_CONST_QUAL", - newintobject(AWCMP_CONST_QUAL)); - (void) dictinsert(d, "AWCMP_LOSSLESS", newintobject(AWCMP_LOSSLESS)); - (void) dictinsert(d, "AWCMP_MPEG_LAYER_I", - newintobject(AWCMP_MPEG_LAYER_I)); - (void) dictinsert(d, "AWCMP_MPEG_LAYER_II", - newintobject(AWCMP_MPEG_LAYER_II)); - (void) dictinsert(d, "HEADER_START_CODE", - newintobject(CL_HEADER_START_CODE)); - (void) dictinsert(d, "BAD_NO_BUFFERSPACE", - newintobject(CL_BAD_NO_BUFFERSPACE)); - (void) dictinsert(d, "BAD_PVBUFFER", newintobject(CL_BAD_PVBUFFER)); - (void) dictinsert(d, "BAD_BUFFERLENGTH_NEG", - newintobject(CL_BAD_BUFFERLENGTH_NEG)); - (void) dictinsert(d, "BAD_BUFFERLENGTH_ODD", - newintobject(CL_BAD_BUFFERLENGTH_ODD)); - (void) dictinsert(d, "BAD_PARAM", newintobject(CL_BAD_PARAM)); - (void) dictinsert(d, "BAD_COMPRESSION_SCHEME", - newintobject(CL_BAD_COMPRESSION_SCHEME)); - (void) dictinsert(d, "BAD_COMPRESSOR_HANDLE", - newintobject(CL_BAD_COMPRESSOR_HANDLE)); - (void) dictinsert(d, "BAD_COMPRESSOR_HANDLE_POINTER", - newintobject(CL_BAD_COMPRESSOR_HANDLE_POINTER)); - (void) dictinsert(d, "BAD_BUFFER_HANDLE", - newintobject(CL_BAD_BUFFER_HANDLE)); - (void) dictinsert(d, "BAD_BUFFER_QUERY_SIZE", - newintobject(CL_BAD_BUFFER_QUERY_SIZE)); - (void) dictinsert(d, "JPEG_ERROR", newintobject(CL_JPEG_ERROR)); - (void) dictinsert(d, "BAD_FRAME_SIZE", - newintobject(CL_BAD_FRAME_SIZE)); - (void) dictinsert(d, "PARAM_OUT_OF_RANGE", - newintobject(CL_PARAM_OUT_OF_RANGE)); - (void) dictinsert(d, "ADDED_ALGORITHM_ERROR", - newintobject(CL_ADDED_ALGORITHM_ERROR)); - (void) dictinsert(d, "BAD_ALGORITHM_TYPE", - newintobject(CL_BAD_ALGORITHM_TYPE)); - (void) dictinsert(d, "BAD_ALGORITHM_NAME", - newintobject(CL_BAD_ALGORITHM_NAME)); - (void) dictinsert(d, "BAD_BUFFERING", newintobject(CL_BAD_BUFFERING)); - (void) dictinsert(d, "BUFFER_NOT_CREATED", - newintobject(CL_BUFFER_NOT_CREATED)); - (void) dictinsert(d, "BAD_BUFFER_EXISTS", - newintobject(CL_BAD_BUFFER_EXISTS)); - (void) dictinsert(d, "BAD_INTERNAL_FORMAT", - newintobject(CL_BAD_INTERNAL_FORMAT)); - (void) dictinsert(d, "BAD_BUFFER_POINTER", - newintobject(CL_BAD_BUFFER_POINTER)); - (void) dictinsert(d, "FRAME_BUFFER_SIZE_ZERO", - newintobject(CL_FRAME_BUFFER_SIZE_ZERO)); - (void) dictinsert(d, "BAD_STREAM_HEADER", - newintobject(CL_BAD_STREAM_HEADER)); - (void) dictinsert(d, "BAD_LICENSE", newintobject(CL_BAD_LICENSE)); - (void) dictinsert(d, "AWARE_ERROR", newintobject(CL_AWARE_ERROR)); - (void) dictinsert(d, "BAD_BUFFER_SIZE_POINTER", - newintobject(CL_BAD_BUFFER_SIZE_POINTER)); - (void) dictinsert(d, "BAD_BUFFER_SIZE", - newintobject(CL_BAD_BUFFER_SIZE)); - (void) dictinsert(d, "BAD_BUFFER_TYPE", - newintobject(CL_BAD_BUFFER_TYPE)); - (void) dictinsert(d, "BAD_HEADER_SIZE", - newintobject(CL_BAD_HEADER_SIZE)); - (void) dictinsert(d, "BAD_FUNCTION_POINTER", - newintobject(CL_BAD_FUNCTION_POINTER)); - (void) dictinsert(d, "BAD_SCHEME_POINTER", - newintobject(CL_BAD_SCHEME_POINTER)); - (void) dictinsert(d, "BAD_STRING_POINTER", - newintobject(CL_BAD_STRING_POINTER)); - (void) dictinsert(d, "BAD_MIN_GT_MAX", - newintobject(CL_BAD_MIN_GT_MAX)); - (void) dictinsert(d, "BAD_INITIAL_VALUE", - newintobject(CL_BAD_INITIAL_VALUE)); - (void) dictinsert(d, "BAD_PARAM_ID_POINTER", - newintobject(CL_BAD_PARAM_ID_POINTER)); - (void) dictinsert(d, "BAD_PARAM_TYPE", - newintobject(CL_BAD_PARAM_TYPE)); - (void) dictinsert(d, "BAD_TEXT_STRING_PTR", - newintobject(CL_BAD_TEXT_STRING_PTR)); - (void) dictinsert(d, "BAD_FUNCTIONALITY", - newintobject(CL_BAD_FUNCTIONALITY)); - (void) dictinsert(d, "BAD_NUMBER_OF_BLOCKS", - newintobject(CL_BAD_NUMBER_OF_BLOCKS)); - (void) dictinsert(d, "BAD_BLOCK_SIZE", - newintobject(CL_BAD_BLOCK_SIZE)); - (void) dictinsert(d, "BAD_POINTER", newintobject(CL_BAD_POINTER)); - (void) dictinsert(d, "BAD_BOARD", newintobject(CL_BAD_BOARD)); - (void) dictinsert(d, "MVC2_ERROR", newintobject(CL_MVC2_ERROR)); -#ifdef IRIX_5_3_LIBRARY - (void) dictinsert(d, "NEXT_NOT_AVAILABLE", - newintobject(CL_NEXT_NOT_AVAILABLE)); - (void) dictinsert(d, "SCHEME_BUSY", newintobject(CL_SCHEME_BUSY)); - (void) dictinsert(d, "SCHEME_NOT_AVAILABLE", - newintobject(CL_SCHEME_NOT_AVAILABLE)); -#endif -#ifdef CL_LUMA_THRESHOLD - /* backward compatibility */ - (void) dictinsert(d, "LUMA_THRESHOLD", - newintobject(CL_LUMA_THRESHOLD)); - (void) dictinsert(d, "CHROMA_THRESHOLD", - newintobject(CL_CHROMA_THRESHOLD)); - (void) dictinsert(d, "EDGE_THRESHOLD", - newintobject(CL_EDGE_THRESHOLD)); - (void) dictinsert(d, "BLENDING", newintobject(CL_BLENDING)); - (void) dictinsert(d, "QUALITY_FACTOR", - newintobject(CL_QUALITY_FACTOR)); - (void) dictinsert(d, "STREAM_HEADERS", - newintobject(CL_STREAM_HEADERS)); - (void) dictinsert(d, "QUALITY_LEVEL", newintobject(CL_QUALITY_LEVEL)); - (void) dictinsert(d, "TILE_THRESHOLD", - newintobject(CL_TILE_THRESHOLD)); - (void) dictinsert(d, "SAMPLES_PER_TILE", - newintobject(CL_SAMPLES_PER_TILE)); -#endif - - if (err_occurred()) - fatal("can't initialize module cl"); - - (void) clSetErrorHandler(cl_ErrorHandler); -} diff --git a/Modules/cmathmodule.c b/Modules/cmathmodule.c deleted file mode 100644 index 9c28623afc..0000000000 --- a/Modules/cmathmodule.c +++ /dev/null @@ -1,314 +0,0 @@ -/* Complex math module */ - -/* much code borrowed from mathmodule.c */ - -#include "allobjects.h" -#include "complexobject.h" - -#include <errno.h> - -#include "mymath.h" - -#ifdef i860 -/* Cray APP has bogus definition of HUGE_VAL in <math.h> */ -#undef HUGE_VAL -#endif - -#ifdef HUGE_VAL -#define CHECK(x) if (errno != 0) ; \ - else if (-HUGE_VAL <= (x) && (x) <= HUGE_VAL) ; \ - else errno = ERANGE -#else -#define CHECK(x) /* Don't know how to check */ -#endif - -#ifndef M_PI -#define M_PI (3.141592653589793239) -#endif - -/* First, the C functions that do the real work */ - -/* constants */ -static complex c_1 = {1., 0.}; -static complex c_half = {0.5, 0.}; -static complex c_i = {0., 1.}; -static complex c_i2 = {0., 0.5}; -static complex c_mi = {0., -1.}; -static complex c_pi2 = {M_PI/2., 0.}; - -/* forward declarations */ -staticforward complex c_log(); -staticforward complex c_prodi(); -staticforward complex c_sqrt(); - - -static complex c_acos(x) - complex x; -{ - return c_neg(c_prodi(c_log(c_sum(x,c_prod(c_i, - c_sqrt(c_diff(c_1,c_prod(x,x)))))))); -} - -static complex c_acosh(x) - complex x; -{ - return c_log(c_sum(x,c_prod(c_i, - c_sqrt(c_diff(c_1,c_prod(x,x)))))); -} - -static complex c_asin(x) - complex x; -{ - return c_neg(c_prodi(c_log(c_sum(c_prod(c_i,x), - c_sqrt(c_diff(c_1,c_prod(x,x))))))); -} - -static complex c_asinh(x) - complex x; -{ - return c_neg(c_log(c_diff(c_sqrt(c_sum(c_1,c_prod(x,x))),x))); -} - -static complex c_atan(x) - complex x; -{ - return c_prod(c_i2,c_log(c_quot(c_sum(c_i,x),c_diff(c_i,x)))); -} - -static complex c_atanh(x) - complex x; -{ - return c_prod(c_half,c_log(c_quot(c_sum(c_1,x),c_diff(c_1,x)))); -} - -static complex c_cos(x) - complex x; -{ - complex r; - r.real = cos(x.real)*cosh(x.imag); - r.imag = -sin(x.real)*sinh(x.imag); - return r; -} - -static complex c_cosh(x) - complex x; -{ - complex r; - r.real = cos(x.imag)*cosh(x.real); - r.imag = sin(x.imag)*sinh(x.real); - return r; -} - -static complex c_exp(x) - complex x; -{ - complex r; - double l = exp(x.real); - r.real = l*cos(x.imag); - r.imag = l*sin(x.imag); - return r; -} - -static complex c_log(x) - complex x; -{ - complex r; - double l = hypot(x.real,x.imag); - r.imag = atan2(x.imag, x.real); - r.real = log(l); - return r; -} - -static complex c_log10(x) - complex x; -{ - complex r; - double l = hypot(x.real,x.imag); - r.imag = atan2(x.imag, x.real)/log(10.); - r.real = log10(l); - return r; -} - -static complex c_prodi(x) - complex x; -{ - complex r; - r.real = -x.imag; - r.imag = x.real; - return r; -} - -static complex c_sin(x) - complex x; -{ - complex r; - r.real = sin(x.real)*cosh(x.imag); - r.imag = cos(x.real)*sinh(x.imag); - return r; -} - -static complex c_sinh(x) - complex x; -{ - complex r; - r.real = cos(x.imag)*sinh(x.real); - r.imag = sin(x.imag)*cosh(x.real); - return r; -} - -static complex c_sqrt(x) - complex x; -{ - complex r; - double s,d; - if (x.real == 0. && x.imag == 0.) - r = x; - else { - s = sqrt(0.5*(fabs(x.real) + hypot(x.real,x.imag))); - d = 0.5*x.imag/s; - if (x.real > 0.) { - r.real = s; - r.imag = d; - } - else if (x.imag >= 0.) { - r.real = d; - r.imag = s; - } - else { - r.real = -d; - r.imag = -s; - } - } - return r; -} - -static complex c_tan(x) - complex x; -{ - complex r; - double sr,cr,shi,chi; - double rs,is,rc,ic; - double d; - sr = sin(x.real); - cr = cos(x.real); - shi = sinh(x.imag); - chi = cosh(x.imag); - rs = sr*chi; - is = cr*shi; - rc = cr*chi; - ic = -sr*shi; - d = rc*rc + ic*ic; - r.real = (rs*rc+is*ic)/d; - r.imag = (is*rc-rs*ic)/d; - return r; -} - -static complex c_tanh(x) - complex x; -{ - complex r; - double si,ci,shr,chr; - double rs,is,rc,ic; - double d; - si = sin(x.imag); - ci = cos(x.imag); - shr = sinh(x.real); - chr = cosh(x.real); - rs = ci*shr; - is = si*chr; - rc = ci*chr; - ic = si*shr; - d = rc*rc + ic*ic; - r.real = (rs*rc+is*ic)/d; - r.imag = (is*rc-rs*ic)/d; - return r; -} - - -/* And now the glue to make them available from Python: */ - -static object * -math_error() -{ - if (errno == EDOM) - err_setstr(ValueError, "math domain error"); - else if (errno == ERANGE) - err_setstr(OverflowError, "math range error"); - else - err_errno(ValueError); /* Unexpected math error */ - return NULL; -} - -static object * -math_1(args, func) - object *args; - complex (*func) FPROTO((complex)); -{ - complex x; - if (!PyArg_ParseTuple(args, "D", &x)) - return NULL; - errno = 0; - x = (*func)(x); - CHECK(x.real); - CHECK(x.imag); - if (errno != 0) - return math_error(); - else - return newcomplexobject(x); -} - -#define FUNC1(stubname, func) \ - static object * stubname(self, args) object *self, *args; { \ - return math_1(args, func); \ - } - -FUNC1(cmath_acos, c_acos) -FUNC1(cmath_acosh, c_acosh) -FUNC1(cmath_asin, c_asin) -FUNC1(cmath_asinh, c_asinh) -FUNC1(cmath_atan, c_atan) -FUNC1(cmath_atanh, c_atanh) -FUNC1(cmath_cos, c_cos) -FUNC1(cmath_cosh, c_cosh) -FUNC1(cmath_exp, c_exp) -FUNC1(cmath_log, c_log) -FUNC1(cmath_log10, c_log10) -FUNC1(cmath_sin, c_sin) -FUNC1(cmath_sinh, c_sinh) -FUNC1(cmath_sqrt, c_sqrt) -FUNC1(cmath_tan, c_tan) -FUNC1(cmath_tanh, c_tanh) - - -static struct methodlist cmath_methods[] = { - {"acos", cmath_acos, 1}, - {"acosh", cmath_acosh, 1}, - {"asin", cmath_asin, 1}, - {"asinh", cmath_asinh, 1}, - {"atan", cmath_atan, 1}, - {"atanh", cmath_atanh, 1}, - {"cos", cmath_cos, 1}, - {"cosh", cmath_cosh, 1}, - {"exp", cmath_exp, 1}, - {"log", cmath_log, 1}, - {"log10", cmath_log10, 1}, - {"sin", cmath_sin, 1}, - {"sinh", cmath_sinh, 1}, - {"sqrt", cmath_sqrt, 1}, - {"tan", cmath_tan, 1}, - {"tanh", cmath_tanh, 1}, - {NULL, NULL} /* sentinel */ -}; - -void -initcmath() -{ - object *m, *d, *v; - - m = Py_InitModule("cmath", cmath_methods); - d = getmoduledict(m); - dictinsert(d, "pi", v = newfloatobject(atan(1.0) * 4.0)); - DECREF(v); - dictinsert(d, "e", v = newfloatobject(exp(1.0))); - DECREF(v); -} diff --git a/Modules/config.c.in b/Modules/config.c.in deleted file mode 100644 index 494a2a227e..0000000000 --- a/Modules/config.c.in +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- C -*- *********************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Module configuration */ - -/* !!! !!! !!! This file is edited by the makesetup script !!! !!! !!! */ - -/* This file contains the table of built-in modules. - See init_builtin() in import.c. */ - -#include "Python.h" - - -/* -- ADDMODULE MARKER 1 -- */ - -extern void PyMarshal_Init(); -extern void initimp(); - -struct _inittab inittab[] = { - -/* -- ADDMODULE MARKER 2 -- */ - - /* This module "lives in" with marshal.c */ - {"marshal", PyMarshal_Init}, - - /* This lives it with import.c */ - {"imp", initimp}, - - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"__builtin__", NULL}, - {"sys", NULL}, - - /* Sentinel */ - {0, 0} -}; diff --git a/Modules/cryptmodule.c b/Modules/cryptmodule.c deleted file mode 100644 index 13c79ba527..0000000000 --- a/Modules/cryptmodule.c +++ /dev/null @@ -1,35 +0,0 @@ -/* cryptmodule.c - by Steve Majewski - */ - -#include "allobjects.h" - -#include <sys/types.h> - - -/* Module crypt */ - - -static object *crypt_crypt(self, args) - object *self, *args; -{ - char *word, *salt; - extern char * crypt(); - - struct passwd *p; - if (!getargs(args, "(ss)", &word, &salt)) { - return NULL; - } - return newstringobject( crypt( word, salt ) ); - -} - -static struct methodlist crypt_methods[] = { - {"crypt", crypt_crypt}, - {NULL, NULL} /* sentinel */ -}; - -void -initcrypt() -{ - initmodule("crypt", crypt_methods); -} diff --git a/Modules/cstubs b/Modules/cstubs deleted file mode 100644 index 246b15f01d..0000000000 --- a/Modules/cstubs +++ /dev/null @@ -1,1369 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* -Input used to generate the Python module "glmodule.c". -The stub generator is a Python script called "cgen.py". - -Each definition must be contained on one line: - -<returntype> <name> <type> <arg> <type> <arg> - -<returntype> can be: void, short, long (XXX maybe others?) - -<type> can be: char, string, short, float, long, or double - string indicates a null terminated string; - if <type> is char and <arg> begins with a *, the * is stripped - and <type> is changed into string - -<arg> has the form <mode> or <mode>[<subscript>] - where <mode> can be - s: arg is sent - r: arg is received (arg is a pointer) - and <subscript> can be (N and I are numbers): - N - argI - retval - N*argI - N*I - N*retval - In the case where the subscript consists of two parts - separated by *, the first part is the width of the matrix, and - the second part is the length of the matrix. This order is - opposite from the order used in C to declare a two-dimensional - matrix. -*/ - -/* - * An attempt has been made to make this module switch threads on qread - * calls. It is far from safe, though. - */ - -#include <gl.h> -#include <device.h> - -#include "allobjects.h" -#include "import.h" -#include "modsupport.h" -#include "cgensupport.h" -#include "ceval.h" - -/* -Some stubs are too complicated for the stub generator. -We can include manually written versions of them here. -A line starting with '%' gives the name of the function so the stub -generator can include it in the table of functions. -*/ - -% qread - -static object * -gl_qread(self, args) - object *self; - object *args; -{ - long retval; - short arg1 ; - BGN_SAVE - retval = qread( & arg1 ); - END_SAVE - { object *v = newtupleobject( 2 ); - if (v == NULL) return NULL; - settupleitem(v, 0, mknewlongobject(retval)); - settupleitem(v, 1, mknewshortobject(arg1)); - return v; - } -} - - -/* -varray -- an array of v.. calls. -The argument is an array (maybe list or tuple) of points. -Each point must be a tuple or list of coordinates (x, y, z). -The points may be 2- or 3-dimensional but must all have the -same dimension. Float and int values may be mixed however. -The points are always converted to 3D double precision points -by assuming z=0.0 if necessary (as indicated in the man page), -and for each point v3d() is called. -*/ - -% varray - -static object * -gl_varray(self, args) - object *self; - object *args; -{ - object *v, *w; - int i, n, width; - double vec[3]; - object * (*getitem) FPROTO((object *, int)); - - if (!getiobjectarg(args, 1, 0, &v)) - return NULL; - - if (is_listobject(v)) { - n = getlistsize(v); - getitem = getlistitem; - } - else if (is_tupleobject(v)) { - n = gettuplesize(v); - getitem = gettupleitem; - } - else { - err_badarg(); - return NULL; - } - - if (n == 0) { - INCREF(None); - return None; - } - if (n > 0) - w = (*getitem)(v, 0); - - width = 0; - if (w == NULL) { - } - else if (is_listobject(w)) { - width = getlistsize(w); - } - else if (is_tupleobject(w)) { - width = gettuplesize(w); - } - - switch (width) { - case 2: - vec[2] = 0.0; - /* Fall through */ - case 3: - break; - default: - err_badarg(); - return NULL; - } - - for (i = 0; i < n; i++) { - w = (*getitem)(v, i); - if (!getidoublearray(w, 1, 0, width, vec)) - return NULL; - v3d(vec); - } - - INCREF(None); - return None; -} - -/* -vnarray, nvarray -- an array of n3f and v3f calls. -The argument is an array (list or tuple) of pairs of points and normals. -Each pair is a tuple (NOT a list) of a point and a normal for that point. -Each point or normal must be a tuple (NOT a list) of coordinates (x, y, z). -Three coordinates must be given. Float and int values may be mixed. -For each pair, n3f() is called for the normal, and then v3f() is called -for the vector. - -vnarray and nvarray differ only in the order of the vector and normal in -the pair: vnarray expects (v, n) while nvarray expects (n, v). -*/ - -static object *gen_nvarray(); /* Forward */ - -% nvarray - -static object * -gl_nvarray(self, args) - object *self; - object *args; -{ - return gen_nvarray(args, 0); -} - -% vnarray - -static object * -gl_vnarray(self, args) - object *self; - object *args; -{ - return gen_nvarray(args, 1); -} - -/* Generic, internal version of {nv,nv}array: inorm indicates the - argument order, 0: normal first, 1: vector first. */ - -static object * -gen_nvarray(args, inorm) - object *args; - int inorm; -{ - object *v, *w, *wnorm, *wvec; - int i, n; - float norm[3], vec[3]; - object * (*getitem) FPROTO((object *, int)); - - if (!getiobjectarg(args, 1, 0, &v)) - return NULL; - - if (is_listobject(v)) { - n = getlistsize(v); - getitem = getlistitem; - } - else if (is_tupleobject(v)) { - n = gettuplesize(v); - getitem = gettupleitem; - } - else { - err_badarg(); - return NULL; - } - - for (i = 0; i < n; i++) { - w = (*getitem)(v, i); - if (!is_tupleobject(w) || gettuplesize(w) != 2) { - err_badarg(); - return NULL; - } - wnorm = gettupleitem(w, inorm); - wvec = gettupleitem(w, 1 - inorm); - if (!getifloatarray(wnorm, 1, 0, 3, norm) || - !getifloatarray(wvec, 1, 0, 3, vec)) - return NULL; - n3f(norm); - v3f(vec); - } - - INCREF(None); - return None; -} - -/* nurbssurface(s_knots[], t_knots[], ctl[][], s_order, t_order, type). - The dimensions of ctl[] are computed as follows: - [len(s_knots) - s_order], [len(t_knots) - t_order] -*/ - -% nurbssurface - -static object * -gl_nurbssurface(self, args) - object *self; - object *args; -{ - long arg1 ; - double * arg2 ; - long arg3 ; - double * arg4 ; - double *arg5 ; - long arg6 ; - long arg7 ; - long arg8 ; - long ncoords; - long s_byte_stride, t_byte_stride; - long s_nctl, t_nctl; - long s, t; - object *v, *w, *pt; - double *pnext; - if (!getilongarraysize(args, 6, 0, &arg1)) - return NULL; - if ((arg2 = NEW(double, arg1 )) == NULL) { - return err_nomem(); - } - if (!getidoublearray(args, 6, 0, arg1 , arg2)) - return NULL; - if (!getilongarraysize(args, 6, 1, &arg3)) - return NULL; - if ((arg4 = NEW(double, arg3 )) == NULL) { - return err_nomem(); - } - if (!getidoublearray(args, 6, 1, arg3 , arg4)) - return NULL; - if (!getilongarg(args, 6, 3, &arg6)) - return NULL; - if (!getilongarg(args, 6, 4, &arg7)) - return NULL; - if (!getilongarg(args, 6, 5, &arg8)) - return NULL; - if (arg8 == N_XYZ) - ncoords = 3; - else if (arg8 == N_XYZW) - ncoords = 4; - else { - err_badarg(); - return NULL; - } - s_nctl = arg1 - arg6; - t_nctl = arg3 - arg7; - if (!getiobjectarg(args, 6, 2, &v)) - return NULL; - if (!is_listobject(v) || getlistsize(v) != s_nctl) { - err_badarg(); - return NULL; - } - if ((arg5 = NEW(double, s_nctl*t_nctl*ncoords )) == NULL) { - return err_nomem(); - } - pnext = arg5; - for (s = 0; s < s_nctl; s++) { - w = getlistitem(v, s); - if (w == NULL || !is_listobject(w) || - getlistsize(w) != t_nctl) { - err_badarg(); - return NULL; - } - for (t = 0; t < t_nctl; t++) { - pt = getlistitem(w, t); - if (!getidoublearray(pt, 1, 0, ncoords, pnext)) - return NULL; - pnext += ncoords; - } - } - s_byte_stride = sizeof(double) * ncoords; - t_byte_stride = s_byte_stride * s_nctl; - nurbssurface( arg1 , arg2 , arg3 , arg4 , - s_byte_stride , t_byte_stride , arg5 , arg6 , arg7 , arg8 ); - DEL(arg2); - DEL(arg4); - DEL(arg5); - INCREF(None); - return None; -} - -/* nurbscurve(knots, ctlpoints, order, type). - The length of ctlpoints is len(knots)-order. */ - -%nurbscurve - -static object * -gl_nurbscurve(self, args) - object *self; - object *args; -{ - long arg1 ; - double * arg2 ; - long arg3 ; - double * arg4 ; - long arg5 ; - long arg6 ; - int ncoords, npoints; - int i; - object *v; - double *pnext; - if (!getilongarraysize(args, 4, 0, &arg1)) - return NULL; - if ((arg2 = NEW(double, arg1 )) == NULL) { - return err_nomem(); - } - if (!getidoublearray(args, 4, 0, arg1 , arg2)) - return NULL; - if (!getilongarg(args, 4, 2, &arg5)) - return NULL; - if (!getilongarg(args, 4, 3, &arg6)) - return NULL; - if (arg6 == N_ST) - ncoords = 2; - else if (arg6 == N_STW) - ncoords = 3; - else { - err_badarg(); - return NULL; - } - npoints = arg1 - arg5; - if (!getiobjectarg(args, 4, 1, &v)) - return NULL; - if (!is_listobject(v) || getlistsize(v) != npoints) { - err_badarg(); - return NULL; - } - if ((arg4 = NEW(double, npoints*ncoords )) == NULL) { - return err_nomem(); - } - pnext = arg4; - for (i = 0; i < npoints; i++) { - if (!getidoublearray(getlistitem(v, i), 1, 0, ncoords, pnext)) - return NULL; - pnext += ncoords; - } - arg3 = (sizeof(double)) * ncoords; - nurbscurve( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 ); - DEL(arg2); - DEL(arg4); - INCREF(None); - return None; -} - -/* pwlcurve(points, type). - Points is a list of points. Type must be N_ST. */ - -%pwlcurve - -static object * -gl_pwlcurve(self, args) - object *self; - object *args; -{ - object *v; - long type; - double *data, *pnext; - long npoints, ncoords; - int i; - if (!getiobjectarg(args, 2, 0, &v)) - return NULL; - if (!getilongarg(args, 2, 1, &type)) - return NULL; - if (!is_listobject(v)) { - err_badarg(); - return NULL; - } - npoints = getlistsize(v); - if (type == N_ST) - ncoords = 2; - else { - err_badarg(); - return NULL; - } - if ((data = NEW(double, npoints*ncoords)) == NULL) { - return err_nomem(); - } - pnext = data; - for (i = 0; i < npoints; i++) { - if (!getidoublearray(getlistitem(v, i), 1, 0, ncoords, pnext)) - return NULL; - pnext += ncoords; - } - pwlcurve(npoints, data, sizeof(double)*ncoords, type); - DEL(data); - INCREF(None); - return None; -} - - -/* Picking and Selecting */ - -static short *pickbuffer = NULL; -static long pickbuffersize; - -static object * -pick_select(args, func) - object *args; - void (*func)(); -{ - if (!getilongarg(args, 1, 0, &pickbuffersize)) - return NULL; - if (pickbuffer != NULL) { - err_setstr(RuntimeError, - "pick/gselect: already picking/selecting"); - return NULL; - } - if ((pickbuffer = NEW(short, pickbuffersize)) == NULL) { - return err_nomem(); - } - (*func)(pickbuffer, pickbuffersize); - INCREF(None); - return None; -} - -static object * -endpick_select(args, func) - object *args; - long (*func)(); -{ - object *v, *w; - int i, nhits, n; - if (!getnoarg(args)) - return NULL; - if (pickbuffer == NULL) { - err_setstr(RuntimeError, - "endpick/endselect: not in pick/select mode"); - return NULL; - } - nhits = (*func)(pickbuffer); - if (nhits < 0) { - nhits = -nhits; /* How to report buffer overflow otherwise? */ - } - /* Scan the buffer to see how many integers */ - n = 0; - for (; nhits > 0; nhits--) { - n += 1 + pickbuffer[n]; - } - v = newlistobject(n); - if (v == NULL) - return NULL; - /* XXX Could do it nicer and interpret the data structure here, - returning a list of lists. But this can be done in Python... */ - for (i = 0; i < n; i++) { - w = newintobject((long)pickbuffer[i]); - if (w == NULL) { - DECREF(v); - return NULL; - } - setlistitem(v, i, w); - } - DEL(pickbuffer); - pickbuffer = NULL; - return v; -} - -extern void pick(), gselect(); -extern long endpick(), endselect(); - -%pick -static object *gl_pick(self, args) object *self, *args; { - return pick_select(args, pick); -} - -%endpick -static object *gl_endpick(self, args) object *self, *args; { - return endpick_select(args, endpick); -} - -%gselect -static object *gl_gselect(self, args) object *self, *args; { - return pick_select(args, gselect); -} - -%endselect -static object *gl_endselect(self, args) object *self, *args; { - return endpick_select(args, endselect); -} - - -/* XXX The generator botches this one. Here's a quick hack to fix it. */ - -/* XXX The generator botches this one. Here's a quick hack to fix it. */ - -% getmatrix float r[16] - -static object * -gl_getmatrix(self, args) - object *self; - object *args; -{ - Matrix arg1; - object *v, *w; - int i, j; - getmatrix( arg1 ); - v = newlistobject(16); - if (v == NULL) { - return err_nomem(); - } - for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) { - w = mknewfloatobject(arg1[i][j]); - if (w == NULL) { - DECREF(v); - return NULL; - } - setlistitem(v, i*4+j, w); - } - return v; -} - -/* Here's an alternate version that returns a 4x4 matrix instead of - a vector. Unfortunately it is incompatible with loadmatrix and - multmatrix... */ - -% altgetmatrix float r[4][4] - -static object * -gl_altgetmatrix(self, args) - object *self; - object *args; -{ - Matrix arg1; - object *v, *w; - int i, j; - getmatrix( arg1 ); - v = newlistobject(4); - if (v == NULL) { - return NULL; - } - for (i = 0; i < 4; i++) { - w = newlistobject(4); - if (w == NULL) { - DECREF(v); - return NULL; - } - setlistitem(v, i, w); - } - for (i = 0; i < 4; i++) { - for (j = 0; j < 4; j++) { - w = mknewfloatobject(arg1[i][j]); - if (w == NULL) { - DECREF(v); - return NULL; - } - setlistitem(getlistitem(v, i), j, w); - } - } - return v; -} - -% lrectwrite - -static object * -gl_lrectwrite(self, args) - object *self; - object *args; -{ - short x1 ; - short y1 ; - short x2 ; - short y2 ; - string parray ; - object *s; - int pixcount; - if (!getishortarg(args, 5, 0, &x1)) - return NULL; - if (!getishortarg(args, 5, 1, &y1)) - return NULL; - if (!getishortarg(args, 5, 2, &x2)) - return NULL; - if (!getishortarg(args, 5, 3, &y2)) - return NULL; - if (!getistringarg(args, 5, 4, &parray)) - return NULL; - if (!getiobjectarg(args, 5, 4, &s)) - return NULL; -#if 0 -/* Don't check this, it breaks experiments with pixmode(PM_SIZE, ...) */ - pixcount = (long)(x2+1-x1) * (long)(y2+1-y1); - if (!is_stringobject(s) || getstringsize(s) != pixcount*sizeof(long)) { - err_setstr(RuntimeError, - "string arg to lrectwrite has wrong size"); - return NULL; - } -#endif - lrectwrite( x1 , y1 , x2 , y2 , (unsigned long *) parray ); - INCREF(None); - return None; -} - -% lrectread - -static object * -gl_lrectread(self, args) - object *self; - object *args; -{ - short x1 ; - short y1 ; - short x2 ; - short y2 ; - object *parray; - int pixcount; - if (!getishortarg(args, 4, 0, &x1)) - return NULL; - if (!getishortarg(args, 4, 1, &y1)) - return NULL; - if (!getishortarg(args, 4, 2, &x2)) - return NULL; - if (!getishortarg(args, 4, 3, &y2)) - return NULL; - pixcount = (long)(x2+1-x1) * (long)(y2+1-y1); - parray = newsizedstringobject((char *)NULL, pixcount*sizeof(long)); - if (parray == NULL) - return NULL; /* No memory */ - lrectread(x1, y1, x2, y2, (unsigned long *) getstringvalue(parray)); - return parray; -} - -% readdisplay - -static object * -gl_readdisplay(self, args) - object *self; - object *args; -{ - short x1, y1, x2, y2; - unsigned long *parray, hints; - long size, size_ret; - object *rv; - - if ( !getargs(args, "hhhhl", &x1, &y1, &x2, &y2, &hints) ) - return 0; - size = (long)(x2+1-x1) * (long)(y2+1-y1); - rv = newsizedstringobject((char *)NULL, size*sizeof(long)); - if ( rv == NULL ) - return NULL; - parray = (unsigned long *)getstringvalue(rv); - size_ret = readdisplay(x1, y1, x2, y2, parray, hints); - if ( size_ret != size ) { - printf("gl_readdisplay: got %d pixels, expected %d\n", - size_ret, size); - err_setstr(RuntimeError, "readdisplay returned unexpected length"); - return NULL; - } - return rv; -} - -/* Desperately needed, here are tools to compress and decompress - the data manipulated by lrectread/lrectwrite. - - gl.packrect(width, height, packfactor, bigdata) --> smalldata - makes 'bigdata' 4*(packfactor**2) times smaller by: - - turning it into B/W (a factor 4) - - replacing squares of size pacfactor by one - representative - - gl.unpackrect(width, height, packfactor, smalldata) --> bigdata - is the inverse; the numeric arguments must be *the same*. - - Both work best if width and height are multiples of packfactor - (in fact unpackrect will leave garbage bytes). -*/ - -% packrect - -static object * -gl_packrect(self, args) - object *self; - object *args; -{ - long width, height, packfactor; - char *s; - object *unpacked, *packed; - int pixcount, packedcount, x, y, r, g, b; - unsigned long pixel; - unsigned char *p; - unsigned long *parray; - if (!getilongarg(args, 4, 0, &width)) - return NULL; - if (!getilongarg(args, 4, 1, &height)) - return NULL; - if (!getilongarg(args, 4, 2, &packfactor)) - return NULL; - if (!getistringarg(args, 4, 3, &s)) /* For type checking only */ - return NULL; - if (!getiobjectarg(args, 4, 3, &unpacked)) - return NULL; - if (width <= 0 || height <= 0 || packfactor <= 0) { - err_setstr(RuntimeError, "packrect args must be > 0"); - return NULL; - } - pixcount = width*height; - packedcount = ((width+packfactor-1)/packfactor) * - ((height+packfactor-1)/packfactor); - if (getstringsize(unpacked) != pixcount*sizeof(long)) { - err_setstr(RuntimeError, - "string arg to packrect has wrong size"); - return NULL; - } - packed = newsizedstringobject((char *)NULL, packedcount); - if (packed == NULL) - return NULL; - parray = (unsigned long *) getstringvalue(unpacked); - p = (unsigned char *) getstringvalue(packed); - for (y = 0; y < height; y += packfactor, parray += packfactor*width) { - for (x = 0; x < width; x += packfactor) { - pixel = parray[x]; - r = pixel & 0xff; - g = (pixel >> 8) & 0xff; - b = (pixel >> 16) & 0xff; - *p++ = (30*r+59*g+11*b) / 100; - } - } - return packed; -} - -% unpackrect - -static unsigned long unpacktab[256]; -static int unpacktab_inited = 0; - -static object * -gl_unpackrect(self, args) - object *self; - object *args; -{ - long width, height, packfactor; - char *s; - object *unpacked, *packed; - int pixcount, packedcount, y; - register unsigned char *p; - register unsigned long *parray; - if (!unpacktab_inited) { - register int white; - for (white = 256; --white >= 0; ) - unpacktab[white] = white * 0x010101L; - unpacktab_inited++; - } - if (!getilongarg(args, 4, 0, &width)) - return NULL; - if (!getilongarg(args, 4, 1, &height)) - return NULL; - if (!getilongarg(args, 4, 2, &packfactor)) - return NULL; - if (!getistringarg(args, 4, 3, &s)) /* For type checking only */ - return NULL; - if (!getiobjectarg(args, 4, 3, &packed)) - return NULL; - if (width <= 0 || height <= 0 || packfactor <= 0) { - err_setstr(RuntimeError, "packrect args must be > 0"); - return NULL; - } - pixcount = width*height; - packedcount = ((width+packfactor-1)/packfactor) * - ((height+packfactor-1)/packfactor); - if (getstringsize(packed) != packedcount) { - err_setstr(RuntimeError, - "string arg to unpackrect has wrong size"); - return NULL; - } - unpacked = newsizedstringobject((char *)NULL, pixcount*sizeof(long)); - if (unpacked == NULL) - return NULL; - parray = (unsigned long *) getstringvalue(unpacked); - p = (unsigned char *) getstringvalue(packed); - if (packfactor == 1 && width*height > 0) { - /* Just expand bytes to longs */ - register int x = width * height; - do { - *parray++ = unpacktab[*p++]; - } while (--x >= 0); - } - else { - register int y; - for (y = 0; y < height-packfactor+1; - y += packfactor, parray += packfactor*width) { - register int x; - for (x = 0; x < width-packfactor+1; x += packfactor) { - register unsigned long pixel = unpacktab[*p++]; - register int i; - for (i = packfactor*width; (i-=width) >= 0;) { - register int j; - for (j = packfactor; --j >= 0; ) - parray[i+x+j] = pixel; - } - } - } - } - return unpacked; -} - -% gversion -static object * -gl_gversion(self, args) - object *self; - object *args; -{ - char buf[20]; - gversion(buf); - return newstringobject(buf); -} - - -/* End of manually written stubs */ - -%% - -long getshade -if !solaris void devport short s long s -void rdr2i long s long s -void rectfs short s short s short s short s -void rects short s short s short s short s -void rmv2i long s long s -void noport -void popviewport -void clear -void clearhitcode -void closeobj -void cursoff -void curson -void doublebuffer -void finish -void gconfig -void ginit -void greset -void multimap -void onemap -void popattributes -void popmatrix -void pushattributes -void pushmatrix -void pushviewport -void qreset -void RGBmode -void singlebuffer -void swapbuffers -void gsync -void gflush -void tpon -void tpoff -void clkon -void clkoff -void ringbell -#void callfunc -void gbegin -void textinit -void initnames -void pclos -void popname -if !solaris void spclos -void zclear -void screenspace -void reshapeviewport -void winpush -void winpop -void foreground -void endfullscrn -if !solaris void endpupmode -void fullscrn -if !solaris void pupmode -void winconstraints -void pagecolor short s -void textcolor short s -void color short s -void curveit short s -void font short s -void linewidth short s -void setlinestyle short s -void setmap short s -void swapinterval short s -void writemask short s -if !solaris void textwritemask short s -void qdevice short s -void unqdevice short s -void curvebasis short s -void curveprecision short s -void loadname short s -void passthrough short s -void pushname short s -void setmonitor short s -if !solaris void setshade short s -void setpattern short s -if !solaris void pagewritemask short s -# -void callobj long s -void delobj long s -void editobj long s -void makeobj long s -void maketag long s -void chunksize long s -void compactify long s -void deltag long s -void lsrepeat long s -void objinsert long s -void objreplace long s -void winclose long s -void blanktime long s -void freepup long s -# This is not in the library!? -###void pupcolor long s -# -void backbuffer long s -void frontbuffer long s -if !solaris void lsbackup long s -void resetls long s -void lampon long s -void lampoff long s -void setbell long s -void blankscreen long s -void depthcue long s -void zbuffer long s -void backface long s -# -void cmov2i long s long s -void draw2i long s long s -void move2i long s long s -void pnt2i long s long s -void patchbasis long s long s -void patchprecision long s long s -void pdr2i long s long s -void pmv2i long s long s -void rpdr2i long s long s -void rpmv2i long s long s -void xfpt2i long s long s -void objdelete long s long s -void patchcurves long s long s -void minsize long s long s -void maxsize long s long s -void keepaspect long s long s -void prefsize long s long s -void stepunit long s long s -void fudge long s long s -void winmove long s long s -# -void attachcursor short s short s -void deflinestyle short s short s -void noise short s short s -void picksize short s short s -void qenter short s short s -void setdepth short s short s -void cmov2s short s short s -void draw2s short s short s -void move2s short s short s -void pdr2s short s short s -void pmv2s short s short s -void pnt2s short s short s -void rdr2s short s short s -void rmv2s short s short s -void rpdr2s short s short s -void rpmv2s short s short s -void xfpt2s short s short s -# -void cmov2 float s float s -void draw2 float s float s -void move2 float s float s -void pnt2 float s float s -void pdr2 float s float s -void pmv2 float s float s -void rdr2 float s float s -void rmv2 float s float s -void rpdr2 float s float s -void rpmv2 float s float s -void xfpt2 float s float s -# -void loadmatrix float s[4*4] -# Really [4][4] -void multmatrix float s[4*4] -# Really [4][4] -void crv float s[3*4] -# Really [4][3] -void rcrv float s[4*4] -# Really [4][4] -# -# Methods that have strings. -# -void addtopup long s char *s long s -void charstr char *s -void getport char *s -long strwidth char *s -long winopen char *s -void wintitle char *s -# -# Methods that have 1 long (# of elements) and an array -# -void polf long s float s[3*arg1] -void polf2 long s float s[2*arg1] -void poly long s float s[3*arg1] -void poly2 long s float s[2*arg1] -void crvn long s float s[3*arg1] -void rcrvn long s float s[4*arg1] -# -void polf2i long s long s[2*arg1] -void polfi long s long s[3*arg1] -void poly2i long s long s[2*arg1] -void polyi long s long s[3*arg1] -# -void polf2s long s short s[2*arg1] -void polfs long s short s[3*arg1] -void polys long s short s[3*arg1] -void poly2s long s short s[2*arg1] -# -void defcursor short s u_short s[128] -# Is this useful? -void writepixels short s u_short s[arg1] -# Should be unsigned short... -void defbasis long s float s[4*4] -if !solaris void gewrite short s short s[arg1] -# -void rotate short s char s -# This is not in the library!? -###void setbutton short s char s -void rot float s char s -# -void circfi long s long s long s -void circi long s long s long s -void cmovi long s long s long s -void drawi long s long s long s -void movei long s long s long s -void pnti long s long s long s -void newtag long s long s long s -void pdri long s long s long s -void pmvi long s long s long s -void rdri long s long s long s -void rmvi long s long s long s -void rpdri long s long s long s -void rpmvi long s long s long s -void xfpti long s long s long s -# -void circ float s float s float s -void circf float s float s float s -void cmov float s float s float s -void draw float s float s float s -void move float s float s float s -void pnt float s float s float s -void scale float s float s float s -void translate float s float s float s -void pdr float s float s float s -void pmv float s float s float s -void rdr float s float s float s -void rmv float s float s float s -void rpdr float s float s float s -void rpmv float s float s float s -void xfpt float s float s float s -# -void RGBcolor short s short s short s -void RGBwritemask short s short s short s -void setcursor short s short s short s -void tie short s short s short s -void circfs short s short s short s -void circs short s short s short s -void cmovs short s short s short s -void draws short s short s short s -void moves short s short s short s -void pdrs short s short s short s -void pmvs short s short s short s -void pnts short s short s short s -void rdrs short s short s short s -void rmvs short s short s short s -void rpdrs short s short s short s -void rpmvs short s short s short s -void xfpts short s short s short s -void curorigin short s short s short s -void cyclemap short s short s short s -# -void patch float s[4*4] float s[4*4] float s[4*4] -void splf long s float s[3*arg1] u_short s[arg1] -void splf2 long s float s[2*arg1] u_short s[arg1] -void splfi long s long s[3*arg1] u_short s[arg1] -void splf2i long s long s[2*arg1] u_short s[arg1] -void splfs long s short s[3*arg1] u_short s[arg1] -void splf2s long s short s[2*arg1] u_short s[arg1] -###void defpattern short s short s u_short s[arg2*arg2/16] -# -void rpatch float s[4*4] float s[4*4] float s[4*4] float s[4*4] -# -# routines that send 4 floats -# -void ortho2 float s float s float s float s -void rect float s float s float s float s -void rectf float s float s float s float s -void xfpt4 float s float s float s float s -# -void textport short s short s short s short s -void mapcolor short s short s short s short s -void scrmask short s short s short s short s -void setvaluator short s short s short s short s -void viewport short s short s short s short s -void shaderange short s short s short s short s -void xfpt4s short s short s short s short s -void rectfi long s long s long s long s -void recti long s long s long s long s -void xfpt4i long s long s long s long s -void prefposition long s long s long s long s -# -void arc float s float s float s short s short s -void arcf float s float s float s short s short s -void arcfi long s long s long s short s short s -void arci long s long s long s short s short s -# -void bbox2 short s short s float s float s float s float s -void bbox2i short s short s long s long s long s long s -void bbox2s short s short s short s short s short s short s -void blink short s short s short s short s short s -void ortho float s float s float s float s float s float s -void window float s float s float s float s float s float s -void lookat float s float s float s float s float s float s short s -# -void perspective short s float s float s float s -void polarview float s short s short s short s -# XXX getichararray not supported -#void writeRGB short s char s[arg1] char s[arg1] char s[arg1] -# -void arcfs short s short s short s short s short s -void arcs short s short s short s short s short s -void rectcopy short s short s short s short s short s short s -if !solaris void RGBcursor short s short s short s short s short s short s short s -# -long getbutton short s -long getcmmode -long getlsbackup -long getresetls -long getdcm -long getzbuffer -long ismex -long isobj long s -long isqueued short s -long istag long s -# -long genobj -long gentag -long getbuffer -long getcolor -long getdisplaymode -long getfont -long getheight -long gethitcode -long getlstyle -long getlwidth -long getmap -long getplanes -long getwritemask -long qtest -long getlsrepeat -long getmonitor -long getopenobj -long getpattern -long winget -long winattach -long getothermonitor -long newpup -# -long getvaluator short s -void winset long s -long dopup long s -void getdepth short r short r -void getcpos short r short r -void getsize long r long r -void getorigin long r long r -void getviewport short r short r short r short r -if !solaris void gettp short r short r short r short r -void getgpos float r float r float r float r -void winposition long s long s long s long s -void gRGBcolor short r short r short r -void gRGBmask short r short r short r -void getscrmask short r short r short r short r -###void gRGBcursor short r short r short r short r short r short r short r short r -void getmcolor short s short r short r short r -void mapw long s short s short s float r float r float r float r float r float r -void mapw2 long s short s short s float r float r -###void defrasterfont short s short s short s Fontchar s[arg3] short s short s[4*arg5] -###long qread short r -void getcursor short r u_short r u_short r long r -# -# For these we receive arrays of stuff -# -###void getdev long s short s[arg1] short r[arg1] -#XXX not generated correctly yet -#void getmatrix float r[16] -###long readpixels short s short r[retval] -###long readRGB short s char r[retval] char r[retval] char r[retval] -###long blkqread short s short r[arg1] -# -# New 4D routines -# -void cmode -void concave long s -void curstype long s -void drawmode long s -void gammaramp short s[256] short s[256] short s[256] -long getbackface -long getdescender -long getdrawmode -long getmmode -long getsm -long getvideo long s -void imakebackground -void lmbind short s short s -void lmdef long s long s long s float s[arg3] -void mmode long s -void normal float s[3] -void overlay long s -void RGBrange short s short s short s short s short s short s short s short s -if !solaris void setvideo long s long s -void shademodel long s -void underlay long s -# -# New Personal Iris/GT Routines -# -void bgnclosedline -void bgnline -void bgnpoint -void bgnpolygon -void bgnsurface -void bgntmesh -void bgntrim -void endclosedline -void endline -void endpoint -void endpolygon -void endsurface -void endtmesh -void endtrim -void blendfunction long s long s -void c3f float s[3] -void c3i long s[3] -void c3s short s[3] -void c4f float s[4] -void c4i long s[4] -void c4s short s[4] -void colorf float s -void cpack long s -void czclear long s long s -void dglclose long s -long dglopen char *s long s -long getgdesc long s -void getnurbsproperty long s float r -void glcompat long s long s -void iconsize long s long s -void icontitle char *s -void lRGBrange short s short s short s short s short s short s long s long s -void linesmooth long s -void lmcolor long s -void logicop long s -###long lrectread short s short s short s short s long r[retval] -###void lrectwrite short s short s short s short s long s[(arg2-arg1+1)*(arg4-arg3+1)] -### Now manual, with string last arg -###long rectread short s short s short s short s short r[retval] -###void rectwrite short s short s short s short s short s[(arg2-arg1+1)*(arg4-arg3+1)] -void lsetdepth long s long s -void lshaderange short s short s long s long s -void n3f float s[3] -void noborder -void pntsmooth long s -void readsource long s -void rectzoom float s float s -void sbox float s float s float s float s -void sboxi long s long s long s long s -void sboxs short s short s short s short s -void sboxf float s float s float s float s -void sboxfi long s long s long s long s -void sboxfs short s short s short s short s -void setnurbsproperty long s float s -void setpup long s long s long s -void smoothline long s -void subpixel long s -void swaptmesh -long swinopen long s -void v2f float s[2] -void v2i long s[2] -void v2s short s[2] -void v3f float s[3] -void v3i long s[3] -void v3s short s[3] -void v4f float s[4] -void v4i long s[4] -void v4s short s[4] -void videocmd long s -long windepth long s -void wmpack long s -void zdraw long s -void zfunction long s -void zsource long s -void zwritemask long s -# -# uses doubles -# -void v2d double s[2] -void v3d double s[3] -void v4d double s[4] -# -# Why isn't this here? -# -void pixmode long s long s -# -# New in IRIX 4.0 -# -long qgetfd -void dither long s diff --git a/Modules/dbhashmodule.c b/Modules/dbhashmodule.c deleted file mode 100644 index a8df0279d3..0000000000 --- a/Modules/dbhashmodule.c +++ /dev/null @@ -1,380 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Berkeley DB hash interface. - Author: Michael McLay - Hacked: Guido van Rossum - - XXX To do: - - provide interface to the B-tree and record libraries too - - provide a way to access the various hash functions - - support more open flags - */ - -#include "allobjects.h" -#include "modsupport.h" - -#include <sys/types.h> -#include <sys/stat.h> -#include <fcntl.h> -#include <db.h> -/* Please don't include internal header files of the Berkeley db package - (it messes up the info required in the Setup file) */ - -typedef struct { - OB_HEAD - DB *di_dbhash; - int di_size; /* -1 means recompute */ -} dbhashobject; - -staticforward typeobject Dbhashtype; - -#define is_dbhashobject(v) ((v)->ob_type == &Dbhashtype) - -static object *DbhashError; - -static object * -newdbhashobject(file, flags, mode, - bsize, ffactor, nelem, cachesize, hash, lorder) - char *file; - int flags; - int mode; - int bsize; - int ffactor; - int nelem; - int cachesize; - int hash; /* XXX ignored */ - int lorder; -{ - dbhashobject *dp; - HASHINFO info; - - if ((dp = NEWOBJ(dbhashobject, &Dbhashtype)) == NULL) - return NULL; - - info.bsize = bsize; - info.ffactor = ffactor; - info.nelem = nelem; - info.cachesize = cachesize; - info.hash = NULL; /* XXX should derive from hash argument */ - info.lorder = lorder; - - if ((dp->di_dbhash = dbopen(file, flags, mode, DB_HASH, &info)) == NULL) { - err_errno(DbhashError); - DECREF(dp); - return NULL; - } - - dp->di_size = -1; - - return (object *)dp; -} - -static void -dbhash_dealloc(dp) - dbhashobject *dp; -{ - if (dp->di_dbhash != NULL) { - if ((dp->di_dbhash->close)(dp->di_dbhash) != 0) - fprintf(stderr, - "Python dbhash: close errno %s in dealloc\n", errno); - } - DEL(dp); -} - -static int -dbhash_length(dp) - dbhashobject *dp; -{ - if (dp->di_size < 0) { - DBT krec, drec; - int status; - int size = 0; - for (status = (dp->di_dbhash->seq)(dp->di_dbhash, &krec, &drec,R_FIRST); - status == 0; - status = (dp->di_dbhash->seq)(dp->di_dbhash, &krec, &drec, R_NEXT)) - size++; - if (status < 0) { - err_errno(DbhashError); - return -1; - } - dp->di_size = size; - } - return dp->di_size; -} - -static object * -dbhash_subscript(dp, key) - dbhashobject *dp; - object *key; -{ - int status; - object *v; - DBT krec, drec; - char *data; - int size; - - if (!getargs(key, "s#", &data, &size)) - return NULL; - krec.data = data; - krec.size = size; - - status = (dp->di_dbhash->get)(dp->di_dbhash, &krec, &drec, 0); - if (status != 0) { - if (status < 0) - err_errno(DbhashError); - else - err_setval(KeyError, key); - return NULL; - } - - return newsizedstringobject((char *)drec.data, (int)drec.size); -} - -static int -dbhash_ass_sub(dp, key, value) - dbhashobject *dp; - object *key, *value; -{ - int status; - DBT krec, drec; - char *data; - int size; - - if (!getargs(key, "s#", &data, &size)) { - err_setstr(TypeError, "dbhash key type must be string"); - return -1; - } - krec.data = data; - krec.size = size; - dp->di_size = -1; - if (value == NULL) { - status = (dp->di_dbhash->del)(dp->di_dbhash, &krec, 0); - } - else { - if (!getargs(value, "s#", &data, &size)) { - err_setstr(TypeError, "dbhash value type must be string"); - return -1; - } - drec.data = data; - drec.size = size; - status = (dp->di_dbhash->put)(dp->di_dbhash, &krec, &drec, 0); - } - if (status != 0) { - if (status < 0) - err_errno(DbhashError); - else - err_setval(KeyError, key); - return -1; - } - return 0; -} - -static mapping_methods dbhash_as_mapping = { - (inquiry)dbhash_length, /*mp_length*/ - (binaryfunc)dbhash_subscript, /*mp_subscript*/ - (objobjargproc)dbhash_ass_sub, /*mp_ass_subscript*/ -}; - -static object * -dbhash_close(dp, args) - dbhashobject *dp; - object *args; -{ - if (!getnoarg(args)) - return NULL; - if (dp->di_dbhash != NULL) { - if ((dp->di_dbhash->close)(dp->di_dbhash) != 0) { - dp->di_dbhash = NULL; - err_errno(DbhashError); - return NULL; - } - } - dp->di_dbhash = NULL; - INCREF(None); - return None; -} - -static object * -dbhash_keys(dp, args) - dbhashobject *dp; - object *args; -{ - object *list, *item; - DBT krec, drec; - int status; - int err; - - if (!getnoarg(args)) - return NULL; - list = newlistobject(0); - if (list == NULL) - return NULL; - for (status = (dp->di_dbhash->seq)(dp->di_dbhash, &krec, &drec, R_FIRST); - status == 0; - status = (dp->di_dbhash->seq)(dp->di_dbhash, &krec, &drec, R_NEXT)) { - item = newsizedstringobject((char *)krec.data, (int)krec.size); - if (item == NULL) { - DECREF(list); - return NULL; - } - err = addlistitem(list, item); - DECREF(item); - if (err != 0) { - DECREF(list); - return NULL; - } - } - if (status < 0) { - err_errno(DbhashError); - DECREF(list); - return NULL; - } - if (dp->di_size < 0) - dp->di_size = getlistsize(list); /* We just did the work for this... */ - return list; -} - -static object * -dbhash_has_key(dp, args) - dbhashobject *dp; - object *args; -{ - DBT krec, drec; - int status; - char *data; - int size; - - if (!getargs(args, "s#", &data, &size)) - return NULL; - krec.data = data; - krec.size = size; - - status = (dp->di_dbhash->get)(dp->di_dbhash, &krec, &drec, 0); - if (status < 0) { - err_errno(DbhashError); - return NULL; - } - - return newintobject(status == 0); -} - -static struct methodlist dbhash_methods[] = { - {"close", (method)dbhash_close}, - {"keys", (method)dbhash_keys}, - {"has_key", (method)dbhash_has_key}, - {NULL, NULL} /* sentinel */ -}; - -static object * -dbhash_getattr(dp, name) - object *dp; - char *name; -{ - return findmethod(dbhash_methods, dp, name); -} - -static typeobject Dbhashtype = { - OB_HEAD_INIT(&Typetype) - 0, - "dbhash", - sizeof(dbhashobject), - 0, - (destructor)dbhash_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)dbhash_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - &dbhash_as_mapping, /*tp_as_mapping*/ -}; - -static object * -dbhashopen(self, args) - object *self; - object *args; -{ - char *file; - char *flag = NULL; - int flags = O_RDONLY; - int mode = 0666; - int bsize = 0; - int ffactor = 0; - int nelem = 0; - int cachesize = 0; - int hash = 0; /* XXX currently ignored */ - int lorder = 0; - - if (!newgetargs(args, "s|siiiiiii", - &file, &flag, &mode, - &bsize, &ffactor, &nelem, &cachesize, &hash, &lorder)) - return NULL; - if (flag != NULL) { - /* XXX need a way to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */ - if (flag[0] == 'r') - flags = O_RDONLY; - else if (flag[0] == 'w') - flags = O_RDWR; - else if (flag[0] == 'c') - flags = O_RDWR|O_CREAT; - else if (flag[0] == 'n') - flags = O_RDWR|O_CREAT|O_TRUNC; - else { - err_setstr(DbhashError, - "Flag should begin with 'r', 'w', 'c' or 'n'"); - return NULL; - } - if (flag[1] == 'l') { -#if defined(O_EXLOCK) && defined(O_SHLOCK) - if (flag[0] == 'r') - flags |= O_SHLOCK; - else - flags |= O_EXLOCK; -#else - err_setstr(DbhashError, "locking not supported on this platform"); - return NULL; -#endif - } - } - return newdbhashobject(file, flags, mode, - bsize, ffactor, nelem, cachesize, hash, lorder); -} - -static struct methodlist dbhashmodule_methods[] = { - {"open", (method)dbhashopen, 1}, - {0, 0}, -}; - -void -initdbhash() { - object *m, *d; - - m = initmodule("dbhash", dbhashmodule_methods); - d = getmoduledict(m); - DbhashError = newstringobject("dbhash.error"); - if (DbhashError == NULL || dictinsert(d, "error", DbhashError)) - fatal("can't define dbhash.error"); -} diff --git a/Modules/dbmmodule.c b/Modules/dbmmodule.c deleted file mode 100644 index 936fb45ab1..0000000000 --- a/Modules/dbmmodule.c +++ /dev/null @@ -1,300 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* DBM module using dictionary interface */ - - -#include "allobjects.h" -#include "modsupport.h" - -#include <sys/types.h> -#include <sys/stat.h> -#include <fcntl.h> -#include <ndbm.h> - -typedef struct { - OB_HEAD - int di_size; /* -1 means recompute */ - DBM *di_dbm; -} dbmobject; - -staticforward typeobject Dbmtype; - -#define is_dbmobject(v) ((v)->ob_type == &Dbmtype) - -static object *DbmError; - -static object * -newdbmobject(file, flags, mode) - char *file; - int flags; - int mode; -{ - dbmobject *dp; - - dp = NEWOBJ(dbmobject, &Dbmtype); - if (dp == NULL) - return NULL; - dp->di_size = -1; - if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) { - err_errno(DbmError); - DECREF(dp); - return NULL; - } - return (object *)dp; -} - -/* Methods */ - -static void -dbm_dealloc(dp) - register dbmobject *dp; -{ - if ( dp->di_dbm ) - dbm_close(dp->di_dbm); - DEL(dp); -} - -static int -dbm_length(dp) - dbmobject *dp; -{ - if ( dp->di_size < 0 ) { - datum key; - int size; - - size = 0; - for ( key=dbm_firstkey(dp->di_dbm); key.dptr; - key = dbm_nextkey(dp->di_dbm)) - size++; - dp->di_size = size; - } - return dp->di_size; -} - -static object * -dbm_subscript(dp, key) - dbmobject *dp; - register object *key; -{ - object *v; - datum drec, krec; - - if (!getargs(key, "s#", &krec.dptr, &krec.dsize) ) - return NULL; - - drec = dbm_fetch(dp->di_dbm, krec); - if ( drec.dptr == 0 ) { - err_setstr(KeyError, GETSTRINGVALUE((stringobject *)key)); - return NULL; - } - if ( dbm_error(dp->di_dbm) ) { - dbm_clearerr(dp->di_dbm); - err_setstr(DbmError, ""); - return NULL; - } - return newsizedstringobject(drec.dptr, drec.dsize); -} - -static int -dbm_ass_sub(dp, v, w) - dbmobject *dp; - object *v, *w; -{ - datum krec, drec; - - if ( !getargs(v, "s#", &krec.dptr, &krec.dsize) ) { - err_setstr(TypeError, "dbm mappings have string indices only"); - return -1; - } - dp->di_size = -1; - if (w == NULL) { - if ( dbm_delete(dp->di_dbm, krec) < 0 ) { - dbm_clearerr(dp->di_dbm); - err_setstr(KeyError, GETSTRINGVALUE((stringobject *)v)); - return -1; - } - } else { - if ( !getargs(w, "s#", &drec.dptr, &drec.dsize) ) { - err_setstr(TypeError, - "dbm mappings have string elements only"); - return -1; - } - if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) { - dbm_clearerr(dp->di_dbm); - err_setstr(DbmError, "Cannot add item to database"); - return -1; - } - } - if ( dbm_error(dp->di_dbm) ) { - dbm_clearerr(dp->di_dbm); - err_setstr(DbmError, ""); - return -1; - } - return 0; -} - -static mapping_methods dbm_as_mapping = { - (inquiry)dbm_length, /*mp_length*/ - (binaryfunc)dbm_subscript, /*mp_subscript*/ - (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/ -}; - -static object * -dbm__close(dp, args) - register dbmobject *dp; - object *args; -{ - if ( !getnoarg(args) ) - return NULL; - if ( dp->di_dbm ) - dbm_close(dp->di_dbm); - dp->di_dbm = NULL; - INCREF(None); - return None; -} - -static object * -dbm_keys(dp, args) - register dbmobject *dp; - object *args; -{ - register object *v, *item; - datum key; - int err; - - if (!getnoarg(args)) - return NULL; - v = newlistobject(0); - if (v == NULL) - return NULL; - for (key = dbm_firstkey(dp->di_dbm); key.dptr; - key = dbm_nextkey(dp->di_dbm)) { - item = newsizedstringobject(key.dptr, key.dsize); - if (item == NULL) { - DECREF(v); - return NULL; - } - err = addlistitem(v, item); - DECREF(item); - if (err != 0) { - DECREF(v); - return NULL; - } - } - return v; -} - -static object * -dbm_has_key(dp, args) - register dbmobject *dp; - object *args; -{ - datum key, val; - - if (!getargs(args, "s#", &key.dptr, &key.dsize)) - return NULL; - val = dbm_fetch(dp->di_dbm, key); - return newintobject(val.dptr != NULL); -} - -static struct methodlist dbm_methods[] = { - {"close", (method)dbm__close}, - {"keys", (method)dbm_keys}, - {"has_key", (method)dbm_has_key}, - {NULL, NULL} /* sentinel */ -}; - -static object * -dbm_getattr(dp, name) - dbmobject *dp; - char *name; -{ - return findmethod(dbm_methods, (object *)dp, name); -} - -static typeobject Dbmtype = { - OB_HEAD_INIT(&Typetype) - 0, - "dbm", - sizeof(dbmobject), - 0, - (destructor)dbm_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)dbm_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - &dbm_as_mapping, /*tp_as_mapping*/ -}; - -/* ----------------------------------------------------------------- */ - -static object * -dbmopen(self, args) - object *self; - object *args; -{ - char *name; - char *flags = "r"; - int iflags; - int mode = 0666; - - if ( !newgetargs(args, "s|si", &name, &flags, &mode) ) - return NULL; - if ( strcmp(flags, "r") == 0 ) - iflags = O_RDONLY; - else if ( strcmp(flags, "w") == 0 ) - iflags = O_RDWR; - else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */ - iflags = O_RDWR|O_CREAT; - else if ( strcmp(flags, "c") == 0 ) - iflags = O_RDWR|O_CREAT; - else if ( strcmp(flags, "n") == 0 ) - iflags = O_RDWR|O_CREAT|O_TRUNC; - else { - err_setstr(DbmError, - "Flags should be one of 'r', 'w', 'c' or 'n'"); - return NULL; - } - return newdbmobject(name, iflags, mode); -} - -static struct methodlist dbmmodule_methods[] = { - { "open", (method)dbmopen, 1 }, - { 0, 0 }, -}; - -void -initdbm() { - object *m, *d; - - m = initmodule("dbm", dbmmodule_methods); - d = getmoduledict(m); - DbmError = newstringobject("dbm.error"); - if ( DbmError == NULL || dictinsert(d, "error", DbmError) ) - fatal("can't define dbm.error"); -} diff --git a/Modules/dlmodule.c b/Modules/dlmodule.c deleted file mode 100644 index 1f1ce462b1..0000000000 --- a/Modules/dlmodule.c +++ /dev/null @@ -1,244 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* dl module */ - -#include "allobjects.h" -#include "modsupport.h" - -#include <dlfcn.h> - -#ifndef RTLD_LAZY -#define RTLD_LAZY 1 -#endif - -typedef struct { - OB_HEAD - ANY *dl_handle; -} dlobject; - -staticforward typeobject Dltype; - -static object *Dlerror; - -static object * -newdlobject(handle) - ANY *handle; -{ - dlobject *xp; - xp = NEWOBJ(dlobject, &Dltype); - if (xp == NULL) - return NULL; - xp->dl_handle = handle; - return (object *)xp; -} - -static void -dl_dealloc(xp) - dlobject *xp; -{ - if (xp->dl_handle != NULL) - dlclose(xp->dl_handle); - DEL(xp); -} - -static object * -dl_close(xp, args) - dlobject *xp; - object *args; -{ - if (!getargs(args, "")) - return NULL; - if (xp->dl_handle != NULL) { - dlclose(xp->dl_handle); - xp->dl_handle = NULL; - } - INCREF(None); - return None; -} - -static object * -dl_sym(xp, args) - dlobject *xp; - object *args; -{ - char *name; - ANY *func; - if (!getargs(args, "s", &name)) - return NULL; - func = dlsym(xp->dl_handle, name); - if (func == NULL) { - INCREF(None); - return None; - } - return newintobject((long)func); -} - -static object * -dl_call(xp, args) - dlobject *xp; - object *args; /* (varargs) */ -{ - object *name; - long (*func)(); - long alist[10]; - long res; - int i; - int n = gettuplesize(args); - if (n < 1) { - err_setstr(TypeError, "at least a name is needed"); - return NULL; - } - name = gettupleitem(args, 0); - if (!is_stringobject(name)) { - err_setstr(TypeError, "function name must be a string"); - return NULL; - } - func = dlsym(xp->dl_handle, getstringvalue(name)); - if (func == NULL) { - err_setstr(ValueError, dlerror()); - return NULL; - } - if (n-1 > 10) { - err_setstr(TypeError, "too many arguments (max 10)"); - return NULL; - } - for (i = 1; i < n; i++) { - object *v = gettupleitem(args, i); - if (is_intobject(v)) - alist[i-1] = getintvalue(v); - else if (is_stringobject(v)) - alist[i-1] = (long)getstringvalue(v); - else if (v == None) - alist[i-1] = (long) ((char *)NULL); - else { - err_setstr(TypeError, - "arguments must be int, string or None"); - return NULL; - } - } - for (; i <= 10; i++) - alist[i-1] = 0; - res = (*func)(alist[0], alist[1], alist[2], alist[3], alist[4], - alist[5], alist[6], alist[7], alist[8], alist[9]); - return newintobject(res); -} - -static struct methodlist dlobject_methods[] = { - {"call", (method)dl_call, 1 /* varargs */}, - {"sym", (method)dl_sym}, - {"close", (method)dl_close}, - {NULL, NULL} /* Sentinel */ -}; - -static object * -dl_getattr(xp, name) - dlobject *xp; - char *name; -{ - return findmethod(dlobject_methods, (object *)xp, name); -} - - -static typeobject Dltype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "dl", /*tp_name*/ - sizeof(dlobject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)dl_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)dl_getattr,/*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ -}; - -static object * -dl_open(self, args) - object *self; - object *args; -{ - char *name; - int mode; - ANY *handle; - if (getargs(args, "z", &name)) - mode = RTLD_LAZY; - else { - err_clear(); - if (!getargs(args, "(zi)", &name, &mode)) - return NULL; -#ifndef RTLD_NOW - if (mode != RTLD_LAZY) { - err_setstr(ValueError, "mode must be 1"); - return NULL; - } -#endif - } - handle = dlopen(name, mode); - if (handle == NULL) { - err_setstr(Dlerror, dlerror()); - return NULL; - } - return newdlobject(handle); -} - -static struct methodlist dl_methods[] = { - {"open", dl_open}, - {NULL, NULL} /* sentinel */ -}; - -void -initdl() -{ - object *m, *d, *x; - - if (sizeof(int) != sizeof(long) || - sizeof(long) != sizeof(char *)) - fatal( - "module dl requires sizeof(int) == sizeof(long) == sizeof(char*)"); - - /* Create the module and add the functions */ - m = initmodule("dl", dl_methods); - - /* Add some symbolic constants to the module */ - d = getmoduledict(m); - Dlerror = x = newstringobject("dl.error"); - dictinsert(d, "error", x); - x = newintobject((long)RTLD_LAZY); - dictinsert(d, "RTLD_LAZY", x); -#ifdef RTLD_NOW - x = newintobject((long)RTLD_NOW); - dictinsert(d, "RTLD_NOW", x); -#endif - - /* Check for errors */ - if (err_occurred()) - fatal("can't initialize module dl"); -} diff --git a/Modules/environment.c b/Modules/environment.c deleted file mode 100644 index 977e9172f4..0000000000 --- a/Modules/environment.c +++ /dev/null @@ -1,104 +0,0 @@ -/* -# Copyright 1995, InfoSeek Corporation -# All rights reserved. -# Written by Andy Bensky -# -# Permission to use, copy, modify, and distribute this Python software -# and its associated documentation for any purpose (subject to the -# restriction in the following sentence) without fee is hereby granted, -# provided that the above copyright notice appears in all copies, and -# that both that copyright notice and this permission notice appear in -# supporting documentation, and that the name of InfoSeek not be used in -# advertising or publicity pertaining to distribution of the software -# without specific, prior written permission. This permission is -# explicitly restricted to the copying and modification of the software -# to remain in Python, compiled Python, or other languages (such as C) -# wherein the modified or derived code is exclusively imported into a -# Python module. -# -# INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS -# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -# FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY -# DIRECT, 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, -# EVEN IF INFOSEEK SHALL HAVE BEEN MADE AWARE OF THE POSSIBILITY OF SUCH -# DAMAGES. -*/ - -/* Hooks to call the Unix putenv() to modify the environment -*/ - -#include "allobjects.h" -#include <stdlib.h> -#include <assert.h> -#include <string.h> - -/* Error conditions that can be raised */ - -/* Headers for functions accessible from Python as module methods */ -static object *put_environ( object *self, object *args ); - -static struct methodlist environ_methods[] = { - {"putenv", put_environ}, - {NULL, NULL} -}; - - -/* - * Name: initenvironment - * Description: - * Initialzation function that Python will use to establish callbacks to - * the methods of this module. - * - * Returns: - * void - - * - * Notes: - */ -void initenvironment() -{ - object *m, *d; - - m = initmodule("environment", environ_methods); - d = getmoduledict(m); -} - -/* - * Name: put_environ - * Description: - * accepts 2 string objects as arguments and forms a string of the - * form string1=string2 that can be passed to the putenv() system call. - * - * Returns: - * None object if successfull, otherwise raises a SystemError exception - * - * - * Notes: - */ -static object *put_environ( object *self, object *args ) -{ - char *string1, *string2; - char *set_str; - object *return_object = None; - - if (args && getargs(args, "(ss)", &string1, &string2)) - { - set_str = malloc(strlen(string1) + strlen(string2) + 2); - assert( set_str ); - (void) sprintf(set_str, "%s=%s", string1, string2); - if ( putenv( set_str ) ) - { - err_setstr(SystemError, "Error in system putenv call."); - return_object = 0; - } - } - else - { - err_setstr(TypeError, "Usage: putenv(string1, string2)"); - return_object = 0; - } - - return( return_object ); -} diff --git a/Modules/fcntlmodule.c b/Modules/fcntlmodule.c deleted file mode 100644 index d2efd60311..0000000000 --- a/Modules/fcntlmodule.c +++ /dev/null @@ -1,185 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* fcntl module */ - -#include "allobjects.h" -#include "modsupport.h" - - -/* fcntl(fd, opt, [arg]) */ - -static object * -fcntl_fcntl(self, args) - object *self; /* Not used */ - object *args; -{ - int fd; - int code; - int arg; - int ret; - char *str; - int len; - char buf[1024]; - - if (getargs(args, "(iis#)", &fd, &code, &str, &len)) { - if (len > sizeof buf) { - err_setstr(ValueError, "fcntl string arg too long"); - return NULL; - } - memcpy(buf, str, len); - BGN_SAVE - ret = fcntl(fd, code, buf); - END_SAVE - if (ret < 0) { - err_errno(IOError); - return NULL; - } - return newsizedstringobject(buf, len); - } - - err_clear(); - if (getargs(args, "(ii)", &fd, &code)) - arg = 0; - else { - err_clear(); - if (!getargs(args, "(iii)", &fd, &code, &arg)) - return NULL; - } - BGN_SAVE - ret = fcntl(fd, code, arg); - END_SAVE - if (ret < 0) { - err_errno(IOError); - return NULL; - } - return newintobject((long)ret); -} - - -/* ioctl(fd, opt, [arg]) */ - -static object * -fcntl_ioctl(self, args) - object *self; /* Not used */ - object *args; -{ - int fd; - int code; - int arg; - int ret; - char *str; - int len; - char buf[1024]; - - if (getargs(args, "(iis#)", &fd, &code, &str, &len)) { - if (len > sizeof buf) { - err_setstr(ValueError, "ioctl string arg too long"); - return NULL; - } - memcpy(buf, str, len); - BGN_SAVE - ret = ioctl(fd, code, buf); - END_SAVE - if (ret < 0) { - err_errno(IOError); - return NULL; - } - return newsizedstringobject(buf, len); - } - - err_clear(); - if (getargs(args, "(ii)", &fd, &code)) - arg = 0; - else { - err_clear(); - if (!getargs(args, "(iii)", &fd, &code, &arg)) - return NULL; - } - BGN_SAVE - ret = ioctl(fd, code, arg); - END_SAVE - if (ret < 0) { - err_errno(IOError); - return NULL; - } - return newintobject((long)ret); -} - - -/* flock(fd, operation) */ - -static object * -fcntl_flock(self, args) - object *self; /* Not used */ - object *args; -{ - int fd; - int code; - int ret; - FILE *f; - - if (!getargs(args, "(ii)", &fd, &code)) - return NULL; - - BGN_SAVE - ret = flock(fd, code); - END_SAVE - if (ret < 0) { - err_errno(IOError); - return NULL; - } - INCREF(None); - return None; -} - - - -/* List of functions */ - -static struct methodlist fcntl_methods[] = { - {"fcntl", fcntl_fcntl}, - {"ioctl", fcntl_ioctl}, - {"flock", fcntl_flock}, - {NULL, NULL} /* sentinel */ -}; - - -/* Module initialisation */ - -void -initfcntl() -{ - object *m, *d; - - /* Create the module and add the functions */ - m = initmodule("fcntl", fcntl_methods); - - /* Add some symbolic constants to the module */ - d = getmoduledict(m); - - /* Check for errors */ - if (err_occurred()) - fatal("can't initialize module fcntl"); -} diff --git a/Modules/flmodule.c b/Modules/flmodule.c deleted file mode 100644 index f1dc634442..0000000000 --- a/Modules/flmodule.c +++ /dev/null @@ -1,2535 +0,0 @@ -/********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* FL module -- interface to Mark Overmars' FORMS Library. */ - -/* This code works with FORMS version 2.2a. - FORMS can be ftp'ed from ftp.cs.ruu.nl (131.211.80.17), directory - /pub/SGI/FORMS. */ - -/* A half-hearted attempt has been made to allow programs using this - * module to exploit parallelism (through the threads module). No provisions - * have been made for multiple threads to use this module at the same time, - * though. So, a program with a forms thread and a non-forms thread will work - * fine but a program with two threads using forms will probably crash (unless - * the program takes precaution to ensure that only one thread can be in - * this module at any time). This will have to be fixed some time. - * (A fix will probably also have to synchronise with the gl module). - */ - -#include "forms.h" - -#include "allobjects.h" -#include "import.h" -#include "modsupport.h" -#include "structmember.h" -#include "ceval.h" - -/* Generic Forms Objects */ - -typedef struct { - OB_HEAD - FL_OBJECT *ob_generic; - struct methodlist *ob_methods; - object *ob_callback; - object *ob_callback_arg; -} genericobject; - -staticforward typeobject GenericObjecttype; - -#define is_genericobject(g) ((g)->ob_type == &GenericObjecttype) - -/* List of all objects (XXX this should be a hash table on address...) */ - -static object *allgenerics = NULL; -static int nfreeslots = 0; - -/* Add an object to the list of known objects */ - -static void -knowgeneric(g) - genericobject *g; -{ - int i, n; - /* Create the list if it doesn't already exist */ - if (allgenerics == NULL) { - allgenerics = newlistobject(0); - if (allgenerics == NULL) { - err_clear(); - return; /* Too bad, live without allgenerics... */ - } - } - if (nfreeslots > 0) { - /* Search the list for reusable slots (NULL items) */ - /* XXX This can be made faster! */ - n = getlistsize(allgenerics); - for (i = 0; i < n; i++) { - if (getlistitem(allgenerics, i) == NULL) { - INCREF(g); - setlistitem(allgenerics, i, (object *)g); - nfreeslots--; - return; - } - } - /* Strange... no free slots found... */ - nfreeslots = 0; - } - /* No free entries, append new item to the end */ - addlistitem(allgenerics, (object *)g); -} - -/* Find an object in the list of known objects */ - -static genericobject * -findgeneric(generic) - FL_OBJECT *generic; -{ - int i, n; - genericobject *g; - - if (allgenerics == NULL) - return NULL; /* No objects known yet */ - n = getlistsize(allgenerics); - for (i = 0; i < n; i++) { - g = (genericobject *)getlistitem(allgenerics, i); - if (g != NULL && g->ob_generic == generic) - return g; - } - return NULL; /* Unknown object */ -} - -/* Remove an object from the list of known objects */ - -static void -forgetgeneric(g) - genericobject *g; -{ - int i, n; - - XDECREF(g->ob_callback); - g->ob_callback = NULL; - XDECREF(g->ob_callback_arg); - g->ob_callback_arg = NULL; - if (allgenerics == NULL) - return; /* No objects known yet */ - n = getlistsize(allgenerics); - for (i = 0; i < n; i++) { - if (g == (genericobject *)getlistitem(allgenerics, i)) { - setlistitem(allgenerics, i, (object *)NULL); - nfreeslots++; - break; - } - } -} - -/* Called when a form is about to be freed -- - remove all the objects that we know about from it. */ - -static void -releaseobjects(form) - FL_FORM *form; -{ - int i, n; - genericobject *g; - - if (allgenerics == NULL) - return; /* No objects known yet */ - n = getlistsize(allgenerics); - for (i = 0; i < n; i++) { - g = (genericobject *)getlistitem(allgenerics, i); - if (g != NULL && g->ob_generic->form == form) { - fl_delete_object(g->ob_generic); - /* The object is now unreachable for - do_forms and check_forms, so - delete it from the list of known objects */ - XDECREF(g->ob_callback); - g->ob_callback = NULL; - XDECREF(g->ob_callback_arg); - g->ob_callback_arg = NULL; - setlistitem(allgenerics, i, (object *)NULL); - nfreeslots++; - } - } -} - - -/* Methods of generic objects */ - -static object * -generic_set_call_back(g, args) - genericobject *g; - object *args; -{ - if (args == NULL) { - XDECREF(g->ob_callback); - XDECREF(g->ob_callback_arg); - g->ob_callback = NULL; - g->ob_callback_arg = NULL; - } - else { - if (!is_tupleobject(args) || gettuplesize(args) != 2) { - err_badarg(); - return NULL; - } - XDECREF(g->ob_callback); - XDECREF(g->ob_callback_arg); - g->ob_callback = gettupleitem(args, 0); - INCREF(g->ob_callback); - g->ob_callback_arg = gettupleitem(args, 1); - INCREF(g->ob_callback_arg); - } - INCREF(None); - return None; -} - -static object * -generic_call(g, args, func) - genericobject *g; - object *args; - void (*func)(FL_OBJECT *); -{ - if (!getnoarg(args)) - return NULL; - (*func)(g->ob_generic); - INCREF(None); - return None; -} - -static object * -generic_delete_object(g, args) - genericobject *g; - object *args; -{ - object *res; - res = generic_call(g, args, fl_delete_object); - if (res != NULL) - forgetgeneric(g); - return res; -} - -static object * -generic_show_object(g, args) - genericobject *g; - object *args; -{ - return generic_call(g, args, fl_show_object); -} - -static object * -generic_hide_object(g, args) - genericobject *g; - object *args; -{ - return generic_call(g, args, fl_hide_object); -} - -static object * -generic_redraw_object(g, args) - genericobject *g; - object *args; -{ - return generic_call(g, args, fl_redraw_object); -} - -static object * -generic_freeze_object(g, args) - genericobject *g; - object *args; -{ - return generic_call(g, args, fl_freeze_object); -} - -static object * -generic_unfreeze_object(g, args) - genericobject *g; - object *args; -{ - return generic_call(g, args, fl_unfreeze_object); -} - -static object * -generic_activate_object(g, args) - genericobject *g; - object *args; -{ - return generic_call(g, args, fl_activate_object); -} - -static object * -generic_deactivate_object(g, args) - genericobject *g; - object *args; -{ - return generic_call(g, args, fl_deactivate_object); -} - -static object * -generic_set_object_shortcut(g, args) - genericobject *g; - object *args; -{ - char *str; - if (!getargs(args, "s", &str)) - return NULL; - fl_set_object_shortcut(g->ob_generic, str); - INCREF(None); - return None; -} - -static struct methodlist generic_methods[] = { - {"set_call_back", (method)generic_set_call_back}, - {"delete_object", (method)generic_delete_object}, - {"show_object", (method)generic_show_object}, - {"hide_object", (method)generic_hide_object}, - {"redraw_object", (method)generic_redraw_object}, - {"freeze_object", (method)generic_freeze_object}, - {"unfreeze_object", (method)generic_unfreeze_object}, - {"activate_object", (method)generic_activate_object}, - {"deactivate_object", (method)generic_deactivate_object}, - {"set_object_shortcut", (method)generic_set_object_shortcut}, - {NULL, NULL} /* sentinel */ -}; - -static void -generic_dealloc(g) - genericobject *g; -{ - fl_free_object(g->ob_generic); - XDECREF(g->ob_callback); - XDECREF(g->ob_callback_arg); - DEL(g); -} - -#define OFF(x) offsetof(FL_OBJECT, x) - -static struct memberlist generic_memberlist[] = { - {"objclass", T_INT, OFF(objclass), RO}, - {"type", T_INT, OFF(type), RO}, - {"boxtype", T_INT, OFF(boxtype)}, - {"x", T_FLOAT, OFF(x)}, - {"y", T_FLOAT, OFF(y)}, - {"w", T_FLOAT, OFF(w)}, - {"h", T_FLOAT, OFF(h)}, - {"col1", T_INT, OFF(col1)}, - {"col2", T_INT, OFF(col2)}, - {"align", T_INT, OFF(align)}, - {"lcol", T_INT, OFF(lcol)}, - {"lsize", T_FLOAT, OFF(lsize)}, - /* "label" is treated specially! */ - {"lstyle", T_INT, OFF(lstyle)}, - {"pushed", T_INT, OFF(pushed), RO}, - {"focus", T_INT, OFF(focus), RO}, - {"belowmouse", T_INT, OFF(belowmouse),RO}, -/* {"frozen", T_INT, OFF(frozen), RO}, */ - {"active", T_INT, OFF(active)}, - {"input", T_INT, OFF(input)}, - {"visible", T_INT, OFF(visible), RO}, - {"radio", T_INT, OFF(radio)}, - {"automatic", T_INT, OFF(automatic)}, - {NULL} /* Sentinel */ -}; - -#undef OFF - -static object * -generic_getattr(g, name) - genericobject *g; - char *name; -{ - object *meth; - - /* XXX Ought to special-case name "__methods__" */ - if (g-> ob_methods) { - meth = findmethod(g->ob_methods, (object *)g, name); - if (meth != NULL) return meth; - err_clear(); - } - - meth = findmethod(generic_methods, (object *)g, name); - if (meth != NULL) - return meth; - err_clear(); - - /* "label" is an exception, getmember only works for char pointers, - not for char arrays */ - if (strcmp(name, "label") == 0) - return newstringobject(g->ob_generic->label); - - return getmember((char *)g->ob_generic, generic_memberlist, name); -} - -static int -generic_setattr(g, name, v) - genericobject *g; - char *name; - object *v; -{ - int ret; - - if (v == NULL) { - err_setstr(TypeError, "can't delete forms object attributes"); - return -1; - } - - /* "label" is an exception: setmember doesn't set strings; - and FORMS wants you to call a function to set the label */ - if (strcmp(name, "label") == 0) { - if (!is_stringobject(v)) { - err_setstr(TypeError, "label attr must be string"); - return -1; - } - fl_set_object_label(g->ob_generic, getstringvalue(v)); - return 0; - } - - ret = setmember((char *)g->ob_generic, generic_memberlist, name, v); - - /* Rather than calling all the various set_object_* functions, - we call fl_redraw_object here. This is sometimes redundant - but I doubt that's a big problem */ - if (ret == 0) - fl_redraw_object(g->ob_generic); - - return ret; -} - -static object * -generic_repr(g) - genericobject *g; -{ - char buf[100]; - sprintf(buf, "<FORMS_object at %lx, objclass=%d>", - (long)g, g->ob_generic->objclass); - return newstringobject(buf); -} - -static typeobject GenericObjecttype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "FORMS_object", /*tp_name*/ - sizeof(genericobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)generic_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)generic_getattr, /*tp_getattr*/ - (setattrfunc)generic_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - (reprfunc)generic_repr, /*tp_repr*/ -}; - -static object * -newgenericobject(generic, methods) - FL_OBJECT *generic; - struct methodlist *methods; -{ - genericobject *g; - g = NEWOBJ(genericobject, &GenericObjecttype); - if (g == NULL) - return NULL; - g-> ob_generic = generic; - g->ob_methods = methods; - g->ob_callback = NULL; - g->ob_callback_arg = NULL; - knowgeneric(g); - return (object *)g; -} - -/**********************************************************************/ -/* Some common calling sequences */ - -/* void func (object, float) */ -static object * -call_forms_INf (func, obj, args) - void (*func)(FL_OBJECT *, float); - FL_OBJECT *obj; - object *args; -{ - float parameter; - - if (!getargs(args, "f", &parameter)) return NULL; - - (*func) (obj, parameter); - - INCREF(None); - return None; -} - -/* void func (object, float) */ -static object * -call_forms_INfINf (func, obj, args) - void (*func)(FL_OBJECT *, float, float); - FL_OBJECT *obj; - object *args; -{ - float par1, par2; - - if (!getargs(args, "(ff)", &par1, &par2)) return NULL; - - (*func) (obj, par1, par2); - - INCREF(None); - return None; -} - -/* void func (object, int) */ -static object * -call_forms_INi (func, obj, args) - void (*func)(FL_OBJECT *, int); - FL_OBJECT *obj; - object *args; -{ - int parameter; - - if (!getintarg(args, &parameter)) return NULL; - - (*func) (obj, parameter); - - INCREF(None); - return None; -} - -/* void func (object, char) */ -static object * -call_forms_INc (func, obj, args) - void (*func)(FL_OBJECT *, int); - FL_OBJECT *obj; - object *args; -{ - char *a; - - if (!getstrarg(args, &a)) return NULL; - - (*func) (obj, a[0]); - - INCREF(None); - return None; -} - -/* void func (object, string) */ -static object * -call_forms_INstr (func, obj, args) - void (*func)(FL_OBJECT *, char *); - FL_OBJECT *obj; - object *args; -{ - char *a; - - if (!getstrarg(args, &a)) return NULL; - - (*func) (obj, a); - - INCREF(None); - return None; -} - - -/* void func (object, int, string) */ -static object * -call_forms_INiINstr (func, obj, args) - void (*func)(FL_OBJECT *, int, char *); - FL_OBJECT *obj; - object *args; -{ - char *b; - int a; - - if (!getargs(args, "(is)", &a, &b)) return NULL; - - (*func) (obj, a, b); - - INCREF(None); - return None; -} - -#ifdef UNUSED -/* void func (object, int, int) */ -static object * -call_forms_INiINi (func, obj, args) - void (*func)(FL_OBJECT *, int, int); - FL_OBJECT *obj; - object *args; -{ - int par1, par2; - - if (!getargs(args, "(ii)", &par1, &par2)) return NULL; - - (*func) (obj, par1, par2); - - INCREF(None); - return None; -} -#endif - -/* int func (object) */ -static object * -call_forms_Ri (func, obj, args) - int (*func)(FL_OBJECT *); - FL_OBJECT *obj; - object *args; -{ - int retval; - - if (!getnoarg(args)) return NULL; - - retval = (*func) (obj); - - return newintobject ((long) retval); -} - -/* char * func (object) */ -static object * -call_forms_Rstr (func, obj, args) - char * (*func)(FL_OBJECT *); - FL_OBJECT *obj; - object *args; -{ - char *str; - - if (!getnoarg(args)) return NULL; - - str = (*func) (obj); - - if (str == NULL) { - INCREF(None); - return None; - } - return newstringobject (str); -} - -/* int func (object) */ -static object * -call_forms_Rf (func, obj, args) - float (*func)(FL_OBJECT *); - FL_OBJECT *obj; - object *args; -{ - float retval; - - if (!getnoarg(args)) return NULL; - - retval = (*func) (obj); - - return newfloatobject (retval); -} - -static object * -call_forms_OUTfOUTf (func, obj, args) - void (*func)(FL_OBJECT *, float *, float *); - FL_OBJECT *obj; - object *args; -{ - float f1, f2; - - if (!getnoarg(args)) return NULL; - - (*func) (obj, &f1, &f2); - - return mkvalue("(ff)", f1, f2); -} - -#ifdef UNUSED -static object * -call_forms_OUTf (func, obj, args) - void (*func)(FL_OBJECT *, float *); - FL_OBJECT *obj; - object *args; -{ - float f; - - if (!getnoarg(args)) return NULL; - - (*func) (obj, &f); - - return newfloatobject (f); -} -#endif - -/**********************************************************************/ -/* Class : browser */ - -static object * -set_browser_topline(g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_set_browser_topline, g-> ob_generic, args); -} - -static object * -clear_browser(g, args) - genericobject *g; - object *args; -{ - return generic_call (g, args, fl_clear_browser); -} - -static object * -add_browser_line (g, args) - genericobject *g; - object *args; -{ - return call_forms_INstr (fl_add_browser_line, g-> ob_generic, args); -} - -static object * -addto_browser (g, args) - genericobject *g; - object *args; -{ - return call_forms_INstr (fl_addto_browser, g-> ob_generic, args); -} - -static object * -insert_browser_line (g, args) - genericobject *g; - object *args; -{ - return call_forms_INiINstr (fl_insert_browser_line, - g-> ob_generic, args); -} - -static object * -delete_browser_line (g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_delete_browser_line, g-> ob_generic, args); -} - -static object * -replace_browser_line (g, args) - genericobject *g; - object *args; -{ - return call_forms_INiINstr (fl_replace_browser_line, - g-> ob_generic, args); -} - -static object * -get_browser_line(g, args) - genericobject *g; - object *args; -{ - int i; - char *str; - - if (!getintarg(args, &i)) - return NULL; - - str = fl_get_browser_line (g->ob_generic, i); - - if (str == NULL) { - INCREF(None); - return None; - } - return newstringobject (str); -} - -static object * -load_browser (g, args) - genericobject *g; - object *args; -{ - /* XXX strictly speaking this is wrong since fl_load_browser - XXX returns int, not void */ - return call_forms_INstr (fl_load_browser, g-> ob_generic, args); -} - -static object * -get_browser_maxline(g, args) - genericobject *g; - object *args; -{ - return call_forms_Ri (fl_get_browser_maxline, g-> ob_generic, args); -} - -static object * -select_browser_line (g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_select_browser_line, g-> ob_generic, args); -} - -static object * -deselect_browser_line (g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_deselect_browser_line, g-> ob_generic, args); -} - -static object * -deselect_browser (g, args) - genericobject *g; - object *args; -{ - return generic_call (g, args, fl_deselect_browser); -} - -static object * -isselected_browser_line (g, args) - genericobject *g; - object *args; -{ - int i, j; - - if (!getintarg(args, &i)) - return NULL; - - j = fl_isselected_browser_line (g->ob_generic, i); - - return newintobject (j); -} - -static object * -get_browser (g, args) - genericobject *g; - object *args; -{ - return call_forms_Ri (fl_get_browser, g-> ob_generic, args); -} - -static object * -set_browser_fontsize (g, args) - genericobject *g; - object *args; -{ - return call_forms_INf (fl_set_browser_fontsize, g-> ob_generic, args); -} - -static object * -set_browser_fontstyle (g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_set_browser_fontstyle, g-> ob_generic, args); -} - -static object * -set_browser_specialkey (g, args) - genericobject *g; - object *args; -{ - return call_forms_INc(fl_set_browser_specialkey, g-> ob_generic, args); -} - -static struct methodlist browser_methods[] = { - {"set_browser_topline", (method)set_browser_topline}, - {"clear_browser", (method)clear_browser}, - {"add_browser_line", (method)add_browser_line}, - {"addto_browser", (method)addto_browser}, - {"insert_browser_line", (method)insert_browser_line}, - {"delete_browser_line", (method)delete_browser_line}, - {"replace_browser_line", (method)replace_browser_line}, - {"get_browser_line", (method)get_browser_line}, - {"load_browser", (method)load_browser}, - {"get_browser_maxline", (method)get_browser_maxline}, - {"select_browser_line", (method)select_browser_line}, - {"deselect_browser_line", (method)deselect_browser_line}, - {"deselect_browser", (method)deselect_browser}, - {"isselected_browser_line", (method)isselected_browser_line}, - {"get_browser", (method)get_browser}, - {"set_browser_fontsize", (method)set_browser_fontsize}, - {"set_browser_fontstyle", (method)set_browser_fontstyle}, - {"set_browser_specialkey", (method)set_browser_specialkey}, - {NULL, NULL} /* sentinel */ -}; - -/* Class: button */ - -static object * -set_button(g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_set_button, g-> ob_generic, args); -} - -static object * -get_button(g, args) - genericobject *g; - object *args; -{ - return call_forms_Ri (fl_get_button, g-> ob_generic, args); -} - -static object * -get_button_numb(g, args) - genericobject *g; - object *args; -{ - return call_forms_Ri (fl_get_button_numb, g-> ob_generic, args); -} - -static object * -set_button_shortcut(g, args) - genericobject *g; - object *args; -{ - return call_forms_INstr (fl_set_button_shortcut, g-> ob_generic, args); -} - -static struct methodlist button_methods[] = { - {"set_button", (method)set_button}, - {"get_button", (method)get_button}, - {"get_button_numb", (method)get_button_numb}, - {"set_button_shortcut", (method)set_button_shortcut}, - {NULL, NULL} /* sentinel */ -}; - -/* Class: choice */ - -static object * -set_choice(g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_set_choice, g-> ob_generic, args); -} - -static object * -get_choice(g, args) - genericobject *g; - object *args; -{ - return call_forms_Ri (fl_get_choice, g-> ob_generic, args); -} - -static object * -clear_choice (g, args) - genericobject *g; - object *args; -{ - return generic_call (g, args, fl_clear_choice); -} - -static object * -addto_choice (g, args) - genericobject *g; - object *args; -{ - return call_forms_INstr (fl_addto_choice, g-> ob_generic, args); -} - -static object * -replace_choice (g, args) - genericobject *g; - object *args; -{ - return call_forms_INiINstr (fl_replace_choice, g-> ob_generic, args); -} - -static object * -delete_choice (g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_delete_choice, g-> ob_generic, args); -} - -static object * -get_choice_text (g, args) - genericobject *g; - object *args; -{ - return call_forms_Rstr (fl_get_choice_text, g-> ob_generic, args); -} - -static object * -set_choice_fontsize (g, args) - genericobject *g; - object *args; -{ - return call_forms_INf (fl_set_choice_fontsize, g-> ob_generic, args); -} - -static object * -set_choice_fontstyle (g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_set_choice_fontstyle, g-> ob_generic, args); -} - -static struct methodlist choice_methods[] = { - {"set_choice", (method)set_choice}, - {"get_choice", (method)get_choice}, - {"clear_choice", (method)clear_choice}, - {"addto_choice", (method)addto_choice}, - {"replace_choice", (method)replace_choice}, - {"delete_choice", (method)delete_choice}, - {"get_choice_text", (method)get_choice_text}, - {"set_choice_fontsize", (method)set_choice_fontsize}, - {"set_choice_fontstyle",(method)set_choice_fontstyle}, - {NULL, NULL} /* sentinel */ -}; - -/* Class : Clock */ - -static object * -get_clock(g, args) - genericobject *g; - object *args; -{ - int i0, i1, i2; - - if (!getnoarg(args)) - return NULL; - - fl_get_clock (g->ob_generic, &i0, &i1, &i2); - - return mkvalue("(iii)", i0, i1, i2); -} - -static struct methodlist clock_methods[] = { - {"get_clock", (method)get_clock}, - {NULL, NULL} /* sentinel */ -}; - -/* CLass : Counters */ - -static object * -get_counter_value(g, args) - genericobject *g; - object *args; -{ - return call_forms_Rf (fl_get_counter_value, g-> ob_generic, args); -} - -static object * -set_counter_value (g, args) - genericobject *g; - object *args; -{ - return call_forms_INf (fl_set_counter_value, g-> ob_generic, args); -} - -static object * -set_counter_precision (g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_set_counter_precision, g-> ob_generic, args); -} - -static object * -set_counter_bounds (g, args) - genericobject *g; - object *args; -{ - return call_forms_INfINf (fl_set_counter_bounds, g-> ob_generic, args); -} - -static object * -set_counter_step (g, args) - genericobject *g; - object *args; -{ - return call_forms_INfINf (fl_set_counter_step, g-> ob_generic, args); -} - -static object * -set_counter_return (g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_set_counter_return, g-> ob_generic, args); -} - -static struct methodlist counter_methods[] = { - {"set_counter_value", (method)set_counter_value}, - {"get_counter_value", (method)get_counter_value}, - {"set_counter_bounds", (method)set_counter_bounds}, - {"set_counter_step", (method)set_counter_step}, - {"set_counter_precision", (method)set_counter_precision}, - {"set_counter_return", (method)set_counter_return}, - {NULL, NULL} /* sentinel */ -}; - - -/* Class: Dials */ - -static object * -get_dial_value(g, args) - genericobject *g; - object *args; -{ - return call_forms_Rf (fl_get_dial_value, g-> ob_generic, args); -} - -static object * -set_dial_value (g, args) - genericobject *g; - object *args; -{ - return call_forms_INf (fl_set_dial_value, g-> ob_generic, args); -} - -static object * -set_dial_bounds (g, args) - genericobject *g; - object *args; -{ - return call_forms_INfINf (fl_set_dial_bounds, g-> ob_generic, args); -} - -static object * -get_dial_bounds (g, args) - genericobject *g; - object *args; -{ - return call_forms_OUTfOUTf (fl_get_dial_bounds, g-> ob_generic, args); -} - -static object * -set_dial_step (g, args) - genericobject *g; - object *args; -{ - return call_forms_INf (fl_set_dial_step, g-> ob_generic, args); -} - -static struct methodlist dial_methods[] = { - {"set_dial_value", (method)set_dial_value}, - {"get_dial_value", (method)get_dial_value}, - {"set_dial_bounds", (method)set_dial_bounds}, - {"get_dial_bounds", (method)get_dial_bounds}, - {"set_dial_step", (method)set_dial_step}, - {NULL, NULL} /* sentinel */ -}; - -/* Class : Input */ - -static object * -set_input (g, args) - genericobject *g; - object *args; -{ - return call_forms_INstr (fl_set_input, g-> ob_generic, args); -} - -static object * -get_input (g, args) - genericobject *g; - object *args; -{ - return call_forms_Rstr (fl_get_input, g-> ob_generic, args); -} - -static object * -set_input_color (g, args) - genericobject *g; - object *args; -{ - return call_forms_INfINf (fl_set_input_color, g-> ob_generic, args); -} - -static object * -set_input_return (g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_set_input_return, g-> ob_generic, args); -} - -static struct methodlist input_methods[] = { - {"set_input", (method)set_input}, - {"get_input", (method)get_input}, - {"set_input_color", (method)set_input_color}, - {"set_input_return", (method)set_input_return}, - {NULL, NULL} /* sentinel */ -}; - - -/* Class : Menu */ - -static object * -set_menu (g, args) - genericobject *g; - object *args; -{ - return call_forms_INstr (fl_set_menu, g-> ob_generic, args); -} - -static object * -get_menu (g, args) - genericobject *g; - object *args; -{ - /* XXX strictly speaking this is wrong since fl_get_menu - XXX returns long, not int */ - return call_forms_Ri (fl_get_menu, g-> ob_generic, args); -} - -static object * -get_menu_text (g, args) - genericobject *g; - object *args; -{ - return call_forms_Rstr (fl_get_menu_text, g-> ob_generic, args); -} - -static object * -addto_menu (g, args) - genericobject *g; - object *args; -{ - return call_forms_INstr (fl_addto_menu, g-> ob_generic, args); -} - -static struct methodlist menu_methods[] = { - {"set_menu", (method)set_menu}, - {"get_menu", (method)get_menu}, - {"get_menu_text", (method)get_menu_text}, - {"addto_menu", (method)addto_menu}, - {NULL, NULL} /* sentinel */ -}; - - -/* Class: Sliders */ - -static object * -get_slider_value(g, args) - genericobject *g; - object *args; -{ - return call_forms_Rf (fl_get_slider_value, g-> ob_generic, args); -} - -static object * -set_slider_value (g, args) - genericobject *g; - object *args; -{ - return call_forms_INf (fl_set_slider_value, g-> ob_generic, args); -} - -static object * -set_slider_bounds (g, args) - genericobject *g; - object *args; -{ - return call_forms_INfINf (fl_set_slider_bounds, g-> ob_generic, args); -} - -static object * -get_slider_bounds (g, args) - genericobject *g; - object *args; -{ - return call_forms_OUTfOUTf(fl_get_slider_bounds, g-> ob_generic, args); -} - -static object * -set_slider_return (g, args) - genericobject *g; - object *args; -{ - return call_forms_INf (fl_set_slider_return, g-> ob_generic, args); -} - -static object * -set_slider_size (g, args) - genericobject *g; - object *args; -{ - return call_forms_INf (fl_set_slider_size, g-> ob_generic, args); -} - -static object * -set_slider_precision (g, args) - genericobject *g; - object *args; -{ - return call_forms_INi (fl_set_slider_precision, g-> ob_generic, args); -} - -static object * -set_slider_step (g, args) - genericobject *g; - object *args; -{ - return call_forms_INf (fl_set_slider_step, g-> ob_generic, args); -} - - -static struct methodlist slider_methods[] = { - {"set_slider_value", (method)set_slider_value}, - {"get_slider_value", (method)get_slider_value}, - {"set_slider_bounds", (method)set_slider_bounds}, - {"get_slider_bounds", (method)get_slider_bounds}, - {"set_slider_return", (method)set_slider_return}, - {"set_slider_size", (method)set_slider_size}, - {"set_slider_precision",(method)set_slider_precision}, - {"set_slider_step", (method)set_slider_step}, - {NULL, NULL} /* sentinel */ -}; - -static object * -set_positioner_xvalue (g, args) - genericobject *g; - object *args; -{ - return call_forms_INf (fl_set_positioner_xvalue, g-> ob_generic, args); -} - -static object * -set_positioner_xbounds (g, args) - genericobject *g; - object *args; -{ - return call_forms_INfINf (fl_set_positioner_xbounds, - g-> ob_generic, args); -} - -static object * -set_positioner_yvalue (g, args) - genericobject *g; - object *args; -{ - return call_forms_INf (fl_set_positioner_yvalue, g-> ob_generic, args); -} - -static object * -set_positioner_ybounds (g, args) - genericobject *g; - object *args; -{ - return call_forms_INfINf (fl_set_positioner_ybounds, - g-> ob_generic, args); -} - -static object * -get_positioner_xvalue (g, args) - genericobject *g; - object *args; -{ - return call_forms_Rf (fl_get_positioner_xvalue, g-> ob_generic, args); -} - -static object * -get_positioner_xbounds (g, args) - genericobject *g; - object *args; -{ - return call_forms_OUTfOUTf (fl_get_positioner_xbounds, - g-> ob_generic, args); -} - -static object * -get_positioner_yvalue (g, args) - genericobject *g; - object *args; -{ - return call_forms_Rf (fl_get_positioner_yvalue, g-> ob_generic, args); -} - -static object * -get_positioner_ybounds (g, args) - genericobject *g; - object *args; -{ - return call_forms_OUTfOUTf (fl_get_positioner_ybounds, - g-> ob_generic, args); -} - -static struct methodlist positioner_methods[] = { - {"set_positioner_xvalue", (method)set_positioner_xvalue}, - {"set_positioner_yvalue", (method)set_positioner_yvalue}, - {"set_positioner_xbounds", (method)set_positioner_xbounds}, - {"set_positioner_ybounds", (method)set_positioner_ybounds}, - {"get_positioner_xvalue", (method)get_positioner_xvalue}, - {"get_positioner_yvalue", (method)get_positioner_yvalue}, - {"get_positioner_xbounds", (method)get_positioner_xbounds}, - {"get_positioner_ybounds", (method)get_positioner_ybounds}, - {NULL, NULL} /* sentinel */ -}; - -/* Class timer */ - -static object * -set_timer (g, args) - genericobject *g; - object *args; -{ - return call_forms_INf (fl_set_timer, g-> ob_generic, args); -} - -static object * -get_timer (g, args) - genericobject *g; - object *args; -{ - return call_forms_Rf (fl_get_timer, g-> ob_generic, args); -} - -static struct methodlist timer_methods[] = { - {"set_timer", (method)set_timer}, - {"get_timer", (method)get_timer}, - {NULL, NULL} /* sentinel */ -}; - -/* Form objects */ - -typedef struct { - OB_HEAD - FL_FORM *ob_form; -} formobject; - -staticforward typeobject Formtype; - -#define is_formobject(v) ((v)->ob_type == &Formtype) - -static object * -form_show_form(f, args) - formobject *f; - object *args; -{ - int place, border; - char *name; - if (!getargs(args, "(iis)", &place, &border, &name)) - return NULL; - fl_show_form(f->ob_form, place, border, name); - INCREF(None); - return None; -} - -static object * -form_call(func, f, args) - FL_FORM *f; - object *args; - void (*func)(FL_FORM *); -{ - if (!getnoarg(args)) return NULL; - - (*func)(f); - - INCREF(None); - return None; -} - -static object * -form_call_INiINi(func, f, args) - FL_FORM *f; - object *args; - void (*func)(FL_FORM *, int, int); -{ - int a, b; - - if (!getargs(args, "(ii)", &a, &b)) return NULL; - - (*func)(f, a, b); - - INCREF(None); - return None; -} - -static object * -form_call_INfINf(func, f, args) - FL_FORM *f; - object *args; - void (*func)(FL_FORM *, float, float); -{ - float a, b; - - if (!getargs(args, "(ff)", &a, &b)) return NULL; - - (*func)(f, a, b); - - INCREF(None); - return None; -} - -static object * -form_hide_form(f, args) - formobject *f; - object *args; -{ - return form_call(fl_hide_form, f-> ob_form, args); -} - -static object * -form_redraw_form(f, args) - formobject *f; - object *args; -{ - return form_call(fl_redraw_form, f-> ob_form, args); -} - -static object * -form_add_object(f, args) - formobject *f; - object *args; -{ - genericobject *g; - if (args == NULL || !is_genericobject(args)) { - err_badarg(); - return NULL; - } - g = (genericobject *)args; - if (findgeneric(g->ob_generic) != NULL) { - err_setstr(RuntimeError, - "add_object of object already in a form"); - return NULL; - } - fl_add_object(f->ob_form, g->ob_generic); - knowgeneric(g); - - INCREF(None); - return None; -} - -static object * -form_set_form_position(f, args) - formobject *f; - object *args; -{ - return form_call_INiINi(fl_set_form_position, f-> ob_form, args); -} - -static object * -form_set_form_size(f, args) - formobject *f; - object *args; -{ - return form_call_INiINi(fl_set_form_size, f-> ob_form, args); -} - -static object * -form_scale_form(f, args) - formobject *f; - object *args; -{ - return form_call_INfINf(fl_scale_form, f-> ob_form, args); -} - -static object * -generic_add_object(f, args, func, internal_methods) - formobject *f; - object *args; - FL_OBJECT *(*func)(int, float, float, float, float, char*); - struct methodlist *internal_methods; -{ - int type; - float x, y, w, h; - char *name; - FL_OBJECT *obj; - - if (!getargs(args,"(iffffs)", &type,&x,&y,&w,&h,&name)) - return NULL; - - fl_addto_form (f-> ob_form); - - obj = (*func) (type, x, y, w, h, name); - - fl_end_form(); - - if (obj == NULL) { - err_nomem(); - return NULL; - } - - return newgenericobject (obj, internal_methods); -} - -static object * -form_add_button(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_button, button_methods); -} - -static object * -form_add_lightbutton(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_lightbutton, button_methods); -} - -static object * -form_add_roundbutton(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_roundbutton, button_methods); -} - -static object * -form_add_menu (f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_menu, menu_methods); -} - -static object * -form_add_slider(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_slider, slider_methods); -} - -static object * -form_add_valslider(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_valslider, slider_methods); -} - -static object * -form_add_dial(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_dial, dial_methods); -} - -static object * -form_add_counter(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_counter, counter_methods); -} - -static object * -form_add_clock(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_clock, clock_methods); -} - -static object * -form_add_box(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_box, - (struct methodlist *)NULL); -} - -static object * -form_add_choice(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_choice, choice_methods); -} - -static object * -form_add_browser(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_browser, browser_methods); -} - -static object * -form_add_positioner(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_positioner, positioner_methods); -} - -static object * -form_add_input(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_input, input_methods); -} - -static object * -form_add_text(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_text, - (struct methodlist *)NULL); -} - -static object * -form_add_timer(f, args) - formobject *f; - object *args; -{ - return generic_add_object(f, args, fl_add_timer, timer_methods); -} - -static object * -form_freeze_form(f, args) - formobject *f; - object *args; -{ - return form_call(fl_freeze_form, f-> ob_form, args); -} - -static object * -form_unfreeze_form(f, args) - formobject *f; - object *args; -{ - return form_call(fl_unfreeze_form, f-> ob_form, args); -} - -static object * -form_activate_form(f, args) - formobject *f; - object *args; -{ - return form_call(fl_activate_form, f-> ob_form, args); -} - -static object * -form_deactivate_form(f, args) - formobject *f; - object *args; -{ - return form_call(fl_deactivate_form, f-> ob_form, args); -} - -static object * -form_bgn_group(f, args) - formobject *f; - object *args; -{ - FL_OBJECT *obj; - - fl_addto_form(f-> ob_form); - obj = fl_bgn_group(); - fl_end_form(); - - if (obj == NULL) { - err_nomem(); - return NULL; - } - - return newgenericobject (obj, (struct methodlist *) NULL); -} - -static object * -form_end_group(f, args) - formobject *f; - object *args; -{ - fl_addto_form(f-> ob_form); - fl_end_group(); - fl_end_form(); - INCREF(None); - return None; -} - -static object * -forms_find_first_or_last(func, f, args) - FL_OBJECT *(*func)(FL_FORM *, int, float, float); - formobject *f; - object *args; -{ - int type; - float mx, my; - FL_OBJECT *generic; - genericobject *g; - - if (!getargs(args, "(iff)", &type, &mx, &my)) return NULL; - - generic = (*func) (f-> ob_form, type, mx, my); - - if (generic == NULL) - { - INCREF(None); - return None; - } - - g = findgeneric(generic); - if (g == NULL) { - err_setstr(RuntimeError, - "forms_find_{first|last} returns unknown object"); - return NULL; - } - INCREF(g); - return (object *) g; -} - -static object * -form_find_first(f, args) - formobject *f; - object *args; -{ - return forms_find_first_or_last(fl_find_first, f, args); -} - -static object * -form_find_last(f, args) - formobject *f; - object *args; -{ - return forms_find_first_or_last(fl_find_last, f, args); -} - -static object * -form_set_object_focus(f, args) - formobject *f; - object *args; -{ - genericobject *g; - if (args == NULL || !is_genericobject(args)) { - err_badarg(); - return NULL; - } - g = (genericobject *)args; - fl_set_object_focus(f->ob_form, g->ob_generic); - INCREF(None); - return None; -} - -static struct methodlist form_methods[] = { -/* adm */ - {"show_form", (method)form_show_form}, - {"hide_form", (method)form_hide_form}, - {"redraw_form", (method)form_redraw_form}, - {"set_form_position", (method)form_set_form_position}, - {"set_form_size", (method)form_set_form_size}, - {"scale_form", (method)form_scale_form}, - {"freeze_form", (method)form_freeze_form}, - {"unfreeze_form", (method)form_unfreeze_form}, - {"activate_form", (method)form_activate_form}, - {"deactivate_form", (method)form_deactivate_form}, - {"bgn_group", (method)form_bgn_group}, - {"end_group", (method)form_end_group}, - {"find_first", (method)form_find_first}, - {"find_last", (method)form_find_last}, - {"set_object_focus", (method)form_set_object_focus}, - -/* basic objects */ - {"add_button", (method)form_add_button}, -/* {"add_bitmap", (method)form_add_bitmap}, */ - {"add_lightbutton", (method)form_add_lightbutton}, - {"add_roundbutton", (method)form_add_roundbutton}, - {"add_menu", (method)form_add_menu}, - {"add_slider", (method)form_add_slider}, - {"add_positioner", (method)form_add_positioner}, - {"add_valslider", (method)form_add_valslider}, - {"add_dial", (method)form_add_dial}, - {"add_counter", (method)form_add_counter}, - {"add_box", (method)form_add_box}, - {"add_clock", (method)form_add_clock}, - {"add_choice", (method)form_add_choice}, - {"add_browser", (method)form_add_browser}, - {"add_input", (method)form_add_input}, - {"add_timer", (method)form_add_timer}, - {"add_text", (method)form_add_text}, - {NULL, NULL} /* sentinel */ -}; - -static void -form_dealloc(f) - formobject *f; -{ - releaseobjects(f->ob_form); - if (f->ob_form->visible) - fl_hide_form(f->ob_form); - fl_free_form(f->ob_form); - DEL(f); -} - -#define OFF(x) offsetof(FL_FORM, x) - -static struct memberlist form_memberlist[] = { - {"window", T_LONG, OFF(window), RO}, - {"w", T_FLOAT, OFF(w)}, - {"h", T_FLOAT, OFF(h)}, - {"x", T_FLOAT, OFF(x), RO}, - {"y", T_FLOAT, OFF(y), RO}, - {"deactivated", T_INT, OFF(deactivated)}, - {"visible", T_INT, OFF(visible), RO}, - {"frozen", T_INT, OFF(frozen), RO}, - {"doublebuf", T_INT, OFF(doublebuf)}, - {NULL} /* Sentinel */ -}; - -#undef OFF - -static object * -form_getattr(f, name) - formobject *f; - char *name; -{ - object *meth; - - meth = findmethod(form_methods, (object *)f, name); - if (meth != NULL) - return meth; - err_clear(); - return getmember((char *)f->ob_form, form_memberlist, name); -} - -static int -form_setattr(f, name, v) - formobject *f; - char *name; - object *v; -{ - int ret; - - if (v == NULL) { - err_setstr(TypeError, "can't delete form attributes"); - return 0; - } - - return setmember((char *)f->ob_form, form_memberlist, name, v); -} - -static object * -form_repr(f) - formobject *f; -{ - char buf[100]; - sprintf(buf, "<FORMS_form at %lx, window=%ld>", - (long)f, f->ob_form->window); - return newstringobject(buf); -} - -static typeobject Formtype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "FORMS_form", /*tp_name*/ - sizeof(formobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)form_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)form_getattr, /*tp_getattr*/ - (setattrfunc)form_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - (reprfunc)form_repr, /*tp_repr*/ -}; - -static object * -newformobject(form) - FL_FORM *form; -{ - formobject *f; - f = NEWOBJ(formobject, &Formtype); - if (f == NULL) - return NULL; - f->ob_form = form; - return (object *)f; -} - - -/* The "fl" module */ - -static object * -forms_make_form(dummy, args) - object *dummy; - object *args; -{ - int type; - float w, h; - FL_FORM *form; - if (!getargs(args, "(iff)", &type, &w, &h)) - return NULL; - form = fl_bgn_form(type, w, h); - if (form == NULL) { - /* XXX Actually, cannot happen! */ - err_nomem(); - return NULL; - } - fl_end_form(); - return newformobject(form); -} - -static object * -forms_activate_all_forms(f, args) - object *f; - object *args; -{ - fl_activate_all_forms(); - INCREF(None); - return None; -} - -static object * -forms_deactivate_all_forms(f, args) - object *f; - object *args; -{ - fl_deactivate_all_forms(); - INCREF(None); - return None; -} - -static object *my_event_callback = NULL; - -static object * -forms_set_event_call_back(dummy, args) - object *dummy; - object *args; -{ - if (args == None) - args = NULL; - my_event_callback = args; - XINCREF(args); - INCREF(None); - return None; -} - -static object * -forms_do_or_check_forms(dummy, args, func) - object *dummy; - object *args; - FL_OBJECT *(*func)(); -{ - FL_OBJECT *generic; - genericobject *g; - object *arg, *res; - - if (!getnoarg(args)) - return NULL; - - for (;;) { - BGN_SAVE - generic = (*func)(); - END_SAVE - if (generic == NULL) { - INCREF(None); - return None; - } - if (generic == FL_EVENT) { - int dev; - short val; - if (my_event_callback == NULL) - return newintobject(-1L); - dev = fl_qread(&val); - arg = mkvalue("(ih)", dev, val); - if (arg == NULL) - return NULL; - res = call_object(my_event_callback, arg); - XDECREF(res); - DECREF(arg); - if (res == NULL) - return NULL; /* Callback raised exception */ - continue; - } - g = findgeneric(generic); - if (g == NULL) { - /* Object not known to us (some dialogs cause this) */ - continue; /* Ignore it */ - } - if (g->ob_callback == NULL) { - INCREF(g); - return ((object *) g); - } - arg = mkvalue("(OO)", (object *)g, g->ob_callback_arg); - if (arg == NULL) - return NULL; - res = call_object(g->ob_callback, arg); - XDECREF(res); - DECREF(arg); - if (res == NULL) - return NULL; /* Callback raised exception */ - } -} - -static object * -forms_do_forms(dummy, args) - object *dummy; - object *args; -{ - return forms_do_or_check_forms(dummy, args, fl_do_forms); -} - -static object * -forms_check_forms(dummy, args) - object *dummy; - object *args; -{ - return forms_do_or_check_forms(dummy, args, fl_check_forms); -} - -static object * -forms_do_only_forms(dummy, args) - object *dummy; - object *args; -{ - return forms_do_or_check_forms(dummy, args, fl_do_only_forms); -} - -static object * -forms_check_only_forms(dummy, args) - object *dummy; - object *args; -{ - return forms_do_or_check_forms(dummy, args, fl_check_only_forms); -} - -#ifdef UNUSED -static object * -fl_call(func, args) - object *args; - void (*func)(); -{ - if (!getnoarg(args)) - return NULL; - (*func)(); - INCREF(None); - return None; -} -#endif - -static object * -forms_set_graphics_mode(dummy, args) - object *dummy; - object *args; -{ - int rgbmode, doublebuf; - - if (!getargs(args, "(ii)", &rgbmode, &doublebuf)) - return NULL; - fl_set_graphics_mode(rgbmode,doublebuf); - INCREF(None); - return None; -} - -static object * -forms_get_rgbmode(dummy, args) - object *dummy; - object *args; -{ - extern int fl_rgbmode; - - if (args != NULL) { - err_badarg(); - return NULL; - } - return newintobject((long)fl_rgbmode); -} - -static object * -forms_show_errors(dummy, args) - object *dummy; - object *args; -{ - int show; - if (!getargs(args, "i", &show)) - return NULL; - fl_show_errors(show); - INCREF(None); - return None; -} - -static object * -forms_set_font_name(dummy, args) - object *dummy; - object *args; -{ - int numb; - char *name; - if (!getargs(args, "(is)", &numb, &name)) - return NULL; - fl_set_font_name(numb, name); - INCREF(None); - return None; -} - - -static object * -forms_qdevice(self, args) - object *self; - object *args; -{ - short arg1; - if (!getargs(args, "h", &arg1)) - return NULL; - fl_qdevice(arg1); - INCREF(None); - return None; -} - -static object * -forms_unqdevice(self, args) - object *self; - object *args; -{ - short arg1; - if (!getargs(args, "h", &arg1)) - return NULL; - fl_unqdevice(arg1); - INCREF(None); - return None; -} - -static object * -forms_isqueued(self, args) - object *self; - object *args; -{ - long retval; - short arg1; - if (!getargs(args, "h", &arg1)) - return NULL; - retval = fl_isqueued(arg1); - - return newintobject(retval); -} - -static object * -forms_qtest(self, args) - object *self; - object *args; -{ - long retval; - retval = fl_qtest(); - return newintobject(retval); -} - - -static object * -forms_qread(self, args) - object *self; - object *args; -{ - int dev; - short val; - BGN_SAVE - dev = fl_qread(&val); - END_SAVE - return mkvalue("(ih)", dev, val); -} - -static object * -forms_qreset(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) return NULL; - - fl_qreset(); - INCREF(None); - return None; -} - -static object * -forms_qenter(self, args) - object *self; - object *args; -{ - short arg1, arg2; - if (!getargs(args, "(hh)", &arg1, &arg2)) - return NULL; - fl_qenter(arg1, arg2); - INCREF(None); - return None; -} - -static object * -forms_color(self, args) - object *self; - object *args; -{ - int arg; - - if (!getintarg(args, &arg)) return NULL; - - fl_color((short) arg); - - INCREF(None); - return None; -} - -static object * -forms_mapcolor(self, args) - object *self; - object *args; -{ - int arg0, arg1, arg2, arg3; - - if (!getargs(args, "(iiii)", &arg0, &arg1, &arg2, &arg3)) - return NULL; - - fl_mapcolor(arg0, (short) arg1, (short) arg2, (short) arg3); - - INCREF(None); - return None; -} - -static object * -forms_getmcolor(self, args) - object *self; - object *args; -{ - int arg; - short r, g, b; - - if (!getintarg(args, &arg)) return NULL; - - fl_getmcolor(arg, &r, &g, &b); - - return mkvalue("(hhh)", r, g, b); -} - -static object * -forms_get_mouse(self, args) - object *self; - object *args; -{ - float x, y; - - if (!getnoarg(args)) return NULL; - - fl_get_mouse(&x, &y); - - return mkvalue("(ff)", x, y); -} - -static object * -forms_tie(self, args) - object *self; - object *args; -{ - short arg1, arg2, arg3; - if (!getargs(args, "(hhh)", &arg1, &arg2, &arg3)) - return NULL; - fl_tie(arg1, arg2, arg3); - INCREF(None); - return None; -} - -static object * -forms_show_message(f, args) - object *f; - object *args; -{ - char *a, *b, *c; - - if (!getargs(args, "(sss)", &a, &b, &c)) return NULL; - - BGN_SAVE - fl_show_message(a, b, c); - END_SAVE - - INCREF(None); - return None; -} - -static object * -forms_show_choice(f, args) - object *f; - object *args; -{ - char *m1, *m2, *m3, *b1, *b2, *b3; - int nb; - char *format; - long rv; - - if (args == NULL || !is_tupleobject(args)) { - err_badarg(); - return NULL; - } - nb = gettuplesize(args) - 3; - if (nb <= 0) { - err_setstr(TypeError, "need at least one button label"); - return NULL; - } - if (is_intobject(gettupleitem(args, 3))) { - err_setstr(TypeError, - "'number-of-buttons' argument not needed"); - return NULL; - } - switch (nb) { - case 1: format = "(ssss)"; break; - case 2: format = "(sssss)"; break; - case 3: format = "(ssssss)"; break; - default: - err_setstr(TypeError, "too many button labels"); - return NULL; - } - - if (!getargs(args, format, &m1, &m2, &m3, &b1, &b2, &b3)) - return NULL; - - BGN_SAVE - rv = fl_show_choice(m1, m2, m3, nb, b1, b2, b3); - END_SAVE - return newintobject(rv); -} - -static object * -forms_show_question(f, args) - object *f; - object *args; -{ - int ret; - char *a, *b, *c; - - if (!getargs(args, "(sss)", &a, &b, &c)) return NULL; - - BGN_SAVE - ret = fl_show_question(a, b, c); - END_SAVE - - return newintobject((long) ret); -} - -static object * -forms_show_input(f, args) - object *f; - object *args; -{ - char *str; - char *a, *b; - - if (!getargs(args, "(ss)", &a, &b)) return NULL; - - BGN_SAVE - str = fl_show_input(a, b); - END_SAVE - - if (str == NULL) { - INCREF(None); - return None; - } - return newstringobject(str); -} - -static object * -forms_file_selector(f, args) - object *f; - object *args; -{ - char *str; - char *a, *b, *c, *d; - - if (!getargs(args, "(ssss)", &a, &b, &c, &d)) return NULL; - - BGN_SAVE - str = fl_show_file_selector(a, b, c, d); - END_SAVE - - if (str == NULL) { - INCREF(None); - return None; - } - return newstringobject(str); -} - - -static object * -forms_file_selector_func(args, func) - object *args; - char *(*func)(); -{ - char *str; - - str = (*func) (); - - if (str == NULL) { - INCREF(None); - return None; - } - return newstringobject(str); -} - -static object * -forms_get_directory(f, args) - object *f; - object *args; -{ - return forms_file_selector_func(args, fl_get_directory); -} - -static object * -forms_get_pattern(f, args) - object *f; - object *args; -{ - return forms_file_selector_func(args, fl_get_pattern); -} - -static object * -forms_get_filename(f, args) - object *f; - object *args; -{ - return forms_file_selector_func(args, fl_get_filename); -} - -static struct methodlist forms_methods[] = { -/* adm */ - {"make_form", forms_make_form}, - {"activate_all_forms", forms_activate_all_forms}, - {"deactivate_all_forms",forms_deactivate_all_forms}, -/* gl support wrappers */ - {"qdevice", forms_qdevice}, - {"unqdevice", forms_unqdevice}, - {"isqueued", forms_isqueued}, - {"qtest", forms_qtest}, - {"qread", forms_qread}, -/* {"blkqread", forms_blkqread}, */ - {"qreset", forms_qreset}, - {"qenter", forms_qenter}, - {"get_mouse", forms_get_mouse}, - {"tie", forms_tie}, -/* {"new_events", forms_new_events}, */ - {"color", forms_color}, - {"mapcolor", forms_mapcolor}, - {"getmcolor", forms_getmcolor}, -/* interaction */ - {"do_forms", forms_do_forms}, - {"do_only_forms", forms_do_only_forms}, - {"check_forms", forms_check_forms}, - {"check_only_forms", forms_check_only_forms}, - {"set_event_call_back", forms_set_event_call_back}, -/* goodies */ - {"show_message", forms_show_message}, - {"show_question", forms_show_question}, - {"show_choice", forms_show_choice}, - {"show_input", forms_show_input}, - {"show_file_selector", forms_file_selector}, - {"file_selector", forms_file_selector}, /* BW compat */ - {"get_directory", forms_get_directory}, - {"get_pattern", forms_get_pattern}, - {"get_filename", forms_get_filename}, - {"set_graphics_mode", forms_set_graphics_mode}, - {"get_rgbmode", forms_get_rgbmode}, - {"show_errors", forms_show_errors}, - {"set_font_name", forms_set_font_name}, - {NULL, NULL} /* sentinel */ -}; - -void -initfl() -{ - initmodule("fl", forms_methods); - foreground(); - fl_init(); -} diff --git a/Modules/fmmodule.c b/Modules/fmmodule.c deleted file mode 100644 index 5fa78bd306..0000000000 --- a/Modules/fmmodule.c +++ /dev/null @@ -1,326 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Font Manager module */ - -#include "allobjects.h" - -#include "modsupport.h" - -#include <gl.h> -#include <device.h> -#include <fmclient.h> - - -/* Font Handle object implementation */ - -typedef struct { - OB_HEAD - fmfonthandle fh_fh; -} fhobject; - -staticforward typeobject Fhtype; - -#define is_fhobject(v) ((v)->ob_type == &Fhtype) - -static object * -newfhobject(fh) - fmfonthandle fh; -{ - fhobject *fhp; - if (fh == NULL) { - err_setstr(RuntimeError, "error creating new font handle"); - return NULL; - } - fhp = NEWOBJ(fhobject, &Fhtype); - if (fhp == NULL) - return NULL; - fhp->fh_fh = fh; - return (object *)fhp; -} - -/* Font Handle methods */ - -static object * -fh_scalefont(self, args) - fhobject *self; - object *args; -{ - double size; - if (!getargs(args, "d", &size)) - return NULL; - return newfhobject(fmscalefont(self->fh_fh, size)); -} - -/* XXX fmmakefont */ - -static object * -fh_setfont(self, args) - fhobject *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - fmsetfont(self->fh_fh); - INCREF(None); - return None; -} - -static object * -fh_getfontname(self, args) - fhobject *self; - object *args; -{ - char fontname[256]; - int len; - if (!getnoarg(args)) - return NULL; - len = fmgetfontname(self->fh_fh, sizeof fontname, fontname); - if (len < 0) { - err_setstr(RuntimeError, "error in fmgetfontname"); - return NULL; - } - return newsizedstringobject(fontname, len); -} - -static object * -fh_getcomment(self, args) - fhobject *self; - object *args; -{ - char comment[256]; - int len; - if (!getnoarg(args)) - return NULL; - len = fmgetcomment(self->fh_fh, sizeof comment, comment); - if (len < 0) { - err_setstr(RuntimeError, "error in fmgetcomment"); - return NULL; - } - return newsizedstringobject(comment, len); -} - -static object * -fh_getfontinfo(self, args) - fhobject *self; - object *args; -{ - fmfontinfo info; - object *v; - if (!getnoarg(args)) - return NULL; - if (fmgetfontinfo(self->fh_fh, &info) < 0) { - err_setstr(RuntimeError, "error in fmgetfontinfo"); - return NULL; - } - return mkvalue("(llllllll)", - info.printermatched, - info.fixed_width, - info.xorig, - info.yorig, - info.xsize, - info.ysize, - info.height, - info.nglyphs); -} - -#if 0 -static object * -fh_getwholemetrics(self, args) - fhobject *self; - object *args; -{ -} -#endif - -static object * -fh_getstrwidth(self, args) - fhobject *self; - object *args; -{ - char *str; - if (!getstrarg(args, &str)) - return NULL; - return newintobject(fmgetstrwidth(self->fh_fh, str)); -} - -static struct methodlist fh_methods[] = { - {"scalefont", (method)fh_scalefont}, - {"setfont", (method)fh_setfont}, - {"getfontname", (method)fh_getfontname}, - {"getcomment", (method)fh_getcomment}, - {"getfontinfo", (method)fh_getfontinfo}, -#if 0 - {"getwholemetrics", (method)fh_getwholemetrics}, -#endif - {"getstrwidth", (method)fh_getstrwidth}, - {NULL, NULL} /* sentinel */ -}; - -static object * -fh_getattr(fhp, name) - fhobject *fhp; - char *name; -{ - return findmethod(fh_methods, (object *)fhp, name); -} - -static void -fh_dealloc(fhp) - fhobject *fhp; -{ - fmfreefont(fhp->fh_fh); - DEL(fhp); -} - -static typeobject Fhtype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "font handle", /*tp_name*/ - sizeof(fhobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)fh_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)fh_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - - -/* Font Manager functions */ - -static object * -fm_init(self, args) - object *self, *args; -{ - if (!getnoarg(args)) - return NULL; - fminit(); - INCREF(None); - return None; -} - -static object * -fm_findfont(self, args) - object *self, *args; -{ - char *str; - if (!getstrarg(args, &str)) - return NULL; - return newfhobject(fmfindfont(str)); -} - -static object * -fm_prstr(self, args) - object *self, *args; -{ - char *str; - if (!getstrarg(args, &str)) - return NULL; - fmprstr(str); - INCREF(None); - return None; -} - -/* XXX This uses a global variable as temporary! Not re-entrant! */ - -static object *fontlist; - -static void -clientproc(fontname) - char *fontname; -{ - int err; - object *v; - if (fontlist == NULL) - return; - v = newstringobject(fontname); - if (v == NULL) - err = -1; - else { - err = addlistitem(fontlist, v); - DECREF(v); - } - if (err != 0) { - DECREF(fontlist); - fontlist = NULL; - } -} - -static object * -fm_enumerate(self, args) - object *self, *args; -{ - object *res; - if (!getnoarg(args)) - return NULL; - fontlist = newlistobject(0); - if (fontlist == NULL) - return NULL; - fmenumerate(clientproc); - res = fontlist; - fontlist = NULL; - return res; -} - -static object * -fm_setpath(self, args) - object *self, *args; -{ - char *str; - if (!getstrarg(args, &str)) - return NULL; - fmsetpath(str); - INCREF(None); - return None; -} - -static object * -fm_fontpath(self, args) - object *self, *args; -{ - if (!getnoarg(args)) - return NULL; - return newstringobject(fmfontpath()); -} - -static struct methodlist fm_methods[] = { - {"init", fm_init}, - {"findfont", fm_findfont}, - {"enumerate", fm_enumerate}, - {"prstr", fm_prstr}, - {"setpath", fm_setpath}, - {"fontpath", fm_fontpath}, - {NULL, NULL} /* sentinel */ -}; - - -void -initfm() -{ - initmodule("fm", fm_methods); - fminit(); -} diff --git a/Modules/gdbmmodule.c b/Modules/gdbmmodule.c deleted file mode 100644 index ecfd31eee6..0000000000 --- a/Modules/gdbmmodule.c +++ /dev/null @@ -1,382 +0,0 @@ -/* GDBM module, hacked from the still-breathing corpse of the - DBM module by anthony.baxter@aaii.oz.au. Original copyright - follows: -*/ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* DBM module using dictionary interface */ - - -#include "allobjects.h" -#include "modsupport.h" - -#include <sys/types.h> -#include <sys/stat.h> -#include <fcntl.h> -#include "gdbm.h" - -typedef struct { - OB_HEAD - int di_size; /* -1 means recompute */ - GDBM_FILE di_dbm; -} dbmobject; - -staticforward typeobject Dbmtype; - -#define is_dbmobject(v) ((v)->ob_type == &Dbmtype) - -static object *DbmError; - -static object * -newdbmobject(file, flags, mode) - char *file; - int flags; - int mode; -{ - dbmobject *dp; - - dp = NEWOBJ(dbmobject, &Dbmtype); - if (dp == NULL) - return NULL; - dp->di_size = -1; - errno = 0; - if ( (dp->di_dbm = gdbm_open(file, 0, flags, mode, NULL)) == 0 ) { - if (errno != 0) - err_errno(DbmError); - else - err_setstr(DbmError, (char *) gdbm_strerror(gdbm_errno)); - DECREF(dp); - return NULL; - } - return (object *)dp; -} - -/* Methods */ - -static void -dbm_dealloc(dp) - register dbmobject *dp; -{ - if ( dp->di_dbm ) - gdbm_close(dp->di_dbm); - DEL(dp); -} - -static int -dbm_length(dp) - dbmobject *dp; -{ - if ( dp->di_size < 0 ) { - datum key,okey; - int size; - okey.dsize=0; - - size = 0; - for ( key=gdbm_firstkey(dp->di_dbm); key.dptr; - key = gdbm_nextkey(dp->di_dbm,okey)) { - size++; - if(okey.dsize) free(okey.dptr); - okey=key; - } - dp->di_size = size; - } - return dp->di_size; -} - -static object * -dbm_subscript(dp, key) - dbmobject *dp; - register object *key; -{ - object *v; - datum drec, krec; - - if (!getargs(key, "s#", &krec.dptr, &krec.dsize) ) - return NULL; - - drec = gdbm_fetch(dp->di_dbm, krec); - if ( drec.dptr == 0 ) { - err_setstr(KeyError, GETSTRINGVALUE((stringobject *)key)); - return NULL; - } - v = newsizedstringobject(drec.dptr, drec.dsize); - free(drec.dptr); - return v; -} - -static int -dbm_ass_sub(dp, v, w) - dbmobject *dp; - object *v, *w; -{ - datum krec, drec; - - if ( !getargs(v, "s#", &krec.dptr, &krec.dsize) ) { - err_setstr(TypeError, "gdbm mappings have string indices only"); - return -1; - } - dp->di_size = -1; - if (w == NULL) { - if ( gdbm_delete(dp->di_dbm, krec) < 0 ) { - err_setstr(KeyError, GETSTRINGVALUE((stringobject *)v)); - return -1; - } - } else { - if ( !getargs(w, "s#", &drec.dptr, &drec.dsize) ) { - err_setstr(TypeError, - "gdbm mappings have string elements only"); - return -1; - } - errno = 0; - if ( gdbm_store(dp->di_dbm, krec, drec, GDBM_REPLACE) < 0 ) { - if (errno != 0) - err_errno(DbmError); - else - err_setstr(DbmError, (char *) gdbm_strerror(gdbm_errno)); - return -1; - } - } - return 0; -} - -static mapping_methods dbm_as_mapping = { - (inquiry)dbm_length, /*mp_length*/ - (binaryfunc)dbm_subscript, /*mp_subscript*/ - (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/ -}; - -static object * -dbm_close(dp, args) - register dbmobject *dp; - object *args; -{ - if ( !getnoarg(args) ) - return NULL; - if ( dp->di_dbm ) - gdbm_close(dp->di_dbm); - dp->di_dbm = NULL; - INCREF(None); - return None; -} - -static object * -dbm_keys(dp, args) - register dbmobject *dp; - object *args; -{ - register object *v, *item; - datum key, okey={ (char *)NULL, 0}; - int err; - - if (dp == NULL || !is_dbmobject(dp)) { - err_badcall(); - return NULL; - } - if (!getnoarg(args)) - return NULL; - v = newlistobject(0); - if (v == NULL) - return NULL; - for (key = gdbm_firstkey(dp->di_dbm); key.dptr; - key = gdbm_nextkey(dp->di_dbm,okey) ) { - item = newsizedstringobject(key.dptr, key.dsize); - if (item == 0) { - DECREF(v); - return NULL; - } - err = addlistitem(v, item); - DECREF(item); - if(okey.dsize) free(okey.dptr); - if (err != 0) { - DECREF(v); - return NULL; - } - okey=key; - } - return v; -} - - -static object * -dbm_has_key(dp, args) - register dbmobject *dp; - object *args; -{ - datum key; - - if (!getargs(args, "s#", &key.dptr, &key.dsize)) - return NULL; - return newintobject((long) gdbm_exists(dp->di_dbm, key)); -} - -static object * -dbm_firstkey(dp, args) - register dbmobject *dp; - object *args; -{ - register object *v; - datum key; - - if (!getnoarg(args)) - return NULL; - key = gdbm_firstkey(dp->di_dbm); - if (key.dptr) { - v = newsizedstringobject(key.dptr, key.dsize); - free(key.dptr); - return v; - } else { - INCREF(None); - return None; - } -} - -static object * -dbm_nextkey(dp, args) - register dbmobject *dp; - object *args; -{ - register object *v; - datum key, nextkey; - - if (!getargs(args, "s#", &key.dptr, &key.dsize)) - return NULL; - nextkey = gdbm_nextkey(dp->di_dbm, key); - if (nextkey.dptr) { - v = newsizedstringobject(nextkey.dptr, nextkey.dsize); - free(nextkey.dptr); - return v; - } else { - INCREF(None); - return None; - } -} - -static object * -dbm_reorganize(dp, args) - register dbmobject *dp; - object *args; -{ - if (!getnoarg(args)) - return NULL; - errno = 0; - if (gdbm_reorganize(dp->di_dbm) < 0) { - if (errno != 0) - err_errno(DbmError); - else - err_setstr(DbmError, (char *) gdbm_strerror(gdbm_errno)); - return NULL; - } - INCREF(None); - return None; -} - -static struct methodlist dbm_methods[] = { - {"close", (method)dbm_close}, - {"keys", (method)dbm_keys}, - {"has_key", (method)dbm_has_key}, - {"firstkey", (method)dbm_firstkey}, - {"nextkey", (method)dbm_nextkey}, - {"reorganize", (method)dbm_reorganize}, - {NULL, NULL} /* sentinel */ -}; - -static object * -dbm_getattr(dp, name) - dbmobject *dp; - char *name; -{ - return findmethod(dbm_methods, (object *)dp, name); -} - -static typeobject Dbmtype = { - OB_HEAD_INIT(&Typetype) - 0, - "gdbm", - sizeof(dbmobject), - 0, - (destructor)dbm_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)dbm_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - &dbm_as_mapping, /*tp_as_mapping*/ -}; - -/* ----------------------------------------------------------------- */ - -static object * -dbmopen(self, args) - object *self; - object *args; -{ - char *name; - char *flags = "r "; - int iflags; - int mode = 0666; - -/* XXXX add other flags. 2nd character can be "f" meaning open in fast mode. */ - if ( !newgetargs(args, "s|si", &name, &flags, &mode) ) - return NULL; - switch (flags[0]) { - case 'r': - iflags = GDBM_READER; - break; - case 'w': - iflags = GDBM_WRITER; - break; - case 'c': - iflags = GDBM_WRCREAT; - break; - case 'n': - iflags = GDBM_NEWDB; - break; - default: - err_setstr(DbmError, - "Flags should be one of 'r', 'w', 'c' or 'n'"); - return NULL; - } - if (flags[1] == 'f') - iflags |= GDBM_FAST; - return newdbmobject(name, iflags, mode); -} - -static struct methodlist dbmmodule_methods[] = { - { "open", (method)dbmopen, 1 }, - { 0, 0 }, -}; - -void -initgdbm() { - object *m, *d; - - m = initmodule("gdbm", dbmmodule_methods); - d = getmoduledict(m); - DbmError = newstringobject("gdbm.error"); - if ( DbmError == NULL || dictinsert(d, "error", DbmError) ) - fatal("can't define gdbm.error"); -} diff --git a/Modules/getpath.c b/Modules/getpath.c deleted file mode 100644 index 4f49cc3a1f..0000000000 --- a/Modules/getpath.c +++ /dev/null @@ -1,67 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Return the initial module search path. */ - -#include "Python.h" -#include "osdefs.h" - - -#ifndef PYTHONPATH -#define PYTHONPATH ".:/usr/local/lib/python" -#endif - - -/* This is called once from pythonrun to initialize sys.path. The - environment variable PYTHONPATH is fetched and the default path - appended. The default path may be passed to the preprocessor; if - not, a hardcoded default is used, which only makes (some) sense on - Unix. */ - -char * -Py_GetPath() -{ - char *path = getenv("PYTHONPATH"); - char *defpath = PYTHONPATH; - static char *buf = NULL; - char *p; - int n; - - if (path == NULL) - path = ""; - n = strlen(path) + strlen(defpath) + 2; - if (buf != NULL) { - free(buf); - buf = NULL; - } - buf = malloc(n); - if (buf == NULL) - Py_FatalError("not enough memory to copy module search path"); - strcpy(buf, path); - p = buf + strlen(buf); - if (p != buf) - *p++ = DELIM; - strcpy(p, defpath); - return buf; -} diff --git a/Modules/grpmodule.c b/Modules/grpmodule.c deleted file mode 100644 index cff9d83f35..0000000000 --- a/Modules/grpmodule.c +++ /dev/null @@ -1,124 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* UNIX group file access module */ - -#include "allobjects.h" -#include "modsupport.h" - -#include <sys/types.h> -#include <grp.h> - -static object *mkgrent(p) - struct group *p; -{ - object *v, *w; - char **member; - if ((w = newlistobject(0)) == NULL) { - return NULL; - } - for (member = p->gr_mem; *member != NULL; member++) { - object *x = newstringobject(*member); - if (x == NULL || addlistitem(w, x) != 0) { - XDECREF(x); - DECREF(w); - return NULL; - } - } - v = mkvalue("(sslO)", - p->gr_name, - p->gr_passwd, -#if defined(NeXT) && defined(_POSIX_SOURCE) && defined(__LITTLE_ENDIAN__) -/* Correct a bug present on Intel machines in NextStep 3.2 and 3.3; - for later versions you may have to remove this */ - (long)p->gr_short_pad, /* ugh-NeXT broke the padding */ -#else - (long)p->gr_gid, -#endif - w); - DECREF(w); - return v; -} - -static object *grp_getgrgid(self, args) - object *self, *args; -{ - int gid; - struct group *p; - if (!getintarg(args, &gid)) - return NULL; - if ((p = getgrgid(gid)) == NULL) { - err_setstr(KeyError, "getgrgid(): gid not found"); - return NULL; - } - return mkgrent(p); -} - -static object *grp_getgrnam(self, args) - object *self, *args; -{ - char *name; - struct group *p; - if (!getstrarg(args, &name)) - return NULL; - if ((p = getgrnam(name)) == NULL) { - err_setstr(KeyError, "getgrnam(): name not found"); - return NULL; - } - return mkgrent(p); -} - -static object *grp_getgrall(self, args) - object *self, *args; -{ - object *d; - struct group *p; - if (!getnoarg(args)) - return NULL; - if ((d = newlistobject(0)) == NULL) - return NULL; - setgrent(); - while ((p = getgrent()) != NULL) { - object *v = mkgrent(p); - if (v == NULL || addlistitem(d, v) != 0) { - XDECREF(v); - DECREF(d); - return NULL; - } - } - return d; -} - -static struct methodlist grp_methods[] = { - {"getgrgid", grp_getgrgid}, - {"getgrnam", grp_getgrnam}, - {"getgrall", grp_getgrall}, - {NULL, NULL} /* sentinel */ -}; - -void -initgrp() -{ - initmodule("grp", grp_methods); -} diff --git a/Modules/imageop.c b/Modules/imageop.c deleted file mode 100644 index 35f9dec57c..0000000000 --- a/Modules/imageop.c +++ /dev/null @@ -1,742 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* imageopmodule - Various operations on pictures */ - -#ifdef sun -#define signed -#endif - -#include "allobjects.h" -#include "modsupport.h" - -#define CHARP(cp, xmax, x, y) ((char *)(cp+y*xmax+x)) -#define SHORTP(cp, xmax, x, y) ((short *)(cp+2*(y*xmax+x))) -#define LONGP(cp, xmax, x, y) ((long *)(cp+4*(y*xmax+x))) - -static object *ImageopError; - -static object * -imageop_crop(self, args) - object *self; - object *args; -{ - char *cp, *ncp; - short *nsp; - long *nlp; - int len, size, x, y, newx1, newx2, newy1, newy2; - int ix, iy, xstep, ystep; - object *rv; - - if ( !getargs(args, "(s#iiiiiii)", &cp, &len, &size, &x, &y, - &newx1, &newy1, &newx2, &newy2) ) - return 0; - - if ( size != 1 && size != 2 && size != 4 ) { - err_setstr(ImageopError, "Size should be 1, 2 or 4"); - return 0; - } - if ( len != size*x*y ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - xstep = (newx1 < newx2)? 1 : -1; - ystep = (newy1 < newy2)? 1 : -1; - - rv = newsizedstringobject(NULL, - (abs(newx2-newx1)+1)*(abs(newy2-newy1)+1)*size); - if ( rv == 0 ) - return 0; - ncp = (char *)getstringvalue(rv); - nsp = (short *)ncp; - nlp = (long *)ncp; - newy2 += ystep; - newx2 += xstep; - for( iy = newy1; iy != newy2; iy+=ystep ) { - for ( ix = newx1; ix != newx2; ix+=xstep ) { - if ( iy < 0 || iy >= y || ix < 0 || ix >= x ) { - if ( size == 1 ) *ncp++ = 0; - else *nlp++ = 0; - } else { - if ( size == 1 ) *ncp++ = *CHARP(cp, x, ix, iy); - else if ( size == 2 ) *nsp++ = *SHORTP(cp, x, ix, iy); - else *nlp++ = *LONGP(cp, x, ix, iy); - } - } - } - return rv; -} - -static object * -imageop_scale(self, args) - object *self; - object *args; -{ - char *cp, *ncp; - short *nsp; - long *nlp; - int len, size, x, y, newx, newy; - int ix, iy; - int oix, oiy; - object *rv; - - if ( !getargs(args, "(s#iiiii)", &cp, &len, &size, &x, &y, &newx, &newy) ) - return 0; - - if ( size != 1 && size != 2 && size != 4 ) { - err_setstr(ImageopError, "Size should be 1, 2 or 4"); - return 0; - } - if ( len != size*x*y ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, newx*newy*size); - if ( rv == 0 ) - return 0; - ncp = (char *)getstringvalue(rv); - nsp = (short *)ncp; - nlp = (long *)ncp; - for( iy = 0; iy < newy; iy++ ) { - for ( ix = 0; ix < newx; ix++ ) { - oix = ix * x / newx; - oiy = iy * y / newy; - if ( size == 1 ) *ncp++ = *CHARP(cp, x, oix, oiy); - else if ( size == 2 ) *nsp++ = *SHORTP(cp, x, oix, oiy); - else *nlp++ = *LONGP(cp, x, oix, oiy); - } - } - return rv; -} - -/* Note: this routine can use a bit of optimizing */ - -static object * -imageop_tovideo(self, args) - object *self; - object *args; -{ - int maxx, maxy, x, y, len; - int i; - unsigned char *cp, *ncp; - int width; - object *rv; - - - if ( !getargs(args, "(s#iii)", &cp, &len, &width, &maxx, &maxy) ) - return 0; - - if ( width != 1 && width != 4 ) { - err_setstr(ImageopError, "Size should be 1 or 4"); - return 0; - } - if ( maxx*maxy*width != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - - if ( width == 1 ) { - memcpy(ncp, cp, maxx); /* Copy first line */ - ncp += maxx; - for (y=1; y<maxy; y++) { /* Interpolate other lines */ - for(x=0; x<maxx; x++) { - i = y*maxx + x; - *ncp++ = ((int)cp[i] + (int)cp[i-maxx]) >> 1; - } - } - } else { - memcpy(ncp, cp, maxx*4); /* Copy first line */ - ncp += maxx*4; - for (y=1; y<maxy; y++) { /* Interpolate other lines */ - for(x=0; x<maxx; x++) { - i = (y*maxx + x)*4 + 1; - *ncp++ = 0; /* Skip alfa comp */ - *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1; - i++; - *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1; - i++; - *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1; - } - } - } - return rv; -} - -static object * -imageop_grey2mono(self, args) - object *self; - object *args; -{ - int tres, x, y, len; - unsigned char *cp, *ncp; - unsigned char ovalue; - object *rv; - int i, bit; - - - if ( !getargs(args, "(s#iii)", &cp, &len, &x, &y, &tres) ) - return 0; - - if ( x*y != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, (len+7)/8); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - - bit = 0x80; - ovalue = 0; - for ( i=0; i < len; i++ ) { - if ( (int)cp[i] > tres ) - ovalue |= bit; - bit >>= 1; - if ( bit == 0 ) { - *ncp++ = ovalue; - bit = 0x80; - ovalue = 0; - } - } - if ( bit != 0x80 ) - *ncp++ = ovalue; - return rv; -} - -static object * -imageop_grey2grey4(self, args) - object *self; - object *args; -{ - int x, y, len; - unsigned char *cp, *ncp; - unsigned char ovalue; - object *rv; - int i; - int pos; - - - if ( !getargs(args, "(s#ii)", &cp, &len, &x, &y) ) - return 0; - - if ( x*y != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, (len+1)/2); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - pos = 0; - ovalue = 0; - for ( i=0; i < len; i++ ) { - ovalue |= ((int)cp[i] & 0xf0) >> pos; - pos += 4; - if ( pos == 8 ) { - *ncp++ = ovalue; - ovalue = 0; - pos = 0; - } - } - if ( pos != 0 ) - *ncp++ = ovalue; - return rv; -} - -static object * -imageop_grey2grey2(self, args) - object *self; - object *args; -{ - int x, y, len; - unsigned char *cp, *ncp; - unsigned char ovalue; - object *rv; - int i; - int pos; - - - if ( !getargs(args, "(s#ii)", &cp, &len, &x, &y) ) - return 0; - - if ( x*y != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, (len+3)/4); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - pos = 0; - ovalue = 0; - for ( i=0; i < len; i++ ) { - ovalue |= ((int)cp[i] & 0xc0) >> pos; - pos += 2; - if ( pos == 8 ) { - *ncp++ = ovalue; - ovalue = 0; - pos = 0; - } - } - if ( pos != 0 ) - *ncp++ = ovalue; - return rv; -} - -static object * -imageop_dither2mono(self, args) - object *self; - object *args; -{ - int sum, x, y, len; - unsigned char *cp, *ncp; - unsigned char ovalue; - object *rv; - int i, bit; - - - if ( !getargs(args, "(s#ii)", &cp, &len, &x, &y) ) - return 0; - - if ( x*y != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, (len+7)/8); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - - bit = 0x80; - ovalue = 0; - sum = 0; - for ( i=0; i < len; i++ ) { - sum += cp[i]; - if ( sum >= 256 ) { - sum -= 256; - ovalue |= bit; - } - bit >>= 1; - if ( bit == 0 ) { - *ncp++ = ovalue; - bit = 0x80; - ovalue = 0; - } - } - if ( bit != 0x80 ) - *ncp++ = ovalue; - return rv; -} - -static object * -imageop_dither2grey2(self, args) - object *self; - object *args; -{ - int x, y, len; - unsigned char *cp, *ncp; - unsigned char ovalue; - object *rv; - int i; - int pos; - int sum = 0, nvalue; - - - if ( !getargs(args, "(s#ii)", &cp, &len, &x, &y) ) - return 0; - - if ( x*y != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, (len+3)/4); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - pos = 1; - ovalue = 0; - for ( i=0; i < len; i++ ) { - sum += cp[i]; - nvalue = sum & 0x180; - sum -= nvalue; - ovalue |= nvalue >> pos; - pos += 2; - if ( pos == 9 ) { - *ncp++ = ovalue; - ovalue = 0; - pos = 1; - } - } - if ( pos != 0 ) - *ncp++ = ovalue; - return rv; -} - -static object * -imageop_mono2grey(self, args) - object *self; - object *args; -{ - int v0, v1, x, y, len, nlen; - unsigned char *cp, *ncp; - object *rv; - int i, bit; - - if ( !getargs(args, "(s#iiii)", &cp, &len, &x, &y, &v0, &v1) ) - return 0; - - nlen = x*y; - if ( (nlen+7)/8 != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, nlen); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - - bit = 0x80; - for ( i=0; i < nlen; i++ ) { - if ( *cp & bit ) - *ncp++ = v1; - else - *ncp++ = v0; - bit >>= 1; - if ( bit == 0 ) { - bit = 0x80; - cp++; - } - } - return rv; -} - -static object * -imageop_grey22grey(self, args) - object *self; - object *args; -{ - int x, y, len, nlen; - unsigned char *cp, *ncp; - object *rv; - int i, pos, value, nvalue; - - if ( !getargs(args, "(s#ii)", &cp, &len, &x, &y) ) - return 0; - - nlen = x*y; - if ( (nlen+3)/4 != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, nlen); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - - pos = 0; - for ( i=0; i < nlen; i++ ) { - if ( pos == 0 ) { - value = *cp++; - pos = 8; - } - pos -= 2; - nvalue = (value >> pos) & 0x03; - *ncp++ = nvalue | (nvalue << 2) | (nvalue << 4) | (nvalue << 6); - } - return rv; -} - -static object * -imageop_grey42grey(self, args) - object *self; - object *args; -{ - int x, y, len, nlen; - unsigned char *cp, *ncp; - object *rv; - int i, pos, value, nvalue; - - if ( !getargs(args, "(s#ii)", &cp, &len, &x, &y) ) - return 0; - - nlen = x*y; - if ( (nlen+1)/2 != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, nlen); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - - pos = 0; - for ( i=0; i < nlen; i++ ) { - if ( pos == 0 ) { - value = *cp++; - pos = 8; - } - pos -= 4; - nvalue = (value >> pos) & 0x0f; - *ncp++ = nvalue | (nvalue << 4); - } - return rv; -} - -static object * -imageop_rgb2rgb8(self, args) - object *self; - object *args; -{ - int x, y, len, nlen; - unsigned long *cp; - unsigned char *ncp; - object *rv; - int i, r, g, b; - unsigned long value, nvalue; - - if ( !getargs(args, "(s#ii)", &cp, &len, &x, &y) ) - return 0; - - nlen = x*y; - if ( nlen*4 != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, nlen); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - - for ( i=0; i < nlen; i++ ) { - /* Bits in source: aaaaaaaa BBbbbbbb GGGggggg RRRrrrrr */ - value = *cp++; -#if 0 - r = (value >> 5) & 7; - g = (value >> 13) & 7; - b = (value >> 22) & 3; -#else - r = (int) ((value & 0xff) / 255. * 7. + .5); - g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5); - b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5); -#endif - nvalue = (r<<5) | (b<<3) | g; - *ncp++ = nvalue; - } - return rv; -} - -static object * -imageop_rgb82rgb(self, args) - object *self; - object *args; -{ - int x, y, len, nlen; - unsigned char *cp; - unsigned long *ncp; - object *rv; - int i, r, g, b; - unsigned long value, nvalue; - - if ( !getargs(args, "(s#ii)", &cp, &len, &x, &y) ) - return 0; - - nlen = x*y; - if ( nlen != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, nlen*4); - if ( rv == 0 ) - return 0; - ncp = (unsigned long *)getstringvalue(rv); - - for ( i=0; i < nlen; i++ ) { - /* Bits in source: RRRBBGGG - ** Red and Green are multiplied by 36.5, Blue by 85 - */ - value = *cp++; - r = (value >> 5) & 7; - g = (value ) & 7; - b = (value >> 3) & 3; - r = (r<<5) | (r<<3) | (r>>1); - g = (g<<5) | (g<<3) | (g>>1); - b = (b<<6) | (b<<4) | (b<<2) | b; - nvalue = r | (g<<8) | (b<<16); - *ncp++ = nvalue; - } - return rv; -} - -static object * -imageop_rgb2grey(self, args) - object *self; - object *args; -{ - int x, y, len, nlen; - unsigned long *cp; - unsigned char *ncp; - object *rv; - int i, r, g, b; - unsigned long value, nvalue; - - if ( !getargs(args, "(s#ii)", &cp, &len, &x, &y) ) - return 0; - - nlen = x*y; - if ( nlen*4 != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, nlen); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)getstringvalue(rv); - - for ( i=0; i < nlen; i++ ) { - value = *cp++; - r = (value ) & 0xff; - g = (value >> 8) & 0xff; - b = (value >> 16) & 0xff; - nvalue = (int)(0.30*r + 0.59*g + 0.11*b); - if ( nvalue > 255 ) nvalue = 255; - *ncp++ = nvalue; - } - return rv; -} - -static object * -imageop_grey2rgb(self, args) - object *self; - object *args; -{ - int x, y, len, nlen; - unsigned char *cp; - unsigned long *ncp; - object *rv; - int i; - unsigned long value; - - if ( !getargs(args, "(s#ii)", &cp, &len, &x, &y) ) - return 0; - - nlen = x*y; - if ( nlen != len ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, nlen*4); - if ( rv == 0 ) - return 0; - ncp = (unsigned long *)getstringvalue(rv); - - for ( i=0; i < nlen; i++ ) { - value = *cp++; - *ncp++ = value | (value << 8 ) | (value << 16); - } - return rv; -} - -/* -static object * -imageop_mul(self, args) - object *self; - object *args; -{ - char *cp, *ncp; - int len, size, x, y; - object *rv; - int i; - - if ( !getargs(args, "(s#iii)", &cp, &len, &size, &x, &y) ) - return 0; - - if ( size != 1 && size != 4 ) { - err_setstr(ImageopError, "Size should be 1 or 4"); - return 0; - } - if ( len != size*x*y ) { - err_setstr(ImageopError, "String has incorrect length"); - return 0; - } - - rv = newsizedstringobject(NULL, XXXX); - if ( rv == 0 ) - return 0; - ncp = (char *)getstringvalue(rv); - - - for ( i=0; i < len; i += size ) { - } - return rv; -} -*/ - -static struct methodlist imageop_methods[] = { - { "crop", imageop_crop }, - { "scale", imageop_scale }, - { "grey2mono", imageop_grey2mono }, - { "grey2grey2", imageop_grey2grey2 }, - { "grey2grey4", imageop_grey2grey4 }, - { "dither2mono", imageop_dither2mono }, - { "dither2grey2", imageop_dither2grey2 }, - { "mono2grey", imageop_mono2grey }, - { "grey22grey", imageop_grey22grey }, - { "grey42grey", imageop_grey42grey }, - { "tovideo", imageop_tovideo }, - { "rgb2rgb8", imageop_rgb2rgb8 }, - { "rgb82rgb", imageop_rgb82rgb }, - { "rgb2grey", imageop_rgb2grey }, - { "grey2rgb", imageop_grey2rgb }, - { 0, 0 } -}; - - -void -initimageop() -{ - object *m, *d; - m = initmodule("imageop", imageop_methods); - d = getmoduledict(m); - ImageopError = newstringobject("imageop.error"); - if ( ImageopError == NULL || dictinsert(d,"error",ImageopError) ) - fatal("can't define imageop.error"); -} diff --git a/Modules/imgfile.c b/Modules/imgfile.c deleted file mode 100644 index 9c318be136..0000000000 --- a/Modules/imgfile.c +++ /dev/null @@ -1,527 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* IMGFILE module - Interface to sgi libimage */ - -/* XXX This modele should be done better at some point. It should return -** an object of image file class, and have routines to manipulate these -** image files in a neater way (so you can get rgb images off a greyscale -** file, for instance, or do a straight display without having to get the -** image bits into python, etc). -** -** Warning: this module is very non-reentrant (esp. the readscaled stuff) -*/ - -#include "allobjects.h" -#include "modsupport.h" - -#include <gl/image.h> -#include <errno.h> - -#include "/usr/people/4Dgifts/iristools/include/izoom.h" - -static object * ImgfileError; /* Exception we raise for various trouble */ - -static int top_to_bottom; /* True if we want top-to-bottom images */ - -/* The image library does not always call the error hander :-(, - therefore we have a global variable indicating that it was called. - It is cleared by imgfile_open(). */ - -static int error_called; - - -/* The error handler */ - -static imgfile_error(str) - char *str; -{ - err_setstr(ImgfileError, str); - error_called = 1; - return; /* To imglib, which will return a failure indicator */ -} - - -/* Open an image file and return a pointer to it. - Make sure we raise an exception if we fail. */ - -static IMAGE * -imgfile_open(fname) - char *fname; -{ - IMAGE *image; - i_seterror(imgfile_error); - error_called = 0; - errno = 0; - if ( (image = iopen(fname, "r")) == NULL ) { - /* Error may already be set by imgfile_error */ - if ( !error_called ) { - if (errno) - err_errno(ImgfileError); - else - err_setstr(ImgfileError, "Can't open image file"); - } - return NULL; - } - return image; -} - -static object * -imgfile_ttob(self, args) - object *self; - object *args; -{ - int newval; - object *rv; - - if (!getargs(args, "i", &newval)) - return NULL; - rv = newintobject(top_to_bottom); - top_to_bottom = newval; - return rv; -} - -static object * -imgfile_read(self, args) - object *self; - object *args; -{ - char *fname; - object *rv; - int xsize, ysize, zsize; - char *cdatap; - long *idatap; - static short rs[8192], gs[8192], bs[8192]; - int x, y; - IMAGE *image; - int yfirst, ylast, ystep; - - if ( !getargs(args, "s", &fname) ) - return NULL; - - if ( (image = imgfile_open(fname)) == NULL ) - return NULL; - - if ( image->colormap != CM_NORMAL ) { - iclose(image); - err_setstr(ImgfileError, "Can only handle CM_NORMAL images"); - return NULL; - } - if ( BPP(image->type) != 1 ) { - iclose(image); - err_setstr(ImgfileError, "Can't handle imgfiles with bpp!=1"); - return NULL; - } - xsize = image->xsize; - ysize = image->ysize; - zsize = image->zsize; - if ( zsize != 1 && zsize != 3) { - iclose(image); - err_setstr(ImgfileError, "Can only handle 1 or 3 byte pixels"); - return NULL; - } - if ( xsize > 8192 ) { - iclose(image); - err_setstr(ImgfileError, "Can't handle image with > 8192 columns"); - return NULL; - } - - if ( zsize == 3 ) zsize = 4; - rv = newsizedstringobject((char *)NULL, xsize*ysize*zsize); - if ( rv == NULL ) { - iclose(image); - return NULL; - } - cdatap = getstringvalue(rv); - idatap = (long *)cdatap; - - if (top_to_bottom) { - yfirst = ysize-1; - ylast = -1; - ystep = -1; - } else { - yfirst = 0; - ylast = ysize; - ystep = 1; - } - for ( y=yfirst; y != ylast && !error_called; y += ystep ) { - if ( zsize == 1 ) { - getrow(image, rs, y, 0); - for(x=0; x<xsize; x++ ) - *cdatap++ = rs[x]; - } else { - getrow(image, rs, y, 0); - getrow(image, gs, y, 1); - getrow(image, bs, y, 2); - for(x=0; x<xsize; x++ ) - *idatap++ = (rs[x] & 0xff) | - ((gs[x] & 0xff)<<8) | - ((bs[x] & 0xff)<<16); - } - } - iclose(image); - if ( error_called ) { - DECREF(rv); - return NULL; - } - return rv; -} - -static IMAGE *glob_image; -static long *glob_datap; -static int glob_width, glob_z, glob_ysize; - -static -xs_get(buf, y) - short *buf; - int y; -{ - if (top_to_bottom) - getrow(glob_image, buf, (glob_ysize-1-y), glob_z); - else - getrow(glob_image, buf, y, glob_z); -} - -static -xs_put_c(buf, y) - short *buf; - int y; -{ - char *datap = (char *)glob_datap + y*glob_width; - int width = glob_width; - - while ( width-- ) - *datap++ = (*buf++) & 0xff; -} - -static -xs_put_0(buf, y) - short *buf; - int y; -{ - long *datap = glob_datap + y*glob_width; - int width = glob_width; - - while ( width-- ) - *datap++ = (*buf++) & 0xff; -} -static -xs_put_12(buf, y) - short *buf; - int y; -{ - long *datap = glob_datap + y*glob_width; - int width = glob_width; - - while ( width-- ) - *datap++ |= ((*buf++) & 0xff) << (glob_z*8); -} - -static void -xscale(image, xsize, ysize, zsize, datap, xnew, ynew, fmode, blur) - IMAGE *image; - int xsize, ysize, zsize; - long *datap; - int xnew, ynew; - int fmode; - double blur; -{ - glob_image = image; - glob_datap = datap; - glob_width = xnew; - glob_ysize = ysize; - if ( zsize == 1 ) { - glob_z = 0; - filterzoom(xs_get, xs_put_c, xsize, ysize, xnew, ynew, fmode, blur); - } else { - glob_z = 0; - filterzoom(xs_get, xs_put_0, xsize, ysize, xnew, ynew, fmode, blur); - glob_z = 1; - filterzoom(xs_get, xs_put_12, xsize, ysize, xnew, ynew, fmode, blur); - glob_z = 2; - filterzoom(xs_get, xs_put_12, xsize, ysize, xnew, ynew, fmode, blur); - } -} - - -static object * -imgfile_readscaled(self, args) - object *self; - object *args; -{ - char *fname; - object *rv; - int xsize, ysize, zsize; - char *cdatap; - long *idatap; - static short rs[8192], gs[8192], bs[8192]; - int x, y; - int xwtd, ywtd, xorig, yorig; - float xfac, yfac; - int cnt; - IMAGE *image; - char *filter; - double blur; - int extended; - int fmode; - int yfirst, ylast, ystep; - - /* - ** Parse args. Funny, since arg 4 and 5 are optional - ** (filter name and blur factor). Also, 4 or 5 arguments indicates - ** extended scale algorithm in stead of simple-minded pixel drop/dup. - */ - extended = 0; - cnt = gettuplesize(args); - if ( cnt == 5 ) { - extended = 1; - if ( !getargs(args, "(siisd)", &fname, &xwtd, &ywtd, &filter, &blur) ) - return NULL; - } else if ( cnt == 4 ) { - extended = 1; - if ( !getargs(args, "(siis)", &fname, &xwtd, &ywtd, &filter) ) - return NULL; - blur = 1.0; - } else if ( !getargs(args, "(sii)", &fname, &xwtd, &ywtd) ) - return NULL; - - /* - ** Check parameters, open file and check type, rows, etc. - */ - if ( extended ) { - if ( strcmp(filter, "impulse") == 0 ) fmode = IMPULSE; - else if ( strcmp( filter, "box") == 0 ) fmode = BOX; - else if ( strcmp( filter, "triangle") == 0 ) fmode = TRIANGLE; - else if ( strcmp( filter, "quadratic") == 0 ) fmode = QUADRATIC; - else if ( strcmp( filter, "gaussian") == 0 ) fmode = GAUSSIAN; - else { - err_setstr(ImgfileError, "Unknown filter type"); - return NULL; - } - } - - if ( (image = imgfile_open(fname)) == NULL ) - return NULL; - - if ( image->colormap != CM_NORMAL ) { - iclose(image); - err_setstr(ImgfileError, "Can only handle CM_NORMAL images"); - return NULL; - } - if ( BPP(image->type) != 1 ) { - iclose(image); - err_setstr(ImgfileError, "Can't handle imgfiles with bpp!=1"); - return NULL; - } - xsize = image->xsize; - ysize = image->ysize; - zsize = image->zsize; - if ( zsize != 1 && zsize != 3) { - iclose(image); - err_setstr(ImgfileError, "Can only handle 1 or 3 byte pixels"); - return NULL; - } - if ( xsize > 8192 ) { - iclose(image); - err_setstr(ImgfileError, "Can't handle image with > 8192 columns"); - return NULL; - } - - if ( zsize == 3 ) zsize = 4; - rv = newsizedstringobject(NULL, xwtd*ywtd*zsize); - if ( rv == NULL ) { - iclose(image); - return NULL; - } - xfac = (float)xsize/(float)xwtd; - yfac = (float)ysize/(float)ywtd; - cdatap = getstringvalue(rv); - idatap = (long *)cdatap; - - if ( extended ) { - xscale(image, xsize, ysize, zsize, idatap, xwtd, ywtd, fmode, blur); - } else { - if (top_to_bottom) { - yfirst = ywtd-1; - ylast = -1; - ystep = -1; - } else { - yfirst = 0; - ylast = ywtd; - ystep = 1; - } - for ( y=yfirst; y != ylast && !error_called; y += ystep ) { - yorig = (int)(y*yfac); - if ( zsize == 1 ) { - getrow(image, rs, yorig, 0); - for(x=0; x<xwtd; x++ ) { - *cdatap++ = rs[(int)(x*xfac)]; - } - } else { - getrow(image, rs, yorig, 0); - getrow(image, gs, yorig, 1); - getrow(image, bs, yorig, 2); - for(x=0; x<xwtd; x++ ) { - xorig = (int)(x*xfac); - *idatap++ = (rs[xorig] & 0xff) | - ((gs[xorig] & 0xff)<<8) | - ((bs[xorig] & 0xff)<<16); - } - } - } - } - iclose(image); - if ( error_called ) { - DECREF(rv); - return NULL; - } - return rv; -} - -static object * -imgfile_getsizes(self, args) - object *self; - object *args; -{ - char *fname; - object *rv; - IMAGE *image; - - if ( !getargs(args, "s", &fname) ) - return NULL; - - if ( (image = imgfile_open(fname)) == NULL ) - return NULL; - rv = mkvalue("(iii)", image->xsize, image->ysize, image->zsize); - iclose(image); - return rv; -} - -static object * -imgfile_write(self, args) - object *self; - object *args; -{ - IMAGE *image; - char *fname; - int xsize, ysize, zsize, len; - char *cdatap; - long *idatap; - short rs[8192], gs[8192], bs[8192]; - short r, g, b; - long rgb; - int x, y; - int yfirst, ylast, ystep; - - - if ( !getargs(args, "(ss#iii)", - &fname, &cdatap, &len, &xsize, &ysize, &zsize) ) - return NULL; - - if ( zsize != 1 && zsize != 3 ) { - err_setstr(ImgfileError, "Can only handle 1 or 3 byte pixels"); - return NULL; - } - if ( len != xsize * ysize * (zsize == 1 ? 1 : 4) ) { - err_setstr(ImgfileError, "Data does not match sizes"); - return NULL; - } - if ( xsize > 8192 ) { - err_setstr(ImgfileError, "Can't handle image with > 8192 columns"); - return NULL; - } - - error_called = 0; - errno = 0; - image =iopen(fname, "w", RLE(1), 3, xsize, ysize, zsize); - if ( image == 0 ) { - if ( ! error_called ) { - if (errno) - err_errno(ImgfileError); - else - err_setstr(ImgfileError, "Can't create image file"); - } - return NULL; - } - - idatap = (long *)cdatap; - - if (top_to_bottom) { - yfirst = ysize-1; - ylast = -1; - ystep = -1; - } else { - yfirst = 0; - ylast = ysize; - ystep = 1; - } - for ( y=yfirst; y != ylast && !error_called; y += ystep ) { - if ( zsize == 1 ) { - for( x=0; x<xsize; x++ ) - rs[x] = *cdatap++; - putrow(image, rs, y, 0); - } else { - for( x=0; x<xsize; x++ ) { - rgb = *idatap++; - r = rgb & 0xff; - g = (rgb >> 8 ) & 0xff; - b = (rgb >> 16 ) & 0xff; - rs[x] = r; - gs[x] = g; - bs[x] = b; - } - putrow(image, rs, y, 0); - putrow(image, gs, y, 1); - putrow(image, bs, y, 2); - } - } - iclose(image); - if ( error_called ) - return NULL; - INCREF(None); - return None; - -} - - -static struct methodlist imgfile_methods[] = { - { "getsizes", imgfile_getsizes }, - { "read", imgfile_read }, - { "readscaled", imgfile_readscaled, 1}, - { "write", imgfile_write }, - { "ttob", imgfile_ttob }, - { NULL, NULL } /* Sentinel */ -}; - - -void -initimgfile() -{ - object *m, *d; - m = initmodule("imgfile", imgfile_methods); - d = getmoduledict(m); - ImgfileError = newstringobject("imgfile.error"); - if ( ImgfileError == NULL || dictinsert(d, "error", ImgfileError) ) - fatal("can't define imgfile.error"); -} diff --git a/Modules/main.c b/Modules/main.c deleted file mode 100644 index e123976a09..0000000000 --- a/Modules/main.c +++ /dev/null @@ -1,241 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Python interpreter main program */ - -#include "Python.h" - - -/* Interface to getopt(): */ -extern int optind; -extern char *optarg; -extern int getopt(); /* PROTO((int, char **, char *)); -- not standardized */ - - -/* Subroutines that live in their own file */ -extern char *Py_GetVersion(); -extern char *Py_GetCopyright(); - - -/* For getprogramname(); set by main() */ -static char *argv0; - -/* For getargcargv(); set by main() */ -static char **orig_argv; -static int orig_argc; - - -/* Short usage message (with %s for argv0) */ -static char *usage_line = -"usage: %s [-d] [-i] [-s] [-u ] [-v] [-c cmd | file | -] [arg] ...\n"; - -/* Long usage message, split into parts < 512 bytes */ -static char *usage_top = "\n\ -Options and arguments (and corresponding environment variables):\n\ --d : debug output from parser (also PYTHONDEBUG=x)\n\ --i : inspect interactively after running script (also PYTHONINSPECT=x)\n\ --s : suppress printing of top level expressions (also PYTHONSUPPRESS=x)\n\ --u : unbuffered stdout and stderr (also PYTHONUNBUFFERED=x)\n\ --v : verbose (trace import statements) (also PYTHONVERBOSE=x)\n\ --c cmd : program passed in as string (terminates option list)\n\ -"; -static char *usage_bot = "\ -file : program read from script file\n\ -- : program read from stdin (default; interactive mode if a tty)\n\ -arg ...: arguments passed to program in sys.argv[1:]\n\ -\n\ -Other environment variables:\n\ -PYTHONSTARTUP: file executed on interactive startup (no default)\n\ -PYTHONPATH : colon-separated list of directories prefixed to the\n\ - default module search path. The result is sys.path.\n\ -"; - - -/* Main program */ - -int -main(argc, argv) - int argc; - char **argv; -{ - int c; - int sts; - char *command = NULL; - char *filename = NULL; - FILE *fp = stdin; - char *p; - int inspect = 0; - int unbuffered = 0; - - orig_argc = argc; /* For getargcargv() */ - orig_argv = argv; - argv0 = argv[0]; /* For getprogramname() */ - - if ((p = getenv("PYTHONDEBUG")) && *p != '\0') - Py_DebugFlag = 1; - if ((p = getenv("PYTHONSUPPRESS")) && *p != '\0') - Py_SuppressPrintingFlag = 1; - if ((p = getenv("PYTHONVERBOSE")) && *p != '\0') - Py_VerboseFlag = 1; - if ((p = getenv("PYTHONINSPECT")) && *p != '\0') - inspect = 1; - if ((p = getenv("PYTHONUNBUFFERED")) && *p != '\0') - unbuffered = 1; - - while ((c = getopt(argc, argv, "c:disuv")) != EOF) { - if (c == 'c') { - /* -c is the last option; following arguments - that look like options are left for the - the command to interpret. */ - command = malloc(strlen(optarg) + 2); - if (command == NULL) - Py_FatalError( - "not enough memory to copy -c argument"); - strcpy(command, optarg); - strcat(command, "\n"); - break; - } - - switch (c) { - - case 'd': - Py_DebugFlag++; - break; - - case 'i': - inspect++; - break; - - case 's': - Py_SuppressPrintingFlag++; - break; - - case 'u': - unbuffered++; - break; - - case 'v': - Py_VerboseFlag++; - break; - - /* This space reserved for other options */ - - default: - fprintf(stderr, usage_line, argv[0]); - fprintf(stderr, usage_top); - fprintf(stderr, usage_bot); - exit(2); - /*NOTREACHED*/ - - } - } - - if (unbuffered) { -#ifndef MPW - setbuf(stdout, (char *)NULL); - setbuf(stderr, (char *)NULL); -#else - /* On MPW (3.2) unbuffered seems to hang */ - setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ); - setvbuf(stderr, (char *)NULL, _IOLBF, BUFSIZ); -#endif - } - - if (command == NULL && optind < argc && - strcmp(argv[optind], "-") != 0) - filename = argv[optind]; - - if (Py_VerboseFlag || - command == NULL && filename == NULL && isatty((int)fileno(fp))) - fprintf(stderr, "Python %s\n%s\n", - Py_GetVersion(), Py_GetCopyright()); - - if (filename != NULL) { - if ((fp = fopen(filename, "r")) == NULL) { - fprintf(stderr, "%s: can't open file '%s'\n", - argv[0], filename); - exit(2); - } - } - - Py_Initialize(); - - if (command != NULL) { - /* Backup optind and force sys.argv[0] = '-c' */ - optind--; - argv[optind] = "-c"; - } - - PySys_SetArgv(argc-optind, argv+optind); - - if (command) { - sts = PyRun_SimpleString(command) != 0; - } - else { - if (filename == NULL && isatty((int)fileno(fp))) { - char *startup = getenv("PYTHONSTARTUP"); - if (startup != NULL && startup[0] != '\0') { - FILE *fp = fopen(startup, "r"); - if (fp != NULL) { - (void) PyRun_SimpleFile(fp, startup); - PyErr_Clear(); - fclose(fp); - } - } - } - sts = PyRun_AnyFile( - fp, filename == NULL ? "<stdin>" : filename) != 0; - if (filename != NULL) - fclose(fp); - } - - if (inspect && isatty((int)fileno(stdin)) && - (filename != NULL || command != NULL)) - sts = PyRun_AnyFile(stdin, "<stdin>") != 0; - - Py_Exit(sts); - /*NOTREACHED*/ -} - - -/* Return the program name -- some code out there needs this. */ - -char * -getprogramname() -{ - return argv0; -} - - -/* Make the *original* argc/argv available to other modules. - This is rare, but it is needed by the secureware extension. */ - -void -getargcargv(argc,argv) - int *argc; - char ***argv; -{ - *argc = orig_argc; - *argv = orig_argv; -} diff --git a/Modules/makesetup b/Modules/makesetup deleted file mode 100755 index 76ee033ac7..0000000000 --- a/Modules/makesetup +++ /dev/null @@ -1,248 +0,0 @@ -#! /bin/sh - -# Convert templates into Makefile and config.c, based on the module -# definitions found in the file Setup. -# -# Usage: makesetup [-s dir] [-c file] [-m file] [Setup] ... [-n [Setup] ...] -# -# Options: -# -s directory: alternative source directory (default derived from $0) -# -c file: alternative config.c template (default $srcdir/config.c.in) -# -c -: don't write config.c -# -m file: alternative Makefile template (default ./Makefile.pre) -# -m -: don't write Makefile -# -# Remaining arguments are one or more Setup files (default ./Setup). -# Setup files after a -n option are used for their variables, modules -# and libraries but not for their .o files. -# -# See Setup.in for a description of the format of the Setup file. -# -# The following edits are made: -# -# Copying config.c.in to config.c: -# - insert an identifying comment at the start -# - for each <module> mentioned in Setup before *noconfig*: -# + insert 'extern void init<module>();' before MARKER 1 -# + insert '{"<module>", initmodule},' before MARKER 2 -# -# Copying Makefile.pre to Makefile: -# - insert an identifying comment at the start -# - replace _MODOBJS_ by the list of objects from Setup (except for -# Setup files after a -n option) -# - replace _MODLIBS_ by the list of libraries from Setup -# - for each object file mentioned in Setup, append a rule -# '<file>.o: <file>.c; <build commands>' to the end of the Makefile -# - for each module mentioned in Setup, append a rule -# which creates a shared library version to the end of the Makefile -# - for each variable definition found in Setup, insert the definition -# before the comment 'Definitions added by makesetup' - -# Loop over command line options -usage=' -usage: makesetup [-s srcdir] [-c config.c.in] [-m Makefile.pre] - [Setup] ... [-n [Setup] ...]' -srcdir='' -config='' -makepre='' -noobjects='' -doconfig=yes -while : -do - case $1 in - -s) shift; srcdir=$1; shift;; - -c) shift; config=$1; shift;; - -m) shift; makepre=$1; shift;; - --) shift; break;; - -n) noobjects=yes;; - -*) echo "$usage" 1>&2; exit 2;; - *) break;; - esac -done - -# Set default srcdir and config if not set by command line -# (Not all systems have dirname) -case $srcdir in -'') case $0 in - */*) srcdir=`echo $0 | sed 's,/[^/]*$,,'`;; - *) srcdir=.;; - esac;; -esac -case $config in -'') config=$srcdir/config.c.in;; -esac -case $makepre in -'') makepre=Makefile.pre;; -esac - -# Newline for sed i and a commands -NL='\ -' - -# Main loop -for i in ${*-Setup} -do - case $i in - -n) echo '*noobjects*';; - *) echo '*doconfig*'; cat "$i";; - esac -done | -sed -e 's/[ ]*#.*//' -e '/^[ ]*$/d' | -( - rulesf="@rules.$$" - trap 'rm -f $rulesf' 0 1 2 3 - echo " -# Rules appended by makedepend -" >$rulesf - DEFS= - MODS= - SHAREDMODS= - OBJS= - LIBS= - LOCALLIBS= - BASELIBS= - while read line - do - # Output DEFS in reverse order so first definition overrides - case $line in - *=*) DEFS="$line$NL$DEFS"; continue;; - '*noobjects*') - case $noobjects in - yes) ;; - *) LOCALLIBS=$LIBS; LIBS=;; - esac - noobjects=yes; - continue;; - '*doconfig*') doconfig=yes; continue;; - '*noconfig*') doconfig=no; continue;; - esac - srcs= - cpps= - libs= - mods= - skip= - for arg in $line - do - case $skip in - libs) libs="$libs $arg"; skip=; continue;; - cpps) cpps="$cpps $arg"; skip=; continue;; - srcs) srcs="$srcs $arg"; skip=; continue;; - esac - case $arg in - -[IDUC]*) cpps="$cpps $arg";; - -[A-Zl]*) libs="$libs $arg";; - *.a) libs="$libs $arg";; - *.o) srcs="$srcs `basename $arg .o`.c";; - *.[cC]) srcs="$srcs $arg";; - *.cc) srcs="$srcs $arg";; - *.c++) srcs="$srcs $arg";; - \$*) libs="$libs $arg" - cpps="$cpps $arg";; - *.*) echo 1>&2 "bad word $arg in $line" - exit 1;; - -u) skip=libs; libs="$libs -u";; - [a-zA-Z_]*) mods="$mods $arg";; - *) echo 1>&2 "bad word $arg in $line" - exit 1;; - esac - done - case $doconfig in - yes) - LIBS="$LIBS $libs" - MODS="$MODS $mods" - ;; - esac - case $noobjects in - yes) continue;; - esac - objs='' - for src in $srcs - do - case $src in - *.c) obj=`basename $src .c`.o; cc='$(CC)';; - *.cc) obj=`basename $src .cc`.o; cc='$(CCC)';; - *.c++) obj=`basename $src .c++`.o; cc='$(CCC)';; - *.C) obj=`basename $src .C`.o; cc='$(CCC)';; - *) continue;; - esac - objs="$objs $obj" - case $src in - glmodule.c) ;; - *) src='$(srcdir)/'$src;; - esac - case $doconfig in - no) cc="$cc \$(CCSHARED)";; - esac - rule="$obj: $src; $cc \$(CFLAGS) $cpps -c $src" - echo "$rule" >>$rulesf - done - case $doconfig in - yes) OBJS="$OBJS $objs";; - esac - for mod in $mods - do - case $objs in - *$mod.o*) base=$mod;; - *) base=${mod}module;; - esac - file="$base\$(SO)" - case $doconfig in - no) SHAREDMODS="$SHAREDMODS $file";; - esac - rule="$file: $objs" - rule="$rule; \$(LDSHARED) $objs $libs -o $file" - echo "$rule" >>$rulesf - done - done - - case $SHAREDMODS in - '') ;; - *) DEFS="SHAREDMODS=$SHAREDMODS$NL$DEFS";; - esac - - case $noobjects in - yes) BASELIBS=$LIBS;; - *) LOCALLIBS=$LIBS;; - esac - LIBS='$(LOCALMODLIBS) $(BASEMODLIBS)' - DEFS="BASEMODLIBS=$BASELIBS$NL$DEFS" - DEFS="LOCALMODLIBS=$LOCALLIBS$NL$DEFS" - - EXTDECLS= - INITBITS= - for mod in $MODS - do - EXTDECLS="${EXTDECLS}extern void init$mod();$NL" - INITBITS="${INITBITS} {\"$mod\", init$mod},$NL" - done - - - case $config in - -) ;; - *) sed -e " - 1i$NL/* Generated automatically from $config by makesetup. */ - /MARKER 1/i$NL$EXTDECLS - /MARKER 2/i$NL$INITBITS - - " $config >config.c - ;; - esac - - case $makepre in - -) ;; - *) sedf="@sed.in.$$" - trap 'rm -f $sedf' 0 1 2 3 - echo "1i\\" >$sedf - str="# Generated automatically from $makepre by makesetup." - echo "$str" >>$sedf - echo "s%_MODOBJS_%$OBJS%" >>$sedf - echo "s%_MODLIBS_%$LIBS%" >>$sedf - echo "/Definitions added by makesetup/a$NL$NL$DEFS" >>$sedf - sed -f $sedf $makepre >Makefile - cat $rulesf >>Makefile - rm -f $sedf - ;; - esac - - rm -f $rulesf -) diff --git a/Modules/mathmodule.c b/Modules/mathmodule.c deleted file mode 100644 index 2beb60913b..0000000000 --- a/Modules/mathmodule.c +++ /dev/null @@ -1,263 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Math module -- standard C math library functions, pi and e */ - -#include "allobjects.h" - -#include <errno.h> - -#define getdoublearg(v, a) getargs(v, "d", a) -#define get2doublearg(v, a, b) getargs(v, "(dd)", a, b) - -#include "mymath.h" - -#ifndef _MSC_VER -#ifndef __STDC__ -extern double fmod PROTO((double, double)); -extern double frexp PROTO((double, int *)); -extern double ldexp PROTO((double, int)); -extern double modf PROTO((double, double *)); -#endif /* __STDC__ */ -#endif /* _MSC_VER */ - - -#if defined(HAVE_HYPOT) && !defined(NeXT) -extern double hypot PROTO((double, double)); -#else -double hypot(x,y) - double x; - double y; -{ - double yx; - - x = fabs(x); - y = fabs(y); - if (x < y) { - double temp = x; - x = y; - y = temp; - } - if (x == 0.) - return 0.; - else { - yx = y/x; - return x*sqrt(1.+yx*yx); - } -} -#endif - -#ifdef i860 -/* Cray APP has bogus definition of HUGE_VAL in <math.h> */ -#undef HUGE_VAL -#endif - -#ifdef HUGE_VAL -#define CHECK(x) if (errno != 0) ; \ - else if (-HUGE_VAL <= (x) && (x) <= HUGE_VAL) ; \ - else errno = ERANGE -#else -#define CHECK(x) /* Don't know how to check */ -#endif - -static object * -math_error() -{ - if (errno == EDOM) - err_setstr(ValueError, "math domain error"); - else if (errno == ERANGE) - err_setstr(OverflowError, "math range error"); - else - err_errno(ValueError); /* Unexpected math error */ - return NULL; -} - -static object * -math_1(args, func) - object *args; - double (*func) FPROTO((double)); -{ - double x; - if (!getdoublearg(args, &x)) - return NULL; - errno = 0; - x = (*func)(x); - CHECK(x); - if (errno != 0) - return math_error(); - else - return newfloatobject(x); -} - -static object * -math_2(args, func) - object *args; - double (*func) FPROTO((double, double)); -{ - double x, y; - if (!get2doublearg(args, &x, &y)) - return NULL; - errno = 0; - x = (*func)(x, y); - CHECK(x); - if (errno != 0) - return math_error(); - else - return newfloatobject(x); -} - -#define FUNC1(stubname, func) \ - static object * stubname(self, args) object *self, *args; { \ - return math_1(args, func); \ - } - -#define FUNC2(stubname, func) \ - static object * stubname(self, args) object *self, *args; { \ - return math_2(args, func); \ - } - -FUNC1(math_acos, acos) -FUNC1(math_asin, asin) -FUNC1(math_atan, atan) -FUNC2(math_atan2, atan2) -FUNC1(math_ceil, ceil) -FUNC1(math_cos, cos) -FUNC1(math_cosh, cosh) -FUNC1(math_exp, exp) -FUNC1(math_fabs, fabs) -FUNC1(math_floor, floor) -FUNC2(math_fmod, fmod) -FUNC2(math_hypot, hypot) -FUNC1(math_log, log) -FUNC1(math_log10, log10) -#ifdef MPW_3_1 /* This hack is needed for MPW 3.1 but not for 3.2 ... */ -FUNC2(math_pow, power) -#else -FUNC2(math_pow, pow) -#endif -FUNC1(math_sin, sin) -FUNC1(math_sinh, sinh) -FUNC1(math_sqrt, sqrt) -FUNC1(math_tan, tan) -FUNC1(math_tanh, tanh) - - -static object * -math_frexp(self, args) - object *self; - object *args; -{ - double x; - int i; - if (!getdoublearg(args, &x)) - return NULL; - errno = 0; - x = frexp(x, &i); - CHECK(x); - if (errno != 0) - return math_error(); - return mkvalue("(di)", x, i); -} - -static object * -math_ldexp(self, args) - object *self; - object *args; -{ - double x, y; - /* Cheat -- allow float as second argument */ - if (!get2doublearg(args, &x, &y)) - return NULL; - errno = 0; - x = ldexp(x, (int)y); - CHECK(x); - if (errno != 0) - return math_error(); - else - return newfloatobject(x); -} - -static object * -math_modf(self, args) - object *self; - object *args; -{ - double x, y; - if (!getdoublearg(args, &x)) - return NULL; - errno = 0; -#ifdef MPW /* MPW C modf expects pointer to extended as second argument */ -{ - extended e; - x = modf(x, &e); - y = e; -} -#else - x = modf(x, &y); -#endif - CHECK(x); - if (errno != 0) - return math_error(); - return mkvalue("(dd)", x, y); -} - -static struct methodlist math_methods[] = { - {"acos", math_acos}, - {"asin", math_asin}, - {"atan", math_atan}, - {"atan2", math_atan2}, - {"ceil", math_ceil}, - {"cos", math_cos}, - {"cosh", math_cosh}, - {"exp", math_exp}, - {"fabs", math_fabs}, - {"floor", math_floor}, - {"fmod", math_fmod}, - {"frexp", math_frexp}, - {"hypot", math_hypot}, - {"ldexp", math_ldexp}, - {"log", math_log}, - {"log10", math_log10}, - {"modf", math_modf}, - {"pow", math_pow}, - {"sin", math_sin}, - {"sinh", math_sinh}, - {"sqrt", math_sqrt}, - {"tan", math_tan}, - {"tanh", math_tanh}, - {NULL, NULL} /* sentinel */ -}; - -void -initmath() -{ - object *m, *d, *v; - - m = initmodule("math", math_methods); - d = getmoduledict(m); - dictinsert(d, "pi", v = newfloatobject(atan(1.0) * 4.0)); - DECREF(v); - dictinsert(d, "e", v = newfloatobject(exp(1.0))); - DECREF(v); -} diff --git a/Modules/md5.h b/Modules/md5.h deleted file mode 100644 index 6a14df6a0a..0000000000 --- a/Modules/md5.h +++ /dev/null @@ -1,94 +0,0 @@ -/* MD5.H - header file for MD5C.C - */ - -/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -rights reserved. - -License to copy and use this software is granted provided that it -is identified as the "RSA Data Security, Inc. MD5 Message-Digest -Algorithm" in all material mentioning or referencing this software -or this function. - -License is also granted to make and use derivative works provided -that such works are identified as "derived from the RSA Data -Security, Inc. MD5 Message-Digest Algorithm" in all material -mentioning or referencing the derived work. - -RSA Data Security, Inc. makes no representations concerning either -the merchantability of this software or the suitability of this -software for any particular purpose. It is provided "as is" -without express or implied warranty of any kind. - -These notices must be retained in any copies of any part of this -documentation and/or software. - */ - -/* ========== include global.h ========== */ -/* GLOBAL.H - RSAREF types and constants - */ - -/* PROTOTYPES should be set to one if and only if the compiler supports - function argument prototyping. -The following makes PROTOTYPES default to 0 if it has not already - been defined with C compiler flags. - */ -#ifdef HAVE_PROTOTYPES -#define PROTOTYPES 1 -#endif -#ifndef PROTOTYPES -#define PROTOTYPES 0 -#endif - -/* POINTER defines a generic pointer type */ -typedef unsigned char *POINTER; - -/* UINT2 defines a two byte word */ -typedef unsigned short int UINT2; - -#ifdef HAVE_LIMITS_H -#include <limits.h> -#else -#ifndef LONG_BIT -#define LONG_BIT 32 -#endif -#endif - -/* UINT4 defines a four byte word */ -#if WORD_BIT == 32 -typedef unsigned int UINT4; -#else -#if LONG_BIT == 32 -typedef unsigned long int UINT4; -#endif -/* Too bad if neither is */ -#endif - -/* PROTO_LIST is defined depending on how PROTOTYPES is defined above. -If using PROTOTYPES, then PROTO_LIST returns the list, otherwise it - returns an empty list. - */ -#if PROTOTYPES -#define PROTO_LIST(list) list -#else -#define PROTO_LIST(list) () -#endif -/* ========== End global.h; continue md5.h ========== */ - -/* MD5 context. */ -typedef struct { - UINT4 state[4]; /* state (ABCD) */ - UINT4 count[2]; /* number of bits, modulo 2^64 (lsb first) */ - unsigned char buffer[64]; /* input buffer */ -} MD5_CTX; - -/* Rename all exported symbols to avoid conflicts with similarly named - symbols in some systems' standard C libraries... */ - -#define MD5Init _Py_MD5Init -#define MD5Update _Py_MD5Update -#define MD5Final _Py_MD5Final - -void MD5Init PROTO_LIST ((MD5_CTX *)); -void MD5Update PROTO_LIST - ((MD5_CTX *, unsigned char *, unsigned int)); -void MD5Final PROTO_LIST ((unsigned char [16], MD5_CTX *)); diff --git a/Modules/md5c.c b/Modules/md5c.c deleted file mode 100644 index d7c7e4fb27..0000000000 --- a/Modules/md5c.c +++ /dev/null @@ -1,337 +0,0 @@ -/* MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm - */ - -/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -rights reserved. - -License to copy and use this software is granted provided that it -is identified as the "RSA Data Security, Inc. MD5 Message-Digest -Algorithm" in all material mentioning or referencing this software -or this function. - -License is also granted to make and use derivative works provided -that such works are identified as "derived from the RSA Data -Security, Inc. MD5 Message-Digest Algorithm" in all material -mentioning or referencing the derived work. - -RSA Data Security, Inc. makes no representations concerning either -the merchantability of this software or the suitability of this -software for any particular purpose. It is provided "as is" -without express or implied warranty of any kind. - -These notices must be retained in any copies of any part of this -documentation and/or software. - */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif -#include "md5.h" - -/* Constants for MD5Transform routine. - */ - -#define S11 7 -#define S12 12 -#define S13 17 -#define S14 22 -#define S21 5 -#define S22 9 -#define S23 14 -#define S24 20 -#define S31 4 -#define S32 11 -#define S33 16 -#define S34 23 -#define S41 6 -#define S42 10 -#define S43 15 -#define S44 21 - -static void MD5Transform PROTO_LIST ((UINT4 [4], unsigned char [64])); -static void Encode PROTO_LIST - ((unsigned char *, UINT4 *, unsigned int)); -static void Decode PROTO_LIST - ((UINT4 *, unsigned char *, unsigned int)); -static void MD5_memcpy PROTO_LIST ((POINTER, POINTER, unsigned int)); -static void MD5_memset PROTO_LIST ((POINTER, int, unsigned int)); - -static unsigned char PADDING[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -/* F, G, H and I are basic MD5 functions. - */ -#define F(x, y, z) (((x) & (y)) | ((~x) & (z))) -#define G(x, y, z) (((x) & (z)) | ((y) & (~z))) -#define H(x, y, z) ((x) ^ (y) ^ (z)) -#define I(x, y, z) ((y) ^ ((x) | (~z))) - -/* ROTATE_LEFT rotates x left n bits. - */ -#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) - -/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. -Rotation is separate from addition to prevent recomputation. - */ -#define FF(a, b, c, d, x, s, ac) { \ - (a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } -#define GG(a, b, c, d, x, s, ac) { \ - (a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } -#define HH(a, b, c, d, x, s, ac) { \ - (a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } -#define II(a, b, c, d, x, s, ac) { \ - (a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } - -/* MD5 initialization. Begins an MD5 operation, writing a new context. - */ -void MD5Init (context) -MD5_CTX *context; /* context */ -{ - context->count[0] = context->count[1] = 0; - /* Load magic initialization constants. -*/ - context->state[0] = 0x67452301; - context->state[1] = 0xefcdab89; - context->state[2] = 0x98badcfe; - context->state[3] = 0x10325476; -} - -/* MD5 block update operation. Continues an MD5 message-digest - operation, processing another message block, and updating the - context. - */ -void MD5Update (context, input, inputLen) -MD5_CTX *context; /* context */ -unsigned char *input; /* input block */ -unsigned int inputLen; /* length of input block */ -{ - unsigned int i, index, partLen; - - /* Compute number of bytes mod 64 */ - index = (unsigned int)((context->count[0] >> 3) & 0x3F); - - /* Update number of bits */ - if ((context->count[0] += ((UINT4)inputLen << 3)) - < ((UINT4)inputLen << 3)) - context->count[1]++; - context->count[1] += ((UINT4)inputLen >> 29); - - partLen = 64 - index; - - /* Transform as many times as possible. -*/ - if (inputLen >= partLen) { - MD5_memcpy - ((POINTER)&context->buffer[index], (POINTER)input, partLen); - MD5Transform (context->state, context->buffer); - - for (i = partLen; i + 63 < inputLen; i += 64) - MD5Transform (context->state, &input[i]); - - index = 0; - } - else - i = 0; - - /* Buffer remaining input */ - MD5_memcpy - ((POINTER)&context->buffer[index], (POINTER)&input[i], - inputLen-i); -} - -/* MD5 finalization. Ends an MD5 message-digest operation, writing the - the message digest and zeroizing the context. - */ -void MD5Final (digest, context) -unsigned char digest[16]; /* message digest */ -MD5_CTX *context; /* context */ -{ - unsigned char bits[8]; - unsigned int index, padLen; - - /* Save number of bits */ - Encode (bits, context->count, 8); - - /* Pad out to 56 mod 64. -*/ - index = (unsigned int)((context->count[0] >> 3) & 0x3f); - padLen = (index < 56) ? (56 - index) : (120 - index); - MD5Update (context, PADDING, padLen); - - /* Append length (before padding) */ - MD5Update (context, bits, 8); - - /* Store state in digest */ - Encode (digest, context->state, 16); - - /* Zeroize sensitive information. -*/ - MD5_memset ((POINTER)context, 0, sizeof (*context)); -} - -/* MD5 basic transformation. Transforms state based on block. - */ -static void MD5Transform (state, block) -UINT4 state[4]; -unsigned char block[64]; -{ - UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; - - Decode (x, block, 64); - - /* Round 1 */ - FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ - FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ - FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ - FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ - FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ - FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ - FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ - FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ - FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ - FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ - FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ - FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ - FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ - FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ - FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ - FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ - - /* Round 2 */ - GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ - GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ - GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ - GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ - GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ - GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ - GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ - GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ - GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ - GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ - GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ - GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ - GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ - GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ - GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ - GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ - - /* Round 3 */ - HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ - HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ - HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ - HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ - HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ - HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ - HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ - HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ - HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ - HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ - HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ - HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ - HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ - HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ - HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ - HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ - - /* Round 4 */ - II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ - II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ - II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ - II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ - II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ - II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ - II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ - II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ - II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ - II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ - II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ - II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ - II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ - II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ - II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ - II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ - - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - - /* Zeroize sensitive information. -*/ - MD5_memset ((POINTER)x, 0, sizeof (x)); -} - -/* Encodes input (UINT4) into output (unsigned char). Assumes len is - a multiple of 4. - */ -static void Encode (output, input, len) -unsigned char *output; -UINT4 *input; -unsigned int len; -{ - unsigned int i, j; - - for (i = 0, j = 0; j < len; i++, j += 4) { - output[j] = (unsigned char)(input[i] & 0xff); - output[j+1] = (unsigned char)((input[i] >> 8) & 0xff); - output[j+2] = (unsigned char)((input[i] >> 16) & 0xff); - output[j+3] = (unsigned char)((input[i] >> 24) & 0xff); - } -} - -/* Decodes input (unsigned char) into output (UINT4). Assumes len is - a multiple of 4. - */ -static void Decode (output, input, len) -UINT4 *output; -unsigned char *input; -unsigned int len; -{ - unsigned int i, j; - - for (i = 0, j = 0; j < len; i++, j += 4) - output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) | - (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24); -} - -/* Note: Replace "for loop" with standard memcpy if possible. - */ - -static void MD5_memcpy (output, input, len) -POINTER output; -POINTER input; -unsigned int len; -{ - unsigned int i; - - for (i = 0; i < len; i++) - output[i] = input[i]; -} - -/* Note: Replace "for loop" with standard memset if possible. - */ -static void MD5_memset (output, value, len) -POINTER output; -int value; -unsigned int len; -{ - unsigned int i; - - for (i = 0; i < len; i++) - ((char *)output)[i] = (char)value; -} diff --git a/Modules/md5module.c b/Modules/md5module.c deleted file mode 100644 index 51c6f6d885..0000000000 --- a/Modules/md5module.c +++ /dev/null @@ -1,200 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* MD5 module */ - -/* This module provides an interface to the RSA Data Security, - Inc. MD5 Message-Digest Algorithm, described in RFC 1321. - It requires the files md5c.c and md5.h (which are slightly changed - from the versions in the RFC to avoid the "global.h" file.) */ - - -/* MD5 objects */ - -#include "allobjects.h" -#include "modsupport.h" - -#include "md5.h" - -typedef struct { - OB_HEAD - MD5_CTX md5; /* the context holder */ -} md5object; - -staticforward typeobject MD5type; - -#define is_md5object(v) ((v)->ob_type == &MD5type) - -static md5object * -newmd5object() -{ - md5object *md5p; - - md5p = NEWOBJ(md5object, &MD5type); - if (md5p == NULL) - return NULL; - - MD5Init(&md5p->md5); /* actual initialisation */ - return md5p; -} - - -/* MD5 methods */ - -static void -md5_dealloc(md5p) - md5object *md5p; -{ - DEL(md5p); -} - - -/* MD5 methods-as-attributes */ - -static object * -md5_update(self, args) - md5object *self; - object *args; -{ - unsigned char *cp; - int len; - - if (!getargs(args, "s#", &cp, &len)) - return NULL; - - MD5Update(&self->md5, cp, len); - - INCREF(None); - return None; -} - -static object * -md5_digest(self, args) - md5object *self; - object *args; -{ - - MD5_CTX mdContext; - unsigned char aDigest[16]; - - if (!getnoarg(args)) - return NULL; - - /* make a temporary copy, and perform the final */ - mdContext = self->md5; - MD5Final(aDigest, &mdContext); - - return newsizedstringobject((char *)aDigest, 16); -} - -static object * -md5_copy(self, args) - md5object *self; - object *args; -{ - md5object *md5p; - - if (!getnoarg(args)) - return NULL; - - if ((md5p = newmd5object()) == NULL) - return NULL; - - md5p->md5 = self->md5; - - return (object *)md5p; -} - -static struct methodlist md5_methods[] = { - {"update", (method)md5_update}, - {"digest", (method)md5_digest}, - {"copy", (method)md5_copy}, - {NULL, NULL} /* sentinel */ -}; - -static object * -md5_getattr(self, name) - md5object *self; - char *name; -{ - return findmethod(md5_methods, (object *)self, name); -} - -statichere typeobject MD5type = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "md5", /*tp_name*/ - sizeof(md5object), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)md5_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)md5_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ -}; - - -/* MD5 functions */ - -static object * -MD5_new(self, args) - object *self; - object *args; -{ - md5object *md5p; - unsigned char *cp = NULL; - int len = 0; - - if (!newgetargs(args, "|s#", &cp, &len)) - return NULL; - - if ((md5p = newmd5object()) == NULL) - return NULL; - - if (cp) - MD5Update(&md5p->md5, cp, len); - - return (object *)md5p; -} - - -/* List of functions exported by this module */ - -static struct methodlist md5_functions[] = { - {"new", (method)MD5_new, 1}, - {"md5", (method)MD5_new, 1}, /* Backward compatibility */ - {NULL, NULL} /* Sentinel */ -}; - - -/* Initialize this module. */ - -void -initmd5() -{ - (void)initmodule("md5", md5_functions); -} diff --git a/Modules/mpzmodule.c b/Modules/mpzmodule.c deleted file mode 100644 index 397f8258ea..0000000000 --- a/Modules/mpzmodule.c +++ /dev/null @@ -1,1809 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* MPZ module */ - -/* This module provides an interface to an alternate Multi-Precision - library, GNU MP in this case */ - -/* XXX note: everywhere where mpz_size is called, - sizeof (limb) == sizeof (long) has been assumed. */ - - -/* MPZ objects */ - -#include "allobjects.h" - -#include <assert.h> -#include <sys/types.h> /* For size_t */ - -/* -** These are the cpp-flags used in this file... -** -** -** MPZ_MDIV_BUG works around the mpz_m{div,mod,...} routines. -** This bug has been fixed in a later release of -** GMP. -** -** MPZ_GET_STR_BUG mpz_get_str corrupts memory, seems to be fixed -** in a later release -** -** MPZ_DEBUG generates a bunch of diagnostic messages -** -** MPZ_SPARE_MALLOC if set, results in extra code that tries to -** minimize the creation of extra objects. -** -** MPZ_TEST_DIV extra diagnostic output on stderr, when division -** routines are involved -** -** MPZ_LIB_DOES_CHECKING if set, assumes that mpz library doesn't call -** alloca with arg < 0 (when casted to a signed -** integral type). -** -** MPZ_CONVERSIONS_AS_METHODS if set, presents the conversions as -** methods. e.g., `mpz(5).long() == 5L' -** Later, Guido provided an interface to the -** standard functions. So this flag has no been -** cleared, and `long(mpz(5)) == 5L' -** -** MP_TEST_ALLOC If set, you would discover why MPZ_GET_STR_BUG -** is needed -** -** MAKEDUMMYINT Must be set if dynamic linking will be used -*/ - - -/* -** IMHO, mpz_m{div,mod,divmod}() do the wrong things when the denominator < 0 -** I assume that this will be fixed in a future release -*/ -/*#define MPZ_MDIV_BUG fixed the (for me) nexessary parts in libgmp.a */ -/* -** IMO, mpz_get_str() assumes a bit too large target space, if he doesn't -** allocate it himself -*/ -#define MPZ_GET_STR_BUG - -#include "gmp.h" -typedef struct { - OB_HEAD - MP_INT mpz; /* the actual number */ -} mpzobject; - -staticforward typeobject MPZtype; - -#define is_mpzobject(v) ((v)->ob_type == &MPZtype) - -static const char initialiser_name[] = "mpz"; - -/* #define MPZ_DEBUG */ - -static mpzobject * -newmpzobject() -{ - mpzobject *mpzp; - - -#ifdef MPZ_DEBUG - fputs( "mpz_object() called...\n", stderr ); -#endif /* def MPZ_DEBUG */ - mpzp = NEWOBJ(mpzobject, &MPZtype); - if (mpzp == NULL) - return NULL; - - mpz_init(&mpzp->mpz); /* actual initialisation */ - return mpzp; -} /* newmpzobject() */ - -#ifdef MPZ_GET_STR_BUG -#include "gmp-impl.h" -#include "longlong.h" -#endif /* def MPZ_GET_STR_BUG */ - -static object * -mpz_format(objp, base, withname) - object *objp; - int base; - unsigned char withname; -{ - mpzobject *mpzp = (mpzobject *)objp; - stringobject *strobjp; - int i; - int cmpres; - int taglong; - char *cp; - char prefix[5], *tcp; - - - tcp = &prefix[0]; - - if (mpzp == NULL || !is_mpzobject(mpzp)) { - err_badcall(); - return NULL; - } - - assert(base >= 2 && base <= 36); - - if (withname) - i = strlen(initialiser_name) + 2; /* e.g. 'mpz(' + ')' */ - else - i = 0; - - if ((cmpres = mpz_cmp_si(&mpzp->mpz, 0L)) == 0) - base = 10; /* '0' in every base, right */ - else if (cmpres < 0) { - *tcp++ = '-'; - i += 1; /* space to hold '-' */ - } - -#ifdef MPZ_DEBUG - fprintf(stderr, "mpz_format: mpz_sizeinbase %d\n", - (int)mpz_sizeinbase(&mpzp->mpz, base)); -#endif /* def MPZ_DEBUG */ -#ifdef MPZ_GET_STR_BUG - i += ((size_t) abs(mpzp->mpz.size) * BITS_PER_MP_LIMB - * __mp_bases[base].chars_per_bit_exactly) + 1; -#else /* def MPZ_GET_STR_BUG */ - i += (int)mpz_sizeinbase(&mpzp->mpz, base); -#endif /* def MPZ_GET_STR_BUG else */ - - if (base == 16) { - *tcp++ = '0'; - *tcp++ = 'x'; - i += 2; /* space to hold '0x' */ - } - else if (base == 8) { - *tcp++ = '0'; - i += 1; /* space to hold the extra '0' */ - } - else if (base > 10) { - *tcp++ = '0' + base / 10; - *tcp++ = '0' + base % 10; - *tcp++ = '#'; - i += 3; /* space to hold e.g. '12#' */ - } - else if (base < 10) { - *tcp++ = '0' + base; - *tcp++ = '#'; - i += 2; /* space to hold e.g. '6#' */ - } - - /* - ** the following code looks if we need a 'L' attached to the number - ** it will also attach an 'L' to the value -0x80000000 - */ - taglong = 0; - if (mpz_size(&mpzp->mpz) > 1 - || (long)mpz_get_ui(&mpzp->mpz) < 0L) { - taglong = 1; - i += 1; /* space to hold 'L' */ - } - -#ifdef MPZ_DEBUG - fprintf(stderr, "mpz_format: requesting string size %d\n", i); -#endif /* def MPZ_DEBUG */ - if ((strobjp = (stringobject *)newsizedstringobject((char *)0, i)) - == NULL) - return NULL; - - /* get the beginning of the string memory and start copying things */ - cp = GETSTRINGVALUE(strobjp); - if (withname) { - strcpy(cp, initialiser_name); - cp += strlen(initialiser_name); - *cp++ = '('; /*')'*/ - } - - /* copy the already prepared prefix; e.g. sign and base indicator */ - *tcp = '\0'; - strcpy(cp, prefix); - cp += tcp - prefix; - - /* since' we have the sign already, let the lib think it's a positive - number */ - if (cmpres < 0) - mpz_neg(&mpzp->mpz,&mpzp->mpz); /* hack Hack HAck HACk HACK */ - (void)mpz_get_str(cp, base, &mpzp->mpz); - if (cmpres < 0) - mpz_neg(&mpzp->mpz,&mpzp->mpz); /* hack Hack HAck HACk HACK */ -#ifdef MPZ_DEBUG - fprintf(stderr, "mpz_format: base (ultim) %d, mpz_get_str: %s\n", - base, cp); -#endif /* def MPZ_DEBUG */ - cp += strlen(cp); - - if (taglong) - *cp++ = 'L'; - if (withname) - *cp++ = /*'('*/ ')'; - - *cp = '\0'; - -#ifdef MPZ_DEBUG - fprintf(stderr, - "mpz_format: cp (str end) 0x%x, begin 0x%x, diff %d, i %d\n", - cp, GETSTRINGVALUE(strobjp), cp - GETSTRINGVALUE(strobjp), i); -#endif /* def MPZ_DEBUG */ - assert(cp - GETSTRINGVALUE(strobjp) <= i); - - if (cp - GETSTRINGVALUE(strobjp) != i) { - strobjp->ob_size -= i - (cp - GETSTRINGVALUE(strobjp)); - } - - return (object *)strobjp; -} /* mpz_format() */ - -/* MPZ methods */ - -static void -mpz_dealloc(mpzp) - mpzobject *mpzp; -{ -#ifdef MPZ_DEBUG - fputs( "mpz_dealloc() called...\n", stderr ); -#endif /* def MPZ_DEBUG */ - mpz_clear(&mpzp->mpz); - DEL(mpzp); -} /* mpz_dealloc() */ - - -/* pointers to frequently used values 0, 1 and -1 */ -static mpzobject *mpz_value_zero, *mpz_value_one, *mpz_value_mone; - -static int -mpz_compare(a, b) - mpzobject *a, *b; -{ - int cmpres; - - - /* guido sez it's better to return -1, 0 or 1 */ - return (cmpres = mpz_cmp( &a->mpz, &b->mpz )) == 0 ? 0 - : cmpres > 0 ? 1 : -1; -} /* mpz_compare() */ - -static object * -mpz_addition(a, b) - mpzobject *a; - mpzobject *b; -{ - mpzobject *z; - - -#ifdef MPZ_SPARE_MALLOC - if (mpz_cmp_ui(&a->mpz, (unsigned long int)0) == 0) { - INCREF(b); - return (object *)b; - } - - if (mpz_cmp_ui(&b->mpz, (unsigned long int)0) == 0) { - INCREF(a); - return (object *)a; - } -#endif /* def MPZ_SPARE_MALLOC */ - - if ((z = newmpzobject()) == NULL) - return NULL; - - mpz_add(&z->mpz, &a->mpz, &b->mpz); - return (object *)z; -} /* mpz_addition() */ - -static object * -mpz_substract(a, b) - mpzobject *a; - mpzobject *b; -{ - mpzobject *z; - - -#ifdef MPZ_SPARE_MALLOC - if (mpz_cmp_ui(&b->mpz, (unsigned long int)0) == 0) { - INCREF(a); - return (object *)a; - } -#endif /* MPZ_SPARE_MALLOC */ - - if ((z = newmpzobject()) == NULL) - return NULL; - - mpz_sub(&z->mpz, &a->mpz, &b->mpz); - return (object *)z; -} /* mpz_substract() */ - -static object * -mpz_multiply(a, b) - mpzobject *a; - mpzobject *b; -{ -#ifdef MPZ_SPARE_MALLOC - int cmpres; -#endif /* def MPZ_SPARE_MALLOC */ - mpzobject *z; - - -#ifdef MPZ_SPARE_MALLOC - if ((cmpres = mpz_cmp_ui(&a->mpz, (unsigned long int)0)) == 0) { - INCREF(mpz_value_zero); - return (object *)mpz_value_zero; - } - if (cmpres > 0 && mpz_cmp_ui(&a->mpz, (unsigned long int)1) == 0) { - INCREF(b); - return (object *)b; - } - - if ((cmpres = mpz_cmp_ui(&b->mpz, (unsigned long_int)0)) == 0) { - INCREF(mpz_value_zero); - return (object *)mpz_value_zero; - } - if (cmpres > 0 && mpz_cmp_ui(&b->mpz, (unsigned long int)1) == 0) { - INCREF(a); - return (object *)a; - } -#endif /* MPZ_SPARE_MALLOC */ - - if ((z = newmpzobject()) == NULL) - return NULL; - - mpz_mul( &z->mpz, &a->mpz, &b->mpz ); - return (object *)z; - -} /* mpz_multiply() */ - -static object * -mpz_divide(a, b) - mpzobject *a; - mpzobject *b; -{ -#ifdef MPZ_SPARE_MALLOC - int cmpres; -#endif /* def MPZ_SPARE_MALLOC */ - mpzobject *z; - - - if (( -#ifdef MPZ_SPARE_MALLOC - cmpres = -#endif /* def MPZ_SPARE_MALLOC */ - mpz_cmp_ui(&b->mpz, (unsigned long int)0)) == 0) { - err_setstr(ZeroDivisionError, "mpz./ by zero"); - return NULL; - } -#ifdef MPZ_SPARE_MALLOC - if (cmpres > 0 && mpz_cmp_ui(&b->mpz(unsigned long int)1) == 0) { - INCREF(a); - return (object *)a; - } -#endif /* def MPZ_SPARE_MALLOC */ - - if ((z = newmpzobject()) == NULL) - return NULL; - -#ifdef MPZ_TEST_DIV - fputs("mpz_divide: div result", stderr); - mpz_div(&z->mpz, &a->mpz, &b->mpz); - mpz_out_str(stderr, 10, &z->mpz); - putc('\n', stderr); -#endif /* def MPZ_TEST_DIV */ -#ifdef MPZ_MDIV_BUG - if ((mpz_cmp_ui(&a->mpz, (unsigned long int)0) < 0) - != (mpz_cmp_ui(&b->mpz, (unsigned long int)0) < 0)) { - /* - ** numerator has other sign than denominator: we have - ** to look at the remainder for a correction, since mpz_mdiv - ** also calls mpz_divmod, I can as well do it myself - */ - MP_INT tmpmpz; - - - mpz_init(&tmpmpz); - mpz_divmod(&z->mpz, &tmpmpz, &a->mpz, &b->mpz); - - if (mpz_cmp_ui(&tmpmpz, (unsigned long int)0) != 0) - mpz_sub_ui(&z->mpz, &z->mpz, (unsigned long int)1); - - mpz_clear(&tmpmpz); - } - else - mpz_div(&z->mpz, &a->mpz, &b->mpz); - /* the ``naive'' implementation does it right for operands - having the same sign */ - -#else /* def MPZ_MDIV_BUG */ - mpz_mdiv(&z->mpz, &a->mpz, &b->mpz); -#endif /* def MPZ_MDIV_BUG else */ -#ifdef MPZ_TEST_DIV - fputs("mpz_divide: mdiv result", stderr); - mpz_out_str(stderr, 10, &z->mpz); - putc('\n', stderr); -#endif /* def MPZ_TEST_DIV */ - return (object *)z; - -} /* mpz_divide() */ - -static object * -mpz_remainder(a, b) - mpzobject *a; - mpzobject *b; -{ -#ifdef MPZ_SPARE_MALLOC - int cmpres; -#endif /* def MPZ_SPARE_MALLOC */ - mpzobject *z; - - - if (( -#ifdef MPZ_SPARE_MALLOC - cmpres = -#endif /* def MPZ_SPARE_MALLOC */ - mpz_cmp_ui(&b->mpz, (unsigned long int)0)) == 0) { - err_setstr(ZeroDivisionError, "mpz.% by zero"); - return NULL; - } -#ifdef MPZ_SPARE_MALLOC - if (cmpres > 0) { - if ((cmpres = mpz_cmp_ui(&b->mpz, (unsigned long int)2)) == 0) { - INCREF(mpz_value_one); - return (object *)mpz_value_one; - } - if (cmpres < 0) { - /* b must be 1 now */ - INCREF(mpz_value_zero); - return (object *)mpz_value_zero; - } - } -#endif /* def MPZ_SPARE_MALLOC */ - - if ((z = newmpzobject()) == NULL) - return NULL; - -#ifdef MPZ_TEST_DIV - fputs("mpz_remain: mod result", stderr); - mpz_mod(&z->mpz, &a->mpz, &b->mpz); - mpz_out_str(stderr, 10, &z->mpz); - putc('\n', stderr); -#endif /* def MPZ_TEST_DIV */ -#ifdef MPZ_MDIV_BUG - - /* the ``naive'' implementation does it right for operands - having the same sign */ - mpz_mod(&z->mpz, &a->mpz, &b->mpz); - - /* assumption: z, a and b all point to different locations */ - if ((mpz_cmp_ui(&a->mpz, (unsigned long int)0) < 0) - != (mpz_cmp_ui(&b->mpz, (unsigned long int)0) < 0) - && mpz_cmp_ui(&z->mpz, (unsigned long int)0) != 0) - mpz_add(&z->mpz, &z->mpz, &b->mpz); - /* - ** numerator has other sign than denominator: we have - ** to look at the remainder for a correction, since mpz_mdiv - ** also calls mpz_divmod, I can as well do it myself - */ -#else /* def MPZ_MDIV_BUG */ - mpz_mmod(&z->mpz, &a->mpz, &b->mpz); -#endif /* def MPZ_MDIV_BUG else */ -#ifdef MPZ_TEST_DIV - fputs("mpz_remain: mmod result", stderr); - mpz_out_str(stderr, 10, &z->mpz); - putc('\n', stderr); -#endif /* def MPZ_TEST_DIV */ - return (object *)z; - -} /* mpz_remainder() */ - -static object * -mpz_div_and_mod(a, b) - mpzobject *a; - mpzobject *b; -{ - object *z = NULL; - mpzobject *x = NULL, *y = NULL; - - - if (mpz_cmp_ui(&b->mpz, (unsigned long int)0) == 0) { - err_setstr(ZeroDivisionError, "mpz.divmod by zero"); - return NULL; - } - - if ((z = newtupleobject(2)) == NULL - || (x = newmpzobject()) == NULL - || (y = newmpzobject()) == NULL) { - XDECREF(z); - XDECREF(x); - XDECREF(y); - return NULL; - } - -#ifdef MPZ_TEST_DIV - fputs("mpz_divmod: dm result", stderr); - mpz_divmod(&x->mpz, &y->mpz, &a->mpz, &b->mpz); - mpz_out_str(stderr, 10, &x->mpz); - putc('\n', stderr); - mpz_out_str(stderr, 10, &y->mpz); - putc('\n', stderr); -#endif /* def MPZ_TEST_DIV */ -#ifdef MPZ_MDIV_BUG - mpz_divmod(&x->mpz, &y->mpz, &a->mpz, &b->mpz); - if ((mpz_cmp_ui(&a->mpz, (unsigned long int)0) < 0) - != (mpz_cmp_ui(&b->mpz, (unsigned long int)0) < 0) - && mpz_cmp_ui(&y->mpz, (unsigned long int)0) != 0) { - /* - ** numerator has other sign than denominator: we have - ** to look at the remainder for a correction. - */ - mpz_add(&y->mpz, &y->mpz, &b->mpz); - mpz_sub_ui(&x->mpz, &x->mpz, (unsigned long int)1); - } -#else /* def MPZ_MDIV_BUG */ - mpz_mdivmod( &x->mpz, &y->mpz, &a->mpz, &b->mpz ); -#endif /* def MPZ_MDIV_BUG else */ -#ifdef MPZ_TEST_DIV - fputs("mpz_divmod: mdm result", stderr); - mpz_out_str(stderr, 10, &x->mpz); - putc('\n', stderr); - mpz_out_str(stderr, 10, &y->mpz); - putc('\n', stderr); -#endif /* def MPZ_TEST_DIV */ - - (void)settupleitem(z, 0, (object *)x); - (void)settupleitem(z, 1, (object *)y); - - return z; -} /* mpz_div_and_mod() */ - -static object * -mpz_power(a, b, m) - mpzobject *a; - mpzobject *b; - mpzobject *m; -{ - mpzobject *z; - int cmpres; - long int longtmp1, longtmp2; - - if ((object *)m!=Py_None) - { - mpzobject *z2; - INCREF(Py_None); - z=(mpzobject *)mpz_power(a, b, (mpzobject *)Py_None); - DECREF(Py_None); - if (z==NULL) return((object *)z); - z2=(mpzobject *)mpz_remainder(z, m); - DECREF(z); - return((object *)z2); - } - - if ((cmpres = mpz_cmp_ui(&b->mpz, (unsigned long int)0)) == 0) { - /* the gnu-mp lib sets pow(0,0) to 0, we to 1 */ - - INCREF(mpz_value_one); - return (object *)mpz_value_one; - } - - if (cmpres < 0) { - err_setstr(ValueError, "mpz.pow to negative exponent"); - return NULL; - } - - if ((cmpres = mpz_cmp_ui(&a->mpz, (unsigned long int)0)) == 0) { - /* the base is 0 */ - - INCREF(mpz_value_zero); - return (object *)mpz_value_zero; - } - else if (cmpres > 0 - && mpz_cmp_ui(&a->mpz, (unsigned long int)1) == 0) { - /* the base is 1 */ - - INCREF(mpz_value_one); - return (object *)mpz_value_one; - } - else if (cmpres < 0 - && mpz_cmp_si(&a->mpz, (long int)-1) == 0) { - - MP_INT tmpmpz; - /* the base is -1: pow(-1, any) == 1,-1 for even,uneven b */ - /* XXX this code needs to be optimized: what's better? - mpz_mmod_ui or mpz_mod_2exp, I choose for the latter - for *un*obvious reasons */ - - /* is the exponent even? */ - mpz_init(&tmpmpz); - - /* look to the remainder after a division by (1 << 1) */ - mpz_mod_2exp(&tmpmpz, &b->mpz, (unsigned long int)1); - - if (mpz_cmp_ui(&tmpmpz, (unsigned int)0) == 0) { - mpz_clear(&tmpmpz); - INCREF(mpz_value_one); - return (object *)mpz_value_one; - } - mpz_clear(&tmpmpz); - INCREF(mpz_value_mone); - return (object *)mpz_value_mone; - } - -#ifdef MPZ_LIB_DOES_CHECKING - /* check if it's doable: sizeof(exp) > sizeof(long) && - abs(base) > 1 ?? --> No Way */ - if (mpz_size(&b->mpz) > 1) - return (object *)err_nomem(); -#else /* def MPZ_LIB_DOES_CHECKING */ - /* wet finger method */ - if (mpz_cmp_ui(&b->mpz, (unsigned long int)0x10000) >= 0) { - err_setstr(ValueError, "mpz.pow outrageous exponent"); - return NULL; - } -#endif /* def MPZ_LIB_DOES_CHECKING else */ - - if ((z = newmpzobject()) == NULL) - return NULL; - - mpz_pow_ui(&z->mpz, &a->mpz, mpz_get_ui(&b->mpz)); - - return (object *)z; -} /* mpz_power() */ - - -static object * -mpz_negative(v) - mpzobject *v; -{ - mpzobject *z; - - -#ifdef MPZ_SPARE_MALLOC - if (mpz_cmp_ui(&v->mpz, (unsigned long int)0) == 0) { - /* -0 == 0 */ - INCREF(v); - return (object *)v; - } -#endif /* def MPZ_SPARE_MALLOC */ - - if ((z = newmpzobject()) == NULL) - return NULL; - - mpz_neg(&z->mpz, &v->mpz); - return (object *)z; -} /* mpz_negative() */ - - -static object * -mpz_positive(v) - mpzobject *v; -{ - INCREF(v); - return (object *)v; -} /* mpz_positive() */ - - -static object * -mpz_absolute(v) - mpzobject *v; -{ - mpzobject *z; - - - if (mpz_cmp_ui(&v->mpz, (unsigned long int)0) >= 0) { - INCREF(v); - return (object *)v; - } - - if ((z = newmpzobject()) == NULL) - return NULL; - - mpz_neg(&z->mpz, &v->mpz); - return (object *)z; -} /* mpz_absolute() */ - -static int -mpz_nonzero(v) - mpzobject *v; -{ - return mpz_cmp_ui(&v->mpz, (unsigned long int)0) != 0; -} /* mpz_nonzero() */ - -static object * -mpz_invert(v) - mpzobject *v; -{ - mpzobject *z; - - - /* I think mpz_com does exactly what needed */ - if ((z = newmpzobject()) == NULL) - return NULL; - - mpz_com(&z->mpz, &v->mpz); - return (object *)z; -} /* mpz_invert() */ - -static object * -mpz_lshift(a, b) - mpzobject *a; - mpzobject *b; -{ - int cmpres; - mpzobject *z; - - - if ((cmpres = mpz_cmp_ui(&b->mpz, (unsigned long int)0)) == 0) { - /* a << 0 == a */ - INCREF(a); - return (object *)a; - } - - if (cmpres < 0) { - err_setstr(ValueError, "mpz.<< negative shift count"); - return NULL; - } - -#ifdef MPZ_LIB_DOES_CHECKING - if (mpz_size(&b->mpz) > 1) - return (object *)err_nomem(); -#else /* def MPZ_LIB_DOES_CHECKING */ - /* wet finger method */ - if (mpz_cmp_ui(&b->mpz, (unsigned long int)0x10000) >= 0) { - err_setstr(ValueError, "mpz.<< outrageous shift count"); - return NULL; - } -#endif /* def MPZ_LIB_DOES_CHECKING else */ - - if ((z = newmpzobject()) == NULL) - return NULL; - - mpz_mul_2exp(&z->mpz, &a->mpz, mpz_get_ui(&b->mpz)); - return (object *)z; -} /* mpz_lshift() */ - -static object * -mpz_rshift(a, b) - mpzobject *a; - mpzobject *b; -{ - int cmpres; - mpzobject *z; - - - if ((cmpres = mpz_cmp_ui(&b->mpz, (unsigned long int)0)) == 0) { - /* a >> 0 == a */ - INCREF(a); - return (object *)a; - } - - if (cmpres < 0) { - err_setstr(ValueError, "mpz.>> negative shift count"); - return NULL; - } - - if (mpz_size(&b->mpz) > 1) - return (object *)err_nomem(); - - if ((z = newmpzobject()) == NULL) - return NULL; - - mpz_div_2exp(&z->mpz, &a->mpz, mpz_get_ui(&b->mpz)); - return (object *)z; -} /* mpz_rshift() */ - -static object * -mpz_andfunc(a, b) - mpzobject *a; - mpzobject *b; -{ - mpzobject *z; - - - if ((z = newmpzobject()) == NULL) - return NULL; - - mpz_and(&z->mpz, &a->mpz, &b->mpz); - return (object *)z; -} /* mpz_andfunc() */ - -/* hack Hack HAck HACk HACK, XXX this code is dead slow */ -void -mpz_xor(res, op1, op2) - MP_INT *res; - const MP_INT *op1; - const MP_INT *op2; -{ - MP_INT tmpmpz; - - mpz_init(&tmpmpz); - - mpz_and(res, op1, op2); - mpz_com(&tmpmpz, res); - mpz_ior(res, op1, op2); - mpz_and(res, res, &tmpmpz); - - mpz_clear(&tmpmpz); -} /* mpz_xor() HACK */ - -static object * -mpz_xorfunc(a, b) - mpzobject *a; - mpzobject *b; -{ - mpzobject *z; - - - if ((z = newmpzobject()) == NULL) - return NULL; - - mpz_xor(&z->mpz, &a->mpz, &b->mpz); - return (object *)z; -} /* mpz_xorfunc() */ - -static object * -mpz_orfunc(a, b) - mpzobject *a; - mpzobject *b; -{ - mpzobject *z; - - - if ((z = newmpzobject()) == NULL) - return NULL; - - mpz_ior(&z->mpz, &a->mpz, &b->mpz); - return (object *)z; -} /* mpz_orfunc() */ - -/* MPZ initialisation */ - -#include "longintrepr.h" - -static object * -MPZ_mpz(self, args) - object *self; - object *args; -{ - mpzobject *mpzp; - object *objp; - - -#ifdef MPZ_DEBUG - fputs("MPZ_mpz() called...\n", stderr); -#endif /* def MPZ_DEBUG */ - - if (!getargs(args, "O", &objp)) - return NULL; - - /* at least we know it's some object */ - /* note DON't DECREF args NEITHER objp */ - - if (is_intobject(objp)) { - long lval; - - if (!getargs(objp, "l", &lval)) - return NULL; - - if (lval == (long)0) { - INCREF(mpz_value_zero); - mpzp = mpz_value_zero; - } - else if (lval == (long)1) { - INCREF(mpz_value_one); - mpzp = mpz_value_one; - } - else if ((mpzp = newmpzobject()) == NULL) - return NULL; - else mpz_set_si(&mpzp->mpz, lval); - } - else if (is_longobject(objp)) { - MP_INT mplongdigit; - int i; - unsigned char isnegative; - - - if ((mpzp = newmpzobject()) == NULL) - return NULL; - - mpz_set_si(&mpzp->mpz, 0L); - mpz_init(&mplongdigit); - - /* how we're gonna handle this? */ - if (isnegative = ((i = ((longobject *)objp)->ob_size) < 0) ) - i = -i; - - while (i--) { - mpz_set_ui(&mplongdigit, - (unsigned long) - ((longobject *)objp)->ob_digit[i]); - mpz_mul_2exp(&mplongdigit,&mplongdigit, - (unsigned long int)i * SHIFT); - mpz_ior(&mpzp->mpz, &mpzp->mpz, &mplongdigit); - } - - if (isnegative) - mpz_neg(&mpzp->mpz, &mpzp->mpz); - - /* get rid of allocation for tmp variable */ - mpz_clear(&mplongdigit); - } - else if (is_stringobject(objp)) { - char *cp; - int len; - MP_INT mplongdigit; - - if (!getargs(objp, "s#", &cp, &len)) - return NULL; - - if ((mpzp = newmpzobject()) == NULL) - return NULL; - - mpz_set_si(&mpzp->mpz, 0L); - mpz_init(&mplongdigit); - - /* let's do it the same way as with the long conversion: - without thinking how it can be faster (-: :-) */ - - cp += len; - while (len--) { - mpz_set_ui(&mplongdigit, (unsigned long)*--cp ); - mpz_mul_2exp(&mplongdigit,&mplongdigit, - (unsigned long int)len * 8); - mpz_ior(&mpzp->mpz, &mpzp->mpz, &mplongdigit); - } - - /* get rid of allocation for tmp variable */ - mpz_clear(&mplongdigit); - } - else if (is_mpzobject(objp)) { - INCREF(objp); - mpzp = (mpzobject *)objp; - } - else { - err_setstr(TypeError, - "mpz.mpz() expects integer, long, string or mpz object argument"); - return NULL; - } - - -#ifdef MPZ_DEBUG - fputs("MPZ_mpz: created mpz=", stderr); - mpz_out_str(stderr, 10, &mpzp->mpz); - putc('\n', stderr); -#endif /* def MPZ_DEBUG */ - return (object *)mpzp; -} /* MPZ_mpz() */ - -static mpzobject * -mpz_mpzcoerce(z) - object *z; -{ - /* shortcut: 9 out of 10 times the type is already ok */ - if (is_mpzobject(z)) { - INCREF(z); - return (mpzobject *)z; /* coercion succeeded */ - } - - /* what types do we accept?: intobjects and longobjects */ - if (is_intobject(z) || is_longobject(z)) - return (mpzobject *)MPZ_mpz((object *)NULL, z); - - err_setstr(TypeError, "number coercion (to mpzobject) failed"); - return NULL; -} /* mpz_mpzcoerce() */ - -/* Forward */ -static void mpz_divm PROTO((MP_INT *res, const MP_INT *num, - const MP_INT *den, const MP_INT *mod)); - -static object * -MPZ_powm(self, args) - object *self; - object *args; -{ - object *base, *exp, *mod; - mpzobject *mpzbase = NULL, *mpzexp = NULL, *mpzmod = NULL; - mpzobject *z; - int tstres; - - - if (!getargs(args, "(OOO)", &base, &exp, &mod)) - return NULL; - - if ((mpzbase = mpz_mpzcoerce(base)) == NULL - || (mpzexp = mpz_mpzcoerce(exp)) == NULL - || (mpzmod = mpz_mpzcoerce(mod)) == NULL - || (z = newmpzobject()) == NULL) { - XDECREF(mpzbase); - XDECREF(mpzexp); - XDECREF(mpzmod); - return NULL; - } - - if ((tstres=mpz_cmp_ui(&mpzexp->mpz, (unsigned long int)0)) == 0) { - INCREF(mpz_value_one); - return (object *)mpz_value_one; - } - - if (tstres < 0) { - MP_INT absexp; - /* negative exp */ - - mpz_init_set(&absexp, &mpzexp->mpz); - mpz_abs(&absexp, &absexp); - mpz_powm(&z->mpz, &mpzbase->mpz, &absexp, &mpzmod->mpz); - - mpz_divm(&z->mpz, &mpz_value_one->mpz, &z->mpz, &mpzmod->mpz); - - mpz_clear(&absexp); - } - else { - mpz_powm(&z->mpz, &mpzbase->mpz, &mpzexp->mpz, &mpzmod->mpz); - } - - DECREF(mpzbase); - DECREF(mpzexp); - DECREF(mpzmod); - - return (object *)z; -} /* MPZ_powm() */ - - -static object * -MPZ_gcd(self, args) - object *self; - object *args; -{ - object *op1, *op2; - mpzobject *mpzop1 = NULL, *mpzop2 = NULL; - mpzobject *z; - - - if (!getargs(args, "(OO)", &op1, &op2)) - return NULL; - - if ((mpzop1 = mpz_mpzcoerce(op1)) == NULL - || (mpzop2 = mpz_mpzcoerce(op2)) == NULL - || (z = newmpzobject()) == NULL) { - XDECREF(mpzop1); - XDECREF(mpzop2); - return NULL; - } - - /* ok, we have three mpzobjects, and an initialised result holder */ - mpz_gcd(&z->mpz, &mpzop1->mpz, &mpzop2->mpz); - - DECREF(mpzop1); - DECREF(mpzop2); - - return (object *)z; -} /* MPZ_gcd() */ - - -static object * -MPZ_gcdext(self, args) - object *self; - object *args; -{ - object *op1, *op2, *z = NULL; - mpzobject *mpzop1 = NULL, *mpzop2 = NULL; - mpzobject *g = NULL, *s = NULL, *t = NULL; - - - if (!getargs(args, "(OO)", &op1, &op2)) - return NULL; - - if ((mpzop1 = mpz_mpzcoerce(op1)) == NULL - || (mpzop2 = mpz_mpzcoerce(op2)) == NULL - || (z = newtupleobject(3)) == NULL - || (g = newmpzobject()) == NULL - || (s = newmpzobject()) == NULL - || (t = newmpzobject()) == NULL) { - XDECREF(mpzop1); - XDECREF(mpzop2); - XDECREF(z); - XDECREF(g); - XDECREF(s); - /*XDECREF(t);*/ - return NULL; - } - - mpz_gcdext(&g->mpz, &s->mpz, &t->mpz, &mpzop1->mpz, &mpzop2->mpz); - - DECREF(mpzop1); - DECREF(mpzop2); - - (void)settupleitem(z, 0, (object *)g); - (void)settupleitem(z, 1, (object *)s); - (void)settupleitem(z, 2, (object *)t); - - return (object *)z; -} /* MPZ_gcdext() */ - - -static object * -MPZ_sqrt(self, args) - object *self; - object *args; -{ - object *op; - mpzobject *mpzop = NULL; - mpzobject *z; - - - if (!getargs(args, "O", &op)) - return NULL; - - if ((mpzop = mpz_mpzcoerce(op)) == NULL - || (z = newmpzobject()) == NULL) { - XDECREF(mpzop); - return NULL; - } - - mpz_sqrt(&z->mpz, &mpzop->mpz); - - DECREF(mpzop); - - return (object *)z; -} /* MPZ_sqrt() */ - - -static object * -MPZ_sqrtrem(self, args) - object *self; - object *args; -{ - object *op, *z = NULL; - mpzobject *mpzop = NULL; - mpzobject *root = NULL, *rem = NULL; - - - if (!getargs(args, "O", &op)) - return NULL; - - if ((mpzop = mpz_mpzcoerce(op)) == NULL - || (z = newtupleobject(2)) == NULL - || (root = newmpzobject()) == NULL - || (rem = newmpzobject()) == NULL) { - XDECREF(mpzop); - XDECREF(z); - XDECREF(root); - /*XDECREF(rem);*/ - return NULL; - } - - mpz_sqrtrem(&root->mpz, &rem->mpz, &mpzop->mpz); - - DECREF(mpzop); - - (void)settupleitem(z, 0, (object *)root); - (void)settupleitem(z, 1, (object *)rem); - - return (object *)z; -} /* MPZ_sqrtrem() */ - - -static void -#if __STDC__ -mpz_divm(MP_INT *res, const MP_INT *num, const MP_INT *den, const MP_INT *mod) -#else -mpz_divm(res, num, den, mod) - MP_INT *res; - const MP_INT *num; - const MP_INT *den; - const MP_INT *mod; -#endif -{ - MP_INT s0, s1, q, r, x, d0, d1; - - mpz_init_set(&s0, num); - mpz_init_set_ui(&s1, 0); - mpz_init(&q); - mpz_init(&r); - mpz_init(&x); - mpz_init_set(&d0, den); - mpz_init_set(&d1, mod); - - while (d1.size != 0) { - mpz_divmod(&q, &r, &d0, &d1); - mpz_set(&d0, &d1); - mpz_set(&d1, &r); - - mpz_mul(&x, &s1, &q); - mpz_sub(&x, &s0, &x); - mpz_set(&s0, &s1); - mpz_set(&s1, &x); - } - - if (d0.size != 1 || d0.d[0] != 1) - res->size = 0; /* trouble: the gcd != 1; set s to zero */ - else { -#ifdef MPZ_MDIV_BUG - /* watch out here! first check the signs, and then perform - the mpz_mod() since mod could point to res */ - if ((s0.size < 0) != (mod->size < 0)) { - mpz_mod(res, &s0, mod); - - if (res->size) - mpz_add(res, res, mod); - } - else - mpz_mod(res, &s0, mod); - -#else /* def MPZ_MDIV_BUG */ - mpz_mmod(res, &s0, mod); -#endif /* def MPZ_MDIV_BUG else */ - } - - mpz_clear(&s0); - mpz_clear(&s1); - mpz_clear(&q); - mpz_clear(&r); - mpz_clear(&x); - mpz_clear(&d0); - mpz_clear(&d1); -} /* mpz_divm() */ - - -static object * -MPZ_divm(self, args) - object *self; - object *args; -{ - object *num, *den, *mod; - mpzobject *mpznum, *mpzden, *mpzmod = NULL; - mpzobject *z = NULL; - - - if (!getargs(args, "(OOO)", &num, &den, &mod)) - return NULL; - - if ((mpznum = mpz_mpzcoerce(num)) == NULL - || (mpzden = mpz_mpzcoerce(den)) == NULL - || (mpzmod = mpz_mpzcoerce(mod)) == NULL - || (z = newmpzobject()) == NULL ) { - XDECREF(mpznum); - XDECREF(mpzden); - XDECREF(mpzmod); - return NULL; - } - - mpz_divm(&z->mpz, &mpznum->mpz, &mpzden->mpz, &mpzmod->mpz); - - DECREF(mpznum); - DECREF(mpzden); - DECREF(mpzmod); - - if (mpz_cmp_ui(&z->mpz, (unsigned long int)0) == 0) { - DECREF(z); - err_setstr(ValueError, "gcd(den, mod) != 1 or num == 0"); - return NULL; - } - - return (object *)z; -} /* MPZ_divm() */ - - -/* MPZ methods-as-attributes */ -#ifdef MPZ_CONVERSIONS_AS_METHODS -static object * -mpz_int(self, args) - mpzobject *self; - object *args; -#else /* def MPZ_CONVERSIONS_AS_METHODS */ -static object * -mpz_int(self) - mpzobject *self; -#endif /* def MPZ_CONVERSIONS_AS_METHODS else */ -{ - long sli; - - -#ifdef MPZ_CONVERSIONS_AS_METHODS - if (!getnoarg(args)) - return NULL; -#endif /* def MPZ_CONVERSIONS_AS_METHODS */ - - if (mpz_size(&self->mpz) > 1 - || (sli = (long)mpz_get_ui(&self->mpz)) < (long)0 ) { - err_setstr(ValueError, "mpz.int() arg too long to convert"); - return NULL; - } - - if (mpz_cmp_ui(&self->mpz, (unsigned long)0) < 0) - sli = -sli; - - return newintobject(sli); -} /* mpz_int() */ - -static object * -#ifdef MPZ_CONVERSIONS_AS_METHODS -mpz_long(self, args) - mpzobject *self; - object *args; -#else /* def MPZ_CONVERSIONS_AS_METHODS */ -mpz_long(self) - mpzobject *self; -#endif /* def MPZ_CONVERSIONS_AS_METHODS else */ -{ - int i, isnegative; - unsigned long int uli; - longobject *longobjp; - int ldcount; - int bitpointer, newbitpointer; - MP_INT mpzscratch; - - -#ifdef MPZ_CONVERSIONS_AS_METHODS - if (!getnoarg(args)) - return NULL; -#endif /* def MPZ_CONVERSIONS_AS_METHODS */ - - /* determine length of python-long to be allocated */ - if ((longobjp = alloclongobject(i = (int) - ((mpz_size(&self->mpz) * BITS_PER_MP_LIMB - + SHIFT - 1) / - SHIFT))) == NULL) - return NULL; - - /* determine sign, and copy self to scratch var */ - mpz_init_set(&mpzscratch, &self->mpz); - if (isnegative = (mpz_cmp_ui(&self->mpz, (unsigned long int)0) < 0)) - mpz_neg(&mpzscratch, &mpzscratch); - - /* let those bits come, let those bits go, - e.g. dismantle mpzscratch, build longobject */ - - bitpointer = 0; /* the number of valid bits in stock */ - newbitpointer = 0; - ldcount = 0; /* the python-long limb counter */ - uli = (unsigned long int)0; - while (i--) { - longobjp->ob_digit[ldcount] = uli & MASK; - - /* check if we've had enough bits for this digit */ - if (bitpointer < SHIFT) { - uli = mpz_get_ui(&mpzscratch); - longobjp->ob_digit[ldcount] |= - (uli << bitpointer) & MASK; - uli >>= SHIFT-bitpointer; - bitpointer += BITS_PER_MP_LIMB; - mpz_div_2exp(&mpzscratch, &mpzscratch, - BITS_PER_MP_LIMB); - } - else - uli >>= SHIFT; - bitpointer -= SHIFT; - ldcount++; - } - - assert(mpz_cmp_ui(&mpzscratch, (unsigned long int)0) == 0); - mpz_clear(&mpzscratch); - assert(ldcount <= longobjp->ob_size); - - /* long_normalize() is file-static */ - /* longobjp = long_normalize(longobjp); */ - while (ldcount > 0 && longobjp->ob_digit[ldcount-1] == 0) - ldcount--; - longobjp->ob_size = ldcount; - - - if (isnegative) - longobjp->ob_size = -longobjp->ob_size; - - return (object *)longobjp; - -} /* mpz_long() */ - - -/* I would have avoided pow() anyways, so ... */ -static const double multiplier = 256.0 * 256.0 * 256.0 * 256.0; - -#ifdef MPZ_CONVERSIONS_AS_METHODS -static object * -mpz_float(self, args) - mpzobject *self; - object *args; -#else /* def MPZ_CONVERSIONS_AS_METHODS */ -static object * -mpz_float(self) - mpzobject *self; -#endif /* def MPZ_CONVERSIONS_AS_METHODS else */ -{ - int i, isnegative; - double x; - double mulstate; - MP_INT mpzscratch; - - -#ifdef MPZ_CONVERSIONS_AS_METHODS - if (!getnoarg(args)) - return NULL; -#endif /* def MPZ_CONVERSIONS_AS_METHODS */ - - i = (int)mpz_size(&self->mpz); - - /* determine sign, and copy abs(self) to scratch var */ - if (isnegative = (mpz_cmp_ui(&self->mpz, (unsigned long int)0) < 0)) { - mpz_init(&mpzscratch); - mpz_neg(&mpzscratch, &self->mpz); - } - else - mpz_init_set(&mpzscratch, &self->mpz); - - /* let those bits come, let those bits go, - e.g. dismantle mpzscratch, build floatobject */ - - x = 0.0; - mulstate = 1.0; - while (i--) { - x += mulstate * mpz_get_ui(&mpzscratch); - mulstate *= multiplier; - mpz_div_2exp(&mpzscratch, &mpzscratch, BITS_PER_MP_LIMB); - } - - assert(mpz_cmp_ui(&mpzscratch, (unsigned long int)0) == 0); - mpz_clear(&mpzscratch); - - if (isnegative) - x = -x; - - return newfloatobject(x); - -} /* mpz_float() */ - -#ifdef MPZ_CONVERSIONS_AS_METHODS -static object * -mpz_hex(self, args) - mpzobject *self; - object *args; -#else /* def MPZ_CONVERSIONS_AS_METHODS */ -static object * -mpz_hex(self) - mpzobject *self; -#endif /* def MPZ_CONVERSIONS_AS_METHODS else */ -{ -#ifdef MPZ_CONVERSIONS_AS_METHODS - if (!getnoarg(args)) - return NULL; -#endif /* def MPZ_CONVERSIONS_AS_METHODS */ - - return mpz_format(self, 16, (unsigned char)1); -} /* mpz_hex() */ - -#ifdef MPZ_CONVERSIONS_AS_METHODS -static object * -mpz_oct(self, args) - mpzobject *self; - object *args; -#else /* def MPZ_CONVERSIONS_AS_METHODS */ -static object * -mpz_oct(self) - mpzobject *self; -#endif /* def MPZ_CONVERSIONS_AS_METHODS else */ -{ -#ifdef MPZ_CONVERSIONS_AS_METHODS - if (!getnoarg(args)) - return NULL; -#endif /* def MPZ_CONVERSIONS_AS_METHODS */ - - return mpz_format(self, 8, (unsigned char)1); -} /* mpz_oct() */ - -static object * -mpz_binary(self, args) - mpzobject *self; - object *args; -{ - int size; - stringobject *strobjp; - char *cp; - MP_INT mp; - unsigned long ldigit; - - if (!getnoarg(args)) - return NULL; - - if (mpz_cmp_ui(&self->mpz, (unsigned long int)0) < 0) { - err_setstr(ValueError, "mpz.binary() arg must be >= 0"); - return NULL; - } - - mpz_init_set(&mp, &self->mpz); - size = (int)mpz_size(&mp); - - if ((strobjp = (stringobject *) - newsizedstringobject((char *)0, - size * sizeof (unsigned long int))) == NULL) - return NULL; - - /* get the beginning of the string memory and start copying things */ - cp = GETSTRINGVALUE(strobjp); - - /* this has been programmed using a (fairly) decent lib-i/f it could - be must faster if we looked into the GMP lib */ - while (size--) { - ldigit = mpz_get_ui(&mp); - mpz_div_2exp(&mp, &mp, BITS_PER_MP_LIMB); - *cp++ = (unsigned char)(ldigit & 0xFF); - *cp++ = (unsigned char)((ldigit >>= 8) & 0xFF); - *cp++ = (unsigned char)((ldigit >>= 8) & 0xFF); - *cp++ = (unsigned char)((ldigit >>= 8) & 0xFF); - } - - while (strobjp->ob_size && !*--cp) - strobjp->ob_size--; - - return (object *)strobjp; -} /* mpz_binary() */ - - -static struct methodlist mpz_methods[] = { -#ifdef MPZ_CONVERSIONS_AS_METHODS - {"int", mpz_int}, - {"long", mpz_long}, - {"float", mpz_float}, - {"hex", mpz_hex}, - {"oct", mpz_oct}, -#endif /* def MPZ_CONVERSIONS_AS_METHODS */ - {"binary", (object *(*)(object *, object *))mpz_binary}, - {NULL, NULL} /* sentinel */ -}; - -static object * -mpz_getattr(self, name) - mpzobject *self; - char *name; -{ - return findmethod(mpz_methods, (object *)self, name); -} /* mpz_getattr() */ - - -static int -mpz_coerce(pv, pw) - object **pv; - object **pw; -{ - object *z; - -#ifdef MPZ_DEBUG - fputs("mpz_coerce() called...\n", stderr); -#endif /* def MPZ_DEBUG */ - - assert(is_mpzobject(*pv)); - - /* always convert other arg to mpz value, except for floats */ - if (!is_floatobject(*pw)) { - if ((z = (object *)mpz_mpzcoerce(*pw)) == NULL) - return -1; /* -1: an error always has been set */ - - INCREF(*pv); - *pw = z; - } - else { - if ((z = mpz_float(*pv, NULL)) == NULL) - return -1; - - INCREF(*pw); - *pv = z; - } - return 0; /* coercion succeeded */ - -} /* mpz_coerce() */ - - -static object * -mpz_repr(v) - object *v; -{ - return mpz_format(v, 10, (unsigned char)1); -} /* mpz_repr() */ - - - -#define UF (unaryfunc) -#define BF (binaryfunc) -#define TF (ternaryfunc) -#define IF (inquiry) -#define CF (coercion) - -static number_methods mpz_as_number = { - BF mpz_addition, /*nb_add*/ - BF mpz_substract, /*nb_subtract*/ - BF mpz_multiply, /*nb_multiply*/ - BF mpz_divide, /*nb_divide*/ - BF mpz_remainder, /*nb_remainder*/ - BF mpz_div_and_mod, /*nb_divmod*/ - TF mpz_power, /*nb_power*/ - UF mpz_negative, /*nb_negative*/ - UF mpz_positive, /*tp_positive*/ - UF mpz_absolute, /*tp_absolute*/ - IF mpz_nonzero, /*tp_nonzero*/ - UF mpz_invert, /*nb_invert*/ - BF mpz_lshift, /*nb_lshift*/ - BF mpz_rshift, /*nb_rshift*/ - BF mpz_andfunc, /*nb_and*/ - BF mpz_xorfunc, /*nb_xor*/ - BF mpz_orfunc, /*nb_or*/ - CF mpz_coerce, /*nb_coerce*/ -#ifndef MPZ_CONVERSIONS_AS_METHODS - UF mpz_int, /*nb_int*/ - UF mpz_long, /*nb_long*/ - UF mpz_float, /*nb_float*/ - UF mpz_oct, /*nb_oct*/ - UF mpz_hex, /*nb_hex*/ -#endif /* ndef MPZ_CONVERSIONS_AS_METHODS */ -}; - -static typeobject MPZtype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "mpz", /*tp_name*/ - sizeof(mpzobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)mpz_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)mpz_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)mpz_compare, /*tp_compare*/ - (reprfunc)mpz_repr, /*tp_repr*/ - &mpz_as_number, /*tp_as_number*/ -}; - -/* List of functions exported by this module */ - -static struct methodlist mpz_functions[] = { -#if 0 - {initialiser_name, MPZ_mpz}, -#else /* 0 */ - /* until guido ``fixes'' struct methodlist */ - {(char *)initialiser_name, MPZ_mpz}, -#endif /* 0 else */ - {"powm", MPZ_powm}, - {"gcd", MPZ_gcd}, - {"gcdext", MPZ_gcdext}, - {"sqrt", MPZ_sqrt}, - {"sqrtrem", MPZ_sqrtrem}, - {"divm", MPZ_divm}, - {NULL, NULL} /* Sentinel */ -}; - - -/* #define MP_TEST_ALLOC */ - -#ifdef MP_TEST_ALLOC -#define MP_TEST_SIZE 4 -static const char mp_test_magic[MP_TEST_SIZE] = {'\xAA','\xAA','\xAA','\xAA'}; -static mp_test_error( location ) - int *location; -{ - /* assumptions: *alloc returns address dividable by 4, - mpz_* routines allocate in chunks dividable by four */ - fprintf(stderr, "MP_TEST_ERROR: location holds 0x%08d\n", *location ); - fatal("MP_TEST_ERROR"); -} /* static mp_test_error() */ -#define MP_EXTRA_ALLOC(size) ((size) + MP_TEST_SIZE) -#define MP_SET_TEST(basep,size) (void)memcpy( ((char *)(basep))+(size), mp_test_magic, MP_TEST_SIZE) -#define MP_DO_TEST(basep,size) if ( !memcmp( ((char *)(basep))+(size), mp_test_magic, MP_TEST_SIZE ) ) \ - ; \ - else \ - mp_test_error((int *)((char *)(basep) + size)) -#else /* def MP_TEST_ALLOC */ -#define MP_EXTRA_ALLOC(size) (size) -#define MP_SET_TEST(basep,size) -#define MP_DO_TEST(basep,size) -#endif /* def MP_TEST_ALLOC else */ - -void *mp_allocate( alloc_size ) - size_t alloc_size; -{ - void *res; - -#ifdef MPZ_DEBUG - fprintf(stderr, "mp_allocate : size %ld\n", - alloc_size); -#endif /* def MPZ_DEBUG */ - - if ( (res = malloc(MP_EXTRA_ALLOC(alloc_size))) == NULL ) - fatal("mp_allocate failure"); - -#ifdef MPZ_DEBUG - fprintf(stderr, "mp_allocate : address 0x%08x\n", res); -#endif /* def MPZ_DEBUG */ - - MP_SET_TEST(res,alloc_size); - - return res; -} /* mp_allocate() */ - - -void *mp_reallocate( ptr, old_size, new_size ) - void *ptr; - size_t old_size; - size_t new_size; -{ - void *res; - -#ifdef MPZ_DEBUG - fprintf(stderr, "mp_reallocate: old address 0x%08x, old size %ld\n", - ptr, old_size); -#endif /* def MPZ_DEBUG */ - - MP_DO_TEST(ptr, old_size); - - if ( (res = realloc(ptr, MP_EXTRA_ALLOC(new_size))) == NULL ) - fatal("mp_reallocate failure"); - -#ifdef MPZ_DEBUG - fprintf(stderr, "mp_reallocate: new address 0x%08x, new size %ld\n", - res, new_size); -#endif /* def MPZ_DEBUG */ - - MP_SET_TEST(res, new_size); - - return res; -} /* mp_reallocate() */ - - -void mp_free( ptr, size ) - void *ptr; - size_t size; -{ - -#ifdef MPZ_DEBUG - fprintf(stderr, "mp_free : old address 0x%08x, old size %ld\n", - ptr, size); -#endif /* def MPZ_DEBUG */ - - MP_DO_TEST(ptr, size); - free(ptr); -} /* mp_free() */ - - - -/* Initialize this module. */ - -void -initmpz() -{ -#ifdef MPZ_DEBUG - fputs( "initmpz() called...\n", stderr ); -#endif /* def MPZ_DEBUG */ - - mp_set_memory_functions( mp_allocate, mp_reallocate, mp_free ); - (void)initmodule("mpz", mpz_functions); - - /* create some frequently used constants */ - if ((mpz_value_zero = newmpzobject()) == NULL) - fatal("initmpz: can't initialize mpz constants"); - mpz_set_ui(&mpz_value_zero->mpz, (unsigned long int)0); - - if ((mpz_value_one = newmpzobject()) == NULL) - fatal("initmpz: can't initialize mpz constants"); - mpz_set_ui(&mpz_value_one->mpz, (unsigned long int)1); - - if ((mpz_value_mone = newmpzobject()) == NULL) - fatal("initmpz: can't initialize mpz constants"); - mpz_set_si(&mpz_value_mone->mpz, (long)-1); - -} /* initmpz() */ -#ifdef MAKEDUMMYINT -int _mpz_dummy_int; /* XXX otherwise, we're .bss-less (DYNLOAD->Jack?) */ -#endif /* def MAKEDUMMYINT */ diff --git a/Modules/newmodule.c b/Modules/newmodule.c deleted file mode 100644 index afe309243b..0000000000 --- a/Modules/newmodule.c +++ /dev/null @@ -1,186 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Module new -- create new objects of various types */ - -#include "allobjects.h" -#include "compile.h" - -static char new_im_doc[] = -"Create a instance method object from (FUNCTION, INSTANCE, CLASS)."; - -static object * -new_instancemethod(unused, args) - object* unused; - object* args; -{ - object* func; - object* self; - object* classObj; - - if (!newgetargs(args, "O!O!O!", - &Functype, &func, - &Instancetype, &self, - &Classtype, &classObj)) - return NULL; - return newinstancemethodobject(func, self, classObj); -} - -/* XXX These internal interfaces have changed -- who'll fix this code? */ -#if 0 - -static char new_function_doc[] = -"Create a function object from (CODE, GLOBALS, [NAME, ARGCOUNT, ARGDEFS])."; - -static object * -new_function(unused, args) - object* unused; - object* args; -{ - object* code; - object* globals; - object* name = None; - int argcount = -1; - object* argdefs = None; - funcobject* newfunc; - - if (!newgetargs(args, "O!O!|SiO!", - &Codetype, &code, - &Mappingtype, &globals, - &name, - &argcount, - &Tupletype, &argdefs)) - return NULL; - - newfunc = (funcobject *)newfuncobject(code, globals); - if (newfunc == NULL) - return NULL; - - if (name != None) { - XINCREF(name); - XDECREF(newfunc->func_name); - newfunc->func_name = name; - } - newfunc->func_argcount = argcount; - if (argdefs != NULL) { - XINCREF(argdefs); - XDECREF(newfunc->func_argdefs); - newfunc->func_argdefs = argdefs; - } - - return (object *)newfunc; -} -#endif - -static char new_code_doc[] = -"Create a code object from (ARGCOUNT, NLOCALS, FLAGS, CODESTRING, CONSTANTS, NAMES, VARNAMES, FILENAME, NAME)."; - -static object * -new_code(unused, args) - object* unused; - object* args; -{ - int argcount; - int nlocals; - int flags; - object* code; - object* consts; - object* names; - object* varnames; - object* filename; - object* name; - -#if 0 - if (!newgetargs(args, "SO!O!SS", - &code, &Tupletype, &consts, &Tupletype, &names, - &filename, &name)) - return NULL; - return (object *)newcodeobject(code, consts, names, filename, name); -#else - if (!newgetargs(args, "iiiSO!O!O!SS", - &argcount, &nlocals, &flags, /* These are new */ - &code, &Tupletype, &consts, &Tupletype, &names, - &Tupletype, &varnames, /* These are new */ - &filename, &name)) - return NULL; - return (object *)newcodeobject(argcount, nlocals, flags, - code, consts, names, varnames, filename, name); -#endif -} - -static char new_module_doc[] = -"Create a module object from (NAME)."; - -static object * -new_module(unused, args) - object* unused; - object* args; -{ - char *name; - - if (!newgetargs(args, "s", &name)) - return NULL; - return newmoduleobject(name); -} - -static char new_class_doc[] = -"Create a class object from (NAME, BASE_CLASSES, DICT)."; - -static object * -new_class(unused, args) - object* unused; - object* args; -{ - object * name; - object * classes; - object * dict; - - if (!newgetargs(args, "SO!O!", &name, &Tupletype, &classes, - &Mappingtype, &dict)) - return NULL; - return newclassobject(classes, dict, name); -} - -static struct methodlist new_methods[] = { - {"instancemethod", new_instancemethod, 1, new_im_doc}, -#if 0 - {"function", new_function, 1, new_function_doc}, -#endif - {"code", new_code, 1, new_code_doc}, - {"module", new_module, 1, new_module_doc}, - {"classobj", new_class, 1, new_class_doc}, - {NULL, NULL} /* sentinel */ -}; - -char new_doc[] = -"Functions to create new objects used by the interpreter.\n\ -\n\ -You need to know a great deal about the interpreter to use this!"; - -void -initnew() -{ - initmodule4("new", new_methods, new_doc, (object *)NULL, - PYTHON_API_VERSION); -} diff --git a/Modules/nismodule.c b/Modules/nismodule.c deleted file mode 100644 index 00c35616bf..0000000000 --- a/Modules/nismodule.c +++ /dev/null @@ -1,344 +0,0 @@ -/*********************************************************** - Written by: - Fred Gansevles <Fred.Gansevles@cs.utwente.nl> - Vakgroep Spa, - Faculteit der Informatica, - Universiteit Twente, - Enschede, - the Netherlands. -******************************************************************/ - -/* NIS module implementation */ - -#include "allobjects.h" -#include "modsupport.h" -#include "ceval.h" - -#include <rpcsvc/ypclnt.h> -#include <sys/time.h> -#include <sys/types.h> -#include <rpc/rpc.h> -#include <rpcsvc/yp_prot.h> - -static object *NisError; - -static object * -nis_error (err) - int err; -{ - err_setstr(NisError, yperr_string(err)); - return NULL; -} - -static struct nis_map { - char *alias; - char *map; -} aliases [] = { - {"passwd", "passwd.byname"}, - {"group", "group.byname"}, - {"networks", "networks.byaddr"}, - {"hosts", "hosts.byname"}, - {"protocols", "protocols.bynumber"}, - {"services", "services.byname"}, - {"aliases", "mail.aliases"}, - {"ethers", "ethers.byname"}, - {0L, 0L} -}; - -static char * -nis_mapname (map) - char *map; -{ - int i; - - for (i=0; aliases[i].alias != 0L; i++) - if (!strcmp (aliases[i].alias, map)) - map = aliases[i].map; - return map; -} - -typedef int (*foreachfunc) PROTO((int, char *, int, char *, int, char *)); - -static int -nis_foreach (instatus, inkey, inkeylen, inval, invallen, indata) - int instatus; - char *inkey; - int inkeylen; - char *inval; - int invallen; - object *indata; -{ - if (instatus == YP_TRUE) { - object *key = newsizedstringobject(inkey, inkeylen); - object *val = newsizedstringobject(inval, invallen); - int err; - if (key == NULL || val == NULL) { - /* XXX error -- don't know how to handle */ - err_clear(); - XDECREF(key); - XDECREF(val); - return 1; - } - err = mappinginsert(indata, key, val); - DECREF(key); - DECREF(val); - if (err != 0) { - err_clear(); - return 1; - } - return 0; - } - return 1; -} - -static object * -nis_match (self, args) - object *self; - object *args; -{ - char *match; - char *domain; - int keylen, len; - char *key, *map; - int err; - object *res; - - if (!getargs(args, "(s#s)", &key, &keylen, &map)) - return NULL; - if ((err = yp_get_default_domain(&domain)) != 0) - return nis_error(err); - BGN_SAVE - map = nis_mapname (map); - err = yp_match (domain, map, key, keylen, &match, &len); - END_SAVE - if (err != 0) - return nis_error(err); - res = newsizedstringobject (match, len); - free (match); - return res; -} - -static object * -nis_cat (self, args) - object *self; - object *args; -{ - char *domain; - char *map; - struct ypall_callback cb; - object *cat; - int err; - - if (!getstrarg(args, &map)) - return NULL; - if ((err = yp_get_default_domain(&domain)) != 0) - return nis_error(err); - cat = newdictobject (); - if (cat == NULL) - return NULL; - cb.foreach = (foreachfunc)nis_foreach; - cb.data = (char *)cat; - BGN_SAVE - map = nis_mapname (map); - err = yp_all (domain, map, &cb); - END_SAVE - if (err != 0) { - DECREF(cat); - return nis_error(err); - } - return cat; -} - -/* These should be u_long on Sun h/w but not on 64-bit h/w. - This is not portable to machines with 16-bit ints and no prototypes */ -#ifndef YPPROC_MAPLIST -#define YPPROC_MAPLIST 11 -#endif -#ifndef YPPROG -#define YPPROG 100004 -#endif -#ifndef YPVERS -#define YPVERS 2 -#endif - -typedef char *domainname; -typedef char *mapname; - -enum nisstat { - NIS_TRUE = 1, - NIS_NOMORE = 2, - NIS_FALSE = 0, - NIS_NOMAP = -1, - NIS_NODOM = -2, - NIS_NOKEY = -3, - NIS_BADOP = -4, - NIS_BADDB = -5, - NIS_YPERR = -6, - NIS_BADARGS = -7, - NIS_VERS = -8 -}; -typedef enum nisstat nisstat; - -struct nismaplist { - mapname map; - struct nismaplist *next; -}; -typedef struct nismaplist nismaplist; - -struct nisresp_maplist { - nisstat stat; - nismaplist *maps; -}; -typedef struct nisresp_maplist nisresp_maplist; - -static struct timeval TIMEOUT = { 25, 0 }; - -static -bool_t -nis_xdr_domainname(xdrs, objp) - XDR *xdrs; - domainname *objp; -{ - if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) { - return (FALSE); - } - return (TRUE); -} - -static -bool_t -nis_xdr_mapname(xdrs, objp) - XDR *xdrs; - mapname *objp; -{ - if (!xdr_string(xdrs, objp, YPMAXMAP)) { - return (FALSE); - } - return (TRUE); -} - -static -bool_t -nis_xdr_ypmaplist(xdrs, objp) - XDR *xdrs; - nismaplist *objp; -{ - if (!nis_xdr_mapname(xdrs, &objp->map)) { - return (FALSE); - } - if (!xdr_pointer(xdrs, (char **)&objp->next, sizeof(nismaplist), nis_xdr_ypmaplist)) { - return (FALSE); - } - return (TRUE); -} - -static -bool_t -nis_xdr_ypstat(xdrs, objp) - XDR *xdrs; - nisstat *objp; -{ - if (!xdr_enum(xdrs, (enum_t *)objp)) { - return (FALSE); - } - return (TRUE); -} - - -static -bool_t -nis_xdr_ypresp_maplist(xdrs, objp) - XDR *xdrs; - nisresp_maplist *objp; -{ - if (!nis_xdr_ypstat(xdrs, &objp->stat)) { - return (FALSE); - } - if (!xdr_pointer(xdrs, (char **)&objp->maps, sizeof(nismaplist), nis_xdr_ypmaplist)) { - return (FALSE); - } - return (TRUE); -} - - -static -nisresp_maplist * -nisproc_maplist_2(argp, clnt) - domainname *argp; - CLIENT *clnt; -{ - static nisresp_maplist res; - - memset(&res, 0, sizeof(res)); - if (clnt_call(clnt, YPPROC_MAPLIST, nis_xdr_domainname, (caddr_t)argp, - nis_xdr_ypresp_maplist, (caddr_t)&res, TIMEOUT) - != RPC_SUCCESS) { - return (NULL); - } - return (&res); -} - -static -nismaplist * -nis_maplist () -{ - nisresp_maplist *list; - char *dom; - CLIENT *cl, *clnt_create(); - char *server; - - yp_get_default_domain (&dom); - yp_master (dom, aliases[0].map, &server); - cl = clnt_create(server, YPPROG, YPVERS, "tcp"); - if (cl == NULL) { - clnt_pcreateerror(server); - return NULL; - } - list = nisproc_maplist_2 (&dom, cl); - if (list == NULL) - return NULL; - if (list->stat != NIS_TRUE) - return NULL; - return list->maps; -} - -static object * -nis_maps (self, args) - object *self; - object *args; -{ - nismaplist *maps; - object *list; - - if ((maps = nis_maplist ()) == NULL) - return NULL; - if ((list = newlistobject(0)) == NULL) - return NULL; - for (maps = maps->next; maps; maps = maps->next) { - if (addlistitem (list, newstringobject (maps->map)) < 0) { - DECREF(list); - list = NULL; - break; - } - } - /* XXX Shouldn't we free the list of maps now? */ - return list; -} - -static struct methodlist nis_methods[] = { - {"match", nis_match}, - {"cat", nis_cat}, - {"maps", nis_maps}, - {NULL, NULL} /* Sentinel */ -}; - -void -initnis () -{ - object *m, *d; - m = initmodule("nis", nis_methods); - d = getmoduledict(m); - NisError = newstringobject("nis.error"); - if (NisError == NULL || dictinsert(d, "error", NisError) != 0) - fatal("Cannot define nis.error"); -} diff --git a/Modules/objc.c b/Modules/objc.c deleted file mode 100644 index 9e70912712..0000000000 --- a/Modules/objc.c +++ /dev/null @@ -1,651 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Objective-C interface for NeXTStep */ -/* Tested with NeXTStep 3.3 on Intel and Sparc architectures */ - -/* Original author: Jon M. Kutemeier */ -/* Revamped and maintained by: Guido van Rossum */ - -/* XXX To do: - - bug??? x.send('name', []) gives weird error - - rename functions from objc_* to ObjC_* - - change send(sel, [a, b, c]) to send(self, a, b, c) - - call back to Python from Objective-C - */ - -/* Python header file */ -#include "Python.h" - -/* NeXT headers */ -#include <sys/param.h> -#include <mach-o/rld.h> -#include <objc/objc.h> -#include <objc/objc-runtime.h> -#import <remote/NXProxy.h> - -/* Distinguish between ObjC classes and instances */ -typedef enum { - OBJC_CLASS, - OBJC_INSTANCE, -} ObjC_Typecode; - -/* Exception raised for ObjC specific errors */ -static PyObject *ObjC_Error; - -/* Python wrapper about ObjC id (instance or class) */ -typedef struct { - PyObject_HEAD - id obj; - ObjC_Typecode type; - int owned; -} ObjCObject; - -/* Corresponding Python type object */ -staticforward PyTypeObject ObjC_Type; - -/* Corresponding Python type check macro */ -#define ObjC_Check(o) ((o)->ob_type == &ObjC_Type) - -/* Create a new ObjCObject */ -static ObjCObject * -newObjCObject(obj, type, owned) - id obj; - ObjC_Typecode type; - int owned; -{ - ObjCObject *self; - - self = PyObject_NEW(ObjCObject, &ObjC_Type); - if (self == NULL) - return NULL; - - self->obj = obj; - self->type = type; - self->owned = owned; - - return self; -} - -static void -objc_sendfree(self) - ObjCObject *self; -{ - if (self->obj) - self->obj = (id)objc_msgSend(self->obj, SELUID("free")); -} - -/* Deallocate an ObjCObject */ -static void -objc_dealloc(self) - ObjCObject *self; -{ - if (self->owned) - objc_sendfree(self); - PyMem_DEL(self); -} - -/* Return a string representation of an ObjCObject */ -static PyObject * -objc_repr(self) - ObjCObject *self; -{ - char buffer[512]; - char *p = buffer; - if (self->obj == nil) - p = "<Objective-C nil>"; - else { - char *t; - switch (self->type) { - case OBJC_CLASS: t = "class"; break; - case OBJC_INSTANCE: t = "instance"; break; - default: t = "???"; break; - } - sprintf(buffer, "<Objective-C %s %s at %lx>", - NAMEOF(self->obj), t, (long)(self->obj)); - } - return PyString_FromString(p); -} - -/*** ObjCObject methods ***/ - -/* Call an object's free method */ -static PyObject * -objc_free(self, args) - ObjCObject *self; - PyObject *args; -{ - if (!PyArg_ParseTuple(args, "")) - return NULL; - objc_sendfree(self); -} - -/* Send a message to an ObjCObject. - The Python call looks like e.g. obj.send('moveTo::', [arg1, arg2]) - which translates into Objective-C as [obj moveTo: arg1 : arg2] */ -static PyObject * -objc_send(self, args) - ObjCObject *self; - PyObject *args; -{ - char *methodname; - char *margBuff = NULL; - PyObject *retobject = NULL; - PyObject *arglist; - id receiver, obj; - char *type; - SEL sel; - Method meth; - unsigned int margCount, margSize; - int offset, i; - - if (!PyArg_ParseTuple(args, "sO!", &methodname, &PyList_Type, &arglist)) - return NULL; - - /* Get the method descriptor from the object */ - - receiver = self->obj; - sel = SELUID(methodname); - - switch(self->type) { - case OBJC_CLASS: - meth = class_getClassMethod(receiver->isa, sel); - break; - case OBJC_INSTANCE: - meth = class_getInstanceMethod(receiver->isa, sel); - break; - default: - PyErr_SetString(ObjC_Error, - "receiver's type is neither instance not class!?!?"); - return NULL; - } - - if (!meth) { - PyErr_SetString(ObjC_Error, "receiver has no method by that name"); - return NULL; - } - - /* Fill in the argument list, type-checking the arguments */ - - margCount = method_getNumberOfArguments(meth); - - if (PyList_Size(arglist) + 2 != margCount) { - PyErr_SetString(ObjC_Error, - "wrong number of arguments for this method"); - return NULL; - } - - margSize = method_getSizeOfArguments(meth); - margBuff = PyMem_NEW(char, margSize+1); - if (margBuff == NULL) - return PyErr_NoMemory(); - - method_getArgumentInfo(meth, 0, &type, &offset); - marg_setValue(margBuff, offset, id, receiver); - - method_getArgumentInfo(meth, 1, &type, &offset); - marg_setValue(margBuff, offset, SEL, sel); - - for (i = 2; i < margCount; i++) { - PyObject *argument; - method_getArgumentInfo(meth, i, &type, &offset); - - argument = PyList_GetItem(arglist, i-2); - - /* scan past protocol-type modifiers */ - while (strchr("rnNoOV", *type) != 0) - type++; - - /* common type checks */ - switch(*type) { - - /* XXX The errors here should point out which argument */ - - case 'c': - case '*': - case 'C': - if (!PyString_Check(argument)) { - PyErr_SetString(ObjC_Error, "string argument expected"); - goto error; - } - break; - - case 'i': - case 's': - case 'I': - case 'S': - case 'l': - case 'L': - case '^': - if (!PyInt_Check(argument)) { - PyErr_SetString(ObjC_Error, "integer argument expected"); - goto error; - } - break; - - case 'f': - case 'd': - if (!PyFloat_Check(argument)) { - PyErr_SetString(ObjC_Error, "float argument expected"); - goto error; - } - break; - - } - - /* convert and store the argument */ - switch (*type) { - - case 'c': /* char */ - marg_setValue(margBuff, offset, char, - PyString_AsString(argument)[0]); - break; - - case 'C': /* unsigned char */ - marg_setValue(margBuff, offset, unsigned char, - PyString_AsString(argument)[0]); - break; - - case '*': /* string */ - marg_setValue(margBuff, offset, char *, - PyString_AsString(argument)); - break; - - case 'i': /* int */ - marg_setValue(margBuff, offset, int, - PyInt_AsLong(argument)); - break; - - case 'I': /* unsigned int */ - marg_setValue(margBuff, offset, unsigned int, - PyInt_AsLong(argument)); - break; - - case 's': /* short */ - marg_setValue(margBuff, offset, short, - PyInt_AsLong(argument)); - break; - - case 'S': /* unsigned short */ - marg_setValue(margBuff, offset, unsigned short, - PyInt_AsLong(argument)); - break; - - case 'l': /* long */ - marg_setValue(margBuff, offset, long, - PyInt_AsLong(argument)); - break; - - case 'L': /* unsigned long */ - marg_setValue(margBuff, offset, unsigned long, - PyInt_AsLong(argument)); - break; - - case 'f': /* float */ - marg_setValue(margBuff, offset, float, - (float)PyFloat_AsDouble(argument)); - break; - - case 'd': /* double */ - marg_setValue(margBuff, offset, double, - PyFloat_AsDouble(argument)); - break; - - case '@': /* id (or None) */ - if (ObjC_Check(argument)) - marg_setValue(margBuff, offset, id, - ((ObjCObject *)(argument))->obj); - else if (argument == Py_None) - marg_setValue(margBuff, offset, id, nil); - else { - PyErr_SetString(ObjC_Error, "id or None argument expected"); - goto error; - } - break; - - case '^': /* void * (use int) */ - marg_setValue(margBuff, offset, void *, - (void *)PyInt_AsLong(argument)); - break; - - case ':': /* SEL (use string or int) */ - if (PyInt_Check(argument)) - marg_setValue(margBuff, offset, SEL, - (SEL)PyInt_AsLong(argument)); - else if (PyString_Check(argument)) - marg_setValue(margBuff, offset, SEL, - SELUID(PyString_AsString(argument))); - else { - PyErr_SetString(ObjC_Error, - "selector string or int argument expected"); - goto error; - } - break; - - case '#': /* Class (may also use int) */ - if (ObjC_Check(argument) && - ((ObjCObject *)argument)->type == OBJC_INSTANCE) - marg_setValue(margBuff, offset, Class *, - (Class *)((ObjCObject *)argument)->obj); - else if (PyInt_Check(argument)) - marg_setValue(margBuff, offset, Class *, - (Class *)PyInt_AsLong(argument)); - else { - PyErr_SetString(ObjC_Error, - "ObjC class object required"); - goto error; - } - break; - - default: - PyErr_SetString(ObjC_Error, "unknown argument type"); - goto error; - - } - } - - /* Call the method and set the return value */ - - type = meth->method_types; - - while (strchr("rnNoOV", *type)) - type++; - - switch(*type) { - -/* Cast objc_msgSendv to a function returning the right thing */ -#define MS_CAST(type) ((type (*)())objc_msgSendv) - - case 'c': - case '*': - case 'C': - retobject = (PyObject *)PyString_FromString( - MS_CAST(char *)(receiver, sel, margSize, margBuff)); - break; - - case 'i': - case 's': - case 'I': - case 'S': - retobject = (PyObject *)PyInt_FromLong( - MS_CAST(int)(receiver, sel, margSize, margBuff)); - break; - - case 'l': - case 'L': - case '^': - retobject = (PyObject *)PyInt_FromLong( - MS_CAST(long)(receiver, sel, margSize, margBuff)); - break; - - case 'f': - retobject = (PyObject *)PyFloat_FromDouble( - MS_CAST(float)(receiver, sel, margSize, margBuff)); - break; - - case 'd': - retobject = (PyObject *)PyFloat_FromDouble( - MS_CAST(double)(receiver, sel, margSize, margBuff)); - break; - - case '@': - obj = MS_CAST(id)(receiver, sel, margSize, margBuff); - if (obj == nil) { - retobject = Py_None; - Py_INCREF(retobject); - } - else if (obj != receiver) - retobject = (PyObject *)newObjCObject(obj, OBJC_INSTANCE, 0); - else { - retobject = (PyObject *)self; - Py_INCREF(retobject); - } - break; - - case ':': - retobject = (PyObject *)PyInt_FromLong( - (long)MS_CAST(SEL)(receiver, sel, margSize, margBuff)); - break; - - case '#': - retobject = (PyObject *)PyInt_FromLong( - (long)MS_CAST(Class *)(receiver, sel, margSize, margBuff)); - break; - -#undef MS_CAST - - } - - error: - PyMem_XDEL(margBuff); - return retobject; -} - -/* List of methods for ObjCObject */ -static PyMethodDef objc_methods[] = { - {"send", (PyCFunction)objc_send, 1}, - {"free", (PyCFunction)objc_free, 1}, - {NULL, NULL} /* sentinel */ -}; - -/* Get an attribute of an ObjCObject */ -static PyObject * -objc_getattr(self, name) - ObjCObject *self; - char *name; -{ - PyObject *method; - - /* Try a function method */ - method = Py_FindMethod(objc_methods, (PyObject *)self, name); - if (method != NULL) - return method; - PyErr_Clear(); - - /* Try an instance variable */ - if (strcmp(name, "obj") == 0) - return PyInt_FromLong((long)self->obj); - if (strcmp(name, "type") == 0) - return PyInt_FromLong((long)self->type); - if (strcmp(name, "owned") == 0) - return PyInt_FromLong((long)self->owned); - if (strcmp(name, "name") == 0) - return PyString_FromString(NAMEOF(self->obj)); - if (strcmp(name, "__members__") == 0) - return Py_BuildValue("[sss]", "name", "obj", "owned", "type"); - - PyErr_SetString(PyExc_AttributeError, name); - return NULL; -} - -/* The type object */ -static PyTypeObject ObjC_Type = { - PyObject_HEAD_INIT(&PyType_Type) - 0, /*ob_size*/ - "objc", /*tp_name*/ - sizeof(ObjCObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)objc_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)objc_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - (reprfunc)objc_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, 0, 0, 0, /*xxx1-4*/ - "Objective-C id wrapper", /*tp_doc*/ -}; - - - -/*** Top-level functions ***/ - -/* Max #files passed to loadobjectfile() */ -#define MAXRLD 128 - -/* Load a list of object files */ -static PyObject * -objc_loadobjectfiles(self, args) -PyObject *self; /* Not used */ -PyObject *args; -{ - NXStream *errorStream; - struct mach_header *new_header; - const char *filenames[MAXRLD+1]; - long ret; - char *streamBuf; - PyObject *filelist, *file; - int listsize, len, maxLen, i; - - if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &filelist)) - return NULL; - - listsize = PyList_Size(filelist); - - if (listsize > MAXRLD) { - PyErr_SetString(ObjC_Error, "more than 128 files in list"); - return NULL; - } - - errorStream = NXOpenMemory(NULL, 0, NX_WRITEONLY); - - for (i = 0; i < listsize; i++) { - file = PyList_GetItem(filelist, i); - - if (!PyString_Check(file)) - { - PyErr_SetString(ObjC_Error, - "all list items must be strings"); - return NULL; - } - - filenames[i] = PyString_AsString(file); - } - - filenames[listsize] = NULL; - - ret = objc_loadModules(filenames, errorStream, NULL, &new_header, NULL); - - /* extract the error messages for the exception */ - - if(ret) { - NXPutc(errorStream, (char)0); - - NXGetMemoryBuffer(errorStream, &streamBuf, &len, &maxLen); - PyErr_SetString(ObjC_Error, streamBuf); - } - - NXCloseMemory(errorStream, NX_FREEBUFFER); - - if(ret) - return NULL; - - Py_XINCREF(Py_None); - return Py_None; -} - -static PyObject * -objc_lookupclass(self, args) -PyObject *self; /* Not used */ -PyObject *args; -{ - char *classname; - id class; - - if (!PyArg_ParseTuple(args, "s", &classname)) - return NULL; - - if (!(class = objc_lookUpClass(classname))) - { - PyErr_SetString(ObjC_Error, "unknown ObjC class"); - return NULL; - } - - return (PyObject *)newObjCObject(class, OBJC_CLASS, 0); -} - -/* List all classes */ -static PyObject * -objc_listclasses(self, args) - ObjCObject *self; - PyObject *args; -{ - NXHashTable *class_hash = objc_getClasses(); - NXHashState state = NXInitHashState(class_hash); - Class classid; - PyObject *list; - - if (!PyArg_ParseTuple(args, "")) - return NULL; - - list = PyList_New(0); - if (list == NULL) - return NULL; - - while (NXNextHashState(class_hash, &state, (void**)&classid)) { - ObjCObject *item = newObjCObject(classid, OBJC_CLASS, 0); - if (item == NULL || PyList_Append(list, (PyObject *)item) < 0) { - Py_XDECREF(item); - Py_DECREF(list); - return NULL; - } - Py_INCREF(item); - } - - return list; -} - -/* List of top-level functions */ -static PyMethodDef objc_class_methods[] = { - {"loadobjectfiles", objc_loadobjectfiles, 1}, - {"lookupclass", objc_lookupclass, 1}, - {"listclasses", objc_listclasses, 1}, - {NULL, NULL} /* sentinel */ -}; - -/* Initialize for the module */ -void -initobjc() -{ - PyObject *m, *d; - - m = Py_InitModule("objc", objc_class_methods); - d = PyModule_GetDict(m); - - ObjC_Error = PyString_FromString("objc.error"); - PyDict_SetItemString(d, "error", ObjC_Error); - - if (PyErr_Occurred()) - Py_FatalError("can't initialize module objc"); - -#ifdef WITH_THREAD - objc_setMultithreaded(1); -#endif -} diff --git a/Modules/parsermodule.c b/Modules/parsermodule.c deleted file mode 100644 index c057135f01..0000000000 --- a/Modules/parsermodule.c +++ /dev/null @@ -1,2176 +0,0 @@ -/* Parser.c - * - * Copyright 1995 by Fred L. Drake, Jr. and Virginia Polytechnic Institute - * and State University, Blacksburg, Virginia, USA. Portions copyright - * 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. - * Copying is permitted under the terms associated with the main Python - * distribution, with the additional restriction that this additional notice - * be included and maintained on all distributed copies. - * - * This module serves to replace the original parser module written by - * Guido. The functionality is not matched precisely, but the original - * may be implemented on top of this. This is desirable since the source - * of the text to be parsed is now divorced from this interface. - * - * Unlike the prior interface, the ability to give a parse tree produced - * by Python code as a tuple to the compiler is enabled by this module. - * See the documentation for more details. - * - */ - -#include "Python.h" /* general Python API */ -#include "graminit.h" /* symbols defined in the grammar */ -#include "node.h" /* internal parser structure */ -#include "token.h" /* token definitions */ - /* ISTERMINAL() / ISNONTERMINAL() */ - -/* - * All the "fudge" declarations are here: - */ - - -/* These appearantly aren't prototyped in any of the standard Python headers, - * either by this name or as 'parse_string()/compile().' This works at - * cutting out the warning, but needs to be done as part of the mainstream - * Python headers if this is going to be supported. It is being handled as - * part of the Great Renaming. - */ -extern node* PyParser_SimpleParseString(char*, int); -extern PyObject* PyNode_Compile(node*, char*); - - -/* This isn't part of the Python runtime, but it's in the library somewhere. - * Where it is varies a bit, so just declare it. - */ -extern char* strdup(const char*); - - -/* - * That's it! Now, on to the module.... - */ - - - -/* String constants used to initialize module attributes. - * - */ -static char* -parser_copyright_string -= "Copyright 1995 by Virginia Polytechnic Institute & State University and\n" - "Fred L. Drake, Jr., Blacksburg, Virginia, USA. Portions copyright\n" - "1991-1995 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands."; - - -static char* -parser_doc_string -= "This is an interface to Python's internal parser."; - -static char* -parser_version_string = "0.1"; - - -/* The function below is copyrigthed by Stichting Mathematisch Centrum. - * original copyright statement is included below, and continues to apply - * in full to the function immediately following. All other material is - * original, copyrighted by Fred L. Drake, Jr. and Virginia Polytechnic - * Institute and State University. Changes were made to comply with the - * new naming conventions. - */ - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -static PyObject* -node2tuple(n) - node *n; -{ - if (n == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - if (ISNONTERMINAL(TYPE(n))) { - int i; - PyObject *v, *w; - v = PyTuple_New(1 + NCH(n)); - if (v == NULL) - return v; - w = PyInt_FromLong(TYPE(n)); - if (w == NULL) { - Py_DECREF(v); - return NULL; - } - PyTuple_SetItem(v, 0, w); - for (i = 0; i < NCH(n); i++) { - w = node2tuple(CHILD(n, i)); - if (w == NULL) { - Py_DECREF(v); - return NULL; - } - PyTuple_SetItem(v, i+1, w); - } - return v; - } - else if (ISTERMINAL(TYPE(n))) { - return Py_BuildValue("(is)", TYPE(n), STR(n)); - } - else { - PyErr_SetString(PyExc_SystemError, - "unrecognized parse tree node type"); - return NULL; - } -} -/* - * End of material copyrighted by Stichting Mathematisch Centrum. - */ - - - -/* There are two types of intermediate objects we're interested in: - * 'eval' and 'exec' types. These constants can be used in the ast_type - * field of the object type to identify which any given object represents. - * These should probably go in an external header to allow other extensions - * to use them, but then, we really should be using C++ too. ;-) - * - * The PyAST_FRAGMENT type is not currently supported. - */ - -#define PyAST_EXPR 1 -#define PyAST_SUITE 2 -#define PyAST_FRAGMENT 3 - - -/* These are the internal objects and definitions required to implement the - * AST type. Most of the internal names are more reminiscent of the 'old' - * naming style, but the code uses the new naming convention. - */ - -static PyObject* -parser_error = 0; - - -typedef struct _PyAST_Object { - - PyObject_HEAD /* standard object header */ - node* ast_node; /* the node* returned by the parser */ - int ast_type; /* EXPR or SUITE ? */ - -} PyAST_Object; - - -staticforward void parser_free(PyAST_Object* ast); -staticforward int parser_compare(PyAST_Object* left, PyAST_Object* right); -staticforward long parser_hash(PyAST_Object* ast); - - -/* static */ -PyTypeObject PyAST_Type = { - - PyObject_HEAD_INIT(&PyType_Type) - 0, - "ast", /* tp_name */ - sizeof(PyAST_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)parser_free, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - (cmpfunc)parser_compare, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0 /* tp_str */ - -}; /* PyAST_Type */ - - -static int -parser_compare_nodes(left, right) - node* left; - node* right; -{ - int j; - - if (TYPE(left) < TYPE(right)) - return (-1); - - if (TYPE(right) < TYPE(left)) - return (1); - - if (ISTERMINAL(TYPE(left))) - return (strcmp(STR(left), STR(right))); - - if (NCH(left) < NCH(right)) - return (-1); - - if (NCH(right) < NCH(left)) - return (1); - - for (j = 0; j < NCH(left); ++j) { - int v = parser_compare_nodes(CHILD(left, j), CHILD(right, j)); - - if (v) - return (v); - } - return (0); - -} /* parser_compare_nodes() */ - - -/* int parser_compare(PyAST_Object* left, PyAST_Object* right) - * - * Comparison function used by the Python operators ==, !=, <, >, <=, >= - * This really just wraps a call to parser_compare_nodes() with some easy - * checks and protection code. - * - */ -static int -parser_compare(left, right) - PyAST_Object* left; - PyAST_Object* right; -{ - if (left == right) - return (0); - - if ((left == 0) || (right == 0)) - return (-1); - - return (parser_compare_nodes(left->ast_node, right->ast_node)); - -} /* parser_compare() */ - - -/* parser_newastobject(node* ast) - * - * Allocates a new Python object representing an AST. This is simply the - * 'wrapper' object that holds a node* and allows it to be passed around in - * Python code. - * - */ -static PyObject* -parser_newastobject(ast, type) - node* ast; - int type; -{ - PyAST_Object* o = PyObject_NEW(PyAST_Object, &PyAST_Type); - - if (o != 0) { - o->ast_node = ast; - o->ast_type = type; - } - return ((PyObject*)o); - -} /* parser_newastobject() */ - - -/* void parser_free(PyAST_Object* ast) - * - * This is called by a del statement that reduces the reference count to 0. - * - */ -static void -parser_free(ast) - PyAST_Object* ast; -{ - PyNode_Free(ast->ast_node); - PyMem_DEL(ast); - -} /* parser_free() */ - - -/* parser_ast2tuple(PyObject* self, PyObject* args) - * - * This provides conversion from a node* to a tuple object that can be - * returned to the Python-level caller. The AST object is not modified. - * - */ -static PyObject* -parser_ast2tuple(self, args) - PyObject* self; - PyObject* args; -{ - PyObject* ast; - PyObject* res = 0; - - if (PyArg_ParseTuple(args, "O!:ast2tuple", &PyAST_Type, &ast)) { - /* - * Convert AST into a tuple representation. Use Guido's function, - * since it's known to work already. - */ - res = node2tuple(((PyAST_Object*)ast)->ast_node); - } - return (res); - -} /* parser_ast2tuple() */ - - -/* parser_compileast(PyObject* self, PyObject* args) - * - * This function creates code objects from the parse tree represented by - * the passed-in data object. An optional file name is passed in as well. - * - */ -static PyObject* -parser_compileast(self, args) - PyObject* self; - PyObject* args; -{ - PyAST_Object* ast; - PyObject* res = 0; - char* str = "<ast>"; - - if (PyArg_ParseTuple(args, "O!|s", &PyAST_Type, &ast, &str)) - res = PyNode_Compile(ast->ast_node, str); - - return (res); - -} /* parser_compileast() */ - - -/* PyObject* parser_isexpr(PyObject* self, PyObject* args) - * PyObject* parser_issuite(PyObject* self, PyObject* args) - * - * Checks the passed-in AST object to determine if it is an expression or - * a statement suite, respectively. The return is a Python truth value. - * - */ -static PyObject* -parser_isexpr(self, args) - PyObject* self; - PyObject* args; -{ - PyAST_Object* ast; - PyObject* res = 0; - - if (PyArg_ParseTuple(args, "O!:isexpr", &PyAST_Type, &ast)) { - /* - * Check to see if the AST represents an expression or not. - */ - res = (ast->ast_type == PyAST_EXPR) ? Py_True : Py_False; - Py_INCREF(res); - } - return (res); - -} /* parser_isexpr() */ - - -static PyObject* -parser_issuite(self, args) - PyObject* self; - PyObject* args; -{ - PyAST_Object* ast; - PyObject* res = 0; - - if (PyArg_ParseTuple(args, "O!:isexpr", &PyAST_Type, &ast)) { - /* - * Check to see if the AST represents an expression or not. - */ - res = (ast->ast_type == PyAST_EXPR) ? Py_False : Py_True; - Py_INCREF(res); - } - return (res); - -} /* parser_issuite() */ - - -/* PyObject* parser_do_parse(PyObject* args, int type) - * - * Internal function to actually execute the parse and return the result if - * successful, or set an exception if not. - * - */ -static PyObject* -parser_do_parse(args, type) - PyObject *args; - int type; -{ - char* string = 0; - PyObject* res = 0; - - if (PyArg_ParseTuple(args, "s", &string)) { - node* n = PyParser_SimpleParseString(string, - (type == PyAST_EXPR) - ? eval_input : file_input); - - if (n != 0) - res = parser_newastobject(n, type); - else - PyErr_SetString(parser_error, "Could not parse string."); - } - return (res); - -} /* parser_do_parse() */ - - -/* PyObject* parser_expr(PyObject* self, PyObject* args) - * PyObject* parser_suite(PyObject* self, PyObject* args) - * - * External interfaces to the parser itself. Which is called determines if - * the parser attempts to recognize an expression ('eval' form) or statement - * suite ('exec' form). The real work is done by parser_do_parse() above. - * - */ -static PyObject* -parser_expr(self, args) - PyObject* self; - PyObject* args; -{ - return (parser_do_parse(args, PyAST_EXPR)); - -} /* parser_expr() */ - - -static PyObject* -parser_suite(self, args) - PyObject* self; - PyObject* args; -{ - return (parser_do_parse(args, PyAST_SUITE)); - -} /* parser_suite() */ - - - -/* This is the messy part of the code. Conversion from a tuple to an AST - * object requires that the input tuple be valid without having to rely on - * catching an exception from the compiler. This is done to allow the - * compiler itself to remain fast, since most of its input will come from - * the parser directly, and therefore be known to be syntactically correct. - * This validation is done to ensure that we don't core dump the compile - * phase, returning an exception instead. - * - * Two aspects can be broken out in this code: creating a node tree from - * the tuple passed in, and verifying that it is indeed valid. It may be - * advantageous to expand the number of AST types to include funcdefs and - * lambdadefs to take advantage of the optimizer, recognizing those ASTs - * here. They are not necessary, and not quite as useful in a raw form. - * For now, let's get expressions and suites working reliably. - */ - - -staticforward node* build_node_tree(PyObject*); -staticforward int validate_expr_tree(node*); -staticforward int validate_suite_tree(node*); - - -/* PyObject* parser_tuple2ast(PyObject* self, PyObject* args) - * - * This is the public function, called from the Python code. It receives a - * single tuple object from the caller, and creates an AST object if the - * tuple can be validated. It does this by checking the first code of the - * tuple, and, if acceptable, builds the internal representation. If this - * step succeeds, the internal representation is validated as fully as - * possible with the various validate_*() routines defined below. - * - * This function must be changed if support is to be added for PyAST_FRAGMENT - * AST objects. - * - */ -static PyObject* -parser_tuple2ast(self, args) - PyObject* self; - PyObject* args; -{ - PyObject* ast = 0; - PyObject* tuple = 0; - int start_sym; - int next_sym; - - if ((PyTuple_Size(args) == 1) - && (tuple = PyTuple_GetItem(args, 0)) - && PyTuple_Check(tuple) - && (PyTuple_Size(tuple) >= 2) - && PyInt_Check(PyTuple_GetItem(tuple, 0)) - && PyTuple_Check(PyTuple_GetItem(tuple, 1)) - && (PyTuple_Size(PyTuple_GetItem(tuple, 1)) >= 2) - && PyInt_Check(PyTuple_GetItem(PyTuple_GetItem(tuple, 1), 0))) { - - /* - * This might be a valid parse tree, but let's do a quick check - * before we jump the gun. - */ - - start_sym = PyInt_AsLong(PyTuple_GetItem(tuple, 0)); - next_sym = PyInt_AsLong(PyTuple_GetItem(PyTuple_GetItem(tuple, 1), 0)); - - if ((start_sym == eval_input) && (next_sym == testlist)) { - /* - * Might be an expression. - */ - node* expression = build_node_tree(PyTuple_GetItem(args, 0)); - - puts("Parser.tuple2ast: built eval input tree."); - if ((expression != 0) && validate_expr_tree(expression)) - ast = parser_newastobject(expression, PyAST_EXPR); - } - else if ((start_sym == file_input) && (next_sym == stmt)) { - /* - * This looks like a suite so far. - */ - node* suite_tree = build_node_tree(PyTuple_GetItem(args, 0)); - - puts("Parser.tuple2ast: built file input tree."); - if ((suite_tree != 0) && validate_suite_tree(suite_tree)) - ast = parser_newastobject(suite_tree, PyAST_SUITE); - } - /* - * Make sure we throw an exception on all errors. We should never - * get this, but we'd do well to be sure something is done. - */ - if ((ast == 0) && !PyErr_Occurred()) { - PyErr_SetString(parser_error, "Unspecified ast error occurred."); - } - } - else { - PyErr_SetString(PyExc_TypeError, - "parser.tuple2ast(): expected single tuple."); - } - return (ast); - -} /* parser_tuple2ast() */ - - -/* int check_terminal_tuple() - * - * Check a tuple to determine that it is indeed a valid terminal node. The - * node is known to be required as a terminal, so we throw an exception if - * there is a failure. The portion of the resulting node tree already built - * is passed in so we can deallocate it in the event of a failure. - * - * The format of an acceptable terminal tuple is "(is)": the fact that elem - * is a tuple and the integer is a valid terminal symbol has been established - * before this function is called. We must check the length of the tuple and - * the type of the second element. We do *NOT* check the actual text of the - * string element, which we could do in many cases. This is done by the - * validate_*() functions which operate on the internal representation. - * - */ -static int -check_terminal_tuple(elem, result) - PyObject* elem; - node* result; -{ - int res = 0; - char* str = 0; - - if (PyTuple_Size(elem) != 2) { - str = "Illegal terminal symbol; node too long."; - } - else if (!PyString_Check(PyTuple_GetItem(elem, 1))) { - str = "Illegal terminal symbol; expected a string."; - } - else - res = 1; - - if ((res == 0) && (result != 0)) { - elem = Py_BuildValue("(os)", elem, str); - PyErr_SetObject(parser_error, elem); - } - return (res); - -} /* check_terminal_tuple() */ - - -/* node* build_node_children() - * - * Iterate across the children of the current non-terminal node and build - * their structures. If successful, return the root of this portion of - * the tree, otherwise, 0. Any required exception will be specified already, - * and no memory will have been deallocated. - * - */ -static node* -build_node_children(tuple, root, line_num) - PyObject* tuple; - node* root; - int* line_num; -{ - int len = PyTuple_Size(tuple); - int i; - - for (i = 1; i < len; ++i) { - /* elem must always be a tuple, however simple */ - PyObject* elem = PyTuple_GetItem(tuple, i); - long type = 0; - char* strn = 0; - - if ((!PyTuple_Check(elem)) || !PyInt_Check(PyTuple_GetItem(elem, 0))) { - PyErr_SetObject(parser_error, - Py_BuildValue("(os)", elem, - "Illegal node construct.")); - return (0); - } - type = PyInt_AsLong(PyTuple_GetItem(elem, 0)); - - if (ISTERMINAL(type)) { - if (check_terminal_tuple(elem, root)) - strn = strdup(PyString_AsString(PyTuple_GetItem(elem, 1))); - else - return (0); - } - else if (!ISNONTERMINAL(type)) { - /* - * It has to be one or the other; this is an error. - * Throw an exception. - */ - PyErr_SetObject(parser_error, - Py_BuildValue("(os)", elem, - "Unknown node type.")); - return (0); - } - PyNode_AddChild(root, type, strn, *line_num); - - if (ISNONTERMINAL(type)) { - node* new_child = CHILD(root, i - 1); - - if (new_child != build_node_children(elem, new_child, line_num)) - return (0); - } - else if (type == NEWLINE) /* It's true: we increment the */ - ++(*line_num); /* line number *after* the newline! */ - } - return (root); - -} /* build_node_children() */ - - -static node* -build_node_tree(tuple) - PyObject* tuple; -{ - node* res = 0; - long num = PyInt_AsLong(PyTuple_GetItem(tuple, 0)); - - if (ISTERMINAL(num)) { - /* - * The tuple is simple, but it doesn't start with a start symbol. - * Throw an exception now and be done with it. - */ - tuple = Py_BuildValue("(os)", tuple, - "Illegal ast tuple; cannot start with terminal symbol."); - PyErr_SetObject(parser_error, tuple); - } - else if (ISNONTERMINAL(num)) { - /* - * Not efficient, but that can be handled later. - */ - int line_num = 0; - - res = PyNode_New(num); - if (res != build_node_children(tuple, res, &line_num)) { - PyNode_Free(res); - res = 0; - } - } - else { - /* - * The tuple is illegal -- if the number is neither TERMINAL nor - * NONTERMINAL, we can't use it. - */ - PyErr_SetObject(parser_error, - Py_BuildValue("(os)", tuple, - "Illegal component tuple.")); - } - return (res); - -} /* build_node_tree() */ - - -#define VALIDATER(n) static int validate_##n(node*) -#define VALIDATE(n) static int validate_##n(node* tree) - - -/* - * Validation for the code above: - */ -VALIDATER(expr_tree); -VALIDATER(suite_tree); - - -/* - * Validation routines used within the validation section: - */ -staticforward int validate_terminal(node*, int, char*); - -#define validate_ampersand(ch) validate_terminal(ch, AMPER, "&") -#define validate_circumflex(ch) validate_terminal(ch, CIRCUMFLEX, "^") -#define validate_colon(ch) validate_terminal(ch, COLON, ":") -#define validate_comma(ch) validate_terminal(ch, COMMA, ",") -#define validate_dedent(ch) validate_terminal(ch, DEDENT, "") -#define validate_equal(ch) validate_terminal(ch, EQUAL, "=") -#define validate_indent(ch) validate_terminal(ch, INDENT, "") -#define validate_lparen(ch) validate_terminal(ch, LPAR, "(") -#define validate_newline(ch) validate_terminal(ch, NEWLINE, "") -#define validate_rparen(ch) validate_terminal(ch, RPAR, ")") -#define validate_semi(ch) validate_terminal(ch, SEMI, ";") -#define validate_star(ch) validate_terminal(ch, STAR, "*") -#define validate_vbar(ch) validate_terminal(ch, VBAR, "|") - -#define validate_compound_stmt(ch) validate_node(ch) -#define validate_name(ch, str) validate_terminal(ch, NAME, str) -#define validate_small_stmt(ch) validate_node(ch) - -VALIDATER(class); VALIDATER(node); -VALIDATER(parameters); VALIDATER(suite); -VALIDATER(testlist); VALIDATER(varargslist); -VALIDATER(fpdef); VALIDATER(fplist); -VALIDATER(stmt); VALIDATER(simple_stmt); -VALIDATER(expr_stmt); -VALIDATER(print_stmt); VALIDATER(del_stmt); -VALIDATER(return_stmt); -VALIDATER(raise_stmt); VALIDATER(import_stmt); -VALIDATER(global_stmt); -VALIDATER(access_stmt); VALIDATER(accesstype); -VALIDATER(exec_stmt); VALIDATER(compound_stmt); -VALIDATER(while); VALIDATER(for); -VALIDATER(try); VALIDATER(except_clause); -VALIDATER(test); VALIDATER(and_test); -VALIDATER(not_test); VALIDATER(comparison); -VALIDATER(comp_op); VALIDATER(expr); -VALIDATER(xor_expr); VALIDATER(and_expr); -VALIDATER(shift_expr); VALIDATER(arith_expr); -VALIDATER(term); VALIDATER(factor); -VALIDATER(atom); VALIDATER(lambdef); -VALIDATER(trailer); VALIDATER(subscript); -VALIDATER(exprlist); VALIDATER(dictmaker); - - -#define is_even(n) (((n) & 1) == 0) -#define is_odd(n) (((n) & 1) == 1) - - -static int -validate_ntype(n, t) - node* n; - int t; -{ - int res = (TYPE(n) == t); - - if (!res) { - char buffer[128]; - - sprintf(buffer, "Expected node type %d, got %d.", t, TYPE(n)); - PyErr_SetString(parser_error, buffer); - } - return (res); - -} /* validate_ntype() */ - - -static int -validate_terminal(terminal, type, string) - node* terminal; - int type; - char* string; -{ - static char buffer[60]; - int res = ((TYPE(terminal) == type) - && (strcmp(string, STR(terminal)) == 0)); - - if (!res) { - sprintf(buffer, "Illegal NAME: expected \"%s\"", string); - PyErr_SetString(parser_error, buffer); - } - return (res); - -} /* validate_terminal() */ - - -VALIDATE(class) { - int nch = NCH(tree); - int res = (((nch == 4) - || ((nch == 7) - && validate_lparen(CHILD(tree, 2)) - && validate_ntype(CHILD(tree, 3), testlist) - && validate_testlist(CHILD(tree, 3)) - && validate_rparen(CHILD(tree, 4)))) - && validate_terminal(CHILD(tree, 0), NAME, "class") - && validate_ntype(CHILD(tree, 1), NAME) - && validate_colon(CHILD(tree, nch - 2)) - && validate_ntype(CHILD(tree, nch - 1), suite) - && validate_suite(CHILD(tree, nch - 1))); - - if (!res) { - if ((nch >= 2) - && validate_ntype(CHILD(tree, 1), NAME)) { - char buffer[128]; - - sprintf(buffer, "Illegal classdef tuple for %s", - STR(CHILD(tree, 1))); - PyErr_SetString(parser_error, buffer); - } - else { - PyErr_SetString(parser_error, "Illegal classdef tuple."); - } - } - return (res); - -} /* validate_class() */ - - -static int -validate_elif(elif_node, test_node, colon_node, suite_node) - node* elif_node; - node* test_node; - node* colon_node; - node* suite_node; -{ - return (validate_ntype(test_node, test) - && validate_ntype(suite_node, suite) - && validate_name(elif_node, "elif") - && validate_colon(colon_node) - && validate_node(test_node) - && validate_suite(suite_node)); - -} /* validate_elif() */ - - -static int -validate_else(else_node, colon_node, suite_node) - node* else_node; - node* colon_node; - node* suite_node; -{ - return (validate_ntype(suite_node, suite) - && validate_name(else_node, "else") - && validate_colon(colon_node) - && validate_suite(suite_node)); - -} /* validate_else() */ - - -VALIDATE(if) { - int nch = NCH(tree); - int res = ((nch >= 4) - && validate_ntype(CHILD(tree, 1), test) - && validate_ntype(CHILD(tree, 3), suite) - && validate_name(CHILD(tree, 0), "if") - && validate_colon(CHILD(tree, 2)) - && validate_parameters(CHILD(tree, 1)) - && validate_suite(CHILD(tree, 3))); - - if (res && ((nch % 4) == 3)) { - /* - * There must be a single 'else' clause, and maybe a series - * of 'elif' clauses. - */ - res = validate_else(CHILD(tree, nch-3), CHILD(tree, nch-2), - CHILD(tree, nch-1)); - nch -= 3; - } - if ((nch % 4) != 0) - res = 0; - else if (res && (nch > 4)) { - /* - * There might be a series of 'elif' clauses. - */ - int j = 4; - while ((j < nch) && res) { - res = validate_elif(CHILD(tree, j), CHILD(tree, j+1), - CHILD(tree, j+2), CHILD(tree, j+3)); - j += 4; - } - } - if (!res && !PyErr_Occurred()) { - PyErr_SetString(parser_error, "Illegal 'if' statement found."); - } - return (res); - -} /* validate_if() */ - - -VALIDATE(parameters) { - int res = 1; - int nch = NCH(tree); - - res = (((nch == 2) - || ((nch == 3) - && validate_varargslist(CHILD(tree, 1)))) - && validate_lparen(CHILD(tree, 0)) - && validate_rparen(CHILD(tree, nch - 1))); - - return (res); - -} /* validate_parameters() */ - - -VALIDATE(suite) { - int res = 1; - int nch = NCH(tree); - - if (nch == 1) { - res = (validate_ntype(CHILD(tree, 0), simple_stmt) - && validate_simple_stmt(CHILD(tree, 0))); - } - else { - res = ((nch >= 5) - && validate_newline(CHILD(tree, 0)) - && validate_indent(CHILD(tree, 1)) - && validate_dedent(CHILD(tree, nch - 1))); - - if (res) { - int i = 2; - - while (TYPE(CHILD(tree, i)) == NEWLINE) - ++i; - res = (validate_ntype(CHILD(tree, i), stmt) - && validate_stmt(CHILD(tree, i))); - - if (res) { - ++i; - while (TYPE(CHILD(tree, i)) == NEWLINE) - ++i; - - while (res && (TYPE(CHILD(tree, i)) != DEDENT)) { - res = (validate_ntype(CHILD(tree, i), stmt) - && validate_stmt(CHILD(tree, i))); - - if (res) { - ++i; - while (TYPE(CHILD(tree, i)) == NEWLINE) - ++i; - } - } - } - } - } - return (res); - -} /* validate_suite() */ - - -VALIDATE(testlist) { - int i; - int nch = NCH(tree); - int res = ((nch >= 1) - && (is_odd(nch) - || validate_comma(CHILD(tree, nch - 1)))); - - /* - * If there are an even, non-zero number of children, the last one - * absolutely must be a comma. Why the trailing comma is allowed, - * I have no idea! - */ - if ((res) && is_odd(nch)) { - /* - * If the number is odd, the last is a test, and can be - * verified. What's left, if anything, can be verified - * as a list of [test, comma] pairs. - */ - --nch; - res = (validate_ntype(CHILD(tree, nch), test) - && validate_test(CHILD(tree, nch))); - } - for (i = 0; res && (i < nch); i += 2) { - res = (validate_ntype(CHILD(tree, i), test) - && validate_test(CHILD(tree, i)) - && validate_comma(CHILD(tree, i + 1))); - } - return (res); - -} /* validate_testlist() */ - - -VALIDATE(varargslist) { - int nch = NCH(tree); - int res = (nch != 0); - - if (res && (TYPE(CHILD(tree, 0)) == fpdef)) { - int pos = 0; - - while (res && (pos < nch)) { - res = (validate_ntype(CHILD(tree, pos), fpdef) - && validate_fpdef(CHILD(tree, pos))); - ++pos; - if (res && (pos < nch) && (TYPE(CHILD(tree, pos)) == EQUAL)) { - res = ((pos + 1 < nch) - && validate_ntype(CHILD(tree, pos + 1), test) - && validate_test(CHILD(tree, pos + 1))); - pos += 2; - } - if (res && (pos < nch)) { - res = validate_comma(CHILD(tree, pos)); - ++pos; - } - } - } - else { - int pos = 0; - - res = ((nch > 1) - && ((nch & 1) == 0) - && validate_star(CHILD(tree, nch - 2)) - && validate_ntype(CHILD(tree, nch - 1), NAME)); - - nch -= 2; - while (res && (pos < nch)) { - /* - * Sequence of: fpdef ['=' test] ',' - */ - res = (validate_ntype(CHILD(tree, pos), fpdef) - && validate_fpdef(CHILD(tree, pos)) - && ((TYPE(CHILD(tree, pos + 1)) == COMMA) - || (((pos + 2) < nch) - && validate_equal(CHILD(tree, pos + 1)) - && validate_ntype(CHILD(tree, pos + 2), test) - && validate_test(CHILD(tree, pos + 2)) - && validate_comma(CHILD(tree, pos + 3))))); - } - } - return (res); - -} /* validate_varargslist() */ - - -VALIDATE(fpdef) { - int nch = NCH(tree); - - return (((nch == 1) - && validate_ntype(CHILD(tree, 0), NAME)) - || ((nch == 3) - && validate_lparen(CHILD(tree, 0)) - && validate_fplist(CHILD(tree, 1)) - && validate_rparen(CHILD(tree, 2)))); - -} /* validate_fpdef() */ - - -VALIDATE(fplist) { - int j; - int nch = NCH(tree); - int res = ((nch != 0) && validate_fpdef(CHILD(tree, 0))); - - if (res && is_even(nch)) { - res = validate_comma(CHILD(tree, nch - 1)); - --nch; - } - for (j = 1; res && (j < nch); j += 2) { - res = (validate_comma(CHILD(tree, j)) - && validate_fpdef(CHILD(tree, j + 1))); - } - return (res); - -} /* validate_fplist() */ - - -VALIDATE(stmt) { - int nch = NCH(tree); - - return ((nch == 1) - && (((TYPE(CHILD(tree, 0)) == simple_stmt) - && validate_simple_stmt(CHILD(tree, 0))) - || (validate_ntype(CHILD(tree, 0), compound_stmt) - && validate_compound_stmt(CHILD(tree, 0))))); - -} /* validate_stmt() */ - - -VALIDATE(simple_stmt) { - int nch = NCH(tree); - int res = ((nch >= 2) - && validate_ntype(CHILD(tree, 0), small_stmt) - && validate_small_stmt(CHILD(tree, 0)) - && validate_newline(CHILD(tree, nch - 1))); - - --nch; /* forget the NEWLINE */ - if (res && (nch >= 2)) { - if (TYPE(CHILD(tree, nch - 1)) == SEMI) - --nch; - } - if (res && (nch > 2)) { - int i; - - for (i = 1; res && (i < nch); i += 2) { - res = (validate_semi(CHILD(tree, i)) - && validate_ntype(CHILD(tree, i + 1), small_stmt) - && validate_small_stmt(CHILD(tree, i + 1))); - } - } - return (res); - -} /* validate_simple_stmt() */ - - -VALIDATE(expr_stmt) { - int j; - int nch = NCH(tree); - int res = (is_odd(nch) - && (validate_testlist(CHILD(tree, 0)))); - - for (j = 1; res && (j < nch); j += 2) { - res = (validate_equal(CHILD(tree, j)) - && validate_ntype(CHILD(tree, j + 1), testlist) - && validate_testlist(CHILD(tree, j + 1))); - } - return (res); - -} /* validate_expr_stmt() */ - - -VALIDATE(print_stmt) { - int j; - int nch = NCH(tree); - int res = ((nch != 0) - && is_even(nch) - && validate_name(CHILD(tree, 0), "print") - && validate_ntype(CHILD(tree, 1), test) - && validate_test(CHILD(tree, 1))); - - for (j = 2; res && (j < nch); j += 2) { - res = (validate_comma(CHILD(tree, j)) - && validate_ntype(CHILD(tree, j + 1), test) - && validate_test(CHILD(tree, 1))); - } - return (res); - -} /* validate_print_stmt() */ - - -VALIDATE(del_stmt) { - - return ((NCH(tree) == 2) - && validate_name(CHILD(tree, 0), "del") - && validate_ntype(CHILD(tree, 1), exprlist) - && validate_exprlist(CHILD(tree, 1))); - -} /* validate_del_stmt() */ - - -VALIDATE(return_stmt) { - int nch = NCH(tree); - int res = (((nch == 1) - || (nch == 2)) - && validate_name(CHILD(tree, 0), "return")); - - if (res && (nch == 2)) { - res = (validate_ntype(CHILD(tree, 1), testlist) - && validate_testlist(CHILD(tree, 1))); - } - return (res); - -} /* validate_return_stmt() */ - - -VALIDATE(raise_stmt) { - int nch = NCH(tree); - int res = (((nch == 2) || (nch == 4)) - && validate_name(CHILD(tree, 0), "raise") - && validate_ntype(CHILD(tree, 1), test) - && validate_test(CHILD(tree, 1))); - - if (res && (nch == 4)) { - res = (validate_comma(CHILD(tree, 2)) - && (TYPE(CHILD(tree, 3)) == test) - && validate_test(CHILD(tree, 3))); - } - return (res); - -} /* validate_raise_stmt() */ - - -VALIDATE(import_stmt) { - int nch = NCH(tree); - int res = ((nch >= 2) - && validate_ntype(CHILD(tree, 0), NAME) - && validate_ntype(CHILD(tree, 1), NAME)); - - if (res && (strcmp(STR(CHILD(tree, 0)), "import") == 0)) { - res = is_even(nch); - if (res) { - int j; - - for (j = 2; res && (j < nch); j += 2) { - res = (validate_comma(CHILD(tree, j)) - && validate_ntype(CHILD(tree, j + 1), NAME)); - } - } - } - else if (res && validate_name(CHILD(tree, 0), "from")) { - res = ((nch >= 4) - && is_even(nch) - && validate_name(CHILD(tree, 2), "import")); - if (nch == 4) { - res = ((TYPE(CHILD(tree, 3)) == NAME) - || validate_ntype(CHILD(tree, 3), STAR)); - } - else { - /* 'from' NAME 'import' NAME (',' NAME)* */ - int j; - - res = validate_ntype(CHILD(tree, 3), NAME); - for (j = 4; res && (j < nch); j += 2) { - res = (validate_comma(CHILD(tree, j)) - && validate_ntype(CHILD(tree, j + 1), NAME)); - } - } - } - else { - res = 0; - } - return (res); - -} /* validate_import_stmt() */ - - -VALIDATE(global_stmt) { - int j; - int nch = NCH(tree); - int res = (is_even(nch) - && validate_name(CHILD(tree, 0), "global") - && validate_ntype(CHILD(tree, 1), NAME)); - - for (j = 2; res && (j < nch); j += 2) { - res = (validate_comma(CHILD(tree, j)) - && validate_ntype(CHILD(tree, j + 1), NAME)); - } - return (res); - -} /* validate_global_stmt() */ - - -VALIDATE(access_stmt) { - int pos = 3; - int nch = NCH(tree); - int res = ((nch >= 4) - && is_even(nch) - && validate_name(CHILD(tree, 0), "access") - && validate_accesstype(CHILD(tree, nch - 1))); - - if (res && (TYPE(CHILD(tree, 1)) != STAR)) { - int j; - - res = validate_ntype(CHILD(tree, 1), NAME); - for (j = 2; res && (j < (nch - 2)); j += 2) { - if (TYPE(CHILD(tree, j)) == COLON) - break; - res = (validate_comma(CHILD(tree, j)) - && validate_ntype(CHILD(tree, j + 1), NAME) - && (pos += 2)); - } - } - else { - res = validate_star(CHILD(tree, 1)); - } - res = (res && validate_colon(CHILD(tree, pos - 1))); - - for (; res && (pos < (nch - 1)); pos += 2) { - res = (validate_accesstype(CHILD(tree, pos)) - && validate_comma(CHILD(tree, pos + 1))); - } - return (res && (pos == (nch - 1))); - -} /* validate_access_stmt() */ - - -VALIDATE(accesstype) { - int nch = NCH(tree); - int res = (nch >= 1); - int i; - - for (i = 0; res && (i < nch); ++i) { - res = validate_ntype(CHILD(tree, i), NAME); - } - return (res); - -} /* validate_accesstype() */ - - -VALIDATE(exec_stmt) { - int nch = NCH(tree); - int res = (((nch == 2) || (nch == 4) || (nch == 6)) - && validate_name(CHILD(tree, 0), "exec") - && validate_expr(CHILD(tree, 1))); - - if (res && (nch > 2)) { - res = (validate_name(CHILD(tree, 2), "in") - && validate_test(CHILD(tree, 3))); - } - if (res && (nch > 4)) { - res = (validate_comma(CHILD(tree, 4)) - && validate_test(CHILD(tree, 5))); - } - return (res); - -} /* validate_exec_stmt() */ - - -VALIDATE(while) { - int nch = NCH(tree); - int res = (((nch == 4) || (nch == 7)) - && validate_name(CHILD(tree, 0), "while") - && validate_ntype(CHILD(tree, 1), test) - && validate_test(CHILD(tree, 1)) - && validate_colon(CHILD(tree, 2)) - && validate_ntype(CHILD(tree, 3), suite) - && validate_suite(CHILD(tree, 3))); - - if (res && (nch == 7)) { - res = (validate_name(CHILD(tree, 4), "else") - && validate_colon(CHILD(tree, 5)) - && validate_ntype(CHILD(tree, 6), suite) - && validate_suite(CHILD(tree, 6))); - } - return (res); - -} /* validate_while() */ - - -VALIDATE(for) { - int nch = NCH(tree); - int res = (((nch == 6) || (nch == 9)) - && validate_name(CHILD(tree, 0), "for") - && validate_ntype(CHILD(tree, 1), exprlist) - && validate_exprlist(CHILD(tree, 1)) - && validate_name(CHILD(tree, 2), "in") - && validate_ntype(CHILD(tree, 3), testlist) - && validate_testlist(CHILD(tree, 3)) - && validate_colon(CHILD(tree, 4)) - && validate_ntype(CHILD(tree, 5), suite) - && validate_suite(CHILD(tree, 5))); - - if (res && (nch == 9)) { - res = (validate_name(CHILD(tree, 6), "else") - && validate_colon(CHILD(tree, 7)) - && validate_ntype(CHILD(tree, 8), suite) - && validate_suite(CHILD(tree, 8))); - } - return (res); - -} /* validate_for() */ - - -VALIDATE(try) { - int nch = NCH(tree); - int res = ((nch >= 6) - && ((nch % 3) == 0) - && validate_name(CHILD(tree, 0), "try") - && validate_colon(CHILD(tree, 1)) - && validate_ntype(CHILD(tree, 2), suite) - && validate_suite(CHILD(tree, 2)) - && validate_colon(CHILD(tree, nch - 2)) - && validate_ntype(CHILD(tree, nch - 1), suite) - && validate_suite(CHILD(tree, nch - 1))); - - if (res && (TYPE(CHILD(tree, 3)) == except_clause)) { - int groups = (nch / 3) - 2; - - res = validate_except_clause(CHILD(tree, 3)); - - if (res && (groups != 0)) { - int cln_pos = 4; - int sui_pos = 5; - int nxt_pos = 6; - - while (res && groups--) { - res = (validate_colon(CHILD(tree, cln_pos)) - && validate_ntype(CHILD(tree, sui_pos), suite) - && validate_suite(CHILD(tree, sui_pos))); - - if (res && (TYPE(CHILD(tree, nxt_pos)) == NAME)) { - res = ((groups == 0) - && validate_name(CHILD(tree, nxt_pos), "else")); - } - else if (res) { - res = (validate_ntype(CHILD(tree, nxt_pos), except_clause) - && validate_except_clause(CHILD(tree, nxt_pos))); - } - /* Update for next group. */ - cln_pos += 3; - sui_pos += 3; - nxt_pos += 3; - } - } - } - else if (res) { - res = ((nch == 6) - && validate_name(CHILD(tree, 3), "finally")); - } - return (res); - -} /* validate_try() */ - - -VALIDATE(except_clause) { - int nch = NCH(tree); - int res = (((nch == 1) || (nch == 2) || (nch == 4)) - && validate_name(CHILD(tree, 0), "except")); - - if (res && (nch > 1)) { - res = (validate_ntype(CHILD(tree, 1), test) - && validate_test(CHILD(tree, 1))); - } - if (res && (nch == 4)) { - res = (validate_comma(CHILD(tree, 2)) - && validate_ntype(CHILD(tree, 3), test) - && validate_test(CHILD(tree, 3))); - } - return (res); - -} /* validate_except_clause() */ - - -VALIDATE(test) { - int nch = NCH(tree); - int res = is_odd(nch); - - if (res && (TYPE(CHILD(tree, 0)) == lambdef)) { - res = ((nch == 1) - && validate_lambdef(CHILD(tree, 0))); - } - else if (res) { - int pos; - - res = (validate_ntype(CHILD(tree, 0), and_test) - && validate_and_test(CHILD(tree, 0))); - - for (pos = 1; res && (pos < nch); pos += 2) { - res = (validate_comma(CHILD(tree, pos)) - && validate_ntype(CHILD(tree, pos + 1), and_test) - && validate_and_test(CHILD(tree, pos + 1))); - } - } - return (res); - -} /* validate_test() */ - - -VALIDATE(and_test) { - int pos; - int nch = NCH(tree); - int res = (is_odd(nch) - && validate_ntype(CHILD(tree, 0), not_test) - && validate_not_test(CHILD(tree, 0))); - - for (pos = 1; res && (pos < nch); pos += 2) { - res = (validate_name(CHILD(tree, pos), "and") - && validate_ntype(CHILD(tree, 0), not_test) - && validate_not_test(CHILD(tree, 0))); - } - return (res); - -} /* validate_and_test() */ - - -VALIDATE(not_test) { - int nch = NCH(tree); - - return (((nch == 2) - && validate_name(CHILD(tree, 0), "not") - && validate_ntype(CHILD(tree, 1), not_test) - && validate_not_test(CHILD(tree, 1))) - || ((nch == 1) - && validate_ntype(CHILD(tree, 0), comparison) - && validate_comparison(CHILD(tree, 0)))); - -} /* validate_not_test() */ - - -VALIDATE(comparison) { - int pos; - int nch = NCH(tree); - int res = (is_odd(nch) - && validate_ntype(CHILD(tree, 0), expr) - && validate_expr(CHILD(tree, 0))); - - for (pos = 1; res && (pos < nch); pos += 2) { - res = (validate_ntype(CHILD(tree, pos), comp_op) - && validate_comp_op(CHILD(tree, pos)) - && validate_ntype(CHILD(tree, pos + 1), expr) - && validate_expr(CHILD(tree, 1))); - } - return (res); - -} /* validate_comparison() */ - - -VALIDATE(comp_op) { - int res = 0; - int nch = NCH(tree); - - if (nch == 1) { - /* - * Only child will be a terminal with a well-defined symbolic name - * or a NAME with a string of either 'is' or 'in' - */ - tree = CHILD(tree, 0); - switch (TYPE(tree)) { - case LESS: - case GREATER: - case EQEQUAL: - case EQUAL: - case LESSEQUAL: - case GREATEREQUAL: - case NOTEQUAL: - res = 1; - break; - case NAME: - res = ((strcmp(STR(tree), "in") == 0) - || (strcmp(STR(tree), "is") == 0)); - if (!res) { - char buffer[128]; - - sprintf(buffer, "Illegal comparison operator: '%s'.", - STR(tree)); - PyErr_SetString(parser_error, buffer); - } - break; - default: - PyErr_SetString(parser_error, - "Illegal comparison operator type."); - break; - } - } - else if (nch == 2) { - res = (validate_ntype(CHILD(tree, 0), NAME) - && validate_ntype(CHILD(tree, 1), NAME) - && (((strcmp(STR(CHILD(tree, 0)), "is") == 0) - && (strcmp(STR(CHILD(tree, 1)), "not") == 0)) - || ((strcmp(STR(CHILD(tree, 0)), "not") == 0) - && (strcmp(STR(CHILD(tree, 1)), "in") == 0)))); - } - - if (!res && !PyErr_Occurred()) { - PyErr_SetString(parser_error, "Unknown comparison operator."); - } - return (res); - -} /* validate_comp_op() */ - - -VALIDATE(expr) { - int j; - int nch = NCH(tree); - int res = (is_odd(nch) - && validate_ntype(CHILD(tree, 0), xor_expr) - && validate_xor_expr(CHILD(tree, 0))); - - for (j = 2; res && (j < nch); j += 2) { - res = (validate_ntype(CHILD(tree, j), xor_expr) - && validate_xor_expr(CHILD(tree, j)) - && validate_vbar(CHILD(tree, j - 1))); - } - return (res); - -} /* validate_expr() */ - - -VALIDATE(xor_expr) { - int j; - int nch = NCH(tree); - int res = (is_odd(nch) - && validate_ntype(CHILD(tree, 0), and_expr) - && validate_and_expr(CHILD(tree, 0))); - - for (j = 2; res && (j < nch); j += 2) { - res = (validate_circumflex(CHILD(tree, j - 1)) - && validate_ntype(CHILD(tree, j), and_expr) - && validate_and_expr(CHILD(tree, j))); - } - return (res); - -} /* validate_xor_expr() */ - - -VALIDATE(and_expr) { - int pos; - int nch = NCH(tree); - int res = (is_odd(nch) - && validate_ntype(CHILD(tree, 0), shift_expr) - && validate_shift_expr(CHILD(tree, 0))); - - for (pos = 1; res && (pos < nch); pos += 2) { - res = (validate_ampersand(CHILD(tree, pos)) - && validate_ntype(CHILD(tree, pos + 1), shift_expr) - && validate_shift_expr(CHILD(tree, pos + 1))); - } - return (res); - -} /* validate_and_expr() */ - - -static int -validate_chain_two_ops(tree, termtype, termvalid, op1, op2) - node* tree; - int termtype; - int (*termvalid)(node*); - int op1, op2; -{ - int pos; - int nch = NCH(tree); - int res = (is_odd(nch) - && validate_ntype(CHILD(tree, 0), termtype) - && (*termvalid)(CHILD(tree, 0))); - - for (pos = 1; res && (pos < nch); pos += 2) { - res = (((TYPE(CHILD(tree, pos)) == op1) - || validate_ntype(CHILD(tree, pos), op2)) - && validate_ntype(CHILD(tree, pos + 1), termtype) - && (*termvalid)(CHILD(tree, pos + 1))); - } - return (res); - -} /* validate_chain_two_ops() */ - - -VALIDATE(shift_expr) { - - return (validate_chain_two_ops(tree, arith_expr, - validate_arith_expr, - LEFTSHIFT, RIGHTSHIFT)); - -} /* validate_shift_expr() */ - - -VALIDATE(arith_expr) { - - return (validate_chain_two_ops(tree, term, - validate_term, - PLUS, MINUS)); - -} /* validate_arith_expr() */ - - -VALIDATE(term) { - int pos; - int nch = NCH(tree); - int res = (is_odd(nch) - && validate_ntype(CHILD(tree, 0), factor) - && validate_factor(CHILD(tree, 0))); - - for (pos = 1; res && (pos < nch); pos += 2) { - res= (((TYPE(CHILD(tree, pos)) == STAR) - || (TYPE(CHILD(tree, pos)) == SLASH) - || validate_ntype(CHILD(tree, pos), PERCENT)) - && validate_ntype(CHILD(tree, pos + 1), factor) - && validate_factor(CHILD(tree, pos + 1))); - } - return (res); - -} /* validate_term() */ - - -VALIDATE(factor) { - int nch = NCH(tree); - int res = (((nch == 2) - && ((TYPE(CHILD(tree, 0)) == PLUS) - || (TYPE(CHILD(tree, 0)) == MINUS) - || validate_ntype(CHILD(tree, 0), TILDE)) - && validate_ntype(CHILD(tree, 1), factor) - && validate_factor(CHILD(tree, 1))) - || ((nch >= 1) - && validate_ntype(CHILD(tree, 0), atom) - && validate_atom(CHILD(tree, 0)))); - - if (res && (TYPE(CHILD(tree, 0)) == atom)) { - int pos; - - for (pos = 1; res && (pos < nch); ++pos) { - res = (validate_ntype(CHILD(tree, pos), trailer) - && validate_trailer(CHILD(tree, pos))); - } - } - return (res); - -} /* validate_factor() */ - - -VALIDATE(atom) { - int pos; - int nch = NCH(tree); - int res = (nch >= 1); - - if (res) { - switch (TYPE(CHILD(tree, 0))) { - case LPAR: - res = ((nch <= 3) - && (validate_rparen(CHILD(tree, nch - 1)))); - - if (res && (nch == 3)) { - res = (validate_ntype(CHILD(tree, 1), testlist) - && validate_testlist(CHILD(tree, 1))); - } - break; - case LSQB: - res = ((nch <= 3) - && validate_ntype(CHILD(tree, nch - 1), RSQB)); - - if (res && (nch == 3)) { - res = (validate_ntype(CHILD(tree, 1), testlist) - && validate_testlist(CHILD(tree, 1))); - } - break; - case LBRACE: - res = ((nch <= 3) - && validate_ntype(CHILD(tree, nch - 1), RBRACE)); - - if (res && (nch == 3)) { - res = (validate_ntype(CHILD(tree, 1), dictmaker) - && validate_dictmaker(CHILD(tree, 1))); - } - break; - case BACKQUOTE: - res = ((nch == 3) - && validate_ntype(CHILD(tree, 1), testlist) - && validate_testlist(CHILD(tree, 1)) - && validate_ntype(CHILD(tree, 2), BACKQUOTE)); - break; - case NAME: - case NUMBER: - res = (nch == 1); - break; - case STRING: - for (pos = 1; res && (pos < nch); ++pos) { - res = validate_ntype(CHILD(tree, pos), STRING); - } - break; - default: - res = 0; - break; - } - } - return (res); - -} /* validate_atom() */ - - -VALIDATE(funcdef) { - - return ((NCH(tree) == 5) - && validate_name(CHILD(tree, 0), "def") - && validate_ntype(CHILD(tree, 1), NAME) - && validate_ntype(CHILD(tree, 2), parameters) - && validate_colon(CHILD(tree, 3)) - && validate_ntype(CHILD(tree, 4), suite) - && validate_parameters(CHILD(tree, 2)) - && validate_suite(CHILD(tree, 4))); - -} /* validate_funcdef() */ - - -VALIDATE(lambdef) { - int nch = NCH(tree); - int res = (((nch == 3) || (nch == 4)) - && validate_name(CHILD(tree, 0), "lambda") - && validate_colon(CHILD(tree, nch - 2)) - && validate_ntype(CHILD(tree, nch - 1), test) - && validate_testlist(CHILD(tree, nch - 1))); - - if (res && (nch == 4)) { - res = (validate_ntype(CHILD(tree, 1), varargslist) - && validate_varargslist(CHILD(tree, 1))); - } - return (res); - -} /* validate_lambdef() */ - - -VALIDATE(trailer) { - int nch = NCH(tree); - int res = ((nch == 2) || (nch == 3)); - - if (res) { - switch (TYPE(CHILD(tree, 0))) { - case LPAR: - res = validate_rparen(CHILD(tree, nch - 1)); - if (res && (nch == 3)) { - res = (validate_ntype(CHILD(tree, 1), testlist) - && validate_testlist(CHILD(tree, 1))); - } - break; - case LSQB: - res = ((nch == 3) - && validate_ntype(CHILD(tree, 1), subscript) - && validate_subscript(CHILD(tree, 1)) - && validate_ntype(CHILD(tree, 2), RSQB)); - break; - case DOT: - res = ((nch == 2) - && validate_ntype(CHILD(tree, 1), NAME)); - break; - default: - res = 0; - break; - } - } - return (res); - -} /* validate_trailer() */ - - -VALIDATE(subscript) { - int nch = NCH(tree); - int res = ((nch >= 1) && (nch <= 3)); - - if (res && is_odd(nch)) { - res = (validate_ntype(CHILD(tree, 0), test) - && validate_test(CHILD(tree, 0))); - - if (res && (nch == 3)) { - res = (validate_colon(CHILD(tree, 1)) - && validate_ntype(CHILD(tree, 2), test) - && validate_test(CHILD(tree, 2))); - } - } - else if (res == 2) { - if (TYPE(CHILD(tree, 0)) == COLON) { - res = (validate_ntype(CHILD(tree, 1), test) - && validate_test(CHILD(tree, 1))); - } - else { - res = (validate_ntype(CHILD(tree, 0), test) - && validate_test(CHILD(tree, 0)) - && validate_colon(CHILD(tree, 1))); - } - } - return (res); - -} /* validate_subscript() */ - - -VALIDATE(exprlist) { - int nch = NCH(tree); - int res = ((nch >= 1) - && validate_ntype(CHILD(tree, 0), expr) - && validate_expr(CHILD(tree, 0))); - - if (res && is_even(nch)) { - res = validate_comma(CHILD(tree, --nch)); - } - if (res && (nch > 1)) { - int pos; - - for (pos = 1; res && (pos < nch); pos += 2) { - res = (validate_comma(CHILD(tree, pos)) - && validate_ntype(CHILD(tree, pos + 1), expr) - && validate_expr(CHILD(tree, pos + 1))); - } - } - return (res); - -} /* validate_exprlist() */ - - -VALIDATE(dictmaker) { - int nch = NCH(tree); - int res = ((nch >= 3) - && validate_ntype(CHILD(tree, 0), test) - && validate_test(CHILD(tree, 0)) - && validate_colon(CHILD(tree, 1)) - && validate_ntype(CHILD(tree, 2), test) - && validate_test(CHILD(tree, 2))); - - if (res && ((nch % 4) == 0)) { - res = validate_comma(CHILD(tree, --nch)); - } - else if (res) { - res = ((nch % 4) == 3); - } - if (res && (nch > 3)) { - int pos = 3; - - /* What's left are groups of: ',' test ':' test */ - while (res && (pos < nch)) { - res = (validate_comma(CHILD(tree, pos)) - && validate_ntype(CHILD(tree, pos + 1), test) - && validate_test(CHILD(tree, pos + 1)) - && validate_colon(CHILD(tree, pos + 2)) - && validate_ntype(CHILD(tree, pos + 3), test) - && validate_test(CHILD(tree, pos + 3))); - pos += 4; - } - } - return (res); - -} /* validate_dictmaker() */ - - -VALIDATE(eval_input) { - int pos; - int nch = NCH(tree); - int res = ((nch >= 2) - && validate_testlist(CHILD(tree, 0)) - && validate_ntype(CHILD(tree, nch - 1), ENDMARKER)); - - for (pos = 1; res && (pos < (nch - 1)); ++pos) { - res = validate_ntype(CHILD(tree, pos), NEWLINE); - } - return (res); - -} /* validate_eval_input() */ - - -VALIDATE(node) { - int nch = 0; /* num. children on current node */ - int res = 1; /* result value */ - node* next = 0; /* node to process after this one */ - - while (res & (tree != 0)) { - nch = NCH(tree); - next = 0; - switch (TYPE(tree)) { - /* - * Definition nodes. - */ - case funcdef: - res = validate_funcdef(tree); - break; - case classdef: - res = validate_class(tree); - break; - /* - * "Trivial" parse tree nodes. - */ - case stmt: - res = validate_stmt(tree); - break; - case small_stmt: - res = ((nch == 1) - && ((TYPE(CHILD(tree, 0)) == expr_stmt) - || (TYPE(CHILD(tree, 0)) == print_stmt) - || (TYPE(CHILD(tree, 0)) == del_stmt) - || (TYPE(CHILD(tree, 0)) == pass_stmt) - || (TYPE(CHILD(tree, 0)) == flow_stmt) - || (TYPE(CHILD(tree, 0)) == import_stmt) - || (TYPE(CHILD(tree, 0)) == global_stmt) - || (TYPE(CHILD(tree, 0)) == access_stmt) - || validate_ntype(CHILD(tree, 0), exec_stmt)) - && (next = CHILD(tree, 0))); - break; - case flow_stmt: - res = ((nch == 1) - && ((TYPE(CHILD(tree, 0)) == break_stmt) - || (TYPE(CHILD(tree, 0)) == continue_stmt) - || (TYPE(CHILD(tree, 0)) == return_stmt) - || validate_ntype(CHILD(tree, 0), raise_stmt)) - && (next = CHILD(tree, 0))); - break; - /* - * Compound statements. - */ - case simple_stmt: - res = validate_simple_stmt(tree); - break; - case compound_stmt: - res = ((NCH(tree) == 1) - && ((TYPE(CHILD(tree, 0)) == if_stmt) - || (TYPE(CHILD(tree, 0)) == while_stmt) - || (TYPE(CHILD(tree, 0)) == for_stmt) - || (TYPE(CHILD(tree, 0)) == try_stmt) - || (TYPE(CHILD(tree, 0)) == funcdef) - || validate_ntype(CHILD(tree, 0), classdef)) - && (next = CHILD(tree, 0))); - break; - /* - * Fundemental statements. - */ - case expr_stmt: - res = validate_expr_stmt(tree); - break; - case print_stmt: - res = validate_print_stmt(tree); - break; - case del_stmt: - res = validate_del_stmt(tree); - break; - case pass_stmt: - res = ((nch == 1) - && validate_name(CHILD(tree, 0), "pass")); - break; - case break_stmt: - res = ((nch == 1) - && validate_name(CHILD(tree, 0), "break")); - break; - case continue_stmt: - res = ((nch == 1) - && validate_name(CHILD(tree, 0), "continue")); - break; - case return_stmt: - res = validate_return_stmt(tree); - break; - case raise_stmt: - res = validate_raise_stmt(tree); - break; - case import_stmt: - res = validate_import_stmt(tree); - break; - case global_stmt: - res = validate_global_stmt(tree); - break; - case access_stmt: - res = validate_access_stmt(tree); - break; - case exec_stmt: - res = validate_exec_stmt(tree); - break; - case if_stmt: - res = validate_if(tree); - break; - case while_stmt: - res = validate_while(tree); - break; - case for_stmt: - res = validate_for(tree); - break; - case try_stmt: - res = validate_try(tree); - break; - case suite: - res = validate_suite(tree); - break; - /* - * Expression nodes. - */ - case testlist: - res = validate_testlist(tree); - break; - case test: - res = validate_test(tree); - break; - case and_test: - res = validate_and_test(tree); - break; - case not_test: - res = validate_not_test(tree); - break; - case comparison: - res = validate_comparison(tree); - break; - case exprlist: - res = validate_exprlist(tree); - break; - case expr: - res = validate_expr(tree); - break; - case xor_expr: - res = validate_xor_expr(tree); - break; - case and_expr: - res = validate_and_expr(tree); - break; - case shift_expr: - res = validate_shift_expr(tree); - break; - case arith_expr: - res = validate_arith_expr(tree); - break; - case term: - res = validate_term(tree); - break; - case factor: - res = validate_factor(tree); - break; - case atom: - res = validate_atom(tree); - break; - - default: - /* Hopefully never reached! */ - res = 0; - break; - } - tree = next; - } - return (res); - -} /* validate_node() */ - - -VALIDATE(expr_tree) { - return (validate_ntype(tree, eval_input) - && validate_eval_input(tree)); - -} /* validate_expr_tree() */ - - -VALIDATE(suite_tree) { - int j; - int nch = NCH(tree); - int res = ((nch >= 1) - && validate_ntype(CHILD(tree, nch - 1), ENDMARKER) - && nch--); - - for (j = 0; res && (j < nch); ++j) { - res = ((TYPE(CHILD(tree, j)) == NEWLINE) - || (validate_ntype(CHILD(tree, j), stmt) - && validate_stmt(CHILD(tree, j)))); - } - return (res); - -} /* validate_suite_tree() */ - - - -/* Functions exported by this module. Most of this should probably - * be converted into an AST object with methods, but that is better - * done directly in Python, allowing subclasses to be created directly. - * We'd really have to write a wrapper around it all anyway. - * - */ -static PyMethodDef parser_functions[] = { - {"ast2tuple", parser_ast2tuple, 1}, - {"compileast", parser_compileast, 1}, - {"expr", parser_expr, 1}, - {"isexpr", parser_isexpr, 1}, - {"issuite", parser_issuite, 1}, - {"suite", parser_suite, 1}, - {"tuple2ast", parser_tuple2ast, 1}, - - {0, 0, 0} - }; - - - -void -initparser() { - PyObject* module = Py_InitModule("parser", parser_functions); - PyObject* dict = PyModule_GetDict(module); - - parser_error = PyString_FromString("parser.ParserError"); - - if ((parser_error == 0) - || (PyDict_SetItemString(dict, "ParserError", parser_error) != 0)) { - /* - * This is serious. - */ - Py_FatalError("can't define parser.error"); - } - /* - * Nice to have, but don't cry if we fail. - */ - PyDict_SetItemString(dict, "__copyright__", - PyString_FromString(parser_copyright_string)); - PyDict_SetItemString(dict, "__doc__", - PyString_FromString(parser_doc_string)); - PyDict_SetItemString(dict, "__version__", - PyString_FromString(parser_version_string)); - -} /* initparser() */ - - -/* - * end of Parser.c - */ diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c deleted file mode 100644 index 338a40c0d2..0000000000 --- a/Modules/posixmodule.c +++ /dev/null @@ -1,1746 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* POSIX module implementation */ - -/* This file is also used for Windows NT and MS-Win. In that case the module - actually calls itself 'nt', not 'posix', and a few functions are - either unimplemented or implemented differently. The source - assumes that for Windows NT, the macro 'NT' is defined independent - of the compiler used. Different compilers define their own feature - test macro, e.g. '__BORLANDC__' or '_MSC_VER'. */ - -/* See also ../Dos/dosmodule.c */ - -#include "allobjects.h" -#include "modsupport.h" -#include "ceval.h" - -#include <string.h> -#include <errno.h> -#include <sys/types.h> -#include <sys/stat.h> -#ifdef HAVE_SYS_WAIT_H -#include <sys/wait.h> /* For WNOHANG */ -#endif - -#include "mytime.h" /* For clock_t on some systems */ - -#ifdef HAVE_FCNTL_H -#include <fcntl.h> -#endif /* HAVE_FCNTL_H */ - -/* Various compilers have only certain posix functions */ -#ifdef __WATCOMC__ /* Watcom compiler */ -#define HAVE_GETCWD 1 -#define HAVE_OPENDIR 1 -#define HAVE_SYSTEM 1 -#if defined(__OS2__) -#define HAVE_EXECV 1 -#define HAVE_WAIT 1 -#endif -#include <process.h> -#else -#ifdef __BORLANDC__ /* Borland compiler */ -#define HAVE_EXECV 1 -#define HAVE_GETCWD 1 -#define HAVE_GETEGID 1 -#define HAVE_GETEUID 1 -#define HAVE_GETGID 1 -#define HAVE_GETPPID 1 -#define HAVE_GETUID 1 -#define HAVE_KILL 1 -#define HAVE_OPENDIR 1 -#define HAVE_PIPE 1 -#define HAVE_POPEN 1 -#define HAVE_SYSTEM 1 -#define HAVE_WAIT 1 -#else -#ifdef _MSC_VER /* Microsoft compiler */ -#ifdef NT -#define HAVE_EXECV 1 -#define HAVE_PIPE 1 -#define HAVE_POPEN 1 -#define HAVE_SYSTEM 1 -#else /* 16-bit Windows */ -#endif /* NT */ -#else /* all other compilers */ -/* Unix functions that the configure script doesn't check for */ -#define HAVE_EXECV 1 -#define HAVE_FORK 1 -#define HAVE_GETCWD 1 -#define HAVE_GETEGID 1 -#define HAVE_GETEUID 1 -#define HAVE_GETGID 1 -#define HAVE_GETPPID 1 -#define HAVE_GETUID 1 -#define HAVE_KILL 1 -#define HAVE_OPENDIR 1 -#define HAVE_PIPE 1 -#define HAVE_POPEN 1 -#define HAVE_SYSTEM 1 -#define HAVE_WAIT 1 -#endif /* _MSC_VER */ -#endif /* __BORLANDC__ */ -#endif /* ! __WATCOMC__ */ - -#ifndef _MSC_VER - -#ifdef HAVE_UNISTD_H -#include <unistd.h> -#endif - -#ifdef NeXT -/* NeXT's <unistd.h> and <utime.h> aren't worth much */ -#undef HAVE_UNISTD_H -#undef HAVE_UTIME_H -/* #undef HAVE_GETCWD */ -#endif - -#ifdef HAVE_UNISTD_H -/* XXX These are for SunOS4.1.3 but shouldn't hurt elsewhere */ -extern int rename(); -extern int pclose(); -extern int lstat(); -extern int symlink(); -#else /* !HAVE_UNISTD_H */ -#if defined(__WATCOMC__) -extern int mkdir PROTO((const char *)); -#else -extern int mkdir PROTO((const char *, mode_t)); -#endif -extern int chdir PROTO((const char *)); -extern int rmdir PROTO((const char *)); -extern int chmod PROTO((const char *, mode_t)); -extern int chown PROTO((const char *, uid_t, gid_t)); -extern char *getcwd PROTO((char *, int)); -extern char *strerror PROTO((int)); -extern int link PROTO((const char *, const char *)); -extern int rename PROTO((const char *, const char *)); -extern int stat PROTO((const char *, struct stat *)); -extern int unlink PROTO((const char *)); -extern int pclose PROTO((FILE *)); -#ifdef HAVE_SYMLINK -extern int symlink PROTO((const char *, const char *)); -#endif /* HAVE_SYMLINK */ -#ifdef HAVE_LSTAT -extern int lstat PROTO((const char *, struct stat *)); -#endif /* HAVE_LSTAT */ -#endif /* !HAVE_UNISTD_H */ - -#endif /* !_MSC_VER */ - -#ifdef HAVE_UTIME_H -#include <utime.h> -#endif /* HAVE_UTIME_H */ - -#ifdef HAVE_SYS_UTIME_H -#include <sys/utime.h> -#define HAVE_UTIME_H /* pretend we do for the rest of this file */ -#endif /* HAVE_SYS_UTIME_H */ - -#ifdef HAVE_SYS_TIMES_H -#include <sys/times.h> -#endif /* HAVE_SYS_TIMES_H */ - -#ifdef HAVE_SYS_PARAM_H -#include <sys/param.h> -#endif /* HAVE_SYS_PARAM_H */ - -#ifdef HAVE_SYS_UTSNAME_H -#include <sys/utsname.h> -#endif /* HAVE_SYS_UTSNAME_H */ - -#ifndef MAXPATHLEN -#define MAXPATHLEN 1024 -#endif /* MAXPATHLEN */ - -#ifdef HAVE_DIRENT_H -#include <dirent.h> -#define NAMLEN(dirent) strlen((dirent)->d_name) -#else -#ifdef __WATCOMC__ -#include <direct.h> -#define NAMLEN(dirent) strlen((dirent)->d_name) -#else -#define dirent direct -#define NAMLEN(dirent) (dirent)->d_namlen -#endif -#ifdef HAVE_SYS_NDIR_H -#include <sys/ndir.h> -#endif -#ifdef HAVE_SYS_DIR_H -#include <sys/dir.h> -#endif -#ifdef HAVE_NDIR_H -#include <ndir.h> -#endif -#endif - -#ifdef _MSC_VER -#include <direct.h> -#include <io.h> -#include <process.h> -#include <windows.h> -#ifdef NT -#define popen _popen -#define pclose _pclose -#else /* 16-bit Windows */ -#include <dos.h> -#include <ctype.h> -#endif /* NT */ -#endif /* _MSC_VER */ - -#ifdef OS2 -#include <io.h> -#endif /* OS2 */ - -/* Return a dictionary corresponding to the POSIX environment table */ - -#if !defined(_MSC_VER) && !defined(__WATCOMC__) -extern char **environ; -#endif /* !_MSC_VER */ - -static object * -convertenviron() -{ - object *d; - char **e; - d = newdictobject(); - if (d == NULL) - return NULL; - if (environ == NULL) - return d; - /* XXX This part ignores errors */ - for (e = environ; *e != NULL; e++) { - object *v; - char *p = strchr(*e, '='); - if (p == NULL) - continue; - v = newstringobject(p+1); - if (v == NULL) - continue; - *p = '\0'; - (void) dictinsert(d, *e, v); - *p = '='; - DECREF(v); - } - return d; -} - - -static object *PosixError; /* Exception posix.error */ - -/* Set a POSIX-specific error from errno, and return NULL */ - -static object * posix_error() -{ - return err_errno(PosixError); -} - - -/* POSIX generic methods */ - -static object * -posix_1str(args, func) - object *args; - int (*func) FPROTO((const char *)); -{ - char *path1; - int res; - if (!getargs(args, "s", &path1)) - return NULL; - BGN_SAVE - res = (*func)(path1); - END_SAVE - if (res < 0) - return posix_error(); - INCREF(None); - return None; -} - -static object * -posix_2str(args, func) - object *args; - int (*func) FPROTO((const char *, const char *)); -{ - char *path1, *path2; - int res; - if (!getargs(args, "(ss)", &path1, &path2)) - return NULL; - BGN_SAVE - res = (*func)(path1, path2); - END_SAVE - if (res < 0) - return posix_error(); - INCREF(None); - return None; -} - -static object * -posix_strint(args, func) - object *args; - int (*func) FPROTO((const char *, int)); -{ - char *path; - int i; - int res; - if (!getargs(args, "(si)", &path, &i)) - return NULL; - BGN_SAVE - res = (*func)(path, i); - END_SAVE - if (res < 0) - return posix_error(); - INCREF(None); - return None; -} - -static object * -posix_strintint(args, func) - object *args; - int (*func) FPROTO((const char *, int, int)); -{ - char *path; - int i,i2; - int res; - if (!getargs(args, "(sii)", &path, &i, &i2)) - return NULL; - BGN_SAVE - res = (*func)(path, i, i2); - END_SAVE - if (res < 0) - return posix_error(); - INCREF(None); - return None; -} - -static object * -posix_do_stat(self, args, statfunc) - object *self; - object *args; - int (*statfunc) FPROTO((const char *, struct stat *)); -{ - struct stat st; - char *path; - int res; - if (!getargs(args, "s", &path)) - return NULL; - BGN_SAVE - res = (*statfunc)(path, &st); - END_SAVE - if (res != 0) - return posix_error(); - return mkvalue("(llllllllll)", - (long)st.st_mode, - (long)st.st_ino, - (long)st.st_dev, - (long)st.st_nlink, - (long)st.st_uid, - (long)st.st_gid, - (long)st.st_size, - (long)st.st_atime, - (long)st.st_mtime, - (long)st.st_ctime); -} - - -/* POSIX methods */ - -static object * -posix_chdir(self, args) - object *self; - object *args; -{ - return posix_1str(args, chdir); -} - -static object * -posix_chmod(self, args) - object *self; - object *args; -{ - return posix_strint(args, chmod); -} - -#ifdef HAVE_CHOWN -static object * -posix_chown(self, args) - object *self; - object *args; -{ - return posix_strintint(args, chown); -} -#endif /* HAVE_CHOWN */ - -#ifdef HAVE_GETCWD -static object * -posix_getcwd(self, args) - object *self; - object *args; -{ - char buf[1026]; - char *res; - if (!getnoarg(args)) - return NULL; - BGN_SAVE - res = getcwd(buf, sizeof buf); - END_SAVE - if (res == NULL) - return posix_error(); - return newstringobject(buf); -} -#endif - -#ifdef HAVE_LINK -static object * -posix_link(self, args) - object *self; - object *args; -{ - return posix_2str(args, link); -} -#endif /* HAVE_LINK */ - -static object * -posix_listdir(self, args) - object *self; - object *args; -{ -#if defined(NT) && !defined(HAVE_OPENDIR) - - char *name; - int len; - object *d, *v; - HANDLE hFindFile; - WIN32_FIND_DATA FileData; - char namebuf[MAX_PATH+5]; - - if (!getargs(args, "s#", &name, &len)) - return NULL; - if (len >= MAX_PATH) { - err_setstr(ValueError, "path too long"); - return NULL; - } - strcpy(namebuf, name); - if (namebuf[len-1] != '/' && namebuf[len-1] != '\\') - namebuf[len++] = '/'; - strcpy(namebuf + len, "*.*"); - - if ((d = newlistobject(0)) == NULL) - return NULL; - - hFindFile = FindFirstFile(namebuf, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) { - errno = GetLastError(); - return posix_error(); - } - do { - if (FileData.cFileName[0] == '.' && - (FileData.cFileName[1] == '\0' || - FileData.cFileName[1] == '.' && - FileData.cFileName[2] == '\0')) - continue; - v = newstringobject(FileData.cFileName); - if (v == NULL) { - DECREF(d); - d = NULL; - break; - } - if (addlistitem(d, v) != 0) { - DECREF(v); - DECREF(d); - d = NULL; - break; - } - DECREF(v); - } while (FindNextFile(hFindFile, &FileData) == TRUE); - - if (FindClose(hFindFile) == FALSE) { - errno = GetLastError(); - return posix_error(); - } - - return d; - -#else /* !NT */ -#ifdef _MSC_VER /* 16-bit Windows */ - -#ifndef MAX_PATH -#define MAX_PATH 250 -#endif - char *name, *pt; - int len; - object *d, *v; - char namebuf[MAX_PATH+5]; - struct _find_t ep; - - if (!getargs(args, "s#", &name, &len)) - return NULL; - if (len >= MAX_PATH) { - err_setstr(ValueError, "path too long"); - return NULL; - } - strcpy(namebuf, name); - for (pt = namebuf; *pt; pt++) - if (*pt == '/') - *pt = '\\'; - if (namebuf[len-1] != '\\') - namebuf[len++] = '\\'; - strcpy(namebuf + len, "*.*"); - - if ((d = newlistobject(0)) == NULL) - return NULL; - - if (_dos_findfirst(namebuf, _A_RDONLY | - _A_HIDDEN | _A_SYSTEM | _A_SUBDIR, &ep) != 0){ - errno = ENOENT; - return posix_error(); - } - do { - if (ep.name[0] == '.' && - (ep.name[1] == '\0' || - ep.name[1] == '.' && - ep.name[2] == '\0')) - continue; - strcpy(namebuf, ep.name); - for (pt = namebuf; *pt; pt++) - if (isupper(*pt)) - *pt = tolower(*pt); - v = newstringobject(namebuf); - if (v == NULL) { - DECREF(d); - d = NULL; - break; - } - if (addlistitem(d, v) != 0) { - DECREF(v); - DECREF(d); - d = NULL; - break; - } - DECREF(v); - } while (_dos_findnext(&ep) == 0); - - return d; - -#else - - char *name; - object *d, *v; - DIR *dirp; - struct dirent *ep; - if (!getargs(args, "s", &name)) - return NULL; - BGN_SAVE - if ((dirp = opendir(name)) == NULL) { - RET_SAVE - return posix_error(); - } - if ((d = newlistobject(0)) == NULL) { - closedir(dirp); - RET_SAVE - return NULL; - } - while ((ep = readdir(dirp)) != NULL) { - if (ep->d_name[0] == '.' && - (NAMLEN(ep) == 1 || - ep->d_name[1] == '.' && NAMLEN(ep) == 2)) - continue; - v = newsizedstringobject(ep->d_name, NAMLEN(ep)); - if (v == NULL) { - DECREF(d); - d = NULL; - break; - } - if (addlistitem(d, v) != 0) { - DECREF(v); - DECREF(d); - d = NULL; - break; - } - DECREF(v); - } - closedir(dirp); - END_SAVE - - return d; - -#endif /* !_MSC_VER */ -#endif /* !NT */ -} - -static object * -posix_mkdir(self, args) - object *self; - object *args; -{ - int res; - char *path; - int mode = 0777; - if (!newgetargs(args, "s|i", &path, &mode)) - return NULL; - BGN_SAVE -#if defined(__WATCOMC__) - res = mkdir(path); -#else - res = mkdir(path, mode); -#endif - END_SAVE - if (res < 0) - return posix_error(); - INCREF(None); - return None; -} - -#ifdef HAVE_NICE -static object * -posix_nice(self, args) - object *self; - object *args; -{ - int increment, value; - - if (!getargs(args, "i", &increment)) - return NULL; - value = nice(increment); - if (value == -1) - return posix_error(); - return newintobject((long) value); -} -#endif /* HAVE_NICE */ - -static object * -posix_rename(self, args) - object *self; - object *args; -{ - return posix_2str(args, rename); -} - -static object * -posix_rmdir(self, args) - object *self; - object *args; -{ - return posix_1str(args, rmdir); -} - -static object * -posix_stat(self, args) - object *self; - object *args; -{ - return posix_do_stat(self, args, stat); -} - -#ifdef HAVE_SYSTEM -static object * -posix_system(self, args) - object *self; - object *args; -{ - char *command; - long sts; - if (!getargs(args, "s", &command)) - return NULL; - BGN_SAVE - sts = system(command); - END_SAVE - return newintobject(sts); -} -#endif - -static object * -posix_umask(self, args) - object *self; - object *args; -{ - int i; - if (!getintarg(args, &i)) - return NULL; - i = umask(i); - if (i < 0) - return posix_error(); - return newintobject((long)i); -} - -static object * -posix_unlink(self, args) - object *self; - object *args; -{ - return posix_1str(args, unlink); -} - -#ifdef HAVE_UNAME -static object * -posix_uname(self, args) - object *self; - object *args; -{ - struct utsname u; - object *v; - int res; - if (!getnoarg(args)) - return NULL; - BGN_SAVE - res = uname(&u); - END_SAVE - if (res < 0) - return posix_error(); - return mkvalue("(sssss)", - u.sysname, - u.nodename, - u.release, - u.version, - u.machine); -} -#endif /* HAVE_UNAME */ - -static object * -posix_utime(self, args) - object *self; - object *args; -{ - char *path; - long atime, mtime; - int res; - -#ifdef HAVE_UTIME_H - struct utimbuf buf; -#define ATIME buf.actime -#define MTIME buf.modtime -#define UTIME_ARG &buf -#else /* HAVE_UTIME_H */ - time_t buf[2]; -#define ATIME buf[0] -#define MTIME buf[1] -#define UTIME_ARG buf -#endif /* HAVE_UTIME_H */ - - if (!getargs(args, "(s(ll))", &path, &atime, &mtime)) - return NULL; - ATIME = atime; - MTIME = mtime; - BGN_SAVE - res = utime(path, UTIME_ARG); - END_SAVE - if (res < 0) - return posix_error(); - INCREF(None); - return None; -#undef UTIME_ARG -#undef ATIME -#undef MTIME -} - - -/* Process operations */ - -static object * -posix__exit(self, args) - object *self; - object *args; -{ - int sts; - if (!getintarg(args, &sts)) - return NULL; - _exit(sts); - /* NOTREACHED */ -} - -#ifdef HAVE_EXECV -static object * -posix_execv(self, args) - object *self; - object *args; -{ - char *path; - object *argv; - char **argvlist; - int i, argc; - object *(*getitem) PROTO((object *, int)); - - /* execv has two arguments: (path, argv), where - argv is a list or tuple of strings. */ - - if (!getargs(args, "(sO)", &path, &argv)) - return NULL; - if (is_listobject(argv)) { - argc = getlistsize(argv); - getitem = getlistitem; - } - else if (is_tupleobject(argv)) { - argc = gettuplesize(argv); - getitem = gettupleitem; - } - else { - badarg: - err_badarg(); - return NULL; - } - - argvlist = NEW(char *, argc+1); - if (argvlist == NULL) - return NULL; - for (i = 0; i < argc; i++) { - if (!getargs((*getitem)(argv, i), "s", &argvlist[i])) { - DEL(argvlist); - goto badarg; - } - } - argvlist[argc] = NULL; - -#ifdef BAD_EXEC_PROTOTYPES - execv(path, (const char **) argvlist); -#else /* BAD_EXEC_PROTOTYPES */ - execv(path, argvlist); -#endif /* BAD_EXEC_PROTOTYPES */ - - /* If we get here it's definitely an error */ - - DEL(argvlist); - return posix_error(); -} - -static object * -posix_execve(self, args) - object *self; - object *args; -{ - char *path; - object *argv, *env; - char **argvlist; - char **envlist; - object *key, *val; - int i, pos, argc, envc; - object *(*getitem) PROTO((object *, int)); - - /* execve has three arguments: (path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!getargs(args, "(sOO)", &path, &argv, &env)) - return NULL; - if (is_listobject(argv)) { - argc = getlistsize(argv); - getitem = getlistitem; - } - else if (is_tupleobject(argv)) { - argc = gettuplesize(argv); - getitem = gettupleitem; - } - else { - err_setstr(TypeError, "argv must be tuple or list"); - return NULL; - } - if (!is_dictobject(env)) { - err_setstr(TypeError, "env must be dictionary"); - return NULL; - } - - argvlist = NEW(char *, argc+1); - if (argvlist == NULL) { - err_nomem(); - return NULL; - } - for (i = 0; i < argc; i++) { - if (!getargs((*getitem)(argv, i), - "s;argv must be list of strings", - &argvlist[i])) { - goto fail_1; - } - } - argvlist[argc] = NULL; - - i = getmappingsize(env); - envlist = NEW(char *, i + 1); - if (envlist == NULL) { - err_nomem(); - goto fail_1; - } - pos = 0; - envc = 0; - while (mappinggetnext(env, &pos, &key, &val)) { - char *p, *k, *v; - if (!getargs(key, "s;non-string key in env", &k) || - !getargs(val, "s;non-string value in env", &v)) { - goto fail_2; - } - p = NEW(char, getstringsize(key) + getstringsize(val) + 2); - if (p == NULL) { - err_nomem(); - goto fail_2; - } - sprintf(p, "%s=%s", k, v); - envlist[envc++] = p; - } - envlist[envc] = 0; - - -#ifdef BAD_EXEC_PROTOTYPES - execve(path, (const char **)argvlist, envlist); -#else /* BAD_EXEC_PROTOTYPES */ - execve(path, argvlist, envlist); -#endif /* BAD_EXEC_PROTOTYPES */ - - /* If we get here it's definitely an error */ - - (void) posix_error(); - - fail_2: - while (--envc >= 0) - DEL(envlist[envc]); - DEL(envlist); - fail_1: - DEL(argvlist); - - return NULL; -} -#endif /* HAVE_EXECV */ - -#ifdef HAVE_FORK -static object * -posix_fork(self, args) - object *self; - object *args; -{ - int pid; - if (!getnoarg(args)) - return NULL; - pid = fork(); - if (pid == -1) - return posix_error(); - return newintobject((long)pid); -} -#endif - -#ifdef HAVE_GETEGID -static object * -posix_getegid(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newintobject((long)getegid()); -} -#endif - -#ifdef HAVE_GETEUID -static object * -posix_geteuid(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newintobject((long)geteuid()); -} -#endif - -#ifdef HAVE_GETGID -static object * -posix_getgid(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newintobject((long)getgid()); -} -#endif - -static object * -posix_getpid(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newintobject((long)getpid()); -} - -#ifdef HAVE_GETPGRP -static object * -posix_getpgrp(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; -#ifdef GETPGRP_HAVE_ARG - return newintobject((long)getpgrp(0)); -#else /* GETPGRP_HAVE_ARG */ - return newintobject((long)getpgrp()); -#endif /* GETPGRP_HAVE_ARG */ -} -#endif /* HAVE_GETPGRP */ - -#ifdef HAVE_SETPGRP -static object * -posix_setpgrp(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; -#ifdef SETPGRP_HAVE_ARG - if (setpgrp(0, 0) < 0) -#else /* SETPGRP_HAVE_ARG */ - if (setpgrp() < 0) -#endif /* SETPGRP_HAVE_ARG */ - return posix_error(); - INCREF(None); - return None; -} - -#endif /* HAVE_SETPGRP */ - -#ifdef HAVE_GETPPID -static object * -posix_getppid(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newintobject((long)getppid()); -} -#endif - -#ifdef HAVE_GETUID -static object * -posix_getuid(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newintobject((long)getuid()); -} -#endif - -#ifdef HAVE_KILL -static object * -posix_kill(self, args) - object *self; - object *args; -{ - int pid, sig; - if (!getargs(args, "(ii)", &pid, &sig)) - return NULL; - if (kill(pid, sig) == -1) - return posix_error(); - INCREF(None); - return None; -} -#endif - -#ifdef HAVE_POPEN -static object * -posix_popen(self, args) - object *self; - object *args; -{ - char *name; - char *mode = "r"; - int bufsize = -1; - FILE *fp; - object *f; - if (!newgetargs(args, "s|si", &name, &mode, &bufsize)) - return NULL; - BGN_SAVE - fp = popen(name, mode); - END_SAVE - if (fp == NULL) - return posix_error(); - f = newopenfileobject(fp, name, mode, pclose); - if (f != NULL) - setfilebufsize(f, bufsize); - return f; -} -#endif /* HAVE_POPEN */ - -#ifdef HAVE_SETUID -static object * -posix_setuid(self, args) - object *self; - object *args; -{ - int uid; - if (!getargs(args, "i", &uid)) - return NULL; - if (setuid(uid) < 0) - return posix_error(); - INCREF(None); - return None; -} -#endif /* HAVE_SETUID */ - -#ifdef HAVE_SETGID -static object * -posix_setgid(self, args) - object *self; - object *args; -{ - int gid; - if (!getargs(args, "i", &gid)) - return NULL; - if (setgid(gid) < 0) - return posix_error(); - INCREF(None); - return None; -} -#endif /* HAVE_SETGID */ - -#ifdef HAVE_WAITPID -static object * -posix_waitpid(self, args) - object *self; - object *args; -{ - int pid, options, sts; - if (!getargs(args, "(ii)", &pid, &options)) - return NULL; - BGN_SAVE - pid = waitpid(pid, &sts, options); - END_SAVE - if (pid == -1) - return posix_error(); - else - return mkvalue("ii", pid, sts); -} -#endif /* HAVE_WAITPID */ - -#ifdef HAVE_WAIT -static object * -posix_wait(self, args) - object *self; - object *args; -{ - int pid, sts; - BGN_SAVE - pid = wait(&sts); - END_SAVE - if (pid == -1) - return posix_error(); - else - return mkvalue("ii", pid, sts); -} -#endif - -static object * -posix_lstat(self, args) - object *self; - object *args; -{ -#ifdef HAVE_LSTAT - return posix_do_stat(self, args, lstat); -#else /* !HAVE_LSTAT */ - return posix_do_stat(self, args, stat); -#endif /* !HAVE_LSTAT */ -} - -#ifdef HAVE_READLINK -static object * -posix_readlink(self, args) - object *self; - object *args; -{ - char buf[MAXPATHLEN]; - char *path; - int n; - if (!getargs(args, "s", &path)) - return NULL; - BGN_SAVE - n = readlink(path, buf, (int) sizeof buf); - END_SAVE - if (n < 0) - return posix_error(); - return newsizedstringobject(buf, n); -} -#endif /* HAVE_READLINK */ - -#ifdef HAVE_SYMLINK -static object * -posix_symlink(self, args) - object *self; - object *args; -{ - return posix_2str(args, symlink); -} -#endif /* HAVE_SYMLINK */ - -#ifdef HAVE_TIMES -#ifndef HZ -#define HZ 60 /* Universal constant :-) */ -#endif /* HZ */ -static object * -posix_times(self, args) - object *self; - object *args; -{ - struct tms t; - clock_t c; - if (!getnoarg(args)) - return NULL; - errno = 0; - c = times(&t); - if (c == (clock_t) -1) - return posix_error(); - return mkvalue("ddddd", - (double)t.tms_utime / HZ, - (double)t.tms_stime / HZ, - (double)t.tms_cutime / HZ, - (double)t.tms_cstime / HZ, - (double)c / HZ); -} -#endif /* HAVE_TIMES */ -#if defined(NT) && !defined(HAVE_TIMES) -#define HAVE_TIMES /* so the method table will pick it up */ -static object * -posix_times(self, args) - object *self; - object *args; -{ - FILETIME create, exit, kernel, user; - HANDLE hProc; - if (!getnoarg(args)) - return NULL; - hProc = GetCurrentProcess(); - GetProcessTimes(hProc,&create, &exit, &kernel, &user); - return mkvalue("ddddd", - (double)(kernel.dwHighDateTime*2E32+kernel.dwLowDateTime) / 2E6, - (double)(user.dwHighDateTime*2E32+user.dwLowDateTime) / 2E6, - (double)0, - (double)0, - (double)0); -} -#endif /* NT */ - -#ifdef HAVE_SETSID -static object * -posix_setsid(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - if (setsid() < 0) - return posix_error(); - INCREF(None); - return None; -} -#endif /* HAVE_SETSID */ - -#ifdef HAVE_SETPGID -static object * -posix_setpgid(self, args) - object *self; - object *args; -{ - int pid, pgrp; - if (!getargs(args, "(ii)", &pid, &pgrp)) - return NULL; - if (setpgid(pid, pgrp) < 0) - return posix_error(); - INCREF(None); - return None; -} -#endif /* HAVE_SETPGID */ - -#ifdef HAVE_TCGETPGRP -static object * -posix_tcgetpgrp(self, args) - object *self; - object *args; -{ - int fd, pgid; - if (!getargs(args, "i", &fd)) - return NULL; - pgid = tcgetpgrp(fd); - if (pgid < 0) - return posix_error(); - return newintobject((long)pgid); -} -#endif /* HAVE_TCGETPGRP */ - -#ifdef HAVE_TCSETPGRP -static object * -posix_tcsetpgrp(self, args) - object *self; - object *args; -{ - int fd, pgid; - if (!getargs(args, "(ii)", &fd, &pgid)) - return NULL; - if (tcsetpgrp(fd, pgid) < 0) - return posix_error(); - INCREF(None); - return None; -} -#endif /* HAVE_TCSETPGRP */ - -/* Functions acting on file descriptors */ - -static object * -posix_open(self, args) - object *self; - object *args; -{ - char *file; - int flag; - int mode = 0777; - int fd; - if (!getargs(args, "(si)", &file, &flag)) { - err_clear(); - if (!getargs(args, "(sii)", &file, &flag, &mode)) - return NULL; - } - BGN_SAVE - fd = open(file, flag, mode); - END_SAVE - if (fd < 0) - return posix_error(); - return newintobject((long)fd); -} - -static object * -posix_close(self, args) - object *self; - object *args; -{ - int fd, res; - if (!getargs(args, "i", &fd)) - return NULL; - BGN_SAVE - res = close(fd); - END_SAVE - if (res < 0) - return posix_error(); - INCREF(None); - return None; -} - -static object * -posix_dup(self, args) - object *self; - object *args; -{ - int fd; - if (!getargs(args, "i", &fd)) - return NULL; - BGN_SAVE - fd = dup(fd); - END_SAVE - if (fd < 0) - return posix_error(); - return newintobject((long)fd); -} - -static object * -posix_dup2(self, args) - object *self; - object *args; -{ - int fd, fd2, res; - if (!getargs(args, "(ii)", &fd, &fd2)) - return NULL; - BGN_SAVE - res = dup2(fd, fd2); - END_SAVE - if (res < 0) - return posix_error(); - INCREF(None); - return None; -} - -static object * -posix_lseek(self, args) - object *self; - object *args; -{ - int fd, how; - long pos, res; - if (!getargs(args, "(ili)", &fd, &pos, &how)) - return NULL; -#ifdef SEEK_SET - /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ - switch (how) { - case 0: how = SEEK_SET; break; - case 1: how = SEEK_CUR; break; - case 2: how = SEEK_END; break; - } -#endif /* SEEK_END */ - BGN_SAVE - res = lseek(fd, pos, how); - END_SAVE - if (res < 0) - return posix_error(); - return newintobject(res); -} - -static object * -posix_read(self, args) - object *self; - object *args; -{ - int fd, size; - object *buffer; - if (!getargs(args, "(ii)", &fd, &size)) - return NULL; - buffer = newsizedstringobject((char *)NULL, size); - if (buffer == NULL) - return NULL; - BGN_SAVE - size = read(fd, getstringvalue(buffer), size); - END_SAVE - if (size < 0) { - DECREF(buffer); - return posix_error(); - } - resizestring(&buffer, size); - return buffer; -} - -static object * -posix_write(self, args) - object *self; - object *args; -{ - int fd, size; - char *buffer; - if (!getargs(args, "(is#)", &fd, &buffer, &size)) - return NULL; - BGN_SAVE - size = write(fd, buffer, size); - END_SAVE - if (size < 0) - return posix_error(); - return newintobject((long)size); -} - -static object * -posix_fstat(self, args) - object *self; - object *args; -{ - int fd; - struct stat st; - int res; - if (!getargs(args, "i", &fd)) - return NULL; - BGN_SAVE - res = fstat(fd, &st); - END_SAVE - if (res != 0) - return posix_error(); - return mkvalue("(llllllllll)", - (long)st.st_mode, - (long)st.st_ino, - (long)st.st_dev, - (long)st.st_nlink, - (long)st.st_uid, - (long)st.st_gid, - (long)st.st_size, - (long)st.st_atime, - (long)st.st_mtime, - (long)st.st_ctime); -} - -static object * -posix_fdopen(self, args) - object *self; - object *args; -{ - extern int fclose PROTO((FILE *)); - int fd; - char *mode = "r"; - int bufsize = -1; - FILE *fp; - object *f; - if (!newgetargs(args, "i|si", &fd, &mode, &bufsize)) - return NULL; - BGN_SAVE - fp = fdopen(fd, mode); - END_SAVE - if (fp == NULL) - return posix_error(); - f = newopenfileobject(fp, "(fdopen)", mode, fclose); - if (f != NULL) - setfilebufsize(f, bufsize); - return f; -} - -#ifdef HAVE_PIPE -static object * -posix_pipe(self, args) - object *self; - object *args; -{ -#if !defined(NT) - int fds[2]; - int res; - if (!getargs(args, "")) - return NULL; - BGN_SAVE - res = pipe(fds); - END_SAVE - if (res != 0) - return posix_error(); - return mkvalue("(ii)", fds[0], fds[1]); -#else /* NT */ - HANDLE read, write; - BOOL ok; - if (!getargs(args, "")) - return NULL; - BGN_SAVE - ok = CreatePipe( &read, &write, NULL, 0); - END_SAVE - if (!ok) - return posix_error(); - return mkvalue("(ii)", read, write); -#endif /* NT */ -} -#endif /* HAVE_PIPE */ - -#ifdef HAVE_MKFIFO -static object * -posix_mkfifo(self, args) - object *self; - object *args; -{ - char *file; - int mode = 0666; - int res; - if (!newgetargs(args, "s|i", &file, &mode)) - return NULL; - BGN_SAVE - res = mkfifo(file, mode); - END_SAVE - if (res < 0) - return posix_error(); - INCREF(None); - return None; -} -#endif - -#ifdef HAVE_FTRUNCATE -static object * -posix_ftruncate(self, args) - object *self; /* Not used */ - object *args; -{ - int fd; - long length; - int res; - - if (!getargs(args, "(il)", &fd, &length)) - return NULL; - - BGN_SAVE - res = ftruncate(fd, length); - END_SAVE - if (res < 0) { - err_errno(IOError); - return NULL; - } - INCREF(None); - return None; -} -#endif - -static struct methodlist posix_methods[] = { - {"chdir", posix_chdir}, - {"chmod", posix_chmod}, -#ifdef HAVE_CHOWN - {"chown", posix_chown}, -#endif /* HAVE_CHOWN */ -#ifdef HAVE_GETCWD - {"getcwd", posix_getcwd}, -#endif -#ifdef HAVE_LINK - {"link", posix_link}, -#endif /* HAVE_LINK */ - {"listdir", posix_listdir}, - {"lstat", posix_lstat}, - {"mkdir", posix_mkdir, 1}, -#ifdef HAVE_NICE - {"nice", posix_nice}, -#endif /* HAVE_NICE */ -#ifdef HAVE_READLINK - {"readlink", posix_readlink}, -#endif /* HAVE_READLINK */ - {"rename", posix_rename}, - {"rmdir", posix_rmdir}, - {"stat", posix_stat}, -#ifdef HAVE_SYMLINK - {"symlink", posix_symlink}, -#endif /* HAVE_SYMLINK */ -#ifdef HAVE_SYSTEM - {"system", posix_system}, -#endif - {"umask", posix_umask}, -#ifdef HAVE_UNAME - {"uname", posix_uname}, -#endif /* HAVE_UNAME */ - {"unlink", posix_unlink}, - {"remove", posix_unlink}, - {"utime", posix_utime}, -#ifdef HAVE_TIMES - {"times", posix_times}, -#endif /* HAVE_TIMES */ - {"_exit", posix__exit}, -#ifdef HAVE_EXECV - {"execv", posix_execv}, - {"execve", posix_execve}, -#endif /* HAVE_EXECV */ -#ifdef HAVE_FORK - {"fork", posix_fork}, -#endif /* HAVE_FORK */ -#ifdef HAVE_GETEGID - {"getegid", posix_getegid}, -#endif /* HAVE_GETEGID */ -#ifdef HAVE_GETEUID - {"geteuid", posix_geteuid}, -#endif /* HAVE_GETEUID */ -#ifdef HAVE_GETGID - {"getgid", posix_getgid}, -#endif /* HAVE_GETGID */ - {"getpid", posix_getpid}, -#ifdef HAVE_GETPGRP - {"getpgrp", posix_getpgrp}, -#endif /* HAVE_GETPGRP */ -#ifdef HAVE_GETPPID - {"getppid", posix_getppid}, -#endif /* HAVE_GETPPID */ -#ifdef HAVE_GETUID - {"getuid", posix_getuid}, -#endif /* HAVE_GETUID */ -#ifdef HAVE_KILL - {"kill", posix_kill}, -#endif /* HAVE_KILL */ -#ifdef HAVE_POPEN - {"popen", posix_popen, 1}, -#endif /* HAVE_POPEN */ -#ifdef HAVE_SETUID - {"setuid", posix_setuid}, -#endif /* HAVE_SETUID */ -#ifdef HAVE_SETGID - {"setgid", posix_setgid}, -#endif /* HAVE_SETGID */ -#ifdef HAVE_SETPGRP - {"setpgrp", posix_setpgrp}, -#endif /* HAVE_SETPGRP */ -#ifdef HAVE_WAIT - {"wait", posix_wait}, -#endif /* HAVE_WAIT */ -#ifdef HAVE_WAITPID - {"waitpid", posix_waitpid}, -#endif /* HAVE_WAITPID */ -#ifdef HAVE_SETSID - {"setsid", posix_setsid}, -#endif /* HAVE_SETSID */ -#ifdef HAVE_SETPGID - {"setpgid", posix_setpgid}, -#endif /* HAVE_SETPGID */ -#ifdef HAVE_TCGETPGRP - {"tcgetpgrp", posix_tcgetpgrp}, -#endif /* HAVE_TCGETPGRP */ -#ifdef HAVE_TCSETPGRP - {"tcsetpgrp", posix_tcsetpgrp}, -#endif /* HAVE_TCSETPGRP */ - {"open", posix_open}, - {"close", posix_close}, - {"dup", posix_dup}, - {"dup2", posix_dup2}, - {"lseek", posix_lseek}, - {"read", posix_read}, - {"write", posix_write}, - {"fstat", posix_fstat}, - {"fdopen", posix_fdopen, 1}, -#ifdef HAVE_PIPE - {"pipe", posix_pipe}, -#endif -#ifdef HAVE_MKFIFO - {"mkfifo", posix_mkfifo, 1}, -#endif -#ifdef HAVE_FTRUNCATE - {"ftruncate", posix_ftruncate, 1}, -#endif - {NULL, NULL} /* Sentinel */ -}; - - -#if defined(_MSC_VER) || defined(__WATCOMC__) -void -initnt() -{ - object *m, *d, *v; - - m = initmodule("nt", posix_methods); - d = getmoduledict(m); - - /* Initialize nt.environ dictionary */ - v = convertenviron(); - if (v == NULL || dictinsert(d, "environ", v) != 0) - fatal("can't define nt.environ"); - DECREF(v); - - /* Initialize nt.error exception */ - PosixError = newstringobject("nt.error"); - if (PosixError == NULL || dictinsert(d, "error", PosixError) != 0) - fatal("can't define nt.error"); -} -#else /* !_MSC_VER */ -void -initposix() -{ - object *m, *d, *v; - - m = initmodule("posix", posix_methods); - d = getmoduledict(m); - - /* Initialize posix.environ dictionary */ - v = convertenviron(); - if (v == NULL || dictinsert(d, "environ", v) != 0) - fatal("can't define posix.environ"); - DECREF(v); - -#ifdef WNOHANG - /* Export WNOHANG symbol */ - v = newintobject((long)WNOHANG); - if (v == NULL || dictinsert(d, "WNOHANG", v) != 0) - fatal("can't define posix.WNOHANG"); - DECREF(v); -#endif - - /* Initialize posix.error exception */ - PosixError = newstringobject("posix.error"); - if (PosixError == NULL || dictinsert(d, "error", PosixError) != 0) - fatal("can't define posix.error"); -} -#endif /* !_MSC_VER */ diff --git a/Modules/pwdmodule.c b/Modules/pwdmodule.c deleted file mode 100644 index ec0e848f7b..0000000000 --- a/Modules/pwdmodule.c +++ /dev/null @@ -1,113 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* UNIX password file access module */ - -#include "allobjects.h" -#include "modsupport.h" - -#include <sys/types.h> -#include <pwd.h> - -static object *mkpwent(p) - struct passwd *p; -{ - return mkvalue("(ssllsss)", - p->pw_name, - p->pw_passwd, -#if defined(NeXT) && defined(_POSIX_SOURCE) && defined(__LITTLE_ENDIAN__) -/* Correct a bug present on Intel machines in NextStep 3.2 and 3.3; - for later versions you may have to remove this */ - (long)p->pw_short_pad1, /* ugh-NeXT broke the padding */ - (long)p->pw_short_pad2, -#else - (long)p->pw_uid, - (long)p->pw_gid, -#endif - p->pw_gecos, - p->pw_dir, - p->pw_shell); -} - -static object *pwd_getpwuid(self, args) - object *self, *args; -{ - int uid; - struct passwd *p; - if (!getintarg(args, &uid)) - return NULL; - if ((p = getpwuid(uid)) == NULL) { - err_setstr(KeyError, "getpwuid(): uid not found"); - return NULL; - } - return mkpwent(p); -} - -static object *pwd_getpwnam(self, args) - object *self, *args; -{ - char *name; - struct passwd *p; - if (!getstrarg(args, &name)) - return NULL; - if ((p = getpwnam(name)) == NULL) { - err_setstr(KeyError, "getpwnam(): name not found"); - return NULL; - } - return mkpwent(p); -} - -static object *pwd_getpwall(self, args) - object *self, *args; -{ - object *d; - struct passwd *p; - if (!getnoarg(args)) - return NULL; - if ((d = newlistobject(0)) == NULL) - return NULL; - setpwent(); - while ((p = getpwent()) != NULL) { - object *v = mkpwent(p); - if (v == NULL || addlistitem(d, v) != 0) { - XDECREF(v); - DECREF(d); - return NULL; - } - } - return d; -} - -static struct methodlist pwd_methods[] = { - {"getpwuid", pwd_getpwuid}, - {"getpwnam", pwd_getpwnam}, - {"getpwall", pwd_getpwall}, - {NULL, NULL} /* sentinel */ -}; - -void -initpwd() -{ - initmodule("pwd", pwd_methods); -} diff --git a/Modules/regexmodule.c b/Modules/regexmodule.c deleted file mode 100644 index 893f4fc31b..0000000000 --- a/Modules/regexmodule.c +++ /dev/null @@ -1,592 +0,0 @@ -/* -XXX support range parameter on search -XXX support mstop parameter on search -*/ - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Regular expression objects */ -/* This uses Tatu Ylonen's copyleft-free reimplementation of - GNU regular expressions */ - -#include "allobjects.h" -#include "modsupport.h" - -#include "regexpr.h" -#include <ctype.h> - -static object *RegexError; /* Exception */ - -typedef struct { - OB_HEAD - struct re_pattern_buffer re_patbuf; /* The compiled expression */ - struct re_registers re_regs; /* The registers from the last match */ - char re_fastmap[256]; /* Storage for fastmap */ - object *re_translate; /* String object for translate table */ - object *re_lastok; /* String object last matched/searched */ - object *re_groupindex; /* Group name to index dictionary */ - object *re_givenpat; /* Pattern with symbolic groups */ - object *re_realpat; /* Pattern without symbolic groups */ -} regexobject; - -/* Regex object methods */ - -static void -reg_dealloc(re) - regexobject *re; -{ - XDEL(re->re_patbuf.buffer); - XDECREF(re->re_translate); - XDECREF(re->re_lastok); - XDECREF(re->re_groupindex); - XDECREF(re->re_givenpat); - XDECREF(re->re_realpat); - DEL(re); -} - -static object * -makeresult(regs) - struct re_registers *regs; -{ - object *v = newtupleobject(RE_NREGS); - if (v != NULL) { - int i; - for (i = 0; i < RE_NREGS; i++) { - object *w; - w = mkvalue("(ii)", regs->start[i], regs->end[i]); - if (w == NULL) { - XDECREF(v); - v = NULL; - break; - } - settupleitem(v, i, w); - } - } - return v; -} - -static object * -reg_match(re, args) - regexobject *re; - object *args; -{ - object *argstring; - char *buffer; - int size; - int offset; - int result; - if (getargs(args, "S", &argstring)) { - offset = 0; - } - else { - err_clear(); - if (!getargs(args, "(Si)", &argstring, &offset)) - return NULL; - } - buffer = getstringvalue(argstring); - size = getstringsize(argstring); - if (offset < 0 || offset > size) { - err_setstr(RegexError, "match offset out of range"); - return NULL; - } - XDECREF(re->re_lastok); - re->re_lastok = NULL; - result = re_match(&re->re_patbuf, buffer, size, offset, &re->re_regs); - if (result < -1) { - /* Failure like stack overflow */ - err_setstr(RegexError, "match failure"); - return NULL; - } - if (result >= 0) { - INCREF(argstring); - re->re_lastok = argstring; - } - return newintobject((long)result); /* Length of the match or -1 */ -} - -static object * -reg_search(re, args) - regexobject *re; - object *args; -{ - object *argstring; - char *buffer; - int size; - int offset; - int range; - int result; - - if (getargs(args, "S", &argstring)) { - offset = 0; - } - else { - err_clear(); - if (!getargs(args, "(Si)", &argstring, &offset)) - return NULL; - } - buffer = getstringvalue(argstring); - size = getstringsize(argstring); - if (offset < 0 || offset > size) { - err_setstr(RegexError, "search offset out of range"); - return NULL; - } - /* NB: In Emacs 18.57, the documentation for re_search[_2] and - the implementation don't match: the documentation states that - |range| positions are tried, while the code tries |range|+1 - positions. It seems more productive to believe the code! */ - range = size - offset; - XDECREF(re->re_lastok); - re->re_lastok = NULL; - result = re_search(&re->re_patbuf, buffer, size, offset, range, - &re->re_regs); - if (result < -1) { - /* Failure like stack overflow */ - err_setstr(RegexError, "match failure"); - return NULL; - } - if (result >= 0) { - INCREF(argstring); - re->re_lastok = argstring; - } - return newintobject((long)result); /* Position of the match or -1 */ -} - -static object * -reg_group(re, args) - regexobject *re; - object *args; -{ - int i, a, b; - if (args != NULL && is_tupleobject(args)) { - int n = gettuplesize(args); - object *res = newtupleobject(n); - if (res == NULL) - return NULL; - for (i = 0; i < n; i++) { - object *v = reg_group(re, gettupleitem(args, i)); - if (v == NULL) { - DECREF(res); - return NULL; - } - settupleitem(res, i, v); - } - return res; - } - if (!getargs(args, "i", &i)) { - object *n; - err_clear(); - if (!getargs(args, "S", &n)) - return NULL; - else { - object *index; - if (re->re_groupindex == NULL) - index = NULL; - else - index = mappinglookup(re->re_groupindex, n); - if (index == NULL) { - err_setstr(RegexError, "group() group name doesn't exist"); - return NULL; - } - i = getintvalue(index); - } - } - if (i < 0 || i >= RE_NREGS) { - err_setstr(RegexError, "group() index out of range"); - return NULL; - } - if (re->re_lastok == NULL) { - err_setstr(RegexError, - "group() only valid after successful match/search"); - return NULL; - } - a = re->re_regs.start[i]; - b = re->re_regs.end[i]; - if (a < 0 || b < 0) { - INCREF(None); - return None; - } - return newsizedstringobject(getstringvalue(re->re_lastok)+a, b-a); -} - -static struct methodlist reg_methods[] = { - {"match", (method)reg_match}, - {"search", (method)reg_search}, - {"group", (method)reg_group}, - {NULL, NULL} /* sentinel */ -}; - -static object * -reg_getattr(re, name) - regexobject *re; - char *name; -{ - if (strcmp(name, "regs") == 0) { - if (re->re_lastok == NULL) { - INCREF(None); - return None; - } - return makeresult(&re->re_regs); - } - if (strcmp(name, "last") == 0) { - if (re->re_lastok == NULL) { - INCREF(None); - return None; - } - INCREF(re->re_lastok); - return re->re_lastok; - } - if (strcmp(name, "translate") == 0) { - if (re->re_translate == NULL) { - INCREF(None); - return None; - } - INCREF(re->re_translate); - return re->re_translate; - } - if (strcmp(name, "groupindex") == 0) { - if (re->re_groupindex == NULL) { - INCREF(None); - return None; - } - INCREF(re->re_groupindex); - return re->re_groupindex; - } - if (strcmp(name, "realpat") == 0) { - if (re->re_realpat == NULL) { - INCREF(None); - return None; - } - INCREF(re->re_realpat); - return re->re_realpat; - } - if (strcmp(name, "givenpat") == 0) { - if (re->re_givenpat == NULL) { - INCREF(None); - return None; - } - INCREF(re->re_givenpat); - return re->re_givenpat; - } - if (strcmp(name, "__members__") == 0) { - object *list = newlistobject(6); - if (list) { - setlistitem(list, 0, newstringobject("last")); - setlistitem(list, 1, newstringobject("regs")); - setlistitem(list, 2, newstringobject("translate")); - setlistitem(list, 3, newstringobject("groupindex")); - setlistitem(list, 4, newstringobject("realpat")); - setlistitem(list, 5, newstringobject("givenpat")); - if (err_occurred()) { - DECREF(list); - list = NULL; - } - } - return list; - } - return findmethod(reg_methods, (object *)re, name); -} - -static typeobject Regextype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "regex", /*tp_name*/ - sizeof(regexobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)reg_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)reg_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - -static object * -newregexobject(pattern, translate, givenpat, groupindex) - object *pattern; - object *translate; - object *givenpat; - object *groupindex; -{ - regexobject *re; - char *pat = getstringvalue(pattern); - int size = getstringsize(pattern); - - if (translate != NULL && getstringsize(translate) != 256) { - err_setstr(RegexError, - "translation table must be 256 bytes"); - return NULL; - } - re = NEWOBJ(regexobject, &Regextype); - if (re != NULL) { - char *error; - re->re_patbuf.buffer = NULL; - re->re_patbuf.allocated = 0; - re->re_patbuf.fastmap = re->re_fastmap; - if (translate) - re->re_patbuf.translate = getstringvalue(translate); - else - re->re_patbuf.translate = NULL; - XINCREF(translate); - re->re_translate = translate; - re->re_lastok = NULL; - re->re_groupindex = groupindex; - INCREF(pattern); - re->re_realpat = pattern; - INCREF(givenpat); - re->re_givenpat = givenpat; - error = re_compile_pattern(pat, size, &re->re_patbuf); - if (error != NULL) { - err_setstr(RegexError, error); - DECREF(re); - re = NULL; - } - } - return (object *)re; -} - -static object * -regex_compile(self, args) - object *self; - object *args; -{ - object *pat = NULL; - object *tran = NULL; - if (!getargs(args, "S", &pat)) { - err_clear(); - if (!getargs(args, "(SS)", &pat, &tran)) - return NULL; - } - return newregexobject(pat, tran, pat, NULL); -} - -static object * -symcomp(pattern, gdict) - object *pattern; - object *gdict; -{ - char *opat = getstringvalue(pattern); - char *oend = opat + getstringsize(pattern); - int group_count = 0; - int escaped = 0; - char *o = opat; - char *n; - char name_buf[128]; - char *g; - object *npattern; - int require_escape = re_syntax & RE_NO_BK_PARENS ? 0 : 1; - - npattern = newsizedstringobject((char*)NULL, getstringsize(pattern)); - if (npattern == NULL) - return NULL; - n = getstringvalue(npattern); - - while (o < oend) { - if (*o == '(' && escaped == require_escape) { - char *backtrack; - escaped = 0; - ++group_count; - *n++ = *o; - if (++o >= oend || *o != '<') - continue; - /* *o == '<' */ - if (o+1 < oend && *(o+1) == '>') - continue; - backtrack = o; - g = name_buf; - for (++o; o < oend;) { - if (*o == '>') { - object *group_name = NULL; - object *group_index = NULL; - *g++ = '\0'; - group_name = newstringobject(name_buf); - group_index = newintobject(group_count); - if (group_name == NULL || group_index == NULL - || mappinginsert(gdict, group_name, group_index) != 0) { - XDECREF(group_name); - XDECREF(group_index); - XDECREF(npattern); - return NULL; - } - ++o; /* eat the '>' */ - break; - } - if (!isalnum(Py_CHARMASK(*o)) && *o != '_') { - o = backtrack; - break; - } - *g++ = *o++; - } - } - if (*o == '[' && !escaped) { - *n++ = *o; - ++o; /* eat the char following '[' */ - *n++ = *o; - while (o < oend && *o != ']') { - ++o; - *n++ = *o; - } - if (o < oend) - ++o; - } - else if (*o == '\\') { - escaped = 1; - *n++ = *o; - ++o; - } - else { - escaped = 0; - *n++ = *o; - ++o; - } - } - - if (resizestring(&npattern, n - getstringvalue(npattern)) == 0) - return npattern; - else { - DECREF(npattern); - return NULL; - } - -} - -static object * -regex_symcomp(self, args) - object *self; - object *args; -{ - object *pattern; - object *tran = NULL; - object *gdict = NULL; - object *npattern; - if (!getargs(args, "S", &pattern)) { - err_clear(); - if (!getargs(args, "(SS)", &pattern, &tran)) - return NULL; - } - gdict = newmappingobject(); - if (gdict == NULL - || (npattern = symcomp(pattern, gdict)) == NULL) { - DECREF(gdict); - DECREF(pattern); - return NULL; - } - return newregexobject(npattern, tran, pattern, gdict); -} - - -static object *cache_pat; -static object *cache_prog; - -static int -update_cache(pat) - object *pat; -{ - if (pat != cache_pat) { - XDECREF(cache_pat); - cache_pat = NULL; - XDECREF(cache_prog); - cache_prog = regex_compile((object *)NULL, pat); - if (cache_prog == NULL) - return -1; - cache_pat = pat; - INCREF(cache_pat); - } - return 0; -} - -static object * -regex_match(self, args) - object *self; - object *args; -{ - object *pat, *string; - if (!getargs(args, "(SS)", &pat, &string)) - return NULL; - if (update_cache(pat) < 0) - return NULL; - return reg_match((regexobject *)cache_prog, string); -} - -static object * -regex_search(self, args) - object *self; - object *args; -{ - object *pat, *string; - if (!getargs(args, "(SS)", &pat, &string)) - return NULL; - if (update_cache(pat) < 0) - return NULL; - return reg_search((regexobject *)cache_prog, string); -} - -static object * -regex_set_syntax(self, args) - object *self, *args; -{ - int syntax; - if (!getintarg(args, &syntax)) - return NULL; - syntax = re_set_syntax(syntax); - return newintobject((long)syntax); -} - -static struct methodlist regex_global_methods[] = { - {"compile", regex_compile, 0}, - {"symcomp", regex_symcomp, 0}, - {"match", regex_match, 0}, - {"search", regex_search, 0}, - {"set_syntax", regex_set_syntax, 0}, - {NULL, NULL} /* sentinel */ -}; - -initregex() -{ - object *m, *d, *v; - - m = initmodule("regex", regex_global_methods); - d = getmoduledict(m); - - /* Initialize regex.error exception */ - RegexError = newstringobject("regex.error"); - if (RegexError == NULL || dictinsert(d, "error", RegexError) != 0) - fatal("can't define regex.error"); - - /* Initialize regex.casefold constant */ - v = newsizedstringobject((char *)NULL, 256); - if (v != NULL) { - int i; - char *s = getstringvalue(v); - for (i = 0; i < 256; i++) { - if (isupper(i)) - s[i] = tolower(i); - else - s[i] = i; - } - dictinsert(d, "casefold", v); - DECREF(v); - } -} diff --git a/Modules/regexpr.c b/Modules/regexpr.c deleted file mode 100644 index 6d6bb0f3be..0000000000 --- a/Modules/regexpr.c +++ /dev/null @@ -1,1702 +0,0 @@ -/* - -regexpr.c - -Author: Tatu Ylonen <ylo@ngs.fi> - -Copyright (c) 1991 Tatu Ylonen, Espoo, Finland - -Permission to use, copy, modify, distribute, and sell this software -and its documentation for any purpose is hereby granted without fee, -provided that the above copyright notice appear in all copies. This -software is provided "as is" without express or implied warranty. - -Created: Thu Sep 26 17:14:05 1991 ylo -Last modified: Mon Nov 4 17:06:48 1991 ylo -Ported to Think C: 19 Jan 1992 guido@cwi.nl - -This code draws many ideas from the regular expression packages by -Henry Spencer of the University of Toronto and Richard Stallman of the -Free Software Foundation. - -Emacs-specific code and syntax table code is almost directly borrowed -from GNU regexp. - -*/ - -#include "myproto.h" /* For PROTO macro --Guido */ - -#include <stdio.h> -#include <assert.h> -#include "regexpr.h" - -#ifdef THINK_C -/* Think C on the Mac really needs these headers... --Guido */ -#include <stdlib.h> -#include <string.h> -#else -#if defined(__STDC__) || defined(_MSC_VER) -/* Don't mess around, use the standard headers */ -#include <stdlib.h> -#include <string.h> -#else -char *malloc(); -void free(); -char *realloc(); -#endif /* __STDC__ */ -#endif /* THINK_C */ - -#define MACRO_BEGIN do { -#define MACRO_END } while (0) - -enum regexp_compiled_ops /* opcodes for compiled regexp */ -{ - Cend, /* end of pattern reached */ - Cbol, /* beginning of line */ - Ceol, /* end of line */ - Cset, /* character set. Followed by 32 bytes of set. */ - Cexact, /* followed by a byte to match */ - Canychar, /* matches any character except newline */ - Cstart_memory, /* set register start addr (followed by reg number) */ - Cend_memory, /* set register end addr (followed by reg number) */ - Cmatch_memory, /* match a duplicate of reg contents (regnum follows)*/ - Cjump, /* followed by two bytes (lsb,msb) of displacement. */ - Cstar_jump, /* will change to jump/update_failure_jump at runtime */ - Cfailure_jump, /* jump to addr on failure */ - Cupdate_failure_jump, /* update topmost failure point and jump */ - Cdummy_failure_jump, /* push a dummy failure point and jump */ - Cbegbuf, /* match at beginning of buffer */ - Cendbuf, /* match at end of buffer */ - Cwordbeg, /* match at beginning of word */ - Cwordend, /* match at end of word */ - Cwordbound, /* match if at word boundary */ - Cnotwordbound, /* match if not at word boundary */ -#ifdef emacs - Cemacs_at_dot, /* emacs only: matches at dot */ -#endif /* emacs */ - Csyntaxspec, /* matches syntax code (1 byte follows) */ - Cnotsyntaxspec /* matches if syntax code does not match (1 byte foll)*/ -}; - -enum regexp_syntax_op /* syntax codes for plain and quoted characters */ -{ - Rend, /* special code for end of regexp */ - Rnormal, /* normal character */ - Ranychar, /* any character except newline */ - Rquote, /* the quote character */ - Rbol, /* match beginning of line */ - Reol, /* match end of line */ - Roptional, /* match preceding expression optionally */ - Rstar, /* match preceding expr zero or more times */ - Rplus, /* match preceding expr one or more times */ - Ror, /* match either of alternatives */ - Ropenpar, /* opening parenthesis */ - Rclosepar, /* closing parenthesis */ - Rmemory, /* match memory register */ - Rextended_memory, /* \vnn to match registers 10-99 */ - Ropenset, /* open set. Internal syntax hard-coded below. */ - /* the following are gnu extensions to "normal" regexp syntax */ - Rbegbuf, /* beginning of buffer */ - Rendbuf, /* end of buffer */ - Rwordchar, /* word character */ - Rnotwordchar, /* not word character */ - Rwordbeg, /* beginning of word */ - Rwordend, /* end of word */ - Rwordbound, /* word bound */ - Rnotwordbound, /* not word bound */ -#ifdef emacs - Remacs_at_dot, /* emacs: at dot */ - Remacs_syntaxspec, /* syntaxspec */ - Remacs_notsyntaxspec, /* notsyntaxspec */ -#endif /* emacs */ - Rnum_ops -}; - -static int re_compile_initialized = 0; -static int regexp_syntax = 0; -int re_syntax = 0; /* Exported copy of regexp_syntax */ -static unsigned char regexp_plain_ops[256]; -static unsigned char regexp_quoted_ops[256]; -static unsigned char regexp_precedences[Rnum_ops]; -static int regexp_context_indep_ops; -static int regexp_ansi_sequences; - -#define NUM_LEVELS 5 /* number of precedence levels in use */ -#define MAX_NESTING 100 /* max nesting level of operators */ - -#ifdef emacs - -/* This code is for emacs compatibility only. */ - -#include "config.h" -#include "lisp.h" -#include "buffer.h" -#include "syntax.h" - -/* emacs defines NULL in some strange way? */ -#undef NULL -#define NULL 0 - -#else /* emacs */ - -#define SYNTAX(ch) re_syntax_table[(unsigned char)(ch)] -#define Sword 1 - -#ifdef SYNTAX_TABLE -char *re_syntax_table; -#else -static char re_syntax_table[256]; -#endif /* SYNTAX_TABLE */ - -#endif /* emacs */ - -static void re_compile_initialize PROTO((void)); -static void re_compile_initialize() -{ - int a; - -#if !defined(emacs) && !defined(SYNTAX_TABLE) - static int syntax_table_inited = 0; - - if (!syntax_table_inited) - { - syntax_table_inited = 1; - memset(re_syntax_table, 0, 256); - for (a = 'a'; a <= 'z'; a++) - re_syntax_table[a] = Sword; - for (a = 'A'; a <= 'Z'; a++) - re_syntax_table[a] = Sword; - for (a = '0'; a <= '9'; a++) - re_syntax_table[a] = Sword; - } -#endif /* !emacs && !SYNTAX_TABLE */ - re_compile_initialized = 1; - for (a = 0; a < 256; a++) - { - regexp_plain_ops[a] = Rnormal; - regexp_quoted_ops[a] = Rnormal; - } - for (a = '0'; a <= '9'; a++) - regexp_quoted_ops[a] = Rmemory; - regexp_plain_ops['\134'] = Rquote; - if (regexp_syntax & RE_NO_BK_PARENS) - { - regexp_plain_ops['('] = Ropenpar; - regexp_plain_ops[')'] = Rclosepar; - } - else - { - regexp_quoted_ops['('] = Ropenpar; - regexp_quoted_ops[')'] = Rclosepar; - } - if (regexp_syntax & RE_NO_BK_VBAR) - regexp_plain_ops['\174'] = Ror; - else - regexp_quoted_ops['\174'] = Ror; - regexp_plain_ops['*'] = Rstar; - if (regexp_syntax & RE_BK_PLUS_QM) - { - regexp_quoted_ops['+'] = Rplus; - regexp_quoted_ops['?'] = Roptional; - } - else - { - regexp_plain_ops['+'] = Rplus; - regexp_plain_ops['?'] = Roptional; - } - if (regexp_syntax & RE_NEWLINE_OR) - regexp_plain_ops['\n'] = Ror; - regexp_plain_ops['\133'] = Ropenset; - regexp_plain_ops['\136'] = Rbol; - regexp_plain_ops['$'] = Reol; - regexp_plain_ops['.'] = Ranychar; - if (!(regexp_syntax & RE_NO_GNU_EXTENSIONS)) - { -#ifdef emacs - regexp_quoted_ops['='] = Remacs_at_dot; - regexp_quoted_ops['s'] = Remacs_syntaxspec; - regexp_quoted_ops['S'] = Remacs_notsyntaxspec; -#endif /* emacs */ - regexp_quoted_ops['w'] = Rwordchar; - regexp_quoted_ops['W'] = Rnotwordchar; - regexp_quoted_ops['<'] = Rwordbeg; - regexp_quoted_ops['>'] = Rwordend; - regexp_quoted_ops['b'] = Rwordbound; - regexp_quoted_ops['B'] = Rnotwordbound; - regexp_quoted_ops['`'] = Rbegbuf; - regexp_quoted_ops['\''] = Rendbuf; - } - if (regexp_syntax & RE_ANSI_HEX) - regexp_quoted_ops['v'] = Rextended_memory; - for (a = 0; a < Rnum_ops; a++) - regexp_precedences[a] = 4; - if (regexp_syntax & RE_TIGHT_VBAR) - { - regexp_precedences[Ror] = 3; - regexp_precedences[Rbol] = 2; - regexp_precedences[Reol] = 2; - } - else - { - regexp_precedences[Ror] = 2; - regexp_precedences[Rbol] = 3; - regexp_precedences[Reol] = 3; - } - regexp_precedences[Rclosepar] = 1; - regexp_precedences[Rend] = 0; - regexp_context_indep_ops = (regexp_syntax & RE_CONTEXT_INDEP_OPS) != 0; - regexp_ansi_sequences = (regexp_syntax & RE_ANSI_HEX) != 0; -} - -int re_set_syntax(syntax) -int syntax; -{ - int ret; - - ret = regexp_syntax; - regexp_syntax = syntax; - re_syntax = syntax; /* Exported copy */ - re_compile_initialize(); - return ret; -} - -static int hex_char_to_decimal PROTO((int)); -static int hex_char_to_decimal(ch) -int ch; -{ - if (ch >= '0' && ch <= '9') - return ch - '0'; - if (ch >= 'a' && ch <= 'f') - return ch - 'a' + 10; - if (ch >= 'A' && ch <= 'F') - return ch - 'A' + 10; - return 16; -} - -char *re_compile_pattern(regex, size, bufp) -char *regex; -int size; -regexp_t bufp; -{ - int a, pos, op, current_level, level, opcode; - int pattern_offset, alloc; - int starts[NUM_LEVELS * MAX_NESTING], starts_base; - int future_jumps[MAX_NESTING], num_jumps; - unsigned char ch; - char *pattern, *translate; - int next_register, paren_depth, num_open_registers, open_registers[RE_NREGS]; - int beginning_context; - -#define NEXTCHAR(var) \ - MACRO_BEGIN \ - if (pos >= size) \ - goto ends_prematurely; \ - (var) = regex[pos]; \ - pos++; \ - MACRO_END - -#define ALLOC(amount) \ - MACRO_BEGIN \ - if (pattern_offset+(amount) > alloc) \ - { \ - alloc += 256 + (amount); \ - pattern = realloc(pattern, alloc); \ - if (!pattern) \ - goto out_of_memory; \ - } \ - MACRO_END - -#define STORE(ch) pattern[pattern_offset++] = (ch) - -#define CURRENT_LEVEL_START (starts[starts_base + current_level]) - -#define SET_LEVEL_START starts[starts_base + current_level] = pattern_offset - -#define PUSH_LEVEL_STARTS if (starts_base < (MAX_NESTING-1)*NUM_LEVELS) \ - starts_base += NUM_LEVELS; \ - else \ - goto too_complex - -#define POP_LEVEL_STARTS starts_base -= NUM_LEVELS - -#define PUT_ADDR(offset,addr) \ - MACRO_BEGIN \ - int disp = (addr) - (offset) - 2; \ - pattern[(offset)] = disp & 0xff; \ - pattern[(offset)+1] = (disp>>8) & 0xff; \ - MACRO_END - -#define INSERT_JUMP(pos,type,addr) \ - MACRO_BEGIN \ - int a, p = (pos), t = (type), ad = (addr); \ - for (a = pattern_offset - 1; a >= p; a--) \ - pattern[a + 3] = pattern[a]; \ - pattern[p] = t; \ - PUT_ADDR(p+1,ad); \ - pattern_offset += 3; \ - MACRO_END - -#define SETBIT(buf,offset,bit) (buf)[(offset)+(bit)/8] |= (1<<((bit) & 7)) - -#define SET_FIELDS \ - MACRO_BEGIN \ - bufp->allocated = alloc; \ - bufp->buffer = pattern; \ - bufp->used = pattern_offset; \ - MACRO_END - -#define GETHEX(var) \ - MACRO_BEGIN \ - char gethex_ch, gethex_value; \ - NEXTCHAR(gethex_ch); \ - gethex_value = hex_char_to_decimal(gethex_ch); \ - if (gethex_value == 16) \ - goto hex_error; \ - NEXTCHAR(gethex_ch); \ - gethex_ch = hex_char_to_decimal(gethex_ch); \ - if (gethex_ch == 16) \ - goto hex_error; \ - (var) = gethex_value * 16 + gethex_ch; \ - MACRO_END - -#define ANSI_TRANSLATE(ch) \ - MACRO_BEGIN \ - switch (ch) \ - { \ - case 'a': \ - case 'A': \ - ch = 7; /* audible bell */ \ - break; \ - case 'b': \ - case 'B': \ - ch = 8; /* backspace */ \ - break; \ - case 'f': \ - case 'F': \ - ch = 12; /* form feed */ \ - break; \ - case 'n': \ - case 'N': \ - ch = 10; /* line feed */ \ - break; \ - case 'r': \ - case 'R': \ - ch = 13; /* carriage return */ \ - break; \ - case 't': \ - case 'T': \ - ch = 9; /* tab */ \ - break; \ - case 'v': \ - case 'V': \ - ch = 11; /* vertical tab */ \ - break; \ - case 'x': /* hex code */ \ - case 'X': \ - GETHEX(ch); \ - break; \ - default: \ - /* other characters passed through */ \ - if (translate) \ - ch = translate[(unsigned char)ch]; \ - break; \ - } \ - MACRO_END - - if (!re_compile_initialized) - re_compile_initialize(); - bufp->used = 0; - bufp->fastmap_accurate = 0; - bufp->uses_registers = 0; - translate = bufp->translate; - pattern = bufp->buffer; - alloc = bufp->allocated; - if (alloc == 0 || pattern == NULL) - { - alloc = 256; - pattern = malloc(alloc); - if (!pattern) - goto out_of_memory; - } - pattern_offset = 0; - starts_base = 0; - num_jumps = 0; - current_level = 0; - SET_LEVEL_START; - num_open_registers = 0; - next_register = 1; - paren_depth = 0; - beginning_context = 1; - op = -1; - /* we use Rend dummy to ensure that pending jumps are updated (due to - low priority of Rend) before exiting the loop. */ - pos = 0; - while (op != Rend) - { - if (pos >= size) - op = Rend; - else - { - NEXTCHAR(ch); - if (translate) - ch = translate[(unsigned char)ch]; - op = regexp_plain_ops[(unsigned char)ch]; - if (op == Rquote) - { - NEXTCHAR(ch); - op = regexp_quoted_ops[(unsigned char)ch]; - if (op == Rnormal && regexp_ansi_sequences) - ANSI_TRANSLATE(ch); - } - } - level = regexp_precedences[op]; - /* printf("ch='%c' op=%d level=%d current_level=%d curlevstart=%d\n", - ch, op, level, current_level, CURRENT_LEVEL_START); */ - if (level > current_level) - { - for (current_level++; current_level < level; current_level++) - SET_LEVEL_START; - SET_LEVEL_START; - } - else - if (level < current_level) - { - current_level = level; - for (;num_jumps > 0 && - future_jumps[num_jumps-1] >= CURRENT_LEVEL_START; - num_jumps--) - PUT_ADDR(future_jumps[num_jumps-1], pattern_offset); - } - switch (op) - { - case Rend: - break; - case Rnormal: - normal_char: - opcode = Cexact; - store_opcode_and_arg: /* opcode & ch must be set */ - SET_LEVEL_START; - ALLOC(2); - STORE(opcode); - STORE(ch); - break; - case Ranychar: - opcode = Canychar; - store_opcode: - SET_LEVEL_START; - ALLOC(1); - STORE(opcode); - break; - case Rquote: - abort(); - /*NOTREACHED*/ - case Rbol: - if (!beginning_context) - if (regexp_context_indep_ops) - goto op_error; - else - goto normal_char; - opcode = Cbol; - goto store_opcode; - case Reol: - if (!((pos >= size) || - ((regexp_syntax & RE_NO_BK_VBAR) ? - (regex[pos] == '\174') : - (pos+1 < size && regex[pos] == '\134' && - regex[pos+1] == '\174')) || - ((regexp_syntax & RE_NO_BK_PARENS)? - (regex[pos] == ')'): - (pos+1 < size && regex[pos] == '\134' && - regex[pos+1] == ')')))) - if (regexp_context_indep_ops) - goto op_error; - else - goto normal_char; - opcode = Ceol; - goto store_opcode; - /* NOTREACHED */ - break; - case Roptional: - if (beginning_context) - if (regexp_context_indep_ops) - goto op_error; - else - goto normal_char; - if (CURRENT_LEVEL_START == pattern_offset) - break; /* ignore empty patterns for ? */ - ALLOC(3); - INSERT_JUMP(CURRENT_LEVEL_START, Cfailure_jump, - pattern_offset + 3); - break; - case Rstar: - case Rplus: - if (beginning_context) - if (regexp_context_indep_ops) - goto op_error; - else - goto normal_char; - if (CURRENT_LEVEL_START == pattern_offset) - break; /* ignore empty patterns for + and * */ - ALLOC(9); - INSERT_JUMP(CURRENT_LEVEL_START, Cfailure_jump, - pattern_offset + 6); - INSERT_JUMP(pattern_offset, Cstar_jump, CURRENT_LEVEL_START); - if (op == Rplus) /* jump over initial failure_jump */ - INSERT_JUMP(CURRENT_LEVEL_START, Cdummy_failure_jump, - CURRENT_LEVEL_START + 6); - break; - case Ror: - ALLOC(6); - INSERT_JUMP(CURRENT_LEVEL_START, Cfailure_jump, - pattern_offset + 6); - if (num_jumps >= MAX_NESTING) - goto too_complex; - STORE(Cjump); - future_jumps[num_jumps++] = pattern_offset; - STORE(0); - STORE(0); - SET_LEVEL_START; - break; - case Ropenpar: - SET_LEVEL_START; - if (next_register < RE_NREGS) - { - bufp->uses_registers = 1; - ALLOC(2); - STORE(Cstart_memory); - STORE(next_register); - open_registers[num_open_registers++] = next_register; - next_register++; - } - paren_depth++; - PUSH_LEVEL_STARTS; - current_level = 0; - SET_LEVEL_START; - break; - case Rclosepar: - if (paren_depth <= 0) - goto parenthesis_error; - POP_LEVEL_STARTS; - current_level = regexp_precedences[Ropenpar]; - paren_depth--; - if (paren_depth < num_open_registers) - { - bufp->uses_registers = 1; - ALLOC(2); - STORE(Cend_memory); - num_open_registers--; - STORE(open_registers[num_open_registers]); - } - break; - case Rmemory: - if (ch == '0') - goto bad_match_register; - assert(ch >= '0' && ch <= '9'); - bufp->uses_registers = 1; - opcode = Cmatch_memory; - ch -= '0'; - goto store_opcode_and_arg; - case Rextended_memory: - NEXTCHAR(ch); - if (ch < '0' || ch > '9') - goto bad_match_register; - NEXTCHAR(a); - if (a < '0' || a > '9') - goto bad_match_register; - ch = 10 * (a - '0') + ch - '0'; - if (ch <= 0 || ch >= RE_NREGS) - goto bad_match_register; - bufp->uses_registers = 1; - opcode = Cmatch_memory; - goto store_opcode_and_arg; - case Ropenset: - { - int complement,prev,offset,range,firstchar; - - SET_LEVEL_START; - ALLOC(1+256/8); - STORE(Cset); - offset = pattern_offset; - for (a = 0; a < 256/8; a++) - STORE(0); - NEXTCHAR(ch); - if (translate) - ch = translate[(unsigned char)ch]; - if (ch == '\136') - { - complement = 1; - NEXTCHAR(ch); - if (translate) - ch = translate[(unsigned char)ch]; - } - else - complement = 0; - prev = -1; - range = 0; - firstchar = 1; - while (ch != '\135' || firstchar) - { - firstchar = 0; - if (regexp_ansi_sequences && ch == '\134') - { - NEXTCHAR(ch); - ANSI_TRANSLATE(ch); - } - if (range) - { - for (a = prev; a <= (int)ch; a++) - SETBIT(pattern, offset, a); - prev = -1; - range = 0; - } - else - if (prev != -1 && ch == '-') - range = 1; - else - { - SETBIT(pattern, offset, ch); - prev = ch; - } - NEXTCHAR(ch); - if (translate) - ch = translate[(unsigned char)ch]; - } - if (range) - SETBIT(pattern, offset, '-'); - if (complement) - { - for (a = 0; a < 256/8; a++) - pattern[offset+a] ^= 0xff; - } - break; - } - case Rbegbuf: - opcode = Cbegbuf; - goto store_opcode; - case Rendbuf: - opcode = Cendbuf; - goto store_opcode; - case Rwordchar: - opcode = Csyntaxspec; - ch = Sword; - goto store_opcode_and_arg; - case Rnotwordchar: - opcode = Cnotsyntaxspec; - ch = Sword; - goto store_opcode_and_arg; - case Rwordbeg: - opcode = Cwordbeg; - goto store_opcode; - case Rwordend: - opcode = Cwordend; - goto store_opcode; - case Rwordbound: - opcode = Cwordbound; - goto store_opcode; - case Rnotwordbound: - opcode = Cnotwordbound; - goto store_opcode; -#ifdef emacs - case Remacs_at_dot: - opcode = Cemacs_at_dot; - goto store_opcode; - case Remacs_syntaxspec: - NEXTCHAR(ch); - if (translate) - ch = translate[(unsigned char)ch]; - opcode = Csyntaxspec; - ch = syntax_spec_code[(unsigned char)ch]; - goto store_opcode_and_arg; - case Remacs_notsyntaxspec: - NEXTCHAR(ch); - if (translate) - ch = translate[(unsigned char)ch]; - opcode = Cnotsyntaxspec; - ch = syntax_spec_code[(unsigned char)ch]; - goto store_opcode_and_arg; -#endif /* emacs */ - default: - abort(); - } - beginning_context = (op == Ropenpar || op == Ror); - } - if (starts_base != 0) - goto parenthesis_error; - assert(num_jumps == 0); - ALLOC(1); - STORE(Cend); - SET_FIELDS; - return NULL; - - op_error: - SET_FIELDS; - return "Badly placed special character"; - - bad_match_register: - SET_FIELDS; - return "Bad match register number"; - - hex_error: - SET_FIELDS; - return "Bad hexadecimal number"; - - parenthesis_error: - SET_FIELDS; - return "Badly placed parenthesis"; - - out_of_memory: - SET_FIELDS; - return "Out of memory"; - - ends_prematurely: - SET_FIELDS; - return "Regular expression ends prematurely"; - - too_complex: - SET_FIELDS; - return "Regular expression too complex"; -} -#undef CHARAT -#undef NEXTCHAR -#undef GETHEX -#undef ALLOC -#undef STORE -#undef CURRENT_LEVEL_START -#undef SET_LEVEL_START -#undef PUSH_LEVEL_STARTS -#undef POP_LEVEL_STARTS -#undef PUT_ADDR -#undef INSERT_JUMP -#undef SETBIT -#undef SET_FIELDS - -static void re_compile_fastmap_aux - PROTO((char *, int, char *, char *, char *)); -static void re_compile_fastmap_aux(code, pos, visited, can_be_null, fastmap) -char *code, *visited, *can_be_null, *fastmap; -int pos; -{ - int a, b, syntaxcode; - - if (visited[pos]) - return; /* we have already been here */ - visited[pos] = 1; - for (;;) - switch (code[pos++]) - { - case Cend: - *can_be_null = 1; - return; - case Cbol: - case Cbegbuf: - case Cendbuf: - case Cwordbeg: - case Cwordend: - case Cwordbound: - case Cnotwordbound: -#ifdef emacs - case Cemacs_at_dot: -#endif /* emacs */ - break; - case Csyntaxspec: - syntaxcode = code[pos++]; - for (a = 0; a < 256; a++) - if (SYNTAX(a) == syntaxcode) - fastmap[a] = 1; - return; - case Cnotsyntaxspec: - syntaxcode = code[pos++]; - for (a = 0; a < 256; a++) - if (SYNTAX(a) != syntaxcode) - fastmap[a] = 1; - return; - case Ceol: - fastmap['\n'] = 1; - if (*can_be_null == 0) - *can_be_null = 2; /* can match null, but only at end of buffer*/ - return; - case Cset: - for (a = 0; a < 256/8; a++) - if (code[pos + a] != 0) - for (b = 0; b < 8; b++) - if (code[pos + a] & (1 << b)) - fastmap[(a << 3) + b] = 1; - pos += 256/8; - return; - case Cexact: - fastmap[(unsigned char)code[pos]] = 1; - return; - case Canychar: - for (a = 0; a < 256; a++) - if (a != '\n') - fastmap[a] = 1; - return; - case Cstart_memory: - case Cend_memory: - pos++; - break; - case Cmatch_memory: - /* should this ever happen for sensible patterns??? */ - *can_be_null = 1; - return; - case Cjump: - case Cdummy_failure_jump: - case Cupdate_failure_jump: - case Cstar_jump: - a = (unsigned char)code[pos++]; - a |= (unsigned char)code[pos++] << 8; - pos += (int)(short)a; - if (visited[pos]) - { - /* argh... the regexp contains empty loops. This is not - good, as this may cause a failure stack overflow when - matching. Oh well. */ - /* this path leads nowhere; pursue other paths. */ - return; - } - visited[pos] = 1; - break; - case Cfailure_jump: - a = (unsigned char)code[pos++]; - a |= (unsigned char)code[pos++] << 8; - a = pos + (int)(short)a; - re_compile_fastmap_aux(code, a, visited, can_be_null, fastmap); - break; - default: - abort(); /* probably some opcode is missing from this switch */ - /*NOTREACHED*/ - } -} - -static int re_do_compile_fastmap PROTO((char *, int, int, char *, char *)); -static int re_do_compile_fastmap(buffer, used, pos, can_be_null, fastmap) -char *buffer, *fastmap, *can_be_null; -int used, pos; -{ - char small_visited[512], *visited; - - if (used <= sizeof(small_visited)) - visited = small_visited; - else - { - visited = malloc(used); - if (!visited) - return 0; - } - *can_be_null = 0; - memset(fastmap, 0, 256); - memset(visited, 0, used); - re_compile_fastmap_aux(buffer, pos, visited, can_be_null, fastmap); - if (visited != small_visited) - free(visited); - return 1; -} - -void re_compile_fastmap(bufp) -regexp_t bufp; -{ - if (!bufp->fastmap || bufp->fastmap_accurate) - return; - assert(bufp->used > 0); - if (!re_do_compile_fastmap(bufp->buffer, bufp->used, 0, &bufp->can_be_null, - bufp->fastmap)) - return; - if (bufp->buffer[0] == Cbol) - bufp->anchor = 1; /* begline */ - else - if (bufp->buffer[0] == Cbegbuf) - bufp->anchor = 2; /* begbuf */ - else - bufp->anchor = 0; /* none */ - bufp->fastmap_accurate = 1; -} - -#define INITIAL_FAILURES 128 /* initial # failure points to allocate */ -#define MAX_FAILURES 4100L /* max # of failure points before failing */ - -int re_match_2(bufp, string1, size1, string2, size2, pos, regs, mstop) -regexp_t bufp; -char *string1, *string2; -int size1, size2, pos, mstop; -regexp_registers_t regs; -{ - struct failure_point { char *text, *partend, *code; } - *failure_stack_start, *failure_sp, *failure_stack_end, - initial_failure_stack[INITIAL_FAILURES]; - char *code, *translate, *text, *textend, *partend, *part_2_end; - char *regstart_text[RE_NREGS], *regstart_partend[RE_NREGS]; - char *regend_text[RE_NREGS], *regend_partend[RE_NREGS]; - int a, b, ch, reg, regch, match_end; - char *regtext, *regpartend, *regtextend; - -#define PREFETCH \ - MACRO_BEGIN \ - if (text == partend) \ - { \ - if (text == textend) \ - goto fail; \ - text = string2; \ - partend = part_2_end; \ - } \ - MACRO_END - -#define NEXTCHAR(var) \ - MACRO_BEGIN \ - PREFETCH; \ - (var) = (unsigned char)*text++; \ - if (translate) \ - (var) = (unsigned char)translate[(var)]; \ - MACRO_END - - assert(pos >= 0 && size1 >= 0 && size2 >= 0 && mstop >= 0); - assert(mstop <= size1 + size2); - assert(pos <= mstop); - - if (pos <= size1) - { - text = string1 + pos; - if (mstop <= size1) - { - partend = string1 + mstop; - textend = partend; - } - else - { - partend = string1 + size1; - textend = string2 + mstop - size1; - } - part_2_end = string2 + mstop - size1; - } - else - { - text = string2 + pos - size1; - partend = string2 + mstop - size1; - textend = partend; - part_2_end = partend; - } - - if (bufp->uses_registers && regs != NULL) - for (a = 0; a < RE_NREGS; a++) - regend_text[a] = NULL; - - code = bufp->buffer; - translate = bufp->translate; - failure_stack_start = failure_sp = initial_failure_stack; - failure_stack_end = initial_failure_stack + INITIAL_FAILURES; - -#if 0 - /* re_search_2 has already done this, and otherwise we get little benefit - from this. So I'll leave this out. */ - if (bufp->fastmap_accurate && !bufp->can_be_null && - text != textend && - !bufp->fastmap[translate ? - (unsigned char)translate[(unsigned char)*text] : - (unsigned char)*text]) - return -1; /* it can't possibly match */ -#endif - - continue_matching: - for (;;) - { - switch (*code++) - { - case Cend: - if (partend != part_2_end) - match_end = text - string1; - else - match_end = text - string2 + size1; - if (regs) - { - regs->start[0] = pos; - regs->end[0] = match_end; - if (!bufp->uses_registers) - { - for (a = 1; a < RE_NREGS; a++) - { - regs->start[a] = -1; - regs->end[a] = -1; - } - } - else - { - for (a = 1; a < RE_NREGS; a++) - { - if (regend_text[a] == NULL) - { - regs->start[a] = -1; - regs->end[a] = -1; - continue; - } - if (regstart_partend[a] != part_2_end) - regs->start[a] = regstart_text[a] - string1; - else - regs->start[a] = regstart_text[a] - string2 + size1; - if (regend_partend[a] != part_2_end) - regs->end[a] = regend_text[a] - string1; - else - regs->end[a] = regend_text[a] - string2 + size1; - } - } - } - if (failure_stack_start != initial_failure_stack) - free((char *)failure_stack_start); - return match_end - pos; - case Cbol: - if (text == string1 || text[-1] == '\n') /* text[-1] always valid */ - break; - goto fail; - case Ceol: - if (text == string2 + size2 || - (text == string1 + size1 ? - (size2 == 0 || *string2 == '\n') : - *text == '\n')) - break; - goto fail; - case Cset: - NEXTCHAR(ch); - if (code[ch/8] & (1<<(ch & 7))) - { - code += 256/8; - break; - } - goto fail; - case Cexact: - NEXTCHAR(ch); - if (ch != (unsigned char)*code++) - goto fail; - break; - case Canychar: - NEXTCHAR(ch); - if (ch == '\n') - goto fail; - break; - case Cstart_memory: - reg = *code++; - regstart_text[reg] = text; - regstart_partend[reg] = partend; - break; - case Cend_memory: - reg = *code++; - regend_text[reg] = text; - regend_partend[reg] = partend; - break; - case Cmatch_memory: - reg = *code++; - if (regend_text[reg] == NULL) - goto fail; /* or should we just match nothing? */ - regtext = regstart_text[reg]; - regtextend = regend_text[reg]; - if (regstart_partend[reg] == regend_partend[reg]) - regpartend = regtextend; - else - regpartend = string1 + size1; - - for (;regtext != regtextend;) - { - NEXTCHAR(ch); - if (regtext == regpartend) - regtext = string2; - regch = (unsigned char)*regtext++; - if (translate) - regch = (unsigned char)translate[regch]; - if (regch != ch) - goto fail; - } - break; - case Cstar_jump: - /* star is coded as: - 1: failure_jump 2 - ... code for operand of star - star_jump 1 - 2: ... code after star - We change the star_jump to update_failure_jump if we can determine - that it is safe to do so; otherwise we change it to an ordinary - jump. - plus is coded as - jump 2 - 1: failure_jump 3 - 2: ... code for operand of plus - star_jump 1 - 3: ... code after plus - For star_jump considerations this is processed identically - to star. */ - a = (unsigned char)*code++; - a |= (unsigned char)*code++ << 8; - a = (int)(short)a; - { - char map[256], can_be_null; - char *p1, *p2; - - p1 = code + a + 3; /* skip the failure_jump */ - assert(p1[-3] == Cfailure_jump); - p2 = code; - /* p1 points inside loop, p2 points to after loop */ - if (!re_do_compile_fastmap(bufp->buffer, bufp->used, - p2 - bufp->buffer, &can_be_null, map)) - goto make_normal_jump; - /* If we might introduce a new update point inside the loop, - we can't optimize because then update_jump would update a - wrong failure point. Thus we have to be quite careful here. */ - loop_p1: - /* loop until we find something that consumes a character */ - switch (*p1++) - { - case Cbol: - case Ceol: - case Cbegbuf: - case Cendbuf: - case Cwordbeg: - case Cwordend: - case Cwordbound: - case Cnotwordbound: -#ifdef emacs - case Cemacs_at_dot: -#endif /* emacs */ - goto loop_p1; - case Cstart_memory: - case Cend_memory: - p1++; - goto loop_p1; - case Cexact: - ch = (unsigned char)*p1++; - if (map[ch]) - goto make_normal_jump; - break; - case Canychar: - for (b = 0; b < 256; b++) - if (b != '\n' && map[b]) - goto make_normal_jump; - break; - case Cset: - for (b = 0; b < 256; b++) - if ((p1[b >> 3] & (1 << (b & 7))) && map[b]) - goto make_normal_jump; - p1 += 256/8; - break; - default: - goto make_normal_jump; - } - /* now we know that we can't backtrack. */ - while (p1 != p2 - 3) - { - switch (*p1++) - { - case Cend: - abort(); /* we certainly shouldn't get this inside loop */ - /*NOTREACHED*/ - case Cbol: - case Ceol: - case Canychar: - case Cbegbuf: - case Cendbuf: - case Cwordbeg: - case Cwordend: - case Cwordbound: - case Cnotwordbound: -#ifdef emacs - case Cemacs_at_dot: -#endif /* emacs */ - break; - case Cset: - p1 += 256/8; - break; - case Cexact: - case Cstart_memory: - case Cend_memory: - case Cmatch_memory: - case Csyntaxspec: - case Cnotsyntaxspec: - p1++; - break; - case Cjump: - case Cstar_jump: - case Cfailure_jump: - case Cupdate_failure_jump: - case Cdummy_failure_jump: - goto make_normal_jump; - default: - printf("regexpr.c: processing star_jump: unknown op %d\n", p1[-1]); - break; - } - } - goto make_update_jump; - } - make_normal_jump: - /* printf("changing to normal jump\n"); */ - code -= 3; - *code = Cjump; - break; - make_update_jump: - /* printf("changing to update jump\n"); */ - code -= 2; - a += 3; /* jump to after the Cfailure_jump */ - code[-1] = Cupdate_failure_jump; - code[0] = a & 0xff; - code[1] = a >> 8; - /* fall to next case */ - case Cupdate_failure_jump: - failure_sp[-1].text = text; - failure_sp[-1].partend = partend; - /* fall to next case */ - case Cjump: - a = (unsigned char)*code++; - a |= (unsigned char)*code++ << 8; - code += (int)(short)a; - break; - case Cdummy_failure_jump: - case Cfailure_jump: - if (failure_sp == failure_stack_end) - { - if (failure_stack_start != initial_failure_stack) - goto error; - failure_stack_start = (struct failure_point *) - malloc(MAX_FAILURES * sizeof(*failure_stack_start)); - if (failure_stack_start == NULL) - { - failure_stack_start = initial_failure_stack; - goto error; - } - failure_stack_end = failure_stack_start + MAX_FAILURES; - memcpy((char *)failure_stack_start, (char *)initial_failure_stack, - INITIAL_FAILURES * sizeof(*failure_stack_start)); - failure_sp = failure_stack_start + INITIAL_FAILURES; - } - a = (unsigned char)*code++; - a |= (unsigned char)*code++ << 8; - a = (int)(short)a; - if (code[-3] == Cdummy_failure_jump) - { /* this is only used in plus */ - assert(*code == Cfailure_jump); - b = (unsigned char)code[1]; - b |= (unsigned char)code[2] << 8; - failure_sp->code = code + (int)(short)b + 3; - failure_sp->text = NULL; - code += a; - } - else - { - failure_sp->code = code + a; - failure_sp->text = text; - failure_sp->partend = partend; - } - failure_sp++; - break; - case Cbegbuf: - if (text == string1) - break; - goto fail; - case Cendbuf: - if (size2 == 0 ? text == string1 + size1 : text == string2 + size2) - break; - goto fail; - case Cwordbeg: - if (text == string2 + size2) - goto fail; - if (size2 == 0 && text == string1 + size1) - goto fail; - if (SYNTAX(text == string1 + size1 ? *string1 : *text) != Sword) - goto fail; - if (text == string1) - break; - if (SYNTAX(text[-1]) != Sword) - break; - goto fail; - case Cwordend: - if (text == string1) - goto fail; - if (SYNTAX(text[-1]) != Sword) - goto fail; - if (text == string2 + size2) - break; - if (size2 == 0 && text == string1 + size1) - break; - if (SYNTAX(*text) == Sword) - goto fail; - break; - case Cwordbound: - /* Note: as in gnu regexp, this also matches at the beginning - and end of buffer. */ - if (text == string1 || text == string2 + size2 || - (size2 == 0 && text == string1 + size1)) - break; - if ((SYNTAX(text[-1]) == Sword) ^ - (SYNTAX(text == string1 + size1 ? *string2 : *text) == Sword)) - break; - goto fail; - case Cnotwordbound: - /* Note: as in gnu regexp, this never matches at the beginning - and end of buffer. */ - if (text == string1 || text == string2 + size2 || - (size2 == 0 && text == string1 + size1)) - goto fail; - if (!((SYNTAX(text[-1]) == Sword) ^ - (SYNTAX(text == string1 + size1 ? *string2 : *text) == Sword))) - goto fail; - break; - case Csyntaxspec: - NEXTCHAR(ch); - if (SYNTAX(ch) != (unsigned char)*code++) - goto fail; - break; - case Cnotsyntaxspec: - NEXTCHAR(ch); - if (SYNTAX(ch) != (unsigned char)*code++) - break; - goto fail; -#ifdef emacs - case Cemacs_at_dot: - if (PTR_CHAR_POS((unsigned char *)text) + 1 != point) - goto fail; - break; -#endif /* emacs */ - default: - abort(); - /*NOTREACHED*/ - } - } -#if 0 /* This line is never reached --Guido */ - abort(); -#endif - /*NOTREACHED*/ - - fail: - if (failure_sp != failure_stack_start) - { - failure_sp--; - text = failure_sp->text; - if (text == NULL) - goto fail; - partend = failure_sp->partend; - code = failure_sp->code; - goto continue_matching; - } - if (failure_stack_start != initial_failure_stack) - free((char *)failure_stack_start); - return -1; - - error: - if (failure_stack_start != initial_failure_stack) - free((char *)failure_stack_start); - return -2; -} - -#undef PREFETCH -#undef NEXTCHAR -#undef PUSH_FAILURE - -int re_match(bufp, string, size, pos, regs) -regexp_t bufp; -char *string; -int size, pos; -regexp_registers_t regs; -{ - return re_match_2(bufp, string, size, (char *)NULL, 0, pos, regs, size); -} - -int re_search_2(bufp, string1, size1, string2, size2, pos, range, regs, - mstop) -regexp_t bufp; -char *string1, *string2; -int size1, size2, pos, range, mstop; -regexp_registers_t regs; -{ - char *fastmap, *translate, *text, *partstart, *partend; - int dir, ret; - char anchor; - - assert(size1 >= 0 && size2 >= 0 && pos >= 0 && mstop >= 0); - assert(pos + range >= 0 && pos + range <= size1 + size2); /* Bugfix by ylo */ - assert(pos <= mstop); - - fastmap = bufp->fastmap; - translate = bufp->translate; - if (fastmap && !bufp->fastmap_accurate) - re_compile_fastmap(bufp); - anchor = bufp->anchor; - if (bufp->can_be_null == 1) /* can_be_null == 2: can match null at eob */ - fastmap = NULL; - if (range < 0) - { - dir = -1; - range = -range; - } - else - dir = 1; - if (anchor == 2) - if (pos != 0) - return -1; - else - range = 0; - for (; range >= 0; range--, pos += dir) - { - if (fastmap) - { - if (dir == 1) - { /* searching forwards */ - if (pos < size1) - { - text = string1 + pos; - if (pos + range > size1) - partend = string1 + size1; - else - partend = string1 + pos + range; - } - else - { - text = string2 + pos - size1; - partend = string2 + pos + range - size1; - } - partstart = text; - if (translate) - while (text != partend && - !fastmap[(unsigned char) - translate[(unsigned char)*text]]) - text++; - else - while (text != partend && !fastmap[(unsigned char)*text]) - text++; - pos += text - partstart; - range -= text - partstart; - if (pos == size1 + size2 && bufp->can_be_null == 0) - return -1; - } - else - { /* searching backwards */ - if (pos <= size1) - { - text = string1 + pos; - partstart = string1 + pos - range; - } - else - { - text = string2 + pos - size1; - if (range < pos - size1) - partstart = string2 + pos - size1 - range; - else - partstart = string2; - } - partend = text; - if (translate) - while (text != partstart && - !fastmap[(unsigned char) - translate[(unsigned char)*text]]) - text--; - else - while (text != partstart && - !fastmap[(unsigned char)*text]) - text--; - pos -= partend - text; - range -= partend - text; - } - } - if (anchor == 1) - { /* anchored to begline */ - if (pos > 0 && - (pos <= size1 ? string1[pos - 1] : - string2[pos - size1 - 1]) != '\n') - continue; - } - assert(pos >= 0 && pos <= size1 + size2); - ret = re_match_2(bufp, string1, size1, string2, size2, pos, regs, mstop); - if (ret >= 0) - return pos; - if (ret == -2) - return -2; - } - return -1; -} - -int re_search(bufp, string, size, startpos, range, regs) -regexp_t bufp; -char *string; -int size, startpos, range; -regexp_registers_t regs; -{ - return re_search_2(bufp, string, size, (char *)NULL, 0, - startpos, range, regs, size); -} - -#ifdef UNUSED - -static struct re_pattern_buffer re_comp_buf; - -char *re_comp(s) -char *s; -{ - if (s == NULL) - { - if (!re_comp_buf.buffer) - return "Out of memory"; - return NULL; - } - if (!re_comp_buf.buffer) - { - /* the buffer will be allocated automatically */ - re_comp_buf.fastmap = malloc(256); - re_comp_buf.translate = NULL; - if (re_comp_buf.fastmap == NULL) - return "Out of memory"; - } - return re_compile_pattern(s, strlen(s), &re_comp_buf); -} - -int re_exec(s) -char *s; -{ - int len = strlen(s); - - return re_search(&re_comp_buf, s, len, 0, len, (regexp_registers_t)NULL) >= 0; -} - -#endif - -#ifdef TEST_REGEXP - -int main() -{ - char buf[500]; - char *cp; - struct re_pattern_buffer exp; - struct re_registers regs; - int a,pos; - char fastmap[256]; - - exp.allocated = 0; - exp.buffer = 0; - exp.translate = NULL; - exp.fastmap = fastmap; - - /* re_set_syntax(RE_NO_BK_PARENS|RE_NO_BK_VBAR|RE_ANSI_HEX); */ - - while (1) - { - printf("Enter regexp:\n"); - gets(buf); - cp=re_compile_pattern(buf, strlen(buf), &exp); - if (cp) - { - printf("Error: %s\n", cp); - continue; - } - re_compile_fastmap(&exp); - printf("dump:\n"); - for (pos = 0; pos < exp.used;) - { - printf("%d: ", pos); - switch (exp.buffer[pos++]) - { - case Cend: - strcpy(buf, "end"); - break; - case Cbol: - strcpy(buf, "bol"); - break; - case Ceol: - strcpy(buf, "eol"); - break; - case Cset: - strcpy(buf, "set "); - for (a = 0; a < 256/8; a++) - sprintf(buf+strlen(buf)," %02x", - (unsigned char)exp.buffer[pos++]); - break; - case Cexact: - sprintf(buf, "exact '%c' 0x%x", exp.buffer[pos], - (unsigned char)exp.buffer[pos]); - pos++; - break; - case Canychar: - strcpy(buf, "anychar"); - break; - case Cstart_memory: - sprintf(buf, "start_memory %d", exp.buffer[pos++]); - break; - case Cend_memory: - sprintf(buf, "end_memory %d", exp.buffer[pos++]); - break; - case Cmatch_memory: - sprintf(buf, "match_memory %d", exp.buffer[pos++]); - break; - case Cjump: - case Cdummy_failure_jump: - case Cstar_jump: - case Cfailure_jump: - case Cupdate_failure_jump: - a = (unsigned char)exp.buffer[pos++]; - a += (unsigned char)exp.buffer[pos++] << 8; - a = (int)(short)a; - switch (exp.buffer[pos-3]) - { - case Cjump: - cp = "jump"; - break; - case Cstar_jump: - cp = "star_jump"; - break; - case Cfailure_jump: - cp = "failure_jump"; - break; - case Cupdate_failure_jump: - cp = "update_failure_jump"; - break; - case Cdummy_failure_jump: - cp = "dummy_failure_jump"; - break; - default: - cp = "unknown jump"; - break; - } - sprintf(buf, "%s %d", cp, a + pos); - break; - case Cbegbuf: - strcpy(buf,"begbuf"); - break; - case Cendbuf: - strcpy(buf,"endbuf"); - break; - case Cwordbeg: - strcpy(buf,"wordbeg"); - break; - case Cwordend: - strcpy(buf,"wordend"); - break; - case Cwordbound: - strcpy(buf,"wordbound"); - break; - case Cnotwordbound: - strcpy(buf,"notwordbound"); - break; - default: - sprintf(buf, "unknown code %d", - (unsigned char)exp.buffer[pos - 1]); - break; - } - printf("%s\n", buf); - } - printf("can_be_null = %d uses_registers = %d anchor = %d\n", - exp.can_be_null, exp.uses_registers, exp.anchor); - - printf("fastmap:"); - for (a = 0; a < 256; a++) - if (exp.fastmap[a]) - printf(" %d", a); - printf("\n"); - printf("Enter strings. An empty line terminates.\n"); - while (fgets(buf, sizeof(buf), stdin)) - { - if (buf[0] == '\n') - break; - a = re_search(&exp, buf, strlen(buf), 0, strlen(buf), &regs); - printf("search returns %d\n", a); - if (a != -1) - { - for (a = 0; a < RE_NREGS; a++) - { - printf("buf %d: %d to %d\n", a, regs.start[a], regs.end[a]); - } - } - } - } -} - -#endif /* TEST_REGEXP */ diff --git a/Modules/regexpr.h b/Modules/regexpr.h deleted file mode 100644 index 0ddb3a184d..0000000000 --- a/Modules/regexpr.h +++ /dev/null @@ -1,165 +0,0 @@ -#ifndef Py_REGEXPR_H -#define Py_REGEXPR_H -#ifdef __cplusplus -extern "C" { -#endif - -/* - -regexpr.h - -Author: Tatu Ylonen <ylo@ngs.fi> - -Copyright (c) 1991 Tatu Ylonen, Espoo, Finland - -Permission to use, copy, modify, distribute, and sell this software -and its documentation for any purpose is hereby granted without fee, -provided that the above copyright notice appear in all copies. This -software is provided "as is" without express or implied warranty. - -Created: Thu Sep 26 17:15:36 1991 ylo -Last modified: Mon Nov 4 15:49:46 1991 ylo - -*/ - -#ifndef REGEXPR_H -#define REGEXPR_H - -#define RE_NREGS 100 /* number of registers available */ - -typedef struct re_pattern_buffer -{ - char *buffer; /* compiled pattern */ - int allocated; /* allocated size of compiled pattern */ - int used; /* actual length of compiled pattern */ - char *fastmap; /* fastmap[ch] is true if ch can start pattern */ - char *translate; /* translation to apply during compilation/matching */ - char fastmap_accurate; /* true if fastmap is valid */ - char can_be_null; /* true if can match empty string */ - char uses_registers; /* registers are used and need to be initialized */ - char anchor; /* anchor: 0=none 1=begline 2=begbuf */ -} *regexp_t; - -typedef struct re_registers -{ - int start[RE_NREGS]; /* start offset of region */ - int end[RE_NREGS]; /* end offset of region */ -} *regexp_registers_t; - -/* bit definitions for syntax */ -#define RE_NO_BK_PARENS 1 /* no quoting for parentheses */ -#define RE_NO_BK_VBAR 2 /* no quoting for vertical bar */ -#define RE_BK_PLUS_QM 4 /* quoting needed for + and ? */ -#define RE_TIGHT_VBAR 8 /* | binds tighter than ^ and $ */ -#define RE_NEWLINE_OR 16 /* treat newline as or */ -#define RE_CONTEXT_INDEP_OPS 32 /* ^$?*+ are special in all contexts */ -#define RE_ANSI_HEX 64 /* ansi sequences (\n etc) and \xhh */ -#define RE_NO_GNU_EXTENSIONS 128 /* no gnu extensions */ - -/* definitions for some common regexp styles */ -#define RE_SYNTAX_AWK (RE_NO_BK_PARENS|RE_NO_BK_VBAR|RE_CONTEXT_INDEP_OPS) -#define RE_SYNTAX_EGREP (RE_SYNTAX_AWK|RE_NEWLINE_OR) -#define RE_SYNTAX_GREP (RE_BK_PLUS_QM|RE_NEWLINE_OR) -#define RE_SYNTAX_EMACS 0 - -/* Rename all exported symbols to avoid conflicts with similarly named - symbols in some systems' standard C libraries... */ - -#define re_syntax _Py_re_syntax -#define re_set_syntax _Py_re_set_syntax -#define re_compile_pattern _Py_re_compile_pattern -#define re_match _Py_re_match -#define re_match_2 _Py_re_match_2 -#define re_search _Py_re_search -#define re_search_2 _Py_re_search_2 -#define re_compile_fastmap _Py_re_compile_fastmap -#define re_comp _Py_re_comp -#define re_exec _Py_re_exec - -#ifdef HAVE_PROTOTYPES - -extern int re_syntax; -/* This is the actual syntax mask. It was added so that Python - could do syntax-dependent munging of patterns before compilation. */ - -int re_set_syntax(int syntax); -/* This sets the syntax to use and returns the previous syntax. The - syntax is specified by a bit mask of the above defined bits. */ - -char *re_compile_pattern(char *regex, int regex_size, regexp_t compiled); -/* This compiles the regexp (given in regex and length in regex_size). - This returns NULL if the regexp compiled successfully, and an error - message if an error was encountered. The buffer field must be - initialized to a memory area allocated by malloc (or to NULL) before - use, and the allocated field must be set to its length (or 0 if buffer is - NULL). Also, the translate field must be set to point to a valid - translation table, or NULL if it is not used. */ - -int re_match(regexp_t compiled, char *string, int size, int pos, - regexp_registers_t regs); -/* This tries to match the regexp against the string. This returns the - length of the matched portion, or -1 if the pattern could not be - matched and -2 if an error (such as failure stack overflow) is - encountered. */ - -int re_match_2(regexp_t compiled, char *string1, int size1, - char *string2, int size2, int pos, regexp_registers_t regs, - int mstop); -/* This tries to match the regexp to the concatenation of string1 and - string2. This returns the length of the matched portion, or -1 if the - pattern could not be matched and -2 if an error (such as failure stack - overflow) is encountered. */ - -int re_search(regexp_t compiled, char *string, int size, int startpos, - int range, regexp_registers_t regs); -/* This rearches for a substring matching the regexp. This returns the first - index at which a match is found. range specifies at how many positions to - try matching; positive values indicate searching forwards, and negative - values indicate searching backwards. mstop specifies the offset beyond - which a match must not go. This returns -1 if no match is found, and - -2 if an error (such as failure stack overflow) is encountered. */ - -int re_search_2(regexp_t compiled, char *string1, int size1, - char *string2, int size2, int startpos, int range, - regexp_registers_t regs, int mstop); -/* This is like re_search, but search from the concatenation of string1 and - string2. */ - -void re_compile_fastmap(regexp_t compiled); -/* This computes the fastmap for the regexp. For this to have any effect, - the calling program must have initialized the fastmap field to point - to an array of 256 characters. */ - -char *re_comp(char *s); -/* BSD 4.2 regex library routine re_comp. This compiles the regexp into - an internal buffer. This returns NULL if the regexp was compiled - successfully, and an error message if there was an error. */ - -int re_exec(char *s); -/* BSD 4.2 regexp library routine re_exec. This returns true if the string - matches the regular expression (that is, a matching part is found - anywhere in the string). */ - -#else /* HAVE_PROTOTYPES */ - -extern int re_syntax; -int re_set_syntax(); -char *re_compile_pattern(); -int re_match(); -int re_match_2(); -int re_search(); -int re_search_2(); -void re_compile_fastmap(); -char *re_comp(); -int re_exec(); - -#endif /* HAVE_PROTOTYPES */ - -#endif /* REGEXPR_H */ - - - -#ifdef __cplusplus -} -#endif -#endif /* !Py_REGEXPR_H */ diff --git a/Modules/rgbimgmodule.c b/Modules/rgbimgmodule.c deleted file mode 100644 index 62e9e0b35b..0000000000 --- a/Modules/rgbimgmodule.c +++ /dev/null @@ -1,752 +0,0 @@ -/* - * fastimg - - * Faster reading and writing of image files. - * - * This code should work on machines with any byte order. - * - * Could someone make this run real fast using multiple processors - * or how about using memory mapped files to speed it up? - * - * Paul Haeberli - 1991 - * - * Changed to return sizes. - * Sjoerd Mullender - 1993 - * Changed to incorporate into Python. - * Sjoerd Mullender - 1993 - */ -#include "allobjects.h" -#include "modsupport.h" -#ifdef HAVE_UNISTD_H -#include <unistd.h> -#endif -#include <string.h> - -/* - * from image.h - * - */ -typedef struct { - unsigned short imagic; /* stuff saved on disk . . */ - unsigned short type; - unsigned short dim; - unsigned short xsize; - unsigned short ysize; - unsigned short zsize; - unsigned long min; - unsigned long max; - unsigned long wastebytes; - char name[80]; - unsigned long colormap; - - long file; /* stuff used in core only */ - unsigned short flags; - short dorev; - short x; - short y; - short z; - short cnt; - unsigned short *ptr; - unsigned short *base; - unsigned short *tmpbuf; - unsigned long offset; - unsigned long rleend; /* for rle images */ - unsigned long *rowstart; /* for rle images */ - long *rowsize; /* for rle images */ -} IMAGE; - -#define IMAGIC 0732 - -#define TYPEMASK 0xff00 -#define BPPMASK 0x00ff -#define ITYPE_VERBATIM 0x0000 -#define ITYPE_RLE 0x0100 -#define ISRLE(type) (((type) & 0xff00) == ITYPE_RLE) -#define ISVERBATIM(type) (((type) & 0xff00) == ITYPE_VERBATIM) -#define BPP(type) ((type) & BPPMASK) -#define RLE(bpp) (ITYPE_RLE | (bpp)) -#define VERBATIM(bpp) (ITYPE_VERBATIM | (bpp)) -/* - * end of image.h stuff - * - */ - -#define RINTLUM (79) -#define GINTLUM (156) -#define BINTLUM (21) - -#define ILUM(r,g,b) ((int)(RINTLUM*(r)+GINTLUM*(g)+BINTLUM*(b))>>8) - -#define OFFSET_R 3 /* this is byte order dependent */ -#define OFFSET_G 2 -#define OFFSET_B 1 -#define OFFSET_A 0 - -#define CHANOFFSET(z) (3-(z)) /* this is byte order dependent */ - -static expandrow PROTO((unsigned char *, unsigned char *, int)); -static setalpha PROTO((unsigned char *, int)); -static copybw PROTO((long *, int)); -static interleaverow PROTO((unsigned char *, unsigned char *, int, int)); -static int compressrow PROTO((unsigned char *, unsigned char *, int, int)); -static lumrow PROTO((unsigned char *, unsigned char *, int)); - -#ifdef ADD_TAGS -#define TAGLEN (5) -#else -#define TAGLEN (0) -#endif - -static object *ImgfileError; - -static int reverse_order; - -#ifdef ADD_TAGS -/* - * addlongimgtag - - * this is used to extract image data from core dumps. - * - */ -addlongimgtag(dptr,xsize,ysize) -unsigned long *dptr; -int xsize, ysize; -{ - dptr = dptr+(xsize*ysize); - dptr[0] = 0x12345678; - dptr[1] = 0x59493333; - dptr[2] = 0x69434222; - dptr[3] = xsize; - dptr[4] = ysize; -} -#endif - -/* - * byte order independent read/write of shorts and longs. - * - */ -static unsigned short getshort(inf) -FILE *inf; -{ - unsigned char buf[2]; - - fread(buf,2,1,inf); - return (buf[0]<<8)+(buf[1]<<0); -} - -static unsigned long getlong(inf) -FILE *inf; -{ - unsigned char buf[4]; - - fread(buf,4,1,inf); - return (buf[0]<<24)+(buf[1]<<16)+(buf[2]<<8)+(buf[3]<<0); -} - -static putshort(outf,val) -FILE *outf; -unsigned short val; -{ - unsigned char buf[2]; - - buf[0] = (val>>8); - buf[1] = (val>>0); - fwrite(buf,2,1,outf); -} - -static int putlong(outf,val) -FILE *outf; -unsigned long val; -{ - unsigned char buf[4]; - - buf[0] = (val>>24); - buf[1] = (val>>16); - buf[2] = (val>>8); - buf[3] = (val>>0); - return fwrite(buf,4,1,outf); -} - -static readheader(inf,image) -FILE *inf; -IMAGE *image; -{ - memset(image,0,sizeof(IMAGE)); - image->imagic = getshort(inf); - image->type = getshort(inf); - image->dim = getshort(inf); - image->xsize = getshort(inf); - image->ysize = getshort(inf); - image->zsize = getshort(inf); -} - -static int writeheader(outf,image) -FILE *outf; -IMAGE *image; -{ - IMAGE t; - - memset(&t,0,sizeof(IMAGE)); - fwrite(&t,sizeof(IMAGE),1,outf); - fseek(outf,0,SEEK_SET); - putshort(outf,image->imagic); - putshort(outf,image->type); - putshort(outf,image->dim); - putshort(outf,image->xsize); - putshort(outf,image->ysize); - putshort(outf,image->zsize); - putlong(outf,image->min); - putlong(outf,image->max); - putlong(outf,0); - return fwrite("no name",8,1,outf); -} - -static int writetab(outf,tab,len) -FILE *outf; -/*unsigned*/ long *tab; -int len; -{ - int r; - - while(len) { - r = putlong(outf,*tab++); - len -= 4; - } - return r; -} - -static readtab(inf,tab,len) -FILE *inf; -/*unsigned*/ long *tab; -int len; -{ - while(len) { - *tab++ = getlong(inf); - len -= 4; - } -} - -/* - * sizeofimage - - * return the xsize and ysize of an iris image file. - * - */ -static object * -sizeofimage(self, args) - object *self, *args; -{ - char *name; - IMAGE image; - FILE *inf; - - if (!getargs(args, "s", &name)) - return NULL; - - inf = fopen(name,"r"); - if(!inf) { - err_setstr(ImgfileError, "can't open image file"); - return NULL; - } - readheader(inf,&image); - fclose(inf); - if(image.imagic != IMAGIC) { - err_setstr(ImgfileError, "bad magic number in image file"); - return NULL; - } - return mkvalue("(ii)", image.xsize, image.ysize); -} - -/* - * longimagedata - - * read in a B/W RGB or RGBA iris image file and return a - * pointer to an array of longs. - * - */ -static object * -longimagedata(self, args) - object *self, *args; -{ - char *name; - unsigned char *base, *lptr; - unsigned char *rledat, *verdat; - long *starttab, *lengthtab; - FILE *inf; - IMAGE image; - int y, z, tablen; - int xsize, ysize, zsize; - int bpp, rle, cur, badorder; - int rlebuflen; - object *rv; - - if (!getargs(args, "s", &name)) - return NULL; - - inf = fopen(name,"r"); - if(!inf) { - err_setstr(ImgfileError,"can't open image file"); - return NULL; - } - readheader(inf,&image); - if(image.imagic != IMAGIC) { - err_setstr(ImgfileError,"bad magic number in image file"); - fclose(inf); - return NULL; - } - rle = ISRLE(image.type); - bpp = BPP(image.type); - if(bpp != 1 ) { - err_setstr(ImgfileError,"image must have 1 byte per pix chan"); - fclose(inf); - return NULL; - } - xsize = image.xsize; - ysize = image.ysize; - zsize = image.zsize; - if(rle) { - tablen = ysize*zsize*sizeof(long); - starttab = (long *)malloc(tablen); - lengthtab = (long *)malloc(tablen); - rlebuflen = 1.05*xsize+10; - rledat = (unsigned char *)malloc(rlebuflen); - fseek(inf,512,SEEK_SET); - readtab(inf,starttab,tablen); - readtab(inf,lengthtab,tablen); - -/* check data order */ - cur = 0; - badorder = 0; - for(y=0; y<ysize; y++) { - for(z=0; z<zsize; z++) { - if(starttab[y+z*ysize]<cur) { - badorder = 1; - break; - } - cur = starttab[y+z*ysize]; - } - if(badorder) - break; - } - - fseek(inf,512+2*tablen,SEEK_SET); - cur = 512+2*tablen; - rv = newsizedstringobject((char *) 0, - (xsize*ysize+TAGLEN)*sizeof(long)); - if (rv == NULL) { - fclose(inf); - free(lengthtab); - free(starttab); - free(rledat); - return NULL; - } - base = (unsigned char *) getstringvalue(rv); -#ifdef ADD_TAGS - addlongimgtag(base,xsize,ysize); -#endif - if(badorder) { - for(z=0; z<zsize; z++) { - lptr = base; - if (reverse_order) - lptr += (ysize - 1) * xsize * sizeof(unsigned long); - for(y=0; y<ysize; y++) { - if(cur != starttab[y+z*ysize]) { - fseek(inf,starttab[y+z*ysize],SEEK_SET); - cur = starttab[y+z*ysize]; - } - if(lengthtab[y+z*ysize]>rlebuflen) { - err_setstr(ImgfileError,"rlebuf is too small - bad poop"); - fclose(inf); - DECREF(rv); - free(rledat); - free(starttab); - free(lengthtab); - return NULL; - } - fread(rledat,lengthtab[y+z*ysize],1,inf); - cur += lengthtab[y+z*ysize]; - expandrow(lptr,rledat,3-z); - if (reverse_order) - lptr -= xsize * sizeof(unsigned long); - else - lptr += xsize * sizeof(unsigned long); - } - } - } else { - lptr = base; - if (reverse_order) - lptr += (ysize - 1) * xsize * sizeof(unsigned long); - for(y=0; y<ysize; y++) { - for(z=0; z<zsize; z++) { - if(cur != starttab[y+z*ysize]) { - fseek(inf,starttab[y+z*ysize],SEEK_SET); - cur = starttab[y+z*ysize]; - } - fread(rledat,lengthtab[y+z*ysize],1,inf); - cur += lengthtab[y+z*ysize]; - expandrow(lptr,rledat,3-z); - } - if (reverse_order) - lptr -= xsize * sizeof(unsigned long); - else - lptr += xsize * sizeof(unsigned long); - } - } - if(zsize == 3) - setalpha(base,xsize*ysize); - else if(zsize<3) - copybw((long *) base,xsize*ysize); - fclose(inf); - free(starttab); - free(lengthtab); - free(rledat); - return rv; - } else { - rv = newsizedstringobject((char *) 0, - (xsize*ysize+TAGLEN)*sizeof(long)); - if (rv == NULL) { - fclose(inf); - return NULL; - } - base = (unsigned char *) getstringvalue(rv); -#ifdef ADD_TAGS - addlongimgtag(base,xsize,ysize); -#endif - verdat = (unsigned char *)malloc(xsize); - fseek(inf,512,SEEK_SET); - for(z=0; z<zsize; z++) { - lptr = base; - if (reverse_order) - lptr += (ysize - 1) * xsize * sizeof(unsigned long); - for(y=0; y<ysize; y++) { - fread(verdat,xsize,1,inf); - interleaverow(lptr,verdat,3-z,xsize); - if (reverse_order) - lptr -= xsize * sizeof(unsigned long); - else - lptr += xsize * sizeof(unsigned long); - } - } - if(zsize == 3) - setalpha(base,xsize*ysize); - else if(zsize<3) - copybw((long *) base,xsize*ysize); - fclose(inf); - free(verdat); - return rv; - } -} - -/* static utility functions for longimagedata */ - -static interleaverow(lptr,cptr,z,n) -unsigned char *lptr, *cptr; -int z, n; -{ - lptr += z; - while(n--) { - *lptr = *cptr++; - lptr += 4; - } -} - -static copybw(lptr,n) -long *lptr; -int n; -{ - while(n>=8) { - lptr[0] = 0xff000000+(0x010101*(lptr[0]&0xff)); - lptr[1] = 0xff000000+(0x010101*(lptr[1]&0xff)); - lptr[2] = 0xff000000+(0x010101*(lptr[2]&0xff)); - lptr[3] = 0xff000000+(0x010101*(lptr[3]&0xff)); - lptr[4] = 0xff000000+(0x010101*(lptr[4]&0xff)); - lptr[5] = 0xff000000+(0x010101*(lptr[5]&0xff)); - lptr[6] = 0xff000000+(0x010101*(lptr[6]&0xff)); - lptr[7] = 0xff000000+(0x010101*(lptr[7]&0xff)); - lptr += 8; - n-=8; - } - while(n--) { - *lptr = 0xff000000+(0x010101*(*lptr&0xff)); - lptr++; - } -} - -static setalpha(lptr,n) -unsigned char *lptr; -{ - while(n>=8) { - lptr[0*4] = 0xff; - lptr[1*4] = 0xff; - lptr[2*4] = 0xff; - lptr[3*4] = 0xff; - lptr[4*4] = 0xff; - lptr[5*4] = 0xff; - lptr[6*4] = 0xff; - lptr[7*4] = 0xff; - lptr += 4*8; - n -= 8; - } - while(n--) { - *lptr = 0xff; - lptr += 4; - } -} - -static expandrow(optr,iptr,z) -unsigned char *optr, *iptr; -int z; -{ - unsigned char pixel, count; - - optr += z; - while(1) { - pixel = *iptr++; - if ( !(count = (pixel & 0x7f)) ) - return; - if(pixel & 0x80) { - while(count>=8) { - optr[0*4] = iptr[0]; - optr[1*4] = iptr[1]; - optr[2*4] = iptr[2]; - optr[3*4] = iptr[3]; - optr[4*4] = iptr[4]; - optr[5*4] = iptr[5]; - optr[6*4] = iptr[6]; - optr[7*4] = iptr[7]; - optr += 8*4; - iptr += 8; - count -= 8; - } - while(count--) { - *optr = *iptr++; - optr+=4; - } - } else { - pixel = *iptr++; - while(count>=8) { - optr[0*4] = pixel; - optr[1*4] = pixel; - optr[2*4] = pixel; - optr[3*4] = pixel; - optr[4*4] = pixel; - optr[5*4] = pixel; - optr[6*4] = pixel; - optr[7*4] = pixel; - optr += 8*4; - count -= 8; - } - while(count--) { - *optr = pixel; - optr+=4; - } - } - } -} - -/* - * longstoimage - - * copy an array of longs to an iris image file. Each long - * represents one pixel. xsize and ysize specify the dimensions of - * the pixel array. zsize specifies what kind of image file to - * write out. if zsize is 1, the luminance of the pixels are - * calculated, and a sinlge channel black and white image is saved. - * If zsize is 3, an RGB image file is saved. If zsize is 4, an - * RGBA image file is saved. - * - */ -static object * -longstoimage(self, args) - object *self, *args; -{ - unsigned char *lptr; - char *name; - int xsize, ysize, zsize; - FILE *outf; - IMAGE image; - int tablen, y, z, pos, len; - long *starttab, *lengthtab; - unsigned char *rlebuf; - unsigned char *lumbuf; - int rlebuflen, goodwrite; - - if (!getargs(args, "(s#iiis)", &lptr, &len, &xsize, &ysize, &zsize, &name)) - return NULL; - - goodwrite = 1; - outf = fopen(name,"w"); - if(!outf) { - err_setstr(ImgfileError,"can't open output file"); - return NULL; - } - tablen = ysize*zsize*sizeof(long); - - starttab = (long *)malloc(tablen); - lengthtab = (long *)malloc(tablen); - rlebuflen = 1.05*xsize+10; - rlebuf = (unsigned char *)malloc(rlebuflen); - lumbuf = (unsigned char *)malloc(xsize*sizeof(long)); - - memset(&image,0,sizeof(IMAGE)); - image.imagic = IMAGIC; - image.type = RLE(1); - if(zsize>1) - image.dim = 3; - else - image.dim = 2; - image.xsize = xsize; - image.ysize = ysize; - image.zsize = zsize; - image.min = 0; - image.max = 255; - goodwrite *= writeheader(outf,&image); - fseek(outf,512+2*tablen,SEEK_SET); - pos = 512+2*tablen; - if (reverse_order) - lptr += (ysize - 1) * xsize * sizeof(unsigned long); - for(y=0; y<ysize; y++) { - for(z=0; z<zsize; z++) { - if(zsize == 1) { - lumrow(lptr,lumbuf,xsize); - len = compressrow(lumbuf,rlebuf,CHANOFFSET(z),xsize); - } else { - len = compressrow(lptr,rlebuf,CHANOFFSET(z),xsize); - } - if(len>rlebuflen) { - err_setstr(ImgfileError,"rlebuf is too small - bad poop"); - free(starttab); - free(lengthtab); - free(rlebuf); - free(lumbuf); - fclose(outf); - return NULL; - } - goodwrite *= fwrite(rlebuf,len,1,outf); - starttab[y+z*ysize] = pos; - lengthtab[y+z*ysize] = len; - pos += len; - } - if (reverse_order) - lptr -= xsize * sizeof(unsigned long); - else - lptr += xsize * sizeof(unsigned long); - } - - fseek(outf,512,SEEK_SET); - goodwrite *= writetab(outf,starttab,tablen); - goodwrite *= writetab(outf,lengthtab,tablen); - free(starttab); - free(lengthtab); - free(rlebuf); - free(lumbuf); - fclose(outf); - if(goodwrite) { - INCREF(None); - return None; - } else { - err_setstr(ImgfileError,"not enough space for image!!"); - return NULL; - } -} - -/* static utility functions for longstoimage */ - -static lumrow(rgbptr,lumptr,n) -unsigned char *rgbptr, *lumptr; -int n; -{ - lumptr += CHANOFFSET(0); - while(n--) { - *lumptr = ILUM(rgbptr[OFFSET_R],rgbptr[OFFSET_G],rgbptr[OFFSET_B]); - lumptr += 4; - rgbptr += 4; - } -} - -static int compressrow(lbuf,rlebuf,z,cnt) -unsigned char *lbuf, *rlebuf; -int z, cnt; -{ - unsigned char *iptr, *ibufend, *sptr, *optr; - short todo, cc; - long count; - - lbuf += z; - iptr = lbuf; - ibufend = iptr+cnt*4; - optr = rlebuf; - - while(iptr<ibufend) { - sptr = iptr; - iptr += 8; - while((iptr<ibufend)&& ((iptr[-8]!=iptr[-4])||(iptr[-4]!=iptr[0]))) - iptr+=4; - iptr -= 8; - count = (iptr-sptr)/4; - while(count) { - todo = count>126 ? 126:count; - count -= todo; - *optr++ = 0x80|todo; - while(todo>8) { - optr[0] = sptr[0*4]; - optr[1] = sptr[1*4]; - optr[2] = sptr[2*4]; - optr[3] = sptr[3*4]; - optr[4] = sptr[4*4]; - optr[5] = sptr[5*4]; - optr[6] = sptr[6*4]; - optr[7] = sptr[7*4]; - optr += 8; - sptr += 8*4; - todo -= 8; - } - while(todo--) { - *optr++ = *sptr; - sptr += 4; - } - } - sptr = iptr; - cc = *iptr; - iptr += 4; - while( (iptr<ibufend) && (*iptr == cc) ) - iptr += 4; - count = (iptr-sptr)/4; - while(count) { - todo = count>126 ? 126:count; - count -= todo; - *optr++ = todo; - *optr++ = cc; - } - } - *optr++ = 0; - return optr - (unsigned char *)rlebuf; -} - -static object * -ttob(self, args) - object *self; - object *args; -{ - int order, oldorder; - - if (!getargs(args, "i", &order)) - return NULL; - oldorder = reverse_order; - reverse_order = order; - return newintobject(oldorder); -} - -static struct methodlist rgbimg_methods[] = { - {"sizeofimage", sizeofimage}, - {"longimagedata", longimagedata}, - {"longstoimage", longstoimage}, - {"ttob", ttob}, - {NULL, NULL} /* sentinel */ -}; - -void -initrgbimg() -{ - object *m, *d; - m = initmodule("rgbimg", rgbimg_methods); - d = getmoduledict(m); - ImgfileError = newstringobject("rgbimg.error"); - if (ImgfileError == NULL || dictinsert(d, "error", ImgfileError)) - fatal("can't define rgbimg.error"); -} diff --git a/Modules/rotormodule.c b/Modules/rotormodule.c deleted file mode 100644 index 6988f881a5..0000000000 --- a/Modules/rotormodule.c +++ /dev/null @@ -1,813 +0,0 @@ -/*********************************************************** -Copyright 1994 by Lance Ellinghouse, -Cathedral City, California Republic, United States of America. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the name of Lance Ellinghouse -not be used in advertising or publicity pertaining to distribution -of the software without specific, written prior permission. - -LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE 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. - -******************************************************************/ - -/* This creates an encryption and decryption engine I am calling - a rotor due to the original design was a harware rotor with - contacts used in Germany during WWII. - -Rotor Module: - -- rotor.newrotor('key') -> rotorobject (default of 6 rotors) -- rotor.newrotor('key', num_rotors) -> rotorobject - -Rotor Objects: - -- ro.setkey('string') -> None (resets the key as defined in newrotor(). -- ro.encrypt('string') -> encrypted string -- ro.decrypt('encrypted string') -> unencrypted string - -- ro.encryptmore('string') -> encrypted string -- ro.decryptmore('encrypted string') -> unencrypted string - -NOTE: the {en,de}cryptmore() methods use the setup that was - established via the {en,de}crypt calls. They will NOT - re-initalize the rotors unless: 1) They have not been - initalized with {en,de}crypt since the last setkey() call; - 2) {en,de}crypt has not been called for this rotor yet. - -NOTE: you MUST use the SAME key in rotor.newrotor() - if you wish to decrypt an encrypted string. - Also, the encrypted string is NOT 0-127 ASCII. - It is considered BINARY data. - -*/ - -/* Rotor objects */ - -#include "Python.h" - -#include "mymath.h" - -#define TRUE 1 -#define FALSE 0 - -typedef struct { - PyObject_HEAD - int seed[3]; - short key[5]; - int isinited; - int size; - int size_mask; - int rotors; - unsigned char *e_rotor; /* [num_rotors][size] */ - unsigned char *d_rotor; /* [num_rotors][size] */ - unsigned char *positions; /* [num_rotors] */ - unsigned char *advances; /* [num_rotors] */ -} PyRotorObject; - -staticforward PyTypeObject PyRotor_Type; - -#define PyRotor_Check(v) ((v)->ob_type == &PyRotor_Type) - -/* - This defines the necessary routines to manage rotor objects -*/ - -static void set_seed( r ) -PyRotorObject *r; -{ - r->seed[0] = r->key[0]; - r->seed[1] = r->key[1]; - r->seed[2] = r->key[2]; - r->isinited = FALSE; -} - -/* Return the next random number in the range [0.0 .. 1.0) */ -static float r_random( r ) -PyRotorObject *r; -{ - int x, y, z; - float val, term; - - x = r->seed[0]; - y = r->seed[1]; - z = r->seed[2]; - - x = 171 * (x % 177) - 2 * (x/177); - y = 172 * (y % 176) - 35 * (y/176); - z = 170 * (z % 178) - 63 * (z/178); - - if (x < 0) x = x + 30269; - if (y < 0) y = y + 30307; - if (z < 0) z = z + 30323; - - r->seed[0] = x; - r->seed[1] = y; - r->seed[2] = z; - - term = (float)( - (((float)x)/(float)30269.0) + - (((float)y)/(float)30307.0) + - (((float)z)/(float)30323.0) - ); - val = term - (float)floor((double)term); - - if (val >= 1.0) val = 0.0; - - return val; -} - -static short r_rand(r,s) -PyRotorObject *r; -short s; -{ - /*short tmp = (short)((int)(r_random(r) * (float)32768.0) % 32768);*/ - short tmp = (short)((short)(r_random(r) * (float)s) % s); - return tmp; -} - -static void set_key(r, key) -PyRotorObject *r; -char *key; -{ -#ifdef BUGGY_CODE_BW_COMPAT - /* See comments below */ - int k1=995, k2=576, k3=767, k4=671, k5=463; -#else - unsigned long k1=995, k2=576, k3=767, k4=671, k5=463; -#endif - int i; - int len=strlen(key); - for (i=0;i<len;i++) { -#ifdef BUGGY_CODE_BW_COMPAT - /* This is the code as it was originally released. - It causes warnings on many systems and can generate - different results as well. If you have files - encrypted using an older version you may want to - #define BUGGY_CODE_BW_COMPAT so as to be able to - decrypt them... */ - k1 = (((k1<<3 | k1<<-13) + key[i]) & 65535); - k2 = (((k2<<3 | k2<<-13) ^ key[i]) & 65535); - k3 = (((k3<<3 | k3<<-13) - key[i]) & 65535); - k4 = ((key[i] - (k4<<3 | k4<<-13)) & 65535); - k5 = (((k5<<3 | k5<<-13) ^ ~key[i]) & 65535); -#else - /* This code should be more portable */ - k1 = (((k1<<3 | k1>>13) + key[i]) & 65535); - k2 = (((k2<<3 | k2>>13) ^ key[i]) & 65535); - k3 = (((k3<<3 | k3>>13) - key[i]) & 65535); - k4 = ((key[i] - (k4<<3 | k4>>13)) & 65535); - k5 = (((k5<<3 | k5>>13) ^ ~key[i]) & 65535); -#endif - } - r->key[0] = (short)k1; - r->key[1] = (short)(k2|1); - r->key[2] = (short)k3; - r->key[3] = (short)k4; - r->key[4] = (short)k5; - - set_seed(r); -} - -/* These define the interface to a rotor object */ -static PyRotorObject * -PyRotor_New(num_rotors, key) - int num_rotors; - char *key; -{ - PyRotorObject *xp; - xp = PyObject_NEW(PyRotorObject, &PyRotor_Type); - if (xp == NULL) - return NULL; - set_key(xp, key); - - xp->size = 256; - xp->size_mask = xp->size - 1; - xp->size_mask = 0; - xp->rotors = num_rotors; - xp->e_rotor = NULL; - xp->d_rotor = NULL; - xp->positions = NULL; - xp->advances = NULL; - - xp->e_rotor = - (unsigned char *)malloc((num_rotors * (xp->size * sizeof(char)))); - if (xp->e_rotor == (unsigned char *)NULL) - goto fail; - xp->d_rotor = - (unsigned char *)malloc((num_rotors * (xp->size * sizeof(char)))); - if (xp->d_rotor == (unsigned char *)NULL) - goto fail; - xp->positions = (unsigned char *)malloc(num_rotors * sizeof(char)); - if (xp->positions == (unsigned char *)NULL) - goto fail; - xp->advances = (unsigned char *)malloc(num_rotors * sizeof(char)); - if (xp->advances == (unsigned char *)NULL) - goto fail; - return xp; -fail: - Py_DECREF(xp); - return (PyRotorObject *)PyErr_NoMemory(); -} - -/* These routines impliment the rotor itself */ - -/* Here is a fairly sofisticated {en,de}cryption system. It is bassed -on the idea of a "rotor" machine. A bunch of rotors, each with a -different permutation of the alphabet, rotate around a different -amount after encrypting one character. The current state of the -rotors is used to encrypt one character. - - The code is smart enought to tell if your alphabet has a number of -characters equal to a power of two. If it does, it uses logical -operations, if not it uses div and mod (both require a division). - - You will need to make two changes to the code 1) convert to c, and -customize for an alphabet of 255 chars 2) add a filter at the -begining, and end, which subtracts one on the way in, and adds one on -the way out. - - You might wish to do some timing studies. Another viable -alternative is to "byte stuff" the encrypted data of a normal (perhaps -this one) encryption routine. - -j' -*/ - -/*(defun RTR-make-id-rotor (rotor) - "Set ROTOR to the identity permutation" - (let ((j 0)) - (while (< j RTR-size) - (aset rotor j j) - (setq j (+ 1 j))) - rotor))*/ -static void RTR_make_id_rotor(r, rtr) - PyRotorObject *r; - unsigned char *rtr; -{ - register int j; - register int size = r->size; - for (j=0;j<size;j++) { - rtr[j] = (unsigned char)j; - } -} - - -/*(defvar RTR-e-rotors - (let ((rv (make-vector RTR-number-of-rotors 0)) - (i 0) - tr) - (while (< i RTR-number-of-rotors) - (setq tr (make-vector RTR-size 0)) - (RTR-make-id-rotor tr) - (aset rv i tr) - (setq i (+ 1 i))) - rv) - "The current set of encryption rotors")*/ -static void RTR_e_rotors(r) - PyRotorObject *r; -{ - int i; - for (i=0;i<r->rotors;i++) { - RTR_make_id_rotor(r,&(r->e_rotor[(i*r->size)])); - } -} - -/*(defvar RTR-d-rotors - (let ((rv (make-vector RTR-number-of-rotors 0)) - (i 0) - tr) - (while (< i RTR-number-of-rotors) - (setq tr (make-vector RTR-size 0)) - (setq j 0) - (while (< j RTR-size) - (aset tr j j) - (setq j (+ 1 j))) - (aset rv i tr) - (setq i (+ 1 i))) - rv) - "The current set of decryption rotors")*/ -static void RTR_d_rotors(r) - PyRotorObject *r; -{ - register int i, j; - for (i=0;i<r->rotors;i++) { - for (j=0;j<r->size;j++) { - r->d_rotor[((i*r->size)+j)] = (unsigned char)j; - } - } -} - -/*(defvar RTR-positions (make-vector RTR-number-of-rotors 1) - "The positions of the rotors at this time")*/ -static void RTR_positions(r) - PyRotorObject *r; -{ - int i; - for (i=0;i<r->rotors;i++) { - r->positions[i] = 1; - } -} - -/*(defvar RTR-advances (make-vector RTR-number-of-rotors 1) - "The number of positions to advance the rotors at a time")*/ -static void RTR_advances(r) - PyRotorObject *r; -{ - int i; - for (i=0;i<r->rotors;i++) { - r->advances[i] = 1; - } -} - -/*(defun RTR-permute-rotor (e d) - "Permute the E rotor, and make the D rotor its inverse" - ;; see Knuth for explaination of algorythm. - (RTR-make-id-rotor e) - (let ((i RTR-size) - q j) - (while (<= 2 i) - (setq q (fair16 i)) ; a little tricky, decrement here - (setq i (- i 1)) ; since we have origin 0 array's - (setq j (aref e q)) - (aset e q (aref e i)) - (aset e i j) - (aset d j i)) - (aset e 0 (aref e 0)) ; don't forget e[0] and d[0] - (aset d (aref e 0) 0)))*/ -static void RTR_permute_rotor(r, e, d) - PyRotorObject *r; - unsigned char *e; - unsigned char *d; -{ - short i = r->size; - short q; - unsigned char j; - RTR_make_id_rotor(r,e); - while (2 <= i) { - q = r_rand(r,i); - i--; - j = e[q]; - e[q] = (unsigned char)e[i]; - e[i] = (unsigned char)j; - d[j] = (unsigned char)i; - } - e[0] = (unsigned char)e[0]; - d[(e[0])] = (unsigned char)0; -} - -/*(defun RTR-init (key) - "Given KEY (a list of 5 16 bit numbers), initialize the rotor machine. -Set the advancement, position, and permutation of the rotors" - (R16-set-state key) - (let (i) - (setq i 0) - (while (< i RTR-number-of-rotors) - (aset RTR-positions i (fair16 RTR-size)) - (aset RTR-advances i (+ 1 (* 2 (fair16 (/ RTR-size 2))))) - (message "Initializing rotor %d..." i) - (RTR-permute-rotor (aref RTR-e-rotors i) (aref RTR-d-rotors i)) - (setq i (+ 1 i)))))*/ -static void RTR_init(r) - PyRotorObject *r; -{ - int i; - set_seed(r); - RTR_positions(r); - RTR_advances(r); - RTR_e_rotors(r); - RTR_d_rotors(r); - for(i=0;i<r->rotors;i++) { - r->positions[i] = r_rand(r,r->size); - r->advances[i] = (1+(2*(r_rand(r,r->size/2)))); - RTR_permute_rotor(r,&(r->e_rotor[(i*r->size)]),&(r->d_rotor[(i*r->size)])); - } - r->isinited = TRUE; -} - -/*(defun RTR-advance () - "Change the RTR-positions vector, using the RTR-advances vector" - (let ((i 0) - (temp 0)) - (if RTR-size-mask - (while (< i RTR-number-of-rotors) - (setq temp (+ (aref RTR-positions i) (aref RTR-advances i))) - (aset RTR-positions i (logand temp RTR-size-mask)) - (if (and (>= temp RTR-size) - (< i (- RTR-number-of-rotors 1))) - (aset RTR-positions (+ i 1) - (+ 1 (aref RTR-positions (+ i 1))))) - (setq i (+ i 1))) - (while (< i RTR-number-of-rotors) - (setq temp (+ (aref RTR-positions i) (aref RTR-advances i))) - (aset RTR-positions i (% temp RTR-size)) - (if (and (>= temp RTR-size) - (< i (- RTR-number-of-rotors 1))) - (aset RTR-positions (+ i 1) - (+ 1 (aref RTR-positions (+ i 1))))) - (setq i (+ i 1))))))*/ -static void RTR_advance(r) - PyRotorObject *r; -{ - register int i=0, temp=0; - if (r->size_mask) { - while (i<r->rotors) { - temp = r->positions[i] + r->advances[i]; - r->positions[i] = temp & r->size_mask; - if ((temp >= r->size) && (i < (r->rotors - 1))) { - r->positions[(i+1)] = 1 + r->positions[(i+1)]; - } - i++; - } - } else { - while (i<r->rotors) { - temp = r->positions[i] + r->advances[i]; - r->positions[i] = temp%r->size; - if ((temp >= r->size) && (i < (r->rotors - 1))) { - r->positions[(i+1)] = 1 + r->positions[(i+1)]; - } - i++; - } - } -} - -/*(defun RTR-e-char (p) - "Encrypt the character P with the current rotor machine" - (let ((i 0)) - (if RTR-size-mask - (while (< i RTR-number-of-rotors) - (setq p (aref (aref RTR-e-rotors i) - (logand (logxor (aref RTR-positions i) - p) - RTR-size-mask))) - (setq i (+ 1 i))) - (while (< i RTR-number-of-rotors) - (setq p (aref (aref RTR-e-rotors i) - (% (logxor (aref RTR-positions i) - p) - RTR-size))) - (setq i (+ 1 i)))) - (RTR-advance) - p))*/ -static unsigned char RTR_e_char(r, p) - PyRotorObject *r; - unsigned char p; -{ - register int i=0; - register unsigned char tp=p; - if (r->size_mask) { - while (i < r->rotors) { - tp = r->e_rotor[(i*r->size)+(((r->positions[i] ^ tp) & r->size_mask))]; - i++; - } - } else { - while (i < r->rotors) { - tp = r->e_rotor[(i*r->size)+(((r->positions[i] ^ tp) % (unsigned int) r->size))]; - i++; - } - } - RTR_advance(r); - return ((unsigned char)tp); -} - -/*(defun RTR-d-char (c) - "Decrypt the character C with the current rotor machine" - (let ((i (- RTR-number-of-rotors 1))) - (if RTR-size-mask - (while (<= 0 i) - (setq c (logand (logxor (aref RTR-positions i) - (aref (aref RTR-d-rotors i) - c)) - RTR-size-mask)) - (setq i (- i 1))) - (while (<= 0 i) - (setq c (% (logxor (aref RTR-positions i) - (aref (aref RTR-d-rotors i) - c)) - RTR-size)) - (setq i (- i 1)))) - (RTR-advance) - c))*/ -static unsigned char RTR_d_char(r, c) - PyRotorObject *r; - unsigned char c; -{ - register int i=r->rotors - 1; - register unsigned char tc=c; - if (r->size_mask) { - while (0 <= i) { - tc = (r->positions[i] ^ r->d_rotor[(i*r->size)+tc]) & r->size_mask; - i--; - } - } else { - while (0 <= i) { - tc = (r->positions[i] ^ r->d_rotor[(i*r->size)+tc]) % (unsigned int) r->size; - i--; - } - } - RTR_advance(r); - return(tc); -} - -/*(defun RTR-e-region (beg end key) - "Perform a rotor encryption of the region from BEG to END by KEY" - (save-excursion - (let ((tenth (/ (- end beg) 10))) - (RTR-init key) - (goto-char beg) - ;; ### make it stop evry 10% or so to tell us - (while (< (point) end) - (let ((fc (following-char))) - (insert-char (RTR-e-char fc) 1) - (delete-char 1))))))*/ -static void RTR_e_region(r, beg, len, doinit) - PyRotorObject *r; - unsigned char *beg; - int len; - int doinit; -{ - register int i; - if (doinit || r->isinited == FALSE) - RTR_init(r); - for (i=0;i<len;i++) { - beg[i]=RTR_e_char(r,beg[i]); - } -} - -/*(defun RTR-d-region (beg end key) - "Perform a rotor decryption of the region from BEG to END by KEY" - (save-excursion - (progn - (RTR-init key) - (goto-char beg) - (while (< (point) end) - (let ((fc (following-char))) - (insert-char (RTR-d-char fc) 1) - (delete-char 1))))))*/ -static void RTR_d_region(r, beg, len, doinit) - PyRotorObject *r; - unsigned char *beg; - int len; - int doinit; -{ - register int i; - if (doinit || r->isinited == FALSE) - RTR_init(r); - for (i=0;i<len;i++) { - beg[i]=RTR_d_char(r,beg[i]); - } -} - - -/*(defun RTR-key-string-to-ints (key) - "Convert a string into a list of 4 numbers" - (let ((k1 995) - (k2 576) - (k3 767) - (k4 671) - (k5 463) - (i 0)) - (while (< i (length key)) - (setq k1 (logand (+ (logior (lsh k1 3) (lsh k1 -13)) (aref key i)) 65535)) - (setq k2 (logand (logxor (logior (lsh k2 3) (lsh k2 -13)) (aref key i)) 65535)) - (setq k3 (logand (- (logior (lsh k3 3) (lsh k3 -13)) (aref key i)) 65535)) - (setq k4 (logand (- (aref key i) (logior (lsh k4 3) (lsh k4 -13))) 65535)) - (setq k5 (logand (logxor (logior (lsh k5 3) (lsh k5 -13)) (lognot (aref key i))) 65535)) - (setq i (+ i 1))) - (list k1 (logior 1 k2) k3 k4 k5)))*/ -/* This is done in set_key() above */ - -#if 0 -/*(defun encrypt-region (beg end key) - "Interactivly encrypt the region" - (interactive "r\nsKey:") - (RTR-e-region beg end (RTR-key-string-to-ints key)))*/ -static void encrypt_region(r, region, len) - PyRotorObject *r; - unsigned char *region; - int len; -{ - RTR_e_region(r,region,len,TRUE); -} - -/*(defun decrypt-region (beg end key) - "Interactivly decrypt the region" - (interactive "r\nsKey:") - (RTR-d-region beg end (RTR-key-string-to-ints key)))*/ -static void decrypt_region(r, region, len) - PyRotorObject *r; - unsigned char *region; - int len; -{ - RTR_d_region(r,region,len,TRUE); -} -#endif - -/* Rotor methods */ - -static void -PyRotor_Dealloc(xp) - PyRotorObject *xp; -{ - PyMem_XDEL(xp->e_rotor); - PyMem_XDEL(xp->d_rotor); - PyMem_XDEL(xp->positions); - PyMem_XDEL(xp->advances); - PyMem_DEL(xp); -} - -static PyObject * -PyRotor_Encrypt(self, args) - PyRotorObject *self; - PyObject * args; -{ - char *string = (char *)NULL; - int len = 0; - PyObject * rtn = (PyObject * )NULL; - char *tmp; - - if (!PyArg_Parse(args,"s#",&string, &len)) - return NULL; - if (!(tmp = (char *)malloc(len+5))) { - PyErr_NoMemory(); - return NULL; - } - memset(tmp,'\0',len+1); - memcpy(tmp,string,len); - RTR_e_region(self,(unsigned char *)tmp,len, TRUE); - rtn = PyString_FromStringAndSize(tmp,len); - free(tmp); - return(rtn); -} - -static PyObject * -PyRotor_EncryptMore(self, args) - PyRotorObject *self; - PyObject * args; -{ - char *string = (char *)NULL; - int len = 0; - PyObject * rtn = (PyObject * )NULL; - char *tmp; - - if (!PyArg_Parse(args,"s#",&string, &len)) - return NULL; - if (!(tmp = (char *)malloc(len+5))) { - PyErr_NoMemory(); - return NULL; - } - memset(tmp,'\0',len+1); - memcpy(tmp,string,len); - RTR_e_region(self,(unsigned char *)tmp,len, FALSE); - rtn = PyString_FromStringAndSize(tmp,len); - free(tmp); - return(rtn); -} - -static PyObject * -PyRotor_Decrypt(self, args) - PyRotorObject *self; - PyObject * args; -{ - char *string = (char *)NULL; - int len = 0; - PyObject * rtn = (PyObject * )NULL; - char *tmp; - - if (!PyArg_Parse(args,"s#",&string, &len)) - return NULL; - if (!(tmp = (char *)malloc(len+5))) { - PyErr_NoMemory(); - return NULL; - } - memset(tmp,'\0',len+1); - memcpy(tmp,string,len); - RTR_d_region(self,(unsigned char *)tmp,len, TRUE); - rtn = PyString_FromStringAndSize(tmp,len); - free(tmp); - return(rtn); -} - -static PyObject * -PyRotor_DecryptMore(self, args) - PyRotorObject *self; - PyObject * args; -{ - char *string = (char *)NULL; - int len = 0; - PyObject * rtn = (PyObject * )NULL; - char *tmp; - - if (!PyArg_Parse(args,"s#",&string, &len)) - return NULL; - if (!(tmp = (char *)malloc(len+5))) { - PyErr_NoMemory(); - return NULL; - } - memset(tmp,'\0',len+1); - memcpy(tmp,string,len); - RTR_d_region(self,(unsigned char *)tmp,len, FALSE); - rtn = PyString_FromStringAndSize(tmp,len); - free(tmp); - return(rtn); -} - -static PyObject * -PyRotor_SetKey(self, args) - PyRotorObject *self; - PyObject * args; -{ - char *string; - - if (PyArg_Parse(args,"s",&string)) - set_key(self,string); - Py_INCREF(Py_None); - return Py_None; -} - -static struct PyMethodDef PyRotor_Methods[] = { - {"encrypt", (PyCFunction)PyRotor_Encrypt}, - {"encryptmore", (PyCFunction)PyRotor_EncryptMore}, - {"decrypt", (PyCFunction)PyRotor_Decrypt}, - {"decryptmore", (PyCFunction)PyRotor_DecryptMore}, - {"setkey", (PyCFunction)PyRotor_SetKey}, - {NULL, NULL} /* sentinel */ -}; - - -/* Return a rotor object's named attribute. */ -static PyObject * -PyRotor_GetAttr(s, name) - PyRotorObject *s; - char *name; -{ - return Py_FindMethod(PyRotor_Methods, (PyObject * ) s, name); -} - -statichere PyTypeObject PyRotor_Type = { - PyObject_HEAD_INIT(&PyType_Type) - 0, /*ob_size*/ - "rotor", /*tp_name*/ - sizeof(PyRotorObject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyRotor_Dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)PyRotor_GetAttr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_hash*/ -}; - - -static PyObject * -PyRotor_Rotor(self, args) - PyObject * self; - PyObject * args; -{ - char *string; - PyRotorObject *r; - int len; - int num_rotors; - - if (PyArg_Parse(args,"s#", &string, &len)) { - num_rotors = 6; - } else { - PyErr_Clear(); - if (!PyArg_Parse(args,"(s#i)", &string, &len, &num_rotors)) - return NULL; - } - r = PyRotor_New(num_rotors, string); - return (PyObject * )r; -} - -static struct PyMethodDef PyRotor_Rotor_Methods[] = { - {"newrotor", (PyCFunction)PyRotor_Rotor}, - {NULL, NULL} /* Sentinel */ -}; - - -/* Initialize this module. - This is called when the first 'import rotor' is done, - via a table in config.c, if config.c is compiled with USE_ROTOR - defined. */ - -void -initrotor() -{ - PyObject * m; - - m = Py_InitModule("rotor", PyRotor_Rotor_Methods); -} diff --git a/Modules/selectmodule.c b/Modules/selectmodule.c deleted file mode 100644 index 5c835887de..0000000000 --- a/Modules/selectmodule.c +++ /dev/null @@ -1,207 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* select - Module containing unix select(2) call */ - -#include "allobjects.h" -#include "modsupport.h" -#include "ceval.h" - -#include <sys/types.h> -#include "myselect.h" /* Also includes mytime.h */ - -static object *SelectError; - -static -list2set(list, set, fd2obj) - object *list; - fd_set *set; - object *fd2obj[FD_SETSIZE]; -{ - int i, len, v, max = -1; - object *o, *filenomethod, *fno; - - for ( i=0; i<FD_SETSIZE; i++ ) { - fd2obj[i] = (object*)0; - } - - FD_ZERO(set); - len = getlistsize(list); - for( i=0; i<len; i++ ) { - o = getlistitem(list, i); - if ( is_intobject(o) ) { - v = getintvalue(o); - } else if ( (filenomethod = getattr(o, "fileno")) != NULL ) { - fno = call_object(filenomethod, NULL); - DECREF(filenomethod); - if ( fno == NULL ) - return -1; - if ( !is_intobject(fno) ) { - err_badarg(); - DECREF(fno); - return -1; - } - v = getintvalue(fno); - DECREF(fno); - } else { - err_badarg(); - return -1; - } - if ( v < 0 || v >= FD_SETSIZE ) { - err_setstr(ValueError, "filedescriptor out of range in select()"); - return -1; - } - if ( v > max ) max = v; - FD_SET(v, set); - fd2obj[v] = o; - } - return max+1; -} - -static object * -set2list(set, max, fd2obj) - fd_set *set; - int max; - object *fd2obj[FD_SETSIZE]; -{ - int i, num=0; - object *list, *o; - - for(i=0; i<max; i++) - if ( FD_ISSET(i,set) ) - num++; - list = newlistobject(num); - num = 0; - for(i=0; i<max; i++) - if ( FD_ISSET(i,set) ) { - if ( i > FD_SETSIZE ) { - err_setstr(SystemError, - "filedescriptor out of range returned in select()"); - return NULL; - } - o = fd2obj[i]; - if ( o == NULL ) { - err_setstr(SystemError, - "Bad filedescriptor returned from select()"); - return NULL; - } - INCREF(o); - setlistitem(list, num, o); - num++; - } - return list; -} - -static object * -select_select(self, args) - object *self; - object *args; -{ - object *rfd2obj[FD_SETSIZE], *wfd2obj[FD_SETSIZE], *efd2obj[FD_SETSIZE]; - object *ifdlist, *ofdlist, *efdlist; - object *ret, *tout; - fd_set ifdset, ofdset, efdset; - double timeout; - struct timeval tv, *tvp; - int seconds; - int imax, omax, emax, max; - int n; - - - /* Get args. Looks funny because of optional timeout argument */ - if ( getargs(args, "(OOOO)", &ifdlist, &ofdlist, &efdlist, &tout) ) { - if (tout == None) - tvp = (struct timeval *)0; - else { - if (!getargs(tout, "d;timeout must be float or None", &timeout)) - return NULL; - seconds = (int)timeout; - timeout = timeout - (double)seconds; - tv.tv_sec = seconds; - tv.tv_usec = (int)(timeout*1000000.0); - tvp = &tv; - } - } else { - /* Doesn't have 4 args, that means no timeout */ - err_clear(); - if (!getargs(args, "(OOO)", &ifdlist, &ofdlist, &efdlist) ) - return 0; - tvp = (struct timeval *)0; - } - if ( !is_listobject(ifdlist) || !is_listobject(ofdlist) || - !is_listobject(efdlist) ) { - err_badarg(); - return 0; - } - - /* Convert lists to fd_sets, and get maximum fd number */ - if( (imax=list2set(ifdlist, &ifdset, rfd2obj)) < 0 ) - return 0; - if( (omax=list2set(ofdlist, &ofdset, wfd2obj)) < 0 ) - return 0; - if( (emax=list2set(efdlist, &efdset, efd2obj)) < 0 ) - return 0; - max = imax; - if ( omax > max ) max = omax; - if ( emax > max ) max = emax; - - BGN_SAVE - n = select(max, &ifdset, &ofdset, &efdset, tvp); - END_SAVE - - if ( n < 0 ) { - err_errno(SelectError); - return 0; - } - - if ( n == 0 ) - imax = omax = emax = 0; /* Speedup hack */ - - ifdlist = set2list(&ifdset, imax, rfd2obj); - ofdlist = set2list(&ofdset, omax, wfd2obj); - efdlist = set2list(&efdset, emax, efd2obj); - ret = mkvalue("OOO", ifdlist, ofdlist, efdlist); - XDECREF(ifdlist); - XDECREF(ofdlist); - XDECREF(efdlist); - return ret; -} - - -static struct methodlist select_methods[] = { - { "select", select_select }, - { 0, 0 }, -}; - - -void -initselect() -{ - object *m, *d; - m = initmodule("select", select_methods); - d = getmoduledict(m); - SelectError = newstringobject("select.error"); - if ( SelectError == NULL || dictinsert(d, "error", SelectError) ) - fatal("Cannot define select.error"); -} diff --git a/Modules/sgimodule.c b/Modules/sgimodule.c deleted file mode 100644 index f19c511a8a..0000000000 --- a/Modules/sgimodule.c +++ /dev/null @@ -1,88 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* SGI module -- random SGI-specific things */ - -#include "allobjects.h" -#include "modsupport.h" -#include "ceval.h" - -#include <errno.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <unistd.h> -#include <fcntl.h> - -static object * -sgi_nap(self, args) - object *self; - object *args; -{ - long ticks; - if (!getargs(args, "l", &ticks)) - return NULL; - BGN_SAVE - sginap(ticks); - END_SAVE - INCREF(None); - return None; -} - -extern char *_getpty(int *, int, mode_t, int); - -static object * -sgi__getpty(self, args) - object *self; - object *args; -{ - int oflag; - int mode; - int nofork; - char *name; - int fildes; - if (!getargs(args, "(iii)", &oflag, &mode, &nofork)) - return NULL; - errno = 0; - name = _getpty(&fildes, oflag, (mode_t)mode, nofork); - if (name == NULL) { - err_errno(IOError); - return NULL; - } - return mkvalue("(si)", name, fildes); -} - -static struct methodlist sgi_methods[] = { - {"nap", sgi_nap}, - {"_getpty", sgi__getpty}, - {NULL, NULL} /* sentinel */ -}; - - -void -initsgi() -{ - initmodule("sgi", sgi_methods); -} - -static int dummy; /* $%#@!& dl wants at least a byte of bss */ diff --git a/Modules/signalmodule.c b/Modules/signalmodule.c deleted file mode 100644 index c310024307..0000000000 --- a/Modules/signalmodule.c +++ /dev/null @@ -1,493 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Signal module -- many thanks to Lance Ellinghaus */ - -#include "Python.h" -#include "intrcheck.h" - -#include <signal.h> - -#ifndef SIG_ERR -#define SIG_ERR ((RETSIGTYPE (*)())-1) -#endif - -#ifndef NSIG -#define NSIG (_SIGMAX + 1) /* For QNX */ -#endif - - -/* - NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS - - When threads are supported, we want the following semantics: - - - only the main thread can set a signal handler - - any thread can get a signal handler - - signals are only delivered to the main thread - - I.e. we don't support "synchronous signals" like SIGFPE (catching - this doesn't make much sense in Python anyway) nor do we support - signals as a means of inter-thread communication, since not all - thread implementations support that (at least our thread library - doesn't). - - We still have the problem that in some implementations signals - generated by the keyboard (e.g. SIGINT) are delivered to all - threads (e.g. SGI), while in others (e.g. Solaris) such signals are - delivered to one random thread (an intermediate possibility would - be to deliver it to the main thread -- POSIX?). For now, we have - a working implementation that works in all three cases -- the - handler ignores signals if getpid() isn't the same as in the main - thread. XXX This is a hack. - -*/ - -#ifdef WITH_THREAD -#include "thread.h" -static long main_thread; -static pid_t main_pid; -#endif - -struct PySignal_SignalArrayStruct { - int tripped; - PyObject *func; -}; - -static struct PySignal_SignalArrayStruct PySignal_SignalHandlerArray[NSIG]; -static int PySignal_IsTripped = 0; /* Speed up sigcheck() when none tripped */ - -static PyObject *PySignal_SignalDefaultHandler; -static PyObject *PySignal_SignalIgnoreHandler; -static PyObject *PySignal_DefaultIntHandler; - -static PyObject * -PySignal_CDefaultIntHandler(self, arg) - PyObject *self; - PyObject *arg; -{ - PyErr_SetNone(PyExc_KeyboardInterrupt); - return (PyObject *)NULL; -} - -void -PyErr_SetInterrupt() -{ - PySignal_IsTripped++; - PySignal_SignalHandlerArray[SIGINT].tripped = 1; -} - -static RETSIGTYPE -PySignal_Handler(sig_num) - int sig_num; -{ -#ifdef WITH_THREAD - /* See NOTES section above */ - if (getpid() == main_pid) { -#endif - PySignal_IsTripped++; - PySignal_SignalHandlerArray[sig_num].tripped = 1; -#ifdef WITH_THREAD - } -#endif -#ifdef SIGCHLD - if (sig_num == SIGCHLD) { - /* To avoid infinite recursion, this signal remains - reset until explicit re-instated. - Don't clear the 'func' field as it is our pointer - to the Python handler... */ - return; - } -#endif - (void *)signal(sig_num, &PySignal_Handler); -} - - -#ifndef DONT_HAVE_SIG_ALARM -static PyObject * -PySignal_Alarm(self, args) - PyObject *self; /* Not used */ - PyObject *args; -{ - int t; - if (!PyArg_Parse(args, "i", &t)) - return (PyObject *)NULL; - /* alarm() returns the number of seconds remaining */ - return PyInt_FromLong(alarm(t)); -} -#endif - -#ifndef DONT_HAVE_SIG_PAUSE -static PyObject * -PySignal_Pause(self, args) - PyObject *self; /* Not used */ - PyObject *args; -{ - if (!PyArg_NoArgs(args)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pause(); - Py_END_ALLOW_THREADS - Py_INCREF(Py_None); - return Py_None; -} -#endif - -static PyObject * -PySignal_Signal(self, args) - PyObject *self; /* Not used */ - PyObject *args; -{ - PyObject *obj; - int sig_num; - PyObject *old_handler; - RETSIGTYPE (*func)(); - if (!PyArg_Parse(args, "(iO)", &sig_num, &obj)) - return (PyObject *)NULL; -#ifdef WITH_THREAD - if (get_thread_ident() != main_thread) { - PyErr_SetString(PyExc_ValueError, - "signal only works in main thread"); - return (PyObject *)NULL; - } -#endif - if (sig_num < 1 || sig_num >= NSIG) { - PyErr_SetString(PyExc_ValueError, - "signal number out of range"); - return (PyObject *)NULL; - } - if (obj == PySignal_SignalIgnoreHandler) - func = SIG_IGN; - else if (obj == PySignal_SignalDefaultHandler) - func = SIG_DFL; - else if (!PyCallable_Check(obj)) { - PyErr_SetString(PyExc_TypeError, -"signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object"); - return (PyObject *)NULL; - } - else - func = PySignal_Handler; - if (signal(sig_num, func) == SIG_ERR) { - PyErr_SetFromErrno(PyExc_RuntimeError); - return (PyObject *)NULL; - } - old_handler = PySignal_SignalHandlerArray[sig_num].func; - PySignal_SignalHandlerArray[sig_num].tripped = 0; - Py_INCREF(obj); - PySignal_SignalHandlerArray[sig_num].func = obj; - return old_handler; -} - -static PyObject * -PySignal_GetSignal(self, args) - PyObject *self; /* Not used */ - PyObject *args; -{ - int sig_num; - PyObject *old_handler; - if (!PyArg_Parse(args, "i", &sig_num)) - return (PyObject *)NULL; - if (sig_num < 1 || sig_num >= NSIG) { - PyErr_SetString(PyExc_ValueError, - "signal number out of range"); - return (PyObject *)NULL; - } - old_handler = PySignal_SignalHandlerArray[sig_num].func; - Py_INCREF(old_handler); - return old_handler; -} - - -/* List of functions defined in the module */ - -static PyMethodDef PySignal_methods[] = { -#ifndef DONT_HAVE_SIG_ALARM - {"alarm", PySignal_Alarm}, -#endif - {"signal", PySignal_Signal}, - {"getsignal", PySignal_GetSignal}, -#ifndef DONT_HAVE_SIG_PAUSE - {"pause", PySignal_Pause}, -#endif - {"default_int_handler", PySignal_CDefaultIntHandler}, - {NULL, NULL} /* sentinel */ -}; - -void -initsignal() -{ - PyObject *m, *d, *x; - int i; - -#ifdef WITH_THREAD - main_thread = get_thread_ident(); - main_pid = getpid(); -#endif - - /* Create the module and add the functions */ - m = Py_InitModule("signal", PySignal_methods); - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - - PySignal_SignalDefaultHandler = PyInt_FromLong((long)SIG_DFL); - PyDict_SetItemString(d, "SIG_DFL", PySignal_SignalDefaultHandler); - PySignal_SignalIgnoreHandler = PyInt_FromLong((long)SIG_IGN); - PyDict_SetItemString(d, "SIG_IGN", PySignal_SignalIgnoreHandler); - PyDict_SetItemString(d, "NSIG", PyInt_FromLong((long)NSIG)); - PySignal_DefaultIntHandler = - PyDict_GetItemString(d, "default_int_handler"); - - PySignal_SignalHandlerArray[0].tripped = 0; - for (i = 1; i < NSIG; i++) { - RETSIGTYPE (*t)(); -#ifdef HAVE_SIGACTION - struct sigaction act; - sigaction(i, 0, &act); - t = act.sa_handler; -#else - t = signal(i, SIG_IGN); - signal(i, t); -#endif - PySignal_SignalHandlerArray[i].tripped = 0; - if (t == SIG_DFL) - PySignal_SignalHandlerArray[i].func = - PySignal_SignalDefaultHandler; - else if (t == SIG_IGN) - PySignal_SignalHandlerArray[i].func = - PySignal_SignalIgnoreHandler; - else - PySignal_SignalHandlerArray[i].func = - Py_None; /* None of our business */ - Py_INCREF(PySignal_SignalHandlerArray[i].func); - } - if (PySignal_SignalHandlerArray[SIGINT].func == - PySignal_SignalDefaultHandler) { - /* Install default int handler */ - Py_DECREF(PySignal_SignalHandlerArray[SIGINT].func); - PySignal_SignalHandlerArray[SIGINT].func = - PySignal_DefaultIntHandler; - Py_INCREF(PySignal_DefaultIntHandler); - signal(SIGINT, &PySignal_Handler); - } - -#ifdef SIGHUP - x = PyInt_FromLong(SIGHUP); - PyDict_SetItemString(d, "SIGHUP", x); -#endif -#ifdef SIGINT - x = PyInt_FromLong(SIGINT); - PyDict_SetItemString(d, "SIGINT", x); -#endif -#ifdef SIGQUIT - x = PyInt_FromLong(SIGQUIT); - PyDict_SetItemString(d, "SIGQUIT", x); -#endif -#ifdef SIGILL - x = PyInt_FromLong(SIGILL); - PyDict_SetItemString(d, "SIGILL", x); -#endif -#ifdef SIGTRAP - x = PyInt_FromLong(SIGTRAP); - PyDict_SetItemString(d, "SIGTRAP", x); -#endif -#ifdef SIGIOT - x = PyInt_FromLong(SIGIOT); - PyDict_SetItemString(d, "SIGIOT", x); -#endif -#ifdef SIGABRT - x = PyInt_FromLong(SIGABRT); - PyDict_SetItemString(d, "SIGABRT", x); -#endif -#ifdef SIGEMT - x = PyInt_FromLong(SIGEMT); - PyDict_SetItemString(d, "SIGEMT", x); -#endif -#ifdef SIGFPE - x = PyInt_FromLong(SIGFPE); - PyDict_SetItemString(d, "SIGFPE", x); -#endif -#ifdef SIGKILL - x = PyInt_FromLong(SIGKILL); - PyDict_SetItemString(d, "SIGKILL", x); -#endif -#ifdef SIGBUS - x = PyInt_FromLong(SIGBUS); - PyDict_SetItemString(d, "SIGBUS", x); -#endif -#ifdef SIGSEGV - x = PyInt_FromLong(SIGSEGV); - PyDict_SetItemString(d, "SIGSEGV", x); -#endif -#ifdef SIGSYS - x = PyInt_FromLong(SIGSYS); - PyDict_SetItemString(d, "SIGSYS", x); -#endif -#ifdef SIGPIPE - x = PyInt_FromLong(SIGPIPE); - PyDict_SetItemString(d, "SIGPIPE", x); -#endif -#ifdef SIGALRM - x = PyInt_FromLong(SIGALRM); - PyDict_SetItemString(d, "SIGALRM", x); -#endif -#ifdef SIGTERM - x = PyInt_FromLong(SIGTERM); - PyDict_SetItemString(d, "SIGTERM", x); -#endif -#ifdef SIGUSR1 - x = PyInt_FromLong(SIGUSR1); - PyDict_SetItemString(d, "SIGUSR1", x); -#endif -#ifdef SIGUSR2 - x = PyInt_FromLong(SIGUSR2); - PyDict_SetItemString(d, "SIGUSR2", x); -#endif -#ifdef SIGCLD - x = PyInt_FromLong(SIGCLD); - PyDict_SetItemString(d, "SIGCLD", x); -#endif -#ifdef SIGCHLD - x = PyInt_FromLong(SIGCHLD); - PyDict_SetItemString(d, "SIGCHLD", x); -#endif -#ifdef SIGPWR - x = PyInt_FromLong(SIGPWR); - PyDict_SetItemString(d, "SIGPWR", x); -#endif -#ifdef SIGIO - x = PyInt_FromLong(SIGIO); - PyDict_SetItemString(d, "SIGIO", x); -#endif -#ifdef SIGURG - x = PyInt_FromLong(SIGURG); - PyDict_SetItemString(d, "SIGURG", x); -#endif -#ifdef SIGWINCH - x = PyInt_FromLong(SIGWINCH); - PyDict_SetItemString(d, "SIGWINCH", x); -#endif -#ifdef SIGPOLL - x = PyInt_FromLong(SIGPOLL); - PyDict_SetItemString(d, "SIGPOLL", x); -#endif -#ifdef SIGSTOP - x = PyInt_FromLong(SIGSTOP); - PyDict_SetItemString(d, "SIGSTOP", x); -#endif -#ifdef SIGTSTP - x = PyInt_FromLong(SIGTSTP); - PyDict_SetItemString(d, "SIGTSTP", x); -#endif -#ifdef SIGCONT - x = PyInt_FromLong(SIGCONT); - PyDict_SetItemString(d, "SIGCONT", x); -#endif -#ifdef SIGTTIN - x = PyInt_FromLong(SIGTTIN); - PyDict_SetItemString(d, "SIGTTIN", x); -#endif -#ifdef SIGTTOU - x = PyInt_FromLong(SIGTTOU); - PyDict_SetItemString(d, "SIGTTOU", x); -#endif -#ifdef SIGVTALRM - x = PyInt_FromLong(SIGVTALRM); - PyDict_SetItemString(d, "SIGVTALRM", x); -#endif -#ifdef SIGPROF - x = PyInt_FromLong(SIGPROF); - PyDict_SetItemString(d, "SIGPROF", x); -#endif -#ifdef SIGCPU - x = PyInt_FromLong(SIGCPU); - PyDict_SetItemString(d, "SIGCPU", x); -#endif -#ifdef SIGFSZ - x = PyInt_FromLong(SIGFSZ); - PyDict_SetItemString(d, "SIGFSZ", x); -#endif - /* Check for errors */ - if (PyErr_Occurred()) - Py_FatalError("can't initialize module signal"); -} - -int -PyErr_CheckSignals() -{ - int i; - PyObject *f; - if (!PySignal_IsTripped) - return 0; -#ifdef WITH_THREAD - if (get_thread_ident() != main_thread) - return 0; -#endif - f = PyEval_GetFrame(); - if (f == (PyObject *)NULL) - f = Py_None; - for (i = 1; i < NSIG; i++) { - if (PySignal_SignalHandlerArray[i].tripped) { - PyObject *arglist, *result; - PySignal_SignalHandlerArray[i].tripped = 0; - arglist = Py_BuildValue("(iO)", i, f); - if (arglist == (PyObject *)NULL) - result = (PyObject *)NULL; - else { - result = PyEval_CallObject( - PySignal_SignalHandlerArray[i].func, arglist); - Py_DECREF(arglist); - } - if (result == (PyObject *)NULL) { - return 1; - } else { - Py_DECREF(result); - } - } - } - PySignal_IsTripped = 0; - return 0; -} - -/* Replacement for intrcheck.c functionality */ - -void -PyOS_InitInterrupts () -{ - initsignal(); -} - -int -PyOS_InterruptOccurred () -{ - if (PySignal_SignalHandlerArray[SIGINT].tripped) { -#ifdef WITH_THREAD - if (get_thread_ident() != main_thread) - return 0; -#endif - PySignal_SignalHandlerArray[SIGINT].tripped = 0; - return 1; - } - return 0; -} diff --git a/Modules/socketmodule.c b/Modules/socketmodule.c deleted file mode 100644 index 5b971f81e6..0000000000 --- a/Modules/socketmodule.c +++ /dev/null @@ -1,1537 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Socket module */ - -/* -This module provides an interface to Berkeley socket IPC. - -Limitations: - -- only AF_INET and AF_UNIX address families are supported -- no read/write operations (use send/recv or makefile instead) - -Module interface: - -- socket.error: exception raised for socket specific errors -- socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd') -- socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...]) -- socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com') -- socket.getservbyname(servicename, protocolname) --> port number -- socket.socket(family, type [, proto]) --> new socket object -- socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h> -- an Internet socket address is a pair (hostname, port) - where hostname can be anything recognized by gethostbyname() - (including the dd.dd.dd.dd notation) and port is in host byte order -- where a hostname is returned, the dd.dd.dd.dd notation is used -- a UNIX domain socket address is a string specifying the pathname - -Socket methods: - -- s.accept() --> new socket object, sockaddr -- s.bind(sockaddr) --> None -- s.close() --> None -- s.connect(sockaddr) --> None -- s.fileno() --> file descriptor -- s.getpeername() --> sockaddr -- s.getsockname() --> sockaddr -- s.getsockopt(level, optname[, buflen]) --> int or string -- s.listen(backlog) --> None -- s.makefile([mode[, bufsize]]) --> file object -- s.recv(buflen [,flags]) --> string -- s.recvfrom(buflen [,flags]) --> string, sockaddr -- s.send(string [,flags]) --> nbytes -- s.sendto(string, [flags,] sockaddr) --> nbytes -- s.setblocking(0 | 1) --> None -- s.setsockopt(level, optname, value) --> None -- s.shutdown(how) --> None -- repr(s) --> "<socket object, fd=%d, family=%d, type=%d, protocol=%d>" - -*/ - -#include "Python.h" - -#include <sys/types.h> -#include "mytime.h" - -#include <signal.h> -#ifndef _MSC_VER -#include <netdb.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <fcntl.h> -#else -#include <winsock.h> -#include <fcntl.h> -#endif -#ifdef HAVE_SYS_UN_H -#include <sys/un.h> -#else -#undef AF_UNIX -#endif - -#ifndef O_NDELAY -#define O_NDELAY O_NONBLOCK /* For QNX only? */ -#endif - -#ifdef USE_GUSI -/* fdopen() isn't declared in stdio.h (sigh) */ -#include <GUSI.h> -#endif - - -/* Here we have some hacks to choose between K&R or ANSI style function - definitions. For NT to build this as an extension module (ie, DLL) - it must be compiled by the C++ compiler, as it takes the address of - a static data item exported from the main Python DLL. -*/ -#ifdef NT -/* seem to be a few differences in the API */ -#define close closesocket -#define NO_DUP /* Define for NT 3.1, Win3.1 and Win95, Undefine for NT3.5 */ -#define FORCE_ANSI_FUNC_DEFS -#endif - -#ifdef FORCE_ANSI_FUNC_DEFS -#define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name ) \ -fnname( arg1type arg1name ) - -#define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \ -fnname( arg1type arg1name, arg2type arg2name ) - -#define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name ) \ -fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name ) - -#define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name, arg4type, arg4name ) \ -fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name, arg4type arg4name ) - -#else /* !FORCE_ANSI_FN_DEFS */ -#define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name ) \ -fnname( arg1name ) \ - arg1type arg1name; - -#define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \ -fnname( arg1name, arg2name ) \ - arg1type arg1name; \ - arg2type arg2name; - -#define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name ) \ -fnname( arg1name, arg2name, arg3name ) \ - arg1type arg1name; \ - arg2type arg2name; \ - arg3type arg3name; - -#define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name, arg4type, arg4name ) \ -fnname( arg1name, arg2name, arg3name, arg4name ) \ - arg1type arg1name; \ - arg2type arg2name; \ - arg3type arg3name; \ - arg4type arg4name; - -#endif /* !FORCE_ANSI_FN_DEFS */ - -/* Global variable holding the exception type for errors detected - by this module (but not argument type or memory errors, etc.). */ - -static PyObject *PySocket_Error; - - -/* Convenience function to raise an error according to errno - and return a NULL pointer from a function. */ - -static PyObject * -PySocket_Err() -{ -#ifdef NT - if (WSAGetLastError()) { - PyObject *v; - v = Py_BuildValue("(is)", WSAGetLastError(), "winsock error"); - if (v != NULL) { - PyErr_SetObject(PySocket_Error, v); - Py_DECREF(v); - } - return NULL; - } - else -#endif - return PyErr_SetFromErrno(PySocket_Error); -} - - -/* The object holding a socket. It holds some extra information, - like the address family, which is used to decode socket address - arguments properly. */ - -typedef struct { - PyObject_HEAD - int sock_fd; /* Socket file descriptor */ - int sock_family; /* Address family, e.g., AF_INET */ - int sock_type; /* Socket type, e.g., SOCK_STREAM */ - int sock_proto; /* Protocol type, usually 0 */ - union sock_addr { - struct sockaddr_in in; -#ifdef AF_UNIX - struct sockaddr_un un; -#endif - } sock_addr; -} PySocketSockObject; - - -/* A forward reference to the Socktype type object. - The Socktype variable contains pointers to various functions, - some of which call newsockobject(), which uses Socktype, so - there has to be a circular reference. */ - -staticforward PyTypeObject PySocketSock_Type; - - -/* Create a new socket object. - This just creates the object and initializes it. - If the creation fails, return NULL and set an exception (implicit - in NEWOBJ()). */ - -static PySocketSockObject * -BUILD_FUNC_DEF_4(PySocketSock_New,int,fd, int,family, int,type, int,proto) -{ - PySocketSockObject *s; - PySocketSock_Type.ob_type = &PyType_Type; - s = PyObject_NEW(PySocketSockObject, &PySocketSock_Type); - if (s != NULL) { - s->sock_fd = fd; - s->sock_family = family; - s->sock_type = type; - s->sock_proto = proto; - } - return s; -} - - -/* Convert a string specifying a host name or one of a few symbolic - names to a numeric IP address. This usually calls gethostbyname() - to do the work; the names "" and "<broadcast>" are special. - Return the length (should always be 4 bytes), or negative if - an error occurred; then an exception is raised. */ - -static int -BUILD_FUNC_DEF_2(setipaddr, char*,name, struct sockaddr_in *,addr_ret) -{ - struct hostent *hp; - int d1, d2, d3, d4; - char ch; -#ifdef HAVE_GETHOSTBYNAME_R - struct hostent hp_allocated; - char buf[1001]; - int buf_len = (sizeof buf) - 1; - int errnop; -#endif /* HAVE_GETHOSTBYNAME_R */ - - if (name[0] == '\0') { - addr_ret->sin_addr.s_addr = INADDR_ANY; - return 4; - } - if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) { - addr_ret->sin_addr.s_addr = INADDR_BROADCAST; - return 4; - } - if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 && - 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 && - 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) { - addr_ret->sin_addr.s_addr = htonl( - ((long) d1 << 24) | ((long) d2 << 16) | - ((long) d3 << 8) | ((long) d4 << 0)); - return 4; - } -#ifdef HAVE_GETHOSTBYNAME_R - Py_BEGIN_ALLOW_THREADS - hp = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop); - Py_END_ALLOW_THREADS -#else /* not HAVE_GETHOSTBYNAME_R */ - hp = gethostbyname(name); -#endif /* HAVE_GETHOSTBYNAME_R */ - - if (hp == NULL) { -#ifdef HAVE_HSTRERROR - /* Let's get real error message to return */ - extern int h_errno; - PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno)); -#else - PyErr_SetString(PySocket_Error, "host not found"); -#endif - return -1; - } - memcpy((char *) &addr_ret->sin_addr, hp->h_addr, hp->h_length); - return hp->h_length; -} - - -/* Create a string object representing an IP address. - This is always a string of the form 'dd.dd.dd.dd' (with variable - size numbers). */ - -static PyObject * -BUILD_FUNC_DEF_1(makeipaddr, struct sockaddr_in *,addr) -{ - long x = ntohl(addr->sin_addr.s_addr); - char buf[100]; - sprintf(buf, "%d.%d.%d.%d", - (int) (x>>24) & 0xff, (int) (x>>16) & 0xff, - (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff); - return PyString_FromString(buf); -} - - -/* Create an object representing the given socket address, - suitable for passing it back to bind(), connect() etc. - The family field of the sockaddr structure is inspected - to determine what kind of address it really is. */ - -/*ARGSUSED*/ -static PyObject * -BUILD_FUNC_DEF_2(makesockaddr,struct sockaddr *,addr, int,addrlen) -{ - if (addrlen == 0) { - /* No address -- may be recvfrom() from known socket */ - Py_INCREF(Py_None); - return Py_None; - } - - switch (addr->sa_family) { - - case AF_INET: - { - struct sockaddr_in *a = (struct sockaddr_in *) addr; - PyObject *addr = makeipaddr(a); - PyObject *ret = Py_BuildValue("Oi", addr, ntohs(a->sin_port)); - Py_XDECREF(addr); - return ret; - } - -#ifdef AF_UNIX - case AF_UNIX: - { - struct sockaddr_un *a = (struct sockaddr_un *) addr; - return PyString_FromString(a->sun_path); - } -#endif /* AF_UNIX */ - - /* More cases here... */ - - default: - PyErr_SetString(PySocket_Error, "return unknown socket address type"); - return NULL; - - } -} - - -/* Parse a socket address argument according to the socket object's - address family. Return 1 if the address was in the proper format, - 0 of not. The address is returned through addr_ret, its length - through len_ret. */ - -static int -BUILD_FUNC_DEF_4( -getsockaddrarg,PySocketSockObject *,s, PyObject *,args, struct sockaddr **,addr_ret, int *,len_ret) -{ - switch (s->sock_family) { - -#ifdef AF_UNIX - case AF_UNIX: - { - struct sockaddr_un* addr; - char *path; - int len; - addr = (struct sockaddr_un* )&(s->sock_addr).un; - if (!PyArg_Parse(args, "s#", &path, &len)) - return 0; - if (len > sizeof addr->sun_path) { - PyErr_SetString(PySocket_Error, "AF_UNIX path too long"); - return 0; - } - addr->sun_family = AF_UNIX; - memcpy(addr->sun_path, path, len); - addr->sun_path[len] = 0; - *addr_ret = (struct sockaddr *) addr; - *len_ret = len + sizeof addr->sun_family; - return 1; - } -#endif /* AF_UNIX */ - - case AF_INET: - { - struct sockaddr_in* addr; - char *host; - int port; - addr=(struct sockaddr_in*)&(s->sock_addr).in; - if (!PyArg_Parse(args, "(si)", &host, &port)) - return 0; - if (setipaddr(host, addr) < 0) - return 0; - addr->sin_family = AF_INET; - addr->sin_port = htons(port); - *addr_ret = (struct sockaddr *) addr; - *len_ret = sizeof *addr; - return 1; - } - - /* More cases here... */ - - default: - PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family"); - return 0; - - } -} - - -/* Get the address length according to the socket object's address family. - Return 1 if the family is known, 0 otherwise. The length is returned - through len_ret. */ - -static int -BUILD_FUNC_DEF_2(getsockaddrlen,PySocketSockObject *,s, int *,len_ret) -{ - switch (s->sock_family) { - -#ifdef AF_UNIX - case AF_UNIX: - { - *len_ret = sizeof (struct sockaddr_un); - return 1; - } -#endif /* AF_UNIX */ - - case AF_INET: - { - *len_ret = sizeof (struct sockaddr_in); - return 1; - } - - /* More cases here... */ - - default: - PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family"); - return 0; - - } -} - - -/* s.accept() method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_accept,PySocketSockObject *,s, PyObject *,args) -{ - char addrbuf[256]; - int addrlen, newfd; - PyObject *sock, *addr, *res; - if (!PyArg_NoArgs(args)) - return NULL; - if (!getsockaddrlen(s, &addrlen)) - return NULL; - Py_BEGIN_ALLOW_THREADS - newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen); - Py_END_ALLOW_THREADS - if (newfd < 0) - return PySocket_Err(); - /* Create the new object with unspecified family, - to avoid calls to bind() etc. on it. */ - sock = (PyObject *) PySocketSock_New(newfd, - s->sock_family, - s->sock_type, - s->sock_proto); - if (sock == NULL) - close(newfd); - addr = makesockaddr((struct sockaddr *) addrbuf, addrlen); - res = Py_BuildValue("OO", sock, addr); - Py_XDECREF(sock); - Py_XDECREF(addr); - return res; -} - - -#if 0 -/* s.allowbroadcast() method */ -/* XXX obsolete -- will disappear in next release */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_allowbroadcast,PySocketSockObject *,s, PyObject *,args) -{ - int flag; - int res; - if (!PyArg_Parse(args, "i", &flag)) - return NULL; - res = setsockopt(s->sock_fd, SOL_SOCKET, SO_BROADCAST, - (ANY *)&flag, sizeof flag); - if (res < 0) - return PySocket_Err(); - Py_INCREF(Py_None); - return Py_None; -} -#endif - - -/* s.setblocking(1 | 0) method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_setblocking,PySocketSockObject*,s,PyObject*,args) -{ - int block; - int delay_flag; - if (!PyArg_GetInt(args, &block)) - return NULL; - Py_BEGIN_ALLOW_THREADS -#ifndef _MSC_VER - delay_flag = fcntl (s->sock_fd, F_GETFL, 0); - if (block) - delay_flag &= (~O_NDELAY); - else - delay_flag |= O_NDELAY; - fcntl (s->sock_fd, F_SETFL, delay_flag); -#else - block = !block; - ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block); -#endif - Py_END_ALLOW_THREADS - - Py_INCREF(Py_None); - return Py_None; -} - - -/* s.setsockopt() method. - With an integer third argument, sets an integer option. - With a string third argument, sets an option from a buffer; - use optional built-in module 'struct' to encode the string. */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_setsockopt,PySocketSockObject *,s, PyObject *,args) -{ - int level; - int optname; - int res; - char *buf; - int buflen; - int flag; - - if (PyArg_Parse(args, "(iii)", &level, &optname, &flag)) { - buf = (char *) &flag; - buflen = sizeof flag; - } - else { - PyErr_Clear(); - if (!PyArg_Parse(args, "(iis#)", &level, &optname, &buf, &buflen)) - return NULL; - } - res = setsockopt(s->sock_fd, level, optname, (ANY *)buf, buflen); - if (res < 0) - return PySocket_Err(); - Py_INCREF(Py_None); - return Py_None; -} - - -/* s.getsockopt() method. - With two arguments, retrieves an integer option. - With a third integer argument, retrieves a string buffer of that size; - use optional built-in module 'struct' to decode the string. */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_getsockopt,PySocketSockObject *,s, PyObject *,args) -{ - int level; - int optname; - int res; - PyObject *buf; - int buflen; - - if (PyArg_Parse(args, "(ii)", &level, &optname)) { - int flag = 0; - int flagsize = sizeof flag; - res = getsockopt(s->sock_fd, level, optname, - (ANY *)&flag, &flagsize); - if (res < 0) - return PySocket_Err(); - return PyInt_FromLong(flag); - } - PyErr_Clear(); - if (!PyArg_Parse(args, "(iii)", &level, &optname, &buflen)) - return NULL; - if (buflen <= 0 || buflen > 1024) { - PyErr_SetString(PySocket_Error, "getsockopt buflen out of range"); - return NULL; - } - buf = PyString_FromStringAndSize((char *)NULL, buflen); - if (buf == NULL) - return NULL; - res = getsockopt(s->sock_fd, level, optname, - (ANY *)PyString_AsString(buf), &buflen); - if (res < 0) { - Py_DECREF(buf); - return PySocket_Err(); - } - _PyString_Resize(&buf, buflen); - return buf; -} - - -/* s.bind(sockaddr) method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_bind,PySocketSockObject *,s, PyObject *,args) -{ - struct sockaddr *addr; - int addrlen; - int res; - if (!getsockaddrarg(s, args, &addr, &addrlen)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = bind(s->sock_fd, addr, addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return PySocket_Err(); - Py_INCREF(Py_None); - return Py_None; -} - - -/* s.close() method. - Set the file descriptor to -1 so operations tried subsequently - will surely fail. */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_close,PySocketSockObject *,s, PyObject *,args) -{ - if (!PyArg_NoArgs(args)) - return NULL; - Py_BEGIN_ALLOW_THREADS - (void) close(s->sock_fd); - Py_END_ALLOW_THREADS - s->sock_fd = -1; - Py_INCREF(Py_None); - return Py_None; -} - - -/* s.connect(sockaddr) method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_connect,PySocketSockObject *,s, PyObject *,args) -{ - struct sockaddr *addr; - int addrlen; - int res; - if (!getsockaddrarg(s, args, &addr, &addrlen)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = connect(s->sock_fd, addr, addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return PySocket_Err(); - Py_INCREF(Py_None); - return Py_None; -} - - -/* s.fileno() method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_fileno,PySocketSockObject *,s, PyObject *,args) -{ - if (!PyArg_NoArgs(args)) - return NULL; - return PyInt_FromLong((long) s->sock_fd); -} - - -/* s.getsockname() method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_getsockname,PySocketSockObject *,s, PyObject *,args) -{ - char addrbuf[256]; - int addrlen, res; - if (!PyArg_NoArgs(args)) - return NULL; - if (!getsockaddrlen(s, &addrlen)) - return NULL; - memset(addrbuf, 0, addrlen); - Py_BEGIN_ALLOW_THREADS - res = getsockname(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return PySocket_Err(); - return makesockaddr((struct sockaddr *) addrbuf, addrlen); -} - - -#ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */ -/* s.getpeername() method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_getpeername,PySocketSockObject *,s, PyObject *,args) -{ - char addrbuf[256]; - int addrlen, res; - if (!PyArg_NoArgs(args)) - return NULL; - if (!getsockaddrlen(s, &addrlen)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return PySocket_Err(); - return makesockaddr((struct sockaddr *) addrbuf, addrlen); -} -#endif /* HAVE_GETPEERNAME */ - - -/* s.listen(n) method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_listen,PySocketSockObject *,s, PyObject *,args) -{ - int backlog; - int res; - if (!PyArg_GetInt(args, &backlog)) - return NULL; - Py_BEGIN_ALLOW_THREADS - if (backlog < 1) - backlog = 1; - res = listen(s->sock_fd, backlog); - Py_END_ALLOW_THREADS - if (res < 0) - return PySocket_Err(); - Py_INCREF(Py_None); - return Py_None; -} - -#ifndef NO_DUP -/* s.makefile(mode) method. - Create a new open file object referring to a dupped version of - the socket's file descriptor. (The dup() call is necessary so - that the open file and socket objects may be closed independent - of each other.) - The mode argument specifies 'r' or 'w' passed to fdopen(). */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_makefile,PySocketSockObject *,s, PyObject *,args) -{ - extern int fclose Py_PROTO((FILE *)); - char *mode = "r"; - int bufsize = -1; - int fd; - FILE *fp; - PyObject *f; - - if (!PyArg_ParseTuple(args, "|si", &mode, &bufsize)) - return NULL; -#ifdef NT - if ( ((fd = _open_osfhandle( s->sock_fd, _O_BINARY )) < 0) || - ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL)) { -#else - if ((fd = dup(s->sock_fd)) < 0 || - (fp = fdopen(fd, mode)) == NULL) { -#endif - if (fd >= 0) - close(fd); - return PySocket_Err(); - } - f = PyFile_FromFile(fp, "<socket>", mode, fclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; -} -#endif /* NO_DUP */ - -/* s.recv(nbytes [,flags]) method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_recv,PySocketSockObject *,s, PyObject *,args) -{ - int len, n, flags; - PyObject *buf; - flags = 0; - if (!PyArg_Parse(args, "i", &len)) { - PyErr_Clear(); - if (!PyArg_Parse(args, "(ii)", &len, &flags)) - return NULL; - } - buf = PyString_FromStringAndSize((char *) 0, len); - if (buf == NULL) - return NULL; - Py_BEGIN_ALLOW_THREADS - n = recv(s->sock_fd, PyString_AsString(buf), len, flags); - Py_END_ALLOW_THREADS - if (n < 0) { - Py_DECREF(buf); - return PySocket_Err(); - } - if (_PyString_Resize(&buf, n) < 0) - return NULL; - return buf; -} - - -/* s.recvfrom(nbytes [,flags]) method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_recvfrom,PySocketSockObject *,s, PyObject *,args) -{ - char addrbuf[256]; - PyObject *buf, *addr, *ret; - int addrlen, len, n, flags; - flags = 0; - if (!PyArg_Parse(args, "i", &len)) { - PyErr_Clear(); - if (!PyArg_Parse(args, "(ii)", &len, &flags)) - return NULL; - } - if (!getsockaddrlen(s, &addrlen)) - return NULL; - buf = PyString_FromStringAndSize((char *) 0, len); - if (buf == NULL) - return NULL; - Py_BEGIN_ALLOW_THREADS - n = recvfrom(s->sock_fd, PyString_AsString(buf), len, flags, -#ifndef NT - (ANY *)addrbuf, &addrlen); -#else - (struct sockaddr *)addrbuf, &addrlen); -#endif - Py_END_ALLOW_THREADS - if (n < 0) { - Py_DECREF(buf); - return PySocket_Err(); - } - if (_PyString_Resize(&buf, n) < 0) - return NULL; - addr = makesockaddr((struct sockaddr *)addrbuf, addrlen); - ret = Py_BuildValue("OO", buf, addr); - Py_XDECREF(addr); - Py_XDECREF(buf); - return ret; -} - - -/* s.send(data [,flags]) method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_send,PySocketSockObject *,s, PyObject *,args) -{ - char *buf; - int len, n, flags; - flags = 0; - if (!PyArg_Parse(args, "s#", &buf, &len)) { - PyErr_Clear(); - if (!PyArg_Parse(args, "(s#i)", &buf, &len, &flags)) - return NULL; - } - Py_BEGIN_ALLOW_THREADS - n = send(s->sock_fd, buf, len, flags); - Py_END_ALLOW_THREADS - if (n < 0) - return PySocket_Err(); - return PyInt_FromLong((long)n); -} - - -/* s.sendto(data, [flags,] sockaddr) method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_sendto,PySocketSockObject *,s, PyObject *,args) -{ - PyObject *addro; - char *buf; - struct sockaddr *addr; - int addrlen, len, n, flags; - flags = 0; - if (!PyArg_Parse(args, "(s#O)", &buf, &len, &addro)) { - PyErr_Clear(); - if (!PyArg_Parse(args, "(s#iO)", &buf, &len, &flags, &addro)) - return NULL; - } - if (!getsockaddrarg(s, addro, &addr, &addrlen)) - return NULL; - Py_BEGIN_ALLOW_THREADS - n = sendto(s->sock_fd, buf, len, flags, addr, addrlen); - Py_END_ALLOW_THREADS - if (n < 0) - return PySocket_Err(); - return PyInt_FromLong((long)n); -} - - -/* s.shutdown(how) method */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_shutdown,PySocketSockObject *,s, PyObject *,args) -{ - int how; - int res; - if (!PyArg_GetInt(args, &how)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = shutdown(s->sock_fd, how); - Py_END_ALLOW_THREADS - if (res < 0) - return PySocket_Err(); - Py_INCREF(Py_None); - return Py_None; -} - - -/* List of methods for socket objects */ - -static PyMethodDef PySocketSock_methods[] = { - {"accept", (PyCFunction)PySocketSock_accept}, -#if 0 - {"allowbroadcast", (PyCFunction)PySocketSock_allowbroadcast}, -#endif - {"setblocking", (PyCFunction)PySocketSock_setblocking}, - {"setsockopt", (PyCFunction)PySocketSock_setsockopt}, - {"getsockopt", (PyCFunction)PySocketSock_getsockopt}, - {"bind", (PyCFunction)PySocketSock_bind}, - {"close", (PyCFunction)PySocketSock_close}, - {"connect", (PyCFunction)PySocketSock_connect}, - {"fileno", (PyCFunction)PySocketSock_fileno}, - {"getsockname", (PyCFunction)PySocketSock_getsockname}, -#ifdef HAVE_GETPEERNAME - {"getpeername", (PyCFunction)PySocketSock_getpeername}, -#endif - {"listen", (PyCFunction)PySocketSock_listen}, -#ifndef NO_DUP - {"makefile", (PyCFunction)PySocketSock_makefile, 1}, -#endif - {"recv", (PyCFunction)PySocketSock_recv}, - {"recvfrom", (PyCFunction)PySocketSock_recvfrom}, - {"send", (PyCFunction)PySocketSock_send}, - {"sendto", (PyCFunction)PySocketSock_sendto}, - {"shutdown", (PyCFunction)PySocketSock_shutdown}, - {NULL, NULL} /* sentinel */ -}; - - -/* Deallocate a socket object in response to the last Py_DECREF(). - First close the file description. */ - -static void -BUILD_FUNC_DEF_1(PySocketSock_dealloc,PySocketSockObject *,s) -{ - (void) close(s->sock_fd); - PyMem_DEL(s); -} - - -/* Return a socket object's named attribute. */ - -static PyObject * -BUILD_FUNC_DEF_2(PySocketSock_getattr,PySocketSockObject *,s, char *,name) -{ - return Py_FindMethod(PySocketSock_methods, (PyObject *) s, name); -} - - -static PyObject * -BUILD_FUNC_DEF_1(PySocketSock_repr,PySocketSockObject *,s) -{ - char buf[512]; - sprintf(buf, - "<socket object, fd=%d, family=%d, type=%d, protocol=%d>", - s->sock_fd, s->sock_family, s->sock_type, s->sock_proto); - return PyString_FromString(buf); -} - - -/* Type object for socket objects. */ - -static PyTypeObject PySocketSock_Type = { - PyObject_HEAD_INIT(0) /* Must fill in type value later */ - 0, - "socket", - sizeof(PySocketSockObject), - 0, - (destructor)PySocketSock_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)PySocketSock_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - (reprfunc)PySocketSock_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ -}; - - -/* Python interface to gethostname(). */ - -/*ARGSUSED*/ -static PyObject * -BUILD_FUNC_DEF_2(PySocket_gethostname,PyObject *,self, PyObject *,args) -{ - char buf[1024]; - int res; - if (!PyArg_NoArgs(args)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = gethostname(buf, (int) sizeof buf - 1); - Py_END_ALLOW_THREADS - if (res < 0) - return PySocket_Err(); - buf[sizeof buf - 1] = '\0'; - return PyString_FromString(buf); -} - - -/* Python interface to gethostbyname(name). */ - -/*ARGSUSED*/ -static PyObject * -BUILD_FUNC_DEF_2(PySocket_gethostbyname,PyObject *,self, PyObject *,args) -{ - char *name; - struct sockaddr_in addrbuf; - if (!PyArg_Parse(args, "s", &name)) - return NULL; - if (setipaddr(name, &addrbuf) < 0) - return NULL; - return makeipaddr(&addrbuf); -} - -/* Python interface to gethostbyaddr(IP). */ - -/*ARGSUSED*/ -static PyObject * -BUILD_FUNC_DEF_2(PySocket_gethostbyaddr,PyObject *,self, PyObject *, args) -{ - struct sockaddr_in addr; - char *ip_num; - struct hostent *h; - char **pch; - PyObject *rtn_tuple = (PyObject *)NULL; - PyObject *name_list = (PyObject *)NULL; - PyObject *addr_list = (PyObject *)NULL; - PyObject *tmp; - - if (!PyArg_Parse(args, "s", &ip_num)) - return NULL; - if (setipaddr(ip_num, &addr) < 0) - return NULL; - h = gethostbyaddr((char *)&addr.sin_addr, - sizeof(addr.sin_addr), - AF_INET); - if (h == NULL) { -#ifdef HAVE_HSTRERROR - /* Let's get real error message to return */ - extern int h_errno; - PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno)); -#else - PyErr_SetString(PySocket_Error, "host not found"); -#endif - return NULL; - } - if ((name_list = PyList_New(0)) == NULL) - goto err; - if ((addr_list = PyList_New(0)) == NULL) - goto err; - for (pch = h->h_aliases; *pch != NULL; pch++) { - tmp = PyString_FromString(*pch); - if (tmp == NULL) - goto err; - PyList_Append(name_list, tmp); - Py_DECREF(tmp); - } - for (pch = h->h_addr_list; *pch != NULL; pch++) { - memcpy((char *) &addr.sin_addr, *pch, h->h_length); - tmp = makeipaddr(&addr); - if (tmp == NULL) - goto err; - PyList_Append(addr_list, tmp); - Py_DECREF(tmp); - } - rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list); - err: - Py_XDECREF(name_list); - Py_XDECREF(addr_list); - return rtn_tuple; -} - - -/* Python interface to getservbyname(name). - This only returns the port number, since the other info is already - known or not useful (like the list of aliases). */ - -/*ARGSUSED*/ -static PyObject * -BUILD_FUNC_DEF_2(PySocket_getservbyname,PyObject *,self, PyObject *,args) -{ - char *name, *proto; - struct servent *sp; - if (!PyArg_Parse(args, "(ss)", &name, &proto)) - return NULL; - Py_BEGIN_ALLOW_THREADS - sp = getservbyname(name, proto); - Py_END_ALLOW_THREADS - if (sp == NULL) { - PyErr_SetString(PySocket_Error, "service/proto not found"); - return NULL; - } - return PyInt_FromLong((long) ntohs(sp->s_port)); -} - - -/* Python interface to socket(family, type, proto). - The third (protocol) argument is optional. - Return a new socket object. */ - -/*ARGSUSED*/ -static PyObject * -BUILD_FUNC_DEF_2(PySocket_socket,PyObject *,self, PyObject *,args) -{ - PySocketSockObject *s; - int fd, family, type, proto; - proto = 0; - if (!PyArg_Parse(args, "(ii)", &family, &type)) { - PyErr_Clear(); - if (!PyArg_Parse(args, "(iii)", &family, &type, &proto)) - return NULL; - } - Py_BEGIN_ALLOW_THREADS - fd = socket(family, type, proto); - Py_END_ALLOW_THREADS - if (fd < 0) - return PySocket_Err(); - s = PySocketSock_New(fd, family, type, proto); - /* If the object can't be created, don't forget to close the - file descriptor again! */ - if (s == NULL) - (void) close(fd); - /* From now on, ignore SIGPIPE and let the error checking - do the work. */ -#ifdef SIGPIPE - (void) signal(SIGPIPE, SIG_IGN); -#endif - return (PyObject *) s; -} - -#ifndef NO_DUP -/* Create a socket object from a numeric file description. - Useful e.g. if stdin is a socket. - Additional arguments as for socket(). */ - -/*ARGSUSED*/ -static PyObject * -BUILD_FUNC_DEF_2(PySocket_fromfd,PyObject *,self, PyObject *,args) -{ - PySocketSockObject *s; - int fd, family, type, proto; - proto = 0; - if (!PyArg_Parse(args, "(iii)", &fd, &family, &type)) { - PyErr_Clear(); - if (!PyArg_Parse(args, "(iiii)", &fd, &family, &type, &proto)) - return NULL; - } - /* Dup the fd so it and the socket can be closed independently */ - fd = dup(fd); - if (fd < 0) - return PySocket_Err(); - s = PySocketSock_New(fd, family, type, proto); - /* From now on, ignore SIGPIPE and let the error checking - do the work. */ -#ifdef SIGPIPE - (void) signal(SIGPIPE, SIG_IGN); -#endif - return (PyObject *) s; -} -#endif /* NO_DUP */ - -/* List of functions exported by this module. */ - -static PyMethodDef PySocket_methods[] = { - {"gethostbyname", PySocket_gethostbyname}, - {"gethostbyaddr", PySocket_gethostbyaddr}, - {"gethostname", PySocket_gethostname}, - {"getservbyname", PySocket_getservbyname}, - {"socket", PySocket_socket}, -#ifndef NO_DUP - {"fromfd", PySocket_fromfd}, -#endif - {NULL, NULL} /* Sentinel */ -}; - - -/* Convenience routine to export an integer value. - For simplicity, errors (which are unlikely anyway) are ignored. */ - -static void -BUILD_FUNC_DEF_3(insint,PyObject *,d, char *,name, int,value) -{ - PyObject *v = PyInt_FromLong((long) value); - if (v == NULL) { - /* Don't bother reporting this error */ - PyErr_Clear(); - } - else { - PyDict_SetItemString(d, name, v); - Py_DECREF(v); - } -} - - -/* Initialize this module. - This is called when the first 'import socket' is done, - via a table in config.c, if config.c is compiled with USE_SOCKET - defined. */ - -void -initsocket() -{ - PyObject *m, *d; - m = Py_InitModule("socket", PySocket_methods); - d = PyModule_GetDict(m); - PySocket_Error = PyString_FromString("socket.error"); - if (PySocket_Error == NULL || - PyDict_SetItemString(d, "error", PySocket_Error) != 0) - Py_FatalError("can't define socket.error"); - insint(d, "AF_INET", AF_INET); -#ifdef AF_UNIX - insint(d, "AF_UNIX", AF_UNIX); -#endif /* AF_UNIX */ - insint(d, "SOCK_STREAM", SOCK_STREAM); - insint(d, "SOCK_DGRAM", SOCK_DGRAM); - insint(d, "SOCK_RAW", SOCK_RAW); - insint(d, "SOCK_SEQPACKET", SOCK_SEQPACKET); - insint(d, "SOCK_RDM", SOCK_RDM); - -#ifdef SO_DEBUG - insint(d, "SO_DEBUG", SO_DEBUG); -#endif -#ifdef SO_ACCEPTCONN - insint(d, "SO_ACCEPTCONN", SO_ACCEPTCONN); -#endif -#ifdef SO_REUSEADDR - insint(d, "SO_REUSEADDR", SO_REUSEADDR); -#endif -#ifdef SO_KEEPALIVE - insint(d, "SO_KEEPALIVE", SO_KEEPALIVE); -#endif -#ifdef SO_DONTROUTE - insint(d, "SO_DONTROUTE", SO_DONTROUTE); -#endif -#ifdef SO_BROADCAST - insint(d, "SO_BROADCAST", SO_BROADCAST); -#endif -#ifdef SO_USELOOPBACK - insint(d, "SO_USELOOPBACK", SO_USELOOPBACK); -#endif -#ifdef SO_LINGER - insint(d, "SO_LINGER", SO_LINGER); -#endif -#ifdef SO_OOBINLINE - insint(d, "SO_OOBINLINE", SO_OOBINLINE); -#endif -#ifdef SO_REUSEPORT - insint(d, "SO_REUSEPORT", SO_REUSEPORT); -#endif - -#ifdef SO_SNDBUF - insint(d, "SO_SNDBUF", SO_SNDBUF); -#endif -#ifdef SO_RCVBUF - insint(d, "SO_RCVBUF", SO_RCVBUF); -#endif -#ifdef SO_SNDLOWAT - insint(d, "SO_SNDLOWAT", SO_SNDLOWAT); -#endif -#ifdef SO_RCVLOWAT - insint(d, "SO_RCVLOWAT", SO_RCVLOWAT); -#endif -#ifdef SO_SNDTIMEO - insint(d, "SO_SNDTIMEO", SO_SNDTIMEO); -#endif -#ifdef SO_RCVTIMEO - insint(d, "SO_RCVTIMEO", SO_RCVTIMEO); -#endif -#ifdef SO_ERROR - insint(d, "SO_ERROR", SO_ERROR); -#endif -#ifdef SO_TYPE - insint(d, "SO_TYPE", SO_TYPE); -#endif - - /* Maximum number of connections for "listen" */ -#ifdef SOMAXCONN - insint(d, "SOMAXCONN", SOMAXCONN); -#else - insint(d, "SOMAXCONN", 5); /* Common value */ -#endif - - /* Flags for send, recv */ -#ifdef MSG_OOB - insint(d, "MSG_OOB", MSG_OOB); -#endif -#ifdef MSG_PEEK - insint(d, "MSG_PEEK", MSG_PEEK); -#endif -#ifdef MSG_DONTROUTE - insint(d, "MSG_DONTROUTE", MSG_DONTROUTE); -#endif -#ifdef MSG_EOR - insint(d, "MSG_EOR", MSG_EOR); -#endif -#ifdef MSG_TRUNC - insint(d, "MSG_TRUNC", MSG_TRUNC); -#endif -#ifdef MSG_CTRUNC - insint(d, "MSG_CTRUNC", MSG_CTRUNC); -#endif -#ifdef MSG_WAITALL - insint(d, "MSG_WAITALL", MSG_WAITALL); -#endif -#ifdef MSG_BTAG - insint(d, "MSG_BTAG", MSG_BTAG); -#endif -#ifdef MSG_ETAG - insint(d, "MSG_ETAG", MSG_ETAG); -#endif - - /* Protocol level and numbers, usable for [gs]etsockopt */ -#ifdef SOL_SOCKET - insint(d, "SOL_SOCKET", SOL_SOCKET); -#endif -#ifdef IPPROTO_IP - insint(d, "IPPROTO_IP", IPPROTO_IP); -#endif -#ifdef IPPROTO_ICMP - insint(d, "IPPROTO_ICMP", IPPROTO_ICMP); -#endif -#ifdef IPPROTO_IGMP - insint(d, "IPPROTO_IGMP", IPPROTO_IGMP); -#endif -#ifdef IPPROTO_GGP - insint(d, "IPPROTO_GGP", IPPROTO_GGP); -#endif -#ifdef IPPROTO_TCP - insint(d, "IPPROTO_TCP", IPPROTO_TCP); -#endif -#ifdef IPPROTO_EGP - insint(d, "IPPROTO_EGP", IPPROTO_EGP); -#endif -#ifdef IPPROTO_PUP - insint(d, "IPPROTO_PUP", IPPROTO_PUP); -#endif -#ifdef IPPROTO_UDP - insint(d, "IPPROTO_UDP", IPPROTO_UDP); -#endif -#ifdef IPPROTO_IDP - insint(d, "IPPROTO_IDP", IPPROTO_IDP); -#endif -#ifdef IPPROTO_HELLO - insint(d, "IPPROTO_HELLO", IPPROTO_HELLO); -#endif -#ifdef IPPROTO_ND - insint(d, "IPPROTO_ND", IPPROTO_ND); -#endif -#ifdef IPPROTO_TP - insint(d, "IPPROTO_TP", IPPROTO_TP); -#endif -#ifdef IPPROTO_XTP - insint(d, "IPPROTO_XTP", IPPROTO_XTP); -#endif -#ifdef IPPROTO_EON - insint(d, "IPPROTO_EON", IPPROTO_EON); -#endif -#ifdef IPPROTO_BIP - insint(d, "IPPROTO_BIP", IPPROTO_BIP); -#endif -/**/ -#ifdef IPPROTO_RAW - insint(d, "IPPROTO_RAW", IPPROTO_RAW); -#endif -#ifdef IPPROTO_MAX - insint(d, "IPPROTO_MAX", IPPROTO_MAX); -#endif - - /* Some port configuration */ -#ifdef IPPORT_RESERVED - insint(d, "IPPORT_RESERVED", IPPORT_RESERVED); -#else - insint(d, "IPPORT_RESERVED", 1024); -#endif -#ifdef IPPORT_USERRESERVED - insint(d, "IPPORT_USERRESERVED", IPPORT_USERRESERVED); -#else - insint(d, "IPPORT_USERRESERVED", 5000); -#endif - - /* Some reserved IP v.4 addresses */ -#ifdef INADDR_ANY - insint(d, "INADDR_ANY", INADDR_ANY); -#else - insint(d, "INADDR_ANY", 0x00000000); -#endif -#ifdef INADDR_BROADCAST - insint(d, "INADDR_BROADCAST", INADDR_BROADCAST); -#else - insint(d, "INADDR_BROADCAST", 0xffffffff); -#endif -#ifdef INADDR_LOOPBACK - insint(d, "INADDR_LOOPBACK", INADDR_LOOPBACK); -#else - insint(d, "INADDR_LOOPBACK", 0x7F000001); -#endif -#ifdef INADDR_UNSPEC_GROUP - insint(d, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP); -#else - insint(d, "INADDR_UNSPEC_GROUP", 0xe0000000); -#endif -#ifdef INADDR_ALLHOSTS_GROUP - insint(d, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP); -#else - insint(d, "INADDR_ALLHOSTS_GROUP", 0xe0000001); -#endif -#ifdef INADDR_MAX_LOCAL_GROUP - insint(d, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP); -#else - insint(d, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff); -#endif -#ifdef INADDR_NONE - insint(d, "INADDR_NONE", INADDR_NONE); -#else - insint(d, "INADDR_NONE", 0xffffffff); -#endif - - /* IP [gs]etsockopt options */ -#ifdef IP_OPTIONS - insint(d, "IP_OPTIONS", IP_OPTIONS); -#endif -#ifdef IP_HDRINCL - insint(d, "IP_HDRINCL", IP_HDRINCL); -#endif -#ifdef IP_TOS - insint(d, "IP_TOS", IP_TOS); -#endif -#ifdef IP_TTL - insint(d, "IP_TTL", IP_TTL); -#endif -#ifdef IP_RECVOPTS - insint(d, "IP_RECVOPTS", IP_RECVOPTS); -#endif -#ifdef IP_RECVRETOPTS - insint(d, "IP_RECVRETOPTS", IP_RECVRETOPTS); -#endif -#ifdef IP_RECVDSTADDR - insint(d, "IP_RECVDSTADDR", IP_RECVDSTADDR); -#endif -#ifdef IP_RETOPTS - insint(d, "IP_RETOPTS", IP_RETOPTS); -#endif -#ifdef IP_MULTICAST_IF - insint(d, "IP_MULTICAST_IF", IP_MULTICAST_IF); -#endif -#ifdef IP_MULTICAST_TTL - insint(d, "IP_MULTICAST_TTL", IP_MULTICAST_TTL); -#endif -#ifdef IP_MULTICAST_LOOP - insint(d, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP); -#endif -#ifdef IP_ADD_MEMBERSHIP - insint(d, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP); -#endif -#ifdef IP_DROP_MEMBERSHIP - insint(d, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP); -#endif - -#ifdef MS_WIN16 -/* All windows sockets require a successful WSAStartup() before use */ - { - const int opt = SO_SYNCHRONOUS_NONALERT; - WSADATA WSAData; - int ret; - ret = WSAStartup(0x0101, &WSAData); /* request version 1.1 */ - switch(ret){ - case WSASYSNOTREADY: - PyErr_SetString(PySocket_Error, - "WSAStartup failed: Network not ready\n"); - break; - case WSAVERNOTSUPPORTED: - case WSAEINVAL: - PyErr_SetString(PySocket_Error, - "WSAStartup failed: Requested version not supported"); - break; - case 0: - /* Setup sockets in non-overlapped mode by default */ - if (setsockopt(INVALID_SOCKET,SOL_SOCKET,SO_OPENTYPE, - (const char *)&opt,sizeof(opt)) != 0) - PyErr_SetString(PySocket_Error, - "setsockopt failed in initsocket"); - break; - default: - PyErr_SetString(PySocket_Error, - "WSAStartup failed"); - break; - } - } -#endif -} - -#ifdef NT -BOOL WINAPI DllMain (HANDLE hInst, - ULONG ul_reason_for_call, - LPVOID lpReserved) -{ - const int opt = SO_SYNCHRONOUS_NONALERT; - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: { - WSADATA WSAData; - BOOL ok = TRUE; - char buf[100] = "Python can't initialize Windows Sockets Module!\n\r"; - if (WSAStartup(MAKEWORD(1,1), &WSAData)) { - wsprintf(buf+strlen(buf), "WSAStartup failed (%d)",WSAGetLastError()); - ok = FALSE; - } - /* - ** Setup sockets in non-overlapped mode by default - */ -// if (ok && setsockopt(INVALID_SOCKET,SOL_SOCKET,SO_OPENTYPE,(const char *)&opt,sizeof(opt)) != 0) { -// wsprintf(buf+strlen(buf),"setsockopt failed (%d)",WSAGetLastError()); -// ok = FALSE; -// } - if (!ok) { - MessageBox(NULL,buf,"WinSock Error",MB_OK|MB_SETFOREGROUND); - return FALSE; - } - break; - } - - case DLL_PROCESS_DETACH: - WSACleanup(); - break; - - } - return TRUE; -} -#endif /* NT */ diff --git a/Modules/soundex.c b/Modules/soundex.c deleted file mode 100644 index c1cbf70d71..0000000000 --- a/Modules/soundex.c +++ /dev/null @@ -1,175 +0,0 @@ -/* - [Header: soundexmodule.c,v 1.2 95/05/02 15:40:45 dwwillia Exp ] - - Perform soundex comparisons on strings. - - Soundex is an algorithm that hashes English strings into numerical value. - Strings that sound the same are hashed to the same value. This allows - for non-literal string matching. - - From: David Wayne Williams <dwwillia@iucf.indiana.edu> - - Apr 29 1996 - added get_soundex method that returns the soundex of a - string (chrish@qnx.com) - May 2 1996 - added doc strings (chrish@qnx.com) -*/ - -#include <string.h> -#include <ctype.h> -#include "Python.h" - -static char soundex_module__doc__[] = -"Perform Soundex comparisons on strings, allowing non-literal matching."; - -static void soundex_hash(char *str, char *result) -{ - char *sptr = str; /* pointer into str */ - char *rptr = result; /* pointer into result */ - - if(*str == NULL) - { - strcpy(result,"000000"); - return; - } - - /* Preserve the first character of the input string. - */ - *(rptr++) = toupper(*(sptr++)); - - /* Translate the rest of the input string into result. The following - transformations are used: - - 1) All vowles, W, and H, are skipped. - - 2) BFPV = 1 - CGJKQSXZ = 2 - DT = 3 - L = 4 - MN = 5 - - 3) Only translate the first of adjacent equal translations. I.E. - remove duplicate digits. - */ - - for(;(rptr - result) < 6 && *sptr != NULL;sptr++) - { - switch (toupper(*sptr)) - { - case 'W': - case 'H': - case 'A': - case 'I': - case 'O': - case 'U': - case 'Y': - break; - case 'B': - case 'F': - case 'P': - case 'V': - if(*(rptr - 1) != '1') - *(rptr++) = '1'; - break; - case 'C': - case 'G': - case 'J': - case 'K': - case 'Q': - case 'S': - case 'X': - case 'Z': - if(*(rptr - 1) != '2') - *(rptr++) = '2'; - break; - case 'D': - case 'T': - if(*(rptr - 1) != '3') - *(rptr++) = '3'; - break; - case 'L': - if(*(rptr - 1) != '4') - *(rptr++) = '4'; - break; - case 'M': - case 'N': - if(*(rptr - 1) != '5') - *(rptr++) = '5'; - break; - default: - break; - } - } - - /* Pad 0's on right side of string out to 6 characters. - */ - for(; rptr < result + 6; rptr++) - *rptr = '0'; - - /* Terminate the result string. - */ - *(result + 6) = NULL; -} - - -/* Return the actual soundex value. */ -/* Added by Chris Herborth (chrish@qnx.com) */ -static char soundex_get_soundex__doc__[] = - "Return the (English) Soundex hash value for a string."; -static PyObject * -get_soundex(PyObject *self, PyObject *args) -{ - char *str; - int retval; - char sdx[7]; - - if(!PyArg_ParseTuple( args, "s", &str)) - return NULL; - - soundex_hash(str, sdx); - - return PyString_FromString(sdx); -} - -static char soundex_sound_similar__doc__[] = - "Compare two strings to see if they sound similar (English)."; -static PyObject * -sound_similar(PyObject *self, PyObject *args) -{ - char *str1, *str2; - int return_value; - char res1[7], res2[7]; - - if(!PyArg_ParseTuple(args, "ss", &str1, &str2)) - return NULL; - - soundex_hash(str1, res1); - soundex_hash(str2, res2); - - if(!strcmp(res1,res2)) - return Py_BuildValue("i",1); - else - return Py_BuildValue("i",0); -} - -/* Python Method Table. - */ -static PyMethodDef SoundexMethods[] = -{ - {"sound_similar", sound_similar, 1, soundex_sound_similar__doc__}, - {"get_soundex", get_soundex, 1, soundex_get_soundex__doc__}, - - {NULL, NULL } /* sentinel */ -}; - - -/* Register the method table. - */ -void -initsoundex() -{ - (void) Py_InitModule4("soundex", - SoundexMethods, - soundex_module__doc__, - (PyObject *)NULL, - PYTHON_API_VERSION); -} diff --git a/Modules/stdwinmodule.c b/Modules/stdwinmodule.c deleted file mode 100644 index 7ada57ac03..0000000000 --- a/Modules/stdwinmodule.c +++ /dev/null @@ -1,2651 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Stdwin module */ - -/* Stdwin itself is a module, not a separate object type. - Object types defined here: - wp: a window - dp: a drawing structure (only one can exist at a time) - mp: a menu - tp: a textedit block - bp: a bitmap -*/ - -/* Rules for translating C stdwin function calls into Python stwin: - - All names drop their initial letter 'w' - - Functions with a window as first parameter are methods of window objects - - There is no equivalent for wclose(); just delete the window object - (all references to it!) (XXX maybe this is a bad idea) - - w.begindrawing() returns a drawing object - - There is no equivalent for wenddrawing(win); just delete the drawing - object (all references to it!) (XXX maybe this is a bad idea) - - Functions that may only be used inside wbegindrawing / wendddrawing - are methods of the drawing object; this includes the text measurement - functions (which however have doubles as module functions). - - Methods of the drawing object drop an initial 'draw' from their name - if they have it, e.g., wdrawline() --> d.line() - - The obvious type conversions: int --> intobject; string --> stringobject - - A text parameter followed by a length parameter is only a text (string) - parameter in Python - - A point or other pair of horizontal and vertical coordinates is always - a pair of integers in Python - - Two points forming a rectangle or endpoints of a line segment are a - pair of points in Python - - The arguments to d.elarc() are three points. - - The functions wgetclip() and wsetclip() are translated into - stdwin.getcutbuffer() and stdwin.setcutbuffer(); 'clip' is really - a bad word for what these functions do (clipping has a different - meaning in the drawing world), while cutbuffer is standard X jargon. - XXX This must change again in the light of changes to stdwin! - - For textedit, similar rules hold, but they are less strict. - XXX more? -*/ - -#include "allobjects.h" -#include "modsupport.h" -#include "ceval.h" -#include "sysmodule.h" -#ifdef macintosh -#include "macglue.h" -#endif - -#ifdef macintosh -#include ":::stdwin:H:stdwin.h" -#else /* !macintosh */ -#include "stdwin.h" -#define HAVE_BITMAPS -#endif /* !macintosh */ - -#ifdef WITH_THREAD - -#include "thread.h" - -static type_lock StdwinLock; /* Lock held when interpreter not locked */ - -#define BGN_STDWIN BGN_SAVE acquire_lock(StdwinLock, 1); -#define RET_STDWIN release_lock(StdwinLock); RET_SAVE -#define END_STDWIN release_lock(StdwinLock); END_SAVE - -#else - -#define BGN_STDWIN BGN_SAVE -#define RET_STDWIN RET_SAVE -#define END_STDWIN END_SAVE - -#endif - -#define getpointarg(v, a) getargs(v, "(ii)", a, (a)+1) -#define get3pointarg(v, a) getargs(v, "((ii)(ii)(ii))", \ - a, a+1, a+2, a+3, a+4, a+5) -#define getrectarg(v, a) getargs(v, "((ii)(ii))", a, a+1, a+2, a+3) -#define getrectintarg(v, a) getargs(v, "(((ii)(ii))i)", a, a+1, a+2, a+3, a+4) -#define getpointintarg(v, a) getargs(v, "((ii)i)", a, a+1, a+2) -#define getrectpointarg(v, a) getargs(v, "(((ii)(ii))(ii))", \ - a, a+1, a+2, a+3, a+4, a+5) - -static object *StdwinError; /* Exception stdwin.error */ - -/* Window and menu object types declared here because of forward references */ - -typedef struct { - OB_HEAD - object *w_title; - WINDOW *w_win; - object *w_attr; /* Attributes dictionary */ -} windowobject; - -staticforward typeobject Windowtype; - -#define is_windowobject(wp) ((wp)->ob_type == &Windowtype) - -typedef struct { - OB_HEAD - MENU *m_menu; - int m_id; - object *m_attr; /* Attributes dictionary */ -} menuobject; - -staticforward typeobject Menutype; - -#define is_menuobject(mp) ((mp)->ob_type == &Menutype) - -typedef struct { - OB_HEAD - BITMAP *b_bitmap; - object *b_attr; /* Attributes dictionary */ -} bitmapobject; - -staticforward typeobject Bitmaptype; - -#define is_bitmapobject(mp) ((mp)->ob_type == &Bitmaptype) - - -/* Strongly stdwin-specific argument handlers */ - -static int -getmenudetail(v, ep) - object *v; - EVENT *ep; -{ - menuobject *mp; - if (!getargs(v, "(Oi)", &mp, &ep->u.m.item)) - return 0; - if (!is_menuobject(mp)) - return err_badarg(); - ep->u.m.id = mp->m_id; - return 1; -} - -static int -geteventarg(v, ep) - object *v; - EVENT *ep; -{ - object *wp, *detail; - int a[4]; - if (!getargs(v, "(iOO)", &ep->type, &wp, &detail)) - return 0; - if (is_windowobject(wp)) - ep->window = ((windowobject *)wp) -> w_win; - else if (wp == None) - ep->window = NULL; - else - return err_badarg(); - switch (ep->type) { - case WE_CHAR: { - char c; - if (!getargs(detail, "c", &c)) - return 0; - ep->u.character = c; - return 1; - } - case WE_COMMAND: - return getintarg(detail, &ep->u.command); - case WE_DRAW: - if (!getrectarg(detail, a)) - return 0; - ep->u.area.left = a[0]; - ep->u.area.top = a[1]; - ep->u.area.right = a[2]; - ep->u.area.bottom = a[3]; - return 1; - case WE_MOUSE_DOWN: - case WE_MOUSE_UP: - case WE_MOUSE_MOVE: - return getargs(detail, "((ii)iii)", - &ep->u.where.h, &ep->u.where.v, - &ep->u.where.clicks, - &ep->u.where.button, - &ep->u.where.mask); - case WE_MENU: - return getmenudetail(detail, ep); - case WE_KEY: - return getargs(detail, "(ii)", - &ep->u.key.code, &ep->u.key.mask); - default: - return 1; - } -} - - -/* Return construction tools */ - -static object * -makepoint(a, b) - int a, b; -{ - return mkvalue("(ii)", a, b); -} - -static object * -makerect(a, b, c, d) - int a, b, c, d; -{ - return mkvalue("((ii)(ii))", a, b, c, d); -} - - -/* Drawing objects */ - -typedef struct { - OB_HEAD - windowobject *d_ref; -} drawingobject; - -static drawingobject *Drawing; /* Set to current drawing object, or NULL */ - -/* Drawing methods */ - -static object * -drawing_close(dp) - drawingobject *dp; -{ - if (dp->d_ref != NULL) { - wenddrawing(dp->d_ref->w_win); - Drawing = NULL; - DECREF(dp->d_ref); - dp->d_ref = NULL; - } - INCREF(None); - return None; -} - -static void -drawing_dealloc(dp) - drawingobject *dp; -{ - if (dp->d_ref != NULL) { - wenddrawing(dp->d_ref->w_win); - Drawing = NULL; - DECREF(dp->d_ref); - dp->d_ref = NULL; - } - free((char *)dp); -} - -static object * -drawing_generic(dp, args, func) - drawingobject *dp; - object *args; - void (*func) FPROTO((int, int, int, int)); -{ - int a[4]; - if (!getrectarg(args, a)) - return NULL; - (*func)(a[0], a[1], a[2], a[3]); - INCREF(None); - return None; -} - -static object * -drawing_line(dp, args) - drawingobject *dp; - object *args; -{ - return drawing_generic(dp, args, wdrawline); -} - -static object * -drawing_xorline(dp, args) - drawingobject *dp; - object *args; -{ - return drawing_generic(dp, args, wxorline); -} - -static object * -drawing_circle(dp, args) - drawingobject *dp; - object *args; -{ - int a[3]; - if (!getpointintarg(args, a)) - return NULL; - wdrawcircle(a[0], a[1], a[2]); - INCREF(None); - return None; -} - -static object * -drawing_fillcircle(dp, args) - drawingobject *dp; - object *args; -{ - int a[3]; - if (!getpointintarg(args, a)) - return NULL; - wfillcircle(a[0], a[1], a[2]); - INCREF(None); - return None; -} - -static object * -drawing_xorcircle(dp, args) - drawingobject *dp; - object *args; -{ - int a[3]; - if (!getpointintarg(args, a)) - return NULL; - wxorcircle(a[0], a[1], a[2]); - INCREF(None); - return None; -} - -static object * -drawing_elarc(dp, args) - drawingobject *dp; - object *args; -{ - int a[6]; - if (!get3pointarg(args, a)) - return NULL; - wdrawelarc(a[0], a[1], a[2], a[3], a[4], a[5]); - INCREF(None); - return None; -} - -static object * -drawing_fillelarc(dp, args) - drawingobject *dp; - object *args; -{ - int a[6]; - if (!get3pointarg(args, a)) - return NULL; - wfillelarc(a[0], a[1], a[2], a[3], a[4], a[5]); - INCREF(None); - return None; -} - -static object * -drawing_xorelarc(dp, args) - drawingobject *dp; - object *args; -{ - int a[6]; - if (!get3pointarg(args, a)) - return NULL; - wxorelarc(a[0], a[1], a[2], a[3], a[4], a[5]); - INCREF(None); - return None; -} - -static object * -drawing_box(dp, args) - drawingobject *dp; - object *args; -{ - return drawing_generic(dp, args, wdrawbox); -} - -static object * -drawing_erase(dp, args) - drawingobject *dp; - object *args; -{ - return drawing_generic(dp, args, werase); -} - -static object * -drawing_paint(dp, args) - drawingobject *dp; - object *args; -{ - return drawing_generic(dp, args, wpaint); -} - -static object * -drawing_invert(dp, args) - drawingobject *dp; - object *args; -{ - return drawing_generic(dp, args, winvert); -} - -static POINT * -getpointsarray(v, psize) - object *v; - int *psize; -{ - int n = -1; - object * (*getitem) PROTO((object *, int)); - int i; - POINT *points; - - if (v == NULL) - ; - else if (is_listobject(v)) { - n = getlistsize(v); - getitem = getlistitem; - } - else if (is_tupleobject(v)) { - n = gettuplesize(v); - getitem = gettupleitem; - } - - if (n <= 0) { - (void) err_badarg(); - return NULL; - } - - points = NEW(POINT, n); - if (points == NULL) { - (void) err_nomem(); - return NULL; - } - - for (i = 0; i < n; i++) { - object *w = (*getitem)(v, i); - int a[2]; - if (!getpointarg(w, a)) { - DEL(points); - return NULL; - } - points[i].h = a[0]; - points[i].v = a[1]; - } - - *psize = n; - return points; -} - -static object * -drawing_poly(dp, args) - drawingobject *dp; - object *args; -{ - int n; - POINT *points = getpointsarray(args, &n); - if (points == NULL) - return NULL; - wdrawpoly(n, points); - DEL(points); - INCREF(None); - return None; -} - -static object * -drawing_fillpoly(dp, args) - drawingobject *dp; - object *args; -{ - int n; - POINT *points = getpointsarray(args, &n); - if (points == NULL) - return NULL; - wfillpoly(n, points); - DEL(points); - INCREF(None); - return None; -} - -static object * -drawing_xorpoly(dp, args) - drawingobject *dp; - object *args; -{ - int n; - POINT *points = getpointsarray(args, &n); - if (points == NULL) - return NULL; - wxorpoly(n, points); - DEL(points); - INCREF(None); - return None; -} - -static object * -drawing_cliprect(dp, args) - drawingobject *dp; - object *args; -{ - return drawing_generic(dp, args, wcliprect); -} - -static object * -drawing_noclip(dp, args) - drawingobject *dp; - object *args; -{ - if (!getnoarg(args)) - return NULL; - wnoclip(); - INCREF(None); - return None; -} - -static object * -drawing_shade(dp, args) - drawingobject *dp; - object *args; -{ - int a[5]; - if (!getrectintarg(args, a)) - return NULL; - wshade(a[0], a[1], a[2], a[3], a[4]); - INCREF(None); - return None; -} - -static object * -drawing_text(dp, args) - drawingobject *dp; - object *args; -{ - int h, v, size; - char *text; - if (!getargs(args, "((ii)s#)", &h, &v, &text, &size)) - return NULL; - wdrawtext(h, v, text, size); - INCREF(None); - return None; -} - -/* The following four are also used as stdwin functions */ - -static object * -drawing_lineheight(dp, args) - drawingobject *dp; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newintobject((long)wlineheight()); -} - -static object * -drawing_baseline(dp, args) - drawingobject *dp; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newintobject((long)wbaseline()); -} - -static object * -drawing_textwidth(dp, args) - drawingobject *dp; - object *args; -{ - char *text; - int size; - if (!getargs(args, "s#", &text, &size)) - return NULL; - return newintobject((long)wtextwidth(text, size)); -} - -static object * -drawing_textbreak(dp, args) - drawingobject *dp; - object *args; -{ - char *text; - int size, width; - if (!getargs(args, "(s#i)", &text, &size, &width)) - return NULL; - return newintobject((long)wtextbreak(text, size, width)); -} - -static object * -drawing_setfont(self, args) - drawingobject *self; - object *args; -{ - char *font; - char style = '\0'; - int size = 0; - if (args == NULL || !is_tupleobject(args)) { - if (!getargs(args, "z", &font)) - return NULL; - } - else { - int n = gettuplesize(args); - if (n == 2) { - if (!getargs(args, "(zi)", &font, &size)) - return NULL; - } - else if (!getargs(args, "(zic)", &font, &size, &style)) { - err_clear(); - if (!getargs(args, "(zci)", &font, &style, &size)) - return NULL; - } - } - if (font != NULL) { - if (!wsetfont(font)) { - err_setstr(StdwinError, "font not found"); - return NULL; - } - } - if (size != 0) - wsetsize(size); - switch (style) { - case 'b': - wsetbold(); - break; - case 'i': - wsetitalic(); - break; - case 'o': - wsetbolditalic(); - break; - case 'u': - wsetunderline(); - break; - case 'p': - wsetplain(); - break; - } - INCREF(None); - return None; -} - -static object * -drawing_getbgcolor(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newintobject((long)wgetbgcolor()); -} - -static object * -drawing_getfgcolor(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newintobject((long)wgetfgcolor()); -} - -static object * -drawing_setbgcolor(self, args) - object *self; - object *args; -{ - long color; - if (!getlongarg(args, &color)) - return NULL; - wsetbgcolor((COLOR)color); - INCREF(None); - return None; -} - -static object * -drawing_setfgcolor(self, args) - object *self; - object *args; -{ - long color; - if (!getlongarg(args, &color)) - return NULL; - wsetfgcolor((COLOR)color); - INCREF(None); - return None; -} - -#ifdef HAVE_BITMAPS - -static object * -drawing_bitmap(self, args) - object *self; - object *args; -{ - int h, v; - object *bp; - object *mask = NULL; - if (!getargs(args, "((ii)O)", &h, &v, &bp)) { - err_clear(); - if (!getargs(args, "((ii)OO)", &h, &v, &bp, &mask)) - return NULL; - if (mask == None) - mask = NULL; - else if (!is_bitmapobject(mask)) { - err_badarg(); - return NULL; - } - } - if (!is_bitmapobject(bp)) { - err_badarg(); - return NULL; - } - if (((bitmapobject *)bp)->b_bitmap == NULL || - mask != NULL && ((bitmapobject *)mask)->b_bitmap == NULL) { - err_setstr(StdwinError, "bitmap object already close"); - return NULL; - } - if (mask == NULL) - wdrawbitmap(h, v, ((bitmapobject *)bp)->b_bitmap, ALLBITS); - else - wdrawbitmap(h, v, - ((bitmapobject *)bp)->b_bitmap, - ((bitmapobject *)bp)->b_bitmap); - INCREF(None); - return None; -} - -#endif /* HAVE_BITMAPS */ - -static struct methodlist drawing_methods[] = { -#ifdef HAVE_BITMAPS - {"bitmap", (method)drawing_bitmap}, -#endif - {"box", (method)drawing_box}, - {"circle", (method)drawing_circle}, - {"cliprect", (method)drawing_cliprect}, - {"close", (method)drawing_close}, - {"elarc", (method)drawing_elarc}, - {"enddrawing", (method)drawing_close}, - {"erase", (method)drawing_erase}, - {"fillcircle", (method)drawing_fillcircle}, - {"fillelarc", (method)drawing_fillelarc}, - {"fillpoly", (method)drawing_fillpoly}, - {"invert", (method)drawing_invert}, - {"line", (method)drawing_line}, - {"noclip", (method)drawing_noclip}, - {"paint", (method)drawing_paint}, - {"poly", (method)drawing_poly}, - {"shade", (method)drawing_shade}, - {"text", (method)drawing_text}, - {"xorcircle", (method)drawing_xorcircle}, - {"xorelarc", (method)drawing_xorelarc}, - {"xorline", (method)drawing_xorline}, - {"xorpoly", (method)drawing_xorpoly}, - - /* Text measuring methods: */ - {"baseline", (method)drawing_baseline}, - {"lineheight", (method)drawing_lineheight}, - {"textbreak", (method)drawing_textbreak}, - {"textwidth", (method)drawing_textwidth}, - - /* Font setting methods: */ - {"setfont", (method)drawing_setfont}, - - /* Color methods: */ - {"getbgcolor", (method)drawing_getbgcolor}, - {"getfgcolor", (method)drawing_getfgcolor}, - {"setbgcolor", (method)drawing_setbgcolor}, - {"setfgcolor", (method)drawing_setfgcolor}, - - {NULL, NULL} /* sentinel */ -}; - -static object * -drawing_getattr(dp, name) - drawingobject *dp; - char *name; -{ - if (dp->d_ref == NULL) { - err_setstr(StdwinError, "drawing object already closed"); - return NULL; - } - return findmethod(drawing_methods, (object *)dp, name); -} - -typeobject Drawingtype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "drawing", /*tp_name*/ - sizeof(drawingobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)drawing_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)drawing_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - - -/* Text(edit) objects */ - -typedef struct { - OB_HEAD - TEXTEDIT *t_text; - windowobject *t_ref; - object *t_attr; /* Attributes dictionary */ -} textobject; - -staticforward typeobject Texttype; - -static textobject * -newtextobject(wp, left, top, right, bottom) - windowobject *wp; - int left, top, right, bottom; -{ - textobject *tp; - tp = NEWOBJ(textobject, &Texttype); - if (tp == NULL) - return NULL; - tp->t_attr = NULL; - INCREF(wp); - tp->t_ref = wp; - tp->t_text = tecreate(wp->w_win, left, top, right, bottom); - if (tp->t_text == NULL) { - DECREF(tp); - return (textobject *) err_nomem(); - } - return tp; -} - -/* Text(edit) methods */ - -static void -text_dealloc(tp) - textobject *tp; -{ - if (tp->t_text != NULL) - tefree(tp->t_text); - XDECREF(tp->t_attr); - XDECREF(tp->t_ref); - DEL(tp); -} - -static object * -text_close(tp, args) - textobject *tp; - object *args; -{ - if (tp->t_text != NULL) { - tefree(tp->t_text); - tp->t_text = NULL; - } - if (tp->t_attr != NULL) { - DECREF(tp->t_attr); - tp->t_attr = NULL; - } - if (tp->t_ref != NULL) { - DECREF(tp->t_ref); - tp->t_ref = NULL; - } - INCREF(None); - return None; -} - -static object * -text_arrow(self, args) - textobject *self; - object *args; -{ - int code; - if (!getintarg(args, &code)) - return NULL; - tearrow(self->t_text, code); - INCREF(None); - return None; -} - -static object * -text_draw(self, args) - textobject *self; - object *args; -{ - register TEXTEDIT *tp = self->t_text; - int a[4]; - int left, top, right, bottom; - if (!getrectarg(args, a)) - return NULL; - if (Drawing != NULL) { - err_setstr(StdwinError, "already drawing"); - return NULL; - } - /* Clip to text area and ignore if area is empty */ - left = tegetleft(tp); - top = tegettop(tp); - right = tegetright(tp); - bottom = tegetbottom(tp); - if (a[0] < left) a[0] = left; - if (a[1] < top) a[1] = top; - if (a[2] > right) a[2] = right; - if (a[3] > bottom) a[3] = bottom; - if (a[0] < a[2] && a[1] < a[3]) { - wbegindrawing(self->t_ref->w_win); - tedrawnew(tp, a[0], a[1], a[2], a[3]); - wenddrawing(self->t_ref->w_win); - } - INCREF(None); - return None; -} - -static object * -text_event(self, args) - textobject *self; - object *args; -{ - register TEXTEDIT *tp = self->t_text; - EVENT e; - if (!geteventarg(args, &e)) - return NULL; - if (e.type == WE_MOUSE_DOWN) { - /* Cheat at the margins */ - int width, height; - wgetdocsize(e.window, &width, &height); - if (e.u.where.h < 0 && tegetleft(tp) == 0) - e.u.where.h = 0; - else if (e.u.where.h > width && tegetright(tp) == width) - e.u.where.h = width; - if (e.u.where.v < 0 && tegettop(tp) == 0) - e.u.where.v = 0; - else if (e.u.where.v > height && tegetright(tp) == height) - e.u.where.v = height; - } - return newintobject((long) teevent(tp, &e)); -} - -static object * -text_getfocus(self, args) - textobject *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return makepoint(tegetfoc1(self->t_text), tegetfoc2(self->t_text)); -} - -static object * -text_getfocustext(self, args) - textobject *self; - object *args; -{ - int f1, f2; - char *text; - if (!getnoarg(args)) - return NULL; - f1 = tegetfoc1(self->t_text); - f2 = tegetfoc2(self->t_text); - text = tegettext(self->t_text); - return newsizedstringobject(text + f1, f2-f1); -} - -static object * -text_getrect(self, args) - textobject *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return makerect(tegetleft(self->t_text), - tegettop(self->t_text), - tegetright(self->t_text), - tegetbottom(self->t_text)); -} - -static object * -text_gettext(self, args) - textobject *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newsizedstringobject(tegettext(self->t_text), - tegetlen(self->t_text)); -} - -static object * -text_move(self, args) - textobject *self; - object *args; -{ - int a[4]; - if (!getrectarg(args, a)) - return NULL; - temovenew(self->t_text, a[0], a[1], a[2], a[3]); - INCREF(None); - return None; -} - -static object * -text_replace(self, args) - textobject *self; - object *args; -{ - char *text; - if (!getstrarg(args, &text)) - return NULL; - tereplace(self->t_text, text); - INCREF(None); - return None; -} - -static object * -text_setactive(self, args) - textobject *self; - object *args; -{ - int flag; - if (!getintarg(args, &flag)) - return NULL; - tesetactive(self->t_text, flag); - INCREF(None); - return None; -} - -static object * -text_setfocus(self, args) - textobject *self; - object *args; -{ - int a[2]; - if (!getpointarg(args, a)) - return NULL; - tesetfocus(self->t_text, a[0], a[1]); - INCREF(None); - return None; -} - -static object * -text_settext(self, args) - textobject *self; - object *args; -{ - char *text; - char *buf; - int size; - if (!getargs(args, "s#", &text, &size)) - return NULL; - if ((buf = NEW(char, size)) == NULL) { - return err_nomem(); - } - memcpy(buf, text, size); - tesetbuf(self->t_text, buf, size); /* Becomes owner of buffer */ - INCREF(None); - return None; -} - -static object * -text_setview(self, args) - textobject *self; - object *args; -{ - int a[4]; - if (args == None) - tenoview(self->t_text); - else { - if (!getrectarg(args, a)) - return NULL; - tesetview(self->t_text, a[0], a[1], a[2], a[3]); - } - INCREF(None); - return None; -} - -static struct methodlist text_methods[] = { - {"arrow", (method)text_arrow}, - {"close", (method)text_close}, - {"draw", (method)text_draw}, - {"event", (method)text_event}, - {"getfocus", (method)text_getfocus}, - {"getfocustext",(method)text_getfocustext}, - {"getrect", (method)text_getrect}, - {"gettext", (method)text_gettext}, - {"move", (method)text_move}, - {"replace", (method)text_replace}, - {"setactive", (method)text_setactive}, - {"setfocus", (method)text_setfocus}, - {"settext", (method)text_settext}, - {"setview", (method)text_setview}, - {NULL, NULL} /* sentinel */ -}; - -static object * -text_getattr(tp, name) - textobject *tp; - char *name; -{ - object *v = NULL; - if (tp->t_ref == NULL) { - err_setstr(StdwinError, "text object already closed"); - return NULL; - } - if (strcmp(name, "__dict__") == 0) { - v = tp->t_attr; - if (v == NULL) - v = None; - } - else if (tp->t_attr != NULL) { - v = dictlookup(tp->t_attr, name); - } - if (v != NULL) { - INCREF(v); - return v; - } - return findmethod(text_methods, (object *)tp, name); -} - -static int -text_setattr(tp, name, v) - textobject *tp; - char *name; - object *v; -{ - if (tp->t_attr == NULL) { - tp->t_attr = newdictobject(); - if (tp->t_attr == NULL) - return -1; - } - if (v == NULL) { - int rv = dictremove(tp->t_attr, name); - if (rv < 0) - err_setstr(AttributeError, - "delete non-existing text object attribute"); - return rv; - } - else - return dictinsert(tp->t_attr, name, v); -} - -statichere typeobject Texttype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "textedit", /*tp_name*/ - sizeof(textobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)text_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)text_getattr, /*tp_getattr*/ - (setattrfunc)text_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - - -/* Menu objects */ - -#define IDOFFSET 10 /* Menu IDs we use start here */ -#define MAXNMENU 200 /* Max #menus we allow */ -static menuobject *menulist[MAXNMENU]; - -static menuobject *newmenuobject PROTO((char *)); -static menuobject * -newmenuobject(title) - char *title; -{ - int id; - MENU *menu; - menuobject *mp; - for (id = 0; id < MAXNMENU; id++) { - if (menulist[id] == NULL) - break; - } - if (id >= MAXNMENU) { - err_setstr(StdwinError, "creating too many menus"); - return NULL; - } - menu = wmenucreate(id + IDOFFSET, title); - if (menu == NULL) - return (menuobject *) err_nomem(); - mp = NEWOBJ(menuobject, &Menutype); - if (mp != NULL) { - mp->m_menu = menu; - mp->m_id = id + IDOFFSET; - mp->m_attr = NULL; - menulist[id] = mp; - } - else - wmenudelete(menu); - return mp; -} - -/* Menu methods */ - -static void -menu_dealloc(mp) - menuobject *mp; -{ - - int id = mp->m_id - IDOFFSET; - if (id >= 0 && id < MAXNMENU && menulist[id] == mp) { - menulist[id] = NULL; - } - if (mp->m_menu != NULL) - wmenudelete(mp->m_menu); - XDECREF(mp->m_attr); - DEL(mp); -} - -static object * -menu_close(mp, args) - menuobject *mp; - object *args; -{ - int id = mp->m_id - IDOFFSET; - if (id >= 0 && id < MAXNMENU && menulist[id] == mp) { - menulist[id] = NULL; - } - mp->m_id = -1; - if (mp->m_menu != NULL) - wmenudelete(mp->m_menu); - mp->m_menu = NULL; - XDECREF(mp->m_attr); - mp->m_attr = NULL; - INCREF(None); - return None; -} - -static object * -menu_additem(self, args) - menuobject *self; - object *args; -{ - char *text; - int shortcut = -1; - if (is_tupleobject(args)) { - char c; - if (!getargs(args, "(sc)", &text, &c)) - return NULL; - shortcut = c; - } - else if (!getstrarg(args, &text)) - return NULL; - wmenuadditem(self->m_menu, text, shortcut); - INCREF(None); - return None; -} - -static object * -menu_setitem(self, args) - menuobject *self; - object *args; -{ - int index; - char *text; - if (!getargs(args, "(is)", &index, &text)) - return NULL; - wmenusetitem(self->m_menu, index, text); - INCREF(None); - return None; -} - -static object * -menu_enable(self, args) - menuobject *self; - object *args; -{ - int index; - int flag; - if (!getargs(args, "(ii)", &index, &flag)) - return NULL; - wmenuenable(self->m_menu, index, flag); - INCREF(None); - return None; -} - -static object * -menu_check(self, args) - menuobject *self; - object *args; -{ - int index; - int flag; - if (!getargs(args, "(ii)", &index, &flag)) - return NULL; - wmenucheck(self->m_menu, index, flag); - INCREF(None); - return None; -} - -static struct methodlist menu_methods[] = { - {"additem", (method)menu_additem}, - {"setitem", (method)menu_setitem}, - {"enable", (method)menu_enable}, - {"check", (method)menu_check}, - {"close", (method)menu_close}, - {NULL, NULL} /* sentinel */ -}; - -static object * -menu_getattr(mp, name) - menuobject *mp; - char *name; -{ - object *v = NULL; - if (mp->m_menu == NULL) { - err_setstr(StdwinError, "menu object already closed"); - return NULL; - } - if (strcmp(name, "__dict__") == 0) { - v = mp->m_attr; - if (v == NULL) - v = None; - } - else if (mp->m_attr != NULL) { - v = dictlookup(mp->m_attr, name); - } - if (v != NULL) { - INCREF(v); - return v; - } - return findmethod(menu_methods, (object *)mp, name); -} - -static int -menu_setattr(mp, name, v) - menuobject *mp; - char *name; - object *v; -{ - if (mp->m_attr == NULL) { - mp->m_attr = newdictobject(); - if (mp->m_attr == NULL) - return -1; - } - if (v == NULL) { - int rv = dictremove(mp->m_attr, name); - if (rv < 0) - err_setstr(AttributeError, - "delete non-existing menu object attribute"); - return rv; - } - else - return dictinsert(mp->m_attr, name, v); -} - -statichere typeobject Menutype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "menu", /*tp_name*/ - sizeof(menuobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)menu_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)menu_getattr, /*tp_getattr*/ - (setattrfunc)menu_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - - -#ifdef HAVE_BITMAPS - -/* Bitmaps objects */ - -static bitmapobject *newbitmapobject PROTO((int, int)); -static bitmapobject * -newbitmapobject(width, height) - int width, height; -{ - BITMAP *bitmap; - bitmapobject *bp; - bitmap = wnewbitmap(width, height); - if (bitmap == NULL) - return (bitmapobject *) err_nomem(); - bp = NEWOBJ(bitmapobject, &Bitmaptype); - if (bp != NULL) { - bp->b_bitmap = bitmap; - bp->b_attr = NULL; - } - else - wfreebitmap(bitmap); - return bp; -} - -/* Bitmap methods */ - -static void -bitmap_dealloc(bp) - bitmapobject *bp; -{ - if (bp->b_bitmap != NULL) - wfreebitmap(bp->b_bitmap); - XDECREF(bp->b_attr); - DEL(bp); -} - -static object * -bitmap_close(bp, args) - bitmapobject *bp; - object *args; -{ - if (bp->b_bitmap != NULL) - wfreebitmap(bp->b_bitmap); - bp->b_bitmap = NULL; - XDECREF(bp->b_attr); - bp->b_attr = NULL; - INCREF(None); - return None; -} - -static object * -bitmap_setbit(self, args) - bitmapobject *self; - object *args; -{ - int a[3]; - if (!getpointintarg(args, a)) - return NULL; - wsetbit(self->b_bitmap, a[0], a[1], a[2]); - INCREF(None); - return None; -} - -static object * -bitmap_getbit(self, args) - bitmapobject *self; - object *args; -{ - int a[2]; - if (!getpointarg(args, a)) - return NULL; - return newintobject((long) wgetbit(self->b_bitmap, a[0], a[1])); -} - -static object * -bitmap_getsize(self, args) - bitmapobject *self; - object *args; -{ - int width, height; - if (!getnoarg(args)) - return NULL; - wgetbitmapsize(self->b_bitmap, &width, &height); - return mkvalue("(ii)", width, height); -} - -static struct methodlist bitmap_methods[] = { - {"close", (method)bitmap_close}, - {"getsize", (method)bitmap_getsize}, - {"getbit", (method)bitmap_getbit}, - {"setbit", (method)bitmap_setbit}, - {NULL, NULL} /* sentinel */ -}; - -static object * -bitmap_getattr(bp, name) - bitmapobject *bp; - char *name; -{ - object *v = NULL; - if (bp->b_bitmap == NULL) { - err_setstr(StdwinError, "bitmap object already closed"); - return NULL; - } - if (strcmp(name, "__dict__") == 0) { - v = bp->b_attr; - if (v == NULL) - v = None; - } - else if (bp->b_attr != NULL) { - v = dictlookup(bp->b_attr, name); - } - if (v != NULL) { - INCREF(v); - return v; - } - return findmethod(bitmap_methods, (object *)bp, name); -} - -static int -bitmap_setattr(bp, name, v) - bitmapobject *bp; - char *name; - object *v; -{ - if (bp->b_attr == NULL) { - bp->b_attr = newdictobject(); - if (bp->b_attr == NULL) - return -1; - } - if (v == NULL) { - int rv = dictremove(bp->b_attr, name); - if (rv < 0) - err_setstr(AttributeError, - "delete non-existing bitmap object attribute"); - return rv; - } - else - return dictinsert(bp->b_attr, name, v); -} - -statichere typeobject Bitmaptype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "bitmap", /*tp_name*/ - sizeof(bitmapobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)bitmap_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)bitmap_getattr, /*tp_getattr*/ - (setattrfunc)bitmap_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - -#endif /* HAVE_BITMAPS */ - - -/* Windows */ - -#define MAXNWIN 50 -static windowobject *windowlist[MAXNWIN]; - -/* Window methods */ - -static void -window_dealloc(wp) - windowobject *wp; -{ - if (wp->w_win != NULL) { - int tag = wgettag(wp->w_win); - if (tag >= 0 && tag < MAXNWIN) - windowlist[tag] = NULL; - else - fprintf(stderr, "XXX help! tag %d in window_dealloc\n", - tag); - wclose(wp->w_win); - } - DECREF(wp->w_title); - if (wp->w_attr != NULL) - DECREF(wp->w_attr); - free((char *)wp); -} - -static object * -window_close(wp, args) - windowobject *wp; - object *args; -{ - if (wp->w_win != NULL) { - int tag = wgettag(wp->w_win); - if (tag >= 0 && tag < MAXNWIN) - windowlist[tag] = NULL; - wclose(wp->w_win); - wp->w_win = NULL; - } - INCREF(None); - return None; -} - -static object * -window_begindrawing(wp, args) - windowobject *wp; - object *args; -{ - drawingobject *dp; - if (!getnoarg(args)) - return NULL; - if (Drawing != NULL) { - err_setstr(StdwinError, "already drawing"); - return NULL; - } - dp = NEWOBJ(drawingobject, &Drawingtype); - if (dp == NULL) - return NULL; - Drawing = dp; - INCREF(wp); - dp->d_ref = wp; - wbegindrawing(wp->w_win); - return (object *)dp; -} - -static object * -window_change(wp, args) - windowobject *wp; - object *args; -{ - int a[4]; - if (!getrectarg(args, a)) - return NULL; - wchange(wp->w_win, a[0], a[1], a[2], a[3]); - INCREF(None); - return None; -} - -static object * -window_gettitle(wp, args) - windowobject *wp; - object *args; -{ - if (!getnoarg(args)) - return NULL; - INCREF(wp->w_title); - return wp->w_title; -} - -static object * -window_getwinpos(wp, args) - windowobject *wp; - object *args; -{ - int h, v; - if (!getnoarg(args)) - return NULL; - wgetwinpos(wp->w_win, &h, &v); - return makepoint(h, v); -} - -static object * -window_getwinsize(wp, args) - windowobject *wp; - object *args; -{ - int width, height; - if (!getnoarg(args)) - return NULL; - wgetwinsize(wp->w_win, &width, &height); - return makepoint(width, height); -} - -static object * -window_setwinpos(wp, args) - windowobject *wp; - object *args; -{ - int a[2]; - if (!getpointarg(args, a)) - return NULL; - wsetwinpos(wp->w_win, a[0], a[1]); - INCREF(None); - return None; -} - -static object * -window_setwinsize(wp, args) - windowobject *wp; - object *args; -{ - int a[2]; - if (!getpointarg(args, a)) - return NULL; - wsetwinsize(wp->w_win, a[0], a[1]); - INCREF(None); - return None; -} - -static object * -window_getdocsize(wp, args) - windowobject *wp; - object *args; -{ - int width, height; - if (!getnoarg(args)) - return NULL; - wgetdocsize(wp->w_win, &width, &height); - return makepoint(width, height); -} - -static object * -window_getorigin(wp, args) - windowobject *wp; - object *args; -{ - int width, height; - if (!getnoarg(args)) - return NULL; - wgetorigin(wp->w_win, &width, &height); - return makepoint(width, height); -} - -static object * -window_scroll(wp, args) - windowobject *wp; - object *args; -{ - int a[6]; - if (!getrectpointarg(args, a)) - return NULL; - wscroll(wp->w_win, a[0], a[1], a[2], a[3], a[4], a[5]); - INCREF(None); - return None; -} - -static object * -window_setdocsize(wp, args) - windowobject *wp; - object *args; -{ - int a[2]; - if (!getpointarg(args, a)) - return NULL; - wsetdocsize(wp->w_win, a[0], a[1]); - INCREF(None); - return None; -} - -static object * -window_setorigin(wp, args) - windowobject *wp; - object *args; -{ - int a[2]; - if (!getpointarg(args, a)) - return NULL; - wsetorigin(wp->w_win, a[0], a[1]); - INCREF(None); - return None; -} - -static object * -window_settitle(wp, args) - windowobject *wp; - object *args; -{ - object *title; - if (!getargs(args, "S", &title)) - return NULL; - DECREF(wp->w_title); - INCREF(title); - wp->w_title = title; - wsettitle(wp->w_win, getstringvalue(title)); - INCREF(None); - return None; -} - -static object * -window_show(wp, args) - windowobject *wp; - object *args; -{ - int a[4]; - if (!getrectarg(args, a)) - return NULL; - wshow(wp->w_win, a[0], a[1], a[2], a[3]); - INCREF(None); - return None; -} - -static object * -window_settimer(wp, args) - windowobject *wp; - object *args; -{ - int a; - if (!getintarg(args, &a)) - return NULL; - wsettimer(wp->w_win, a); - INCREF(None); - return None; -} - -static object * -window_menucreate(self, args) - windowobject *self; - object *args; -{ - menuobject *mp; - char *title; - if (!getstrarg(args, &title)) - return NULL; - wmenusetdeflocal(1); - mp = newmenuobject(title); - if (mp == NULL) - return NULL; - wmenuattach(self->w_win, mp->m_menu); - return (object *)mp; -} - -static object * -window_textcreate(self, args) - windowobject *self; - object *args; -{ - int a[4]; - if (!getrectarg(args, a)) - return NULL; - return (object *) - newtextobject(self, a[0], a[1], a[2], a[3]); -} - -static object * -window_setselection(self, args) - windowobject *self; - object *args; -{ - int sel, size, ok; - char *text; - if (!getargs(args, "(is#)", &sel, &text, &size)) - return NULL; - ok = wsetselection(self->w_win, sel, text, size); - return newintobject(ok); -} - -static object * -window_setwincursor(self, args) - windowobject *self; - object *args; -{ - char *name; - CURSOR *c; - if (!getargs(args, "z", &name)) - return NULL; - if (name == NULL) - c = NULL; - else { - c = wfetchcursor(name); - if (c == NULL) { - err_setstr(StdwinError, "no such cursor"); - return NULL; - } - } - wsetwincursor(self->w_win, c); - INCREF(None); - return None; -} - -static object * -window_setactive(self, args) - windowobject *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - wsetactive(self->w_win); - INCREF(None); - return None; -} - -#ifdef CWI_HACKS -static object * -window_getxwindowid(self, args) - windowobject *self; - object *args; -{ - long wid = wgetxwindowid(self->w_win); - return newintobject(wid); -} -#endif - -static struct methodlist window_methods[] = { - {"begindrawing",(method)window_begindrawing}, - {"change", (method)window_change}, - {"close", (method)window_close}, - {"getdocsize", (method)window_getdocsize}, - {"getorigin", (method)window_getorigin}, - {"gettitle", (method)window_gettitle}, - {"getwinpos", (method)window_getwinpos}, - {"getwinsize", (method)window_getwinsize}, - {"menucreate", (method)window_menucreate}, - {"scroll", (method)window_scroll}, - {"setactive", (method)window_setactive}, - {"setdocsize", (method)window_setdocsize}, - {"setorigin", (method)window_setorigin}, - {"setselection",(method)window_setselection}, - {"settimer", (method)window_settimer}, - {"settitle", (method)window_settitle}, - {"setwincursor",(method)window_setwincursor}, - {"setwinpos", (method)window_setwinpos}, - {"setwinsize", (method)window_setwinsize}, - {"show", (method)window_show}, - {"textcreate", (method)window_textcreate}, -#ifdef CWI_HACKS - {"getxwindowid",(method)window_getxwindowid}, -#endif - {NULL, NULL} /* sentinel */ -}; - -static object * -window_getattr(wp, name) - windowobject *wp; - char *name; -{ - object *v = NULL; - if (wp->w_win == NULL) { - err_setstr(StdwinError, "window already closed"); - return NULL; - } - if (strcmp(name, "__dict__") == 0) { - v = wp->w_attr; - if (v == NULL) - v = None; - } - else if (wp->w_attr != NULL) { - v = dictlookup(wp->w_attr, name); - } - if (v != NULL) { - INCREF(v); - return v; - } - return findmethod(window_methods, (object *)wp, name); -} - -static int -window_setattr(wp, name, v) - windowobject *wp; - char *name; - object *v; -{ - if (wp->w_attr == NULL) { - wp->w_attr = newdictobject(); - if (wp->w_attr == NULL) - return -1; - } - if (v == NULL) { - int rv = dictremove(wp->w_attr, name); - if (rv < 0) - err_setstr(AttributeError, - "delete non-existing menu object attribute"); - return rv; - } - else - return dictinsert(wp->w_attr, name, v); -} - -statichere typeobject Windowtype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "window", /*tp_name*/ - sizeof(windowobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)window_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)window_getattr, /*tp_getattr*/ - (setattrfunc)window_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - -/* Stdwin methods */ - -static object * -stdwin_done(sw, args) - object *sw; - object *args; -{ - if (!getnoarg(args)) - return NULL; - wdone(); - /* XXX There is no protection against continued use of - XXX stdwin functions or objects after this call is made. - XXX Use at own risk */ - INCREF(None); - return None; -} - -static object * -stdwin_open(sw, args) - object *sw; - object *args; -{ - int tag; - object *title; - windowobject *wp; - if (!getargs(args, "S", &title)) - return NULL; - for (tag = 0; tag < MAXNWIN; tag++) { - if (windowlist[tag] == NULL) - break; - } - if (tag >= MAXNWIN) { - err_setstr(StdwinError, "creating too many windows"); - return NULL; - } - wp = NEWOBJ(windowobject, &Windowtype); - if (wp == NULL) - return NULL; - INCREF(title); - wp->w_title = title; - wp->w_win = wopen(getstringvalue(title), (void (*)()) NULL); - wp->w_attr = NULL; - if (wp->w_win == NULL) { - DECREF(wp); - return NULL; - } - windowlist[tag] = wp; - wsettag(wp->w_win, tag); - return (object *)wp; -} - -static object * -window2object(win) - WINDOW *win; -{ - object *w; - if (win == NULL) - w = None; - else { - int tag = wgettag(win); - if (tag < 0 || tag >= MAXNWIN || windowlist[tag] == NULL || - windowlist[tag]->w_win != win) - w = None; - else - w = (object *)windowlist[tag]; - } - INCREF(w); - return w; -} - -static object * -stdwin_get_poll_event(poll, args) - int poll; - object *args; -{ - EVENT e; - object *u, *v, *w; - if (!getnoarg(args)) - return NULL; - if (Drawing != NULL) { - err_setstr(StdwinError, "cannot getevent() while drawing"); - return NULL; - } - again: - BGN_STDWIN - if (poll) { - if (!wpollevent(&e)) { - RET_STDWIN - INCREF(None); - return None; - } - } - else - wgetevent(&e); - END_STDWIN - if (e.type == WE_COMMAND && e.u.command == WC_CANCEL) { - /* Turn keyboard interrupts into exceptions */ - err_set(KeyboardInterrupt); - return NULL; - } - if (e.type == WE_COMMAND && e.u.command == WC_CLOSE) { - /* Turn WC_CLOSE commands into WE_CLOSE events */ - e.type = WE_CLOSE; - } - v = window2object(e.window); - switch (e.type) { - case WE_CHAR: - { - char c[1]; - c[0] = e.u.character; - w = newsizedstringobject(c, 1); - } - break; - case WE_COMMAND: - w = newintobject((long)e.u.command); - break; - case WE_DRAW: - w = makerect(e.u.area.left, e.u.area.top, - e.u.area.right, e.u.area.bottom); - break; - case WE_MOUSE_DOWN: - case WE_MOUSE_MOVE: - case WE_MOUSE_UP: - w = mkvalue("((ii)iii)", - e.u.where.h, e.u.where.v, - e.u.where.clicks, - e.u.where.button, - e.u.where.mask); - break; - case WE_MENU: - if (e.u.m.id >= IDOFFSET && e.u.m.id < IDOFFSET+MAXNMENU && - menulist[e.u.m.id - IDOFFSET] != NULL) - w = mkvalue("(Oi)", - menulist[e.u.m.id - IDOFFSET], e.u.m.item); - else { - /* Ghost menu event. - Can occur only on the Mac if another part - of the aplication has installed a menu; - like the THINK C console library. */ - DECREF(v); - goto again; - } - break; - case WE_KEY: - w = mkvalue("(ii)", e.u.key.code, e.u.key.mask); - break; - case WE_LOST_SEL: - w = newintobject((long)e.u.sel); - break; - default: - w = None; - INCREF(w); - break; - } - if (w == NULL) { - DECREF(v); - return NULL; - } - u = mkvalue("(iOO)", e.type, v, w); - XDECREF(v); - XDECREF(w); - return u; -} - -static object * -stdwin_getevent(sw, args) - object *sw; - object *args; -{ - return stdwin_get_poll_event(0, args); -} - -static object * -stdwin_pollevent(sw, args) - object *sw; - object *args; -{ - return stdwin_get_poll_event(1, args); -} - -static object * -stdwin_setdefwinpos(sw, args) - object *sw; - object *args; -{ - int a[2]; - if (!getpointarg(args, a)) - return NULL; - wsetdefwinpos(a[0], a[1]); - INCREF(None); - return None; -} - -static object * -stdwin_setdefwinsize(sw, args) - object *sw; - object *args; -{ - int a[2]; - if (!getpointarg(args, a)) - return NULL; - wsetdefwinsize(a[0], a[1]); - INCREF(None); - return None; -} - -static object * -stdwin_setdefscrollbars(sw, args) - object *sw; - object *args; -{ - int a[2]; - if (!getpointarg(args, a)) - return NULL; - wsetdefscrollbars(a[0], a[1]); - INCREF(None); - return None; -} - -static object * -stdwin_getdefwinpos(self, args) - object *self; - object *args; -{ - int h, v; - if (!getnoarg(args)) - return NULL; - wgetdefwinpos(&h, &v); - return makepoint(h, v); -} - -static object * -stdwin_getdefwinsize(self, args) - object *self; - object *args; -{ - int width, height; - if (!getnoarg(args)) - return NULL; - wgetdefwinsize(&width, &height); - return makepoint(width, height); -} - -static object * -stdwin_getdefscrollbars(self, args) - object *self; - object *args; -{ - int h, v; - if (!getnoarg(args)) - return NULL; - wgetdefscrollbars(&h, &v); - return makepoint(h, v); -} - -static object * -stdwin_menucreate(self, args) - object *self; - object *args; -{ - char *title; - if (!getstrarg(args, &title)) - return NULL; - wmenusetdeflocal(0); - return (object *)newmenuobject(title); -} - -static object * -stdwin_askfile(self, args) - object *self; - object *args; -{ - char *prompt, *dflt; - int new, ret; - char buf[256]; - if (!getargs(args, "(ssi)", &prompt, &dflt, &new)) - return NULL; - strncpy(buf, dflt, sizeof buf); - buf[sizeof buf - 1] = '\0'; - BGN_STDWIN - ret = waskfile(prompt, buf, sizeof buf, new); - END_STDWIN - if (!ret) { - err_set(KeyboardInterrupt); - return NULL; - } - return newstringobject(buf); -} - -static object * -stdwin_askync(self, args) - object *self; - object *args; -{ - char *prompt; - int new, ret; - if (!getargs(args, "(si)", &prompt, &new)) - return NULL; - BGN_STDWIN - ret = waskync(prompt, new); - END_STDWIN - if (ret < 0) { - err_set(KeyboardInterrupt); - return NULL; - } - return newintobject((long)ret); -} - -static object * -stdwin_askstr(self, args) - object *self; - object *args; -{ - char *prompt, *dflt; - int ret; - char buf[256]; - if (!getargs(args, "(ss)", &prompt, &dflt)) - return NULL; - strncpy(buf, dflt, sizeof buf); - buf[sizeof buf - 1] = '\0'; - BGN_STDWIN - ret = waskstr(prompt, buf, sizeof buf); - END_STDWIN - if (!ret) { - err_set(KeyboardInterrupt); - return NULL; - } - return newstringobject(buf); -} - -static object * -stdwin_message(self, args) - object *self; - object *args; -{ - char *msg; - if (!getstrarg(args, &msg)) - return NULL; - BGN_STDWIN - wmessage(msg); - END_STDWIN - INCREF(None); - return None; -} - -static object * -stdwin_fleep(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - wfleep(); - INCREF(None); - return None; -} - -static object * -stdwin_setcutbuffer(self, args) - object *self; - object *args; -{ - int i, size; - char *str; - if (!getargs(args, "(is#)", &i, &str, &size)) - return NULL; - wsetcutbuffer(i, str, size); - INCREF(None); - return None; -} - -static object * -stdwin_getactive(self, args) - object *self; - object *args; -{ - return window2object(wgetactive()); -} - -static object * -stdwin_getcutbuffer(self, args) - object *self; - object *args; -{ - int i; - char *str; - int len; - if (!getintarg(args, &i)) - return NULL; - str = wgetcutbuffer(i, &len); - if (str == NULL) { - str = ""; - len = 0; - } - return newsizedstringobject(str, len); -} - -static object * -stdwin_rotatecutbuffers(self, args) - object *self; - object *args; -{ - int i; - if (!getintarg(args, &i)) - return NULL; - wrotatecutbuffers(i); - INCREF(None); - return None; -} - -static object * -stdwin_getselection(self, args) - object *self; - object *args; -{ - int sel; - char *data; - int len; - if (!getintarg(args, &sel)) - return NULL; - data = wgetselection(sel, &len); - if (data == NULL) { - data = ""; - len = 0; - } - return newsizedstringobject(data, len); -} - -static object * -stdwin_resetselection(self, args) - object *self; - object *args; -{ - int sel; - if (!getintarg(args, &sel)) - return NULL; - wresetselection(sel); - INCREF(None); - return None; -} - -static object * -stdwin_fetchcolor(self, args) - object *self; - object *args; -{ - char *colorname; - COLOR color; - if (!getstrarg(args, &colorname)) - return NULL; - color = wfetchcolor(colorname); -#ifdef BADCOLOR - if (color == BADCOLOR) { - err_setstr(StdwinError, "color name not found"); - return NULL; - } -#endif - return newintobject((long)color); -} - -static object * -stdwin_getscrsize(self, args) - object *self; - object *args; -{ - int width, height; - if (!getnoarg(args)) - return NULL; - wgetscrsize(&width, &height); - return makepoint(width, height); -} - -static object * -stdwin_getscrmm(self, args) - object *self; - object *args; -{ - int width, height; - if (!getnoarg(args)) - return NULL; - wgetscrmm(&width, &height); - return makepoint(width, height); -} - -#ifdef unix -static object * -stdwin_connectionnumber(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newintobject((long) wconnectionnumber()); -} -#endif - -static object * -stdwin_listfontnames(self, args) - object *self; - object *args; -{ - char *pattern; - char **fontnames; - int count; - object *list; - if (!getargs(args, "z", &pattern)) - return NULL; - fontnames = wlistfontnames(pattern, &count); - list = newlistobject(count); - if (list != NULL) { - int i; - for (i = 0; i < count; i++) { - object *v = newstringobject(fontnames[i]); - if (v == NULL) { - DECREF(list); - list = NULL; - break; - } - setlistitem(list, i, v); - } - } - return list; -} - -#ifdef HAVE_BITMAPS -static object * -stdwin_newbitmap(self, args) - object *self; - object *args; -{ - int width, height; - bitmapobject *bp; - if (!getargs(args, "(ii)", &width, &height)) - return NULL; - return (object *)newbitmapobject(width, height); -} -#endif - -static struct methodlist stdwin_methods[] = { - {"askfile", stdwin_askfile}, - {"askstr", stdwin_askstr}, - {"askync", stdwin_askync}, - {"done", stdwin_done}, - {"fetchcolor", stdwin_fetchcolor}, -#ifdef unix - {"fileno", stdwin_connectionnumber}, - {"connectionnumber", stdwin_connectionnumber}, -#endif - {"fleep", stdwin_fleep}, - {"getactive", stdwin_getactive}, - {"getcutbuffer", stdwin_getcutbuffer}, - {"getdefscrollbars", stdwin_getdefscrollbars}, - {"getdefwinpos", stdwin_getdefwinpos}, - {"getdefwinsize", stdwin_getdefwinsize}, - {"getevent", stdwin_getevent}, - {"getscrmm", stdwin_getscrmm}, - {"getscrsize", stdwin_getscrsize}, - {"getselection", stdwin_getselection}, - {"listfontnames", stdwin_listfontnames}, - {"menucreate", stdwin_menucreate}, - {"message", stdwin_message}, -#ifdef HAVE_BITMAPS - {"newbitmap", stdwin_newbitmap}, -#endif - {"open", stdwin_open}, - {"pollevent", stdwin_pollevent}, - {"resetselection", stdwin_resetselection}, - {"rotatecutbuffers", stdwin_rotatecutbuffers}, - {"setcutbuffer", stdwin_setcutbuffer}, - {"setdefscrollbars", stdwin_setdefscrollbars}, - {"setdefwinpos", stdwin_setdefwinpos}, - {"setdefwinsize", stdwin_setdefwinsize}, - - /* Text measuring methods borrow code from drawing objects: */ - {"baseline", (method)drawing_baseline}, - {"lineheight", (method)drawing_lineheight}, - {"textbreak", (method)drawing_textbreak}, - {"textwidth", (method)drawing_textwidth}, - - /* Same for font setting methods: */ - {"setfont", (method)drawing_setfont}, - - /* Same for color setting/getting methods: */ - {"getbgcolor", (method)drawing_getbgcolor}, - {"getfgcolor", (method)drawing_getfgcolor}, - {"setbgcolor", (method)drawing_setbgcolor}, - {"setfgcolor", (method)drawing_setfgcolor}, - - {NULL, NULL} /* sentinel */ -}; - -#ifndef macintosh -static int -checkstringlist(args, ps, pn) - object *args; - char ***ps; - int *pn; -{ - int i, n; - char **s; - if (!is_listobject(args)) { - err_setstr(TypeError, "list of strings expected"); - return 0; - } - n = getlistsize(args); - s = NEW(char *, n+1); - if (s == NULL) { - err_nomem(); - return 0; - } - for (i = 0; i < n; i++) { - object *item = getlistitem(args, i); - if (!is_stringobject(item)) { - err_setstr(TypeError, "list of strings expected"); - return 0; - } - s[i] = getstringvalue(item); - } - s[n] = NULL; /* In case caller wants a NULL-terminated list */ - *ps = s; - *pn = n; - return 1; -} - -static int -putbackstringlist(list, s, n) - object *list; - char **s; - int n; -{ - int oldsize = getlistsize(list); - object *newlist; - int i; - if (n == oldsize) - return 1; - newlist = newlistobject(n); - for (i = 0; i < n && newlist != NULL; i++) { - object *item = newstringobject(s[i]); - if (item == NULL) { - DECREF(newlist); - newlist = NULL; - } - else - setlistitem(newlist, i, item); - } - if (newlist == NULL) - return 0; - (*list->ob_type->tp_as_sequence->sq_ass_slice) - (list, 0, oldsize, newlist); - DECREF(newlist); - return 1; -} -#endif /* macintosh */ - -void -initstdwin() -{ - object *m, *d; - static int inited = 0; - - if (!inited) { -#ifdef macintosh - winit(); - PyMac_DoYieldEnabled = 0; -#else - char buf[1000]; - int argc = 0; - char **argv = NULL; - object *sys_argv = sysget("argv"); - if (sys_argv != NULL) { - if (!checkstringlist(sys_argv, &argv, &argc)) - err_clear(); - } - if (argc > 0) { - /* If argv[0] has a ".py" suffix, remove the suffix */ - char *p = strrchr(argv[0], '.'); - if (p != NULL && strcmp(p, ".py") == 0) { - int n = p - argv[0]; - if (n >= sizeof(buf)) - n = sizeof(buf)-1; - strncpy(buf, argv[0], n); - buf[n] = '\0'; - argv[0] = buf; - } - } - winitargs(&argc, &argv); - if (argv != NULL) { - if (!putbackstringlist(sys_argv, argv, argc)) - err_clear(); - } -#endif - inited = 1; - } - m = initmodule("stdwin", stdwin_methods); - d = getmoduledict(m); - - /* Initialize stdwin.error exception */ - StdwinError = newstringobject("stdwin.error"); - if (StdwinError == NULL || dictinsert(d, "error", StdwinError) != 0) - fatal("can't define stdwin.error"); -#ifdef WITH_THREAD - StdwinLock = allocate_lock(); - if (StdwinLock == NULL) - fatal("can't allocate stdwin lock"); -#endif -} diff --git a/Modules/stropmodule.c b/Modules/stropmodule.c deleted file mode 100644 index a82c3138ed..0000000000 --- a/Modules/stropmodule.c +++ /dev/null @@ -1,602 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* strop module */ - -#include "allobjects.h" -#include "modsupport.h" - -#include <ctype.h> -/* XXX This file assumes that the <ctype.h> is*() functions - XXX are defined for all 8-bit characters! */ - -#include <errno.h> - - -static object * -split_whitespace(s, len) - char *s; - int len; -{ - int i, j, err; - object *list, *item; - - list = newlistobject(0); - if (list == NULL) - return NULL; - - i = 0; - while (i < len) { - while (i < len && isspace(Py_CHARMASK(s[i]))) { - i = i+1; - } - j = i; - while (i < len && !isspace(Py_CHARMASK(s[i]))) { - i = i+1; - } - if (j < i) { - item = newsizedstringobject(s+j, (int)(i-j)); - if (item == NULL) { - DECREF(list); - return NULL; - } - err = addlistitem(list, item); - DECREF(item); - if (err < 0) { - DECREF(list); - return NULL; - } - } - } - - return list; -} - - -static object * -strop_splitfields(self, args) - object *self; /* Not used */ - object *args; -{ - int len, n, i, j, err; - char *s, *sub; - object *list, *item; - - sub = NULL; - n = 0; - if (!newgetargs(args, "s#|z#", &s, &len, &sub, &n)) - return NULL; - if (sub == NULL) - return split_whitespace(s, len); - if (n == 0) { - err_setstr(ValueError, "empty separator"); - return NULL; - } - - list = newlistobject(0); - if (list == NULL) - return NULL; - - i = j = 0; - while (i+n <= len) { - if (s[i] == sub[0] && (n == 1 || strncmp(s+i, sub, n) == 0)) { - item = newsizedstringobject(s+j, (int)(i-j)); - if (item == NULL) - goto fail; - err = addlistitem(list, item); - DECREF(item); - if (err < 0) - goto fail; - i = j = i + n; - } - else - i++; - } - item = newsizedstringobject(s+j, (int)(len-j)); - if (item == NULL) - goto fail; - err = addlistitem(list, item); - DECREF(item); - if (err < 0) - goto fail; - - return list; - - fail: - DECREF(list); - return NULL; -} - - -static object * -strop_joinfields(self, args) - object *self; /* Not used */ - object *args; -{ - object *seq, *item, *res; - object * (*getitem) FPROTO((object *, int)); - char *sep, *p; - int seplen, seqlen, reslen, itemlen, i; - - sep = NULL; - seplen = 0; - if (!newgetargs(args, "O|s#", &seq, &sep, &seplen)) - return NULL; - if (sep == NULL) { - sep = " "; - seplen = 1; - } - if (is_listobject(seq)) { - getitem = getlistitem; - seqlen = getlistsize(seq); - } - else if (is_tupleobject(seq)) { - getitem = gettupleitem; - seqlen = gettuplesize(seq); - } - else { - err_setstr(TypeError, "first argument must be list/tuple"); - return NULL; - } - reslen = 0; - for (i = 0; i < seqlen; i++) { - item = getitem(seq, i); - if (!is_stringobject(item)) { - err_setstr(TypeError, - "first argument must be list/tuple of strings"); - return NULL; - } - if (i > 0) - reslen = reslen + seplen; - reslen = reslen + getstringsize(item); - } - if (seqlen == 1) { - /* Optimization if there's only one item */ - item = getitem(seq, 0); - INCREF(item); - return item; - } - res = newsizedstringobject((char *)NULL, reslen); - if (res == NULL) - return NULL; - p = getstringvalue(res); - for (i = 0; i < seqlen; i++) { - item = getitem(seq, i); - if (i > 0) { - memcpy(p, sep, seplen); - p += seplen; - } - itemlen = getstringsize(item); - memcpy(p, getstringvalue(item), itemlen); - p += itemlen; - } - if (p != getstringvalue(res) + reslen) { - err_setstr(SystemError, "strop.joinfields: assertion failed"); - return NULL; - } - return res; -} - - -static object * -strop_find(self, args) - object *self; /* Not used */ - object *args; -{ - char *s, *sub; - int len, n, i; - - if (getargs(args, "(s#s#i)", &s, &len, &sub, &n, &i)) { - if (i < 0) - i += len; - if (i < 0) - i = 0; - } - else { - err_clear(); - if (!getargs(args, "(s#s#)", &s, &len, &sub, &n)) - return NULL; - i = 0; - } - - if (n == 0) - return newintobject((long)i); - - len -= n; - for (; i <= len; ++i) - if (s[i] == sub[0] && - (n == 1 || strncmp(&s[i+1], &sub[1], n-1) == 0)) - return newintobject((long)i); - - return newintobject(-1L); -} - - -static object * -strop_rfind(self, args) - object *self; /* Not used */ - object *args; -{ - char *s, *sub; - int len, n, i, j; - - if (getargs(args, "(s#s#i)", &s, &len, &sub, &n, &i)) { - if (i < 0) - i += len; - if (i < 0) - i = 0; - } - else { - err_clear(); - if (!getargs(args, "(s#s#)", &s, &len, &sub, &n)) - return NULL; - i = 0; - } - - if (n == 0) - return newintobject((long)len); - - for (j = len-n; j >= i; --j) - if (s[j] == sub[0] && - (n == 1 || strncmp(&s[j+1], &sub[1], n-1) == 0)) - return newintobject((long)j); - - return newintobject(-1L); -} - - -static object * -strop_strip(self, args) - object *self; /* Not used */ - object *args; -{ - char *s; - int len, i, j; - - if (!getargs(args, "s#", &s, &len)) - return NULL; - - i = 0; - while (i < len && isspace(Py_CHARMASK(s[i]))) { - i++; - } - - j = len; - do { - j--; - } while (j >= i && isspace(Py_CHARMASK(s[j]))); - j++; - - if (i == 0 && j == len) { - INCREF(args); - return args; - } - else - return newsizedstringobject(s+i, j-i); -} - - -static object * -strop_lower(self, args) - object *self; /* Not used */ - object *args; -{ - char *s, *s_new; - int i, n; - object *new; - int changed; - - if (!getargs(args, "s#", &s, &n)) - return NULL; - new = newsizedstringobject(NULL, n); - if (new == NULL) - return NULL; - s_new = getstringvalue(new); - changed = 0; - for (i = 0; i < n; i++) { - int c = Py_CHARMASK(*s++); - if (isupper(c)) { - changed = 1; - *s_new = tolower(c); - } else - *s_new = c; - s_new++; - } - if (!changed) { - DECREF(new); - INCREF(args); - return args; - } - return new; -} - - -static object * -strop_upper(self, args) - object *self; /* Not used */ - object *args; -{ - char *s, *s_new; - int i, n; - object *new; - int changed; - - if (!getargs(args, "s#", &s, &n)) - return NULL; - new = newsizedstringobject(NULL, n); - if (new == NULL) - return NULL; - s_new = getstringvalue(new); - changed = 0; - for (i = 0; i < n; i++) { - int c = Py_CHARMASK(*s++); - if (islower(c)) { - changed = 1; - *s_new = toupper(c); - } else - *s_new = c; - s_new++; - } - if (!changed) { - DECREF(new); - INCREF(args); - return args; - } - return new; -} - - -static object * -strop_swapcase(self, args) - object *self; /* Not used */ - object *args; -{ - char *s, *s_new; - int i, n; - object *new; - int changed; - - if (!getargs(args, "s#", &s, &n)) - return NULL; - new = newsizedstringobject(NULL, n); - if (new == NULL) - return NULL; - s_new = getstringvalue(new); - changed = 0; - for (i = 0; i < n; i++) { - int c = Py_CHARMASK(*s++); - if (islower(c)) { - changed = 1; - *s_new = toupper(c); - } - else if (isupper(c)) { - changed = 1; - *s_new = tolower(c); - } - else - *s_new = c; - s_new++; - } - if (!changed) { - DECREF(new); - INCREF(args); - return args; - } - return new; -} - - -static object * -strop_atoi(self, args) - object *self; /* Not used */ - object *args; -{ - extern long mystrtol PROTO((const char *, char **, int)); - extern unsigned long mystrtoul PROTO((const char *, char **, int)); - char *s, *end; - int base = 10; - long x; - - if (args != NULL && is_tupleobject(args)) { - if (!getargs(args, "(si)", &s, &base)) - return NULL; - if (base != 0 && base < 2 || base > 36) { - err_setstr(ValueError, "invalid base for atoi()"); - return NULL; - } - } - else if (!getargs(args, "s", &s)) - return NULL; - errno = 0; - if (base == 0 && s[0] == '0') - x = (long) mystrtoul(s, &end, base); - else - x = mystrtol(s, &end, base); - if (*end != '\0') { - err_setstr(ValueError, "invalid literal for atoi()"); - return NULL; - } - else if (errno != 0) { - err_setstr(OverflowError, "atoi() literal too large"); - return NULL; - } - return newintobject(x); -} - - -static object * -strop_atol(self, args) - object *self; /* Not used */ - object *args; -{ - char *s, *end; - int base = 10; - object *x; - - if (args != NULL && is_tupleobject(args)) { - if (!getargs(args, "(si)", &s, &base)) - return NULL; - if (base != 0 && base < 2 || base > 36) { - err_setstr(ValueError, "invalid base for atol()"); - return NULL; - } - } - else if (!getargs(args, "s", &s)) - return NULL; - x = long_escan(s, &end, base); - if (x == NULL) - return NULL; - if (base == 0 && (*end == 'l' || *end == 'L')) - end++; - if (*end != '\0') { - err_setstr(ValueError, "invalid literal for atol()"); - DECREF(x); - return NULL; - } - return x; -} - - -static object * -strop_atof(self, args) - object *self; /* Not used */ - object *args; -{ - extern double strtod PROTO((const char *, char **)); - char *s, *end; - double x; - - if (!getargs(args, "s", &s)) - return NULL; - errno = 0; - x = strtod(s, &end); - if (*end != '\0') { - err_setstr(ValueError, "invalid literal for atof()"); - return NULL; - } - else if (errno != 0) { - err_setstr(OverflowError, "atof() literal too large"); - return NULL; - } - return newfloatobject(x); -} - - -static object * -strop_translate(self, args) - object *self; - object *args; -{ - char *input, *table, *output; - int inlen, tablen; - object *result; - int i; - - if (!newgetargs(args, "s#s#", &input, &inlen, &table, &tablen)) - return NULL; - if (tablen != 256) { - err_setstr(ValueError, - "translation table must be 256 characters long"); - return NULL; - } - result = newsizedstringobject((char *)NULL, inlen); - if (result == NULL) - return NULL; - output = getstringvalue(result); - for (i = 0; i < inlen; i++) { - int c = Py_CHARMASK(*input++); - *output++ = table[c]; - } - return result; -} - - -/* List of functions defined in the module */ - -static struct methodlist strop_methods[] = { - {"atof", strop_atof}, - {"atoi", strop_atoi}, - {"atol", strop_atol}, - {"find", strop_find}, - {"join", strop_joinfields, 1}, - {"joinfields", strop_joinfields, 1}, - {"lower", strop_lower}, - {"rfind", strop_rfind}, - {"split", strop_splitfields, 1}, - {"splitfields", strop_splitfields, 1}, - {"strip", strop_strip}, - {"swapcase", strop_swapcase}, - {"translate", strop_translate, 1}, - {"upper", strop_upper}, - {NULL, NULL} /* sentinel */ -}; - - -void -initstrop() -{ - object *m, *d, *s; - char buf[256]; - int c, n; - m = initmodule("strop", strop_methods); - d = getmoduledict(m); - - /* Create 'whitespace' object */ - n = 0; - for (c = 0; c < 256; c++) { - if (isspace(c)) - buf[n++] = c; - } - s = newsizedstringobject(buf, n); - if (s) { - dictinsert(d, "whitespace", s); - DECREF(s); - } - /* Create 'lowercase' object */ - n = 0; - for (c = 0; c < 256; c++) { - if (islower(c)) - buf[n++] = c; - } - s = newsizedstringobject(buf, n); - if (s) { - dictinsert(d, "lowercase", s); - DECREF(s); - } - - /* Create 'uppercase' object */ - n = 0; - for (c = 0; c < 256; c++) { - if (isupper(c)) - buf[n++] = c; - } - s = newsizedstringobject(buf, n); - if (s) { - dictinsert(d, "uppercase", s); - DECREF(s); - } - - if (err_occurred()) - fatal("can't initialize module strop"); -} diff --git a/Modules/structmodule.c b/Modules/structmodule.c deleted file mode 100644 index 649f330710..0000000000 --- a/Modules/structmodule.c +++ /dev/null @@ -1,487 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* struct module -- pack values into and (out of) strings */ - -#include "allobjects.h" -#include "modsupport.h" - -static object *StructError; - - -/* Define various structs to figure out the alignments of types */ - -#ifdef __MWERKS__ -/* -** XXXX We have a problem here. There are no unique alignment rules -** on the PowerPC mac. -*/ -#ifdef __powerc -#pragma options align=mac68k -#endif -#endif /* __MWERKS__ */ - -typedef struct { char c; short x; } s_short; -typedef struct { char c; int x; } s_int; -typedef struct { char c; long x; } s_long; -typedef struct { char c; float x; } s_float; -typedef struct { char c; double x; } s_double; - -#define SHORT_ALIGN (sizeof(s_short) - sizeof(short)) -#define INT_ALIGN (sizeof(s_int) - sizeof(int)) -#define LONG_ALIGN (sizeof(s_long) - sizeof(long)) -#define FLOAT_ALIGN (sizeof(s_float) - sizeof(float)) -#define DOUBLE_ALIGN (sizeof(s_double) - sizeof(double)) - -#ifdef __powerc -#pragma options align=reset -#endif - - -/* Align a size according to a format code */ - -static int -align(size, c) - int size; - int c; -{ - int a; - - switch (c) { - case 'h': a = SHORT_ALIGN; break; - case 'i': a = INT_ALIGN; break; - case 'l': a = LONG_ALIGN; break; - case 'f': a = FLOAT_ALIGN; break; - case 'd': a = DOUBLE_ALIGN; break; - default: return size; - } - return (size + a - 1) / a * a; -} - - -/* calculate the size of a format string */ - -static int -calcsize(fmt) - char *fmt; -{ - char *s; - char c; - int size, num, itemsize, x; - - s = fmt; - size = 0; - while ((c = *s++) != '\0') { - if ('0' <= c && c <= '9') { - num = c - '0'; - while ('0' <= (c = *s++) && c <= '9') { - x = num*10 + (c - '0'); - if (x/10 != num) { - err_setstr(StructError, - "int overflow in fmt"); - return -1; - } - num = x; - } - if (c == '\0') - break; - } - else - num = 1; - - size = align(size, c); - - switch (c) { - - case 'x': /* pad byte */ - case 'b': /* byte-sized int */ - case 'c': /* char */ - itemsize = 1; - break; - - case 'h': /* short ("half-size)" int */ - itemsize = sizeof(short); - break; - - case 'i': /* natural-size int */ - itemsize = sizeof(int); - break; - - case 'l': /* long int */ - itemsize = sizeof(long); - break; - - case 'f': /* float */ - itemsize = sizeof(float); - break; - - case 'd': /* double */ - itemsize = sizeof(double); - break; - - default: - err_setstr(StructError, "bad char in fmt"); - return -1; - - } - - x = num * itemsize; - size += x; - if (x/itemsize != num || size < 0) { - err_setstr(StructError, "total struct size too long"); - return -1; - } - - } - - return size; -} - - -/* pack(fmt, v1, v2, ...) --> string */ - -static object * -struct_calcsize(self, args) - object *self; /* Not used */ - object *args; -{ - char *fmt; - int size; - - if (!getargs(args, "s", &fmt)) - return NULL; - size = calcsize(fmt); - if (size < 0) - return NULL; - return newintobject((long)size); -} - - -/* pack(fmt, v1, v2, ...) --> string */ - -static object * -struct_pack(self, args) - object *self; /* Not used */ - object *args; -{ - object *format, *result, *v; - char *fmt; - int size, num; - int i, n; - char *s, *res, *restart; - char c; - long ival; - double fval; - - if (args == NULL || !is_tupleobject(args) || - (n = gettuplesize(args)) < 1) { - err_badarg(); - return NULL; - } - format = gettupleitem(args, 0); - if (!getargs(format, "s", &fmt)) - return NULL; - size = calcsize(fmt); - if (size < 0) - return NULL; - result = newsizedstringobject((char *)NULL, size); - if (result == NULL) - return NULL; - - s = fmt; - i = 1; - res = restart = getstringvalue(result); - - while ((c = *s++) != '\0') { - if ('0' <= c && c <= '9') { - num = c - '0'; - while ('0' <= (c = *s++) && c <= '9') - num = num*10 + (c - '0'); - if (c == '\0') - break; - } - else - num = 1; - - res = restart + align((int)(res-restart), c); - - while (--num >= 0) { - switch (c) { - - case 'x': /* pad byte */ - *res++ = '\0'; - break; - - case 'l': - case 'i': - case 'h': - case 'b': - if (i >= n) { - err_setstr(StructError, - "insufficient arguments to pack"); - goto fail; - } - v = gettupleitem(args, i++); - if (!is_intobject(v)) { - err_setstr(StructError, - "bad argument type to pack"); - goto fail; - } - ival = getintvalue(v); - switch (c) { - case 'b': - *res++ = ival; - break; - case 'h': - *(short*)res = ival; - res += sizeof(short); - break; - case 'i': - *(int*)res = ival; - res += sizeof(int); - break; - case 'l': - *(long*)res = ival; - res += sizeof(long); - break; - } - break; - - case 'c': - if (i >= n) { - err_setstr(StructError, - "insufficient arguments to pack"); - goto fail; - } - v = gettupleitem(args, i++); - if (!is_stringobject(v) || - getstringsize(v) != 1) { - err_setstr(StructError, - "bad argument type to pack"); - goto fail; - } - *res++ = getstringvalue(v)[0]; - break; - - case 'd': - case 'f': - if (i >= n) { - err_setstr(StructError, - "insufficient arguments to pack"); - goto fail; - } - v = gettupleitem(args, i++); - if (!is_floatobject(v)) { - err_setstr(StructError, - "bad argument type to pack"); - goto fail; - } - fval = getfloatvalue(v); - switch (c) { - case 'f': - *(float*)res = (float)fval; - res += sizeof(float); - break; - case 'd': - memcpy(res, (char*)&fval, sizeof fval); - res += sizeof(double); - break; - } - break; - - default: - err_setstr(StructError, "bad char in fmt"); - goto fail; - - } - } - } - - if (i < n) { - err_setstr(StructError, "too many arguments for pack fmt"); - goto fail; - } - - return result; - - fail: - DECREF(result); - return NULL; -} - - -/* Helper to convert a list to a tuple */ - -static object * -totuple(list) - object *list; -{ - int len = getlistsize(list); - object *tuple = newtupleobject(len); - if (tuple != NULL) { - int i; - for (i = 0; i < len; i++) { - object *v = getlistitem(list, i); - INCREF(v); - settupleitem(tuple, i, v); - } - } - DECREF(list); - return tuple; -} - - -/* unpack(fmt, string) --> (v1, v2, ...) */ - -static object * -struct_unpack(self, args) - object *self; /* Not used */ - object *args; -{ - char *str, *start, *fmt, *s; - char c; - int len, size, num, x; - object *res, *v; - - if (!getargs(args, "(ss#)", &fmt, &start, &len)) - return NULL; - size = calcsize(fmt); - if (size != len) { - err_setstr(StructError, "unpack str size does not match fmt"); - return NULL; - } - res = newlistobject(0); - if (res == NULL) - return NULL; - str = start; - s = fmt; - while ((c = *s++) != '\0') { - if ('0' <= c && c <= '9') { - num = c - '0'; - while ('0' <= (c = *s++) && c <= '9') - num = num*10 + (c - '0'); - if (c == '\0') - break; - } - else - num = 1; - - str = start + align((int)(str-start), c); - - while (--num >= 0) { - switch (c) { - - case 'x': - str++; - continue; - - case 'b': - x = *str++; - if (x >= 128) - x -= 256; - v = newintobject((long)x); - break; - - case 'c': - v = newsizedstringobject(str, 1); - str++; - break; - - case 'h': - v = newintobject((long)*(short*)str); - str += sizeof(short); - break; - - case 'i': - v = newintobject((long)*(int*)str); - str += sizeof(int); - break; - - case 'l': - v = newintobject(*(long*)str); - str += sizeof(long); - break; - - case 'f': - v = newfloatobject((double)*(float*)str); - str += sizeof(float); - break; - - case 'd': - { - double d; - memcpy((char *)&d, str, sizeof d); - v = newfloatobject(d); - str += sizeof(double); - break; - } - - default: - err_setstr(StructError, "bad char in fmt"); - goto fail; - - } - if (v == NULL || addlistitem(res, v) < 0) - goto fail; - DECREF(v); - } - } - - return totuple(res); - - fail: - DECREF(res); - return NULL; -} - - -/* List of functions */ - -static struct methodlist struct_methods[] = { - {"calcsize", struct_calcsize}, - {"pack", struct_pack, 1/*varargs*/}, - {"unpack", struct_unpack}, - {NULL, NULL} /* sentinel */ -}; - - -/* Module initialization */ - -void -initstruct() -{ - object *m, *d; - - /* Create the module and add the functions */ - m = initmodule("struct", struct_methods); - - /* Add some symbolic constants to the module */ - d = getmoduledict(m); - StructError = newstringobject("struct.error"); - dictinsert(d, "error", StructError); - - /* Check for errors */ - if (err_occurred()) - fatal("can't initialize module struct"); -} diff --git a/Modules/sunaudiodev.c b/Modules/sunaudiodev.c deleted file mode 100644 index fad8debf23..0000000000 --- a/Modules/sunaudiodev.c +++ /dev/null @@ -1,488 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Sad objects */ - -#include "allobjects.h" -#include "modsupport.h" -#include "structmember.h" - -#ifdef HAVE_SYS_AUDIOIO_H -#define SOLARIS -#endif - -#include <stropts.h> -#include <sys/ioctl.h> -#ifdef SOLARIS -#include <sys/audioio.h> -#else -#include <sun/audioio.h> -#endif - -/* #define offsetof(str,mem) ((int)(((str *)0)->mem)) */ - -typedef struct { - OB_HEAD - int x_fd; /* The open file */ - int x_icount; /* # samples read */ - int x_ocount; /* # samples written */ - int x_isctl; /* True if control device */ - -} sadobject; - -typedef struct { - OB_HEAD - audio_info_t ai; -} sadstatusobject; - -staticforward typeobject Sadtype; -staticforward typeobject Sadstatustype; -static sadstatusobject *sads_alloc(); /* Forward */ - -static object *SunAudioError; - -static int dummy_for_dl; - -#define is_sadobject(v) ((v)->ob_type == &Sadtype) -#define is_sadstatusobject(v) ((v)->ob_type == &Sadstatustype) - -static sadobject * -newsadobject(arg) - object *arg; -{ - sadobject *xp; - int fd; - char *mode; - int imode; - - /* Check arg for r/w/rw */ - if ( !getargs(arg, "s", &mode) ) - return 0; - if ( strcmp(mode, "r") == 0 ) - imode = 0; - else if ( strcmp(mode, "w") == 0 ) - imode = 1; - else if ( strcmp(mode, "rw") == 0 ) - imode = 2; - else if ( strcmp(mode, "control") == 0 ) - imode = -1; - else { - err_setstr(SunAudioError, - "Mode should be one of 'r', 'w', 'rw' or 'control'"); - return 0; - } - - /* Open the correct device */ - if ( imode < 0 ) - fd = open("/dev/audioctl", 2); /* XXXX Chaeck that this works */ - else - fd = open("/dev/audio", imode); - if ( fd < 0 ) { - err_errno(SunAudioError); - return NULL; - } - - /* Create and initialize the object */ - xp = NEWOBJ(sadobject, &Sadtype); - if (xp == NULL) - return NULL; - xp->x_fd = fd; - xp->x_icount = xp->x_ocount = 0; - xp->x_isctl = (imode < 0); - - return xp; -} - -/* Sad methods */ - -static void -sad_dealloc(xp) - sadobject *xp; -{ - close(xp->x_fd); - DEL(xp); -} - -static object * -sad_read(self, args) - sadobject *self; - object *args; -{ - int size, count; - char *cp; - object *rv; - - if ( !getargs(args, "i", &size) ) - return 0; - rv = newsizedstringobject(NULL, size); - if ( rv == NULL ) - return 0; - - cp = getstringvalue(rv); - - count = read(self->x_fd, cp, size); - if ( count < 0 ) { - DECREF(rv); - err_errno(SunAudioError); - return NULL; - } - if ( count != size ) - printf("sunaudio: funny read rv %d wtd %d\n", count, size); - self->x_icount += count; - return rv; -} - -static object * -sad_write(self, args) - sadobject *self; - object *args; -{ - char *cp; - int count, size; - - if ( !getargs(args, "s#", &cp, &size) ) - return 0; - - count = write(self->x_fd, cp, size); - if ( count < 0 ) { - err_errno(SunAudioError); - return NULL; - } - if ( count != size ) - printf("sunaudio: funny write rv %d wanted %d\n", count, size); - self->x_ocount += count; - - INCREF(None); - return None; -} - -static object * -sad_getinfo(self, args) - sadobject *self; - object *args; -{ - sadstatusobject *rv; - - if ( !getargs(args, "") ) - return NULL; - rv = sads_alloc(); - if ( ioctl(self->x_fd, AUDIO_GETINFO, &rv->ai) < 0 ) { - err_errno(SunAudioError); - DECREF(rv); - return NULL; - } - return (object *)rv; -} - -static object * -sad_setinfo(self, arg) - sadobject *self; - sadstatusobject *arg; -{ - if ( !is_sadstatusobject(arg) ) { - err_setstr(TypeError, "Must be sun audio status object"); - return NULL; - } - if ( ioctl(self->x_fd, AUDIO_SETINFO, &arg->ai) < 0 ) { - err_errno(SunAudioError); - return NULL; - } - INCREF(None); - return None; -} - -static object * -sad_ibufcount(self, args) - sadobject *self; - object *args; -{ - audio_info_t ai; - object *rv; - - if ( !getargs(args, "") ) - return 0; - if ( ioctl(self->x_fd, AUDIO_GETINFO, &ai) < 0 ) { - err_errno(SunAudioError); - return NULL; - } - rv = newintobject(ai.record.samples - self->x_icount); - return rv; -} - -static object * -sad_obufcount(self, args) - sadobject *self; - object *args; -{ - audio_info_t ai; - object *rv; - - if ( !getargs(args, "") ) - return 0; - if ( ioctl(self->x_fd, AUDIO_GETINFO, &ai) < 0 ) { - err_errno(SunAudioError); - return NULL; - } - rv = newintobject(self->x_ocount - ai.play.samples); - return rv; -} - -static object * -sad_drain(self, args) - sadobject *self; - object *args; -{ - - if ( !getargs(args, "") ) - return 0; - if ( ioctl(self->x_fd, AUDIO_DRAIN, 0) < 0 ) { - err_errno(SunAudioError); - return NULL; - } - INCREF(None); - return None; -} - -#ifdef SOLARIS -static object * -sad_getdev(self, args) - sadobject *self; - object *args; -{ - struct audio_device ad; - - if ( !getargs(args, "") ) - return 0; - if ( ioctl(self->x_fd, AUDIO_GETDEV, &ad) < 0 ) { - err_errno(SunAudioError); - return NULL; - } - return mkvalue("(sss)", ad.name, ad.version, ad.config); -} -#endif - -static object * -sad_flush(self, args) - sadobject *self; - object *args; -{ - - if ( !getargs(args, "") ) - return 0; - if ( ioctl(self->x_fd, I_FLUSH, FLUSHW) < 0 ) { - err_errno(SunAudioError); - return NULL; - } - INCREF(None); - return None; -} - -static object * -sad_close(self, args) - sadobject *self; - object *args; -{ - - if ( !getargs(args, "") ) - return 0; - if ( self->x_fd >= 0 ) { - close(self->x_fd); - self->x_fd = -1; - } - INCREF(None); - return None; -} - -static struct methodlist sad_methods[] = { - { "read", (method)sad_read }, - { "write", (method)sad_write }, - { "ibufcount", (method)sad_ibufcount }, - { "obufcount", (method)sad_obufcount }, -#define CTL_METHODS 4 - { "getinfo", (method)sad_getinfo }, - { "setinfo", (method)sad_setinfo }, - { "drain", (method)sad_drain }, - { "flush", (method)sad_flush }, -#ifdef SOLARIS - { "getdev", (method)sad_getdev }, -#endif - { "close", (method)sad_close }, - {NULL, NULL} /* sentinel */ -}; - -static object * -sad_getattr(xp, name) - sadobject *xp; - char *name; -{ - if ( xp->x_isctl ) - return findmethod(sad_methods+CTL_METHODS, (object *)xp, name); - else - return findmethod(sad_methods, (object *)xp, name); -} - -/* ----------------------------------------------------------------- */ - -static sadstatusobject * -sads_alloc() { - sadstatusobject *rv; - - rv = NEWOBJ(sadstatusobject, &Sadstatustype); - return rv; -} - -static void -sads_dealloc(xp) - sadstatusobject *xp; -{ - DEL(xp); -} - -#define OFF(x) offsetof(audio_info_t,x) -static struct memberlist sads_ml[] = { - { "i_sample_rate", T_UINT, OFF(record.sample_rate) }, - { "i_channels", T_UINT, OFF(record.channels) }, - { "i_precision", T_UINT, OFF(record.precision) }, - { "i_encoding", T_UINT, OFF(record.encoding) }, - { "i_gain", T_UINT, OFF(record.gain) }, - { "i_port", T_UINT, OFF(record.port) }, - { "i_samples", T_UINT, OFF(record.samples) }, - { "i_eof", T_UINT, OFF(record.eof) }, - { "i_pause", T_UBYTE, OFF(record.pause) }, - { "i_error", T_UBYTE, OFF(record.error) }, - { "i_waiting", T_UBYTE, OFF(record.waiting) }, - { "i_open", T_UBYTE, OFF(record.open) , RO}, - { "i_active", T_UBYTE, OFF(record.active) , RO}, -#ifdef SOLARIS - { "i_buffer_size", T_UINT, OFF(record.buffer_size) }, - { "i_balance", T_UBYTE, OFF(record.balance) }, - { "i_avail_ports", T_UINT, OFF(record.avail_ports) }, -#endif - - { "o_sample_rate", T_UINT, OFF(play.sample_rate) }, - { "o_channels", T_UINT, OFF(play.channels) }, - { "o_precision", T_UINT, OFF(play.precision) }, - { "o_encoding", T_UINT, OFF(play.encoding) }, - { "o_gain", T_UINT, OFF(play.gain) }, - { "o_port", T_UINT, OFF(play.port) }, - { "o_samples", T_UINT, OFF(play.samples) }, - { "o_eof", T_UINT, OFF(play.eof) }, - { "o_pause", T_UBYTE, OFF(play.pause) }, - { "o_error", T_UBYTE, OFF(play.error) }, - { "o_waiting", T_UBYTE, OFF(play.waiting) }, - { "o_open", T_UBYTE, OFF(play.open) , RO}, - { "o_active", T_UBYTE, OFF(play.active) , RO}, -#ifdef SOLARIS - { "o_buffer_size", T_UINT, OFF(play.buffer_size) }, - { "o_balance", T_UBYTE, OFF(play.balance) }, - { "o_avail_ports", T_UINT, OFF(play.avail_ports) }, -#endif - - { "monitor_gain", T_UINT, OFF(monitor_gain) }, - { NULL, 0, 0}, -}; - -static object * -sads_getattr(xp, name) - sadstatusobject *xp; - char *name; -{ - return getmember((char *)&xp->ai, sads_ml, name); -} - -static int -sads_setattr(xp, name, v) - sadstatusobject *xp; - char *name; - object *v; -{ - - if (v == NULL) { - err_setstr(TypeError, - "can't delete sun audio status attributes"); - return 0; - } - return setmember((char *)&xp->ai, sads_ml, name, v); -} - -/* ------------------------------------------------------------------- */ - - -static typeobject Sadtype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "sun_audio_device", /*tp_name*/ - sizeof(sadobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)sad_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)sad_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - -static typeobject Sadstatustype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "sun_audio_device_status", /*tp_name*/ - sizeof(sadstatusobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)sads_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)sads_getattr, /*tp_getattr*/ - (setattrfunc)sads_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; -/* ------------------------------------------------------------------- */ - -static object * -sadopen(self, args) - object *self; - object *args; -{ - object *rv; - - rv = (object *)newsadobject(args); - return rv; -} - -static struct methodlist sunaudiodev_methods[] = { - { "open", sadopen }, - { 0, 0 }, -}; - -void -initsunaudiodev() { - object *m, *d; - - m = initmodule("sunaudiodev", sunaudiodev_methods); - d = getmoduledict(m); - SunAudioError = newstringobject("sunaudiodev.error"); - if ( SunAudioError == NULL || dictinsert(d, "error", SunAudioError) ) - fatal("can't define sunaudiodev.error"); -} diff --git a/Modules/svmodule.c b/Modules/svmodule.c deleted file mode 100644 index dd48b7aea9..0000000000 --- a/Modules/svmodule.c +++ /dev/null @@ -1,994 +0,0 @@ -/********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* SV module -- interface to the Indigo video board */ - -#include <sys/time.h> -#include <svideo.h> -#include "allobjects.h" -#include "import.h" -#include "modsupport.h" -#include "compile.h" -#include "ceval.h" -#include "yuv.h" /* for YUV conversion functions */ - -typedef struct { - OB_HEAD - SV_nodeP ob_svideo; - svCaptureInfo ob_info; -} svobject; - -typedef struct { - OB_HEAD - void *ob_capture; - int ob_mustunlock; - svCaptureInfo ob_info; - svobject *ob_svideo; -} captureobject; - -static object *SvError; /* exception sv.error */ - -static object *newcaptureobject PROTO((svobject *, void *, int)); - -/* Set a SV-specific error from svideo_errno and return NULL */ -static object * -sv_error() -{ - err_setstr(SvError, svStrerror(svideo_errno)); - return NULL; -} - -static object * -svc_conversion(self, args, function, factor) - captureobject *self; - object *args; - void (*function)(); - float factor; -{ - object *output; - int invert; - - if (!getargs(args, "i", &invert)) - return NULL; - - output = newsizedstringobject(NULL, (int) (self->ob_info.width * self->ob_info.height * factor)); - if (output == NULL) - return NULL; - - (*function)((boolean) invert, self->ob_capture, getstringvalue(output), - self->ob_info.width, self->ob_info.height); - - return output; -} - -/* - * 3 functions to convert from Starter Video YUV 4:1:1 format to - * Compression Library 4:2:2 Duplicate Chroma format. - */ -static object * -svc_YUVtoYUV422DC(self, args) - captureobject *self; - object *args; -{ - if (self->ob_info.format != SV_YUV411_FRAMES) { - err_setstr(SvError, "data has bad format"); - return NULL; - } - return svc_conversion(self, args, yuv_sv411_to_cl422dc, 2.0); -} - -static object * -svc_YUVtoYUV422DC_quarter(self, args) - captureobject *self; - object *args; -{ - if (self->ob_info.format != SV_YUV411_FRAMES) { - err_setstr(SvError, "data has bad format"); - return NULL; - } - return svc_conversion(self, args, yuv_sv411_to_cl422dc_quartersize, 0.5); -} - -static object * -svc_YUVtoYUV422DC_sixteenth(self, args) - captureobject *self; - object *args; -{ - if (self->ob_info.format != SV_YUV411_FRAMES) { - err_setstr(SvError, "data has bad format"); - return NULL; - } - return svc_conversion(self, args, yuv_sv411_to_cl422dc_sixteenthsize, 0.125); -} - -static object * -svc_YUVtoRGB(self, args) - captureobject *self; - object *args; -{ - switch (self->ob_info.format) { - case SV_YUV411_FRAMES: - case SV_YUV411_FRAMES_AND_BLANKING_BUFFER: - break; - default: - err_setstr(SvError, "data had bad format"); - return NULL; - } - return svc_conversion(self, args, svYUVtoRGB, (float) sizeof(long)); -} - -static object * -svc_RGB8toRGB32(self, args) - captureobject *self; - object *args; -{ - if (self->ob_info.format != SV_RGB8_FRAMES) { - err_setstr(SvError, "data has bad format"); - return NULL; - } - return svc_conversion(self, args, svRGB8toRGB32, (float) sizeof(long)); -} - -static object * -svc_InterleaveFields(self, args) - captureobject *self; - object *args; -{ - if (self->ob_info.format != SV_RGB8_FRAMES) { - err_setstr(SvError, "data has bad format"); - return NULL; - } - return svc_conversion(self, args, svInterleaveFields, 1.0); -} - -static object * -svc_GetFields(self, args) - captureobject *self; - object *args; -{ - object *f1, *f2, *ret; - int fieldsize; - - if (self->ob_info.format != SV_RGB8_FRAMES) { - err_setstr(SvError, "data has bad format"); - return NULL; - } - - fieldsize = self->ob_info.width * self->ob_info.height / 2; - f1 = newsizedstringobject((char *) self->ob_capture, fieldsize); - f2 = newsizedstringobject((char *) self->ob_capture + fieldsize, fieldsize); - ret = mkvalue("(OO)", f1, f2); - XDECREF(f1); - XDECREF(f2); - return ret; -} - -static object * -svc_UnlockCaptureData(self, args) - captureobject *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - - if (!self->ob_mustunlock) { - err_setstr(SvError, "buffer should not be unlocked"); - return NULL; - } - - if (svUnlockCaptureData(self->ob_svideo->ob_svideo, self->ob_capture)) - return sv_error(); - - self->ob_mustunlock = 0; - - INCREF(None); - return None; -} - -#ifdef USE_GL -#include <gl.h> - -static object * -svc_lrectwrite(self, args) - captureobject *self; - object *args; -{ - Screencoord x1, x2, y1, y2; - - if (!getargs(args, "(hhhh)", &x1, &x2, &y1, &y2)) - return NULL; - - lrectwrite(x1, x2, y1, y2, (unsigned long *) self->ob_capture); - - INCREF(None); - return None; -} -#endif - -static object * -svc_writefile(self, args) - captureobject *self; - object *args; -{ - object *file; - int size; - - if (!getargs(args, "O", &file)) - return NULL; - - if (!is_fileobject(file)) { - err_setstr(SvError, "not a file object"); - return NULL; - } - - size = self->ob_info.width * self->ob_info.height; - - if (fwrite(self->ob_capture, sizeof(long), size, getfilefile(file)) != size) { - err_setstr(SvError, "writing failed"); - return NULL; - } - - INCREF(None); - return None; -} - -static object * -svc_FindVisibleRegion(self, args) - captureobject *self; - object *args; -{ - void *visible; - int width; - - if (!getnoarg(args)) - return NULL; - - if (svFindVisibleRegion(self->ob_svideo->ob_svideo, self->ob_capture, &visible, self->ob_info.width)) - return sv_error(); - - if (visible == NULL) { - err_setstr(SvError, "data in wrong format"); - return NULL; - } - - return newcaptureobject(self->ob_svideo, visible, 0); -} - -static struct methodlist capture_methods[] = { - {"YUVtoRGB", (method)svc_YUVtoRGB}, - {"RGB8toRGB32", (method)svc_RGB8toRGB32}, - {"InterleaveFields", (method)svc_InterleaveFields}, - {"UnlockCaptureData", (method)svc_UnlockCaptureData}, - {"FindVisibleRegion", (method)svc_FindVisibleRegion}, - {"GetFields", (method)svc_GetFields}, - {"YUVtoYUV422DC", (method)svc_YUVtoYUV422DC}, - {"YUVtoYUV422DC_quarter",(method)svc_YUVtoYUV422DC_quarter}, - {"YUVtoYUV422DC_sixteenth",(method)svc_YUVtoYUV422DC_sixteenth}, -#ifdef USE_GL - {"lrectwrite", (method)svc_lrectwrite}, -#endif - {"writefile", (method)svc_writefile}, - {NULL, NULL} /* sentinel */ -}; - -static void -capture_dealloc(self) - captureobject *self; -{ - if (self->ob_capture != NULL) { - if (self->ob_mustunlock) - (void) svUnlockCaptureData(self->ob_svideo->ob_svideo, self->ob_capture); - self->ob_capture = NULL; - DECREF(self->ob_svideo); - self->ob_svideo = NULL; - } - DEL(self); -} - -static object * -capture_getattr(self, name) - svobject *self; - char *name; -{ - return findmethod(capture_methods, (object *)self, name); -} - -typeobject Capturetype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "capture", /*tp_name*/ - sizeof(captureobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)capture_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)capture_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - -static object * -newcaptureobject(self, ptr, mustunlock) - svobject *self; - void *ptr; - int mustunlock; -{ - captureobject *p; - - p = NEWOBJ(captureobject, &Capturetype); - if (p == NULL) - return NULL; - p->ob_svideo = self; - INCREF(self); - p->ob_capture = ptr; - p->ob_mustunlock = mustunlock; - p->ob_info = self->ob_info; - return (object *) p; -} - -static object * -sv_GetCaptureData(self, args) - svobject *self; - object *args; -{ - void *ptr; - long fieldID; - object *res, *c; - - if (!getnoarg(args)) - return NULL; - - if (svGetCaptureData(self->ob_svideo, &ptr, &fieldID)) - return sv_error(); - - if (ptr == NULL) { - err_setstr(SvError, "no data available"); - return NULL; - } - - c = newcaptureobject(self, ptr, 1); - if (c == NULL) - return NULL; - res = mkvalue("(Oi)", c, fieldID); - DECREF(c); - return res; -} - -static object * -sv_BindGLWindow(self, args) - svobject *self; - object *args; -{ - long wid; - int mode; - - if (!getargs(args, "(ii)", &wid, &mode)) - return NULL; - - if (svBindGLWindow(self->ob_svideo, wid, mode)) - return sv_error(); - - INCREF(None); - return None; -} - -static object * -sv_EndContinuousCapture(self, args) - svobject *self; - object *args; -{ - - if (!getnoarg(args)) - return NULL; - - if (svEndContinuousCapture(self->ob_svideo)) - return sv_error(); - - INCREF(None); - return None; -} - -static object * -sv_IsVideoDisplayed(self, args) - svobject *self; - object *args; -{ - int v; - - if (!getnoarg(args)) - return NULL; - - v = svIsVideoDisplayed(self->ob_svideo); - if (v == -1) - return sv_error(); - - return newintobject((long) v); -} - -static object * -sv_OutputOffset(self, args) - svobject *self; - object *args; -{ - int x_offset; - int y_offset; - - if (!getargs(args, "(ii)", &x_offset, &y_offset)) - return NULL; - - if (svOutputOffset(self->ob_svideo, x_offset, y_offset)) - return sv_error(); - - INCREF(None); - return None; -} - -static object * -sv_PutFrame(self, args) - svobject *self; - object *args; -{ - char *buffer; - - if (!getargs(args, "s", &buffer)) - return NULL; - - if (svPutFrame(self->ob_svideo, buffer)) - return sv_error(); - - INCREF(None); - return None; -} - -static object * -sv_QuerySize(self, args) - svobject *self; - object *args; -{ - int w; - int h; - int rw; - int rh; - - if (!getargs(args, "(ii)", &w, &h)) - return NULL; - - if (svQuerySize(self->ob_svideo, w, h, &rw, &rh)) - return sv_error(); - - return mkvalue("(ii)", (long) rw, (long) rh); -} - -static object * -sv_SetSize(self, args) - svobject *self; - object *args; -{ - int w; - int h; - - if (!getargs(args, "(ii)", &w, &h)) - return NULL; - - if (svSetSize(self->ob_svideo, w, h)) - return sv_error(); - - INCREF(None); - return None; -} - -static object * -sv_SetStdDefaults(self, args) - svobject *self; - object *args; -{ - - if (!getnoarg(args)) - return NULL; - - if (svSetStdDefaults(self->ob_svideo)) - return sv_error(); - - INCREF(None); - return None; -} - -static object * -sv_UseExclusive(self, args) - svobject *self; - object *args; -{ - boolean onoff; - int mode; - - if (!getargs(args, "(ii)", &onoff, &mode)) - return NULL; - - if (svUseExclusive(self->ob_svideo, onoff, mode)) - return sv_error(); - - INCREF(None); - return None; -} - -static object * -sv_WindowOffset(self, args) - svobject *self; - object *args; -{ - int x_offset; - int y_offset; - - if (!getargs(args, "(ii)", &x_offset, &y_offset)) - return NULL; - - if (svWindowOffset(self->ob_svideo, x_offset, y_offset)) - return sv_error(); - - INCREF(None); - return None; -} - -static object * -sv_CaptureBurst(self, args) - svobject *self; - object *args; -{ - int bytes, i; - svCaptureInfo info; - void *bitvector = NULL; - object *videodata, *bitvecobj, *res; - static object *evenitem, *odditem; - - if (!getargs(args, "(iiiii)", &info.format, &info.width, &info.height, - &info.size, &info.samplingrate)) - return NULL; - - switch (info.format) { - case SV_RGB8_FRAMES: - bitvector = malloc(SV_BITVEC_SIZE(info.size)); - break; - case SV_YUV411_FRAMES_AND_BLANKING_BUFFER: - break; - default: - err_setstr(SvError, "illegal format specified"); - return NULL; - } - - if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes)) { - if (bitvector) - free(bitvector); - return sv_error(); - } - - videodata = newsizedstringobject(NULL, bytes); - if (videodata == NULL) { - if (bitvector) - free(bitvector); - return NULL; - } - - /* XXX -- need to do something about the bitvector */ - if (svCaptureBurst(self->ob_svideo, &info, getstringvalue(videodata), - bitvector)) { - if (bitvector) - free(bitvector); - DECREF(videodata); - return sv_error(); - } - - if (bitvector) { - if (evenitem == NULL) { - evenitem = newintobject(0); - if (evenitem == NULL) { - free(bitvector); - DECREF(videodata); - return NULL; - } - } - if (odditem == NULL) { - odditem = newintobject(1); - if (odditem == NULL) { - free(bitvector); - DECREF(videodata); - return NULL; - } - } - bitvecobj = newtupleobject(2 * info.size); - if (bitvecobj == NULL) { - free(bitvecobj); - DECREF(videodata); - return NULL; - } - for (i = 0; i < 2 * info.size; i++) { - if (SV_GET_FIELD(bitvector, i) == SV_EVEN_FIELD) { - INCREF(evenitem); - settupleitem(bitvecobj, i, evenitem); - } else { - INCREF(odditem); - settupleitem(bitvecobj, i, odditem); - } - } - free(bitvector); - } else { - bitvecobj = None; - INCREF(None); - } - - res = mkvalue("((iiiii)OO)", info.format, info.width, info.height, - info.size, info.samplingrate, videodata, bitvecobj); - DECREF(videodata); - DECREF(bitvecobj); - return res; -} - -static object * -sv_CaptureOneFrame(self, args) - svobject *self; - object *args; -{ - svCaptureInfo info; - int format, width, height; - int bytes; - object *videodata, *res; - - if (!getargs(args, "(iii)", &format, &width, &height)) - return NULL; - info.format = format; - info.width = width; - info.height = height; - info.size = 0; - info.samplingrate = 0; - if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes)) - return sv_error(); - videodata = newsizedstringobject(NULL, bytes); - if (videodata == NULL) - return NULL; - if (svCaptureOneFrame(self->ob_svideo, format, &width, &height, - getstringvalue(videodata))) { - DECREF(videodata); - return sv_error(); - } - - res = mkvalue("(iiO)", width, height, videodata); - DECREF(videodata); - return res; -} - -static object * -sv_InitContinuousCapture(self, args) - svobject *self; - object *args; -{ - svCaptureInfo info; - - if (!getargs(args, "(iiiii)", &info.format, &info.width, &info.height, - &info.size, &info.samplingrate)) - return NULL; - - if (svInitContinuousCapture(self->ob_svideo, &info)) - return sv_error(); - - self->ob_info = info; - - return mkvalue("(iiiii)", info.format, info.width, info.height, - info.size, info.samplingrate); -} - -static object * -sv_LoadMap(self, args) - svobject *self; - object *args; -{ - object *rgb, *v, *cell; - rgb_tuple *mapp; - int maptype; - int i, j; /* indices */ - - if (!getargs(args, "(iO)", &maptype, &rgb)) - return NULL; - if (!is_listobject(rgb) || getlistsize(rgb) != 256) { - err_badarg(); - return NULL; - } - mapp = NEW(rgb_tuple, 256); - if (mapp == NULL) - return err_nomem(); - for (i = 0; i < 256; i++) { - v = getlistitem(rgb, i); - if (!is_tupleobject(v) || gettuplesize(v) != 3) { - DEL(mapp); - err_badarg(); - return NULL; - } - for (j = 0; j < 3; j++) { - cell = gettupleitem(v, j); - if (!is_intobject(cell)) { - DEL(mapp); - err_badarg(); - return NULL; - } - switch (j) { - case 0: mapp[i].red = getintvalue(cell); break; - case 1: mapp[i].blue = getintvalue(cell); break; - case 2: mapp[i].green = getintvalue(cell); break; - } - } - } - - if (svLoadMap(self->ob_svideo, maptype, mapp)) { - DEL(mapp); - return sv_error(); - } - - DEL(mapp); - - INCREF(None); - return None; -} - -static object * -sv_CloseVideo(self, args) - svobject *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - - if (svCloseVideo(self->ob_svideo)) - return sv_error(); - self->ob_svideo = NULL; - - INCREF(None); - return None; -} - -static object * -doParams(self, args, func, modified) - svobject *self; - object *args; - int (*func)(SV_nodeP, long *, int); - int modified; -{ - object *list, *v; - long *PVbuffer; - long length; - int i; - - if (!getargs(args, "O", &list)) - return NULL; - if (!is_listobject(list)) { - err_badarg(); - return NULL; - } - length = getlistsize(list); - PVbuffer = NEW(long, length); - if (PVbuffer == NULL) - return err_nomem(); - for (i = 0; i < length; i++) { - v = getlistitem(list, i); - if (!is_intobject(v)) { - DEL(PVbuffer); - err_badarg(); - return NULL; - } - PVbuffer[i] = getintvalue(v); - } - - if ((*func)(self->ob_svideo, PVbuffer, length)) { - DEL(PVbuffer); - return sv_error(); - } - - if (modified) { - for (i = 0; i < length; i++) - setlistitem(list, i, newintobject(PVbuffer[i])); - } - - DEL(PVbuffer); - - INCREF(None); - return None; -} - -static object * -sv_GetParam(self, args) - object *self, *args; -{ - return doParams(self, args, svGetParam, 1); -} - -static object * -sv_GetParamRange(self, args) - object *self, *args; -{ - return doParams(self, args, svGetParamRange, 1); -} - -static object * -sv_SetParam(self, args) - object *self, *args; -{ - return doParams(self, args, svSetParam, 0); -} - -static struct methodlist svideo_methods[] = { - {"BindGLWindow", (method)sv_BindGLWindow}, - {"EndContinuousCapture",(method)sv_EndContinuousCapture}, - {"IsVideoDisplayed", (method)sv_IsVideoDisplayed}, - {"OutputOffset", (method)sv_OutputOffset}, - {"PutFrame", (method)sv_PutFrame}, - {"QuerySize", (method)sv_QuerySize}, - {"SetSize", (method)sv_SetSize}, - {"SetStdDefaults", (method)sv_SetStdDefaults}, - {"UseExclusive", (method)sv_UseExclusive}, - {"WindowOffset", (method)sv_WindowOffset}, - {"InitContinuousCapture",(method)sv_InitContinuousCapture}, - {"CaptureBurst", (method)sv_CaptureBurst}, - {"CaptureOneFrame", (method)sv_CaptureOneFrame}, - {"GetCaptureData", (method)sv_GetCaptureData}, - {"CloseVideo", (method)sv_CloseVideo}, - {"LoadMap", (method)sv_LoadMap}, - {"GetParam", (method)sv_GetParam}, - {"GetParamRange", (method)sv_GetParamRange}, - {"SetParam", (method)sv_SetParam}, - {NULL, NULL} /* sentinel */ -}; - -static object * -sv_conversion(self, args, function, inputfactor, factor) - object *self, *args; - void (*function)(); - int inputfactor; - float factor; -{ - int invert, width, height, inputlength; - char *input; - object *output; - - if (!getargs(args, "(is#ii)", &invert, &input, &inputlength, &width, &height)) - return NULL; - - if (width * height * inputfactor > inputlength) { - err_setstr(SvError, "input buffer not long enough"); - return NULL; - } - - output = newsizedstringobject(NULL, (int) (width * height * factor)); - if (output == NULL) - return NULL; - - (*function)(invert, input, getstringvalue(output), width, height); - - return output; -} - -static object * -sv_InterleaveFields(self, args) - object *self, *args; -{ - return sv_conversion(self, args, svInterleaveFields, 1, 1.0); -} - -static object * -sv_RGB8toRGB32(self, args) - object *self, *args; -{ - return sv_conversion(self, args, svRGB8toRGB32, 1, (float) sizeof(long)); -} - -static object * -sv_YUVtoRGB(self, args) - object *self, *args; -{ - return sv_conversion(self, args, svYUVtoRGB, 2, (float) sizeof(long)); -} - -static void -svideo_dealloc(self) - svobject *self; -{ - if (self->ob_svideo != NULL) - (void) svCloseVideo(self->ob_svideo); - DEL(self); -} - -static object * -svideo_getattr(self, name) - svobject *self; - char *name; -{ - return findmethod(svideo_methods, (object *)self, name); -} - -typeobject Svtype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "sv", /*tp_name*/ - sizeof(svobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)svideo_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)svideo_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - -static object * -newsvobject(svp) - SV_nodeP svp; -{ - svobject *p; - - p = NEWOBJ(svobject, &Svtype); - if (p == NULL) - return NULL; - p->ob_svideo = svp; - p->ob_info.format = 0; - p->ob_info.size = 0; - p->ob_info.width = 0; - p->ob_info.height = 0; - p->ob_info.samplingrate = 0; - return (object *) p; -} - -static object * -sv_OpenVideo(self, args) - object *self, *args; -{ - SV_nodeP svp; - - if (!getnoarg(args)) - return NULL; - - svp = svOpenVideo(); - if (svp == NULL) - return sv_error(); - - return newsvobject(svp); -} - -static struct methodlist sv_methods[] = { - {"InterleaveFields", (method)sv_InterleaveFields}, - {"RGB8toRGB32", (method)sv_RGB8toRGB32}, - {"YUVtoRGB", (method)sv_YUVtoRGB}, - {"OpenVideo", (method)sv_OpenVideo}, - {NULL, NULL} /* Sentinel */ -}; - -void -initsv() -{ - object *m, *d; - - m = initmodule("sv", sv_methods); - d = getmoduledict(m); - - SvError = newstringobject("sv.error"); - if (SvError == NULL || dictinsert(d, "error", SvError) != 0) - fatal("can't define sv.error"); -} diff --git a/Modules/sybasemodule.c b/Modules/sybasemodule.c deleted file mode 100644 index 860203fbfc..0000000000 --- a/Modules/sybasemodule.c +++ /dev/null @@ -1,309 +0,0 @@ -/* -Subject: Re: Sybase module -- input sought -From: jredford@lehman.com -To: ags@uncompaghre.informatics.jax.org (Alexander G. Smith) -Cc: python-list@cwi.nl -Date: Tue, 10 May 94 11:53:13 -0400 - - -input sought? how about a complete module? :) - -This is a fairly incomplete work.. but I have done things dramatically -differently than sybperl would. Given the nature of the language I -find it is easier to simply get ALL results & then muck with the rows -later as parts of the data. This is a subset of the functionality of a -Modula-3 interface to Sybase that I wrote.. I could send you that if -you are interested in a more complete picture. -*/ - -#include <stdio.h> - -#include <sybfront.h> -#include <sybdb.h> - -#include "allobjects.h" -#include "modsupport.h" - - -static object *SybaseError; /* exception sybase.error */ - - -typedef struct { - OB_HEAD - LOGINREC *login; /* login record */ - DBPROCESS *dbproc; /* login record */ -} sybdbobject; - -extern typeobject SybDbtype; /* Forward */ - - -static sybdbobject * - newsybdbobject(char *user, char *passwd, char *server) -{ - sybdbobject *s; - - s = NEWOBJ(sybdbobject, &SybDbtype); - if (s != NULL) { - s->login = dblogin(); - if (user) { - (void)DBSETLUSER(s->login, user); - } - if (passwd) { - (void)DBSETLPWD(s->login, passwd); - } - if(!(s->dbproc = dbopen(s->login, server))) { - dbloginfree(s->login); - DEL(s); - return (NULL); - } - } - return s; -} - -/* OBJECT FUNCTIONS: sybdb */ - -/* Common code for returning pending results */ -static object - *getresults (DBPROCESS *dbp) -{ - object *results; - object *list; - object *tuple; - object *o; - int retcode; - int cols; - int *fmt; - int i; - - results = newlistobject(0); - while ((retcode = dbresults(dbp)) != NO_MORE_RESULTS) { - if (retcode == SUCCEED && DBROWS(dbp) == SUCCEED) { - list = newlistobject(0); - cols = dbnumcols(dbp); - fmt = (int *)malloc(sizeof(int) * cols); - for (i = 1; i <= cols; i++) { - switch(dbcoltype(dbp, i)) { - case SYBCHAR: - fmt[i-1] = SYBCHAR; - break; - case SYBINT1: - fmt[i-1] = SYBINT1; - break; - case SYBINT2: - fmt[i-1] = SYBINT2; - break; - case SYBINT4: - fmt[i-1] = SYBINT4; - break; - case SYBFLT8: - fmt[i-1] = SYBFLT8; - break; - } - } - while (dbnextrow(dbp) != NO_MORE_ROWS) { - tuple = newtupleobject(cols); - for (i = 1; i <= cols; i++) { - switch(fmt[i-1]) { - case SYBCHAR: - o = newsizedstringobject((char *)dbdata(dbp, i), dbdatlen(dbp, i)); - settupleitem(tuple, i-1, o); - break; - case SYBINT1: - o = newintobject(*((char *)dbdata(dbp, i))); - settupleitem(tuple, i-1, o); - break; - case SYBINT2: - o = newintobject(*((short *)dbdata(dbp, i))); - settupleitem(tuple, i-1, o); - break; - case SYBINT4: - o = newintobject(*((int *)dbdata(dbp, i))); - settupleitem(tuple, i-1, o); - break; - case SYBFLT8: - o = newfloatobject(*((double *)dbdata(dbp, i))); - settupleitem(tuple, i-1, o); - break; - } - } - addlistitem(list,tuple); - } - free(fmt); - addlistitem(results,list); - } - } - return (results); -} - -static object - *sybdb_sql (self, args) -object *self; -object *args; -{ - char *sql; - DBPROCESS *dbp; - - dbp = ((sybdbobject *)self)->dbproc; - err_clear (); - if (!getargs (args, "s", &sql)) { - return NULL; - } - dbcancel(dbp); - dbcmd(dbp, sql); - dbsqlexec(dbp); - return getresults(dbp); -} - -static object - *sybdb_sp (self, args) -object *self; -object *args; -{ - char *sp; - DBPROCESS *dbp; - object *spargs; - object *sparg; - object *results; - object *r; - int spargcnt; - int i; - int retstatus; - - dbp = ((sybdbobject *)self)->dbproc; - err_clear (); - if (!getargs (args, "(sO)", &sp, &spargs)) { - return NULL; - } - - dbcancel(dbp); - dbrpcinit(dbp, sp, 0); - - if (is_tupleobject(spargs)) { - spargcnt=gettuplesize(spargs); - for (i=0; i < spargcnt; i++) { - sparg = gettupleitem(spargs,i); - if (is_intobject(sparg)) { - int i; - i = getintvalue(sparg); - dbrpcparam(dbp, NULL, 0, SYBINT4, -1, -1, &i); - } else if (is_floatobject(sparg)) { - double i; - i = getfloatvalue(sparg); - dbrpcparam(dbp, NULL, 0, SYBFLT8, -1, -1, &i); - } else if (is_stringobject(sparg)) { - dbrpcparam(dbp, NULL, 0, SYBCHAR, -1, getstringsize(sparg), getstringvalue(sparg)); - } else { - err_setstr (SybaseError, "Could not handle paramaters to procedure."); - return NULL; - } - } - } else if (spargs != None) { - err_setstr (SybaseError, "Could not handle paramaters to procedure."); - return NULL; - } - dbrpcsend(dbp); - dbsqlok(dbp); - - results = getresults(dbp); - retstatus = dbretstatus(dbp); - - r = mkvalue("(iO)", retstatus, results); - DECREF(results); - return (r); -} - - -static struct methodlist sybdb_methods[] = { - {"sql", sybdb_sql}, - {"sp", sybdb_sp}, - {NULL, NULL} /* sentinel */ -}; - -static void -sybdb_dealloc(s) - sybdbobject *s; -{ - dbloginfree(s->login); - dbclose(s->dbproc); - DEL(s); -} - -static object * -sybdb_getattr(s, name) - sybdbobject *s; - char *name; -{ - return findmethod(sybdb_methods, (object *) s, name); -} - - -typeobject SybDbtype = { - OB_HEAD_INIT(&Typetype) - 0, - "sybdb", - sizeof(sybdbobject), - 0, - sybdb_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - sybdb_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ -}; - - - - - -/* MODULE FUNCTIONS: sybase */ - -static object - *sybase_new (self, args) -object *self; /* Not used */ -object *args; -{ - char *user, *passwd, *server; - object *db; - - err_clear (); - if (!getargs (args, "(zzz)", &user, &passwd, &server)) { - return NULL; - } - db = (object *) newsybdbobject(user, passwd, server); - if (!db) { - /* XXX Should be setting some errstr stuff here based on sybase errors */ - err_setstr (SybaseError, "Could not open connection to server."); - return NULL; - } - return db; -} - - -/* List of module functions */ -static struct methodlist sybase_methods[]= -{ - {"new", sybase_new}, - {NULL, NULL} /* sentinel */ -}; - -/* Module initialisation */ -void initsybase () -{ - object *m, *d; - - /* Create the module and add the functions */ - m = initmodule ("sybase", sybase_methods); - /* Add some symbolic constants to the module */ - d = getmoduledict (m); - SybaseError = newstringobject ("sybase.error"); - if (SybaseError == NULL || dictinsert (d, "error", SybaseError) != 0) { - fatal ("can't define sybase.error"); - } - /* Check for errors */ - if (err_occurred ()){ - fatal ("can't initialize module sybase"); - } -} diff --git a/Modules/syslogmodule.c b/Modules/syslogmodule.c deleted file mode 100644 index 06c4f34218..0000000000 --- a/Modules/syslogmodule.c +++ /dev/null @@ -1,209 +0,0 @@ -/*********************************************************** -Copyright 1994 by Lance Ellinghouse, -Cathedral City, California Republic, United States of America. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the name of Lance Ellinghouse -not be used in advertising or publicity pertaining to distribution -of the software without specific, written prior permission. - -LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE 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. - -******************************************************************/ - -/****************************************************************** - -Revision history: - -95/06/29 (Steve Clift) - - Changed arg parsing to use PyArg_ParseTuple. - - Added PyErr_Clear() call(s) where needed. - - Fix core dumps if user message contains format specifiers. - - Change openlog arg defaults to match normal syslog behaviour. - - Plug memory leak in openlog(). - - Fix setlogmask() to return previous mask value. - -******************************************************************/ - -/* syslog module */ - -#include "Python.h" - -#include <syslog.h> - -static PyObject * -syslog_openlog(self, args) - PyObject * self; - PyObject * args; -{ - long logopt = 0; - long facility = LOG_USER; - - static PyObject *ident_o = NULL; - - Py_XDECREF(ident_o); - if (!PyArg_ParseTuple(args, "S|ll;ident string [, logoption [, facility]]", - &ident_o, &logopt, &facility)) { - return NULL; - } - Py_INCREF(ident_o); /* This is needed because openlog() does NOT make a copy - and syslog() later uses it.. cannot trash it. */ - - openlog(PyString_AsString(ident_o), logopt, facility); - - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -syslog_syslog(self, args) - PyObject * self; - PyObject * args; -{ - char *message, *s; - int priority = LOG_INFO | LOG_USER; - - if (!PyArg_ParseTuple(args, "is;[priority,] message string", - &priority, &message)) { - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "s;[priority,] message string", &message)) { - return NULL; - } - } - syslog(priority, "%s", message); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -syslog_closelog(self, args) - PyObject * self; - PyObject * args; -{ - if (!PyArg_ParseTuple(args, "")) - return NULL; - closelog(); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -syslog_setlogmask(self, args) - PyObject * self; - PyObject * args; -{ - long maskpri, omaskpri; - - if (!PyArg_ParseTuple(args,"l;mask for priority",&maskpri)) - return NULL; - omaskpri = setlogmask(maskpri); - return PyInt_FromLong(omaskpri); -} - -static PyObject * -syslog_log_mask(self, args) - PyObject * self; - PyObject * args; -{ - long mask; - long pri; - if (!PyArg_ParseTuple(args,"l",&pri)) - return NULL; - mask = LOG_MASK(pri); - return PyInt_FromLong(mask); -} - -static PyObject * -syslog_log_upto(self, args) - PyObject * self; - PyObject * args; -{ - long mask; - long pri; - if (!PyArg_ParseTuple(args,"l",&pri)) - return NULL; - mask = LOG_UPTO(pri); - return PyInt_FromLong(mask); -} - -/* List of functions defined in the module */ - -static PyMethodDef syslog_methods[] = { - {"openlog", syslog_openlog, METH_VARARGS}, - {"closelog", syslog_closelog, METH_VARARGS}, - {"syslog", syslog_syslog, METH_VARARGS}, - {"setlogmask", syslog_setlogmask, METH_VARARGS}, - {"LOG_MASK", syslog_log_mask, METH_VARARGS}, - {"LOG_UPTO", syslog_log_upto, METH_VARARGS}, - {NULL, NULL, 0} -}; - -/* Initialization function for the module */ - -#define DICT_SET_INT(d, s, x) \ - PyDict_SetItemString(d, s, PyInt_FromLong((long) (x))) - -void -initsyslog() -{ - PyObject *m, *d; - - /* Create the module and add the functions */ - m = Py_InitModule("syslog", syslog_methods); - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - - /* Priorities */ - DICT_SET_INT(d, "LOG_EMERG", LOG_EMERG); - DICT_SET_INT(d, "LOG_ALERT", LOG_ALERT); - DICT_SET_INT(d, "LOG_CRIT", LOG_CRIT); - DICT_SET_INT(d, "LOG_ERR", LOG_ERR); - DICT_SET_INT(d, "LOG_WARNING", LOG_WARNING); - DICT_SET_INT(d, "LOG_NOTICE", LOG_NOTICE); - DICT_SET_INT(d, "LOG_INFO", LOG_INFO); - DICT_SET_INT(d, "LOG_DEBUG", LOG_DEBUG); - - /* openlog() option flags */ - DICT_SET_INT(d, "LOG_PID", LOG_PID); - DICT_SET_INT(d, "LOG_CONS", LOG_CONS); - DICT_SET_INT(d, "LOG_NDELAY", LOG_NDELAY); - DICT_SET_INT(d, "LOG_NOWAIT", LOG_NOWAIT); -#ifdef LOG_PERROR - DICT_SET_INT(d, "LOG_PERROR", LOG_PERROR); -#endif - - /* Facilities */ - DICT_SET_INT(d, "LOG_KERN", LOG_KERN); - DICT_SET_INT(d, "LOG_USER", LOG_USER); - DICT_SET_INT(d, "LOG_MAIL", LOG_MAIL); - DICT_SET_INT(d, "LOG_DAEMON", LOG_DAEMON); - DICT_SET_INT(d, "LOG_AUTH", LOG_AUTH); - DICT_SET_INT(d, "LOG_LPR", LOG_LPR); - DICT_SET_INT(d, "LOG_NEWS", LOG_NEWS); - DICT_SET_INT(d, "LOG_UUCP", LOG_UUCP); - DICT_SET_INT(d, "LOG_CRON", LOG_CRON); - DICT_SET_INT(d, "LOG_LOCAL0", LOG_LOCAL0); - DICT_SET_INT(d, "LOG_LOCAL1", LOG_LOCAL1); - DICT_SET_INT(d, "LOG_LOCAL2", LOG_LOCAL2); - DICT_SET_INT(d, "LOG_LOCAL3", LOG_LOCAL3); - DICT_SET_INT(d, "LOG_LOCAL4", LOG_LOCAL4); - DICT_SET_INT(d, "LOG_LOCAL5", LOG_LOCAL5); - DICT_SET_INT(d, "LOG_LOCAL6", LOG_LOCAL6); - DICT_SET_INT(d, "LOG_LOCAL7", LOG_LOCAL7); - - /* Check for errors */ - if (PyErr_Occurred()) - Py_FatalError("can't initialize module syslog"); -} diff --git a/Modules/termios.c b/Modules/termios.c deleted file mode 100644 index 4148d85dc1..0000000000 --- a/Modules/termios.c +++ /dev/null @@ -1,243 +0,0 @@ -/* termiosmodule.c -- POSIX terminal I/O module implementation. */ - -#include <Python.h> - -#define PyInit_termios inittermios - -#include <termios.h> - -#define BAD "bad termios argument" - -static PyObject *TermiosError; - -/* termios = tcgetattr(fd) - termios is - [iflag, oflag, cflag, lflag, ispeed, ospeed, [cc[0], ..., cc[NCCS]]] - - Return the attributes of the terminal device. */ - -static PyObject * -termios_tcgetattr(self, args) - PyObject *self; - PyObject *args; -{ - int fd; - struct termios mode; - PyObject *cc; - speed_t ispeed, ospeed; - PyObject *v; - int i; - char ch; - - if (!PyArg_Parse(args, "i", &fd)) - return NULL; - - if (tcgetattr(fd, &mode) == -1) - PyErr_SetFromErrno(TermiosError); - - ispeed = cfgetispeed(&mode); - ospeed = cfgetospeed(&mode); - - cc = PyList_New(NCCS); - if (cc == NULL) - return NULL; - for (i = 0; i < NCCS; i++) { - ch = (char)mode.c_cc[i]; - v = PyString_FromStringAndSize(&ch, 1); - if (v == NULL) - return NULL; - PyList_SetItem(cc, i, v); - } - - /* Convert the MIN and TIME slots to integer. On some systems, the - MIN and TIME slots are the same as the EOF and EOL slots. So we - only do this in noncanonical input mode. */ - if (mode.c_lflag & ICANON == 0) { - v = PyInt_FromLong((long)mode.c_cc[VMIN]); - if (v == NULL) - return NULL; - PyList_SetItem(cc, VMIN, v); - v = PyInt_FromLong((long)mode.c_cc[VTIME]); - if (v == NULL) - return NULL; - PyList_SetItem(cc, VTIME, v); - } - - v = PyList_New(7); - PyList_SetItem(v, 0, PyInt_FromLong((long)mode.c_iflag)); - PyList_SetItem(v, 1, PyInt_FromLong((long)mode.c_oflag)); - PyList_SetItem(v, 2, PyInt_FromLong((long)mode.c_cflag)); - PyList_SetItem(v, 3, PyInt_FromLong((long)mode.c_lflag)); - PyList_SetItem(v, 4, PyInt_FromLong((long)ispeed)); - PyList_SetItem(v, 5, PyInt_FromLong((long)ospeed)); - PyList_SetItem(v, 6, cc); - - return v; -} - -/* tcsetattr(fd, when, termios) - Set the attributes of the terminal device. */ - -static PyObject * -termios_tcsetattr(self, args) - PyObject *self; - PyObject *args; -{ - int fd, when; - struct termios mode; - speed_t ispeed, ospeed; - PyObject *term, *cc, *v; - int i; - - if (!PyArg_Parse(args, "(iiO)", &fd, &when, &term)) - return NULL; - if (!PyList_Check(term) || PyList_Size(term) != 7) { - PyErr_SetString(PyExc_TypeError, BAD); - return NULL; - } - for (i = 0; i < 6; i++) - if (!PyInt_Check(PyList_GetItem(term, i))) { - PyErr_SetString(PyExc_TypeError, BAD); - return NULL; - } - - mode.c_iflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 0)); - mode.c_oflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 1)); - mode.c_cflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 2)); - mode.c_lflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 3)); - ispeed = (speed_t) PyInt_AsLong(PyList_GetItem(term, 4)); - ospeed = (speed_t) PyInt_AsLong(PyList_GetItem(term, 5)); - cc = PyList_GetItem(term, 6); - - if (!PyList_Check(cc) || PyList_Size(cc) != NCCS) { - PyErr_SetString(PyExc_TypeError, BAD); - return NULL; - } - - for (i = 0; i < NCCS; i++) { - v = PyList_GetItem(cc, i); - if (PyString_Check(v) && PyString_Size(v) == 1) - mode.c_cc[i] = (cc_t) * PyString_AsString(v); - else if (PyInt_Check(v)) - mode.c_cc[i] = (cc_t) PyInt_AsLong(v); - else { - PyErr_SetString(PyExc_TypeError, BAD); - return NULL; - } - } - - if (cfsetispeed(&mode, (speed_t) ispeed) == -1) - PyErr_SetFromErrno(TermiosError); - if (cfsetospeed(&mode, (speed_t) ospeed) == -1) - PyErr_SetFromErrno(TermiosError); - if (tcsetattr(fd, when, &mode) == -1) - PyErr_SetFromErrno(TermiosError); - - Py_INCREF(Py_None); - return Py_None; -} - -/* tcsendbreak(fd, duration) - Generate a break condition. */ - -static PyObject * -termios_tcsendbreak(self, args) - PyObject *self; - PyObject *args; -{ - int fd, duration; - - if (!PyArg_Parse(args, "(ii)", &fd, &duration)) - return NULL; - if (tcsendbreak(fd, duration) == -1) - PyErr_SetFromErrno(TermiosError); - - Py_INCREF(Py_None); - return Py_None; -} - -/* tcdrain(fd) - Wait until all queued output to the terminal has been - transmitted. */ - -static PyObject * -termios_tcdrain(self, args) - PyObject *self; - PyObject *args; -{ - int fd; - - if (!PyArg_Parse(args, "i", &fd)) - return NULL; - if (tcdrain(fd) == -1) - PyErr_SetFromErrno(TermiosError); - - Py_INCREF(Py_None); - return Py_None; -} - -/* tcflush(fd, queue) - Clear the input and/or output queues associated with - the terminal. */ - -static PyObject * -termios_tcflush(self, args) - PyObject *self; - PyObject *args; -{ - int fd, queue; - - if (!PyArg_Parse(args, "(ii)", &fd, &queue)) - return NULL; - if (tcflush(fd, queue) == -1) - PyErr_SetFromErrno(TermiosError); - - Py_INCREF(Py_None); - return Py_None; -} - -/* tcflow(fd, action) - Perform operations relating to XON/XOFF flow control on - the terminal. */ - -static PyObject * -termios_tcflow(self, args) - PyObject *self; - PyObject *args; -{ - int fd, action; - - if (!PyArg_Parse(args, "(ii)", &fd, &action)) - return NULL; - if (tcflow(fd, action) == -1) - PyErr_SetFromErrno(TermiosError); - - Py_INCREF(Py_None); - return Py_None; -} - -static PyMethodDef termios_methods[] = -{ - {"tcgetattr", termios_tcgetattr}, - {"tcsetattr", termios_tcsetattr}, - {"tcsendbreak", termios_tcsendbreak}, - {"tcdrain", termios_tcdrain}, - {"tcflush", termios_tcflush}, - {"tcflow", termios_tcflow}, - {NULL, NULL} -}; - -void -PyInit_termios() -{ - PyObject *m, *d; - - m = Py_InitModule("termios", termios_methods); - - d = PyModule_GetDict(m); - TermiosError = Py_BuildValue("s", "termios.error"); - PyDict_SetItemString(d, "error", TermiosError); - - if (PyErr_Occurred()) - Py_FatalError("can't initialize module termios"); -} diff --git a/Modules/threadmodule.c b/Modules/threadmodule.c deleted file mode 100644 index befe6a225c..0000000000 --- a/Modules/threadmodule.c +++ /dev/null @@ -1,326 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Thread module */ -/* Interface to Sjoerd's portable C thread library */ - -#include "allobjects.h" - -#ifndef WITH_THREAD -Error! The rest of Python is not compiled with thread support. -Rerun configure, adding a --with-thread option. -#endif - -#include "thread.h" - -extern int threads_started; - -static object *ThreadError; - - -/* Lock objects */ - -typedef struct { - OB_HEAD - type_lock lock_lock; -} lockobject; - -staticforward typeobject Locktype; - -#define is_lockobject(v) ((v)->ob_type == &Locktype) - -type_lock -getlocklock(lock) - object *lock; -{ - if (lock == NULL || !is_lockobject(lock)) - return NULL; - else - return ((lockobject *) lock)->lock_lock; -} - -static lockobject * -newlockobject() -{ - lockobject *self; - self = NEWOBJ(lockobject, &Locktype); - if (self == NULL) - return NULL; - self->lock_lock = allocate_lock(); - if (self->lock_lock == NULL) { - DEL(self); - self = NULL; - err_setstr(ThreadError, "can't allocate lock"); - } - return self; -} - -static void -lock_dealloc(self) - lockobject *self; -{ - /* Unlock the lock so it's safe to free it */ - acquire_lock(self->lock_lock, 0); - release_lock(self->lock_lock); - - free_lock(self->lock_lock); - DEL(self); -} - -static object * -lock_acquire_lock(self, args) - lockobject *self; - object *args; -{ - int i; - - if (args != NULL) { - if (!getargs(args, "i", &i)) - return NULL; - } - else - i = 1; - - BGN_SAVE - i = acquire_lock(self->lock_lock, i); - END_SAVE - - if (args == NULL) { - INCREF(None); - return None; - } - else - return newintobject((long)i); -} - -static object * -lock_release_lock(self, args) - lockobject *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - - /* Sanity check: the lock must be locked */ - if (acquire_lock(self->lock_lock, 0)) { - release_lock(self->lock_lock); - err_setstr(ThreadError, "release unlocked lock"); - return NULL; - } - - release_lock(self->lock_lock); - INCREF(None); - return None; -} - -static object * -lock_locked_lock(self, args) - lockobject *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - - if (acquire_lock(self->lock_lock, 0)) { - release_lock(self->lock_lock); - return newintobject(0L); - } - return newintobject(1L); -} - -static struct methodlist lock_methods[] = { - {"acquire_lock", (method)lock_acquire_lock}, - {"acquire", (method)lock_acquire_lock}, - {"release_lock", (method)lock_release_lock}, - {"release", (method)lock_release_lock}, - {"locked_lock", (method)lock_locked_lock}, - {"locked", (method)lock_locked_lock}, - {NULL, NULL} /* sentinel */ -}; - -static object * -lock_getattr(self, name) - lockobject *self; - char *name; -{ - return findmethod(lock_methods, (object *)self, name); -} - -static typeobject Locktype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "lock", /*tp_name*/ - sizeof(lockobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)lock_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)lock_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ -}; - - -/* Module functions */ - -static void -t_bootstrap(args_raw) - void *args_raw; -{ - object *args = (object *) args_raw; - object *func, *arg, *res; - - threads_started++; - - restore_thread((void *)NULL); - func = gettupleitem(args, 0); - arg = gettupleitem(args, 1); - res = call_object(func, arg); - DECREF(args); /* Matches the INCREF(args) in thread_start_new_thread */ - if (res == NULL) { - if (err_occurred() == SystemExit) - err_clear(); - else { - fprintf(stderr, "Unhandled exception in thread:\n"); - print_error(); /* From pythonmain.c */ - } - } - else - DECREF(res); - (void) save_thread(); /* Should always be NULL */ - exit_thread(); -} - -static object * -thread_start_new_thread(self, args) - object *self; /* Not used */ - object *args; -{ - object *func, *arg; - - if (!getargs(args, "(OO)", &func, &arg)) - return NULL; - INCREF(args); - /* Initialize the interpreter's stack save/restore mechanism */ - init_save_thread(); - if (!start_new_thread(t_bootstrap, (void*) args)) { - DECREF(args); - err_setstr(ThreadError, "can't start new thread\n"); - return NULL; - } - /* Otherwise the DECREF(args) is done by t_bootstrap */ - INCREF(None); - return None; -} - -static object * -thread_exit_thread(self, args) - object *self; /* Not used */ - object *args; -{ - if (!getnoarg(args)) - return NULL; - err_set(SystemExit); - return NULL; -} - -#ifndef NO_EXIT_PROG -static object * -thread_exit_prog(self, args) - object *self; /* Not used */ - object *args; -{ - int sts; - if (!getargs(args, "i", &sts)) - return NULL; - goaway(sts); /* Calls exit_prog(sts) or _exit_prog(sts) */ - for (;;) { } /* Should not be reached */ -} -#endif - -static object * -thread_allocate_lock(self, args) - object *self; /* Not used */ - object *args; -{ - if (!getnoarg(args)) - return NULL; - return (object *) newlockobject(); -} - -static object * -thread_get_ident(self, args) - object *self; /* Not used */ - object *args; -{ - long ident; - if (!getnoarg(args)) - return NULL; - ident = get_thread_ident(); - if (ident == -1) { - err_setstr(ThreadError, "no current thread ident"); - return NULL; - } - return newintobject(ident); -} - -static struct methodlist thread_methods[] = { - {"start_new_thread", (method)thread_start_new_thread}, - {"start_new", (method)thread_start_new_thread}, - {"allocate_lock", (method)thread_allocate_lock}, - {"allocate", (method)thread_allocate_lock}, - {"exit_thread", (method)thread_exit_thread}, - {"exit", (method)thread_exit_thread}, - {"get_ident", (method)thread_get_ident}, -#ifndef NO_EXIT_PROG - {"exit_prog", (method)thread_exit_prog}, -#endif - {NULL, NULL} /* sentinel */ -}; - - -/* Initialization function */ - -void -initthread() -{ - object *m, *d, *x; - - /* Create the module and add the functions */ - m = initmodule("thread", thread_methods); - - /* Add a symbolic constant */ - d = getmoduledict(m); - ThreadError = newstringobject("thread.error"); - INCREF(ThreadError); - dictinsert(d, "error", ThreadError); - - /* Check for errors */ - if (err_occurred()) - fatal("can't initialize module thread"); - - /* Initialize the C thread library */ - init_thread(); -} diff --git a/Modules/timemodule.c b/Modules/timemodule.c deleted file mode 100644 index d8c1b2b027..0000000000 --- a/Modules/timemodule.c +++ /dev/null @@ -1,482 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Time module */ - -#include "allobjects.h" -#include "modsupport.h" -#include "ceval.h" - -#ifdef macintosh -#include <time.h> -#else -#include <sys/types.h> -#endif - -#ifdef QUICKWIN -#include <io.h> -#endif - -#ifdef HAVE_UNISTD_H -#include <unistd.h> -#endif - -#ifdef HAVE_SELECT -#include "myselect.h" -#else -#include "mytime.h" -#endif - -#ifdef HAVE_FTIME -#include <sys/timeb.h> -#endif - -#ifdef __WATCOMC__ -#include <i86.h> -#else -#ifdef _M_IX86 -#include <windows.h> -#define timezone _timezone -#define tzname _tzname -#define daylight _daylight -#define altzone _altzone -#endif -#endif - -/* Forward declarations */ -static int floatsleep PROTO((double)); -static double floattime PROTO(()); - -static object * -time_time(self, args) - object *self; - object *args; -{ - double secs; - if (!getnoarg(args)) - return NULL; - secs = floattime(); - if (secs == 0.0) { - err_errno(IOError); - return NULL; - } - return newfloatobject(secs); -} - -#ifdef HAVE_CLOCK - -#ifndef CLOCKS_PER_SEC -#ifdef CLK_TCK -#define CLOCKS_PER_SEC CLK_TCK -#else -#define CLOCKS_PER_SEC 1000000 -#endif -#endif - -static object * -time_clock(self, args) - object *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - return newfloatobject(((double)clock()) / CLOCKS_PER_SEC); -} -#endif /* HAVE_CLOCK */ - -static object * -time_sleep(self, args) - object *self; - object *args; -{ - double secs; - if (!getargs(args, "d", &secs)) - return NULL; - BGN_SAVE - if (floatsleep(secs) != 0) { - RET_SAVE - return NULL; - } - END_SAVE - INCREF(None); - return None; -} - -static object * -time_convert(when, function) - time_t when; - struct tm * (*function) PROTO((const time_t *)); -{ - struct tm *p = function(&when); - return mkvalue("(iiiiiiiii)", - p->tm_year + 1900, - p->tm_mon + 1, /* Want January == 1 */ - p->tm_mday, - p->tm_hour, - p->tm_min, - p->tm_sec, - (p->tm_wday + 6) % 7, /* Want Monday == 0 */ - p->tm_yday + 1, /* Want January, 1 == 1 */ - p->tm_isdst); -} - -static object * -time_gmtime(self, args) - object *self; - object *args; -{ - double when; - if (!getargs(args, "d", &when)) - return NULL; - return time_convert((time_t)when, gmtime); -} - -static object * -time_localtime(self, args) - object *self; - object *args; -{ - double when; - if (!getargs(args, "d", &when)) - return NULL; - return time_convert((time_t)when, localtime); -} - -static int -gettmarg(args, p) - object *args; - struct tm *p; -{ - if (!getargs(args, "(iiiiiiiii)", - &p->tm_year, - &p->tm_mon, - &p->tm_mday, - &p->tm_hour, - &p->tm_min, - &p->tm_sec, - &p->tm_wday, - &p->tm_yday, - &p->tm_isdst)) - return 0; - if (p->tm_year >= 1900) - p->tm_year -= 1900; - p->tm_mon--; - p->tm_wday = (p->tm_wday + 1) % 7; - p->tm_yday--; - return 1; -} - -#ifdef HAVE_STRFTIME -static object * -time_strftime(self, args) - object *self; - object *args; -{ - struct tm buf; - const char *fmt; - char *outbuf = 0; - int i; - - if (!PyArg_ParseTuple(args, "s(iiiiiiiii)", - &fmt, - &(buf.tm_year), - &(buf.tm_mon), - &(buf.tm_mday), - &(buf.tm_hour), - &(buf.tm_min), - &(buf.tm_sec), - &(buf.tm_wday), - &(buf.tm_yday), - &(buf.tm_isdst))) - return NULL; - if (buf.tm_year >= 1900) - buf.tm_year -= 1900; - buf.tm_mon--; - buf.tm_wday = (buf.tm_wday + 1) % 7; - buf.tm_yday--; - /* I hate these functions that presume you know how big the output */ - /* will be ahead of time... */ - for (i = 1024 ; i < 8192 ; i += 1024) { - outbuf = malloc(i); - if (outbuf == NULL) { - return err_nomem(); - } - if (strftime(outbuf, i-1, fmt, &buf) != 0) { - object *ret; - ret = newstringobject(outbuf); - free(outbuf); - return ret; - } - free(outbuf); - } - return err_nomem(); -} -#endif /* HAVE_STRFTIME */ - -static object * -time_asctime(self, args) - object *self; - object *args; -{ - struct tm buf; - char *p; - if (!gettmarg(args, &buf)) - return NULL; - p = asctime(&buf); - if (p[24] == '\n') - p[24] = '\0'; - return newstringobject(p); -} - -static object * -time_ctime(self, args) - object *self; - object *args; -{ - double dt; - time_t tt; - char *p; - if (!getargs(args, "d", &dt)) - return NULL; - tt = dt; - p = ctime(&tt); - if (p[24] == '\n') - p[24] = '\0'; - return newstringobject(p); -} - -static object * -time_mktime(self, args) - object *self; - object *args; -{ - struct tm buf; - time_t tt; - tt = time(&tt); - buf = *localtime(&tt); - if (!gettmarg(args, &buf)) - return NULL; - tt = mktime(&buf); - if (tt == (time_t)(-1)) { - err_setstr(OverflowError, "mktime argument out of range"); - return NULL; - } - return newfloatobject((double)tt); -} - -static struct methodlist time_methods[] = { - {"time", time_time}, -#ifdef HAVE_CLOCK - {"clock", time_clock}, -#endif - {"sleep", time_sleep}, - {"gmtime", time_gmtime}, - {"localtime", time_localtime}, - {"asctime", time_asctime}, - {"ctime", time_ctime}, - {"mktime", time_mktime}, -#ifdef HAVE_STRFTIME - {"strftime", time_strftime, 1}, -#endif - {NULL, NULL} /* sentinel */ -}; - -static void -ins(d, name, v) - object *d; - char *name; - object *v; -{ - if (v == NULL) - fatal("Can't initialize time module -- NULL value"); - if (dictinsert(d, name, v) != 0) - fatal("Can't initialize time module -- dictinsert failed"); - DECREF(v); -} - -void -inittime() -{ - object *m, *d; - m = initmodule("time", time_methods); - d = getmoduledict(m); -#ifdef HAVE_TZNAME - tzset(); - ins(d, "timezone", newintobject((long)timezone)); -#ifdef HAVE_ALTZONE - ins(d, "altzone", newintobject((long)altzone)); -#else - ins(d, "altzone", newintobject((long)timezone-3600)); -#endif - ins(d, "daylight", newintobject((long)daylight)); - ins(d, "tzname", mkvalue("(zz)", tzname[0], tzname[1])); -#else /* !HAVE_TZNAME */ -#if HAVE_TM_ZONE - { -#define YEAR ((time_t)((365 * 24 + 6) * 3600)) - time_t t; - struct tm *p; - long winterzone, summerzone; - char wintername[10], summername[10]; - /* XXX This won't work on the southern hemisphere. - XXX Anybody got a better idea? */ - t = (time((time_t *)0) / YEAR) * YEAR; - p = localtime(&t); - winterzone = -p->tm_gmtoff; - strncpy(wintername, p->tm_zone ? p->tm_zone : " ", 9); - wintername[9] = '\0'; - t += YEAR/2; - p = localtime(&t); - summerzone = -p->tm_gmtoff; - strncpy(summername, p->tm_zone ? p->tm_zone : " ", 9); - summername[9] = '\0'; - ins(d, "timezone", newintobject(winterzone)); - ins(d, "altzone", newintobject(summerzone)); - ins(d, "daylight", newintobject((long)(winterzone != summerzone))); - ins(d, "tzname", mkvalue("(zz)", wintername, summername)); - } -#endif /* HAVE_TM_ZONE */ -#endif /* !HAVE_TZNAME */ -} - - -/* Implement floattime() for various platforms */ - -static double -floattime() -{ - /* There are three ways to get the time: - (1) gettimeofday() -- resolution in microseconds - (2) ftime() -- resolution in milliseconds - (3) time() -- resolution in seconds - In all cases the return value is a float in seconds. - Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may - fail, so we fall back on ftime() or time(). - Note: clock resolution does not imply clock accuracy! */ -#ifdef HAVE_GETTIMEOFDAY - { - struct timeval t; -#ifdef GETTIMEOFDAY_NO_TZ - if (gettimeofday(&t) == 0) - return (double)t.tv_sec + t.tv_usec*0.000001; -#else /* !GETTIMEOFDAY_NO_TZ */ - if (gettimeofday(&t, (struct timezone *)NULL) == 0) - return (double)t.tv_sec + t.tv_usec*0.000001; -#endif /* !GETTIMEOFDAY_NO_TZ */ - } -#endif /* !HAVE_GETTIMEOFDAY */ - { -#ifdef HAVE_FTIME - struct timeb t; - ftime(&t); - return (double)t.time + (double)t.millitm * (double)0.001; -#else /* !HAVE_FTIME */ - time_t secs; - time(&secs); - return (double)secs; -#endif /* !HAVE_FTIME */ - } -} - - -/* Implement floatsleep() for various platforms. - When interrupted (or when another error occurs), return -1 and - set an exception; else return 0. */ - -static int -#ifdef MPW -floatsleep(double secs) -#else -floatsleep(secs) - double secs; -#endif /* MPW */ -{ -#ifdef HAVE_SELECT - struct timeval t; - double frac; - extern double fmod PROTO((double, double)); - extern double floor PROTO((double)); - frac = fmod(secs, 1.0); - secs = floor(secs); - t.tv_sec = (long)secs; - t.tv_usec = (long)(frac*1000000.0); - if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) { - err_errno(IOError); - return -1; - } -#else /* !HAVE_SELECT */ -#ifdef macintosh -#define MacTicks (* (long *)0x16A) - long deadline; - deadline = MacTicks + (long)(secs * 60.0); - while (MacTicks < deadline) { - if (sigcheck()) - return -1; - } -#else /* !macintosh */ -#ifdef __WATCOMC__ - /* XXX Can't interrupt this sleep */ - delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */ -#else /* !__WATCOMC__ */ -#ifdef MSDOS - struct timeb t1, t2; - double frac; - extern double fmod PROTO((double, double)); - extern double floor PROTO((double)); - if (secs <= 0.0) - return; - frac = fmod(secs, 1.0); - secs = floor(secs); - ftime(&t1); - t2.time = t1.time + (int)secs; - t2.millitm = t1.millitm + (int)(frac*1000.0); - while (t2.millitm >= 1000) { - t2.time++; - t2.millitm -= 1000; - } - for (;;) { -#ifdef QUICKWIN - _wyield(); -#endif - if (sigcheck()) - return -1; - ftime(&t1); - if (t1.time > t2.time || - t1.time == t2.time && t1.millitm >= t2.millitm) - break; - } -#else /* !MSDOS */ -#ifdef _M_IX86 - /* XXX Can't interrupt this sleep */ - Sleep((int)(secs*1000)); -#else /* _M_IX86 */ - /* XXX Can't interrupt this sleep */ - sleep((int)secs); -#endif /* _M_IX86 */ -#endif /* !MSDOS */ -#endif /* !__WATCOMC__ */ -#endif /* !macintosh */ -#endif /* !HAVE_SELECT */ - return 0; -} diff --git a/Modules/timing.h b/Modules/timing.h deleted file mode 100644 index af26f1a6cb..0000000000 --- a/Modules/timing.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 1993 George V. Neville-Neil - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by George V. Neville-Neil - * 4. The name, George Neville-Neil may not be used to endorse or promote - * products derived from this software without specific prior - * written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#ifndef _TIMING_H_ -#define _TIMING_H_ - -#ifdef TIME_WITH_SYS_TIME -#include <sys/time.h> -#include <time.h> -#else /* !TIME_WITH_SYS_TIME */ -#ifdef HAVE_SYS_TIME_H -#include <sys/time.h> -#else /* !HAVE_SYS_TIME_H */ -#include <time.h> -#endif /* !HAVE_SYS_TIME_H */ -#endif /* !TIME_WITH_SYS_TIME */ - -static struct timeval aftertp, beforetp; - -#define BEGINTIMING gettimeofday(&beforetp, NULL) - -#define ENDTIMING gettimeofday(&aftertp, NULL); \ - if(beforetp.tv_usec > aftertp.tv_usec) \ - { \ - aftertp.tv_usec += 1000000; \ - aftertp.tv_sec--; \ - } - -#define TIMINGUS (((aftertp.tv_sec - beforetp.tv_sec) * 1000000) + \ - (aftertp.tv_usec - beforetp.tv_usec)) - -#define TIMINGMS (((aftertp.tv_sec - beforetp.tv_sec) * 1000) + \ - ((aftertp.tv_usec - beforetp.tv_usec) / 1000)) - -#define TIMINGS ((aftertp.tv_sec - beforetp.tv_sec) + \ - (aftertp.tv_usec - beforetp.tv_usec) / 1000000) - -#endif /* _TIMING_H_ */ diff --git a/Modules/timingmodule.c b/Modules/timingmodule.c deleted file mode 100644 index f4fd1ab835..0000000000 --- a/Modules/timingmodule.c +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Author: George V. Neville-Neil - */ - -#include "allobjects.h" -#include "import.h" -#include "modsupport.h" -#include "ceval.h" - -/* Our stuff... */ -#include "timing.h" - -static object * -start_timing(self, args) - object *self; - object *args; -{ - if (!getargs(args, "")) - return NULL; - - INCREF(None); - BEGINTIMING; - return None; -} - -static object * -finish_timing(self, args) - object *self; - object *args; -{ - if (!getargs(args, "")) - return NULL; - - ENDTIMING - INCREF(None); - return None; -} - -static object * -seconds(self, args) - object *self; - object *args; -{ - if (!getargs(args, "")) - return NULL; - - return newintobject(TIMINGS); - -} - -static object * -milli(self, args) - object *self; - object *args; -{ - if (!getargs(args, "")) - return NULL; - - return newintobject(TIMINGMS); - -} -static object * -micro(self, args) - object *self; - object *args; -{ - if (!getargs(args, "")) - return NULL; - - return newintobject(TIMINGUS); - -} - - -static struct methodlist timing_methods[] = { - {"start", start_timing}, - {"finish", finish_timing}, - {"seconds", seconds}, - {"milli", milli}, - {"micro", micro}, - {NULL, NULL} -}; - - -void inittiming() -{ - object *m; - - m = initmodule("timing", timing_methods); - -} diff --git a/Modules/tkappinit.c b/Modules/tkappinit.c deleted file mode 100644 index daff9e56e0..0000000000 --- a/Modules/tkappinit.c +++ /dev/null @@ -1,36 +0,0 @@ -/* appinit.c -- Tcl and Tk application initialization. */ - -#include <tcl.h> -#include <tk.h> - -int -Tcl_AppInit (interp) - Tcl_Interp *interp; -{ - Tk_Window main; - - main = Tk_MainWindow(interp); - - if (Tcl_Init (interp) == TCL_ERROR) - return TCL_ERROR; - if (Tk_Init (interp) == TCL_ERROR) - return TCL_ERROR; - -#ifdef WITH_MOREBUTTONS - { - extern Tcl_CmdProc studButtonCmd; - extern Tcl_CmdProc triButtonCmd; - - Tcl_CreateCommand(interp, "studbutton", studButtonCmd, - (ClientData) main, NULL); - Tcl_CreateCommand(interp, "tributton", triButtonCmd, - (ClientData) main, NULL); - } -#endif -#ifdef WITH_XXX - -#endif - - return TCL_OK; -} - diff --git a/Modules/xxmodule.c b/Modules/xxmodule.c deleted file mode 100644 index ac81f7781c..0000000000 --- a/Modules/xxmodule.c +++ /dev/null @@ -1,210 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Use this file as a template to start implementing a module that - also declares objects types. All occurrences of 'xxo' should be changed - to something reasonable for your objects. After that, all other - occurrences of 'xx' should be changed to something reasonable for your - module. If your module is named foo your sourcefile should be named - foomodule.c. - - You will probably want to delete all references to 'x_attr' and add - your own types of attributes instead. Maybe you want to name your - local variables other than 'self'. If your object type is needed in - other files, you'll have to create a file "foobarobject.h"; see - intobject.h for an example. */ - -/* Xxo objects */ - -#include "allobjects.h" - -static object *ErrorObject; - -typedef struct { - OB_HEAD - object *x_attr; /* Attributes dictionary */ -} xxoobject; - -staticforward typeobject Xxotype; - -#define is_xxoobject(v) ((v)->ob_type == &Xxotype) - -static xxoobject * -newxxoobject(arg) - object *arg; -{ - xxoobject *self; - self = NEWOBJ(xxoobject, &Xxotype); - if (self == NULL) - return NULL; - self->x_attr = NULL; - return self; -} - -/* Xxo methods */ - -static void -xxo_dealloc(self) - xxoobject *self; -{ - XDECREF(self->x_attr); - DEL(self); -} - -static object * -xxo_demo(self, args) - xxoobject *self; - object *args; -{ - if (!getnoarg(args)) - return NULL; - INCREF(None); - return None; -} - -static struct methodlist xxo_methods[] = { - {"demo", (method)xxo_demo}, - {NULL, NULL} /* sentinel */ -}; - -static object * -xxo_getattr(self, name) - xxoobject *self; - char *name; -{ - if (self->x_attr != NULL) { - object *v = dictlookup(self->x_attr, name); - if (v != NULL) { - INCREF(v); - return v; - } - } - return findmethod(xxo_methods, (object *)self, name); -} - -static int -xxo_setattr(self, name, v) - xxoobject *self; - char *name; - object *v; -{ - if (self->x_attr == NULL) { - self->x_attr = newdictobject(); - if (self->x_attr == NULL) - return -1; - } - if (v == NULL) { - int rv = dictremove(self->x_attr, name); - if (rv < 0) - err_setstr(AttributeError, - "delete non-existing xxo attribute"); - return rv; - } - else - return dictinsert(self->x_attr, name, v); -} - -staticforward typeobject Xxotype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "xxo", /*tp_name*/ - sizeof(xxoobject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)xxo_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)xxo_getattr, /*tp_getattr*/ - (setattrfunc)xxo_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ -}; -/* --------------------------------------------------------------------- */ - -/* Function of two integers returning integer */ - -static object * -xx_foo(self, args) - object *self; /* Not used */ - object *args; -{ - long i, j; - long res; - if (!getargs(args, "(ll)", &i, &j)) - return NULL; - res = i+j; /* XXX Do something here */ - return newintobject(res); -} - - -/* Function of no arguments returning new xxo object */ - -static object * -xx_new(self, args) - object *self; /* Not used */ - object *args; -{ - int i, j; - xxoobject *rv; - - if (!getnoarg(args)) - return NULL; - rv = newxxoobject(args); - if ( rv == NULL ) - return NULL; - return (object *)rv; -} - - -/* List of functions defined in the module */ - -static struct methodlist xx_methods[] = { - {"foo", xx_foo}, - {"new", xx_new}, - {NULL, NULL} /* sentinel */ -}; - - -/* Initialization function for the module (*must* be called initxx) */ - -void -initxx() -{ - object *m, *d; - - /* Create the module and add the functions */ - m = initmodule("xx", xx_methods); - - /* Add some symbolic constants to the module */ - d = getmoduledict(m); - ErrorObject = newstringobject("xx.error"); - dictinsert(d, "error", ErrorObject); - - /* Check for errors */ - if (err_occurred()) - fatal("can't initialize module xx"); -} diff --git a/Modules/yuv.h b/Modules/yuv.h deleted file mode 100644 index 7de0fbe16c..0000000000 --- a/Modules/yuv.h +++ /dev/null @@ -1,122 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#ifndef Py_YUV_H -#define Py_YUV_H -#ifdef __cplusplus -extern "C" { -#endif - -/* - * SVideo YUV 4:1:1 format. - * - * 4 consecutive quadwords describe 8 pixels on 2 lines, as depicted - * below. An array of (width/4) of the below structure describes 2 - * scan lines. - * - * +-------------------+ - * | 00 | 01 | 02 | 03 | . . . - * +-------------------+ - * | 10 | 11 | 12 | 13 | . . . - * +-------------------+ - */ -struct yuv411 { - struct { - unsigned int dummy:8; - unsigned int y0:8; - unsigned int u0:2; - unsigned int v0:2; - unsigned int y1:8; - unsigned int u1:2; - unsigned int v1:2; - } v[4]; -}; - -#define YUV411_Y00(y) (y).v[0].y0 -#define YUV411_Y01(y) (y).v[1].y0 -#define YUV411_Y02(y) (y).v[2].y0 -#define YUV411_Y03(y) (y).v[3].y0 -#define YUV411_Y10(y) (y).v[0].y1 -#define YUV411_Y11(y) (y).v[1].y1 -#define YUV411_Y12(y) (y).v[2].y1 -#define YUV411_Y13(y) (y).v[3].y1 -#define YUV411_U00(y) ((y).v[0].u0<<6|(y).v[1].u0<<4|(y).v[2].u0<<2|(y).v[3].u0) -#define YUV411_U01(y) YUV411_U00(y) -#define YUV411_U02(y) YUV411_U00(y) -#define YUV411_U03(y) YUV411_U00(y) -#define YUV411_U10(y) ((y).v[0].u1<<6|(y).v[1].u1<<4|(y).v[2].u1<<2|(y).v[3].u1) -#define YUV411_U11(y) YUV411_U10(y) -#define YUV411_U12(y) YUV411_U10(y) -#define YUV411_U13(y) YUV411_U10(y) -#define YUV411_V00(y) ((y).v[0].v0<<6|(y).v[1].v0<<4|(y).v[2].v0<<2|(y).v[3].v0) -#define YUV411_V01(y) YUV411_V00(y) -#define YUV411_V02(y) YUV411_V00(y) -#define YUV411_V03(y) YUV411_V00(y) -#define YUV411_V10(y) ((y).v[0].v1<<6|(y).v[1].v1<<4|(y).v[2].v1<<2|(y).v[3].v1) -#define YUV411_V11(y) YUV411_V10(y) -#define YUV411_V12(y) YUV411_V10(y) -#define YUV411_V13(y) YUV411_V10(y) - -/* - * Compression Library YUV 4:2:2 format. - * - * 1 longword describes 2 pixels. - * - * +-------+ - * | 0 | 1 | - * +-------+ - */ -struct yuv422 { - unsigned int u:8; - unsigned int y0:8; - unsigned int v:8; - unsigned int y1:8; -}; -#define YUV422_Y0(y) (y).y0 -#define YUV422_Y1(y) (y).y1 -#define YUV422_U0(y) (y).u -#define YUV422_U1(y) (y).u -#define YUV422_V0(y) (y).v -#define YUV422_V1(y) (y).v - -/* - * Compression library YUV 4:2:2 Duplicate Chroma format. - * - * This is like the previous format, but the U and V values are - * duplicated vertically (and hence there is some redundancy in the - * data). With other words, lines 2*n and 2*n+1 have the same U and V - * values but different Y values. - */ - -/* - * Conversion functions. - */ -void yuv_sv411_to_cl422dc(int, void *, void *, int, int); -void yuv_sv411_to_cl422dc_quartersize(int, void *, void *, int, int); -void yuv_sv411_to_cl422dc_sixteenthsize(int, void *, void *, int, int); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_YUV_H */ diff --git a/Modules/yuvconvert.c b/Modules/yuvconvert.c deleted file mode 100644 index 68933b7f62..0000000000 --- a/Modules/yuvconvert.c +++ /dev/null @@ -1,141 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#include "yuv.h" - -void -yuv_sv411_to_cl422dc(int invert, void *data, void *yuv, int width, int height) -{ - struct yuv411 *in = data; - struct yuv422 *out_even = yuv; - struct yuv422 *out_odd = out_even + width / 2; - int i, j; /* counters */ - - for (i = height / 2; i--; ) { - for (j = width / 4; j--; ) { - YUV422_Y0(*out_even) = YUV411_Y00(*in); - YUV422_U0(*out_even) = YUV411_U00(*in); - YUV422_V0(*out_even) = YUV411_V00(*in); - YUV422_Y1(*out_even) = YUV411_Y01(*in); - out_even++; - YUV422_Y0(*out_even) = YUV411_Y02(*in); - YUV422_U0(*out_even) = YUV411_U02(*in); - YUV422_V0(*out_even) = YUV411_V02(*in); - YUV422_Y1(*out_even) = YUV411_Y03(*in); - out_even++; - YUV422_Y0(*out_odd) = YUV411_Y10(*in); - YUV422_U0(*out_odd) = YUV411_U10(*in); - YUV422_V0(*out_odd) = YUV411_V10(*in); - YUV422_Y1(*out_odd) = YUV411_Y11(*in); - out_odd++; - YUV422_Y0(*out_odd) = YUV411_Y12(*in); - YUV422_U0(*out_odd) = YUV411_U12(*in); - YUV422_V0(*out_odd) = YUV411_V12(*in); - YUV422_Y1(*out_odd) = YUV411_Y13(*in); - out_odd++; - in++; - } - out_even += width / 2; - out_odd += width / 2; - } -} - -void -yuv_sv411_to_cl422dc_quartersize(int invert, void *data, void *yuv, - int width, int height) -{ - int w4 = width / 4; /* quarter of width is used often */ - struct yuv411 *in_even = data; - struct yuv411 *in_odd = in_even + w4; - struct yuv422 *out_even = yuv; - struct yuv422 *out_odd = out_even + w4; - int i, j; /* counters */ - int u, v; /* U and V values */ - - for (i = height / 4; i--; ) { - for (j = w4; j--; ) { - u = YUV411_U00(*in_even); - v = YUV411_V00(*in_even); - - YUV422_Y0(*out_even) = YUV411_Y00(*in_even); - YUV422_U0(*out_even) = u; - YUV422_V0(*out_even) = v; - YUV422_Y1(*out_even) = YUV411_Y02(*in_even); - - YUV422_Y0(*out_odd) = YUV411_Y10(*in_odd); - YUV422_U0(*out_odd) = u; - YUV422_V0(*out_odd) = v; - YUV422_Y1(*out_odd) = YUV411_Y12(*in_odd); - - in_even++; - in_odd++; - out_even++; - out_odd++; - } - in_even += w4; - in_odd += w4; - out_even += w4; - out_odd += w4; - } -} - -void -yuv_sv411_to_cl422dc_sixteenthsize(int invert, void *data, void *yuv, - int width, int height) -{ - int w4_3 = 3 * width / 4; /* three quarters of width is used often */ - int w8 = width / 8; /* and so is one eighth */ - struct yuv411 *in_even = data; - struct yuv411 *in_odd = in_even + width / 2; - struct yuv422 *out_even = yuv; - struct yuv422 *out_odd = out_even + w8; - int i, j; /* counters */ - int u, v; /* U and V values */ - - for (i = height / 8; i--; ) { - for (j = w8; j--; ) { - u = YUV411_U00(in_even[0]); - v = YUV411_V00(in_even[0]); - - YUV422_Y0(*out_even) = YUV411_Y00(in_even[0]); - YUV422_U0(*out_even) = u; - YUV422_V0(*out_even) = v; - YUV422_Y1(*out_even) = YUV411_Y00(in_even[1]); - - YUV422_Y0(*out_odd) = YUV411_Y00(in_odd[0]); - YUV422_U0(*out_odd) = u; - YUV422_V0(*out_odd) = v; - YUV422_Y1(*out_odd) = YUV411_Y00(in_even[1]); - - in_even += 2; - in_odd += 2; - out_even++; - out_odd++; - } - in_even += w4_3; - in_odd += w4_3; - out_even += w8; - out_odd += w8; - } -} diff --git a/Objects/Makefile.in b/Objects/Makefile.in deleted file mode 100644 index 2689f90684..0000000000 --- a/Objects/Makefile.in +++ /dev/null @@ -1,96 +0,0 @@ -# NOTE: Makefile.in is converted into Makefile by the configure script -# in the parent directory. Once configure has run, you can recreate -# the Makefile by running just config.status. - -# === Variables set by config.stat === - -srcdir= @srcdir@ -VPATH= @srcdir@ - -CC= @CC@ -RANLIB= @RANLIB@ -AR= @AR@ - -DEFS= @DEFS@ - - -# === Other things that are customizable but not by configure === - -INCLDIR= $(srcdir)/../Include -OPT= @OPT@ -CFLAGS= $(OPT) -I$(INCLDIR) -I.. $(DEFS) - -MKDEP= mkdep -SHELL= /bin/sh - - -# === Fixed definitions === - -OBJS= abstract.o accessobject.o \ - classobject.o cobject.o complexobject.o \ - fileobject.o floatobject.o \ - frameobject.o funcobject.o intobject.o listobject.o \ - longobject.o mappingobject.o methodobject.o \ - moduleobject.o object.o rangeobject.o stringobject.o \ - tupleobject.o typeobject.o - -SRCS= abstract.c accessobject.c \ - classobject.c cobject.c complexobject.c \ - fileobject.c floatobject.c \ - frameobject.c funcobject.c intobject.c listobject.c \ - longobject.c mappingobject.c methodobject.c \ - moduleobject.c object.c rangeobject.c stringobject.c \ - tupleobject.c typeobject.c - -LIB= libObjects.a - - -# === Rules === - -all: $(LIB) - -$(LIB): $& $(OBJS) - -rm -f $(LIB) - $(AR) cr $(LIB) $(OBJS) - $(RANLIB) $(LIB) - -clean: - -rm -f *.o core *~ [@,#]* *.old *.orig *.rej - -clobber: clean - -rm -f *.a tags TAGS - -Makefile: $(srcdir)/Makefile.in ../config.status - (cd ..; CONFIG_FILES=Objects/Makefile CONFIG_HEADERS= \ - $(SHELL) config.status) - -depend: - $(MKDEP) $(CFLAGS) `echo $(OBJS) | tr ' ' '\012' | \ - sed 's|\(.*\)\.o|$(srcdir)/\1.c|'` - -.PRECIOUS: Makefile - -abstract.o: abstract.c -accessobject.o: accessobject.c -classobject.o: classobject.c -cobject.o: cobject.c -complexobject.o: complexobject.c -fileobject.o: fileobject.c -floatobject.o: floatobject.c -frameobject.o: frameobject.c -funcobject.o: funcobject.c -intobject.o: intobject.c -listobject.o: listobject.c -longobject.o: longobject.c -mappingobject.o: mappingobject.c -methodobject.o: methodobject.c -moduleobject.o: moduleobject.c -object.o: object.c -rangeobject.o: rangeobject.c -stringobject.o: stringobject.c -tupleobject.o: tupleobject.c -typeobject.o: typeobject.c - -# DO NOT DELETE THIS LINE -- mkdep uses it. -# DO NOT PUT ANYTHING AFTER THIS LINE, IT WILL GO AWAY. -# IF YOU PUT ANYTHING HERE IT WILL GO AWAY diff --git a/Objects/abstract.c b/Objects/abstract.c deleted file mode 100644 index 1efec1a4f6..0000000000 --- a/Objects/abstract.c +++ /dev/null @@ -1,1026 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Abstract Object Interface (many thanks to Jim Fulton) */ - -#include "Python.h" - -#define Py_TRY(E) if(!(E)) return NULL -#define Py_ASSERT(EXP,E,V) if(!(EXP)) return PyErr_SetString(E,V), (void*)NULL -#define SPAM printf("line %d\n",__LINE__) - -static PyObject * -Py_ReturnMethodError(name) - char *name; -{ - if(! name) name = "Unknown Error"; - PyErr_SetString(PyExc_AttributeError,name); - return 0; -} - -PyObject * -Py_ReturnNullError() -{ - if(! PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, - "null argument to internal routine"); - return 0; -} - -int -PyObject_Cmp(o1, o2, result) - PyObject *o1; - PyObject *o2; - int *result; -{ - int r; - - if(! o1 || ! o2) return Py_ReturnNullError(),-1; - r=PyObject_Compare(o1,o2); - if(PyErr_Occurred()) return -1; - *result=r; - return 0; -} - -#if 0 /* Already in object.c */ -int -PyCallable_Check(x) - PyObject *x; -{ - if (x == NULL) - return 0; - if (x->ob_type->tp_call != NULL || - PyFunction_Check(x) || - PyMethod_Check(x) || - PyCFunction_Check(x) || - PyClass_Check(x)) - return 1; - if (PyInstance_Check(x)) { - PyObject *call = PyObject_GetAttrString(x, "__call__"); - if (call == NULL) { - PyErr_Clear(); - return 0; - } - /* Could test recursively but don't, for fear of endless - recursion if some joker sets self.__call__ = self */ - Py_DECREF(call); - return 1; - } - return 0; -} -#endif - -PyObject * -PyObject_Type(o) - PyObject *o; -{ - PyObject *v; - - if(! o) return Py_ReturnNullError(); - v = (PyObject *)o->ob_type; - Py_INCREF(v); - return v; -} - -int -PyObject_Length(o) - PyObject *o; -{ - PySequenceMethods *m; - - if(! o) return Py_ReturnNullError(),-1; - - if((m=o->ob_type->tp_as_sequence) && m->sq_length) - return m->sq_length(o); - - return PyMapping_Length(o); -} - -PyObject * -PyObject_GetItem(o, key) - PyObject *o; - PyObject *key; -{ - PyMappingMethods *m; - - if(! o || ! key) return Py_ReturnNullError(); - - if((m=o->ob_type->tp_as_mapping) && m->mp_subscript) - return m->mp_subscript(o,key); - - if(PyInt_Check(key)) - return PySequence_GetItem(o,PyInt_AsLong(key)); - - PyErr_SetString(PyExc_TypeError,"expected integer index"); - return NULL; -} - -int -PyObject_SetItem(o, key, value) - PyObject *o; - PyObject *key; - PyObject *value; -{ - PyMappingMethods *m; - - if(! o || ! key || ! value) return Py_ReturnNullError(),-1; - if((m=o->ob_type->tp_as_mapping) && m->mp_ass_subscript) - return m->mp_ass_subscript(o,key,value); - - if(PyInt_Check(key)) - return PySequence_SetItem(o,PyInt_AsLong(key),value); - - PyErr_SetString(PyExc_TypeError,"expeced integer index"); - return -1; -} - -int -PyNumber_Check(o) - PyObject *o; -{ - return o && o->ob_type->tp_as_number; -} - - -#define BINOP(opname, ropname, thisfunc) \ - if (!PyInstance_Check(v) && !PyInstance_Check(w)) \ - ; \ - else \ - return PyInstance_DoBinOp(v, w, opname, ropname, thisfunc) - -PyObject * -PyNumber_Or(v, w) - PyObject *v, *w; -{ - extern int PyNumber_Coerce(); - - BINOP("__or__", "__ror__", PyNumber_Or); - if (v->ob_type->tp_as_number != NULL) { - PyObject *x; - PyObject * (*f) Py_FPROTO((PyObject *, PyObject *)); - if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - if ((f = v->ob_type->tp_as_number->nb_or) != NULL) - x = (*f)(v, w); - Py_DECREF(v); - Py_DECREF(w); - if (f != NULL) - return x; - } - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for |"); - return NULL; -} - -PyObject * -PyNumber_Xor(v, w) - PyObject *v, *w; -{ - extern int PyNumber_Coerce(); - - BINOP("__xor__", "__rxor__", PyNumber_Xor); - if (v->ob_type->tp_as_number != NULL) { - PyObject *x; - PyObject * (*f) Py_FPROTO((PyObject *, PyObject *)); - if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - if ((f = v->ob_type->tp_as_number->nb_xor) != NULL) - x = (*f)(v, w); - Py_DECREF(v); - Py_DECREF(w); - if (f != NULL) - return x; - } - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for ^"); - return NULL; -} - -PyObject * -PyNumber_And(v, w) - PyObject *v, *w; -{ - BINOP("__and__", "__rand__", PyNumber_And); - if (v->ob_type->tp_as_number != NULL) { - PyObject *x; - PyObject * (*f) Py_FPROTO((PyObject *, PyObject *)); - if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - if ((f = v->ob_type->tp_as_number->nb_and) != NULL) - x = (*f)(v, w); - Py_DECREF(v); - Py_DECREF(w); - if (f != NULL) - return x; - } - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for &"); - return NULL; -} - -PyObject * -PyNumber_Lshift(v, w) - PyObject *v, *w; -{ - BINOP("__lshift__", "__rlshift__", PyNumber_Lshift); - if (v->ob_type->tp_as_number != NULL) { - PyObject *x; - PyObject * (*f) Py_FPROTO((PyObject *, PyObject *)); - if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - if ((f = v->ob_type->tp_as_number->nb_lshift) != NULL) - x = (*f)(v, w); - Py_DECREF(v); - Py_DECREF(w); - if (f != NULL) - return x; - } - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for <<"); - return NULL; -} - -PyObject * -PyNumber_Rshift(v, w) - PyObject *v, *w; -{ - BINOP("__rshift__", "__rrshift__", PyNumber_Rshift); - if (v->ob_type->tp_as_number != NULL) { - PyObject *x; - PyObject * (*f) Py_FPROTO((PyObject *, PyObject *)); - if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - if ((f = v->ob_type->tp_as_number->nb_rshift) != NULL) - x = (*f)(v, w); - Py_DECREF(v); - Py_DECREF(w); - if (f != NULL) - return x; - } - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for >>"); - return NULL; -} - -PyObject * -PyNumber_Add(v, w) - PyObject *v, *w; -{ - BINOP("__add__", "__radd__", PyNumber_Add); - if (v->ob_type->tp_as_sequence != NULL) - return (*v->ob_type->tp_as_sequence->sq_concat)(v, w); - else if (v->ob_type->tp_as_number != NULL) { - PyObject *x; - if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - x = (*v->ob_type->tp_as_number->nb_add)(v, w); - Py_DECREF(v); - Py_DECREF(w); - return x; - } - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for +"); - return NULL; -} - -PyObject * -PyNumber_Subtract(v, w) - PyObject *v, *w; -{ - BINOP("__sub__", "__rsub__", PyNumber_Subtract); - if (v->ob_type->tp_as_number != NULL) { - PyObject *x; - if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - x = (*v->ob_type->tp_as_number->nb_subtract)(v, w); - Py_DECREF(v); - Py_DECREF(w); - return x; - } - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for -"); - return NULL; -} - -PyObject * -PyNumber_Multiply(v, w) - PyObject *v, *w; -{ - PyTypeObject *tp; - tp = v->ob_type; - BINOP("__mul__", "__rmul__", PyNumber_Multiply); - if (tp->tp_as_number != NULL && - w->ob_type->tp_as_sequence != NULL && - !PyInstance_Check(v)) { - /* number*sequence -- swap v and w */ - PyObject *tmp = v; - v = w; - w = tmp; - tp = v->ob_type; - } - if (tp->tp_as_number != NULL) { - PyObject *x; - if (PyInstance_Check(v)) { - /* Instances of user-defined classes get their - other argument uncoerced, so they may - implement sequence*number as well as - number*number. */ - Py_INCREF(v); - Py_INCREF(w); - } - else if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - x = (*v->ob_type->tp_as_number->nb_multiply)(v, w); - Py_DECREF(v); - Py_DECREF(w); - return x; - } - if (tp->tp_as_sequence != NULL) { - if (!PyInt_Check(w)) { - PyErr_SetString(PyExc_TypeError, - "can't multiply sequence with non-int"); - return NULL; - } - return (*tp->tp_as_sequence->sq_repeat) - (v, (int)PyInt_AsLong(w)); - } - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for *"); - return NULL; -} - -PyObject * -PyNumber_Divide(v, w) - PyObject *v, *w; -{ - BINOP("__div__", "__rdiv__", PyNumber_Divide); - if (v->ob_type->tp_as_number != NULL) { - PyObject *x; - if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - x = (*v->ob_type->tp_as_number->nb_divide)(v, w); - Py_DECREF(v); - Py_DECREF(w); - return x; - } - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for /"); - return NULL; -} - -PyObject * -PyNumber_Remainder(v, w) - PyObject *v, *w; -{ - if (PyString_Check(v)) { - return PyString_Format(v, w); - } - BINOP("__mod__", "__rmod__", PyNumber_Remainder); - if (v->ob_type->tp_as_number != NULL) { - PyObject *x; - if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - x = (*v->ob_type->tp_as_number->nb_remainder)(v, w); - Py_DECREF(v); - Py_DECREF(w); - return x; - } - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for %"); - return NULL; -} - -PyObject * -PyNumber_Divmod(v, w) - PyObject *v, *w; -{ - PyObject *res; - - if (PyInstance_Check(v) || PyInstance_Check(w)) - return PyInstance_DoBinOp(v, w, "__divmod__", "__rdivmod__", - PyNumber_Divmod); - if (v->ob_type->tp_as_number == NULL || - w->ob_type->tp_as_number == NULL) { - PyErr_SetString(PyExc_TypeError, - "divmod() requires numeric or class instance arguments"); - return NULL; - } - if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - res = (*v->ob_type->tp_as_number->nb_divmod)(v, w); - Py_DECREF(v); - Py_DECREF(w); - return res; -} - - -static PyObject * -do_pow(v, w) - PyObject *v, *w; -{ - PyObject *res; - if (PyInstance_Check(v) || PyInstance_Check(w)) - return PyInstance_DoBinOp(v, w, "__pow__", "__rpow__", do_pow); - if (v->ob_type->tp_as_number == NULL || - w->ob_type->tp_as_number == NULL) { - PyErr_SetString(PyExc_TypeError, - "pow() requires numeric arguments"); - return NULL; - } - if (PyFloat_Check(w) && PyFloat_AsDouble(v) < 0.0) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "negative number to float power"); - return NULL; - } - if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - res = (*v->ob_type->tp_as_number->nb_power)(v, w, Py_None); - Py_DECREF(v); - Py_DECREF(w); - return res; -} - -PyObject * -PyNumber_Power(v,w,z) - PyObject *v, *w, *z; -{ - PyObject *res; - PyObject *v1, *z1, *w2, *z2; - - if (z == Py_None) - return do_pow(v, w); - /* XXX The ternary version doesn't do class instance coercions */ - if (PyInstance_Check(v)) - return v->ob_type->tp_as_number->nb_power(v, w, z); - if (v->ob_type->tp_as_number == NULL || - z->ob_type->tp_as_number == NULL || - w->ob_type->tp_as_number == NULL) { - PyErr_SetString(PyExc_TypeError, "pow() requires numeric arguments"); - return NULL; - } - if (PyNumber_Coerce(&v, &w) != 0) - return NULL; - res = NULL; - v1 = v; - z1 = z; - if (PyNumber_Coerce(&v1, &z1) != 0) - goto error2; - w2 = w; - z2 = z1; - if (PyNumber_Coerce(&w2, &z2) != 0) - goto error1; - res = (*v1->ob_type->tp_as_number->nb_power)(v1, w2, z2); - Py_DECREF(w2); - Py_DECREF(z2); - error1: - Py_DECREF(v1); - Py_DECREF(z1); - error2: - Py_DECREF(v); - Py_DECREF(w); - return res; -} - - -PyObject * -PyNumber_Negative(v) - PyObject *v; -{ - if (v->ob_type->tp_as_number != NULL) - return (*v->ob_type->tp_as_number->nb_negative)(v); - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for unary -"); - return NULL; -} - -PyObject * -PyNumber_Positive(v) - PyObject *v; -{ - if (v->ob_type->tp_as_number != NULL) - return (*v->ob_type->tp_as_number->nb_positive)(v); - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for unary +"); - return NULL; -} - -PyObject * -PyNumber_Invert(v) - PyObject *v; -{ - PyObject * (*f) Py_FPROTO((PyObject *)); - if (v->ob_type->tp_as_number != NULL && - (f = v->ob_type->tp_as_number->nb_invert) != NULL) - return (*f)(v); - PyErr_SetString(PyExc_TypeError, "bad operand type(s) for unary ~"); - return NULL; -} - -PyObject * -PyNumber_Absolute(o) - PyObject *o; -{ - PyNumberMethods *m; - - if(! o) return Py_ReturnNullError(); - if((m=o->ob_type->tp_as_number) && m->nb_absolute) - return m->nb_absolute(o); - - return Py_ReturnMethodError("__abs__"); -} - -PyObject * -PyNumber_Int(o) - PyObject *o; -{ - PyNumberMethods *m; - - if(! o) return Py_ReturnNullError(); - if((m=o->ob_type->tp_as_number) && m->nb_int) - return m->nb_int(o); - - return Py_ReturnMethodError("__int__"); -} - -PyObject * -PyNumber_Long(o) - PyObject *o; -{ - PyNumberMethods *m; - - if(! o) return Py_ReturnNullError(); - if((m=o->ob_type->tp_as_number) && m->nb_long) - return m->nb_long(o); - - return Py_ReturnMethodError("__long__"); -} - -PyObject * -PyNumber_Float(o) - PyObject *o; -{ - PyNumberMethods *m; - - if(! o) return Py_ReturnNullError(); - if((m=o->ob_type->tp_as_number) && m->nb_float) - return m->nb_float(o); - - return Py_ReturnMethodError("__float__"); -} - - -int -PySequence_Check(o) - PyObject *o; -{ - return o && o->ob_type->tp_as_sequence; -} - -int -PySequence_Length(s) - PyObject *s; -{ - PySequenceMethods *m; - - if(! s) return Py_ReturnNullError(),-1; - - if((m=s->ob_type->tp_as_sequence) && m->sq_length) - return m->sq_length(s); - - Py_ReturnMethodError("__len__"); - return -1; -} - -PyObject * -PySequence_Concat(s, o) - PyObject *s; - PyObject *o; -{ - PySequenceMethods *m; - - if(! s || ! o) return Py_ReturnNullError(); - - if((m=s->ob_type->tp_as_sequence) && m->sq_concat) - return m->sq_concat(s,o); - - return Py_ReturnMethodError("__concat__"); -} - -PyObject * -PySequence_Repeat(o, count) - PyObject *o; - int count; -{ - PySequenceMethods *m; - - if(! o) return Py_ReturnNullError(); - - if((m=o->ob_type->tp_as_sequence) && m->sq_repeat) - return m->sq_repeat(o,count); - - return Py_ReturnMethodError("__repeat__"); -} - -PyObject * -PySequence_GetItem(s, i) - PyObject *s; - int i; -{ - PySequenceMethods *m; - int l; - - if(! s) return Py_ReturnNullError(); - - if(! ((m=s->ob_type->tp_as_sequence) && m->sq_length && m->sq_item)) - return Py_ReturnMethodError("__getitem__"); - - if(0 > (l=m->sq_length(s))) return NULL; - - if(i < 0) i += l; - - return m->sq_item(s,i); -} - -PyObject * -PySequence_GetSlice(s, i1, i2) - PyObject *s; - int i1; - int i2; -{ - PySequenceMethods *m; - int l; - - if(! s) return Py_ReturnNullError(); - - if(! ((m=s->ob_type->tp_as_sequence) && m->sq_length && m->sq_slice)) - return Py_ReturnMethodError("__getslice__"); - - if(0 > (l=m->sq_length(s))) return NULL; - - if(i1 < 0) i1 += l; - if(i2 < 0) i2 += l; - - return m->sq_slice(s,i1,i2); -} - -int -PySequence_SetItem(s, i, o) - PyObject *s; - int i; - PyObject *o; -{ - PySequenceMethods *m; - int l; - if(! s) return Py_ReturnNullError(),-1; - - if(! ((m=s->ob_type->tp_as_sequence) && m->sq_length && m->sq_ass_item)) - return Py_ReturnMethodError("__setitem__"),-1; - - if(i < 0) - { - if(0 > (l=m->sq_length(s))) return -1; - i += l; - } - - return m->sq_ass_item(s,i,o); -} - -int -PySequence_SetSlice(s, i1, i2, o) - PyObject *s; - int i1; - int i2; - PyObject *o; -{ - PySequenceMethods *m; - int l; - - if(! s) return Py_ReturnNullError(),-1; - - if(! ((m=s->ob_type->tp_as_sequence) && m->sq_length && m->sq_ass_slice)) - return Py_ReturnMethodError("__setslice__"),-1; - - if(0 > (l=m->sq_length(s))) return -1; - - if(i1 < 0) i1 += l; - if(i2 < 0) i2 += l; - - return m->sq_ass_slice(s,i1,i2,o); -} - -PyObject * -PySequence_Tuple(s) - PyObject *s; -{ - int l, i; - PyObject *t, *item; - - if(! s) return Py_ReturnNullError(); - - Py_TRY((l=PySequence_Length(s)) != -1); - Py_TRY(t=PyTuple_New(l)); - - for(i=0; i < l; i++) - { - if(item=PySequence_GetItem(s,i)) - { - if(PyTuple_SetItem(t,i,item) == -1) - { - Py_DECREF(item); - Py_DECREF(t); - return NULL; - } - } - else - { - Py_DECREF(t); - return NULL; - } - } - return t; -} - -int -PySequence_Count(s, o) - PyObject *s; - PyObject *o; -{ - int l, i, n=0, not_equal, err; - PyObject *item; - - if(! s || ! o) return Py_ReturnNullError(), -1; - Py_TRY((l=PySequence_Length(s)) != -1),-1; - - for(i=0; i < l; i++) - { - Py_TRY(item=PySequence_GetItem(s,i)),-1; - err=PyObject_Cmp(item,o,&not_equal) == -1; - Py_DECREF(item); - if(err) return -1; - n += ! not_equal; - } - return n; -} - -int -PySequence_In(s, o) - PyObject *s; - PyObject *o; -{ - int l, i, not_equal, err; - PyObject *item; - - if(! o || ! s) return Py_ReturnNullError(), -1; - Py_TRY((l=PySequence_Length(s)) != -1),-1; - - for(i=0; i < l; i++) - { - Py_TRY(item=PySequence_GetItem(s,i)),-1; - err=PyObject_Cmp(item,o,&not_equal) == -1; - Py_DECREF(item); - if(err) return -1; - if(! not_equal) return 1; - } - return 0; -} - -int -PySequence_Index(s, o) - PyObject *s; - PyObject *o; -{ - int l, i, n=0, not_equal, err; - PyObject *item; - - if(! s || ! o) return Py_ReturnNullError(), -1; - Py_TRY((l=PySequence_Length(s)) != -1),-1; - - for(i=0; i < l; i++) - { - Py_TRY(item=PySequence_GetItem(s,i)),-1; - err=PyObject_Cmp(item,o,&not_equal) == -1; - Py_DECREF(item); - if(err) return -1; - if(! not_equal) return n; - } - return -1; -} - -int -PyMapping_Check(o) - PyObject *o; -{ - return o && o->ob_type->tp_as_mapping; -} - -int -PyMapping_Length(s) - PyObject *s; -{ - PyMappingMethods *m; - - if(! s) return Py_ReturnNullError(),-1; - - if((m=s->ob_type->tp_as_mapping) && m->mp_length) - return m->mp_length(s); - - Py_ReturnMethodError("__len__"); - return -1; -} - -int -PyMapping_HasKeyString(o, key) - PyObject *o; - char *key; -{ - PyObject *v; - - v=PyMapping_GetItemString(o,key); - if(v) return 1; - PyErr_Clear(); - return 0; -} - -int -PyMapping_HasKey(o, key) - PyObject *o; - PyObject *key; -{ - PyObject *v; - - v=PyObject_GetItem(o,key); - if(v) return 1; - PyErr_Clear(); - return 0; -} - -PyObject * -PyObject_CallObject(o, a) - PyObject *o, *a; -{ - PyObject *r; - - if(a) return PyEval_CallObject(o,a); - - if(! (a=PyTuple_New(0))) - return NULL; - r=PyEval_CallObject(o,a); - Py_DECREF(a); - return r; -} - -PyObject * -#ifdef HAVE_STDARG_PROTOTYPES -/* VARARGS 2 */ -PyObject_CallFunction(PyObject *callable, char *format, ...) -#else -/* VARARGS */ -PyObject_CallFunction(va_alist) va_dcl -#endif -{ - va_list va; - PyObject *args, *retval; -#ifdef HAVE_STDARG_PROTOTYPES - va_start(va, format); -#else - PyObject *callable; - char *format; - va_start(va); - callable = va_arg(va, PyObject *); - format = va_arg(va, char *); -#endif - - if( ! callable) - { - va_end(va); - return Py_ReturnNullError(); - } - - if(format) - args = Py_VaBuildValue(format, va); - else - args = PyTuple_New(0); - - va_end(va); - if(! args) return NULL; - - if(! PyTuple_Check(args)) - { - PyObject *a; - - Py_TRY(a=PyTuple_New(1)); - Py_TRY(PyTuple_SetItem(a,0,args) != -1); - args=a; - } - retval = PyObject_CallObject(callable,args); - Py_DECREF(args); - return retval; -} - -PyObject * -#ifdef HAVE_STDARG_PROTOTYPES -/* VARARGS 2 */ -PyObject_CallMethod(PyObject *o, char *name, char *format, ...) -#else -/* VARARGS */ -PyObject_CallMethod(va_alist) va_dcl -#endif -{ - va_list va; - PyObject *args, *method=0, *retval; -#ifdef HAVE_STDARG_PROTOTYPES - va_start(va, format); -#else - PyObject *o; - char *name; - char *format; - va_start(va); - o = va_arg(va, PyObject *); - name = va_arg(va, char *); - format = va_arg(va, char *); -#endif - - if( ! o || ! name) - { - va_end(va); - return Py_ReturnNullError(); - } - - method=PyObject_GetAttrString(o,name); - if(! method) - { - va_end(va); - PyErr_SetString(PyExc_AttributeError,name); - return 0; - } - - if(! (PyCallable_Check(method))) - { - va_end(va); - PyErr_SetString(PyExc_TypeError,"call of non-callable attribute"); - return 0; - } - - if(format) - args = Py_VaBuildValue(format, va); - else - args = PyTuple_New(0); - - va_end(va); - - if(! args) return NULL; - - if(! PyTuple_Check(args)) - { - PyObject *a; - - Py_TRY(a=PyTuple_New(1)); - Py_TRY(PyTuple_SetItem(a,0,args) != -1); - args=a; - } - - retval = PyObject_CallObject(method,args); - Py_DECREF(args); - Py_DECREF(method); - return retval; -} - -PyObject * -PyMapping_GetItemString(o, key) - PyObject *o; - char *key; -{ - PyObject *okey, *r; - - if( ! key) return Py_ReturnNullError(); - Py_TRY(okey=PyString_FromString(key)); - r = PyObject_GetItem(o,okey); - Py_DECREF(okey); - return r; -} - -int -PyMapping_SetItemString(o, key, value) - PyObject *o; - char *key; - PyObject *value; -{ - PyObject *okey; - int r; - - if( ! key) return Py_ReturnNullError(),-1; - if (!(okey=PyString_FromString(key))) return -1; - r = PyObject_SetItem(o,okey,value); - Py_DECREF(okey); - return r; -} diff --git a/Objects/accessobject.c b/Objects/accessobject.c deleted file mode 100644 index f3c7dfc9b9..0000000000 --- a/Objects/accessobject.c +++ /dev/null @@ -1,360 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Access object implementation */ - -/* XXX TO DO LIST - - __init__ and __del__ (and all other similar methods) - should be usable even when private, not ignored -*/ - -#include "allobjects.h" -#include "ceval.h" -#include "structmember.h" -#include "modsupport.h" /* For getargs() etc. */ - -typedef struct { - OB_HEAD - object *ac_value; - object *ac_owner; - typeobject *ac_type; - int ac_mode; -} accessobject; - -/* Forward */ -static int typecheck PROTO((object *, typeobject *)); -static int ownercheck PROTO((object *, object *, int, int)); - -object * -newaccessobject(value, owner, type, mode) - object *value; - object *owner; - typeobject *type; - int mode; -{ - accessobject *ap; - if (!typecheck(value, type)) { - err_setstr(AccessError, - "access: initial value has inappropriate type"); - return NULL; - } - ap = NEWOBJ(accessobject, &Accesstype); - if (ap == NULL) - return NULL; - XINCREF(value); - ap->ac_value = value; - XINCREF(owner); - ap->ac_owner = owner; - XINCREF(type); - ap->ac_type = (typeobject *)type; - ap->ac_mode = mode; - return (object *)ap; -} - -object * -cloneaccessobject(op) - object *op; -{ - register accessobject *ap; - if (!is_accessobject(op)) { - err_badcall(); - return NULL; - } - ap = (accessobject *)op; - return newaccessobject(ap->ac_value, ap->ac_owner, - ap->ac_type, ap->ac_mode); -} - -void -setaccessowner(op, owner) - object *op; - object *owner; -{ - register accessobject *ap; - if (!is_accessobject(op)) - return; /* XXX no error */ - ap = (accessobject *)op; - XDECREF(ap->ac_owner); - XINCREF(owner); - ap->ac_owner = owner; -} - -int -hasaccessvalue(op) - object *op; -{ - if (!is_accessobject(op)) - return 0; - return ((accessobject *)op)->ac_value != NULL; -} - -object * -getaccessvalue(op, caller) - object *op; - object *caller; -{ - register accessobject *ap; - if (!is_accessobject(op)) { - err_badcall(); - return NULL; - } - ap = (accessobject *)op; - - if (!ownercheck(caller, ap->ac_owner, AC_R, ap->ac_mode)) { - err_setstr(AccessError, "read access denied"); - return NULL; - } - - if (ap->ac_value == NULL) { - err_setstr(AccessError, "no current value"); - return NULL; - } - INCREF(ap->ac_value); - return ap->ac_value; -} - -int -setaccessvalue(op, caller, value) - object *op; - object *caller; - object *value; -{ - register accessobject *ap; - if (!is_accessobject(op)) { - err_badcall(); - return -1; - } - ap = (accessobject *)op; - - if (!ownercheck(caller, ap->ac_owner, AC_W, ap->ac_mode)) { - err_setstr(AccessError, "write access denied"); - return -1; - } - - if (!typecheck(value, ap->ac_type)) { - err_setstr(AccessError, "assign value of inappropriate type"); - return -1; - } - - if (value == NULL) { /* Delete it */ - if (ap->ac_value == NULL) { - err_setstr(AccessError, "no current value"); - return -1; - } - DECREF(ap->ac_value); - ap->ac_value = NULL; - return 0; - } - XDECREF(ap->ac_value); - INCREF(value); - ap->ac_value = value; - return 0; -} - -static int -typecheck(value, type) - object *value; - typeobject *type; -{ - object *x; - if (value == NULL || type == NULL) - return 1; /* No check */ - if (value->ob_type == type) - return 1; /* Exact match */ - if (type == &Anynumbertype) { - if (value->ob_type->tp_as_number == NULL) - return 0; - if (!is_instanceobject(value)) - return 1; - /* For instances, make sure it really looks like a number */ - x = getattr(value, "__sub__"); - if (x == NULL) { - err_clear(); - return 0; - } - DECREF(x); - return 1; - } - if (type == &Anysequencetype) { - if (value->ob_type->tp_as_sequence == NULL) - return 0; - if (!is_instanceobject(value)) - return 1; - /* For instances, make sure it really looks like a sequence */ - x = getattr(value, "__getslice__"); - if (x == NULL) { - err_clear(); - return 0; - } - DECREF(x); - return 1; - } - if (type == &Anymappingtype) { - if (value->ob_type->tp_as_mapping == NULL) - return 0; - if (!is_instanceobject(value)) - return 1; - /* For instances, make sure it really looks like a mapping */ - x = getattr(value, "__getitem__"); - if (x == NULL) { - err_clear(); - return 0; - } - DECREF(x); - return 1; - } - return 0; -} - -static int -isprivileged(caller) - object *caller; -{ - object *g; - static char privileged[] = "__privileged__"; - if (caller != NULL && hasattr(caller, privileged)) - return 1; - g = getglobals(); - if (g != NULL && dictlookup(g, privileged)) - return 1; - return 0; -} - -static int -ownercheck(caller, owner, access, mode) - object *caller; - object *owner; - int access; - int mode; -{ - int mask = AC_PUBLIC; - if (caller == owner || isprivileged(caller)) - mask |= AC_PRIVATE | AC_PROTECTED; - else if (caller != NULL && owner != NULL && - is_classobject(owner) && is_classobject(caller) && - (issubclass(caller, owner) || - issubclass(owner, caller))) - mask |= AC_PROTECTED; - return access & mode & mask; -} - -/* Access methods */ - -static void -access_dealloc(ap) - accessobject *ap; -{ - XDECREF(ap->ac_value); - XDECREF(ap->ac_owner); - XDECREF(ap->ac_type); - DEL(ap); -} - -#define OFF(x) offsetof(accessobject, x) - -static struct memberlist access_memberlist[] = { - {"ac_value", T_OBJECT, OFF(ac_value)}, - {"ac_owner", T_OBJECT, OFF(ac_owner)}, - {"ac_type", T_OBJECT, OFF(ac_type)}, - {"ac_mode", T_INT, OFF(ac_mode)}, - {NULL} /* Sentinel */ -}; - -static object * -access_getattr(ap, name) - accessobject *ap; - char *name; -{ - return getmember((char *)ap, access_memberlist, name); -} - -static object * -access_repr(ap) - accessobject *ap; -{ - char buf[300]; - char buf2[20]; - char *ownername; - typeobject *type = ap->ac_type; - if (is_classobject(ap->ac_owner)) { - ownername = - getstringvalue(((classobject *)ap->ac_owner)->cl_name); - } - else { - sprintf(buf2, "0x%lx", (long)ap->ac_owner); - ownername = buf2; - } - sprintf(buf, - "<access object, value 0x%lx, owner %.100s, type %.100s, mode %04o>", - (long)(ap->ac_value), - ownername, - type ? type->tp_name : "-", - ap->ac_mode); - return newstringobject(buf); -} - -typeobject Accesstype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "access", /*tp_name*/ - sizeof(accessobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)access_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)access_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - (reprfunc)access_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ -}; - - -/* Pseudo type objects to indicate collections of types */ - -/* XXX This should be replaced by a more general "subclassing" - XXX mechanism for type objects... */ - -typeobject Anynumbertype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "*number*", /*tp_name*/ -}; - -/* XXX Should really distinguish mutable and immutable sequences as well */ - -typeobject Anysequencetype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "*sequence*", /*tp_name*/ -}; - -typeobject Anymappingtype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "*mapping*", /*tp_name*/ -}; diff --git a/Objects/classobject.c b/Objects/classobject.c deleted file mode 100644 index f5a0d2a36c..0000000000 --- a/Objects/classobject.c +++ /dev/null @@ -1,1316 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Class object implementation */ - -#include "allobjects.h" -#include "structmember.h" - -/* Forward */ -static object *class_lookup PROTO((classobject *, char *, classobject **)); -static object *instance_getattr1 PROTO((instanceobject *, char *)); - -object * -newclassobject(bases, dict, name) - object *bases; /* NULL or tuple of classobjects! */ - object *dict; - object *name; /* String; NULL if unknown */ -{ - int pos; - object *key, *value; - classobject *op, *dummy; - if (dictlookup(dict, "__doc__") == NULL) { - if (dictinsert(dict, "__doc__", None) < 0) - return NULL; - } - if (bases == NULL) { - bases = newtupleobject(0); - if (bases == NULL) - return NULL; - } - else - INCREF(bases); - op = NEWOBJ(classobject, &Classtype); - if (op == NULL) { - DECREF(bases); - return NULL; - } - op->cl_bases = bases; - INCREF(dict); - op->cl_dict = dict; - XINCREF(name); - op->cl_name = name; - op->cl_getattr = class_lookup(op, "__getattr__", &dummy); - op->cl_setattr = class_lookup(op, "__setattr__", &dummy); - op->cl_delattr = class_lookup(op, "__delattr__", &dummy); - XINCREF(op->cl_getattr); - XINCREF(op->cl_setattr); - XINCREF(op->cl_delattr); - pos = 0; - while (mappinggetnext(dict, &pos, &key, &value)) { - if (is_accessobject(value)) - setaccessowner(value, (object *)op); - } - return (object *) op; -} - -/* Class methods */ - -static void -class_dealloc(op) - classobject *op; -{ - DECREF(op->cl_bases); - DECREF(op->cl_dict); - XDECREF(op->cl_name); - free((ANY *)op); -} - -static object * -class_lookup(cp, name, pclass) - classobject *cp; - char *name; - classobject **pclass; -{ - int i, n; - object *value = dictlookup(cp->cl_dict, name); - if (value != NULL) { - *pclass = cp; - return value; - } - n = gettuplesize(cp->cl_bases); - for (i = 0; i < n; i++) { - object *v = class_lookup((classobject *) - gettupleitem(cp->cl_bases, i), name, pclass); - if (v != NULL) - return v; - } - return NULL; -} - -static object * -class_getattr(op, name) - register classobject *op; - register char *name; -{ - register object *v; - classobject *class; - if (name[0] == '_' && name[1] == '_') { - if (strcmp(name, "__dict__") == 0) { - if (getrestricted()) { - err_setstr(RuntimeError, - "class.__dict__ not accessible in restricted mode"); - return NULL; - } - INCREF(op->cl_dict); - return op->cl_dict; - } - if (strcmp(name, "__bases__") == 0) { - INCREF(op->cl_bases); - return op->cl_bases; - } - if (strcmp(name, "__name__") == 0) { - if (op->cl_name == NULL) - v = None; - else - v = op->cl_name; - INCREF(v); - return v; - } - } - v = class_lookup(op, name, &class); - if (v == NULL) { - err_setstr(AttributeError, name); - return NULL; - } - if (is_accessobject(v)) { - v = getaccessvalue(v, getowner()); - if (v == NULL) - return NULL; - } - else - INCREF(v); - if (is_funcobject(v)) { - object *w = newinstancemethodobject(v, (object *)NULL, - (object *)class); - DECREF(v); - v = w; - } - return v; -} - -static int -class_setattr(op, name, v) - classobject *op; - char *name; - object *v; -{ - object *ac; - if (name[0] == '_' && name[1] == '_') { - int n = strlen(name); - if (name[n-1] == '_' && name[n-2] == '_') { - err_setstr(TypeError, "read-only special attribute"); - return -1; - } - } - if (getrestricted()) { - err_setstr(RuntimeError, - "classes are read-only in restricted mode"); - return -1; - } - ac = dictlookup(op->cl_dict, name); - if (ac != NULL && is_accessobject(ac)) - return setaccessvalue(ac, getowner(), v); - if (v == NULL) { - int rv = dictremove(op->cl_dict, name); - if (rv < 0) - err_setstr(AttributeError, - "delete non-existing class attribute"); - return rv; - } - else - return dictinsert(op->cl_dict, name, v); -} - -static object * -class_repr(op) - classobject *op; -{ - char buf[140]; - char *name; - if (op->cl_name == NULL || !is_stringobject(op->cl_name)) - name = "?"; - else - name = getstringvalue(op->cl_name); - sprintf(buf, "<class %.100s at %lx>", name, (long)op); - return newstringobject(buf); -} - -typeobject Classtype = { - OB_HEAD_INIT(&Typetype) - 0, - "class", - sizeof(classobject), - 0, - (destructor)class_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)class_getattr, /*tp_getattr*/ - (setattrfunc)class_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - (reprfunc)class_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ -}; - -int -issubclass(class, base) - object *class; - object *base; -{ - int i, n; - classobject *cp; - if (class == base) - return 1; - if (class == NULL || !is_classobject(class)) - return 0; - cp = (classobject *)class; - n = gettuplesize(cp->cl_bases); - for (i = 0; i < n; i++) { - if (issubclass(gettupleitem(cp->cl_bases, i), base)) - return 1; - } - return 0; -} - - -/* Instance objects */ - -static int -addaccess(class, inst) - classobject *class; - instanceobject *inst; -{ - int i, n, pos, ret; - object *key, *value, *ac; - - n = gettuplesize(class->cl_bases); - for (i = 0; i < n; i++) { - if (addaccess((classobject *)gettupleitem(class->cl_bases, i), inst) < 0) - return -1; - } - - pos = 0; - while (mappinggetnext(class->cl_dict, &pos, &key, &value)) { - if (!is_accessobject(value)) - continue; - if (hasaccessvalue(value)) - continue; - ac = dict2lookup(inst->in_dict, key); - if (ac != NULL && is_accessobject(ac)) { - err_setval(ConflictError, key); - return -1; - } - ac = cloneaccessobject(value); - if (ac == NULL) - return -1; - ret = dict2insert(inst->in_dict, key, ac); - DECREF(ac); - if (ret != 0) - return -1; - } - return 0; -} - -object * -newinstanceobject(class, arg, kw) - object *class; - object *arg; - object *kw; -{ - register instanceobject *inst; - object *init; - if (!is_classobject(class)) { - err_badcall(); - return NULL; - } - inst = NEWOBJ(instanceobject, &Instancetype); - if (inst == NULL) - return NULL; - INCREF(class); - inst->in_class = (classobject *)class; - inst->in_dict = newdictobject(); - if (inst->in_dict == NULL || - addaccess((classobject *)class, inst) != 0) { - DECREF(inst); - return NULL; - } - init = instance_getattr1(inst, "__init__"); - if (init == NULL) { - err_clear(); - if (arg != NULL && (!is_tupleobject(arg) || - gettuplesize(arg) != 0) || kw != NULL) { - err_setstr(TypeError, - "this constructor takes no arguments"); - DECREF(inst); - inst = NULL; - } - } - else { - object *res = PyEval_CallObjectWithKeywords(init, arg, kw); - DECREF(init); - if (res == NULL) { - DECREF(inst); - inst = NULL; - } - else { - if (res != None) { - err_setstr(TypeError, - "__init__() should return None"); - DECREF(inst); - inst = NULL; - } - DECREF(res); - } - } - return (object *)inst; -} - -/* Instance methods */ - -static void -instance_dealloc(inst) - register instanceobject *inst; -{ - object *error_type, *error_value, *error_traceback; - object *del; - /* Call the __del__ method if it exists. First temporarily - revive the object and save the current exception, if any. */ -#ifdef Py_TRACE_REFS - /* much too complicated if Py_TRACE_REFS defined */ - extern long ref_total; - inst->ob_type = &Instancetype; - NEWREF(inst); - ref_total--; /* compensate for increment in NEWREF */ -#ifdef COUNT_ALLOCS - inst->ob_type->tp_alloc--; /* ditto */ -#endif -#else /* !Py_TRACE_REFS */ - INCREF(inst); -#endif /* !Py_TRACE_REFS */ - err_fetch(&error_type, &error_value, &error_traceback); - if ((del = instance_getattr1(inst, "__del__")) != NULL) { - object *res = call_object(del, (object *)NULL); - DECREF(del); - XDECREF(res); - /* XXX If __del__ raised an exception, it is ignored! */ - } - /* Restore the saved exception and undo the temporary revival */ - err_restore(error_type, error_value, error_traceback); - /* Can't use DECREF here, it would cause a recursive call */ - if (--inst->ob_refcnt > 0) { -#ifdef COUNT_ALLOCS - inst->ob_type->tp_free--; -#endif - return; /* __del__ added a reference; don't delete now */ - } -#ifdef Py_TRACE_REFS -#ifdef COUNT_ALLOCS - inst->ob_type->tp_free--; /* compensate for increment in UNREF */ -#endif - UNREF(inst); - inst->ob_type = NULL; -#endif /* Py_TRACE_REFS */ - DECREF(inst->in_class); - XDECREF(inst->in_dict); - free((ANY *)inst); -} - -static object * -instance_getattr1(inst, name) - register instanceobject *inst; - register char *name; -{ - register object *v; - classobject *class; - if (name[0] == '_' && name[1] == '_') { - if (strcmp(name, "__dict__") == 0) { - if (getrestricted()) { - err_setstr(RuntimeError, - "instance.__dict__ not accessible in restricted mode"); - return NULL; - } - INCREF(inst->in_dict); - return inst->in_dict; - } - if (strcmp(name, "__class__") == 0) { - INCREF(inst->in_class); - return (object *)inst->in_class; - } - } - class = NULL; - v = dictlookup(inst->in_dict, name); - if (v == NULL) { - v = class_lookup(inst->in_class, name, &class); - if (v == NULL) { - err_setstr(AttributeError, name); - return NULL; - } - } - if (is_accessobject(v)) { - v = getaccessvalue(v, getowner()); - if (v == NULL) - return NULL; - } - else - INCREF(v); - if (class != NULL) { - if (is_funcobject(v)) { - object *w = newinstancemethodobject(v, (object *)inst, - (object *)class); - DECREF(v); - v = w; - } - else if (is_instancemethodobject(v)) { - object *im_class = instancemethodgetclass(v); - /* Only if classes are compatible */ - if (issubclass((object *)class, im_class)) { - object *im_func = instancemethodgetfunc(v); - object *w = newinstancemethodobject(im_func, - (object *)inst, im_class); - DECREF(v); - v = w; - } - } - } - return v; -} - -static object * -instance_getattr(inst, name) - register instanceobject *inst; - register char *name; -{ - register object *func, *res; - res = instance_getattr1(inst, name); - if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) { - object *args; - err_clear(); - args = mkvalue("(Os)", inst, name); - if (args == NULL) - return NULL; - res = call_object(func, args); - DECREF(args); - } - return res; -} - -static int -instance_setattr1(inst, name, v) - instanceobject *inst; - char *name; - object *v; -{ - object *ac; - ac = dictlookup(inst->in_dict, name); - if (ac != NULL && is_accessobject(ac)) - return setaccessvalue(ac, getowner(), v); - if (v == NULL) { - int rv = dictremove(inst->in_dict, name); - if (rv < 0) - err_setstr(AttributeError, - "delete non-existing instance attribute"); - return rv; - } - else - return dictinsert(inst->in_dict, name, v); -} - -static int -instance_setattr(inst, name, v) - instanceobject *inst; - char *name; - object *v; -{ - object *func, *args, *res; - if (name[0] == '_' && name[1] == '_') { - int n = strlen(name); - if (name[n-1] == '_' && name[n-2] == '_') { - err_setstr(TypeError, "read-only special attribute"); - return -1; - } - } - if (v == NULL) - func = inst->in_class->cl_delattr; - else - func = inst->in_class->cl_setattr; - if (func == NULL) - return instance_setattr1(inst, name, v); - if (v == NULL) - args = mkvalue("(Os)", inst, name); - else - args = mkvalue("(OsO)", inst, name, v); - if (args == NULL) - return -1; - res = call_object(func, args); - DECREF(args); - if (res == NULL) - return -1; - DECREF(res); - return 0; -} - -static object * -instance_repr(inst) - instanceobject *inst; -{ - object *func; - object *res; - - func = instance_getattr(inst, "__repr__"); - if (func == NULL) { - char buf[140]; - object *classname = inst->in_class->cl_name; - char *cname; - if (classname != NULL && is_stringobject(classname)) - cname = getstringvalue(classname); - else - cname = "?"; - err_clear(); - sprintf(buf, "<%.100s instance at %lx>", cname, (long)inst); - return newstringobject(buf); - } - res = call_object(func, (object *)NULL); - DECREF(func); - return res; -} - -static object * -instance_compare1(inst, other) - object *inst, *other; -{ - return instancebinop(inst, other, "__cmp__", "__rcmp__", - instance_compare1); -} - -static int -instance_compare(inst, other) - object *inst, *other; -{ - object *result; - long outcome; - result = instance_compare1(inst, other); - if (result == NULL || !is_intobject(result)) { - error: - err_clear(); - return (inst < other) ? -1 : 1; - } - outcome = getintvalue(result); - DECREF(result); - if (outcome < 0) - return -1; - else if (outcome > 0) - return 1; - return 0; -} - -static long -instance_hash(inst) - instanceobject *inst; -{ - object *func; - object *res; - long outcome; - - func = instance_getattr(inst, "__hash__"); - if (func == NULL) { - /* If there is no __cmp__ method, we hash on the address. - If a __cmp__ method exists, there must be a __hash__. */ - err_clear(); - func = instance_getattr(inst, "__cmp__"); - if (func == NULL) { - err_clear(); - outcome = (long)inst; - if (outcome == -1) - outcome = -2; - return outcome; - } - err_setstr(TypeError, "unhashable instance"); - return -1; - } - res = call_object(func, (object *)NULL); - DECREF(func); - if (res == NULL) - return -1; - if (is_intobject(res)) { - outcome = getintvalue(res); - if (outcome == -1) - outcome = -2; - } - else { - err_setstr(TypeError, "__hash__() should return an int"); - outcome = -1; - } - DECREF(res); - return outcome; -} - -static int -instance_length(inst) - instanceobject *inst; -{ - object *func; - object *res; - int outcome; - - func = instance_getattr(inst, "__len__"); - if (func == NULL) - return -1; - res = call_object(func, (object *)NULL); - DECREF(func); - if (res == NULL) - return -1; - if (is_intobject(res)) { - outcome = getintvalue(res); - if (outcome < 0) - err_setstr(ValueError, "__len__() should return >= 0"); - } - else { - err_setstr(TypeError, "__len__() should return an int"); - outcome = -1; - } - DECREF(res); - return outcome; -} - -static object * -instance_subscript(inst, key) - instanceobject *inst; - object *key; -{ - object *func; - object *arg; - object *res; - - func = instance_getattr(inst, "__getitem__"); - if (func == NULL) - return NULL; - arg = mkvalue("(O)", key); - if (arg == NULL) { - DECREF(func); - return NULL; - } - res = call_object(func, arg); - DECREF(func); - DECREF(arg); - return res; -} - -static int -instance_ass_subscript(inst, key, value) - instanceobject*inst; - object *key; - object *value; -{ - object *func; - object *arg; - object *res; - - if (value == NULL) - func = instance_getattr(inst, "__delitem__"); - else - func = instance_getattr(inst, "__setitem__"); - if (func == NULL) - return -1; - if (value == NULL) - arg = mkvalue("(O)", key); - else - arg = mkvalue("(OO)", key, value); - if (arg == NULL) { - DECREF(func); - return -1; - } - res = call_object(func, arg); - DECREF(func); - DECREF(arg); - if (res == NULL) - return -1; - DECREF(res); - return 0; -} - -static mapping_methods instance_as_mapping = { - (inquiry)instance_length, /*mp_length*/ - (binaryfunc)instance_subscript, /*mp_subscript*/ - (objobjargproc)instance_ass_subscript, /*mp_ass_subscript*/ -}; - -static object * -instance_item(inst, i) - instanceobject *inst; - int i; -{ - object *func, *arg, *res; - - func = instance_getattr(inst, "__getitem__"); - if (func == NULL) - return NULL; - arg = mkvalue("(i)", i); - if (arg == NULL) { - DECREF(func); - return NULL; - } - res = call_object(func, arg); - DECREF(func); - DECREF(arg); - return res; -} - -static object * -instance_slice(inst, i, j) - instanceobject *inst; - int i, j; -{ - object *func, *arg, *res; - - func = instance_getattr(inst, "__getslice__"); - if (func == NULL) - return NULL; - arg = mkvalue("(ii)", i, j); - if (arg == NULL) { - DECREF(func); - return NULL; - } - res = call_object(func, arg); - DECREF(func); - DECREF(arg); - return res; -} - -static int -instance_ass_item(inst, i, item) - instanceobject *inst; - int i; - object *item; -{ - object *func, *arg, *res; - - if (item == NULL) - func = instance_getattr(inst, "__delitem__"); - else - func = instance_getattr(inst, "__setitem__"); - if (func == NULL) - return -1; - if (item == NULL) - arg = mkvalue("i", i); - else - arg = mkvalue("(iO)", i, item); - if (arg == NULL) { - DECREF(func); - return -1; - } - res = call_object(func, arg); - DECREF(func); - DECREF(arg); - if (res == NULL) - return -1; - DECREF(res); - return 0; -} - -static int -instance_ass_slice(inst, i, j, value) - instanceobject *inst; - int i, j; - object *value; -{ - object *func, *arg, *res; - - if (value == NULL) - func = instance_getattr(inst, "__delslice__"); - else - func = instance_getattr(inst, "__setslice__"); - if (func == NULL) - return -1; - if (value == NULL) - arg = mkvalue("(ii)", i, j); - else - arg = mkvalue("(iiO)", i, j, value); - if (arg == NULL) { - DECREF(func); - return -1; - } - res = call_object(func, arg); - DECREF(func); - DECREF(arg); - if (res == NULL) - return -1; - DECREF(res); - return 0; -} - -static sequence_methods instance_as_sequence = { - (inquiry)instance_length, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - (intargfunc)instance_item, /*sq_item*/ - (intintargfunc)instance_slice, /*sq_slice*/ - (intobjargproc)instance_ass_item, /*sq_ass_item*/ - (intintobjargproc)instance_ass_slice, /*sq_ass_slice*/ -}; - -static object * -generic_unary_op(self, methodname) - instanceobject *self; - char *methodname; -{ - object *func, *res; - - if ((func = instance_getattr(self, methodname)) == NULL) - return NULL; - res = call_object(func, (object *)NULL); - DECREF(func); - return res; -} - - -/* Forward */ -static int halfbinop PROTO((object *, object *, char *, object **, - object * (*) PROTO((object *, object *)), int )); - - -/* Implement a binary operator involving at least one class instance. */ - -object * -instancebinop(v, w, opname, ropname, thisfunc) - object *v; - object *w; - char *opname; - char *ropname; - object * (*thisfunc) PROTO((object *, object *)); -{ - char buf[256]; - object *result = NULL; - if (halfbinop(v, w, opname, &result, thisfunc, 0) <= 0) - return result; - if (halfbinop(w, v, ropname, &result, thisfunc, 1) <= 0) - return result; - sprintf(buf, "%s nor %s defined for these operands", opname, ropname); - err_setstr(TypeError, buf); - return NULL; -} - - -/* Try one half of a binary operator involving a class instance. - Return value: - -1 if an exception is to be reported right away - 0 if we have a valid result - 1 if we could try another operation -*/ - -static int -halfbinop(v, w, opname, r_result, thisfunc, swapped) - object *v; - object *w; - char *opname; - object **r_result; - object * (*thisfunc) PROTO((object *, object *)); - int swapped; -{ - object *func; - object *args; - object *coerce; - object *coerced = NULL; - object *v1; - - if (!is_instanceobject(v)) - return 1; - coerce = getattr(v, "__coerce__"); - if (coerce == NULL) { - err_clear(); - } - else { - args = mkvalue("(O)", w); - if (args == NULL) { - return -1; - } - coerced = call_object(coerce, args); - DECREF(args); - DECREF(coerce); - if (coerced == NULL) { - return -1; - } - if (coerced == None) { - DECREF(coerced); - return 1; - } - if (!is_tupleobject(coerced) || gettuplesize(coerced) != 2) { - DECREF(coerced); - err_setstr(TypeError, - "coercion should return None or 2-tuple"); - return -1; - } - v1 = gettupleitem(coerced, 0); - w = gettupleitem(coerced, 1); - if (v1 != v) { - v = v1; - if (!is_instanceobject(v) && !is_instanceobject(w)) { - if (swapped) - *r_result = (*thisfunc)(w, v); - else - *r_result = (*thisfunc)(v, w); - DECREF(coerced); - return *r_result == NULL ? -1 : 0; - } - } - w = gettupleitem(coerced, 1); - } - func = getattr(v, opname); - if (func == NULL) { - XDECREF(coerced); - if (err_occurred() != AttributeError) - return -1; - err_clear(); - return 1; - } - args = mkvalue("(O)", w); - if (args == NULL) { - DECREF(func); - XDECREF(coerced); - return -1; - } - *r_result = call_object(func, args); - DECREF(args); - DECREF(func); - XDECREF(coerced); - return *r_result == NULL ? -1 : 0; -} - -static int -instance_coerce(pv, pw) - object **pv; - object **pw; -{ - object *v = *pv; - object *w = *pw; - object *coerce; - object *args; - object *coerced; - - coerce = getattr(v, "__coerce__"); - if (coerce == NULL) { - /* No __coerce__ method: always OK */ - err_clear(); - INCREF(v); - INCREF(w); - return 0; - } - /* Has __coerce__ method: call it */ - args = mkvalue("(O)", w); - if (args == NULL) { - return -1; - } - coerced = call_object(coerce, args); - DECREF(args); - DECREF(coerce); - if (coerced == NULL) { - /* __coerce__ call raised an exception */ - return -1; - } - if (coerced == None) { - /* __coerce__ says "I can't do it" */ - DECREF(coerced); - return 1; - } - if (!is_tupleobject(coerced) || gettuplesize(coerced) != 2) { - /* __coerce__ return value is malformed */ - DECREF(coerced); - err_setstr(TypeError, - "coercion should return None or 2-tuple"); - return -1; - } - /* __coerce__ returned two new values */ - *pv = gettupleitem(coerced, 0); - *pw = gettupleitem(coerced, 1); - INCREF(*pv); - INCREF(*pw); - DECREF(coerced); - return 0; -} - - -#define UNARY(funcname, methodname) \ -static object *funcname(self) instanceobject *self; { \ - return generic_unary_op(self, methodname); \ -} - -UNARY(instance_neg, "__neg__") -UNARY(instance_pos, "__pos__") -UNARY(instance_abs, "__abs__") - -static int -instance_nonzero(self) - instanceobject *self; -{ - object *func, *res; - long outcome; - - if ((func = instance_getattr(self, "__nonzero__")) == NULL) { - err_clear(); - if ((func = instance_getattr(self, "__len__")) == NULL) { - err_clear(); - /* Fall back to the default behavior: - all instances are nonzero */ - return 1; - } - } - res = call_object(func, (object *)NULL); - DECREF(func); - if (res == NULL) - return -1; - if (!is_intobject(res)) { - DECREF(res); - err_setstr(TypeError, "__nonzero__ should return an int"); - return -1; - } - outcome = getintvalue(res); - DECREF(res); - if (outcome < 0) { - err_setstr(ValueError, "__nonzero__ should return >= 0"); - return -1; - } - return outcome > 0; -} - -UNARY(instance_invert, "__invert__") -UNARY(instance_int, "__int__") -UNARY(instance_long, "__long__") -UNARY(instance_float, "__float__") -UNARY(instance_oct, "__oct__") -UNARY(instance_hex, "__hex__") - -/* This version is for ternary calls only (z != None) */ -static object * -instance_pow(v, w, z) - object *v; - object *w; - object *z; -{ - /* XXX Doesn't do coercions... */ - object *func; - object *args; - object *result; - func = getattr(v, "__pow__"); - if (func == NULL) - return NULL; - args = mkvalue("(OO)", w, z); - if (args == NULL) { - DECREF(func); - return NULL; - } - result = call_object(func, args); - DECREF(func); - DECREF(args); - return result; -} - -static number_methods instance_as_number = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - 0, /*nb_divide*/ - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - (ternaryfunc)instance_pow, /*nb_power*/ - (unaryfunc)instance_neg, /*nb_negative*/ - (unaryfunc)instance_pos, /*nb_positive*/ - (unaryfunc)instance_abs, /*nb_absolute*/ - (inquiry)instance_nonzero, /*nb_nonzero*/ - (unaryfunc)instance_invert, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - (coercion)instance_coerce, /*nb_coerce*/ - (unaryfunc)instance_int, /*nb_int*/ - (unaryfunc)instance_long, /*nb_long*/ - (unaryfunc)instance_float, /*nb_float*/ - (unaryfunc)instance_oct, /*nb_oct*/ - (unaryfunc)instance_hex, /*nb_hex*/ -}; - -typeobject Instancetype = { - OB_HEAD_INIT(&Typetype) - 0, - "instance", - sizeof(instanceobject), - 0, - (destructor)instance_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)instance_getattr, /*tp_getattr*/ - (setattrfunc)instance_setattr, /*tp_setattr*/ - instance_compare, /*tp_compare*/ - (reprfunc)instance_repr, /*tp_repr*/ - &instance_as_number, /*tp_as_number*/ - &instance_as_sequence, /*tp_as_sequence*/ - &instance_as_mapping, /*tp_as_mapping*/ - (hashfunc)instance_hash, /*tp_hash*/ -}; - - -/* Instance method objects are used for two purposes: - (a) as bound instance methods (returned by instancename.methodname) - (b) as unbound methods (returned by ClassName.methodname) - In case (b), im_self is NULL -*/ - -typedef struct { - OB_HEAD - object *im_func; /* The function implementing the method */ - object *im_self; /* The instance it is bound to, or NULL */ - object *im_class; /* The class that defined the method */ -} instancemethodobject; - -object * -newinstancemethodobject(func, self, class) - object *func; - object *self; - object *class; -{ - register instancemethodobject *im; - if (!is_funcobject(func)) { - err_badcall(); - return NULL; - } - im = NEWOBJ(instancemethodobject, &Instancemethodtype); - if (im == NULL) - return NULL; - INCREF(func); - im->im_func = func; - XINCREF(self); - im->im_self = self; - INCREF(class); - im->im_class = class; - return (object *)im; -} - -object * -instancemethodgetfunc(im) - register object *im; -{ - if (!is_instancemethodobject(im)) { - err_badcall(); - return NULL; - } - return ((instancemethodobject *)im)->im_func; -} - -object * -instancemethodgetself(im) - register object *im; -{ - if (!is_instancemethodobject(im)) { - err_badcall(); - return NULL; - } - return ((instancemethodobject *)im)->im_self; -} - -object * -instancemethodgetclass(im) - register object *im; -{ - if (!is_instancemethodobject(im)) { - err_badcall(); - return NULL; - } - return ((instancemethodobject *)im)->im_class; -} - -/* Class method methods */ - -#define OFF(x) offsetof(instancemethodobject, x) - -static struct memberlist instancemethod_memberlist[] = { - {"im_func", T_OBJECT, OFF(im_func)}, - {"im_self", T_OBJECT, OFF(im_self)}, - {"im_class", T_OBJECT, OFF(im_class)}, - /* Dummies that are not handled by getattr() except for __members__ */ - {"__doc__", T_INT, 0}, - {"__name__", T_INT, 0}, - {NULL} /* Sentinel */ -}; - -static object * -instancemethod_getattr(im, name) - register instancemethodobject *im; - char *name; -{ - if (name[0] == '_') { - funcobject *func = (funcobject *)(im->im_func); - if (strcmp(name, "__name__") == 0) { - INCREF(func->func_name); - return func->func_name; - } - if (strcmp(name, "__doc__") == 0) { - INCREF(func->func_doc); - return func->func_doc; - } - } - if (getrestricted()) { - err_setstr(RuntimeError, - "instance-method attributes not accessible in restricted mode"); - return NULL; - } - return getmember((char *)im, instancemethod_memberlist, name); -} - -static void -instancemethod_dealloc(im) - register instancemethodobject *im; -{ - DECREF(im->im_func); - XDECREF(im->im_self); - DECREF(im->im_class); - free((ANY *)im); -} - -static int -instancemethod_compare(a, b) - instancemethodobject *a, *b; -{ - if (a->im_self != b->im_self) - return (a->im_self < b->im_self) ? -1 : 1; - return cmpobject(a->im_func, b->im_func); -} - -static object * -instancemethod_repr(a) - instancemethodobject *a; -{ - char buf[240]; - instanceobject *self = (instanceobject *)(a->im_self); - funcobject *func = (funcobject *)(a->im_func); - classobject *class = (classobject *)(a->im_class); - object *fclassname, *iclassname, *funcname; - char *fcname, *icname, *fname; - fclassname = class->cl_name; - funcname = func->func_name; - if (fclassname != NULL && is_stringobject(fclassname)) - fcname = getstringvalue(fclassname); - else - fcname = "?"; - if (funcname != NULL && is_stringobject(funcname)) - fname = getstringvalue(funcname); - else - fname = "?"; - if (self == NULL) - sprintf(buf, "<unbound method %.100s.%.100s>", fcname, fname); - else { - iclassname = self->in_class->cl_name; - if (iclassname != NULL && is_stringobject(iclassname)) - icname = getstringvalue(iclassname); - else - icname = "?"; - sprintf(buf, "<method %.60s.%.60s of %.60s instance at %lx>", - fcname, fname, icname, (long)self); - } - return newstringobject(buf); -} - -static long -instancemethod_hash(a) - instancemethodobject *a; -{ - long x, y; - if (a->im_self == NULL) - x = hashobject(None); - else - x = hashobject(a->im_self); - if (x == -1) - return -1; - y = hashobject(a->im_func); - if (y == -1) - return -1; - return x ^ y; -} - -typeobject Instancemethodtype = { - OB_HEAD_INIT(&Typetype) - 0, - "instance method", - sizeof(instancemethodobject), - 0, - (destructor)instancemethod_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)instancemethod_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)instancemethod_compare, /*tp_compare*/ - (reprfunc)instancemethod_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)instancemethod_hash, /*tp_hash*/ -}; diff --git a/Objects/cobject.c b/Objects/cobject.c deleted file mode 100644 index f14a4d9407..0000000000 --- a/Objects/cobject.c +++ /dev/null @@ -1,100 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Wrap void* pointers to be passed between C modules */ - -#include "Python.h" - - -/* Declarations for objects of type PyCObject */ - -typedef struct { - PyObject_HEAD - void *cobject; - void (*destructor)(void *); -} PyCObject; - -PyObject * -PyCObject_FromVoidPtr(cobj, destr) - void *cobj; - void (*destr)(void *); -{ - PyCObject *self; - - self = PyObject_NEW(PyCObject, &PyCObject_Type); - if (self == NULL) - return NULL; - self->cobject=cobj; - self->destructor=destr; - return (PyObject *)self; -} - -void * -PyCObject_AsVoidPtr(self) - PyObject *self; -{ - return ((PyCObject *)self)->cobject; -} - -static void -PyCObject_dealloc(self) - PyCObject *self; -{ - if(self->destructor) (self->destructor)(self->cobject); - PyMem_DEL(self); -} - -static char PyCObject_Type__doc__[] = -"C objects to be exported from one extension module to another\n" -"\n" -"C objects are used for communication between extension modules. They\n" -"provide a way for an extension module to export a C interface to other\n" -"extension modules, so that extension modules can use the Python import\n" -"mechanism to link to one another.\n" -; - -PyTypeObject PyCObject_Type = { - PyObject_HEAD_INIT(&PyType_Type) - 0, /*ob_size*/ - "PyCObject", /*tp_name*/ - sizeof(PyCObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyCObject_dealloc, /*tp_dealloc*/ - (printfunc)0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - (cmpfunc)0, /*tp_compare*/ - (reprfunc)0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)0, /*tp_hash*/ - (ternaryfunc)0, /*tp_call*/ - (reprfunc)0, /*tp_str*/ - - /* Space for future expansion */ - 0L,0L,0L,0L, - PyCObject_Type__doc__ /* Documentation string */ -}; diff --git a/Objects/complexobject.c b/Objects/complexobject.c deleted file mode 100644 index d49c6d352f..0000000000 --- a/Objects/complexobject.c +++ /dev/null @@ -1,573 +0,0 @@ -/* Complex object implementation */ - -/* Borrows heavily from floatobject.c */ - -#ifndef WITHOUT_COMPLEX - -#include "allobjects.h" -#include "modsupport.h" - -#include <errno.h> -#include "mymath.h" - -#ifdef i860 -/* Cray APP has bogus definition of HUGE_VAL in <math.h> */ -#undef HUGE_VAL -#endif - -#ifdef HUGE_VAL -#define CHECK(x) if (errno != 0) ; \ - else if (-HUGE_VAL <= (x) && (x) <= HUGE_VAL) ; \ - else errno = ERANGE -#else -#define CHECK(x) /* Don't know how to check */ -#endif - -#ifdef HAVE_LIMITS_H -#include <limits.h> -#endif - -#ifndef LONG_MAX -#define LONG_MAX 0X7FFFFFFFL -#endif - -#ifndef LONG_MIN -#define LONG_MIN (-LONG_MAX-1) -#endif - -#ifdef __NeXT__ -#ifdef __sparc__ -/* - * This works around a bug in the NS/Sparc 3.3 pre-release - * limits.h header file. - * 10-Feb-1995 bwarsaw@cnri.reston.va.us - */ -#undef LONG_MIN -#define LONG_MIN (-LONG_MAX-1) -#endif -#endif - -#if !defined(__STDC__) && !defined(macintosh) -extern double fmod PROTO((double, double)); -extern double pow PROTO((double, double)); -#endif - - -/* elementary operations on complex numbers */ - -static int c_error; -static complex c_1 = {1., 0.}; - -complex c_sum(a,b) - complex a,b; -{ - complex r; - r.real = a.real + b.real; - r.imag = a.imag + b.imag; - return r; -} - -complex c_diff(a,b) - complex a,b; -{ - complex r; - r.real = a.real - b.real; - r.imag = a.imag - b.imag; - return r; -} - -complex c_neg(a) - complex a; -{ - complex r; - r.real = -a.real; - r.imag = -a.imag; - return r; -} - -complex c_prod(a,b) - complex a,b; -{ - complex r; - r.real = a.real*b.real - a.imag*b.imag; - r.imag = a.real*b.imag + a.imag*b.real; - return r; -} - -complex c_quot(a,b) - complex a,b; -{ - complex r; - double d = b.real*b.real + b.imag*b.imag; - if (d == 0.) - c_error = 1; - r.real = (a.real*b.real + a.imag*b.imag)/d; - r.imag = (a.imag*b.real - a.real*b.imag)/d; - return r; -} - -complex c_pow(a,b) - complex a,b; -{ - complex r; - double vabs,len,at,phase; - if (b.real == 0. && b.imag == 0.) { - r.real = 1.; - r.imag = 0.; - } - else if (a.real == 0. && a.imag == 0.) { - if (b.imag != 0. || b.real < 0.) - c_error = 2; - r.real = 0.; - r.imag = 0.; - } - else { - vabs = hypot(a.real,a.imag); - len = pow(vabs,b.real); - at = atan2(a.imag, a.real); - phase = at*b.real; - if (b.imag != 0.0) { - len /= exp(at*b.imag); - phase += b.imag*log(vabs); - } - r.real = len*cos(phase); - r.imag = len*sin(phase); - } - return r; -} - -static complex c_powu(x, n) - complex x; - long n; -{ - complex r = c_1; - complex p = x; - long mask = 1; - while (mask > 0 && n >= mask) { - if (n & mask) - r = c_prod(r,p); - mask <<= 1; - p = c_prod(p,p); - } - return r; -} - -static complex c_powi(x, n) - complex x; - long n; -{ - complex cn; - - if (n > 100 || n < -100) { - cn.real = (double) n; - cn.imag = 0.; - return c_pow(x,cn); - } - else if (n > 0) - return c_powu(x,n); - else - return c_quot(c_1,c_powu(x,-n)); - -} - -PyObject * -PyComplex_FromCComplex(complex cval) -{ - register complexobject *op = (complexobject *) malloc(sizeof(complexobject)); - if (op == NULL) - return err_nomem(); - op->ob_type = &Complextype; - op->cval = cval; - NEWREF(op); - return (object *) op; -} - -PyObject * -PyComplex_FromDoubles(double real, double imag) { - complex c; - c.real = real; - c.imag = imag; - return PyComplex_FromCComplex(c); -} - -double -PyComplex_RealAsDouble(PyObject *op) { - if (PyComplex_Check(op)) { - return ((PyComplexObject *)op)->cval.real; - } else { - return PyFloat_AsDouble(op); - } -} - -double -PyComplex_ImagAsDouble(PyObject *op) { - if (PyComplex_Check(op)) { - return ((PyComplexObject *)op)->cval.imag; - } else { - return 0.0; - } -} - -complex -PyComplex_AsCComplex(PyObject *op) { - complex cv; - if (PyComplex_Check(op)) { - return ((PyComplexObject *)op)->cval; - } else { - cv.real = PyFloat_AsDouble(op); - cv.imag = 0.; - return cv; - } -} - -static void -complex_dealloc(op) - object *op; -{ - DEL(op); -} - - -static void -complex_buf_repr(buf, v) - char *buf; - complexobject *v; -{ - if (v->cval.real == 0.) - sprintf(buf, "%.12gj", v->cval.imag); - else - sprintf(buf, "(%.12g%+.12gj)", v->cval.real, v->cval.imag); -} - -static int -complex_print(v, fp, flags) - complexobject *v; - FILE *fp; - int flags; /* Not used but required by interface */ -{ - char buf[100]; - complex_buf_repr(buf, v); - fputs(buf, fp); - return 0; -} - -static object * -complex_repr(v) - complexobject *v; -{ - char buf[100]; - complex_buf_repr(buf, v); - return newstringobject(buf); -} - -static int -complex_compare(v, w) - complexobject *v, *w; -{ -/* Note: "greater" and "smaller" have no meaning for complex numbers, - but Python requires that they be defined nevertheless. */ - complex i = v->cval; - complex j = w->cval; - if (i.real == j.real && i.imag == j.imag) - return 0; - else if (i.real != j.real) - return (i.real < j.real) ? -1 : 1; - else - return (i.imag < j.imag) ? -1 : 1; -} - -static long -complex_hash(v) - complexobject *v; -{ - double intpart, fractpart; - int expo; - long x; - /* This is designed so that Python numbers with the same - value hash to the same value, otherwise comparisons - of mapping keys will turn out weird */ - -#ifdef MPW /* MPW C modf expects pointer to extended as second argument */ -{ - extended e; - fractpart = modf(v->cval.real, &e); - intpart = e; -} -#else - fractpart = modf(v->cval.real, &intpart); -#endif - - if (fractpart == 0.0) { - if (intpart > 0x7fffffffL || -intpart > 0x7fffffffL) { - /* Convert to long int and use its hash... */ - object *w = dnewlongobject(v->cval.real); - if (w == NULL) - return -1; - x = hashobject(w); - DECREF(w); - return x; - } - x = (long)intpart; - } - else { - fractpart = frexp(fractpart, &expo); - fractpart = fractpart*2147483648.0; /* 2**31 */ - x = (long) (intpart + fractpart) ^ expo; /* Rather arbitrary */ - } - if (x == -1) - x = -2; - return x; -} - -static object * -complex_add(v, w) - complexobject *v; - complexobject *w; -{ - return newcomplexobject(c_sum(v->cval,w->cval)); -} - -static object * -complex_sub(v, w) - complexobject *v; - complexobject *w; -{ - return newcomplexobject(c_diff(v->cval,w->cval)); -} - -static object * -complex_mul(v, w) - complexobject *v; - complexobject *w; -{ - return newcomplexobject(c_prod(v->cval,w->cval)); -} - -static object * -complex_div(v, w) - complexobject *v; - complexobject *w; -{ - complex quot; - c_error = 0; - quot = c_quot(v->cval,w->cval); - if (c_error == 1) { - err_setstr(ZeroDivisionError, "float division"); - return NULL; - } - return newcomplexobject(quot); -} - - -static object * -complex_pow(v, w, z) - complexobject *v; - object *w; - complexobject *z; -{ - complex p; - complex exponent; - long int_exponent; - - if ((object *)z!=None) { - err_setstr(ValueError, "complex modulo"); - return NULL; - } - - c_error = 0; - exponent = ((complexobject*)w)->cval; - int_exponent = (long)exponent.real; - if (exponent.imag == 0. && exponent.real == int_exponent) - p = c_powi(v->cval,int_exponent); - else - p = c_pow(v->cval,exponent); - - if (c_error == 2) { - err_setstr(ValueError, "0.0 to a negative or complex power"); - return NULL; - } - - return newcomplexobject(p); -} - -static object * -complex_neg(v) - complexobject *v; -{ - complex neg; - neg.real = -v->cval.real; - neg.imag = -v->cval.imag; - return newcomplexobject(neg); -} - -static object * -complex_pos(v) - complexobject *v; -{ - INCREF(v); - return (object *)v; -} - -static object * -complex_abs(v) - complexobject *v; -{ - return newfloatobject(hypot(v->cval.real,v->cval.imag)); -} - -static int -complex_nonzero(v) - complexobject *v; -{ - return v->cval.real != 0.0 && v->cval.imag != 0.0; -} - -static int -complex_coerce(pv, pw) - object **pv; - object **pw; -{ - complex cval; - cval.imag = 0.; - if (is_intobject(*pw)) { - cval.real = (double)getintvalue(*pw); - *pw = newcomplexobject(cval); - INCREF(*pv); - return 0; - } - else if (is_longobject(*pw)) { - cval.real = dgetlongvalue(*pw); - *pw = newcomplexobject(cval); - INCREF(*pv); - return 0; - } - else if (is_floatobject(*pw)) { - cval.real = getfloatvalue(*pw); - *pw = newcomplexobject(cval); - INCREF(*pv); - return 0; - } - return 1; /* Can't do it */ -} - -static object * -complex_int(v) - object *v; -{ - double x = ((complexobject *)v)->cval.real; - if (x < 0 ? (x = ceil(x)) < (double)LONG_MIN - : (x = floor(x)) > (double)LONG_MAX) { - err_setstr(OverflowError, "float too large to convert"); - return NULL; - } - return newintobject((long)x); -} - -static object * -complex_long(v) - object *v; -{ - double x = ((complexobject *)v)->cval.real; - return dnewlongobject(x); -} - -static object * -complex_float(v) - object *v; -{ - double x = ((complexobject *)v)->cval.real; - return newfloatobject(x); -} - - -static object * -complex_new(self, args) - object *self; - object *args; -{ - complex cval; - - cval.imag = 0.; - if (!PyArg_ParseTuple(args, "d|d", &cval.real, &cval.imag)) - return NULL; - return newcomplexobject(cval); -} - -static object * -complex_conjugate(self) - object *self; -{ - complex c = ((complexobject *)self)->cval; - c.imag = -c.imag; - return newcomplexobject(c); -} - -static PyMethodDef complex_methods[] = { - {"conjugate", (PyCFunction)complex_conjugate, 1}, - {NULL, NULL} /* sentinel */ -}; - - -static object * -complex_getattr(self, name) - complexobject *self; - char *name; -{ - complex cval; - if (strcmp(name, "real") == 0) - return (object *)newfloatobject(self->cval.real); - else if (strcmp(name, "imag") == 0) - return (object *)newfloatobject(self->cval.imag); - else if (strcmp(name, "conj") == 0) { - cval.real = self->cval.real; - cval.imag = -self->cval.imag; - return (object *)newcomplexobject(cval); - } - return findmethod(complex_methods, (object *)self, name); -} - -static number_methods complex_as_number = { - (binaryfunc)complex_add, /*nb_add*/ - (binaryfunc)complex_sub, /*nb_subtract*/ - (binaryfunc)complex_mul, /*nb_multiply*/ - (binaryfunc)complex_div, /*nb_divide*/ - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - (ternaryfunc)complex_pow, /*nb_power*/ - (unaryfunc)complex_neg, /*nb_negative*/ - (unaryfunc)complex_pos, /*nb_positive*/ - (unaryfunc)complex_abs, /*nb_absolute*/ - (inquiry)complex_nonzero, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - (coercion)complex_coerce, /*nb_coerce*/ - (unaryfunc)complex_int, /*nb_int*/ - (unaryfunc)complex_long, /*nb_long*/ - (unaryfunc)complex_float, /*nb_float*/ - 0, /*nb_oct*/ - 0, /*nb_hex*/ -}; - -typeobject Complextype = { - OB_HEAD_INIT(&Typetype) - 0, - "complex", - sizeof(complexobject), - 0, - (destructor)complex_dealloc, /*tp_dealloc*/ - (printfunc)complex_print, /*tp_print*/ - (getattrfunc)complex_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)complex_compare, /*tp_compare*/ - (reprfunc)complex_repr, /*tp_repr*/ - &complex_as_number, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)complex_hash, /*tp_hash*/ -}; - -#endif diff --git a/Objects/dictobject.c b/Objects/dictobject.c deleted file mode 100644 index 42e68d8007..0000000000 --- a/Objects/dictobject.c +++ /dev/null @@ -1,845 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Mapping object implementation; using a hash table */ - -/* This file should really be called "dictobject.c", since "mapping" - is the generic name for objects with an unorderred arbitrary key - set (just like lists are sequences), but since it improves (and was - originally derived from) a file by that name I had to change its - name. For the user these objects are still called "dictionaries". */ - -#include "allobjects.h" -#include "modsupport.h" - - -/* -Table of primes suitable as keys, in ascending order. -The first line are the largest primes less than some powers of two, -the second line is the largest prime less than 6000, -the third line is a selection from Knuth, Vol. 3, Sec. 6.1, Table 1, -and the next three lines were suggested by Steve Kirsch. -The final value is a sentinel. -*/ -static long primes[] = { - 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2017, 4093, - 5987, - 9551, 15683, 19609, 31397, - 65521L, 131071L, 262139L, 524287L, 1048573L, 2097143L, - 4194301L, 8388593L, 16777213L, 33554393L, 67108859L, - 134217689L, 268435399L, 536870909L, 1073741789L, - 0 -}; - -/* Object used as dummy key to fill deleted entries */ -static object *dummy; /* Initialized by first call to newmappingobject() */ - -/* -Invariant for entries: when in use, de_value is not NULL and de_key is -not NULL and not dummy; when not in use, de_value is NULL and de_key -is either NULL or dummy. A dummy key value cannot be replaced by -NULL, since otherwise other keys may be lost. -*/ -typedef struct { - long me_hash; - object *me_key; - object *me_value; -} mappingentry; - -/* -To ensure the lookup algorithm terminates, the table size must be a -prime number and there must be at least one NULL key in the table. -The value ma_fill is the number of non-NULL keys; ma_used is the number -of non-NULL, non-dummy keys. -To avoid slowing down lookups on a near-full table, we resize the table -when it is more than half filled. -*/ -typedef struct { - OB_HEAD - int ma_fill; - int ma_used; - int ma_size; - mappingentry *ma_table; -} mappingobject; - -object * -newmappingobject() -{ - register mappingobject *mp; - if (dummy == NULL) { /* Auto-initialize dummy */ - dummy = newstringobject("<dummy key>"); - if (dummy == NULL) - return NULL; - } - mp = NEWOBJ(mappingobject, &Mappingtype); - if (mp == NULL) - return NULL; - mp->ma_size = 0; - mp->ma_table = NULL; - mp->ma_fill = 0; - mp->ma_used = 0; - return (object *)mp; -} - -/* -The basic lookup function used by all operations. -This is essentially Algorithm D from Knuth Vol. 3, Sec. 6.4. -Open addressing is preferred over chaining since the link overhead for -chaining would be substantial (100% with typical malloc overhead). - -First a 32-bit hash value, 'sum', is computed from the key string. -The first character is added an extra time shifted by 8 to avoid hashing -single-character keys (often heavily used variables) too close together. -All arithmetic on sum should ignore overflow. - -The initial probe index is then computed as sum mod the table size. -Subsequent probe indices are incr apart (mod table size), where incr -is also derived from sum, with the additional requirement that it is -relative prime to the table size (i.e., 1 <= incr < size, since the size -is a prime number). My choice for incr is somewhat arbitrary. -*/ -static mappingentry *lookmapping PROTO((mappingobject *, object *, long)); -static mappingentry * -lookmapping(mp, key, hash) - register mappingobject *mp; - object *key; - long hash; -{ - register int i, incr; - register unsigned long sum = (unsigned long) hash; - register mappingentry *freeslot = NULL; - /* We must come up with (i, incr) such that 0 <= i < ma_size - and 0 < incr < ma_size and both are a function of hash */ - i = sum % mp->ma_size; - do { - sum = 3*sum + 1; - incr = sum % mp->ma_size; - } while (incr == 0); - for (;;) { - register mappingentry *ep = &mp->ma_table[i]; - if (ep->me_key == NULL) { - if (freeslot != NULL) - return freeslot; - else - return ep; - } - if (ep->me_key == dummy) { - if (freeslot == NULL) - freeslot = ep; - } - else if (ep->me_hash == hash && - cmpobject(ep->me_key, key) == 0) { - return ep; - } - i = (i + incr) % mp->ma_size; - } -} - -/* -Internal routine to insert a new item into the table. -Used both by the internal resize routine and by the public insert routine. -Eats a reference to key and one to value. -*/ -static void insertmapping PROTO((mappingobject *, object *, long, object *)); -static void -insertmapping(mp, key, hash, value) - register mappingobject *mp; - object *key; - long hash; - object *value; -{ - object *old_value; - register mappingentry *ep; - ep = lookmapping(mp, key, hash); - if (ep->me_value != NULL) { - old_value = ep->me_value; - ep->me_value = value; - DECREF(old_value); /* which **CAN** re-enter */ - DECREF(key); - } - else { - if (ep->me_key == NULL) - mp->ma_fill++; - else - DECREF(ep->me_key); - ep->me_key = key; - ep->me_hash = hash; - ep->me_value = value; - mp->ma_used++; - } -} - -/* -Restructure the table by allocating a new table and reinserting all -items again. When entries have been deleted, the new table may -actually be smaller than the old one. -*/ -static int mappingresize PROTO((mappingobject *)); -static int -mappingresize(mp) - mappingobject *mp; -{ - register int oldsize = mp->ma_size; - register int newsize; - register mappingentry *oldtable = mp->ma_table; - register mappingentry *newtable; - register mappingentry *ep; - register int i; - newsize = mp->ma_size; - for (i = 0; ; i++) { - if (primes[i] <= 0) { - /* Ran out of primes */ - err_nomem(); - return -1; - } - if (primes[i] > mp->ma_used*2) { - newsize = primes[i]; - if (newsize != primes[i]) { - /* Integer truncation */ - err_nomem(); - return -1; - } - break; - } - } - newtable = (mappingentry *) calloc(sizeof(mappingentry), newsize); - if (newtable == NULL) { - err_nomem(); - return -1; - } - mp->ma_size = newsize; - mp->ma_table = newtable; - mp->ma_fill = 0; - mp->ma_used = 0; - - /* Make two passes, so we can avoid decrefs - (and possible side effects) till the table is copied */ - for (i = 0, ep = oldtable; i < oldsize; i++, ep++) { - if (ep->me_value != NULL) - insertmapping(mp,ep->me_key,ep->me_hash,ep->me_value); - } - for (i = 0, ep = oldtable; i < oldsize; i++, ep++) { - if (ep->me_value == NULL) - XDECREF(ep->me_key); - } - - XDEL(oldtable); - return 0; -} - -object * -mappinglookup(op, key) - object *op; - object *key; -{ - long hash; - if (!is_mappingobject(op)) { - err_badcall(); - return NULL; - } - if (((mappingobject *)op)->ma_table == NULL) - return NULL; -#ifdef CACHE_HASH - if (!is_stringobject(key) || (hash = ((stringobject *) key)->ob_shash) == -1) -#endif - hash = hashobject(key); - if (hash == -1) - return NULL; - return lookmapping((mappingobject *)op, key, hash) -> me_value; -} - -int -mappinginsert(op, key, value) - register object *op; - object *key; - object *value; -{ - register mappingobject *mp; - register long hash; - if (!is_mappingobject(op)) { - err_badcall(); - return -1; - } -#ifdef CACHE_HASH - if (!is_stringobject(key) || (hash = ((stringobject *) key)->ob_shash) == -1) -#endif - hash = hashobject(key); - if (hash == -1) - return -1; - mp = (mappingobject *)op; - /* if fill >= 2/3 size, resize */ - if (mp->ma_fill*3 >= mp->ma_size*2) { - if (mappingresize(mp) != 0) { - if (mp->ma_fill+1 > mp->ma_size) - return -1; - } - } - INCREF(value); - INCREF(key); - insertmapping(mp, key, hash, value); - return 0; -} - -int -mappingremove(op, key) - object *op; - object *key; -{ - register mappingobject *mp; - register long hash; - register mappingentry *ep; - object *old_value, *old_key; - - if (!is_mappingobject(op)) { - err_badcall(); - return -1; - } -#ifdef CACHE_HASH - if (!is_stringobject(key) || (hash = ((stringobject *) key)->ob_shash) == -1) -#endif - hash = hashobject(key); - if (hash == -1) - return -1; - mp = (mappingobject *)op; - if (((mappingobject *)op)->ma_table == NULL) - goto empty; - ep = lookmapping(mp, key, hash); - if (ep->me_value == NULL) { - empty: - err_setval(KeyError, key); - return -1; - } - old_key = ep->me_key; - INCREF(dummy); - ep->me_key = dummy; - old_value = ep->me_value; - ep->me_value = NULL; - mp->ma_used--; - DECREF(old_value); - DECREF(old_key); - return 0; -} - -void -mappingclear(op) - object *op; -{ - int i, n; - register mappingentry *table; - mappingobject *mp; - if (!is_mappingobject(op)) - return; - mp = (mappingobject *)op; - table = mp->ma_table; - if (table == NULL) - return; - n = mp->ma_size; - mp->ma_size = mp->ma_used = mp->ma_fill = 0; - mp->ma_table = NULL; - for (i = 0; i < n; i++) { - XDECREF(table[i].me_key); - XDECREF(table[i].me_value); - } - DEL(table); -} - -int -mappinggetnext(op, ppos, pkey, pvalue) - object *op; - int *ppos; - object **pkey; - object **pvalue; -{ - int i; - register mappingobject *mp; - if (!is_dictobject(op)) - return 0; - mp = (mappingobject *)op; - i = *ppos; - if (i < 0) - return 0; - while (i < mp->ma_size && mp->ma_table[i].me_value == NULL) - i++; - *ppos = i+1; - if (i >= mp->ma_size) - return 0; - if (pkey) - *pkey = mp->ma_table[i].me_key; - if (pvalue) - *pvalue = mp->ma_table[i].me_value; - return 1; -} - -/* Methods */ - -static void -mapping_dealloc(mp) - register mappingobject *mp; -{ - register int i; - register mappingentry *ep; - for (i = 0, ep = mp->ma_table; i < mp->ma_size; i++, ep++) { - if (ep->me_key != NULL) - DECREF(ep->me_key); - if (ep->me_value != NULL) - DECREF(ep->me_value); - } - XDEL(mp->ma_table); - DEL(mp); -} - -static int -mapping_print(mp, fp, flags) - register mappingobject *mp; - register FILE *fp; - register int flags; -{ - register int i; - register int any; - register mappingentry *ep; - fprintf(fp, "{"); - any = 0; - for (i = 0, ep = mp->ma_table; i < mp->ma_size; i++, ep++) { - if (ep->me_value != NULL) { - if (any++ > 0) - fprintf(fp, ", "); - if (printobject((object *)ep->me_key, fp, 0) != 0) - return -1; - fprintf(fp, ": "); - if (printobject(ep->me_value, fp, 0) != 0) - return -1; - } - } - fprintf(fp, "}"); - return 0; -} - -static object * -mapping_repr(mp) - mappingobject *mp; -{ - auto object *v; - object *sepa, *colon; - register int i; - register int any; - register mappingentry *ep; - v = newstringobject("{"); - sepa = newstringobject(", "); - colon = newstringobject(": "); - any = 0; - for (i = 0, ep = mp->ma_table; i < mp->ma_size && v; i++, ep++) { - if (ep->me_value != NULL) { - if (any++) - joinstring(&v, sepa); - joinstring_decref(&v, reprobject(ep->me_key)); - joinstring(&v, colon); - joinstring_decref(&v, reprobject(ep->me_value)); - } - } - joinstring_decref(&v, newstringobject("}")); - XDECREF(sepa); - XDECREF(colon); - return v; -} - -static int -mapping_length(mp) - mappingobject *mp; -{ - return mp->ma_used; -} - -static object * -mapping_subscript(mp, key) - mappingobject *mp; - register object *key; -{ - object *v; - long hash; - if (mp->ma_table == NULL) { - err_setval(KeyError, key); - return NULL; - } -#ifdef CACHE_HASH - if (!is_stringobject(key) || (hash = ((stringobject *) key)->ob_shash) == -1) -#endif - hash = hashobject(key); - if (hash == -1) - return NULL; - v = lookmapping(mp, key, hash) -> me_value; - if (v == NULL) - err_setval(KeyError, key); - else - INCREF(v); - return v; -} - -static int -mapping_ass_sub(mp, v, w) - mappingobject *mp; - object *v, *w; -{ - if (w == NULL) - return mappingremove((object *)mp, v); - else - return mappinginsert((object *)mp, v, w); -} - -static mapping_methods mapping_as_mapping = { - (inquiry)mapping_length, /*mp_length*/ - (binaryfunc)mapping_subscript, /*mp_subscript*/ - (objobjargproc)mapping_ass_sub, /*mp_ass_subscript*/ -}; - -static object * -mapping_keys(mp, args) - register mappingobject *mp; - object *args; -{ - register object *v; - register int i, j; - if (!getnoarg(args)) - return NULL; - v = newlistobject(mp->ma_used); - if (v == NULL) - return NULL; - for (i = 0, j = 0; i < mp->ma_size; i++) { - if (mp->ma_table[i].me_value != NULL) { - object *key = mp->ma_table[i].me_key; - INCREF(key); - setlistitem(v, j, key); - j++; - } - } - return v; -} - -static object * -mapping_values(mp, args) - register mappingobject *mp; - object *args; -{ - register object *v; - register int i, j; - if (!getnoarg(args)) - return NULL; - v = newlistobject(mp->ma_used); - if (v == NULL) - return NULL; - for (i = 0, j = 0; i < mp->ma_size; i++) { - if (mp->ma_table[i].me_value != NULL) { - object *value = mp->ma_table[i].me_value; - INCREF(value); - setlistitem(v, j, value); - j++; - } - } - return v; -} - -static object * -mapping_items(mp, args) - register mappingobject *mp; - object *args; -{ - register object *v; - register int i, j; - if (!getnoarg(args)) - return NULL; - v = newlistobject(mp->ma_used); - if (v == NULL) - return NULL; - for (i = 0, j = 0; i < mp->ma_size; i++) { - if (mp->ma_table[i].me_value != NULL) { - object *key = mp->ma_table[i].me_key; - object *value = mp->ma_table[i].me_value; - object *item = newtupleobject(2); - if (item == NULL) { - DECREF(v); - return NULL; - } - INCREF(key); - settupleitem(item, 0, key); - INCREF(value); - settupleitem(item, 1, value); - setlistitem(v, j, item); - j++; - } - } - return v; -} - -int -getmappingsize(mp) - object *mp; -{ - if (mp == NULL || !is_mappingobject(mp)) { - err_badcall(); - return 0; - } - return ((mappingobject *)mp)->ma_used; -} - -object * -getmappingkeys(mp) - object *mp; -{ - if (mp == NULL || !is_mappingobject(mp)) { - err_badcall(); - return NULL; - } - return mapping_keys((mappingobject *)mp, (object *)NULL); -} - -object * -getmappingvalues(mp) - object *mp; -{ - if (mp == NULL || !is_mappingobject(mp)) { - err_badcall(); - return NULL; - } - return mapping_values((mappingobject *)mp, (object *)NULL); -} - -object * -getmappingitems(mp) - object *mp; -{ - if (mp == NULL || !is_mappingobject(mp)) { - err_badcall(); - return NULL; - } - return mapping_items((mappingobject *)mp, (object *)NULL); -} - -static int -mapping_compare(a, b) - mappingobject *a, *b; -{ - object *akeys, *bkeys; - int i, n, res; - if (a == b) - return 0; - if (a->ma_used == 0) { - if (b->ma_used != 0) - return -1; - else - return 0; - } - else { - if (b->ma_used == 0) - return 1; - } - akeys = mapping_keys(a, (object *)NULL); - bkeys = mapping_keys(b, (object *)NULL); - if (akeys == NULL || bkeys == NULL) { - /* Oops, out of memory -- what to do? */ - /* For now, sort on address! */ - XDECREF(akeys); - XDECREF(bkeys); - if (a < b) - return -1; - else - return 1; - } - sortlist(akeys); - sortlist(bkeys); - n = a->ma_used < b->ma_used ? a->ma_used : b->ma_used; /* smallest */ - res = 0; - for (i = 0; i < n; i++) { - object *akey, *bkey, *aval, *bval; - long ahash, bhash; - akey = getlistitem(akeys, i); - bkey = getlistitem(bkeys, i); - res = cmpobject(akey, bkey); - if (res != 0) - break; -#ifdef CACHE_HASH - if (!is_stringobject(akey) || (ahash = ((stringobject *) akey)->ob_shash) == -1) -#endif - ahash = hashobject(akey); - if (ahash == -1) - err_clear(); /* Don't want errors here */ -#ifdef CACHE_HASH - if (!is_stringobject(bkey) || (bhash = ((stringobject *) bkey)->ob_shash) == -1) -#endif - bhash = hashobject(bkey); - if (bhash == -1) - err_clear(); /* Don't want errors here */ - aval = lookmapping(a, akey, ahash) -> me_value; - bval = lookmapping(b, bkey, bhash) -> me_value; - res = cmpobject(aval, bval); - if (res != 0) - break; - } - if (res == 0) { - if (a->ma_used < b->ma_used) - res = -1; - else if (a->ma_used > b->ma_used) - res = 1; - } - DECREF(akeys); - DECREF(bkeys); - return res; -} - -static object * -mapping_has_key(mp, args) - register mappingobject *mp; - object *args; -{ - object *key; - long hash; - register long ok; - if (!getargs(args, "O", &key)) - return NULL; -#ifdef CACHE_HASH - if (!is_stringobject(key) || (hash = ((stringobject *) key)->ob_shash) == -1) -#endif - hash = hashobject(key); - if (hash == -1) - return NULL; - ok = mp->ma_size != 0 && lookmapping(mp, key, hash)->me_value != NULL; - return newintobject(ok); -} - -static struct methodlist mapp_methods[] = { - {"has_key", (method)mapping_has_key}, - {"items", (method)mapping_items}, - {"keys", (method)mapping_keys}, - {"values", (method)mapping_values}, - {NULL, NULL} /* sentinel */ -}; - -static object * -mapping_getattr(mp, name) - mappingobject *mp; - char *name; -{ - return findmethod(mapp_methods, (object *)mp, name); -} - -typeobject Mappingtype = { - OB_HEAD_INIT(&Typetype) - 0, - "dictionary", - sizeof(mappingobject), - 0, - (destructor)mapping_dealloc, /*tp_dealloc*/ - (printfunc)mapping_print, /*tp_print*/ - (getattrfunc)mapping_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)mapping_compare, /*tp_compare*/ - (reprfunc)mapping_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - &mapping_as_mapping, /*tp_as_mapping*/ -}; - -/* For backward compatibility with old dictionary interface */ - -static object *last_name_object; -static char *last_name_char; /* NULL or == getstringvalue(last_name_object) */ - -object * -getattro(v, name) - object *v; - object *name; -{ - if (name != last_name_object) { - XDECREF(last_name_object); - INCREF(name); - last_name_object = name; - last_name_char = getstringvalue(name); - } - return getattr(v, last_name_char); -} - -int -setattro(v, name, value) - object *v; - object *name; - object *value; -{ - if (name != last_name_object) { - XDECREF(last_name_object); - INCREF(name); - last_name_object = name; - last_name_char = getstringvalue(name); - } - return setattr(v, last_name_char, value); -} - -object * -dictlookup(v, key) - object *v; - char *key; -{ - if (key != last_name_char) { - XDECREF(last_name_object); - last_name_object = newstringobject(key); - if (last_name_object == NULL) { - last_name_char = NULL; - return NULL; - } - last_name_char = getstringvalue(last_name_object); - } - return mappinglookup(v, last_name_object); -} - -int -dictinsert(v, key, item) - object *v; - char *key; - object *item; -{ - if (key != last_name_char) { - XDECREF(last_name_object); - last_name_object = newstringobject(key); - if (last_name_object == NULL) { - last_name_char = NULL; - return -1; - } - last_name_char = getstringvalue(last_name_object); - } - return mappinginsert(v, last_name_object, item); -} - -int -dictremove(v, key) - object *v; - char *key; -{ - if (key != last_name_char) { - XDECREF(last_name_object); - last_name_object = newstringobject(key); - if (last_name_object == NULL) { - last_name_char = NULL; - return -1; - } - last_name_char = getstringvalue(last_name_object); - } - return mappingremove(v, last_name_object); -} diff --git a/Objects/fileobject.c b/Objects/fileobject.c deleted file mode 100644 index 0a03c475d4..0000000000 --- a/Objects/fileobject.c +++ /dev/null @@ -1,846 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* File object implementation */ - -#include "allobjects.h" -#include "modsupport.h" -#include "structmember.h" -#include "ceval.h" - -#ifdef THINK_C -#define HAVE_FOPENRF -#endif -#ifdef __MWERKS__ -/* Mwerks fopen() doesn't always set errno */ -#define NO_FOPEN_ERRNO -#endif - -#define BUF(v) GETSTRINGVALUE((stringobject *)v) - -#include <errno.h> - -typedef struct { - OB_HEAD - FILE *f_fp; - object *f_name; - object *f_mode; - int (*f_close) PROTO((FILE *)); - int f_softspace; /* Flag used by 'print' command */ -} fileobject; - -FILE * -getfilefile(f) - object *f; -{ - if (f == NULL || !is_fileobject(f)) - return NULL; - else - return ((fileobject *)f)->f_fp; -} - -object * -getfilename(f) - object *f; -{ - if (f == NULL || !is_fileobject(f)) - return NULL; - else - return ((fileobject *)f)->f_name; -} - -object * -newopenfileobject(fp, name, mode, close) - FILE *fp; - char *name; - char *mode; - int (*close) FPROTO((FILE *)); -{ - fileobject *f = NEWOBJ(fileobject, &Filetype); - if (f == NULL) - return NULL; - f->f_fp = NULL; - f->f_name = newstringobject(name); - f->f_mode = newstringobject(mode); - f->f_close = close; - f->f_softspace = 0; - if (f->f_name == NULL || f->f_mode == NULL) { - DECREF(f); - return NULL; - } - f->f_fp = fp; - return (object *) f; -} - -object * -newfileobject(name, mode) - char *name, *mode; -{ - extern int fclose PROTO((FILE *)); - fileobject *f; - f = (fileobject *) newopenfileobject((FILE *)NULL, name, mode, fclose); - if (f == NULL) - return NULL; -#ifdef HAVE_FOPENRF - if (*mode == '*') { - FILE *fopenRF(); - f->f_fp = fopenRF(name, mode+1); - } - else -#endif - { - BGN_SAVE - f->f_fp = fopen(name, mode); - END_SAVE - } - if (f->f_fp == NULL) { -#ifdef NO_FOPEN_ERRNO - if ( errno == 0 ) { - err_setstr(IOError, "Cannot open file"); - DECREF(f); - return NULL; - } -#endif - err_errno(IOError); - DECREF(f); - return NULL; - } - return (object *)f; -} - -void -setfilebufsize(f, bufsize) - object *f; - int bufsize; -{ - if (bufsize >= 0) { -#ifdef HAVE_SETVBUF - int type; - switch (bufsize) { - case 0: - type = _IONBF; - break; - case 1: - type = _IOLBF; - bufsize = BUFSIZ; - break; - default: - type = _IOFBF; - } - setvbuf(((fileobject *)f)->f_fp, (char *)NULL, type, bufsize); -#endif /* HAVE_SETVBUF */ - } -} - -static object * -err_closed() -{ - err_setstr(ValueError, "I/O operation on closed file"); - return NULL; -} - -/* Methods */ - -static void -file_dealloc(f) - fileobject *f; -{ - if (f->f_fp != NULL && f->f_close != NULL) { - BGN_SAVE - (*f->f_close)(f->f_fp); - END_SAVE - } - if (f->f_name != NULL) - DECREF(f->f_name); - if (f->f_mode != NULL) - DECREF(f->f_mode); - free((char *)f); -} - -static object * -file_repr(f) - fileobject *f; -{ - char buf[300]; - sprintf(buf, "<%s file '%.256s', mode '%.10s' at %lx>", - f->f_fp == NULL ? "closed" : "open", - getstringvalue(f->f_name), - getstringvalue(f->f_mode), - (long)f); - return newstringobject(buf); -} - -static object * -file_close(f, args) - fileobject *f; - object *args; -{ - int sts = 0; - if (!getnoarg(args)) - return NULL; - if (f->f_fp != NULL) { - if (f->f_close != NULL) { - BGN_SAVE - errno = 0; - sts = (*f->f_close)(f->f_fp); - END_SAVE - } - f->f_fp = NULL; - } - if (sts == EOF) - return err_errno(IOError); - if (sts != 0) - return newintobject((long)sts); - INCREF(None); - return None; -} - -static object * -file_seek(f, args) - fileobject *f; - object *args; -{ - long offset; - int whence; - int ret; - - if (f->f_fp == NULL) - return err_closed(); - whence = 0; - if (!getargs(args, "l", &offset)) { - err_clear(); - if (!getargs(args, "(li)", &offset, &whence)) - return NULL; - } - BGN_SAVE - errno = 0; - ret = fseek(f->f_fp, offset, whence); - END_SAVE - if (ret != 0) { - err_errno(IOError); - clearerr(f->f_fp); - return NULL; - } - INCREF(None); - return None; -} - -#ifdef HAVE_FTRUNCATE -static object * -file_truncate(f, args) - fileobject *f; - object *args; -{ - long newsize; - int ret; - - if (f->f_fp == NULL) - return err_closed(); - if (!getargs(args, "l", &newsize)) { - err_clear(); - if (!getnoarg(args)) - return NULL; - BGN_SAVE - errno = 0; - newsize = ftell(f->f_fp); /* default to current position*/ - END_SAVE - if (newsize == -1L) { - err_errno(IOError); - clearerr(f->f_fp); - return NULL; - } - } - BGN_SAVE - errno = 0; - ret = fflush(f->f_fp); - END_SAVE - if (ret == 0) { - BGN_SAVE - errno = 0; - ret = ftruncate(fileno(f->f_fp), newsize); - END_SAVE - } - if (ret != 0) { - err_errno(IOError); - clearerr(f->f_fp); - return NULL; - } - INCREF(None); - return None; -} -#endif /* HAVE_FTRUNCATE */ - -static object * -file_tell(f, args) - fileobject *f; - object *args; -{ - long offset; - if (f->f_fp == NULL) - return err_closed(); - if (!getnoarg(args)) - return NULL; - BGN_SAVE - errno = 0; - offset = ftell(f->f_fp); - END_SAVE - if (offset == -1L) { - err_errno(IOError); - clearerr(f->f_fp); - return NULL; - } - return newintobject(offset); -} - -static object * -file_fileno(f, args) - fileobject *f; - object *args; -{ - if (f->f_fp == NULL) - return err_closed(); - if (!getnoarg(args)) - return NULL; - return newintobject((long) fileno(f->f_fp)); -} - -static object * -file_flush(f, args) - fileobject *f; - object *args; -{ - int res; - - if (f->f_fp == NULL) - return err_closed(); - if (!getnoarg(args)) - return NULL; - BGN_SAVE - errno = 0; - res = fflush(f->f_fp); - END_SAVE - if (res != 0) { - err_errno(IOError); - clearerr(f->f_fp); - return NULL; - } - INCREF(None); - return None; -} - -static object * -file_isatty(f, args) - fileobject *f; - object *args; -{ - long res; - if (f->f_fp == NULL) - return err_closed(); - if (!getnoarg(args)) - return NULL; - BGN_SAVE - res = isatty((int)fileno(f->f_fp)); - END_SAVE - return newintobject(res); -} - -static object * -file_read(f, args) - fileobject *f; - object *args; -{ - int n, n1, n2, n3; - object *v; - - if (f->f_fp == NULL) - return err_closed(); - if (args == NULL) - n = -1; - else { - if (!getargs(args, "i", &n)) - return NULL; - } - n2 = n >= 0 ? n : BUFSIZ; - v = newsizedstringobject((char *)NULL, n2); - if (v == NULL) - return NULL; - n1 = 0; - BGN_SAVE - for (;;) { - n3 = fread(BUF(v)+n1, 1, n2-n1, f->f_fp); - /* XXX Error check? */ - if (n3 == 0) - break; - n1 += n3; - if (n1 == n) - break; - if (n < 0) { - n2 = n1 + BUFSIZ; - RET_SAVE - if (resizestring(&v, n2) < 0) - return NULL; - RES_SAVE - } - } - END_SAVE - if (n1 != n2) - resizestring(&v, n1); - return v; -} - -/* Internal routine to get a line. - Size argument interpretation: - > 0: max length; - = 0: read arbitrary line; - < 0: strip trailing '\n', raise EOFError if EOF reached immediately -*/ - -static object * -getline(f, n) - fileobject *f; - int n; -{ - register FILE *fp; - register int c; - register char *buf, *end; - int n1, n2; - object *v; - - fp = f->f_fp; - n2 = n > 0 ? n : 100; - v = newsizedstringobject((char *)NULL, n2); - if (v == NULL) - return NULL; - buf = BUF(v); - end = buf + n2; - - BGN_SAVE - for (;;) { - if ((c = getc(fp)) == EOF) { - clearerr(fp); - if (sigcheck()) { - RET_SAVE - DECREF(v); - return NULL; - } - if (n < 0 && buf == BUF(v)) { - RET_SAVE - DECREF(v); - err_setstr(EOFError, - "EOF when reading a line"); - return NULL; - } - break; - } - if ((*buf++ = c) == '\n') { - if (n < 0) - buf--; - break; - } - if (buf == end) { - if (n > 0) - break; - n1 = n2; - n2 += 1000; - RET_SAVE - if (resizestring(&v, n2) < 0) - return NULL; - RES_SAVE - buf = BUF(v) + n1; - end = BUF(v) + n2; - } - } - END_SAVE - - n1 = buf - BUF(v); - if (n1 != n2) - resizestring(&v, n1); - return v; -} - -/* External C interface */ - -object * -filegetline(f, n) - object *f; - int n; -{ - if (f == NULL) { - err_badcall(); - return NULL; - } - if (!is_fileobject(f)) { - object *reader; - object *args; - object *result; - reader = getattr(f, "readline"); - if (reader == NULL) - return NULL; - if (n <= 0) - args = mkvalue("()"); - else - args = mkvalue("(i)", n); - if (args == NULL) { - DECREF(reader); - return NULL; - } - result = call_object(reader, args); - DECREF(reader); - DECREF(args); - if (result != NULL && !is_stringobject(result)) { - DECREF(result); - result = NULL; - err_setstr(TypeError, - "object.readline() returned non-string"); - } - if (n < 0 && result != NULL) { - char *s = getstringvalue(result); - int len = getstringsize(result); - if (len == 0) { - DECREF(result); - result = NULL; - err_setstr(EOFError, - "EOF when reading a line"); - } - else if (s[len-1] == '\n') { - if (result->ob_refcnt == 1) - resizestring(&result, len-1); - else { - object *v; - v = newsizedstringobject(s, len-1); - DECREF(result); - result = v; - } - } - } - return result; - } - if (((fileobject*)f)->f_fp == NULL) - return err_closed(); - return getline((fileobject *)f, n); -} - -/* Python method */ - -static object * -file_readline(f, args) - fileobject *f; - object *args; -{ - int n; - - if (f->f_fp == NULL) - return err_closed(); - if (args == NULL) - n = 0; /* Unlimited */ - else { - if (!getintarg(args, &n)) - return NULL; - if (n == 0) - return newstringobject(""); - if (n < 0) - n = 0; - } - - return getline(f, n); -} - -static object * -file_readlines(f, args) - fileobject *f; - object *args; -{ - object *list; - object *line; - - if (f->f_fp == NULL) - return err_closed(); - if (!getnoarg(args)) - return NULL; - if ((list = newlistobject(0)) == NULL) - return NULL; - for (;;) { - line = getline(f, 0); - if (line != NULL && getstringsize(line) == 0) { - DECREF(line); - break; - } - if (line == NULL || addlistitem(list, line) != 0) { - DECREF(list); - XDECREF(line); - return NULL; - } - DECREF(line); - } - return list; -} - -static object * -file_write(f, args) - fileobject *f; - object *args; -{ - char *s; - int n, n2; - if (f->f_fp == NULL) - return err_closed(); - if (!getargs(args, "s#", &s, &n)) - return NULL; - f->f_softspace = 0; - BGN_SAVE - errno = 0; - n2 = fwrite(s, 1, n, f->f_fp); - END_SAVE - if (n2 != n) { - err_errno(IOError); - clearerr(f->f_fp); - return NULL; - } - INCREF(None); - return None; -} - -static object * -file_writelines(f, args) - fileobject *f; - object *args; -{ - int i, n; - if (f->f_fp == NULL) - return err_closed(); - if (args == NULL || !is_listobject(args)) { - err_setstr(TypeError, - "writelines() requires list of strings"); - return NULL; - } - n = getlistsize(args); - f->f_softspace = 0; - BGN_SAVE - errno = 0; - for (i = 0; i < n; i++) { - object *line = getlistitem(args, i); - int len; - int nwritten; - if (!is_stringobject(line)) { - RET_SAVE - err_setstr(TypeError, - "writelines() requires list of strings"); - return NULL; - } - len = getstringsize(line); - nwritten = fwrite(getstringvalue(line), 1, len, f->f_fp); - if (nwritten != len) { - RET_SAVE - err_errno(IOError); - clearerr(f->f_fp); - return NULL; - } - } - END_SAVE - INCREF(None); - return None; -} - -static struct methodlist file_methods[] = { - {"close", (method)file_close, 0}, - {"flush", (method)file_flush, 0}, - {"fileno", (method)file_fileno, 0}, - {"isatty", (method)file_isatty, 0}, - {"read", (method)file_read, 0}, - {"readline", (method)file_readline, 0}, - {"readlines", (method)file_readlines, 0}, - {"seek", (method)file_seek, 0}, -#ifdef HAVE_FTRUNCATE - {"truncate", (method)file_truncate, 0}, -#endif - {"tell", (method)file_tell, 0}, - {"write", (method)file_write, 0}, - {"writelines", (method)file_writelines, 0}, - {NULL, NULL} /* sentinel */ -}; - -#define OFF(x) offsetof(fileobject, x) - -static struct memberlist file_memberlist[] = { - {"softspace", T_INT, OFF(f_softspace)}, - {"mode", T_OBJECT, OFF(f_mode), RO}, - {"name", T_OBJECT, OFF(f_name), RO}, - /* getattr(f, "closed") is implemented without this table */ - {"closed", T_INT, 0, RO}, - {NULL} /* Sentinel */ -}; - -static object * -file_getattr(f, name) - fileobject *f; - char *name; -{ - object *res; - - res = findmethod(file_methods, (object *)f, name); - if (res != NULL) - return res; - err_clear(); - if (strcmp(name, "closed") == 0) - return newintobject((long)(f->f_fp == 0)); - return getmember((char *)f, file_memberlist, name); -} - -static int -file_setattr(f, name, v) - fileobject *f; - char *name; - object *v; -{ - if (v == NULL) { - err_setstr(AttributeError, "can't delete file attributes"); - return -1; - } - return setmember((char *)f, file_memberlist, name, v); -} - -typeobject Filetype = { - OB_HEAD_INIT(&Typetype) - 0, - "file", - sizeof(fileobject), - 0, - (destructor)file_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)file_getattr, /*tp_getattr*/ - (setattrfunc)file_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - (reprfunc)file_repr, /*tp_repr*/ -}; - -/* Interface for the 'soft space' between print items. */ - -int -softspace(f, newflag) - object *f; - int newflag; -{ - int oldflag = 0; - if (f == NULL) { - /* Do nothing */ - } - else if (is_fileobject(f)) { - oldflag = ((fileobject *)f)->f_softspace; - ((fileobject *)f)->f_softspace = newflag; - } - else { - object *v; - v = getattr(f, "softspace"); - if (v == NULL) - err_clear(); - else { - if (is_intobject(v)) - oldflag = getintvalue(v); - DECREF(v); - } - v = newintobject((long)newflag); - if (v == NULL) - err_clear(); - else { - if (setattr(f, "softspace", v) != 0) - err_clear(); - DECREF(v); - } - } - return oldflag; -} - -/* Interfaces to write objects/strings to file-like objects */ - -int -writeobject(v, f, flags) - object *v; - object *f; - int flags; -{ - object *writer, *value, *args, *result; - if (f == NULL) { - err_setstr(TypeError, "writeobject with NULL file"); - return -1; - } - else if (is_fileobject(f)) { - FILE *fp = getfilefile(f); - if (fp == NULL) { - err_closed(); - return -1; - } - return printobject(v, fp, flags); - } - writer = getattr(f, "write"); - if (writer == NULL) - return -1; - if (flags & PRINT_RAW) - value = strobject(v); - else - value = reprobject(v); - if (value == NULL) { - DECREF(writer); - return -1; - } - args = mkvalue("(O)", value); - if (value == NULL) { - DECREF(value); - DECREF(writer); - return -1; - } - result = call_object(writer, args); - DECREF(args); - DECREF(value); - DECREF(writer); - if (result == NULL) - return -1; - DECREF(result); - return 0; -} - -void -writestring(s, f) - char *s; - object *f; -{ - if (f == NULL) { - /* Do nothing */ - } - else if (is_fileobject(f)) { - FILE *fp = getfilefile(f); - if (fp != NULL) - fputs(s, fp); - } - else if (!err_occurred()) { - object *v = newstringobject(s); - if (v == NULL) { - err_clear(); - } - else { - if (writeobject(v, f, PRINT_RAW) != 0) - err_clear(); - DECREF(v); - } - } -} diff --git a/Objects/floatobject.c b/Objects/floatobject.c deleted file mode 100644 index f37a9bd8dd..0000000000 --- a/Objects/floatobject.c +++ /dev/null @@ -1,526 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Float object implementation */ - -/* XXX There should be overflow checks here, but it's hard to check - for any kind of float exception without losing portability. */ - -#include "allobjects.h" -#include "modsupport.h" - -#include <errno.h> -#include <ctype.h> -#include "mymath.h" - -#ifdef i860 -/* Cray APP has bogus definition of HUGE_VAL in <math.h> */ -#undef HUGE_VAL -#endif - -#ifdef HUGE_VAL -#define CHECK(x) if (errno != 0) ; \ - else if (-HUGE_VAL <= (x) && (x) <= HUGE_VAL) ; \ - else errno = ERANGE -#else -#define CHECK(x) /* Don't know how to check */ -#endif - -#ifdef HAVE_LIMITS_H -#include <limits.h> -#endif - -#ifndef LONG_MAX -#define LONG_MAX 0X7FFFFFFFL -#endif - -#ifndef LONG_MIN -#define LONG_MIN (-LONG_MAX-1) -#endif - -#ifdef __NeXT__ -#ifdef __sparc__ -/* - * This works around a bug in the NS/Sparc 3.3 pre-release - * limits.h header file. - * 10-Feb-1995 bwarsaw@cnri.reston.va.us - */ -#undef LONG_MIN -#define LONG_MIN (-LONG_MAX-1) -#endif -#endif - -#if !defined(__STDC__) && !defined(macintosh) -extern double fmod PROTO((double, double)); -extern double pow PROTO((double, double)); -#endif - -object * -#ifdef __SC__ -newfloatobject(double fval) -#else -newfloatobject(fval) - double fval; -#endif -{ - /* For efficiency, this code is copied from newobject() */ - register floatobject *op = (floatobject *) malloc(sizeof(floatobject)); - if (op == NULL) - return err_nomem(); - op->ob_type = &Floattype; - op->ob_fval = fval; - NEWREF(op); - return (object *) op; -} - -static void -float_dealloc(op) - object *op; -{ - DEL(op); -} - -double -getfloatvalue(op) - object *op; -{ - number_methods *nb; - floatobject *fo; - double val; - - if (op && is_floatobject(op)) - return GETFLOATVALUE((floatobject*) op); - - if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || - nb->nb_float == NULL) { - err_badarg(); - return -1; - } - - fo = (floatobject*) (*nb->nb_float) (op); - if (fo == NULL) - return -1; - if (!is_floatobject(fo)) { - err_setstr(TypeError, "nb_float should return float object"); - return -1; - } - - val = GETFLOATVALUE(fo); - DECREF(fo); - - return val; -} - -/* Methods */ - -void -float_buf_repr(buf, v) - char *buf; - floatobject *v; -{ - register char *cp; - /* Subroutine for float_repr and float_print. - We want float numbers to be recognizable as such, - i.e., they should contain a decimal point or an exponent. - However, %g may print the number as an integer; - in such cases, we append ".0" to the string. */ - sprintf(buf, "%.12g", v->ob_fval); - cp = buf; - if (*cp == '-') - cp++; - for (; *cp != '\0'; cp++) { - /* Any non-digit means it's not an integer; - this takes care of NAN and INF as well. */ - if (!isdigit(Py_CHARMASK(*cp))) - break; - } - if (*cp == '\0') { - *cp++ = '.'; - *cp++ = '0'; - *cp++ = '\0'; - } -} - -/* ARGSUSED */ -static int -float_print(v, fp, flags) - floatobject *v; - FILE *fp; - int flags; /* Not used but required by interface */ -{ - char buf[100]; - float_buf_repr(buf, v); - fputs(buf, fp); - return 0; -} - -static object * -float_repr(v) - floatobject *v; -{ - char buf[100]; - float_buf_repr(buf, v); - return newstringobject(buf); -} - -static int -float_compare(v, w) - floatobject *v, *w; -{ - double i = v->ob_fval; - double j = w->ob_fval; - return (i < j) ? -1 : (i > j) ? 1 : 0; -} - -static long -float_hash(v) - floatobject *v; -{ - double intpart, fractpart; - int expo; - long x; - /* This is designed so that Python numbers with the same - value hash to the same value, otherwise comparisons - of mapping keys will turn out weird */ - -#ifdef MPW /* MPW C modf expects pointer to extended as second argument */ -{ - extended e; - fractpart = modf(v->ob_fval, &e); - intpart = e; -} -#else - fractpart = modf(v->ob_fval, &intpart); -#endif - - if (fractpart == 0.0) { - if (intpart > 0x7fffffffL || -intpart > 0x7fffffffL) { - /* Convert to long int and use its hash... */ - object *w = dnewlongobject(v->ob_fval); - if (w == NULL) - return -1; - x = hashobject(w); - DECREF(w); - return x; - } - x = (long)intpart; - } - else { - fractpart = frexp(fractpart, &expo); - fractpart = fractpart*2147483648.0; /* 2**31 */ - x = (long) (intpart + fractpart) ^ expo; /* Rather arbitrary */ - } - if (x == -1) - x = -2; - return x; -} - -static object * -float_add(v, w) - floatobject *v; - floatobject *w; -{ - return newfloatobject(v->ob_fval + w->ob_fval); -} - -static object * -float_sub(v, w) - floatobject *v; - floatobject *w; -{ - return newfloatobject(v->ob_fval - w->ob_fval); -} - -static object * -float_mul(v, w) - floatobject *v; - floatobject *w; -{ - return newfloatobject(v->ob_fval * w->ob_fval); -} - -static object * -float_div(v, w) - floatobject *v; - floatobject *w; -{ - if (w->ob_fval == 0) { - err_setstr(ZeroDivisionError, "float division"); - return NULL; - } - return newfloatobject(v->ob_fval / w->ob_fval); -} - -static object * -float_rem(v, w) - floatobject *v; - floatobject *w; -{ - double vx, wx; - double /* div, */ mod; - wx = w->ob_fval; - if (wx == 0.0) { - err_setstr(ZeroDivisionError, "float modulo"); - return NULL; - } - vx = v->ob_fval; - mod = fmod(vx, wx); - /* div = (vx - mod) / wx; */ - if (wx*mod < 0) { - mod += wx; - /* div -= 1.0; */ - } - return newfloatobject(mod); -} - -static object * -float_divmod(v, w) - floatobject *v; - floatobject *w; -{ - double vx, wx; - double div, mod; - wx = w->ob_fval; - if (wx == 0.0) { - err_setstr(ZeroDivisionError, "float divmod()"); - return NULL; - } - vx = v->ob_fval; - mod = fmod(vx, wx); - div = (vx - mod) / wx; - if (wx*mod < 0) { - mod += wx; - div -= 1.0; - } - return mkvalue("(dd)", div, mod); -} - -static double powu(x, n) - double x; - long n; -{ - double r = 1.; - double p = x; - long mask = 1; - while (mask > 0 && n >= mask) { - if (n & mask) - r *= p; - mask <<= 1; - p *= p; - } - return r; -} - -static double powi(x, n) - double x; - long n; -{ - if (n > 10000 || n < -10000) - return pow(x, (double) n); - else if (n > 0) - return powu(x, n); - else - return 1./powu(x, -n); -} - -static object * -float_pow(v, w, z) - floatobject *v; - object *w; - floatobject *z; -{ - double iv, iw, ix; - long intw; - /* XXX Doesn't handle overflows if z!=None yet; it may never do so :( - * The z parameter is really only going to be useful for integers and - * long integers. Maybe something clever with logarithms could be done. - * [AMK] - */ - iv = v->ob_fval; - iw = ((floatobject *)w)->ob_fval; - intw = (long)iw; - if (iw == intw) { - errno = 0; - ix = powi(iv, intw); - } - else { - /* Sort out special cases here instead of relying on pow() */ - if (iw == 0.0) { /* x**0 is 1, even 0**0 */ - if ((object *)z!=None) { - ix=fmod(1.0, z->ob_fval); - if (ix!=0 && z->ob_fval<0) ix+=z->ob_fval; - } - else ix=1.0; - return newfloatobject(ix); - } - if (iv == 0.0) { - if (iw < 0.0) { - err_setstr(ValueError, "0.0 to a negative power"); - return NULL; - } - return newfloatobject(0.0); - } - errno = 0; - ix = pow(iv, iw); - } - CHECK(ix); - if (errno != 0) { - /* XXX could it be another type of error? */ - err_errno(OverflowError); - return NULL; - } - if ((object *)z!=None) { - ix=fmod(ix, z->ob_fval); /* XXX To Be Rewritten */ - if ( ix!=0 && - ((iv<0 && z->ob_fval>0) || (iv>0 && z->ob_fval<0) )) { - ix+=z->ob_fval; - } - } - return newfloatobject(ix); -} - -static object * -float_neg(v) - floatobject *v; -{ - return newfloatobject(-v->ob_fval); -} - -static object * -float_pos(v) - floatobject *v; -{ - INCREF(v); - return (object *)v; -} - -static object * -float_abs(v) - floatobject *v; -{ - if (v->ob_fval < 0) - return float_neg(v); - else - return float_pos(v); -} - -static int -float_nonzero(v) - floatobject *v; -{ - return v->ob_fval != 0.0; -} - -static int -float_coerce(pv, pw) - object **pv; - object **pw; -{ - if (is_intobject(*pw)) { - long x = getintvalue(*pw); - *pw = newfloatobject((double)x); - INCREF(*pv); - return 0; - } - else if (is_longobject(*pw)) { - *pw = newfloatobject(dgetlongvalue(*pw)); - INCREF(*pv); - return 0; - } - return 1; /* Can't do it */ -} - -static object * -float_int(v) - object *v; -{ - double x = getfloatvalue(v); - if (x < 0 ? (x = ceil(x)) < (double)LONG_MIN - : (x = floor(x)) > (double)LONG_MAX) { - err_setstr(OverflowError, "float too large to convert"); - return NULL; - } - return newintobject((long)x); -} - -static object * -float_long(v) - object *v; -{ - double x = getfloatvalue(v); - return dnewlongobject(x); -} - -static object * -float_float(v) - object *v; -{ - INCREF(v); - return v; -} - - -static number_methods float_as_number = { - (binaryfunc)float_add, /*nb_add*/ - (binaryfunc)float_sub, /*nb_subtract*/ - (binaryfunc)float_mul, /*nb_multiply*/ - (binaryfunc)float_div, /*nb_divide*/ - (binaryfunc)float_rem, /*nb_remainder*/ - (binaryfunc)float_divmod, /*nb_divmod*/ - (ternaryfunc)float_pow, /*nb_power*/ - (unaryfunc)float_neg, /*nb_negative*/ - (unaryfunc)float_pos, /*nb_positive*/ - (unaryfunc)float_abs, /*nb_absolute*/ - (inquiry)float_nonzero, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - (coercion)float_coerce, /*nb_coerce*/ - (unaryfunc)float_int, /*nb_int*/ - (unaryfunc)float_long, /*nb_long*/ - (unaryfunc)float_float, /*nb_float*/ - 0, /*nb_oct*/ - 0, /*nb_hex*/ -}; - -typeobject Floattype = { - OB_HEAD_INIT(&Typetype) - 0, - "float", - sizeof(floatobject), - 0, - (destructor)float_dealloc, /*tp_dealloc*/ - (printfunc)float_print, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)float_compare, /*tp_compare*/ - (reprfunc)float_repr, /*tp_repr*/ - &float_as_number, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)float_hash, /*tp_hash*/ -}; diff --git a/Objects/frameobject.c b/Objects/frameobject.c deleted file mode 100644 index 6441855d26..0000000000 --- a/Objects/frameobject.c +++ /dev/null @@ -1,356 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Frame object implementation */ - -#include "allobjects.h" - -#include "compile.h" -#include "frameobject.h" -#include "opcode.h" -#include "structmember.h" -#include "bltinmodule.h" - -#define OFF(x) offsetof(frameobject, x) - -static struct memberlist frame_memberlist[] = { - {"f_back", T_OBJECT, OFF(f_back), RO}, - {"f_code", T_OBJECT, OFF(f_code), RO}, - {"f_builtins", T_OBJECT, OFF(f_builtins),RO}, - {"f_globals", T_OBJECT, OFF(f_globals), RO}, - {"f_locals", T_OBJECT, OFF(f_locals), RO}, - {"f_owner", T_OBJECT, OFF(f_owner), RO}, -#if 0 - {"f_fastlocals",T_OBJECT, OFF(f_fastlocals),RO}, /* XXX Unsafe */ -#endif - {"f_lasti", T_INT, OFF(f_lasti), RO}, - {"f_lineno", T_INT, OFF(f_lineno), RO}, - {"f_restricted",T_INT, OFF(f_restricted),RO}, - {"f_trace", T_OBJECT, OFF(f_trace)}, - {NULL} /* Sentinel */ -}; - -static object * -frame_getattr(f, name) - frameobject *f; - char *name; -{ - if (strcmp(name, "f_locals") == 0) - fast_2_locals(f); - return getmember((char *)f, frame_memberlist, name); -} - -static int -frame_setattr(f, name, value) - frameobject *f; - char *name; - object *value; -{ - return setmember((char *)f, frame_memberlist, name, value); -} - -/* Stack frames are allocated and deallocated at a considerable rate. - In an attempt to improve the speed of function calls, we maintain a - separate free list of stack frames (just like integers are - allocated in a special way -- see intobject.c). When a stack frame - is on the free list, only the following members have a meaning: - ob_type == &Frametype - f_back next item on free list, or NULL - f_nvalues size of f_valuestack - f_valuestack array of (f_nvalues+1) object pointers, or NULL - f_nblocks size of f_blockstack - f_blockstack array of (f_nblocks+1) blocks, or NULL - Note that the value and block stacks are preserved -- this can save - another malloc() call or two (and two free() calls as well!). - Also note that, unlike for integers, each frame object is a - malloc'ed object in its own right -- it is only the actual calls to - malloc() that we are trying to save here, not the administration. - After all, while a typical program may make millions of calls, a - call depth of more than 20 or 30 is probably already exceptional - unless the program contains run-away recursion. I hope. -*/ - -static frameobject *free_list = NULL; - -static void -frame_dealloc(f) - frameobject *f; -{ - XDECREF(f->f_back); - XDECREF(f->f_code); - XDECREF(f->f_builtins); - XDECREF(f->f_globals); - XDECREF(f->f_locals); - XDECREF(f->f_owner); - XDECREF(f->f_fastlocals); - XDECREF(f->f_trace); - f->f_back = free_list; - free_list = f; -} - -typeobject Frametype = { - OB_HEAD_INIT(&Typetype) - 0, - "frame", - sizeof(frameobject), - 0, - (destructor)frame_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)frame_getattr, /*tp_getattr*/ - (setattrfunc)frame_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ -}; - -frameobject * -newframeobject(back, code, globals, locals, owner, nvalues, nblocks) - frameobject *back; - codeobject *code; - object *globals; - object *locals; - object *owner; - int nvalues; - int nblocks; -{ - static object *builtin_object; - frameobject *f; - object *builtins; - if (builtin_object == NULL) { - builtin_object = newstringobject("__builtins__"); - if (builtin_object == NULL) - return NULL; - } - if ((back != NULL && !is_frameobject(back)) || - code == NULL || !is_codeobject(code) || - globals == NULL || !is_dictobject(globals) || - locals != NULL && !is_dictobject(locals) || - nvalues < 0 || nblocks < 0) { - err_badcall(); - return NULL; - } - builtins = mappinglookup(globals, builtin_object); - if (builtins != NULL && is_moduleobject(builtins)) - builtins = getmoduledict(builtins); - if (builtins == NULL || !is_mappingobject(builtins)) { - err_setstr(TypeError, "bad __builtins__ dictionary"); - return NULL; - } - if (free_list == NULL) { - f = NEWOBJ(frameobject, &Frametype); - if (f == NULL) - return NULL; - f->f_nvalues = f->f_nblocks = 0; - f->f_valuestack = NULL; - f->f_blockstack = NULL; - } - else { - f = free_list; - free_list = free_list->f_back; - f->ob_type = &Frametype; - NEWREF(f); - } - XINCREF(back); - f->f_back = back; - INCREF(code); - f->f_code = code; - XINCREF(builtins); - f->f_builtins = builtins; - INCREF(globals); - f->f_globals = globals; - if (code->co_flags & CO_NEWLOCALS) { - if (code->co_flags & CO_OPTIMIZED) - locals = NULL; /* Let fast_2_locals handle it */ - else { - locals = newdictobject(); - if (locals == NULL) { - DECREF(f); - return NULL; - } - } - } - else { - if (locals == NULL) - locals = globals; - INCREF(locals); - } - f->f_locals = locals; - XINCREF(owner); - f->f_owner = owner; - f->f_fastlocals = NULL; - if (code->co_nlocals > 0) { - f->f_fastlocals = newlistobject(code->co_nlocals); - if (f->f_fastlocals == NULL) { - DECREF(f); - return NULL; - } - } - if (nvalues > f->f_nvalues || f->f_valuestack == NULL) { - XDEL(f->f_valuestack); - f->f_valuestack = NEW(object *, nvalues+1); - f->f_nvalues = nvalues; - } - if (nblocks > f->f_nblocks || f->f_blockstack == NULL) { - XDEL(f->f_blockstack); - f->f_blockstack = NEW(block, nblocks+1); - f->f_nblocks = nblocks; - } - f->f_iblock = 0; - f->f_lasti = 0; - f->f_lineno = -1; - f->f_restricted = (builtins != getbuiltindict()); - f->f_trace = NULL; - if (f->f_valuestack == NULL || f->f_blockstack == NULL) { - err_nomem(); - DECREF(f); - return NULL; - } - return f; -} - -object ** -extend_stack(f, level, incr) - frameobject *f; - int level; - int incr; -{ - f->f_nvalues = level + incr + 10; - f->f_valuestack = - (object **) realloc((ANY *)f->f_valuestack, - sizeof(object *) * (f->f_nvalues + 1)); - if (f->f_valuestack == NULL) { - err_nomem(); - return NULL; - } - return f->f_valuestack + level; -} - -/* Block management */ - -void -setup_block(f, type, handler, level) - frameobject *f; - int type; - int handler; - int level; -{ - block *b; - if (f->f_iblock >= f->f_nblocks) - fatal("XXX block stack overflow"); - b = &f->f_blockstack[f->f_iblock++]; - b->b_type = type; - b->b_level = level; - b->b_handler = handler; -} - -block * -pop_block(f) - frameobject *f; -{ - block *b; - if (f->f_iblock <= 0) - fatal("XXX block stack underflow"); - b = &f->f_blockstack[--f->f_iblock]; - return b; -} - -/* Convert between "fast" version of locals and dictionary version */ - -void -fast_2_locals(f) - frameobject *f; -{ - /* Merge f->f_fastlocals into f->f_locals */ - object *locals, *fast, *map; - object *error_type, *error_value, *error_traceback; - int j; - if (f == NULL) - return; - locals = f->f_locals; - if (locals == NULL) { - locals = f->f_locals = newdictobject(); - if (locals == NULL) { - err_clear(); /* Can't report it :-( */ - return; - } - } - fast = f->f_fastlocals; - if (fast == NULL || f->f_code->co_nlocals == 0) - return; - map = f->f_code->co_varnames; - if (!is_dictobject(locals) || !is_listobject(fast) || - !is_tupleobject(map)) - return; - err_fetch(&error_type, &error_value, &error_traceback); - for (j = gettuplesize(map); --j >= 0; ) { - object *key = gettupleitem(map, j); - object *value = getlistitem(fast, j); - if (value == NULL) { - err_clear(); - if (dict2remove(locals, key) != 0) - err_clear(); - } - else { - if (dict2insert(locals, key, value) != 0) - err_clear(); - } - } - err_restore(error_type, error_value, error_traceback); -} - -void -locals_2_fast(f, clear) - frameobject *f; - int clear; -{ - /* Merge f->f_locals into f->f_fastlocals */ - object *locals, *fast, *map; - object *error_type, *error_value, *error_traceback; - int j; - if (f == NULL) - return; - locals = f->f_locals; - fast = f->f_fastlocals; - map = f->f_code->co_varnames; - if (locals == NULL || fast == NULL || f->f_code->co_nlocals == 0) - return; - if (!is_dictobject(locals) || !is_listobject(fast) || - !is_tupleobject(map)) - return; - err_fetch(&error_type, &error_value, &error_traceback); - for (j = gettuplesize(map); --j >= 0; ) { - object *key = gettupleitem(map, j); - object *value = dict2lookup(locals, key); - if (value == NULL) - err_clear(); - else - INCREF(value); - if (value != NULL || clear) - if (setlistitem(fast, j, value) != 0) - err_clear(); - } - err_restore(error_type, error_value, error_traceback); -} diff --git a/Objects/funcobject.c b/Objects/funcobject.c deleted file mode 100644 index f6ec71ee73..0000000000 --- a/Objects/funcobject.c +++ /dev/null @@ -1,211 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Function object implementation */ - -#include "allobjects.h" -#include "compile.h" -#include "structmember.h" - -object * -newfuncobject(code, globals) - object *code; - object *globals; -{ - funcobject *op = NEWOBJ(funcobject, &Functype); - if (op != NULL) { - object *doc; - object *consts; - INCREF(code); - op->func_code = code; - INCREF(globals); - op->func_globals = globals; - op->func_name = ((codeobject *)code)->co_name; - INCREF(op->func_name); - op->func_defaults = NULL; /* No default arguments */ - consts = ((codeobject *)code)->co_consts; - if (gettuplesize(consts) >= 1) { - doc = gettupleitem(consts, 0); - if (!is_stringobject(doc)) - doc = None; - } - else - doc = None; - INCREF(doc); - op->func_doc = doc; - } - return (object *)op; -} - -object * -getfunccode(op) - object *op; -{ - if (!is_funcobject(op)) { - err_badcall(); - return NULL; - } - return ((funcobject *) op) -> func_code; -} - -object * -getfuncglobals(op) - object *op; -{ - if (!is_funcobject(op)) { - err_badcall(); - return NULL; - } - return ((funcobject *) op) -> func_globals; -} - -object * -PyFunction_GetDefaults(op) - object *op; -{ - if (!is_funcobject(op)) { - err_badcall(); - return NULL; - } - return ((funcobject *) op) -> func_defaults; -} - -int -PyFunction_SetDefaults(op, defaults) - object *op; - object *defaults; -{ - if (!is_funcobject(op)) { - err_badcall(); - return -1; - } - if (defaults == None) - defaults = NULL; - else if (is_tupleobject(defaults)) - XINCREF(defaults); - else { - err_setstr(SystemError, "non-tuple default args"); - return -1; - } - XDECREF(((funcobject *) op) -> func_defaults); - ((funcobject *) op) -> func_defaults = defaults; - return 0; -} - -/* Methods */ - -#define OFF(x) offsetof(funcobject, x) - -static struct memberlist func_memberlist[] = { - {"func_code", T_OBJECT, OFF(func_code), READONLY}, - {"func_globals",T_OBJECT, OFF(func_globals), READONLY}, - {"func_name", T_OBJECT, OFF(func_name), READONLY}, - {"__name__", T_OBJECT, OFF(func_name), READONLY}, - {"func_defaults",T_OBJECT, OFF(func_defaults), READONLY}, - {"func_doc", T_OBJECT, OFF(func_doc)}, - {"__doc__", T_OBJECT, OFF(func_doc)}, - {NULL} /* Sentinel */ -}; - -static object * -func_getattr(op, name) - funcobject *op; - char *name; -{ - if (name[0] != '_' && getrestricted()) { - err_setstr(RuntimeError, - "function attributes not accessible in restricted mode"); - return NULL; - } - return getmember((char *)op, func_memberlist, name); -} - -static void -func_dealloc(op) - funcobject *op; -{ - DECREF(op->func_code); - DECREF(op->func_globals); - DECREF(op->func_name); - XDECREF(op->func_defaults); - XDECREF(op->func_doc); - DEL(op); -} - -static object* -func_repr(op) - funcobject *op; -{ - char buf[140]; - if (op->func_name == None) - sprintf(buf, "<anonymous function at %lx>", (long)op); - else - sprintf(buf, "<function %.100s at %lx>", - getstringvalue(op->func_name), - (long)op); - return newstringobject(buf); -} - -static int -func_compare(f, g) - funcobject *f, *g; -{ - int c; - if (f->func_globals != g->func_globals) - return (f->func_globals < g->func_globals) ? -1 : 1; - c = cmpobject(f->func_defaults, g->func_defaults); - if (c != 0) - return c; - return cmpobject(f->func_code, g->func_code); -} - -static long -func_hash(f) - funcobject *f; -{ - long h; - h = hashobject(f->func_code); - if (h == -1) return h; - h = h ^ (long)f->func_globals; - if (h == -1) h = -2; - return h; -} - -typeobject Functype = { - OB_HEAD_INIT(&Typetype) - 0, - "function", - sizeof(funcobject), - 0, - (destructor)func_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)func_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)func_compare, /*tp_compare*/ - (reprfunc)func_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)func_hash, /*tp_hash*/ -}; diff --git a/Objects/intobject.c b/Objects/intobject.c deleted file mode 100644 index ca2961e835..0000000000 --- a/Objects/intobject.c +++ /dev/null @@ -1,779 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Integer object implementation */ - -#include "allobjects.h" -#include "modsupport.h" - -#ifdef HAVE_LIMITS_H -#include <limits.h> -#endif - -#ifndef LONG_MAX -#define LONG_MAX 0X7FFFFFFFL -#endif - -#ifndef LONG_MIN -#define LONG_MIN (-LONG_MAX-1) -#endif - -#ifndef CHAR_BIT -#define CHAR_BIT 8 -#endif - -#ifndef LONG_BIT -#define LONG_BIT (CHAR_BIT * sizeof(long)) -#endif - -long -getmaxint() -{ - return LONG_MAX; /* To initialize sys.maxint */ -} - -/* Standard Booleans */ - -intobject FalseObject = { - OB_HEAD_INIT(&Inttype) - 0 -}; - -intobject TrueObject = { - OB_HEAD_INIT(&Inttype) - 1 -}; - -static object * -err_ovf(msg) - char *msg; -{ - err_setstr(OverflowError, msg); - return NULL; -} - -/* Integers are quite normal objects, to make object handling uniform. - (Using odd pointers to represent integers would save much space - but require extra checks for this special case throughout the code.) - Since, a typical Python program spends much of its time allocating - and deallocating integers, these operations should be very fast. - Therefore we use a dedicated allocation scheme with a much lower - overhead (in space and time) than straight malloc(): a simple - dedicated free list, filled when necessary with memory from malloc(). -*/ - -#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ -#define N_INTOBJECTS (BLOCK_SIZE / sizeof(intobject)) - -static intobject * -fill_free_list() -{ - intobject *p, *q; - p = NEW(intobject, N_INTOBJECTS); - if (p == NULL) - return (intobject *)err_nomem(); - q = p + N_INTOBJECTS; - while (--q > p) - *(intobject **)q = q-1; - *(intobject **)q = NULL; - return p + N_INTOBJECTS - 1; -} - -static intobject *free_list = NULL; -#ifndef NSMALLPOSINTS -#define NSMALLPOSINTS 100 -#endif -#ifndef NSMALLNEGINTS -#define NSMALLNEGINTS 1 -#endif -#if NSMALLNEGINTS + NSMALLPOSINTS > 0 -/* References to small integers are saved in this array so that they - can be shared. - The integers that are saved are those in the range - -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive). -*/ -static intobject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS]; -#endif -#ifdef COUNT_ALLOCS -int quick_int_allocs, quick_neg_int_allocs; -#endif - -object * -newintobject(ival) - long ival; -{ - register intobject *v; -#if NSMALLNEGINTS + NSMALLPOSINTS > 0 - if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS && - (v = small_ints[ival + NSMALLNEGINTS]) != NULL) { - INCREF(v); -#ifdef COUNT_ALLOCS - if (ival >= 0) - quick_int_allocs++; - else - quick_neg_int_allocs++; -#endif - return (object *) v; - } -#endif - if (free_list == NULL) { - if ((free_list = fill_free_list()) == NULL) - return NULL; - } - v = free_list; - free_list = *(intobject **)free_list; - v->ob_type = &Inttype; - v->ob_ival = ival; - NEWREF(v); -#if NSMALLNEGINTS + NSMALLPOSINTS > 0 - if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { - /* save this one for a following allocation */ - INCREF(v); - small_ints[ival + NSMALLNEGINTS] = v; - } -#endif - return (object *) v; -} - -static void -int_dealloc(v) - intobject *v; -{ - *(intobject **)v = free_list; - free_list = v; -} - -long -getintvalue(op) - register object *op; -{ - number_methods *nb; - intobject *io; - long val; - - if (op && is_intobject(op)) - return GETINTVALUE((intobject*) op); - - if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - err_badarg(); - return -1; - } - - io = (intobject*) (*nb->nb_int) (op); - if (io == NULL) - return -1; - if (!is_intobject(io)) { - err_setstr(TypeError, "nb_int should return int object"); - return -1; - } - - val = GETINTVALUE(io); - DECREF(io); - - return val; -} - -/* Methods */ - -/* ARGSUSED */ -static int -int_print(v, fp, flags) - intobject *v; - FILE *fp; - int flags; /* Not used but required by interface */ -{ - fprintf(fp, "%ld", v->ob_ival); - return 0; -} - -static object * -int_repr(v) - intobject *v; -{ - char buf[20]; - sprintf(buf, "%ld", v->ob_ival); - return newstringobject(buf); -} - -static int -int_compare(v, w) - intobject *v, *w; -{ - register long i = v->ob_ival; - register long j = w->ob_ival; - return (i < j) ? -1 : (i > j) ? 1 : 0; -} - -static long -int_hash(v) - intobject *v; -{ - long x = v -> ob_ival; - if (x == -1) - x = -2; - return x; -} - -static object * -int_add(v, w) - intobject *v; - intobject *w; -{ - register long a, b, x; - a = v->ob_ival; - b = w->ob_ival; - x = a + b; - if ((x^a) < 0 && (x^b) < 0) - return err_ovf("integer addition"); - return newintobject(x); -} - -static object * -int_sub(v, w) - intobject *v; - intobject *w; -{ - register long a, b, x; - a = v->ob_ival; - b = w->ob_ival; - x = a - b; - if ((x^a) < 0 && (x^~b) < 0) - return err_ovf("integer subtraction"); - return newintobject(x); -} - -/* -Integer overflow checking used to be done using a double, but on 64 -bit machines (where both long and double are 64 bit) this fails -because the double doesn't have enouvg precision. John Tromp suggests -the following algorithm: - -Suppose again we normalize a and b to be nonnegative. -Let ah and al (bh and bl) be the high and low 32 bits of a (b, resp.). -Now we test ah and bh against zero and get essentially 3 possible outcomes. - -1) both ah and bh > 0 : then report overflow - -2) both ah and bh = 0 : then compute a*b and report overflow if it comes out - negative - -3) ah > 0 and bh = 0 : compute ah*bl and report overflow if it's >= 2^31 - compute al*bl and report overflow if it's negative - add (ah*bl)<<32 to al*bl and report overflow if - it's negative - -In case of no overflow the result is then negated if necessary. - -The majority of cases will be 2), in which case this method is the same as -what I suggested before. If multiplication is expensive enough, then the -other method is faster on case 3), but also more work to program, so I -guess the above is the preferred solution. - -*/ - -static object * -int_mul(v, w) - intobject *v; - intobject *w; -{ - long a, b, ah, bh, x, y; - int s = 1; - - a = v->ob_ival; - b = w->ob_ival; - ah = a >> (LONG_BIT/2); - bh = b >> (LONG_BIT/2); - - /* Quick test for common case: two small positive ints */ - - if (ah == 0 && bh == 0) { - x = a*b; - if (x < 0) - goto bad; - return newintobject(x); - } - - /* Arrange that a >= b >= 0 */ - - if (a < 0) { - a = -a; - if (a < 0) { - /* Largest negative */ - if (b == 0 || b == 1) { - x = a*b; - goto ok; - } - else - goto bad; - } - s = -s; - ah = a >> (LONG_BIT/2); - } - if (b < 0) { - b = -b; - if (b < 0) { - /* Largest negative */ - if (a == 0 || a == 1 && s == 1) { - x = a*b; - goto ok; - } - else - goto bad; - } - s = -s; - bh = b >> (LONG_BIT/2); - } - - /* 1) both ah and bh > 0 : then report overflow */ - - if (ah != 0 && bh != 0) - goto bad; - - /* 2) both ah and bh = 0 : then compute a*b and report - overflow if it comes out negative */ - - if (ah == 0 && bh == 0) { - x = a*b; - if (x < 0) - goto bad; - return newintobject(x*s); - } - - if (a < b) { - /* Swap */ - x = a; - a = b; - b = x; - ah = bh; - /* bh not used beyond this point */ - } - - /* 3) ah > 0 and bh = 0 : compute ah*bl and report overflow if - it's >= 2^31 - compute al*bl and report overflow if it's negative - add (ah*bl)<<32 to al*bl and report overflow if - it's negative - (NB b == bl in this case, and we make a = al) */ - - y = ah*b; - if (y >= (1L << (LONG_BIT/2))) - goto bad; - a &= (1L << (LONG_BIT/2)) - 1; - x = a*b; - if (x < 0) - goto bad; - x += y << LONG_BIT/2; - if (x < 0) - goto bad; - ok: - return newintobject(x * s); - - bad: - return err_ovf("integer multiplication"); -} - -static int -i_divmod(x, y, p_xdivy, p_xmody) - register intobject *x, *y; - long *p_xdivy, *p_xmody; -{ - long xi = x->ob_ival; - long yi = y->ob_ival; - long xdivy, xmody; - - if (yi == 0) { - err_setstr(ZeroDivisionError, "integer division or modulo"); - return -1; - } - if (yi < 0) { - if (xi < 0) - xdivy = -xi / -yi; - else - xdivy = - (xi / -yi); - } - else { - if (xi < 0) - xdivy = - (-xi / yi); - else - xdivy = xi / yi; - } - xmody = xi - xdivy*yi; - if (xmody < 0 && yi > 0 || xmody > 0 && yi < 0) { - xmody += yi; - xdivy -= 1; - } - *p_xdivy = xdivy; - *p_xmody = xmody; - return 0; -} - -static object * -int_div(x, y) - intobject *x; - intobject *y; -{ - long d, m; - if (i_divmod(x, y, &d, &m) < 0) - return NULL; - return newintobject(d); -} - -static object * -int_mod(x, y) - intobject *x; - intobject *y; -{ - long d, m; - if (i_divmod(x, y, &d, &m) < 0) - return NULL; - return newintobject(m); -} - -static object * -int_divmod(x, y) - intobject *x; - intobject *y; -{ - long d, m; - if (i_divmod(x, y, &d, &m) < 0) - return NULL; - return mkvalue("(ll)", d, m); -} - -static object * -int_pow(v, w, z) - intobject *v; - intobject *w; - intobject *z; -{ -#if 1 - register long iv, iw, iz, ix, temp, prev; - int zset = 0; - iv = v->ob_ival; - iw = w->ob_ival; - if (iw < 0) { - err_setstr(ValueError, "integer to the negative power"); - return NULL; - } - if ((object *)z != None) { - iz = z->ob_ival; - zset = 1; - } - /* - * XXX: The original exponentiation code stopped looping - * when temp hit zero; this code will continue onwards - * unnecessarily, but at least it won't cause any errors. - * Hopefully the speed improvement from the fast exponentiation - * will compensate for the slight inefficiency. - * XXX: Better handling of overflows is desperately needed. - */ - temp = iv; - ix = 1; - while (iw > 0) { - prev = ix; /* Save value for overflow check */ - if (iw & 1) { - ix = ix*temp; - if (temp == 0) - break; /* Avoid ix / 0 */ - if (ix / temp != prev) - return err_ovf("integer pow()"); - } - iw >>= 1; /* Shift exponent down by 1 bit */ - if (iw==0) break; - prev = temp; - temp *= temp; /* Square the value of temp */ - if (prev!=0 && temp/prev!=prev) - return err_ovf("integer pow()"); - if (zset) { - /* If we did a multiplication, perform a modulo */ - ix = ix % iz; - temp = temp % iz; - } - } - if (zset) { - object *t1, *t2; - long int div, mod; - t1=newintobject(ix); - t2=newintobject(iz); - if (t1==NULL || t2==NULL || - i_divmod((intobject *)t1, (intobject *)t2, &div, &mod)<0) { - XDECREF(t1); - XDECREF(t2); - return(NULL); - } - DECREF(t1); - DECREF(t2); - ix=mod; - } - return newintobject(ix); -#else - register long iv, iw, ix; - iv = v->ob_ival; - iw = w->ob_ival; - if (iw < 0) { - err_setstr(ValueError, "integer to the negative power"); - return NULL; - } - if ((object *)z != None) { - err_setstr(TypeError, "pow(int, int, int) not yet supported"); - return NULL; - } - ix = 1; - while (--iw >= 0) { - long prev = ix; - ix = ix * iv; - if (iv == 0) - break; /* 0 to some power -- avoid ix / 0 */ - if (ix / iv != prev) - return err_ovf("integer pow()"); - } - return newintobject(ix); -#endif -} - -static object * -int_neg(v) - intobject *v; -{ - register long a, x; - a = v->ob_ival; - x = -a; - if (a < 0 && x < 0) - return err_ovf("integer negation"); - return newintobject(x); -} - -static object * -int_pos(v) - intobject *v; -{ - INCREF(v); - return (object *)v; -} - -static object * -int_abs(v) - intobject *v; -{ - if (v->ob_ival >= 0) - return int_pos(v); - else - return int_neg(v); -} - -static int -int_nonzero(v) - intobject *v; -{ - return v->ob_ival != 0; -} - -static object * -int_invert(v) - intobject *v; -{ - return newintobject(~v->ob_ival); -} - -static object * -int_lshift(v, w) - intobject *v; - intobject *w; -{ - register long a, b; - a = v->ob_ival; - b = w->ob_ival; - if (b < 0) { - err_setstr(ValueError, "negative shift count"); - return NULL; - } - if (a == 0 || b == 0) { - INCREF(v); - return (object *) v; - } - if (b >= LONG_BIT) { - return newintobject(0L); - } - a = (unsigned long)a << b; - return newintobject(a); -} - -static object * -int_rshift(v, w) - intobject *v; - intobject *w; -{ - register long a, b; - a = v->ob_ival; - b = w->ob_ival; - if (b < 0) { - err_setstr(ValueError, "negative shift count"); - return NULL; - } - if (a == 0 || b == 0) { - INCREF(v); - return (object *) v; - } - if (b >= LONG_BIT) { - if (a < 0) - a = -1; - else - a = 0; - } - else { - if (a < 0) - a = ~( ~(unsigned long)a >> b ); - else - a = (unsigned long)a >> b; - } - return newintobject(a); -} - -static object * -int_and(v, w) - intobject *v; - intobject *w; -{ - register long a, b; - a = v->ob_ival; - b = w->ob_ival; - return newintobject(a & b); -} - -static object * -int_xor(v, w) - intobject *v; - intobject *w; -{ - register long a, b; - a = v->ob_ival; - b = w->ob_ival; - return newintobject(a ^ b); -} - -static object * -int_or(v, w) - intobject *v; - intobject *w; -{ - register long a, b; - a = v->ob_ival; - b = w->ob_ival; - return newintobject(a | b); -} - -static object * -int_int(v) - intobject *v; -{ - INCREF(v); - return (object *)v; -} - -static object * -int_long(v) - intobject *v; -{ - return newlongobject((v -> ob_ival)); -} - -static object * -int_float(v) - intobject *v; -{ - return newfloatobject((double)(v -> ob_ival)); -} - -static object * -int_oct(v) - intobject *v; -{ - char buf[20]; - long x = v -> ob_ival; - if (x == 0) - strcpy(buf, "0"); - else if (x > 0) - sprintf(buf, "0%lo", x); - else - sprintf(buf, "-0%lo", -x); - return newstringobject(buf); -} - -static object * -int_hex(v) - intobject *v; -{ - char buf[20]; - long x = v -> ob_ival; - if (x >= 0) - sprintf(buf, "0x%lx", x); - else - sprintf(buf, "-0x%lx", -x); - return newstringobject(buf); -} - -static number_methods int_as_number = { - (binaryfunc)int_add, /*nb_add*/ - (binaryfunc)int_sub, /*nb_subtract*/ - (binaryfunc)int_mul, /*nb_multiply*/ - (binaryfunc)int_div, /*nb_divide*/ - (binaryfunc)int_mod, /*nb_remainder*/ - (binaryfunc)int_divmod, /*nb_divmod*/ - (ternaryfunc)int_pow, /*nb_power*/ - (unaryfunc)int_neg, /*nb_negative*/ - (unaryfunc)int_pos, /*nb_positive*/ - (unaryfunc)int_abs, /*nb_absolute*/ - (inquiry)int_nonzero, /*nb_nonzero*/ - (unaryfunc)int_invert, /*nb_invert*/ - (binaryfunc)int_lshift, /*nb_lshift*/ - (binaryfunc)int_rshift, /*nb_rshift*/ - (binaryfunc)int_and, /*nb_and*/ - (binaryfunc)int_xor, /*nb_xor*/ - (binaryfunc)int_or, /*nb_or*/ - 0, /*nb_coerce*/ - (unaryfunc)int_int, /*nb_int*/ - (unaryfunc)int_long, /*nb_long*/ - (unaryfunc)int_float, /*nb_float*/ - (unaryfunc)int_oct, /*nb_oct*/ - (unaryfunc)int_hex, /*nb_hex*/ -}; - -typeobject Inttype = { - OB_HEAD_INIT(&Typetype) - 0, - "int", - sizeof(intobject), - 0, - (destructor)int_dealloc, /*tp_dealloc*/ - (printfunc)int_print, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)int_compare, /*tp_compare*/ - (reprfunc)int_repr, /*tp_repr*/ - &int_as_number, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)int_hash, /*tp_hash*/ -}; diff --git a/Objects/listobject.c b/Objects/listobject.c deleted file mode 100644 index b3e3378c88..0000000000 --- a/Objects/listobject.c +++ /dev/null @@ -1,795 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* List object implementation */ - -#include "allobjects.h" -#include "modsupport.h" -#include "ceval.h" -#ifdef STDC_HEADERS -#include <stddef.h> -#else -#include <sys/types.h> /* For size_t */ -#endif - -#define ROUNDUP(n, block) ((((n)+(block)-1)/(block))*(block)) - -static int -roundup(n) - int n; -{ - if (n < 500) - return ROUNDUP(n, 10); - else - return ROUNDUP(n, 100); -} - -#define NRESIZE(var, type, nitems) RESIZE(var, type, roundup(nitems)) - -object * -newlistobject(size) - int size; -{ - int i; - listobject *op; - size_t nbytes; - if (size < 0) { - err_badcall(); - return NULL; - } - nbytes = size * sizeof(object *); - /* Check for overflow */ - if (nbytes / sizeof(object *) != size) { - return err_nomem(); - } - op = (listobject *) malloc(sizeof(listobject)); - if (op == NULL) { - return err_nomem(); - } - if (size <= 0) { - op->ob_item = NULL; - } - else { - op->ob_item = (object **) malloc(nbytes); - if (op->ob_item == NULL) { - free((ANY *)op); - return err_nomem(); - } - } - op->ob_type = &Listtype; - op->ob_size = size; - for (i = 0; i < size; i++) - op->ob_item[i] = NULL; - NEWREF(op); - return (object *) op; -} - -int -getlistsize(op) - object *op; -{ - if (!is_listobject(op)) { - err_badcall(); - return -1; - } - else - return ((listobject *)op) -> ob_size; -} - -object * -getlistitem(op, i) - object *op; - int i; -{ - if (!is_listobject(op)) { - err_badcall(); - return NULL; - } - if (i < 0 || i >= ((listobject *)op) -> ob_size) { - err_setstr(IndexError, "list index out of range"); - return NULL; - } - return ((listobject *)op) -> ob_item[i]; -} - -int -setlistitem(op, i, newitem) - register object *op; - register int i; - register object *newitem; -{ - register object *olditem; - register object **p; - if (!is_listobject(op)) { - XDECREF(newitem); - err_badcall(); - return -1; - } - if (i < 0 || i >= ((listobject *)op) -> ob_size) { - XDECREF(newitem); - err_setstr(IndexError, "list assignment index out of range"); - return -1; - } - p = ((listobject *)op) -> ob_item + i; - olditem = *p; - *p = newitem; - XDECREF(olditem); - return 0; -} - -static int -ins1(self, where, v) - listobject *self; - int where; - object *v; -{ - int i; - object **items; - if (v == NULL) { - err_badcall(); - return -1; - } - items = self->ob_item; - NRESIZE(items, object *, self->ob_size+1); - if (items == NULL) { - err_nomem(); - return -1; - } - if (where < 0) - where = 0; - if (where > self->ob_size) - where = self->ob_size; - for (i = self->ob_size; --i >= where; ) - items[i+1] = items[i]; - INCREF(v); - items[where] = v; - self->ob_item = items; - self->ob_size++; - return 0; -} - -int -inslistitem(op, where, newitem) - object *op; - int where; - object *newitem; -{ - if (!is_listobject(op)) { - err_badcall(); - return -1; - } - return ins1((listobject *)op, where, newitem); -} - -int -addlistitem(op, newitem) - object *op; - object *newitem; -{ - if (!is_listobject(op)) { - err_badcall(); - return -1; - } - return ins1((listobject *)op, - (int) ((listobject *)op)->ob_size, newitem); -} - -/* Methods */ - -static void -list_dealloc(op) - listobject *op; -{ - int i; - if (op->ob_item != NULL) { - for (i = 0; i < op->ob_size; i++) { - XDECREF(op->ob_item[i]); - } - free((ANY *)op->ob_item); - } - free((ANY *)op); -} - -static int -list_print(op, fp, flags) - listobject *op; - FILE *fp; - int flags; -{ - int i; - fprintf(fp, "["); - for (i = 0; i < op->ob_size; i++) { - if (i > 0) - fprintf(fp, ", "); - if (printobject(op->ob_item[i], fp, 0) != 0) - return -1; - } - fprintf(fp, "]"); - return 0; -} - -static object * -list_repr(v) - listobject *v; -{ - object *s, *comma; - int i; - s = newstringobject("["); - comma = newstringobject(", "); - for (i = 0; i < v->ob_size && s != NULL; i++) { - if (i > 0) - joinstring(&s, comma); - joinstring_decref(&s, reprobject(v->ob_item[i])); - } - XDECREF(comma); - joinstring_decref(&s, newstringobject("]")); - return s; -} - -static int -list_compare(v, w) - listobject *v, *w; -{ - int len = (v->ob_size < w->ob_size) ? v->ob_size : w->ob_size; - int i; - for (i = 0; i < len; i++) { - int cmp = cmpobject(v->ob_item[i], w->ob_item[i]); - if (cmp != 0) - return cmp; - } - return v->ob_size - w->ob_size; -} - -static int -list_length(a) - listobject *a; -{ - return a->ob_size; -} - -static object * -list_item(a, i) - listobject *a; - int i; -{ - if (i < 0 || i >= a->ob_size) { - err_setstr(IndexError, "list index out of range"); - return NULL; - } - INCREF(a->ob_item[i]); - return a->ob_item[i]; -} - -static object * -list_slice(a, ilow, ihigh) - listobject *a; - int ilow, ihigh; -{ - listobject *np; - int i; - if (ilow < 0) - ilow = 0; - else if (ilow > a->ob_size) - ilow = a->ob_size; - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > a->ob_size) - ihigh = a->ob_size; - np = (listobject *) newlistobject(ihigh - ilow); - if (np == NULL) - return NULL; - for (i = ilow; i < ihigh; i++) { - object *v = a->ob_item[i]; - INCREF(v); - np->ob_item[i - ilow] = v; - } - return (object *)np; -} - -object * -getlistslice(a, ilow, ihigh) - object *a; - int ilow, ihigh; -{ - if (!is_listobject(a)) { - err_badcall(); - return NULL; - } - return list_slice((listobject *)a, ilow, ihigh); -} - -static object * -list_concat(a, bb) - listobject *a; - object *bb; -{ - int size; - int i; - listobject *np; - if (!is_listobject(bb)) { - err_badarg(); - return NULL; - } -#define b ((listobject *)bb) - size = a->ob_size + b->ob_size; - np = (listobject *) newlistobject(size); - if (np == NULL) { - return NULL; - } - for (i = 0; i < a->ob_size; i++) { - object *v = a->ob_item[i]; - INCREF(v); - np->ob_item[i] = v; - } - for (i = 0; i < b->ob_size; i++) { - object *v = b->ob_item[i]; - INCREF(v); - np->ob_item[i + a->ob_size] = v; - } - return (object *)np; -#undef b -} - -static object * -list_repeat(a, n) - listobject *a; - int n; -{ - int i, j; - int size; - listobject *np; - object **p; - if (n < 0) - n = 0; - size = a->ob_size * n; - np = (listobject *) newlistobject(size); - if (np == NULL) - return NULL; - p = np->ob_item; - for (i = 0; i < n; i++) { - for (j = 0; j < a->ob_size; j++) { - *p = a->ob_item[j]; - INCREF(*p); - p++; - } - } - return (object *) np; -} - -static int -list_ass_slice(a, ilow, ihigh, v) - listobject *a; - int ilow, ihigh; - object *v; -{ - /* Because [X]DECREF can recursively invoke list operations on - this list, we must postpone all [X]DECREF activity until - after the list is back in its canonical shape. Therefore - we must allocate an additional array, 'recycle', into which - we temporarily copy the items that are deleted from the - list. :-( */ - object **recycle, **p; - object **item; - int n; /* Size of replacement list */ - int d; /* Change in size */ - int k; /* Loop index */ -#define b ((listobject *)v) - if (v == NULL) - n = 0; - else if (is_listobject(v)) { - n = b->ob_size; - if (a == b) { - /* Special case "a[i:j] = a" -- copy b first */ - int ret; - v = list_slice(b, 0, n); - ret = list_ass_slice(a, ilow, ihigh, v); - DECREF(v); - return ret; - } - } - else { - err_badarg(); - return -1; - } - if (ilow < 0) - ilow = 0; - else if (ilow > a->ob_size) - ilow = a->ob_size; - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > a->ob_size) - ihigh = a->ob_size; - item = a->ob_item; - d = n - (ihigh-ilow); - if (ihigh > ilow) - p = recycle = NEW(object *, (ihigh-ilow)); - else - p = recycle = NULL; - if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */ - for (k = ilow; k < ihigh; k++) - *p++ = item[k]; - if (d < 0) { - for (/*k = ihigh*/; k < a->ob_size; k++) - item[k+d] = item[k]; - a->ob_size += d; - NRESIZE(item, object *, a->ob_size); /* Can't fail */ - a->ob_item = item; - } - } - else { /* Insert d items; recycle ihigh-ilow items */ - NRESIZE(item, object *, a->ob_size + d); - if (item == NULL) { - XDEL(recycle); - err_nomem(); - return -1; - } - for (k = a->ob_size; --k >= ihigh; ) - item[k+d] = item[k]; - for (/*k = ihigh-1*/; k >= ilow; --k) - *p++ = item[k]; - a->ob_item = item; - a->ob_size += d; - } - for (k = 0; k < n; k++, ilow++) { - object *w = b->ob_item[k]; - XINCREF(w); - item[ilow] = w; - } - if (recycle) { - while (--p >= recycle) - XDECREF(*p); - DEL(recycle); - } - return 0; -#undef b -} - -int -setlistslice(a, ilow, ihigh, v) - object *a; - int ilow, ihigh; - object *v; -{ - if (!is_listobject(a)) { - err_badcall(); - return -1; - } - return list_ass_slice((listobject *)a, ilow, ihigh, v); -} - -static int -list_ass_item(a, i, v) - listobject *a; - int i; - object *v; -{ - object *old_value; - if (i < 0 || i >= a->ob_size) { - err_setstr(IndexError, "list assignment index out of range"); - return -1; - } - if (v == NULL) - return list_ass_slice(a, i, i+1, v); - INCREF(v); - old_value = a->ob_item[i]; - a->ob_item[i] = v; - DECREF(old_value); - return 0; -} - -static object * -ins(self, where, v) - listobject *self; - int where; - object *v; -{ - if (ins1(self, where, v) != 0) - return NULL; - INCREF(None); - return None; -} - -static object * -listinsert(self, args) - listobject *self; - object *args; -{ - int i; - object *v; - if (!getargs(args, "(iO)", &i, &v)) - return NULL; - return ins(self, i, v); -} - -static object * -listappend(self, args) - listobject *self; - object *args; -{ - object *v; - if (!getargs(args, "O", &v)) - return NULL; - return ins(self, (int) self->ob_size, v); -} - -static object *comparefunc; - -static int -cmp(v, w) - const ANY *v, *w; -{ - object *t, *res; - long i; - - if (err_occurred()) - return 0; - - if (comparefunc == NULL) - return cmpobject(* (object **) v, * (object **) w); - - /* Call the user-supplied comparison function */ - t = mkvalue("(OO)", * (object **) v, * (object **) w); - if (t == NULL) - return 0; - res = call_object(comparefunc, t); - DECREF(t); - if (res == NULL) - return 0; - if (!is_intobject(res)) { - err_setstr(TypeError, "comparison function should return int"); - i = 0; - } - else { - i = getintvalue(res); - if (i < 0) - i = -1; - else if (i > 0) - i = 1; - } - DECREF(res); - return (int) i; -} - -static object * -listsort(self, args) - listobject *self; - object *args; -{ - object *save_comparefunc; - if (self->ob_size <= 1) { - INCREF(None); - return None; - } - save_comparefunc = comparefunc; - comparefunc = args; - if (comparefunc != NULL) { - /* Test the comparison function for obvious errors */ - (void) cmp((ANY *)&self->ob_item[0], (ANY *)&self->ob_item[1]); - if (err_occurred()) { - comparefunc = save_comparefunc; - return NULL; - } - } - qsort((char *)self->ob_item, - (int) self->ob_size, sizeof(object *), cmp); - comparefunc = save_comparefunc; - if (err_occurred()) - return NULL; - INCREF(None); - return None; -} - -static object * -listreverse(self, args) - listobject *self; - object *args; -{ - register object **p, **q; - register object *tmp; - - if (args != NULL) { - err_badarg(); - return NULL; - } - - if (self->ob_size > 1) { - for (p = self->ob_item, q = self->ob_item + self->ob_size - 1; - p < q; p++, q--) { - tmp = *p; - *p = *q; - *q = tmp; - } - } - - INCREF(None); - return None; -} - -int -reverselist(v) - object *v; -{ - if (v == NULL || !is_listobject(v)) { - err_badcall(); - return -1; - } - v = listreverse((listobject *)v, (object *)NULL); - if (v == NULL) - return -1; - DECREF(v); - return 0; -} - -int -sortlist(v) - object *v; -{ - if (v == NULL || !is_listobject(v)) { - err_badcall(); - return -1; - } - v = listsort((listobject *)v, (object *)NULL); - if (v == NULL) - return -1; - DECREF(v); - return 0; -} - -object * -listtuple(v) - object *v; -{ - object *w; - object **p; - int n; - if (v == NULL || !is_listobject(v)) { - err_badcall(); - return NULL; - } - n = ((listobject *)v)->ob_size; - w = newtupleobject(n); - if (w == NULL) - return NULL; - p = ((tupleobject *)w)->ob_item; - memcpy((ANY *)p, - (ANY *)((listobject *)v)->ob_item, - n*sizeof(object *)); - while (--n >= 0) { - INCREF(*p); - p++; - } - return w; -} - -static object * -listindex(self, args) - listobject *self; - object *args; -{ - int i; - - if (args == NULL) { - err_badarg(); - return NULL; - } - for (i = 0; i < self->ob_size; i++) { - if (cmpobject(self->ob_item[i], args) == 0) - return newintobject((long)i); - } - err_setstr(ValueError, "list.index(x): x not in list"); - return NULL; -} - -static object * -listcount(self, args) - listobject *self; - object *args; -{ - int count = 0; - int i; - - if (args == NULL) { - err_badarg(); - return NULL; - } - for (i = 0; i < self->ob_size; i++) { - if (cmpobject(self->ob_item[i], args) == 0) - count++; - } - return newintobject((long)count); -} - -static object * -listremove(self, args) - listobject *self; - object *args; -{ - int i; - - if (args == NULL) { - err_badarg(); - return NULL; - } - for (i = 0; i < self->ob_size; i++) { - if (cmpobject(self->ob_item[i], args) == 0) { - if (list_ass_slice(self, i, i+1, (object *)NULL) != 0) - return NULL; - INCREF(None); - return None; - } - - } - err_setstr(ValueError, "list.remove(x): x not in list"); - return NULL; -} - -static struct methodlist list_methods[] = { - {"append", (method)listappend}, - {"count", (method)listcount}, - {"index", (method)listindex}, - {"insert", (method)listinsert}, - {"sort", (method)listsort, 0}, - {"remove", (method)listremove}, - {"reverse", (method)listreverse}, - {NULL, NULL} /* sentinel */ -}; - -static object * -list_getattr(f, name) - listobject *f; - char *name; -{ - return findmethod(list_methods, (object *)f, name); -} - -static sequence_methods list_as_sequence = { - (inquiry)list_length, /*sq_length*/ - (binaryfunc)list_concat, /*sq_concat*/ - (intargfunc)list_repeat, /*sq_repeat*/ - (intargfunc)list_item, /*sq_item*/ - (intintargfunc)list_slice, /*sq_slice*/ - (intobjargproc)list_ass_item, /*sq_ass_item*/ - (intintobjargproc)list_ass_slice, /*sq_ass_slice*/ -}; - -typeobject Listtype = { - OB_HEAD_INIT(&Typetype) - 0, - "list", - sizeof(listobject), - 0, - (destructor)list_dealloc, /*tp_dealloc*/ - (printfunc)list_print, /*tp_print*/ - (getattrfunc)list_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)list_compare, /*tp_compare*/ - (reprfunc)list_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - &list_as_sequence, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ -}; diff --git a/Objects/longobject.c b/Objects/longobject.c deleted file mode 100644 index 1ec4511a70..0000000000 --- a/Objects/longobject.c +++ /dev/null @@ -1,1423 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Long (arbitrary precision) integer object implementation */ - -/* XXX The functional organization of this file is terrible */ - -#include "allobjects.h" -#include "longintrepr.h" -#include "mymath.h" -#include <assert.h> -#include <ctype.h> - -#define ABS(x) ((x) < 0 ? -(x) : (x)) - -/* Forward */ -static longobject *long_normalize PROTO((longobject *)); -static longobject *mul1 PROTO((longobject *, wdigit)); -static longobject *muladd1 PROTO((longobject *, wdigit, wdigit)); -static longobject *divrem1 PROTO((longobject *, wdigit, digit *)); -static object *long_format PROTO((object *aa, int base)); - -static int ticker; /* XXX Could be shared with ceval? */ - -#define SIGCHECK(block) \ - if (--ticker < 0) { \ - ticker = 100; \ - if (sigcheck()) { block; } \ - } - -/* Normalize (remove leading zeros from) a long int object. - Doesn't attempt to free the storage--in most cases, due to the nature - of the algorithms used, this could save at most be one word anyway. */ - -static longobject * -long_normalize(v) - register longobject *v; -{ - int j = ABS(v->ob_size); - register int i = j; - - while (i > 0 && v->ob_digit[i-1] == 0) - --i; - if (i != j) - v->ob_size = (v->ob_size < 0) ? -(i) : i; - return v; -} - -/* Allocate a new long int object with size digits. - Return NULL and set exception if we run out of memory. */ - -longobject * -alloclongobject(size) - int size; -{ - return NEWVAROBJ(longobject, &Longtype, size); -} - -/* Create a new long int object from a C long int */ - -object * -newlongobject(ival) - long ival; -{ - /* Assume a C long fits in at most 3 'digits' */ - /* XXX On 64 bit machines this isn't true!!! */ - longobject *v = alloclongobject(3); - if (v != NULL) { - if (ival < 0) { - ival = -ival; - v->ob_size = -(v->ob_size); - } - v->ob_digit[0] = ival & MASK; - v->ob_digit[1] = (ival >> SHIFT) & MASK; - v->ob_digit[2] = ((unsigned long)ival >> (2*SHIFT)) & MASK; - v = long_normalize(v); - } - return (object *)v; -} - -/* Create a new long int object from a C double */ - -object * -#ifdef MPW -dnewlongobject(double dval) -#else -dnewlongobject(dval) - double dval; -#endif /* MPW */ -{ - longobject *v; - double frac; - int i, ndig, expo, neg; - neg = 0; - if (dval < 0.0) { - neg = 1; - dval = -dval; - } - frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */ - if (expo <= 0) - return newlongobject(0L); - ndig = (expo-1) / SHIFT + 1; /* Number of 'digits' in result */ - v = alloclongobject(ndig); - if (v == NULL) - return NULL; - frac = ldexp(frac, (expo-1) % SHIFT + 1); - for (i = ndig; --i >= 0; ) { - long bits = (long)frac; - v->ob_digit[i] = bits; - frac = frac - (double)bits; - frac = ldexp(frac, SHIFT); - } - if (neg) - v->ob_size = -(v->ob_size); - return (object *)v; -} - -/* Get a C long int from a long int object. - Returns -1 and sets an error condition if overflow occurs. */ - -long -getlongvalue(vv) - object *vv; -{ - register longobject *v; - long x, prev; - int i, sign; - - if (vv == NULL || !is_longobject(vv)) { - err_badcall(); - return -1; - } - v = (longobject *)vv; - i = v->ob_size; - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << SHIFT) + v->ob_digit[i]; - if ((x >> SHIFT) != prev) { - err_setstr(OverflowError, - "long int too long to convert"); - return -1; - } - } - return x * sign; -} - -/* Get a C double from a long int object. No overflow check. */ - -double -dgetlongvalue(vv) - object *vv; -{ - register longobject *v; - double x; - double multiplier = (double) (1L << SHIFT); - int i, sign; - - if (vv == NULL || !is_longobject(vv)) { - err_badcall(); - return -1; - } - v = (longobject *)vv; - i = v->ob_size; - sign = 1; - x = 0.0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - x = x*multiplier + (double)v->ob_digit[i]; - } - return x * sign; -} - -/* Multiply by a single digit, ignoring the sign. */ - -static longobject * -mul1(a, n) - longobject *a; - wdigit n; -{ - return muladd1(a, n, (digit)0); -} - -/* Multiply by a single digit and add a single digit, ignoring the sign. */ - -static longobject * -muladd1(a, n, extra) - longobject *a; - wdigit n; - wdigit extra; -{ - int size_a = ABS(a->ob_size); - longobject *z = alloclongobject(size_a+1); - twodigits carry = extra; - int i; - - if (z == NULL) - return NULL; - for (i = 0; i < size_a; ++i) { - carry += (twodigits)a->ob_digit[i] * n; - z->ob_digit[i] = carry & MASK; - carry >>= SHIFT; - } - z->ob_digit[i] = carry; - return long_normalize(z); -} - -/* Divide a long integer by a digit, returning both the quotient - (as function result) and the remainder (through *prem). - The sign of a is ignored; n should not be zero. */ - -static longobject * -divrem1(a, n, prem) - longobject *a; - wdigit n; - digit *prem; -{ - int size = ABS(a->ob_size); - longobject *z; - int i; - twodigits rem = 0; - - assert(n > 0 && n <= MASK); - z = alloclongobject(size); - if (z == NULL) - return NULL; - for (i = size; --i >= 0; ) { - rem = (rem << SHIFT) + a->ob_digit[i]; - z->ob_digit[i] = rem/n; - rem %= n; - } - *prem = rem; - return long_normalize(z); -} - -/* Convert a long int object to a string, using a given conversion base. - Return a string object. - If base is 8 or 16, add the proper prefix '0' or '0x'. - External linkage: used in bltinmodule.c by hex() and oct(). */ - -static object * -long_format(aa, base) - object *aa; - int base; -{ - register longobject *a = (longobject *)aa; - stringobject *str; - int i; - int size_a = ABS(a->ob_size); - char *p; - int bits; - char sign = '\0'; - - if (a == NULL || !is_longobject(a)) { - err_badcall(); - return NULL; - } - assert(base >= 2 && base <= 36); - - /* Compute a rough upper bound for the length of the string */ - i = base; - bits = 0; - while (i > 1) { - ++bits; - i >>= 1; - } - i = 6 + (size_a*SHIFT + bits-1) / bits; - str = (stringobject *) newsizedstringobject((char *)0, i); - if (str == NULL) - return NULL; - p = GETSTRINGVALUE(str) + i; - *p = '\0'; - *--p = 'L'; - if (a->ob_size < 0) - sign = '-'; - - INCREF(a); - do { - digit rem; - longobject *temp = divrem1(a, (digit)base, &rem); - if (temp == NULL) { - DECREF(a); - DECREF(str); - return NULL; - } - if (rem < 10) - rem += '0'; - else - rem += 'A'-10; - assert(p > GETSTRINGVALUE(str)); - *--p = rem; - DECREF(a); - a = temp; - SIGCHECK({ - DECREF(a); - DECREF(str); - return NULL; - }) - } while (ABS(a->ob_size) != 0); - DECREF(a); - if (base == 8) { - if (size_a != 0) - *--p = '0'; - } - else if (base == 16) { - *--p = 'x'; - *--p = '0'; - } - else if (base != 10) { - *--p = '#'; - *--p = '0' + base%10; - if (base > 10) - *--p = '0' + base/10; - } - if (sign) - *--p = sign; - if (p != GETSTRINGVALUE(str)) { - char *q = GETSTRINGVALUE(str); - assert(p > q); - do { - } while ((*q++ = *p++) != '\0'); - q--; - resizestring((object **)&str, (int) (q - GETSTRINGVALUE(str))); - } - return (object *)str; -} - -#if 0 -/* Convert a string to a long int object, in a given base. - Base zero implies a default depending on the number. - External linkage: used in compile.c and stropmodule.c. */ - -object * -long_scan(str, base) - char *str; - int base; -{ - return long_escan(str, (char **)NULL, base); -} -#endif - -object * -long_escan(str, pend, base) - char *str; - char **pend; - int base; -{ - int sign = 1; - longobject *z; - - if (base != 0 && base < 2 || base > 36) { - err_setstr(ValueError, "invalid base for long literal"); - return NULL; - } - while (*str != '\0' && isspace(Py_CHARMASK(*str))) - str++; - if (*str == '+') - ++str; - else if (*str == '-') { - ++str; - sign = -1; - } - while (*str != '\0' && isspace(Py_CHARMASK(*str))) - str++; - if (base == 0) { - if (str[0] != '0') - base = 10; - else if (str[1] == 'x' || str[1] == 'X') - base = 16; - else - base = 8; - } - if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) - str += 2; - z = alloclongobject(0); - for ( ; z != NULL; ++str) { - int k = -1; - longobject *temp; - - if (*str <= '9') - k = *str - '0'; - else if (*str >= 'a') - k = *str - 'a' + 10; - else if (*str >= 'A') - k = *str - 'A' + 10; - if (k < 0 || k >= base) - break; - temp = muladd1(z, (digit)base, (digit)k); - DECREF(z); - z = temp; - } - if (sign < 0 && z != NULL && z->ob_size != 0) - z->ob_size = -(z->ob_size); - if (pend) - *pend = str; - return (object *) z; -} - -static longobject *x_divrem PROTO((longobject *, longobject *, longobject **)); -static object *long_pos PROTO((longobject *)); -static long_divrem PROTO((longobject *, longobject *, - longobject **, longobject **)); - -/* Long division with remainder, top-level routine */ - -static int -long_divrem(a, b, pdiv, prem) - longobject *a, *b; - longobject **pdiv; - longobject **prem; -{ - int size_a = ABS(a->ob_size), size_b = ABS(b->ob_size); - longobject *z; - - if (size_b == 0) { - err_setstr(ZeroDivisionError, "long division or modulo"); - return -1; - } - if (size_a < size_b || - size_a == size_b && - a->ob_digit[size_a-1] < b->ob_digit[size_b-1]) { - /* |a| < |b|. */ - *pdiv = alloclongobject(0); - INCREF(a); - *prem = (longobject *) a; - return 0; - } - if (size_b == 1) { - digit rem = 0; - z = divrem1(a, b->ob_digit[0], &rem); - if (z == NULL) - return -1; - *prem = (longobject *) newlongobject((long)rem); - } - else { - z = x_divrem(a, b, prem); - if (z == NULL) - return -1; - } - /* Set the signs. - The quotient z has the sign of a*b; - the remainder r has the sign of a, - so a = b*z + r. */ - if ((a->ob_size < 0) != (b->ob_size < 0)) - z->ob_size = -(z->ob_size); - if (a->ob_size < 0 && (*prem)->ob_size != 0) - (*prem)->ob_size = -((*prem)->ob_size); - *pdiv = z; - return 0; -} - -/* Unsigned long division with remainder -- the algorithm */ - -static longobject * -x_divrem(v1, w1, prem) - longobject *v1, *w1; - longobject **prem; -{ - int size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size); - digit d = (twodigits)BASE / (w1->ob_digit[size_w-1] + 1); - longobject *v = mul1(v1, d); - longobject *w = mul1(w1, d); - longobject *a; - int j, k; - - if (v == NULL || w == NULL) { - XDECREF(v); - XDECREF(w); - return NULL; - } - - assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */ - assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */ - assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */ - - size_v = ABS(v->ob_size); - a = alloclongobject(size_v - size_w + 1); - - for (j = size_v, k = a->ob_size-1; a != NULL && k >= 0; --j, --k) { - digit vj = (j >= size_v) ? 0 : v->ob_digit[j]; - twodigits q; - stwodigits carry = 0; - int i; - - SIGCHECK({ - DECREF(a); - a = NULL; - break; - }) - if (vj == w->ob_digit[size_w-1]) - q = MASK; - else - q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) / - w->ob_digit[size_w-1]; - - while (w->ob_digit[size_w-2]*q > - (( - ((twodigits)vj << SHIFT) - + v->ob_digit[j-1] - - q*w->ob_digit[size_w-1] - ) << SHIFT) - + v->ob_digit[j-2]) - --q; - - for (i = 0; i < size_w && i+k < size_v; ++i) { - twodigits z = w->ob_digit[i] * q; - digit zz = z >> SHIFT; - carry += v->ob_digit[i+k] - z + ((twodigits)zz << SHIFT); - v->ob_digit[i+k] = carry & MASK; - carry = (carry >> SHIFT) - zz; - } - - if (i+k < size_v) { - carry += v->ob_digit[i+k]; - v->ob_digit[i+k] = 0; - } - - if (carry == 0) - a->ob_digit[k] = q; - else { - assert(carry == -1); - a->ob_digit[k] = q-1; - carry = 0; - for (i = 0; i < size_w && i+k < size_v; ++i) { - carry += v->ob_digit[i+k] + w->ob_digit[i]; - v->ob_digit[i+k] = carry & MASK; - carry >>= SHIFT; - } - } - } /* for j, k */ - - if (a == NULL) - *prem = NULL; - else { - a = long_normalize(a); - *prem = divrem1(v, d, &d); - /* d receives the (unused) remainder */ - if (*prem == NULL) { - DECREF(a); - a = NULL; - } - } - DECREF(v); - DECREF(w); - return a; -} - -/* Methods */ - -/* Forward */ -static void long_dealloc PROTO((object *)); -static object *long_repr PROTO((object *)); -static int long_compare PROTO((longobject *, longobject *)); -static long long_hash PROTO((longobject *)); - -static object *long_add PROTO((longobject *, longobject *)); -static object *long_sub PROTO((longobject *, longobject *)); -static object *long_mul PROTO((longobject *, longobject *)); -static object *long_div PROTO((longobject *, longobject *)); -static object *long_mod PROTO((longobject *, longobject *)); -static object *long_divmod PROTO((longobject *, longobject *)); -static object *long_pow PROTO((longobject *, longobject *, longobject *)); -static object *long_neg PROTO((longobject *)); -static object *long_pos PROTO((longobject *)); -static object *long_abs PROTO((longobject *)); -static int long_nonzero PROTO((longobject *)); -static object *long_invert PROTO((longobject *)); -static object *long_lshift PROTO((longobject *, longobject *)); -static object *long_rshift PROTO((longobject *, longobject *)); -static object *long_and PROTO((longobject *, longobject *)); -static object *long_xor PROTO((longobject *, longobject *)); -static object *long_or PROTO((longobject *, longobject *)); - -static void -long_dealloc(v) - object *v; -{ - DEL(v); -} - -static object * -long_repr(v) - object *v; -{ - return long_format(v, 10); -} - -static int -long_compare(a, b) - longobject *a, *b; -{ - int sign; - - if (a->ob_size != b->ob_size) { - if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0) - sign = 0; - else - sign = a->ob_size - b->ob_size; - } - else { - int i = ABS(a->ob_size); - while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) - ; - if (i < 0) - sign = 0; - else { - sign = (int)a->ob_digit[i] - (int)b->ob_digit[i]; - if (a->ob_size < 0) - sign = -sign; - } - } - return sign < 0 ? -1 : sign > 0 ? 1 : 0; -} - -static long -long_hash(v) - longobject *v; -{ - long x; - int i, sign; - - /* This is designed so that Python ints and longs with the - same value hash to the same value, otherwise comparisons - of mapping keys will turn out weird */ - i = v->ob_size; - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - /* Force a 32-bit circular shift */ - x = ((x << SHIFT) & ~MASK) | ((x >> (32-SHIFT)) & MASK); - x += v->ob_digit[i]; - } - x = x * sign; - if (x == -1) - x = -2; - return x; -} - - -/* Add the absolute values of two long integers. */ - -static longobject *x_add PROTO((longobject *, longobject *)); -static longobject * -x_add(a, b) - longobject *a, *b; -{ - int size_a = ABS(a->ob_size), size_b = ABS(b->ob_size); - longobject *z; - int i; - digit carry = 0; - - /* Ensure a is the larger of the two: */ - if (size_a < size_b) { - { longobject *temp = a; a = b; b = temp; } - { int size_temp = size_a; size_a = size_b; size_b = size_temp; } - } - z = alloclongobject(size_a+1); - if (z == NULL) - return NULL; - for (i = 0; i < size_b; ++i) { - carry += a->ob_digit[i] + b->ob_digit[i]; - z->ob_digit[i] = carry & MASK; - /* The following assumes unsigned shifts don't - propagate the sign bit. */ - carry >>= SHIFT; - } - for (; i < size_a; ++i) { - carry += a->ob_digit[i]; - z->ob_digit[i] = carry & MASK; - carry >>= SHIFT; - } - z->ob_digit[i] = carry; - return long_normalize(z); -} - -/* Subtract the absolute values of two integers. */ - -static longobject *x_sub PROTO((longobject *, longobject *)); -static longobject * -x_sub(a, b) - longobject *a, *b; -{ - int size_a = ABS(a->ob_size), size_b = ABS(b->ob_size); - longobject *z; - int i; - int sign = 1; - digit borrow = 0; - - /* Ensure a is the larger of the two: */ - if (size_a < size_b) { - sign = -1; - { longobject *temp = a; a = b; b = temp; } - { int size_temp = size_a; size_a = size_b; size_b = size_temp; } - } - else if (size_a == size_b) { - /* Find highest digit where a and b differ: */ - i = size_a; - while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) - ; - if (i < 0) - return alloclongobject(0); - if (a->ob_digit[i] < b->ob_digit[i]) { - sign = -1; - { longobject *temp = a; a = b; b = temp; } - } - size_a = size_b = i+1; - } - z = alloclongobject(size_a); - if (z == NULL) - return NULL; - for (i = 0; i < size_b; ++i) { - /* The following assumes unsigned arithmetic - works module 2**N for some N>SHIFT. */ - borrow = a->ob_digit[i] - b->ob_digit[i] - borrow; - z->ob_digit[i] = borrow & MASK; - borrow >>= SHIFT; - borrow &= 1; /* Keep only one sign bit */ - } - for (; i < size_a; ++i) { - borrow = a->ob_digit[i] - borrow; - z->ob_digit[i] = borrow & MASK; - borrow >>= SHIFT; - } - assert(borrow == 0); - if (sign < 0) - z->ob_size = -(z->ob_size); - return long_normalize(z); -} - -static object * -long_add(a, b) - longobject *a; - longobject *b; -{ - longobject *z; - - if (a->ob_size < 0) { - if (b->ob_size < 0) { - z = x_add(a, b); - if (z != NULL && z->ob_size != 0) - z->ob_size = -(z->ob_size); - } - else - z = x_sub(b, a); - } - else { - if (b->ob_size < 0) - z = x_sub(a, b); - else - z = x_add(a, b); - } - return (object *)z; -} - -static object * -long_sub(a, b) - longobject *a; - longobject *b; -{ - longobject *z; - - if (a->ob_size < 0) { - if (b->ob_size < 0) - z = x_sub(a, b); - else - z = x_add(a, b); - if (z != NULL && z->ob_size != 0) - z->ob_size = -(z->ob_size); - } - else { - if (b->ob_size < 0) - z = x_add(a, b); - else - z = x_sub(a, b); - } - return (object *)z; -} - -static object * -long_mul(a, b) - longobject *a; - longobject *b; -{ - int size_a; - int size_b; - longobject *z; - int i; - - size_a = ABS(a->ob_size); - size_b = ABS(b->ob_size); - z = alloclongobject(size_a + size_b); - if (z == NULL) - return NULL; - for (i = 0; i < z->ob_size; ++i) - z->ob_digit[i] = 0; - for (i = 0; i < size_a; ++i) { - twodigits carry = 0; - twodigits f = a->ob_digit[i]; - int j; - - SIGCHECK({ - DECREF(z); - return NULL; - }) - for (j = 0; j < size_b; ++j) { - carry += z->ob_digit[i+j] + b->ob_digit[j] * f; - z->ob_digit[i+j] = carry & MASK; - carry >>= SHIFT; - } - for (; carry != 0; ++j) { - assert(i+j < z->ob_size); - carry += z->ob_digit[i+j]; - z->ob_digit[i+j] = carry & MASK; - carry >>= SHIFT; - } - } - if (a->ob_size < 0) - z->ob_size = -(z->ob_size); - if (b->ob_size < 0) - z->ob_size = -(z->ob_size); - return (object *) long_normalize(z); -} - -/* The / and % operators are now defined in terms of divmod(). - The expression a mod b has the value a - b*floor(a/b). - The long_divrem function gives the remainder after division of - |a| by |b|, with the sign of a. This is also expressed - as a - b*trunc(a/b), if trunc truncates towards zero. - Some examples: - a b a rem b a mod b - 13 10 3 3 - -13 10 -3 7 - 13 -10 3 -7 - -13 -10 -3 -3 - So, to get from rem to mod, we have to add b if a and b - have different signs. We then subtract one from the 'div' - part of the outcome to keep the invariant intact. */ - -static int l_divmod PROTO((longobject *, longobject *, - longobject **, longobject **)); -static int -l_divmod(v, w, pdiv, pmod) - longobject *v; - longobject *w; - longobject **pdiv; - longobject **pmod; -{ - longobject *div, *mod; - - if (long_divrem(v, w, &div, &mod) < 0) - return -1; - if (mod->ob_size < 0 && w->ob_size > 0 || - mod->ob_size > 0 && w->ob_size < 0) { - longobject *temp; - longobject *one; - temp = (longobject *) long_add(mod, w); - DECREF(mod); - mod = temp; - if (mod == NULL) { - DECREF(div); - return -1; - } - one = (longobject *) newlongobject(1L); - if (one == NULL || - (temp = (longobject *) long_sub(div, one)) == NULL) { - DECREF(mod); - DECREF(div); - XDECREF(one); - return -1; - } - DECREF(one); - DECREF(div); - div = temp; - } - *pdiv = div; - *pmod = mod; - return 0; -} - -static object * -long_div(v, w) - longobject *v; - longobject *w; -{ - longobject *div, *mod; - if (l_divmod(v, w, &div, &mod) < 0) - return NULL; - DECREF(mod); - return (object *)div; -} - -static object * -long_mod(v, w) - longobject *v; - longobject *w; -{ - longobject *div, *mod; - if (l_divmod(v, w, &div, &mod) < 0) - return NULL; - DECREF(div); - return (object *)mod; -} - -static object * -long_divmod(v, w) - longobject *v; - longobject *w; -{ - object *z; - longobject *div, *mod; - if (l_divmod(v, w, &div, &mod) < 0) - return NULL; - z = newtupleobject(2); - if (z != NULL) { - settupleitem(z, 0, (object *) div); - settupleitem(z, 1, (object *) mod); - } - else { - DECREF(div); - DECREF(mod); - } - return z; -} - -static object * -long_pow(a, b, c) - longobject *a; - longobject *b; - longobject *c; -{ - longobject *z, *div, *mod; - int size_b, i; - - size_b = b->ob_size; - if (size_b < 0) { - err_setstr(ValueError, "long integer to the negative power"); - return NULL; - } - z = (longobject *)newlongobject(1L); - INCREF(a); - for (i = 0; i < size_b; ++i) { - digit bi = b->ob_digit[i]; - int j; - - for (j = 0; j < SHIFT; ++j) { - longobject *temp; - - if (bi & 1) { - temp = (longobject *)long_mul(z, a); - DECREF(z); - if ((object*)c!=None && temp!=NULL) { - l_divmod(temp, c, &div, &mod); - XDECREF(div); - DECREF(temp); - temp = mod; - } - z = temp; - if (z == NULL) - break; - } - bi >>= 1; - if (bi == 0 && i+1 == size_b) - break; - temp = (longobject *)long_mul(a, a); - DECREF(a); - if ((object*)c!=None && temp!=NULL) { - l_divmod(temp, c, &div, &mod); - XDECREF(div); - DECREF(temp); - temp = mod; - } - a = temp; - if (a == NULL) { - DECREF(z); - z = NULL; - break; - } - } - if (a == NULL || z == NULL) - break; - } - XDECREF(a); - if ((object*)c!=None && z!=NULL) { - l_divmod(z, c, &div, &mod); - XDECREF(div); - DECREF(z); - z=mod; - } - return (object *)z; -} - -static object * -long_invert(v) - longobject *v; -{ - /* Implement ~x as -(x+1) */ - longobject *x; - longobject *w; - w = (longobject *)newlongobject(1L); - if (w == NULL) - return NULL; - x = (longobject *) long_add(v, w); - DECREF(w); - if (x == NULL) - return NULL; - if (x->ob_size != 0) - x->ob_size = -(x->ob_size); - return (object *)x; -} - -static object * -long_pos(v) - longobject *v; -{ - INCREF(v); - return (object *)v; -} - -static object * -long_neg(v) - longobject *v; -{ - longobject *z; - int i, n; - n = ABS(v->ob_size); - if (n == 0) { - /* -0 == 0 */ - INCREF(v); - return (object *) v; - } - z = alloclongobject(ABS(n)); - if (z == NULL) - return NULL; - for (i = 0; i < n; i++) - z->ob_digit[i] = v->ob_digit[i]; - z->ob_size = -(v->ob_size); - return (object *)z; -} - -static object * -long_abs(v) - longobject *v; -{ - if (v->ob_size < 0) - return long_neg(v); - else { - INCREF(v); - return (object *)v; - } -} - -static int -long_nonzero(v) - longobject *v; -{ - return ABS(v->ob_size) != 0; -} - -static object * -long_rshift(a, b) - longobject *a; - longobject *b; -{ - longobject *z; - long shiftby; - int newsize, wordshift, loshift, hishift, i, j; - digit lomask, himask; - - if (a->ob_size < 0) { - /* Right shifting negative numbers is harder */ - longobject *a1, *a2, *a3; - a1 = (longobject *) long_invert(a); - if (a1 == NULL) return NULL; - a2 = (longobject *) long_rshift(a1, b); - DECREF(a1); - if (a2 == NULL) return NULL; - a3 = (longobject *) long_invert(a2); - DECREF(a2); - return (object *) a3; - } - - shiftby = getlongvalue((object *)b); - if (shiftby == -1L && err_occurred()) - return NULL; - if (shiftby < 0) { - err_setstr(ValueError, "negative shift count"); - return NULL; - } - wordshift = shiftby / SHIFT; - newsize = ABS(a->ob_size) - wordshift; - if (newsize <= 0) { - z = alloclongobject(0); - return (object *)z; - } - loshift = shiftby % SHIFT; - hishift = SHIFT - loshift; - lomask = ((digit)1 << hishift) - 1; - himask = MASK ^ lomask; - z = alloclongobject(newsize); - if (z == NULL) - return NULL; - if (a->ob_size < 0) - z->ob_size = -(z->ob_size); - for (i = 0, j = wordshift; i < newsize; i++, j++) { - z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask; - if (i+1 < newsize) - z->ob_digit[i] |= - (a->ob_digit[j+1] << hishift) & himask; - } - return (object *) long_normalize(z); -} - -static object * -long_lshift(a, b) - longobject *a; - longobject *b; -{ - longobject *z; - long shiftby; - int newsize, wordshift, loshift, hishift, i, j; - digit lomask, himask; - - shiftby = getlongvalue((object *)b); - if (shiftby == -1L && err_occurred()) - return NULL; - if (shiftby < 0) { - err_setstr(ValueError, "negative shift count"); - return NULL; - } - if (shiftby > MASK) { - err_setstr(ValueError, "outrageous left shift count"); - return NULL; - } - if (shiftby % SHIFT == 0) { - wordshift = shiftby / SHIFT; - loshift = 0; - hishift = SHIFT; - newsize = ABS(a->ob_size) + wordshift; - lomask = MASK; - himask = 0; - } - else { - wordshift = shiftby / SHIFT + 1; - loshift = SHIFT - shiftby%SHIFT; - hishift = shiftby % SHIFT; - newsize = ABS(a->ob_size) + wordshift; - lomask = ((digit)1 << hishift) - 1; - himask = MASK ^ lomask; - } - z = alloclongobject(newsize); - if (z == NULL) - return NULL; - if (a->ob_size < 0) - z->ob_size = -(z->ob_size); - for (i = 0; i < wordshift; i++) - z->ob_digit[i] = 0; - for (i = wordshift, j = 0; i < newsize; i++, j++) { - if (i > 0) - z->ob_digit[i-1] |= - (a->ob_digit[j] << hishift) & himask; - z->ob_digit[i] = - (a->ob_digit[j] >> loshift) & lomask; - } - return (object *) long_normalize(z); -} - - -/* Bitwise and/xor/or operations */ - -#define MAX(x, y) ((x) < (y) ? (y) : (x)) -#define MIN(x, y) ((x) > (y) ? (y) : (x)) - -static object *long_bitwise PROTO((longobject *, int, longobject *)); -static object * -long_bitwise(a, op, b) - longobject *a; - int op; /* '&', '|', '^' */ - longobject *b; -{ - digit maska, maskb; /* 0 or MASK */ - int negz; - int size_a, size_b, size_z; - longobject *z; - int i; - digit diga, digb; - object *v; - - if (a->ob_size < 0) { - a = (longobject *) long_invert(a); - maska = MASK; - } - else { - INCREF(a); - maska = 0; - } - if (b->ob_size < 0) { - b = (longobject *) long_invert(b); - maskb = MASK; - } - else { - INCREF(b); - maskb = 0; - } - - size_a = a->ob_size; - size_b = b->ob_size; - size_z = MAX(size_a, size_b); - z = alloclongobject(size_z); - if (a == NULL || b == NULL || z == NULL) { - XDECREF(a); - XDECREF(b); - XDECREF(z); - return NULL; - } - - negz = 0; - switch (op) { - case '^': - if (maska != maskb) { - maska ^= MASK; - negz = -1; - } - break; - case '&': - if (maska && maskb) { - op = '|'; - maska ^= MASK; - maskb ^= MASK; - negz = -1; - } - break; - case '|': - if (maska || maskb) { - op = '&'; - maska ^= MASK; - maskb ^= MASK; - negz = -1; - } - break; - } - - for (i = 0; i < size_z; ++i) { - diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska; - digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb; - switch (op) { - case '&': z->ob_digit[i] = diga & digb; break; - case '|': z->ob_digit[i] = diga | digb; break; - case '^': z->ob_digit[i] = diga ^ digb; break; - } - } - - DECREF(a); - DECREF(b); - z = long_normalize(z); - if (negz == 0) - return (object *) z; - v = long_invert(z); - DECREF(z); - return v; -} - -static object * -long_and(a, b) - longobject *a; - longobject *b; -{ - return long_bitwise(a, '&', b); -} - -static object * -long_xor(a, b) - longobject *a; - longobject *b; -{ - return long_bitwise(a, '^', b); -} - -static object * -long_or(a, b) - longobject *a; - longobject *b; -{ - return long_bitwise(a, '|', b); -} - -static int -long_coerce(pv, pw) - object **pv; - object **pw; -{ - if (is_intobject(*pw)) { - *pw = newlongobject(getintvalue(*pw)); - INCREF(*pv); - return 0; - } - return 1; /* Can't do it */ -} - -static object * -long_int(v) - object *v; -{ - long x; - x = getlongvalue(v); - if (err_occurred()) - return NULL; - return newintobject(x); -} - -static object * -long_long(v) - object *v; -{ - INCREF(v); - return v; -} - -static object * -long_float(v) - object *v; -{ - return newfloatobject(dgetlongvalue(v)); -} - -static object * -long_oct(v) - object *v; -{ - return long_format(v, 8); -} - -static object * -long_hex(v) - object *v; -{ - return long_format(v, 16); -} - - -#define UF (unaryfunc) -#define BF (binaryfunc) -#define TF (ternaryfunc) -#define IF (inquiry) - -static number_methods long_as_number = { - BF long_add, /*nb_add*/ - BF long_sub, /*nb_subtract*/ - BF long_mul, /*nb_multiply*/ - BF long_div, /*nb_divide*/ - BF long_mod, /*nb_remainder*/ - BF long_divmod, /*nb_divmod*/ - TF long_pow, /*nb_power*/ - UF long_neg, /*nb_negative*/ - UF long_pos, /*tp_positive*/ - UF long_abs, /*tp_absolute*/ - IF long_nonzero,/*tp_nonzero*/ - UF long_invert, /*nb_invert*/ - BF long_lshift, /*nb_lshift*/ - BF long_rshift, /*nb_rshift*/ - BF long_and, /*nb_and*/ - BF long_xor, /*nb_xor*/ - BF long_or, /*nb_or*/ - (int (*) FPROTO((object **, object **))) - (coercion)long_coerce, /*nb_coerce*/ - UF long_int, /*nb_int*/ - UF long_long, /*nb_long*/ - UF long_float, /*nb_float*/ - UF long_oct, /*nb_oct*/ - UF long_hex, /*nb_hex*/ -}; - -typeobject Longtype = { - OB_HEAD_INIT(&Typetype) - 0, - "long int", - sizeof(longobject) - sizeof(digit), - sizeof(digit), - (destructor)long_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - (int (*) FPROTO((object *, object *))) - (cmpfunc)long_compare, /*tp_compare*/ - (reprfunc)long_repr, /*tp_repr*/ - &long_as_number,/*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (long (*) FPROTO((object *))) - (hashfunc)long_hash, /*tp_hash*/ -}; diff --git a/Objects/mappingobject.c b/Objects/mappingobject.c deleted file mode 100644 index 42e68d8007..0000000000 --- a/Objects/mappingobject.c +++ /dev/null @@ -1,845 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Mapping object implementation; using a hash table */ - -/* This file should really be called "dictobject.c", since "mapping" - is the generic name for objects with an unorderred arbitrary key - set (just like lists are sequences), but since it improves (and was - originally derived from) a file by that name I had to change its - name. For the user these objects are still called "dictionaries". */ - -#include "allobjects.h" -#include "modsupport.h" - - -/* -Table of primes suitable as keys, in ascending order. -The first line are the largest primes less than some powers of two, -the second line is the largest prime less than 6000, -the third line is a selection from Knuth, Vol. 3, Sec. 6.1, Table 1, -and the next three lines were suggested by Steve Kirsch. -The final value is a sentinel. -*/ -static long primes[] = { - 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2017, 4093, - 5987, - 9551, 15683, 19609, 31397, - 65521L, 131071L, 262139L, 524287L, 1048573L, 2097143L, - 4194301L, 8388593L, 16777213L, 33554393L, 67108859L, - 134217689L, 268435399L, 536870909L, 1073741789L, - 0 -}; - -/* Object used as dummy key to fill deleted entries */ -static object *dummy; /* Initialized by first call to newmappingobject() */ - -/* -Invariant for entries: when in use, de_value is not NULL and de_key is -not NULL and not dummy; when not in use, de_value is NULL and de_key -is either NULL or dummy. A dummy key value cannot be replaced by -NULL, since otherwise other keys may be lost. -*/ -typedef struct { - long me_hash; - object *me_key; - object *me_value; -} mappingentry; - -/* -To ensure the lookup algorithm terminates, the table size must be a -prime number and there must be at least one NULL key in the table. -The value ma_fill is the number of non-NULL keys; ma_used is the number -of non-NULL, non-dummy keys. -To avoid slowing down lookups on a near-full table, we resize the table -when it is more than half filled. -*/ -typedef struct { - OB_HEAD - int ma_fill; - int ma_used; - int ma_size; - mappingentry *ma_table; -} mappingobject; - -object * -newmappingobject() -{ - register mappingobject *mp; - if (dummy == NULL) { /* Auto-initialize dummy */ - dummy = newstringobject("<dummy key>"); - if (dummy == NULL) - return NULL; - } - mp = NEWOBJ(mappingobject, &Mappingtype); - if (mp == NULL) - return NULL; - mp->ma_size = 0; - mp->ma_table = NULL; - mp->ma_fill = 0; - mp->ma_used = 0; - return (object *)mp; -} - -/* -The basic lookup function used by all operations. -This is essentially Algorithm D from Knuth Vol. 3, Sec. 6.4. -Open addressing is preferred over chaining since the link overhead for -chaining would be substantial (100% with typical malloc overhead). - -First a 32-bit hash value, 'sum', is computed from the key string. -The first character is added an extra time shifted by 8 to avoid hashing -single-character keys (often heavily used variables) too close together. -All arithmetic on sum should ignore overflow. - -The initial probe index is then computed as sum mod the table size. -Subsequent probe indices are incr apart (mod table size), where incr -is also derived from sum, with the additional requirement that it is -relative prime to the table size (i.e., 1 <= incr < size, since the size -is a prime number). My choice for incr is somewhat arbitrary. -*/ -static mappingentry *lookmapping PROTO((mappingobject *, object *, long)); -static mappingentry * -lookmapping(mp, key, hash) - register mappingobject *mp; - object *key; - long hash; -{ - register int i, incr; - register unsigned long sum = (unsigned long) hash; - register mappingentry *freeslot = NULL; - /* We must come up with (i, incr) such that 0 <= i < ma_size - and 0 < incr < ma_size and both are a function of hash */ - i = sum % mp->ma_size; - do { - sum = 3*sum + 1; - incr = sum % mp->ma_size; - } while (incr == 0); - for (;;) { - register mappingentry *ep = &mp->ma_table[i]; - if (ep->me_key == NULL) { - if (freeslot != NULL) - return freeslot; - else - return ep; - } - if (ep->me_key == dummy) { - if (freeslot == NULL) - freeslot = ep; - } - else if (ep->me_hash == hash && - cmpobject(ep->me_key, key) == 0) { - return ep; - } - i = (i + incr) % mp->ma_size; - } -} - -/* -Internal routine to insert a new item into the table. -Used both by the internal resize routine and by the public insert routine. -Eats a reference to key and one to value. -*/ -static void insertmapping PROTO((mappingobject *, object *, long, object *)); -static void -insertmapping(mp, key, hash, value) - register mappingobject *mp; - object *key; - long hash; - object *value; -{ - object *old_value; - register mappingentry *ep; - ep = lookmapping(mp, key, hash); - if (ep->me_value != NULL) { - old_value = ep->me_value; - ep->me_value = value; - DECREF(old_value); /* which **CAN** re-enter */ - DECREF(key); - } - else { - if (ep->me_key == NULL) - mp->ma_fill++; - else - DECREF(ep->me_key); - ep->me_key = key; - ep->me_hash = hash; - ep->me_value = value; - mp->ma_used++; - } -} - -/* -Restructure the table by allocating a new table and reinserting all -items again. When entries have been deleted, the new table may -actually be smaller than the old one. -*/ -static int mappingresize PROTO((mappingobject *)); -static int -mappingresize(mp) - mappingobject *mp; -{ - register int oldsize = mp->ma_size; - register int newsize; - register mappingentry *oldtable = mp->ma_table; - register mappingentry *newtable; - register mappingentry *ep; - register int i; - newsize = mp->ma_size; - for (i = 0; ; i++) { - if (primes[i] <= 0) { - /* Ran out of primes */ - err_nomem(); - return -1; - } - if (primes[i] > mp->ma_used*2) { - newsize = primes[i]; - if (newsize != primes[i]) { - /* Integer truncation */ - err_nomem(); - return -1; - } - break; - } - } - newtable = (mappingentry *) calloc(sizeof(mappingentry), newsize); - if (newtable == NULL) { - err_nomem(); - return -1; - } - mp->ma_size = newsize; - mp->ma_table = newtable; - mp->ma_fill = 0; - mp->ma_used = 0; - - /* Make two passes, so we can avoid decrefs - (and possible side effects) till the table is copied */ - for (i = 0, ep = oldtable; i < oldsize; i++, ep++) { - if (ep->me_value != NULL) - insertmapping(mp,ep->me_key,ep->me_hash,ep->me_value); - } - for (i = 0, ep = oldtable; i < oldsize; i++, ep++) { - if (ep->me_value == NULL) - XDECREF(ep->me_key); - } - - XDEL(oldtable); - return 0; -} - -object * -mappinglookup(op, key) - object *op; - object *key; -{ - long hash; - if (!is_mappingobject(op)) { - err_badcall(); - return NULL; - } - if (((mappingobject *)op)->ma_table == NULL) - return NULL; -#ifdef CACHE_HASH - if (!is_stringobject(key) || (hash = ((stringobject *) key)->ob_shash) == -1) -#endif - hash = hashobject(key); - if (hash == -1) - return NULL; - return lookmapping((mappingobject *)op, key, hash) -> me_value; -} - -int -mappinginsert(op, key, value) - register object *op; - object *key; - object *value; -{ - register mappingobject *mp; - register long hash; - if (!is_mappingobject(op)) { - err_badcall(); - return -1; - } -#ifdef CACHE_HASH - if (!is_stringobject(key) || (hash = ((stringobject *) key)->ob_shash) == -1) -#endif - hash = hashobject(key); - if (hash == -1) - return -1; - mp = (mappingobject *)op; - /* if fill >= 2/3 size, resize */ - if (mp->ma_fill*3 >= mp->ma_size*2) { - if (mappingresize(mp) != 0) { - if (mp->ma_fill+1 > mp->ma_size) - return -1; - } - } - INCREF(value); - INCREF(key); - insertmapping(mp, key, hash, value); - return 0; -} - -int -mappingremove(op, key) - object *op; - object *key; -{ - register mappingobject *mp; - register long hash; - register mappingentry *ep; - object *old_value, *old_key; - - if (!is_mappingobject(op)) { - err_badcall(); - return -1; - } -#ifdef CACHE_HASH - if (!is_stringobject(key) || (hash = ((stringobject *) key)->ob_shash) == -1) -#endif - hash = hashobject(key); - if (hash == -1) - return -1; - mp = (mappingobject *)op; - if (((mappingobject *)op)->ma_table == NULL) - goto empty; - ep = lookmapping(mp, key, hash); - if (ep->me_value == NULL) { - empty: - err_setval(KeyError, key); - return -1; - } - old_key = ep->me_key; - INCREF(dummy); - ep->me_key = dummy; - old_value = ep->me_value; - ep->me_value = NULL; - mp->ma_used--; - DECREF(old_value); - DECREF(old_key); - return 0; -} - -void -mappingclear(op) - object *op; -{ - int i, n; - register mappingentry *table; - mappingobject *mp; - if (!is_mappingobject(op)) - return; - mp = (mappingobject *)op; - table = mp->ma_table; - if (table == NULL) - return; - n = mp->ma_size; - mp->ma_size = mp->ma_used = mp->ma_fill = 0; - mp->ma_table = NULL; - for (i = 0; i < n; i++) { - XDECREF(table[i].me_key); - XDECREF(table[i].me_value); - } - DEL(table); -} - -int -mappinggetnext(op, ppos, pkey, pvalue) - object *op; - int *ppos; - object **pkey; - object **pvalue; -{ - int i; - register mappingobject *mp; - if (!is_dictobject(op)) - return 0; - mp = (mappingobject *)op; - i = *ppos; - if (i < 0) - return 0; - while (i < mp->ma_size && mp->ma_table[i].me_value == NULL) - i++; - *ppos = i+1; - if (i >= mp->ma_size) - return 0; - if (pkey) - *pkey = mp->ma_table[i].me_key; - if (pvalue) - *pvalue = mp->ma_table[i].me_value; - return 1; -} - -/* Methods */ - -static void -mapping_dealloc(mp) - register mappingobject *mp; -{ - register int i; - register mappingentry *ep; - for (i = 0, ep = mp->ma_table; i < mp->ma_size; i++, ep++) { - if (ep->me_key != NULL) - DECREF(ep->me_key); - if (ep->me_value != NULL) - DECREF(ep->me_value); - } - XDEL(mp->ma_table); - DEL(mp); -} - -static int -mapping_print(mp, fp, flags) - register mappingobject *mp; - register FILE *fp; - register int flags; -{ - register int i; - register int any; - register mappingentry *ep; - fprintf(fp, "{"); - any = 0; - for (i = 0, ep = mp->ma_table; i < mp->ma_size; i++, ep++) { - if (ep->me_value != NULL) { - if (any++ > 0) - fprintf(fp, ", "); - if (printobject((object *)ep->me_key, fp, 0) != 0) - return -1; - fprintf(fp, ": "); - if (printobject(ep->me_value, fp, 0) != 0) - return -1; - } - } - fprintf(fp, "}"); - return 0; -} - -static object * -mapping_repr(mp) - mappingobject *mp; -{ - auto object *v; - object *sepa, *colon; - register int i; - register int any; - register mappingentry *ep; - v = newstringobject("{"); - sepa = newstringobject(", "); - colon = newstringobject(": "); - any = 0; - for (i = 0, ep = mp->ma_table; i < mp->ma_size && v; i++, ep++) { - if (ep->me_value != NULL) { - if (any++) - joinstring(&v, sepa); - joinstring_decref(&v, reprobject(ep->me_key)); - joinstring(&v, colon); - joinstring_decref(&v, reprobject(ep->me_value)); - } - } - joinstring_decref(&v, newstringobject("}")); - XDECREF(sepa); - XDECREF(colon); - return v; -} - -static int -mapping_length(mp) - mappingobject *mp; -{ - return mp->ma_used; -} - -static object * -mapping_subscript(mp, key) - mappingobject *mp; - register object *key; -{ - object *v; - long hash; - if (mp->ma_table == NULL) { - err_setval(KeyError, key); - return NULL; - } -#ifdef CACHE_HASH - if (!is_stringobject(key) || (hash = ((stringobject *) key)->ob_shash) == -1) -#endif - hash = hashobject(key); - if (hash == -1) - return NULL; - v = lookmapping(mp, key, hash) -> me_value; - if (v == NULL) - err_setval(KeyError, key); - else - INCREF(v); - return v; -} - -static int -mapping_ass_sub(mp, v, w) - mappingobject *mp; - object *v, *w; -{ - if (w == NULL) - return mappingremove((object *)mp, v); - else - return mappinginsert((object *)mp, v, w); -} - -static mapping_methods mapping_as_mapping = { - (inquiry)mapping_length, /*mp_length*/ - (binaryfunc)mapping_subscript, /*mp_subscript*/ - (objobjargproc)mapping_ass_sub, /*mp_ass_subscript*/ -}; - -static object * -mapping_keys(mp, args) - register mappingobject *mp; - object *args; -{ - register object *v; - register int i, j; - if (!getnoarg(args)) - return NULL; - v = newlistobject(mp->ma_used); - if (v == NULL) - return NULL; - for (i = 0, j = 0; i < mp->ma_size; i++) { - if (mp->ma_table[i].me_value != NULL) { - object *key = mp->ma_table[i].me_key; - INCREF(key); - setlistitem(v, j, key); - j++; - } - } - return v; -} - -static object * -mapping_values(mp, args) - register mappingobject *mp; - object *args; -{ - register object *v; - register int i, j; - if (!getnoarg(args)) - return NULL; - v = newlistobject(mp->ma_used); - if (v == NULL) - return NULL; - for (i = 0, j = 0; i < mp->ma_size; i++) { - if (mp->ma_table[i].me_value != NULL) { - object *value = mp->ma_table[i].me_value; - INCREF(value); - setlistitem(v, j, value); - j++; - } - } - return v; -} - -static object * -mapping_items(mp, args) - register mappingobject *mp; - object *args; -{ - register object *v; - register int i, j; - if (!getnoarg(args)) - return NULL; - v = newlistobject(mp->ma_used); - if (v == NULL) - return NULL; - for (i = 0, j = 0; i < mp->ma_size; i++) { - if (mp->ma_table[i].me_value != NULL) { - object *key = mp->ma_table[i].me_key; - object *value = mp->ma_table[i].me_value; - object *item = newtupleobject(2); - if (item == NULL) { - DECREF(v); - return NULL; - } - INCREF(key); - settupleitem(item, 0, key); - INCREF(value); - settupleitem(item, 1, value); - setlistitem(v, j, item); - j++; - } - } - return v; -} - -int -getmappingsize(mp) - object *mp; -{ - if (mp == NULL || !is_mappingobject(mp)) { - err_badcall(); - return 0; - } - return ((mappingobject *)mp)->ma_used; -} - -object * -getmappingkeys(mp) - object *mp; -{ - if (mp == NULL || !is_mappingobject(mp)) { - err_badcall(); - return NULL; - } - return mapping_keys((mappingobject *)mp, (object *)NULL); -} - -object * -getmappingvalues(mp) - object *mp; -{ - if (mp == NULL || !is_mappingobject(mp)) { - err_badcall(); - return NULL; - } - return mapping_values((mappingobject *)mp, (object *)NULL); -} - -object * -getmappingitems(mp) - object *mp; -{ - if (mp == NULL || !is_mappingobject(mp)) { - err_badcall(); - return NULL; - } - return mapping_items((mappingobject *)mp, (object *)NULL); -} - -static int -mapping_compare(a, b) - mappingobject *a, *b; -{ - object *akeys, *bkeys; - int i, n, res; - if (a == b) - return 0; - if (a->ma_used == 0) { - if (b->ma_used != 0) - return -1; - else - return 0; - } - else { - if (b->ma_used == 0) - return 1; - } - akeys = mapping_keys(a, (object *)NULL); - bkeys = mapping_keys(b, (object *)NULL); - if (akeys == NULL || bkeys == NULL) { - /* Oops, out of memory -- what to do? */ - /* For now, sort on address! */ - XDECREF(akeys); - XDECREF(bkeys); - if (a < b) - return -1; - else - return 1; - } - sortlist(akeys); - sortlist(bkeys); - n = a->ma_used < b->ma_used ? a->ma_used : b->ma_used; /* smallest */ - res = 0; - for (i = 0; i < n; i++) { - object *akey, *bkey, *aval, *bval; - long ahash, bhash; - akey = getlistitem(akeys, i); - bkey = getlistitem(bkeys, i); - res = cmpobject(akey, bkey); - if (res != 0) - break; -#ifdef CACHE_HASH - if (!is_stringobject(akey) || (ahash = ((stringobject *) akey)->ob_shash) == -1) -#endif - ahash = hashobject(akey); - if (ahash == -1) - err_clear(); /* Don't want errors here */ -#ifdef CACHE_HASH - if (!is_stringobject(bkey) || (bhash = ((stringobject *) bkey)->ob_shash) == -1) -#endif - bhash = hashobject(bkey); - if (bhash == -1) - err_clear(); /* Don't want errors here */ - aval = lookmapping(a, akey, ahash) -> me_value; - bval = lookmapping(b, bkey, bhash) -> me_value; - res = cmpobject(aval, bval); - if (res != 0) - break; - } - if (res == 0) { - if (a->ma_used < b->ma_used) - res = -1; - else if (a->ma_used > b->ma_used) - res = 1; - } - DECREF(akeys); - DECREF(bkeys); - return res; -} - -static object * -mapping_has_key(mp, args) - register mappingobject *mp; - object *args; -{ - object *key; - long hash; - register long ok; - if (!getargs(args, "O", &key)) - return NULL; -#ifdef CACHE_HASH - if (!is_stringobject(key) || (hash = ((stringobject *) key)->ob_shash) == -1) -#endif - hash = hashobject(key); - if (hash == -1) - return NULL; - ok = mp->ma_size != 0 && lookmapping(mp, key, hash)->me_value != NULL; - return newintobject(ok); -} - -static struct methodlist mapp_methods[] = { - {"has_key", (method)mapping_has_key}, - {"items", (method)mapping_items}, - {"keys", (method)mapping_keys}, - {"values", (method)mapping_values}, - {NULL, NULL} /* sentinel */ -}; - -static object * -mapping_getattr(mp, name) - mappingobject *mp; - char *name; -{ - return findmethod(mapp_methods, (object *)mp, name); -} - -typeobject Mappingtype = { - OB_HEAD_INIT(&Typetype) - 0, - "dictionary", - sizeof(mappingobject), - 0, - (destructor)mapping_dealloc, /*tp_dealloc*/ - (printfunc)mapping_print, /*tp_print*/ - (getattrfunc)mapping_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)mapping_compare, /*tp_compare*/ - (reprfunc)mapping_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - &mapping_as_mapping, /*tp_as_mapping*/ -}; - -/* For backward compatibility with old dictionary interface */ - -static object *last_name_object; -static char *last_name_char; /* NULL or == getstringvalue(last_name_object) */ - -object * -getattro(v, name) - object *v; - object *name; -{ - if (name != last_name_object) { - XDECREF(last_name_object); - INCREF(name); - last_name_object = name; - last_name_char = getstringvalue(name); - } - return getattr(v, last_name_char); -} - -int -setattro(v, name, value) - object *v; - object *name; - object *value; -{ - if (name != last_name_object) { - XDECREF(last_name_object); - INCREF(name); - last_name_object = name; - last_name_char = getstringvalue(name); - } - return setattr(v, last_name_char, value); -} - -object * -dictlookup(v, key) - object *v; - char *key; -{ - if (key != last_name_char) { - XDECREF(last_name_object); - last_name_object = newstringobject(key); - if (last_name_object == NULL) { - last_name_char = NULL; - return NULL; - } - last_name_char = getstringvalue(last_name_object); - } - return mappinglookup(v, last_name_object); -} - -int -dictinsert(v, key, item) - object *v; - char *key; - object *item; -{ - if (key != last_name_char) { - XDECREF(last_name_object); - last_name_object = newstringobject(key); - if (last_name_object == NULL) { - last_name_char = NULL; - return -1; - } - last_name_char = getstringvalue(last_name_object); - } - return mappinginsert(v, last_name_object, item); -} - -int -dictremove(v, key) - object *v; - char *key; -{ - if (key != last_name_char) { - XDECREF(last_name_object); - last_name_object = newstringobject(key); - if (last_name_object == NULL) { - last_name_char = NULL; - return -1; - } - last_name_char = getstringvalue(last_name_object); - } - return mappingremove(v, last_name_object); -} diff --git a/Objects/methodobject.c b/Objects/methodobject.c deleted file mode 100644 index 1444924b69..0000000000 --- a/Objects/methodobject.c +++ /dev/null @@ -1,260 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Method object implementation */ - -#include "allobjects.h" - -#include "token.h" - -typedef struct { - OB_HEAD - struct methodlist *m_ml; - object *m_self; -} methodobject; - -object * -newmethodobject(ml, self) - struct methodlist *ml; - object *self; -{ - methodobject *op = NEWOBJ(methodobject, &Methodtype); - if (op != NULL) { - op->m_ml = ml; - XINCREF(self); - op->m_self = self; - } - return (object *)op; -} - -method -getmethod(op) - object *op; -{ - if (!is_methodobject(op)) { - err_badcall(); - return NULL; - } - return ((methodobject *)op) -> m_ml -> ml_meth; -} - -object * -getself(op) - object *op; -{ - if (!is_methodobject(op)) { - err_badcall(); - return NULL; - } - return ((methodobject *)op) -> m_self; -} - -int -getflags(op) - object *op; -{ - if (!is_methodobject(op)) { - err_badcall(); - return -1; - } - return ((methodobject *)op) -> m_ml -> ml_flags; -} - -/* Methods (the standard built-in methods, that is) */ - -static void -meth_dealloc(m) - methodobject *m; -{ - XDECREF(m->m_self); - free((char *)m); -} - -static object * -meth_getattr(m, name) - methodobject *m; - char *name; -{ - if (strcmp(name, "__name__") == 0) { - return newstringobject(m->m_ml->ml_name); - } - if (strcmp(name, "__doc__") == 0) { - char *doc = m->m_ml->ml_doc; - if (doc != NULL) - return newstringobject(doc); - INCREF(None); - return None; - } - if (strcmp(name, "__self__") == 0) { - object *self; - if (getrestricted()) { - err_setstr(RuntimeError, - "method.__self__ not accessible in restricted mode"); - return NULL; - } - self = m->m_self; - if (self == NULL) - self = None; - INCREF(self); - return self; - } - if (strcmp(name, "__members__") == 0) { - return mkvalue("[sss]", "__doc__", "__name__", "__self__"); - } - err_setstr(AttributeError, name); - return NULL; -} - -static object * -meth_repr(m) - methodobject *m; -{ - char buf[200]; - if (m->m_self == NULL) - sprintf(buf, "<built-in function %.80s>", m->m_ml->ml_name); - else - sprintf(buf, - "<built-in method %.80s of %.80s object at %lx>", - m->m_ml->ml_name, m->m_self->ob_type->tp_name, - (long)m->m_self); - return newstringobject(buf); -} - -static int -meth_compare(a, b) - methodobject *a, *b; -{ - if (a->m_self != b->m_self) - return cmpobject(a->m_self, b->m_self); - if (a->m_ml->ml_meth == b->m_ml->ml_meth) - return 0; - if (strcmp(a->m_ml->ml_name, b->m_ml->ml_name) < 0) - return -1; - else - return 1; -} - -static long -meth_hash(a) - methodobject *a; -{ - long x; - if (a->m_self == NULL) - x = 0; - else { - x = hashobject(a->m_self); - if (x == -1) - return -1; - } - return x ^ (long) a->m_ml->ml_meth; -} - -typeobject Methodtype = { - OB_HEAD_INIT(&Typetype) - 0, - "builtin_function_or_method", - sizeof(methodobject), - 0, - (destructor)meth_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)meth_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)meth_compare, /*tp_compare*/ - (reprfunc)meth_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)meth_hash, /*tp_hash*/ -}; - -/* List all methods in a chain -- helper for findmethodinchain */ - -static object * -listmethodchain(chain) - struct methodchain *chain; -{ - struct methodchain *c; - struct methodlist *ml; - int i, n; - object *v; - - n = 0; - for (c = chain; c != NULL; c = c->link) { - for (ml = c->methods; ml->ml_name != NULL; ml++) - n++; - } - v = newlistobject(n); - if (v == NULL) - return NULL; - i = 0; - for (c = chain; c != NULL; c = c->link) { - for (ml = c->methods; ml->ml_name != NULL; ml++) { - setlistitem(v, i, newstringobject(ml->ml_name)); - i++; - } - } - if (err_occurred()) { - DECREF(v); - return NULL; - } - sortlist(v); - return v; -} - -/* Find a method in a method chain */ - -object * -findmethodinchain(chain, self, name) - struct methodchain *chain; - object *self; - char *name; -{ - if (strcmp(name, "__methods__") == 0) - return listmethodchain(chain); - while (chain != NULL) { - struct methodlist *ml = chain->methods; - for (; ml->ml_name != NULL; ml++) { - if (name[0] == ml->ml_name[0] && - strcmp(name+1, ml->ml_name+1) == 0) - return newmethodobject(ml, self); - } - chain = chain->link; - } - err_setstr(AttributeError, name); - return NULL; -} - -/* Find a method in a single method list */ - -object * -findmethod(methods, self, name) - struct methodlist *methods; - object *self; - char *name; -{ - struct methodchain chain; - chain.methods = methods; - chain.link = NULL; - return findmethodinchain(&chain, self, name); -} diff --git a/Objects/moduleobject.c b/Objects/moduleobject.c deleted file mode 100644 index 7377a98235..0000000000 --- a/Objects/moduleobject.c +++ /dev/null @@ -1,175 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Module object implementation */ - -#include "allobjects.h" -#include "ceval.h" - -typedef struct { - OB_HEAD - object *md_dict; -} moduleobject; - -object * -newmoduleobject(name) - char *name; -{ - moduleobject *m; - object *nameobj; - m = NEWOBJ(moduleobject, &Moduletype); - if (m == NULL) - return NULL; - nameobj = newstringobject(name); - m->md_dict = newdictobject(); - if (m->md_dict == NULL || nameobj == NULL) - goto fail; - if (dictinsert(m->md_dict, "__name__", nameobj) != 0) - goto fail; - if (dictinsert(m->md_dict, "__doc__", None) != 0) - goto fail; - DECREF(nameobj); - return (object *)m; - - fail: - XDECREF(nameobj); - DECREF(m); - return NULL; -} - -object * -getmoduledict(m) - object *m; -{ - if (!is_moduleobject(m)) { - err_badcall(); - return NULL; - } - return ((moduleobject *)m) -> md_dict; -} - -char * -getmodulename(m) - object *m; -{ - object *nameobj; - if (!is_moduleobject(m)) { - err_badarg(); - return NULL; - } - nameobj = dictlookup(((moduleobject *)m)->md_dict, "__name__"); - if (nameobj == NULL || !is_stringobject(nameobj)) { - err_setstr(SystemError, "nameless module"); - return NULL; - } - return getstringvalue(nameobj); -} - -/* Methods */ - -static void -module_dealloc(m) - moduleobject *m; -{ - if (m->md_dict != NULL) { - mappingclear(m->md_dict); - DECREF(m->md_dict); - } - free((char *)m); -} - -static object * -module_repr(m) - moduleobject *m; -{ - char buf[100]; - char *name = getmodulename((object *)m); - if (name == NULL) { - err_clear(); - name = "?"; - } - sprintf(buf, "<module '%.80s'>", name); - return newstringobject(buf); -} - -static object * -module_getattr(m, name) - moduleobject *m; - char *name; -{ - object *res; - if (strcmp(name, "__dict__") == 0) { - INCREF(m->md_dict); - return m->md_dict; - } - res = dictlookup(m->md_dict, name); - if (res == NULL) - err_setstr(AttributeError, name); - else { - if (is_accessobject(res)) - res = getaccessvalue(res, getglobals()); - else - INCREF(res); - } - return res; -} - -static int -module_setattr(m, name, v) - moduleobject *m; - char *name; - object *v; -{ - object *ac; - if (name[0] == '_' && strcmp(name, "__dict__") == 0) { - err_setstr(TypeError, "read-only special attribute"); - return -1; - } - ac = dictlookup(m->md_dict, name); - if (ac != NULL && is_accessobject(ac)) - return setaccessvalue(ac, getglobals(), v); - if (v == NULL) { - int rv = dictremove(m->md_dict, name); - if (rv < 0) - err_setstr(AttributeError, - "delete non-existing module attribute"); - return rv; - } - else - return dictinsert(m->md_dict, name, v); -} - -typeobject Moduletype = { - OB_HEAD_INIT(&Typetype) - 0, /*ob_size*/ - "module", /*tp_name*/ - sizeof(moduleobject), /*tp_size*/ - 0, /*tp_itemsize*/ - (destructor)module_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)module_getattr, /*tp_getattr*/ - (setattrfunc)module_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - (reprfunc)module_repr, /*tp_repr*/ -}; diff --git a/Objects/object.c b/Objects/object.c deleted file mode 100644 index 79943897bc..0000000000 --- a/Objects/object.c +++ /dev/null @@ -1,582 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Generic object operations; and implementation of None (NoObject) */ - -#include "allobjects.h" - -#if defined( Py_TRACE_REFS ) || defined( Py_REF_DEBUG ) -long ref_total; -#endif - -/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros. - These are used by the individual routines for object creation. - Do not call them otherwise, they do not initialize the object! */ - -#ifdef COUNT_ALLOCS -static typeobject *type_list; -extern int tuple_zero_allocs, fast_tuple_allocs; -extern int quick_int_allocs, quick_neg_int_allocs; -extern int null_strings, one_strings; -void -dump_counts() -{ - typeobject *tp; - - for (tp = type_list; tp; tp = tp->tp_next) - fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n", - tp->tp_name, tp->tp_alloc, tp->tp_free, - tp->tp_maxalloc); - fprintf(stderr, "fast tuple allocs: %d, empty: %d\n", - fast_tuple_allocs, tuple_zero_allocs); - fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n", - quick_int_allocs, quick_neg_int_allocs); - fprintf(stderr, "null strings: %d, 1-strings: %d\n", - null_strings, one_strings); -} - -PyObject * -get_counts() -{ - PyTypeObject *tp; - PyObject *result; - PyObject *v; - - result = PyList_New(0); - if (result == NULL) - return NULL; - for (tp = type_list; tp; tp = tp->tp_next) { - v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_alloc, - tp->tp_free, tp->tp_maxalloc); - if (v == NULL) { - Py_DECREF(result); - return NULL; - } - if (PyList_Append(result, v) < 0) { - Py_DECREF(v); - Py_DECREF(result); - return NULL; - } - Py_DECREF(v); - } - return result; -} - -void -inc_count(tp) - typeobject *tp; -{ - if (tp->tp_alloc == 0) { - /* first time; insert in linked list */ - if (tp->tp_next != NULL) /* sanity check */ - fatal("XXX inc_count sanity check"); - tp->tp_next = type_list; - type_list = tp; - } - tp->tp_alloc++; - if (tp->tp_alloc - tp->tp_free > tp->tp_maxalloc) - tp->tp_maxalloc = tp->tp_alloc - tp->tp_free; -} -#endif - -object * -newobject(tp) - typeobject *tp; -{ - object *op = (object *) malloc(tp->tp_basicsize); - if (op == NULL) - return err_nomem(); - op->ob_type = tp; - NEWREF(op); - return op; -} - -varobject * -newvarobject(tp, size) - typeobject *tp; - int size; -{ - varobject *op = (varobject *) - malloc(tp->tp_basicsize + size * tp->tp_itemsize); - if (op == NULL) - return (varobject *)err_nomem(); - op->ob_type = tp; - op->ob_size = size; - NEWREF(op); - return op; -} - -int -printobject(op, fp, flags) - object *op; - FILE *fp; - int flags; -{ - int ret = 0; - if (sigcheck()) - return -1; - if (op == NULL) { - fprintf(fp, "<nil>"); - } - else { - if (op->ob_refcnt <= 0) - fprintf(fp, "<refcnt %u at %lx>", - op->ob_refcnt, (long)op); - else if (op->ob_type->tp_print == NULL) { - if (op->ob_type->tp_repr == NULL) { - fprintf(fp, "<%s object at %lx>", - op->ob_type->tp_name, (long)op); - } - else { - object *s; - if (flags & PRINT_RAW) - s = strobject(op); - else - s = reprobject(op); - if (s == NULL) - ret = -1; - else if (!is_stringobject(s)) { - err_setstr(TypeError, - "repr not string"); - ret = -1; - } - else { - fprintf(fp, "%s", getstringvalue(s)); - } - XDECREF(s); - } - } - else - ret = (*op->ob_type->tp_print)(op, fp, flags); - } - if (ret == 0) { - if (ferror(fp)) { - err_errno(IOError); - clearerr(fp); - ret = -1; - } - } - return ret; -} - -object * -reprobject(v) - object *v; -{ - if (sigcheck()) - return NULL; - if (v == NULL) - return newstringobject("<NULL>"); - else if (v->ob_type->tp_repr == NULL) { - char buf[120]; - sprintf(buf, "<%.80s object at %lx>", - v->ob_type->tp_name, (long)v); - return newstringobject(buf); - } - else - return (*v->ob_type->tp_repr)(v); -} - -object * -strobject(v) - object *v; -{ - if (v == NULL) - return newstringobject("<NULL>"); - else if (is_stringobject(v)) { - INCREF(v); - return v; - } - else if (v->ob_type->tp_str != NULL) - return (*v->ob_type->tp_str)(v); - else { - object *func; - object *res; - if (!is_instanceobject(v) || - (func = getattr(v, "__str__")) == NULL) { - err_clear(); - return reprobject(v); - } - res = call_object(func, (object *)NULL); - DECREF(func); - return res; - } -} - -static object * -do_cmp(v, w) - object *v, *w; -{ - /* __rcmp__ actually won't be called unless __cmp__ isn't defined, - because the check in cmpobject() reverses the objects first. - This is intentional -- it makes no sense to define cmp(x,y) different - than -cmp(y,x). */ - if (is_instanceobject(v) || is_instanceobject(w)) - return instancebinop(v, w, "__cmp__", "__rcmp__", do_cmp); - return newintobject((long)cmpobject(v, w)); -} - -int -cmpobject(v, w) - object *v, *w; -{ - typeobject *tp; - if (v == w) - return 0; - if (v == NULL) - return -1; - if (w == NULL) - return 1; - if (is_instanceobject(v) || is_instanceobject(w)) { - object *res; - int c; - if (!is_instanceobject(v)) - return -cmpobject(w, v); - res = do_cmp(v, w); - if (res == NULL) { - err_clear(); - return (v < w) ? -1 : 1; - } - if (!is_intobject(res)) { - DECREF(res); - return (v < w) ? -1 : 1; - } - c = getintvalue(res); - DECREF(res); - return (c < 0) ? -1 : (c > 0) ? 1 : 0; - } - if ((tp = v->ob_type) != w->ob_type) { - if (tp->tp_as_number != NULL && - w->ob_type->tp_as_number != NULL) { - if (coerce(&v, &w) != 0) { - err_clear(); - /* XXX Should report the error, - XXX but the interface isn't there... */ - } - else { - int cmp = (*v->ob_type->tp_compare)(v, w); - DECREF(v); - DECREF(w); - return cmp; - } - } - return strcmp(tp->tp_name, w->ob_type->tp_name); - } - if (tp->tp_compare == NULL) - return (v < w) ? -1 : 1; - return (*tp->tp_compare)(v, w); -} - -long -hashobject(v) - object *v; -{ - typeobject *tp = v->ob_type; - if (tp->tp_hash != NULL) - return (*tp->tp_hash)(v); - if (tp->tp_compare == NULL) - return (long) v; /* Use address as hash value */ - /* If there's a cmp but no hash defined, the object can't be hashed */ - err_setstr(TypeError, "unhashable type"); - return -1; -} - -object * -getattr(v, name) - object *v; - char *name; -{ - if (v->ob_type->tp_getattr == NULL) { - err_setstr(AttributeError, "attribute-less object"); - return NULL; - } - else { - return (*v->ob_type->tp_getattr)(v, name); - } -} - -int -hasattr(v, name) - object *v; - char *name; -{ - object *res = getattr(v, name); - if (res != NULL) { - DECREF(res); - return 1; - } - err_clear(); - return 0; -} - -int -setattr(v, name, w) - object *v; - char *name; - object *w; -{ - if (v->ob_type->tp_setattr == NULL) { - if (v->ob_type->tp_getattr == NULL) - err_setstr(TypeError, - "attribute-less object (assign or del)"); - else - err_setstr(TypeError, - "object has read-only attributes"); - return -1; - } - else { - return (*v->ob_type->tp_setattr)(v, name, w); - } -} - -/* Test a value used as condition, e.g., in a for or if statement. - Return -1 if an error occurred */ - -int -testbool(v) - object *v; -{ - int res; - if (v == None) - res = 0; - else if (v->ob_type->tp_as_number != NULL) - res = (*v->ob_type->tp_as_number->nb_nonzero)(v); - else if (v->ob_type->tp_as_mapping != NULL) - res = (*v->ob_type->tp_as_mapping->mp_length)(v); - else if (v->ob_type->tp_as_sequence != NULL) - res = (*v->ob_type->tp_as_sequence->sq_length)(v); - else - res = 1; - if (res > 0) - res = 1; - return res; -} - -/* Coerce two numeric types to the "larger" one. - Increment the reference count on each argument. - Return -1 and raise an exception if no coercion is possible - (and then no reference count is incremented). -*/ - -int -coerce(pv, pw) - object **pv, **pw; -{ - register object *v = *pv; - register object *w = *pw; - int res; - - if (v->ob_type == w->ob_type && !is_instanceobject(v)) { - INCREF(v); - INCREF(w); - return 0; - } - if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) { - res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw); - if (res <= 0) - return res; - } - if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) { - res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv); - if (res <= 0) - return res; - } - err_setstr(TypeError, "number coercion failed"); - return -1; -} - - -/* Test whether an object can be called */ - -int -callable(x) - object *x; -{ - if (x == NULL) - return 0; - if (x->ob_type->tp_call != NULL || - is_funcobject(x) || - is_instancemethodobject(x) || - is_methodobject(x) || - is_classobject(x)) - return 1; - if (is_instanceobject(x)) { - object *call = getattr(x, "__call__"); - if (call == NULL) { - err_clear(); - return 0; - } - /* Could test recursively but don't, for fear of endless - recursion if some joker sets self.__call__ = self */ - DECREF(call); - return 1; - } - return 0; -} - - -/* -NoObject is usable as a non-NULL undefined value, used by the macro None. -There is (and should be!) no way to create other objects of this type, -so there is exactly one (which is indestructible, by the way). -*/ - -/* ARGSUSED */ -static object * -none_repr(op) - object *op; -{ - return newstringobject("None"); -} - -static typeobject Notype = { - OB_HEAD_INIT(&Typetype) - 0, - "None", - 0, - 0, - 0, /*tp_dealloc*/ /*never called*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - (reprfunc)none_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ -}; - -object NoObject = { - OB_HEAD_INIT(&Notype) -}; - - -#ifdef Py_TRACE_REFS - -static object refchain = {&refchain, &refchain}; - -NEWREF(op) - object *op; -{ - ref_total++; - op->ob_refcnt = 1; - op->_ob_next = refchain._ob_next; - op->_ob_prev = &refchain; - refchain._ob_next->_ob_prev = op; - refchain._ob_next = op; -#ifdef COUNT_ALLOCS - inc_count(op->ob_type); -#endif -} - -UNREF(op) - register object *op; -{ - register object *p; - if (op->ob_refcnt < 0) - fatal("UNREF negative refcnt"); - if (op == &refchain || - op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) - fatal("UNREF invalid object"); -#ifdef SLOW_UNREF_CHECK - for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { - if (p == op) - break; - } - if (p == &refchain) /* Not found */ - fatal("UNREF unknown object"); -#endif - op->_ob_next->_ob_prev = op->_ob_prev; - op->_ob_prev->_ob_next = op->_ob_next; - op->_ob_next = op->_ob_prev = NULL; -#ifdef COUNT_ALLOCS - op->ob_type->tp_free++; -#endif -} - -DELREF(op) - object *op; -{ - destructor dealloc = op->ob_type->tp_dealloc; - UNREF(op); - op->ob_type = NULL; - (*dealloc)(op); -} - -_Py_PrintReferences(fp) - FILE *fp; -{ - object *op; - fprintf(fp, "Remaining objects (except strings referenced once):\n"); - for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { - if (op->ob_refcnt == 1 && is_stringobject(op)) - continue; /* Will be printed elsewhere */ - fprintf(fp, "[%d] ", op->ob_refcnt); - if (printobject(op, fp, 0) != 0) - err_clear(); - putc('\n', fp); - } -} - -PyObject * -_Py_GetObjects(self, args) - PyObject *self; - PyObject *args; -{ - int i, n; - PyObject *t = NULL; - PyObject *res, *op; - - if (!PyArg_ParseTuple(args, "i|O", &n, &t)) - return NULL; - op = refchain._ob_next; - res = PyList_New(0); - if (res == NULL) - return NULL; - for (i = 0; (n == 0 || i < n) && op != &refchain; i++) { - while (op == self || op == args || op == res || op == t || - t != NULL && op->ob_type != (PyTypeObject *) t) { - op = op->_ob_next; - if (op == &refchain) - return res; - } - if (PyList_Append(res, op) < 0) { - Py_DECREF(res); - return NULL; - } - op = op->_ob_next; - } - return res; -} - -#endif - - -/* Hack to force loading of cobject.o */ -static PyTypeObject *cobject_hack = &PyCObject_Type; - - -/* Hack to force loading of abstract.o */ -static int (*abstract_hack) FPROTO((PyObject *)) = &PyObject_Length; diff --git a/Objects/rangeobject.c b/Objects/rangeobject.c deleted file mode 100644 index dcb7a19828..0000000000 --- a/Objects/rangeobject.c +++ /dev/null @@ -1,257 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Range object implementation */ - -#include "allobjects.h" - -typedef struct { - OB_HEAD - long start; - long step; - long len; - int reps; -} rangeobject; - - -object * -newrangeobject(start, len, step, reps) - long start, len, step; - int reps; -{ - rangeobject *obj = (rangeobject *) newobject(&Rangetype); - - obj->start = start; - obj->len = len; - obj->step = step; - obj->reps = reps; - - return (object *) obj; -} - -static void -range_dealloc(r) - rangeobject *r; -{ - DEL(r); -} - -static object * -range_item(r, i) - rangeobject *r; - int i; -{ - if (i < 0 || i >= r->len * r->reps) { - err_setstr(IndexError, "range object index out of range"); - return NULL; - } - - return newintobject(r->start + (i % r->len) * r->step); -} - -static int -range_length(r) - rangeobject *r; -{ - return r->len * r->reps; -} - -static int -range_print(r, fp, flags) - rangeobject *r; - FILE *fp; - int flags; -{ - int i, j; - - fprintf(fp, "("); - for (i = 0; i < r->reps; ++i) - for (j = 0; j < r->len; ++j) { - if (j > 0 || i > 0) - fprintf(fp, ", "); - - fprintf(fp, "%d", r->start + j * r->step); - } - - if (r->len == 1 && r->reps == 1) - fprintf(fp, ","); - fprintf(fp, ")"); - return 0; -} - -static object * -range_repr(r) - rangeobject *r; -{ - char buf[80]; - sprintf(buf, "(xrange(%ld, %ld, %ld) * %d)", - r->start, - r->start + r->len * r->step, - r->step, - r->reps); - return newstringobject(buf); -} - -static object * -range_concat(r, obj) - rangeobject *r; - object *obj; -{ - err_setstr(TypeError, "cannot concatenate range objects"); - return NULL; -} - -static object * -range_repeat(r, n) - rangeobject *r; - int n; -{ - if (n < 0) - return (object *) newrangeobject(0, 0, 1, 1); - - else if (n == 1) { - INCREF(r); - return (object *) r; - } - - else - return (object *) newrangeobject( - r->start, - r->len, - r->step, - r->reps * n); -} - -static int -range_compare(r1, r2) - rangeobject *r1, *r2; -{ - if (r1->start != r2->start) - return r1->start - r2->start; - - else if (r1->step != r2->step) - return r1->step - r2->step; - - else if (r1->len != r2->len) - return r1->len - r2->len; - - else - return r1->reps - r2->reps; -} - -static object * -range_slice(r, low, high) - rangeobject *r; - int low, high; -{ - if (r->reps != 1) { - err_setstr(TypeError, "cannot slice a replicated range"); - return NULL; - } - if (low < 0) - low = 0; - else if (low > r->len) - low = r->len; - if (high < 0) - high = 0; - if (high < low) - high = low; - else if (high > r->len) - high = r->len; - - if (low == 0 && high == r->len) { - INCREF(r); - return (object *) r; - } - - return (object *) newrangeobject( - low * r->step + r->start, - high - low, - r->step, - 1); -} - -static object * -range_tolist(self, args) -rangeobject *self; -object *args; -{ - object *thelist; - int j; - int len = self->len * self->reps; - - if (! getargs(args, "")) - return NULL; - - if ((thelist = newlistobject(len)) == NULL) - return NULL; - - for (j = 0; j < len; ++j) - if ((setlistitem(thelist, j, - (object *) newintobject( - self->start + (j % self->len) * self->step))) < 0) - return NULL; - - return thelist; -} - -static object * -range_getattr(r, name) - rangeobject *r; - char *name; -{ - static struct methodlist range_methods[] = { - {"tolist", (method)range_tolist}, - {NULL, NULL} - }; - - return findmethod(range_methods, (object *) r, name); -} - -static sequence_methods range_as_sequence = { - (inquiry)range_length, /*sq_length*/ - (binaryfunc)range_concat, /*sq_concat*/ - (intargfunc)range_repeat, /*sq_repeat*/ - (intargfunc)range_item, /*sq_item*/ - (intintargfunc)range_slice, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ -}; - -typeobject Rangetype = { - OB_HEAD_INIT(&Typetype) - 0, /* Number of items for varobject */ - "xrange", /* Name of this type */ - sizeof(rangeobject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)range_dealloc, /*tp_dealloc*/ - (printfunc)range_print, /*tp_print*/ - (getattrfunc)range_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)range_compare, /*tp_compare*/ - (reprfunc)range_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - &range_as_sequence, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ -}; diff --git a/Objects/stringobject.c b/Objects/stringobject.c deleted file mode 100644 index 1e11c503cb..0000000000 --- a/Objects/stringobject.c +++ /dev/null @@ -1,923 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* String object implementation */ - -#include "allobjects.h" - -#include <ctype.h> - -#ifdef COUNT_ALLOCS -int null_strings, one_strings; -#endif - -#ifdef HAVE_LIMITS_H -#include <limits.h> -#else -#ifndef UCHAR_MAX -#define UCHAR_MAX 255 -#endif -#endif - -static stringobject *characters[UCHAR_MAX + 1]; -#ifndef DONT_SHARE_SHORT_STRINGS -static stringobject *nullstring; -#endif - -/* - Newsizedstringobject() and newstringobject() try in certain cases - to share string objects. When the size of the string is zero, - these routines always return a pointer to the same string object; - when the size is one, they return a pointer to an already existing - object if the contents of the string is known. For - newstringobject() this is always the case, for - newsizedstringobject() this is the case when the first argument in - not NULL. - A common practice to allocate a string and then fill it in or - change it must be done carefully. It is only allowed to change the - contents of the string if the obect was gotten from - newsizedstringobject() with a NULL first argument, because in the - future these routines may try to do even more sharing of objects. -*/ -object * -newsizedstringobject(str, size) - char *str; - int size; -{ - register stringobject *op; -#ifndef DONT_SHARE_SHORT_STRINGS - if (size == 0 && (op = nullstring) != NULL) { -#ifdef COUNT_ALLOCS - null_strings++; -#endif - INCREF(op); - return (object *)op; - } - if (size == 1 && str != NULL && (op = characters[*str & UCHAR_MAX]) != NULL) { -#ifdef COUNT_ALLOCS - one_strings++; -#endif - INCREF(op); - return (object *)op; - } -#endif /* DONT_SHARE_SHORT_STRINGS */ - op = (stringobject *) - malloc(sizeof(stringobject) + size * sizeof(char)); - if (op == NULL) - return err_nomem(); - op->ob_type = &Stringtype; - op->ob_size = size; -#ifdef CACHE_HASH - op->ob_shash = -1; -#endif - NEWREF(op); - if (str != NULL) - memcpy(op->ob_sval, str, size); - op->ob_sval[size] = '\0'; -#ifndef DONT_SHARE_SHORT_STRINGS - if (size == 0) { - nullstring = op; - INCREF(op); - } else if (size == 1 && str != NULL) { - characters[*str & UCHAR_MAX] = op; - INCREF(op); - } -#endif - return (object *) op; -} - -object * -newstringobject(str) - char *str; -{ - register unsigned int size = strlen(str); - register stringobject *op; -#ifndef DONT_SHARE_SHORT_STRINGS - if (size == 0 && (op = nullstring) != NULL) { -#ifdef COUNT_ALLOCS - null_strings++; -#endif - INCREF(op); - return (object *)op; - } - if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) { -#ifdef COUNT_ALLOCS - one_strings++; -#endif - INCREF(op); - return (object *)op; - } -#endif /* DONT_SHARE_SHORT_STRINGS */ - op = (stringobject *) - malloc(sizeof(stringobject) + size * sizeof(char)); - if (op == NULL) - return err_nomem(); - op->ob_type = &Stringtype; - op->ob_size = size; -#ifdef CACHE_HASH - op->ob_shash = -1; -#endif - NEWREF(op); - strcpy(op->ob_sval, str); -#ifndef DONT_SHARE_SHORT_STRINGS - if (size == 0) { - nullstring = op; - INCREF(op); - } else if (size == 1) { - characters[*str & UCHAR_MAX] = op; - INCREF(op); - } -#endif - return (object *) op; -} - -static void -string_dealloc(op) - object *op; -{ - DEL(op); -} - -int -getstringsize(op) - register object *op; -{ - if (!is_stringobject(op)) { - err_badcall(); - return -1; - } - return ((stringobject *)op) -> ob_size; -} - -/*const*/ char * -getstringvalue(op) - register object *op; -{ - if (!is_stringobject(op)) { - err_badcall(); - return NULL; - } - return ((stringobject *)op) -> ob_sval; -} - -/* Methods */ - -static int -string_print(op, fp, flags) - stringobject *op; - FILE *fp; - int flags; -{ - int i; - char c; - int quote; - /* XXX Ought to check for interrupts when writing long strings */ - if (flags & PRINT_RAW) { - fwrite(op->ob_sval, 1, (int) op->ob_size, fp); - return 0; - } - - /* figure out which quote to use; single is prefered */ - quote = '\''; - if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"')) - quote = '"'; - - fputc(quote, fp); - for (i = 0; i < op->ob_size; i++) { - c = op->ob_sval[i]; - if (c == quote || c == '\\') - fprintf(fp, "\\%c", c); - else if (c < ' ' || c >= 0177) - fprintf(fp, "\\%03o", c & 0377); - else - fputc(c, fp); - } - fputc(quote, fp); - return 0; -} - -static object * -string_repr(op) - register stringobject *op; -{ - /* XXX overflow? */ - int newsize = 2 + 4 * op->ob_size * sizeof(char); - object *v = newsizedstringobject((char *)NULL, newsize); - if (v == NULL) { - return NULL; - } - else { - register int i; - register char c; - register char *p; - int quote; - - /* figure out which quote to use; single is prefered */ - quote = '\''; - if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"')) - quote = '"'; - - p = ((stringobject *)v)->ob_sval; - *p++ = quote; - for (i = 0; i < op->ob_size; i++) { - c = op->ob_sval[i]; - if (c == quote || c == '\\') - *p++ = '\\', *p++ = c; - else if (c < ' ' || c >= 0177) { - sprintf(p, "\\%03o", c & 0377); - while (*p != '\0') - p++; - } - else - *p++ = c; - } - *p++ = quote; - *p = '\0'; - resizestring(&v, (int) (p - ((stringobject *)v)->ob_sval)); - return v; - } -} - -static int -string_length(a) - stringobject *a; -{ - return a->ob_size; -} - -static object * -string_concat(a, bb) - register stringobject *a; - register object *bb; -{ - register unsigned int size; - register stringobject *op; - if (!is_stringobject(bb)) { - err_badarg(); - return NULL; - } -#define b ((stringobject *)bb) - /* Optimize cases with empty left or right operand */ - if (a->ob_size == 0) { - INCREF(bb); - return bb; - } - if (b->ob_size == 0) { - INCREF(a); - return (object *)a; - } - size = a->ob_size + b->ob_size; - op = (stringobject *) - malloc(sizeof(stringobject) + size * sizeof(char)); - if (op == NULL) - return err_nomem(); - op->ob_type = &Stringtype; - op->ob_size = size; -#ifdef CACHE_HASH - op->ob_shash = -1; -#endif - NEWREF(op); - memcpy(op->ob_sval, a->ob_sval, (int) a->ob_size); - memcpy(op->ob_sval + a->ob_size, b->ob_sval, (int) b->ob_size); - op->ob_sval[size] = '\0'; - return (object *) op; -#undef b -} - -static object * -string_repeat(a, n) - register stringobject *a; - register int n; -{ - register int i; - register unsigned int size; - register stringobject *op; - if (n < 0) - n = 0; - size = a->ob_size * n; - if (size == a->ob_size) { - INCREF(a); - return (object *)a; - } - op = (stringobject *) - malloc(sizeof(stringobject) + size * sizeof(char)); - if (op == NULL) - return err_nomem(); - op->ob_type = &Stringtype; - op->ob_size = size; -#ifdef CACHE_HASH - op->ob_shash = -1; -#endif - NEWREF(op); - for (i = 0; i < size; i += a->ob_size) - memcpy(op->ob_sval+i, a->ob_sval, (int) a->ob_size); - op->ob_sval[size] = '\0'; - return (object *) op; -} - -/* String slice a[i:j] consists of characters a[i] ... a[j-1] */ - -static object * -string_slice(a, i, j) - register stringobject *a; - register int i, j; /* May be negative! */ -{ - if (i < 0) - i = 0; - if (j < 0) - j = 0; /* Avoid signed/unsigned bug in next line */ - if (j > a->ob_size) - j = a->ob_size; - if (i == 0 && j == a->ob_size) { /* It's the same as a */ - INCREF(a); - return (object *)a; - } - if (j < i) - j = i; - return newsizedstringobject(a->ob_sval + i, (int) (j-i)); -} - -static object * -string_item(a, i) - stringobject *a; - register int i; -{ - int c; - object *v; - if (i < 0 || i >= a->ob_size) { - err_setstr(IndexError, "string index out of range"); - return NULL; - } - c = a->ob_sval[i] & UCHAR_MAX; - v = (object *) characters[c]; -#ifdef COUNT_ALLOCS - if (v != NULL) - one_strings++; -#endif - if (v == NULL) { - v = newsizedstringobject((char *)NULL, 1); - if (v == NULL) - return NULL; - characters[c] = (stringobject *) v; - ((stringobject *)v)->ob_sval[0] = c; - } - INCREF(v); - return v; -} - -static int -string_compare(a, b) - stringobject *a, *b; -{ - int len_a = a->ob_size, len_b = b->ob_size; - int min_len = (len_a < len_b) ? len_a : len_b; - int cmp; - if (min_len > 0) { - cmp = *a->ob_sval - *b->ob_sval; - if (cmp == 0) - cmp = memcmp(a->ob_sval, b->ob_sval, min_len); - if (cmp != 0) - return cmp; - } - return (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0; -} - -static long -string_hash(a) - stringobject *a; -{ - register int len; - register unsigned char *p; - register long x; - -#ifdef CACHE_HASH - if (a->ob_shash != -1) - return a->ob_shash; -#endif - len = a->ob_size; - p = (unsigned char *) a->ob_sval; - x = *p << 7; - while (--len >= 0) - x = (3*x) ^ *p++; - x ^= a->ob_size; - if (x == -1) - x = -2; -#ifdef CACHE_HASH - a->ob_shash = x; -#endif - return x; -} - -static sequence_methods string_as_sequence = { - (inquiry)string_length, /*sq_length*/ - (binaryfunc)string_concat, /*sq_concat*/ - (intargfunc)string_repeat, /*sq_repeat*/ - (intargfunc)string_item, /*sq_item*/ - (intintargfunc)string_slice, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ -}; - -typeobject Stringtype = { - OB_HEAD_INIT(&Typetype) - 0, - "string", - sizeof(stringobject), - sizeof(char), - (destructor)string_dealloc, /*tp_dealloc*/ - (printfunc)string_print, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)string_compare, /*tp_compare*/ - (reprfunc)string_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - &string_as_sequence, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)string_hash, /*tp_hash*/ -}; - -void -joinstring(pv, w) - register object **pv; - register object *w; -{ - register object *v; - if (*pv == NULL) - return; - if (w == NULL || !is_stringobject(*pv)) { - DECREF(*pv); - *pv = NULL; - return; - } - v = string_concat((stringobject *) *pv, w); - DECREF(*pv); - *pv = v; -} - -void -joinstring_decref(pv, w) - register object **pv; - register object *w; -{ - joinstring(pv, w); - XDECREF(w); -} - - -/* The following function breaks the notion that strings are immutable: - it changes the size of a string. We get away with this only if there - is only one module referencing the object. You can also think of it - as creating a new string object and destroying the old one, only - more efficiently. In any case, don't use this if the string may - already be known to some other part of the code... */ - -int -resizestring(pv, newsize) - object **pv; - int newsize; -{ - register object *v; - register stringobject *sv; - v = *pv; - if (!is_stringobject(v) || v->ob_refcnt != 1) { - *pv = 0; - DECREF(v); - err_badcall(); - return -1; - } - /* XXX UNREF/NEWREF interface should be more symmetrical */ -#ifdef Py_REF_DEBUG - --_Py_RefTotal; -#endif - UNREF(v); - *pv = (object *) - realloc((char *)v, - sizeof(stringobject) + newsize * sizeof(char)); - if (*pv == NULL) { - DEL(v); - err_nomem(); - return -1; - } - NEWREF(*pv); - sv = (stringobject *) *pv; - sv->ob_size = newsize; - sv->ob_sval[newsize] = '\0'; - return 0; -} - -/* Helpers for formatstring */ - -static object * -getnextarg(args, arglen, p_argidx) - object *args; - int arglen; - int *p_argidx; -{ - int argidx = *p_argidx; - if (argidx < arglen) { - (*p_argidx)++; - if (arglen < 0) - return args; - else - return gettupleitem(args, argidx); - } - err_setstr(TypeError, "not enough arguments for format string"); - return NULL; -} - -#define F_LJUST (1<<0) -#define F_SIGN (1<<1) -#define F_BLANK (1<<2) -#define F_ALT (1<<3) -#define F_ZERO (1<<4) - -extern double fabs PROTO((double)); - -static char * -formatfloat(flags, prec, type, v) - int flags; - int prec; - int type; - object *v; -{ - char fmt[20]; - static char buf[120]; - double x; - if (!getargs(v, "d;float argument required", &x)) - return NULL; - if (prec < 0) - prec = 6; - if (prec > 50) - prec = 50; /* Arbitrary limitation */ - if (type == 'f' && fabs(x)/1e25 >= 1e25) - type = 'g'; - sprintf(fmt, "%%%s.%d%c", (flags&F_ALT) ? "#" : "", prec, type); - sprintf(buf, fmt, x); - return buf; -} - -static char * -formatint(flags, prec, type, v) - int flags; - int prec; - int type; - object *v; -{ - char fmt[20]; - static char buf[50]; - long x; - if (!getargs(v, "l;int argument required", &x)) - return NULL; - if (prec < 0) - prec = 1; - sprintf(fmt, "%%%s.%dl%c", (flags&F_ALT) ? "#" : "", prec, type); - sprintf(buf, fmt, x); - return buf; -} - -static char * -formatchar(v) - object *v; -{ - static char buf[2]; - if (is_stringobject(v)) { - if (!getargs(v, "c;%c requires int or char", &buf[0])) - return NULL; - } - else { - if (!getargs(v, "b;%c requires int or char", &buf[0])) - return NULL; - } - buf[1] = '\0'; - return buf; -} - - -/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...) */ - -object * -formatstring(format, args) - object *format; - object *args; -{ - char *fmt, *res; - int fmtcnt, rescnt, reslen, arglen, argidx; - int args_owned = 0; - object *result; - object *dict = NULL; - if (format == NULL || !is_stringobject(format) || args == NULL) { - err_badcall(); - return NULL; - } - fmt = getstringvalue(format); - fmtcnt = getstringsize(format); - reslen = rescnt = fmtcnt + 100; - result = newsizedstringobject((char *)NULL, reslen); - if (result == NULL) - return NULL; - res = getstringvalue(result); - if (is_tupleobject(args)) { - arglen = gettuplesize(args); - argidx = 0; - } - else { - arglen = -1; - argidx = -2; - } - if (args->ob_type->tp_as_mapping) - dict = args; - while (--fmtcnt >= 0) { - if (*fmt != '%') { - if (--rescnt < 0) { - rescnt = fmtcnt + 100; - reslen += rescnt; - if (resizestring(&result, reslen) < 0) - return NULL; - res = getstringvalue(result) + reslen - rescnt; - --rescnt; - } - *res++ = *fmt++; - } - else { - /* Got a format specifier */ - int flags = 0; - char *fmtstart = fmt++; - int width = -1; - int prec = -1; - int size = 0; - int c = '\0'; - int fill; - object *v; - object *temp = NULL; - char *buf; - int sign; - int len; - if (*fmt == '(') { - char *keystart; - int keylen; - object *key; - - if (dict == NULL) { - err_setstr(TypeError, - "format requires a mapping"); - goto error; - } - ++fmt; - --fmtcnt; - keystart = fmt; - while (--fmtcnt >= 0 && *fmt != ')') - fmt++; - keylen = fmt - keystart; - ++fmt; - if (fmtcnt < 0) { - err_setstr(ValueError, - "incomplete format key"); - goto error; - } - key = newsizedstringobject(keystart, keylen); - if (key == NULL) - goto error; - if (args_owned) { - DECREF(args); - args_owned = 0; - } - args = PyObject_GetItem(dict, key); - DECREF(key); - if (args == NULL) { - goto error; - } - args_owned = 1; - arglen = -1; - argidx = -2; - } - while (--fmtcnt >= 0) { - switch (c = *fmt++) { - case '-': flags |= F_LJUST; continue; - case '+': flags |= F_SIGN; continue; - case ' ': flags |= F_BLANK; continue; - case '#': flags |= F_ALT; continue; - case '0': flags |= F_ZERO; continue; - } - break; - } - if (c == '*') { - v = getnextarg(args, arglen, &argidx); - if (v == NULL) - goto error; - if (!is_intobject(v)) { - err_setstr(TypeError, "* wants int"); - goto error; - } - width = getintvalue(v); - if (width < 0) - width = 0; - if (--fmtcnt >= 0) - c = *fmt++; - } - else if (c >= 0 && isdigit(c)) { - width = c - '0'; - while (--fmtcnt >= 0) { - c = Py_CHARMASK(*fmt++); - if (!isdigit(c)) - break; - if ((width*10) / 10 != width) { - err_setstr(ValueError, - "width too big"); - goto error; - } - width = width*10 + (c - '0'); - } - } - if (c == '.') { - prec = 0; - if (--fmtcnt >= 0) - c = *fmt++; - if (c == '*') { - v = getnextarg(args, arglen, &argidx); - if (v == NULL) - goto error; - if (!is_intobject(v)) { - err_setstr(TypeError, - "* wants int"); - goto error; - } - prec = getintvalue(v); - if (prec < 0) - prec = 0; - if (--fmtcnt >= 0) - c = *fmt++; - } - else if (c >= 0 && isdigit(c)) { - prec = c - '0'; - while (--fmtcnt >= 0) { - c = Py_CHARMASK(*fmt++); - if (!isdigit(c)) - break; - if ((prec*10) / 10 != prec) { - err_setstr(ValueError, - "prec too big"); - goto error; - } - prec = prec*10 + (c - '0'); - } - } - } /* prec */ - if (fmtcnt >= 0) { - if (c == 'h' || c == 'l' || c == 'L') { - size = c; - if (--fmtcnt >= 0) - c = *fmt++; - } - } - if (fmtcnt < 0) { - err_setstr(ValueError, "incomplete format"); - goto error; - } - if (c != '%') { - v = getnextarg(args, arglen, &argidx); - if (v == NULL) - goto error; - } - sign = 0; - fill = ' '; - switch (c) { - case '%': - buf = "%"; - len = 1; - break; - case 's': - temp = strobject(v); - if (temp == NULL) - goto error; - buf = getstringvalue(temp); - len = getstringsize(temp); - if (prec >= 0 && len > prec) - len = prec; - break; - case 'i': - case 'd': - case 'u': - case 'o': - case 'x': - case 'X': - if (c == 'i') - c = 'd'; - buf = formatint(flags, prec, c, v); - if (buf == NULL) - goto error; - len = strlen(buf); - sign = (c == 'd'); - if (flags&F_ZERO) - fill = '0'; - break; - case 'e': - case 'E': - case 'f': - case 'g': - case 'G': - buf = formatfloat(flags, prec, c, v); - if (buf == NULL) - goto error; - len = strlen(buf); - sign = 1; - if (flags&F_ZERO) - fill = '0'; - break; - case 'c': - buf = formatchar(v); - if (buf == NULL) - goto error; - len = 1; - break; - default: - err_setstr(ValueError, - "unsupported format character"); - goto error; - } - if (sign) { - if (*buf == '-' || *buf == '+') { - sign = *buf++; - len--; - } - else if (flags & F_SIGN) - sign = '+'; - else if (flags & F_BLANK) - sign = ' '; - else - sign = '\0'; - } - if (width < len) - width = len; - if (rescnt < width + (sign != '\0')) { - reslen -= rescnt; - rescnt = width + fmtcnt + 100; - reslen += rescnt; - if (resizestring(&result, reslen) < 0) - return NULL; - res = getstringvalue(result) + reslen - rescnt; - } - if (sign) { - if (fill != ' ') - *res++ = sign; - rescnt--; - if (width > len) - width--; - } - if (width > len && !(flags&F_LJUST)) { - do { - --rescnt; - *res++ = fill; - } while (--width > len); - } - if (sign && fill == ' ') - *res++ = sign; - memcpy(res, buf, len); - res += len; - rescnt -= len; - while (--width >= len) { - --rescnt; - *res++ = ' '; - } - if (dict && (argidx < arglen) && c != '%') { - err_setstr(TypeError, - "not all arguments converted"); - goto error; - } - XDECREF(temp); - } /* '%' */ - } /* until end */ - if (argidx < arglen && !dict) { - err_setstr(TypeError, "not all arguments converted"); - goto error; - } - if (args_owned) - DECREF(args); - resizestring(&result, reslen - rescnt); - return result; - error: - DECREF(result); - if (args_owned) - DECREF(args); - return NULL; -} diff --git a/Objects/tupleobject.c b/Objects/tupleobject.c deleted file mode 100644 index 19c3641d18..0000000000 --- a/Objects/tupleobject.c +++ /dev/null @@ -1,458 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Tuple object implementation */ - -#include "allobjects.h" - -#ifndef MAXSAVESIZE -#define MAXSAVESIZE 20 -#endif - -#if MAXSAVESIZE > 0 -/* Entries 1 upto MAXSAVESIZE are free lists, entry 0 is the empty - tuple () of which at most one instance will be allocated. -*/ -static tupleobject *free_tuples[MAXSAVESIZE]; -#endif -#ifdef COUNT_ALLOCS -int fast_tuple_allocs; -int tuple_zero_allocs; -#endif - -object * -newtupleobject(size) - register int size; -{ - register int i; - register tupleobject *op; - if (size < 0) { - err_badcall(); - return NULL; - } -#if MAXSAVESIZE > 0 - if (size == 0 && free_tuples[0]) { - op = free_tuples[0]; - INCREF(op); -#ifdef COUNT_ALLOCS - tuple_zero_allocs++; -#endif - return (object *) op; - } - if (0 < size && size < MAXSAVESIZE && (op = free_tuples[size]) != NULL) { - free_tuples[size] = (tupleobject *) op->ob_item[0]; -#ifdef COUNT_ALLOCS - fast_tuple_allocs++; -#endif - } else -#endif - { - op = (tupleobject *) - malloc(sizeof(tupleobject) + size * sizeof(object *)); - if (op == NULL) - return err_nomem(); - } - op->ob_type = &Tupletype; - op->ob_size = size; - for (i = 0; i < size; i++) - op->ob_item[i] = NULL; - NEWREF(op); -#if MAXSAVESIZE > 0 - if (size == 0) { - free_tuples[0] = op; - INCREF(op); /* extra INCREF so that this is never freed */ - } -#endif - return (object *) op; -} - -int -gettuplesize(op) - register object *op; -{ - if (!is_tupleobject(op)) { - err_badcall(); - return -1; - } - else - return ((tupleobject *)op)->ob_size; -} - -object * -gettupleitem(op, i) - register object *op; - register int i; -{ - if (!is_tupleobject(op)) { - err_badcall(); - return NULL; - } - if (i < 0 || i >= ((tupleobject *)op) -> ob_size) { - err_setstr(IndexError, "tuple index out of range"); - return NULL; - } - return ((tupleobject *)op) -> ob_item[i]; -} - -int -settupleitem(op, i, newitem) - register object *op; - register int i; - object *newitem; -{ - register object *olditem; - register object **p; - if (!is_tupleobject(op)) { - XDECREF(newitem); - err_badcall(); - return -1; - } - if (i < 0 || i >= ((tupleobject *)op) -> ob_size) { - XDECREF(newitem); - err_setstr(IndexError, "tuple assignment index out of range"); - return -1; - } - p = ((tupleobject *)op) -> ob_item + i; - olditem = *p; - *p = newitem; - XDECREF(olditem); - return 0; -} - -/* Methods */ - -static void -tupledealloc(op) - register tupleobject *op; -{ - register int i; - for (i = 0; i < op->ob_size; i++) - XDECREF(op->ob_item[i]); -#if MAXSAVESIZE > 0 - if (0 < op->ob_size && op->ob_size < MAXSAVESIZE) { - op->ob_item[0] = (object *) free_tuples[op->ob_size]; - free_tuples[op->ob_size] = op; - } else -#endif - free((ANY *)op); -} - -static int -tupleprint(op, fp, flags) - tupleobject *op; - FILE *fp; - int flags; -{ - int i; - fprintf(fp, "("); - for (i = 0; i < op->ob_size; i++) { - if (i > 0) - fprintf(fp, ", "); - if (printobject(op->ob_item[i], fp, 0) != 0) - return -1; - } - if (op->ob_size == 1) - fprintf(fp, ","); - fprintf(fp, ")"); - return 0; -} - -static object * -tuplerepr(v) - tupleobject *v; -{ - object *s, *comma; - int i; - s = newstringobject("("); - comma = newstringobject(", "); - for (i = 0; i < v->ob_size && s != NULL; i++) { - if (i > 0) - joinstring(&s, comma); - joinstring_decref(&s, reprobject(v->ob_item[i])); - } - DECREF(comma); - if (v->ob_size == 1) - joinstring_decref(&s, newstringobject(",")); - joinstring_decref(&s, newstringobject(")")); - return s; -} - -static int -tuplecompare(v, w) - register tupleobject *v, *w; -{ - register int len = - (v->ob_size < w->ob_size) ? v->ob_size : w->ob_size; - register int i; - for (i = 0; i < len; i++) { - int cmp = cmpobject(v->ob_item[i], w->ob_item[i]); - if (cmp != 0) - return cmp; - } - return v->ob_size - w->ob_size; -} - -static long -tuplehash(v) - tupleobject *v; -{ - register long x, y; - register int len = v->ob_size; - register object **p; - x = 0x345678L; - p = v->ob_item; - while (--len >= 0) { - y = hashobject(*p++); - if (y == -1) - return -1; - x = (x + x + x) ^ y; - } - x ^= v->ob_size; - if (x == -1) - x = -2; - return x; -} - -static int -tuplelength(a) - tupleobject *a; -{ - return a->ob_size; -} - -static object * -tupleitem(a, i) - register tupleobject *a; - register int i; -{ - if (i < 0 || i >= a->ob_size) { - err_setstr(IndexError, "tuple index out of range"); - return NULL; - } - INCREF(a->ob_item[i]); - return a->ob_item[i]; -} - -static object * -tupleslice(a, ilow, ihigh) - register tupleobject *a; - register int ilow, ihigh; -{ - register tupleobject *np; - register int i; - if (ilow < 0) - ilow = 0; - if (ihigh > a->ob_size) - ihigh = a->ob_size; - if (ihigh < ilow) - ihigh = ilow; - if (ilow == 0 && ihigh == a->ob_size) { - /* XXX can only do this if tuples are immutable! */ - INCREF(a); - return (object *)a; - } - np = (tupleobject *)newtupleobject(ihigh - ilow); - if (np == NULL) - return NULL; - for (i = ilow; i < ihigh; i++) { - object *v = a->ob_item[i]; - INCREF(v); - np->ob_item[i - ilow] = v; - } - return (object *)np; -} - -object * -gettupleslice(op, i, j) - object *op; - int i, j; -{ - if (op == NULL || !is_tupleobject(op)) { - err_badcall(); - return NULL; - } - return tupleslice((tupleobject *)op, i, j); -} - -static object * -tupleconcat(a, bb) - register tupleobject *a; - register object *bb; -{ - register int size; - register int i; - tupleobject *np; - if (!is_tupleobject(bb)) { - err_badarg(); - return NULL; - } -#define b ((tupleobject *)bb) - size = a->ob_size + b->ob_size; - np = (tupleobject *) newtupleobject(size); - if (np == NULL) { - return NULL; - } - for (i = 0; i < a->ob_size; i++) { - object *v = a->ob_item[i]; - INCREF(v); - np->ob_item[i] = v; - } - for (i = 0; i < b->ob_size; i++) { - object *v = b->ob_item[i]; - INCREF(v); - np->ob_item[i + a->ob_size] = v; - } - return (object *)np; -#undef b -} - -static object * -tuplerepeat(a, n) - tupleobject *a; - int n; -{ - int i, j; - int size; - tupleobject *np; - object **p; - if (n < 0) - n = 0; - if (a->ob_size*n == a->ob_size) { - /* Since tuples are immutable, we can return a shared - copy in this case */ - INCREF(a); - return (object *)a; - } - size = a->ob_size * n; - np = (tupleobject *) newtupleobject(size); - if (np == NULL) - return NULL; - p = np->ob_item; - for (i = 0; i < n; i++) { - for (j = 0; j < a->ob_size; j++) { - *p = a->ob_item[j]; - INCREF(*p); - p++; - } - } - return (object *) np; -} - -static sequence_methods tuple_as_sequence = { - (inquiry)tuplelength, /*sq_length*/ - (binaryfunc)tupleconcat, /*sq_concat*/ - (intargfunc)tuplerepeat, /*sq_repeat*/ - (intargfunc)tupleitem, /*sq_item*/ - (intintargfunc)tupleslice, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ -}; - -typeobject Tupletype = { - OB_HEAD_INIT(&Typetype) - 0, - "tuple", - sizeof(tupleobject) - sizeof(object *), - sizeof(object *), - (destructor)tupledealloc, /*tp_dealloc*/ - (printfunc)tupleprint, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)tuplecompare, /*tp_compare*/ - (reprfunc)tuplerepr, /*tp_repr*/ - 0, /*tp_as_number*/ - &tuple_as_sequence, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)tuplehash, /*tp_hash*/ -}; - -/* The following function breaks the notion that tuples are immutable: - it changes the size of a tuple. We get away with this only if there - is only one module referencing the object. You can also think of it - as creating a new tuple object and destroying the old one, only - more efficiently. In any case, don't use this if the tuple may - already be known to some other part of the code... - If last_is_sticky is set, the tuple will grow or shrink at the - front, otherwise it will grow or shrink at the end. */ - -int -resizetuple(pv, newsize, last_is_sticky) - object **pv; - int newsize; - int last_is_sticky; -{ - register tupleobject *v; - register tupleobject *sv; - int i; - int sizediff; - - v = (tupleobject *) *pv; - if (v == NULL || !is_tupleobject(v) || v->ob_refcnt != 1) { - *pv = 0; - DECREF(v); - err_badcall(); - return -1; - } - sizediff = newsize - v->ob_size; - if (sizediff == 0) - return 0; - /* XXX UNREF/NEWREF interface should be more symmetrical */ -#ifdef Py_REF_DEBUG - --_Py_RefTotal; -#endif - UNREF(v); - if (last_is_sticky && sizediff < 0) { - /* shrinking: move entries to the front and zero moved entries */ - for (i = 0; i < newsize; i++) { - XDECREF(v->ob_item[i]); - v->ob_item[i] = v->ob_item[i - sizediff]; - v->ob_item[i - sizediff] = NULL; - } - } - for (i = newsize; i < v->ob_size; i++) { - XDECREF(v->ob_item[i]); - v->ob_item[i] = NULL; - } - sv = (tupleobject *) - realloc((char *)v, - sizeof(tupleobject) + newsize * sizeof(object *)); - *pv = (object *) sv; - if (sv == NULL) { - DEL(v); - err_nomem(); - return -1; - } - NEWREF(sv); - for (i = sv->ob_size; i < newsize; i++) - sv->ob_item[i] = NULL; - if (last_is_sticky && sizediff > 0) { - /* growing: move entries to the end and zero moved entries */ - for (i = newsize - 1; i >= sizediff; i--) { - sv->ob_item[i] = sv->ob_item[i - sizediff]; - sv->ob_item[i - sizediff] = NULL; - } - } - sv->ob_size = newsize; - return 0; -} diff --git a/Objects/typeobject.c b/Objects/typeobject.c deleted file mode 100644 index b770bce3c6..0000000000 --- a/Objects/typeobject.c +++ /dev/null @@ -1,83 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Type object implementation */ - -#include "allobjects.h" - -/* Type object implementation */ - -static object * -type_getattr(t, name) - typeobject *t; - char *name; -{ - if (strcmp(name, "__name__") == 0) - return newstringobject(t->tp_name); - if (strcmp(name, "__doc__") == 0) { - char *doc = t->tp_doc; - if (doc != NULL) - return newstringobject(doc); - INCREF(None); - return None; - } - if (strcmp(name, "__members__") == 0) - return mkvalue("[ss]", "__doc__", "__name__"); - err_setstr(AttributeError, name); - return NULL; -} - -static object * -type_repr(v) - typeobject *v; -{ - char buf[100]; - sprintf(buf, "<type '%.80s'>", v->tp_name); - return newstringobject(buf); -} - -typeobject Typetype = { - OB_HEAD_INIT(&Typetype) - 0, /* Number of items for varobject */ - "type", /* Name of this type */ - sizeof(typeobject), /* Basic object size */ - 0, /* Item size for varobject */ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)type_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - (reprfunc)type_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_xxx1*/ - 0, /*tp_xxx2*/ - 0, /*tp_xxx3*/ - 0, /*tp_xxx4*/ - "Define the behaviour of a particular type of object.", -}; diff --git a/Objects/xxobject.c b/Objects/xxobject.c deleted file mode 100644 index bb8a5f677f..0000000000 --- a/Objects/xxobject.c +++ /dev/null @@ -1,140 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Use this file as a template to start implementing a new object type. - If your objects will be called foobar, start by copying this file to - foobarobject.c, changing all occurrences of xx to foobar and all - occurrences of Xx by Foobar. You will probably want to delete all - references to 'x_attr' and add your own types of attributes - instead. Maybe you want to name your local variables other than - 'xp'. If your object type is needed in other files, you'll have to - create a file "foobarobject.h"; see intobject.h for an example. */ - - -/* Xx objects */ - -#include "Python.h" - -typedef struct { - PyObject_HEAD - PyObject *x_attr; /* Attributes dictionary */ -} xxobject; - -staticforward PyTypeObject Xxtype; - -#define is_xxobject(v) ((v)->ob_type == &Xxtype) - -static xxobject * -newxxobject(arg) - PyObject *arg; -{ - xxobject *xp; - xp = PyObject_NEW(xxobject, &Xxtype); - if (xp == NULL) - return NULL; - xp->x_attr = NULL; - return xp; -} - -/* Xx methods */ - -static void -xx_dealloc(xp) - xxobject *xp; -{ - Py_XDECREF(xp->x_attr); - PyMem_DEL(xp); -} - -static PyObject * -xx_demo(self, args) - xxobject *self; - PyObject *args; -{ - if (!PyArg_NoArgs(args)) - return NULL; - Py_INCREF(Py_None); - return Py_None; -} - -static Py_MethodDef xx_methods[] = { - {"demo", (PyCFunction)xx_demo}, - {NULL, NULL} /* sentinel */ -}; - -static PyObject * -xx_getattr(xp, name) - xxobject *xp; - char *name; -{ - if (xp->x_attr != NULL) { - PyObject *v = PyDict_GetItemString(xp->x_attr, name); - if (v != NULL) { - Py_INCREF(v); - return v; - } - } - return Py_FindMethod(xx_methods, (PyObject *)xp, name); -} - -static int -xx_setattr(xp, name, v) - xxobject *xp; - char *name; - PyObject *v; -{ - if (xp->x_attr == NULL) { - xp->x_attr = PyDict_New(); - if (xp->x_attr == NULL) - return -1; - } - if (v == NULL) { - int rv = PyDict_DelItemString(xp->x_attr, name); - if (rv < 0) - PyErr_SetString(PyExc_AttributeError, - "delete non-existing xx attribute"); - return rv; - } - else - return PyDict_SetItemString(xp->x_attr, name, v); -} - -static PyTypeObject Xxtype = { - PyObject_HEAD_INIT(&PyType_Type) - 0, /*ob_size*/ - "xx", /*tp_name*/ - sizeof(xxobject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)xx_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)xx_getattr, /*tp_getattr*/ - (setattrfunc)xx_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ -}; diff --git a/PC/config.c b/PC/config.c deleted file mode 100644 index fed3745be8..0000000000 --- a/PC/config.c +++ /dev/null @@ -1,99 +0,0 @@ -/* -*- C -*- *********************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Module configuration */ - -/* This file contains the table of built-in modules. - See init_builtin() in import.c. */ - -#include "Python.h" - -extern void initarray(); -extern void initaudioop(); -extern void initbinascii(); -extern void initenvironment(); -extern void initimageop(); -extern void initmath(); -extern void initmd5(); -extern void initnew(); -extern void initnt(); -extern void initregex(); -extern void initrgbimg(); -extern void initrotor(); -extern void initsignal(); -extern void initsocket(); -extern void initsoundex(); -extern void initstrop(); -extern void initstruct(); -extern void inittime(); - -/* -- ADDMODULE MARKER 1 -- */ - -extern void PyMarshal_Init(); -extern void initimp(); - -struct { - char *name; - void (*initfunc)(); -} inittab[] = { - - {"array", initarray}, -#ifdef M_I386 - {"audioop", initaudioop}, -#endif - {"binascii", initbinascii}, - {"environment", initenvironment}, - {"imageop", initimageop}, - {"math", initmath}, - {"md5", initmd5}, - {"new", initnew}, - {"nt", initnt}, /* Use the NT os functions, not posix */ - {"regex", initregex}, - {"rgbimg", initrgbimg}, - {"rotor", initrotor}, - {"signal", initsignal}, -#ifdef USE_SOCKET - {"socket", initsocket}, -#endif - {"soundex", initsoundex}, - {"strop", initstrop}, - {"struct", initstruct}, - {"time", inittime}, - -/* -- ADDMODULE MARKER 2 -- */ - - /* This module "lives in" with marshal.c */ - {"marshal", PyMarshal_Init}, - - /* This lives it with import.c */ - {"imp", initimp}, - - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"__builtin__", NULL}, - {"sys", NULL}, - - /* Sentinel */ - {0, 0} -}; diff --git a/PC/config.h b/PC/config.h deleted file mode 100644 index 3c382de9be..0000000000 --- a/PC/config.h +++ /dev/null @@ -1,406 +0,0 @@ -#ifndef Py_CONFIG_H -#define Py_CONFIG_H -#ifdef __cplusplus -extern "C" { -#endif - -/* config.h. NOT Generated automatically by configure. - -This is a manually maintained version used for the Watcom, -Borland and and Microsoft Visual C++ compilers. It is a -standard part of the Python distribution. - -*/ - -/* - Some systems require special declarations for data items imported - or exported from dynamic link libraries. Note that the definition - of DL_IMPORT covers both cases. Define USE_DL_IMPORT for the client - of a DLL. Define USE_DL_EXPORT when making a DLL. -*/ - -#include <io.h> -#define HAVE_LIMITS_H -#define HAVE_HYPOT -#define DONT_HAVE_SIG_ALARM -#define DONT_HAVE_SIG_PAUSE -#define LONG_BIT 32 - -/* Microsoft C defines _MSC_VER */ - -#if defined(_MSC_VER) && _MSC_VER > 850 -/* Start of defines for NT using VC++ 2.0 and up */ -#define NT -#ifdef _M_IX86 -#define COMPILER "[MSC 32 bit (Intel)]" -#else -#define COMPILER "[MSC (Unknown)]" -#endif -#define PYTHONPATH "c:\\python\\lib" -typedef int pid_t; -#define WORD_BIT 32 -#pragma warning(disable:4113) -#define hypot _hypot -#include <stdio.h> -#define HAVE_CLOCK -#define HAVE_STRFTIME -#define NT_THREADS -#define WITH_THREAD -#ifndef NETSCAPE_PI -#define USE_SOCKET -#define _COMPLEX_DEFINED -#endif -#ifdef USE_DL_IMPORT -#define DL_IMPORT(RTYPE) __declspec(dllimport) RTYPE -#endif -#ifdef USE_DL_EXPORT -#define DL_IMPORT(RTYPE) __declspec(dllexport) RTYPE -#endif -#endif /* NT */ - -#if defined(_MSC_VER) && _MSC_VER <= 850 -/* Start of defines for 16-bit Windows using VC++ 1.5 */ -#define COMPILER "[MSC 16-bit]" -#define MS_WIN16 -#define PYTHONPATH "c:\\python\\lib;c:\\python\\lib\\dos_8x3" -#define IMPORT_8x3_NAMES -typedef int pid_t; -#define WORD_BIT 16 -#define _COMPLEX_DEFINED -#pragma warning(disable:4113) -#define memcpy memmove /* memcpy dangerous pointer wrap in Win 3.1 */ -#define hypot _hypot -#define SIGINT 2 -#include <stdio.h> -/* Windows 3.1 will not tolerate any console io in a dll */ -#ifdef _USRDLL -#include <time.h> -#define stdin ((FILE *)0) -#define stdout ((FILE *)1) -#define stderr ((FILE *)2) -#define fflush Py_fflush -int Py_fflush(FILE *); -#define fgets Py_fgets -char *Py_fgets(char *, int, FILE *); -#define fileno Py_fileno -int Py_fileno(FILE *); -#define fprintf Py_fprintf -int Py_fprintf(FILE *, const char *, ...); -#define printf Py_printf -int Py_printf(const char *, ...); -#define sscanf Py_sscanf -int Py_sscanf(const char *, const char *, ...); -clock_t clock(); -void _exit(int); -void exit(int); -int sscanf(const char *, const char *, ...); -#endif /* _USRDLL */ -#ifndef NETSCAPE_PI -/* use sockets, but not in a Netscape dll */ -#define USE_SOCKET -#endif -#endif /* MS_WIN16 */ - -/* The Watcom compiler defines __WATCOMC__ */ -#ifdef __WATCOMC__ -#define COMPILER "[Watcom]" -#define PYTHONPATH "c:\\python\\lib;c:\\python\\lib\\dos_8x3" -#define IMPORT_8x3_NAMES -#include <ctype.h> -#include <direct.h> -typedef int mode_t; -typedef int uid_t; -typedef int gid_t; -#ifdef M_I386 -#define WORD_BIT 32 -#else -#define WORD_BIT 16 -#endif -#define VA_LIST_IS_ARRAY -#define HAVE_CLOCK -#define HAVE_STRFTIME -#ifdef USE_DL_EXPORT -#define DL_IMPORT(RTYPE) RTYPE __export -#endif -#endif /* __WATCOMC__ */ - -/* The Borland compiler defines __BORLANDC__ */ -#ifdef __BORLANDC__ -#define COMPILER "[Borland]" -#define PYTHONPATH "c:\\python\\lib;c:\\python\\lib\\dos_8x3" -#define IMPORT_8x3_NAMES -#define HAVE_CLOCK -#define HAVE_STRFTIME -#ifdef USE_DL_IMPORT -#define DL_IMPORT(RTYPE) RTYPE __import -#endif -#endif /* BORLANDC */ - -/* Fairly standard from here! */ - -/* Define if on AIX 3. - System headers sometimes define this. - We just want to avoid a redefinition error message. */ -#ifndef _ALL_SOURCE -/* #undef _ALL_SOURCE */ -#endif - -/* Define to empty if the keyword does not work. */ -/* #define const */ - -/* Define if you have dirent.h. */ -/* #define DIRENT 1 */ - -/* Define to the type of elements in the array set by `getgroups'. - Usually this is either `int' or `gid_t'. */ -/* #undef GETGROUPS_T */ - -/* Define to `int' if <sys/types.h> doesn't define. */ -/* #undef gid_t */ - -/* Define if your struct tm has tm_zone. */ -/* #undef HAVE_TM_ZONE */ - -/* Define if you don't have tm_zone but do have the external array - tzname. */ -#define HAVE_TZNAME - -/* Define if on MINIX. */ -/* #undef _MINIX */ - -/* Define to `int' if <sys/types.h> doesn't define. */ -/* #undef mode_t */ - -/* Define if you don't have dirent.h, but have ndir.h. */ -/* #undef NDIR */ - -/* Define to `long' if <sys/types.h> doesn't define. */ -/* #undef off_t */ - -/* Define to `int' if <sys/types.h> doesn't define. */ -/* #undef pid_t */ - -/* Define if the system does not provide POSIX.1 features except - with this defined. */ -/* #undef _POSIX_1_SOURCE */ - -/* Define if you need to in order for stat and other things to work. */ -/* #undef _POSIX_SOURCE */ - -/* Define as the return type of signal handlers (int or void). */ -#define RETSIGTYPE void - -/* Define to `unsigned' if <sys/types.h> doesn't define. */ -/* #undef size_t */ - -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define if you don't have dirent.h, but have sys/dir.h. */ -/* #undef SYSDIR */ - -/* Define if you don't have dirent.h, but have sys/ndir.h. */ -/* #undef SYSNDIR */ - -/* Define if you can safely include both <sys/time.h> and <time.h>. */ -/* #undef TIME_WITH_SYS_TIME */ - -/* Define if your <sys/time.h> declares struct tm. */ -/* #define TM_IN_SYS_TIME 1 */ - -/* Define to `int' if <sys/types.h> doesn't define. */ -/* #undef uid_t */ - -/* Define if the closedir function returns void instead of int. */ -/* #undef VOID_CLOSEDIR */ - -/* Define if your <unistd.h> contains bad prototypes for exec*() - (as it does on SGI IRIX 4.x) */ -/* #undef BAD_EXEC_PROTOTYPES */ - -/* Define if your compiler botches static forward declarations - (as it does on SCI ODT 3.0) */ -#define BAD_STATIC_FORWARD 1 - -/* Define if getpgrp() must be called as getpgrp(0) - and (consequently) setpgrp() as setpgrp(0, 0). */ -/* #undef GETPGRP_HAVE_ARGS */ - -/* Define this if your time.h defines altzone */ -/* #define HAVE_ALTZONE */ - -/* Define if your compiler supports function prototypes */ -#define HAVE_PROTOTYPES - -/* Define if you can safely include both <sys/select.h> and <sys/time.h> - (which you can't on SCO ODT 3.0). */ -/* #undef SYS_SELECT_WITH_SYS_TIME */ - -/* Define if you want to use SGI (IRIX 4) dynamic linking. - This requires the "dl" library by Jack Jansen, - ftp://ftp.cwi.nl/pub/dynload/dl-1.6.tar.Z. - Don't bother on IRIX 5, it already has dynamic linking using SunOS - style shared libraries */ -/* #undef WITH_SGI_DL */ - -/* Define if you want to emulate SGI (IRIX 4) dynamic linking. - This is rumoured to work on VAX (Ultrix), Sun3 (SunOS 3.4), - Sequent Symmetry (Dynix), and Atari ST. - This requires the "dl-dld" library, - ftp://ftp.cwi.nl/pub/dynload/dl-dld-1.1.tar.Z, - as well as the "GNU dld" library, - ftp://ftp.cwi.nl/pub/dynload/dld-3.2.3.tar.Z. - Don't bother on SunOS 4 or 5, they already have dynamic linking using - shared libraries */ -/* #undef WITH_DL_DLD */ - -/* Define if you want to compile in rudimentary thread support */ -/* #undef WITH_THREAD */ - -/* Define if you want to use the GNU readline library */ -/* #define WITH_READLINE 1 */ - -/* Define if you have clock. */ -/* #define HAVE_CLOCK */ - -/* Define if you have ftime. */ -#define HAVE_FTIME - -/* Define if you have getpeername. */ -/* #undef HAVE_GETPEERNAME */ - -/* Define if you have getpgrp. */ -/* #undef HAVE_GETPGRP */ - -/* Define if you have getpid. */ -/* #undef HAVE_GETPID */ - -/* Define if you have gettimeofday. */ -/* #undef HAVE_GETTIMEOFDAY */ - -/* Define if you have getwd. */ -/* #undef HAVE_GETWD */ - -/* Define if you have lstat. */ -/* #undef HAVE_LSTAT */ - -/* Define if you have nice. */ -/* #undef HAVE_NICE */ - -/* Define if you have readlink. */ -/* #undef HAVE_READLINK */ - -/* Define if you have select. */ -/* #undef HAVE_SELECT */ - -/* Define if you have setpgid. */ -/* #undef HAVE_SETPGID */ - -/* Define if you have setpgrp. */ -/* #undef HAVE_SETPGRP */ - -/* Define if you have setsid. */ -/* #undef HAVE_SETSID */ - -/* Define if you have siginterrupt. */ -/* #undef HAVE_SIGINTERRUPT */ - -/* Define if you have symlink. */ -/* #undef HAVE_SYMLINK */ - -/* Define if you have tcgetpgrp. */ -/* #undef HAVE_TCGETPGRP */ - -/* Define if you have tcsetpgrp. */ -/* #undef HAVE_TCSETPGRP */ - -/* Define if you have times. */ -/* #undef HAVE_TIMES */ - -/* Define if you have uname. */ -/* #undef HAVE_UNAME */ - -/* Define if you have waitpid. */ -/* #undef HAVE_WAITPID */ - -/* Define if you have the <dlfcn.h> header file. */ -/* #undef HAVE_DLFCN_H */ - -/* Define if you have the <fcntl.h> header file. */ -#define HAVE_FCNTL_H 1 - -/* Define if you have the <signal.h> header file. */ -#define HAVE_SIGNAL_H 1 - -/* Define if you have the <stdarg.h> header file. */ -#define HAVE_STDARG_H 1 - -/* Define if you have the <stdarg.h> prototypes. */ -#define HAVE_STDARG_PROTOTYPES - -/* Define if you have the <stdlib.h> header file. */ -#define HAVE_STDLIB_H 1 - -/* Define if you have the <sys/audioio.h> header file. */ -/* #undef HAVE_SYS_AUDIOIO_H */ - -/* Define if you have the <sys/param.h> header file. */ -/* #define HAVE_SYS_PARAM_H 1 */ - -/* Define if you have the <sys/select.h> header file. */ -/* #define HAVE_SYS_SELECT_H 1 */ - -/* Define if you have the <sys/time.h> header file. */ -/* #define HAVE_SYS_TIME_H 1 */ - -/* Define if you have the <sys/times.h> header file. */ -/* #define HAVE_SYS_TIMES_H 1 */ - -/* Define if you have the <sys/un.h> header file. */ -/* #define HAVE_SYS_UN_H 1 */ - -/* Define if you have the <sys/utime.h> header file. */ -#define HAVE_SYS_UTIME_H 1 - -/* Define if you have the <sys/utsname.h> header file. */ -/* #define HAVE_SYS_UTSNAME_H 1 */ - -/* Define if you have the <thread.h> header file. */ -/* #undef HAVE_THREAD_H */ - -/* Define if you have the <unistd.h> header file. */ -/* #define HAVE_UNISTD_H 1 */ - -/* Define if you have the <utime.h> header file. */ -/* #define HAVE_UTIME_H 1 */ - -/* Define if you have the dl library (-ldl). */ -/* #undef HAVE_LIBDL */ - -/* Define if you have the mpc library (-lmpc). */ -/* #undef HAVE_LIBMPC */ - -/* Define if you have the nsl library (-lnsl). */ -#define HAVE_LIBNSL 1 - -/* Define if you have the seq library (-lseq). */ -/* #undef HAVE_LIBSEQ */ - -/* Define if you have the socket library (-lsocket). */ -#define HAVE_LIBSOCKET 1 - -/* Define if you have the sun library (-lsun). */ -/* #undef HAVE_LIBSUN */ - -/* Define if you have the termcap library (-ltermcap). */ -/* #undef HAVE_LIBTERMCAP */ - -/* Define if you have the termlib library (-ltermlib). */ -/* #undef HAVE_LIBTERMLIB */ - -/* Define if you have the thread library (-lthread). */ -/* #undef HAVE_LIBTHREAD */ -#ifdef __cplusplus -} -#endif -#endif /* !Py_CONFIG_H */ diff --git a/Parser/Makefile.in b/Parser/Makefile.in deleted file mode 100644 index 1b8f1f8b63..0000000000 --- a/Parser/Makefile.in +++ /dev/null @@ -1,91 +0,0 @@ -# NOTE: Makefile.in is converted into Makefile by the configure script -# in the parent directory. Once configure has run, you can recreate -# the Makefile by running just config.status. - -# === Variables set by config.stat === - -srcdir= @srcdir@ -VPATH= @srcdir@ - -CC= @CC@ -RANLIB= @RANLIB@ -AR= @AR@ - -DEFS= @DEFS@ - - -# === Other things that are customizable but not by configure === - -INCLDIR= $(srcdir)/../Include -OPT= @OPT@ -CFLAGS= $(OPT) -I$(INCLDIR) -I.. $(DEFS) - -MKDEP= mkdep -SHELL= /bin/sh - - -# === Fixed definitions === - -PARSEROBJS= acceler.o grammar1.o \ - intrcheck.o listnode.o myreadline.o node.o parser.o \ - parsetok.o tokenizer.o bitset.o \ - firstsets.o grammar.o metagrammar.o pgen.o \ - printgrammar.o - -PGENOBJS= pgenmain.o - -OBJS= $(PGENOBJS) $(PARSEROBJS) - -PGEN= pgen - -LIB= libParser.a - - -# === Rules === - -all: $(LIB) $(PGEN) - -$(LIB): $& $(PARSEROBJS) - -rm -f $(LIB) - $(AR) cr $(LIB) $(PARSEROBJS) - $(RANLIB) $(LIB) - -$(PGEN): $(PGENOBJS) $(LIB) - $(CC) $(OPT) $(PGENOBJS) $(LIB) -o $(PGEN) - -clean: - -rm -f *.o core *~ [@,#]* *.old *.orig *.rej - -clobber: clean - -rm -f $(PGEN) *.a tags TAGS - -Makefile: $(srcdir)/Makefile.in ../config.status - (cd ..; CONFIG_FILES=Parser/Makefile CONFIG_HEADERS= \ - $(SHELL) config.status) - -depend: - $(MKDEP) $(CFLAGS) `echo $(OBJS) | tr ' ' '\012' | \ - sed 's|\(.*\)\.o|$(srcdir)/\1.c|'` - -.PRECIOUS: Makefile - -acceler.o: acceler.c -grammar1.o: grammar1.c -intrcheck.o: intrcheck.c -listnode.o: listnode.c -myreadline.o: myreadline.c -node.o: node.c -parser.o: parser.c -parsetok.o: parsetok.c -tokenizer.o: tokenizer.c -bitset.o: bitset.c -firstsets.o: firstsets.c -grammar.o: grammar.c -metagrammar.o: metagrammar.c -pgen.o: pgen.c -printgrammar.o: printgrammar.c -pgenmain.o: pgenmain.c - -# DO NOT DELETE THIS LINE -- mkdep uses it. -# DO NOT PUT ANYTHING AFTER THIS LINE, IT WILL GO AWAY. -# IF YOU PUT ANYTHING HERE IT WILL GO AWAY diff --git a/Parser/acceler.c b/Parser/acceler.c deleted file mode 100644 index 9f75b5da6c..0000000000 --- a/Parser/acceler.c +++ /dev/null @@ -1,153 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Parser accelerator module */ - -/* The parser as originally conceived had disappointing performance. - This module does some precomputation that speeds up the selection - of a DFA based upon a token, turning a search through an array - into a simple indexing operation. The parser now cannot work - without the accelerators installed. Note that the accelerators - are installed dynamically when the parser is initialized, they - are not part of the static data structure written on graminit.[ch] - by the parser generator. */ - -#include "pgenheaders.h" -#include "grammar.h" -#include "node.h" -#include "token.h" -#include "parser.h" - -/* Forward references */ -static void fixdfa PROTO((grammar *, dfa *)); -static void fixstate PROTO((grammar *, state *)); - -void -addaccelerators(g) - grammar *g; -{ - dfa *d; - int i; -#ifdef DEBUG - fprintf(stderr, "Adding parser accelerators ...\n"); -#endif - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) - fixdfa(g, d); - g->g_accel = 1; -#ifdef DEBUG - fprintf(stderr, "Done.\n"); -#endif -} - -static void -fixdfa(g, d) - grammar *g; - dfa *d; -{ - state *s; - int j; - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) - fixstate(g, s); -} - -static void -fixstate(g, s) - grammar *g; - state *s; -{ - arc *a; - int k; - int *accel; - int nl = g->g_ll.ll_nlabels; - s->s_accept = 0; - accel = NEW(int, nl); - for (k = 0; k < nl; k++) - accel[k] = -1; - a = s->s_arc; - for (k = s->s_narcs; --k >= 0; a++) { - int lbl = a->a_lbl; - label *l = &g->g_ll.ll_label[lbl]; - int type = l->lb_type; - if (a->a_arrow >= (1 << 7)) { - printf("XXX too many states!\n"); - continue; - } - if (ISNONTERMINAL(type)) { - dfa *d1 = finddfa(g, type); - int ibit; - if (type - NT_OFFSET >= (1 << 7)) { - printf("XXX too high nonterminal number!\n"); - continue; - } - for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) { - if (testbit(d1->d_first, ibit)) { -#ifdef applec -#define MPW_881_BUG /* Undefine if bug below is fixed */ -#endif -#ifdef MPW_881_BUG - /* In 881 mode MPW 3.1 has a code - generation bug which seems to - set the upper bits; fix this by - explicitly masking them off */ - int temp; -#endif - if (accel[ibit] != -1) - printf("XXX ambiguity!\n"); -#ifdef MPW_881_BUG - temp = 0xFFFF & - (a->a_arrow | (1 << 7) | - ((type - NT_OFFSET) << 8)); - accel[ibit] = temp; -#else - accel[ibit] = a->a_arrow | (1 << 7) | - ((type - NT_OFFSET) << 8); -#endif - } - } - } - else if (lbl == EMPTY) - s->s_accept = 1; - else if (lbl >= 0 && lbl < nl) - accel[lbl] = a->a_arrow; - } - while (nl > 0 && accel[nl-1] == -1) - nl--; - for (k = 0; k < nl && accel[k] == -1;) - k++; - if (k < nl) { - int i; - s->s_accel = NEW(int, nl-k); - if (s->s_accel == NULL) { - fprintf(stderr, "no mem to add parser accelerators\n"); - exit(1); - } - s->s_lower = k; - s->s_upper = nl; - for (i = 0; k < nl; i++, k++) - s->s_accel[i] = accel[k]; - } - DEL(accel); -} diff --git a/Parser/assert.h b/Parser/assert.h deleted file mode 100644 index b0c08abee2..0000000000 --- a/Parser/assert.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef Py_ASSERT_H -#define Py_ASSERT_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#ifdef MPW /* This is for MPW's File command */ - -#define assert(e) { if (!(e)) { printf("### Python: Assertion failed:\n\ - File %s; Line %d\n", __FILE__, __LINE__); abort(); } } -#else -#define assert(e) { if (!(e)) { printf("Assertion failed\n"); abort(); } } -#endif - -#ifdef __cplusplus -} -#endif -#endif /* !Py_ASSERT_H */ diff --git a/Parser/bitset.c b/Parser/bitset.c deleted file mode 100644 index dd32d0e111..0000000000 --- a/Parser/bitset.c +++ /dev/null @@ -1,99 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Bitset primitives used by the parser generator */ - -#include "pgenheaders.h" -#include "bitset.h" - -bitset -newbitset(nbits) - int nbits; -{ - int nbytes = NBYTES(nbits); - bitset ss = NEW(BYTE, nbytes); - - if (ss == NULL) - fatal("no mem for bitset"); - - ss += nbytes; - while (--nbytes >= 0) - *--ss = 0; - return ss; -} - -void -delbitset(ss) - bitset ss; -{ - DEL(ss); -} - -int -addbit(ss, ibit) - bitset ss; - int ibit; -{ - int ibyte = BIT2BYTE(ibit); - BYTE mask = BIT2MASK(ibit); - - if (ss[ibyte] & mask) - return 0; /* Bit already set */ - ss[ibyte] |= mask; - return 1; -} - -#if 0 /* Now a macro */ -int -testbit(ss, ibit) - bitset ss; - int ibit; -{ - return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0; -} -#endif - -int -samebitset(ss1, ss2, nbits) - bitset ss1, ss2; - int nbits; -{ - int i; - - for (i = NBYTES(nbits); --i >= 0; ) - if (*ss1++ != *ss2++) - return 0; - return 1; -} - -void -mergebitset(ss1, ss2, nbits) - bitset ss1, ss2; - int nbits; -{ - int i; - - for (i = NBYTES(nbits); --i >= 0; ) - *ss1++ |= *ss2++; -} diff --git a/Parser/firstsets.c b/Parser/firstsets.c deleted file mode 100644 index b76230d4f9..0000000000 --- a/Parser/firstsets.c +++ /dev/null @@ -1,133 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Computation of FIRST stets */ - -#include "pgenheaders.h" -#include "grammar.h" -#include "token.h" - -extern int debugging; - -/* Forward */ -static void calcfirstset PROTO((grammar *, dfa *)); - -void -addfirstsets(g) - grammar *g; -{ - int i; - dfa *d; - - printf("Adding FIRST sets ...\n"); - for (i = 0; i < g->g_ndfas; i++) { - d = &g->g_dfa[i]; - if (d->d_first == NULL) - calcfirstset(g, d); - } -} - -static void -calcfirstset(g, d) - grammar *g; - dfa *d; -{ - int i, j; - state *s; - arc *a; - int nsyms; - int *sym; - int nbits; - static bitset dummy; - bitset result; - int type; - dfa *d1; - label *l0; - - if (debugging) - printf("Calculate FIRST set for '%s'\n", d->d_name); - - if (dummy == NULL) - dummy = newbitset(1); - if (d->d_first == dummy) { - fprintf(stderr, "Left-recursion for '%s'\n", d->d_name); - return; - } - if (d->d_first != NULL) { - fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n", - d->d_name); - } - d->d_first = dummy; - - l0 = g->g_ll.ll_label; - nbits = g->g_ll.ll_nlabels; - result = newbitset(nbits); - - sym = NEW(int, 1); - if (sym == NULL) - fatal("no mem for new sym in calcfirstset"); - nsyms = 1; - sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL); - - s = &d->d_state[d->d_initial]; - for (i = 0; i < s->s_narcs; i++) { - a = &s->s_arc[i]; - for (j = 0; j < nsyms; j++) { - if (sym[j] == a->a_lbl) - break; - } - if (j >= nsyms) { /* New label */ - RESIZE(sym, int, nsyms + 1); - if (sym == NULL) - fatal("no mem to resize sym in calcfirstset"); - sym[nsyms++] = a->a_lbl; - type = l0[a->a_lbl].lb_type; - if (ISNONTERMINAL(type)) { - d1 = finddfa(g, type); - if (d1->d_first == dummy) { - fprintf(stderr, - "Left-recursion below '%s'\n", - d->d_name); - } - else { - if (d1->d_first == NULL) - calcfirstset(g, d1); - mergebitset(result, d1->d_first, nbits); - } - } - else if (ISTERMINAL(type)) { - addbit(result, a->a_lbl); - } - } - } - d->d_first = result; - if (debugging) { - printf("FIRST set for '%s': {", d->d_name); - for (i = 0; i < nbits; i++) { - if (testbit(result, i)) - printf(" %s", labelrepr(&l0[i])); - } - printf(" }\n"); - } -} diff --git a/Parser/grammar.c b/Parser/grammar.c deleted file mode 100644 index 90050272b0..0000000000 --- a/Parser/grammar.c +++ /dev/null @@ -1,249 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Grammar implementation */ - -#include "pgenheaders.h" - -#include <ctype.h> - -#include "assert.h" -#include "token.h" -#include "grammar.h" - -extern int debugging; - -grammar * -newgrammar(start) - int start; -{ - grammar *g; - - g = NEW(grammar, 1); - if (g == NULL) - fatal("no mem for new grammar"); - g->g_ndfas = 0; - g->g_dfa = NULL; - g->g_start = start; - g->g_ll.ll_nlabels = 0; - g->g_ll.ll_label = NULL; - g->g_accel = 0; - return g; -} - -dfa * -adddfa(g, type, name) - grammar *g; - int type; - char *name; -{ - dfa *d; - - RESIZE(g->g_dfa, dfa, g->g_ndfas + 1); - if (g->g_dfa == NULL) - fatal("no mem to resize dfa in adddfa"); - d = &g->g_dfa[g->g_ndfas++]; - d->d_type = type; - d->d_name = name; - d->d_nstates = 0; - d->d_state = NULL; - d->d_initial = -1; - d->d_first = NULL; - return d; /* Only use while fresh! */ -} - -int -addstate(d) - dfa *d; -{ - state *s; - - RESIZE(d->d_state, state, d->d_nstates + 1); - if (d->d_state == NULL) - fatal("no mem to resize state in addstate"); - s = &d->d_state[d->d_nstates++]; - s->s_narcs = 0; - s->s_arc = NULL; - s->s_lower = 0; - s->s_upper = 0; - s->s_accel = NULL; - s->s_accept = 0; - return s - d->d_state; -} - -void -addarc(d, from, to, lbl) - dfa *d; - int lbl; -{ - state *s; - arc *a; - - assert(0 <= from && from < d->d_nstates); - assert(0 <= to && to < d->d_nstates); - - s = &d->d_state[from]; - RESIZE(s->s_arc, arc, s->s_narcs + 1); - if (s->s_arc == NULL) - fatal("no mem to resize arc list in addarc"); - a = &s->s_arc[s->s_narcs++]; - a->a_lbl = lbl; - a->a_arrow = to; -} - -int -addlabel(ll, type, str) - labellist *ll; - int type; - char *str; -{ - int i; - label *lb; - - for (i = 0; i < ll->ll_nlabels; i++) { - if (ll->ll_label[i].lb_type == type && - strcmp(ll->ll_label[i].lb_str, str) == 0) - return i; - } - RESIZE(ll->ll_label, label, ll->ll_nlabels + 1); - if (ll->ll_label == NULL) - fatal("no mem to resize labellist in addlabel"); - lb = &ll->ll_label[ll->ll_nlabels++]; - lb->lb_type = type; - lb->lb_str = str; /* XXX strdup(str) ??? */ - return lb - ll->ll_label; -} - -/* Same, but rather dies than adds */ - -int -findlabel(ll, type, str) - labellist *ll; - int type; - char *str; -{ - int i; - - for (i = 0; i < ll->ll_nlabels; i++) { - if (ll->ll_label[i].lb_type == type /*&& - strcmp(ll->ll_label[i].lb_str, str) == 0*/) - return i; - } - fprintf(stderr, "Label %d/'%s' not found\n", type, str); - fatal("grammar.c:findlabel()"); - /*NOTREACHED*/ -} - -/* Forward */ -static void translabel PROTO((grammar *, label *)); - -void -translatelabels(g) - grammar *g; -{ - int i; - -#ifdef DEBUG - printf("Translating labels ...\n"); -#endif - /* Don't translate EMPTY */ - for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) - translabel(g, &g->g_ll.ll_label[i]); -} - -static void -translabel(g, lb) - grammar *g; - label *lb; -{ - int i; - - if (debugging) - printf("Translating label %s ...\n", labelrepr(lb)); - - if (lb->lb_type == NAME) { - for (i = 0; i < g->g_ndfas; i++) { - if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { - if (debugging) - printf("Label %s is non-terminal %d.\n", - lb->lb_str, - g->g_dfa[i].d_type); - lb->lb_type = g->g_dfa[i].d_type; - lb->lb_str = NULL; - return; - } - } - for (i = 0; i < (int)N_TOKENS; i++) { - if (strcmp(lb->lb_str, tok_name[i]) == 0) { - if (debugging) - printf("Label %s is terminal %d.\n", - lb->lb_str, i); - lb->lb_type = i; - lb->lb_str = NULL; - return; - } - } - printf("Can't translate NAME label '%s'\n", lb->lb_str); - return; - } - - if (lb->lb_type == STRING) { - if (isalpha(lb->lb_str[1])) { - char *p; - if (debugging) - printf("Label %s is a keyword\n", lb->lb_str); - lb->lb_type = NAME; - lb->lb_str++; - p = strchr(lb->lb_str, '\''); - if (p) - *p = '\0'; - } - else if (lb->lb_str[2] == lb->lb_str[0]) { - int type = (int) tok_1char(lb->lb_str[1]); - if (type != OP) { - lb->lb_type = type; - lb->lb_str = NULL; - } - else - printf("Unknown OP label %s\n", - lb->lb_str); - } - else if (lb->lb_str[2] && lb->lb_str[3] == lb->lb_str[0]) { - int type = (int) tok_2char(lb->lb_str[1], - lb->lb_str[2]); - if (type != OP) { - lb->lb_type = type; - lb->lb_str = NULL; - } - else - printf("Unknown OP label %s\n", - lb->lb_str); - } - else - printf("Can't translate STRING label %s\n", - lb->lb_str); - } - else - printf("Can't translate label '%s'\n", labelrepr(lb)); -} diff --git a/Parser/grammar1.c b/Parser/grammar1.c deleted file mode 100644 index 2abd3db371..0000000000 --- a/Parser/grammar1.c +++ /dev/null @@ -1,83 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Grammar subroutines needed by parser */ - -#include "pgenheaders.h" -#include "assert.h" -#include "grammar.h" -#include "token.h" - -/* Return the DFA for the given type */ - -dfa * -finddfa(g, type) - grammar *g; - register int type; -{ - register dfa *d; -#if 1 - /* Massive speed-up */ - d = &g->g_dfa[type - NT_OFFSET]; - assert(d->d_type == type); - return d; -#else - /* Old, slow version */ - register int i; - - for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) { - if (d->d_type == type) - return d; - } - assert(0); - /* NOTREACHED */ -#endif -} - -char * -labelrepr(lb) - label *lb; -{ - static char buf[100]; - - if (lb->lb_type == ENDMARKER) - return "EMPTY"; - else if (ISNONTERMINAL(lb->lb_type)) { - if (lb->lb_str == NULL) { - sprintf(buf, "NT%d", lb->lb_type); - return buf; - } - else - return lb->lb_str; - } - else { - if (lb->lb_str == NULL) - return tok_name[lb->lb_type]; - else { - sprintf(buf, "%.32s(%.32s)", - tok_name[lb->lb_type], lb->lb_str); - return buf; - } - } -} diff --git a/Parser/intrcheck.c b/Parser/intrcheck.c deleted file mode 100644 index dd53a1acc2..0000000000 --- a/Parser/intrcheck.c +++ /dev/null @@ -1,184 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Check for interrupts */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "myproto.h" -#include "intrcheck.h" - - -#ifdef QUICKWIN - -#include <io.h> - -void -initintr() -{ -} - -int -intrcheck() -{ - _wyield(); -} - -#define OK - -#endif /* QUICKWIN */ - -#ifdef _M_IX86 -#include <io.h> -#endif - -#if defined(MSDOS) && !defined(QUICKWIN) - -#ifdef __GNUC__ - -/* This is for DJGPP's GO32 extender. I don't know how to trap - * control-C (There's no API for ctrl-C, and I don't want to mess with - * the interrupt vectors.) However, this DOES catch control-break. - * --Amrit - */ - -#include <go32.h> - -void -initintr() -{ - _go32_want_ctrl_break(1 /* TRUE */); -} - -int -intrcheck() -{ - return _go32_was_ctrl_break_hit(); -} - -#else /* !__GNUC__ */ - -/* This might work for MS-DOS (untested though): */ - -void -initintr() -{ -} - -int -intrcheck() -{ - int interrupted = 0; - while (kbhit()) { - if (getch() == '\003') - interrupted = 1; - } - return interrupted; -} - -#endif /* __GNUC__ */ - -#define OK - -#endif /* MSDOS && !QUICKWIN */ - - -#ifdef macintosh - -/* The Mac interrupt code has moved to macglue.c */ -#define OK - -#endif /* macintosh */ - - -#ifndef OK - -/* Default version -- for real operating systems and for Standard C */ - -#include <stdio.h> -#include <string.h> -#include <signal.h> - -static int interrupted; - -void -PyErr_SetInterrupt() -{ - interrupted = 1; -} - -/* ARGSUSED */ -static RETSIGTYPE -#ifdef _M_IX86 -intcatcher(int sig) /* So the C compiler shuts up */ -#else /* _M_IX86 */ -intcatcher(sig) - int sig; /* Not used by required by interface */ -#endif /* _M_IX86 */ -{ - extern void goaway PROTO((int)); - static char message[] = -"python: to interrupt a truly hanging Python program, interrupt once more.\n"; - switch (interrupted++) { - case 0: - break; - case 1: - write(2, message, strlen(message)); - break; - case 2: - interrupted = 0; - goaway(1); - break; - } - signal(SIGINT, intcatcher); -} - -void -initintr() -{ - if (signal(SIGINT, SIG_IGN) != SIG_IGN) - signal(SIGINT, intcatcher); -#ifdef HAVE_SIGINTERRUPT - /* This is for SunOS and other modern BSD derivatives. - It means that system calls (like read()) are not restarted - after an interrupt. This is necessary so interrupting a - read() or readline() call works as expected. - XXX On old BSD (pure 4.2 or older) you may have to do this - differently! */ - siginterrupt(SIGINT, 1); -#endif /* HAVE_SIGINTERRUPT */ -} - -int -intrcheck() -{ - if (!interrupted) - return 0; - interrupted = 0; - return 1; -} - -#endif /* !OK */ diff --git a/Parser/listnode.c b/Parser/listnode.c deleted file mode 100644 index 719b1bb9c9..0000000000 --- a/Parser/listnode.c +++ /dev/null @@ -1,94 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* List a node on a file */ - -#include "pgenheaders.h" -#include "token.h" -#include "node.h" - -/* Forward */ -static void list1node PROTO((FILE *, node *)); -static void listnode PROTO((FILE *, node *)); - -void -listtree(n) - node *n; -{ - listnode(stdout, n); -} - -static int level, atbol; - -static void -listnode(fp, n) - FILE *fp; - node *n; -{ - level = 0; - atbol = 1; - list1node(fp, n); -} - -static void -list1node(fp, n) - FILE *fp; - node *n; -{ - if (n == 0) - return; - if (ISNONTERMINAL(TYPE(n))) { - int i; - for (i = 0; i < NCH(n); i++) - list1node(fp, CHILD(n, i)); - } - else if (ISTERMINAL(TYPE(n))) { - switch (TYPE(n)) { - case INDENT: - ++level; - break; - case DEDENT: - --level; - break; - default: - if (atbol) { - int i; - for (i = 0; i < level; ++i) - fprintf(fp, "\t"); - atbol = 0; - } - if (TYPE(n) == NEWLINE) { - if (STR(n) != NULL) - fprintf(fp, "%s", STR(n)); - fprintf(fp, "\n"); - atbol = 1; - } - else - fprintf(fp, "%s ", STR(n)); - break; - } - } - else - fprintf(fp, "? "); -} diff --git a/Parser/metagrammar.c b/Parser/metagrammar.c deleted file mode 100644 index bb0750bc13..0000000000 --- a/Parser/metagrammar.c +++ /dev/null @@ -1,176 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#include "pgenheaders.h" -#include "metagrammar.h" -#include "grammar.h" -#include "pgen.h" -static arc arcs_0_0[3] = { - {2, 0}, - {3, 0}, - {4, 1}, -}; -static arc arcs_0_1[1] = { - {0, 1}, -}; -static state states_0[2] = { - {3, arcs_0_0}, - {1, arcs_0_1}, -}; -static arc arcs_1_0[1] = { - {5, 1}, -}; -static arc arcs_1_1[1] = { - {6, 2}, -}; -static arc arcs_1_2[1] = { - {7, 3}, -}; -static arc arcs_1_3[1] = { - {3, 4}, -}; -static arc arcs_1_4[1] = { - {0, 4}, -}; -static state states_1[5] = { - {1, arcs_1_0}, - {1, arcs_1_1}, - {1, arcs_1_2}, - {1, arcs_1_3}, - {1, arcs_1_4}, -}; -static arc arcs_2_0[1] = { - {8, 1}, -}; -static arc arcs_2_1[2] = { - {9, 0}, - {0, 1}, -}; -static state states_2[2] = { - {1, arcs_2_0}, - {2, arcs_2_1}, -}; -static arc arcs_3_0[1] = { - {10, 1}, -}; -static arc arcs_3_1[2] = { - {10, 1}, - {0, 1}, -}; -static state states_3[2] = { - {1, arcs_3_0}, - {2, arcs_3_1}, -}; -static arc arcs_4_0[2] = { - {11, 1}, - {13, 2}, -}; -static arc arcs_4_1[1] = { - {7, 3}, -}; -static arc arcs_4_2[3] = { - {14, 4}, - {15, 4}, - {0, 2}, -}; -static arc arcs_4_3[1] = { - {12, 4}, -}; -static arc arcs_4_4[1] = { - {0, 4}, -}; -static state states_4[5] = { - {2, arcs_4_0}, - {1, arcs_4_1}, - {3, arcs_4_2}, - {1, arcs_4_3}, - {1, arcs_4_4}, -}; -static arc arcs_5_0[3] = { - {5, 1}, - {16, 1}, - {17, 2}, -}; -static arc arcs_5_1[1] = { - {0, 1}, -}; -static arc arcs_5_2[1] = { - {7, 3}, -}; -static arc arcs_5_3[1] = { - {18, 1}, -}; -static state states_5[4] = { - {3, arcs_5_0}, - {1, arcs_5_1}, - {1, arcs_5_2}, - {1, arcs_5_3}, -}; -static dfa dfas[6] = { - {256, "MSTART", 0, 2, states_0, - "\070\000\000"}, - {257, "RULE", 0, 5, states_1, - "\040\000\000"}, - {258, "RHS", 0, 2, states_2, - "\040\010\003"}, - {259, "ALT", 0, 2, states_3, - "\040\010\003"}, - {260, "ITEM", 0, 5, states_4, - "\040\010\003"}, - {261, "ATOM", 0, 4, states_5, - "\040\000\003"}, -}; -static label labels[19] = { - {0, "EMPTY"}, - {256, 0}, - {257, 0}, - {4, 0}, - {0, 0}, - {1, 0}, - {11, 0}, - {258, 0}, - {259, 0}, - {18, 0}, - {260, 0}, - {9, 0}, - {10, 0}, - {261, 0}, - {16, 0}, - {14, 0}, - {3, 0}, - {7, 0}, - {8, 0}, -}; -static grammar gram = { - 6, - dfas, - {19, labels}, - 256 -}; - -grammar * -meta_grammar() -{ - return &gram; -} diff --git a/Parser/myreadline.c b/Parser/myreadline.c deleted file mode 100644 index d210d8b963..0000000000 --- a/Parser/myreadline.c +++ /dev/null @@ -1,191 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Readline interface for tokenizer.c. - By default, we have a super simple my_readline function. - Optionally, we can use the GNU readline library (to be found in the - bash distribution). - my_readline() has a different return value from GNU readline(): - - NULL if an interrupt occurred or if an error occurred - - a malloc'ed empty string if EOF was read - - a malloc'ed string ending in \n normally -*/ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include <stdio.h> -#include <string.h> -#include <errno.h> - -#include "myproto.h" -#include "mymalloc.h" -#include "intrcheck.h" - -#ifdef WITH_READLINE - -extern char *readline(); - -#include <setjmp.h> -#include <signal.h> - -static jmp_buf jbuf; - -/* ARGSUSED */ -static RETSIGTYPE -onintr(sig) - int sig; -{ - longjmp(jbuf, 1); -} - -#else /* !WITH_READLINE */ - -/* This function restarts a fgets() after an EINTR error occurred - except if intrcheck() returns true. */ - -static int -my_fgets(buf, len, fp) - char *buf; - int len; - FILE *fp; -{ - char *p; - for (;;) { - errno = 0; - p = fgets(buf, len, fp); - if (p != NULL) - return 0; /* No error */ - if (feof(fp)) { - return -1; /* EOF */ - } -#ifdef EINTR - if (errno == EINTR) { - if (intrcheck()) { - return 1; /* Interrupt */ - } - continue; - } -#endif - if (intrcheck()) { - return 1; /* Interrupt */ - } - return -2; /* Error */ - } - /* NOTREACHED */ -} - -#endif /* WITH_READLINE */ - - -#ifdef WITH_READLINE -void -PyOS_ReadlineInit() -{ - static int been_here; - if (!been_here) { - /* Force rebind of TAB to insert-tab */ - extern int rl_insert(); - rl_bind_key('\t', rl_insert); - been_here++; - } -} -#endif - - -char * -my_readline(prompt) - char *prompt; -{ - int n; - char *p; -#ifdef WITH_READLINE - RETSIGTYPE (*old_inthandler)(); - PyOS_ReadlineInit(); - old_inthandler = signal(SIGINT, onintr); - if (setjmp(jbuf)) { -#ifdef HAVE_SIGRELSE - /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */ - sigrelse(SIGINT); -#endif - signal(SIGINT, old_inthandler); - return NULL; - } - p = readline(prompt); - signal(SIGINT, old_inthandler); - if (p == NULL) { - p = malloc(1); - if (p != NULL) - *p = '\0'; - return p; - } - n = strlen(p); - if (n > 0) - add_history(p); - if ((p = realloc(p, n+2)) != NULL) { - p[n] = '\n'; - p[n+1] = '\0'; - } - return p; -#else /* !WITH_READLINE */ - n = 100; - if ((p = malloc(n)) == NULL) - return NULL; - fflush(stdout); - if (prompt) - fprintf(stderr, "%s", prompt); - fflush(stderr); - switch (my_fgets(p, n, stdin)) { - case 0: /* Normal case */ - break; - case 1: /* Interrupt */ - free(p); - return NULL; - case -1: /* EOF */ - case -2: /* Error */ - default: /* Shouldn't happen */ - *p = '\0'; - break; - } -#ifdef MPW - /* Hack for MPW C where the prompt comes right back in the input */ - /* XXX (Actually this would be rather nice on most systems...) */ - n = strlen(prompt); - if (strncmp(p, prompt, n) == 0) - memmove(p, p + n, strlen(p) - n + 1); -#endif - n = strlen(p); - while (n > 0 && p[n-1] != '\n') { - int incr = n+2; - p = realloc(p, n + incr); - if (p == NULL) - return NULL; - if (my_fgets(p+n, incr, stdin) != 0) - break; - n += strlen(p+n); - } - return realloc(p, n+1); -#endif /* !WITH_READLINE */ -} diff --git a/Parser/node.c b/Parser/node.c deleted file mode 100644 index 2c048c7adb..0000000000 --- a/Parser/node.c +++ /dev/null @@ -1,100 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Parse tree node implementation */ - -#include "pgenheaders.h" -#include "node.h" - -node * -newtree(type) - int type; -{ - node *n = NEW(node, 1); - if (n == NULL) - return NULL; - n->n_type = type; - n->n_str = NULL; - n->n_lineno = 0; - n->n_nchildren = 0; - n->n_child = NULL; - return n; -} - -#define XXX 3 /* Node alignment factor to speed up realloc */ -#define XXXROUNDUP(n) ((n) == 1 ? 1 : ((n) + XXX - 1) / XXX * XXX) - -node * -addchild(n1, type, str, lineno) - register node *n1; - int type; - char *str; - int lineno; -{ - register int nch = n1->n_nchildren; - register int nch1 = nch+1; - register node *n; - if (XXXROUNDUP(nch) < nch1) { - n = n1->n_child; - nch1 = XXXROUNDUP(nch1); - RESIZE(n, node, nch1); - if (n == NULL) - return NULL; - n1->n_child = n; - } - n = &n1->n_child[n1->n_nchildren++]; - n->n_type = type; - n->n_str = str; - n->n_lineno = lineno; - n->n_nchildren = 0; - n->n_child = NULL; - return n; -} - -/* Forward */ -static void freechildren PROTO((node *)); - - -void -freetree(n) - node *n; -{ - if (n != NULL) { - freechildren(n); - DEL(n); - } -} - -static void -freechildren(n) - node *n; -{ - int i; - for (i = NCH(n); --i >= 0; ) - freechildren(CHILD(n, i)); - if (n->n_child != NULL) - DEL(n->n_child); - if (STR(n) != NULL) - DEL(STR(n)); -} diff --git a/Parser/parser.c b/Parser/parser.c deleted file mode 100644 index 54cc9ee33c..0000000000 --- a/Parser/parser.c +++ /dev/null @@ -1,421 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Parser implementation */ - -/* For a description, see the comments at end of this file */ - -/* XXX To do: error recovery */ - -#include "pgenheaders.h" -#include "assert.h" -#include "token.h" -#include "grammar.h" -#include "node.h" -#include "parser.h" -#include "errcode.h" - - -#ifdef DEBUG -extern int debugging; -#define D(x) if (!debugging); else x -#else -#define D(x) -#endif - - -/* STACK DATA TYPE */ - -static void s_reset PROTO((stack *)); - -static void -s_reset(s) - stack *s; -{ - s->s_top = &s->s_base[MAXSTACK]; -} - -#define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK]) - -static int s_push PROTO((stack *, dfa *, node *)); - -static int -s_push(s, d, parent) - register stack *s; - dfa *d; - node *parent; -{ - register stackentry *top; - if (s->s_top == s->s_base) { - fprintf(stderr, "s_push: parser stack overflow\n"); - return -1; - } - top = --s->s_top; - top->s_dfa = d; - top->s_parent = parent; - top->s_state = 0; - return 0; -} - -#ifdef DEBUG - -static void s_pop PROTO((stack *)); - -static void -s_pop(s) - register stack *s; -{ - if (s_empty(s)) - fatal("s_pop: parser stack underflow -- FATAL"); - s->s_top++; -} - -#else /* !DEBUG */ - -#define s_pop(s) (s)->s_top++ - -#endif - - -/* PARSER CREATION */ - -parser_state * -newparser(g, start) - grammar *g; - int start; -{ - parser_state *ps; - - if (!g->g_accel) - addaccelerators(g); - ps = NEW(parser_state, 1); - if (ps == NULL) - return NULL; - ps->p_grammar = g; - ps->p_tree = newtree(start); - if (ps->p_tree == NULL) { - DEL(ps); - return NULL; - } - s_reset(&ps->p_stack); - (void) s_push(&ps->p_stack, finddfa(g, start), ps->p_tree); - return ps; -} - -void -delparser(ps) - parser_state *ps; -{ - /* NB If you want to save the parse tree, - you must set p_tree to NULL before calling delparser! */ - freetree(ps->p_tree); - DEL(ps); -} - - -/* PARSER STACK OPERATIONS */ - -static int shift PROTO((stack *, int, char *, int, int)); - -static int -shift(s, type, str, newstate, lineno) - register stack *s; - int type; - char *str; - int newstate; - int lineno; -{ - assert(!s_empty(s)); - if (addchild(s->s_top->s_parent, type, str, lineno) == NULL) { - fprintf(stderr, "shift: no mem in addchild\n"); - return -1; - } - s->s_top->s_state = newstate; - return 0; -} - -static int push PROTO((stack *, int, dfa *, int, int)); - -static int -push(s, type, d, newstate, lineno) - register stack *s; - int type; - dfa *d; - int newstate; - int lineno; -{ - register node *n; - n = s->s_top->s_parent; - assert(!s_empty(s)); - if (addchild(n, type, (char *)NULL, lineno) == NULL) { - fprintf(stderr, "push: no mem in addchild\n"); - return -1; - } - s->s_top->s_state = newstate; - return s_push(s, d, CHILD(n, NCH(n)-1)); -} - - -/* PARSER PROPER */ - -static int classify PROTO((grammar *, int, char *)); - -static int -classify(g, type, str) - grammar *g; - register int type; - char *str; -{ - register int n = g->g_ll.ll_nlabels; - - if (type == NAME) { - register char *s = str; - register label *l = g->g_ll.ll_label; - register int i; - for (i = n; i > 0; i--, l++) { - if (l->lb_type == NAME && l->lb_str != NULL && - l->lb_str[0] == s[0] && - strcmp(l->lb_str, s) == 0) { - D(printf("It's a keyword\n")); - return n - i; - } - } - } - - { - register label *l = g->g_ll.ll_label; - register int i; - for (i = n; i > 0; i--, l++) { - if (l->lb_type == type && l->lb_str == NULL) { - D(printf("It's a token we know\n")); - return n - i; - } - } - } - - D(printf("Illegal token\n")); - return -1; -} - -int -addtoken(ps, type, str, lineno) - register parser_state *ps; - register int type; - char *str; - int lineno; -{ - register int ilabel; - - D(printf("Token %s/'%s' ... ", tok_name[type], str)); - - /* Find out which label this token is */ - ilabel = classify(ps->p_grammar, type, str); - if (ilabel < 0) - return E_SYNTAX; - - /* Loop until the token is shifted or an error occurred */ - for (;;) { - /* Fetch the current dfa and state */ - register dfa *d = ps->p_stack.s_top->s_dfa; - register state *s = &d->d_state[ps->p_stack.s_top->s_state]; - - D(printf(" DFA '%s', state %d:", - d->d_name, ps->p_stack.s_top->s_state)); - - /* Check accelerator */ - if (s->s_lower <= ilabel && ilabel < s->s_upper) { - register int x = s->s_accel[ilabel - s->s_lower]; - if (x != -1) { - if (x & (1<<7)) { - /* Push non-terminal */ - int nt = (x >> 8) + NT_OFFSET; - int arrow = x & ((1<<7)-1); - dfa *d1 = finddfa(ps->p_grammar, nt); - if (push(&ps->p_stack, nt, d1, - arrow, lineno) < 0) { - D(printf(" MemError: push.\n")); - return E_NOMEM; - } - D(printf(" Push ...\n")); - continue; - } - - /* Shift the token */ - if (shift(&ps->p_stack, type, str, - x, lineno) < 0) { - D(printf(" MemError: shift.\n")); - return E_NOMEM; - } - D(printf(" Shift.\n")); - /* Pop while we are in an accept-only state */ - while (s = &d->d_state - [ps->p_stack.s_top->s_state], - s->s_accept && s->s_narcs == 1) { - D(printf(" Direct pop.\n")); - s_pop(&ps->p_stack); - if (s_empty(&ps->p_stack)) { - D(printf(" ACCEPT.\n")); - return E_DONE; - } - d = ps->p_stack.s_top->s_dfa; - } - return E_OK; - } - } - - if (s->s_accept) { - /* Pop this dfa and try again */ - s_pop(&ps->p_stack); - D(printf(" Pop ...\n")); - if (s_empty(&ps->p_stack)) { - D(printf(" Error: bottom of stack.\n")); - return E_SYNTAX; - } - continue; - } - - /* Stuck, report syntax error */ - D(printf(" Error.\n")); - return E_SYNTAX; - } -} - - -#ifdef DEBUG - -/* DEBUG OUTPUT */ - -void -dumptree(g, n) - grammar *g; - node *n; -{ - int i; - - if (n == NULL) - printf("NIL"); - else { - label l; - l.lb_type = TYPE(n); - l.lb_str = STR(n); - printf("%s", labelrepr(&l)); - if (ISNONTERMINAL(TYPE(n))) { - printf("("); - for (i = 0; i < NCH(n); i++) { - if (i > 0) - printf(","); - dumptree(g, CHILD(n, i)); - } - printf(")"); - } - } -} - -void -showtree(g, n) - grammar *g; - node *n; -{ - int i; - - if (n == NULL) - return; - if (ISNONTERMINAL(TYPE(n))) { - for (i = 0; i < NCH(n); i++) - showtree(g, CHILD(n, i)); - } - else if (ISTERMINAL(TYPE(n))) { - printf("%s", tok_name[TYPE(n)]); - if (TYPE(n) == NUMBER || TYPE(n) == NAME) - printf("(%s)", STR(n)); - printf(" "); - } - else - printf("? "); -} - -void -printtree(ps) - parser_state *ps; -{ - if (debugging) { - printf("Parse tree:\n"); - dumptree(ps->p_grammar, ps->p_tree); - printf("\n"); - printf("Tokens:\n"); - showtree(ps->p_grammar, ps->p_tree); - printf("\n"); - } - printf("Listing:\n"); - listtree(ps->p_tree); - printf("\n"); -} - -#endif /* DEBUG */ - -/* - -Description ------------ - -The parser's interface is different than usual: the function addtoken() -must be called for each token in the input. This makes it possible to -turn it into an incremental parsing system later. The parsing system -constructs a parse tree as it goes. - -A parsing rule is represented as a Deterministic Finite-state Automaton -(DFA). A node in a DFA represents a state of the parser; an arc represents -a transition. Transitions are either labeled with terminal symbols or -with non-terminals. When the parser decides to follow an arc labeled -with a non-terminal, it is invoked recursively with the DFA representing -the parsing rule for that as its initial state; when that DFA accepts, -the parser that invoked it continues. The parse tree constructed by the -recursively called parser is inserted as a child in the current parse tree. - -The DFA's can be constructed automatically from a more conventional -language description. An extended LL(1) grammar (ELL(1)) is suitable. -Certain restrictions make the parser's life easier: rules that can produce -the empty string should be outlawed (there are other ways to put loops -or optional parts in the language). To avoid the need to construct -FIRST sets, we can require that all but the last alternative of a rule -(really: arc going out of a DFA's state) must begin with a terminal -symbol. - -As an example, consider this grammar: - -expr: term (OP term)* -term: CONSTANT | '(' expr ')' - -The DFA corresponding to the rule for expr is: - -------->.---term-->.-------> - ^ | - | | - \----OP----/ - -The parse tree generated for the input a+b is: - -(expr: (term: (NAME: a)), (OP: +), (term: (NAME: b))) - -*/ diff --git a/Parser/parser.h b/Parser/parser.h deleted file mode 100644 index 9949a0edf8..0000000000 --- a/Parser/parser.h +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef Py_PARSER_H -#define Py_PARSER_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Parser interface */ - -#define MAXSTACK 500 - -typedef struct { - int s_state; /* State in current DFA */ - dfa *s_dfa; /* Current DFA */ - struct _node *s_parent; /* Where to add next node */ -} stackentry; - -typedef struct { - stackentry *s_top; /* Top entry */ - stackentry s_base[MAXSTACK];/* Array of stack entries */ - /* NB The stack grows down */ -} stack; - -typedef struct { - stack p_stack; /* Stack of parser states */ - grammar *p_grammar; /* Grammar to use */ - node *p_tree; /* Top of parse tree */ -} parser_state; - -parser_state *newparser PROTO((grammar *g, int start)); -void delparser PROTO((parser_state *ps)); -int addtoken PROTO((parser_state *ps, int type, char *str, int lineno)); -void addaccelerators PROTO((grammar *g)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_PARSER_H */ diff --git a/Parser/parsetok.c b/Parser/parsetok.c deleted file mode 100644 index 5e7957e299..0000000000 --- a/Parser/parsetok.c +++ /dev/null @@ -1,181 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Parser-tokenizer link implementation */ - -#include "pgenheaders.h" -#include "tokenizer.h" -#include "node.h" -#include "grammar.h" -#include "parser.h" -#include "parsetok.h" -#include "errcode.h" - - -/* Forward */ -static node *parsetok PROTO((struct tok_state *, grammar *, int, - perrdetail *)); - -/* Parse input coming from a string. Return error code, print some errors. */ - -node * -parsestring(s, g, start, err_ret) - char *s; - grammar *g; - int start; - perrdetail *err_ret; -{ - struct tok_state *tok; - - err_ret->error = E_OK; - err_ret->filename = NULL; - err_ret->lineno = 0; - err_ret->offset = 0; - err_ret->text = NULL; - - if ((tok = tok_setups(s)) == NULL) { - err_ret->error = E_NOMEM; - return NULL; - } - - return parsetok(tok, g, start, err_ret); -} - - -/* Parse input coming from a file. Return error code, print some errors. */ - -node * -parsefile(fp, filename, g, start, ps1, ps2, err_ret) - FILE *fp; - char *filename; - grammar *g; - int start; - char *ps1, *ps2; - perrdetail *err_ret; -{ - struct tok_state *tok; - - err_ret->error = E_OK; - err_ret->filename = filename; - err_ret->lineno = 0; - err_ret->offset = 0; - err_ret->text = NULL; - - if ((tok = tok_setupf(fp, ps1, ps2)) == NULL) { - err_ret->error = E_NOMEM; - return NULL; - } - -#ifdef macintosh - { - int tabsize = guesstabsize(filename); - if (tabsize > 0) - tok->tabsize = tabsize; - } -#endif - - return parsetok(tok, g, start, err_ret); -} - -/* Parse input coming from the given tokenizer structure. - Return error code. */ - -static node * -parsetok(tok, g, start, err_ret) - struct tok_state *tok; - grammar *g; - int start; - perrdetail *err_ret; -{ - parser_state *ps; - node *n; - int started = 0; - - if ((ps = newparser(g, start)) == NULL) { - fprintf(stderr, "no mem for new parser\n"); - err_ret->error = E_NOMEM; - return NULL; - } - - for (;;) { - char *a, *b; - int type; - int len; - char *str; - - type = tok_get(tok, &a, &b); - if (type == ERRORTOKEN) { - err_ret->error = tok->done; - break; - } - if (type == ENDMARKER && started) { - type = NEWLINE; /* Add an extra newline */ - started = 0; - } - else - started = 1; - len = b - a; /* XXX this may compute NULL - NULL */ - str = NEW(char, len + 1); - if (str == NULL) { - fprintf(stderr, "no mem for next token\n"); - err_ret->error = E_NOMEM; - break; - } - if (len > 0) - strncpy(str, a, len); - str[len] = '\0'; - if ((err_ret->error = - addtoken(ps, (int)type, str, tok->lineno)) != E_OK) - break; - } - - if (err_ret->error == E_DONE) { - n = ps->p_tree; - ps->p_tree = NULL; - } - else - n = NULL; - - delparser(ps); - - if (n == NULL) { - if (tok->lineno <= 1 && tok->done == E_EOF) - err_ret->error = E_EOF; - err_ret->lineno = tok->lineno; - err_ret->offset = tok->cur - tok->buf; - if (tok->buf != NULL) { - int len = tok->inp - tok->buf; - err_ret->text = malloc(len + 1); - if (err_ret->text != NULL) { - if (len > 0) - strncpy(err_ret->text, tok->buf, len); - err_ret->text[len] = '\0'; - } - } - } - - tok_free(tok); - - return n; -} diff --git a/Parser/pgen.c b/Parser/pgen.c deleted file mode 100644 index db08d77969..0000000000 --- a/Parser/pgen.c +++ /dev/null @@ -1,766 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Parser generator */ -/* XXX This file is not yet fully PROTOized */ - -/* For a description, see the comments at end of this file */ - -#include "pgenheaders.h" -#include "assert.h" -#include "token.h" -#include "node.h" -#include "grammar.h" -#include "metagrammar.h" -#include "pgen.h" - -extern int debugging; - - -/* PART ONE -- CONSTRUCT NFA -- Cf. Algorithm 3.2 from [Aho&Ullman 77] */ - -typedef struct _nfaarc { - int ar_label; - int ar_arrow; -} nfaarc; - -typedef struct _nfastate { - int st_narcs; - nfaarc *st_arc; -} nfastate; - -typedef struct _nfa { - int nf_type; - char *nf_name; - int nf_nstates; - nfastate *nf_state; - int nf_start, nf_finish; -} nfa; - -/* Forward */ -static compile_rhs PROTO((labellist *ll, nfa *nf, node *n, int *pa, int *pb)); -static compile_alt PROTO((labellist *ll, nfa *nf, node *n, int *pa, int *pb)); -static compile_item PROTO((labellist *ll, nfa *nf, node *n, int *pa, int *pb)); -static compile_atom PROTO((labellist *ll, nfa *nf, node *n, int *pa, int *pb)); - -static int -addnfastate(nf) - nfa *nf; -{ - nfastate *st; - - RESIZE(nf->nf_state, nfastate, nf->nf_nstates + 1); - if (nf->nf_state == NULL) - fatal("out of mem"); - st = &nf->nf_state[nf->nf_nstates++]; - st->st_narcs = 0; - st->st_arc = NULL; - return st - nf->nf_state; -} - -static void -addnfaarc(nf, from, to, lbl) - nfa *nf; - int from, to, lbl; -{ - nfastate *st; - nfaarc *ar; - - st = &nf->nf_state[from]; - RESIZE(st->st_arc, nfaarc, st->st_narcs + 1); - if (st->st_arc == NULL) - fatal("out of mem"); - ar = &st->st_arc[st->st_narcs++]; - ar->ar_label = lbl; - ar->ar_arrow = to; -} - -static nfa * -newnfa(name) - char *name; -{ - nfa *nf; - static type = NT_OFFSET; /* All types will be disjunct */ - - nf = NEW(nfa, 1); - if (nf == NULL) - fatal("no mem for new nfa"); - nf->nf_type = type++; - nf->nf_name = name; /* XXX strdup(name) ??? */ - nf->nf_nstates = 0; - nf->nf_state = NULL; - nf->nf_start = nf->nf_finish = -1; - return nf; -} - -typedef struct _nfagrammar { - int gr_nnfas; - nfa **gr_nfa; - labellist gr_ll; -} nfagrammar; - -/* Forward */ -static compile_rule PROTO((nfagrammar *gr, node *n)); - -static nfagrammar * -newnfagrammar() -{ - nfagrammar *gr; - - gr = NEW(nfagrammar, 1); - if (gr == NULL) - fatal("no mem for new nfa grammar"); - gr->gr_nnfas = 0; - gr->gr_nfa = NULL; - gr->gr_ll.ll_nlabels = 0; - gr->gr_ll.ll_label = NULL; - addlabel(&gr->gr_ll, ENDMARKER, "EMPTY"); - return gr; -} - -static nfa * -addnfa(gr, name) - nfagrammar *gr; - char *name; -{ - nfa *nf; - - nf = newnfa(name); - RESIZE(gr->gr_nfa, nfa *, gr->gr_nnfas + 1); - if (gr->gr_nfa == NULL) - fatal("out of mem"); - gr->gr_nfa[gr->gr_nnfas++] = nf; - addlabel(&gr->gr_ll, NAME, nf->nf_name); - return nf; -} - -#ifdef DEBUG - -static char REQNFMT[] = "metacompile: less than %d children\n"; - -#define REQN(i, count) \ - if (i < count) { \ - fprintf(stderr, REQNFMT, count); \ - fatal("REQN"); \ - } else - -#else -#define REQN(i, count) /* empty */ -#endif - -static nfagrammar * -metacompile(n) - node *n; -{ - nfagrammar *gr; - int i; - - printf("Compiling (meta-) parse tree into NFA grammar\n"); - gr = newnfagrammar(); - REQ(n, MSTART); - i = n->n_nchildren - 1; /* Last child is ENDMARKER */ - n = n->n_child; - for (; --i >= 0; n++) { - if (n->n_type != NEWLINE) - compile_rule(gr, n); - } - return gr; -} - -static -compile_rule(gr, n) - nfagrammar *gr; - node *n; -{ - nfa *nf; - - REQ(n, RULE); - REQN(n->n_nchildren, 4); - n = n->n_child; - REQ(n, NAME); - nf = addnfa(gr, n->n_str); - n++; - REQ(n, COLON); - n++; - REQ(n, RHS); - compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish); - n++; - REQ(n, NEWLINE); -} - -static -compile_rhs(ll, nf, n, pa, pb) - labellist *ll; - nfa *nf; - node *n; - int *pa, *pb; -{ - int i; - int a, b; - - REQ(n, RHS); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - REQ(n, ALT); - compile_alt(ll, nf, n, pa, pb); - if (--i <= 0) - return; - n++; - a = *pa; - b = *pb; - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - for (; --i >= 0; n++) { - REQ(n, VBAR); - REQN(i, 1); - --i; - n++; - REQ(n, ALT); - compile_alt(ll, nf, n, &a, &b); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - } -} - -static -compile_alt(ll, nf, n, pa, pb) - labellist *ll; - nfa *nf; - node *n; - int *pa, *pb; -{ - int i; - int a, b; - - REQ(n, ALT); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - REQ(n, ITEM); - compile_item(ll, nf, n, pa, pb); - --i; - n++; - for (; --i >= 0; n++) { - if (n->n_type == COMMA) { /* XXX Temporary */ - REQN(i, 1); - --i; - n++; - } - REQ(n, ITEM); - compile_item(ll, nf, n, &a, &b); - addnfaarc(nf, *pb, a, EMPTY); - *pb = b; - } -} - -static -compile_item(ll, nf, n, pa, pb) - labellist *ll; - nfa *nf; - node *n; - int *pa, *pb; -{ - int i; - int a, b; - - REQ(n, ITEM); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - if (n->n_type == LSQB) { - REQN(i, 3); - n++; - REQ(n, RHS); - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, *pb, EMPTY); - compile_rhs(ll, nf, n, &a, &b); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - REQN(i, 1); - n++; - REQ(n, RSQB); - } - else { - compile_atom(ll, nf, n, pa, pb); - if (--i <= 0) - return; - n++; - addnfaarc(nf, *pb, *pa, EMPTY); - if (n->n_type == STAR) - *pb = *pa; - else - REQ(n, PLUS); - } -} - -static -compile_atom(ll, nf, n, pa, pb) - labellist *ll; - nfa *nf; - node *n; - int *pa, *pb; -{ - int i; - - REQ(n, ATOM); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - if (n->n_type == LPAR) { - REQN(i, 3); - n++; - REQ(n, RHS); - compile_rhs(ll, nf, n, pa, pb); - n++; - REQ(n, RPAR); - } - else if (n->n_type == NAME || n->n_type == STRING) { - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str)); - } - else - REQ(n, NAME); -} - -static void -dumpstate(ll, nf, istate) - labellist *ll; - nfa *nf; - int istate; -{ - nfastate *st; - int i; - nfaarc *ar; - - printf("%c%2d%c", - istate == nf->nf_start ? '*' : ' ', - istate, - istate == nf->nf_finish ? '.' : ' '); - st = &nf->nf_state[istate]; - ar = st->st_arc; - for (i = 0; i < st->st_narcs; i++) { - if (i > 0) - printf("\n "); - printf("-> %2d %s", ar->ar_arrow, - labelrepr(&ll->ll_label[ar->ar_label])); - ar++; - } - printf("\n"); -} - -static void -dumpnfa(ll, nf) - labellist *ll; - nfa *nf; -{ - int i; - - printf("NFA '%s' has %d states; start %d, finish %d\n", - nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish); - for (i = 0; i < nf->nf_nstates; i++) - dumpstate(ll, nf, i); -} - - -/* PART TWO -- CONSTRUCT DFA -- Algorithm 3.1 from [Aho&Ullman 77] */ - -static void -addclosure(ss, nf, istate) - bitset ss; - nfa *nf; - int istate; -{ - if (addbit(ss, istate)) { - nfastate *st = &nf->nf_state[istate]; - nfaarc *ar = st->st_arc; - int i; - - for (i = st->st_narcs; --i >= 0; ) { - if (ar->ar_label == EMPTY) - addclosure(ss, nf, ar->ar_arrow); - ar++; - } - } -} - -typedef struct _ss_arc { - bitset sa_bitset; - int sa_arrow; - int sa_label; -} ss_arc; - -typedef struct _ss_state { - bitset ss_ss; - int ss_narcs; - ss_arc *ss_arc; - int ss_deleted; - int ss_finish; - int ss_rename; -} ss_state; - -typedef struct _ss_dfa { - int sd_nstates; - ss_state *sd_state; -} ss_dfa; - -/* Forward */ -static printssdfa PROTO((int xx_nstates, ss_state *xx_state, int nbits, - labellist *ll, char *msg)); -static simplify PROTO((int xx_nstates, ss_state *xx_state)); -static convert PROTO((dfa *d, int xx_nstates, ss_state *xx_state)); - -static -makedfa(gr, nf, d) - nfagrammar *gr; - nfa *nf; - dfa *d; -{ - int nbits = nf->nf_nstates; - bitset ss; - int xx_nstates; - ss_state *xx_state, *yy; - ss_arc *zz; - int istate, jstate, iarc, jarc, ibit; - nfastate *st; - nfaarc *ar; - - ss = newbitset(nbits); - addclosure(ss, nf, nf->nf_start); - xx_state = NEW(ss_state, 1); - if (xx_state == NULL) - fatal("no mem for xx_state in makedfa"); - xx_nstates = 1; - yy = &xx_state[0]; - yy->ss_ss = ss; - yy->ss_narcs = 0; - yy->ss_arc = NULL; - yy->ss_deleted = 0; - yy->ss_finish = testbit(ss, nf->nf_finish); - if (yy->ss_finish) - printf("Error: nonterminal '%s' may produce empty.\n", - nf->nf_name); - - /* This algorithm is from a book written before - the invention of structured programming... */ - - /* For each unmarked state... */ - for (istate = 0; istate < xx_nstates; ++istate) { - yy = &xx_state[istate]; - ss = yy->ss_ss; - /* For all its states... */ - for (ibit = 0; ibit < nf->nf_nstates; ++ibit) { - if (!testbit(ss, ibit)) - continue; - st = &nf->nf_state[ibit]; - /* For all non-empty arcs from this state... */ - for (iarc = 0; iarc < st->st_narcs; iarc++) { - ar = &st->st_arc[iarc]; - if (ar->ar_label == EMPTY) - continue; - /* Look up in list of arcs from this state */ - for (jarc = 0; jarc < yy->ss_narcs; ++jarc) { - zz = &yy->ss_arc[jarc]; - if (ar->ar_label == zz->sa_label) - goto found; - } - /* Add new arc for this state */ - RESIZE(yy->ss_arc, ss_arc, yy->ss_narcs + 1); - if (yy->ss_arc == NULL) - fatal("out of mem"); - zz = &yy->ss_arc[yy->ss_narcs++]; - zz->sa_label = ar->ar_label; - zz->sa_bitset = newbitset(nbits); - zz->sa_arrow = -1; - found: ; - /* Add destination */ - addclosure(zz->sa_bitset, nf, ar->ar_arrow); - } - } - /* Now look up all the arrow states */ - for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) { - zz = &xx_state[istate].ss_arc[jarc]; - for (jstate = 0; jstate < xx_nstates; jstate++) { - if (samebitset(zz->sa_bitset, - xx_state[jstate].ss_ss, nbits)) { - zz->sa_arrow = jstate; - goto done; - } - } - RESIZE(xx_state, ss_state, xx_nstates + 1); - if (xx_state == NULL) - fatal("out of mem"); - zz->sa_arrow = xx_nstates; - yy = &xx_state[xx_nstates++]; - yy->ss_ss = zz->sa_bitset; - yy->ss_narcs = 0; - yy->ss_arc = NULL; - yy->ss_deleted = 0; - yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish); - done: ; - } - } - - if (debugging) - printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, - "before minimizing"); - - simplify(xx_nstates, xx_state); - - if (debugging) - printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, - "after minimizing"); - - convert(d, xx_nstates, xx_state); - - /* XXX cleanup */ -} - -static -printssdfa(xx_nstates, xx_state, nbits, ll, msg) - int xx_nstates; - ss_state *xx_state; - int nbits; - labellist *ll; - char *msg; -{ - int i, ibit, iarc; - ss_state *yy; - ss_arc *zz; - - printf("Subset DFA %s\n", msg); - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - printf(" Subset %d", i); - if (yy->ss_finish) - printf(" (finish)"); - printf(" { "); - for (ibit = 0; ibit < nbits; ibit++) { - if (testbit(yy->ss_ss, ibit)) - printf("%d ", ibit); - } - printf("}\n"); - for (iarc = 0; iarc < yy->ss_narcs; iarc++) { - zz = &yy->ss_arc[iarc]; - printf(" Arc to state %d, label %s\n", - zz->sa_arrow, - labelrepr(&ll->ll_label[zz->sa_label])); - } - } -} - - -/* PART THREE -- SIMPLIFY DFA */ - -/* Simplify the DFA by repeatedly eliminating states that are - equivalent to another oner. This is NOT Algorithm 3.3 from - [Aho&Ullman 77]. It does not always finds the minimal DFA, - but it does usually make a much smaller one... (For an example - of sub-optimal behaviour, try S: x a b+ | y a b+.) -*/ - -static int -samestate(s1, s2) - ss_state *s1, *s2; -{ - int i; - - if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish) - return 0; - for (i = 0; i < s1->ss_narcs; i++) { - if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow || - s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label) - return 0; - } - return 1; -} - -static void -renamestates(xx_nstates, xx_state, from, to) - int xx_nstates; - ss_state *xx_state; - int from, to; -{ - int i, j; - - if (debugging) - printf("Rename state %d to %d.\n", from, to); - for (i = 0; i < xx_nstates; i++) { - if (xx_state[i].ss_deleted) - continue; - for (j = 0; j < xx_state[i].ss_narcs; j++) { - if (xx_state[i].ss_arc[j].sa_arrow == from) - xx_state[i].ss_arc[j].sa_arrow = to; - } - } -} - -static -simplify(xx_nstates, xx_state) - int xx_nstates; - ss_state *xx_state; -{ - int changes; - int i, j; - - do { - changes = 0; - for (i = 1; i < xx_nstates; i++) { - if (xx_state[i].ss_deleted) - continue; - for (j = 0; j < i; j++) { - if (xx_state[j].ss_deleted) - continue; - if (samestate(&xx_state[i], &xx_state[j])) { - xx_state[i].ss_deleted++; - renamestates(xx_nstates, xx_state, i, j); - changes++; - break; - } - } - } - } while (changes); -} - - -/* PART FOUR -- GENERATE PARSING TABLES */ - -/* Convert the DFA into a grammar that can be used by our parser */ - -static -convert(d, xx_nstates, xx_state) - dfa *d; - int xx_nstates; - ss_state *xx_state; -{ - int i, j; - ss_state *yy; - ss_arc *zz; - - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - yy->ss_rename = addstate(d); - } - - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - for (j = 0; j < yy->ss_narcs; j++) { - zz = &yy->ss_arc[j]; - addarc(d, yy->ss_rename, - xx_state[zz->sa_arrow].ss_rename, - zz->sa_label); - } - if (yy->ss_finish) - addarc(d, yy->ss_rename, yy->ss_rename, 0); - } - - d->d_initial = 0; -} - - -/* PART FIVE -- GLUE IT ALL TOGETHER */ - -static grammar * -maketables(gr) - nfagrammar *gr; -{ - int i; - nfa *nf; - dfa *d; - grammar *g; - - if (gr->gr_nnfas == 0) - return NULL; - g = newgrammar(gr->gr_nfa[0]->nf_type); - /* XXX first rule must be start rule */ - g->g_ll = gr->gr_ll; - - for (i = 0; i < gr->gr_nnfas; i++) { - nf = gr->gr_nfa[i]; - if (debugging) { - printf("Dump of NFA for '%s' ...\n", nf->nf_name); - dumpnfa(&gr->gr_ll, nf); - } - printf("Making DFA for '%s' ...\n", nf->nf_name); - d = adddfa(g, nf->nf_type, nf->nf_name); - makedfa(gr, gr->gr_nfa[i], d); - } - - return g; -} - -grammar * -pgen(n) - node *n; -{ - nfagrammar *gr; - grammar *g; - - gr = metacompile(n); - g = maketables(gr); - translatelabels(g); - addfirstsets(g); - return g; -} - - -/* - -Description ------------ - -Input is a grammar in extended BNF (using * for repetition, + for -at-least-once repetition, [] for optional parts, | for alternatives and -() for grouping). This has already been parsed and turned into a parse -tree. - -Each rule is considered as a regular expression in its own right. -It is turned into a Non-deterministic Finite Automaton (NFA), which -is then turned into a Deterministic Finite Automaton (DFA), which is then -optimized to reduce the number of states. See [Aho&Ullman 77] chapter 3, -or similar compiler books (this technique is more often used for lexical -analyzers). - -The DFA's are used by the parser as parsing tables in a special way -that's probably unique. Before they are usable, the FIRST sets of all -non-terminals are computed. - -Reference ---------- - -[Aho&Ullman 77] - Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977 - (first edition) - -*/ diff --git a/Parser/pgen.h b/Parser/pgen.h deleted file mode 100644 index d5d0a2779a..0000000000 --- a/Parser/pgen.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef Py_PGEN_H -#define Py_PGEN_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Parser generator interface */ - -extern grammar *meta_grammar PROTO((void)); - -struct _node; -extern grammar *pgen PROTO((struct _node *)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_PGEN_H */ diff --git a/Parser/pgenmain.c b/Parser/pgenmain.c deleted file mode 100644 index 77743e6cc3..0000000000 --- a/Parser/pgenmain.c +++ /dev/null @@ -1,204 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Parser generator main program */ - -/* This expects a filename containing the grammar as argv[1] (UNIX) - or asks the console for such a file name (THINK C). - It writes its output on two files in the current directory: - - "graminit.c" gets the grammar as a bunch of initialized data - - "graminit.h" gets the grammar's non-terminals as #defines. - Error messages and status info during the generation process are - written to stdout, or sometimes to stderr. */ - -/* XXX TO DO: - - check for duplicate definitions of names (instead of fatal err) -*/ - -#include "pgenheaders.h" -#include "grammar.h" -#include "node.h" -#include "parsetok.h" -#include "pgen.h" - -int debugging; - -/* Forward */ -grammar *getgrammar PROTO((char *filename)); -#ifdef THINK_C -int main PROTO((int, char **)); -char *askfile PROTO((void)); -#endif - -void -goaway(sts) - int sts; -{ - exit(sts); -} - -int -main(argc, argv) - int argc; - char **argv; -{ - grammar *g; - FILE *fp; - char *filename; - -#ifdef THINK_C - filename = askfile(); -#else - if (argc != 2) { - fprintf(stderr, "usage: %s grammar\n", argv[0]); - goaway(2); - } - filename = argv[1]; -#endif - g = getgrammar(filename); - fp = fopen("graminit.c", "w"); - if (fp == NULL) { - perror("graminit.c"); - goaway(1); - } - printf("Writing graminit.c ...\n"); - printgrammar(g, fp); - fclose(fp); - fp = fopen("graminit.h", "w"); - if (fp == NULL) { - perror("graminit.h"); - goaway(1); - } - printf("Writing graminit.h ...\n"); - printnonterminals(g, fp); - fclose(fp); - goaway(0); -} - -grammar * -getgrammar(filename) - char *filename; -{ - FILE *fp; - node *n; - grammar *g0, *g; - perrdetail err; - - fp = fopen(filename, "r"); - if (fp == NULL) { - perror(filename); - goaway(1); - } - g0 = meta_grammar(); - n = parsefile(fp, filename, g0, g0->g_start, - (char *)NULL, (char *)NULL, &err); - fclose(fp); - if (n == NULL) { - fprintf(stderr, "Parsing error %d, line %d.\n", - err.error, err.lineno); - if (err.text != NULL) { - int i; - fprintf(stderr, "%s", err.text); - i = strlen(err.text); - if (i == 0 || err.text[i-1] != '\n') - fprintf(stderr, "\n"); - for (i = 0; i < err.offset; i++) { - if (err.text[i] == '\t') - putc('\t', stderr); - else - putc(' ', stderr); - } - fprintf(stderr, "^\n"); - free(err.text); - } - goaway(1); - } - g = pgen(n); - if (g == NULL) { - printf("Bad grammar.\n"); - goaway(1); - } - return g; -} - -#ifdef THINK_C -char * -askfile() -{ - char buf[256]; - static char name[256]; - printf("Input file name: "); - if (fgets(buf, sizeof buf, stdin) == NULL) { - printf("EOF\n"); - goaway(1); - } - /* XXX The (unsigned char *) case is needed by THINK C 3.0 */ - if (sscanf(/*(unsigned char *)*/buf, " %s ", name) != 1) { - printf("No file\n"); - goaway(1); - } - return name; -} -#endif - -void -fatal(msg) - char *msg; -{ - fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg); - goaway(1); -} - -#ifdef macintosh -/* ARGSUSED */ -int -guesstabsize(path) - char *path; -{ - return 4; -} -#endif - -/* No-nonsense my_readline() for tokenizer.c */ - -char * -my_readline(prompt) - char *prompt; -{ - int n = 1000; - char *p = malloc(n); - char *q; - if (p == NULL) - return NULL; - fprintf(stderr, "%s", prompt); - q = fgets(p, n, stdin); - if (q == NULL) { - *p = '\0'; - return p; - } - n = strlen(p); - if (n > 0 && p[n-1] != '\n') - p[n-1] = '\n'; - return realloc(p, n+1); -} diff --git a/Parser/printgrammar.c b/Parser/printgrammar.c deleted file mode 100644 index ad1ef106fc..0000000000 --- a/Parser/printgrammar.c +++ /dev/null @@ -1,149 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Print a bunch of C initializers that represent a grammar */ - -#include "pgenheaders.h" -#include "grammar.h" - -/* Forward */ -static void printarcs PROTO((int, dfa *, FILE *)); -static void printstates PROTO((grammar *, FILE *)); -static void printdfas PROTO((grammar *, FILE *)); -static void printlabels PROTO((grammar *, FILE *)); - -void -printgrammar(g, fp) - grammar *g; - FILE *fp; -{ - fprintf(fp, "#include \"pgenheaders.h\"\n"); - fprintf(fp, "#include \"grammar.h\"\n"); - printdfas(g, fp); - printlabels(g, fp); - fprintf(fp, "grammar gram = {\n"); - fprintf(fp, "\t%d,\n", g->g_ndfas); - fprintf(fp, "\tdfas,\n"); - fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); - fprintf(fp, "\t%d\n", g->g_start); - fprintf(fp, "};\n"); -} - -void -printnonterminals(g, fp) - grammar *g; - FILE *fp; -{ - dfa *d; - int i; - - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) - fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); -} - -static void -printarcs(i, d, fp) - int i; - dfa *d; - FILE *fp; -{ - arc *a; - state *s; - int j, k; - - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) { - fprintf(fp, "static arc arcs_%d_%d[%d] = {\n", - i, j, s->s_narcs); - a = s->s_arc; - for (k = 0; k < s->s_narcs; k++, a++) - fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); - fprintf(fp, "};\n"); - } -} - -static void -printstates(g, fp) - grammar *g; - FILE *fp; -{ - state *s; - dfa *d; - int i, j; - - d = g->g_dfa; - for (i = 0; i < g->g_ndfas; i++, d++) { - printarcs(i, d, fp); - fprintf(fp, "static state states_%d[%d] = {\n", - i, d->d_nstates); - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) - fprintf(fp, "\t{%d, arcs_%d_%d},\n", - s->s_narcs, i, j); - fprintf(fp, "};\n"); - } -} - -static void -printdfas(g, fp) - grammar *g; - FILE *fp; -{ - dfa *d; - int i, j; - - printstates(g, fp); - fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); - d = g->g_dfa; - for (i = 0; i < g->g_ndfas; i++, d++) { - fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", - d->d_type, d->d_name, d->d_initial, d->d_nstates, i); - fprintf(fp, "\t \""); - for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) - fprintf(fp, "\\%03o", d->d_first[j] & 0xff); - fprintf(fp, "\"},\n"); - } - fprintf(fp, "};\n"); -} - -static void -printlabels(g, fp) - grammar *g; - FILE *fp; -{ - label *l; - int i; - - fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels); - l = g->g_ll.ll_label; - for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { - if (l->lb_str == NULL) - fprintf(fp, "\t{%d, 0},\n", l->lb_type); - else - fprintf(fp, "\t{%d, \"%s\"},\n", - l->lb_type, l->lb_str); - } - fprintf(fp, "};\n"); -} diff --git a/Parser/tokenizer.c b/Parser/tokenizer.c deleted file mode 100644 index 942072dc1f..0000000000 --- a/Parser/tokenizer.c +++ /dev/null @@ -1,745 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Tokenizer implementation */ - -#include "pgenheaders.h" - -#include <ctype.h> - -#include "tokenizer.h" -#include "errcode.h" - -extern char *my_readline PROTO((char *)); -/* Return malloc'ed string including trailing \n; - empty malloc'ed string for EOF; - NULL if interrupted */ - -/* Don't ever change this -- it would break the portability of Python code */ -#define TABSIZE 8 - -/* Forward */ -static struct tok_state *tok_new PROTO((void)); -static int tok_nextc PROTO((struct tok_state *tok)); -static void tok_backup PROTO((struct tok_state *tok, int c)); - -/* Token names */ - -char *tok_name[] = { - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "BACKQUOTE", - "LBRACE", - "RBRACE", - "EQEQUAL", - "NOTEQUAL", - "LESSEQUAL", - "GREATEREQUAL", - "TILDE", - "CIRCUMFLEX", - "LEFTSHIFT", - "RIGHTSHIFT", - "DOUBLESTAR", - /* This table must match the #defines in token.h! */ - "OP", - "<ERRORTOKEN>", - "<N_TOKENS>" -}; - - -/* Create and initialize a new tok_state structure */ - -static struct tok_state * -tok_new() -{ - struct tok_state *tok = NEW(struct tok_state, 1); - if (tok == NULL) - return NULL; - tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL; - tok->done = E_OK; - tok->fp = NULL; - tok->tabsize = TABSIZE; - tok->indent = 0; - tok->indstack[0] = 0; - tok->atbol = 1; - tok->pendin = 0; - tok->prompt = tok->nextprompt = NULL; - tok->lineno = 0; - tok->level = 0; - return tok; -} - - -/* Set up tokenizer for string */ - -struct tok_state * -tok_setups(str) - char *str; -{ - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; - tok->buf = tok->cur = tok->end = tok->inp = str; - return tok; -} - - -/* Set up tokenizer for file */ - -struct tok_state * -tok_setupf(fp, ps1, ps2) - FILE *fp; - char *ps1, *ps2; -{ - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; - if ((tok->buf = NEW(char, BUFSIZ)) == NULL) { - DEL(tok); - return NULL; - } - tok->cur = tok->inp = tok->buf; - tok->end = tok->buf + BUFSIZ; - tok->fp = fp; - tok->prompt = ps1; - tok->nextprompt = ps2; - return tok; -} - - -/* Free a tok_state structure */ - -void -tok_free(tok) - struct tok_state *tok; -{ - if (tok->fp != NULL && tok->buf != NULL) - DEL(tok->buf); - DEL(tok); -} - - -/* Get next char, updating state; error code goes into tok->done */ - -static int -tok_nextc(tok) - register struct tok_state *tok; -{ - for (;;) { - if (tok->cur != tok->inp) { - return *tok->cur++; /* Fast path */ - } - if (tok->done != E_OK) - return EOF; - if (tok->fp == NULL) { - char *end = strchr(tok->inp, '\n'); - if (end != NULL) - end++; - else { - end = strchr(tok->inp, '\0'); - if (end == tok->inp) { - tok->done = E_EOF; - return EOF; - } - } - if (tok->start == NULL) - tok->buf = tok->cur; - tok->lineno++; - tok->inp = end; - return *tok->cur++; - } - if (tok->prompt != NULL) { - char *new = my_readline(tok->prompt); - if (tok->nextprompt != NULL) - tok->prompt = tok->nextprompt; - if (new == NULL) - tok->done = E_INTR; - else if (*new == '\0') { - free(new); - tok->done = E_EOF; - } - else if (tok->start != NULL) { - int start = tok->start - tok->buf; - int oldlen = tok->cur - tok->buf; - int newlen = oldlen + strlen(new); - char *buf = realloc(tok->buf, newlen+1); - tok->lineno++; - if (buf == NULL) { - free(tok->buf); - tok->buf = NULL; - free(new); - tok->done = E_NOMEM; - return EOF; - } - tok->buf = buf; - tok->cur = tok->buf + oldlen; - strcpy(tok->buf + oldlen, new); - free(new); - tok->inp = tok->buf + newlen; - tok->end = tok->inp + 1; - tok->start = tok->buf + start; - } - else { - tok->lineno++; - if (tok->buf != NULL) - free(tok->buf); - tok->buf = new; - tok->cur = tok->buf; - tok->inp = strchr(tok->buf, '\0'); - tok->end = tok->inp + 1; - } - } - else { - int done = 0; - int cur = 0; - char *pt; - if (tok->start == NULL) { - if (tok->buf == NULL) { - tok->buf = NEW(char, BUFSIZ); - if (tok->buf == NULL) { - tok->done = E_NOMEM; - return EOF; - } - tok->end = tok->buf + BUFSIZ; - } - if (fgets(tok->buf, (int)(tok->end - tok->buf), - tok->fp) == NULL) { - tok->done = E_EOF; - done = 1; - } - else { - tok->done = E_OK; - tok->inp = strchr(tok->buf, '\0'); - done = tok->inp[-1] == '\n'; - } - } - else { - cur = tok->cur - tok->buf; - if (feof(tok->fp)) { - tok->done = E_EOF; - done = 1; - } - else - tok->done = E_OK; - } - tok->lineno++; - /* Read until '\n' or EOF */ - while (!done) { - int curstart = tok->start == NULL ? -1 : - tok->start - tok->buf; - int curvalid = tok->inp - tok->buf; - int cursize = tok->end - tok->buf; - int newsize = curvalid + BUFSIZ; - char *newbuf = tok->buf; - RESIZE(newbuf, char, newsize); - if (newbuf == NULL) { - tok->done = E_NOMEM; - tok->cur = tok->inp; - return EOF; - } - tok->buf = newbuf; - tok->inp = tok->buf + curvalid; - tok->end = tok->buf + newsize; - tok->start = curstart < 0 ? NULL : - tok->buf + curstart; - if (fgets(tok->inp, - (int)(tok->end - tok->inp), - tok->fp) == NULL) { - /* Last line does not end in \n, - fake one */ - strcpy(tok->inp, "\n"); - } - tok->inp = strchr(tok->inp, '\0'); - done = tok->inp[-1] == '\n'; - } - tok->cur = tok->buf + cur; - /* replace "\r\n" with "\n" */ - pt = tok->inp - 2; - if (pt >= tok->buf && *pt == '\r') { - *pt++ = '\n'; - *pt = '\0'; - tok->inp = pt; - } - } - if (tok->done != E_OK) { - if (tok->prompt != NULL) - fprintf(stderr, "\n"); - tok->cur = tok->inp; - return EOF; - } - } - /*NOTREACHED*/ -} - - -/* Back-up one character */ - -static void -tok_backup(tok, c) - register struct tok_state *tok; - register int c; -{ - if (c != EOF) { - if (--tok->cur < tok->buf) - fatal("tok_backup: begin of buffer"); - if (*tok->cur != c) - *tok->cur = c; - } -} - - -/* Return the token corresponding to a single character */ - -int -tok_1char(c) - int c; -{ - switch (c) { - case '(': return LPAR; - case ')': return RPAR; - case '[': return LSQB; - case ']': return RSQB; - case ':': return COLON; - case ',': return COMMA; - case ';': return SEMI; - case '+': return PLUS; - case '-': return MINUS; - case '*': return STAR; - case '/': return SLASH; - case '|': return VBAR; - case '&': return AMPER; - case '<': return LESS; - case '>': return GREATER; - case '=': return EQUAL; - case '.': return DOT; - case '%': return PERCENT; - case '`': return BACKQUOTE; - case '{': return LBRACE; - case '}': return RBRACE; - case '^': return CIRCUMFLEX; - case '~': return TILDE; - default: return OP; - } -} - - -int -tok_2char(c1, c2) - int c1, c2; -{ - switch (c1) { - case '=': - switch (c2) { - case '=': return EQEQUAL; - } - break; - case '!': - switch (c2) { - case '=': return NOTEQUAL; - } - break; - case '<': - switch (c2) { - case '>': return NOTEQUAL; - case '=': return LESSEQUAL; - case '<': return LEFTSHIFT; - } - break; - case '>': - switch (c2) { - case '=': return GREATEREQUAL; - case '>': return RIGHTSHIFT; - } - break; - case '*': - switch (c2) { - case '*': return DOUBLESTAR; - } - break; - } - return OP; -} - - -/* Get next token, after space stripping etc. */ - -int -tok_get(tok, p_start, p_end) - register struct tok_state *tok; /* In/out: tokenizer state */ - char **p_start, **p_end; /* Out: point to start/end of token */ -{ - register int c; - int blankline; - - *p_start = *p_end = NULL; - nextline: - tok->start = NULL; - blankline = 0; - - /* Get indentation level */ - if (tok->atbol) { - register int col = 0; - tok->atbol = 0; - for (;;) { - c = tok_nextc(tok); - if (c == ' ') - col++; - else if (c == '\t') - col = (col/tok->tabsize + 1) * tok->tabsize; - else if (c == '\014') /* Control-L (formfeed) */ - col = 0; /* For Emacs users */ - else - break; - } - tok_backup(tok, c); - if (c == '#' || c == '\n') { - /* Lines with only whitespace and/or comments - shouldn't affect the indentation and are - not passed to the parser as NEWLINE tokens, - except *totally* empty lines in interactive - mode, which signal the end of a command group. */ - if (col == 0 && c == '\n' && tok->prompt != NULL) - blankline = 0; /* Let it through */ - else - blankline = 1; /* Ignore completely */ - /* We can't jump back right here since we still - may need to skip to the end of a comment */ - } - if (!blankline && tok->level == 0) { - if (col == tok->indstack[tok->indent]) { - /* No change */ - } - else if (col > tok->indstack[tok->indent]) { - /* Indent -- always one */ - if (tok->indent+1 >= MAXINDENT) { - fprintf(stderr, "excessive indent\n"); - tok->done = E_TOKEN; - tok->cur = tok->inp; - return ERRORTOKEN; - } - tok->pendin++; - tok->indstack[++tok->indent] = col; - } - else /* col < tok->indstack[tok->indent] */ { - /* Dedent -- any number, must be consistent */ - while (tok->indent > 0 && - col < tok->indstack[tok->indent]) { - tok->indent--; - tok->pendin--; - } - if (col != tok->indstack[tok->indent]) { - fprintf(stderr, "inconsistent dedent\n"); - tok->done = E_TOKEN; - tok->cur = tok->inp; - return ERRORTOKEN; - } - } - } - } - - tok->start = tok->cur; - - /* Return pending indents/dedents */ - if (tok->pendin != 0) { - if (tok->pendin < 0) { - tok->pendin++; - return DEDENT; - } - else { - tok->pendin--; - return INDENT; - } - } - - again: - tok->start = NULL; - /* Skip spaces */ - do { - c = tok_nextc(tok); - } while (c == ' ' || c == '\t' || c == '\014'); - - /* Set start of current token */ - tok->start = tok->cur - 1; - - /* Skip comment */ - if (c == '#') { - /* Hack to allow overriding the tabsize in the file. - This is also recognized by vi, when it occurs near the - beginning or end of the file. (Will vi never die...?) - For Python it must be at the beginning of the file! */ - /* XXX The real vi syntax is actually different :-( */ - /* XXX Should recognize Emacs syntax, too */ - int x; - if (sscanf(tok->cur, - " vi:set tabsize=%d:", &x) == 1 && - x >= 1 && x <= 40) { - /* fprintf(stderr, "# vi:set tabsize=%d:\n", x); */ - tok->tabsize = x; - } - do { - c = tok_nextc(tok); - } while (c != EOF && c != '\n'); - } - - /* Check for EOF and errors now */ - if (c == EOF) { - return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; - } - - /* Identifier (most frequent token!) */ - if (isalpha(c) || c == '_') { - do { - c = tok_nextc(tok); - } while (isalnum(c) || c == '_'); - tok_backup(tok, c); - *p_start = tok->start; - *p_end = tok->cur; - return NAME; - } - - /* Newline */ - if (c == '\n') { - tok->atbol = 1; - if (blankline || tok->level > 0) - goto nextline; - *p_start = tok->start; - *p_end = tok->cur - 1; /* Leave '\n' out of the string */ - return NEWLINE; - } - - /* Period or number starting with period? */ - if (c == '.') { - c = tok_nextc(tok); - if (isdigit(c)) { - goto fraction; - } - else { - tok_backup(tok, c); - *p_start = tok->start; - *p_end = tok->cur; - return DOT; - } - } - - /* Number */ - if (isdigit(c)) { - if (c == '0') { - /* Hex or octal */ - c = tok_nextc(tok); - if (c == '.') - goto fraction; -#ifndef WITHOUT_COMPLEX - if (c == 'j' || c == 'J') - goto imaginary; -#endif - if (c == 'x' || c == 'X') { - /* Hex */ - do { - c = tok_nextc(tok); - } while (isxdigit(c)); - } - else { - /* XXX This is broken! E.g., - 09.9 should be accepted as float! */ - /* Octal; c is first char of it */ - /* There's no 'isoctdigit' macro, sigh */ - while ('0' <= c && c < '8') { - c = tok_nextc(tok); - } - } - if (c == 'l' || c == 'L') - c = tok_nextc(tok); - } - else { - /* Decimal */ - do { - c = tok_nextc(tok); - } while (isdigit(c)); - if (c == 'l' || c == 'L') - c = tok_nextc(tok); - else { - /* Accept floating point numbers. - XXX This accepts incomplete things like - XXX 12e or 1e+; worry run-time */ - if (c == '.') { - fraction: - /* Fraction */ - do { - c = tok_nextc(tok); - } while (isdigit(c)); - } - if (c == 'e' || c == 'E') { - /* Exponent part */ - c = tok_nextc(tok); - if (c == '+' || c == '-') - c = tok_nextc(tok); - while (isdigit(c)) { - c = tok_nextc(tok); - } - } -#ifndef WITHOUT_COMPLEX - if (c == 'j' || c == 'J') - /* Imaginary part */ - imaginary: - c = tok_nextc(tok); -#endif - } - } - tok_backup(tok, c); - *p_start = tok->start; - *p_end = tok->cur; - return NUMBER; - } - - /* String */ - if (c == '\'' || c == '"') { - int quote = c; - int triple = 0; - int tripcount = 0; - for (;;) { - c = tok_nextc(tok); - if (c == '\n') { - if (!triple) { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - tripcount = 0; - } - else if (c == EOF) { - tok->done = E_TOKEN; - tok->cur = tok->inp; - return ERRORTOKEN; - } - else if (c == quote) { - tripcount++; - if (tok->cur == tok->start+2) { - c = tok_nextc(tok); - if (c == quote) { - triple = 1; - tripcount = 0; - continue; - } - tok_backup(tok, c); - } - if (!triple || tripcount == 3) - break; - } - else if (c == '\\') { - tripcount = 0; - c = tok_nextc(tok); - if (c == EOF) { - tok->done = E_TOKEN; - tok->cur = tok->inp; - return ERRORTOKEN; - } - } - else - tripcount = 0; - } - *p_start = tok->start; - *p_end = tok->cur; - return STRING; - } - - /* Line continuation */ - if (c == '\\') { - c = tok_nextc(tok); - if (c != '\n') { - tok->done = E_TOKEN; - tok->cur = tok->inp; - return ERRORTOKEN; - } - goto again; /* Read next line */ - } - - /* Check for two-character token */ - { - int c2 = tok_nextc(tok); - int token = tok_2char(c, c2); - if (token != OP) { - *p_start = tok->start; - *p_end = tok->cur; - return token; - } - tok_backup(tok, c2); - } - - /* Keep track of parentheses nesting level */ - switch (c) { - case '(': - case '[': - case '{': - tok->level++; - break; - case ')': - case ']': - case '}': - tok->level--; - break; - } - - /* Punctuation character */ - *p_start = tok->start; - *p_end = tok->cur; - return tok_1char(c); -} - - -#ifdef DEBUG - -void -tok_dump(type, start, end) - int type; - char *start, *end; -{ - printf("%s", tok_name[type]); - if (type == NAME || type == NUMBER || type == STRING || type == OP) - printf("(%.*s)", (int)(end - start), start); -} - -#endif diff --git a/Parser/tokenizer.h b/Parser/tokenizer.h deleted file mode 100644 index d5b36647b6..0000000000 --- a/Parser/tokenizer.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef Py_TOKENIZER_H -#define Py_TOKENIZER_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Tokenizer interface */ - -#include "token.h" /* For token types */ - -#define MAXINDENT 100 /* Max indentation level */ - -/* Tokenizer state */ -struct tok_state { - /* Input state; buf <= cur <= inp <= end */ - /* NB an entire line is held in the buffer */ - char *buf; /* Input buffer, or NULL; malloc'ed if fp != NULL */ - char *cur; /* Next character in buffer */ - char *inp; /* End of data in buffer */ - char *end; /* End of input buffer if buf != NULL */ - char *start; /* Start of current token if not NULL */ - int done; /* E_OK normally, E_EOF at EOF, otherwise error code */ - /* NB If done != E_OK, cur must be == inp!!! */ - FILE *fp; /* Rest of input; NULL if tokenizing a string */ - int tabsize; /* Tab spacing */ - int indent; /* Current indentation index */ - int indstack[MAXINDENT]; /* Stack of indents */ - int atbol; /* Nonzero if at begin of new line */ - int pendin; /* Pending indents (if > 0) or dedents (if < 0) */ - char *prompt, *nextprompt; /* For interactive prompting */ - int lineno; /* Current line number */ - int level; /* () [] {} Parentheses nesting level */ - /* Used to allow free continuations inside them */ -}; - -extern struct tok_state *tok_setups PROTO((char *)); -extern struct tok_state *tok_setupf PROTO((FILE *, char *, char *)); -extern void tok_free PROTO((struct tok_state *)); -extern int tok_get PROTO((struct tok_state *, char **, char **)); - -#ifdef __cplusplus -} -#endif -#endif /* !Py_TOKENIZER_H */ diff --git a/Python/Makefile.in b/Python/Makefile.in deleted file mode 100644 index 5be2532c4d..0000000000 --- a/Python/Makefile.in +++ /dev/null @@ -1,122 +0,0 @@ -# NOTE: Makefile.in is converted into Makefile by the configure script -# in the parent directory. Once configure has run, you can recreate -# the Makefile by running just config.status. - -# === Variables set by config.stat === - -srcdir= @srcdir@ -VPATH= @srcdir@ - -CC= @CC@ -RANLIB= @RANLIB@ -AR= @AR@ - -DEFS= @DEFS@ -LIBOBJS= @LIBOBJS@ -LIBS= @LIBS@ -DLINCLDIR= @DLINCLDIR@ - -# Machine-dependent subdirectories -MACHDEP= @MACHDEP@ - - -# === Other things that are customizable but not by configure === - -INCLDIR= $(srcdir)/../Include -OPT= @OPT@ -CFLAGS= $(OPT) -I$(INCLDIR) -I.. $(DEFS) - -MKDEP= mkdep -SHELL= /bin/sh - - -# === Fixed definitions === - -OBJS= \ - bltinmodule.o \ - ceval.o cgensupport.o compile.o \ - errors.o \ - frozen.o \ - getargs.o getcompiler.o getcopyright.o getmtime.o \ - getplatform.o getversion.o graminit.o \ - import.o importdl.o \ - marshal.o modsupport.o mystrtoul.o \ - pythonrun.o \ - sigcheck.o structmember.o sysmodule.o \ - traceback.o \ - $(LIBOBJS) - -LIB= libPython.a - -SYSLIBS= -lm - - -# === Rules === - -all: $(LIB) - -$(LIB): $& $(OBJS) - -rm -f $(LIB) - $(AR) cr $(LIB) $(OBJS) - $(RANLIB) $(LIB) - -clean: - -rm -f *.o core *~ [@,#]* *.old *.orig *.rej - -clobber: clean - -rm -f *.a tags TAGS - -Makefile: $(srcdir)/Makefile.in ../config.status - (cd ..; CONFIG_FILES=Python/Makefile CONFIG_HEADERS= \ - $(SHELL) config.status) - -getplatform.o: getplatform.c Makefile - $(CC) -c $(CFLAGS) -DPLATFORM='"$(MACHDEP)"' \ - $(srcdir)/getplatform.c - -importdl.o: importdl.c - $(CC) -c $(CFLAGS) -I$(DLINCLDIR) $(srcdir)/importdl.c - -depend: - $(MKDEP) $(CFLAGS) `echo $(OBJS) | tr ' ' '\012' | \ - sed 's|\(.*\)\.o|$(srcdir)/\1.c|'` - -.PRECIOUS: Makefile - -bltinmodule.o: bltinmodule.c -ceval.o: ceval.c -cgensupport.o: cgensupport.c -compile.o: compile.c -dup2.o: dup2.c -errors.o: errors.c -fmod.o: fmod.c -frozen.o: frozen.c -frozenmain.o: frozenmain.c -getargs.o: getargs.c -getcompiler.o: getcompiler.c -getcopyright.o: getcopyright.c -getcwd.o: getcwd.c -getmtime.o: getmtime.c -getopt.o: getopt.c -getplatform.o: getplatform.c -getversion.o: getversion.c -graminit.o: graminit.c -import.o: import.c -importdl.o: importdl.c -marshal.o: marshal.c -memmove.o: memmove.c -modsupport.o: modsupport.c -mystrtoul.o: mystrtoul.c -pythonrun.o: pythonrun.c -sigcheck.o: sigcheck.c -strerror.o: strerror.c -strtod.o: strtod.c -structmember.o: structmember.c -sysmodule.o: sysmodule.c -thread.o: thread.c -traceback.o: traceback.c -version.o: version.c - -# DO NOT DELETE THIS LINE -- mkdep uses it. -# DO NOT PUT ANYTHING AFTER THIS LINE, IT WILL GO AWAY. -# IF YOU PUT ANYTHING HERE IT WILL GO AWAY diff --git a/Python/atof.c b/Python/atof.c deleted file mode 100644 index 894490a47b..0000000000 --- a/Python/atof.c +++ /dev/null @@ -1,76 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Just in case you haven't got an atof() around... - This one doesn't check for bad syntax or overflow, - and is slow and inaccurate. - But it's good enough for the occasional string literal... */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include <ctype.h> - -double atof(s) - char *s; -{ - double a = 0.0; - int e = 0; - int c; - while ((c = *s++) != '\0' && isdigit(c)) { - a = a*10.0 + (c - '0'); - } - if (c == '.') { - while ((c = *s++) != '\0' && isdigit(c)) { - a = a*10.0 + (c - '0'); - e = e-1; - } - } - if (c == 'e' || c == 'E') { - int sign = 1; - int i = 0; - c = *s++; - if (c == '+') - c = *s++; - else if (c == '-') { - c = *s++; - sign = -1; - } - while (isdigit(c)) { - i = i*10 + (c - '0'); - c = *s++; - } - e += i*sign; - } - while (e > 0) { - a *= 10.0; - e--; - } - while (e < 0) { - a *= 0.1; - e++; - } - return a; -} diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c deleted file mode 100644 index 0eedb65e37..0000000000 --- a/Python/bltinmodule.c +++ /dev/null @@ -1,1714 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Built-in functions */ - -#include "allobjects.h" - -#include "node.h" -#include "graminit.h" -#include "bltinmodule.h" -#include "import.h" -#include "compile.h" -#include "eval.h" - -/* Forward */ -static object *filterstring PROTO((object *, object *)); -static object *filtertuple PROTO((object *, object *)); - -static object * -builtin___import__(self, args) - object *self; - object *args; -{ - char *name; - object *globals = NULL; - object *locals = NULL; - object *fromlist = NULL; - - if (!newgetargs(args, "s|OOO:__import__", - &name, &globals, &locals, &fromlist)) - return NULL; - return import_module(name); -} - - -static object * -builtin_abs(self, args) - object *self; - object *args; -{ - object *v; - number_methods *nm; - - if (!newgetargs(args, "O:abs", &v)) - return NULL; - if ((nm = v->ob_type->tp_as_number) == NULL) { - err_setstr(TypeError, "abs() requires numeric argument"); - return NULL; - } - return (*nm->nb_absolute)(v); -} - -static object * -builtin_apply(self, args) - object *self; - object *args; -{ - object *func, *alist = NULL, *kwdict = NULL; - - if (!newgetargs(args, "O|OO:apply", &func, &alist, &kwdict)) - return NULL; - if (alist != NULL && !is_tupleobject(alist)) { - err_setstr(TypeError, "apply() 2nd argument must be tuple"); - return NULL; - } - if (kwdict != NULL && !is_dictobject(kwdict)) { - err_setstr(TypeError, - "apply() 3rd argument must be dictionary"); - return NULL; - } - return PyEval_CallObjectWithKeywords(func, alist, kwdict); -} - -static object * -builtin_callable(self, args) - object *self; - object *args; -{ - object *v; - - if (!newgetargs(args, "O:callable", &v)) - return NULL; - return newintobject((long)callable(v)); -} - -static object * -builtin_filter(self, args) - object *self; - object *args; -{ - object *func, *seq, *result; - sequence_methods *sqf; - int len; - register int i, j; - - if (!newgetargs(args, "OO:filter", &func, &seq)) - return NULL; - - if (is_stringobject(seq)) { - object *r = filterstring(func, seq); - return r; - } - - if (is_tupleobject(seq)) { - object *r = filtertuple(func, seq); - return r; - } - - if ((sqf = seq->ob_type->tp_as_sequence) == NULL) { - err_setstr(TypeError, - "argument 2 to filter() must be a sequence type"); - goto Fail_2; - } - - if ((len = (*sqf->sq_length)(seq)) < 0) - goto Fail_2; - - if (is_listobject(seq) && seq->ob_refcnt == 1) { - INCREF(seq); - result = seq; - } - else { - if ((result = newlistobject(len)) == NULL) - goto Fail_2; - } - - for (i = j = 0; ; ++i) { - object *item, *good; - int ok; - - if ((item = (*sqf->sq_item)(seq, i)) == NULL) { - if (i < len) - goto Fail_1; - if (err_occurred() == IndexError) { - err_clear(); - break; - } - goto Fail_1; - } - - if (func == None) { - good = item; - INCREF(good); - } - else { - object *arg = mkvalue("(O)", item); - if (arg == NULL) - goto Fail_1; - good = call_object(func, arg); - DECREF(arg); - if (good == NULL) { - DECREF(item); - goto Fail_1; - } - } - ok = testbool(good); - DECREF(good); - if (ok) { - if (j < len) { - if (setlistitem(result, j++, item) < 0) - goto Fail_1; - } - else { - j++; - if (addlistitem(result, item) < 0) - goto Fail_1; - } - } else { - DECREF(item); - } - } - - - if (j < len && setlistslice(result, j, len, NULL) < 0) - goto Fail_1; - - return result; - -Fail_1: - DECREF(result); -Fail_2: - return NULL; -} - -static object * -builtin_chr(self, args) - object *self; - object *args; -{ - long x; - char s[1]; - - if (!newgetargs(args, "l:chr", &x)) - return NULL; - if (x < 0 || x >= 256) { - err_setstr(ValueError, "chr() arg not in range(256)"); - return NULL; - } - s[0] = x; - return newsizedstringobject(s, 1); -} - -static object * -builtin_cmp(self, args) - object *self; - object *args; -{ - object *a, *b; - - if (!newgetargs(args, "OO:cmp", &a, &b)) - return NULL; - return newintobject((long)cmpobject(a, b)); -} - -static object * -builtin_coerce(self, args) - object *self; - object *args; -{ - object *v, *w; - object *res; - - if (!newgetargs(args, "OO:coerce", &v, &w)) - return NULL; - if (coerce(&v, &w) < 0) - return NULL; - res = mkvalue("(OO)", v, w); - DECREF(v); - DECREF(w); - return res; -} - -static object * -builtin_compile(self, args) - object *self; - object *args; -{ - char *str; - char *filename; - char *startstr; - int start; - - if (!newgetargs(args, "sss:compile", &str, &filename, &startstr)) - return NULL; - if (strcmp(startstr, "exec") == 0) - start = file_input; - else if (strcmp(startstr, "eval") == 0) - start = eval_input; - else if (strcmp(startstr, "single") == 0) - start = single_input; - else { - err_setstr(ValueError, - "compile() mode must be 'exec' or 'eval' or 'single'"); - return NULL; - } - return compile_string(str, filename, start); -} - -#ifndef WITHOUT_COMPLEX - -static object * -builtin_complex(self, args) - object *self; - object *args; -{ - object *r, *i; - number_methods *nbr, *nbi; - complex cr, ci; - - i = NULL; - if (!newgetargs(args, "O|O:complex", &r, &i)) - return NULL; - if ((nbr = r->ob_type->tp_as_number) == NULL || - nbr->nb_float == NULL || (i != NULL && - ((nbi = i->ob_type->tp_as_number) == NULL || - nbi->nb_float == NULL))) { - err_setstr(TypeError, - "complex() argument can't be converted to complex"); - return NULL; - } - if (is_complexobject(r)) - cr = ((complexobject*)r)->cval; - else { - cr.real = getfloatvalue((*nbr->nb_float)(r)); - cr.imag = 0.; - } - if (i == NULL) { - ci.real = 0.; - ci.imag = 0.; - } - else if (is_complexobject(i)) - ci = ((complexobject*)i)->cval; - else { - ci.real = getfloatvalue((*nbi->nb_float)(i)); - ci.imag = 0.; - } - cr.real -= ci.imag; - cr.imag += ci.real; - return newcomplexobject(cr); -} - -#endif - -static object * -builtin_dir(self, args) - object *self; - object *args; -{ - object *v = NULL; - object *d; - - if (!newgetargs(args, "|O:dir", &v)) - return NULL; - if (v == NULL) { - d = getlocals(); - INCREF(d); - } - else { - d = getattr(v, "__dict__"); - if (d == NULL) { - err_setstr(TypeError, - "dir() argument must have __dict__ attribute"); - return NULL; - } - } - if (is_dictobject(d)) { - v = getdictkeys(d); - if (sortlist(v) != 0) { - DECREF(v); - v = NULL; - } - } - else { - v = PyObject_CallMethod(d, "keys", NULL); - if (v == NULL) { - PyErr_Clear(); - v = newlistobject(0); - } - } - DECREF(d); - return v; -} - -static object * -do_divmod(v, w) - object *v, *w; -{ - object *res; - - if (is_instanceobject(v) || is_instanceobject(w)) - return instancebinop(v, w, "__divmod__", "__rdivmod__", - do_divmod); - if (v->ob_type->tp_as_number == NULL || - w->ob_type->tp_as_number == NULL) { - err_setstr(TypeError, - "divmod() requires numeric or class instance arguments"); - return NULL; - } - if (coerce(&v, &w) != 0) - return NULL; - res = (*v->ob_type->tp_as_number->nb_divmod)(v, w); - DECREF(v); - DECREF(w); - return res; -} - -static object * -builtin_divmod(self, args) - object *self; - object *args; -{ - object *v, *w; - - if (!newgetargs(args, "OO:divmod", &v, &w)) - return NULL; - return do_divmod(v, w); -} - -static object * -builtin_eval(self, args) - object *self; - object *args; -{ - object *cmd; - object *globals = None, *locals = None; - char *str; - - if (!newgetargs(args, "O|O!O!:eval", - &cmd, - &Mappingtype, &globals, - &Mappingtype, &locals)) - return NULL; - if (globals == None) { - globals = getglobals(); - if (locals == None) - locals = getlocals(); - } - else if (locals == None) - locals = globals; - if (dictlookup(globals, "__builtins__") == NULL) { - if (dictinsert(globals, "__builtins__", getbuiltins()) != 0) - return NULL; - } - if (is_codeobject(cmd)) - return eval_code((codeobject *) cmd, globals, locals); - if (!is_stringobject(cmd)) { - err_setstr(TypeError, - "eval() argument 1 must be string or code object"); - return NULL; - } - str = getstringvalue(cmd); - if (strlen(str) != getstringsize(cmd)) { - err_setstr(ValueError, - "embedded '\\0' in string arg"); - return NULL; - } - while (*str == ' ' || *str == '\t') - str++; - return run_string(str, eval_input, globals, locals); -} - -static object * -builtin_execfile(self, args) - object *self; - object *args; -{ - char *filename; - object *globals = None, *locals = None; - object *res; - FILE* fp; - - if (!newgetargs(args, "s|O!O!:execfile", - &filename, - &Mappingtype, &globals, - &Mappingtype, &locals)) - return NULL; - if (globals == None) { - globals = getglobals(); - if (locals == None) - locals = getlocals(); - } - else if (locals == None) - locals = globals; - if (dictlookup(globals, "__builtins__") == NULL) { - if (dictinsert(globals, "__builtins__", getbuiltins()) != 0) - return NULL; - } - BGN_SAVE - fp = fopen(filename, "r"); - END_SAVE - if (fp == NULL) { - err_errno(IOError); - return NULL; - } - res = run_file(fp, filename, file_input, globals, locals); - BGN_SAVE - fclose(fp); - END_SAVE - return res; -} - -static object * -builtin_float(self, args) - object *self; - object *args; -{ - object *v; - number_methods *nb; - - if (!newgetargs(args, "O:float", &v)) - return NULL; - if ((nb = v->ob_type->tp_as_number) == NULL || - nb->nb_float == NULL) { - err_setstr(TypeError, - "float() argument can't be converted to float"); - return NULL; - } - return (*nb->nb_float)(v); -} - -static object * -builtin_getattr(self, args) - object *self; - object *args; -{ - object *v; - object *name; - - if (!newgetargs(args, "OS:getattr", &v, &name)) - return NULL; - return getattro(v, name); -} - -static object * -builtin_globals(self, args) - object *self; - object *args; -{ - object *d; - - if (!newgetargs(args, "")) - return NULL; - d = getglobals(); - INCREF(d); - return d; -} - -static object * -builtin_hasattr(self, args) - object *self; - object *args; -{ - object *v; - object *name; - - if (!newgetargs(args, "OS:hasattr", &v, &name)) - return NULL; - v = getattro(v, name); - if (v == NULL) { - err_clear(); - return newintobject(0L); - } - DECREF(v); - return newintobject(1L); -} - -static object * -builtin_id(self, args) - object *self; - object *args; -{ - object *v; - - if (!newgetargs(args, "O:id", &v)) - return NULL; - return newintobject((long)v); -} - -static object * -builtin_map(self, args) - object *self; - object *args; -{ - typedef struct { - object *seq; - sequence_methods *sqf; - int len; - } sequence; - - object *func, *result; - sequence *seqs = NULL, *sqp; - int n, len; - register int i, j; - - n = gettuplesize(args); - if (n < 2) { - err_setstr(TypeError, "map() requires at least two args"); - return NULL; - } - - func = gettupleitem(args, 0); - n--; - - if ((seqs = NEW(sequence, n)) == NULL) { - err_nomem(); - goto Fail_2; - } - - for (len = 0, i = 0, sqp = seqs; i < n; ++i, ++sqp) { - int curlen; - - if ((sqp->seq = gettupleitem(args, i + 1)) == NULL) - goto Fail_2; - - if (! (sqp->sqf = sqp->seq->ob_type->tp_as_sequence)) { - static char errmsg[] = - "argument %d to map() must be a sequence object"; - char errbuf[sizeof(errmsg) + 3]; - - sprintf(errbuf, errmsg, i+2); - err_setstr(TypeError, errbuf); - goto Fail_2; - } - - if ((curlen = sqp->len = (*sqp->sqf->sq_length)(sqp->seq)) < 0) - goto Fail_2; - - if (curlen > len) - len = curlen; - } - - if ((result = (object *) newlistobject(len)) == NULL) - goto Fail_2; - - /* XXX Special case map(None, single_list) could be more efficient */ - for (i = 0; ; ++i) { - object *alist, *item, *value; - int any = 0; - - if (func == None && n == 1) - alist = NULL; - else { - if ((alist = newtupleobject(n)) == NULL) - goto Fail_1; - } - - for (j = 0, sqp = seqs; j < n; ++j, ++sqp) { - if (sqp->len < 0) { - INCREF(None); - item = None; - } - else { - item = (*sqp->sqf->sq_item)(sqp->seq, i); - if (item == NULL) { - if (i < sqp->len) - goto Fail_0; - if (err_occurred() == IndexError) { - err_clear(); - INCREF(None); - item = None; - sqp->len = -1; - } - else { - goto Fail_0; - } - } - else - any = 1; - - } - if (!alist) - break; - if (settupleitem(alist, j, item) < 0) { - DECREF(item); - goto Fail_0; - } - continue; - - Fail_0: - XDECREF(alist); - goto Fail_1; - } - - if (!alist) - alist = item; - - if (!any) { - DECREF(alist); - break; - } - - if (func == None) - value = alist; - else { - value = call_object(func, alist); - DECREF(alist); - if (value == NULL) - goto Fail_1; - } - if (i >= len) { - if (addlistitem(result, value) < 0) - goto Fail_1; - } - else { - if (setlistitem(result, i, value) < 0) - goto Fail_1; - } - } - - DEL(seqs); - return result; - -Fail_1: - DECREF(result); -Fail_2: - if (seqs) DEL(seqs); - return NULL; -} - -static object * -builtin_setattr(self, args) - object *self; - object *args; -{ - object *v; - object *name; - object *value; - - if (!newgetargs(args, "OSO:setattr", &v, &name, &value)) - return NULL; - if (setattro(v, name, value) != 0) - return NULL; - INCREF(None); - return None; -} - -static object * -builtin_delattr(self, args) - object *self; - object *args; -{ - object *v; - object *name; - - if (!newgetargs(args, "OS:delattr", &v, &name)) - return NULL; - if (setattro(v, name, (object *)NULL) != 0) - return NULL; - INCREF(None); - return None; -} - -static object * -builtin_hash(self, args) - object *self; - object *args; -{ - object *v; - long x; - - if (!newgetargs(args, "O:hash", &v)) - return NULL; - x = hashobject(v); - if (x == -1) - return NULL; - return newintobject(x); -} - -static object * -builtin_hex(self, args) - object *self; - object *args; -{ - object *v; - number_methods *nb; - - if (!newgetargs(args, "O:hex", &v)) - return NULL; - - if ((nb = v->ob_type->tp_as_number) == NULL || - nb->nb_hex == NULL) { - err_setstr(TypeError, - "hex() argument can't be converted to hex"); - return NULL; - } - return (*nb->nb_hex)(v); -} - -static object *builtin_raw_input PROTO((object *, object *)); - -static object * -builtin_input(self, args) - object *self; - object *args; -{ - object *line; - char *str; - object *res; - object *globals, *locals; - - line = builtin_raw_input(self, args); - if (line == NULL) - return line; - if (!getargs(line, "s;embedded '\\0' in input line", &str)) - return NULL; - while (*str == ' ' || *str == '\t') - str++; - globals = getglobals(); - locals = getlocals(); - if (dictlookup(globals, "__builtins__") == NULL) { - if (dictinsert(globals, "__builtins__", getbuiltins()) != 0) - return NULL; - } - res = run_string(str, eval_input, globals, locals); - DECREF(line); - return res; -} - -static object * -builtin_int(self, args) - object *self; - object *args; -{ - object *v; - number_methods *nb; - - if (!newgetargs(args, "O:int", &v)) - return NULL; - if ((nb = v->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - err_setstr(TypeError, - "int() argument can't be converted to int"); - return NULL; - } - return (*nb->nb_int)(v); -} - -static object * -builtin_len(self, args) - object *self; - object *args; -{ - object *v; - long len; - typeobject *tp; - - if (!newgetargs(args, "O:len", &v)) - return NULL; - tp = v->ob_type; - if (tp->tp_as_sequence != NULL) { - len = (*tp->tp_as_sequence->sq_length)(v); - } - else if (tp->tp_as_mapping != NULL) { - len = (*tp->tp_as_mapping->mp_length)(v); - } - else { - err_setstr(TypeError, "len() of unsized object"); - return NULL; - } - if (len < 0) - return NULL; - else - return newintobject(len); -} - -static object * -builtin_list(self, args) - object *self; - object *args; -{ - object *v; - sequence_methods *sqf; - - if (!newgetargs(args, "O:list", &v)) - return NULL; - if ((sqf = v->ob_type->tp_as_sequence) != NULL) { - int n = (*sqf->sq_length)(v); - int i; - object *l; - if (n < 0) - return NULL; - l = newlistobject(n); - if (l == NULL) - return NULL; - for (i = 0; i < n; i++) { - object *item = (*sqf->sq_item)(v, i); - if (item == NULL) { - DECREF(l); - l = NULL; - break; - } - setlistitem(l, i, item); - } - /* XXX Should support indefinite-length sequences */ - return l; - } - err_setstr(TypeError, "list() argument must be a sequence"); - return NULL; -} - -static object * -builtin_locals(self, args) - object *self; - object *args; -{ - object *d; - - if (!newgetargs(args, "")) - return NULL; - d = getlocals(); - INCREF(d); - return d; -} - -static object * -builtin_long(self, args) - object *self; - object *args; -{ - object *v; - number_methods *nb; - - if (!newgetargs(args, "O:long", &v)) - return NULL; - if ((nb = v->ob_type->tp_as_number) == NULL || - nb->nb_long == NULL) { - err_setstr(TypeError, - "long() argument can't be converted to long"); - return NULL; - } - return (*nb->nb_long)(v); -} - -static object * -min_max(args, sign) - object *args; - int sign; -{ - int i; - object *v, *w, *x; - sequence_methods *sq; - - if (gettuplesize(args) > 1) - v = args; - else if (!newgetargs(args, "O:min/max", &v)) - return NULL; - sq = v->ob_type->tp_as_sequence; - if (sq == NULL) { - err_setstr(TypeError, "min() or max() of non-sequence"); - return NULL; - } - w = NULL; - for (i = 0; ; i++) { - x = (*sq->sq_item)(v, i); /* Implies INCREF */ - if (x == NULL) { - if (err_occurred() == IndexError) { - err_clear(); - break; - } - XDECREF(w); - return NULL; - } - if (w == NULL) - w = x; - else { - if (cmpobject(x, w) * sign > 0) { - DECREF(w); - w = x; - } - else - DECREF(x); - } - } - if (w == NULL) - err_setstr(ValueError, "min() or max() of empty sequence"); - return w; -} - -static object * -builtin_min(self, v) - object *self; - object *v; -{ - return min_max(v, -1); -} - -static object * -builtin_max(self, v) - object *self; - object *v; -{ - return min_max(v, 1); -} - -static object * -builtin_oct(self, args) - object *self; - object *args; -{ - object *v; - number_methods *nb; - - if (!newgetargs(args, "O:oct", &v)) - return NULL; - if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL || - nb->nb_oct == NULL) { - err_setstr(TypeError, - "oct() argument can't be converted to oct"); - return NULL; - } - return (*nb->nb_oct)(v); -} - -static object * -builtin_open(self, args) - object *self; - object *args; -{ - char *name; - char *mode = "r"; - int bufsize = -1; - object *f; - - if (!newgetargs(args, "s|si:open", &name, &mode, &bufsize)) - return NULL; - f = newfileobject(name, mode); - if (f != NULL) - setfilebufsize(f, bufsize); - return f; -} - -static object * -builtin_ord(self, args) - object *self; - object *args; -{ - char c; - - if (!newgetargs(args, "c:ord", &c)) - return NULL; - return newintobject((long)(c & 0xff)); -} - -static object * -do_pow(v, w) - object *v, *w; -{ - object *res; - if (is_instanceobject(v) || is_instanceobject(w)) - return instancebinop(v, w, "__pow__", "__rpow__", do_pow); - if (v->ob_type->tp_as_number == NULL || - w->ob_type->tp_as_number == NULL) { - err_setstr(TypeError, "pow() requires numeric arguments"); - return NULL; - } - if ( -#ifndef WITHOUT_COMPLEX - !is_complexobject(v) && -#endif - is_floatobject(w) && getfloatvalue(v) < 0.0) { - if (!err_occurred()) - err_setstr(ValueError, "negative number to float power"); - return NULL; - } - if (coerce(&v, &w) != 0) - return NULL; - res = (*v->ob_type->tp_as_number->nb_power)(v, w, None); - DECREF(v); - DECREF(w); - return res; -} - -static object * -builtin_pow(self, args) - object *self; - object *args; -{ - object *v, *w, *z = None, *res; - object *v1, *z1, *w2, *z2; - - if (!newgetargs(args, "OO|O:pow", &v, &w, &z)) - return NULL; - if (z == None) - return do_pow(v, w); - /* XXX The ternary version doesn't do class instance coercions */ - if (is_instanceobject(v)) - return v->ob_type->tp_as_number->nb_power(v, w, z); - if (v->ob_type->tp_as_number == NULL || - z->ob_type->tp_as_number == NULL || - w->ob_type->tp_as_number == NULL) { - err_setstr(TypeError, "pow() requires numeric arguments"); - return NULL; - } - if (coerce(&v, &w) != 0) - return NULL; - res = NULL; - v1 = v; - z1 = z; - if (coerce(&v1, &z1) != 0) - goto error2; - w2 = w; - z2 = z1; - if (coerce(&w2, &z2) != 0) - goto error1; - res = (*v1->ob_type->tp_as_number->nb_power)(v1, w2, z2); - DECREF(w2); - DECREF(z2); - error1: - DECREF(v1); - DECREF(z1); - error2: - DECREF(v); - DECREF(w); - return res; -} - -static object * -builtin_range(self, args) - object *self; - object *args; -{ - long ilow = 0, ihigh = 0, istep = 1; - int i, n; - object *v; - - if (gettuplesize(args) <= 1) { - if (!newgetargs(args, - "l;range() requires 1-3 int arguments", - &ihigh)) - return NULL; - } - else { - if (!newgetargs(args, - "ll|l;range() requires 1-3 int arguments", - &ilow, &ihigh, &istep)) - return NULL; - } - if (istep == 0) { - err_setstr(ValueError, "zero step for range()"); - return NULL; - } - /* XXX ought to check overflow of subtraction */ - if (istep > 0) - n = (ihigh - ilow + istep - 1) / istep; - else - n = (ihigh - ilow + istep + 1) / istep; - if (n < 0) - n = 0; - v = newlistobject(n); - if (v == NULL) - return NULL; - for (i = 0; i < n; i++) { - object *w = newintobject(ilow); - if (w == NULL) { - DECREF(v); - return NULL; - } - setlistitem(v, i, w); - ilow += istep; - } - return v; -} - -static object * -builtin_xrange(self, args) - object *self; - object *args; -{ - long ilow = 0, ihigh = 0, istep = 1; - long n; - - if (gettuplesize(args) <= 1) { - if (!newgetargs(args, - "l;xrange() requires 1-3 int arguments", - &ihigh)) - return NULL; - } - else { - if (!newgetargs(args, - "ll|l;xrange() requires 1-3 int arguments", - &ilow, &ihigh, &istep)) - return NULL; - } - if (istep == 0) { - err_setstr(ValueError, "zero step for xrange()"); - return NULL; - } - /* XXX ought to check overflow of subtraction */ - if (istep > 0) - n = (ihigh - ilow + istep - 1) / istep; - else - n = (ihigh - ilow + istep + 1) / istep; - if (n < 0) - n = 0; - return newrangeobject(ilow, n, istep, 1); -} - -extern char *my_readline PROTO((char *)); - -static object * -builtin_raw_input(self, args) - object *self; - object *args; -{ - object *v = NULL; - object *f; - - if (!newgetargs(args, "|O:[raw_]input", &v)) - return NULL; - if (getfilefile(sysget("stdin")) == stdin && - getfilefile(sysget("stdout")) == stdout && - isatty(fileno(stdin)) && isatty(fileno(stdout))) { - object *po; - char *prompt; - char *s; - object *result; - if (v != NULL) { - po = strobject(v); - if (po == NULL) - return NULL; - prompt = getstringvalue(po); - } - else { - po = NULL; - prompt = ""; - } - s = my_readline(prompt); - XDECREF(po); - if (s == NULL) { - err_set(KeyboardInterrupt); - return NULL; - } - if (*s == '\0') { - err_set(EOFError); - result = NULL; - } - else { /* strip trailing '\n' */ - result = newsizedstringobject(s, strlen(s)-1); - } - free(s); - return result; - } - if (v != NULL) { - f = sysget("stdout"); - if (f == NULL) { - err_setstr(RuntimeError, "lost sys.stdout"); - return NULL; - } - flushline(); - if (writeobject(v, f, PRINT_RAW) != 0) - return NULL; - } - f = sysget("stdin"); - if (f == NULL) { - err_setstr(RuntimeError, "lost sys.stdin"); - return NULL; - } - return filegetline(f, -1); -} - -static object * -builtin_reduce(self, args) - object *self; - object *args; -{ - object *seq, *func, *result = NULL; - sequence_methods *sqf; - register int i; - - if (!newgetargs(args, "OO|O:reduce", &func, &seq, &result)) - return NULL; - if (result != NULL) - INCREF(result); - - if ((sqf = seq->ob_type->tp_as_sequence) == NULL) { - err_setstr(TypeError, - "2nd argument to reduce() must be a sequence object"); - return NULL; - } - - if ((args = newtupleobject(2)) == NULL) - goto Fail; - - for (i = 0; ; ++i) { - object *op2; - - if (args->ob_refcnt > 1) { - DECREF(args); - if ((args = newtupleobject(2)) == NULL) - goto Fail; - } - - if ((op2 = (*sqf->sq_item)(seq, i)) == NULL) { - if (err_occurred() == IndexError) { - err_clear(); - break; - } - goto Fail; - } - - if (result == NULL) - result = op2; - else { - settupleitem(args, 0, result); - settupleitem(args, 1, op2); - if ((result = call_object(func, args)) == NULL) - goto Fail; - } - } - - DECREF(args); - - if (result == NULL) - err_setstr(TypeError, - "reduce of empty sequence with no initial value"); - - return result; - -Fail: - XDECREF(args); - XDECREF(result); - return NULL; -} - -static object * -builtin_reload(self, args) - object *self; - object *args; -{ - object *v; - - if (!newgetargs(args, "O:reload", &v)) - return NULL; - return reload_module(v); -} - -static object * -builtin_repr(self, args) - object *self; - object *args; -{ - object *v; - - if (!newgetargs(args, "O:repr", &v)) - return NULL; - return reprobject(v); -} - -static object * -builtin_round(self, args) - object *self; - object *args; -{ - extern double floor PROTO((double)); - extern double ceil PROTO((double)); - double x; - double f; - int ndigits = 0; - int i; - - if (!newgetargs(args, "d|i:round", &x, &ndigits)) - return NULL; - f = 1.0; - for (i = ndigits; --i >= 0; ) - f = f*10.0; - for (i = ndigits; ++i <= 0; ) - f = f*0.1; - if (x >= 0.0) - return newfloatobject(floor(x*f + 0.5) / f); - else - return newfloatobject(ceil(x*f - 0.5) / f); -} - -static object * -builtin_str(self, args) - object *self; - object *args; -{ - object *v; - - if (!newgetargs(args, "O:str", &v)) - return NULL; - return strobject(v); -} - -static object * -builtin_tuple(self, args) - object *self; - object *args; -{ - object *v; - sequence_methods *sqf; - - if (!newgetargs(args, "O:tuple", &v)) - return NULL; - if (is_tupleobject(v)) { - INCREF(v); - return v; - } - if (is_listobject(v)) - return listtuple(v); - if (is_stringobject(v)) { - int n = getstringsize(v); - object *t = newtupleobject(n); - if (t != NULL) { - int i; - char *p = getstringvalue(v); - for (i = 0; i < n; i++) { - object *item = newsizedstringobject(p+i, 1); - if (item == NULL) { - DECREF(t); - t = NULL; - break; - } - settupleitem(t, i, item); - } - } - return t; - } - /* Generic sequence object */ - if ((sqf = v->ob_type->tp_as_sequence) != NULL) { - int n = (*sqf->sq_length)(v); - int i; - object *t; - if (n < 0) - return NULL; - t = newtupleobject(n); - if (t == NULL) - return NULL; - for (i = 0; i < n; i++) { - object *item = (*sqf->sq_item)(v, i); - if (item == NULL) { - DECREF(t); - t = NULL; - break; - } - settupleitem(t, i, item); - } - /* XXX Should support indefinite-length sequences */ - return t; - } - /* None of the above */ - err_setstr(TypeError, "tuple() argument must be a sequence"); - return NULL; -} - -static object * -builtin_type(self, args) - object *self; - object *args; -{ - object *v; - - if (!newgetargs(args, "O:type", &v)) - return NULL; - v = (object *)v->ob_type; - INCREF(v); - return v; -} - -static object * -builtin_vars(self, args) - object *self; - object *args; -{ - object *v = NULL; - object *d; - - if (!newgetargs(args, "|O:vars", &v)) - return NULL; - if (v == NULL) { - d = getlocals(); - if (d == NULL) { - if (!err_occurred()) - err_setstr(SystemError, "no locals!?"); - } - else - INCREF(d); - } - else { - d = getattr(v, "__dict__"); - if (d == NULL) { - err_setstr(TypeError, - "vars() argument must have __dict__ attribute"); - return NULL; - } - } - return d; -} - -static struct methodlist builtin_methods[] = { - {"__import__", builtin___import__, 1}, - {"abs", builtin_abs, 1}, - {"apply", builtin_apply, 1}, - {"callable", builtin_callable, 1}, - {"chr", builtin_chr, 1}, - {"cmp", builtin_cmp, 1}, - {"coerce", builtin_coerce, 1}, - {"compile", builtin_compile, 1}, -#ifndef WITHOUT_COMPLEX - {"complex", builtin_complex, 1}, -#endif - {"delattr", builtin_delattr, 1}, - {"dir", builtin_dir, 1}, - {"divmod", builtin_divmod, 1}, - {"eval", builtin_eval, 1}, - {"execfile", builtin_execfile, 1}, - {"filter", builtin_filter, 1}, - {"float", builtin_float, 1}, - {"getattr", builtin_getattr, 1}, - {"globals", builtin_globals, 1}, - {"hasattr", builtin_hasattr, 1}, - {"hash", builtin_hash, 1}, - {"hex", builtin_hex, 1}, - {"id", builtin_id, 1}, - {"input", builtin_input, 1}, - {"int", builtin_int, 1}, - {"len", builtin_len, 1}, - {"list", builtin_list, 1}, - {"locals", builtin_locals, 1}, - {"long", builtin_long, 1}, - {"map", builtin_map, 1}, - {"max", builtin_max, 1}, - {"min", builtin_min, 1}, - {"oct", builtin_oct, 1}, - {"open", builtin_open, 1}, - {"ord", builtin_ord, 1}, - {"pow", builtin_pow, 1}, - {"range", builtin_range, 1}, - {"raw_input", builtin_raw_input, 1}, - {"reduce", builtin_reduce, 1}, - {"reload", builtin_reload, 1}, - {"repr", builtin_repr, 1}, - {"round", builtin_round, 1}, - {"setattr", builtin_setattr, 1}, - {"str", builtin_str, 1}, - {"tuple", builtin_tuple, 1}, - {"type", builtin_type, 1}, - {"vars", builtin_vars, 1}, - {"xrange", builtin_xrange, 1}, - {NULL, NULL}, -}; - -static object *builtin_mod; -static object *builtin_dict; - -object * -getbuiltinmod() -{ - return builtin_mod; -} - -object * -getbuiltindict() -{ - return builtin_dict; -} - -/* Predefined exceptions */ - -object *AccessError; -object *AttributeError; -object *ConflictError; -object *EOFError; -object *IOError; -object *ImportError; -object *IndexError; -object *KeyError; -object *KeyboardInterrupt; -object *MemoryError; -object *NameError; -object *OverflowError; -object *RuntimeError; -object *SyntaxError; -object *SystemError; -object *SystemExit; -object *TypeError; -object *ValueError; -object *ZeroDivisionError; - -static object * -newstdexception(name) - char *name; -{ - object *v = newstringobject(name); - if (v == NULL || dictinsert(builtin_dict, name, v) != 0) - fatal("no mem for new standard exception"); - return v; -} - -static void -initerrors() -{ - AccessError = newstdexception("AccessError"); - AttributeError = newstdexception("AttributeError"); - ConflictError = newstdexception("ConflictError"); - EOFError = newstdexception("EOFError"); - IOError = newstdexception("IOError"); - ImportError = newstdexception("ImportError"); - IndexError = newstdexception("IndexError"); - KeyError = newstdexception("KeyError"); - KeyboardInterrupt = newstdexception("KeyboardInterrupt"); - MemoryError = newstdexception("MemoryError"); - NameError = newstdexception("NameError"); - OverflowError = newstdexception("OverflowError"); - RuntimeError = newstdexception("RuntimeError"); - SyntaxError = newstdexception("SyntaxError"); - SystemError = newstdexception("SystemError"); - SystemExit = newstdexception("SystemExit"); - TypeError = newstdexception("TypeError"); - ValueError = newstdexception("ValueError"); - ZeroDivisionError = newstdexception("ZeroDivisionError"); -} - -void -initbuiltin() -{ - builtin_mod = initmodule("__builtin__", builtin_methods); - builtin_dict = getmoduledict(builtin_mod); - INCREF(builtin_dict); - initerrors(); - (void) dictinsert(builtin_dict, "None", None); -} - - -/* Helper for filter(): filter a tuple through a function */ - -static object * -filtertuple(func, tuple) - object *func; - object *tuple; -{ - object *result; - register int i, j; - int len = gettuplesize(tuple); - - if (len == 0) { - INCREF(tuple); - return tuple; - } - - if ((result = newtupleobject(len)) == NULL) - return NULL; - - for (i = j = 0; i < len; ++i) { - object *item, *good; - int ok; - - if ((item = gettupleitem(tuple, i)) == NULL) - goto Fail_1; - if (func == None) { - INCREF(item); - good = item; - } - else { - object *arg = mkvalue("(O)", item); - if (arg == NULL) - goto Fail_1; - good = call_object(func, arg); - DECREF(arg); - if (good == NULL) - goto Fail_1; - } - ok = testbool(good); - DECREF(good); - if (ok) { - INCREF(item); - if (settupleitem(result, j++, item) < 0) - goto Fail_1; - } - } - - if (resizetuple(&result, j, 0) < 0) - return NULL; - - return result; - -Fail_1: - DECREF(result); - return NULL; -} - - -/* Helper for filter(): filter a string through a function */ - -static object * -filterstring(func, strobj) - object *func; - object *strobj; -{ - object *result; - register int i, j; - int len = getstringsize(strobj); - - if (func == None) { - /* No character is ever false -- share input string */ - INCREF(strobj); - return strobj; - } - if ((result = newsizedstringobject(NULL, len)) == NULL) - return NULL; - - for (i = j = 0; i < len; ++i) { - object *item, *arg, *good; - int ok; - - item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i); - if (item == NULL) - goto Fail_1; - arg = mkvalue("(O)", item); - DECREF(item); - if (arg == NULL) - goto Fail_1; - good = call_object(func, arg); - DECREF(arg); - if (good == NULL) - goto Fail_1; - ok = testbool(good); - DECREF(good); - if (ok) - GETSTRINGVALUE((stringobject *)result)[j++] = - GETSTRINGVALUE((stringobject *)item)[0]; - } - - if (resizestring(&result, j) < 0) - return NULL; - - return result; - -Fail_1: - DECREF(result); - return NULL; -} diff --git a/Python/ceval.c b/Python/ceval.c deleted file mode 100644 index 3797792117..0000000000 --- a/Python/ceval.c +++ /dev/null @@ -1,2975 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Execute compiled code */ - -/* XXX TO DO: - XXX how to pass arguments to call_trace? - XXX totally get rid of access stuff - XXX speed up searching for keywords by using a dictionary - XXX unknown keyword shouldn't raise KeyError? - XXX document it! - */ - -#include "allobjects.h" - -#include "compile.h" -#include "frameobject.h" -#include "eval.h" -#include "opcode.h" -#include "graminit.h" - -#include <ctype.h> - -/* Turn this on if your compiler chokes on the big switch: */ -/* #define CASE_TOO_BIG 1 */ - -#ifdef DEBUG -/* For debugging the interpreter: */ -#define LLTRACE 1 /* Low-level trace feature */ -#define CHECKEXC 1 /* Double-check exception checking */ -#endif - - -/* Forward declarations */ - -static object *eval_code2 PROTO((codeobject *, - object *, object *, - object **, int, - object **, int, - object **, int, - object *)); -#ifdef LLTRACE -static int prtrace PROTO((object *, char *)); -#endif -static void call_exc_trace PROTO((object **, object**, frameobject *)); -static int call_trace - PROTO((object **, object **, frameobject *, char *, object *)); -static object *add PROTO((object *, object *)); -static object *sub PROTO((object *, object *)); -static object *pow PROTO((object *, object *)); -static object *mul PROTO((object *, object *)); -static object *divide PROTO((object *, object *)); -static object *mod PROTO((object *, object *)); -static object *neg PROTO((object *)); -static object *pos PROTO((object *)); -static object *not PROTO((object *)); -static object *invert PROTO((object *)); -static object *lshift PROTO((object *, object *)); -static object *rshift PROTO((object *, object *)); -static object *and PROTO((object *, object *)); -static object *xor PROTO((object *, object *)); -static object *or PROTO((object *, object *)); -static object *call_builtin PROTO((object *, object *, object *)); -static object *call_function PROTO((object *, object *, object *)); -static object *apply_subscript PROTO((object *, object *)); -static object *loop_subscript PROTO((object *, object *)); -static int slice_index PROTO((object *, int, int *)); -static object *apply_slice PROTO((object *, object *, object *)); -static int assign_subscript PROTO((object *, object *, object *)); -static int assign_slice PROTO((object *, object *, object *, object *)); -static int cmp_exception PROTO((object *, object *)); -static int cmp_member PROTO((object *, object *)); -static object *cmp_outcome PROTO((int, object *, object *)); -static int import_from PROTO((object *, object *, object *)); -static object *build_class PROTO((object *, object *, object *)); -static int access_statement PROTO((object *, object *, frameobject *)); -static int exec_statement PROTO((object *, object *, object *)); -static object *find_from_args PROTO((frameobject *, int)); - - -/* Pointer to current frame, used to link new frames to */ - -static frameobject *current_frame; - -#ifdef WITH_THREAD - -#include <errno.h> -#include "thread.h" - -static type_lock interpreter_lock = 0; -static long main_thread = 0; - -void -init_save_thread() -{ - if (interpreter_lock) - return; - interpreter_lock = allocate_lock(); - acquire_lock(interpreter_lock, 1); - main_thread = get_thread_ident(); -} - -#endif - -/* Functions save_thread and restore_thread are always defined so - dynamically loaded modules needn't be compiled separately for use - with and without threads: */ - -object * -save_thread() -{ -#ifdef WITH_THREAD - if (interpreter_lock) { - object *res; - res = (object *)current_frame; - current_frame = NULL; - release_lock(interpreter_lock); - return res; - } -#endif - return NULL; -} - -void -restore_thread(x) - object *x; -{ -#ifdef WITH_THREAD - if (interpreter_lock) { - int err; - err = errno; - acquire_lock(interpreter_lock, 1); - errno = err; - current_frame = (frameobject *)x; - } -#endif -} - - -/* Mechanism whereby asynchronously executing callbacks (e.g. UNIX - signal handlers or Mac I/O completion routines) can schedule calls - to a function to be called synchronously. - The synchronous function is called with one void* argument. - It should return 0 for success or -1 for failure -- failure should - be accompanied by an exception. - - If registry succeeds, the registry function returns 0; if it fails - (e.g. due to too many pending calls) it returns -1 (without setting - an exception condition). - - Note that because registry may occur from within signal handlers, - or other asynchronous events, calling malloc() is unsafe! - -#ifdef WITH_THREAD - Any thread can schedule pending calls, but only the main thread - will execute them. -#endif - - XXX WARNING! ASYNCHRONOUSLY EXECUTING CODE! - There are two possible race conditions: - (1) nested asynchronous registry calls; - (2) registry calls made while pending calls are being processed. - While (1) is very unlikely, (2) is a real possibility. - The current code is safe against (2), but not against (1). - The safety against (2) is derived from the fact that only one - thread (the main thread) ever takes things out of the queue. -*/ - -#define NPENDINGCALLS 32 -static struct { - int (*func) PROTO((ANY *)); - ANY *arg; -} pendingcalls[NPENDINGCALLS]; -static volatile int pendingfirst = 0; -static volatile int pendinglast = 0; - -int -Py_AddPendingCall(func, arg) - int (*func) PROTO((ANY *)); - ANY *arg; -{ - static int busy = 0; - int i, j; - /* XXX Begin critical section */ - /* XXX If you want this to be safe against nested - XXX asynchronous calls, you'll have to work harder! */ - if (busy) - return -1; - busy = 1; - i = pendinglast; - j = (i + 1) % NPENDINGCALLS; - if (j == pendingfirst) - return -1; /* Queue full */ - pendingcalls[i].func = func; - pendingcalls[i].arg = arg; - pendinglast = j; - busy = 0; - /* XXX End critical section */ - return 0; -} - -int -Py_MakePendingCalls() -{ - static int busy = 0; -#ifdef WITH_THREAD - if (get_thread_ident() != main_thread) - return 0; -#endif - if (busy) - return 0; - busy = 1; - for (;;) { - int i; - int (*func) PROTO((ANY *)); - ANY *arg; - i = pendingfirst; - if (i == pendinglast) - break; /* Queue empty */ - func = pendingcalls[i].func; - arg = pendingcalls[i].arg; - pendingfirst = (i + 1) % NPENDINGCALLS; - if (func(arg) < 0) { - busy = 0; - return -1; - } - } - busy = 0; - return 0; -} - - -/* Status code for main loop (reason for stack unwind) */ - -enum why_code { - WHY_NOT, /* No error */ - WHY_EXCEPTION, /* Exception occurred */ - WHY_RERAISE, /* Exception re-raised by 'finally' */ - WHY_RETURN, /* 'return' statement */ - WHY_BREAK /* 'break' statement */ -}; - - -/* Backward compatible interface */ - -object * -eval_code(co, globals, locals) - codeobject *co; - object *globals; - object *locals; -{ - return eval_code2(co, - globals, locals, - (object **)NULL, 0, - (object **)NULL, 0, - (object **)NULL, 0, - (object *)NULL); -} - - -/* Interpreter main loop */ - -static object * -eval_code2(co, globals, locals, - args, argcount, kws, kwcount, defs, defcount, owner) - codeobject *co; - object *globals; - object *locals; - object **args; - int argcount; - object **kws; /* length: 2*kwcount */ - int kwcount; - object **defs; - int defcount; - object *owner; -{ - register unsigned char *next_instr; - register int opcode; /* Current opcode */ - register int oparg; /* Current opcode argument, if any */ - register object **stack_pointer; - register enum why_code why; /* Reason for block stack unwind */ - register int err; /* Error status -- nonzero if error */ - register object *x; /* Result object -- NULL if error */ - register object *v; /* Temporary objects popped off stack */ - register object *w; - register object *u; - register object *t; - register frameobject *f; /* Current frame */ - register object **fastlocals; - object *retval; /* Return value */ - int defmode = 0; /* Default access mode for new variables */ -#ifdef LLTRACE - int lltrace; -#endif -#if defined(DEBUG) || defined(LLTRACE) - /* Make it easier to find out where we are with a debugger */ - char *filename = getstringvalue(co->co_filename); -#endif - -/* Code access macros */ - -#define GETCONST(i) Getconst(f, i) -#define GETNAME(i) Getname(f, i) -#define GETNAMEV(i) Getnamev(f, i) -#define FIRST_INSTR() (GETUSTRINGVALUE(f->f_code->co_code)) -#define INSTR_OFFSET() (next_instr - FIRST_INSTR()) -#define NEXTOP() (*next_instr++) -#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) -#define JUMPTO(x) (next_instr = FIRST_INSTR() + (x)) -#define JUMPBY(x) (next_instr += (x)) - -/* Stack manipulation macros */ - -#define STACK_LEVEL() (stack_pointer - f->f_valuestack) -#define EMPTY() (STACK_LEVEL() == 0) -#define TOP() (stack_pointer[-1]) -#define BASIC_PUSH(v) (*stack_pointer++ = (v)) -#define BASIC_POP() (*--stack_pointer) - -#define CHECK_STACK(n) (STACK_LEVEL() + (n) < f->f_nvalues || \ - (stack_pointer = extend_stack(f, STACK_LEVEL(), n))) - -#ifdef LLTRACE -#define PUSH(v) (BASIC_PUSH(v), lltrace && prtrace(TOP(), "push")) -#define POP() (lltrace && prtrace(TOP(), "pop"), BASIC_POP()) -#else -#define PUSH(v) BASIC_PUSH(v) -#define POP() BASIC_POP() -#endif - -/* Local variable macros */ - -#define GETLOCAL(i) (fastlocals[i]) -#define SETLOCAL(i, value) do { XDECREF(GETLOCAL(i)); \ - GETLOCAL(i) = value; } while (0) - - if (globals == NULL) { - err_setstr(SystemError, "eval_code2: NULL globals"); - return NULL; - } - -#ifdef LLTRACE - lltrace = dictlookup(globals, "__lltrace__") != NULL; -#endif - - f = newframeobject( - current_frame, /*back*/ - co, /*code*/ - globals, /*globals*/ - locals, /*locals*/ - owner, /*owner*/ - 50, /*nvalues*/ - 20); /*nblocks*/ - if (f == NULL) - return NULL; - - current_frame = f; - - if (co->co_nlocals > 0) - fastlocals = ((listobject *)f->f_fastlocals)->ob_item; - - if (co->co_argcount > 0 || - co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) { - int i; - int n = argcount; - object *kwdict = NULL; - if (co->co_flags & CO_VARKEYWORDS) { - kwdict = newmappingobject(); - if (kwdict == NULL) - goto fail; - } - if (argcount > co->co_argcount) { - if (!(co->co_flags & CO_VARARGS)) { - err_setstr(TypeError, "too many arguments"); - goto fail; - } - n = co->co_argcount; - } - for (i = 0; i < n; i++) { - x = args[i]; - INCREF(x); - SETLOCAL(i, x); - } - if (co->co_flags & CO_VARARGS) { - u = newtupleobject(argcount - n); - for (i = n; i < argcount; i++) { - x = args[i]; - INCREF(x); - SETTUPLEITEM(u, i-n, x); - } - SETLOCAL(co->co_argcount, u); - } - for (i = 0; i < kwcount; i++) { - object *keyword = kws[2*i]; - object *value = kws[2*i + 1]; - int j; - /* XXX slow -- speed up using dictionary? */ - for (j = 0; j < co->co_argcount; j++) { - object *nm = GETTUPLEITEM(co->co_varnames, j); - if (cmpobject(keyword, nm) == 0) - break; - } - if (j >= co->co_argcount) { - if (kwdict == NULL) { - err_setval(KeyError/*XXX*/, keyword); - goto fail; - } - mappinginsert(kwdict, keyword, value); - } - else { - if (GETLOCAL(j) != NULL) { - err_setstr(TypeError, - "keyword parameter redefined"); - goto fail; - } - INCREF(value); - SETLOCAL(j, value); - } - } - if (argcount < co->co_argcount) { - int m = co->co_argcount - defcount; - for (i = argcount; i < m; i++) { - if (GETLOCAL(i) == NULL) { - err_setstr(TypeError, - "not enough arguments"); - goto fail; - } - } - if (n > m) - i = n - m; - else - i = 0; - for (; i < defcount; i++) { - if (GETLOCAL(m+i) == NULL) { - object *def = defs[i]; - INCREF(def); - SETLOCAL(m+i, def); - } - } - } - if (kwdict != NULL) { - i = co->co_argcount; - if (co->co_flags & CO_VARARGS) - i++; - SETLOCAL(i, kwdict); - } - if (0) { - fail: - XDECREF(kwdict); - goto fail2; - } - } - else { - if (argcount > 0 || kwcount > 0) { - err_setstr(TypeError, "no arguments expected"); - fail2: - current_frame = f->f_back; - DECREF(f); - return NULL; - } - } - - if (sys_trace != NULL) { - /* sys_trace, if defined, is a function that will - be called on *every* entry to a code block. - Its return value, if not None, is a function that - will be called at the start of each executed line - of code. (Actually, the function must return - itself in order to continue tracing.) - The trace functions are called with three arguments: - a pointer to the current frame, a string indicating - why the function is called, and an argument which - depends on the situation. The global trace function - (sys.trace) is also called whenever an exception - is detected. */ - if (call_trace(&sys_trace, &f->f_trace, f, "call", - None/*XXX how to compute arguments now?*/)) { - /* Trace function raised an error */ - current_frame = f->f_back; - DECREF(f); - return NULL; - } - } - - if (sys_profile != NULL) { - /* Similar for sys_profile, except it needn't return - itself and isn't called for "line" events */ - if (call_trace(&sys_profile, (object**)0, f, "call", - None/*XXX*/)) { - current_frame = f->f_back; - DECREF(f); - return NULL; - } - } - - next_instr = GETUSTRINGVALUE(f->f_code->co_code); - stack_pointer = f->f_valuestack; - - why = WHY_NOT; - err = 0; - x = None; /* Not a reference, just anything non-NULL */ - - for (;;) { - static int ticker; - - /* Do periodic things. - Doing this every time through the loop would add - too much overhead (a function call per instruction). - So we do it only every Nth instruction. */ - - if (pendingfirst != pendinglast) { - if (Py_MakePendingCalls() < 0) { - why = WHY_EXCEPTION; - goto on_error; - } - } - - if (--ticker < 0) { - ticker = sys_checkinterval; - if (sigcheck()) { - why = WHY_EXCEPTION; - goto on_error; - } - -#ifdef WITH_THREAD - if (interpreter_lock) { - /* Give another thread a chance */ - - current_frame = NULL; - release_lock(interpreter_lock); - - /* Other threads may run now */ - - acquire_lock(interpreter_lock, 1); - current_frame = f; - } -#endif - } - - /* Extract opcode and argument */ - -#if defined(DEBUG) || defined(LLTRACE) - f->f_lasti = INSTR_OFFSET(); -#endif - - opcode = NEXTOP(); - if (HAS_ARG(opcode)) - oparg = NEXTARG(); - -#ifdef LLTRACE - /* Instruction tracing */ - - if (lltrace) { - if (HAS_ARG(opcode)) { - printf("%d: %d, %d\n", - (int) (INSTR_OFFSET() - 3), - opcode, oparg); - } - else { - printf("%d: %d\n", - (int) (INSTR_OFFSET() - 1), opcode); - } - } -#endif - - if (!CHECK_STACK(3)) { - x = NULL; - break; - } - - /* Main switch on opcode */ - - switch (opcode) { - - /* BEWARE! - It is essential that any operation that fails sets either - x to NULL, err to nonzero, or why to anything but WHY_NOT, - and that no operation that succeeds does this! */ - - /* case STOP_CODE: this is an error! */ - - case POP_TOP: - v = POP(); - DECREF(v); - break; - - case ROT_TWO: - v = POP(); - w = POP(); - PUSH(v); - PUSH(w); - break; - - case ROT_THREE: - v = POP(); - w = POP(); - x = POP(); - PUSH(v); - PUSH(x); - PUSH(w); - break; - - case DUP_TOP: - v = TOP(); - INCREF(v); - PUSH(v); - break; - - case UNARY_POSITIVE: - v = POP(); - x = pos(v); - DECREF(v); - PUSH(x); - break; - - case UNARY_NEGATIVE: - v = POP(); - x = neg(v); - DECREF(v); - PUSH(x); - break; - - case UNARY_NOT: - v = POP(); - x = not(v); - DECREF(v); - PUSH(x); - break; - - case UNARY_CONVERT: - v = POP(); - x = reprobject(v); - DECREF(v); - PUSH(x); - break; - - case UNARY_INVERT: - v = POP(); - x = invert(v); - DECREF(v); - PUSH(x); - break; - - case BINARY_POWER: - w = POP(); - v = POP(); - x = pow(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_MULTIPLY: - w = POP(); - v = POP(); - x = mul(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_DIVIDE: - w = POP(); - v = POP(); - x = divide(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_MODULO: - w = POP(); - v = POP(); - x = mod(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_ADD: - w = POP(); - v = POP(); - x = add(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_SUBTRACT: - w = POP(); - v = POP(); - x = sub(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_SUBSCR: - w = POP(); - v = POP(); - x = apply_subscript(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_LSHIFT: - w = POP(); - v = POP(); - x = lshift(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_RSHIFT: - w = POP(); - v = POP(); - x = rshift(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_AND: - w = POP(); - v = POP(); - x = and(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_XOR: - w = POP(); - v = POP(); - x = xor(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case BINARY_OR: - w = POP(); - v = POP(); - x = or(v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case SLICE+0: - case SLICE+1: - case SLICE+2: - case SLICE+3: - if ((opcode-SLICE) & 2) - w = POP(); - else - w = NULL; - if ((opcode-SLICE) & 1) - v = POP(); - else - v = NULL; - u = POP(); - x = apply_slice(u, v, w); - DECREF(u); - XDECREF(v); - XDECREF(w); - PUSH(x); - break; - - case STORE_SLICE+0: - case STORE_SLICE+1: - case STORE_SLICE+2: - case STORE_SLICE+3: - if ((opcode-STORE_SLICE) & 2) - w = POP(); - else - w = NULL; - if ((opcode-STORE_SLICE) & 1) - v = POP(); - else - v = NULL; - u = POP(); - t = POP(); - err = assign_slice(u, v, w, t); /* u[v:w] = t */ - DECREF(t); - DECREF(u); - XDECREF(v); - XDECREF(w); - break; - - case DELETE_SLICE+0: - case DELETE_SLICE+1: - case DELETE_SLICE+2: - case DELETE_SLICE+3: - if ((opcode-DELETE_SLICE) & 2) - w = POP(); - else - w = NULL; - if ((opcode-DELETE_SLICE) & 1) - v = POP(); - else - v = NULL; - u = POP(); - err = assign_slice(u, v, w, (object *)NULL); - /* del u[v:w] */ - DECREF(u); - XDECREF(v); - XDECREF(w); - break; - - case STORE_SUBSCR: - w = POP(); - v = POP(); - u = POP(); - /* v[w] = u */ - err = assign_subscript(v, w, u); - DECREF(u); - DECREF(v); - DECREF(w); - break; - - case DELETE_SUBSCR: - w = POP(); - v = POP(); - /* del v[w] */ - err = assign_subscript(v, w, (object *)NULL); - DECREF(v); - DECREF(w); - break; - - case PRINT_EXPR: - v = POP(); - /* Print value except if procedure result */ - /* Before printing, also assign to '_' */ - if (v != None && - (err = dictinsert(f->f_builtins, "_", v)) == 0 && - !suppress_print) { - flushline(); - x = sysget("stdout"); - err = writeobject(v, x, 0); - softspace(x, 1); - flushline(); - } - DECREF(v); - break; - - case PRINT_ITEM: - v = POP(); - w = sysget("stdout"); - if (softspace(w, 1)) - writestring(" ", w); - err = writeobject(v, w, PRINT_RAW); - if (err == 0 && is_stringobject(v)) { - /* XXX move into writeobject() ? */ - char *s = getstringvalue(v); - int len = getstringsize(v); - if (len > 0 && - isspace(Py_CHARMASK(s[len-1])) && - s[len-1] != ' ') - softspace(w, 0); - } - DECREF(v); - break; - - case PRINT_NEWLINE: - x = sysget("stdout"); - if (x == NULL) - err_setstr(RuntimeError, "lost sys.stdout"); - else { - writestring("\n", x); - softspace(x, 0); - } - break; - - case BREAK_LOOP: - why = WHY_BREAK; - break; - - case RAISE_VARARGS: - u = v = w = NULL; - switch (oparg) { - case 3: - u = POP(); /* traceback */ - if (u == None) { - DECREF(u); - u = NULL; - } - else if (!PyTraceBack_Check(u)) { - err_setstr(TypeError, - "raise 3rd arg must be traceback or None"); - goto raise_error; - } - /* Fallthrough */ - case 2: - v = POP(); /* value */ - /* Fallthrough */ - case 1: - w = POP(); /* exc */ - break; - default: - err_setstr(SystemError, - "bad RAISE_VARARGS oparg"); - goto raise_error; - } - if (v == NULL) { - v = None; - INCREF(v); - } - /* A tuple is equivalent to its first element here */ - while (is_tupleobject(w) && gettuplesize(w) > 0) { - t = w; - w = GETTUPLEITEM(w, 0); - INCREF(w); - DECREF(t); - } - if (is_stringobject(w)) { - ; - } else if (is_classobject(w)) { - if (!is_instanceobject(v) - || !issubclass((object*)((instanceobject*)v)->in_class, - w)) { - err_setstr(TypeError, - "a class exception must have a value that is an instance of the class"); - goto raise_error; - } - } else if (is_instanceobject(w)) { - if (v != None) { - err_setstr(TypeError, - "an instance exception may not have a separate value"); - goto raise_error; - } - else { - DECREF(v); - v = w; - w = (object*) ((instanceobject*)w)->in_class; - INCREF(w); - } - } - else { - err_setstr(TypeError, - "exceptions must be strings, classes, or instances"); - goto raise_error; - } - err_restore(w, v, u); - if (u == NULL) - why = WHY_EXCEPTION; - else - why = WHY_RERAISE; - break; - raise_error: - XDECREF(v); - XDECREF(w); - XDECREF(u); - why = WHY_EXCEPTION; - break; - - case LOAD_LOCALS: - if ((x = f->f_locals) == NULL) { - err_setstr(SystemError, "no locals"); - break; - } - INCREF(x); - PUSH(x); - break; - - case RETURN_VALUE: - retval = POP(); - why = WHY_RETURN; - break; - - case EXEC_STMT: - w = POP(); - v = POP(); - u = POP(); - err = exec_statement(u, v, w); - DECREF(u); - DECREF(v); - DECREF(w); - break; - - case POP_BLOCK: - { - block *b = pop_block(f); - while (STACK_LEVEL() > b->b_level) { - v = POP(); - DECREF(v); - } - } - break; - - case END_FINALLY: - v = POP(); - if (is_intobject(v)) { - why = (enum why_code) getintvalue(v); - if (why == WHY_RETURN) - retval = POP(); - } - else if (is_stringobject(v) || is_classobject(v)) { - w = POP(); - u = POP(); - err_restore(v, w, u); - why = WHY_RERAISE; - break; - } - else if (v != None) { - err_setstr(SystemError, - "'finally' pops bad exception"); - why = WHY_EXCEPTION; - } - DECREF(v); - break; - - case BUILD_CLASS: - u = POP(); - v = POP(); - w = POP(); - x = build_class(u, v, w); - PUSH(x); - DECREF(u); - DECREF(v); - DECREF(w); - break; - - case STORE_NAME: - w = GETNAMEV(oparg); - v = POP(); - if ((x = f->f_locals) == NULL) { - err_setstr(SystemError, "no locals"); - break; - } - u = dict2lookup(x, w); - if (u == NULL) { - if (defmode != 0) { - if (v != None) - u = (object *)v->ob_type; - else - u = NULL; - x = newaccessobject(v, x, - (typeobject *)u, - defmode); - DECREF(v); - if (x == NULL) - break; - v = x; - } - } - else if (is_accessobject(u)) { - err = setaccessvalue(u, x, v); - DECREF(v); - break; - } - err = dict2insert(x, w, v); - DECREF(v); - break; - - case DELETE_NAME: - w = GETNAMEV(oparg); - if ((x = f->f_locals) == NULL) { - err_setstr(SystemError, "no locals"); - break; - } - u = dict2lookup(x, w); - if (u != NULL && is_accessobject(u)) { - err = setaccessvalue(u, x, - (object *)NULL); - break; - } - if ((err = dict2remove(x, w)) != 0) - err_setval(NameError, w); - break; - -#ifdef CASE_TOO_BIG - default: switch (opcode) { -#endif - - case UNPACK_TUPLE: - v = POP(); - if (!is_tupleobject(v)) { - err_setstr(TypeError, "unpack non-tuple"); - why = WHY_EXCEPTION; - } - else if (gettuplesize(v) != oparg) { - err_setstr(ValueError, - "unpack tuple of wrong size"); - why = WHY_EXCEPTION; - } - else { - if (!CHECK_STACK(oparg)) { - x = NULL; - break; - } - for (; --oparg >= 0; ) { - w = GETTUPLEITEM(v, oparg); - INCREF(w); - PUSH(w); - } - } - DECREF(v); - break; - - case UNPACK_LIST: - v = POP(); - if (!is_listobject(v)) { - err_setstr(TypeError, "unpack non-list"); - why = WHY_EXCEPTION; - } - else if (getlistsize(v) != oparg) { - err_setstr(ValueError, - "unpack list of wrong size"); - why = WHY_EXCEPTION; - } - else { - if (!CHECK_STACK(oparg)) { - x = NULL; - break; - } - for (; --oparg >= 0; ) { - w = getlistitem(v, oparg); - INCREF(w); - PUSH(w); - } - } - DECREF(v); - break; - - case STORE_ATTR: - w = GETNAMEV(oparg); - v = POP(); - u = POP(); - err = setattro(v, w, u); /* v.w = u */ - DECREF(v); - DECREF(u); - break; - - case DELETE_ATTR: - w = GETNAMEV(oparg); - v = POP(); - err = setattro(v, w, (object *)NULL); /* del v.w */ - DECREF(v); - break; - - case STORE_GLOBAL: - w = GETNAMEV(oparg); - v = POP(); - if (f->f_locals != NULL) { - u = dict2lookup(f->f_locals, w); - if (u != NULL && is_accessobject(u)) { - err = setaccessvalue(u, f->f_globals, - v); - DECREF(v); - break; - } - } - err = dict2insert(f->f_globals, w, v); - DECREF(v); - break; - - case DELETE_GLOBAL: - w = GETNAMEV(oparg); - if (f->f_locals != NULL) { - u = dict2lookup(f->f_locals, w); - if (u != NULL && is_accessobject(u)) { - err = setaccessvalue(u, f->f_globals, - (object *)NULL); - break; - } - } - if ((err = dict2remove(f->f_globals, w)) != 0) - err_setval(NameError, w); - break; - - case LOAD_CONST: - x = GETCONST(oparg); - INCREF(x); - PUSH(x); - break; - - case LOAD_NAME: - w = GETNAMEV(oparg); - if ((x = f->f_locals) == NULL) { - err_setstr(SystemError, "no locals"); - break; - } - x = dict2lookup(x, w); - if (x == NULL) { - err_clear(); - x = dict2lookup(f->f_globals, w); - if (x == NULL) { - err_clear(); - x = dict2lookup(f->f_builtins, w); - if (x == NULL) { - err_setval(NameError, w); - break; - } - } - } - if (is_accessobject(x)) { - x = getaccessvalue(x, f->f_globals /* XXX */); - if (x == NULL) - break; - } - else - INCREF(x); - PUSH(x); - break; - - case LOAD_GLOBAL: - w = GETNAMEV(oparg); - x = dict2lookup(f->f_globals, w); - if (x == NULL) { - err_clear(); - x = dict2lookup(f->f_builtins, w); - if (x == NULL) { - err_setval(NameError, w); - break; - } - } - if (is_accessobject(x)) { - x = getaccessvalue(x, f->f_globals); - if (x == NULL) - break; - } - else - INCREF(x); - PUSH(x); - break; - -#if 0 - case LOAD_LOCAL: - w = GETNAMEV(oparg); - if ((x = f->f_locals) == NULL) { - err_setstr(SystemError, "no locals"); - break; - } - x = dict2lookup(x, w); - if (x == NULL) { - err_setval(NameError, w); - break; - } - if (is_accessobject(x)) { - x = getaccessvalue(x, f->f_locals); - if (x == NULL) - break; - } - else - INCREF(x); - PUSH(x); - break; -#endif - - case LOAD_FAST: - x = GETLOCAL(oparg); - if (x == NULL) { - err_setval(NameError, - gettupleitem(co->co_varnames, - oparg)); - break; - } - if (is_accessobject(x)) { - x = getaccessvalue(x, f->f_locals); - if (x == NULL) - break; - } - else - INCREF(x); - PUSH(x); - break; - - case STORE_FAST: - v = POP(); - w = GETLOCAL(oparg); - if (w != NULL && is_accessobject(w)) { - err = setaccessvalue(w, f->f_locals, v); - DECREF(v); - break; - } - SETLOCAL(oparg, v); - break; - - case DELETE_FAST: - x = GETLOCAL(oparg); - if (x == NULL) { - err_setval(NameError, - gettupleitem(co->co_varnames, - oparg)); - break; - } - if (is_accessobject(x)) { - err = setaccessvalue(x, f->f_locals, - (object *)NULL); - break; - } - SETLOCAL(oparg, NULL); - break; - - case BUILD_TUPLE: - x = newtupleobject(oparg); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - SETTUPLEITEM(x, oparg, w); - } - PUSH(x); - } - break; - - case BUILD_LIST: - x = newlistobject(oparg); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - err = setlistitem(x, oparg, w); - if (err != 0) - break; - } - PUSH(x); - } - break; - - case BUILD_MAP: - x = newdictobject(); - PUSH(x); - break; - - case LOAD_ATTR: - w = GETNAMEV(oparg); - v = POP(); - x = getattro(v, w); - DECREF(v); - PUSH(x); - break; - - case COMPARE_OP: - w = POP(); - v = POP(); - x = cmp_outcome(oparg, v, w); - DECREF(v); - DECREF(w); - PUSH(x); - break; - - case IMPORT_NAME: - w = GETNAMEV(oparg); - x = dictlookup(f->f_builtins, "__import__"); - if (x == NULL) { - err_setstr(ImportError, - "__import__ not found"); - break; - } - if (is_methodobject(x)) { - u = None; - INCREF(u); - } - else { - u = find_from_args(f, INSTR_OFFSET()); - if (u == NULL) { - x = u; - break; - } - } - w = mkvalue("(OOOO)", - w, - f->f_globals, - f->f_locals == NULL ? None : f->f_locals, - u); - DECREF(u); - if (w == NULL) { - x = NULL; - break; - } - x = call_object(x, w); - DECREF(w); - PUSH(x); - break; - - case IMPORT_FROM: - w = GETNAMEV(oparg); - v = TOP(); - fast_2_locals(f); - if ((x = f->f_locals) == NULL) { - err_setstr(SystemError, "no locals"); - break; - } - err = import_from(x, v, w); - locals_2_fast(f, 0); - break; - - case ACCESS_MODE: - v = POP(); - w = GETNAMEV(oparg); - if (getstringvalue(w)[0] == '*') - defmode = getintvalue(v); - else - err = access_statement(w, v, f); - DECREF(v); - break; - - case JUMP_FORWARD: - JUMPBY(oparg); - break; - - case JUMP_IF_FALSE: - err = testbool(TOP()); - if (err > 0) - err = 0; - else if (err == 0) - JUMPBY(oparg); - break; - - case JUMP_IF_TRUE: - err = testbool(TOP()); - if (err > 0) { - err = 0; - JUMPBY(oparg); - } - break; - - case JUMP_ABSOLUTE: - JUMPTO(oparg); - break; - - case FOR_LOOP: - /* for v in s: ... - On entry: stack contains s, i. - On exit: stack contains s, i+1, s[i]; - but if loop exhausted: - s, i are popped, and we jump */ - w = POP(); /* Loop index */ - v = POP(); /* Sequence object */ - u = loop_subscript(v, w); - if (u != NULL) { - PUSH(v); - x = newintobject(getintvalue(w)+1); - PUSH(x); - DECREF(w); - PUSH(u); - } - else { - DECREF(v); - DECREF(w); - /* A NULL can mean "s exhausted" - but also an error: */ - if (err_occurred()) - why = WHY_EXCEPTION; - else - JUMPBY(oparg); - } - break; - - case SETUP_LOOP: - case SETUP_EXCEPT: - case SETUP_FINALLY: - setup_block(f, opcode, INSTR_OFFSET() + oparg, - STACK_LEVEL()); - break; - - case SET_LINENO: -#ifdef LLTRACE - if (lltrace) - printf("--- %s:%d \n", filename, oparg); -#endif - f->f_lineno = oparg; - if (f->f_trace != NULL) { - /* Trace each line of code reached */ - f->f_lasti = INSTR_OFFSET(); - err = call_trace(&f->f_trace, &f->f_trace, - f, "line", None); - } - break; - - case CALL_FUNCTION: - { - int na = oparg & 0xff; - int nk = (oparg>>8) & 0xff; - int n = na + 2*nk; - object **pfunc = stack_pointer - n - 1; - object *func = *pfunc; - object *self = NULL; - object *class = NULL; - f->f_lasti = INSTR_OFFSET() - 3; /* For tracing */ - if (is_instancemethodobject(func)) { - self = instancemethodgetself(func); - class = instancemethodgetclass(func); - func = instancemethodgetfunc(func); - INCREF(func); - if (self != NULL) { - INCREF(self); - DECREF(*pfunc); - *pfunc = self; - na++; - n++; - } - else { - /* Unbound methods must be - called with an instance of - the class (or a derived - class) as first argument */ - if (na > 0 && - (self = stack_pointer[-n]) - != NULL && - is_instanceobject(self) && - issubclass( - (object *) - (((instanceobject *)self) - ->in_class), - class)) - /* Handy-dandy */ ; - else { - err_setstr(TypeError, - "unbound method must be called with class instance 1st argument"); - x = NULL; - break; - } - } - } - else - INCREF(func); - if (is_funcobject(func)) { - object *co = getfunccode(func); - object *globals = getfuncglobals(func); - object *argdefs = PyFunction_GetDefaults(func); - object **d; - int nd; - if (argdefs != NULL) { - d = &GETTUPLEITEM(argdefs, 0); - nd = ((tupleobject *)argdefs)->ob_size; - } - else { - d = NULL; - nd = 0; - } - x = eval_code2( - (codeobject *)co, - globals, (object *)NULL, - stack_pointer-n, na, - stack_pointer-2*nk, nk, - d, nd, - class); - } - else { - object *args = newtupleobject(na); - object *kwdict = NULL; - if (args == NULL) { - x = NULL; - break; - } - if (nk > 0) { - kwdict = newdictobject(); - if (kwdict == NULL) { - x = NULL; - break; - } - err = 0; - while (--nk >= 0) { - object *value = POP(); - object *key = POP(); - err = mappinginsert( - kwdict, key, value); - if (err) { - DECREF(key); - DECREF(value); - break; - } - } - if (err) { - DECREF(args); - DECREF(kwdict); - break; - } - } - while (--na >= 0) { - w = POP(); - SETTUPLEITEM(args, na, w); - } - x = PyEval_CallObjectWithKeywords( - func, args, kwdict); - DECREF(args); - XDECREF(kwdict); - } - DECREF(func); - while (stack_pointer > pfunc) { - w = POP(); - DECREF(w); - } - PUSH(x); - break; - } - - case MAKE_FUNCTION: - v = POP(); /* code object */ - x = newfuncobject(v, f->f_globals); - DECREF(v); - /* XXX Maybe this should be a separate opcode? */ - if (x != NULL && oparg > 0) { - v = newtupleobject(oparg); - if (v == NULL) { - DECREF(x); - x = NULL; - break; - } - while (--oparg >= 0) { - w = POP(); - SETTUPLEITEM(v, oparg, w); - } - err = PyFunction_SetDefaults(x, v); - DECREF(v); - } - PUSH(x); - break; - - default: - fprintf(stderr, - "XXX lineno: %d, opcode: %d\n", - f->f_lineno, opcode); - err_setstr(SystemError, "unknown opcode"); - why = WHY_EXCEPTION; - break; - -#ifdef CASE_TOO_BIG - } -#endif - - } /* switch */ - - on_error: - - /* Quickly continue if no error occurred */ - - if (why == WHY_NOT) { - if (err == 0 && x != NULL) { -#ifdef CHECKEXC - if (err_occurred()) - fprintf(stderr, - "XXX undetected error\n"); - else -#endif - continue; /* Normal, fast path */ - } - why = WHY_EXCEPTION; - x = None; - err = 0; - } - -#ifdef CHECKEXC - /* Double-check exception status */ - - if (why == WHY_EXCEPTION || why == WHY_RERAISE) { - if (!err_occurred()) { - fprintf(stderr, "XXX ghost error\n"); - err_setstr(SystemError, "ghost error"); - why = WHY_EXCEPTION; - } - } - else { - if (err_occurred()) { - fprintf(stderr, - "XXX undetected error (why=%d)\n", - why); - why = WHY_EXCEPTION; - } - } -#endif - - /* Log traceback info if this is a real exception */ - - if (why == WHY_EXCEPTION) { - f->f_lasti = INSTR_OFFSET() - 1; - if (HAS_ARG(opcode)) - f->f_lasti -= 2; - tb_here(f); - - if (f->f_trace) - call_exc_trace(&f->f_trace, &f->f_trace, f); - if (sys_profile) - call_exc_trace(&sys_profile, (object**)0, f); - } - - /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ - - if (why == WHY_RERAISE) - why = WHY_EXCEPTION; - - /* Unwind stacks if a (pseudo) exception occurred */ - - while (why != WHY_NOT && f->f_iblock > 0) { - block *b = pop_block(f); - while (STACK_LEVEL() > b->b_level) { - v = POP(); - XDECREF(v); - } - if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { - why = WHY_NOT; - JUMPTO(b->b_handler); - break; - } - if (b->b_type == SETUP_FINALLY || - b->b_type == SETUP_EXCEPT && - why == WHY_EXCEPTION) { - if (why == WHY_EXCEPTION) { - object *exc, *val, *tb; - err_fetch(&exc, &val, &tb); - if (val == NULL) { - val = None; - INCREF(val); - } - /* Make the raw exception data - available to the handler, - so a program can emulate the - Python main loop. Don't do - this for 'finally'. */ - if (b->b_type == SETUP_EXCEPT) { - sysset("exc_traceback", tb); - sysset("exc_value", val); - sysset("exc_type", exc); - } - PUSH(tb); - PUSH(val); - PUSH(exc); - } - else { - if (why == WHY_RETURN) - PUSH(retval); - v = newintobject((long)why); - PUSH(v); - } - why = WHY_NOT; - JUMPTO(b->b_handler); - break; - } - } /* unwind stack */ - - /* End the loop if we still have an error (or return) */ - - if (why != WHY_NOT) - break; - - } /* main loop */ - - /* Pop remaining stack entries */ - - while (!EMPTY()) { - v = POP(); - XDECREF(v); - } - - if (why != WHY_RETURN) - retval = NULL; - - if (f->f_trace) { - if (why == WHY_RETURN) { - if (call_trace(&f->f_trace, &f->f_trace, f, - "return", retval)) { - XDECREF(retval); - retval = NULL; - why = WHY_EXCEPTION; - } - } - } - - if (sys_profile && why == WHY_RETURN) { - if (call_trace(&sys_profile, (object**)0, - f, "return", retval)) { - XDECREF(retval); - retval = NULL; - why = WHY_EXCEPTION; - } - } - - /* Restore previous frame and release the current one */ - - current_frame = f->f_back; - DECREF(f); - - return retval; -} - -#ifdef LLTRACE -static int -prtrace(v, str) - object *v; - char *str; -{ - printf("%s ", str); - if (printobject(v, stdout, 0) != 0) - err_clear(); /* Don't know what else to do */ - printf("\n"); -} -#endif - -static void -call_exc_trace(p_trace, p_newtrace, f) - object **p_trace, **p_newtrace; - frameobject *f; -{ - object *type, *value, *traceback, *arg; - int err; - err_fetch(&type, &value, &traceback); - if (value == NULL) { - value = None; - INCREF(value); - } - arg = mkvalue("(OOO)", type, value, traceback); - if (arg == NULL) { - err_restore(type, value, traceback); - return; - } - err = call_trace(p_trace, p_newtrace, f, "exception", arg); - DECREF(arg); - if (err == 0) - err_restore(type, value, traceback); - else { - XDECREF(type); - XDECREF(value); - XDECREF(traceback); - } -} - -static int -call_trace(p_trace, p_newtrace, f, msg, arg) - object **p_trace; /* in/out; may not be NULL; - may not point to NULL variable initially */ - object **p_newtrace; /* in/out; may be NULL; - may point to NULL variable; - may be same variable as p_newtrace */ - frameobject *f; - char *msg; - object *arg; -{ - object *args, *what; - object *res = NULL; - static int tracing = 0; - - if (tracing) { - /* Don't do recursive traces */ - if (p_newtrace) { - XDECREF(*p_newtrace); - *p_newtrace = NULL; - } - return 0; - } - - args = newtupleobject(3); - if (args == NULL) - goto cleanup; - what = newstringobject(msg); - if (what == NULL) - goto cleanup; - INCREF(f); - SETTUPLEITEM(args, 0, (object *)f); - SETTUPLEITEM(args, 1, what); - if (arg == NULL) - arg = None; - INCREF(arg); - SETTUPLEITEM(args, 2, arg); - tracing++; - fast_2_locals(f); - res = call_object(*p_trace, args); /* May clear *p_trace! */ - locals_2_fast(f, 1); - tracing--; - cleanup: - XDECREF(args); - if (res == NULL) { - /* The trace proc raised an exception */ - tb_here(f); - XDECREF(*p_trace); - *p_trace = NULL; - if (p_newtrace) { - XDECREF(*p_newtrace); - *p_newtrace = NULL; - } - return -1; - } - else { - if (p_newtrace) { - XDECREF(*p_newtrace); - if (res == None) - *p_newtrace = NULL; - else { - INCREF(res); - *p_newtrace = res; - } - } - DECREF(res); - return 0; - } -} - -object * -getbuiltins() -{ - if (current_frame == NULL) - return getbuiltinmod(); - else - return current_frame->f_builtins; -} - -object * -getlocals() -{ - if (current_frame == NULL) - return NULL; - fast_2_locals(current_frame); - return current_frame->f_locals; -} - -object * -getglobals() -{ - if (current_frame == NULL) - return NULL; - else - return current_frame->f_globals; -} - -object * -getowner() -{ - if (current_frame == NULL) - return NULL; - else - return current_frame->f_owner; -} - -object * -getframe() -{ - return (object *)current_frame; -} - -int -getrestricted() -{ - return current_frame == NULL ? 0 : current_frame->f_restricted; -} - -void -flushline() -{ - object *f = sysget("stdout"); - if (softspace(f, 0)) - writestring("\n", f); -} - - -#define BINOP(opname, ropname, thisfunc) \ - if (!is_instanceobject(v) && !is_instanceobject(w)) \ - ; \ - else \ - return instancebinop(v, w, opname, ropname, thisfunc) - - -static object * -or(v, w) - object *v, *w; -{ - BINOP("__or__", "__ror__", or); - if (v->ob_type->tp_as_number != NULL) { - object *x; - object * (*f) FPROTO((object *, object *)); - if (coerce(&v, &w) != 0) - return NULL; - if ((f = v->ob_type->tp_as_number->nb_or) != NULL) - x = (*f)(v, w); - DECREF(v); - DECREF(w); - if (f != NULL) - return x; - } - err_setstr(TypeError, "bad operand type(s) for |"); - return NULL; -} - -static object * -xor(v, w) - object *v, *w; -{ - BINOP("__xor__", "__rxor__", xor); - if (v->ob_type->tp_as_number != NULL) { - object *x; - object * (*f) FPROTO((object *, object *)); - if (coerce(&v, &w) != 0) - return NULL; - if ((f = v->ob_type->tp_as_number->nb_xor) != NULL) - x = (*f)(v, w); - DECREF(v); - DECREF(w); - if (f != NULL) - return x; - } - err_setstr(TypeError, "bad operand type(s) for ^"); - return NULL; -} - -static object * -and(v, w) - object *v, *w; -{ - BINOP("__and__", "__rand__", and); - if (v->ob_type->tp_as_number != NULL) { - object *x; - object * (*f) FPROTO((object *, object *)); - if (coerce(&v, &w) != 0) - return NULL; - if ((f = v->ob_type->tp_as_number->nb_and) != NULL) - x = (*f)(v, w); - DECREF(v); - DECREF(w); - if (f != NULL) - return x; - } - err_setstr(TypeError, "bad operand type(s) for &"); - return NULL; -} - -static object * -lshift(v, w) - object *v, *w; -{ - BINOP("__lshift__", "__rlshift__", lshift); - if (v->ob_type->tp_as_number != NULL) { - object *x; - object * (*f) FPROTO((object *, object *)); - if (coerce(&v, &w) != 0) - return NULL; - if ((f = v->ob_type->tp_as_number->nb_lshift) != NULL) - x = (*f)(v, w); - DECREF(v); - DECREF(w); - if (f != NULL) - return x; - } - err_setstr(TypeError, "bad operand type(s) for <<"); - return NULL; -} - -static object * -rshift(v, w) - object *v, *w; -{ - BINOP("__rshift__", "__rrshift__", rshift); - if (v->ob_type->tp_as_number != NULL) { - object *x; - object * (*f) FPROTO((object *, object *)); - if (coerce(&v, &w) != 0) - return NULL; - if ((f = v->ob_type->tp_as_number->nb_rshift) != NULL) - x = (*f)(v, w); - DECREF(v); - DECREF(w); - if (f != NULL) - return x; - } - err_setstr(TypeError, "bad operand type(s) for >>"); - return NULL; -} - -static object * -add(v, w) - object *v, *w; -{ - BINOP("__add__", "__radd__", add); - if (v->ob_type->tp_as_sequence != NULL) - return (*v->ob_type->tp_as_sequence->sq_concat)(v, w); - else if (v->ob_type->tp_as_number != NULL) { - object *x; - if (coerce(&v, &w) != 0) - return NULL; - x = (*v->ob_type->tp_as_number->nb_add)(v, w); - DECREF(v); - DECREF(w); - return x; - } - err_setstr(TypeError, "bad operand type(s) for +"); - return NULL; -} - -static object * -sub(v, w) - object *v, *w; -{ - BINOP("__sub__", "__rsub__", sub); - if (v->ob_type->tp_as_number != NULL) { - object *x; - if (coerce(&v, &w) != 0) - return NULL; - x = (*v->ob_type->tp_as_number->nb_subtract)(v, w); - DECREF(v); - DECREF(w); - return x; - } - err_setstr(TypeError, "bad operand type(s) for -"); - return NULL; -} - -static object * -mul(v, w) - object *v, *w; -{ - typeobject *tp; - tp = v->ob_type; - BINOP("__mul__", "__rmul__", mul); - if (tp->tp_as_number != NULL && - w->ob_type->tp_as_sequence != NULL && - !is_instanceobject(v)) { - /* number*sequence -- swap v and w */ - object *tmp = v; - v = w; - w = tmp; - tp = v->ob_type; - } - if (tp->tp_as_number != NULL) { - object *x; - if (is_instanceobject(v)) { - /* Instances of user-defined classes get their - other argument uncoerced, so they may - implement sequence*number as well as - number*number. */ - INCREF(v); - INCREF(w); - } - else if (coerce(&v, &w) != 0) - return NULL; - x = (*v->ob_type->tp_as_number->nb_multiply)(v, w); - DECREF(v); - DECREF(w); - return x; - } - if (tp->tp_as_sequence != NULL) { - if (!is_intobject(w)) { - err_setstr(TypeError, - "can't multiply sequence with non-int"); - return NULL; - } - return (*tp->tp_as_sequence->sq_repeat) - (v, (int)getintvalue(w)); - } - err_setstr(TypeError, "bad operand type(s) for *"); - return NULL; -} - -static object * -divide(v, w) - object *v, *w; -{ - BINOP("__div__", "__rdiv__", divide); - if (v->ob_type->tp_as_number != NULL) { - object *x; - if (coerce(&v, &w) != 0) - return NULL; - x = (*v->ob_type->tp_as_number->nb_divide)(v, w); - DECREF(v); - DECREF(w); - return x; - } - err_setstr(TypeError, "bad operand type(s) for /"); - return NULL; -} - -static object * -mod(v, w) - object *v, *w; -{ - if (is_stringobject(v)) { - return formatstring(v, w); - } - BINOP("__mod__", "__rmod__", mod); - if (v->ob_type->tp_as_number != NULL) { - object *x; - if (coerce(&v, &w) != 0) - return NULL; - x = (*v->ob_type->tp_as_number->nb_remainder)(v, w); - DECREF(v); - DECREF(w); - return x; - } - err_setstr(TypeError, "bad operand type(s) for %"); - return NULL; -} - -static object * -pow(v, w) - object *v, *w; -{ - object *res; - BINOP("__pow__", "__rpow__", pow); - if (v->ob_type->tp_as_number == NULL || - w->ob_type->tp_as_number == NULL) { - err_setstr(TypeError, "pow() requires numeric arguments"); - return NULL; - } - if ( -#ifndef WITHOUT_COMPLEX - !is_complexobject(v) && -#endif - is_floatobject(w) && getfloatvalue(v) < 0.0) { - if (!err_occurred()) - err_setstr(ValueError, "negative number to float power"); - return NULL; - } - if (coerce(&v, &w) != 0) - return NULL; - res = (*v->ob_type->tp_as_number->nb_power)(v, w, None); - DECREF(v); - DECREF(w); - return res; -} - -static object * -neg(v) - object *v; -{ - if (v->ob_type->tp_as_number != NULL) - return (*v->ob_type->tp_as_number->nb_negative)(v); - err_setstr(TypeError, "bad operand type(s) for unary -"); - return NULL; -} - -static object * -pos(v) - object *v; -{ - if (v->ob_type->tp_as_number != NULL) - return (*v->ob_type->tp_as_number->nb_positive)(v); - err_setstr(TypeError, "bad operand type(s) for unary +"); - return NULL; -} - -static object * -invert(v) - object *v; -{ - object * (*f) FPROTO((object *)); - if (v->ob_type->tp_as_number != NULL && - (f = v->ob_type->tp_as_number->nb_invert) != NULL) - return (*f)(v); - err_setstr(TypeError, "bad operand type(s) for unary ~"); - return NULL; -} - -static object * -not(v) - object *v; -{ - int outcome = testbool(v); - object *w; - if (outcome < 0) - return NULL; - if (outcome == 0) - w = True; - else - w = False; - INCREF(w); - return w; -} - - -/* External interface to call any callable object. - The arg must be a tuple or NULL. */ - -object * -call_object(func, arg) - object *func; - object *arg; -{ - return PyEval_CallObjectWithKeywords(func, arg, (object *)NULL); -} - -object * -PyEval_CallObjectWithKeywords(func, arg, kw) - object *func; - object *arg; - object *kw; -{ - ternaryfunc call; - object *result; - - if (arg == NULL) - arg = newtupleobject(0); - else if (!is_tupleobject(arg)) { - err_setstr(TypeError, "argument list must be a tuple"); - return NULL; - } - else - INCREF(arg); - - if (kw != NULL && !is_dictobject(kw)) { - err_setstr(TypeError, "keyword list must be a dictionary"); - return NULL; - } - - if (call = func->ob_type->tp_call) - result = (*call)(func, arg, kw); - else if (is_instancemethodobject(func) || is_funcobject(func)) - result = call_function(func, arg, kw); - else - result = call_builtin(func, arg, kw); - - DECREF(arg); - - if (result == NULL && !err_occurred()) - err_setstr(SystemError, - "NULL result without error in call_object"); - - return result; -} - -static object * -call_builtin(func, arg, kw) - object *func; - object *arg; - object *kw; -{ - if (is_methodobject(func)) { - method meth = getmethod(func); - object *self = getself(func); - int flags = getflags(func); - if (!(flags & METH_VARARGS)) { - int size = gettuplesize(arg); - if (size == 1) - arg = GETTUPLEITEM(arg, 0); - else if (size == 0) - arg = NULL; - } - if (flags & METH_KEYWORDS) - return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); - if (kw != NULL && getmappingsize(kw) != 0) { - err_setstr(TypeError, - "this function takes no keyword arguments"); - return NULL; - } - return (*meth)(self, arg); - } - if (is_classobject(func)) { - return newinstanceobject(func, arg, kw); - } - if (is_instanceobject(func)) { - object *res, *call = getattr(func,"__call__"); - if (call == NULL) { - err_clear(); - err_setstr(AttributeError, - "no __call__ method defined"); - return NULL; - } - res = PyEval_CallObjectWithKeywords(call, arg, kw); - DECREF(call); - return res; - } - err_setstr(TypeError, "call of non-function"); - return NULL; -} - -static object * -call_function(func, arg, kw) - object *func; - object *arg; - object *kw; -{ - object *class = NULL; /* == owner */ - object *argdefs; - object **d, **k; - int nk, nd; - object *result; - - if (kw != NULL && !is_dictobject(kw)) { - err_badcall(); - return NULL; - } - - if (is_instancemethodobject(func)) { - object *self = instancemethodgetself(func); - class = instancemethodgetclass(func); - func = instancemethodgetfunc(func); - if (self == NULL) { - /* Unbound methods must be called with an instance of - the class (or a derived class) as first argument */ - if (gettuplesize(arg) >= 1) { - self = GETTUPLEITEM(arg, 0); - if (self != NULL && - is_instanceobject(self) && - issubclass((object *) - (((instanceobject *)self)->in_class), - class)) - /* Handy-dandy */ ; - else - self = NULL; - } - if (self == NULL) { - err_setstr(TypeError, - "unbound method must be called with class instance 1st argument"); - return NULL; - } - INCREF(arg); - } - else { - int argcount = gettuplesize(arg); - object *newarg = newtupleobject(argcount + 1); - int i; - if (newarg == NULL) - return NULL; - INCREF(self); - SETTUPLEITEM(newarg, 0, self); - for (i = 0; i < argcount; i++) { - object *v = GETTUPLEITEM(arg, i); - XINCREF(v); - SETTUPLEITEM(newarg, i+1, v); - } - arg = newarg; - } - } - else { - if (!is_funcobject(func)) { - err_setstr(TypeError, "call of non-function"); - return NULL; - } - INCREF(arg); - } - - argdefs = PyFunction_GetDefaults(func); - if (argdefs != NULL && is_tupleobject(argdefs)) { - d = &GETTUPLEITEM((tupleobject *)argdefs, 0); - nd = gettuplesize(argdefs); - } - else { - d = NULL; - nd = 0; - } - - if (kw != NULL) { - int pos, i; - nk = getmappingsize(kw); - k = NEW(object *, 2*nk); - if (k == NULL) { - err_nomem(); - DECREF(arg); - return NULL; - } - pos = i = 0; - while (mappinggetnext(kw, &pos, &k[i], &k[i+1])) - i += 2; - nk = i/2; - /* XXX This is broken if the caller deletes dict items! */ - } - else { - k = NULL; - nk = 0; - } - - result = eval_code2( - (codeobject *)getfunccode(func), - getfuncglobals(func), (object *)NULL, - &GETTUPLEITEM(arg, 0), gettuplesize(arg), - k, nk, - d, nd, - class); - - DECREF(arg); - XDEL(k); - - return result; -} - -static object * -apply_subscript(v, w) - object *v, *w; -{ - typeobject *tp = v->ob_type; - if (tp->tp_as_sequence == NULL && tp->tp_as_mapping == NULL) { - err_setstr(TypeError, "unsubscriptable object"); - return NULL; - } - if (tp->tp_as_mapping != NULL) { - return (*tp->tp_as_mapping->mp_subscript)(v, w); - } - else { - int i; - if (!is_intobject(w)) { - err_setstr(TypeError, "sequence subscript not int"); - return NULL; - } - i = getintvalue(w); - if (i < 0) { - int len = (*tp->tp_as_sequence->sq_length)(v); - if (len < 0) - return NULL; - i += len; - } - return (*tp->tp_as_sequence->sq_item)(v, i); - } -} - -static object * -loop_subscript(v, w) - object *v, *w; -{ - sequence_methods *sq = v->ob_type->tp_as_sequence; - int i; - if (sq == NULL) { - err_setstr(TypeError, "loop over non-sequence"); - return NULL; - } - i = getintvalue(w); - v = (*sq->sq_item)(v, i); - if (v) - return v; - if (err_occurred() == IndexError) - err_clear(); - return NULL; -} - -static int -slice_index(v, isize, pi) - object *v; - int isize; - int *pi; -{ - if (v != NULL) { - if (!is_intobject(v)) { - err_setstr(TypeError, "slice index must be int"); - return -1; - } - *pi = getintvalue(v); - if (*pi < 0) - *pi += isize; - } - return 0; -} - -static object * -apply_slice(u, v, w) /* return u[v:w] */ - object *u, *v, *w; -{ - typeobject *tp = u->ob_type; - int ilow, ihigh, isize; - if (tp->tp_as_sequence == NULL) { - err_setstr(TypeError, "only sequences can be sliced"); - return NULL; - } - ilow = 0; - isize = ihigh = (*tp->tp_as_sequence->sq_length)(u); - if (isize < 0) - return NULL; - if (slice_index(v, isize, &ilow) != 0) - return NULL; - if (slice_index(w, isize, &ihigh) != 0) - return NULL; - return (*tp->tp_as_sequence->sq_slice)(u, ilow, ihigh); -} - -static int -assign_subscript(w, key, v) /* w[key] = v */ - object *w; - object *key; - object *v; -{ - typeobject *tp = w->ob_type; - sequence_methods *sq; - mapping_methods *mp; - int (*func1)(); - int (*func2)(); - if ((mp = tp->tp_as_mapping) != NULL && - (func1 = mp->mp_ass_subscript) != NULL) { - return (*func1)(w, key, v); - } - else if ((sq = tp->tp_as_sequence) != NULL && - (func2 = sq->sq_ass_item) != NULL) { - if (!is_intobject(key)) { - err_setstr(TypeError, - "sequence subscript must be integer (assign or del)"); - return -1; - } - else { - int i = getintvalue(key); - if (i < 0) { - int len = (*sq->sq_length)(w); - if (len < 0) - return -1; - i += len; - } - return (*func2)(w, i, v); - } - } - else { - err_setstr(TypeError, - "can't assign to this subscripted object"); - return -1; - } -} - -static int -assign_slice(u, v, w, x) /* u[v:w] = x */ - object *u, *v, *w, *x; -{ - sequence_methods *sq = u->ob_type->tp_as_sequence; - int ilow, ihigh, isize; - if (sq == NULL) { - err_setstr(TypeError, "assign to slice of non-sequence"); - return -1; - } - if (sq == NULL || sq->sq_ass_slice == NULL) { - err_setstr(TypeError, "unassignable slice"); - return -1; - } - ilow = 0; - isize = ihigh = (*sq->sq_length)(u); - if (isize < 0) - return -1; - if (slice_index(v, isize, &ilow) != 0) - return -1; - if (slice_index(w, isize, &ihigh) != 0) - return -1; - return (*sq->sq_ass_slice)(u, ilow, ihigh, x); -} - -static int -cmp_exception(err, v) - object *err, *v; -{ - if (is_tupleobject(v)) { - int i, n; - n = gettuplesize(v); - for (i = 0; i < n; i++) { - /* Test recursively */ - if (cmp_exception(err, GETTUPLEITEM(v, i))) - return 1; - } - return 0; - } - if (is_classobject(v) && is_classobject(err)) - return issubclass(err, v); - return err == v; -} - -static int -cmp_member(v, w) - object *v, *w; -{ - int i, cmp; - object *x; - sequence_methods *sq; - /* Special case for char in string */ - if (is_stringobject(w)) { - register char *s, *end; - register char c; - if (!is_stringobject(v) || getstringsize(v) != 1) { - err_setstr(TypeError, - "string member test needs char left operand"); - return -1; - } - c = getstringvalue(v)[0]; - s = getstringvalue(w); - end = s + getstringsize(w); - while (s < end) { - if (c == *s++) - return 1; - } - return 0; - } - sq = w->ob_type->tp_as_sequence; - if (sq == NULL) { - err_setstr(TypeError, - "'in' or 'not in' needs sequence right argument"); - return -1; - } - for (i = 0; ; i++) { - x = (*sq->sq_item)(w, i); - if (x == NULL) { - if (err_occurred() == IndexError) { - err_clear(); - break; - } - return -1; - } - cmp = cmpobject(v, x); - XDECREF(x); - if (cmp == 0) - return 1; - } - return 0; -} - -static object * -cmp_outcome(op, v, w) - int op; - register object *v; - register object *w; -{ - register int cmp; - register int res = 0; - switch (op) { - case IS: - case IS_NOT: - res = (v == w); - if (op == (int) IS_NOT) - res = !res; - break; - case IN: - case NOT_IN: - res = cmp_member(v, w); - if (res < 0) - return NULL; - if (op == (int) NOT_IN) - res = !res; - break; - case EXC_MATCH: - res = cmp_exception(v, w); - break; - default: - cmp = cmpobject(v, w); - switch (op) { - case LT: res = cmp < 0; break; - case LE: res = cmp <= 0; break; - case EQ: res = cmp == 0; break; - case NE: res = cmp != 0; break; - case GT: res = cmp > 0; break; - case GE: res = cmp >= 0; break; - /* XXX no default? (res is initialized to 0 though) */ - } - } - v = res ? True : False; - INCREF(v); - return v; -} - -static int -import_from(locals, v, name) - object *locals; - object *v; - object *name; -{ - object *w, *x; - if (!is_moduleobject(v)) { - err_setstr(TypeError, "import-from requires module object"); - return -1; - } - w = getmoduledict(v); - if (getstringvalue(name)[0] == '*') { - int pos, err; - object *name, *value; - pos = 0; - while (mappinggetnext(w, &pos, &name, &value)) { - if (!is_stringobject(name) || - getstringvalue(name)[0] == '_') - continue; - if (is_accessobject(value)) { - value = getaccessvalue(value, (object *)NULL); - if (value == NULL) { - err_clear(); - continue; - } - } - else - INCREF(value); - err = dict2insert(locals, name, value); - DECREF(value); - if (err != 0) - return -1; - } - return 0; - } - else { - x = dict2lookup(w, name); - if (x == NULL) { - char buf[250]; - sprintf(buf, "cannot import name %.230s", - getstringvalue(name)); - err_setstr(ImportError, buf); - return -1; - } - else - return dict2insert(locals, name, x); - } -} - -static object * -build_class(methods, bases, name) - object *methods; /* dictionary */ - object *bases; /* tuple containing classes */ - object *name; /* string */ -{ - int i; - if (!is_tupleobject(bases)) { - err_setstr(SystemError, "build_class with non-tuple bases"); - return NULL; - } - if (gettuplesize(bases) > 0) { - object *base; - base = GETTUPLEITEM(bases, 0); - /* Call the base's *type*, if it is callable. - This code is a hook for Donald Beaudry's type extensions. - In unexended Python it will never be triggered since its - types are not callable. */ - if (base->ob_type->ob_type->tp_call) { - object *args; - object *class; - args = mkvalue("(OOO)", name, bases, methods); - class = call_object((object *)base->ob_type, args); - DECREF(args); - return class; - } - } - if (!is_dictobject(methods)) { - err_setstr(SystemError, "build_class with non-dictionary"); - return NULL; - } - if (!is_stringobject(name)) { - err_setstr(SystemError, "build_class witn non-string name"); - return NULL; - } - for (i = gettuplesize(bases); --i >= 0; ) { - object *base = GETTUPLEITEM(bases, i); - if (!is_classobject(base)) { - err_setstr(TypeError, - "base is not a class object"); - return NULL; - } - } - return newclassobject(bases, methods, name); -} - -static int -access_statement(name, vmode, f) - object *name; - object *vmode; - frameobject *f; -{ - int mode = getintvalue(vmode); - object *value, *ac; - typeobject *type; - int ret; - fast_2_locals(f); - value = dict2lookup(f->f_locals, name); - if (value && is_accessobject(value)) { - err_setstr(AccessError, "can't override access"); - return -1; - } - err_clear(); - if (value != NULL && value != None) - type = value->ob_type; - else - type = NULL; - ac = newaccessobject(value, f->f_locals, type, mode); - if (ac == NULL) - return -1; - ret = mappinginsert(f->f_locals, name, ac); - DECREF(ac); - locals_2_fast(f, 0); - return ret; -} - -static int -exec_statement(prog, globals, locals) - object *prog; - object *globals; - object *locals; -{ - char *s; - int n; - object *v; - int plain = 0; - - if (is_tupleobject(prog) && globals == None && locals == None && - ((n = gettuplesize(prog)) == 2 || n == 3)) { - /* Backward compatibility hack */ - globals = gettupleitem(prog, 1); - if (n == 3) - locals = gettupleitem(prog, 2); - prog = gettupleitem(prog, 0); - } - if (globals == None) { - globals = getglobals(); - if (locals == None) { - locals = getlocals(); - plain = 1; - } - } - else if (locals == None) - locals = globals; - if (!is_stringobject(prog) && - !is_codeobject(prog) && - !is_fileobject(prog)) { - err_setstr(TypeError, - "exec 1st arg must be string, code or file object"); - return -1; - } - if (!is_dictobject(globals) || !is_dictobject(locals)) { - err_setstr(TypeError, - "exec 2nd/3rd args must be dict or None"); - return -1; - } - if (dictlookup(globals, "__builtins__") == NULL) - dictinsert(globals, "__builtins__", current_frame->f_builtins); - if (is_codeobject(prog)) { - if (eval_code((codeobject *) prog, globals, locals) == NULL) - return -1; - return 0; - } - if (is_fileobject(prog)) { - FILE *fp = getfilefile(prog); - char *name = getstringvalue(getfilename(prog)); - if (run_file(fp, name, file_input, globals, locals) == NULL) - return -1; - return 0; - } - s = getstringvalue(prog); - if (strlen(s) != getstringsize(prog)) { - err_setstr(ValueError, "embedded '\\0' in exec string"); - return -1; - } - v = run_string(s, file_input, globals, locals); - if (v == NULL) - return -1; - DECREF(v); - if (plain) - locals_2_fast(current_frame, 0); - return 0; -} - -/* Hack for newimp.py */ -static object * -find_from_args(f, nexti) - frameobject *f; - int nexti; -{ - int opcode; - int oparg; - object *list, *name; - unsigned char *next_instr; - - next_instr = GETUSTRINGVALUE(f->f_code->co_code) + nexti; - opcode = (*next_instr++); - if (opcode != IMPORT_FROM) { - INCREF(None); - return None; - } - - list = newlistobject(0); - if (list == NULL) - return NULL; - - do { - oparg = (next_instr[1]<<8) + next_instr[0]; - next_instr += 2; - name = Getnamev(f, oparg); - if (addlistitem(list, name) < 0) { - DECREF(list); - break; - } - opcode = (*next_instr++); - } while (opcode == IMPORT_FROM); - - return list; -} diff --git a/Python/cgensupport.c b/Python/cgensupport.c deleted file mode 100644 index 6951467306..0000000000 --- a/Python/cgensupport.c +++ /dev/null @@ -1,377 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Functions used by cgen output */ - -#include "allobjects.h" -#include "cgensupport.h" - - -/* Functions to extract arguments. - These needs to know the total number of arguments supplied, - since the argument list is a tuple only of there is more than - one argument. */ - -int -getiobjectarg(args, nargs, i, p_arg) - register object *args; - int nargs, i; - object **p_arg; -{ - if (nargs != 1) { - if (args == NULL || !is_tupleobject(args) || - nargs != gettuplesize(args) || - i < 0 || i >= nargs) { - return err_badarg(); - } - else { - args = gettupleitem(args, i); - } - } - if (args == NULL) { - return err_badarg(); - } - *p_arg = args; - return 1; -} - -int -getilongarg(args, nargs, i, p_arg) - register object *args; - int nargs, i; - long *p_arg; -{ - if (nargs != 1) { - if (args == NULL || !is_tupleobject(args) || - nargs != gettuplesize(args) || - i < 0 || i >= nargs) { - return err_badarg(); - } - args = gettupleitem(args, i); - } - if (args == NULL || !is_intobject(args)) { - return err_badarg(); - } - *p_arg = getintvalue(args); - return 1; -} - -int -getishortarg(args, nargs, i, p_arg) - register object *args; - int nargs, i; - short *p_arg; -{ - long x; - if (!getilongarg(args, nargs, i, &x)) - return 0; - *p_arg = x; - return 1; -} - -static int -extractdouble(v, p_arg) - register object *v; - double *p_arg; -{ - if (v == NULL) { - /* Fall through to error return at end of function */ - } - else if (is_floatobject(v)) { - *p_arg = GETFLOATVALUE((floatobject *)v); - return 1; - } - else if (is_intobject(v)) { - *p_arg = GETINTVALUE((intobject *)v); - return 1; - } - else if (is_longobject(v)) { - *p_arg = dgetlongvalue(v); - return 1; - } - return err_badarg(); -} - -static int -extractfloat(v, p_arg) - register object *v; - float *p_arg; -{ - if (v == NULL) { - /* Fall through to error return at end of function */ - } - else if (is_floatobject(v)) { - *p_arg = GETFLOATVALUE((floatobject *)v); - return 1; - } - else if (is_intobject(v)) { - *p_arg = GETINTVALUE((intobject *)v); - return 1; - } - else if (is_longobject(v)) { - *p_arg = dgetlongvalue(v); - return 1; - } - return err_badarg(); -} - -int -getifloatarg(args, nargs, i, p_arg) - register object *args; - int nargs, i; - float *p_arg; -{ - object *v; - float x; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (!extractfloat(v, &x)) - return 0; - *p_arg = x; - return 1; -} - -int -getistringarg(args, nargs, i, p_arg) - object *args; - int nargs, i; - string *p_arg; -{ - object *v; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (!is_stringobject(v)) { - return err_badarg(); - } - *p_arg = getstringvalue(v); - return 1; -} - -int -getichararg(args, nargs, i, p_arg) - object *args; - int nargs, i; - char *p_arg; -{ - string x; - if (!getistringarg(args, nargs, i, &x)) - return 0; - if (x[0] == '\0' || x[1] != '\0') { - /* Not exactly one char */ - return err_badarg(); - } - *p_arg = x[0]; - return 1; -} - -int -getilongarraysize(args, nargs, i, p_arg) - object *args; - int nargs, i; - long *p_arg; -{ - object *v; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - *p_arg = gettuplesize(v); - return 1; - } - if (is_listobject(v)) { - *p_arg = getlistsize(v); - return 1; - } - return err_badarg(); -} - -int -getishortarraysize(args, nargs, i, p_arg) - object *args; - int nargs, i; - short *p_arg; -{ - long x; - if (!getilongarraysize(args, nargs, i, &x)) - return 0; - *p_arg = x; - return 1; -} - -/* XXX The following four are too similar. Should share more code. */ - -int -getilongarray(args, nargs, i, n, p_arg) - object *args; - int nargs, i; - int n; - long *p_arg; /* [n] */ -{ - object *v, *w; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - if (gettuplesize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = gettupleitem(v, i); - if (!is_intobject(w)) { - return err_badarg(); - } - p_arg[i] = getintvalue(w); - } - return 1; - } - else if (is_listobject(v)) { - if (getlistsize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = getlistitem(v, i); - if (!is_intobject(w)) { - return err_badarg(); - } - p_arg[i] = getintvalue(w); - } - return 1; - } - else { - return err_badarg(); - } -} - -int -getishortarray(args, nargs, i, n, p_arg) - object *args; - int nargs, i; - int n; - short *p_arg; /* [n] */ -{ - object *v, *w; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - if (gettuplesize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = gettupleitem(v, i); - if (!is_intobject(w)) { - return err_badarg(); - } - p_arg[i] = getintvalue(w); - } - return 1; - } - else if (is_listobject(v)) { - if (getlistsize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = getlistitem(v, i); - if (!is_intobject(w)) { - return err_badarg(); - } - p_arg[i] = getintvalue(w); - } - return 1; - } - else { - return err_badarg(); - } -} - -int -getidoublearray(args, nargs, i, n, p_arg) - object *args; - int nargs, i; - int n; - double *p_arg; /* [n] */ -{ - object *v, *w; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - if (gettuplesize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = gettupleitem(v, i); - if (!extractdouble(w, &p_arg[i])) - return 0; - } - return 1; - } - else if (is_listobject(v)) { - if (getlistsize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = getlistitem(v, i); - if (!extractdouble(w, &p_arg[i])) - return 0; - } - return 1; - } - else { - return err_badarg(); - } -} - -int -getifloatarray(args, nargs, i, n, p_arg) - object *args; - int nargs, i; - int n; - float *p_arg; /* [n] */ -{ - object *v, *w; - if (!getiobjectarg(args, nargs, i, &v)) - return 0; - if (is_tupleobject(v)) { - if (gettuplesize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = gettupleitem(v, i); - if (!extractfloat(w, &p_arg[i])) - return 0; - } - return 1; - } - else if (is_listobject(v)) { - if (getlistsize(v) != n) { - return err_badarg(); - } - for (i = 0; i < n; i++) { - w = getlistitem(v, i); - if (!extractfloat(w, &p_arg[i])) - return 0; - } - return 1; - } - else { - return err_badarg(); - } -} diff --git a/Python/compile.c b/Python/compile.c deleted file mode 100644 index 3a1d3f68cf..0000000000 --- a/Python/compile.c +++ /dev/null @@ -1,2864 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Compile an expression node to intermediate code */ - -/* XXX TO DO: - XXX Compute maximum needed stack sizes while compiling; - XXX then frame object can be one malloc and no stack checks are needed - XXX add __doc__ attribute == co_doc to code object attributes - XXX don't execute doc string - XXX Generate simple jump for break/return outside 'try...finally' - XXX get rid of SET_LINENO instructions, use JAR's table trick - XXX (need an option to put them back in, for debugger!) - XXX other JAR tricks? -*/ - -#include "allobjects.h" - -#include "node.h" -#include "token.h" -#include "graminit.h" -#include "compile.h" -#include "opcode.h" -#include "structmember.h" - -#include <ctype.h> -#include <errno.h> - -#define OFF(x) offsetof(codeobject, x) - -static struct memberlist code_memberlist[] = { - {"co_argcount", T_INT, OFF(co_argcount), READONLY}, - {"co_nlocals", T_INT, OFF(co_nlocals), READONLY}, - {"co_flags", T_INT, OFF(co_flags), READONLY}, - {"co_code", T_OBJECT, OFF(co_code), READONLY}, - {"co_consts", T_OBJECT, OFF(co_consts), READONLY}, - {"co_names", T_OBJECT, OFF(co_names), READONLY}, - {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY}, - {"co_filename", T_OBJECT, OFF(co_filename), READONLY}, - {"co_name", T_OBJECT, OFF(co_name), READONLY}, - {NULL} /* Sentinel */ -}; - -static object * -code_getattr(co, name) - codeobject *co; - char *name; -{ - return getmember((char *)co, code_memberlist, name); -} - -static void -code_dealloc(co) - codeobject *co; -{ - XDECREF(co->co_code); - XDECREF(co->co_consts); - XDECREF(co->co_names); - XDECREF(co->co_filename); - XDECREF(co->co_name); - XDECREF(co->co_varnames); - DEL(co); -} - -static object * -code_repr(co) - codeobject *co; -{ - char buf[500]; - int lineno = -1; - char *p = GETSTRINGVALUE(co->co_code); - char *filename = "???"; - char *name = "???"; - if (*p == SET_LINENO) - lineno = (p[1] & 0xff) | ((p[2] & 0xff) << 8); - if (co->co_filename && is_stringobject(co->co_filename)) - filename = getstringvalue(co->co_filename); - if (co->co_name && is_stringobject(co->co_name)) - name = getstringvalue(co->co_name); - sprintf(buf, "<code object %.100s at %lx, file \"%.300s\", line %d>", - name, (long)co, filename, lineno); - return newstringobject(buf); -} - -static int -code_compare(co, cp) - codeobject *co, *cp; -{ - int cmp; - cmp = cp->co_argcount - cp->co_argcount; - if (cmp) return cmp; - cmp = cp->co_nlocals - cp->co_nlocals; - if (cmp) return cmp; - cmp = cp->co_flags - cp->co_flags; - if (cmp) return cmp; - cmp = cmpobject((object *)co->co_code, (object *)cp->co_code); - if (cmp) return cmp; - cmp = cmpobject(co->co_consts, cp->co_consts); - if (cmp) return cmp; - cmp = cmpobject(co->co_names, cp->co_names); - if (cmp) return cmp; - cmp = cmpobject(co->co_varnames, cp->co_varnames); - return cmp; -} - -static long -code_hash(co) - codeobject *co; -{ - long h, h1, h2, h3, h4; - h1 = hashobject((object *)co->co_code); - if (h1 == -1) return -1; - h2 = hashobject(co->co_consts); - if (h2 == -1) return -1; - h3 = hashobject(co->co_names); - if (h3 == -1) return -1; - h4 = hashobject(co->co_varnames); - if (h4 == -1) return -1; - h = h1 ^ h2 ^ h3 ^ h4 ^ - co->co_argcount ^ co->co_nlocals ^ co->co_flags; - if (h == -1) h = -2; - return h; -} - -typeobject Codetype = { - OB_HEAD_INIT(&Typetype) - 0, - "code", - sizeof(codeobject), - 0, - (destructor)code_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)code_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - (cmpfunc)code_compare, /*tp_compare*/ - (reprfunc)code_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)code_hash, /*tp_hash*/ -}; - -codeobject * -newcodeobject(argcount, nlocals, flags, - code, consts, names, varnames, filename, name) - int argcount; - int nlocals; - int flags; - object *code; - object *consts; - object *names; - object *varnames; - object *filename; - object *name; -{ - codeobject *co; - int i; - /* Check argument types */ - if (argcount < 0 || nlocals < 0 || - code == NULL || !is_stringobject(code) || - consts == NULL || !is_tupleobject(consts) || - names == NULL || !is_tupleobject(names) || - varnames == NULL || !is_tupleobject(varnames) || - name == NULL || !is_stringobject(name) || - filename == NULL || !is_stringobject(filename)) { - err_badcall(); - return NULL; - } - /* Make sure names and varnames are all strings */ - for (i = gettuplesize(names); --i >= 0; ) { - object *v = gettupleitem(names, i); - if (v == NULL || !is_stringobject(v)) { - err_badcall(); - return NULL; - } - } - for (i = gettuplesize(varnames); --i >= 0; ) { - object *v = gettupleitem(varnames, i); - if (v == NULL || !is_stringobject(v)) { - err_badcall(); - return NULL; - } - } - co = NEWOBJ(codeobject, &Codetype); - if (co != NULL) { - co->co_argcount = argcount; - co->co_nlocals = nlocals; - co->co_flags = flags; - INCREF(code); - co->co_code = (stringobject *)code; - INCREF(consts); - co->co_consts = consts; - INCREF(names); - co->co_names = names; - INCREF(varnames); - co->co_varnames = varnames; - INCREF(filename); - co->co_filename = filename; - INCREF(name); - co->co_name = name; - } - return co; -} - - -/* Data structure used internally */ - -#define MAXBLOCKS 20 /* Max static block nesting within a function */ - -struct compiling { - object *c_code; /* string */ - object *c_consts; /* list of objects */ - object *c_names; /* list of strings (names) */ - object *c_globals; /* dictionary (value=None) */ - object *c_locals; /* dictionary (value=localID) */ - object *c_varnames; /* list (inverse of c_locals) */ - int c_nlocals; /* index of next local */ - int c_argcount; /* number of top-level arguments */ - int c_flags; /* same as co_flags */ - int c_nexti; /* index into c_code */ - int c_errors; /* counts errors occurred */ - int c_infunction; /* set when compiling a function */ - int c_interactive; /* generating code for interactive command */ - int c_loops; /* counts nested loops */ - int c_begin; /* begin of current loop, for 'continue' */ - int c_block[MAXBLOCKS]; /* stack of block types */ - int c_nblocks; /* current block stack level */ - char *c_filename; /* filename of current node */ - char *c_name; /* name of object (e.g. function) */ -}; - - -/* Interface to the block stack */ - -static void -block_push(c, type) - struct compiling *c; - int type; -{ - if (c->c_nblocks >= MAXBLOCKS) { - err_setstr(SystemError, "too many statically nested blocks"); - c->c_errors++; - } - else { - c->c_block[c->c_nblocks++] = type; - } -} - -static void -block_pop(c, type) - struct compiling *c; - int type; -{ - if (c->c_nblocks > 0) - c->c_nblocks--; - if (c->c_block[c->c_nblocks] != type && c->c_errors == 0) { - err_setstr(SystemError, "bad block pop"); - c->c_errors++; - } -} - - -/* Prototype forward declarations */ - -static int com_init PROTO((struct compiling *, char *)); -static void com_free PROTO((struct compiling *)); -static void com_done PROTO((struct compiling *)); -static void com_node PROTO((struct compiling *, struct _node *)); -static void com_factor PROTO((struct compiling *, struct _node *)); -static void com_addbyte PROTO((struct compiling *, int)); -static void com_addint PROTO((struct compiling *, int)); -static void com_addoparg PROTO((struct compiling *, int, int)); -static void com_addfwref PROTO((struct compiling *, int, int *)); -static void com_backpatch PROTO((struct compiling *, int)); -static int com_add PROTO((struct compiling *, object *, object *)); -static int com_addconst PROTO((struct compiling *, object *)); -static int com_addname PROTO((struct compiling *, object *)); -static void com_addopname PROTO((struct compiling *, int, node *)); -static void com_list PROTO((struct compiling *, node *, int)); -static int com_argdefs PROTO((struct compiling *, node *)); -static int com_newlocal PROTO((struct compiling *, char *)); - -static int -com_init(c, filename) - struct compiling *c; - char *filename; -{ - if ((c->c_code = newsizedstringobject((char *)NULL, 1000)) == NULL) - goto fail_3; - if ((c->c_consts = newlistobject(0)) == NULL) - goto fail_2; - if ((c->c_names = newlistobject(0)) == NULL) - goto fail_1; - if ((c->c_globals = newdictobject()) == NULL) - goto fail_0; - if ((c->c_locals = newdictobject()) == NULL) - goto fail_00; - if ((c->c_varnames = newlistobject(0)) == NULL) - goto fail_000; - c->c_nlocals = 0; - c->c_argcount = 0; - c->c_flags = 0; - c->c_nexti = 0; - c->c_errors = 0; - c->c_infunction = 0; - c->c_interactive = 0; - c->c_loops = 0; - c->c_begin = 0; - c->c_nblocks = 0; - c->c_filename = filename; - c->c_name = "?"; - return 1; - - fail_000: - DECREF(c->c_locals); - fail_00: - DECREF(c->c_globals); - fail_0: - DECREF(c->c_names); - fail_1: - DECREF(c->c_consts); - fail_2: - DECREF(c->c_code); - fail_3: - return 0; -} - -static void -com_free(c) - struct compiling *c; -{ - XDECREF(c->c_code); - XDECREF(c->c_consts); - XDECREF(c->c_names); - XDECREF(c->c_globals); - XDECREF(c->c_locals); - XDECREF(c->c_varnames); -} - -static void -com_done(c) - struct compiling *c; -{ - if (c->c_code != NULL) - resizestring(&c->c_code, c->c_nexti); -} - -static void -com_addbyte(c, byte) - struct compiling *c; - int byte; -{ - int len; - /*fprintf(stderr, "%3d: %3d\n", c->c_nexti, byte);*/ - if (byte < 0 || byte > 255) { - /* - fprintf(stderr, "XXX compiling bad byte: %d\n", byte); - fatal("com_addbyte: byte out of range"); - */ - err_setstr(SystemError, "com_addbyte: byte out of range"); - c->c_errors++; - } - if (c->c_code == NULL) - return; - len = getstringsize(c->c_code); - if (c->c_nexti >= len) { - if (resizestring(&c->c_code, len+1000) != 0) { - c->c_errors++; - return; - } - } - getstringvalue(c->c_code)[c->c_nexti++] = byte; -} - -static void -com_addint(c, x) - struct compiling *c; - int x; -{ - com_addbyte(c, x & 0xff); - com_addbyte(c, x >> 8); /* XXX x should be positive */ -} - -static void -com_addoparg(c, op, arg) - struct compiling *c; - int op; - int arg; -{ - com_addbyte(c, op); - com_addint(c, arg); -} - -static void -com_addfwref(c, op, p_anchor) - struct compiling *c; - int op; - int *p_anchor; -{ - /* Compile a forward reference for backpatching */ - int here; - int anchor; - com_addbyte(c, op); - here = c->c_nexti; - anchor = *p_anchor; - *p_anchor = here; - com_addint(c, anchor == 0 ? 0 : here - anchor); -} - -static void -com_backpatch(c, anchor) - struct compiling *c; - int anchor; /* Must be nonzero */ -{ - unsigned char *code = (unsigned char *) getstringvalue(c->c_code); - int target = c->c_nexti; - int dist; - int prev; - for (;;) { - /* Make the JUMP instruction at anchor point to target */ - prev = code[anchor] + (code[anchor+1] << 8); - dist = target - (anchor+2); - code[anchor] = dist & 0xff; - code[anchor+1] = dist >> 8; - if (!prev) - break; - anchor -= prev; - } -} - -/* Handle literals and names uniformly */ - -static int -com_add(c, list, v) - struct compiling *c; - object *list; - object *v; -{ - int n = getlistsize(list); - int i; - for (i = n; --i >= 0; ) { - object *w = getlistitem(list, i); - if (v->ob_type == w->ob_type && cmpobject(v, w) == 0) - return i; - } - if (addlistitem(list, v) != 0) - c->c_errors++; - return n; -} - -static int -com_addconst(c, v) - struct compiling *c; - object *v; -{ - return com_add(c, c->c_consts, v); -} - -static int -com_addname(c, v) - struct compiling *c; - object *v; -{ - return com_add(c, c->c_names, v); -} - -static void -com_addopnamestr(c, op, name) - struct compiling *c; - int op; - char *name; -{ - object *v; - int i; - if (name == NULL || (v = newstringobject(name)) == NULL) { - c->c_errors++; - i = 255; - } - else { - i = com_addname(c, v); - DECREF(v); - } - /* Hack to replace *_NAME opcodes by *_GLOBAL if necessary */ - switch (op) { - case LOAD_NAME: - case STORE_NAME: - case DELETE_NAME: - if (dictlookup(c->c_globals, name) != NULL) { - switch (op) { - case LOAD_NAME: op = LOAD_GLOBAL; break; - case STORE_NAME: op = STORE_GLOBAL; break; - case DELETE_NAME: op = DELETE_GLOBAL; break; - } - } - } - com_addoparg(c, op, i); -} - -static void -com_addopname(c, op, n) - struct compiling *c; - int op; - node *n; -{ - char *name; - char buffer[1000]; - /* XXX it is possible to write this code without the 1000 - chars on the total length of dotted names, I just can't be - bothered right now */ - if (TYPE(n) == STAR) - name = "*"; - else if (TYPE(n) == dotted_name) { - char *p = buffer; - int i; - name = buffer; - for (i = 0; i < NCH(n); i += 2) { - char *s = STR(CHILD(n, i)); - if (p + strlen(s) > buffer + (sizeof buffer) - 2) { - err_setstr(MemoryError, - "dotted_name too long"); - name = NULL; - break; - } - if (p != buffer) - *p++ = '.'; - strcpy(p, s); - p = strchr(p, '\0'); - } - } - else { - REQ(n, NAME); - name = STR(n); - } - com_addopnamestr(c, op, name); -} - -static object * -parsenumber(s) - char *s; -{ - extern long mystrtol PROTO((const char *, char **, int)); - extern unsigned long mystrtoul PROTO((const char *, char **, int)); - extern double atof PROTO((const char *)); - char *end; - long x; -#ifndef WITHOUT_COMPLEX - complex c; - int imflag; -#endif - - errno = 0; - end = s + strlen(s) - 1; -#ifndef WITHOUT_COMPLEX - imflag = *end == 'j' || *end == 'J'; -#endif - if (*end == 'l' || *end == 'L') - return long_scan(s, 0); - if (s[0] == '0') - x = (long) mystrtoul(s, &end, 0); - else - x = mystrtol(s, &end, 0); - if (*end == '\0') { - if (errno != 0) { - err_setstr(OverflowError, - "integer literal too large"); - return NULL; - } - return newintobject(x); - } - /* XXX Huge floats may silently fail */ -#ifndef WITHOUT_COMPLEX - if (imflag) { - c.real = 0.; - c.imag = atof(s); - return newcomplexobject(c); - } - else -#endif - return newfloatobject(atof(s)); -} - -static object * -parsestr(s) - char *s; -{ - object *v; - int len; - char *buf; - char *p; - char *end; - int c; - int quote = *s; - if (quote != '\'' && quote != '\"') { - err_badcall(); - return NULL; - } - s++; - len = strlen(s); - if (s[--len] != quote) { - err_badcall(); - return NULL; - } - if (len >= 4 && s[0] == quote && s[1] == quote) { - s += 2; - len -= 2; - if (s[--len] != quote || s[--len] != quote) { - err_badcall(); - return NULL; - } - } - if (strchr(s, '\\') == NULL) - return newsizedstringobject(s, len); - v = newsizedstringobject((char *)NULL, len); - p = buf = getstringvalue(v); - end = s + len; - while (s < end) { - if (*s != '\\') { - *p++ = *s++; - continue; - } - s++; - switch (*s++) { - /* XXX This assumes ASCII! */ - case '\n': break; - case '\\': *p++ = '\\'; break; - case '\'': *p++ = '\''; break; - case '\"': *p++ = '\"'; break; - case 'b': *p++ = '\b'; break; - case 'f': *p++ = '\014'; break; /* FF */ - case 't': *p++ = '\t'; break; - case 'n': *p++ = '\n'; break; - case 'r': *p++ = '\r'; break; - case 'v': *p++ = '\013'; break; /* VT */ - case 'a': *p++ = '\007'; break; /* BEL, not classic C */ - case '0': case '1': case '2': case '3': - case '4': case '5': case '6': case '7': - c = s[-1] - '0'; - if ('0' <= *s && *s <= '7') { - c = (c<<3) + *s++ - '0'; - if ('0' <= *s && *s <= '7') - c = (c<<3) + *s++ - '0'; - } - *p++ = c; - break; - case 'x': - if (isxdigit(Py_CHARMASK(*s))) { - sscanf(s, "%x", &c); - *p++ = c; - do { - s++; - } while (isxdigit(Py_CHARMASK(*s))); - break; - } - /* FALLTHROUGH */ - default: *p++ = '\\'; *p++ = s[-1]; break; - } - } - resizestring(&v, (int)(p - buf)); - return v; -} - -static object * -parsestrplus(n) - node *n; -{ - object *v; - int i; - REQ(CHILD(n, 0), STRING); - if ((v = parsestr(STR(CHILD(n, 0)))) != NULL) { - /* String literal concatenation */ - for (i = 1; i < NCH(n) && v != NULL; i++) { - joinstring_decref(&v, parsestr(STR(CHILD(n, i)))); - } - } - return v; -} - -static void -com_list_constructor(c, n) - struct compiling *c; - node *n; -{ - int len; - int i; - if (TYPE(n) != testlist) - REQ(n, exprlist); - /* exprlist: expr (',' expr)* [',']; likewise for testlist */ - len = (NCH(n) + 1) / 2; - for (i = 0; i < NCH(n); i += 2) - com_node(c, CHILD(n, i)); - com_addoparg(c, BUILD_LIST, len); -} - -static void -com_dictmaker(c, n) - struct compiling *c; - node *n; -{ - int i; - /* dictmaker: test ':' test (',' test ':' value)* [','] */ - for (i = 0; i+2 < NCH(n); i += 4) { - /* We must arrange things just right for STORE_SUBSCR. - It wants the stack to look like (value) (dict) (key) */ - com_addbyte(c, DUP_TOP); - com_node(c, CHILD(n, i+2)); /* value */ - com_addbyte(c, ROT_TWO); - com_node(c, CHILD(n, i)); /* key */ - com_addbyte(c, STORE_SUBSCR); - } -} - -static void -com_atom(c, n) - struct compiling *c; - node *n; -{ - node *ch; - object *v; - int i; - REQ(n, atom); - ch = CHILD(n, 0); - switch (TYPE(ch)) { - case LPAR: - if (TYPE(CHILD(n, 1)) == RPAR) - com_addoparg(c, BUILD_TUPLE, 0); - else - com_node(c, CHILD(n, 1)); - break; - case LSQB: - if (TYPE(CHILD(n, 1)) == RSQB) - com_addoparg(c, BUILD_LIST, 0); - else - com_list_constructor(c, CHILD(n, 1)); - break; - case LBRACE: /* '{' [dictmaker] '}' */ - com_addoparg(c, BUILD_MAP, 0); - if (TYPE(CHILD(n, 1)) != RBRACE) - com_dictmaker(c, CHILD(n, 1)); - break; - case BACKQUOTE: - com_node(c, CHILD(n, 1)); - com_addbyte(c, UNARY_CONVERT); - break; - case NUMBER: - if ((v = parsenumber(STR(ch))) == NULL) { - c->c_errors++; - i = 255; - } - else { - i = com_addconst(c, v); - DECREF(v); - } - com_addoparg(c, LOAD_CONST, i); - break; - case STRING: - v = parsestrplus(n); - if (v == NULL) { - c->c_errors++; - i = 255; - } - else { - i = com_addconst(c, v); - DECREF(v); - } - com_addoparg(c, LOAD_CONST, i); - break; - case NAME: - com_addopname(c, LOAD_NAME, ch); - break; - default: - fprintf(stderr, "node type %d\n", TYPE(ch)); - err_setstr(SystemError, "com_atom: unexpected node type"); - c->c_errors++; - } -} - -static void -com_slice(c, n, op) - struct compiling *c; - node *n; - int op; -{ - if (NCH(n) == 1) { - com_addbyte(c, op); - } - else if (NCH(n) == 2) { - if (TYPE(CHILD(n, 0)) != COLON) { - com_node(c, CHILD(n, 0)); - com_addbyte(c, op+1); - } - else { - com_node(c, CHILD(n, 1)); - com_addbyte(c, op+2); - } - } - else { - com_node(c, CHILD(n, 0)); - com_node(c, CHILD(n, 2)); - com_addbyte(c, op+3); - } -} - -static void -com_apply_subscript(c, n) - struct compiling *c; - node *n; -{ - REQ(n, subscript); - if (TYPE(CHILD(n, 0)) == COLON || (NCH(n) > 1 && TYPE(CHILD(n, 1)) == COLON)) { - /* It's a slice: [expr] ':' [expr] */ - com_slice(c, n, SLICE); - } - else { - /* It's a list of subscripts */ - if (NCH(n) == 1) - com_node(c, CHILD(n, 0)); - else { - int i; - int len = (NCH(n)+1)/2; - for (i = 0; i < NCH(n); i += 2) - com_node(c, CHILD(n, i)); - com_addoparg(c, BUILD_TUPLE, len); - } - com_addbyte(c, BINARY_SUBSCR); - } -} - -static int -com_argument(c, n, inkeywords) - struct compiling *c; - node *n; /* argument */ - int inkeywords; -{ - node *m; - REQ(n, argument); /* [test '='] test; really [ keyword '='] keyword */ - if (NCH(n) == 1) { - if (inkeywords) { - err_setstr(SyntaxError, - "non-keyword arg after keyword arg"); - c->c_errors++; - } - else { - com_node(c, CHILD(n, 0)); - } - return 0; - } - m = n; - do { - m = CHILD(m, 0); - } while (NCH(m) == 1); - if (TYPE(m) != NAME) { - err_setstr(SyntaxError, "keyword can't be an expression"); - c->c_errors++; - } - else { - object *v = newstringobject(STR(m)); - if (v == NULL) - c->c_errors++; - else { - com_addoparg(c, LOAD_CONST, com_addconst(c, v)); - DECREF(v); - } - } - com_node(c, CHILD(n, 2)); - return 1; -} - -static void -com_call_function(c, n) - struct compiling *c; - node *n; /* EITHER arglist OR ')' */ -{ - if (TYPE(n) == RPAR) { - com_addoparg(c, CALL_FUNCTION, 0); - } - else { - int inkeywords, i, na, nk; - REQ(n, arglist); - inkeywords = 0; - na = 0; - nk = 0; - for (i = 0; i < NCH(n); i += 2) { - inkeywords = com_argument(c, CHILD(n, i), inkeywords); - if (!inkeywords) - na++; - else - nk++; - } - if (na > 255 || nk > 255) { - err_setstr(SyntaxError, "more than 255 arguments"); - c->c_errors++; - } - com_addoparg(c, CALL_FUNCTION, na | (nk << 8)); - } -} - -static void -com_select_member(c, n) - struct compiling *c; - node *n; -{ - com_addopname(c, LOAD_ATTR, n); -} - -static void -com_apply_trailer(c, n) - struct compiling *c; - node *n; -{ - REQ(n, trailer); - switch (TYPE(CHILD(n, 0))) { - case LPAR: - com_call_function(c, CHILD(n, 1)); - break; - case DOT: - com_select_member(c, CHILD(n, 1)); - break; - case LSQB: - com_apply_subscript(c, CHILD(n, 1)); - break; - default: - err_setstr(SystemError, - "com_apply_trailer: unknown trailer type"); - c->c_errors++; - } -} - -static void -com_power(c, n) - struct compiling *c; - node *n; -{ - int i; - REQ(n, power); - com_atom(c, CHILD(n, 0)); - for (i = 1; i < NCH(n); i++) { - if (TYPE(CHILD(n, i)) == DOUBLESTAR) { - com_factor(c, CHILD(n, i+1)); - com_addbyte(c, BINARY_POWER); - break; - } - else - com_apply_trailer(c, CHILD(n, i)); - } -} - -static void -com_factor(c, n) - struct compiling *c; - node *n; -{ - REQ(n, factor); - if (TYPE(CHILD(n, 0)) == PLUS) { - com_factor(c, CHILD(n, 1)); - com_addbyte(c, UNARY_POSITIVE); - } - else if (TYPE(CHILD(n, 0)) == MINUS) { - com_factor(c, CHILD(n, 1)); - com_addbyte(c, UNARY_NEGATIVE); - } - else if (TYPE(CHILD(n, 0)) == TILDE) { - com_factor(c, CHILD(n, 1)); - com_addbyte(c, UNARY_INVERT); - } - else { - com_power(c, CHILD(n, 0)); - } -} - -static void -com_term(c, n) - struct compiling *c; - node *n; -{ - int i; - int op; - REQ(n, term); - com_factor(c, CHILD(n, 0)); - for (i = 2; i < NCH(n); i += 2) { - com_factor(c, CHILD(n, i)); - switch (TYPE(CHILD(n, i-1))) { - case STAR: - op = BINARY_MULTIPLY; - break; - case SLASH: - op = BINARY_DIVIDE; - break; - case PERCENT: - op = BINARY_MODULO; - break; - default: - err_setstr(SystemError, - "com_term: operator not *, / or %"); - c->c_errors++; - op = 255; - } - com_addbyte(c, op); - } -} - -static void -com_arith_expr(c, n) - struct compiling *c; - node *n; -{ - int i; - int op; - REQ(n, arith_expr); - com_term(c, CHILD(n, 0)); - for (i = 2; i < NCH(n); i += 2) { - com_term(c, CHILD(n, i)); - switch (TYPE(CHILD(n, i-1))) { - case PLUS: - op = BINARY_ADD; - break; - case MINUS: - op = BINARY_SUBTRACT; - break; - default: - err_setstr(SystemError, - "com_arith_expr: operator not + or -"); - c->c_errors++; - op = 255; - } - com_addbyte(c, op); - } -} - -static void -com_shift_expr(c, n) - struct compiling *c; - node *n; -{ - int i; - int op; - REQ(n, shift_expr); - com_arith_expr(c, CHILD(n, 0)); - for (i = 2; i < NCH(n); i += 2) { - com_arith_expr(c, CHILD(n, i)); - switch (TYPE(CHILD(n, i-1))) { - case LEFTSHIFT: - op = BINARY_LSHIFT; - break; - case RIGHTSHIFT: - op = BINARY_RSHIFT; - break; - default: - err_setstr(SystemError, - "com_shift_expr: operator not << or >>"); - c->c_errors++; - op = 255; - } - com_addbyte(c, op); - } -} - -static void -com_and_expr(c, n) - struct compiling *c; - node *n; -{ - int i; - int op; - REQ(n, and_expr); - com_shift_expr(c, CHILD(n, 0)); - for (i = 2; i < NCH(n); i += 2) { - com_shift_expr(c, CHILD(n, i)); - if (TYPE(CHILD(n, i-1)) == AMPER) { - op = BINARY_AND; - } - else { - err_setstr(SystemError, - "com_and_expr: operator not &"); - c->c_errors++; - op = 255; - } - com_addbyte(c, op); - } -} - -static void -com_xor_expr(c, n) - struct compiling *c; - node *n; -{ - int i; - int op; - REQ(n, xor_expr); - com_and_expr(c, CHILD(n, 0)); - for (i = 2; i < NCH(n); i += 2) { - com_and_expr(c, CHILD(n, i)); - if (TYPE(CHILD(n, i-1)) == CIRCUMFLEX) { - op = BINARY_XOR; - } - else { - err_setstr(SystemError, - "com_xor_expr: operator not ^"); - c->c_errors++; - op = 255; - } - com_addbyte(c, op); - } -} - -static void -com_expr(c, n) - struct compiling *c; - node *n; -{ - int i; - int op; - REQ(n, expr); - com_xor_expr(c, CHILD(n, 0)); - for (i = 2; i < NCH(n); i += 2) { - com_xor_expr(c, CHILD(n, i)); - if (TYPE(CHILD(n, i-1)) == VBAR) { - op = BINARY_OR; - } - else { - err_setstr(SystemError, - "com_expr: expr operator not |"); - c->c_errors++; - op = 255; - } - com_addbyte(c, op); - } -} - -static enum cmp_op -cmp_type(n) - node *n; -{ - REQ(n, comp_op); - /* comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '==' - | 'in' | 'not' 'in' | 'is' | 'is' not' */ - if (NCH(n) == 1) { - n = CHILD(n, 0); - switch (TYPE(n)) { - case LESS: return LT; - case GREATER: return GT; - case EQEQUAL: /* == */ - case EQUAL: return EQ; - case LESSEQUAL: return LE; - case GREATEREQUAL: return GE; - case NOTEQUAL: return NE; /* <> or != */ - case NAME: if (strcmp(STR(n), "in") == 0) return IN; - if (strcmp(STR(n), "is") == 0) return IS; - } - } - else if (NCH(n) == 2) { - switch (TYPE(CHILD(n, 0))) { - case NAME: if (strcmp(STR(CHILD(n, 1)), "in") == 0) - return NOT_IN; - if (strcmp(STR(CHILD(n, 0)), "is") == 0) - return IS_NOT; - } - } - return BAD; -} - -static void -com_comparison(c, n) - struct compiling *c; - node *n; -{ - int i; - enum cmp_op op; - int anchor; - REQ(n, comparison); /* comparison: expr (comp_op expr)* */ - com_expr(c, CHILD(n, 0)); - if (NCH(n) == 1) - return; - - /**************************************************************** - The following code is generated for all but the last - comparison in a chain: - - label: on stack: opcode: jump to: - - a <code to load b> - a, b DUP_TOP - a, b, b ROT_THREE - b, a, b COMPARE_OP - b, 0-or-1 JUMP_IF_FALSE L1 - b, 1 POP_TOP - b - - We are now ready to repeat this sequence for the next - comparison in the chain. - - For the last we generate: - - b <code to load c> - b, c COMPARE_OP - 0-or-1 - - If there were any jumps to L1 (i.e., there was more than one - comparison), we generate: - - 0-or-1 JUMP_FORWARD L2 - L1: b, 0 ROT_TWO - 0, b POP_TOP - 0 - L2: - ****************************************************************/ - - anchor = 0; - - for (i = 2; i < NCH(n); i += 2) { - com_expr(c, CHILD(n, i)); - if (i+2 < NCH(n)) { - com_addbyte(c, DUP_TOP); - com_addbyte(c, ROT_THREE); - } - op = cmp_type(CHILD(n, i-1)); - if (op == BAD) { - err_setstr(SystemError, - "com_comparison: unknown comparison op"); - c->c_errors++; - } - com_addoparg(c, COMPARE_OP, op); - if (i+2 < NCH(n)) { - com_addfwref(c, JUMP_IF_FALSE, &anchor); - com_addbyte(c, POP_TOP); - } - } - - if (anchor) { - int anchor2 = 0; - com_addfwref(c, JUMP_FORWARD, &anchor2); - com_backpatch(c, anchor); - com_addbyte(c, ROT_TWO); - com_addbyte(c, POP_TOP); - com_backpatch(c, anchor2); - } -} - -static void -com_not_test(c, n) - struct compiling *c; - node *n; -{ - REQ(n, not_test); /* 'not' not_test | comparison */ - if (NCH(n) == 1) { - com_comparison(c, CHILD(n, 0)); - } - else { - com_not_test(c, CHILD(n, 1)); - com_addbyte(c, UNARY_NOT); - } -} - -static void -com_and_test(c, n) - struct compiling *c; - node *n; -{ - int i; - int anchor; - REQ(n, and_test); /* not_test ('and' not_test)* */ - anchor = 0; - i = 0; - for (;;) { - com_not_test(c, CHILD(n, i)); - if ((i += 2) >= NCH(n)) - break; - com_addfwref(c, JUMP_IF_FALSE, &anchor); - com_addbyte(c, POP_TOP); - } - if (anchor) - com_backpatch(c, anchor); -} - -static void -com_test(c, n) - struct compiling *c; - node *n; -{ - REQ(n, test); /* and_test ('and' and_test)* | lambdef */ - if (NCH(n) == 1 && TYPE(CHILD(n, 0)) == lambdef) { - object *v; - int i; - int ndefs = com_argdefs(c, CHILD(n, 0)); - v = (object *) compile(CHILD(n, 0), c->c_filename); - if (v == NULL) { - c->c_errors++; - i = 255; - } - else { - i = com_addconst(c, v); - DECREF(v); - } - com_addoparg(c, LOAD_CONST, i); - com_addoparg(c, MAKE_FUNCTION, ndefs); - } - else { - int anchor = 0; - int i = 0; - for (;;) { - com_and_test(c, CHILD(n, i)); - if ((i += 2) >= NCH(n)) - break; - com_addfwref(c, JUMP_IF_TRUE, &anchor); - com_addbyte(c, POP_TOP); - } - if (anchor) - com_backpatch(c, anchor); - } -} - -static void -com_list(c, n, toplevel) - struct compiling *c; - node *n; - int toplevel; /* If nonzero, *always* build a tuple */ -{ - /* exprlist: expr (',' expr)* [',']; likewise for testlist */ - if (NCH(n) == 1 && !toplevel) { - com_node(c, CHILD(n, 0)); - } - else { - int i; - int len; - len = (NCH(n) + 1) / 2; - for (i = 0; i < NCH(n); i += 2) - com_node(c, CHILD(n, i)); - com_addoparg(c, BUILD_TUPLE, len); - } -} - - -/* Begin of assignment compilation */ - -static void com_assign_name PROTO((struct compiling *, node *, int)); -static void com_assign PROTO((struct compiling *, node *, int)); - -static void -com_assign_attr(c, n, assigning) - struct compiling *c; - node *n; - int assigning; -{ - com_addopname(c, assigning ? STORE_ATTR : DELETE_ATTR, n); -} - -static void -com_assign_slice(c, n, assigning) - struct compiling *c; - node *n; - int assigning; -{ - com_slice(c, n, assigning ? STORE_SLICE : DELETE_SLICE); -} - -static void -com_assign_subscript(c, n, assigning) - struct compiling *c; - node *n; - int assigning; -{ - if (NCH(n) == 1) - com_node(c, CHILD(n, 0)); - else { - int i; - int len = (NCH(n)+1)/2; - for (i = 0; i < NCH(n); i += 2) - com_node(c, CHILD(n, i)); - com_addoparg(c, BUILD_TUPLE, len); - } - com_addbyte(c, assigning ? STORE_SUBSCR : DELETE_SUBSCR); -} - -static void -com_assign_trailer(c, n, assigning) - struct compiling *c; - node *n; - int assigning; -{ - REQ(n, trailer); - switch (TYPE(CHILD(n, 0))) { - case LPAR: /* '(' [exprlist] ')' */ - err_setstr(SyntaxError, "can't assign to function call"); - c->c_errors++; - break; - case DOT: /* '.' NAME */ - com_assign_attr(c, CHILD(n, 1), assigning); - break; - case LSQB: /* '[' subscript ']' */ - n = CHILD(n, 1); - REQ(n, subscript); /* subscript: expr (',' expr)* | [expr] ':' [expr] */ - if (TYPE(CHILD(n, 0)) == COLON || (NCH(n) > 1 && TYPE(CHILD(n, 1)) == COLON)) - com_assign_slice(c, n, assigning); - else - com_assign_subscript(c, n, assigning); - break; - default: - err_setstr(SystemError, "unknown trailer type"); - c->c_errors++; - } -} - -static void -com_assign_tuple(c, n, assigning) - struct compiling *c; - node *n; - int assigning; -{ - int i; - if (TYPE(n) != testlist) - REQ(n, exprlist); - if (assigning) - com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2); - for (i = 0; i < NCH(n); i += 2) - com_assign(c, CHILD(n, i), assigning); -} - -static void -com_assign_list(c, n, assigning) - struct compiling *c; - node *n; - int assigning; -{ - int i; - if (assigning) - com_addoparg(c, UNPACK_LIST, (NCH(n)+1)/2); - for (i = 0; i < NCH(n); i += 2) - com_assign(c, CHILD(n, i), assigning); -} - -static void -com_assign_name(c, n, assigning) - struct compiling *c; - node *n; - int assigning; -{ - REQ(n, NAME); - com_addopname(c, assigning ? STORE_NAME : DELETE_NAME, n); -} - -static void -com_assign(c, n, assigning) - struct compiling *c; - node *n; - int assigning; -{ - /* Loop to avoid trivial recursion */ - for (;;) { - switch (TYPE(n)) { - - case exprlist: - case testlist: - if (NCH(n) > 1) { - com_assign_tuple(c, n, assigning); - return; - } - n = CHILD(n, 0); - break; - - case test: - case and_test: - case not_test: - case comparison: - case expr: - case xor_expr: - case and_expr: - case shift_expr: - case arith_expr: - case term: - case factor: - if (NCH(n) > 1) { - err_setstr(SyntaxError, - "can't assign to operator"); - c->c_errors++; - return; - } - n = CHILD(n, 0); - break; - - case power: /* atom trailer* ('**' power)* */ -/* ('+'|'-'|'~') factor | atom trailer* */ - if (TYPE(CHILD(n, 0)) != atom) { - err_setstr(SyntaxError, - "can't assign to operator"); - c->c_errors++; - return; - } - if (NCH(n) > 1) { /* trailer or exponent present */ - int i; - com_node(c, CHILD(n, 0)); - for (i = 1; i+1 < NCH(n); i++) { - if (TYPE(CHILD(n, i)) == DOUBLESTAR) { - err_setstr(SyntaxError, - "can't assign to operator"); - c->c_errors++; - return; - } - com_apply_trailer(c, CHILD(n, i)); - } /* NB i is still alive */ - com_assign_trailer(c, - CHILD(n, i), assigning); - return; - } - n = CHILD(n, 0); - break; - - case atom: - switch (TYPE(CHILD(n, 0))) { - case LPAR: - n = CHILD(n, 1); - if (TYPE(n) == RPAR) { - /* XXX Should allow () = () ??? */ - err_setstr(SyntaxError, - "can't assign to ()"); - c->c_errors++; - return; - } - break; - case LSQB: - n = CHILD(n, 1); - if (TYPE(n) == RSQB) { - err_setstr(SyntaxError, - "can't assign to []"); - c->c_errors++; - return; - } - com_assign_list(c, n, assigning); - return; - case NAME: - com_assign_name(c, CHILD(n, 0), assigning); - return; - default: - err_setstr(SyntaxError, - "can't assign to literal"); - c->c_errors++; - return; - } - break; - - default: - fprintf(stderr, "node type %d\n", TYPE(n)); - err_setstr(SystemError, "com_assign: bad node"); - c->c_errors++; - return; - - } - } -} - -static void -com_expr_stmt(c, n) - struct compiling *c; - node *n; -{ - REQ(n, expr_stmt); /* testlist ('=' testlist)* */ - com_node(c, CHILD(n, NCH(n)-1)); - if (NCH(n) == 1) { - if (c->c_interactive) - com_addbyte(c, PRINT_EXPR); - else - com_addbyte(c, POP_TOP); - } - else { - int i; - for (i = 0; i < NCH(n)-2; i+=2) { - if (i+2 < NCH(n)-2) - com_addbyte(c, DUP_TOP); - com_assign(c, CHILD(n, i), 1/*assign*/); - } - } -} - -static void -com_print_stmt(c, n) - struct compiling *c; - node *n; -{ - int i; - REQ(n, print_stmt); /* 'print' (test ',')* [test] */ - for (i = 1; i < NCH(n); i += 2) { - com_node(c, CHILD(n, i)); - com_addbyte(c, PRINT_ITEM); - } - if (TYPE(CHILD(n, NCH(n)-1)) != COMMA) - com_addbyte(c, PRINT_NEWLINE); - /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */ -} - -static void -com_return_stmt(c, n) - struct compiling *c; - node *n; -{ - REQ(n, return_stmt); /* 'return' [testlist] */ - if (!c->c_infunction) { - err_setstr(SyntaxError, "'return' outside function"); - c->c_errors++; - } - if (NCH(n) < 2) - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - else - com_node(c, CHILD(n, 1)); - com_addbyte(c, RETURN_VALUE); -} - -static void -com_raise_stmt(c, n) - struct compiling *c; - node *n; -{ - REQ(n, raise_stmt); /* 'raise' test [',' test [',' test]] */ - com_node(c, CHILD(n, 1)); - if (NCH(n) > 3) { - com_node(c, CHILD(n, 3)); - if (NCH(n) > 5) - com_node(c, CHILD(n, 5)); - } - com_addoparg(c, RAISE_VARARGS, NCH(n)/2); -} - -static void -com_import_stmt(c, n) - struct compiling *c; - node *n; -{ - int i; - REQ(n, import_stmt); - /* 'import' dotted_name (',' dotted_name)* | - 'from' dotted_name 'import' ('*' | NAME (',' NAME)*) */ - if (STR(CHILD(n, 0))[0] == 'f') { - /* 'from' dotted_name 'import' ... */ - REQ(CHILD(n, 1), dotted_name); - com_addopname(c, IMPORT_NAME, CHILD(n, 1)); - for (i = 3; i < NCH(n); i += 2) - com_addopname(c, IMPORT_FROM, CHILD(n, i)); - com_addbyte(c, POP_TOP); - } - else { - /* 'import' ... */ - for (i = 1; i < NCH(n); i += 2) { - REQ(CHILD(n, i), dotted_name); - com_addopname(c, IMPORT_NAME, CHILD(n, i)); - com_addopname(c, STORE_NAME, CHILD(CHILD(n, i), 0)); - } - } -} - -static void -com_global_stmt(c, n) - struct compiling *c; - node *n; -{ - int i; - REQ(n, global_stmt); - /* 'global' NAME (',' NAME)* */ - for (i = 1; i < NCH(n); i += 2) { - char *s = STR(CHILD(n, i)); - if (dictlookup(c->c_locals, s) != NULL) { - err_setstr(SyntaxError, "name is local and global"); - c->c_errors++; - } - else if (dictinsert(c->c_globals, s, None) != 0) - c->c_errors++; - } -} - -static int -com_newlocal_o(c, nameval) - struct compiling *c; - object *nameval; -{ - int i; - object *ival; - if (getlistsize(c->c_varnames) != c->c_nlocals) { - /* This is usually caused by an error on a previous call */ - if (c->c_errors == 0) { - err_setstr(SystemError, "mixed up var name/index"); - c->c_errors++; - } - return 0; - } - ival = newintobject(i = c->c_nlocals++); - if (ival == NULL) - c->c_errors++; - else if (mappinginsert(c->c_locals, nameval, ival) != 0) - c->c_errors++; - else if (addlistitem(c->c_varnames, nameval) != 0) - c->c_errors++; - XDECREF(ival); - return i; -} - -static int -com_addlocal_o(c, nameval) - struct compiling *c; - object *nameval; -{ - object *ival = mappinglookup(c->c_locals, nameval); - if (ival != NULL) - return getintvalue(ival); - return com_newlocal_o(c, nameval); -} - -static int -com_newlocal(c, name) - struct compiling *c; - char *name; -{ - object *nameval = newstringobject(name); - int i; - if (nameval == NULL) { - c->c_errors++; - return 0; - } - i = com_newlocal_o(c, nameval); - DECREF(nameval); - return i; -} - -#define strequ(a, b) (strcmp((a), (b)) == 0) - -static void -com_access_stmt(c, n) - struct compiling *c; - node *n; -{ -#if 0 - int i, j, k, mode, imode; - object *vmode; - REQ(n, access_stmt); - /* 'access' NAME (',' NAME)* ':' accesstype (',' accesstype)* - accesstype: NAME+ */ - - /* Find where the colon is */ - i = 1; - while (TYPE(CHILD(n,i-1)) != COLON) - i += 1; - - /* Calculate the mode mask */ - mode = 0; - for (j = i; j < NCH(n); j += 2) { - int r = 0, w = 0, p = 0; - for (k = 0; k < NCH(CHILD(n,j)); k++) { - if (strequ(STR(CHILD(CHILD(n,j),k)), "public")) - p = 0; - else if (strequ(STR(CHILD(CHILD(n,j),k)), "protected")) - p = 1; - else if (strequ(STR(CHILD(CHILD(n,j),k)), "private")) - p = 2; - else if (strequ(STR(CHILD(CHILD(n,j),k)), "read")) - r = 1; - else if (strequ(STR(CHILD(CHILD(n,j),k)), "write")) - w = 1; - else /* XXX should make this an exception */ - fprintf(stderr, "bad access type %s\n", - STR(CHILD(CHILD(n,j),k))); - } - if (r == 0 && w == 0) - r = w = 1; - if (p == 0) { - if (r == 1) mode |= AC_R_PUBLIC; - if (w == 1) mode |= AC_W_PUBLIC; - } else if (p == 1) { - if (r == 1) mode |= AC_R_PROTECTED; - if (w == 1) mode |= AC_W_PROTECTED; - } else { - if (r == 1) mode |= AC_R_PRIVATE; - if (w == 1) mode |= AC_W_PRIVATE; - } - } - vmode = newintobject((long)mode); - imode = com_addconst(c, vmode); - XDECREF(vmode); - for (i = 1; TYPE(CHILD(n,i-1)) != COLON; i+=2) { - com_addoparg(c, LOAD_CONST, imode); - com_addopname(c, ACCESS_MODE, CHILD(n, i)); - } -#endif -} - -static void -com_exec_stmt(c, n) - struct compiling *c; - node *n; -{ - REQ(n, exec_stmt); - /* exec_stmt: 'exec' expr ['in' expr [',' expr]] */ - com_node(c, CHILD(n, 1)); - if (NCH(n) >= 4) - com_node(c, CHILD(n, 3)); - else - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - if (NCH(n) >= 6) - com_node(c, CHILD(n, 5)); - else - com_addbyte(c, DUP_TOP); - com_addbyte(c, EXEC_STMT); -} - -static void -com_if_stmt(c, n) - struct compiling *c; - node *n; -{ - int i; - int anchor = 0; - REQ(n, if_stmt); - /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */ - for (i = 0; i+3 < NCH(n); i+=4) { - int a = 0; - node *ch = CHILD(n, i+1); - if (i > 0) - com_addoparg(c, SET_LINENO, ch->n_lineno); - com_node(c, CHILD(n, i+1)); - com_addfwref(c, JUMP_IF_FALSE, &a); - com_addbyte(c, POP_TOP); - com_node(c, CHILD(n, i+3)); - com_addfwref(c, JUMP_FORWARD, &anchor); - com_backpatch(c, a); - com_addbyte(c, POP_TOP); - } - if (i+2 < NCH(n)) - com_node(c, CHILD(n, i+2)); - com_backpatch(c, anchor); -} - -static void -com_while_stmt(c, n) - struct compiling *c; - node *n; -{ - int break_anchor = 0; - int anchor = 0; - int save_begin = c->c_begin; - REQ(n, while_stmt); /* 'while' test ':' suite ['else' ':' suite] */ - com_addfwref(c, SETUP_LOOP, &break_anchor); - block_push(c, SETUP_LOOP); - c->c_begin = c->c_nexti; - com_addoparg(c, SET_LINENO, n->n_lineno); - com_node(c, CHILD(n, 1)); - com_addfwref(c, JUMP_IF_FALSE, &anchor); - com_addbyte(c, POP_TOP); - c->c_loops++; - com_node(c, CHILD(n, 3)); - c->c_loops--; - com_addoparg(c, JUMP_ABSOLUTE, c->c_begin); - c->c_begin = save_begin; - com_backpatch(c, anchor); - com_addbyte(c, POP_TOP); - com_addbyte(c, POP_BLOCK); - block_pop(c, SETUP_LOOP); - if (NCH(n) > 4) - com_node(c, CHILD(n, 6)); - com_backpatch(c, break_anchor); -} - -static void -com_for_stmt(c, n) - struct compiling *c; - node *n; -{ - object *v; - int break_anchor = 0; - int anchor = 0; - int save_begin = c->c_begin; - REQ(n, for_stmt); - /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */ - com_addfwref(c, SETUP_LOOP, &break_anchor); - block_push(c, SETUP_LOOP); - com_node(c, CHILD(n, 3)); - v = newintobject(0L); - if (v == NULL) - c->c_errors++; - com_addoparg(c, LOAD_CONST, com_addconst(c, v)); - XDECREF(v); - c->c_begin = c->c_nexti; - com_addoparg(c, SET_LINENO, n->n_lineno); - com_addfwref(c, FOR_LOOP, &anchor); - com_assign(c, CHILD(n, 1), 1/*assigning*/); - c->c_loops++; - com_node(c, CHILD(n, 5)); - c->c_loops--; - com_addoparg(c, JUMP_ABSOLUTE, c->c_begin); - c->c_begin = save_begin; - com_backpatch(c, anchor); - com_addbyte(c, POP_BLOCK); - block_pop(c, SETUP_LOOP); - if (NCH(n) > 8) - com_node(c, CHILD(n, 8)); - com_backpatch(c, break_anchor); -} - -/* Code generated for "try: S finally: Sf" is as follows: - - SETUP_FINALLY L - <code for S> - POP_BLOCK - LOAD_CONST <nil> - L: <code for Sf> - END_FINALLY - - The special instructions use the block stack. Each block - stack entry contains the instruction that created it (here - SETUP_FINALLY), the level of the value stack at the time the - block stack entry was created, and a label (here L). - - SETUP_FINALLY: - Pushes the current value stack level and the label - onto the block stack. - POP_BLOCK: - Pops en entry from the block stack, and pops the value - stack until its level is the same as indicated on the - block stack. (The label is ignored.) - END_FINALLY: - Pops a variable number of entries from the *value* stack - and re-raises the exception they specify. The number of - entries popped depends on the (pseudo) exception type. - - The block stack is unwound when an exception is raised: - when a SETUP_FINALLY entry is found, the exception is pushed - onto the value stack (and the exception condition is cleared), - and the interpreter jumps to the label gotten from the block - stack. - - Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...": - (The contents of the value stack is shown in [], with the top - at the right; 'tb' is trace-back info, 'val' the exception's - associated value, and 'exc' the exception.) - - Value stack Label Instruction Argument - [] SETUP_EXCEPT L1 - [] <code for S> - [] POP_BLOCK - [] JUMP_FORWARD L0 - - [tb, val, exc] L1: DUP ) - [tb, val, exc, exc] <evaluate E1> ) - [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 - [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 ) - [tb, val, exc, 1] POP ) - [tb, val, exc] POP - [tb, val] <assign to V1> (or POP if no V1) - [tb] POP - [] <code for S1> - JUMP_FORWARD L0 - - [tb, val, exc, 0] L2: POP - [tb, val, exc] DUP - .............................etc....................... - - [tb, val, exc, 0] Ln+1: POP - [tb, val, exc] END_FINALLY # re-raise exception - - [] L0: <next statement> - - Of course, parts are not generated if Vi or Ei is not present. -*/ - -static void -com_try_except(c, n) - struct compiling *c; - node *n; -{ - int except_anchor = 0; - int end_anchor = 0; - int else_anchor = 0; - int i; - node *ch; - - com_addfwref(c, SETUP_EXCEPT, &except_anchor); - block_push(c, SETUP_EXCEPT); - com_node(c, CHILD(n, 2)); - com_addbyte(c, POP_BLOCK); - block_pop(c, SETUP_EXCEPT); - com_addfwref(c, JUMP_FORWARD, &else_anchor); - com_backpatch(c, except_anchor); - for (i = 3; - i < NCH(n) && TYPE(ch = CHILD(n, i)) == except_clause; - i += 3) { - /* except_clause: 'except' [expr [',' expr]] */ - if (except_anchor == 0) { - err_setstr(SyntaxError, - "default 'except:' must be last"); - c->c_errors++; - break; - } - except_anchor = 0; - com_addoparg(c, SET_LINENO, ch->n_lineno); - if (NCH(ch) > 1) { - com_addbyte(c, DUP_TOP); - com_node(c, CHILD(ch, 1)); - com_addoparg(c, COMPARE_OP, EXC_MATCH); - com_addfwref(c, JUMP_IF_FALSE, &except_anchor); - com_addbyte(c, POP_TOP); - } - com_addbyte(c, POP_TOP); - if (NCH(ch) > 3) - com_assign(c, CHILD(ch, 3), 1/*assigning*/); - else - com_addbyte(c, POP_TOP); - com_addbyte(c, POP_TOP); - com_node(c, CHILD(n, i+2)); - com_addfwref(c, JUMP_FORWARD, &end_anchor); - if (except_anchor) { - com_backpatch(c, except_anchor); - com_addbyte(c, POP_TOP); - } - } - com_addbyte(c, END_FINALLY); - com_backpatch(c, else_anchor); - if (i < NCH(n)) - com_node(c, CHILD(n, i+2)); - com_backpatch(c, end_anchor); -} - -static void -com_try_finally(c, n) - struct compiling *c; - node *n; -{ - int finally_anchor = 0; - node *ch; - - com_addfwref(c, SETUP_FINALLY, &finally_anchor); - block_push(c, SETUP_FINALLY); - com_node(c, CHILD(n, 2)); - com_addbyte(c, POP_BLOCK); - block_pop(c, SETUP_FINALLY); - block_push(c, END_FINALLY); - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - com_backpatch(c, finally_anchor); - ch = CHILD(n, NCH(n)-1); - com_addoparg(c, SET_LINENO, ch->n_lineno); - com_node(c, ch); - com_addbyte(c, END_FINALLY); - block_pop(c, END_FINALLY); -} - -static void -com_try_stmt(c, n) - struct compiling *c; - node *n; -{ - REQ(n, try_stmt); - /* 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] - | 'try' ':' suite 'finally' ':' suite */ - if (TYPE(CHILD(n, 3)) != except_clause) - com_try_finally(c, n); - else - com_try_except(c, n); -} - -static object * -get_docstring(n) - node *n; -{ - int i; - - switch (TYPE(n)) { - - case suite: - if (NCH(n) == 1) - return get_docstring(CHILD(n, 0)); - else { - for (i = 0; i < NCH(n); i++) { - node *ch = CHILD(n, i); - if (TYPE(ch) == stmt) - return get_docstring(ch); - } - } - break; - - case file_input: - for (i = 0; i < NCH(n); i++) { - node *ch = CHILD(n, i); - if (TYPE(ch) == stmt) - return get_docstring(ch); - } - break; - - case stmt: - case simple_stmt: - case small_stmt: - return get_docstring(CHILD(n, 0)); - - case expr_stmt: - case testlist: - case test: - case and_test: - case not_test: - case comparison: - case expr: - case xor_expr: - case and_expr: - case shift_expr: - case arith_expr: - case term: - case factor: - case power: - if (NCH(n) == 1) - return get_docstring(CHILD(n, 0)); - break; - - case atom: - if (TYPE(CHILD(n, 0)) == STRING) - return parsestrplus(n); - break; - - } - return NULL; -} - -static void -com_suite(c, n) - struct compiling *c; - node *n; -{ - REQ(n, suite); - /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */ - if (NCH(n) == 1) { - com_node(c, CHILD(n, 0)); - } - else { - int i; - for (i = 0; i < NCH(n); i++) { - node *ch = CHILD(n, i); - if (TYPE(ch) == stmt) - com_node(c, ch); - } - } -} - -/* ARGSUSED */ -static void -com_continue_stmt(c, n) - struct compiling *c; - node *n; /* Not used, but passed for consistency */ -{ - int i = c->c_nblocks; - if (i-- > 0 && c->c_block[i] == SETUP_LOOP) { - com_addoparg(c, JUMP_ABSOLUTE, c->c_begin); - } - else { - err_setstr(SyntaxError, "'continue' not properly in loop"); - c->c_errors++; - } - /* XXX Could allow it inside a 'finally' clause - XXX if we could pop the exception still on the stack */ -} - -static int -com_argdefs(c, n) - struct compiling *c; - node *n; -{ - int i, nch, nargs, ndefs; - if (TYPE(n) == lambdef) { - /* lambdef: 'lambda' [varargslist] ':' test */ - n = CHILD(n, 1); - } - else { - REQ(n, funcdef); /* funcdef: 'def' NAME parameters ... */ - n = CHILD(n, 2); - REQ(n, parameters); /* parameters: '(' [varargslist] ')' */ - n = CHILD(n, 1); - } - if (TYPE(n) != varargslist) - return 0; - /* varargslist: - (fpdef ['=' test] ',')* '*' ....... | - fpdef ['=' test] (',' fpdef ['=' test])* [','] */ - nch = NCH(n); - nargs = 0; - ndefs = 0; - for (i = 0; i < nch; i++) { - int t; - if (TYPE(CHILD(n, i)) == STAR || TYPE(CHILD(n, i)) == DOUBLESTAR) - break; - nargs++; - i++; - if (i >= nch) - t = RPAR; /* Anything except EQUAL or COMMA */ - else - t = TYPE(CHILD(n, i)); - if (t == EQUAL) { - i++; - ndefs++; - com_node(c, CHILD(n, i)); - i++; - if (i >= nch) - break; - t = TYPE(CHILD(n, i)); - } - else { - /* Treat "(a=1, b)" as "(a=1, b=None)" */ - if (ndefs) { - com_addoparg(c, LOAD_CONST, - com_addconst(c, None)); - ndefs++; - } - } - if (t != COMMA) - break; - } - return ndefs; -} - -static void -com_funcdef(c, n) - struct compiling *c; - node *n; -{ - object *v; - REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */ - v = (object *)compile(n, c->c_filename); - if (v == NULL) - c->c_errors++; - else { - int i = com_addconst(c, v); - int ndefs = com_argdefs(c, n); - com_addoparg(c, LOAD_CONST, i); - com_addoparg(c, MAKE_FUNCTION, ndefs); - com_addopname(c, STORE_NAME, CHILD(n, 1)); - DECREF(v); - } -} - -static void -com_bases(c, n) - struct compiling *c; - node *n; -{ - int i; - REQ(n, testlist); - /* testlist: test (',' test)* [','] */ - for (i = 0; i < NCH(n); i += 2) - com_node(c, CHILD(n, i)); - com_addoparg(c, BUILD_TUPLE, (NCH(n)+1) / 2); -} - -static void -com_classdef(c, n) - struct compiling *c; - node *n; -{ - int i; - object *v; - REQ(n, classdef); - /* classdef: class NAME ['(' testlist ')'] ':' suite */ - if ((v = newstringobject(STR(CHILD(n, 1)))) == NULL) { - c->c_errors++; - return; - } - /* Push the class name on the stack */ - i = com_addconst(c, v); - com_addoparg(c, LOAD_CONST, i); - DECREF(v); - /* Push the tuple of base classes on the stack */ - if (TYPE(CHILD(n, 2)) != LPAR) - com_addoparg(c, BUILD_TUPLE, 0); - else - com_bases(c, CHILD(n, 3)); - v = (object *)compile(n, c->c_filename); - if (v == NULL) - c->c_errors++; - else { - i = com_addconst(c, v); - com_addoparg(c, LOAD_CONST, i); - com_addoparg(c, MAKE_FUNCTION, 0); - com_addoparg(c, CALL_FUNCTION, 0); - com_addbyte(c, BUILD_CLASS); - com_addopname(c, STORE_NAME, CHILD(n, 1)); - DECREF(v); - } -} - -static void -com_node(c, n) - struct compiling *c; - node *n; -{ - switch (TYPE(n)) { - - /* Definition nodes */ - - case funcdef: - com_funcdef(c, n); - break; - case classdef: - com_classdef(c, n); - break; - - /* Trivial parse tree nodes */ - - case stmt: - case small_stmt: - case flow_stmt: - com_node(c, CHILD(n, 0)); - break; - - case simple_stmt: - /* small_stmt (';' small_stmt)* [';'] NEWLINE */ - com_addoparg(c, SET_LINENO, n->n_lineno); - { - int i; - for (i = 0; i < NCH(n)-1; i += 2) - com_node(c, CHILD(n, i)); - } - break; - - case compound_stmt: - com_addoparg(c, SET_LINENO, n->n_lineno); - com_node(c, CHILD(n, 0)); - break; - - /* Statement nodes */ - - case expr_stmt: - com_expr_stmt(c, n); - break; - case print_stmt: - com_print_stmt(c, n); - break; - case del_stmt: /* 'del' exprlist */ - com_assign(c, CHILD(n, 1), 0/*delete*/); - break; - case pass_stmt: - break; - case break_stmt: - if (c->c_loops == 0) { - err_setstr(SyntaxError, "'break' outside loop"); - c->c_errors++; - } - com_addbyte(c, BREAK_LOOP); - break; - case continue_stmt: - com_continue_stmt(c, n); - break; - case return_stmt: - com_return_stmt(c, n); - break; - case raise_stmt: - com_raise_stmt(c, n); - break; - case import_stmt: - com_import_stmt(c, n); - break; - case global_stmt: - com_global_stmt(c, n); - break; - case access_stmt: - com_access_stmt(c, n); - break; - case exec_stmt: - com_exec_stmt(c, n); - break; - case if_stmt: - com_if_stmt(c, n); - break; - case while_stmt: - com_while_stmt(c, n); - break; - case for_stmt: - com_for_stmt(c, n); - break; - case try_stmt: - com_try_stmt(c, n); - break; - case suite: - com_suite(c, n); - break; - - /* Expression nodes */ - - case testlist: - com_list(c, n, 0); - break; - case test: - com_test(c, n); - break; - case and_test: - com_and_test(c, n); - break; - case not_test: - com_not_test(c, n); - break; - case comparison: - com_comparison(c, n); - break; - case exprlist: - com_list(c, n, 0); - break; - case expr: - com_expr(c, n); - break; - case xor_expr: - com_xor_expr(c, n); - break; - case and_expr: - com_and_expr(c, n); - break; - case shift_expr: - com_shift_expr(c, n); - break; - case arith_expr: - com_arith_expr(c, n); - break; - case term: - com_term(c, n); - break; - case factor: - com_factor(c, n); - break; - case power: - com_power(c, n); - break; - case atom: - com_atom(c, n); - break; - - default: - fprintf(stderr, "node type %d\n", TYPE(n)); - err_setstr(SystemError, "com_node: unexpected node type"); - c->c_errors++; - } -} - -static void com_fplist PROTO((struct compiling *, node *)); - -static void -com_fpdef(c, n) - struct compiling *c; - node *n; -{ - REQ(n, fpdef); /* fpdef: NAME | '(' fplist ')' */ - if (TYPE(CHILD(n, 0)) == LPAR) - com_fplist(c, CHILD(n, 1)); - else - com_addoparg(c, STORE_FAST, com_newlocal(c, STR(CHILD(n, 0)))); -} - -static void -com_fplist(c, n) - struct compiling *c; - node *n; -{ - REQ(n, fplist); /* fplist: fpdef (',' fpdef)* [','] */ - if (NCH(n) == 1) { - com_fpdef(c, CHILD(n, 0)); - } - else { - int i; - com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2); - for (i = 0; i < NCH(n); i += 2) - com_fpdef(c, CHILD(n, i)); - } -} - -static void -com_arglist(c, n) - struct compiling *c; - node *n; -{ - int nch, i; - int complex = 0; - REQ(n, varargslist); - /* varargslist: - (fpdef ['=' test] ',')* (fpdef ['=' test] | '*' .....) */ - nch = NCH(n); - /* Enter all arguments in table of locals */ - for (i = 0; i < nch; i++) { - node *ch = CHILD(n, i); - node *fp; - char *name; - if (TYPE(ch) == STAR || TYPE(ch) == DOUBLESTAR) - break; - REQ(ch, fpdef); /* fpdef: NAME | '(' fplist ')' */ - fp = CHILD(ch, 0); - if (TYPE(fp) == NAME) - name = STR(fp); - else { - name = ""; - complex= 1; - } - com_newlocal(c, name); - c->c_argcount++; - if (++i >= nch) - break; - ch = CHILD(n, i); - if (TYPE(ch) == EQUAL) - i += 2; - else - REQ(ch, COMMA); - } - /* Handle *arguments */ - if (i < nch) { - node *ch; - ch = CHILD(n, i); - if (TYPE(ch) != DOUBLESTAR) { - REQ(ch, STAR); - ch = CHILD(n, i+1); - if (TYPE(ch) == NAME) { - c->c_flags |= CO_VARARGS; - i += 3; - com_newlocal(c, STR(ch)); - } - } - } - /* Handle **keywords */ - if (i < nch) { - node *ch; - ch = CHILD(n, i); - if (TYPE(ch) != DOUBLESTAR) { - REQ(ch, STAR); - ch = CHILD(n, i+1); - REQ(ch, STAR); - ch = CHILD(n, i+2); - } - else - ch = CHILD(n, i+1); - REQ(ch, NAME); - c->c_flags |= CO_VARKEYWORDS; - com_newlocal(c, STR(ch)); - } - if (complex) { - /* Generate code for complex arguments only after - having counted the simple arguments */ - int ilocal = 0; - for (i = 0; i < nch; i++) { - node *ch = CHILD(n, i); - node *fp; - if (TYPE(ch) == STAR || TYPE(ch) == DOUBLESTAR) - break; - REQ(ch, fpdef); /* fpdef: NAME | '(' fplist ')' */ - fp = CHILD(ch, 0); - if (TYPE(fp) != NAME) { - com_addoparg(c, LOAD_FAST, ilocal); - com_fpdef(c, ch); - } - ilocal++; - if (++i >= nch) - break; - ch = CHILD(n, i); - if (TYPE(ch) == EQUAL) - i += 2; - else - REQ(ch, COMMA); - } - } -} - -static void -com_file_input(c, n) - struct compiling *c; - node *n; -{ - int i; - object *doc; - REQ(n, file_input); /* (NEWLINE | stmt)* ENDMARKER */ - doc = get_docstring(n); - if (doc != NULL) { - int i = com_addconst(c, doc); - DECREF(doc); - com_addoparg(c, LOAD_CONST, i); - com_addopnamestr(c, STORE_NAME, "__doc__"); - } - for (i = 0; i < NCH(n); i++) { - node *ch = CHILD(n, i); - if (TYPE(ch) != ENDMARKER && TYPE(ch) != NEWLINE) - com_node(c, ch); - } -} - -/* Top-level compile-node interface */ - -static void -compile_funcdef(c, n) - struct compiling *c; - node *n; -{ - object *doc; - node *ch; - REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */ - c->c_name = STR(CHILD(n, 1)); - doc = get_docstring(CHILD(n, 4)); - if (doc != NULL) { - (void) com_addconst(c, doc); - DECREF(doc); - } - else - (void) com_addconst(c, None); /* No docstring */ - ch = CHILD(n, 2); /* parameters: '(' [varargslist] ')' */ - ch = CHILD(ch, 1); /* ')' | varargslist */ - if (TYPE(ch) == varargslist) - com_arglist(c, ch); - c->c_infunction = 1; - com_node(c, CHILD(n, 4)); - c->c_infunction = 0; - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - com_addbyte(c, RETURN_VALUE); -} - -static void -compile_lambdef(c, n) - struct compiling *c; - node *n; -{ - node *ch; - REQ(n, lambdef); /* lambdef: 'lambda' [varargslist] ':' test */ - c->c_name = "<lambda>"; - - ch = CHILD(n, 1); - (void) com_addconst(c, None); /* No docstring */ - if (TYPE(ch) == varargslist) { - com_arglist(c, ch); - ch = CHILD(n, 3); - } - else - ch = CHILD(n, 2); - com_node(c, ch); - com_addbyte(c, RETURN_VALUE); -} - -static void -compile_classdef(c, n) - struct compiling *c; - node *n; -{ - node *ch; - object *doc; - REQ(n, classdef); - /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */ - c->c_name = STR(CHILD(n, 1)); - ch = CHILD(n, NCH(n)-1); /* The suite */ - doc = get_docstring(ch); - if (doc != NULL) { - int i = com_addconst(c, doc); - DECREF(doc); - com_addoparg(c, LOAD_CONST, i); - com_addopnamestr(c, STORE_NAME, "__doc__"); - } - else - (void) com_addconst(c, None); - com_node(c, ch); - com_addbyte(c, LOAD_LOCALS); - com_addbyte(c, RETURN_VALUE); -} - -static void -compile_node(c, n) - struct compiling *c; - node *n; -{ - com_addoparg(c, SET_LINENO, n->n_lineno); - - switch (TYPE(n)) { - - case single_input: /* One interactive command */ - /* NEWLINE | simple_stmt | compound_stmt NEWLINE */ - c->c_interactive++; - n = CHILD(n, 0); - if (TYPE(n) != NEWLINE) - com_node(c, n); - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - com_addbyte(c, RETURN_VALUE); - c->c_interactive--; - break; - - case file_input: /* A whole file, or built-in function exec() */ - com_file_input(c, n); - com_addoparg(c, LOAD_CONST, com_addconst(c, None)); - com_addbyte(c, RETURN_VALUE); - break; - - case eval_input: /* Built-in function input() */ - com_node(c, CHILD(n, 0)); - com_addbyte(c, RETURN_VALUE); - break; - - case lambdef: /* anonymous function definition */ - compile_lambdef(c, n); - break; - - case funcdef: /* A function definition */ - compile_funcdef(c, n); - break; - - case classdef: /* A class definition */ - compile_classdef(c, n); - break; - - default: - fprintf(stderr, "node type %d\n", TYPE(n)); - err_setstr(SystemError, "compile_node: unexpected node type"); - c->c_errors++; - } -} - -/* Optimization for local variables in functions (and *only* functions). - - This replaces all LOAD_NAME, STORE_NAME and DELETE_NAME - instructions that refer to local variables with LOAD_FAST etc. - The latter instructions are much faster because they don't need to - look up the variable name in a dictionary. - - To find all local variables, we check all STORE_NAME, IMPORT_FROM - and DELETE_NAME instructions. This yields all local variables, - function definitions, class definitions and import statements. - Argument names have already been entered into the list by the - special processing for the argument list. - - All remaining LOAD_NAME instructions must refer to non-local (global - or builtin) variables, so are replaced by LOAD_GLOBAL. - - There are two problems: 'from foo import *' and 'exec' may introduce - local variables that we can't know while compiling. If this is the - case, we can still optimize bona fide locals (since those - statements will be surrounded by fast_2_locals() and - locals_2_fast()), but we can't change LOAD_NAME to LOAD_GLOBAL. - - NB: this modifies the string object c->c_code! */ - -static void -optimize(c) - struct compiling *c; -{ - unsigned char *next_instr, *cur_instr; - int opcode; - int oparg; - object *name; - object *error_type, *error_value, *error_traceback; - -#define NEXTOP() (*next_instr++) -#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) -#define GETITEM(v, i) (getlistitem((v), (i))) -#define GETNAMEOBJ(i) (GETITEM(c->c_names, (i))) - - err_fetch(&error_type, &error_value, &error_traceback); - - c->c_flags |= CO_OPTIMIZED; - - next_instr = (unsigned char *) getstringvalue(c->c_code); - for (;;) { - opcode = NEXTOP(); - if (opcode == STOP_CODE) - break; - if (HAS_ARG(opcode)) - oparg = NEXTARG(); - switch (opcode) { - case STORE_NAME: - case DELETE_NAME: - case IMPORT_FROM: - com_addlocal_o(c, GETNAMEOBJ(oparg)); - break; - case EXEC_STMT: - c->c_flags &= ~CO_OPTIMIZED; - break; - } - } - - if (dictlookup(c->c_locals, "*") != NULL) - c->c_flags &= ~CO_OPTIMIZED; - - next_instr = (unsigned char *) getstringvalue(c->c_code); - for (;;) { - cur_instr = next_instr; - opcode = NEXTOP(); - if (opcode == STOP_CODE) - break; - if (HAS_ARG(opcode)) - oparg = NEXTARG(); - if (opcode == LOAD_NAME || - opcode == STORE_NAME || - opcode == DELETE_NAME) { - object *v; - int i; - name = GETNAMEOBJ(oparg); - v = dict2lookup(c->c_locals, name); - if (v == NULL) { - err_clear(); - if (opcode == LOAD_NAME && - (c->c_flags&CO_OPTIMIZED)) - cur_instr[0] = LOAD_GLOBAL; - continue; - } - i = getintvalue(v); - switch (opcode) { - case LOAD_NAME: cur_instr[0] = LOAD_FAST; break; - case STORE_NAME: cur_instr[0] = STORE_FAST; break; - case DELETE_NAME: cur_instr[0] = DELETE_FAST; break; - } - cur_instr[1] = i & 0xff; - cur_instr[2] = (i>>8) & 0xff; - } - } - - if (c->c_errors == 0) - err_restore(error_type, error_value, error_traceback); -} - -codeobject * -compile(n, filename) - node *n; - char *filename; -{ - struct compiling sc; - codeobject *co; - if (!com_init(&sc, filename)) - return NULL; - compile_node(&sc, n); - com_done(&sc); - if ((TYPE(n) == funcdef || TYPE(n) == lambdef) && sc.c_errors == 0) { - optimize(&sc); - sc.c_flags |= CO_NEWLOCALS; - } - else if (TYPE(n) == classdef) - sc.c_flags |= CO_NEWLOCALS; - co = NULL; - if (sc.c_errors == 0) { - object *consts, *names, *varnames, *filename, *name; - consts = listtuple(sc.c_consts); - names = listtuple(sc.c_names); - varnames = listtuple(sc.c_varnames); - filename = newstringobject(sc.c_filename); - name = newstringobject(sc.c_name); - if (!err_occurred()) - co = newcodeobject(sc.c_argcount, - sc.c_nlocals, - sc.c_flags, - sc.c_code, - consts, - names, - varnames, - filename, - name); - XDECREF(consts); - XDECREF(names); - XDECREF(varnames); - XDECREF(filename); - XDECREF(name); - } - com_free(&sc); - return co; -} diff --git a/Python/dup2.c b/Python/dup2.c deleted file mode 100644 index 85ec5d5e5f..0000000000 --- a/Python/dup2.c +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Public domain dup2() lookalike - * by Curtis Jackson @ AT&T Technologies, Burlington, NC - * electronic address: burl!rcj - * - * dup2 performs the following functions: - * - * Check to make sure that fd1 is a valid open file descriptor. - * Check to see if fd2 is already open; if so, close it. - * Duplicate fd1 onto fd2; checking to make sure fd2 is a valid fd. - * Return fd2 if all went well; return BADEXIT otherwise. - */ - -#include <fcntl.h> - -#define BADEXIT -1 - -int -dup2(fd1, fd2) -int fd1, fd2; -{ - if (fd1 != fd2) { - if (fcntl(fd1, F_GETFL) < 0) - return BADEXIT; - if (fcntl(fd2, F_GETFL) >= 0) - close(fd2); - if (fcntl(fd1, F_DUPFD, fd2) < 0) - return BADEXIT; - } - return fd2; -} diff --git a/Python/errors.c b/Python/errors.c deleted file mode 100644 index 3c721b8ff6..0000000000 --- a/Python/errors.c +++ /dev/null @@ -1,198 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Error handling -- see also run.c */ - -/* New error handling interface. - - The following problem exists (existed): methods of built-in modules - are called with 'self' and 'args' arguments, but without a context - argument, so they have no way to raise a specific exception. - The same is true for the object implementations: no context argument. - The old convention was to set 'errno' and to return NULL. - The caller (usually call_function() in eval.c) detects the NULL - return value and then calls puterrno(ctx) to turn the errno value - into a true exception. Problems with this approach are: - - it used standard errno values to indicate Python-specific errors, - but this means that when such an error code is reported by a system - call (e.g., in module posix), the user gets a confusing message - - errno is a global variable, which makes extensions to a multi- - threading environment difficult; e.g., in IRIX, multi-threaded - programs must use the function oserror() instead of looking in errno - - there is no portable way to add new error numbers for specic - situations -- the value space for errno is reserved to the OS, yet - the way to turn module-specific errors into a module-specific - exception requires module-specific values for errno - - there is no way to add a more situation-specific message to an - error. - - The new interface solves all these problems. To return an error, a - built-in function calls err_set(exception), err_setval(exception, - value) or err_setstr(exception, string), and returns NULL. These - functions save the value for later use by puterrno(). To adapt this - scheme to a multi-threaded environment, only the implementation of - err_setval() has to be changed. -*/ - -#include "allobjects.h" -#include "traceback.h" - -#include <errno.h> - -#ifdef SYMANTEC__CFM68K__ -#pragma lib_export on -#endif - -#ifdef macintosh -/* Replace strerror with a Mac specific routine. - XXX PROBLEM: some positive errors have a meaning for MacOS, - but some library routines set Unix error numbers... -*/ -extern char *PyMac_StrError PROTO((int)); -#undef strerror -#define strerror PyMac_StrError -#endif /* macintosh */ - -#ifndef __STDC__ -extern char *strerror PROTO((int)); -#endif - -/* Last exception stored by err_setval() */ - -static object *last_exception; -static object *last_exc_val; - -void -err_restore(exception, value, traceback) - object *exception; - object *value; - object *traceback; -{ - err_clear(); - - last_exception = exception; - last_exc_val = value; - (void) tb_store(traceback); - XDECREF(traceback); -} - -void -err_setval(exception, value) - object *exception; - object *value; -{ - XINCREF(exception); - XINCREF(value); - err_restore(exception, value, (object *)NULL); -} - -void -err_set(exception) - object *exception; -{ - err_setval(exception, (object *)NULL); -} - -void -err_setstr(exception, string) - object *exception; - char *string; -{ - object *value = newstringobject(string); - err_setval(exception, value); - XDECREF(value); -} - - -object * -err_occurred() -{ - return last_exception; -} - -void -err_fetch(p_exc, p_val, p_tb) - object **p_exc; - object **p_val; - object **p_tb; -{ - *p_exc = last_exception; - last_exception = NULL; - *p_val = last_exc_val; - last_exc_val = NULL; - *p_tb = tb_fetch(); -} - -void -err_clear() -{ - object *tb; - XDECREF(last_exception); - last_exception = NULL; - XDECREF(last_exc_val); - last_exc_val = NULL; - /* Also clear interpreter stack trace */ - tb = tb_fetch(); - XDECREF(tb); -} - -/* Convenience functions to set a type error exception and return 0 */ - -int -err_badarg() -{ - err_setstr(TypeError, "illegal argument type for built-in operation"); - return 0; -} - -object * -err_nomem() -{ - err_set(MemoryError); - return NULL; -} - -object * -err_errno(exc) - object *exc; -{ - object *v; - int i = errno; -#ifdef EINTR - if (i == EINTR && sigcheck()) - return NULL; -#endif - v = mkvalue("(is)", i, strerror(i)); - if (v != NULL) { - err_setval(exc, v); - DECREF(v); - } - return NULL; -} - -void -err_badcall() -{ - err_setstr(SystemError, "bad argument to internal function"); -} diff --git a/Python/fmod.c b/Python/fmod.c deleted file mode 100644 index 777166bcb6..0000000000 --- a/Python/fmod.c +++ /dev/null @@ -1,52 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Portable fmod(x, y) implementation for systems that don't have it */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "mymath.h" -#include <errno.h> - -double -fmod(double x, double y) -{ - double i, f; - - if (y == 0.0) { - errno = EDOM; - return 0.0; - } - - /* return f such that x = i*y + f for some integer i - such that |f| < |y| and f has the same sign as x */ - - i = floor(x/y); - f = x - i*y; - if ((x < 0.0) != (y < 0.0)) - f = f-y; - return f; -} diff --git a/Python/frozen.c b/Python/frozen.c deleted file mode 100644 index 633931485c..0000000000 --- a/Python/frozen.c +++ /dev/null @@ -1,49 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Dummy frozen modules initializer */ - -#include "Python.h" - -/* In order to test the support for frozen modules, by default we - define a single frozen module, __hello__. Loading it will print - some famous words... */ - -static unsigned char M___hello__[] = { - 99,0,0,0,0,0,0,115,15,0,0,0,127,0,0,127, - 1,0,100,0,0,71,72,100,1,0,83,40,2,0,0,0, - 115,14,0,0,0,72,101,108,108,111,32,119,111,114,108,100, - 46,46,46,78,40,0,0,0,0,40,0,0,0,0,115,8, - 0,0,0,104,101,108,108,111,46,112,121,115,1,0,0,0, - 63, -}; - -struct frozen { - char *name; - unsigned char *code; - int size; -} _PyImport_FrozenModules[] = { - {"__hello__", M___hello__, 81}, - {0, 0, 0} /* sentinel */ -}; diff --git a/Python/frozenmain.c b/Python/frozenmain.c deleted file mode 100644 index 17979b3ead..0000000000 --- a/Python/frozenmain.c +++ /dev/null @@ -1,93 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Python interpreter main program for frozen scripts */ - -#include "Python.h" - -/* Subroutines that live in their own file */ -extern char *Py_GetVersion(); -extern char *Py_GetCopyright(); - -/* For getprogramname(); set by main() */ -static char *argv0; - -/* Main program */ - -int -main(argc, argv) - int argc; - char **argv; -{ - char *p; - int n, sts; - int inspect = 0; - int unbuffered = 0; - - argv0 = argv[0]; - - if ((p = getenv("PYTHONDEBUG")) && *p != '\0') - Py_DebugFlag = 1; - if ((p = getenv("PYTHONSUPPRESS")) && *p != '\0') - Py_SuppressPrintingFlag = 1; - if ((p = getenv("PYTHONVERBOSE")) && *p != '\0') - Py_VerboseFlag = 1; - if ((p = getenv("PYTHONINSPECT")) && *p != '\0') - inspect = 1; - if ((p = getenv("PYTHONUNBUFFERED")) && *p != '\0') - unbuffered = 1; - - if (unbuffered) { - setbuf(stdout, (char *)NULL); - setbuf(stderr, (char *)NULL); - } - - if (Py_VerboseFlag) - fprintf(stderr, "Python %s\n%s\n", - Py_GetVersion(), Py_GetCopyright()); - Py_Initialize(); - PySys_SetArgv(argc, argv); - - n = PyImport_ImportFrozenModule("__main__"); - if (n == 0) - Py_FatalError("__main__ not frozen"); - if (n < 0) { - PyErr_Print(); - sts = 1; - } - else - sts = 0; - - if (inspect && isatty((int)fileno(stdin))) - sts = PyRun_AnyFile(stdin, "<stdin>") != 0; - - Py_Exit(sts); - /*NOTREACHED*/ -} - -char * -getprogramname() -{ - return argv0; -} diff --git a/Python/getargs.c b/Python/getargs.c deleted file mode 100644 index 7ec31c3535..0000000000 --- a/Python/getargs.c +++ /dev/null @@ -1,615 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* New getargs implementation */ - -/* XXX There are several unchecked sprintf or strcat calls in this file. - XXX The only way these can become a danger is if some C code in the - XXX Python source (or in an extension) uses ridiculously long names - XXX or riduculously deep nesting in format strings. */ - -#include "allobjects.h" - - -int getargs PROTO((object *, char *, ...)); -int newgetargs PROTO((object *, char *, ...)); -int vgetargs PROTO((object *, char *, va_list)); - - -/* Forward */ -static int vgetargs1 PROTO((object *, char *, va_list *, int)); -static void seterror PROTO((int, char *, int *, char *, char *)); -static char *convertitem PROTO((object *, char **, va_list *, int *, char *)); -static char *converttuple PROTO((object *, char **, va_list *, - int *, char *, int)); -static char *convertsimple PROTO((object *, char **, va_list *, char *)); -static char *convertsimple1 PROTO((object *, char **, va_list *)); - - -#ifdef HAVE_STDARG_PROTOTYPES -/* VARARGS2 */ -int getargs(object *args, char *format, ...) -#else -/* VARARGS */ -int getargs(va_alist) va_dcl -#endif -{ - int retval; - va_list va; -#ifdef HAVE_STDARG_PROTOTYPES - - va_start(va, format); -#else - object *args; - char *format; - - va_start(va); - args = va_arg(va, object *); - format = va_arg(va, char *); -#endif - retval = vgetargs1(args, format, &va, 1); - va_end(va); - return retval; -} - - -#ifdef HAVE_STDARG_PROTOTYPES -/* VARARGS2 */ -int newgetargs(object *args, char *format, ...) -#else -/* VARARGS */ -int newgetargs(va_alist) va_dcl -#endif -{ - int retval; - va_list va; -#ifdef HAVE_STDARG_PROTOTYPES - - va_start(va, format); -#else - object *args; - char *format; - - va_start(va); - args = va_arg(va, object *); - format = va_arg(va, char *); -#endif - retval = vgetargs1(args, format, &va, 0); - va_end(va); - return retval; -} - - -int -vgetargs(args, format, va) - object *args; - char *format; - va_list va; -{ - va_list lva; - -#ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); -#else - lva = va; -#endif - - return vgetargs1(args, format, &lva, 0); -} - - -static int -vgetargs1(args, format, p_va, compat) - object *args; - char *format; - va_list *p_va; - int compat; -{ - char msgbuf[256]; - int levels[32]; - char *fname = NULL; - char *message = NULL; - int min = -1; - int max = 0; - int level = 0; - char *formatsave = format; - int i, len; - char *msg; - - for (;;) { - int c = *format++; - if (c == '(' /* ')' */) { - if (level == 0) - max++; - level++; - } - else if (/* '(' */ c == ')') { - if (level == 0) - fatal(/* '(' */ - "excess ')' in getargs format"); - else - level--; - } - else if (c == '\0') - break; - else if (c == ':') { - fname = format; - break; - } - else if (c == ';') { - message = format; - break; - } - else if (level != 0) - ; /* Pass */ - else if (isalpha(c)) - max++; - else if (c == '|') - min = max; - } - - if (level != 0) - fatal(/* '(' */ "missing ')' in getargs format"); - - if (min < 0) - min = max; - - format = formatsave; - - if (compat) { - if (max == 0) { - if (args == NULL) - return 1; - sprintf(msgbuf, "%s requires no arguments", - fname==NULL ? "function" : fname); - err_setstr(TypeError, msgbuf); - return 0; - } - else if (min == 1 && max == 1) { - if (args == NULL) { - sprintf(msgbuf, - "%s requires at least one argument", - fname==NULL ? "function" : fname); - err_setstr(TypeError, msgbuf); - return 0; - } - msg = convertitem(args, &format, p_va, levels, msgbuf); - if (msg == NULL) - return 1; - seterror(levels[0], msg, levels+1, fname, message); - return 0; - } - else { - err_setstr(SystemError, - "old style getargs format uses new features"); - return 0; - } - } - - if (!is_tupleobject(args)) { - err_setstr(SystemError, - "new style getargs format but argument is not a tuple"); - return 0; - } - - len = gettuplesize(args); - - if (len < min || max < len) { - if (message == NULL) { - sprintf(msgbuf, - "%s requires %s %d argument%s; %d given", - fname==NULL ? "function" : fname, - min==max ? "exactly" - : len < min ? "at least" : "at most", - len < min ? min : max, - (len < min ? min : max) == 1 ? "" : "s", - len); - message = msgbuf; - } - err_setstr(TypeError, message); - return 0; - } - - for (i = 0; i < len; i++) { - if (*format == '|') - format++; - msg = convertitem(gettupleitem(args, i), &format, p_va, - levels, msgbuf); - if (msg) { - seterror(i+1, msg, levels, fname, message); - return 0; - } - } - - return 1; -} - - - -static void -seterror(iarg, msg, levels, fname, message) - int iarg; - char *msg; - int *levels; - char *fname; - char *message; -{ - char buf[256]; - int i; - char *p = buf; - - if (err_occurred()) - return; - if (iarg == 0 && message == NULL) - message = msg; - else if (message == NULL) { - if (fname != NULL) { - sprintf(p, "%s, ", fname); - p += strlen(p); - } - sprintf(p, "argument %d", iarg); - i = 0; - p += strlen(p); - while (levels[i] > 0) { - sprintf(p, ", item %d", levels[i]-1); - p += strlen(p); - i++; - } - sprintf(p, ": expected %s found", msg); - message = buf; - } - err_setstr(TypeError, message); -} - - -/* Convert a tuple argument. - On entry, *p_format points to the character _after_ the opening '('. - On successful exit, *p_format points to the closing ')'. - If successful: - *p_format and *p_va are updated, - *levels and *msgbuf are untouched, - and NULL is returned. - If the argument is invalid: - *p_format is unchanged, - *p_va is undefined, - *levels is a 0-terminated list of item numbers, - *msgbuf contains an error message, whose format is: - "<typename1>, <typename2>", where: - <typename1> is the name of the expected type, and - <typename2> is the name of the actual type, - (so you can surround it by "expected ... found"), - and msgbuf is returned. -*/ - -static char * -converttuple(arg, p_format, p_va, levels, msgbuf, toplevel) - object *arg; - char **p_format; - va_list *p_va; - int *levels; - char *msgbuf; - int toplevel; -{ - int level = 0; - int n = 0; - char *format = *p_format; - int i; - - for (;;) { - int c = *format++; - if (c == '(') { - if (level == 0) - n++; - level++; - } - else if (c == ')') { - if (level == 0) - break; - level--; - } - else if (c == ':' || c == ';' || c == '\0') - break; - else if (level == 0 && isalpha(c)) - n++; - } - - if (!is_tupleobject(arg)) { - levels[0] = 0; - sprintf(msgbuf, - toplevel ? "%d arguments, %s" : "%d-tuple, %s", - n, arg == None ? "None" : arg->ob_type->tp_name); - return msgbuf; - } - - if ((i = gettuplesize(arg)) != n) { - levels[0] = 0; - sprintf(msgbuf, - toplevel ? "%d arguments, %d" : "%d-tuple, %d-tuple", - n, i); - return msgbuf; - } - - format = *p_format; - for (i = 0; i < n; i++) { - char *msg; - msg = convertitem(gettupleitem(arg, i), &format, p_va, - levels+1, msgbuf); - if (msg != NULL) { - levels[0] = i+1; - return msg; - } - } - - *p_format = format; - return NULL; -} - - -/* Convert a single item. */ - -static char * -convertitem(arg, p_format, p_va, levels, msgbuf) - object *arg; - char **p_format; - va_list *p_va; - int *levels; - char *msgbuf; -{ - char *msg; - char *format = *p_format; - - if (*format == '(' /* ')' */) { - format++; - msg = converttuple(arg, &format, p_va, levels, msgbuf, 0); - if (msg == NULL) - format++; - } - else { - msg = convertsimple(arg, &format, p_va, msgbuf); - if (msg != NULL) - levels[0] = 0; - } - if (msg == NULL) - *p_format = format; - return msg; -} - - -/* Convert a non-tuple argument. Adds to convertsimple1 functionality - by appending ", <actual argument type>" to error message. */ - -static char * -convertsimple(arg, p_format, p_va, msgbuf) - object *arg; - char **p_format; - va_list *p_va; - char *msgbuf; -{ - char *msg = convertsimple1(arg, p_format, p_va); - if (msg != NULL) { - sprintf(msgbuf, "%.50s, %.50s", msg, - arg == None ? "None" : arg->ob_type->tp_name); - msg = msgbuf; - } - return msg; -} - - -/* Convert a non-tuple argument. Return NULL if conversion went OK, - or a string representing the expected type if the conversion failed. - When failing, an exception may or may not have been raised. - Don't call if a tuple is expected. */ - -static char * -convertsimple1(arg, p_format, p_va) - object *arg; - char **p_format; - va_list *p_va; -{ - char *format = *p_format; - char c = *format++; - - switch (c) { - - case 'b': /* byte -- very short int */ - { - char *p = va_arg(*p_va, char *); - long ival = getintvalue(arg); - if (ival == -1 && err_occurred()) - return "integer<b>"; - else - *p = ival; - break; - } - - case 'h': /* short int */ - { - short *p = va_arg(*p_va, short *); - long ival = getintvalue(arg); - if (ival == -1 && err_occurred()) - return "integer<h>"; - else - *p = ival; - break; - } - - case 'i': /* int */ - { - int *p = va_arg(*p_va, int *); - long ival = getintvalue(arg); - if (ival == -1 && err_occurred()) - return "integer<i>"; - else - *p = ival; - break; - } - - case 'l': /* long int */ - { - long *p = va_arg(*p_va, long *); - long ival = getintvalue(arg); - if (ival == -1 && err_occurred()) - return "integer<l>"; - else - *p = ival; - break; - } - - case 'f': /* float */ - { - float *p = va_arg(*p_va, float *); - double dval = getfloatvalue(arg); - if (err_occurred()) - return "float<f>"; - else - *p = dval; - break; - } - - case 'd': /* double */ - { - double *p = va_arg(*p_va, double *); - double dval = getfloatvalue(arg); - if (err_occurred()) - return "float<d>"; - else - *p = dval; - break; - } - - case 'D': /* complex double */ - { - complex *p = va_arg(*p_va, complex *); - complex cval = PyComplex_AsCComplex(arg); - if (err_occurred()) - return "complex<D>"; - else - *p = cval; - break; - } - - case 'c': /* char */ - { - char *p = va_arg(*p_va, char *); - if (is_stringobject(arg) && getstringsize(arg) == 1) - *p = getstringvalue(arg)[0]; - else - return "char"; - break; - } - - case 's': /* string */ - { - char **p = va_arg(*p_va, char **); - if (is_stringobject(arg)) - *p = getstringvalue(arg); - else - return "string"; - if (*format == '#') { - int *q = va_arg(*p_va, int *); - *q = getstringsize(arg); - format++; - } - else if (strlen(*p) != getstringsize(arg)) - return "string without null bytes"; - break; - } - - case 'z': /* string, may be NULL (None) */ - { - char **p = va_arg(*p_va, char **); - if (arg == None) - *p = 0; - else if (is_stringobject(arg)) - *p = getstringvalue(arg); - else - return "None or string"; - if (*format == '#') { - int *q = va_arg(*p_va, int *); - if (arg == None) - *q = 0; - else - *q = getstringsize(arg); - format++; - } - else if (*p != NULL && strlen(*p) != getstringsize(arg)) - return "None or string without null bytes"; - break; - } - - case 'S': /* string object */ - { - object **p = va_arg(*p_va, object **); - if (is_stringobject(arg)) - *p = arg; - else - return "string"; - break; - } - - case 'O': /* object */ - { - typeobject *type; - object **p; - if (*format == '!') { - format++; - type = va_arg(*p_va, typeobject*); - if (arg->ob_type != type) - return type->tp_name; - else { - p = va_arg(*p_va, object **); - *p = arg; - } - } - else if (*format == '?') { - inquiry pred = va_arg(*p_va, inquiry); - format++; - if ((*pred)(arg)) { - p = va_arg(*p_va, object **); - *p = arg; - } - } - else if (*format == '&') { - typedef int (*converter) PROTO((object *, void *)); - converter convert = va_arg(*p_va, converter); - void *addr = va_arg(*p_va, void *); - format++; - if (! (*convert)(arg, addr)) - return "(unspecified)"; - } - else { - p = va_arg(*p_va, object **); - *p = arg; - } - break; - } - - default: - return "impossible<bad format char>"; - - } - - *p_format = format; - return NULL; -} diff --git a/Python/getcompiler.c b/Python/getcompiler.c deleted file mode 100644 index 56ff4867b9..0000000000 --- a/Python/getcompiler.c +++ /dev/null @@ -1,51 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Return the compiler identification, if possible. */ - -#include "Python.h" - -#ifndef COMPILER - -#ifdef __GNUC__ -#define COMPILER " [GCC " __VERSION__ "]" -#endif - -#endif /* !COMPILER */ - -#ifndef COMPILER - -#ifdef __cplusplus -#define COMPILER "[C++]" -#else -#define COMPILER "[C]" -#endif - -#endif /* !COMPILER */ - -char * -Py_GetCompiler() -{ - return COMPILER; -} diff --git a/Python/getcopyright.c b/Python/getcopyright.c deleted file mode 100644 index 5ed7787a3c..0000000000 --- a/Python/getcopyright.c +++ /dev/null @@ -1,33 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Return the copyright string. This is updated manually. */ - -#include "Python.h" - -const char * -Py_GetCopyright() -{ - return "Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam"; -} diff --git a/Python/getcwd.c b/Python/getcwd.c deleted file mode 100644 index 894993faa0..0000000000 --- a/Python/getcwd.c +++ /dev/null @@ -1,106 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Two PD getcwd() implementations. - Author: Guido van Rossum, CWI Amsterdam, Jan 1991, <guido@cwi.nl>. */ - -#include <stdio.h> -#include <errno.h> - -#ifdef HAVE_GETWD - -/* Version for BSD systems -- use getwd() */ - -#ifdef HAVE_SYS_PARAM_H -#include <sys/param.h> -#endif - -#ifndef MAXPATHLEN -#define MAXPATHLEN 1024 -#endif - -extern char *getwd(); - -char * -getcwd(buf, size) - char *buf; - int size; -{ - char localbuf[MAXPATHLEN+1]; - char *ret; - - if (size <= 0) { - errno = EINVAL; - return NULL; - } - ret = getwd(localbuf); - if (ret != NULL && strlen(localbuf) >= size) { - errno = ERANGE; - return NULL; - } - if (ret == NULL) { - errno = EACCES; /* Most likely error */ - return NULL; - } - strncpy(buf, localbuf, size); - return buf; -} - -#else /* !HAVE_GETWD */ - -/* Version for really old UNIX systems -- use pipe from pwd */ - -#ifndef PWD_CMD -#define PWD_CMD "/bin/pwd" -#endif - -char * -getcwd(buf, size) - char *buf; - int size; -{ - FILE *fp; - char *p; - int sts; - if (size <= 0) { - errno = EINVAL; - return NULL; - } - if ((fp = popen(PWD_CMD, "r")) == NULL) - return NULL; - if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { - errno = EACCES; /* Most likely error */ - return NULL; - } - for (p = buf; *p != '\n'; p++) { - if (*p == '\0') { - errno = ERANGE; - return NULL; - } - } - *p = '\0'; - return buf; -} - -#endif /* !HAVE_GETWD */ diff --git a/Python/getmtime.c b/Python/getmtime.c deleted file mode 100644 index fde6a3b9c2..0000000000 --- a/Python/getmtime.c +++ /dev/null @@ -1,46 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Subroutine to get the last modification time of a file */ - -/* (A separate file because this may be OS dependent) */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include <sys/types.h> -#include <sys/stat.h> -#include "rename2.h" - -long -getmtime(path) - char *path; -{ - struct stat st; - if (stat(path, &st) != 0) - return -1; - else - return st.st_mtime; -} diff --git a/Python/getopt.c b/Python/getopt.c deleted file mode 100644 index c08f07fa03..0000000000 --- a/Python/getopt.c +++ /dev/null @@ -1,88 +0,0 @@ -/*---------------------------------------------------------------------------* - * <RCS keywords> - * - * C++ Library - * - * Copyright 1992-1994, David Gottner - * - * All Rights Reserved - * - * Permission to use, copy, modify, and distribute this software and its - * documentation for any purpose and without fee is hereby granted, - * provided that the above copyright notice, this permission notice and - * the following disclaimer notice appear unmodified in all copies. - * - * I DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL I - * 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. - * - * Nevertheless, I would like to know about bugs in this library or - * suggestions for improvment. Send bug reports and feedback to - * davegottner@delphi.com. - *---------------------------------------------------------------------------*/ - -#include <stdio.h> -#include <string.h> - -#define bool int -#define TRUE 1 -#define FALSE 0 - - -bool opterr = TRUE; /* generate error messages */ -int optind = 1; /* index into argv array */ -char * optarg = NULL; /* optional argument */ - - -int getopt(argc,argv,optstring) -int argc; -char *argv[]; -char optstring[]; -{ - static char *opt_ptr = ""; - register char *ptr; - int option; - - if (*opt_ptr == '\0') { - - if (optind >= argc || argv[optind][0] != '-') - return -1; - - else if (strcmp(argv[optind], "--") == 0) { - ++optind; - return -1; - } - - opt_ptr = &argv[optind++][1]; - } - - if ((ptr = strchr(optstring, option = *opt_ptr++)) == NULL) { - if (opterr) - fprintf(stderr, "Unknown option: -%c\n", option); - - return '?'; - } - - if (*(ptr + 1) == ':') { - if (*opt_ptr != '\0') { - optarg = opt_ptr; - opt_ptr = ""; - } - - else { - if (optind >= argc) { - if (opterr) - fprintf(stderr, - "Argument expected for the -%c option\n", option); - return '?'; - } - - optarg = argv[optind++]; - } - } - - return option; -} diff --git a/Python/getplatform.c b/Python/getplatform.c deleted file mode 100644 index 7142fd6a2e..0000000000 --- a/Python/getplatform.c +++ /dev/null @@ -1,35 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#include "Python.h" - -#ifndef PLATFORM -#define PLATFORM "unknown" -#endif - -char * -Py_GetPlatform() -{ - return PLATFORM; -} diff --git a/Python/getversion.c b/Python/getversion.c deleted file mode 100644 index efc7849e43..0000000000 --- a/Python/getversion.c +++ /dev/null @@ -1,47 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Return the full version string. */ - -#include "Python.h" - -#include "patchlevel.h" - -#define VERSION "%s (%s) %s" - -#ifdef __DATE__ -#define DATE __DATE__ -#else -#define DATE "October 13 1995" -#endif - -extern const char *Py_GetCompiler(); - -const char * -Py_GetVersion() -{ - static char version[80]; - sprintf(version, VERSION, PATCHLEVEL, DATE, Py_GetCompiler()); - return version; -} diff --git a/Python/graminit.c b/Python/graminit.c deleted file mode 100644 index f8b76acf16..0000000000 --- a/Python/graminit.c +++ /dev/null @@ -1,1436 +0,0 @@ -#include "pgenheaders.h" -#include "grammar.h" -static arc arcs_0_0[3] = { - {2, 1}, - {3, 1}, - {4, 2}, -}; -static arc arcs_0_1[1] = { - {0, 1}, -}; -static arc arcs_0_2[1] = { - {2, 1}, -}; -static state states_0[3] = { - {3, arcs_0_0}, - {1, arcs_0_1}, - {1, arcs_0_2}, -}; -static arc arcs_1_0[3] = { - {2, 0}, - {6, 0}, - {7, 1}, -}; -static arc arcs_1_1[1] = { - {0, 1}, -}; -static state states_1[2] = { - {3, arcs_1_0}, - {1, arcs_1_1}, -}; -static arc arcs_2_0[1] = { - {9, 1}, -}; -static arc arcs_2_1[2] = { - {2, 1}, - {7, 2}, -}; -static arc arcs_2_2[1] = { - {0, 2}, -}; -static state states_2[3] = { - {1, arcs_2_0}, - {2, arcs_2_1}, - {1, arcs_2_2}, -}; -static arc arcs_3_0[1] = { - {11, 1}, -}; -static arc arcs_3_1[1] = { - {12, 2}, -}; -static arc arcs_3_2[1] = { - {13, 3}, -}; -static arc arcs_3_3[1] = { - {14, 4}, -}; -static arc arcs_3_4[1] = { - {15, 5}, -}; -static arc arcs_3_5[1] = { - {0, 5}, -}; -static state states_3[6] = { - {1, arcs_3_0}, - {1, arcs_3_1}, - {1, arcs_3_2}, - {1, arcs_3_3}, - {1, arcs_3_4}, - {1, arcs_3_5}, -}; -static arc arcs_4_0[1] = { - {16, 1}, -}; -static arc arcs_4_1[2] = { - {17, 2}, - {18, 3}, -}; -static arc arcs_4_2[1] = { - {18, 3}, -}; -static arc arcs_4_3[1] = { - {0, 3}, -}; -static state states_4[4] = { - {1, arcs_4_0}, - {2, arcs_4_1}, - {1, arcs_4_2}, - {1, arcs_4_3}, -}; -static arc arcs_5_0[3] = { - {19, 1}, - {23, 2}, - {24, 3}, -}; -static arc arcs_5_1[3] = { - {20, 4}, - {22, 5}, - {0, 1}, -}; -static arc arcs_5_2[2] = { - {12, 6}, - {23, 3}, -}; -static arc arcs_5_3[1] = { - {12, 7}, -}; -static arc arcs_5_4[1] = { - {21, 8}, -}; -static arc arcs_5_5[4] = { - {19, 1}, - {23, 2}, - {24, 3}, - {0, 5}, -}; -static arc arcs_5_6[2] = { - {22, 9}, - {0, 6}, -}; -static arc arcs_5_7[1] = { - {0, 7}, -}; -static arc arcs_5_8[2] = { - {22, 5}, - {0, 8}, -}; -static arc arcs_5_9[2] = { - {24, 3}, - {23, 10}, -}; -static arc arcs_5_10[1] = { - {23, 3}, -}; -static state states_5[11] = { - {3, arcs_5_0}, - {3, arcs_5_1}, - {2, arcs_5_2}, - {1, arcs_5_3}, - {1, arcs_5_4}, - {4, arcs_5_5}, - {2, arcs_5_6}, - {1, arcs_5_7}, - {2, arcs_5_8}, - {2, arcs_5_9}, - {1, arcs_5_10}, -}; -static arc arcs_6_0[2] = { - {12, 1}, - {16, 2}, -}; -static arc arcs_6_1[1] = { - {0, 1}, -}; -static arc arcs_6_2[1] = { - {25, 3}, -}; -static arc arcs_6_3[1] = { - {18, 1}, -}; -static state states_6[4] = { - {2, arcs_6_0}, - {1, arcs_6_1}, - {1, arcs_6_2}, - {1, arcs_6_3}, -}; -static arc arcs_7_0[1] = { - {19, 1}, -}; -static arc arcs_7_1[2] = { - {22, 2}, - {0, 1}, -}; -static arc arcs_7_2[2] = { - {19, 1}, - {0, 2}, -}; -static state states_7[3] = { - {1, arcs_7_0}, - {2, arcs_7_1}, - {2, arcs_7_2}, -}; -static arc arcs_8_0[2] = { - {3, 1}, - {4, 1}, -}; -static arc arcs_8_1[1] = { - {0, 1}, -}; -static state states_8[2] = { - {2, arcs_8_0}, - {1, arcs_8_1}, -}; -static arc arcs_9_0[1] = { - {26, 1}, -}; -static arc arcs_9_1[2] = { - {27, 2}, - {2, 3}, -}; -static arc arcs_9_2[2] = { - {26, 1}, - {2, 3}, -}; -static arc arcs_9_3[1] = { - {0, 3}, -}; -static state states_9[4] = { - {1, arcs_9_0}, - {2, arcs_9_1}, - {2, arcs_9_2}, - {1, arcs_9_3}, -}; -static arc arcs_10_0[9] = { - {28, 1}, - {29, 1}, - {30, 1}, - {31, 1}, - {32, 1}, - {33, 1}, - {34, 1}, - {35, 1}, - {36, 1}, -}; -static arc arcs_10_1[1] = { - {0, 1}, -}; -static state states_10[2] = { - {9, arcs_10_0}, - {1, arcs_10_1}, -}; -static arc arcs_11_0[1] = { - {9, 1}, -}; -static arc arcs_11_1[2] = { - {20, 0}, - {0, 1}, -}; -static state states_11[2] = { - {1, arcs_11_0}, - {2, arcs_11_1}, -}; -static arc arcs_12_0[1] = { - {37, 1}, -}; -static arc arcs_12_1[2] = { - {21, 2}, - {0, 1}, -}; -static arc arcs_12_2[2] = { - {22, 1}, - {0, 2}, -}; -static state states_12[3] = { - {1, arcs_12_0}, - {2, arcs_12_1}, - {2, arcs_12_2}, -}; -static arc arcs_13_0[1] = { - {38, 1}, -}; -static arc arcs_13_1[1] = { - {39, 2}, -}; -static arc arcs_13_2[1] = { - {0, 2}, -}; -static state states_13[3] = { - {1, arcs_13_0}, - {1, arcs_13_1}, - {1, arcs_13_2}, -}; -static arc arcs_14_0[1] = { - {40, 1}, -}; -static arc arcs_14_1[1] = { - {0, 1}, -}; -static state states_14[2] = { - {1, arcs_14_0}, - {1, arcs_14_1}, -}; -static arc arcs_15_0[4] = { - {41, 1}, - {42, 1}, - {43, 1}, - {44, 1}, -}; -static arc arcs_15_1[1] = { - {0, 1}, -}; -static state states_15[2] = { - {4, arcs_15_0}, - {1, arcs_15_1}, -}; -static arc arcs_16_0[1] = { - {45, 1}, -}; -static arc arcs_16_1[1] = { - {0, 1}, -}; -static state states_16[2] = { - {1, arcs_16_0}, - {1, arcs_16_1}, -}; -static arc arcs_17_0[1] = { - {46, 1}, -}; -static arc arcs_17_1[1] = { - {0, 1}, -}; -static state states_17[2] = { - {1, arcs_17_0}, - {1, arcs_17_1}, -}; -static arc arcs_18_0[1] = { - {47, 1}, -}; -static arc arcs_18_1[2] = { - {9, 2}, - {0, 1}, -}; -static arc arcs_18_2[1] = { - {0, 2}, -}; -static state states_18[3] = { - {1, arcs_18_0}, - {2, arcs_18_1}, - {1, arcs_18_2}, -}; -static arc arcs_19_0[1] = { - {48, 1}, -}; -static arc arcs_19_1[1] = { - {21, 2}, -}; -static arc arcs_19_2[2] = { - {22, 3}, - {0, 2}, -}; -static arc arcs_19_3[1] = { - {21, 4}, -}; -static arc arcs_19_4[2] = { - {22, 5}, - {0, 4}, -}; -static arc arcs_19_5[1] = { - {21, 6}, -}; -static arc arcs_19_6[1] = { - {0, 6}, -}; -static state states_19[7] = { - {1, arcs_19_0}, - {1, arcs_19_1}, - {2, arcs_19_2}, - {1, arcs_19_3}, - {2, arcs_19_4}, - {1, arcs_19_5}, - {1, arcs_19_6}, -}; -static arc arcs_20_0[2] = { - {49, 1}, - {51, 2}, -}; -static arc arcs_20_1[1] = { - {50, 3}, -}; -static arc arcs_20_2[1] = { - {50, 4}, -}; -static arc arcs_20_3[2] = { - {22, 1}, - {0, 3}, -}; -static arc arcs_20_4[1] = { - {49, 5}, -}; -static arc arcs_20_5[2] = { - {23, 6}, - {12, 7}, -}; -static arc arcs_20_6[1] = { - {0, 6}, -}; -static arc arcs_20_7[2] = { - {22, 8}, - {0, 7}, -}; -static arc arcs_20_8[1] = { - {12, 7}, -}; -static state states_20[9] = { - {2, arcs_20_0}, - {1, arcs_20_1}, - {1, arcs_20_2}, - {2, arcs_20_3}, - {1, arcs_20_4}, - {2, arcs_20_5}, - {1, arcs_20_6}, - {2, arcs_20_7}, - {1, arcs_20_8}, -}; -static arc arcs_21_0[1] = { - {12, 1}, -}; -static arc arcs_21_1[2] = { - {52, 0}, - {0, 1}, -}; -static state states_21[2] = { - {1, arcs_21_0}, - {2, arcs_21_1}, -}; -static arc arcs_22_0[1] = { - {53, 1}, -}; -static arc arcs_22_1[1] = { - {12, 2}, -}; -static arc arcs_22_2[2] = { - {22, 1}, - {0, 2}, -}; -static state states_22[3] = { - {1, arcs_22_0}, - {1, arcs_22_1}, - {2, arcs_22_2}, -}; -static arc arcs_23_0[1] = { - {54, 1}, -}; -static arc arcs_23_1[2] = { - {23, 2}, - {12, 3}, -}; -static arc arcs_23_2[1] = { - {14, 4}, -}; -static arc arcs_23_3[2] = { - {22, 5}, - {14, 4}, -}; -static arc arcs_23_4[1] = { - {55, 6}, -}; -static arc arcs_23_5[1] = { - {12, 3}, -}; -static arc arcs_23_6[2] = { - {22, 4}, - {0, 6}, -}; -static state states_23[7] = { - {1, arcs_23_0}, - {2, arcs_23_1}, - {1, arcs_23_2}, - {2, arcs_23_3}, - {1, arcs_23_4}, - {1, arcs_23_5}, - {2, arcs_23_6}, -}; -static arc arcs_24_0[1] = { - {12, 1}, -}; -static arc arcs_24_1[2] = { - {12, 1}, - {0, 1}, -}; -static state states_24[2] = { - {1, arcs_24_0}, - {2, arcs_24_1}, -}; -static arc arcs_25_0[1] = { - {56, 1}, -}; -static arc arcs_25_1[1] = { - {57, 2}, -}; -static arc arcs_25_2[2] = { - {58, 3}, - {0, 2}, -}; -static arc arcs_25_3[1] = { - {21, 4}, -}; -static arc arcs_25_4[2] = { - {22, 5}, - {0, 4}, -}; -static arc arcs_25_5[1] = { - {21, 6}, -}; -static arc arcs_25_6[1] = { - {0, 6}, -}; -static state states_25[7] = { - {1, arcs_25_0}, - {1, arcs_25_1}, - {2, arcs_25_2}, - {1, arcs_25_3}, - {2, arcs_25_4}, - {1, arcs_25_5}, - {1, arcs_25_6}, -}; -static arc arcs_26_0[6] = { - {59, 1}, - {60, 1}, - {61, 1}, - {62, 1}, - {10, 1}, - {63, 1}, -}; -static arc arcs_26_1[1] = { - {0, 1}, -}; -static state states_26[2] = { - {6, arcs_26_0}, - {1, arcs_26_1}, -}; -static arc arcs_27_0[1] = { - {64, 1}, -}; -static arc arcs_27_1[1] = { - {21, 2}, -}; -static arc arcs_27_2[1] = { - {14, 3}, -}; -static arc arcs_27_3[1] = { - {15, 4}, -}; -static arc arcs_27_4[3] = { - {65, 1}, - {66, 5}, - {0, 4}, -}; -static arc arcs_27_5[1] = { - {14, 6}, -}; -static arc arcs_27_6[1] = { - {15, 7}, -}; -static arc arcs_27_7[1] = { - {0, 7}, -}; -static state states_27[8] = { - {1, arcs_27_0}, - {1, arcs_27_1}, - {1, arcs_27_2}, - {1, arcs_27_3}, - {3, arcs_27_4}, - {1, arcs_27_5}, - {1, arcs_27_6}, - {1, arcs_27_7}, -}; -static arc arcs_28_0[1] = { - {67, 1}, -}; -static arc arcs_28_1[1] = { - {21, 2}, -}; -static arc arcs_28_2[1] = { - {14, 3}, -}; -static arc arcs_28_3[1] = { - {15, 4}, -}; -static arc arcs_28_4[2] = { - {66, 5}, - {0, 4}, -}; -static arc arcs_28_5[1] = { - {14, 6}, -}; -static arc arcs_28_6[1] = { - {15, 7}, -}; -static arc arcs_28_7[1] = { - {0, 7}, -}; -static state states_28[8] = { - {1, arcs_28_0}, - {1, arcs_28_1}, - {1, arcs_28_2}, - {1, arcs_28_3}, - {2, arcs_28_4}, - {1, arcs_28_5}, - {1, arcs_28_6}, - {1, arcs_28_7}, -}; -static arc arcs_29_0[1] = { - {68, 1}, -}; -static arc arcs_29_1[1] = { - {39, 2}, -}; -static arc arcs_29_2[1] = { - {58, 3}, -}; -static arc arcs_29_3[1] = { - {9, 4}, -}; -static arc arcs_29_4[1] = { - {14, 5}, -}; -static arc arcs_29_5[1] = { - {15, 6}, -}; -static arc arcs_29_6[2] = { - {66, 7}, - {0, 6}, -}; -static arc arcs_29_7[1] = { - {14, 8}, -}; -static arc arcs_29_8[1] = { - {15, 9}, -}; -static arc arcs_29_9[1] = { - {0, 9}, -}; -static state states_29[10] = { - {1, arcs_29_0}, - {1, arcs_29_1}, - {1, arcs_29_2}, - {1, arcs_29_3}, - {1, arcs_29_4}, - {1, arcs_29_5}, - {2, arcs_29_6}, - {1, arcs_29_7}, - {1, arcs_29_8}, - {1, arcs_29_9}, -}; -static arc arcs_30_0[1] = { - {69, 1}, -}; -static arc arcs_30_1[1] = { - {14, 2}, -}; -static arc arcs_30_2[1] = { - {15, 3}, -}; -static arc arcs_30_3[2] = { - {70, 4}, - {71, 5}, -}; -static arc arcs_30_4[1] = { - {14, 6}, -}; -static arc arcs_30_5[1] = { - {14, 7}, -}; -static arc arcs_30_6[1] = { - {15, 8}, -}; -static arc arcs_30_7[1] = { - {15, 9}, -}; -static arc arcs_30_8[3] = { - {70, 4}, - {66, 5}, - {0, 8}, -}; -static arc arcs_30_9[1] = { - {0, 9}, -}; -static state states_30[10] = { - {1, arcs_30_0}, - {1, arcs_30_1}, - {1, arcs_30_2}, - {2, arcs_30_3}, - {1, arcs_30_4}, - {1, arcs_30_5}, - {1, arcs_30_6}, - {1, arcs_30_7}, - {3, arcs_30_8}, - {1, arcs_30_9}, -}; -static arc arcs_31_0[1] = { - {72, 1}, -}; -static arc arcs_31_1[2] = { - {21, 2}, - {0, 1}, -}; -static arc arcs_31_2[2] = { - {22, 3}, - {0, 2}, -}; -static arc arcs_31_3[1] = { - {21, 4}, -}; -static arc arcs_31_4[1] = { - {0, 4}, -}; -static state states_31[5] = { - {1, arcs_31_0}, - {2, arcs_31_1}, - {2, arcs_31_2}, - {1, arcs_31_3}, - {1, arcs_31_4}, -}; -static arc arcs_32_0[2] = { - {3, 1}, - {2, 2}, -}; -static arc arcs_32_1[1] = { - {0, 1}, -}; -static arc arcs_32_2[1] = { - {73, 3}, -}; -static arc arcs_32_3[1] = { - {6, 4}, -}; -static arc arcs_32_4[2] = { - {6, 4}, - {74, 1}, -}; -static state states_32[5] = { - {2, arcs_32_0}, - {1, arcs_32_1}, - {1, arcs_32_2}, - {1, arcs_32_3}, - {2, arcs_32_4}, -}; -static arc arcs_33_0[2] = { - {75, 1}, - {77, 2}, -}; -static arc arcs_33_1[2] = { - {76, 3}, - {0, 1}, -}; -static arc arcs_33_2[1] = { - {0, 2}, -}; -static arc arcs_33_3[1] = { - {75, 1}, -}; -static state states_33[4] = { - {2, arcs_33_0}, - {2, arcs_33_1}, - {1, arcs_33_2}, - {1, arcs_33_3}, -}; -static arc arcs_34_0[1] = { - {78, 1}, -}; -static arc arcs_34_1[2] = { - {79, 0}, - {0, 1}, -}; -static state states_34[2] = { - {1, arcs_34_0}, - {2, arcs_34_1}, -}; -static arc arcs_35_0[2] = { - {80, 1}, - {81, 2}, -}; -static arc arcs_35_1[1] = { - {78, 2}, -}; -static arc arcs_35_2[1] = { - {0, 2}, -}; -static state states_35[3] = { - {2, arcs_35_0}, - {1, arcs_35_1}, - {1, arcs_35_2}, -}; -static arc arcs_36_0[1] = { - {57, 1}, -}; -static arc arcs_36_1[2] = { - {82, 0}, - {0, 1}, -}; -static state states_36[2] = { - {1, arcs_36_0}, - {2, arcs_36_1}, -}; -static arc arcs_37_0[10] = { - {83, 1}, - {84, 1}, - {85, 1}, - {86, 1}, - {87, 1}, - {88, 1}, - {89, 1}, - {58, 1}, - {80, 2}, - {90, 3}, -}; -static arc arcs_37_1[1] = { - {0, 1}, -}; -static arc arcs_37_2[1] = { - {58, 1}, -}; -static arc arcs_37_3[2] = { - {80, 1}, - {0, 3}, -}; -static state states_37[4] = { - {10, arcs_37_0}, - {1, arcs_37_1}, - {1, arcs_37_2}, - {2, arcs_37_3}, -}; -static arc arcs_38_0[1] = { - {91, 1}, -}; -static arc arcs_38_1[2] = { - {92, 0}, - {0, 1}, -}; -static state states_38[2] = { - {1, arcs_38_0}, - {2, arcs_38_1}, -}; -static arc arcs_39_0[1] = { - {93, 1}, -}; -static arc arcs_39_1[2] = { - {94, 0}, - {0, 1}, -}; -static state states_39[2] = { - {1, arcs_39_0}, - {2, arcs_39_1}, -}; -static arc arcs_40_0[1] = { - {95, 1}, -}; -static arc arcs_40_1[2] = { - {96, 0}, - {0, 1}, -}; -static state states_40[2] = { - {1, arcs_40_0}, - {2, arcs_40_1}, -}; -static arc arcs_41_0[1] = { - {97, 1}, -}; -static arc arcs_41_1[3] = { - {98, 0}, - {99, 0}, - {0, 1}, -}; -static state states_41[2] = { - {1, arcs_41_0}, - {3, arcs_41_1}, -}; -static arc arcs_42_0[1] = { - {100, 1}, -}; -static arc arcs_42_1[3] = { - {101, 0}, - {102, 0}, - {0, 1}, -}; -static state states_42[2] = { - {1, arcs_42_0}, - {3, arcs_42_1}, -}; -static arc arcs_43_0[1] = { - {103, 1}, -}; -static arc arcs_43_1[4] = { - {23, 0}, - {104, 0}, - {105, 0}, - {0, 1}, -}; -static state states_43[2] = { - {1, arcs_43_0}, - {4, arcs_43_1}, -}; -static arc arcs_44_0[4] = { - {101, 1}, - {102, 1}, - {106, 1}, - {107, 2}, -}; -static arc arcs_44_1[1] = { - {103, 2}, -}; -static arc arcs_44_2[1] = { - {0, 2}, -}; -static state states_44[3] = { - {4, arcs_44_0}, - {1, arcs_44_1}, - {1, arcs_44_2}, -}; -static arc arcs_45_0[1] = { - {108, 1}, -}; -static arc arcs_45_1[3] = { - {109, 1}, - {24, 2}, - {0, 1}, -}; -static arc arcs_45_2[1] = { - {103, 3}, -}; -static arc arcs_45_3[2] = { - {24, 2}, - {0, 3}, -}; -static state states_45[4] = { - {1, arcs_45_0}, - {3, arcs_45_1}, - {1, arcs_45_2}, - {2, arcs_45_3}, -}; -static arc arcs_46_0[7] = { - {16, 1}, - {110, 2}, - {112, 3}, - {115, 4}, - {12, 5}, - {116, 5}, - {117, 6}, -}; -static arc arcs_46_1[2] = { - {9, 7}, - {18, 5}, -}; -static arc arcs_46_2[2] = { - {9, 8}, - {111, 5}, -}; -static arc arcs_46_3[2] = { - {113, 9}, - {114, 5}, -}; -static arc arcs_46_4[1] = { - {9, 10}, -}; -static arc arcs_46_5[1] = { - {0, 5}, -}; -static arc arcs_46_6[2] = { - {117, 6}, - {0, 6}, -}; -static arc arcs_46_7[1] = { - {18, 5}, -}; -static arc arcs_46_8[1] = { - {111, 5}, -}; -static arc arcs_46_9[1] = { - {114, 5}, -}; -static arc arcs_46_10[1] = { - {115, 5}, -}; -static state states_46[11] = { - {7, arcs_46_0}, - {2, arcs_46_1}, - {2, arcs_46_2}, - {2, arcs_46_3}, - {1, arcs_46_4}, - {1, arcs_46_5}, - {2, arcs_46_6}, - {1, arcs_46_7}, - {1, arcs_46_8}, - {1, arcs_46_9}, - {1, arcs_46_10}, -}; -static arc arcs_47_0[1] = { - {118, 1}, -}; -static arc arcs_47_1[2] = { - {17, 2}, - {14, 3}, -}; -static arc arcs_47_2[1] = { - {14, 3}, -}; -static arc arcs_47_3[1] = { - {21, 4}, -}; -static arc arcs_47_4[1] = { - {0, 4}, -}; -static state states_47[5] = { - {1, arcs_47_0}, - {2, arcs_47_1}, - {1, arcs_47_2}, - {1, arcs_47_3}, - {1, arcs_47_4}, -}; -static arc arcs_48_0[3] = { - {16, 1}, - {110, 2}, - {52, 3}, -}; -static arc arcs_48_1[2] = { - {119, 4}, - {18, 5}, -}; -static arc arcs_48_2[1] = { - {120, 6}, -}; -static arc arcs_48_3[1] = { - {12, 5}, -}; -static arc arcs_48_4[1] = { - {18, 5}, -}; -static arc arcs_48_5[1] = { - {0, 5}, -}; -static arc arcs_48_6[1] = { - {111, 5}, -}; -static state states_48[7] = { - {3, arcs_48_0}, - {2, arcs_48_1}, - {1, arcs_48_2}, - {1, arcs_48_3}, - {1, arcs_48_4}, - {1, arcs_48_5}, - {1, arcs_48_6}, -}; -static arc arcs_49_0[2] = { - {21, 1}, - {14, 2}, -}; -static arc arcs_49_1[3] = { - {22, 3}, - {14, 2}, - {0, 1}, -}; -static arc arcs_49_2[2] = { - {21, 4}, - {0, 2}, -}; -static arc arcs_49_3[2] = { - {21, 5}, - {0, 3}, -}; -static arc arcs_49_4[1] = { - {0, 4}, -}; -static arc arcs_49_5[2] = { - {22, 3}, - {0, 5}, -}; -static state states_49[6] = { - {2, arcs_49_0}, - {3, arcs_49_1}, - {2, arcs_49_2}, - {2, arcs_49_3}, - {1, arcs_49_4}, - {2, arcs_49_5}, -}; -static arc arcs_50_0[1] = { - {57, 1}, -}; -static arc arcs_50_1[2] = { - {22, 2}, - {0, 1}, -}; -static arc arcs_50_2[2] = { - {57, 1}, - {0, 2}, -}; -static state states_50[3] = { - {1, arcs_50_0}, - {2, arcs_50_1}, - {2, arcs_50_2}, -}; -static arc arcs_51_0[1] = { - {21, 1}, -}; -static arc arcs_51_1[2] = { - {22, 2}, - {0, 1}, -}; -static arc arcs_51_2[2] = { - {21, 1}, - {0, 2}, -}; -static state states_51[3] = { - {1, arcs_51_0}, - {2, arcs_51_1}, - {2, arcs_51_2}, -}; -static arc arcs_52_0[1] = { - {21, 1}, -}; -static arc arcs_52_1[1] = { - {14, 2}, -}; -static arc arcs_52_2[1] = { - {21, 3}, -}; -static arc arcs_52_3[2] = { - {22, 4}, - {0, 3}, -}; -static arc arcs_52_4[2] = { - {21, 1}, - {0, 4}, -}; -static state states_52[5] = { - {1, arcs_52_0}, - {1, arcs_52_1}, - {1, arcs_52_2}, - {2, arcs_52_3}, - {2, arcs_52_4}, -}; -static arc arcs_53_0[1] = { - {121, 1}, -}; -static arc arcs_53_1[1] = { - {12, 2}, -}; -static arc arcs_53_2[2] = { - {16, 3}, - {14, 4}, -}; -static arc arcs_53_3[1] = { - {9, 5}, -}; -static arc arcs_53_4[1] = { - {15, 6}, -}; -static arc arcs_53_5[1] = { - {18, 7}, -}; -static arc arcs_53_6[1] = { - {0, 6}, -}; -static arc arcs_53_7[1] = { - {14, 4}, -}; -static state states_53[8] = { - {1, arcs_53_0}, - {1, arcs_53_1}, - {2, arcs_53_2}, - {1, arcs_53_3}, - {1, arcs_53_4}, - {1, arcs_53_5}, - {1, arcs_53_6}, - {1, arcs_53_7}, -}; -static arc arcs_54_0[1] = { - {122, 1}, -}; -static arc arcs_54_1[2] = { - {22, 2}, - {0, 1}, -}; -static arc arcs_54_2[2] = { - {122, 1}, - {0, 2}, -}; -static state states_54[3] = { - {1, arcs_54_0}, - {2, arcs_54_1}, - {2, arcs_54_2}, -}; -static arc arcs_55_0[1] = { - {21, 1}, -}; -static arc arcs_55_1[2] = { - {20, 2}, - {0, 1}, -}; -static arc arcs_55_2[1] = { - {21, 3}, -}; -static arc arcs_55_3[1] = { - {0, 3}, -}; -static state states_55[4] = { - {1, arcs_55_0}, - {2, arcs_55_1}, - {1, arcs_55_2}, - {1, arcs_55_3}, -}; -static dfa dfas[56] = { - {256, "single_input", 0, 3, states_0, - "\004\030\001\000\140\341\153\001\071\000\001\000\140\104\171\002"}, - {257, "file_input", 0, 2, states_1, - "\204\030\001\000\140\341\153\001\071\000\001\000\140\104\171\002"}, - {258, "eval_input", 0, 3, states_2, - "\000\020\001\000\000\000\000\000\000\000\001\000\140\104\171\000"}, - {259, "funcdef", 0, 6, states_3, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {260, "parameters", 0, 4, states_4, - "\000\000\001\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {261, "varargslist", 0, 11, states_5, - "\000\020\201\001\000\000\000\000\000\000\000\000\000\000\000\000"}, - {262, "fpdef", 0, 4, states_6, - "\000\020\001\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {263, "fplist", 0, 3, states_7, - "\000\020\001\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {264, "stmt", 0, 2, states_8, - "\000\030\001\000\140\341\153\001\071\000\001\000\140\104\171\002"}, - {265, "simple_stmt", 0, 4, states_9, - "\000\020\001\000\140\341\153\001\000\000\001\000\140\104\171\000"}, - {266, "small_stmt", 0, 2, states_10, - "\000\020\001\000\140\341\153\001\000\000\001\000\140\104\171\000"}, - {267, "expr_stmt", 0, 2, states_11, - "\000\020\001\000\000\000\000\000\000\000\001\000\140\104\171\000"}, - {268, "print_stmt", 0, 3, states_12, - "\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000"}, - {269, "del_stmt", 0, 3, states_13, - "\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000"}, - {270, "pass_stmt", 0, 2, states_14, - "\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000"}, - {271, "flow_stmt", 0, 2, states_15, - "\000\000\000\000\000\340\001\000\000\000\000\000\000\000\000\000"}, - {272, "break_stmt", 0, 2, states_16, - "\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, - {273, "continue_stmt", 0, 2, states_17, - "\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000"}, - {274, "return_stmt", 0, 3, states_18, - "\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000"}, - {275, "raise_stmt", 0, 7, states_19, - "\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, - {276, "import_stmt", 0, 9, states_20, - "\000\000\000\000\000\000\012\000\000\000\000\000\000\000\000\000"}, - {277, "dotted_name", 0, 2, states_21, - "\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {278, "global_stmt", 0, 3, states_22, - "\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000"}, - {279, "access_stmt", 0, 7, states_23, - "\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, - {280, "accesstype", 0, 2, states_24, - "\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {281, "exec_stmt", 0, 7, states_25, - "\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, - {282, "compound_stmt", 0, 2, states_26, - "\000\010\000\000\000\000\000\000\071\000\000\000\000\000\000\002"}, - {283, "if_stmt", 0, 8, states_27, - "\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"}, - {284, "while_stmt", 0, 8, states_28, - "\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000"}, - {285, "for_stmt", 0, 10, states_29, - "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000"}, - {286, "try_stmt", 0, 10, states_30, - "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"}, - {287, "except_clause", 0, 5, states_31, - "\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000"}, - {288, "suite", 0, 5, states_32, - "\004\020\001\000\140\341\153\001\000\000\001\000\140\104\171\000"}, - {289, "test", 0, 4, states_33, - "\000\020\001\000\000\000\000\000\000\000\001\000\140\104\171\000"}, - {290, "and_test", 0, 2, states_34, - "\000\020\001\000\000\000\000\000\000\000\001\000\140\104\071\000"}, - {291, "not_test", 0, 3, states_35, - "\000\020\001\000\000\000\000\000\000\000\001\000\140\104\071\000"}, - {292, "comparison", 0, 2, states_36, - "\000\020\001\000\000\000\000\000\000\000\000\000\140\104\071\000"}, - {293, "comp_op", 0, 4, states_37, - "\000\000\000\000\000\000\000\004\000\000\371\007\000\000\000\000"}, - {294, "expr", 0, 2, states_38, - "\000\020\001\000\000\000\000\000\000\000\000\000\140\104\071\000"}, - {295, "xor_expr", 0, 2, states_39, - "\000\020\001\000\000\000\000\000\000\000\000\000\140\104\071\000"}, - {296, "and_expr", 0, 2, states_40, - "\000\020\001\000\000\000\000\000\000\000\000\000\140\104\071\000"}, - {297, "shift_expr", 0, 2, states_41, - "\000\020\001\000\000\000\000\000\000\000\000\000\140\104\071\000"}, - {298, "arith_expr", 0, 2, states_42, - "\000\020\001\000\000\000\000\000\000\000\000\000\140\104\071\000"}, - {299, "term", 0, 2, states_43, - "\000\020\001\000\000\000\000\000\000\000\000\000\140\104\071\000"}, - {300, "factor", 0, 3, states_44, - "\000\020\001\000\000\000\000\000\000\000\000\000\140\104\071\000"}, - {301, "power", 0, 4, states_45, - "\000\020\001\000\000\000\000\000\000\000\000\000\000\100\071\000"}, - {302, "atom", 0, 11, states_46, - "\000\020\001\000\000\000\000\000\000\000\000\000\000\100\071\000"}, - {303, "lambdef", 0, 5, states_47, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\100\000"}, - {304, "trailer", 0, 7, states_48, - "\000\000\001\000\000\000\020\000\000\000\000\000\000\100\000\000"}, - {305, "subscript", 0, 6, states_49, - "\000\120\001\000\000\000\000\000\000\000\001\000\140\104\171\000"}, - {306, "exprlist", 0, 3, states_50, - "\000\020\001\000\000\000\000\000\000\000\000\000\140\104\071\000"}, - {307, "testlist", 0, 3, states_51, - "\000\020\001\000\000\000\000\000\000\000\001\000\140\104\171\000"}, - {308, "dictmaker", 0, 5, states_52, - "\000\020\001\000\000\000\000\000\000\000\001\000\140\104\171\000"}, - {309, "classdef", 0, 8, states_53, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, - {310, "arglist", 0, 3, states_54, - "\000\020\001\000\000\000\000\000\000\000\001\000\140\104\171\000"}, - {311, "argument", 0, 4, states_55, - "\000\020\001\000\000\000\000\000\000\000\001\000\140\104\171\000"}, -}; -static label labels[123] = { - {0, "EMPTY"}, - {256, 0}, - {4, 0}, - {265, 0}, - {282, 0}, - {257, 0}, - {264, 0}, - {0, 0}, - {258, 0}, - {307, 0}, - {259, 0}, - {1, "def"}, - {1, 0}, - {260, 0}, - {11, 0}, - {288, 0}, - {7, 0}, - {261, 0}, - {8, 0}, - {262, 0}, - {22, 0}, - {289, 0}, - {12, 0}, - {16, 0}, - {36, 0}, - {263, 0}, - {266, 0}, - {13, 0}, - {267, 0}, - {268, 0}, - {269, 0}, - {270, 0}, - {271, 0}, - {276, 0}, - {278, 0}, - {279, 0}, - {281, 0}, - {1, "print"}, - {1, "del"}, - {306, 0}, - {1, "pass"}, - {272, 0}, - {273, 0}, - {274, 0}, - {275, 0}, - {1, "break"}, - {1, "continue"}, - {1, "return"}, - {1, "raise"}, - {1, "import"}, - {277, 0}, - {1, "from"}, - {23, 0}, - {1, "global"}, - {1, "access"}, - {280, 0}, - {1, "exec"}, - {294, 0}, - {1, "in"}, - {283, 0}, - {284, 0}, - {285, 0}, - {286, 0}, - {309, 0}, - {1, "if"}, - {1, "elif"}, - {1, "else"}, - {1, "while"}, - {1, "for"}, - {1, "try"}, - {287, 0}, - {1, "finally"}, - {1, "except"}, - {5, 0}, - {6, 0}, - {290, 0}, - {1, "or"}, - {303, 0}, - {291, 0}, - {1, "and"}, - {1, "not"}, - {292, 0}, - {293, 0}, - {20, 0}, - {21, 0}, - {28, 0}, - {31, 0}, - {30, 0}, - {29, 0}, - {29, 0}, - {1, "is"}, - {295, 0}, - {18, 0}, - {296, 0}, - {33, 0}, - {297, 0}, - {19, 0}, - {298, 0}, - {34, 0}, - {35, 0}, - {299, 0}, - {14, 0}, - {15, 0}, - {300, 0}, - {17, 0}, - {24, 0}, - {32, 0}, - {301, 0}, - {302, 0}, - {304, 0}, - {9, 0}, - {10, 0}, - {26, 0}, - {308, 0}, - {27, 0}, - {25, 0}, - {2, 0}, - {3, 0}, - {1, "lambda"}, - {310, 0}, - {305, 0}, - {1, "class"}, - {311, 0}, -}; -grammar gram = { - 56, - dfas, - {123, labels}, - 256 -}; diff --git a/Python/import.c b/Python/import.c deleted file mode 100644 index 53a7ba4930..0000000000 --- a/Python/import.c +++ /dev/null @@ -1,1047 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Module definition and import implementation */ - -#include "allobjects.h" - -/* XXX Some of the following are duplicate with allobjects.h... */ -#include "node.h" -#include "token.h" -#include "graminit.h" -#include "import.h" -#include "errcode.h" -#include "sysmodule.h" -#include "bltinmodule.h" -#include "pythonrun.h" -#include "marshal.h" -#include "compile.h" -#include "eval.h" -#include "osdefs.h" -#include "importdl.h" -#ifdef macintosh -/* 'argument' is a grammar symbol, but also used in some mac header files */ -#undef argument -#include "macglue.h" -#endif - -extern long getmtime(); /* In getmtime.c */ - -/* Magic word to reject .pyc files generated by other Python versions */ -/* Change for each incompatible change */ -/* The value of CR and LF is incorporated so if you ever read or write - a .pyc file in text mode the magic number will be wrong; also, the - Apple MPW compiler swaps their values, botching string constants */ -/* XXX Perhaps the magic number should be frozen and a version field - added to the .pyc file header? */ -#define MAGIC (11913 | ((long)'\r'<<16) | ((long)'\n'<<24)) - -object *import_modules; /* This becomes sys.modules */ - - -/* Initialize things */ - -void -initimport() -{ - if (import_modules != NULL) - fatal("duplicate initimport() call"); - if ((import_modules = newdictobject()) == NULL) - fatal("no mem for dictionary of modules"); -} - - -/* Un-initialize things, as good as we can */ - -void -doneimport() -{ - if (import_modules != NULL) { - object *tmp = import_modules; - import_modules = NULL; - /* This deletes all modules from sys.modules. - When a module is deallocated, it in turn clears its dictionary, - thus hopefully breaking any circular references between modules - and between a module's dictionary and its functions. - Note that "import" will fail while we are cleaning up. - */ - mappingclear(tmp); - DECREF(tmp); - } -} - - -/* Helper for pythonrun.c -- return magic number */ - -long -get_pyc_magic() -{ - return MAGIC; -} - - -/* Helper for sysmodule.c -- return modules dictionary */ - -object * -get_modules() -{ - return import_modules; -} - - -/* Get the module object corresponding to a module name. - First check the modules dictionary if there's one there, - if not, create a new one and insert in in the modules dictionary. - Because the former action is most common, THIS DOES NOT RETURN A - 'NEW' REFERENCE! */ - -object * -add_module(name) - char *name; -{ - object *m; - - if (import_modules == NULL) { - err_setstr(SystemError, "sys.modules has been deleted"); - return NULL; - } - if ((m = dictlookup(import_modules, name)) != NULL && - is_moduleobject(m)) - return m; - m = newmoduleobject(name); - if (m == NULL) - return NULL; - if (dictinsert(import_modules, name, m) != 0) { - DECREF(m); - return NULL; - } - DECREF(m); /* Yes, it still exists, in modules! */ - - return m; -} - - -/* Execute a code object in a module and return the module object - WITH INCREMENTED REFERENCE COUNT */ - -object * -exec_code_module(name, co) - char *name; - object *co; -{ - object *m, *d, *v; - - m = add_module(name); - if (m == NULL) - return NULL; - d = getmoduledict(m); - if (dictlookup(d, "__builtins__") == NULL) { - if (dictinsert(d, "__builtins__", getbuiltins()) != 0) - return NULL; - } - /* Remember the filename as the __file__ attribute */ - if (dictinsert(d, "__file__", ((codeobject *)co)->co_filename) != 0) - err_clear(); /* Not important enough to report */ - v = eval_code((codeobject *)co, d, d); /* XXX owner? */ - if (v == NULL) - return NULL; - DECREF(v); - INCREF(m); - - return m; -} - - -/* Given a pathname for a Python source file, fill a buffer with the - pathname for the corresponding compiled file. Return the pathname - for the compiled file, or NULL if there's no space in the buffer. - Doesn't set an exception. */ - -static char * -make_compiled_pathname(pathname, buf, buflen) - char *pathname; - char *buf; - int buflen; -{ - int len; - - len = strlen(pathname); - if (len+2 > buflen) - return NULL; - strcpy(buf, pathname); - strcpy(buf+len, "c"); - - return buf; -} - - -/* Given a pathname for a Python source file, its time of last - modification, and a pathname for a compiled file, check whether the - compiled file represents the same version of the source. If so, - return a FILE pointer for the compiled file, positioned just after - the header; if not, return NULL. - Doesn't set an exception. */ - -static FILE * -check_compiled_module(pathname, mtime, cpathname) - char *pathname; - long mtime; - char *cpathname; -{ - FILE *fp; - long magic; - long pyc_mtime; - - fp = fopen(cpathname, "rb"); - if (fp == NULL) - return NULL; - magic = rd_long(fp); - if (magic != MAGIC) { - if (verbose) - fprintf(stderr, "# %s has bad magic\n", cpathname); - fclose(fp); - return NULL; - } - pyc_mtime = rd_long(fp); - if (pyc_mtime != mtime) { - if (verbose) - fprintf(stderr, "# %s has bad mtime\n", cpathname); - fclose(fp); - return NULL; - } - if (verbose) - fprintf(stderr, "# %s matches %s\n", cpathname, pathname); - return fp; -} - - -/* Read a code object from a file and check it for validity */ - -static codeobject * -read_compiled_module(fp) - FILE *fp; -{ - object *co; - - co = rd_object(fp); - /* Ugly: rd_object() may return NULL with or without error */ - if (co == NULL || !is_codeobject(co)) { - if (!err_occurred()) - err_setstr(ImportError, - "Non-code object in .pyc file"); - XDECREF(co); - return NULL; - } - return (codeobject *)co; -} - - -/* Load a module from a compiled file, execute it, and return its - module object WITH INCREMENTED REFERENCE COUNT */ - -static object * -load_compiled_module(name, cpathname, fp) - char *name; - char *cpathname; - FILE *fp; -{ - long magic; - codeobject *co; - object *m; - - magic = rd_long(fp); - if (magic != MAGIC) { - err_setstr(ImportError, "Bad magic number in .pyc file"); - return NULL; - } - (void) rd_long(fp); - co = read_compiled_module(fp); - if (co == NULL) - return NULL; - if (verbose) - fprintf(stderr, "import %s # precompiled from %s\n", - name, cpathname); - m = exec_code_module(name, (object *)co); - DECREF(co); - - return m; -} - -/* Parse a source file and return the corresponding code object */ - -static codeobject * -parse_source_module(pathname, fp) - char *pathname; - FILE *fp; -{ - codeobject *co; - node *n; - - n = parse_file(fp, pathname, file_input); - if (n == NULL) - return NULL; - co = compile(n, pathname); - freetree(n); - - return co; -} - - -/* Write a compiled module to a file, placing the time of last - modification of its source into the header. - Errors are ignored, if a write error occurs an attempt is made to - remove the file. */ - -static void -write_compiled_module(co, cpathname, mtime) - codeobject *co; - char *cpathname; - long mtime; -{ - FILE *fp; - - fp = fopen(cpathname, "wb"); - if (fp == NULL) { - if (verbose) - fprintf(stderr, - "# can't create %s\n", cpathname); - return; - } - wr_long(MAGIC, fp); - /* First write a 0 for mtime */ - wr_long(0L, fp); - wr_object((object *)co, fp); - if (ferror(fp)) { - if (verbose) - fprintf(stderr, "# can't write %s\n", cpathname); - /* Don't keep partial file */ - fclose(fp); - (void) unlink(cpathname); - return; - } - /* Now write the true mtime */ - fseek(fp, 4L, 0); - wr_long(mtime, fp); - fflush(fp); - fclose(fp); - if (verbose) - fprintf(stderr, "# wrote %s\n", cpathname); -#ifdef macintosh - setfiletype(cpathname, 'Pyth', 'PYC '); -#endif -} - - -/* Load a source module from a given file and return its module - object WITH INCREMENTED REFERENCE COUNT. If there's a matching - byte-compiled file, use that instead. */ - -static object * -load_source_module(name, pathname, fp) - char *name; - char *pathname; - FILE *fp; -{ - long mtime; - FILE *fpc; - char buf[MAXPATHLEN+1]; - char *cpathname; - codeobject *co; - object *m; - - mtime = getmtime(pathname); - cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1); - if (cpathname != NULL && - (fpc = check_compiled_module(pathname, mtime, cpathname))) { - co = read_compiled_module(fpc); - fclose(fpc); - if (co == NULL) - return NULL; - if (verbose) - fprintf(stderr, "import %s # precompiled from %s\n", - name, cpathname); - } - else { - co = parse_source_module(pathname, fp); - if (co == NULL) - return NULL; - if (verbose) - fprintf(stderr, "import %s # from %s\n", - name, pathname); - write_compiled_module(co, cpathname, mtime); - } - m = exec_code_module(name, (object *)co); - DECREF(co); - - return m; -} - - -/* Search the path (default sys.path) for a module. Return the - corresponding filedescr struct, and (via return arguments) the - pathname and an open file. Return NULL if the module is not found. */ - -static struct filedescr * -find_module(name, path, buf, buflen, p_fp) - char *name; - object *path; - /* Output parameters: */ - char *buf; - int buflen; - FILE **p_fp; -{ - int i, npath, len, namelen; - struct filedescr *fdp; - FILE *fp = NULL; - -#ifdef NT - if ((fp=PyWin_FindRegisteredModule(name, &fdp, buf, buflen))!=NULL) { - *p_fp = fp; - return fdp; - } -#endif - - - if (path == NULL) - path = sysget("path"); - if (path == NULL || !is_listobject(path)) { - err_setstr(ImportError, - "sys.path must be a list of directory names"); - return NULL; - } - npath = getlistsize(path); - namelen = strlen(name); - for (i = 0; i < npath; i++) { - object *v = getlistitem(path, i); - if (!is_stringobject(v)) - continue; - len = getstringsize(v); - if (len + 2 + namelen + import_maxsuffixsize >= buflen) - continue; /* Too long */ - strcpy(buf, getstringvalue(v)); - if (strlen(buf) != len) - continue; /* v contains '\0' */ -#ifdef macintosh - if ( PyMac_FindResourceModule(name, buf) ) { - static struct filedescr resfiledescr = { "", "", PY_RESOURCE}; - - return &resfiledescr; - } -#endif - if (len > 0 && buf[len-1] != SEP) - buf[len++] = SEP; -#ifdef IMPORT_8x3_NAMES - /* see if we are searching in directory dos_8x3 */ - if (len > 7 && !strncmp(buf + len - 8, "dos_8x3", 7)){ - int j; - char ch; /* limit name to eight lower-case characters */ - for (j = 0; (ch = name[j]) && j < 8; j++) - if (isupper(ch)) - buf[len++] = tolower(ch); - else - buf[len++] = ch; - } - else{ /* Not in dos_8x3, use the full name */ - strcpy(buf+len, name); - len += namelen; - } -#else - strcpy(buf+len, name); - len += namelen; -#endif - for (fdp = import_filetab; fdp->suffix != NULL; fdp++) { - strcpy(buf+len, fdp->suffix); - if (verbose > 1) - fprintf(stderr, "# trying %s\n", buf); - fp = fopen(buf, fdp->mode); - if (fp != NULL) - break; - } - if (fp != NULL) - break; - } - if (fp == NULL) { - char buf[256]; - sprintf(buf, "No module named %.200s", name); - err_setstr(ImportError, buf); - return NULL; - } - - *p_fp = fp; - return fdp; -} - - -/* Load an external module using the default search path and return - its module object WITH INCREMENTED REFERENCE COUNT */ - -static object * -load_module(name) - char *name; -{ - char buf[MAXPATHLEN+1]; - struct filedescr *fdp; - FILE *fp = NULL; - object *m; - - fdp = find_module(name, (object *)NULL, buf, MAXPATHLEN+1, &fp); - if (fdp == NULL) - return NULL; - - switch (fdp->type) { - - case PY_SOURCE: - m = load_source_module(name, buf, fp); - break; - - case PY_COMPILED: - m = load_compiled_module(name, buf, fp); - break; - - case C_EXTENSION: - m = load_dynamic_module(name, buf, fp); - break; - -#ifdef macintosh - case PY_RESOURCE: - m = PyMac_LoadResourceModule(name, buf); - break; -#endif - - default: - err_setstr(SystemError, - "find_module returned unexpected result"); - m = NULL; - - } - if ( fp ) - fclose(fp); - - return m; -} - - -/* Initialize a built-in module. - Return 1 for succes, 0 if the module is not found, and -1 with - an exception set if the initialization failed. */ - -static int -init_builtin(name) - char *name; -{ - int i; - for (i = 0; inittab[i].name != NULL; i++) { - if (strcmp(name, inittab[i].name) == 0) { - if (inittab[i].initfunc == NULL) { - err_setstr(ImportError, - "Cannot re-init internal module"); - return -1; - } - if (verbose) - fprintf(stderr, "import %s # builtin\n", - name); - (*inittab[i].initfunc)(); - if (err_occurred()) - return -1; - return 1; - } - } - return 0; -} - - -/* Frozen modules */ - -extern struct frozen { - char *name; - char *code; - int size; -} frozen_modules[]; - -static struct frozen * -find_frozen(name) - char *name; -{ - struct frozen *p; - - for (p = frozen_modules; ; p++) { - if (p->name == NULL) - return NULL; - if (strcmp(p->name, name) == 0) - break; - } - return p; -} - -static object * -get_frozen_object(name) - char *name; -{ - struct frozen *p = find_frozen(name); - - if (p == NULL) { - err_setstr(ImportError, "No such frozen object"); - return NULL; - } - return rds_object(p->code, p->size); -} - -/* Initialize a frozen module. - Return 1 for succes, 0 if the module is not found, and -1 with - an exception set if the initialization failed. - This function is also used from frozenmain.c */ - -int -init_frozen(name) - char *name; -{ - struct frozen *p = find_frozen(name); - object *co; - object *m; - - if (p == NULL) - return 0; - if (verbose) - fprintf(stderr, "import %s # frozen\n", name); - co = rds_object(p->code, p->size); - if (co == NULL) - return -1; - if (!is_codeobject(co)) { - DECREF(co); - err_setstr(TypeError, "frozen object is not a code object"); - return -1; - } - m = exec_code_module(name, co); - DECREF(co); - if (m == NULL) - return -1; - DECREF(m); - return 1; -} - - -/* Import a module, either built-in, frozen, or external, and return - its module object WITH INCREMENTED REFERENCE COUNT */ - -object * -import_module(name) - char *name; -{ - object *m; - - if (import_modules == NULL) { - err_setstr(SystemError, "sys.modules has been deleted"); - return NULL; - } - if ((m = dictlookup(import_modules, name)) != NULL) { - INCREF(m); - } - else { - int i; - if ((i = init_builtin(name)) || (i = init_frozen(name))) { - if (i < 0) - return NULL; - if ((m = dictlookup(import_modules, name)) == NULL) { - if (err_occurred() == NULL) - err_setstr(SystemError, - "built-in module not initialized properly"); - } - else - INCREF(m); - } - else - m = load_module(name); - } - - return m; -} - - -/* Re-import a module of any kind and return its module object, WITH - INCREMENTED REFERENCE COUNT */ - -object * -reload_module(m) - object *m; -{ - char *name; - int i; - - if (m == NULL || !is_moduleobject(m)) { - err_setstr(TypeError, "reload() argument must be module"); - return NULL; - } - name = getmodulename(m); - if (name == NULL) - return NULL; - if (import_modules == NULL) { - err_setstr(SystemError, "sys.modules has been deleted"); - return NULL; - } - if (m != dictlookup(import_modules, name)) { - err_setstr(ImportError, "reload() module not in sys.modules"); - return NULL; - } - /* Check for built-in and frozen modules */ - if ((i = init_builtin(name)) || (i = init_frozen(name))) { - if (i < 0) - return NULL; - INCREF(m); - } - else - m = load_module(name); - return m; -} - - -/* Module 'imp' provides Python access to the primitives used for - importing modules. -*/ - -static object * -imp_get_magic(self, args) - object *self; - object *args; -{ - char buf[4]; - - if (!newgetargs(args, "")) - return NULL; - buf[0] = (MAGIC >> 0) & 0xff; - buf[1] = (MAGIC >> 8) & 0xff; - buf[2] = (MAGIC >> 16) & 0xff; - buf[3] = (MAGIC >> 24) & 0xff; - - return newsizedstringobject(buf, 4); -} - -static object * -imp_get_suffixes(self, args) - object *self; - object *args; -{ - object *list; - struct filedescr *fdp; - - if (!newgetargs(args, "")) - return NULL; - list = newlistobject(0); - if (list == NULL) - return NULL; - for (fdp = import_filetab; fdp->suffix != NULL; fdp++) { - object *item = mkvalue("ssi", - fdp->suffix, fdp->mode, fdp->type); - if (item == NULL) { - DECREF(list); - return NULL; - } - if (addlistitem(list, item) < 0) { - DECREF(list); - DECREF(item); - return NULL; - } - DECREF(item); - } - return list; -} - -static object * -imp_find_module(self, args) - object *self; - object *args; -{ - extern int fclose PROTO((FILE *)); - char *name; - object *path = NULL; - object *fob, *ret; - struct filedescr *fdp; - char pathname[MAXPATHLEN+1]; - FILE *fp; - if (!newgetargs(args, "s|O!", &name, &Listtype, &path)) - return NULL; - fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp); - if (fdp == NULL) - return NULL; - fob = newopenfileobject(fp, pathname, fdp->mode, fclose); - if (fob == NULL) { - fclose(fp); - return NULL; - } - ret = mkvalue("Os(ssi)", - fob, pathname, fdp->suffix, fdp->mode, fdp->type); - DECREF(fob); - return ret; -} - -static object * -imp_init_builtin(self, args) - object *self; - object *args; -{ - char *name; - int ret; - object *m; - if (!newgetargs(args, "s", &name)) - return NULL; - ret = init_builtin(name); - if (ret < 0) - return NULL; - if (ret == 0) { - INCREF(None); - return None; - } - m = add_module(name); - XINCREF(m); - return m; -} - -static object * -imp_init_frozen(self, args) - object *self; - object *args; -{ - char *name; - int ret; - object *m; - if (!newgetargs(args, "s", &name)) - return NULL; - ret = init_frozen(name); - if (ret < 0) - return NULL; - if (ret == 0) { - INCREF(None); - return None; - } - m = add_module(name); - XINCREF(m); - return m; -} - -static object * -imp_get_frozen_object(self, args) - object *self; - object *args; -{ - char *name; - - if (!newgetargs(args, "s", &name)) - return NULL; - return get_frozen_object(name); -} - -static object * -imp_is_builtin(self, args) - object *self; - object *args; -{ - int i; - char *name; - if (!newgetargs(args, "s", &name)) - return NULL; - for (i = 0; inittab[i].name != NULL; i++) { - if (strcmp(name, inittab[i].name) == 0) { - if (inittab[i].initfunc == NULL) - return newintobject(-1); - else - return newintobject(1); - } - } - return newintobject(0); -} - -static object * -imp_is_frozen(self, args) - object *self; - object *args; -{ - struct frozen *p; - char *name; - if (!newgetargs(args, "s", &name)) - return NULL; - for (p = frozen_modules; ; p++) { - if (p->name == NULL) - break; - if (strcmp(p->name, name) == 0) - return newintobject(1); - } - return newintobject(0); -} - -static FILE * -get_file(pathname, fob, mode) - char *pathname; - object *fob; - char *mode; -{ - FILE *fp; - if (fob == NULL) { - fp = fopen(pathname, mode); - if (fp == NULL) - err_errno(IOError); - } - else { - fp = getfilefile(fob); - if (fp == NULL) - err_setstr(ValueError, "bad/closed file object"); - } - return fp; -} - -static object * -imp_load_compiled(self, args) - object *self; - object *args; -{ - char *name; - char *pathname; - object *fob = NULL; - object *m; - FILE *fp; - if (!newgetargs(args, "ssO!", &name, &pathname, &Filetype, &fob)) - return NULL; - fp = get_file(pathname, fob, "rb"); - if (fp == NULL) - return NULL; - m = load_compiled_module(name, pathname, fp); - return m; -} - -static object * -imp_load_dynamic(self, args) - object *self; - object *args; -{ - char *name; - char *pathname; - object *fob = NULL; - object *m; - FILE *fp = NULL; - if (!newgetargs(args, "ss|O!", &name, &pathname, &Filetype, &fob)) - return NULL; - if (fob) - fp = get_file(pathname, fob, "r"); - m = load_dynamic_module(name, pathname, fp); - return m; -} - -static object * -imp_load_source(self, args) - object *self; - object *args; -{ - char *name; - char *pathname; - object *fob = NULL; - object *m; - FILE *fp; - if (!newgetargs(args, "ssO!", &name, &pathname, &Filetype, &fob)) - return NULL; - fp = get_file(pathname, fob, "r"); - if (fp == NULL) - return NULL; - m = load_source_module(name, pathname, fp); - return m; -} - -#ifdef macintosh -static object * -imp_load_resource(self, args) - object *self; - object *args; -{ - char *name; - char *pathname; - object *m; - - if (!newgetargs(args, "ss", &name, &pathname)) - return NULL; - m = PyMac_LoadResourceModule(name, pathname); - return m; -} -#endif /* macintosh */ - -static object * -imp_new_module(self, args) - object *self; - object *args; -{ - char *name; - if (!newgetargs(args, "s", &name)) - return NULL; - return newmoduleobject(name); -} - -static struct methodlist imp_methods[] = { - {"get_frozen_object", imp_get_frozen_object, 1}, - {"get_magic", imp_get_magic, 1}, - {"get_suffixes", imp_get_suffixes, 1}, - {"find_module", imp_find_module, 1}, - {"init_builtin", imp_init_builtin, 1}, - {"init_frozen", imp_init_frozen, 1}, - {"is_builtin", imp_is_builtin, 1}, - {"is_frozen", imp_is_frozen, 1}, - {"load_compiled", imp_load_compiled, 1}, - {"load_dynamic", imp_load_dynamic, 1}, - {"load_source", imp_load_source, 1}, - {"new_module", imp_new_module, 1}, -#ifdef macintosh - {"load_resource", imp_load_resource, 1}, -#endif - {NULL, NULL} /* sentinel */ -}; - -void -initimp() -{ - object *m, *d, *v; - - m = initmodule("imp", imp_methods); - d = getmoduledict(m); - - v = newintobject(SEARCH_ERROR); - dictinsert(d, "SEARCH_ERROR", v); - XDECREF(v); - - v = newintobject(PY_SOURCE); - dictinsert(d, "PY_SOURCE", v); - XDECREF(v); - - v = newintobject(PY_COMPILED); - dictinsert(d, "PY_COMPILED", v); - XDECREF(v); - - v = newintobject(C_EXTENSION); - dictinsert(d, "C_EXTENSION", v); - XDECREF(v); - -#ifdef macintosh - v = newintobject(PY_RESOURCE); - dictinsert(d, "PY_RESOURCE", v); - XDECREF(v); -#endif - - - if (err_occurred()) - fatal("imp module initialization failed"); -} diff --git a/Python/importdl.c b/Python/importdl.c deleted file mode 100644 index 832f02276e..0000000000 --- a/Python/importdl.c +++ /dev/null @@ -1,539 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Support for dynamic loading of extension modules */ -/* If no dynamic linking is supported, this file still generates some code! */ - -#include "allobjects.h" -#include "osdefs.h" -#include "importdl.h" - -/* Explanation of some of the the various #defines used by dynamic linking... - - symbol -- defined for: - - DYNAMIC_LINK -- any kind of dynamic linking - USE_RLD -- NeXT dynamic linking - USE_DL -- Jack's dl for IRIX 4 or GNU dld with emulation for Jack's dl - USE_SHLIB -- SunOS or IRIX 5 (SVR4?) shared libraries - _AIX -- AIX style dynamic linking - NT -- NT style dynamic linking (using DLLs) - WIN16_DL -- Windows 16-bit dynamic linking (using DLLs) - _DL_FUNCPTR_DEFINED -- if the typedef dl_funcptr has been defined - USE_MAC_DYNAMIC_LOADING -- Mac CFM shared libraries - SHORT_EXT -- short extension for dynamic module, e.g. ".so" - LONG_EXT -- long extension, e.g. "module.so" - hpux -- HP-UX Dynamic Linking - defined by the compiler - __NetBSD__ -- NetBSD shared libraries (not quite SVR4 compatible) - __FreeBSD__ -- FreeBSD shared libraries - - (The other WITH_* symbols are used only once, to set the - appropriate symbols.) -*/ - -/* Configure dynamic linking */ - -#ifdef __hpux -#define hpux -#endif - -#ifdef hpux -#define DYNAMIC_LINK -#include <errno.h> -typedef void (*dl_funcptr)(); -#define _DL_FUNCPTR_DEFINED 1 -#define SHORT_EXT ".sl" -#define LONG_EXT "module.sl" -#endif - -#if defined(__NetBSD__) || defined(__FreeBSD__) -#define DYNAMIC_LINK -#define USE_SHLIB - -#define dlerror() "error in dynamic linking" -#endif - -#ifdef __WIN32__ -#define NT -#endif - -#ifdef MS_WIN16 -#define WIN16_DL -#endif - -#if defined(NT) || defined(WIN16_DL) -#define DYNAMIC_LINK -#include <windows.h> -typedef FARPROC dl_funcptr; -#define _DL_FUNCPTR_DEFINED -#define SHORT_EXT ".pyd" -#define LONG_EXT ".dll" -#endif - -#ifdef NeXT -#define DYNAMIC_LINK -#define USE_RLD -#endif - -#ifdef WITH_SGI_DL -#define DYNAMIC_LINK -#define USE_DL -#endif - -#ifdef WITH_DL_DLD -#define DYNAMIC_LINK -#define USE_DL -#endif - -#ifdef __CFM68K__ -#define USE_MAC_DYNAMIC_LOADING -#endif - -#ifdef USE_MAC_DYNAMIC_LOADING -#define DYNAMIC_LINK -#define SHORT_EXT ".slb" -#define LONG_EXT "module.slb" -#ifndef _DL_FUNCPTR_DEFINED -typedef void (*dl_funcptr)(); -#endif -#endif - -#if !defined(DYNAMIC_LINK) && defined(HAVE_DLFCN_H) && defined(HAVE_DLOPEN) -#define DYNAMIC_LINK -#define USE_SHLIB -#endif - -#ifdef _AIX -#define DYNAMIC_LINK -#include <sys/ldr.h> -typedef void (*dl_funcptr)(); -#define _DL_FUNCPTR_DEFINED -static void aix_loaderror(char *name); -#endif - -#ifdef DYNAMIC_LINK - -#ifdef USE_SHLIB -#include <sys/types.h> -#include <sys/stat.h> -#if defined(__NetBSD__) || defined(__FreeBSD__) -#include <nlist.h> -#include <link.h> -#else -#include <dlfcn.h> -#endif -#ifndef _DL_FUNCPTR_DEFINED -typedef void (*dl_funcptr)(); -#endif -#ifndef RTLD_LAZY -#define RTLD_LAZY 1 -#endif -#define SHORT_EXT ".so" -#define LONG_EXT "module.so" -#endif /* USE_SHLIB */ - -#if defined(USE_DL) || defined(hpux) -#include "dl.h" -#endif - -#ifdef USE_MAC_DYNAMIC_LOADING -#include <Aliases.h> -#include <CodeFragments.h> -#ifdef SYMANTEC__CFM68K__ /* Really just an older version of Universal Headers */ -#define CFragConnectionID ConnectionID -#define kLoadCFrag 0x01 -#endif -#include <Files.h> -#include "macdefs.h" -#include "macglue.h" -#endif - -#ifdef USE_RLD -#include <mach-o/rld.h> -#define FUNCNAME_PATTERN "_init%.200s" -#ifndef _DL_FUNCPTR_DEFINED -typedef void (*dl_funcptr)(); -#endif -#endif /* USE_RLD */ - -extern char *getprogramname(); - -#ifndef FUNCNAME_PATTERN -#if defined(__hp9000s300) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__BORLANDC__) -#define FUNCNAME_PATTERN "_init%.200s" -#else -#define FUNCNAME_PATTERN "init%.200s" -#endif -#endif - -#if !defined(SHORT_EXT) && !defined(LONG_EXT) -#define SHORT_EXT ".o" -#define LONG_EXT "module.o" -#endif /* !SHORT_EXT && !LONG_EXT */ - -#endif /* DYNAMIC_LINK */ - -/* Max length of module suffix searched for -- accommodates "module.slb" */ -#ifndef MAXSUFFIXSIZE -#define MAXSUFFIXSIZE 12 -#endif - -/* Pass it on to import.c */ -int import_maxsuffixsize = MAXSUFFIXSIZE; - -struct filedescr import_filetab[] = { -#ifdef SHORT_EXT - {SHORT_EXT, "rb", C_EXTENSION}, -#endif /* !SHORT_EXT */ -#ifdef LONG_EXT - {LONG_EXT, "rb", C_EXTENSION}, -#endif /* !LONG_EXT */ - {".py", "r", PY_SOURCE}, - {".pyc", "rb", PY_COMPILED}, - {0, 0} -}; - -object * -load_dynamic_module(name, pathname, fp) - char *name; - char *pathname; - FILE *fp; -{ -#ifndef DYNAMIC_LINK - err_setstr(ImportError, "dynamically linked modules not supported"); - return NULL; -#else - object *m; - char funcname[258]; - dl_funcptr p = NULL; -#ifdef USE_SHLIB - static struct { - dev_t dev; - ino_t ino; - void *handle; - } handles[128]; - static int nhandles = 0; -#endif - sprintf(funcname, FUNCNAME_PATTERN, name); -#ifdef USE_SHLIB - if (fp != NULL) { - int i; - struct stat statb; - fstat(fileno(fp), &statb); - for (i = 0; i < nhandles; i++) { - if (statb.st_dev == handles[i].dev && - statb.st_ino == handles[i].ino) { - p = (dl_funcptr) dlsym(handles[i].handle, - funcname); - goto got_it; - } - } - if (nhandles < 128) { - handles[nhandles].dev = statb.st_dev; - handles[nhandles].ino = statb.st_ino; - } - } -#endif /* USE_SHLIB */ -#ifdef USE_MAC_DYNAMIC_LOADING - /* - ** Dynamic loading of CFM shared libraries on the Mac. - ** The code has become more convoluted than it was, because we want to be able - ** to put multiple modules in a single file. For this reason, we have to determine - ** the fragment name, and we cannot use the library entry point but we have to locate - ** the correct init routine "by hand". - */ - { - FSSpec libspec; - CFragConnectionID connID; - Ptr mainAddr; - Str255 errMessage; - OSErr err; - Boolean isfolder, didsomething; - char buf[512]; - Str63 fragname; - Ptr symAddr; - CFragSymbolClass class; - - /* First resolve any aliases to find the real file */ - (void)FSMakeFSSpec(0, 0, Pstring(pathname), &libspec); - err = ResolveAliasFile(&libspec, 1, &isfolder, &didsomething); - if ( err ) { - sprintf(buf, "%s: %s", pathname, PyMac_StrError(err)); - err_setstr(ImportError, buf); - return NULL; - } - /* Next, determine the fragment name, by stripping '.slb' and 'module' */ - memcpy(fragname+1, libspec.name+1, libspec.name[0]); - fragname[0] = libspec.name[0]; - if( strncmp((char *)(fragname+1+fragname[0]-4), ".slb", 4) == 0 ) - fragname[0] -= 4; - if ( strncmp((char *)(fragname+1+fragname[0]-6), "module", 6) == 0 ) - fragname[0] -= 6; - /* Load the fragment (or return the connID if it is already loaded */ - err = GetDiskFragment(&libspec, 0, 0, fragname, - kLoadCFrag, &connID, &mainAddr, - errMessage); - if ( err ) { - sprintf(buf, "%.*s: %s", errMessage[0], errMessage+1, PyMac_StrError(err)); - err_setstr(ImportError, buf); - return NULL; - } - /* Locate the address of the correct init function */ - err = FindSymbol(connID, Pstring(funcname), &symAddr, &class); - if ( err ) { - sprintf(buf, "%s: %s", funcname, PyMac_StrError(err)); - err_setstr(ImportError, buf); - return NULL; - } - p = (dl_funcptr)symAddr; - } -#endif /* USE_MAC_DYNAMIC_LOADING */ -#ifdef USE_SHLIB - { -#ifdef RTLD_NOW - /* RTLD_NOW: resolve externals now - (i.e. core dump now if some are missing) */ - void *handle = dlopen(pathname, RTLD_NOW); -#else - void *handle; - if (verbose) - printf("dlopen(\"%s\", %d);\n", pathname, RTLD_LAZY); - handle = dlopen(pathname, RTLD_LAZY); -#endif /* RTLD_NOW */ - if (handle == NULL) { - err_setstr(ImportError, dlerror()); - return NULL; - } - if (fp != NULL && nhandles < 128) - handles[nhandles++].handle = handle; - p = (dl_funcptr) dlsym(handle, funcname); - } -#endif /* USE_SHLIB */ -#ifdef _AIX - p = (dl_funcptr) load(pathname, 1, 0); - if (p == NULL) { - aix_loaderror(pathname); - return NULL; - } -#endif /* _AIX */ -#ifdef NT - { - HINSTANCE hDLL; - hDLL = LoadLibrary(pathname); - if (hDLL==NULL){ - char errBuf[256]; - unsigned int errorCode; - - /* Get an error string from Win32 error code */ - char theInfo[256]; /* Pointer to error text from system */ - int theLength; /* Length of error text */ - - errorCode = GetLastError(); - - theLength = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, /* flags */ - NULL, /* message source */ - errorCode, /* the message (error) ID */ - 0, /* default language environment */ - (LPTSTR) theInfo, /* the buffer */ - sizeof(theInfo), /* the buffer size */ - NULL); /* no additional format args. */ - - /* Problem: could not get the error message. This should not happen if called correctly. */ - if (theLength == 0) { - sprintf(errBuf, "DLL load failed with error code %d", errorCode); - } else { - int len; - /* For some reason a \r\n is appended to the text */ - if (theLength >= 2 && theInfo[theLength-2] == '\r' && theInfo[theLength-1] == '\n') { - theLength -= 2; - theInfo[theLength] = '\0'; - } - strcpy(errBuf, "DLL load failed: "); - len = strlen(errBuf); - strncpy(errBuf+len, theInfo, sizeof(errBuf)-len); - errBuf[sizeof(errBuf)-1] = '\0'; - } - err_setstr(ImportError, errBuf); - return NULL; - } - p = GetProcAddress(hDLL, funcname); - } -#endif /* NT */ -#ifdef WIN16_DL - { - HINSTANCE hDLL; - hDLL = LoadLibrary(pathname); - if (hDLL < HINSTANCE_ERROR){ - char errBuf[256]; - sprintf(errBuf, "DLL load failed with error code %d", hDLL); - err_setstr(ImportError, errBuf); - return NULL; - } - p = GetProcAddress(hDLL, funcname); - } -#endif /* WIN16_DL */ -#ifdef USE_DL - p = dl_loadmod(getprogramname(), pathname, funcname); -#endif /* USE_DL */ -#ifdef USE_RLD - { - NXStream *errorStream; - struct mach_header *new_header; - const char *filenames[2]; - long ret; - unsigned long ptr; - - errorStream = NXOpenMemory(NULL, 0, NX_WRITEONLY); - filenames[0] = pathname; - filenames[1] = NULL; - ret = rld_load(errorStream, &new_header, - filenames, NULL); - - /* extract the error messages for the exception */ - if(!ret) { - char *streamBuf; - int len, maxLen; - - NXPutc(errorStream, (char)0); - - NXGetMemoryBuffer(errorStream, - &streamBuf, &len, &maxLen); - err_setstr(ImportError, streamBuf); - } - - if(ret && rld_lookup(errorStream, funcname, &ptr)) - p = (dl_funcptr) ptr; - - NXCloseMemory(errorStream, NX_FREEBUFFER); - - if(!ret) - return NULL; - } -#endif /* USE_RLD */ -#ifdef hpux - { - shl_t lib; - int flags; - - flags = BIND_DEFERRED; - if (verbose) - { - flags = BIND_IMMEDIATE | BIND_NONFATAL | BIND_VERBOSE; - printf("shl_load %s\n",pathname); - } - lib = shl_load(pathname, flags, 0); - if (lib == NULL) - { - char buf[256]; - if (verbose) - perror(pathname); - sprintf(buf, "Failed to load %.200s", pathname); - err_setstr(ImportError, buf); - return NULL; - } - if (verbose) - printf("shl_findsym %s\n", funcname); - shl_findsym(&lib, funcname, TYPE_UNDEFINED, (void *) &p); - if (p == NULL && verbose) - perror(funcname); - } -#endif /* hpux */ - got_it: - if (p == NULL) { - err_setstr(ImportError, - "dynamic module does not define init function"); - return NULL; - } - (*p)(); - - m = dictlookup(import_modules, name); - if (m == NULL) { - if (err_occurred() == NULL) - err_setstr(SystemError, - "dynamic module not initialized properly"); - return NULL; - } - if (verbose) - fprintf(stderr, - "import %s # dynamically loaded from %s\n", - name, pathname); - INCREF(m); - return m; -#endif /* DYNAMIC_LINK */ -} - - -#ifdef _AIX - -#include <ctype.h> /* for isdigit() */ -#include <errno.h> /* for global errno */ -#include <string.h> /* for strerror() */ - -void aix_loaderror(char *pathname) -{ - - char *message[8], errbuf[1024]; - int i,j; - - struct errtab { - int errno; - char *errstr; - } load_errtab[] = { - {L_ERROR_TOOMANY, "too many errors, rest skipped."}, - {L_ERROR_NOLIB, "can't load library:"}, - {L_ERROR_UNDEF, "can't find symbol in library:"}, - {L_ERROR_RLDBAD, - "RLD index out of range or bad relocation type:"}, - {L_ERROR_FORMAT, "not a valid, executable xcoff file:"}, - {L_ERROR_MEMBER, - "file not an archive or does not contain requested member:"}, - {L_ERROR_TYPE, "symbol table mismatch:"}, - {L_ERROR_ALIGN, "text allignment in file is wrong."}, - {L_ERROR_SYSTEM, "System error:"}, - {L_ERROR_ERRNO, NULL} - }; - -#define LOAD_ERRTAB_LEN (sizeof(load_errtab)/sizeof(load_errtab[0])) -#define ERRBUF_APPEND(s) strncat(errbuf, s, sizeof(errbuf)-strlen(errbuf)-1) - - sprintf(errbuf, " from module %.200s ", pathname); - - if (!loadquery(1, &message[0], sizeof(message))) - ERRBUF_APPEND(strerror(errno)); - for(i = 0; message[i] && *message[i]; i++) { - int nerr = atoi(message[i]); - for (j=0; j<LOAD_ERRTAB_LEN ; j++) { - if (nerr == load_errtab[i].errno && load_errtab[i].errstr) - ERRBUF_APPEND(load_errtab[i].errstr); - } - while (isdigit(*message[i])) message[i]++ ; - ERRBUF_APPEND(message[i]); - ERRBUF_APPEND("\n"); - } - errbuf[strlen(errbuf)-1] = '\0'; /* trim off last newline */ - err_setstr(ImportError, errbuf); - return; -} - -#endif /* _AIX */ diff --git a/Python/importdl.h b/Python/importdl.h deleted file mode 100644 index 8dbf55f5d3..0000000000 --- a/Python/importdl.h +++ /dev/null @@ -1,42 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Definitions for dynamic loading of extension modules */ -#ifdef macintosh -enum filetype {SEARCH_ERROR, PY_SOURCE, PY_COMPILED, C_EXTENSION, PY_RESOURCE}; -#else -enum filetype {SEARCH_ERROR, PY_SOURCE, PY_COMPILED, C_EXTENSION}; -#endif - -extern struct filedescr { - char *suffix; - char *mode; - enum filetype type; -} import_filetab[]; - -extern object *import_modules; - -extern object *load_dynamic_module PROTO((char *name, char *pathname, FILE *)); - -extern int import_maxsuffixsize; diff --git a/Python/marshal.c b/Python/marshal.c deleted file mode 100644 index 916faa77e4..0000000000 --- a/Python/marshal.c +++ /dev/null @@ -1,633 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Write Python objects to files and read them back. - This is intended for writing and reading compiled Python code only; - a true persistent storage facility would be much harder, since - it would have to take circular links and sharing into account. */ - -#include "allobjects.h" -#include "modsupport.h" -#include "longintrepr.h" -#include "compile.h" -#include "marshal.h" - -#include <errno.h> - -#define TYPE_NULL '0' -#define TYPE_NONE 'N' -#define TYPE_INT 'i' -#define TYPE_FLOAT 'f' -#define TYPE_COMPLEX 'x' -#define TYPE_LONG 'l' -#define TYPE_STRING 's' -#define TYPE_TUPLE '(' -#define TYPE_LIST '[' -#define TYPE_DICT '{' -#define TYPE_CODE 'c' -#define TYPE_UNKNOWN '?' - -typedef struct { - FILE *fp; - /* If fp == NULL, the following are valid: */ - object *str; - char *ptr; - char *end; -} WFILE; - -#define w_byte(c, p) if (((p)->fp)) putc((c), (p)->fp); \ - else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \ - else w_more(c, p) - -static void -w_more(c, p) - char c; - WFILE *p; -{ - int size, newsize; - if (p->str == NULL) - return; /* An error already occurred */ - size = getstringsize(p->str); - newsize = size + 1024; - if (resizestring(&p->str, newsize) != 0) { - p->ptr = p->end = NULL; - } - else { - p->ptr = GETSTRINGVALUE((stringobject *)p->str) + size; - p->end = GETSTRINGVALUE((stringobject *)p->str) + newsize; - *p->ptr++ = c; - } -} - -static void -w_string(s, n, p) - char *s; - int n; - WFILE *p; -{ - if (p->fp != NULL) { - fwrite(s, 1, n, p->fp); - } - else { - while (--n >= 0) { - w_byte(*s, p); - s++; - } - } -} - -static void -w_short(x, p) - int x; - WFILE *p; -{ - w_byte( x & 0xff, p); - w_byte((x>> 8) & 0xff, p); -} - -static void -w_long(x, p) - long x; - WFILE *p; -{ - w_byte((int)( x & 0xff), p); - w_byte((int)((x>> 8) & 0xff), p); - w_byte((int)((x>>16) & 0xff), p); - w_byte((int)((x>>24) & 0xff), p); -} - -static void -w_object(v, p) - object *v; - WFILE *p; -{ - int i, n; - - if (v == NULL) - w_byte(TYPE_NULL, p); - else if (v == None) - w_byte(TYPE_NONE, p); - else if (is_intobject(v)) { - w_byte(TYPE_INT, p); - w_long(getintvalue(v), p); - } - else if (is_longobject(v)) { - longobject *ob = (longobject *)v; - w_byte(TYPE_LONG, p); - n = ob->ob_size; - w_long((long)n, p); - if (n < 0) - n = -n; - for (i = 0; i < n; i++) - w_short(ob->ob_digit[i], p); - } - else if (is_floatobject(v)) { - extern void float_buf_repr PROTO((char *, floatobject *)); - char buf[256]; /* Plenty to format any double */ - float_buf_repr(buf, (floatobject *)v); - n = strlen(buf); - w_byte(TYPE_FLOAT, p); - w_byte(n, p); - w_string(buf, n, p); - } -#ifndef WITHOUT_COMPLEX - else if (is_complexobject(v)) { - extern void float_buf_repr PROTO((char *, floatobject *)); - char buf[256]; /* Plenty to format any double */ - floatobject *temp; - w_byte(TYPE_COMPLEX, p); - temp = (floatobject*)newfloatobject(PyComplex_RealAsDouble(v)); - float_buf_repr(buf, temp); - DECREF(temp); - n = strlen(buf); - w_byte(n, p); - w_string(buf, n, p); - temp = (floatobject*)newfloatobject(PyComplex_ImagAsDouble(v)); - float_buf_repr(buf, temp); - DECREF(temp); - n = strlen(buf); - w_byte(n, p); - w_string(buf, n, p); - } -#endif - else if (is_stringobject(v)) { - w_byte(TYPE_STRING, p); - n = getstringsize(v); - w_long((long)n, p); - w_string(getstringvalue(v), n, p); - } - else if (is_tupleobject(v)) { - w_byte(TYPE_TUPLE, p); - n = gettuplesize(v); - w_long((long)n, p); - for (i = 0; i < n; i++) { - w_object(GETTUPLEITEM(v, i), p); - } - } - else if (is_listobject(v)) { - w_byte(TYPE_LIST, p); - n = getlistsize(v); - w_long((long)n, p); - for (i = 0; i < n; i++) { - w_object(getlistitem(v, i), p); - } - } - else if (is_dictobject(v)) { - int pos; - object *key, *value; - w_byte(TYPE_DICT, p); - /* This one is NULL object terminated! */ - pos = 0; - while (mappinggetnext(v, &pos, &key, &value)) { - w_object(key, p); - w_object(value, p); - } - w_object((object *)NULL, p); - } - else if (is_codeobject(v)) { - codeobject *co = (codeobject *)v; - w_byte(TYPE_CODE, p); - w_short(co->co_argcount, p); - w_short(co->co_nlocals, p); - w_short(co->co_flags, p); - w_object((object *)co->co_code, p); - w_object(co->co_consts, p); - w_object(co->co_names, p); - w_object(co->co_varnames, p); - w_object(co->co_filename, p); - w_object(co->co_name, p); - } - else { - w_byte(TYPE_UNKNOWN, p); - } -} - -void -wr_long(x, fp) - long x; - FILE *fp; -{ - WFILE wf; - wf.fp = fp; - w_long(x, &wf); -} - -void -wr_object(x, fp) - object *x; - FILE *fp; -{ - WFILE wf; - wf.fp = fp; - w_object(x, &wf); -} - -typedef WFILE RFILE; /* Same struct with different invariants */ - -#define rs_byte(p) (((p)->ptr != (p)->end) ? (unsigned char)*(p)->ptr++ : EOF) - -#define r_byte(p) ((p)->fp ? getc((p)->fp) : rs_byte(p)) - -static int -r_string(s, n, p) - char *s; - int n; - RFILE *p; -{ - if (p->fp != NULL) - return fread(s, 1, n, p->fp); - if (p->end - p->ptr < n) - n = p->end - p->ptr; - memcpy(s, p->ptr, n); - p->ptr += n; - return n; -} - -static int -r_short(p) - RFILE *p; -{ - register short x; - x = r_byte(p); - x |= r_byte(p) << 8; - /* XXX If your short is > 16 bits, add sign-extension here!!! */ - return x; -} - -static long -r_long(p) - RFILE *p; -{ - register long x; - register FILE *fp = p->fp; - if (fp) { - x = getc(fp); - x |= (long)getc(fp) << 8; - x |= (long)getc(fp) << 16; - x |= (long)getc(fp) << 24; - } - else { - x = rs_byte(p); - x |= (long)rs_byte(p) << 8; - x |= (long)rs_byte(p) << 16; - x |= (long)rs_byte(p) << 24; - } - /* XXX If your long is > 32 bits, add sign-extension here!!! */ - return x; -} - -static object * -r_object(p) - RFILE *p; -{ - object *v, *v2; - long i, n; - int type = r_byte(p); - - switch (type) { - - case EOF: - err_setstr(EOFError, "EOF read where object expected"); - return NULL; - - case TYPE_NULL: - return NULL; - - case TYPE_NONE: - INCREF(None); - return None; - - case TYPE_INT: - return newintobject(r_long(p)); - - case TYPE_LONG: - { - int size; - longobject *ob; - n = r_long(p); - size = n<0 ? -n : n; - ob = alloclongobject(size); - if (ob == NULL) - return NULL; - ob->ob_size = n; - for (i = 0; i < size; i++) - ob->ob_digit[i] = r_short(p); - return (object *)ob; - } - - case TYPE_FLOAT: - { - extern double atof PROTO((const char *)); - char buf[256]; - n = r_byte(p); - if (r_string(buf, (int)n, p) != n) { - err_setstr(EOFError, - "EOF read where object expected"); - return NULL; - } - buf[n] = '\0'; - return newfloatobject(atof(buf)); - } - -#ifndef WITHOUT_COMPLEX - case TYPE_COMPLEX: - { - extern double atof PROTO((const char *)); - char buf[256]; - complex c; - n = r_byte(p); - if (r_string(buf, (int)n, p) != n) { - err_setstr(EOFError, - "EOF read where object expected"); - return NULL; - } - buf[n] = '\0'; - c.real = atof(buf); - n = r_byte(p); - if (r_string(buf, (int)n, p) != n) { - err_setstr(EOFError, - "EOF read where object expected"); - return NULL; - } - buf[n] = '\0'; - c.imag = atof(buf); - return newcomplexobject(c); - } -#endif - - case TYPE_STRING: - n = r_long(p); - v = newsizedstringobject((char *)NULL, n); - if (v != NULL) { - if (r_string(getstringvalue(v), (int)n, p) != n) { - DECREF(v); - v = NULL; - err_setstr(EOFError, - "EOF read where object expected"); - } - } - return v; - - case TYPE_TUPLE: - n = r_long(p); - v = newtupleobject((int)n); - if (v == NULL) - return v; - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - DECREF(v); - v = NULL; - break; - } - SETTUPLEITEM(v, (int)i, v2); - } - return v; - - case TYPE_LIST: - n = r_long(p); - v = newlistobject((int)n); - if (v == NULL) - return v; - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - DECREF(v); - v = NULL; - break; - } - setlistitem(v, (int)i, v2); - } - return v; - - case TYPE_DICT: - v = newdictobject(); - if (v == NULL) - return NULL; - for (;;) { - object *key, *val; - key = r_object(p); - if (key == NULL) - break; /* XXXX and how about memory errors? */ - val = r_object(p); - /* XXXX error check? */ - dict2insert(v, key, val); - DECREF(key); - XDECREF(val); - } - return v; - - case TYPE_CODE: - { - int argcount = r_short(p); - int nlocals = r_short(p); - int flags = r_short(p); - object *code = NULL; - object *consts = NULL; - object *names = NULL; - object *varnames = NULL; - object *filename = NULL; - object *name = NULL; - - code = r_object(p); - if (code) consts = r_object(p); - if (consts) names = r_object(p); - if (names) varnames = r_object(p); - if (varnames) filename = r_object(p); - if (filename) name = r_object(p); - - if (!err_occurred()) { - v = (object *) newcodeobject( - argcount, nlocals, flags, - code, consts, names, varnames, - filename, name); - } - else - v = NULL; - XDECREF(code); - XDECREF(consts); - XDECREF(names); - XDECREF(varnames); - XDECREF(filename); - XDECREF(name); - - } - return v; - - default: - err_setstr(TypeError, "read unknown object"); - return NULL; - - } -} - -long -rd_long(fp) - FILE *fp; -{ - RFILE rf; - rf.fp = fp; - return r_long(&rf); -} - -object * -rd_object(fp) - FILE *fp; -{ - RFILE rf; - if (err_occurred()) { - fatal("XXX rd_object called with exception set"); /* tmp */ - fprintf(stderr, "XXX rd_object called with exception set\n"); - return NULL; - } - rf.fp = fp; - return r_object(&rf); -} - -object * -rds_object(str, len) - char *str; - int len; -{ - RFILE rf; - if (err_occurred()) { - fprintf(stderr, "XXX rds_object called with exception set\n"); - return NULL; - } - rf.fp = NULL; - rf.str = NULL; - rf.ptr = str; - rf.end = str + len; - return r_object(&rf); -} - -/* And an interface for Python programs... */ - -static object * -marshal_dump(self, args) - object *self; - object *args; -{ - WFILE wf; - object *x; - object *f; - if (!getargs(args, "(OO)", &x, &f)) - return NULL; - if (!is_fileobject(f)) { - err_setstr(TypeError, "marshal.dump() 2nd arg must be file"); - return NULL; - } - wf.fp = getfilefile(f); - wf.str = NULL; - wf.ptr = wf.end = NULL; - w_object(x, &wf); - INCREF(None); - return None; -} - -static object * -marshal_load(self, args) - object *self; - object *args; -{ - RFILE rf; - object *f; - object *v; - if (!getargs(args, "O", &f)) - return NULL; - if (!is_fileobject(f)) { - err_setstr(TypeError, "marshal.load() arg must be file"); - return NULL; - } - rf.fp = getfilefile(f); - rf.str = NULL; - rf.ptr = rf.end = NULL; - err_clear(); - v = r_object(&rf); - if (err_occurred()) { - XDECREF(v); - v = NULL; - } - return v; -} - -static object * -marshal_dumps(self, args) - object *self; - object *args; -{ - WFILE wf; - object *x; - if (!getargs(args, "O", &x)) - return NULL; - wf.fp = NULL; - wf.str = newsizedstringobject((char *)NULL, 50); - if (wf.str == NULL) - return NULL; - wf.ptr = GETSTRINGVALUE((stringobject *)wf.str); - wf.end = wf.ptr + getstringsize(wf.str); - w_object(x, &wf); - if (wf.str != NULL) - resizestring(&wf.str, - (int) (wf.ptr - GETSTRINGVALUE((stringobject *)wf.str))); - return wf.str; -} - -static object * -marshal_loads(self, args) - object *self; - object *args; -{ - RFILE rf; - object *v; - char *s; - int n; - if (!getargs(args, "s#", &s, &n)) - return NULL; - rf.fp = NULL; - rf.str = args; - rf.ptr = s; - rf.end = s + n; - err_clear(); - v = r_object(&rf); - if (err_occurred()) { - XDECREF(v); - v = NULL; - } - return v; -} - -static struct methodlist marshal_methods[] = { - {"dump", marshal_dump}, - {"load", marshal_load}, - {"dumps", marshal_dumps}, - {"loads", marshal_loads}, - {NULL, NULL} /* sentinel */ -}; - -void -initmarshal() -{ - (void) initmodule("marshal", marshal_methods); -} diff --git a/Python/memmove.c b/Python/memmove.c deleted file mode 100644 index c299d12ba9..0000000000 --- a/Python/memmove.c +++ /dev/null @@ -1,51 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* A perhaps slow but I hope correct implementation of memmove */ - -extern char *memcpy(); - -char * -memmove(dst, src, n) - char *dst; - char *src; - int n; -{ - char *realdst = dst; - if (n <= 0) - return dst; - if (src >= dst+n || dst >= src+n) - return memcpy(dst, src, n); - if (src > dst) { - while (--n >= 0) - *dst++ = *src++; - } - else if (src < dst) { - src += n; - dst += n; - while (--n >= 0) - *--dst = *--src; - } - return realdst; -} diff --git a/Python/modsupport.c b/Python/modsupport.c deleted file mode 100644 index b1aa1b5cc9..0000000000 --- a/Python/modsupport.c +++ /dev/null @@ -1,472 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Module support implementation */ - -#include "allobjects.h" -#include "import.h" - -#ifdef MPW /* MPW pushes 'extended' for float and double types with varargs */ -typedef extended va_double; -#else -typedef double va_double; -#endif - -/* initmodule4() parameters: - - name is the module name - - methods is the list of top-level functions - - doc is the documentation string - - passthrough is passed as self to functions defined in the module - - api_version is the value of PYTHON_API_VERSION at the time the - module was compiled -*/ - -static char api_version_warning[] = -"WARNING: Python C API version mismatch for module %s:\n\ - This Python has API version %d, module %s has version %d.\n"; - -object * -initmodule4(name, methods, doc, passthrough, module_api_version) - char *name; - struct methodlist *methods; - char *doc; - object *passthrough; - int module_api_version; -{ - object *m, *d, *v; - struct methodlist *ml; - if (module_api_version != PYTHON_API_VERSION) - fprintf(stderr, api_version_warning, - name, PYTHON_API_VERSION, name, module_api_version); - if ((m = add_module(name)) == NULL) { - fprintf(stderr, "initializing module: %s\n", name); - fatal("can't create a module"); - } - d = getmoduledict(m); - for (ml = methods; ml->ml_name != NULL; ml++) { - v = newmethodobject(ml, passthrough); - if (v == NULL || dictinsert(d, ml->ml_name, v) != 0) { - fprintf(stderr, "initializing module: %s\n", name); - fatal("can't initialize module"); - } - DECREF(v); - } - if (doc != NULL) { - v = newstringobject(doc); - if (v == NULL || dictinsert(d, "__doc__", v) != 0) - fatal("can't add doc string"); - DECREF(v); - } - return m; -} - - -/* Helper for mkvalue() to scan the length of a format */ - -static int countformat PROTO((char *format, int endchar)); -static int countformat(format, endchar) - char *format; - int endchar; -{ - int count = 0; - int level = 0; - while (level > 0 || *format != endchar) { - switch (*format) { - case '\0': - /* Premature end */ - err_setstr(SystemError, "unmatched paren in format"); - return -1; - case '(': - case '[': - case '{': - if (level == 0) - count++; - level++; - break; - case ')': - case ']': - case '}': - level--; - break; - case '#': - case '&': - case ',': - case ':': - case ' ': - case '\t': - break; - default: - if (level == 0) - count++; - } - format++; - } - return count; -} - - -/* Generic function to create a value -- the inverse of getargs() */ -/* After an original idea and first implementation by Steven Miale */ - -static object *do_mktuple PROTO((char**, va_list *, int, int)); -static object *do_mklist PROTO((char**, va_list *, int, int)); -static object *do_mkdict PROTO((char**, va_list *, int, int)); -static object *do_mkvalue PROTO((char**, va_list *)); - - -static object * -do_mkdict(p_format, p_va, endchar, n) - char **p_format; - va_list *p_va; - int endchar; - int n; -{ - object *d; - int i; - if (n < 0) - return NULL; - if ((d = newdictobject()) == NULL) - return NULL; - for (i = 0; i < n; i+= 2) { - object *k, *v; - k = do_mkvalue(p_format, p_va); - if (k == NULL) { - DECREF(d); - return NULL; - } - v = do_mkvalue(p_format, p_va); - if (v == NULL) { - DECREF(k); - DECREF(d); - return NULL; - } - if (dict2insert(d, k, v) < 0) { - DECREF(k); - DECREF(v); - DECREF(d); - return NULL; - } - } - if (d != NULL && **p_format != endchar) { - DECREF(d); - d = NULL; - err_setstr(SystemError, "Unmatched paren in format"); - } - else if (endchar) - ++*p_format; - return d; -} - -static object * -do_mklist(p_format, p_va, endchar, n) - char **p_format; - va_list *p_va; - int endchar; - int n; -{ - object *v; - int i; - if (n < 0) - return NULL; - if ((v = newlistobject(n)) == NULL) - return NULL; - for (i = 0; i < n; i++) { - object *w = do_mkvalue(p_format, p_va); - if (w == NULL) { - DECREF(v); - return NULL; - } - setlistitem(v, i, w); - } - if (v != NULL && **p_format != endchar) { - DECREF(v); - v = NULL; - err_setstr(SystemError, "Unmatched paren in format"); - } - else if (endchar) - ++*p_format; - return v; -} - -static object * -do_mktuple(p_format, p_va, endchar, n) - char **p_format; - va_list *p_va; - int endchar; - int n; -{ - object *v; - int i; - if (n < 0) - return NULL; - if ((v = newtupleobject(n)) == NULL) - return NULL; - for (i = 0; i < n; i++) { - object *w = do_mkvalue(p_format, p_va); - if (w == NULL) { - DECREF(v); - return NULL; - } - settupleitem(v, i, w); - } - if (v != NULL && **p_format != endchar) { - DECREF(v); - v = NULL; - err_setstr(SystemError, "Unmatched paren in format"); - } - else if (endchar) - ++*p_format; - return v; -} - -static object * -do_mkvalue(p_format, p_va) - char **p_format; - va_list *p_va; -{ - for (;;) { - switch (*(*p_format)++) { - case '(': - return do_mktuple(p_format, p_va, ')', - countformat(*p_format, ')')); - - case '[': - return do_mklist(p_format, p_va, ']', - countformat(*p_format, ']')); - - case '{': - return do_mkdict(p_format, p_va, '}', - countformat(*p_format, '}')); - - case 'b': - case 'h': - case 'i': - return newintobject((long)va_arg(*p_va, int)); - - case 'l': - return newintobject((long)va_arg(*p_va, long)); - - case 'f': - case 'd': - return newfloatobject((double)va_arg(*p_va, va_double)); - - case 'c': - { - char p[1]; - p[0] = va_arg(*p_va, int); - return newsizedstringobject(p, 1); - } - - case 's': - case 'z': - { - object *v; - char *str = va_arg(*p_va, char *); - int n; - if (**p_format == '#') { - ++*p_format; - n = va_arg(*p_va, int); - } - else - n = -1; - if (str == NULL) { - v = None; - INCREF(v); - } - else { - if (n < 0) - n = strlen(str); - v = newsizedstringobject(str, n); - } - return v; - } - - case 'S': - case 'O': - if (**p_format == '&') { - typedef object *(*converter) PROTO((void *)); - converter func = va_arg(*p_va, converter); - void *arg = va_arg(*p_va, void *); - ++*p_format; - return (*func)(arg); - } - else { - object *v; - v = va_arg(*p_va, object *); - if (v != NULL) - INCREF(v); - else if (!err_occurred()) - /* If a NULL was passed - * because a call that should - * have constructed a value - * failed, that's OK, and we - * pass the error on; but if - * no error occurred it's not - * clear that the caller knew - * what she was doing. */ - err_setstr(SystemError, - "NULL object passed to mkvalue"); - return v; - } - - case ':': - case ',': - case ' ': - case '\t': - break; - - default: - err_setstr(SystemError, - "bad format char passed to mkvalue"); - return NULL; - - } - } -} - - -#ifdef HAVE_STDARG_PROTOTYPES -/* VARARGS 2 */ -object *mkvalue(char *format, ...) -#else -/* VARARGS */ -object *mkvalue(va_alist) va_dcl -#endif -{ - va_list va; - object* retval; -#ifdef HAVE_STDARG_PROTOTYPES - va_start(va, format); -#else - char *format; - va_start(va); - format = va_arg(va, char *); -#endif - retval = vmkvalue(format, va); - va_end(va); - return retval; -} - -object * -vmkvalue(format, va) - char *format; - va_list va; -{ - char *f = format; - int n = countformat(f, '\0'); - va_list lva; - -#ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); -#else - lva = va; -#endif - - if (n < 0) - return NULL; - if (n == 0) { - INCREF(None); - return None; - } - if (n == 1) - return do_mkvalue(&f, &lva); - return do_mktuple(&f, &lva, '\0', n); -} - - -#ifdef HAVE_STDARG_PROTOTYPES -object * -PyEval_CallFunction(object *obj, char *format, ...) -#else -object * -PyEval_CallFunction(obj, format, va_alist) - object *obj; - char *format; - va_dcl -#endif -{ - va_list vargs; - object *args; - object *res; - -#ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, format); -#else - va_start(vargs); -#endif - - args = vmkvalue(format, vargs); - va_end(vargs); - - if (args == NULL) - return NULL; - - res = call_object(obj, args); - DECREF(args); - - return res; -} - - -#ifdef HAVE_STDARG_PROTOTYPES -object * -PyEval_CallMethod(object *obj, char *methonname, char *format, ...) -#else -object * -PyEval_CallMethod(obj, methonname, format, va_alist) - object *obj; - char *methonname; - char *format; - va_dcl -#endif -{ - va_list vargs; - object *meth; - object *args; - object *res; - - meth = getattr(obj, methonname); - if (meth == NULL) - return NULL; - -#ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, format); -#else - va_start(vargs); -#endif - - args = vmkvalue(format, vargs); - va_end(vargs); - - if (args == NULL) { - DECREF(meth); - return NULL; - } - - res = call_object(meth, args); - DECREF(meth); - DECREF(args); - - return res; -} diff --git a/Python/mystrtoul.c b/Python/mystrtoul.c deleted file mode 100644 index a646283789..0000000000 --- a/Python/mystrtoul.c +++ /dev/null @@ -1,174 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -/* Convert a possibly signed character to a nonnegative int */ -/* XXX This assumes characters are 8 bits wide */ -#ifdef __CHAR_UNSIGNED__ -#define Py_CHARMASK(c) (c) -#else -#define Py_CHARMASK(c) ((c) & 0xff) -#endif - -#include "rename2.h" - -/* strtol and strtoul, renamed to avoid conflicts */ - -/* -** strtoul -** This is a general purpose routine for converting -** an ascii string to an integer in an arbitrary base. -** Leading white space is ignored. If 'base' is zero -** it looks for a leading 0, 0x or 0X to tell which -** base. If these are absent it defaults to 10. -** Base must be 0 or between 2 and 36 (inclusive). -** If 'ptr' is non-NULL it will contain a pointer to -** the end of the scan. -** Errors due to bad pointers will probably result in -** exceptions - we don't check for them. -*/ - -#include <ctype.h> -#include <errno.h> - -unsigned long -mystrtoul(str, ptr, base) -register char * str; -char ** ptr; -int base; -{ - register unsigned long result; /* return value of the function */ - register int c; /* current input character */ - register unsigned long temp; /* used in overflow testing */ - int ovf; /* true if overflow occurred */ - - result = 0; - ovf = 0; - -/* catch silly bases */ - if (base != 0 && (base < 2 || base > 36)) - { - if (ptr) - *ptr = str; - return 0; - } - -/* skip leading white space */ - while (*str && isspace(Py_CHARMASK(*str))) - str++; - -/* check for leading 0 or 0x for auto-base or base 16 */ - switch (base) - { - case 0: /* look for leading 0, 0x or 0X */ - if (*str == '0') - { - str++; - if (*str == 'x' || *str == 'X') - { - str++; - base = 16; - } - else - base = 8; - } - else - base = 10; - break; - - case 16: /* skip leading 0x or 0X */ - if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X')) - str += 2; - break; - } - -/* do the conversion */ - while (c = Py_CHARMASK(*str)) - { - if (isdigit(c) && c - '0' < base) - c -= '0'; - else - { - if (isupper(c)) - c = tolower(c); - if (c >= 'a' && c <= 'z') - c -= 'a' - 10; - else /* non-"digit" character */ - break; - if (c >= base) /* non-"digit" character */ - break; - } - temp = result; - result = result * base + c; -#ifndef MPW - if ((result - c) / base != temp) /* overflow */ - ovf = 1; -#endif - str++; - } - -/* set pointer to point to the last character scanned */ - if (ptr) - *ptr = str; - if (ovf) - { - result = ~0; - errno = ERANGE; - } - return result; -} - -long -mystrtol(str, ptr, base) -char * str; -char ** ptr; -int base; -{ - long result; - char sign; - - while (*str && isspace(Py_CHARMASK(*str))) - str++; - - sign = *str; - if (sign == '+' || sign == '-') - str++; - - result = (long) mystrtoul(str, ptr, base); - - /* Signal overflow if the result appears negative, - except for the largest negative integer */ - if (result < 0 && !(sign == '-' && result == -result)) { - errno = ERANGE; - result = 0x7fffffff; - } - - if (sign == '-') - result = -result; - - return result; -} diff --git a/Python/pythonmain.c b/Python/pythonmain.c deleted file mode 100644 index 000a3d789f..0000000000 --- a/Python/pythonmain.c +++ /dev/null @@ -1,211 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Python interpreter main program */ - -#include "allobjects.h" - -extern int debugging; /* Needed in parser.c, declared in pythonrun.c */ -extern int verbose; /* Needed in import.c, declared in pythonrun.c */ -extern int suppress_print; /* Needed in ceval.c, declared in pythonrun.c */ - -/* Interface to getopt(): */ -extern int optind; -extern char *optarg; -extern int getopt(); /* PROTO((int, char **, char *)); -- not standardized */ - -extern char *getenv(); - -extern char *getversion(); -extern char *getcopyright(); - -int -realmain(argc, argv) - int argc; - char **argv; -{ - int c; - int sts; - char *command = NULL; - char *filename = NULL; - FILE *fp = stdin; - char *p; - int inspect = 0; - int unbuffered = 0; - - if ((p = getenv("PYTHONDEBUG")) && *p != '\0') - debugging = 1; - if ((p = getenv("PYTHONSUPPRESS")) && *p != '\0') - suppress_print = 1; - if ((p = getenv("PYTHONVERBOSE")) && *p != '\0') - verbose = 1; - if ((p = getenv("PYTHONINSPECT")) && *p != '\0') - inspect = 1; - if ((p = getenv("PYTHONUNBUFFERED")) && *p != '\0') - unbuffered = 1; - -#ifdef macintosh - PyMac_InteractiveOptions(&inspect, &verbose, &suppress_print, &unbuffered, &debugging); -#endif - - while ((c = getopt(argc, argv, "c:disuv")) != EOF) { - if (c == 'c') { - /* -c is the last option; following arguments - that look like options are left for the - the command to interpret. */ - command = malloc(strlen(optarg) + 2); - if (command == NULL) - fatal("not enough memory to copy -c argument"); - strcpy(command, optarg); - strcat(command, "\n"); - break; - } - - switch (c) { - - case 'd': - debugging++; - break; - - case 'i': - inspect++; - break; - - case 's': - suppress_print++; - break; - - case 'u': - unbuffered++; - break; - - case 'v': - verbose++; - break; - - /* This space reserved for other options */ - - default: - fprintf(stderr, -"usage: %s [-d] [-i] [-s] [-u ] [-v] [-c cmd | file | -] [arg] ...\n", - argv[0]); -#if !(defined(__CFM68K__) && defined(__MWERKS__)) - /* Mwerks cfm68k linker doesn't like these... */ - fprintf(stderr, "\ -\n\ -Options and arguments (and corresponding environment variables):\n\ --d : debug output from parser (also PYTHONDEBUG=x)\n\ --i : inspect interactively after running script (also PYTHONINSPECT=x)\n\ --s : suppress the printing of top level expressions (also PYTHONSUPPRESS=x)\n\ --u : unbuffered stdout and stderr (also PYTHONUNBUFFERED=x)\n\ --v : verbose (trace import statements) (also PYTHONVERBOSE=x)\n\ --c cmd : program passed in as string (terminates option list)\n\ -"); - /* ANSI does not allow strings > 512 chars - and MPW doesn't like it either -- so split it! */ - fprintf(stderr, "\ -file : program read from script file\n\ -- : program read from stdin (default; interactive mode if a tty)\n\ -arg ...: arguments passed to program in sys.argv[1:]\n\ -\n\ -Other environment variables:\n\ -PYTHONSTARTUP: file executed on interactive startup (no default)\n\ -PYTHONPATH : colon-separated list of directories prefixed to the\n\ - default module search path. The result is sys.path.\n\ -"); -#endif /* !cfm68k || !mwerks */ - exit(2); - /*NOTREACHED*/ - - } - } - - if (unbuffered) { -#ifndef MPW - setbuf(stdout, (char *)NULL); - setbuf(stderr, (char *)NULL); -#else - /* On MPW (3.2) unbuffered seems to hang */ - setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ); - setvbuf(stderr, (char *)NULL, _IOLBF, BUFSIZ); -#endif - } - - if (command == NULL && optind < argc && strcmp(argv[optind], "-") != 0) - filename = argv[optind]; - - if (verbose || - command == NULL && filename == NULL && isatty((int)fileno(fp))) - fprintf(stderr, "Python %s\n%s\n", - getversion(), getcopyright()); - - if (filename != NULL) { - if ((fp = fopen(filename, "r")) == NULL) { - fprintf(stderr, "%s: can't open file '%s'\n", - argv[0], filename); - exit(2); - } - } - - initall(); - - if (command != NULL) { - /* Backup optind and force sys.argv[0] = '-c' */ - optind--; - argv[optind] = "-c"; - } - - setpythonargv(argc-optind, argv+optind); - - if (command) { - sts = run_command(command) != 0; - } - else { - if (filename == NULL && isatty((int)fileno(fp))) { - char *startup = getenv("PYTHONSTARTUP"); -#ifdef macintosh - if (startup == NULL) - startup = "PythonStartup"; -#endif - if (startup != NULL && startup[0] != '\0') { - FILE *fp = fopen(startup, "r"); - if (fp != NULL) { - (void) run_script(fp, startup); - err_clear(); - fclose(fp); - } - } - } - sts = run(fp, filename == NULL ? "<stdin>" : filename) != 0; - if (filename != NULL) - fclose(fp); - } - - if (inspect && isatty((int)fileno(stdin)) && - (filename != NULL || command != NULL)) - sts = run(stdin, "<stdin>") != 0; - - goaway(sts); - /*NOTREACHED*/ -} diff --git a/Python/pythonrun.c b/Python/pythonrun.c deleted file mode 100644 index 1da9d9e45e..0000000000 --- a/Python/pythonrun.c +++ /dev/null @@ -1,744 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Python interpreter top-level routines, including init/exit */ - -#include "allobjects.h" - -#include "grammar.h" -#include "node.h" -#include "parsetok.h" -#include "graminit.h" -#undef argument /* Avoid conflict on Mac */ -#include "errcode.h" -#include "sysmodule.h" -#include "bltinmodule.h" -#include "compile.h" -#include "eval.h" -#include "ceval.h" -#include "import.h" -#include "marshal.h" - -#ifdef HAVE_SIGNAL_H -#include <signal.h> -#endif - -#ifdef NT -#undef BYTE -#undef arglist -#include "windows.h" -#endif - -extern char *getpythonpath(); - -extern grammar gram; /* From graminit.c */ - -/* Forward */ -static void initmain PROTO((void)); -static object *run_err_node PROTO((node *n, char *filename, - object *globals, object *locals)); -static object *run_node PROTO((node *n, char *filename, - object *globals, object *locals)); -static object *run_pyc_file PROTO((FILE *fp, char *filename, - object *globals, object *locals)); -static void err_input PROTO((perrdetail *)); -static void initsigs PROTO((void)); - -int debugging; /* Needed by parser.c */ -int verbose; /* Needed by import.c */ -int suppress_print; /* Needed by ceval.c */ - -/* Initialize all */ - -void -initall() -{ - static int inited; - - if (inited) - return; - inited = 1; - - initimport(); - - /* Modules '__builtin__' and 'sys' are initialized here, - they are needed by random bits of the interpreter. - All other modules are optional and are initialized - when they are first imported. */ - - initbuiltin(); /* Also initializes builtin exceptions */ - initsys(); - - setpythonpath(getpythonpath()); - - initsigs(); /* Signal handling stuff, including initintr() */ - - initmain(); -} - -/* Create __main__ module */ - -static void -initmain() -{ - object *m, *d; - m = add_module("__main__"); - if (m == NULL) - fatal("can't create __main__ module"); - d = getmoduledict(m); - if (dictlookup(d, "__builtins__") == NULL) { - if (dictinsert(d, "__builtins__", getbuiltins())) - fatal("can't add __builtins__ to __main__"); - } -} - -/* Parse input from a file and execute it */ - -int -run(fp, filename) - FILE *fp; - char *filename; -{ - if (filename == NULL) - filename = "???"; - if (isatty((int)fileno(fp))) - return run_tty_loop(fp, filename); - else - return run_script(fp, filename); -} - -int -run_tty_loop(fp, filename) - FILE *fp; - char *filename; -{ - object *v; - int ret; - v = sysget("ps1"); - if (v == NULL) { - sysset("ps1", v = newstringobject(">>> ")); - XDECREF(v); - } - v = sysget("ps2"); - if (v == NULL) { - sysset("ps2", v = newstringobject("... ")); - XDECREF(v); - } - for (;;) { - ret = run_tty_1(fp, filename); -#ifdef Py_REF_DEBUG - fprintf(stderr, "[%ld refs]\n", _Py_RefTotal); -#endif - if (ret == E_EOF) - return 0; - /* - if (ret == E_NOMEM) - return -1; - */ - } -} - -int -run_tty_1(fp, filename) - FILE *fp; - char *filename; -{ - object *m, *d, *v, *w; - node *n; - perrdetail err; - char *ps1, *ps2; - v = sysget("ps1"); - w = sysget("ps2"); - if (v != NULL && is_stringobject(v)) { - INCREF(v); - ps1 = getstringvalue(v); - } - else { - v = NULL; - ps1 = ""; - } - if (w != NULL && is_stringobject(w)) { - INCREF(w); - ps2 = getstringvalue(w); - } - else { - w = NULL; - ps2 = ""; - } - BGN_SAVE - n = parsefile(fp, filename, &gram, single_input, ps1, ps2, &err); - END_SAVE - XDECREF(v); - XDECREF(w); - if (n == NULL) { - if (err.error == E_EOF) { - if (err.text) - free(err.text); - return E_EOF; - } - err_input(&err); - print_error(); - return err.error; - } - m = add_module("__main__"); - if (m == NULL) - return -1; - d = getmoduledict(m); - v = run_node(n, filename, d, d); - if (v == NULL) { - print_error(); - return -1; - } - DECREF(v); - flushline(); - return 0; -} - -int -run_script(fp, filename) - FILE *fp; - char *filename; -{ - object *m, *d, *v; - char *ext; - - m = add_module("__main__"); - if (m == NULL) - return -1; - d = getmoduledict(m); - ext = filename + strlen(filename) - 4; -#ifdef macintosh - /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */ - if ( strcmp(ext, ".pyc") == 0 || getfiletype(filename) == 'PYC ' || - getfiletype(filename) == 'APPL' ) { -#else - if ( strcmp(ext, ".pyc") == 0 ) { -#endif /* macintosh */ - /* Try to run a pyc file. First, re-open in binary */ - /* Don't close, done in main: fclose(fp); */ - if( (fp = fopen(filename, "rb")) == NULL ) { - fprintf(stderr, "python: Can't reopen .pyc file\n"); - return -1; - } - v = run_pyc_file(fp, filename, d, d); - } else { - v = run_file(fp, filename, file_input, d, d); - } - if (v == NULL) { - print_error(); - return -1; - } - DECREF(v); - flushline(); - return 0; -} - -int -run_command(command) - char *command; -{ - object *m, *d, *v; - m = add_module("__main__"); - if (m == NULL) - return -1; - d = getmoduledict(m); - v = run_string(command, file_input, d, d); - if (v == NULL) { - print_error(); - return -1; - } - DECREF(v); - flushline(); - return 0; -} - -void -print_error() -{ - object *exception, *v, *tb, *f; - err_fetch(&exception, &v, &tb); - flushline(); - fflush(stdout); - if (exception == NULL) - fatal("print_error called but no exception"); - if (exception == SystemExit) { - if (v == NULL || v == None) - goaway(0); - if (is_intobject(v)) - goaway((int)getintvalue(v)); - else { - /* OK to use real stderr here */ - printobject(v, stderr, PRINT_RAW); - fprintf(stderr, "\n"); - goaway(1); - } - } - sysset("last_type", exception); - sysset("last_value", v); - sysset("last_traceback", tb); - f = sysget("stderr"); - if (f == NULL) - fprintf(stderr, "lost sys.stderr\n"); - else { - tb_print(tb, f); - if (exception == SyntaxError) { - object *message; - char *filename, *text; - int lineno, offset; - if (!getargs(v, "(O(ziiz))", &message, - &filename, &lineno, &offset, &text)) - err_clear(); - else { - char buf[10]; - writestring(" File \"", f); - if (filename == NULL) - writestring("<string>", f); - else - writestring(filename, f); - writestring("\", line ", f); - sprintf(buf, "%d", lineno); - writestring(buf, f); - writestring("\n", f); - if (text != NULL) { - char *nl; - if (offset > 0 && - offset == strlen(text)) - offset--; - for (;;) { - nl = strchr(text, '\n'); - if (nl == NULL || - nl-text >= offset) - break; - offset -= (nl+1-text); - text = nl+1; - } - while (*text == ' ' || *text == '\t') { - text++; - offset--; - } - writestring(" ", f); - writestring(text, f); - if (*text == '\0' || - text[strlen(text)-1] != '\n') - writestring("\n", f); - writestring(" ", f); - offset--; - while (offset > 0) { - writestring(" ", f); - offset--; - } - writestring("^\n", f); - } - INCREF(message); - DECREF(v); - v = message; - } - } - if (is_classobject(exception)) { - object* className = ((classobject*)exception)->cl_name; - if (className == NULL) - writestring("<unknown>", f); - else { - if (writeobject(className, f, PRINT_RAW) != 0) - err_clear(); - } - } else { - if (writeobject(exception, f, PRINT_RAW) != 0) - err_clear(); - } - if (v != NULL && v != None) { - writestring(": ", f); - if (writeobject(v, f, PRINT_RAW) != 0) - err_clear(); - } - writestring("\n", f); - } - XDECREF(exception); - XDECREF(v); - XDECREF(tb); -} - -object * -run_string(str, start, globals, locals) - char *str; - int start; - object *globals, *locals; -{ - return run_err_node(parse_string(str, start), - "<string>", globals, locals); -} - -object * -run_file(fp, filename, start, globals, locals) - FILE *fp; - char *filename; - int start; - object *globals, *locals; -{ - return run_err_node(parse_file(fp, filename, start), - filename, globals, locals); -} - -static object * -run_err_node(n, filename, globals, locals) - node *n; - char *filename; - object *globals, *locals; -{ - if (n == NULL) - return NULL; - return run_node(n, filename, globals, locals); -} - -static object * -run_node(n, filename, globals, locals) - node *n; - char *filename; - object *globals, *locals; -{ - codeobject *co; - object *v; - co = compile(n, filename); - freetree(n); - if (co == NULL) - return NULL; - v = eval_code(co, globals, locals); - DECREF(co); - return v; -} - -static object * -run_pyc_file(fp, filename, globals, locals) - FILE *fp; - char *filename; - object *globals, *locals; -{ - codeobject *co; - object *v; - long magic; - long get_pyc_magic(); - - magic = rd_long(fp); - if (magic != get_pyc_magic()) { - err_setstr(RuntimeError, - "Bad magic number in .pyc file"); - return NULL; - } - (void) rd_long(fp); - v = rd_object(fp); - fclose(fp); - if (v == NULL || !is_codeobject(v)) { - XDECREF(v); - err_setstr(RuntimeError, - "Bad code object in .pyc file"); - return NULL; - } - co = (codeobject *)v; - v = eval_code(co, globals, locals); - DECREF(co); - return v; -} - -object * -compile_string(str, filename, start) - char *str; - char *filename; - int start; -{ - node *n; - codeobject *co; - n = parse_string(str, start); - if (n == NULL) - return NULL; - co = compile(n, filename); - freetree(n); - return (object *)co; -} - -/* Simplified interface to parsefile -- return node or set exception */ - -node * -parse_file(fp, filename, start) - FILE *fp; - char *filename; - int start; -{ - node *n; - perrdetail err; - BGN_SAVE - n = parsefile(fp, filename, &gram, start, - (char *)0, (char *)0, &err); - END_SAVE - if (n == NULL) - err_input(&err); - return n; -} - -/* Simplified interface to parsestring -- return node or set exception */ - -node * -parse_string(str, start) - char *str; - int start; -{ - node *n; - perrdetail err; - n = parsestring(str, &gram, start, &err); - if (n == NULL) - err_input(&err); - return n; -} - -/* Set the error appropriate to the given input error code (see errcode.h) */ - -static void -err_input(err) - perrdetail *err; -{ - object *v, *w; - char *msg = NULL; - v = mkvalue("(ziiz)", err->filename, - err->lineno, err->offset, err->text); - if (err->text != NULL) { - free(err->text); - err->text = NULL; - } - switch (err->error) { - case E_SYNTAX: - msg = "invalid syntax"; - break; - case E_TOKEN: - msg = "invalid token"; - - break; - case E_INTR: - err_set(KeyboardInterrupt); - return; - case E_NOMEM: - err_nomem(); - return; - case E_EOF: - msg = "unexpected EOF while parsing"; - break; - default: - fprintf(stderr, "error=%d\n", err->error); - msg = "unknown parsing error"; - break; - } - w = mkvalue("(sO)", msg, v); - XDECREF(v); - err_setval(SyntaxError, w); - XDECREF(w); -} - -/* Print fatal error message and abort */ - -void -fatal(msg) - char *msg; -{ - fprintf(stderr, "Fatal Python error: %s\n", msg); -#ifdef macintosh - for (;;); -#endif -#ifdef NT - OutputDebugString("Fatal Python error:"); - OutputDebugString(msg); - OutputDebugString("\n"); -#endif - abort(); -} - -/* Clean up and exit */ - -#ifdef WITH_THREAD -#include "thread.h" -int threads_started = 0; /* Set by threadmodule.c and maybe others */ -#endif - -#define NEXITFUNCS 32 -static void (*exitfuncs[NEXITFUNCS])(); -static int nexitfuncs = 0; - -int Py_AtExit(func) - void (*func) PROTO((void)); -{ - if (nexitfuncs >= NEXITFUNCS) - return -1; - exitfuncs[nexitfuncs++] = func; - return 0; -} - -void -cleanup() -{ - object *exitfunc = sysget("exitfunc"); - - if (exitfunc) { - object *res; - INCREF(exitfunc); - sysset("exitfunc", (object *)NULL); - res = call_object(exitfunc, (object *)NULL); - if (res == NULL) { - fprintf(stderr, "Error in sys.exitfunc:\n"); - print_error(); - } - DECREF(exitfunc); - } - - flushline(); - - while (nexitfuncs > 0) - (*exitfuncs[--nexitfuncs])(); -} - -#ifdef COUNT_ALLOCS -extern void dump_counts PROTO((void)); -#endif - -void -goaway(sts) - int sts; -{ - cleanup(); - -#ifdef COUNT_ALLOCS - dump_counts(); -#endif - -#ifdef WITH_THREAD - - /* Other threads may still be active, so skip most of the - cleanup actions usually done (these are mostly for - debugging anyway). */ - - (void) save_thread(); -#ifndef NO_EXIT_PROG - if (threads_started) - _exit_prog(sts); - else - exit_prog(sts); -#else /* !NO_EXIT_PROG */ - if (threads_started) - _exit(sts); - else - exit(sts); -#endif /* !NO_EXIT_PROG */ - -#else /* WITH_THREAD */ - - doneimport(); - - err_clear(); - -#ifdef Py_REF_DEBUG - fprintf(stderr, "[%ld refs]\n", _Py_RefTotal); -#endif - -#ifdef Py_TRACE_REFS - if (askyesno("Print left references?")) { - _Py_PrintReferences(stderr); - } -#endif /* Py_TRACE_REFS */ - -#ifdef macintosh - PyMac_Exit(sts); -#else - exit(sts); -#endif -#endif /* WITH_THREAD */ - /*NOTREACHED*/ -} - -#ifdef HAVE_SIGNAL_H -static RETSIGTYPE -sighandler(sig) - int sig; -{ - signal(sig, SIG_DFL); /* Don't catch recursive signals */ - cleanup(); /* Do essential clean-up */ -#ifdef HAVE_GETPID - kill(getpid(), sig); /* Pretend the signal killed us */ -#else - exit(1); -#endif - /*NOTREACHED*/ -} -#endif - -static void -initsigs() -{ - RETSIGTYPE (*t)(); -#ifdef HAVE_SIGNAL_H -#ifdef SIGPIPE - signal(SIGPIPE, SIG_IGN); -#endif -#ifdef SIGHUP - t = signal(SIGHUP, SIG_IGN); - if (t == SIG_DFL) - signal(SIGHUP, sighandler); - else - signal(SIGHUP, t); -#endif -#ifdef SIGTERM - t = signal(SIGTERM, SIG_IGN); - if (t == SIG_DFL) - signal(SIGTERM, sighandler); - else - signal(SIGTERM, t); -#endif -#endif /* HAVE_SIGNAL_H */ - initintr(); /* May imply initsignal() */ -} - -#ifdef Py_TRACE_REFS -/* Ask a yes/no question */ - -int -askyesno(prompt) - char *prompt; -{ - char buf[256]; - - printf("%s [ny] ", prompt); - if (fgets(buf, sizeof buf, stdin) == NULL) - return 0; - return buf[0] == 'y' || buf[0] == 'Y'; -} -#endif - -#ifdef MPW - -/* Check for file descriptor connected to interactive device. - Pretend that stdin is always interactive, other files never. */ - -int -isatty(fd) - int fd; -{ - return fd == fileno(stdin); -} - -#endif diff --git a/Python/sigcheck.c b/Python/sigcheck.c deleted file mode 100644 index 4a4d11d599..0000000000 --- a/Python/sigcheck.c +++ /dev/null @@ -1,43 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Sigcheck is similar to intrcheck() but sets an exception when an - interrupt occurs. It can't be in the intrcheck.c file since that - file (and the whole directory it is in) doesn't know about objects - or exceptions. It can't be in errors.c because it can be - overridden (at link time) by a more powerful version implemented in - signalmodule.c. */ - -#include "allobjects.h" -#include "intrcheck.h" - -/* ARGSUSED */ -int -sigcheck() -{ - if (!intrcheck()) - return 0; - err_set(KeyboardInterrupt); - return -1; -} diff --git a/Python/strerror.c b/Python/strerror.c deleted file mode 100644 index 3f9438a756..0000000000 --- a/Python/strerror.c +++ /dev/null @@ -1,47 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* PD implementation of strerror() for systems that don't have it. - Author: Guido van Rossum, CWI Amsterdam, Oct. 1990, <guido@cwi.nl>. */ - -#include <stdio.h> - -extern int sys_nerr; -extern char *sys_errlist[]; - -char * -strerror(err) - int err; -{ - static char buf[20]; - if (err >= 0 && err < sys_nerr) - return sys_errlist[err]; - sprintf(buf, "Unknown errno %d", err); - return buf; -} - -#ifdef macintosh -int sys_nerr = 0; -char *sys_errlist[1] = 0; -#endif diff --git a/Python/strtod.c b/Python/strtod.c deleted file mode 100644 index dddc98bb56..0000000000 --- a/Python/strtod.c +++ /dev/null @@ -1,158 +0,0 @@ -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -/* comp.sources.misc strtod(), as posted in comp.lang.tcl, - with bugfix for "123000.0" and acceptance of space after 'e' sign nuked. - - ************************************************************ - * YOU MUST EDIT THE MACHINE-DEPENDENT DEFINITIONS BELOW!!! * - ************************************************************ -*/ - -/* File : stdtod.c (Modified version of str2dbl.c) - Author : Richard A. O'Keefe @ Quintus Computer Systems, Inc. - Updated: Tuesday August 2nd, 1988 - Defines: double strtod (char *str, char**ptr) -*/ - -/* This is an implementation of the strtod() function described in the - System V manuals, with a different name to avoid linker problems. - All that str2dbl() does itself is check that the argument is well-formed - and is in range. It leaves the work of conversion to atof(), which is - assumed to exist and deliver correct results (if they can be represented). - - There are two reasons why this should be provided to the net: - (a) some UNIX systems do not yet have strtod(), or do not have it - available in the BSD "universe" (but they do have atof()). - (b) some of the UNIX systems that *do* have it get it wrong. - (some crash with large arguments, some assign the wrong *ptr value). - There is a reason why *we* are providing it: we need a correct version - of strtod(), and if we give this one away maybe someone will look for - mistakes in it and fix them for us (:-). -*/ - -/* The following constants are machine-specific. MD{MIN,MAX}EXPT are - integers and MD{MIN,MAX}FRAC are strings such that - 0.${MDMAXFRAC}e${MDMAXEXPT} is the largest representable double, - 0.${MDMINFRAC}e${MDMINEXPT} is the smallest representable +ve double - MD{MIN,MAX}FRAC must not have any trailing zeros. - The values here are for IEEE-754 64-bit floats. - It is not perfectly clear to me whether an IEEE infinity should be - returned for overflow, nor what a portable way of writing one is, - so HUGE is just 0.MAXFRAC*10**MAXEXPT (this seems still to be the - UNIX convention). - - I do know about <values.h>, but the whole point of this file is that - we can't always trust that stuff to be there or to be correct. -*/ -static int MDMINEXPT = {-323}; -static char MDMINFRAC[] = "494065645841246544"; -static double ZERO = 0.0; - -static int MDMAXEXPT = { 309}; -static char MDMAXFRAC[] = "17976931348623157"; -static double HUGE = 1.7976931348623157e308; - -extern double atof(); /* Only called when result known to be ok */ - -#include <errno.h> -extern int errno; - -double strtod(str, ptr) - char *str; - char **ptr; - { - int sign, scale, dotseen; - int esign, expt; - char *save; - register char *sp, *dp; - register int c; - char *buforg, *buflim; - char buffer[64]; /* 45-digit significand + */ - /* 13-digit exponent */ - sp = str; - while (*sp == ' ') sp++; - sign = 1; - if (*sp == '-') sign -= 2, sp++; - dotseen = 0, scale = 0; - dp = buffer; - *dp++ = '0'; *dp++ = '.'; - buforg = dp, buflim = buffer+48; - for (save = sp; c = *sp; sp++) - if (c == '.') { - if (dotseen) break; - dotseen++; - } else - if ((unsigned)(c-'0') > (unsigned)('9'-'0')) { - break; - } else - if (c == '0') { - if (dp != buforg) { - /* This is not the first digit, so we want to keep it */ - if (dp < buflim) *dp++ = c; - if (!dotseen) scale++; - } else { - /* No non-zero digits seen yet */ - /* If a . has been seen, scale must be adjusted */ - if (dotseen) scale--; - } - } else { - /* This is a nonzero digit, so we want to keep it */ - if (dp < buflim) *dp++ = c; - /* If it precedes a ., scale must be adjusted */ - if (!dotseen) scale++; - } - if (sp == save) { - if (ptr) *ptr = str; - errno = EDOM; /* what should this be? */ - return ZERO; - } - - while (dp > buforg && dp[-1] == '0') --dp; - if (dp == buforg) *dp++ = '0'; - *dp = '\0'; - /* Now the contents of buffer are - +--+--------+-+--------+ - |0.|fraction|\|leftover| - +--+--------+-+--------+ - ^dp points here - where fraction begins with 0 iff it is "0", and has at most - 45 digits in it, and leftover is at least 16 characters. - */ - save = sp, expt = 0, esign = 1; - do { - c = *sp++; - if (c != 'e' && c != 'E') break; - c = *sp++; - if (c == '-') esign -= 2, c = *sp++; else - if (c == '+' /* || c == ' ' */ ) c = *sp++; - if ((unsigned)(c-'0') > (unsigned)('9'-'0')) break; - while (c == '0') c = *sp++; - for (; (unsigned)(c-'0') <= (unsigned)('9'-'0'); c = *sp++) - expt = expt*10 + c-'0'; - if (esign < 0) expt = -expt; - save = sp-1; - } while (0); - if (ptr) *ptr = save; - expt += scale; - /* Now the number is sign*0.fraction*10**expt */ - errno = ERANGE; - if (expt > MDMAXEXPT) { - return HUGE*sign; - } else - if (expt == MDMAXEXPT) { - if (strcmp(buforg, MDMAXFRAC) > 0) return HUGE*sign; - } else - if (expt < MDMINEXPT) { - return ZERO*sign; - } else - if (expt == MDMINEXPT) { - if (strcmp(buforg, MDMINFRAC) < 0) return ZERO*sign; - } - /* We have now established that the number can be */ - /* represented without overflow or underflow */ - (void) sprintf(dp, "E%d", expt); - errno = 0; - return atof(buffer)*sign; - } diff --git a/Python/structmember.c b/Python/structmember.c deleted file mode 100644 index 81a52030ce..0000000000 --- a/Python/structmember.c +++ /dev/null @@ -1,262 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Map C struct members to Python object attributes */ - -#include "allobjects.h" - -#include "structmember.h" - -static object * -listmembers(mlist) - struct memberlist *mlist; -{ - int i, n; - object *v; - for (n = 0; mlist[n].name != NULL; n++) - ; - v = newlistobject(n); - if (v != NULL) { - for (i = 0; i < n; i++) - setlistitem(v, i, newstringobject(mlist[i].name)); - if (err_occurred()) { - DECREF(v); - v = NULL; - } - else { - sortlist(v); - } - } - return v; -} - -object * -getmember(addr, mlist, name) - char *addr; - struct memberlist *mlist; - char *name; -{ - struct memberlist *l; - - if (strcmp(name, "__members__") == 0) - return listmembers(mlist); - for (l = mlist; l->name != NULL; l++) { - if (strcmp(l->name, name) == 0) { - object *v; - addr += l->offset; - switch (l->type) { - case T_BYTE: - v = newintobject((long) - (((*(char*)addr & 0xff) - ^ 0x80) - 0x80)); - break; - case T_UBYTE: - v = newintobject((long) *(char*)addr & 0xff); - break; - case T_SHORT: - v = newintobject((long) *(short*)addr); - break; - case T_USHORT: - v = newintobject((long) - *(unsigned short*)addr); - break; - case T_INT: - v = newintobject((long) *(int*)addr); - break; - case T_UINT: - v = newintobject((long) *(unsigned int*)addr); - break; - case T_LONG: - v = newintobject(*(long*)addr); - break; - case T_ULONG: - v = dnewlongobject((double) - *(unsigned long*)addr); - break; - case T_FLOAT: - v = newfloatobject((double)*(float*)addr); - break; - case T_DOUBLE: - v = newfloatobject(*(double*)addr); - break; - case T_STRING: - if (*(char**)addr == NULL) { - INCREF(None); - v = None; - } - else - v = newstringobject(*(char**)addr); - break; - case T_STRING_INPLACE: - v = newstringobject((char*)addr); - break; -#ifdef macintosh - case T_PSTRING: - if (*(char**)addr == NULL) { - INCREF(None); - v = None; - } - else - v = newsizedstringobject((*(char**)addr)+1, - **(unsigned char**)addr); - break; - case T_PSTRING_INPLACE: - v = newsizedstringobject(((char*)addr)+1, - *(unsigned char*)addr); - break; -#endif /* macintosh */ - case T_CHAR: - v = newsizedstringobject((char*)addr, 1); - break; - case T_OBJECT: - v = *(object **)addr; - if (v == NULL) - v = None; - INCREF(v); - break; - default: - err_setstr(SystemError, "bad memberlist type"); - v = NULL; - } - return v; - } - } - - err_setstr(AttributeError, name); - return NULL; -} - -int -setmember(addr, mlist, name, v) - char *addr; - struct memberlist *mlist; - char *name; - object *v; -{ - struct memberlist *l; - - for (l = mlist; l->name != NULL; l++) { - if (strcmp(l->name, name) == 0) { -#ifdef macintosh - if (l->readonly || l->type == T_STRING || l->type == T_PSTRING) { -#else - if (l->readonly || l->type == T_STRING ) { -#endif /* macintosh */ - err_setstr(TypeError, "readonly attribute"); - return -1; - } - if (v == NULL && l->type != T_OBJECT) { - err_setstr(TypeError, - "can't delete numeric/char attribute"); - return -1; - } - addr += l->offset; - switch (l->type) { - case T_BYTE: - case T_UBYTE: - if (!is_intobject(v)) { - err_badarg(); - return -1; - } - *(char*)addr = getintvalue(v); - break; - case T_SHORT: - case T_USHORT: - if (!is_intobject(v)) { - err_badarg(); - return -1; - } - *(short*)addr = getintvalue(v); - break; - case T_UINT: - case T_INT: - if (!is_intobject(v)) { - err_badarg(); - return -1; - } - *(int*)addr = getintvalue(v); - break; - case T_LONG: - if (!is_intobject(v)) { - err_badarg(); - return -1; - } - *(long*)addr = getintvalue(v); - break; - case T_ULONG: - if (is_intobject(v)) - *(long*)addr = getintvalue(v); - else if (is_longobject(v)) - *(long*)addr = getlongvalue(v); - else { - err_badarg(); - return -1; - } - break; - case T_FLOAT: - if (is_intobject(v)) - *(float*)addr = getintvalue(v); - else if (is_floatobject(v)) - *(float*)addr = getfloatvalue(v); - else { - err_badarg(); - return -1; - } - break; - case T_DOUBLE: - if (is_intobject(v)) - *(double*)addr = getintvalue(v); - else if (is_floatobject(v)) - *(double*)addr = getfloatvalue(v); - else { - err_badarg(); - return -1; - } - break; - case T_OBJECT: - XDECREF(*(object **)addr); - XINCREF(v); - *(object **)addr = v; - break; - case T_CHAR: - if (is_stringobject(v) && - getstringsize(v) == 1) { - *(char*)addr = - getstringvalue(v)[0]; - } - else { - err_badarg(); - return -1; - } - default: - err_setstr(SystemError, "bad memberlist type"); - return -1; - } - return 0; - } - } - - err_setstr(AttributeError, name); - return -1; -} diff --git a/Python/sysmodule.c b/Python/sysmodule.c deleted file mode 100644 index 17a785273e..0000000000 --- a/Python/sysmodule.c +++ /dev/null @@ -1,361 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* System module */ - -/* -Various bits of information used by the interpreter are collected in -module 'sys'. -Function member: -- exit(sts): raise SystemExit -Data members: -- stdin, stdout, stderr: standard file objects -- modules: the table of modules (dictionary) -- path: module search path (list of strings) -- argv: script arguments (list of strings) -- ps1, ps2: optional primary and secondary prompts (strings) -*/ - -#include "allobjects.h" - -#include "sysmodule.h" -#include "import.h" -#include "modsupport.h" -#include "osdefs.h" - -object *sys_trace, *sys_profile; -int sys_checkinterval = 10; - -static object *sysdict; - -#ifdef NT -extern void *PyWin_DLLhModule; -#endif - -object * -sysget(name) - char *name; -{ - return dictlookup(sysdict, name); -} - -FILE * -sysgetfile(name, def) - char *name; - FILE *def; -{ - FILE *fp = NULL; - object *v = sysget(name); - if (v != NULL && is_fileobject(v)) - fp = getfilefile(v); - if (fp == NULL) - fp = def; - return fp; -} - -int -sysset(name, v) - char *name; - object *v; -{ - if (v == NULL) { - if (dictlookup(sysdict, name) == NULL) - return 0; - else - return dictremove(sysdict, name); - } - else - return dictinsert(sysdict, name, v); -} - -static object * -sys_exit(self, args) - object *self; - object *args; -{ - /* Raise SystemExit so callers may catch it or clean up. */ - err_setval(SystemExit, args); - return NULL; -} - -static object * -sys_settrace(self, args) - object *self; - object *args; -{ - if (args == None) - args = NULL; - else - XINCREF(args); - XDECREF(sys_trace); - sys_trace = args; - INCREF(None); - return None; -} - -static object * -sys_setprofile(self, args) - object *self; - object *args; -{ - if (args == None) - args = NULL; - else - XINCREF(args); - XDECREF(sys_profile); - sys_profile = args; - INCREF(None); - return None; -} - -static object * -sys_setcheckinterval(self, args) - object *self; - object *args; -{ - if (!newgetargs(args, "i", &sys_checkinterval)) - return NULL; - INCREF(None); - return None; -} - -#ifdef USE_MALLOPT -/* Link with -lmalloc (or -lmpc) on an SGI */ -#include <malloc.h> - -static object * -sys_mdebug(self, args) - object *self; - object *args; -{ - int flag; - if (!getargs(args, "i", &flag)) - return NULL; - mallopt(M_DEBUG, flag); - INCREF(None); - return None; -} -#endif /* USE_MALLOPT */ - -static object * -sys_getrefcount(self, args) - object *self; - object *args; -{ - object *arg; - if (!getargs(args, "O", &arg)) - return NULL; - return newintobject((long) arg->ob_refcnt); -} - -#ifdef COUNT_ALLOCS -static PyObject * -sys_getcounts(self, args) - PyObject *self, *args; -{ - extern PyObject *get_counts Py_PROTO((void)); - - if (!PyArg_Parse(args, "")) - return NULL; - return get_counts(); -} -#endif - -#ifdef Py_TRACE_REFS -/* Defined in objects.c because it uses static globals if that file */ -extern PyObject *_Py_GetObjects Py_PROTO((PyObject *, PyObject *)); -#endif - -static struct methodlist sys_methods[] = { - {"exit", sys_exit, 0}, - {"getrefcount", sys_getrefcount, 0}, -#ifdef COUNT_ALLOCS - {"getcounts", sys_getcounts, 0}, -#endif -#ifdef Py_TRACE_REFS - {"getobjects", _Py_GetObjects, 1}, -#endif -#ifdef USE_MALLOPT - {"mdebug", sys_mdebug, 0}, -#endif - {"setprofile", sys_setprofile, 0}, - {"settrace", sys_settrace, 0}, - {"setcheckinterval", sys_setcheckinterval, 1}, - {NULL, NULL} /* sentinel */ -}; - -static object *sysin, *sysout, *syserr; - -static object * -list_builtin_module_names() -{ - object *list = newlistobject(0); - int i; - if (list == NULL) - return NULL; - for (i = 0; inittab[i].name != NULL; i++) { - object *name = newstringobject(inittab[i].name); - if (name == NULL) - break; - addlistitem(list, name); - DECREF(name); - } - if (sortlist(list) != 0) { - DECREF(list); - list = NULL; - } - return list; -} - -void -initsys() -{ - extern long getmaxint PROTO((void)); - extern char *getversion PROTO((void)); - extern char *getcopyright PROTO((void)); - extern char *getplatform PROTO((void)); - extern int fclose PROTO((FILE *)); - object *m = initmodule("sys", sys_methods); - object *v; - sysdict = getmoduledict(m); - INCREF(sysdict); - /* NB keep an extra ref to the std files to avoid closing them - when the user deletes them */ - sysin = newopenfileobject(stdin, "<stdin>", "r", fclose); - sysout = newopenfileobject(stdout, "<stdout>", "w", fclose); - syserr = newopenfileobject(stderr, "<stderr>", "w", fclose); - if (err_occurred()) - fatal("can't initialize sys.std{in,out,err}"); - dictinsert(sysdict, "stdin", sysin); - dictinsert(sysdict, "stdout", sysout); - dictinsert(sysdict, "stderr", syserr); - dictinsert(sysdict, "version", v = newstringobject(getversion())); - XDECREF(v); - dictinsert(sysdict, "copyright", v = newstringobject(getcopyright())); - XDECREF(v); - dictinsert(sysdict, "platform", v = newstringobject(getplatform())); - XDECREF(v); - dictinsert(sysdict, "maxint", v = newintobject(getmaxint())); - XDECREF(v); - dictinsert(sysdict, "modules", get_modules()); - dictinsert(sysdict, "builtin_module_names", - v = list_builtin_module_names()); - XDECREF(v); -#ifdef NT - dictinsert(sysdict, "dllhandle", v = newintobject((int)PyWin_DLLhModule)); - XDECREF(v); - dictinsert(sysdict, "winver", v = newstringobject(WIN32_PATCH_LEVEL)); - XDECREF(v); -#endif - if (err_occurred()) - fatal("can't insert sys.* objects in sys dict"); -} - -static object * -makepathobject(path, delim) - char *path; - int delim; -{ - int i, n; - char *p; - object *v, *w; - - n = 1; - p = path; - while ((p = strchr(p, delim)) != NULL) { - n++; - p++; - } - v = newlistobject(n); - if (v == NULL) - return NULL; - for (i = 0; ; i++) { - p = strchr(path, delim); - if (p == NULL) - p = strchr(path, '\0'); /* End of string */ - w = newsizedstringobject(path, (int) (p - path)); - if (w == NULL) { - DECREF(v); - return NULL; - } - setlistitem(v, i, w); - if (*p == '\0') - break; - path = p+1; - } - return v; -} - -void -setpythonpath(path) - char *path; -{ - object *v; - if ((v = makepathobject(path, DELIM)) == NULL) - fatal("can't create sys.path"); - if (sysset("path", v) != 0) - fatal("can't assign sys.path"); - DECREF(v); -} - -static object * -makeargvobject(argc, argv) - int argc; - char **argv; -{ - object *av; - if (argc <= 0 || argv == NULL) { - /* Ensure at least one (empty) argument is seen */ - static char *empty_argv[1] = {""}; - argv = empty_argv; - argc = 1; - } - av = newlistobject(argc); - if (av != NULL) { - int i; - for (i = 0; i < argc; i++) { - object *v = newstringobject(argv[i]); - if (v == NULL) { - DECREF(av); - av = NULL; - break; - } - setlistitem(av, i, v); - } - } - return av; -} - -void -setpythonargv(argc, argv) - int argc; - char **argv; -{ - object *av = makeargvobject(argc, argv); - if (av == NULL) - fatal("no mem for sys.argv"); - if (sysset("argv", av) != 0) - fatal("can't assign sys.argv"); - DECREF(av); -} diff --git a/Python/thread.c b/Python/thread.c deleted file mode 100644 index 2d80b097e9..0000000000 --- a/Python/thread.c +++ /dev/null @@ -1,137 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Thread package. - This is intended to be usable independently from Python. - The implementation for system foobar is in a file thread_foobar.h - which is included by this file dependent on config settings. - Stuff shared by all thread_*.h files is collected here. */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include <stdio.h> - -#ifdef HAVE_STDLIB_H -#include <stdlib.h> -#else -extern char *getenv(); -#endif - -#include "thread.h" - -#ifdef __ksr__ -#define _POSIX_THREADS -#endif - -#ifndef _POSIX_THREADS - -#ifdef __sgi -#define SGI_THREADS -#endif - -#ifdef HAVE_THREAD_H -#define SOLARIS_THREADS -#endif - -#if defined(sun) && !defined(SOLARIS_THREADS) -#define SUN_LWP -#endif - -#endif /* _POSIX_THREADS */ - -#ifdef __STDC__ -#define _P(args) args -#define _P0() (void) -#define _P1(v,t) (t) -#define _P2(v1,t1,v2,t2) (t1,t2) -#else -#define _P(args) () -#define _P0() () -#define _P1(v,t) (v) t; -#define _P2(v1,t1,v2,t2) (v1,v2) t1; t2; -#endif /* __STDC__ */ - -#ifdef DEBUG -static int thread_debug = 0; -#define dprintf(args) ((thread_debug & 1) && printf args) -#define d2printf(args) ((thread_debug & 8) && printf args) -#else -#define dprintf(args) -#define d2printf(args) -#endif - -static int initialized; - -static void _init_thread(); /* Forward */ - -void init_thread _P0() -{ -#ifdef DEBUG - char *p = getenv("THREADDEBUG"); - - if (p) { - if (*p) - thread_debug = atoi(p); - else - thread_debug = 1; - } -#endif /* DEBUG */ - if (initialized) - return; - initialized = 1; - dprintf(("init_thread called\n")); - _init_thread(); -} - -#ifdef SGI_THREADS -#include "thread_sgi.h" -#endif - -#ifdef SOLARIS_THREADS -#include "thread_solaris.h" -#endif - -#ifdef SUN_LWP -#include "thread_lwp.h" -#endif - -#ifdef _POSIX_THREADS -#include "thread_pthread.h" -#endif - -#ifdef C_THREADS -#include "thread_cthread.h" -#endif - -#ifdef NT_THREADS -#include "thread_nt.h" -#endif - -/* -#ifdef FOOBAR_THREADS -#include "thread_foobar.h" -#endif -*/ diff --git a/Python/thread_cthread.h b/Python/thread_cthread.h deleted file mode 100644 index 1a1a8608c7..0000000000 --- a/Python/thread_cthread.h +++ /dev/null @@ -1,160 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#include <cthreads.h> - - -/* - * Initialization. - */ -static void _init_thread _P0() -{ - cthread_init(); -} - -/* - * Thread support. - */ -int start_new_thread _P2(func, void (*func) _P((void *)), arg, void *arg) -{ - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ - - dprintf(("start_new_thread called\n")); - if (!initialized) - init_thread(); - (void) cthread_fork(func, arg); - return success < 0 ? 0 : 1; -} - -long get_thread_ident _P0() -{ - if (!initialized) - init_thread(); -} - -static void do_exit_thread _P1(no_cleanup, int no_cleanup) -{ - dprintf(("exit_thread called\n")); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); - cthread_exit(0); -} - -void exit_thread _P0() -{ - do_exit_thread(0); -} - -void _exit_thread _P0() -{ - do_exit_thread(1); -} - -#ifndef NO_EXIT_PROG -static void do_exit_prog _P2(status, int status, no_cleanup, int no_cleanup) -{ - dprintf(("exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); -} - -void exit_prog _P1(status, int status) -{ - do_exit_prog(status, 0); -} - -void _exit_prog _P1(status, int status) -{ - do_exit_prog(status, 1); -} -#endif /* NO_EXIT_PROG */ - -/* - * Lock support. - */ -type_lock allocate_lock _P0() -{ - - dprintf(("allocate_lock called\n")); - if (!initialized) - init_thread(); - - dprintf(("allocate_lock() -> %lx\n", (long)lock)); - return (type_lock) lock; -} - -void free_lock _P1(lock, type_lock lock) -{ - dprintf(("free_lock(%lx) called\n", (long)lock)); -} - -int acquire_lock _P2(lock, type_lock lock, waitflag, int waitflag) -{ - int success; - - dprintf(("acquire_lock(%lx, %d) called\n", (long)lock, waitflag)); - dprintf(("acquire_lock(%lx, %d) -> %d\n", (long)lock, waitflag, success)); - return success; -} - -void release_lock _P1(lock, type_lock lock) -{ - dprintf(("release_lock(%lx) called\n", (long)lock)); -} - -/* - * Semaphore support. - */ -type_sema allocate_sema _P1(value, int value) -{ - dprintf(("allocate_sema called\n")); - if (!initialized) - init_thread(); - - dprintf(("allocate_sema() -> %lx\n", (long) sema)); - return (type_sema) sema; -} - -void free_sema _P1(sema, type_sema sema) -{ - dprintf(("free_sema(%lx) called\n", (long) sema)); -} - -void down_sema _P1(sema, type_sema sema) -{ - dprintf(("down_sema(%lx) called\n", (long) sema)); - dprintf(("down_sema(%lx) return\n", (long) sema)); -} - -void up_sema _P1(sema, type_sema sema) -{ - dprintf(("up_sema(%lx)\n", (long) sema)); -} diff --git a/Python/thread_foobar.h b/Python/thread_foobar.h deleted file mode 100644 index 772f26b6f9..0000000000 --- a/Python/thread_foobar.h +++ /dev/null @@ -1,154 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* - * Initialization. - */ -static void _init_thread _P0() -{ -} - -/* - * Thread support. - */ -int start_new_thread _P2(func, void (*func) _P((void *)), arg, void *arg) -{ - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ - - dprintf(("start_new_thread called\n")); - if (!initialized) - init_thread(); - return success < 0 ? 0 : 1; -} - -long get_thread_ident _P0() -{ - if (!initialized) - init_thread(); -} - -static void do_exit_thread _P1(no_cleanup, int no_cleanup) -{ - dprintf(("exit_thread called\n")); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); -} - -void exit_thread _P0() -{ - do_exit_thread(0); -} - -void _exit_thread _P0() -{ - do_exit_thread(1); -} - -#ifndef NO_EXIT_PROG -static void do_exit_prog _P2(status, int status, no_cleanup, int no_cleanup) -{ - dprintf(("exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); -} - -void exit_prog _P1(status, int status) -{ - do_exit_prog(status, 0); -} - -void _exit_prog _P1(status, int status) -{ - do_exit_prog(status, 1); -} -#endif /* NO_EXIT_PROG */ - -/* - * Lock support. - */ -type_lock allocate_lock _P0() -{ - - dprintf(("allocate_lock called\n")); - if (!initialized) - init_thread(); - - dprintf(("allocate_lock() -> %lx\n", (long)lock)); - return (type_lock) lock; -} - -void free_lock _P1(lock, type_lock lock) -{ - dprintf(("free_lock(%lx) called\n", (long)lock)); -} - -int acquire_lock _P2(lock, type_lock lock, waitflag, int waitflag) -{ - int success; - - dprintf(("acquire_lock(%lx, %d) called\n", (long)lock, waitflag)); - dprintf(("acquire_lock(%lx, %d) -> %d\n", (long)lock, waitflag, success)); - return success; -} - -void release_lock _P1(lock, type_lock lock) -{ - dprintf(("release_lock(%lx) called\n", (long)lock)); -} - -/* - * Semaphore support. - */ -type_sema allocate_sema _P1(value, int value) -{ - dprintf(("allocate_sema called\n")); - if (!initialized) - init_thread(); - - dprintf(("allocate_sema() -> %lx\n", (long) sema)); - return (type_sema) sema; -} - -void free_sema _P1(sema, type_sema sema) -{ - dprintf(("free_sema(%lx) called\n", (long) sema)); -} - -void down_sema _P1(sema, type_sema sema) -{ - dprintf(("down_sema(%lx) called\n", (long) sema)); - dprintf(("down_sema(%lx) return\n", (long) sema)); -} - -void up_sema _P1(sema, type_sema sema) -{ - dprintf(("up_sema(%lx)\n", (long) sema)); -} diff --git a/Python/thread_lwp.h b/Python/thread_lwp.h deleted file mode 100644 index a4e943f008..0000000000 --- a/Python/thread_lwp.h +++ /dev/null @@ -1,202 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#include <stdlib.h> -#include <lwp/lwp.h> -#include <lwp/stackdep.h> - -#define STACKSIZE 1000 /* stacksize for a thread */ -#define NSTACKS 2 /* # stacks to be put in cache initialy */ - -struct lock { - int lock_locked; - cv_t lock_condvar; - mon_t lock_monitor; -}; - - -/* - * Initialization. - */ -static void _init_thread _P0() -{ - lwp_setstkcache(STACKSIZE, NSTACKS); -} - -/* - * Thread support. - */ - - -int start_new_thread _P2(func, void (*func) _P((void *)), arg, void *arg) -{ - thread_t tid; - int success; - dprintf(("start_new_thread called\n")); - if (!initialized) - init_thread(); - success = lwp_create(&tid, func, MINPRIO, 0, lwp_newstk(), 1, arg); - return success < 0 ? 0 : 1; -} - -long get_thread_ident _P0() -{ - thread_t tid; - if (!initialized) - init_thread(); - if (lwp_self(&tid) < 0) - return -1; - return tid.thread_id; -} - -static void do_exit_thread _P1(no_cleanup, int no_cleanup) -{ - dprintf(("exit_thread called\n")); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); - lwp_destroy(SELF); -} - -void exit_thread _P0() -{ - do_exit_thread(0); -} - -void _exit_thread _P0() -{ - do_exit_thread(1); -} - -#ifndef NO_EXIT_PROG -static void do_exit_prog _P2(status, int status, no_cleanup, int no_cleanup) -{ - dprintf(("exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); - pod_exit(status); -} - -void exit_prog _P1(status, int status) -{ - do_exit_prog(status, 0); -} - -void _exit_prog _P1(status, int status) -{ - do_exit_prog(status, 1); -} -#endif /* NO_EXIT_PROG */ - -/* - * Lock support. - */ -type_lock allocate_lock _P0() -{ - struct lock *lock; - extern char *malloc(); - - dprintf(("allocate_lock called\n")); - if (!initialized) - init_thread(); - - lock = (struct lock *) malloc(sizeof(struct lock)); - lock->lock_locked = 0; - (void) mon_create(&lock->lock_monitor); - (void) cv_create(&lock->lock_condvar, lock->lock_monitor); - dprintf(("allocate_lock() -> %lx\n", (long)lock)); - return (type_lock) lock; -} - -void free_lock _P1(lock, type_lock lock) -{ - dprintf(("free_lock(%lx) called\n", (long)lock)); - mon_destroy(((struct lock *) lock)->lock_monitor); - free((char *) lock); -} - -int acquire_lock _P2(lock, type_lock lock, waitflag, int waitflag) -{ - int success; - - dprintf(("acquire_lock(%lx, %d) called\n", (long)lock, waitflag)); - success = 0; - - (void) mon_enter(((struct lock *) lock)->lock_monitor); - if (waitflag) - while (((struct lock *) lock)->lock_locked) - cv_wait(((struct lock *) lock)->lock_condvar); - if (!((struct lock *) lock)->lock_locked) { - success = 1; - ((struct lock *) lock)->lock_locked = 1; - } - cv_broadcast(((struct lock *) lock)->lock_condvar); - mon_exit(((struct lock *) lock)->lock_monitor); - dprintf(("acquire_lock(%lx, %d) -> %d\n", (long)lock, waitflag, success)); - return success; -} - -void release_lock _P1(lock, type_lock lock) -{ - dprintf(("release_lock(%lx) called\n", (long)lock)); - (void) mon_enter(((struct lock *) lock)->lock_monitor); - ((struct lock *) lock)->lock_locked = 0; - cv_broadcast(((struct lock *) lock)->lock_condvar); - mon_exit(((struct lock *) lock)->lock_monitor); -} - -/* - * Semaphore support. - */ -type_sema allocate_sema _P1(value, int value) -{ - type_sema sema = 0; - dprintf(("allocate_sema called\n")); - if (!initialized) - init_thread(); - - dprintf(("allocate_sema() -> %lx\n", (long) sema)); - return (type_sema) sema; -} - -void free_sema _P1(sema, type_sema sema) -{ - dprintf(("free_sema(%lx) called\n", (long) sema)); -} - -void down_sema _P1(sema, type_sema sema) -{ - dprintf(("down_sema(%lx) called\n", (long) sema)); - dprintf(("down_sema(%lx) return\n", (long) sema)); -} - -void up_sema _P1(sema, type_sema sema) -{ - dprintf(("up_sema(%lx)\n", (long) sema)); -} diff --git a/Python/thread_nt.h b/Python/thread_nt.h deleted file mode 100644 index 453e942b99..0000000000 --- a/Python/thread_nt.h +++ /dev/null @@ -1,245 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* This code implemented by Dag.Gruneau@elsa.preseco.comm.se */ - -#include "windows.h" -#include "limits.h" - -long get_thread_ident(void); - -/* - * Change all headers to pure ANSI as no one will use K&R style on an - * NT - */ - -/* - * Initialization of the C package, should not be needed. - */ -static void _init_thread(void) -{ -} - -/* - * Thread support. - */ -int start_new_thread(void (*func)(void *), void *arg) -{ - HANDLE aThread; - DWORD aThreadId; - - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ - dprintf(("%ld: start_new_thread called\n", get_thread_ident())); - if (!initialized) - init_thread(); - - aThread = CreateThread( - NULL, /* No security attributes */ - 0, /* use default stack size */ - (LPTHREAD_START_ROUTINE) func, /* thread function */ - (LPVOID) arg, /* argument to thread function */ - 0, /* use the default creation flags */ - &aThreadId); /* returns the thread identifier */ - - if (aThread != NULL) { - CloseHandle(aThread); /* We do not want to have any zombies hanging around */ - success = 1; - dprintf(("%ld: start_new_thread succeeded: %ld\n", get_thread_ident(), aThreadId)); - } - - return success; -} - -/* - * Return the thread Id instead of an handle. The Id is said to uniquely identify the - * thread in the system - */ -long get_thread_ident(void) -{ - if (!initialized) - init_thread(); - - return GetCurrentThreadId(); -} - -static void do_exit_thread(int no_cleanup) -{ - dprintf(("%ld: exit_thread called\n", get_thread_ident())); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); - ExitThread(0); -} - -void exit_thread(void) -{ - do_exit_thread(0); -} - -void _exit_thread(void) -{ - do_exit_thread(1); -} - -#ifndef NO_EXIT_PROG -static void do_exit_prog(int status, int no_cleanup) -{ - dprintf(("exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); -} - -void exit_prog(int status) -{ - do_exit_prog(status, 0); -} - -void _exit_prog _P1(int status) -{ - do_exit_prog(status, 1); -} -#endif /* NO_EXIT_PROG */ - -/* - * Lock support. It has too be implemented as semaphores. - * I [Dag] tried to implement it with mutex but I could find a way to - * tell whether a thread already own the lock or not. - */ -type_lock allocate_lock(void) -{ - HANDLE aLock; - - dprintf(("allocate_lock called\n")); - if (!initialized) - init_thread(); - - aLock = CreateSemaphore(NULL, /* Security attributes */ - 1, /* Initial value */ - 1, /* Maximum value */ - NULL); - /* Name of semaphore */ - - dprintf(("%ld: allocate_lock() -> %lx\n", get_thread_ident(), (long)aLock)); - - return (type_lock) aLock; -} - -void free_lock(type_lock aLock) -{ - dprintf(("%ld: free_lock(%lx) called\n", get_thread_ident(),(long)aLock)); - - CloseHandle((HANDLE) aLock); -} - -/* - * Return 1 on success if the lock was acquired - * - * and 0 if the lock was not acquired. This means a 0 is returned - * if the lock has already been acquired by this thread! - */ -int acquire_lock(type_lock aLock, int waitflag) -{ - int success = 1; - DWORD waitResult; - - dprintf(("%ld: acquire_lock(%lx, %d) called\n", get_thread_ident(),(long)aLock, waitflag)); - - waitResult = WaitForSingleObject((HANDLE) aLock, (waitflag == 1 ? INFINITE : 0)); - - if (waitResult != WAIT_OBJECT_0) { - success = 0; /* We failed */ - } - - dprintf(("%ld: acquire_lock(%lx, %d) -> %d\n", get_thread_ident(),(long)aLock, waitflag, success)); - - return success; -} - -void release_lock(type_lock aLock) -{ - dprintf(("%ld: release_lock(%lx) called\n", get_thread_ident(),(long)aLock)); - - if (!ReleaseSemaphore( - (HANDLE) aLock, /* Handle of semaphore */ - 1, /* increment count by one */ - NULL)) /* not interested in previous count */ - { - dprintf(("%ld: Could not release_lock(%lx) error: %l\n", get_thread_ident(), (long)aLock, GetLastError())); - } -} - -/* - * Semaphore support. - */ -type_sema allocate_sema(int value) -{ - HANDLE aSemaphore; - - dprintf(("%ld: allocate_sema called\n", get_thread_ident())); - if (!initialized) - init_thread(); - - aSemaphore = CreateSemaphore( NULL, /* Security attributes */ - value, /* Initial value */ - INT_MAX, /* Maximum value */ - NULL); /* Name of semaphore */ - - dprintf(("%ld: allocate_sema() -> %lx\n", get_thread_ident(), (long)aSemaphore)); - - return (type_sema) aSemaphore; -} - -void free_sema(type_sema aSemaphore) -{ - dprintf(("%ld: free_sema(%lx) called\n", get_thread_ident(), (long)aSemaphore)); - - CloseHandle((HANDLE) aSemaphore); -} - -void down_sema(type_sema aSemaphore) -{ - DWORD waitResult; - - dprintf(("%ld: down_sema(%lx) called\n", get_thread_ident(), (long)aSemaphore)); - - waitResult = WaitForSingleObject( (HANDLE) aSemaphore, INFINITE); - - dprintf(("%ld: down_sema(%lx) return: %l\n", get_thread_ident(),(long) aSemaphore, waitResult)); -} - -void up_sema(type_sema aSemaphore) -{ - ReleaseSemaphore( - (HANDLE) aSemaphore, /* Handle of semaphore */ - 1, /* increment count by one */ - NULL); /* not interested in previous count */ - - dprintf(("%ld: up_sema(%lx)\n", get_thread_ident(), (long)aSemaphore)); -} diff --git a/Python/thread_os2.h b/Python/thread_os2.h deleted file mode 100644 index f9eda928db..0000000000 --- a/Python/thread_os2.h +++ /dev/null @@ -1,214 +0,0 @@ -/*********************************************************** - Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, - The Netherlands. - - All Rights Reserved - - Permission to use, copy, modify, and distribute this software and its - documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch - Centrum or CWI not be used in advertising or publicity pertaining to - distribution of the software without specific, written prior permission. - - STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO - THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - - ******************************************************************/ - -/* This code implemented by cvale@netcom.com */ - -#define INCL_DOSPROCESS -#define INCL_DOSSEMAPHORES -#include "os2.h" -#include "limits.h" - -#include "process.h" - -long get_thread_ident(void); - - -/* - * Initialization of the C package, should not be needed. - */ -static void _init_thread(void) -{ -} - -/* - * Thread support. - */ -int start_new_thread(void (*func)(void *), void *arg) -{ - int aThread; - int success = 1; - - aThread = _beginthread(func,4096,arg); - - if( aThread == -1 ) { - success = 0; - fprintf(stderr,"aThread failed == %d",aThread); - dprintf(("_beginthread failed. return %ld\n", errno)); - } - - return success; -} - -long get_thread_ident(void) -{ - PPIB pib; - PTIB tib; - - if (!initialized) - init_thread(); - - DosGetInfoBlocks(&tib,&pib); - return tib->tib_ptib2->tib2_ultid; -} - -static void do_exit_thread(int no_cleanup) -{ - dprintf(("%ld: exit_thread called\n", get_thread_ident())); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); - _endthread(); -} - -void exit_thread(void) -{ - do_exit_thread(0); -} - -void _exit_thread(void) -{ - do_exit_thread(1); -} - -#ifndef NO_EXIT_PROG -static void do_exit_prog(int status, int no_cleanup) -{ - dprintf(("exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); -} - -void exit_prog(int status) -{ - do_exit_prog(status, 0); -} - -void _exit_prog _P1(int status) -{ - do_exit_prog(status, 1); -} -#endif /* NO_EXIT_PROG */ - -/* - * Lock support. It has too be implemented as semaphores. - * I [Dag] tried to implement it with mutex but I could find a way to - * tell whether a thread already own the lock or not. - */ -type_lock allocate_lock(void) -{ - HMTX aLock; - APIRET rc; - - dprintf(("allocate_lock called\n")); - if (!initialized) - init_thread(); - - DosCreateMutexSem(NULL, /* Sem name */ - &aLock, /* the semaphone */ - 0, /* shared ? */ - 0); /* initial state */ - - dprintf(("%ld: allocate_lock() -> %lx\n", get_thread_ident(), (long)aLock)); - - return (type_lock) aLock; -} - -void free_lock(type_lock aLock) -{ - dprintf(("%ld: free_lock(%lx) called\n", get_thread_ident(),(long)aLock)); - - DosCloseMutexSem((HMTX)aLock); -} - -/* - * Return 1 on success if the lock was acquired - * - * and 0 if the lock was not acquired. This means a 0 is returned - * if the lock has already been acquired by this thread! - */ -int acquire_lock(type_lock aLock, int waitflag) -{ - int success = 1; - ULONG rc, count; - PID pid = 0; - TID tid = 0; - - dprintf(("%ld: acquire_lock(%lx, %d) called\n", get_thread_ident(), - (long)aLock, waitflag)); - - DosQueryMutexSem((HMTX)aLock,&pid,&tid,&count); - if( tid == get_thread_ident() ) { /* if we own this lock */ - success = 0; - } else { - rc = DosRequestMutexSem((HMTX) aLock, - (waitflag == 1 ? SEM_INDEFINITE_WAIT : 0)); - - if( rc != 0) { - success = 0; /* We failed */ - } - } - - dprintf(("%ld: acquire_lock(%lx, %d) -> %d\n", - get_thread_ident(),(long)aLock, waitflag, success)); - - return success; -} - -void release_lock(type_lock aLock) -{ - dprintf(("%ld: release_lock(%lx) called\n", get_thread_ident(),(long)aLock)); - - if ( DosReleaseMutexSem( (HMTX) aLock ) != 0 ) { - dprintf(("%ld: Could not release_lock(%lx) error: %l\n", - get_thread_ident(), (long)aLock, GetLastError())); - } -} - -/* - * Semaphore support. - */ -type_sema allocate_sema(int value) -{ - return (type_sema) 0; -} - -void free_sema(type_sema aSemaphore) -{ - -} - -void down_sema(type_sema aSemaphore) -{ - -} - -void up_sema(type_sema aSemaphore) -{ - dprintf(("%ld: up_sema(%lx)\n", get_thread_ident(), (long)aSemaphore)); -} diff --git a/Python/thread_pthread.h b/Python/thread_pthread.h deleted file mode 100644 index a4222cf1e0..0000000000 --- a/Python/thread_pthread.h +++ /dev/null @@ -1,283 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#ifdef sun -#define FLORIDA_HACKS -#endif - -#ifdef FLORIDA_HACKS -/* Hacks for Florida State Posix threads implementation */ -#undef _POSIX_THREADS -#include "/ufs/guido/src/python/Contrib/pthreads/src/pthread.h" -#define pthread_attr_default ((pthread_attr_t *)0) -#define pthread_mutexattr_default ((pthread_mutexattr_t *)0) -#define pthread_condattr_default ((pthread_condattr_t *)0) -#define TRYLOCK_OFFSET 1 -#else /* !FLORIDA_HACKS */ -#include <pthread.h> -#define TRYLOCK_OFFSET 0 -#endif /* FLORIDA_HACKS */ -#include <stdlib.h> - -/* A pthread mutex isn't sufficient to model the Python lock type - * because, according to Draft 5 of the docs (P1003.4a/D5), both of the - * following are undefined: - * -> a thread tries to lock a mutex it already has locked - * -> a thread tries to unlock a mutex locked by a different thread - * pthread mutexes are designed for serializing threads over short pieces - * of code anyway, so wouldn't be an appropriate implementation of - * Python's locks regardless. - * - * The pthread_lock struct implements a Python lock as a "locked?" bit - * and a <condition, mutex> pair. In general, if the bit can be acquired - * instantly, it is, else the pair is used to block the thread until the - * bit is cleared. 9 May 1994 tim@ksr.com - */ - -typedef struct { - char locked; /* 0=unlocked, 1=locked */ - /* a <cond, mutex> pair to handle an acquire of a locked lock */ - pthread_cond_t lock_released; - pthread_mutex_t mut; -} pthread_lock; - -#define CHECK_STATUS(name) if (status < 0) { perror(name); error=1; } - -/* - * Initialization. - */ -static void _init_thread _P0() -{ -} - -/* - * Thread support. - */ - - -int start_new_thread _P2(func, void (*func) _P((void *)), arg, void *arg) -{ -#if defined(SGI_THREADS) && defined(USE_DL) - long addr, size; - static int local_initialized = 0; -#endif /* SGI_THREADS and USE_DL */ - pthread_t th; - int success; - dprintf(("start_new_thread called\n")); - if (!initialized) - init_thread(); - success = pthread_create(&th, pthread_attr_default, func, arg); - return success < 0 ? 0 : 1; -} - -long get_thread_ident _P0() -{ - pthread_t threadid; - if (!initialized) - init_thread(); - /* Jump through some hoops for Alpha OSF/1 */ - threadid = pthread_self(); - return (long) *(long *) &threadid; -} - -static void do_exit_thread _P1(no_cleanup, int no_cleanup) -{ - dprintf(("exit_thread called\n")); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); -} - -void exit_thread _P0() -{ - do_exit_thread(0); -} - -void _exit_thread _P0() -{ - do_exit_thread(1); -} - -#ifndef NO_EXIT_PROG -static void do_exit_prog _P2(status, int status, no_cleanup, int no_cleanup) -{ - dprintf(("exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); -} - -void exit_prog _P1(status, int status) -{ - do_exit_prog(status, 0); -} - -void _exit_prog _P1(status, int status) -{ - do_exit_prog(status, 1); -} -#endif /* NO_EXIT_PROG */ - -/* - * Lock support. - */ -type_lock allocate_lock _P0() -{ - pthread_lock *lock; - int status, error = 0; - - dprintf(("allocate_lock called\n")); - if (!initialized) - init_thread(); - - lock = (pthread_lock *) malloc(sizeof(pthread_lock)); - if (lock) { - lock->locked = 0; - - status = pthread_mutex_init(&lock->mut, - pthread_mutexattr_default); - CHECK_STATUS("pthread_mutex_init"); - - status = pthread_cond_init(&lock->lock_released, - pthread_condattr_default); - CHECK_STATUS("pthread_cond_init"); - - if (error) { - free((void *)lock); - lock = 0; - } - } - - dprintf(("allocate_lock() -> %lx\n", (long)lock)); - return (type_lock) lock; -} - -void free_lock _P1(lock, type_lock lock) -{ - pthread_lock *thelock = (pthread_lock *)lock; - int status, error = 0; - - dprintf(("free_lock(%lx) called\n", (long)lock)); - - status = pthread_mutex_destroy( &thelock->mut ); - CHECK_STATUS("pthread_mutex_destroy"); - - status = pthread_cond_destroy( &thelock->lock_released ); - CHECK_STATUS("pthread_cond_destroy"); - - free((void *)thelock); -} - -int acquire_lock _P2(lock, type_lock lock, waitflag, int waitflag) -{ - int success; - pthread_lock *thelock = (pthread_lock *)lock; - int status, error = 0; - - dprintf(("acquire_lock(%lx, %d) called\n", (long)lock, waitflag)); - - status = pthread_mutex_lock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_lock[1]"); - success = thelock->locked == 0; - if (success) thelock->locked = 1; - status = pthread_mutex_unlock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_unlock[1]"); - - if ( !success && waitflag ) { - /* continue trying until we get the lock */ - - /* mut must be locked by me -- part of the condition - * protocol */ - status = pthread_mutex_lock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_lock[2]"); - while ( thelock->locked ) { - status = pthread_cond_wait(&thelock->lock_released, - &thelock->mut); - CHECK_STATUS("pthread_cond_wait"); - } - thelock->locked = 1; - status = pthread_mutex_unlock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_unlock[2]"); - success = 1; - } - if (error) success = 0; - dprintf(("acquire_lock(%lx, %d) -> %d\n", (long)lock, waitflag, success)); - return success; -} - -void release_lock _P1(lock, type_lock lock) -{ - pthread_lock *thelock = (pthread_lock *)lock; - int status, error = 0; - - dprintf(("release_lock(%lx) called\n", (long)lock)); - - status = pthread_mutex_lock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_lock[3]"); - - thelock->locked = 0; - - status = pthread_mutex_unlock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_unlock[3]"); - - /* wake up someone (anyone, if any) waiting on the lock */ - status = pthread_cond_signal( &thelock->lock_released ); - CHECK_STATUS("pthread_cond_signal"); -} - -/* - * Semaphore support. - */ -/* NOTE: 100% non-functional at this time - tim */ - -type_sema allocate_sema _P1(value, int value) -{ - char *sema = 0; - dprintf(("allocate_sema called\n")); - if (!initialized) - init_thread(); - - dprintf(("allocate_sema() -> %lx\n", (long) sema)); - return (type_sema) sema; -} - -void free_sema _P1(sema, type_sema sema) -{ - dprintf(("free_sema(%lx) called\n", (long) sema)); -} - -void down_sema _P1(sema, type_sema sema) -{ - dprintf(("down_sema(%lx) called\n", (long) sema)); - dprintf(("down_sema(%lx) return\n", (long) sema)); -} - -void up_sema _P1(sema, type_sema sema) -{ - dprintf(("up_sema(%lx)\n", (long) sema)); -} diff --git a/Python/thread_sgi.h b/Python/thread_sgi.h deleted file mode 100644 index 654d4aec3a..0000000000 --- a/Python/thread_sgi.h +++ /dev/null @@ -1,439 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#ifdef WITH_SGI_DL -#define USE_DL -#endif - -#include <stdlib.h> -#include <stdio.h> -#include <signal.h> -#include <sys/types.h> -#include <sys/wait.h> -#include <sys/prctl.h> -#include <ulocks.h> -#include <errno.h> - -#define HDR_SIZE 2680 /* sizeof(ushdr_t) */ -#define MAXPROC 100 /* max # of threads that can be started */ - -static usptr_t *shared_arena; -static ulock_t count_lock; /* protection for some variables */ -static ulock_t wait_lock; /* lock used to wait for other threads */ -static int waiting_for_threads; /* protected by count_lock */ -static int nthreads; /* protected by count_lock */ -static int exit_status; -#ifndef NO_EXIT_PROG -static int do_exit; /* indicates that the program is to exit */ -#endif -static int exiting; /* we're already exiting (for maybe_exit) */ -static pid_t my_pid; /* PID of main thread */ -static struct pidlist { - pid_t parent; - pid_t child; -} pidlist[MAXPROC]; /* PIDs of other threads; protected by count_lock */ -static int maxpidindex; /* # of PIDs in pidlist */ - -#ifndef NO_EXIT_PROG -/* - * This routine is called as a signal handler when another thread - * exits. When that happens, we must see whether we have to exit as - * well (because of an exit_prog()) or whether we should continue on. - */ -static void exit_sig _P0() -{ - d2printf(("exit_sig called\n")); - if (exiting && getpid() == my_pid) { - d2printf(("already exiting\n")); - return; - } - if (do_exit) { - d2printf(("exiting in exit_sig\n")); -#ifdef DEBUG - if ((thread_debug & 8) == 0) - thread_debug &= ~1; /* don't produce debug messages */ -#endif - exit_thread(); - } -} - -/* - * This routine is called when a process calls exit(). If that wasn't - * done from the library, we do as if an exit_prog() was intended. - */ -static void maybe_exit _P0() -{ - dprintf(("maybe_exit called\n")); - if (exiting) { - dprintf(("already exiting\n")); - return; - } - exit_prog(0); -} -#endif /* NO_EXIT_PROG */ - -/* - * Initialization. - */ -static void _init_thread _P0() -{ -#ifndef NO_EXIT_PROG - struct sigaction s; -#endif /* NO_EXIT_PROG */ -#ifdef USE_DL - long addr, size; -#endif /* USE_DL */ - - -#ifdef USE_DL - if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) - perror("usconfig - CONF_INITSIZE (check)"); - if (usconfig(CONF_INITSIZE, size) < 0) - perror("usconfig - CONF_INITSIZE (reset)"); - addr = (long) dl_getrange(size + HDR_SIZE); - dprintf(("trying to use addr %lx-%lx for shared arena\n", addr, addr+size)); - errno = 0; - if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && errno != 0) - perror("usconfig - CONF_ATTACHADDR (set)"); -#endif /* USE_DL */ - if (usconfig(CONF_INITUSERS, 16) < 0) - perror("usconfig - CONF_INITUSERS"); - my_pid = getpid(); /* so that we know which is the main thread */ -#ifndef NO_EXIT_PROG - atexit(maybe_exit); - s.sa_handler = exit_sig; - sigemptyset(&s.sa_mask); - /*sigaddset(&s.sa_mask, SIGUSR1);*/ - s.sa_flags = 0; - sigaction(SIGUSR1, &s, 0); - if (prctl(PR_SETEXITSIG, SIGUSR1) < 0) - perror("prctl - PR_SETEXITSIG"); -#endif /* NO_EXIT_PROG */ - if (usconfig(CONF_ARENATYPE, US_SHAREDONLY) < 0) - perror("usconfig - CONF_ARENATYPE"); - usconfig(CONF_LOCKTYPE, US_DEBUG); /* XXX */ -#ifdef DEBUG - if (thread_debug & 4) - usconfig(CONF_LOCKTYPE, US_DEBUGPLUS); - else if (thread_debug & 2) - usconfig(CONF_LOCKTYPE, US_DEBUG); -#endif /* DEBUG */ - if ((shared_arena = usinit(tmpnam(0))) == 0) - perror("usinit"); -#ifdef USE_DL - if (usconfig(CONF_ATTACHADDR, addr) < 0) /* reset address */ - perror("usconfig - CONF_ATTACHADDR (reset)"); -#endif /* USE_DL */ - if ((count_lock = usnewlock(shared_arena)) == NULL) - perror("usnewlock (count_lock)"); - (void) usinitlock(count_lock); - if ((wait_lock = usnewlock(shared_arena)) == NULL) - perror("usnewlock (wait_lock)"); - dprintf(("arena start: %lx, arena size: %ld\n", (long) shared_arena, (long) usconfig(CONF_GETSIZE, shared_arena))); -} - -/* - * Thread support. - */ - -static void clean_threads _P0() -{ - int i, j; - pid_t mypid, pid; - - /* clean up any exited threads */ - mypid = getpid(); - i = 0; - while (i < maxpidindex) { - if (pidlist[i].parent == mypid && (pid = pidlist[i].child) > 0) { - pid = waitpid(pid, 0, WNOHANG); - if (pid > 0) { - /* a thread has exited */ - pidlist[i] = pidlist[--maxpidindex]; - /* remove references to children of dead proc */ - for (j = 0; j < maxpidindex; j++) - if (pidlist[j].parent == pid) - pidlist[j].child = -1; - continue; /* don't increment i */ - } - } - i++; - } - /* clean up the list */ - i = 0; - while (i < maxpidindex) { - if (pidlist[i].child == -1) { - pidlist[i] = pidlist[--maxpidindex]; - continue; /* don't increment i */ - } - i++; - } -} - -int start_new_thread _P2(func, void (*func) _P((void *)), arg, void *arg) -{ -#ifdef USE_DL - long addr, size; - static int local_initialized = 0; -#endif /* USE_DL */ - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ - - dprintf(("start_new_thread called\n")); - if (!initialized) - init_thread(); - switch (ussetlock(count_lock)) { - case 0: return 0; - case -1: perror("ussetlock (count_lock)"); - } - if (maxpidindex >= MAXPROC) - success = -1; - else { -#ifdef USE_DL - if (!local_initialized) { - if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) - perror("usconfig - CONF_INITSIZE (check)"); - if (usconfig(CONF_INITSIZE, size) < 0) - perror("usconfig - CONF_INITSIZE (reset)"); - addr = (long) dl_getrange(size + HDR_SIZE); - dprintf(("trying to use addr %lx-%lx for sproc\n", - addr, addr+size)); - errno = 0; - if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && - errno != 0) - perror("usconfig - CONF_ATTACHADDR (set)"); - } -#endif /* USE_DL */ - clean_threads(); - if ((success = sproc(func, PR_SALL, arg)) < 0) - perror("sproc"); -#ifdef USE_DL - if (!local_initialized) { - if (usconfig(CONF_ATTACHADDR, addr) < 0) - /* reset address */ - perror("usconfig - CONF_ATTACHADDR (reset)"); - local_initialized = 1; - } -#endif /* USE_DL */ - if (success >= 0) { - nthreads++; - pidlist[maxpidindex].parent = getpid(); - pidlist[maxpidindex++].child = success; - dprintf(("pidlist[%d] = %d\n", - maxpidindex-1, success)); - } - } - if (usunsetlock(count_lock) < 0) - perror("usunsetlock (count_lock)"); - return success < 0 ? 0 : 1; -} - -long get_thread_ident _P0() -{ - return getpid(); -} - -static void do_exit_thread _P1(no_cleanup, int no_cleanup) -{ - dprintf(("exit_thread called\n")); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); - if (ussetlock(count_lock) < 0) - perror("ussetlock (count_lock)"); - nthreads--; - if (getpid() == my_pid) { - /* main thread; wait for other threads to exit */ - exiting = 1; -#ifndef NO_EXIT_PROG - if (do_exit) { - int i; - - /* notify other threads */ - clean_threads(); - if (nthreads >= 0) { - dprintf(("kill other threads\n")); - for (i = 0; i < maxpidindex; i++) - if (pidlist[i].child > 0) - (void) kill(pidlist[i].child, - SIGKILL); - _exit(exit_status); - } - } -#endif /* NO_EXIT_PROG */ - waiting_for_threads = 1; - if (ussetlock(wait_lock) < 0) - perror("ussetlock (wait_lock)"); - for (;;) { - if (nthreads < 0) { - dprintf(("really exit (%d)\n", exit_status)); - if (no_cleanup) - _exit(exit_status); - else - exit(exit_status); - } - if (usunsetlock(count_lock) < 0) - perror("usunsetlock (count_lock)"); - dprintf(("waiting for other threads (%d)\n", nthreads)); - if (ussetlock(wait_lock) < 0) - perror("ussetlock (wait_lock)"); - if (ussetlock(count_lock) < 0) - perror("ussetlock (count_lock)"); - } - } - /* not the main thread */ - if (waiting_for_threads) { - dprintf(("main thread is waiting\n")); - if (usunsetlock(wait_lock) < 0) - perror("usunsetlock (wait_lock)"); - } -#ifndef NO_EXIT_PROG - else if (do_exit) - (void) kill(my_pid, SIGUSR1); -#endif /* NO_EXIT_PROG */ - if (usunsetlock(count_lock) < 0) - perror("usunsetlock (count_lock)"); - _exit(0); -} - -void exit_thread _P0() -{ - do_exit_thread(0); -} - -void _exit_thread _P0() -{ - do_exit_thread(1); -} - -#ifndef NO_EXIT_PROG -static void do_exit_prog _P2(status, int status, no_cleanup, int no_cleanup) -{ - dprintf(("exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); - do_exit = 1; - exit_status = status; - do_exit_thread(no_cleanup); -} - -void exit_prog _P1(status, int status) -{ - do_exit_prog(status, 0); -} - -void _exit_prog _P1(status, int status) -{ - do_exit_prog(status, 1); -} -#endif /* NO_EXIT_PROG */ - -/* - * Lock support. - */ -type_lock allocate_lock _P0() -{ - ulock_t lock; - - dprintf(("allocate_lock called\n")); - if (!initialized) - init_thread(); - - if ((lock = usnewlock(shared_arena)) == NULL) - perror("usnewlock"); - (void) usinitlock(lock); - dprintf(("allocate_lock() -> %lx\n", (long)lock)); - return (type_lock) lock; -} - -void free_lock _P1(lock, type_lock lock) -{ - dprintf(("free_lock(%lx) called\n", (long)lock)); - usfreelock((ulock_t) lock, shared_arena); -} - -int acquire_lock _P2(lock, type_lock lock, waitflag, int waitflag) -{ - int success; - - dprintf(("acquire_lock(%lx, %d) called\n", (long)lock, waitflag)); - errno = 0; /* clear it just in case */ - if (waitflag) - success = ussetlock((ulock_t) lock); - else - success = uscsetlock((ulock_t) lock, 1); /* Try it once */ - if (success < 0) - perror(waitflag ? "ussetlock" : "uscsetlock"); - dprintf(("acquire_lock(%lx, %d) -> %d\n", (long)lock, waitflag, success)); - return success; -} - -void release_lock _P1(lock, type_lock lock) -{ - dprintf(("release_lock(%lx) called\n", (long)lock)); - if (usunsetlock((ulock_t) lock) < 0) - perror("usunsetlock"); -} - -/* - * Semaphore support. - */ -type_sema allocate_sema _P1(value, int value) -{ - usema_t *sema; - dprintf(("allocate_sema called\n")); - if (!initialized) - init_thread(); - - if ((sema = usnewsema(shared_arena, value)) == NULL) - perror("usnewsema"); - dprintf(("allocate_sema() -> %lx\n", (long) sema)); - return (type_sema) sema; -} - -void free_sema _P1(sema, type_sema sema) -{ - dprintf(("free_sema(%lx) called\n", (long) sema)); - usfreesema((usema_t *) sema, shared_arena); -} - -void down_sema _P1(sema, type_sema sema) -{ - dprintf(("down_sema(%lx) called\n", (long) sema)); - if (uspsema((usema_t *) sema) < 0) - perror("uspsema"); - dprintf(("down_sema(%lx) return\n", (long) sema)); -} - -void up_sema _P1(sema, type_sema sema) -{ - dprintf(("up_sema(%lx)\n", (long) sema)); - if (usvsema((usema_t *) sema) < 0) - perror("usvsema"); -} diff --git a/Python/thread_solaris.h b/Python/thread_solaris.h deleted file mode 100644 index 199d7d09d6..0000000000 --- a/Python/thread_solaris.h +++ /dev/null @@ -1,226 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -#include <stdlib.h> -#include <stdio.h> -#include <unistd.h> -#include </usr/include/thread.h> - - -/* - * Initialization. - */ -static void _init_thread _P0() -{ -} - -/* - * Thread support. - */ -struct func_arg { - void (*func) _P((void *)); - void *arg; -}; - -static void *new_func _P1(funcarg, void *funcarg) -{ - void (*func) _P((void *)); - void *arg; - - func = ((struct func_arg *) funcarg)->func; - arg = ((struct func_arg *) funcarg)->arg; - free(funcarg); - (*func)(arg); - return 0; -} - - -int start_new_thread _P2(func, void (*func) _P((void *)), arg, void *arg) -{ - struct func_arg *funcarg; - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ - - dprintf(("start_new_thread called\n")); - if (!initialized) - init_thread(); - funcarg = (struct func_arg *) malloc(sizeof(struct func_arg)); - funcarg->func = func; - funcarg->arg = arg; - if (thr_create(0, 0, new_func, funcarg, THR_DETACHED, 0)) { - perror("thr_create"); - free((void *) funcarg); - success = -1; - } - return success < 0 ? 0 : 1; -} - -long get_thread_ident _P0() -{ - if (!initialized) - init_thread(); - return thr_self(); -} - -static void do_exit_thread _P1(no_cleanup, int no_cleanup) -{ - dprintf(("exit_thread called\n")); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); - thr_exit(0); -} - -void exit_thread _P0() -{ - do_exit_thread(0); -} - -void _exit_thread _P0() -{ - do_exit_thread(1); -} - -#ifndef NO_EXIT_PROG -static void do_exit_prog _P2(status, int status, no_cleanup, int no_cleanup) -{ - dprintf(("exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); - if (no_cleanup) - _exit(status); - else - exit(status); -} - -void exit_prog _P1(status, int status) -{ - do_exit_prog(status, 0); -} - -void _exit_prog _P1(status, int status) -{ - do_exit_prog(status, 1); -} -#endif /* NO_EXIT_PROG */ - -/* - * Lock support. - */ -type_lock allocate_lock _P0() -{ - mutex_t *lock; - - dprintf(("allocate_lock called\n")); - if (!initialized) - init_thread(); - - lock = (mutex_t *) malloc(sizeof(mutex_t)); - if (mutex_init(lock, USYNC_THREAD, 0)) { - perror("mutex_init"); - free((void *) lock); - lock = 0; - } - dprintf(("allocate_lock() -> %lx\n", (long)lock)); - return (type_lock) lock; -} - -void free_lock _P1(lock, type_lock lock) -{ - dprintf(("free_lock(%lx) called\n", (long)lock)); - mutex_destroy((mutex_t *) lock); - free((void *) lock); -} - -int acquire_lock _P2(lock, type_lock lock, waitflag, int waitflag) -{ - int success; - - dprintf(("acquire_lock(%lx, %d) called\n", (long)lock, waitflag)); - if (waitflag) - success = mutex_lock((mutex_t *) lock); - else - success = mutex_trylock((mutex_t *) lock); - if (success < 0) - perror(waitflag ? "mutex_lock" : "mutex_trylock"); - else - success = !success; /* solaris does it the other way round */ - dprintf(("acquire_lock(%lx, %d) -> %d\n", (long)lock, waitflag, success)); - return success; -} - -void release_lock _P1(lock, type_lock lock) -{ - dprintf(("release_lock(%lx) called\n", (long)lock)); - if (mutex_unlock((mutex_t *) lock)) - perror("mutex_unlock"); -} - -/* - * Semaphore support. - */ -type_sema allocate_sema _P1(value, int value) -{ - sema_t *sema; - dprintf(("allocate_sema called\n")); - if (!initialized) - init_thread(); - - sema = (sema_t *) malloc(sizeof(sema_t)); - if (sema_init(sema, value, USYNC_THREAD, 0)) { - perror("sema_init"); - free((void *) sema); - sema = 0; - } - dprintf(("allocate_sema() -> %lx\n", (long) sema)); - return (type_sema) sema; -} - -void free_sema _P1(sema, type_sema sema) -{ - dprintf(("free_sema(%lx) called\n", (long) sema)); - if (sema_destroy((sema_t *) sema)) - perror("sema_destroy"); - free((void *) sema); -} - -void down_sema _P1(sema, type_sema sema) -{ - dprintf(("down_sema(%lx) called\n", (long) sema)); - if (sema_wait((sema_t *) sema)) - perror("sema_wait"); - dprintf(("down_sema(%lx) return\n", (long) sema)); -} - -void up_sema _P1(sema, type_sema sema) -{ - dprintf(("up_sema(%lx)\n", (long) sema)); - if (sema_post((sema_t *) sema)) - perror("sema_post"); -} diff --git a/Python/traceback.c b/Python/traceback.c deleted file mode 100644 index 57502a148c..0000000000 --- a/Python/traceback.c +++ /dev/null @@ -1,271 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. - -******************************************************************/ - -/* Traceback implementation */ - -#include "allobjects.h" - -#include "sysmodule.h" -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -#include "structmember.h" -#include "osdefs.h" - -typedef struct _tracebackobject { - OB_HEAD - struct _tracebackobject *tb_next; - frameobject *tb_frame; - int tb_lasti; - int tb_lineno; -} tracebackobject; - -#define OFF(x) offsetof(tracebackobject, x) - -static struct memberlist tb_memberlist[] = { - {"tb_next", T_OBJECT, OFF(tb_next)}, - {"tb_frame", T_OBJECT, OFF(tb_frame)}, - {"tb_lasti", T_INT, OFF(tb_lasti)}, - {"tb_lineno", T_INT, OFF(tb_lineno)}, - {NULL} /* Sentinel */ -}; - -static object * -tb_getattr(tb, name) - tracebackobject *tb; - char *name; -{ - return getmember((char *)tb, tb_memberlist, name); -} - -static void -tb_dealloc(tb) - tracebackobject *tb; -{ - XDECREF(tb->tb_next); - XDECREF(tb->tb_frame); - DEL(tb); -} - -#define Tracebacktype PyTraceBack_Type -#define is_tracebackobject PyTraceBack_Check - -typeobject Tracebacktype = { - OB_HEAD_INIT(&Typetype) - 0, - "traceback", - sizeof(tracebackobject), - 0, - (destructor)tb_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)tb_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ -}; - -static tracebackobject * -newtracebackobject(next, frame, lasti, lineno) - tracebackobject *next; - frameobject *frame; - int lasti, lineno; -{ - tracebackobject *tb; - if ((next != NULL && !is_tracebackobject(next)) || - frame == NULL || !is_frameobject(frame)) { - err_badcall(); - return NULL; - } - tb = NEWOBJ(tracebackobject, &Tracebacktype); - if (tb != NULL) { - XINCREF(next); - tb->tb_next = next; - XINCREF(frame); - tb->tb_frame = frame; - tb->tb_lasti = lasti; - tb->tb_lineno = lineno; - } - return tb; -} - -static tracebackobject *tb_current = NULL; - -int -tb_here(frame) - frameobject *frame; -{ - tracebackobject *tb; - tb = newtracebackobject(tb_current, frame, frame->f_lasti, frame->f_lineno); - if (tb == NULL) - return -1; - XDECREF(tb_current); - tb_current = tb; - return 0; -} - -object * -tb_fetch() -{ - object *v; - v = (object *)tb_current; - tb_current = NULL; - return v; -} - -int -tb_store(v) - object *v; -{ - if (v != NULL && !is_tracebackobject(v)) { - err_badcall(); - return -1; - } - XDECREF(tb_current); - XINCREF(v); - tb_current = (tracebackobject *)v; - return 0; -} - -static void -tb_displayline(f, filename, lineno, name) - object *f; - char *filename; - int lineno; - char *name; -{ - FILE *xfp; - char linebuf[1000]; - int i; -#ifdef MPW - /* This is needed by MPW's File and Line commands */ -#define FMT " File \"%.900s\"; line %d # in %s\n" -#else - /* This is needed by Emacs' compile command */ -#define FMT " File \"%.900s\", line %d, in %s\n" -#endif - xfp = fopen(filename, "r"); - if (xfp == NULL) { - /* Search tail of filename in sys.path before giving up */ - object *path; - char *tail = strrchr(filename, SEP); - if (tail == NULL) - tail = filename; - else - tail++; - path = sysget("path"); - if (path != NULL && is_listobject(path)) { - int npath = getlistsize(path); - int taillen = strlen(tail); - char namebuf[MAXPATHLEN+1]; - for (i = 0; i < npath; i++) { - object *v = getlistitem(path, i); - if (is_stringobject(v)) { - int len; - len = getstringsize(v); - if (len + 1 + taillen >= MAXPATHLEN) - continue; /* Too long */ - strcpy(namebuf, getstringvalue(v)); - if (strlen(namebuf) != len) - continue; /* v contains '\0' */ - if (len > 0 && namebuf[len-1] != SEP) - namebuf[len++] = SEP; - strcpy(namebuf+len, tail); - xfp = fopen(namebuf, "r"); - if (xfp != NULL) { - filename = namebuf; - break; - } - } - } - } - } - sprintf(linebuf, FMT, filename, lineno, name); - writestring(linebuf, f); - if (xfp == NULL) - return; - for (i = 0; i < lineno; i++) { - if (fgets(linebuf, sizeof linebuf, xfp) == NULL) - break; - } - if (i == lineno) { - char *p = linebuf; - while (*p == ' ' || *p == '\t' || *p == '\014') - p++; - writestring(" ", f); - writestring(p, f); - if (strchr(p, '\n') == NULL) - writestring("\n", f); - } - fclose(xfp); -} - -static void -tb_printinternal(tb, f, limit) - tracebackobject *tb; - object *f; - int limit; -{ - int depth = 0; - tracebackobject *tb1 = tb; - while (tb1 != NULL) { - depth++; - tb1 = tb1->tb_next; - } - while (tb != NULL && !intrcheck()) { - if (depth <= limit) - tb_displayline(f, - getstringvalue(tb->tb_frame->f_code->co_filename), - tb->tb_lineno, - getstringvalue(tb->tb_frame->f_code->co_name)); - depth--; - tb = tb->tb_next; - } -} - -int -tb_print(v, f) - object *v; - object *f; -{ - object *limitv; - int limit = 1000; - if (v == NULL) - return 0; - if (!is_tracebackobject(v)) { - err_badcall(); - return -1; - } - limitv = sysget("tracebacklimit"); - if (limitv && is_intobject(limitv)) { - limit = getintvalue(limitv); - if (limit <= 0) - return 0; - } - writestring("Traceback (innermost last):\n", f); - tb_printinternal((tracebackobject *)v, f, limit); - return 0; -} diff --git a/README b/README deleted file mode 100644 index 3bda2f8bc2..0000000000 --- a/README +++ /dev/null @@ -1,569 +0,0 @@ -This is Python release 1.3 -========================== - - -What's new in this release? ---------------------------- - -- Keyword parameters (see the last chapter of the tutorial). -- Third argument to raise (the stacktrace to provide). -- Faster function and method calls. -- Jim Fulton's abstract object interface (Include/abstract.h). -- Support for Tk 4.0 in Tkinter (Tkinter now supports keywords!). -- Rewritten htmllib.py (HTML parser), with new formatter.py. -- Rewritten rexec.py (restricted execution). -- New modules ni.py and ihooks.py (package support and more). -- And lots more that you'll have to discover on your own (see chapter - 12 of the Tutorial or the Misc/NEWS file). - - -What is Python anyway? ----------------------- - -Python is an interpreted object-oriented programming language, and is -often compared to Tcl, Perl or Scheme. For a quick summary of what -Python can mean for a UNIX/C programmer, read Misc/BLURB.LUTZ. - - -If you don't read instructions ------------------------------- - -Congratulations on getting this far. :-) - -To start building right away (on UNIX): type "./configure" in the -current directory and when it finishes, type "make". The section -Build Instructions below is still recommended reading. :-) - - -Copyright issues ----------------- - -Python is COPYRIGHTED but free to use for all. See the full copyright -notice at the end of this file. - -The Python distribution is *not* affected by the GNU Public Licence -(GPL). There are interfaces to some GNU code but these are entirely -optional and no GNU code is distributed with Python. For all these -packages, GPL-free public domain versions also exist. - - -A modest plug -============= - - -************************************************************************* -* * -* Python exists, and is free, thanks to the contributed efforts * -* of many people. The PSA was created to maximize the results * -* of those efforts, by helping to coordinate them. The PSA * -* operates web, ftp and email servers, organizes Python * -* workshops, and engages in other activities that benefit the * -* Python user community. The PSA is seeking support for these * -* activities. See this URL for information on how to join: * -* http://www.python.org/psa/Joining.html * -* * -************************************************************************* - - -Build instructions -================== - -Before you start building Python, you must first configure it. This -entails (at least) running the script "./configure", which figures out -your system configuration and creates several Makefiles. (It takes a -minute or two -- please be patient!) When it's done, you are ready to -run make. Typing "make" in the toplevel directory will recursively -run make in each of the subdirectories Parser, Objects, Python and -Modules, creating a library file in each one. The executable of the -interpreter is built in the Modules subdirectory and moved up here -when it is built. If you want or need to, you can also chdir into -each subdirectory in turn and run make there manually (do the Modules -subdirectory last!). - -NOTE: if you rerun the configure script with different options, remove -all object files by running "make clean" before rebuilding. Believe -it or not, "make clean" sometimes helps to clean up other inexplicable -problems as well. Try it before sending in a bug report! - - -Troubleshooting ---------------- - -If you run into trouble, see section 3 of the FAQ (file Misc/FAQ) for -hints on what can go wrong, and how to fix it. - - -Platform specific notes ------------------------ - -(Some of these may no longer apply. If you find you can build Python -on these platforms without the special directions mentioned here, let -me know so I can remove them!) - -Linux: Once you've built Python, use it to run the regen.py script in - the Lib/linux1 directory. Apparently the files as distributed - don't match the system headers on some Linux versions. - -AIX: Read the file Misc/AIX-NOTES before trying to build. - -HP-UX: Read the file Misc/HPUX-NOTES if you want to be able to - use shared libraries for dynamically loaded modules. - -Minix: When using ack, use "CC=cc AR=aal RANLIB=: ./configure"! - -SCO: 1) Everything works much better if you add -U__STDC__ to the - defs. This is because all the SCO header files are broken. - Anything that isn't mentioned in the C standard it's - conditionally excluded when __STDC__ is defined. - - 2) Due to the U.S. export restrictions, SCO broke the crypt - stuff out into a separate library, libcrypt_i.a so the LIBS - needed be set to: - - LIBS=' -lsocket -lcrypt_i' - - -Configuring the set of built-in modules ---------------------------------------- - -You can configure the interpreter to contain fewer or more built-in -modules by editing the file Modules/Setup. This file is initially -copied (when the toplevel Makefile makes Modules/Makefile for the -first time) from Setup.in; if it does not exist yet, make a copy -yourself. Never edit Setup.in -- always edit Setup. Read the -comments in the file for information on what kind of edits you can -make. When you have edited Setup, Makefile and config.c in Modules -will automatically be rebuilt the next time you run make in the -toplevel directory. - -Especially on SGI IRIX, there are modules that interface to many SGI -specific system libraries, e.g. the GL library and the audio hardware. - - -Setting the optimization/debugging options ------------------------------------------- - -If you want to change the optimization/debugging options for the C -compiler, assign to the OPT variable on the toplevel make command; -e.g. "make OPT=-g" will build a debugging version of Python on most -platforms. The default is OPT=-O; a value for OPT in the environment -when the configure script is run overrides this default (likewise for -CC; and the initial value for LIBS is used as the base set of -libraries to link with). - - -Testing -------- - -To test the interpreter that you have just built, type "make test". -This runs the test set silently, twice (once with no compiled files, -once with the compiled files left by the previous test run). Each -test run should print "All tests OK." and nothing more. (The test set -does not test the built-in modules, but will find most other problems -with the interpreter.) - -IMPORTANT: If the tests fail and you decide to mail a bug report, -*don't* include the output of "make test". It is useless. Run the -following command instead: - - PYTHONPATH=../Lib:../Lib/test:./Modules ./python -c 'import testall' - -(substituting the top of the source tree for .. if you built in a -different directory). This gives the output of the tests and shows -which test failed. - - -Installing ----------- - -To install the interpreter as /usr/local/bin/python, type "make -install". To install the library as /usr/local/lib/python, type "make -libinstall". To install the manual page as -/usr/local/man/man1/python.1, type "make maninstall". To install the -Emacs editing mode for python, manually copy the file -Misc/python-mode.el to your local Emacs lisp directory. The directory -/usr/local can be overridden at configuration time by passing ---prefix=DIRECTORY to the configure script, or at make time by passing -"prefix=DIRECTORY" to make. See below for more information on --prefix. - -If you plan to do development of extension modules or to embed Python -in another application and don't want to reference the original source -tree, you can type "make inclinstall" and "make libainstall" to -install the include files and lib*.a files, respectively, as -/usr/local/include/Py/*.h and /usr/local/lib/python/lib/lib*.a. The -make libainstall target also installs copies of several other files -used or produced during the build process which are needed to build -extensions or to generate their Makefiles. - - -Configuration options and variables ------------------------------------ - -Some special cases are handled by passing environment variables or -options to the configure script. - -NOTE: if you rerun the configure script with different options, remove -all object files by running "make clean" before rebuilding. - ---with(out)-gcc: The configure script uses gcc (the GNU C compiler) if - it finds it. If you don't want this, or if this compiler is - installed but broken on your platform, pass the option - --without-gcc. You can also pass "CC=cc" (or whatever the - name of the proper C compiler is) in the environment, but the - advantage of using --without-gcc is that this option is - remembered by the config.status script for its --recheck - option. - ---prefix, --exec-prefix: If you want to install the binaries and the - Python library somewhere else than in /usr/local/{bin,lib}, - you can pass the option --prefix=DIRECTORY; the interpreter - binary will be installed as DIRECTORY/bin/python and the - library files as DIRECTORY/lib/python/*. If you pass - --exec-prefix=DIRECTORY (as well) this overrides the - installation prefix for architecture-dependent files (like the - interpreter binary). Note that --prefix=DIRECTORY also - affects the default module search path (sys.path), when - Modules/config.c is compiled. Passing make the option - prefix=DIRECTORY (and/or exec_prefix=DIRECTORY) overrides the - prefix set at configuration time; this may be more convenient - than re-running the configure script if you change your mind - about the install prefix... - ---with-readline: You can use the GNU readline library to improve the - interactive user interface: this gives you line editing and - command history when calling python interactively. You need - to configure build the GNU readline library before running the - configure script. Its sources are not distributed with - Python; you can ftp them from any GNU mirror site, or from its - home site: - <URL:ftp://slc2.ins.cwru.edu/pub/dist/readline-2.0.tar.gz> (or - a higher version number -- using version 1.x is not - recommended). - - A GPL-free version was posted to comp.sources.misc in volume - 31 and is widely available from FTP archive sites, e.g. - <URL:ftp://gatekeeper.dec.com/.b/usenet/comp.sources.misc/ - volume31/editline/part01.Z> - - Pass the Python configure script the option - --with-readline=DIRECTORY where DIRECTORY is the absolute - pathname of the directory where you've built the readline - library. Some hints on building and using the readline - library are in the FAQ (file Misc/FAQ). - ---with-thread: On SGI IRIX, and on Sun SOLARIS 2, you can use multiple - threads. To enable this, pass --with-thread. In the - Modules/Setup file, enable the thread module. (Threads aren't - enabled automatically because there are run-time penalties - when support for them is compiled in even if you don't use - them.) - ---with-sgi-dl: On SGI IRIX 4, dynamic loading of extension modules is - supported by the "dl" library by Jack Jansen, which is - ftp'able from <URL:ftp://ftp.cwi.nl/pub/dynload/dl-1.6.tar.Z>. - This is enabled (after you've ftp'ed and compiled the dl - library!) by passing --with-sgi-dl=DIRECTORY where DIRECTORY - is the absolute pathname of the dl library. (Don't bother on - IRIX 5, it already has dynamic linking using SunOS style - shared libraries.) Support for this feature is deprecated. - ---with-dl-dld: Dynamic loading of modules is rumoured to be supported - on some other systems: VAX (Ultrix), Sun3 (SunOS 3.4), Sequent - Symmetry (Dynix), and Atari ST. This is done using a - combination of the GNU dynamic loading package - (<URL:ftp://ftp.cwi.nl/pub/dynload/dl-dld-1.1.tar.Z>) and an - emulation of the SGI dl library mentioned above (the emulation - can be found at - <URL:ftp://ftp.cwi.nl/pub/dynload/dld-3.2.3.tar.Z>). To - enable this, ftp and compile both libraries, then call the - configure passing it the option - --with-dl-dld=DL_DIRECTORY,DLD_DIRECTORY where DL_DIRECTORY is - the absolute pathname of the dl emulation library and - DLD_DIRECTORY is the absolute pathname of the GNU dld library. - (Don't bother on SunOS 4 or 5, they already have dynamic - linking using shared libraries.) Support for this feature is - deprecated. - ---with-libm, --with-libc: It is possible to specify alternative - versions for the Math library (default -lm) and the C library - (default the empty string) using the options - --with-libm=STRING and --with-libc=STRING, respectively. E.g. - if your system requires that you pass -lc_s to the C compiler - to use the shared C library, you can pass --with-libc=-lc_s. - These libraries are passed after all other libraries, the C - library last. - - -Extensions ----------- - -You can also build an "extended" interpreter, using modules that are -not contained in the Modules directory. Extensions are distributed as -a separate tar file (currently extensions.tar.gz). See the README -file there. - - -Building for multiple architectures (using the VPATH feature) -------------------------------------------------------------- - -If your file system is shared between multiple architectures, it -usually is not necessary to make copies of the sources for each -architecture you want to support. If the make program supports the -VPATH feature, you can create an empty build directory for each -architecture, and in each directory run the configure script (on the -appropriate machine with the appropriate options). This creates the -necessary subdirectories and the Makefiles therein. The Makefiles -contain a line VPATH=... which points to directory containing the -actual sources. (On SGI systems, use "smake" instead of "make" if you -use VPATH -- don't try gnumake.) - -For example, the following is all you need to build a minimal Python -in /usr/tmp/python (assuming ~guido/src/python is the toplevel -directory and you want to build in /usr/tmp/python): - - $ mkdir /usr/tmp/python - $ cd /usr/tmp/python - $ ~guido/src/python/configure - [...] - $ make - [...] - $ - -Note that Modules/Makefile copies the original Setup file to the build -directory if it finds no Setup file there. This means that you can -edit the Setup file for each architecture independently. For this -reason, subsequent changes to the original Setup file are not tracked -automatically, as they might overwrite local changes. To force a copy -of a changed original Setup file, delete the target Setup file. (The -makesetup script supports multiple input files, so if you want to be -fancy you can change the rules to create an empty Setup.local if it -doesn't exist and run it with arguments $(srcdir)/Setup Setup.local; -however this assumes that you only need to add modules.) - - -Building on non-UNIX systems ----------------------------- - -On non-UNIX systems, you will have to fake the effect of running the -configure script manually. A good start is to copy the file -config.h.in to config.h and edit the latter to reflect the actual -configuration of your system. Most symbols must simply be defined as -1 only if the corresponding feature is present and can be left alone -otherwise; however RETSIGTYPE must always be defined, either as int or -as void, and the *_t type symbols must be defined as some variant of -int if they need to be defined at all. Then arrange that the symbol -HAVE_CONFIG_H is defined during compilation (usually by passing an -argument of the form `-DHAVE_CONFIG_H' to the compiler, but this is -necessarily system-dependent). - -I have tried to collect instructions, Makefiles and additional sources -for various platforms in this release. The following directories -exist: - -Mac/ Apple Macintosh, using THINK C 6.0 or MPW 3.2. -Dos/ MS-DOS and Windows 3.1, using Microsoft C. -Nt/ Windows NT, using Microsoft Visual C/C++. -Os2/ OS/2. - -Most of these instructions were last tested with a previous Python -release, so you may still experience occasional problems. If you have -fixes or suggestions, please let me know and I'll try to incorporate -them in the next release. - - - -Miscellaneous issues -==================== - - -Documentation -------------- - -All documentation is provided in the subdirectory Doc in the form of -LaTeX files. In order of importance for new users: Tutorial (tut), -Library Reference (lib), Language Reference (ref), Extending (ext). -Especially the Library Reference is of immense value since much of -Python's power (including the built-in data types and functions!) is -described here. - -To print the documentation from the LaTeX files, chdir into the Doc -subdirectory, type "make" (let's hope you have LaTeX installed!), and -send the four resulting PostScript files (tut.ps, lib.ps, ref.ps, and -ext.ps) to the printer. See the README file there. - -All documentation is also available on-line via the World-Wide Web -(WWW): <URL:http://www.cwi.nl/~guido/Python.html>. It can also be -downloaded separately from the ftp archives (see below) in Emacs INFO, -HTML or PostScript form -- see the FAQ (file Misc/FAQ) for more info. - - -Emacs mode ----------- - -There's an excellent Emacs editing mode for Python code; see the file -Misc/python-mode.el. Originally written by Tim Peters, who's no -longer on the net, it is now maintained by Barry Warsaw -<bwarsaw@cnri.reston.va.com>. - -BTW, if you want to use font-lock for Python sources, here's something -to put in your .emacs file: - - (defun my-python-mode-hook () - (setq font-lock-keywords python-font-lock-keywords) - (font-lock-mode 1)) - (add-hook 'python-mode-hook 'my-python-mode-hook) - - - -Bug reports ------------ - -Bugs are best reported to the comp.lang.python newsgroup or the Python -mailing list -- see the section "Newsgroup and mailing list" below. -Before posting, read the FAQ (file Misc/FAQ) first to see if your -problem has already been answered! - - -Ftp access ----------- - -Python's "home ftp site" is ftp.cwi.nl, directory pub/python. See the -FAQ (file Misc/FAQ) for a list of other ftp sites carrying the Python -distribution. - - -Newsgroup and mailing list --------------------------- - -There are a newsgroup and a mailing list devoted to Python -programming, design and bugs. The newsgroup, comp.lang.python, -contains exactly the same messages as the mailing list. To subscribe -to the mailing list, send mail containing your real name and e-mail -address to "python-list-request@cwi.nl" (a real person reads these -messages, so no LISTPROC or Majordomo commands, please). - - -The Tk interface ----------------- - -Tk (the user interface component of John Ousterhout's Tcl language) is -also usable from Python. Since this requires that you first build and -install Tcl/Tk, the Tk interface is not enabled by default. It -requires Tcl 7.4 and Tk 4.0. (Support for Tk 3.6 and Tcl 7.3 can be -found in Lib/tk3inter/.) - -To enable the Python/Tk interface, once you've built and installed -Tcl/Tk, all you need to do is edit two lines in Modules/Setup; search -for the string "_tkinter". Un-comment one (normally the first) of the -lines beginning with "#_tkinter" and un-comment the line beginning with -"#TKPATH". (If you have installed Tcl/Tk in unusual places you will -have to edit the first line as well to fix the -I and -L options.) -See the Build Instructions above for more details. - -There is little documentation. Begin with fetching the "Tk Lifesaver" -document, e.g. <URL:ftp://ftp.cwi.nl/pub/python/doc/tkinter-doc.tar.gz> -(a gzipped tar file containing a PostScript file). There are demos in -the Demo/tkinter directory, in the subdirectories guido, matt and www. - -Note that there's a Python module called "Tkinter" (capital T) which -lives in Lib/tkinter/Tkinter.py, and a C module called "tkinter" -(lower case t) which lives in Modules/_tkinter.c. Demos and -normal Tk applications only import the Python Tkinter module -- only -the latter uses the C _tkinter module directly. In order to find the C -_tkinter module, it must be compiled and linked into the Python -interpreter -- the _tkinter line in the Setup file does this. In order -to find the Python Tkinter module, sys.path must be set correctly -- -the TKPATH assignment in the Setup file takes care of this, but only -if you install Python properly ("make install libinstall"). (You can -also use dynamic loading for the C _tkinter module, in which case you -must manually fix up sys.path or set $PYTHONPATH for the Python -Tkinter module.) - -See <URL:http://www.smli.com/research/tcl/> for more info on where -to get Tcl/Tk. - - -Distribution structure ----------------------- - -Most subdirectories have their own README file. Most files have -comments. - -ChangeLog A raw list of changes since the first 1.0.0 BETA release -Contrib/ Interesting or useful Python code contributed by others -Demo/ Demonstration scripts, modules and programs -Doc/ Documentation (LaTeX sources) -Extensions/ Extension modules (distributed separately) -Grammar/ Input for the parser generator -Include/ Public header files -Lib/ Python library modules -Makefile.in Source from which config.status creates Makefile -Misc/ Miscellaneous files -Modules/ Implementation of most built-in modules -Objects/ Implementation of most built-in object types -Parser/ The parser and tokenizer and their input handling -Python/ The "compiler" and interpreter -README The file you're reading now -Tools/ Some useful programs written in Python -acconfig.h Additional input for the autoheader program -config.h.in Source from which config.status creates config.h -configure Configuration shell script (GNU autoconf output) -configure.in Configuration specification (GNU autoconf input) - -The following files will (may) be created in the toplevel directory by -the configuration and build processes: - -Makefile Build rules -config.cache cache of configuration variables -config.h Configuration header -config.log log from last configure run -config.status status from last run of configure script -python The executable interpreter -tags, TAGS Tags files for vi and Emacs - - -Author's address ----------------- - -Guido van Rossum -CWI, dept. CST -P.O. Box 94079 -1090 GB Amsterdam -The Netherlands - -E-mail: guido@cwi.nl - - - -Copyright notice -================ - -The Python source is copyrighted, but you can freely use and copy it -as long as you don't change or remove the copyright notice: - ----------------------------------------------------------------------- -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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. ----------------------------------------------------------------------- - - ---Guido van Rossum, CWI, Amsterdam <mailto:guido@cwi.nl> -<http://www.cwi.nl/~guido/> diff --git a/TODO b/TODO deleted file mode 100644 index 8802fbd50b..0000000000 --- a/TODO +++ /dev/null @@ -1,475 +0,0 @@ -(-) many module should export their symbolic constants instead of -relying on a module written in Python - -(-) change regexmodule.c to cooperate with other non-python users and -to export the symbolic constants - -(-) save/restore sys.exc_{type,value,traceback} around except clauses. - -(-) don't call class instance's __del__ more than once????? - -(-) add "access" to posix? What name should it have? - -(-) add facility to "freeze" lists and dictionaries? - -(-) add WNOHANG to posix - -(-) support lists in newgetargs() - -(-) syntax errors detected during compilation should give line number - -(-) dbm.open(): rwmode, filemode should be made optional; same for gdbm - -(-) find a bsd hash interface - -(-) posix.mkdir(): mode should be made optional - -(-) find a more useful order than alphabetical for Doc/libfuncs.tex - -====================================================================== - -(*) use my getopt.c on Linux - -(*) get Extensions/X11/Doc checked in and out - -(-) investigate PPRC <URL:ftp://ftp.parc.xerox.com/pub/ppcr/> - -(*) add buffering parameter to fdopen() and popen() - -(-) interface to getdtablesize() in posix - -(-) reentrancy with global variables vs. decref in -./Modules/cdmodule.c ./Modules/flmodule.c ./Objects/accessobject.c -./Objects/frameobject.c ./Python/traceback.c - -(*) fix reentrancy in list updates? - -(-) speed up regsub.gsub - -(*) change md5.md5() to md5.new() - -(-) try posixenviron.c and merge back into posixmodule.c? - -(*) document chown() - -(-) add and document chroot() ? - -(*) use add gethostname_r and release thread lock when it exists - -(-) Add `@CFLAGS@', `@CPPFLAGS@', and `@LDFLAGS@' to `Makefile.in' - -(-) modules should be able to define a module destructor hook - -(-) destroy modules in reverse order of importation? - -(-) make array a standard built-in object - -(-) makesetup should accept .o files without corresponding .c file - -(*) use autoconf 2.0 - -====================================================================== -Release 1.1.1 (10 Nov 1994) -====================================================================== - -(-) try Boehm/Dehmers/Weiser conservative garbage collector - -(*) implement new 'flatten' module - -(-) document new Python/C API - -(*) __import__, module imp - -(-) add various things to module dictionary, e.g. pathname, dictionary -where found, __version__ string? - -(-) pass dict of builtins to exec / execfile / eval ??? - -(?) stack frame correspondence problem (Jim Roskind) -(probably solved by err_fetch / err_restore) - -(-) make lots of places use newgetargs - -(*) no tp_str member in typeobject - -(-) readline 2.0 on sequent has ^C problem (works only first time) - -(*) add explanatory comments to Setup (especially about SGI modules -like 'cd') - -(-) need to add truncate() and ftruncate() to posixmodule.c (Windows: -chsize(fd, size) (solution: added to file objects instead) - -====================================================================== -Release 1.1 (11 Oct 1994) -====================================================================== - -(-) improve performance of list.append/insert etc. by keeping high/low -watermark instead of realloc'ing each time? - -(-) findmethod should cache (also findmember?) - -(-) sysget("check_interval") is called before each method call which -breaks dictlookup caching - -(*) core dump on import of ridiculously long module name - -(-) core dump on repr / print of deeply nested or recursive object - -(*) parsing from string should calculate line numbers - -(-) whrandom doc needs update - -(*) mpz power is still binary insterad of ternary - -(*) design interface to call arbitrary asynchronous routines - -(*) whrandom.set...(0,0,0) doesn't generate random numbers - -(*) Lance's latest curses additions - -(*) Jack's new code: - (*) new xxmodule.c - (*) mac has type for .pyc files - (*) should run .pyc files when passed as command line argument - -(*) all new all singing all dancing freeze script - -(*) make clean should remove *.so and not Makefile.pre - -(-) fix signalmodule.c to re-establish SIGC[H]LD handler - -(*) try out Kees Blom's railroad diagram generator - -(-) redesign error handling (cf. Donald's mail) - -(*) do MPW and THINK still not support sys_errlist? Indeed not (neither). - -(-) does MPW 3.2 need the MPW_881_BUG defined in Parser/acceler.c - -(-) rename MPW_3_1 define (which really means 3.x) - -(*) incorporate urlparse.py, uu.py - -(*) rewrite instance __getattr__ etc. to store ptr in class instead of -instance -- also have separate __delattr__ - -(-) add warning to docs about sys.exc_traceback and sys.last_traceback. - -(-) Some stdwin wishes: - - (-) stdwinmodule should keep track of textedit rec's per window - (in a chain) so it can unlink them when the window is closed - before the te rec - - (-) textedit flashes at return or backspace - - (-) there's no way to show the text caret after a multi-line paste? - -(*) termios module - -(*) put signal patches out separately - -(-) latex docs for signal module - -(*) More MPW and Mac changes - -(*) Sjoerd's compileall script - -(-) systematically create /usr/local/lib/python/<machine>-<os>/ - subdirectories, with a lib/ subdirectory containing the lib*.a - files etc. - -(-) need newer DOS binary (16 bit version doesn't do default args) - -(*) support for dynamically loadable libraries in makesetup and Extensions. - e.g. add a make rule to build .so files (unfortunately need to figure - out what ld option is needed) (more appropriate for makesetup - script?) - -(*) Move tkinter into the standard Modules directory; Tkinter c.s. to - Lib/tkinter etc. (???) - -(-) document Tk - -(-) class browser - -(-) interactive Python GUI (a la NT thingie) - -(*) speedup finddfa (and classify?) - -(-) more stuff under CVS (demo, extensions) - -(*) Mac port of 1.1 - -(*) Mac port of STDWIN 0.9.9 to THINK C 6.0 - -(-) use const for char * parameters (and many more) where possible - -(-) The Great Renaming! - -(*) redo __xxx__ operators for class instances - -(-) document __getattr__, __setattr__ - -(*) add __delattr__ to class instances - -(-) many things that take strings should also take arrays of chars - -(-) add list of existing extensions to FAQ - -(-) update "recent additions" chapter in tutorial - -(-) rewrite "output formatting" chapter in tutorial - -(*) pass OPT from environment via configure to Makefile - -(*) version.c should be recompiled for each link - -(*) stropmodule should export find/rfind instead of index/rindex - -(*) add __getattr__, __setattr__ to class instances - -(*) fix pow(x, y, z) for integers - -(*) add tuple(seq) to turn any sequence into a tuple - -(*) Win32s for PC - -(*) integrate NT changes - -(*) write a script and add a "Make" rule (perhaps) that changes - #!/usr/local/bin/python to something else in all scripts around. - -(*) int*int overflow check shouldn't doubles on alpha (cf. John Tromp's mail) - -(*) add signal.alarm() - -(*) when abort()ing because of unexpected exception, print a message - first (Jack) - ----------------------------------------------------------------------- -(from BUGS1.0.1) ----------------------------------------------------------------------- -(-) document addpack, urllib, ... - -(*) import.c from JaapV - -(*) document os.exec* - -(*) name sunaudiodevmodule.c is too long - -(*) play with / include SUIT interface - -(-) make regsub.[g]sub() optionally case insensitive - -====================================================================== - -(*) ought to use features from autoconf 1.8 - -(*) errors in __repr__() are handled wrong when called from format - -(*) long(0x80000000) has wrong value! - -(-) hex(0x80000000) shouldn't have sign (?) - -(*) need way to set buffering at file open time - -(*) need way to force stdout unbuffered - -(*) restart CVS tree - -(?) build shared libs for SunOS 4.1.3 - -(-) dynamic linking on the Mac (is this a dream?) - -(*) X patches from Adrian Phillips - -(*) Jaap's freeze script - -(-) Incorporate with contrib status: - - additions to glmodule by rg3h - (*) Jaap's posixfile module (with locking) - (*) pthreads interface - -(-) Later: - - put the offending object in IOError and posix.error - - make module marshal work with user-defined file-like objects - - built-in help? - - hierarchical module names? - -Big plans: - -- allow separate interpreters (a la Xt's Applocation Contexts, and Tcl) -- great renaming -- complete reflexive nature of the language, e.g. have interfaces et -create any kind of object -(*) GUI interface a la Tk - - -====================================================================== -For FAQ: - -(*) why don't strings (numbers, tuples, ...) have methods / attributes - -(*) why are strings / numbers / tuples immutable - -why don't list methods return self - -====================================================================== -PM/TODO list after Egypt (from mailing list): - -make .pyc files executable (how?) - -thread status and improvements (lock stmt; signal/wait) - -optional optimizations - -pthread migration - -(*) test/incorporate new SUIT - -shorten excessively long filenames (sunaudiodevmodule.c) - -(*) default parameter values - -multiple interpreter objects - -(*) import shlib bug (irix5.2) (reload, dlclose) - -(*) addpack.py - -(*) newmodule.c (or other hacks to create new modules, classes, functions - etc. from their components) - -persistency - -new Dbhash.py, dbhash library - -(-) reraise; or raise 3rd param for traceback? - -or- except type, value, tbackobjec - -(-) redesign exceptions from scratch? - -(-) dbm objects miss items(), values() methods - -(*) jar's new profile - -(-) answer q about coerce() - -(*) reconsider pass [expression] ??? -or- don't print non-interactive - exprs -or- option to suppress printing non-None expressions - -(*) should be able to hash code objs (add fns to convert between lists/tuples) - -(-) describe() ? - -(-) distribute demo2 with Holmes - -(*) re-reply on try-continue - -(-) classes are too slow - -(-) add += etc. ? - -optimize tuple = tuple - -allow (a, b) = [1, 2] and [1, 2] = (1, 2) ??? - -wustl is not un the northwest of the US? - -(*) MPW doesn't like \000 in string literals? - -MPW patches, unixemu patches - -prepare tar files with - - mac think projects (*) - - mpw makefiles - - dos makefiles - - mac unixemu lib - -explain rules about == vs. 'is' for strings (* by others on the list) - -(*) bug in ceval.c DELETE_FAST - -(*) possible optimize LOAD_NAME -> LOAD_GLOBAL - -get dos python with suit (inesc) - -(*) docs for try/continue are wrong and unclear - -better hashing fn? - -(*) add improved nested indent to python-mode.el - -(*) add a section to tutorial on "new" features - -rewrite section on formatting in tutorial - -====================================================================== -TODO-TOO list: - -test for overflow when converting python long to float - -lift restrictions on tuple or list in many cases - -(*) allow long ints with sensible values for getargs "i" - -(*) multiline string literals - -what to do about 64-bit int literals (on 64-bit machines) in .pyc -files? (Currently truncated w/o warning!) - -DOCUMENTATION UPDATE! E.g. ref.tex doesn't describe: -(*) - line joins w/o backslash -(*) - double-quoted strings; \" in strings - - more? -Should double-check all changes with docs! - -(?) Interrupting output still sometimes doesn't call clearerr() properly - -sometimes ghost errors when interrupting during debugging in -'continue' mode? - -typing a comment to a primary prompt shouldn't issue a secondary prompt - -readline: add hooks to recognize Python syntax and to expand Python -commands and names - -should have absolute pathnames in function objects - -in general check that all the exceptions are modernized and that the -messages aren't giving the same error twice (e.g., stdwinmodule.c!) - -- check read/write allowed for file objects - -- introduce macros to set/inspect errno for syscalls, to support things - like getoserr() - -====================================================================== -DOS/Windows Python - -(???) command line options? - -(*) os.system() - -(???) interrupts - -(???) wrap - -(*) pc module - -(*) dospath.py - -DOS/Windows Python -- TO DO - -(*) memtest from config.h - -(*) copy sources back - -(*) build DOS version - -(*) distribute 386 version - -(*) Mac 1.0.1 release? -====================================================================== diff --git a/Tools/README b/Tools/README deleted file mode 100644 index acf755af8e..0000000000 --- a/Tools/README +++ /dev/null @@ -1,14 +0,0 @@ -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! - -freeze Create a stand-alone executable from a Python program. - -modulator Interactively generate boiler plate for an extension - module. Works easiest if you have Tk. - -scripts A number of useful single-file programs, e.g. for - converting old Python sources to the current language - definition. diff --git a/Tools/bgen/README b/Tools/bgen/README deleted file mode 100644 index 70700c652a..0000000000 --- a/Tools/bgen/README +++ /dev/null @@ -1,7 +0,0 @@ -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! diff --git a/Tools/bgen/bgen/bgen.py b/Tools/bgen/bgen/bgen.py deleted file mode 100644 index db28b0a87d..0000000000 --- a/Tools/bgen/bgen/bgen.py +++ /dev/null @@ -1,12 +0,0 @@ -"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/Tools/bgen/bgen/bgenBuffer.py b/Tools/bgen/bgen/bgenBuffer.py deleted file mode 100644 index af9fb1976c..0000000000 --- a/Tools/bgen/bgen/bgenBuffer.py +++ /dev/null @@ -1,243 +0,0 @@ -"""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] - - def declare(self, name): - self.declareBuffer(name) - self.declareSize(name) - - def declareBuffer(self, name): - self.declareInputBuffer(name) - self.declareOutputBuffer(name) - - def declareInputBuffer(self, name): - Output("%s *%s__in__;", self.datatype, name) - - def declareOutputBuffer(self, name): - Output("%s %s__out__[%s];", self.datatype, name, self.size) - - def declareSize(self, name): - Output("%s %s__len__;", self.sizetype, name) - Output("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) - 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): - 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 declareOutputBuffer(self, name): - pass - - -class OutputOnlyBufferMixIn(OutputOnlyMixIn): - - def declareInputBuffer(self, name): - pass - - -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 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) - - -# ----- 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 declareInputBuffer(self, name): - Output("%s *%s__in__;", self.type, name) - - def declareSize(self, name): - Output("int %s__in_len__;", name) - - def declareOutputBuffer(self, name): - Output("%s %s__out__;", self.type, 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 declareSize(self, name): - pass - - 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 declareSize(self, name): - pass - - def passOutput(self, name): - return "%s__out__" % name diff --git a/Tools/bgen/bgen/bgenGenerator.py b/Tools/bgen/bgen/bgenGenerator.py deleted file mode 100644 index b5bd2c6be9..0000000000 --- a/Tools/bgen/bgen/bgenGenerator.py +++ /dev/null @@ -1,259 +0,0 @@ -from bgenOutput import * -from bgenType import * -from bgenVariable import * - - -Error = "bgenGenerator.Error" - - -# Strings to specify argument transfer modes in generator calls -IN = "in" -OUT = "out" -INOUT = IN_OUT = "in-out" - - -class BaseFunctionGenerator: - - def __init__(self, name): - print "<--", name - self.name = name - self.prefix = name - self.objecttype = "PyObject" # Type of _self argument to function - - def setprefix(self, prefix): - self.prefix = prefix - - def generate(self): - print "-->", self.name - self.functionheader() - self.functionbody() - self.functiontrailer() - - def functionheader(self): - Output() - Output("static PyObject *%s_%s(_self, _args)", - self.prefix, self.name) - IndentLevel() - Output("%s *_self;", self.objecttype) - Output("PyObject *_args;") - DedentLevel() - OutLbrace() - Output("PyObject *_res = NULL;") - - def functionbody(self): - Output("/* XXX To be provided */") - - def functiontrailer(self): - OutRbrace() - - def reference(self, name = None): - if name is None: - name = self.name - docstring = self.docstring() - Output("{\"%s\", (PyCFunction)%s_%s, 1,", name, self.prefix, self.name) - Output(" %s},", stringify(docstring)) - - def docstring(self): - return None - - -_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): - BaseFunctionGenerator.__init__(self, name) - 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): - BaseFunctionGenerator.__init__(self, name) - 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): - import string - input = [] - output = [] - for arg in self.argumentList: - if arg.flags == ErrorMode or arg.flags == SelfMode: - continue - if arg.type == 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)" % string.joinfields(input, ", ") - if not output or output == ["void"]: - outstr = "None" - else: - outstr = "(%s)" % string.joinfields(output, ", ") - return instr + " -> " + outstr - - def functionbody(self): - self.declarations() - self.getargs() - self.callit() - self.checkit() - self.returnvalue() - - def declarations(self): - for arg in self.argumentList: - arg.declare() - - def getargs(self): - fmt = "" - lst = "" - sep = ",\n" + ' '*len("if (!PyArg_ParseTuple(") - for arg in self.argumentList: - if arg.flags == SelfMode: - continue - if arg.mode in (InMode, InOutMode): - fmt = fmt + arg.getargsFormat() - args = arg.getargsArgs() - if args: - lst = lst + sep + args - 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 callit(self): - args = "" - if self.rv: - s = "%s = %s(" % (self.rv.name, self.name) - else: - s = "%s(" % self.name - 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 - if self.rv: - Output("%s = %s(%s);", - self.rv.name, self.name, args) - else: - Output("%s(%s);", self.name, args) - - def checkit(self): - for arg in self.argumentList: - arg.errorCheck() - - def returnvalue(self): - fmt = "" - lst = "" - sep = ",\n" + ' '*len("return Py_BuildValue(") - for arg in self.argumentList: - if not arg: continue - if arg.flags == ErrorMode: continue - if arg.mode in (OutMode, InOutMode): - fmt = fmt + arg.mkvalueFormat() - lst = lst + sep + arg.mkvalueArgs() - 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;") - - -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 = Generator(void, "eggs", - Variable(stringptr, 'cmd'), - Variable(int, 'x'), - Variable(double, 'y', InOutMode), - Variable(int, 'status', ErrorMode), - ) - eggs.setprefix("spam") - print "/* START */" - eggs.generate() - - -if __name__ == "__main__": - _test() diff --git a/Tools/bgen/bgen/bgenGeneratorGroup.py b/Tools/bgen/bgen/bgenGeneratorGroup.py deleted file mode 100644 index 294828f76c..0000000000 --- a/Tools/bgen/bgen/bgenGeneratorGroup.py +++ /dev/null @@ -1,35 +0,0 @@ -from bgenOutput import * - -class GeneratorGroup: - - def __init__(self, prefix): - self.prefix = prefix - self.generators = [] - - def add(self, g): - 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(): - from bgenGenerator import Generator - group = GeneratorGroup("spam") - eggs = Generator(void, "eggs") - group.add(eggs) - print "/* START */" - group.generate() - -if __name__ == "__main__": - _test() diff --git a/Tools/bgen/bgen/bgenHeapBuffer.py b/Tools/bgen/bgen/bgenHeapBuffer.py deleted file mode 100644 index c6160ba479..0000000000 --- a/Tools/bgen/bgen/bgenHeapBuffer.py +++ /dev/null @@ -1,110 +0,0 @@ -# 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 declareOutputBuffer(self, name): - Output("%s *%s__out__;", self.datatype, 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) - 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 declareInputBuffer(self, name): - pass - - 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) diff --git a/Tools/bgen/bgen/bgenModule.py b/Tools/bgen/bgen/bgenModule.py deleted file mode 100644 index f339016f00..0000000000 --- a/Tools/bgen/bgen/bgenModule.py +++ /dev/null @@ -1,85 +0,0 @@ -from bgenOutput import * -from bgenGeneratorGroup import GeneratorGroup - -class Module(GeneratorGroup): - - def __init__(self, name, prefix = None, - includestuff = None, - finalstuff = None, - initstuff = None, - variablestuff = None): - GeneratorGroup.__init__(self, prefix or name) - self.name = name - self.includestuff = includestuff - self.initstuff = initstuff - self.finalstuff = finalstuff - self.variablestuff = variablestuff - - def addobject(self, od): - self.generators.append(od) - - 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()", 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("""Py_FatalError("can't initialize %s.Error");""", - self.name) - DedentLevel() - if self.variablestuff: - Output("%s", self.variablestuff) - Output() - - def exceptionInitializer(self): - return """PyString_FromString("%s.Error")""" % self.name - - -def _test(): - from bgenGenerator import Generator - m = Module("spam", "", "#include <stdio.h>") - g = Generator(None, "bacon") - m.add(g) - m.generate() - -if __name__ == "__main__": - _test() diff --git a/Tools/bgen/bgen/bgenObjectDefinition.py b/Tools/bgen/bgen/bgenObjectDefinition.py deleted file mode 100644 index dd1ad326ed..0000000000 --- a/Tools/bgen/bgen/bgenObjectDefinition.py +++ /dev/null @@ -1,183 +0,0 @@ -from bgenOutput import * -from bgenGeneratorGroup import GeneratorGroup - -class ObjectDefinition(GeneratorGroup): - "Spit out code that together defines a new Python object type" - - 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.argref = "" # set to "*" if arg to <type>_New should be pointer - self.static = "static " # set to "" to make <type>_New and <type>_Convert public - self.basechain = "NULL" # set to &<basetype>_chain to chain methods - - def add(self, g): - g.setselftype(self.objecttype, self.itselftype) - GeneratorGroup.add(self, g) - - def reference(self): - # In case we are referenced from a module - pass - - def generate(self): - # XXX This should use long strings and %(varname)s substitution! - - OutHeader2("Object type " + self.name) - - sf = self.static and "staticforward " - Output("%sPyTypeObject %s;", sf, self.typename) - Output() - Output("#define %s_Check(x) ((x)->ob_type == &%s)", - self.prefix, self.typename) - Output() - 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() - Output("%sPyMethodChain %s_chain = { %s_methods, %s };", - self.static, self.prefix, self.prefix, self.basechain) - - self.outputGetattr() - - self.outputSetattr() - - self.outputTypeObject() - - OutHeader2("End object type " + self.name) - - def outputStructMembers(self): - Output("%s ob_itself;", self.itselftype) - - def outputNew(self): - Output() - Output("%sPyObject *%s_New(itself)", self.static, self.prefix) - IndentLevel() - Output("%s %sitself;", self.itselftype, self.argref) - DedentLevel() - OutLbrace() - Output("%s *it;", self.objecttype) - self.outputCheckNewArg() - Output("it = PyObject_NEW(%s, &%s);", self.objecttype, self.typename) - Output("if (it == NULL) return NULL;") - 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("%s%s_Convert(v, p_itself)", self.static, self.prefix) - IndentLevel() - Output("PyObject *v;") - Output("%s *p_itself;", self.itselftype) - DedentLevel() - 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(self)", self.prefix) - IndentLevel() - Output("%s *self;", self.objecttype) - DedentLevel() - OutLbrace() - self.outputCleanupStructMembers() - Output("PyMem_DEL(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(self, name)", self.prefix) - IndentLevel() - Output("%s *self;", self.objecttype) - Output("char *name;") - DedentLevel() - 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 outputTypeObject(self): - sf = self.static and "staticforward " - Output() - Output("%sPyTypeObject %s = {", sf, self.typename) - IndentLevel() - Output("PyObject_HEAD_INIT(&PyType_Type)") - Output("0, /*ob_size*/") - 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) - DedentLevel() - Output("};") - - -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 = "" diff --git a/Tools/bgen/bgen/bgenOutput.py b/Tools/bgen/bgen/bgenOutput.py deleted file mode 100644 index 1a512e5c8b..0000000000 --- a/Tools/bgen/bgen/bgenOutput.py +++ /dev/null @@ -1,221 +0,0 @@ -"""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 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 - import string - lines = string.splitfields(text, '\n') - for i in range(len(lines)): - if lines[i] and lines[i][0] != '#': - lines[i] = indent + lines[i] - text = string.joinfields(lines, '\n') - _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? :-) - - import string - lines = string.splitfields(text, '\n') - indent = "" - for line in lines: - if string.strip(line): - for c in line: - if c not in string.whitespace: - 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/Tools/bgen/bgen/bgenStackBuffer.py b/Tools/bgen/bgen/bgenStackBuffer.py deleted file mode 100644 index 1b6350a99e..0000000000 --- a/Tools/bgen/bgen/bgenStackBuffer.py +++ /dev/null @@ -1,59 +0,0 @@ -"""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 declareSize(self, name): - Output("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/Tools/bgen/bgen/bgenStringBuffer.py b/Tools/bgen/bgen/bgenStringBuffer.py deleted file mode 100644 index 7d9c77e296..0000000000 --- a/Tools/bgen/bgen/bgenStringBuffer.py +++ /dev/null @@ -1,64 +0,0 @@ -"""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 declareSize(self, name): - pass - - 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/Tools/bgen/bgen/bgenType.py b/Tools/bgen/bgen/bgenType.py deleted file mode 100644 index ba9a53e430..0000000000 --- a/Tools/bgen/bgen/bgenType.py +++ /dev/null @@ -1,241 +0,0 @@ -"""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): - """Declare a variable of the type with a given name. - - Example: int.declare('spam') prints "int spam;" - """ - Output("%s %s;", self.typeName, name) - - def getargs(self): - return self.getargsFormat(), self.getargsArgs() - - def getargsFormat(self): - """Return the format for this type for use with [new]getargs(). - - Example: int.getargsFormat() returns the string "i". - """ - return self.fmt - - def getargsArgs(self, name): - """Return an argument for use with [new]getargs(). - - Example: int.getargsArgs("spam") returns the string "&spam". - """ - return "&" + name - - 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.""" - - 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 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 mkvalue(). - - This is normally the same as getargsFormat() but it is - a separate function to allow future divergence. - """ - return self.getargsFormat() - - def mkvalueArgs(self, name): - """Return an argument for use with mkvalue(). - - Example: int.mkvalueArgs("spam") returns the string "spam". - """ - return name - - def cleanup(self, name): - """Clean up if necessary. - - This is normally empty; it may deallocate buffers etc. - """ - pass - - -# 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, "this type can only be used for input parameters" - -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, "this type can only be used for output parameters" - -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") -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") - - -# 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 declare(self, name): - pass - - 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 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/Tools/bgen/bgen/bgenVariable.py b/Tools/bgen/bgen/bgenVariable.py deleted file mode 100644 index 310cc8f9e8..0000000000 --- a/Tools/bgen/bgen/bgenVariable.py +++ /dev/null @@ -1,88 +0,0 @@ -"""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 - - -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 != SelfMode: - self.type.declare(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 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 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 cleanup(self): - """Call the type's cleanup method.""" - return self.type.cleanup(self.name) diff --git a/Tools/bgen/bgen/bgenlocations.py b/Tools/bgen/bgen/bgenlocations.py deleted file mode 100644 index 3ec9c055ab..0000000000 --- a/Tools/bgen/bgen/bgenlocations.py +++ /dev/null @@ -1,12 +0,0 @@ -# -# Local customizations -# - -# Where to find the Universal Header include files: -INCLUDEDIR="Sap:CW8 Gold:Metrowerks CodeWarrior:MacOS Support:Headers:Universal Headers:" - -# Where to put the python definitions file: -TOOLBOXDIR="Moes:Development:Jack:Python 1.3:Mac:Lib:toolbox:" - -# Creator for C files: -CREATOR="CWIE" diff --git a/Tools/bgen/bgen/macsupport.py b/Tools/bgen/bgen/macsupport.py deleted file mode 100644 index 0f21b3fcf6..0000000000 --- a/Tools/bgen/bgen/macsupport.py +++ /dev/null @@ -1,168 +0,0 @@ -"""\ -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") -ScriptCode = Type("ScriptCode", "h") -Size = Type("Size", "l") -Style = Type("Style", "b") - -UInt8 = Type("UInt8", "b") -SInt8 = Type("SInt8", "b") -UInt16 = Type("UInt16", "h") -SInt16 = Type("SInt16", "h") -UInt32 = Type("UInt32", "l") -SInt32 = Type("SInt32", "l") - -# Pascal strings -ConstStr255Param = OpaqueArrayType("Str255", "PyMac_BuildStr255", "PyMac_GetStr255") -Str255 = OpaqueArrayType("Str255", "PyMac_BuildStr255", "PyMac_GetStr255") - -# File System Specifications -FSSpec_ptr = OpaqueType("FSSpec", "PyMac_BuildFSSpec", "PyMac_GetFSSpec") - -# OSType and ResType: 4-byte character strings -def OSTypeType(typename): - return OpaqueByValueType(typename, "PyMac_BuildOSType", "PyMac_GetOSType") -OSType = OSTypeType("OSType") -ResType = OSTypeType("ResType") - -# 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", "WinObj_WhichWindow", "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") - -# Event records -EventRecord = OpaqueType("EventRecord", "PyMac_BuildEventRecord", "PyMac_GetEventRecord") -EventRecord_ptr = EventRecord - -# 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') - - -# Various buffer types - -InBuffer = VarInputBufferType('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) - - -# Predefine various pieces of program text to be passed to Module() later: - -# Stuff added immediately after the system include files -includestuff = """ -#define SystemSevenOrLater 1 - -#include "macglue.h" -#include <Memory.h> -#include <Dialogs.h> -#include <Menus.h> -#include <Controls.h> - -extern PyObject *ResObj_New(Handle); -extern int ResObj_Convert(PyObject *, Handle *); -extern PyObject *OptResObj_New(Handle); -extern int OptResObj_Convert(PyObject *, Handle *); - -extern PyObject *WinObj_New(WindowPtr); -extern int WinObj_Convert(PyObject *, WindowPtr *); -extern PyTypeObject Window_Type; -#define WinObj_Check(x) ((x)->ob_type == &Window_Type) - -extern PyObject *DlgObj_New(DialogPtr); -extern int DlgObj_Convert(PyObject *, DialogPtr *); -extern PyTypeObject Dialog_Type; -#define DlgObj_Check(x) ((x)->ob_type == &Dialog_Type) - -extern PyObject *MenuObj_New(MenuHandle); -extern int MenuObj_Convert(PyObject *, MenuHandle *); - -extern PyObject *CtlObj_New(ControlHandle); -extern int CtlObj_Convert(PyObject *, ControlHandle *); - -extern PyObject *GrafObj_New(GrafPtr); -extern int GrafObj_Convert(PyObject *, GrafPtr *); - -extern PyObject *BMObj_New(BitMapPtr); -extern int BMObj_Convert(PyObject *, BitMapPtr *); - -extern PyObject *WinObj_WhichWindow(WindowPtr); -""" - -# 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 return values special" - def makereturnvar(self): - if self.returntype is OSErr: - return Variable(self.returntype, "_err", ErrorMode) - else: - return Variable(self.returntype, "_rv", OutMode) - -class OSErrFunctionGenerator(OSErrMixIn, FunctionGenerator): pass -class OSErrMethodGenerator(OSErrMixIn, MethodGenerator): pass - - -class MacModule(Module): - "Subclass which gets the exception initializer from macglue.c" - def exceptionInitializer(self): - return "PyMac_GetOSErrException()" - -_SetOutputFileName = SetOutputFileName # Save original -def SetOutputFileName(file = None): - "Set the output file name and set its creator&type to CWIE&TEXT" - _SetOutputFileName(file) - if file: - import MacOS - MacOS.SetCreatorAndType(file, 'CWIE', 'TEXT') diff --git a/Tools/bgen/bgen/scantools.py b/Tools/bgen/bgen/scantools.py deleted file mode 100644 index ec5c733ebb..0000000000 --- a/Tools/bgen/bgen/scantools.py +++ /dev/null @@ -1,508 +0,0 @@ -"""\ - -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 regex -import regsub -import string -import sys -import os -import fnmatch -from types import * -try: - import MacOS -except ImportError: - MacOS = None - -from bgenlocations import CREATOR, INCLUDEDIR - -Error = "scantools.Error" - -class Scanner: - - 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() - print type, string.join(modes) - - def initsilent(self): - self.silent = 0 - - 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 initblacklists(self): - self.blacklistnames = self.makeblacklistnames() - self.blacklisttypes = ["unknown", "-"] + self.makeblacklisttypes() - - def makeblacklistnames(self): - return [] - - def makeblacklisttypes(self): - return [] - - def initrepairinstructions(self): - self.repairinstructions = self.makerepairinstructions() - - 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", `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 = string.find(line, '#') - if i >= 0: line = line[:i] - words = map(string.strip, string.splitfields(line, ':')) - if words == ['']: continue - if len(words) <> 3: - print "Line", startlineno, - print ": bad line (not 3 colon-separated fields)" - print `line` - continue - [fpat, pat, rep] = words - if not fpat: fpat = "*" - if not pat: - print "Line", startlineno, - print "Empty pattern" - print `line` - continue - patparts = map(string.strip, string.splitfields(pat, ',')) - repparts = map(string.strip, string.splitfields(rep, ',')) - patterns = [] - for p in patparts: - if not p: - print "Line", startlineno, - print "Empty pattern part" - print `line` - continue - pattern = string.split(p) - if len(pattern) > 3: - print "Line", startlineno, - print "Pattern part has > 3 words" - print `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 `line` - continue - replacement = string.split(p) - if len(replacement) > 3: - print "Line", startlineno, - print "Pattern part has > 3 words" - print `line` - replacement = replacement[:3] - else: - while len(replacement) < 3: - replacement.append("*") - replacements.append(replacement) - list.append((fpat, patterns, replacements)) - return list - - def openrepairfile(self, filename = "REPAIR"): - try: - return open(filename, "r") - except IOError, msg: - print `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.specfile = sys.stdout - self.defsfile = None - self.scanfile = sys.stdin - self.lineno = 0 - self.line = "" - - def initpaths(self): - self.includepath = [':', INCLUDEDIR] - - def initpatterns(self): - self.head_pat = "^extern pascal[ \t]+" # XXX Mac specific! - self.tail_pat = "[;={}]" - self.type_pat = "pascal[ \t\n]+\(<type>[a-zA-Z0-9_ \t]*[a-zA-Z0-9_]\)[ \t\n]+" - self.name_pat = "\(<name>[a-zA-Z0-9_]+\)[ \t\n]*" - self.args_pat = "(\(<args>\([^(;=)]+\|([^(;=)]*)\)*\))" - self.whole_pat = self.type_pat + self.name_pat + self.args_pat - self.sym_pat = "^[ \t]*\(<name>[a-zA-Z0-9_]+\)[ \t]*=" + \ - "[ \t]*\(<defn>[-0-9'\"][^\t\n,;}]*\),?" - self.asplit_pat = "^\(<type>.*[^a-zA-Z0-9_]\)\(<name>[a-zA-Z0-9_]+\)$" - - def compilepatterns(self): - for name in dir(self): - if name[-4:] == "_pat": - pat = getattr(self, name) - prog = regex.symcomp(pat) - setattr(self, name[:-4], prog) - - def initosspecifics(self): - if MacOS: - 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() - - 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 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 openoutput(self, filename): - file = open(filename, 'w') - self.setfiletype(filename) - return file - - def setinput(self, scan = sys.stdin): - 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 - - 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 %s", `fullname`) - try: - return open(fullname, 'r') - except IOError: - pass - # If not on the path, or absolute, try default open() - try: - return open(filename, 'r') - 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: - 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 = %s", `inputname`) - if not self.specfile: - self.report("(No interface specifications will be written)") - else: - self.report("specfile = %s", `self.specfile.name`) - self.specfile.write("# Generated from %s\n\n" % `inputname`) - if not self.defsfile: - self.report("(No symbol definitions will be written)") - else: - self.report("defsfile = %s", `self.defsfile.name`) - self.defsfile.write("# Generated from %s\n\n" % `inputname`) - self.alreadydone = [] - try: - while 1: - try: line = self.getline() - except EOFError: break - if self.defsfile and self.sym.match(line) >= 0: - self.dosymdef() - continue - if self.head.match(line) >= 0: - self.dofuncspec() - continue - except EOFError: - self.error("Uncaught EOF error") - self.reportusedtypes() - - def dosymdef(self): - name, defn = self.sym.group('name', 'defn') - self.defsfile.write("%s = %s\n" % (name, defn)) - - def dofuncspec(self): - raw = self.line - while self.tail.search(raw) < 0: - line = self.getline() - raw = raw + line - self.processrawspec(raw) - - def processrawspec(self, raw): - if self.whole.search(raw) < 0: - self.report("Bad raw spec: %s", `raw`) - return - type, name, args = self.whole.group('type', 'name', 'args') - if name in self.alreadydone: - self.report("Name has already been defined: %s", `name`) - return - self.report("==> %s %s <==", type, name) - if self.blacklisted(type, name): - self.error("*** %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): - ##for arg in arglist: - ## self.report(" %s", `arg`) - self.error("*** %s %s unmanageable", type, name) - return - self.alreadydone.append(name) - self.generate(type, name, arglist) - - def extractarglist(self, args): - args = string.strip(args) - if not args or args == "void": - return [] - parts = map(string.strip, string.splitfields(args, ",")) - arglist = [] - for part in parts: - arg = self.extractarg(part) - arglist.append(arg) - return arglist - - def extractarg(self, part): - mode = "InMode" - if self.asplit.match(part) < 0: - self.error("Indecipherable argument: %s", `part`) - return ("unknown", part, mode) - type, name = self.asplit.group('type', 'name') - type = regsub.gsub("\*", " ptr ", type) - type = string.strip(type) - type = regsub.gsub("[ \t]+", "_", 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" - 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 = string.atoi(item[i][1:]) - 1 - newitem[i] = old[index][i] - new.append(tuple(newitem)) - ##self.report("old: %s", `old`) - ##self.report("new: %s", `new`) - return new - - def generate(self, type, name, arglist): - self.typeused(type, 'return') - classname, listname = self.destination(type, name, arglist) - if not self.specfile: return - self.specfile.write("f = %s(%s, %s,\n" % (classname, type, `name`)) - for atype, aname, amode in arglist: - self.typeused(atype, amode) - self.specfile.write(" (%s, %s, %s),\n" % - (atype, `aname`, amode)) - self.specfile.write(")\n") - self.specfile.write("%s.append(f)\n\n" % listname) - - def destination(self, type, name, arglist): - return "FunctionGenerator", "functions" - - 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 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/Tools/freeze/README b/Tools/freeze/README deleted file mode 100644 index 5befaf08ca..0000000000 --- a/Tools/freeze/README +++ /dev/null @@ -1,170 +0,0 @@ -THE FREEZE SCRIPT -================= - - -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? ----------------------------------------------- - -Freeze uses a pretty simple-minded algorithm to find the modules that -your program uses: given a file containing Python source code, it -scans for lines beginning with the word "import" or "from" (possibly -preceded by whitespace) and then it knows where to find the module -name(s) in those lines. It then recursively scans the source for -those modules (if found, and not already processed) in the same way. - -Freeze will not see import statements hidden behind another statement, -like this: - - if some_test: import M # M not seen - -or like this: - - import A; import B; import C # B and C not seen - -nor will it see import statements constructed using string -operations and passed to 'exec', like this: - - exec "import %s" % "M" # M not seen - -On the other hand, Freeze will think you are importing a module even -if the import statement it sees will never be executed, like this: - - if 0: - import M # M is seen - -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? --------------------- - -Ideally, 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 /ufs/guido/src/python/Tools/freeze/freeze.py). - -Unfortunately, this doesn't work. Well, it might, but somehow it's -extremely unlikely that it'll work on the first try. (If it does, -skip to the next section.) Most likely you'll get this error message: - - needed directory /usr/local/lib/python/lib not found - -The reason is that Freeze require that some files that are normally -kept inside the Python build tree are installed, and it searches for -it in the default install location. (The default install prefix is -/usr/local; these particular files are installed at lib/python/lib -under the install prefix.) - -The particular set of files needed is installed only if you run "make -libainstall" (note: "liba", not "lib") in the Python build tree (which -is the tree where you build Python -- often, but not necessarily, this -is also the Python source tree). If you have in fact done a "make -libainstall" but used a different prefix, all you need to do is pass -that same prefix to Freeze with the -p option: - - python freeze.py -p your-prefix hello.py - -If you haven't run "make libainstall" yet, you should do it now -(perhaps figuring out first *where* you want everything to be -installed). - - -How do I configure Freeze? --------------------------- - -It's a good idea to change the first line marked with XXX in freeze.py -(an assignment to variable PACK) to point to the absolute pathname of -the directory where Freeze lives (Tools/freeze in the Python source -tree.) This makes it possible to call Freeze from other directories. - -You can also edit the assignment to variable PREFIX (also marked with -XXX) -- this saves a lot of -p options. - - -How do I use Freeze with extensions modules? --------------------------------------------- - -XXX to be written. (In short: pass -e extensionbuilddir.) - - -How do I use Freeze with dynamically loaded extension modules? --------------------------------------------------------------- - -XXX to be written. (In short: pass -e modulebuilddir -- this even -works if you built the modules in Python's own Modules directory.) - - -What do I do next? ------------------- - -Freeze creates three files: frozen.c, config.c and Makefile. 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". On the -other hand, if the argument was "hello", the binary will be called -"hello.bin". If you passed any other filename, all bets are off. :-) -In any case, the name of the file will be printed as the last message -from Freeze. - - -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 -- read the text above to find out how to install -relevant parts of Python properly and how to configure Freeze to find -them. - -A common problem is having installed an old version -- rerunning "make -libainstall" often clears up problems with missing modules or -libraries at link time. - - -What is nfreeze.py? -------------------- - -The script nfreeze.py is an unsupported variant on freeze.py which -creates all files in a temporary directory and runs "make" there. It -has the advantage that it doesn't overwrite files in the current -directory, but the disadvantage is that it removes all files when it -is finished. - - ---Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl> -<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html> diff --git a/Tools/freeze/checkextensions.py b/Tools/freeze/checkextensions.py deleted file mode 100644 index a7890d83f6..0000000000 --- a/Tools/freeze/checkextensions.py +++ /dev/null @@ -1,87 +0,0 @@ -# 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 string -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) - if skipofiles and w[-2:] == '.o': - continue - if w[0] != '-' and w[-2:] in ('.o', '.a'): - w = os.path.join(e, w) - 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 = string.find(str, '$', i) - if i < 0: - break - i = i+1 - var = str[i:i+1] - i = i+1 - if var == '(': - j = string.find(str, ')', 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/Tools/freeze/findmodules.py b/Tools/freeze/findmodules.py deleted file mode 100644 index 9e02f2be36..0000000000 --- a/Tools/freeze/findmodules.py +++ /dev/null @@ -1,127 +0,0 @@ -# Determine the names and filenames of the modules imported by a -# script, recursively. This is done by scanning for lines containing -# import statements. (The scanning has only superficial knowledge of -# Python syntax and no knowledge of semantics, so in theory the result -# may be incorrect -- however this is quite unlikely if you don't -# intentionally obscure your Python code.) - -import os -import regex -import string -import sys - - -# Top-level interface. -# First argument is the main program (script). -# Second optional argument is list of modules to be searched as well. - -def findmodules(scriptfile, modules = [], path = sys.path): - todo = {} - todo['__main__'] = scriptfile - for name in modules: - mod = os.path.basename(name) - if mod[-3:] == '.py': mod = mod[:-3] - elif mod[-4:] == '.pyc': mod = mod[:-4] - todo[mod] = name - done = closure(todo) - return done - - -# Compute the closure of scanfile() and findmodule(). -# Return a dictionary mapping module names to filenames. -# Writes to stderr if a file can't be or read. - -def closure(todo): - done = {} - while todo: - newtodo = {} - for modname in todo.keys(): - if not done.has_key(modname): - filename = todo[modname] - if filename is None: - filename = findmodule(modname) - done[modname] = filename - if filename in ('<builtin>', '<unknown>'): - continue - try: - modules = scanfile(filename) - except IOError, msg: - sys.stderr.write("%s: %s\n" % - (filename, str(msg))) - continue - for m in modules: - if not done.has_key(m): - newtodo[m] = None - todo = newtodo - return done - - -# Scan a file looking for import statements. -# Return list of module names. -# Can raise IOError. - -importstr = '\(^\|:\)[ \t]*import[ \t]+\([a-zA-Z0-9_, \t]+\)' -fromstr = '\(^\|:\)[ \t]*from[ \t]+\([a-zA-Z0-9_]+\)[ \t]+import[ \t]+' -isimport = regex.compile(importstr) -isfrom = regex.compile(fromstr) - -def scanfile(filename): - allmodules = {} - f = open(filename, 'r') - try: - while 1: - line = f.readline() - if not line: break # EOF - while line[-2:] == '\\\n': # Continuation line - line = line[:-2] + ' ' - line = line + f.readline() - if isimport.search(line) >= 0: - rawmodules = isimport.group(2) - modules = string.splitfields(rawmodules, ',') - for i in range(len(modules)): - modules[i] = string.strip(modules[i]) - elif isfrom.search(line) >= 0: - modules = [isfrom.group(2)] - else: - continue - for mod in modules: - allmodules[mod] = None - finally: - f.close() - return allmodules.keys() - - -# Find the file containing a module, given its name. -# Return filename, or '<builtin>', or '<unknown>'. - -builtins = sys.builtin_module_names -tails = ['.py', '.pyc'] - -def findmodule(modname, path = sys.path): - if modname in builtins: return '<builtin>' - for dirname in path: - for tail in tails: - fullname = os.path.join(dirname, modname + tail) - try: - f = open(fullname, 'r') - except IOError: - continue - f.close() - return fullname - return '<unknown>' - - -# Test the above functions. - -def test(): - if not sys.argv[1:]: - print 'usage: python findmodules.py scriptfile [morefiles ...]' - sys.exit(2) - done = findmodules(sys.argv[1], sys.argv[2:]) - items = done.items() - items.sort() - for mod, file in [('Module', 'File')] + items: - print "%-15s %s" % (mod, file) - -if __name__ == '__main__': - test() diff --git a/Tools/freeze/freeze.py b/Tools/freeze/freeze.py deleted file mode 100755 index 1fe5553f37..0000000000 --- a/Tools/freeze/freeze.py +++ /dev/null @@ -1,300 +0,0 @@ -#! /usr/local/bin/python - -# "Freeze" a Python script into a binary. -# Usage: see variable usage_msg below (before the imports!) - -# HINTS: -# - Edit the lines marked XXX below to localize. -# - Make sure the #! line above matches the localizations. -# - You must have done "make inclinstall libainstall" in the Python -# build directory. -# - The script name should end in ".py". -# - The script should not use dynamically loaded modules -# (*.so on most systems). - - -# Usage message - -usage_msg = """ -usage: freeze [-p prefix] [-P exec_prefix] [-e extension] script [module] ... - --p prefix: This is the prefix used when you ran - 'Make inclinstall libainstall' in the Python build directory. - (If you never ran this, freeze won't work.) - The default is /usr/local. - --P exec_prefix: Like -p but this is the 'exec_prefix', used to - install objects etc. The default is the value for -p. - --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. - More than one -e option may be given. - -script: The Python script to be executed by the resulting binary. - It *must* end with a .py suffix! - -module ...: Additional Python modules (referenced by pathname) - that will be included in the resulting binary. These - may be .py or .pyc files. - -NOTES: - -In order to use freeze successfully, you must have built Python and -installed it. In particular, the following two non-standard make -targets must have been executed: - - make inclinstall - make libainstall # Note: 'liba', not 'lib' - -The -p and -P options passed into the freeze script must correspond to -the --prefix and --exec-prefix options passed into Python's configure -script. -""" - - -# XXX Change the following line to point to your Tools/freeze directory -PACK = '/ufs/guido/src/python/Tools/freeze' - -# XXX Change the following line to point to your install prefix -PREFIX = '/usr/local' - -# XXX Change the following line to point to your install exec_prefix -EXEC_PREFIX = None # If None, use -p option for default - - -# Import standard modules - -import cmp -import getopt -import os -import string -import sys -import addpack - - -# Set the directory to look for the freeze-private modules - -dir = os.path.dirname(sys.argv[0]) -if dir: - pack = dir -else: - pack = PACK -addpack.addpack(pack) - - -# Import the freeze-private modules - -import checkextensions -import findmodules -import makeconfig -import makefreeze -import makemakefile -import parsesetup - - -# Main program - -def main(): - # overridable context - prefix = PREFIX # settable with -p option - exec_prefix = None # settable with -P option - extensions = [] - path = sys.path - - # output files - frozen_c = 'frozen.c' - config_c = 'config.c' - target = 'a.out' # normally derived from script name - makefile = 'Makefile' - - # parse command line - try: - opts, args = getopt.getopt(sys.argv[1:], 'e:p:P:') - except getopt.error, msg: - usage('getopt error: ' + str(msg)) - - # proces option arguments - for o, a in opts: - if o == '-e': - extensions.append(a) - if o == '-p': - prefix = a - if o == '-P': - exec_prefix = a - - # default exec_prefix - if exec_prefix is None: - exec_prefix = EXEC_PREFIX - if exec_prefix is None: - exec_prefix = prefix - - # locations derived from options - binlib = os.path.join(exec_prefix, 'lib/python/lib') - incldir = os.path.join(prefix, 'include/Py') - config_c_in = os.path.join(binlib, 'config.c.in') - frozenmain_c = os.path.join(binlib, 'frozenmain.c') - getpath_c = os.path.join(binlib, 'getpath.c') - supp_sources = [frozenmain_c, getpath_c] - makefile_in = os.path.join(binlib, 'Makefile') - defines = ['-DHAVE_CONFIG_H', - '-DPYTHONPATH=\\"$(PYTHONPATH)\\"'] - includes = ['-I' + incldir, '-I' + binlib] - - # sanity check of directories and files - for dir in [prefix, exec_prefix, binlib, incldir] + extensions: - 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) - for file in [config_c_in, makefile_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) - 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 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' - - # Actual work starts here... - - dict = findmodules.findmodules(scriptfile, modules, path) - names = dict.keys() - names.sort() - print "Modules being frozen:" - for name in names: - print '\t', name - - backup = frozen_c + '~' - try: - os.rename(frozen_c, backup) - except os.error: - backup = None - outfp = open(frozen_c, 'w') - try: - makefreeze.makefreeze(outfp, dict) - finally: - outfp.close() - if backup: - if cmp.cmp(backup, frozen_c): - sys.stderr.write('%s not changed, not written\n' % - frozen_c) - os.rename(backup, frozen_c) - - builtins = [] - unknown = [] - mods = dict.keys() - mods.sort() - for mod in mods: - if dict[mod] == '<builtin>': - builtins.append(mod) - elif dict[mod] == '<unknown>': - unknown.append(mod) - - addfiles = [] - if unknown: - addfiles, addmods = \ - checkextensions.checkextensions(unknown, extensions) - for mod in addmods: - unknown.remove(mod) - builtins = builtins + addmods - if unknown: - sys.stderr.write('Warning: unknown modules remain: %s\n' % - string.join(unknown)) - - builtins.sort() - infp = open(config_c_in) - backup = config_c + '~' - try: - os.rename(config_c, backup) - except os.error: - backup = None - outfp = open(config_c, 'w') - try: - makeconfig.makeconfig(infp, outfp, builtins) - finally: - outfp.close() - infp.close() - if backup: - if cmp.cmp(backup, config_c): - sys.stderr.write('%s not changed, not written\n' % - config_c) - os.rename(backup, config_c) - - cflags = defines + includes + ['$(OPT)'] - libs = [] - for n in 'Modules', 'Python', 'Objects', 'Parser': - n = 'lib%s.a' % n - n = os.path.join(binlib, n) - libs.append(n) - - makevars = parsesetup.getmakevars(makefile_in) - somevars = {} - for key in makevars.keys(): - somevars[key] = makevars[key] - - somevars['CFLAGS'] = string.join(cflags) # override - files = ['$(OPT)', config_c, frozen_c] + \ - supp_sources + addfiles + libs + \ - ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] - - backup = makefile + '~' - try: - os.rename(makefile, backup) - except os.error: - backup = None - outfp = open(makefile, 'w') - try: - makemakefile.makemakefile(outfp, somevars, files, target) - finally: - outfp.close() - if backup: - if not cmp.cmp(backup, makefile): - print 'previous Makefile saved as', backup - else: - sys.stderr.write('%s not changed, not written\n' % - makefile) - os.rename(backup, makefile) - - # Done! - - print 'Now run make to build the target:', target - - -# Print usage message and exit - -def usage(msg = None): - if msg: - sys.stderr.write(str(msg) + '\n') - sys.stderr.write(usage_msg) - sys.exit(2) - - -main() diff --git a/Tools/freeze/hello.py b/Tools/freeze/hello.py deleted file mode 100644 index f978acc883..0000000000 --- a/Tools/freeze/hello.py +++ /dev/null @@ -1 +0,0 @@ -print 'Hello world...' diff --git a/Tools/freeze/makeconfig.py b/Tools/freeze/makeconfig.py deleted file mode 100644 index 958c2be4ff..0000000000 --- a/Tools/freeze/makeconfig.py +++ /dev/null @@ -1,57 +0,0 @@ -import regex - - -# Write the config.c file - -never = ['marshal', '__main__', '__builtin__', 'sys'] - -def makeconfig(infp, outfp, modules): - m1 = regex.compile('-- ADDMODULE MARKER 1 --') - m2 = regex.compile('-- ADDMODULE MARKER 2 --') - while 1: - line = infp.readline() - if not line: break - outfp.write(line) - if m1 and m1.search(line) >= 0: - m1 = None - for mod in modules: - if mod in never: - continue - outfp.write('extern void init%s();\n' % mod) - elif m2 and m2.search(line) >= 0: - 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(): - import sys - 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/Tools/freeze/makefreeze.py b/Tools/freeze/makefreeze.py deleted file mode 100644 index 4a3da99d35..0000000000 --- a/Tools/freeze/makefreeze.py +++ /dev/null @@ -1,91 +0,0 @@ -import marshal - - -# Write a file containing frozen code for the modules in the dictionary. - -header = """ -struct frozen { - char *name; - unsigned char *code; - int size; -} frozen_modules[] = { -""" -trailer = """\ - {0, 0, 0} /* sentinel */ -}; -""" - -def makefreeze(outfp, dict): - done = [] - mods = dict.keys() - mods.sort() - for mod in mods: - modfn = dict[mod] - try: - str = makecode(modfn) - except IOError, msg: - sys.stderr.write("%s: %s\n" % (modfn, str(msg))) - continue - if str: - done.append(mod, len(str)) - writecode(outfp, mod, str) - outfp.write(header) - for mod, size in done: - outfp.write('\t{"%s", M_%s, %d},\n' % (mod, mod, size)) - outfp.write(trailer) - - -# Return code string for a given module -- either a .py or a .pyc -# file. Return either a string or None (if it's not Python code). -# May raise IOError. - -def makecode(filename): - if filename[-3:] == '.py': - f = open(filename, 'r') - try: - text = f.read() - code = compile(text, filename, 'exec') - finally: - f.close() - return marshal.dumps(code) - if filename[-4:] == '.pyc': - f = open(filename, 'rb') - try: - f.seek(8) - str = f.read() - finally: - f.close() - return str - # Can't generate code for this extension - return None - - -# 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('static 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') - - -# Test for the above functions. - -def test(): - import os - import sys - if not sys.argv[1:]: - print 'usage: python freezepython.py file.py(c) ...' - sys.exit(2) - dict = {} - for arg in sys.argv[1:]: - base = os.path.basename(arg) - mod, ext = os.path.splitext(base) - dict[mod] = arg - makefreeze(sys.stdout, dict) - -if __name__ == '__main__': - test() diff --git a/Tools/freeze/makemakefile.py b/Tools/freeze/makemakefile.py deleted file mode 100644 index 5418f939a8..0000000000 --- a/Tools/freeze/makemakefile.py +++ /dev/null @@ -1,27 +0,0 @@ -# Write the actual Makefile. - -import os -import string - -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" % 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) -c %s\n" % file) - files[i] = dest - deps.append(dest) - - outfp.write("\n%s: %s\n" % (target, string.join(deps))) - outfp.write("\t$(CC) %s -o %s\n" % (string.join(files), target)) diff --git a/Tools/freeze/nfreeze.py b/Tools/freeze/nfreeze.py deleted file mode 100755 index 3706e734e5..0000000000 --- a/Tools/freeze/nfreeze.py +++ /dev/null @@ -1,312 +0,0 @@ -#! /usr/local/bin/python - -# "Freeze" a Python script into a binary. -# Usage: see variable usage_msg below (before the imports!) - -# This version builds the frozen binary in a temporary directory; -# courtesy Jaap Vermeulen. Use the -l option to get the functionality -# of the standard version. - -# HINTS: -# - Edit the lines marked XXX below to localize. -# - You must have done "make inclinstall libainstall" in the Python -# build directory. -# - The script should not use dynamically loaded modules -# (*.so on most systems). - - -# Usage message - -usage_msg = """ -usage: freeze [-p prefix] [-e extension] [-l] ... script [module] ... - --p prefix: This is the prefix used when you ran - 'Make inclinstall libainstall' in the Python build directory. - (If you never ran this, freeze won't work.) - The default is /usr/local. - --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. - More than one -e option may be given. - --l: Local compilation. Instead of using a temporary directory - that is removed after succesful compilation, the current - directory is used and temporary files are not removed. - -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. -""" - - -# XXX Change the following line to point to your Tools/freeze directory -PACK = '/ufs/guido/src/python/Tools/freeze' - -# XXX Change the following line to point to your install prefix -PREFIX = '/usr/local' - -# XXX Change the following line to point to your favority temporary directory -TMPDIR = '/usr/tmp' - - -# Import standard modules - -import cmp -import getopt -import os -import string -import sys -import addpack - - -# Set the directory to look for the freeze-private modules - -dir = os.path.dirname(sys.argv[0]) -if dir: - pack = dir -else: - pack = PACK -addpack.addpack(pack) - - -# Establish temporary directory name - -tmpdir = os.path.join(TMPDIR, 'freeze.' + `os.getpid()`) - - -# Import the freeze-private modules - -import checkextensions -import findmodules -import makeconfig -import makefreeze -import makemakefile -import parsesetup - - -# Main program - -def main(): - # module variable - global tmpdir - - # overridable context - prefix = PREFIX # settable with -p option - extensions = [] - path = sys.path - - # output files - frozen_c = 'frozen.c' - config_c = 'config.c' - target = 'a.out' # normally derived from script name - makefile = 'Makefile' - - # parse command line - try: - opts, args = getopt.getopt(sys.argv[1:], 'e:p:l') - except getopt.error, msg: - usage('getopt error: ' + str(msg)) - - # proces option arguments - for o, a in opts: - if o == '-e': - extensions.append(a) - if o == '-l': - tmpdir = None - if o == '-p': - prefix = a - - # locations derived from options - binlib = os.path.join(prefix, 'lib/python/lib') - incldir = os.path.join(prefix, 'include/Py') - 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') - defines = ['-DHAVE_CONFIG_H', '-DUSE_FROZEN', '-DNO_MAIN', - '-DPYTHONPATH=\\"$(PYTHONPATH)\\"'] - includes = ['-I' + incldir, '-I' + binlib] - - # sanity check of directories and files - for dir in [prefix, binlib, incldir] + extensions: - 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) - for file in config_c_in, makefile_in, frozenmain_c: - 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) - 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 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' - - # use temporary directory - if tmpdir: - try: os.mkdir(tmpdir, 0700) - except os.error, errmsg: - sys.stderr.write('mkdir: (%s) %s\n' % errmsg) - sys.stderr.write('Error: cannot create temporary directory: %s\n' % (tmpdir,)) - sys.exit(2) - frozen_c = os.path.join(tmpdir, frozen_c) - config_c = os.path.join(tmpdir, config_c) - makefile = os.path.join(tmpdir, makefile) - - dict = findmodules.findmodules(scriptfile, modules, path) - - # Actual work starts here... - - backup = frozen_c + '~' - try: - os.rename(frozen_c, backup) - except os.error: - backup = None - outfp = open(frozen_c, 'w') - try: - makefreeze.makefreeze(outfp, dict) - finally: - outfp.close() - if backup: - if cmp.cmp(backup, frozen_c): - sys.stderr.write('%s not changed, not written\n' % - frozen_c) - os.rename(backup, frozen_c) - - builtins = [] - unknown = [] - mods = dict.keys() - mods.sort() - for mod in mods: - if dict[mod] == '<builtin>': - builtins.append(mod) - elif dict[mod] == '<unknown>': - unknown.append(mod) - - addfiles = [] - if unknown: - addfiles, addmods = \ - checkextensions.checkextensions(unknown, extensions) - for mod in addmods: - unknown.remove(mod) - builtins = builtins + addmods - if unknown: - sys.stderr.write('Warning: unknown modules remain: %s\n' % - string.join(unknown)) - - builtins.sort() - infp = open(config_c_in) - backup = config_c + '~' - try: - os.rename(config_c, backup) - except os.error: - backup = None - outfp = open(config_c, 'w') - try: - makeconfig.makeconfig(infp, outfp, builtins) - finally: - outfp.close() - infp.close() - if backup: - if cmp.cmp(backup, config_c): - sys.stderr.write('%s not changed, not written\n' % - config_c) - os.rename(backup, config_c) - - cflags = defines + includes + ['$(OPT)'] - libs = [] - for n in 'Modules', 'Python', 'Objects', 'Parser': - n = 'lib%s.a' % n - n = os.path.join(binlib, n) - libs.append(n) - - makevars = parsesetup.getmakevars(makefile_in) - somevars = {} - for key in makevars.keys(): - somevars[key] = makevars[key] - - somevars['CFLAGS'] = string.join(cflags) # override - files = ['$(OPT)', config_c, frozen_c, frozenmain_c] + \ - addfiles + libs + \ - ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] - - backup = makefile + '~' - try: - os.rename(makefile, backup) - except os.error: - backup = None - outfp = open(makefile, 'w') - try: - makemakefile.makemakefile(outfp, somevars, files, target) - finally: - outfp.close() - if backup: - if not cmp.cmp(backup, makefile): - print 'previous Makefile saved as', backup - - # Done! - - if tmpdir: - # Run make - curdir = os.getcwd() - os.chdir(tmpdir) - status = os.system('make > /dev/null') - os.chdir(curdir) - - if status: - sys.stderr.write('Compilation failed. Files left in %s\n' % - (tmpdir,)) - else: - tmptarget = os.path.join(tmpdir, target) - try: os.rename(tmptarget, target) - except os.error: - os.system('cp %s %s' % (tmptarget, target)) - os.system('rm -rf %s' % (tmpdir,)) - print 'Frozen target:', target - tmpdir = None - else: - print 'Now run make to build the target:', target - - -# Print usage message and exit - -def usage(msg = None): - if msg: - sys.stderr.write(str(msg) + '\n') - sys.stderr.write(usage_msg) - sys.exit(2) - - -try: main() -finally: - if tmpdir: - os.system('rm -rf %s' % (tmpdir,)) diff --git a/Tools/freeze/parsesetup.py b/Tools/freeze/parsesetup.py deleted file mode 100644 index 1795671e94..0000000000 --- a/Tools/freeze/parsesetup.py +++ /dev/null @@ -1,98 +0,0 @@ -# Parse Makefiles and Python Setup(.in) files. - -import regex -import string - - -# Extract variable definitions from a Makefile. -# Return a dictionary mapping names to values. -# May raise IOError. - -makevardef = regex.compile('^\([a-zA-Z0-9_]+\)[ \t]*=\(.*\)') - -def getmakevars(filename): - variables = {} - fp = open(filename) - try: - while 1: - line = fp.readline() - if not line: - break - if makevardef.match(line) < 0: - continue - name, value = makevardef.group(1, 2) - # Strip trailing comment - i = string.find(value, '#') - if i >= 0: - value = value[:i] - value = string.strip(value) - 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 = regex.compile('^\([a-zA-Z0-9_]+\)=\(.*\)') - -def getsetupinfo(filename): - modules = {} - variables = {} - fp = open(filename) - try: - while 1: - line = fp.readline() - if not line: - break - # Strip comments - i = string.find(line, '#') - if i >= 0: - line = line[:i] - if setupvardef.match(line) >= 0: - name, value = setupvardef.group(1, 2) - variables[name] = string.strip(value) - else: - words = string.split(line) - 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/Tools/modulator/EXAMPLE.py b/Tools/modulator/EXAMPLE.py deleted file mode 100644 index d4b254ae8c..0000000000 --- a/Tools/modulator/EXAMPLE.py +++ /dev/null @@ -1,53 +0,0 @@ -# -# Example input file for modulator if you don't have tk. -# -# You may also have to strip some imports out of modulator to make -# it work. - -import genmodule - -# -# Generate code for a simple object with a method called sample - -o = genmodule.object() -o.name = 'simple object' -o.abbrev = 'simp' -o.methodlist = ['sample'] -o.funclist = ['new'] - -# -# Generate code for an object that looks numberish -# -o2 = genmodule.object() -o2.name = 'number-like object' -o2.abbrev = 'nl' -o2.typelist = ['tp_as_number'] -o2.funclist = ['new', 'tp_repr', 'tp_compare'] - -# -# Generate code for a method with a full complement of functions, -# some methods, accessible as sequence and allowing structmember.c type -# structure access as well. -# -o3 = genmodule.object() -o3.name = 'over-the-top object' -o3.abbrev = 'ot' -o3.methodlist = ['method1', 'method2'] -o3.funclist = ['new', 'tp_dealloc', 'tp_print', 'tp_getattr', 'tp_setattr', - 'tp_compare', 'tp_repr', 'tp_hash'] -o3.typelist = ['tp_as_sequence', 'structure'] - -# -# Now generate code for a module that incorporates these object types. -# Also add the boilerplates for functions to create instances of each -# type. -# -m = genmodule.module() -m.name = 'sample' -m.abbrev = 'sample' -m.methodlist = ['newsimple', 'newnumberish', 'newott'] -m.objects = [o, o2, o3] - -fp = open('EXAMPLEmodule.c', 'w') -genmodule.write(fp, m) -fp.close() diff --git a/Tools/modulator/README b/Tools/modulator/README deleted file mode 100644 index 30b5622034..0000000000 --- a/Tools/modulator/README +++ /dev/null @@ -1,24 +0,0 @@ -This is release 1.2 of modulator, a generator of boilerplate code for -modules to be written in C. - -Difference between 1.2 and 1.1: __doc__ templates are now generated -(thanks to Jim Fulton). - -Difference between 1.1 and 1.0: the templates now use "new-style" -naming conventions. Many thanks to Chak Tan <tan@ee.rochester.edu> for -supplying them. - -Usage when you have tk is *really* simple: start modulator, fill out -the forms specifying all the objects and methods, tell modulator -whether objects should also be accessible as sequences, etc and press -'generate code'. It will write a complete skeleton module for you. - -Usage when you don't have tk is slightly more difficult. Look at -EXAMPLE.py for some details. - -Oh yeah: you'll probably want to change Templates/copyright, or all -your code ends up as being copyrighted to CWI:-) - -Let me know what you think, - Jack Jansen, jack@cwi.nl - diff --git a/Tools/modulator/ScrolledListbox.py b/Tools/modulator/ScrolledListbox.py deleted file mode 100644 index 89686ef351..0000000000 --- a/Tools/modulator/ScrolledListbox.py +++ /dev/null @@ -1,37 +0,0 @@ -# A ScrolledList widget feels like a list widget but also has a -# vertical scroll bar on its right. (Later, options may be added to -# add a horizontal bar as well, to make the bars disappear -# automatically when not needed, to move them to the other side of the -# window, etc.) -# -# Configuration options are passed to the List widget. -# A Frame widget is inserted between the master and the list, to hold -# the Scrollbar widget. -# Most methods calls are inherited from the List widget; Pack methods -# are redirected to the Frame widget however. - -from Tkinter import * -from Tkinter import _cnfmerge - -class ScrolledListbox(Listbox): - def __init__(self, master=None, cnf={}): - cnf = _cnfmerge(cnf) - fcnf = {} - vcnf = {'name': 'vbar', - Pack: {'side': 'right', 'fill': 'y'},} - for k in cnf.keys(): - if type(k) == ClassType or k == 'name': - fcnf[k] = cnf[k] - del cnf[k] - self.frame = Frame(master, fcnf) - self.vbar = Scrollbar(self.frame, vcnf) - cnf[Pack] = {'side': 'left', 'fill': 'both', 'expand': 'yes'} - cnf['name'] = 'list' - Listbox.__init__(self, self.frame, cnf) - self['yscrollcommand'] = (self.vbar, 'set') - self.vbar['command'] = (self, 'yview') - - # Copy Pack methods of self.frame -- hack! - for m in Pack.__dict__.keys(): - if m[0] != '_' and m != 'config': - setattr(self, m, getattr(self.frame, m)) diff --git a/Tools/modulator/Templates/copyright b/Tools/modulator/Templates/copyright deleted file mode 100644 index 86206c3376..0000000000 --- a/Tools/modulator/Templates/copyright +++ /dev/null @@ -1,23 +0,0 @@ -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee 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, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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/Tools/modulator/Templates/module_head b/Tools/modulator/Templates/module_head deleted file mode 100644 index be001090b9..0000000000 --- a/Tools/modulator/Templates/module_head +++ /dev/null @@ -1,6 +0,0 @@ - -#include "Python.h" - -static PyObject *ErrorObject; - -/* ----------------------------------------------------- */ diff --git a/Tools/modulator/Templates/module_method b/Tools/modulator/Templates/module_method deleted file mode 100644 index 9e6c0d2c12..0000000000 --- a/Tools/modulator/Templates/module_method +++ /dev/null @@ -1,16 +0,0 @@ - -static char $abbrev$_$method$__doc__[] = -"" -; - -static PyObject * -$abbrev$_$method$(self, args) - PyObject *self; /* Not used */ - PyObject *args; -{ - - if (!PyArg_ParseTuple(args, "")) - return NULL; - Py_INCREF(Py_None); - return Py_None; -} diff --git a/Tools/modulator/Templates/module_tail b/Tools/modulator/Templates/module_tail deleted file mode 100644 index 59cc50b6c0..0000000000 --- a/Tools/modulator/Templates/module_tail +++ /dev/null @@ -1,37 +0,0 @@ - -/* List of methods defined in the module */ - -static struct PyMethodDef $abbrev$_methods[] = { - $methodlist$ - {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ -}; - - -/* Initialization function for the module (*must* be called init$name$) */ - -static char $name$_module_documentation[] = -"" -; - -void -init$name$() -{ - PyObject *m, *d; - - /* Create the module and add the functions */ - m = Py_InitModule4("$name$", $abbrev$_methods, - $name$_module_documentation, - (PyObject*)NULL,PYTHON_API_VERSION); - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - ErrorObject = PyString_FromString("$name$.error"); - PyDict_SetItemString(d, "error", ErrorObject); - - /* XXXX Add constants here */ - - /* Check for errors */ - if (PyErr_Occurred()) - Py_FatalError("can't initialize module $name$"); -} - diff --git a/Tools/modulator/Templates/object_head b/Tools/modulator/Templates/object_head deleted file mode 100644 index 9e6fa5eeac..0000000000 --- a/Tools/modulator/Templates/object_head +++ /dev/null @@ -1,13 +0,0 @@ - -/* Declarations for objects of type $name$ */ - -typedef struct { - PyObject_HEAD - /* XXXX Add your own stuff here */ -} $abbrev$object; - -staticforward PyTypeObject $Abbrev$type; - - - -/* ---------------------------------------------------------------- */ diff --git a/Tools/modulator/Templates/object_method b/Tools/modulator/Templates/object_method deleted file mode 100644 index 95414947c4..0000000000 --- a/Tools/modulator/Templates/object_method +++ /dev/null @@ -1,16 +0,0 @@ - -static char $abbrev$_$method$__doc__[] = -"" -; - -static PyObject * -$abbrev$_$method$(self, args) - $abbrev$object *self; - PyObject *args; -{ - if (!PyArg_ParseTuple(args, "")) - return NULL; - Py_INCREF(Py_None); - return Py_None; -} - diff --git a/Tools/modulator/Templates/object_mlist b/Tools/modulator/Templates/object_mlist deleted file mode 100644 index a12a9e1be1..0000000000 --- a/Tools/modulator/Templates/object_mlist +++ /dev/null @@ -1,8 +0,0 @@ - -static struct PyMethodDef $abbrev$_methods[] = { - $methodlist$ - {NULL, NULL} /* sentinel */ -}; - -/* ---------- */ - diff --git a/Tools/modulator/Templates/object_new b/Tools/modulator/Templates/object_new deleted file mode 100644 index 30c5e363e6..0000000000 --- a/Tools/modulator/Templates/object_new +++ /dev/null @@ -1,13 +0,0 @@ - -static $abbrev$object * -new$abbrev$object() -{ - $abbrev$object *self; - - self = PyObject_NEW($abbrev$object, &$Abbrev$type); - if (self == NULL) - return NULL; - /* XXXX Add your own initializers here */ - return self; -} - diff --git a/Tools/modulator/Templates/object_structure b/Tools/modulator/Templates/object_structure deleted file mode 100644 index 4bb92ef7f1..0000000000 --- a/Tools/modulator/Templates/object_structure +++ /dev/null @@ -1,42 +0,0 @@ - -/* Code to access structure members by accessing attributes */ - -#include "structmember.h" - -#define OFF(x) offsetof(XXXXobject, x) - -static struct memberlist $abbrev$_memberlist[] = { - /* XXXX Add lines like { "foo", T_INT, OFF(foo), RO } */ - - {NULL} /* Sentinel */ -}; - -static PyObject * -$abbrev$_getattr(self, name) - $abbrev$object *self; - char *name; -{ - PyObject *rv; - - /* XXXX Add your own getattr code here */ - rv = PyMember_Get((char *)/*XXXX*/0, $abbrev$_memberlist, name); - if (rv) - return rv; - PyErr_Clear(); - return Py_FindMethod($abbrev$_methods, (PyObject *)self, name); -} - - -static int -$abbrev$_setattr(self, name, v) - $abbrev$object *self; - char *name; - PyObject *v; -{ - /* XXXX Add your own setattr code here */ - if ( v == NULL ) { - PyErr_SetString(PyExc_AttributeError, "Cannot delete attribute"); - return -1; - } - return PyMember_Set((char *)/*XXXX*/0, $abbrev$_memberlist, name, v); -} diff --git a/Tools/modulator/Templates/object_tail b/Tools/modulator/Templates/object_tail deleted file mode 100644 index 1d1334c9fe..0000000000 --- a/Tools/modulator/Templates/object_tail +++ /dev/null @@ -1,33 +0,0 @@ - -static char $Abbrev$type__doc__[] = -"" -; - -static PyTypeObject $Abbrev$type = { - PyObject_HEAD_INIT(&PyType_Type) - 0, /*ob_size*/ - "$name$", /*tp_name*/ - sizeof($abbrev$object), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)$tp_dealloc$, /*tp_dealloc*/ - (printfunc)$tp_print$, /*tp_print*/ - (getattrfunc)$tp_getattr$, /*tp_getattr*/ - (setattrfunc)$tp_setattr$, /*tp_setattr*/ - (cmpfunc)$tp_compare$, /*tp_compare*/ - (reprfunc)$tp_repr$, /*tp_repr*/ - $tp_as_number$, /*tp_as_number*/ - $tp_as_sequence$, /*tp_as_sequence*/ - $tp_as_mapping$, /*tp_as_mapping*/ - (hashfunc)$tp_hash$, /*tp_hash*/ - (ternaryfunc)$tp_call$, /*tp_call*/ - (reprfunc)$tp_str$, /*tp_str*/ - - /* Space for future expansion */ - 0L,0L,0L,0L, - $Abbrev$type__doc__ /* Documentation string */ -}; - -/* End of code for $name$ objects */ -/* -------------------------------------------------------- */ - diff --git a/Tools/modulator/Templates/object_tp_as_mapping b/Tools/modulator/Templates/object_tp_as_mapping deleted file mode 100644 index 440904f56a..0000000000 --- a/Tools/modulator/Templates/object_tp_as_mapping +++ /dev/null @@ -1,34 +0,0 @@ - -/* Code to access $name$ objects as mappings */ - -static int -$abbrev$_length(self) - $abbrev$object *self; -{ - /* XXXX Return the size of the mapping */ -} - -static PyObject * -$abbrev$_subscript(self, key) - $abbrev$object *self; - PyObject *key; -{ - /* XXXX Return the item of self indexed by key */ -} - -static int -$abbrev$_ass_sub(self, v, w) - $abbrev$object *self; - PyObject *v, *w; -{ - /* XXXX Put w in self under key v */ - return 0; -} - -static PyMappingMethods $abbrev$_as_mapping = { - (inquiry)$abbrev$_length, /*mp_length*/ - (binaryfunc)$abbrev$_subscript, /*mp_subscript*/ - (objobjargproc)$abbrev$_ass_sub, /*mp_ass_subscript*/ -}; - -/* -------------------------------------------------------- */ diff --git a/Tools/modulator/Templates/object_tp_as_number b/Tools/modulator/Templates/object_tp_as_number deleted file mode 100644 index 2f90edc2f5..0000000000 --- a/Tools/modulator/Templates/object_tp_as_number +++ /dev/null @@ -1,206 +0,0 @@ - -/* Code to access $name$ objects as numbers */ - -static PyObject * -$abbrev$_add(v, w) - $abbrev$object *v; - $abbrev$object *w; -{ - /* XXXX Add them */ -} - -static PyObject * -$abbrev$_sub(v, w) - $abbrev$object *v; - $abbrev$object *w; -{ - /* XXXX Subtract them */ -} - -static PyObject * -$abbrev$_mul(v, w) - $abbrev$object *v; - $abbrev$object *w; -{ - /* XXXX Multiply them */ -} - -static PyObject * -$abbrev$_div(x, y) - $abbrev$object *x; - $abbrev$object *y; -{ - /* XXXX Divide them */ -} - -static PyObject * -$abbrev$_mod(x, y) - $abbrev$object *x; - $abbrev$object *y; -{ - /* XXXX Modulo them */ -} - -static PyObject * -$abbrev$_divmod(x, y) - $abbrev$object *x; - $abbrev$object *y; -{ - /* XXXX Return 2-tuple with div and mod */ -} - -static PyObject * -$abbrev$_pow(v, w, z) - $abbrev$object *v; - $abbrev$object *w; - $abbrev$object *z; -{ - /* XXXX */ -} - -static PyObject * -$abbrev$_neg(v) - $abbrev$object *v; -{ - /* XXXX */ -} - -static PyObject * -$abbrev$_pos(v) - $abbrev$object *v; -{ - /* XXXX */ -} - -static PyObject * -$abbrev$_abs(v) - $abbrev$object *v; -{ - /* XXXX */ -} - -static int -$abbrev$_nonzero(v) - $abbrev$object *v; -{ - /* XXXX Return 1 if non-zero */ -} - -static PyObject * -$abbrev$_invert(v) - $abbrev$object *v; -{ - /* XXXX */ -} - -static PyObject * -$abbrev$_lshift(v, w) - $abbrev$object *v; - $abbrev$object *w; -{ - /* XXXX */ -} - -static PyObject * -$abbrev$_rshift(v, w) - $abbrev$object *v; - $abbrev$object *w; -{ - /* XXXX */ -} - -static PyObject * -$abbrev$_and(v, w) - $abbrev$object *v; - $abbrev$object *w; -{ - /* XXXX */ -} - -static PyObject * -$abbrev$_xor(v, w) - $abbrev$object *v; - $abbrev$object *w; -{ - /* XXXX */ -} - -static PyObject * -$abbrev$_or(v, w) - $abbrev$object *v; - $abbrev$object *w; -{ - /* XXXX */ -} - -static int -$abbrev$_coerce(pv, pw) - PyObject **pv; - PyObject **pw; -{ - /* XXXX I haven't a clue... */ - return 1; -} - -static PyObject * -$abbrev$_int(v) - $abbrev$object *v; -{ - /* XXXX */ -} - -static PyObject * -$abbrev$_long(v) - $abbrev$object *v; -{ - /* XXXX */ -} - -static PyObject * -$abbrev$_float(v) - $abbrev$object *v; -{ - /* XXXX */ -} - -static PyObject * -$abbrev$_oct(v) - $abbrev$object *v; -{ - /* XXXX Return object as octal stringobject */ -} - -static PyObject * -$abbrev$_hex(v) - $abbrev$object *v; -{ - /* XXXX Return object as hex stringobject */ -} - -static PyNumberMethods $abbrev$_as_number = { - (binaryfunc)$abbrev$_add, /*nb_add*/ - (binaryfunc)$abbrev$_sub, /*nb_subtract*/ - (binaryfunc)$abbrev$_mul, /*nb_multiply*/ - (binaryfunc)$abbrev$_div, /*nb_divide*/ - (binaryfunc)$abbrev$_mod, /*nb_remainder*/ - (binaryfunc)$abbrev$_divmod, /*nb_divmod*/ - (ternaryfunc)$abbrev$_pow, /*nb_power*/ - (unaryfunc)$abbrev$_neg, /*nb_negative*/ - (unaryfunc)$abbrev$_pos, /*nb_positive*/ - (unaryfunc)$abbrev$_abs, /*nb_absolute*/ - (inquiry)$abbrev$_nonzero, /*nb_nonzero*/ - (unaryfunc)$abbrev$_invert, /*nb_invert*/ - (binaryfunc)$abbrev$_lshift, /*nb_lshift*/ - (binaryfunc)$abbrev$_rshift, /*nb_rshift*/ - (binaryfunc)$abbrev$_and, /*nb_and*/ - (binaryfunc)$abbrev$_xor, /*nb_xor*/ - (binaryfunc)$abbrev$_or, /*nb_or*/ - (coercion)$abbrev$_coerce, /*nb_coerce*/ - (unaryfunc)$abbrev$_int, /*nb_int*/ - (unaryfunc)$abbrev$_long, /*nb_long*/ - (unaryfunc)$abbrev$_float, /*nb_float*/ - (unaryfunc)$abbrev$_oct, /*nb_oct*/ - (unaryfunc)$abbrev$_hex, /*nb_hex*/ -}; - -/* ------------------------------------------------------- */ diff --git a/Tools/modulator/Templates/object_tp_as_sequence b/Tools/modulator/Templates/object_tp_as_sequence deleted file mode 100644 index bc0f470262..0000000000 --- a/Tools/modulator/Templates/object_tp_as_sequence +++ /dev/null @@ -1,73 +0,0 @@ - -/* Code to handle accessing $name$ objects as sequence objects */ - -static int -$abbrev$_length(self) - $abbrev$object *self; -{ - /* XXXX Return the size of the object */ -} - -static PyObject * -$abbrev$_concat(self, bb) - $abbrev$object *self; - PyObject *bb; -{ - /* XXXX Return the concatenation of self and bb */ -} - -static PyObject * -$abbrev$_repeat(self, n) - $abbrev$object *self; - int n; -{ - /* XXXX Return a new object that is n times self */ -} - -static PyObject * -$abbrev$_item(self, i) - $abbrev$object *self; - int i; -{ - /* XXXX Return the i-th object of self */ -} - -static PyObject * -$abbrev$_slice(self, ilow, ihigh) - $abbrev$object *self; - int ilow, ihigh; -{ - /* XXXX Return the ilow..ihigh slice of self in a new object */ -} - -static int -$abbrev$_ass_item(self, i, v) - $abbrev$object *self; - int i; - PyObject *v; -{ - /* XXXX Assign to the i-th element of self */ - return 0; -} - -static int -$abbrev$_ass_slice(self, ilow, ihigh, v) - PyListObject *self; - int ilow, ihigh; - PyObject *v; -{ - /* XXXX Replace ilow..ihigh slice of self with v */ - return 0; -} - -static PySequenceMethods $abbrev$_as_sequence = { - (inquiry)$abbrev$_length, /*sq_length*/ - (binaryfunc)$abbrev$_concat, /*sq_concat*/ - (intargfunc)$abbrev$_repeat, /*sq_repeat*/ - (intargfunc)$abbrev$_item, /*sq_item*/ - (intintargfunc)$abbrev$_slice, /*sq_slice*/ - (intobjargproc)$abbrev$_ass_item, /*sq_ass_item*/ - (intintobjargproc)$abbrev$_ass_slice, /*sq_ass_slice*/ -}; - -/* -------------------------------------------------------------- */ diff --git a/Tools/modulator/Templates/object_tp_call b/Tools/modulator/Templates/object_tp_call deleted file mode 100644 index be4cc4bfa3..0000000000 --- a/Tools/modulator/Templates/object_tp_call +++ /dev/null @@ -1,10 +0,0 @@ - -static PyObject * -$abbrev$_call(self, args, kwargs) - $abbrev$object *self; - PyObject *args; - PyObject *kwargs; -{ - /* XXXX Return the result of calling self with argument args */ -} - diff --git a/Tools/modulator/Templates/object_tp_compare b/Tools/modulator/Templates/object_tp_compare deleted file mode 100644 index a2e2e9de74..0000000000 --- a/Tools/modulator/Templates/object_tp_compare +++ /dev/null @@ -1,7 +0,0 @@ - -static int -$abbrev$_compare(v, w) - $abbrev$object *v, *w; -{ - /* XXXX Compare objects and return -1, 0 or 1 */ -} diff --git a/Tools/modulator/Templates/object_tp_dealloc b/Tools/modulator/Templates/object_tp_dealloc deleted file mode 100644 index ca15c0359d..0000000000 --- a/Tools/modulator/Templates/object_tp_dealloc +++ /dev/null @@ -1,8 +0,0 @@ - -static void -$abbrev$_dealloc(self) - $abbrev$object *self; -{ - /* XXXX Add your own cleanup code here */ - PyMem_DEL(self); -} diff --git a/Tools/modulator/Templates/object_tp_getattr b/Tools/modulator/Templates/object_tp_getattr deleted file mode 100644 index 8e42aea964..0000000000 --- a/Tools/modulator/Templates/object_tp_getattr +++ /dev/null @@ -1,9 +0,0 @@ - -static PyObject * -$abbrev$_getattr(self, name) - $abbrev$object *self; - char *name; -{ - /* XXXX Add your own getattr code here */ - return Py_FindMethod($abbrev$_methods, (PyObject *)self, name); -} diff --git a/Tools/modulator/Templates/object_tp_hash b/Tools/modulator/Templates/object_tp_hash deleted file mode 100644 index 1681b4a384..0000000000 --- a/Tools/modulator/Templates/object_tp_hash +++ /dev/null @@ -1,7 +0,0 @@ - -static long -$abbrev$_hash(self) - $abbrev$object *self; -{ - /* XXXX Return a hash of self (or -1) */ -} diff --git a/Tools/modulator/Templates/object_tp_print b/Tools/modulator/Templates/object_tp_print deleted file mode 100644 index 017712e3b8..0000000000 --- a/Tools/modulator/Templates/object_tp_print +++ /dev/null @@ -1,10 +0,0 @@ - -static int -$abbrev$_print(self, fp, flags) - $abbrev$object *self; - FILE *fp; - int flags; -{ - /* XXXX Add code here to print self to fp */ - return 0; -} diff --git a/Tools/modulator/Templates/object_tp_repr b/Tools/modulator/Templates/object_tp_repr deleted file mode 100644 index 16aebc7427..0000000000 --- a/Tools/modulator/Templates/object_tp_repr +++ /dev/null @@ -1,10 +0,0 @@ - -static PyObject * -$abbrev$_repr(self) - $abbrev$object *self; -{ - PyObject *s; - - /* XXXX Add code here to put self into s */ - return s; -} diff --git a/Tools/modulator/Templates/object_tp_setattr b/Tools/modulator/Templates/object_tp_setattr deleted file mode 100644 index 15701b6226..0000000000 --- a/Tools/modulator/Templates/object_tp_setattr +++ /dev/null @@ -1,12 +0,0 @@ - -static int -$abbrev$_setattr(self, name, v) - $abbrev$object *self; - char *name; - PyObject *v; -{ - /* Set attribute 'name' to value 'v'. v==NULL means delete */ - - /* XXXX Add your own setattr code here */ - return -1; -} diff --git a/Tools/modulator/Templates/object_tp_str b/Tools/modulator/Templates/object_tp_str deleted file mode 100644 index bed15dfdf7..0000000000 --- a/Tools/modulator/Templates/object_tp_str +++ /dev/null @@ -1,11 +0,0 @@ - -static PyObject * -$abbrev$_str(self) - $abbrev$object *self; -{ - PyObject *s; - - /* XXXX Add code here to put self into s */ - return s; -} - diff --git a/Tools/modulator/Tkextra.py b/Tools/modulator/Tkextra.py deleted file mode 100755 index 25681aed7d..0000000000 --- a/Tools/modulator/Tkextra.py +++ /dev/null @@ -1,235 +0,0 @@ -#! /usr/local/bin/python - -# A Python function that generates dialog boxes with a text message, -# optional bitmap, and any number of buttons. -# Cf. Ousterhout, Tcl and the Tk Toolkit, Figs. 27.2-3, pp. 269-270. - -from Tkinter import * - -mainWidget = None - -def dialog(master, title, text, bitmap, default, *args): - - # 1. Create the top-level window and divide it into top - # and bottom parts. - - w = Toplevel(master, {'class': 'Dialog'}) - w.title(title) - w.iconname('Dialog') - - top = Frame(w, {'relief': 'raised', 'bd': 1, - Pack: {'side': 'top', 'fill': 'both'}}) - bot = Frame(w, {'relief': 'raised', 'bd': 1, - Pack: {'side': 'bottom', 'fill': 'both'}}) - - # 2. Fill the top part with the bitmap and message. - - msg = Message(top, - {'width': '3i', - 'text': text, - 'font': '-Adobe-Times-Medium-R-Normal-*-180-*', - Pack: {'side': 'right', 'expand': 1, - 'fill': 'both', - 'padx': '3m', 'pady': '3m'}}) - if bitmap: - bm = Label(top, {'bitmap': bitmap, - Pack: {'side': 'left', - 'padx': '3m', 'pady': '3m'}}) - - # 3. Create a row of buttons at the bottom of the dialog. - - buttons = [] - i = 0 - for but in args: - b = Button(bot, {'text': but, - 'command': ('set', 'button', i)}) - buttons.append(b) - if i == default: - bd = Frame(bot, {'relief': 'sunken', 'bd': 1, - Pack: {'side': 'left', 'expand': 1, - 'padx': '3m', 'pady': '2m'}}) - b.lift() - b.pack ({'in': bd, 'side': 'left', - 'padx': '2m', 'pady': '2m', - 'ipadx': '2m', 'ipady': '1m'}) - else: - b.pack ({'side': 'left', 'expand': 1, - 'padx': '3m', 'pady': '3m', - 'ipady': '2m', 'ipady': '1m'}) - i = i+1 - - # 4. Set up a binding for <Return>, if there's a default, - # set a grab, and claim the focus too. - - if default >= 0: - w.bind('<Return>', - lambda e, b=buttons[default], i=default: - (b.flash(), - b.setvar('button', i))) - - oldFocus = w.tk.call('focus') # XXX - w.grab_set() - w.focus() - - # 5. Wait for the user to respond, then restore the focus - # and return the index of the selected button. - - w.waitvar('button') - w.destroy() - w.tk.call('focus', oldFocus) # XXX - return w.getint(w.getvar('button')) - -def strdialog(master, title, text, bitmap, default, *args): - - # 1. Create the top-level window and divide it into top - # and bottom parts. - - w = Toplevel(master, {'class': 'Dialog'}) - w.title(title) - w.iconname('Dialog') - - top = Frame(w, {'relief': 'raised', 'bd': 1, - Pack: {'side': 'top', 'fill': 'both'}}) - if args: - bot = Frame(w, {'relief': 'raised', 'bd': 1, - Pack: {'side': 'bottom', 'fill': 'both'}}) - - # 2. Fill the top part with the bitmap, message and input field. - - if bitmap: - bm = Label(top, {'bitmap': bitmap, - Pack: {'side': 'left', - 'padx': '3m', 'pady': '3m'}}) - - msg = Message(top, - {'width': '3i', - 'text': text, - 'font': '-Adobe-Times-Medium-R-Normal-*-180-*', - Pack: {'side': 'left', - 'fill': 'both', - 'padx': '3m', 'pady': '3m'}}) - - field = Entry(top, - {'relief':'sunken', - Pack:{'side':'left', - 'fill':'x', - 'expand':1, - 'padx':'3m', 'pady':'3m'}}) - # 3. Create a row of buttons at the bottom of the dialog. - - buttons = [] - i = 0 - for but in args: - b = Button(bot, {'text': but, - 'command': ('set', 'button', i)}) - buttons.append(b) - if i == default: - bd = Frame(bot, {'relief': 'sunken', 'bd': 1, - Pack: {'side': 'left', 'expand': 1, - 'padx': '3m', 'pady': '2m'}}) - b.lift() - b.pack ({'in': bd, 'side': 'left', - 'padx': '2m', 'pady': '2m', - 'ipadx': '2m', 'ipady': '1m'}) - else: - b.pack ({'side': 'left', 'expand': 1, - 'padx': '3m', 'pady': '3m', - 'ipady': '2m', 'ipady': '1m'}) - i = i+1 - - # 4. Set up a binding for <Return>, if there's a default, - # set a grab, and claim the focus too. - - if not args: - w.bind('<Return>', lambda arg, top=top: top.setvar('button', 0)) - field.bind('<Return>', lambda arg, top=top: top.setvar('button', 0)) - elif default >= 0: - w.bind('<Return>', - lambda e, b=buttons[default], i=default: - (b.flash(), - b.setvar('button', i))) - field.bind('<Return>', - lambda e, b=buttons[default], i=default: - (b.flash(), - b.setvar('button', i))) - - oldFocus = w.tk.call('focus') # XXX - w.grab_set() - field.focus() - - # 5. Wait for the user to respond, then restore the focus - # and return the index of the selected button. - - w.waitvar('button') - v = field.get() - w.destroy() - w.tk.call('focus', oldFocus) # XXX - if args: - return v, w.getint(w.getvar('button')) - else: - return v - -def message(str): - i = dialog(mainWidget, 'Message', str, '', 0, 'OK') - -def askyn(str): - i = dialog(mainWidget, 'Question', str, '', 0, 'No', 'Yes') - return i - -def askync(str): - i = dialog(mainWidget, 'Question', str, '', 0, 'Cancel', 'No', 'Yes') - return i-1 - -def askstr(str): - i = strdialog(mainWidget, 'Question', str, '', 0) - return i - -def askfile(str): # XXXX For now... - i = strdialog(mainWidget, 'Question', str, '', 0) - return i - -# The rest is the test program. - -def _go(): - i = dialog(mainWidget, - 'Not Responding', - "The file server isn't responding right now; " - "I'll keep trying.", - '', - -1, - 'OK') - print 'pressed button', i - i = dialog(mainWidget, - 'File Modified', - 'File "tcl.h" has been modified since ' - 'the last time it was saved. ' - 'Do you want to save it before exiting the application?', - 'warning', - 0, - 'Save File', - 'Discard Changes', - 'Return To Editor') - print 'pressed button', i - print message('Test of message') - print askyn('Test of yes/no') - print askync('Test of yes/no/cancel') - print askstr('Type a string:') - print strdialog(mainWidget, 'Question', 'Another string:', '', - 0, 'Save', 'Save as text') - -def _test(): - import sys - global mainWidget - mainWidget = Frame() - Pack.config(mainWidget) - start = Button(mainWidget, - {'text': 'Press Here To Start', 'command': _go}) - start.pack() - endit = Button(mainWidget, - {'text': 'Exit', - 'command': 'exit', - Pack: {'fill' : 'both'}}) - mainWidget.mainloop() - -if __name__ == '__main__': - _test() diff --git a/Tools/modulator/genmodule.py b/Tools/modulator/genmodule.py deleted file mode 100755 index e5c69bfdcf..0000000000 --- a/Tools/modulator/genmodule.py +++ /dev/null @@ -1,161 +0,0 @@ -# -# Genmodule - A python program to help you build (template) modules. -# -# Usage: -# -# o = genmodule.object() -# o.name = 'dwarve object' -# o.abbrev = 'dw' -# o.funclist = ['new', 'dealloc', 'getattr', 'setattr'] -# o.methodlist = ['dig'] -# -# m = genmodule.module() -# m.name = 'beings' -# m.abbrev = 'be' -# m.methodlist = ['newdwarve'] -# m.objects = [o] -# -# genmodule.write(sys.stdout, m) -# -import sys -import os -import varsubst -import string - -error = 'genmodule.error' - -# -# Names of functions in the object-description struct. -# -FUNCLIST = ['new', 'tp_dealloc', 'tp_print', 'tp_getattr', 'tp_setattr', - 'tp_compare', 'tp_repr', 'tp_hash', 'tp_call', 'tp_str'] -TYPELIST = ['tp_as_number', 'tp_as_sequence', 'tp_as_mapping', 'structure'] - -# -# writer is a base class for the object and module classes -# it contains code common to both. -# -class writer: - def __init__(self): - self._subst = None - - def makesubst(self): - if not self._subst: - if not self.__dict__.has_key('abbrev'): - self.abbrev = self.name - self.Abbrev = string.upper(self.abbrev[0])+self.abbrev[1:] - subst = varsubst.Varsubst(self.__dict__) - subst.useindent(1) - self._subst = subst.subst - - def addcode(self, name, fp): - ifp = self.opentemplate(name) - self.makesubst() - d = ifp.read() - d = self._subst(d) - fp.write(d) - - def opentemplate(self, name): - for p in sys.path: - fn = os.path.join(p, name) - if os.path.exists(fn): - return open(fn, 'r') - fn = os.path.join(p, 'Templates') - fn = os.path.join(fn, name) - if os.path.exists(fn): - return open(fn, 'r') - raise error, 'Template '+name+' not found for '+self._type+' '+ \ - self.name - -class module(writer): - _type = 'module' - - def writecode(self, fp): - self.addcode('copyright', fp) - self.addcode('module_head', fp) - for o in self.objects: - o.writehead(fp) - for o in self.objects: - o.writebody(fp) - new_ml = '' - for fn in self.methodlist: - self.method = fn - self.addcode('module_method', fp) - new_ml = new_ml + ( - '{"%s",\t(PyCFunction)%s_%s,\tMETH_VARARGS,\t%s_%s__doc__},\n' - %(fn, self.abbrev, fn, self.abbrev, fn)) - self.methodlist = new_ml - self.addcode('module_tail', fp) - -class object(writer): - _type = 'object' - def __init__(self): - self.typelist = [] - self.methodlist = [] - self.funclist = ['new'] - writer.__init__(self) - - def writecode(self, fp): - self.addcode('copyright', fp) - self.writehead(fp) - self.writebody(fp) - - def writehead(self, fp): - self.addcode('object_head', fp) - - def writebody(self, fp): - new_ml = '' - for fn in self.methodlist: - self.method = fn - self.addcode('object_method', fp) - new_ml = new_ml + ( - '{"%s",\t(PyCFunction)%s_%s,\tMETH_VARARGS,\t%s_%s__doc__},\n' - %(fn, self.abbrev, fn, self.abbrev, fn)) - self.methodlist = new_ml - self.addcode('object_mlist', fp) - - # Add getattr if we have methods - if self.methodlist and not 'tp_getattr' in self.funclist: - self.funclist.insert(0, 'tp_getattr') - - for fn in FUNCLIST: - setattr(self, fn, '0') - - # - # Special case for structure-access objects: put getattr in the - # list of functions but don't generate code for it directly, - # the code is obtained from the object_structure template. - # The same goes for setattr. - # - if 'structure' in self.typelist: - if 'tp_getattr' in self.funclist: - self.funclist.remove('tp_getattr') - if 'tp_setattr' in self.funclist: - self.funclist.remove('tp_setattr') - self.tp_getattr = self.abbrev + '_getattr' - self.tp_setattr = self.abbrev + '_setattr' - for fn in self.funclist: - self.addcode('object_'+fn, fp) - setattr(self, fn, '%s_%s'%(self.abbrev, fn[3:])) - for tn in TYPELIST: - setattr(self, tn, '0') - for tn in self.typelist: - self.addcode('object_'+tn, fp) - setattr(self, tn, '&%s_%s'%(self.abbrev, tn[3:])) - self.addcode('object_tail', fp) - -def write(fp, obj): - obj.writecode(fp) - -if __name__ == '__main__': - o = object() - o.name = 'dwarve object' - o.abbrev = 'dw' - o.funclist = ['new', 'tp_dealloc'] - o.methodlist = ['dig'] - m = module() - m.name = 'beings' - m.abbrev = 'be' - m.methodlist = ['newdwarve'] - m.objects = [o] - write(sys.stdout, m) diff --git a/Tools/modulator/modulator.py b/Tools/modulator/modulator.py deleted file mode 100755 index 02ad80d572..0000000000 --- a/Tools/modulator/modulator.py +++ /dev/null @@ -1,379 +0,0 @@ -#! /usr/local/bin/python -# -# Modulator - Generate skeleton modules. -# -# The user fills out some forms with information about what the module -# should support (methods, objects), names of these things, prefixes to -# use for C code, whether the objects should also support access as numbers, -# etc etc etc. -# When the user presses 'Generate code' we generate a complete skeleton -# module in C. -# -# Alternatively, the selections made can be save to a python sourcefile and -# this sourcefile can be passed on the command line (resulting in the same -# skeleton C code). -# -# Jack Jansen, CWI, October 1994. -# - -import sys, os -if os.name <> 'mac': - sys.path.append(os.path.join(os.environ['HOME'], 'src/python/Tools/modulator')) - -from Tkinter import * -from Tkextra import * -from ScrolledListbox import ScrolledListbox -import sys -import genmodule -import string - -oops = 'oops' - -# Check that string is a legal C identifier -def checkid(str): - if not str: return 0 - if not str[0] in string.letters+'_': - return 0 - for c in str[1:]: - if not c in string.letters+string.digits+'_': - return 0 - return 1 - -def getlistlist(list): - rv = [] - n = list.size() - for i in range(n): - rv.append(list.get(i)) - return rv - -class UI: - def __init__(self): - self.main = Frame() - self.main.pack() - self.main.master.title('Modulator: Module view') - self.cmdframe = Frame(self.main, {'relief':'raised', 'bd':'0.5m', - Pack:{'side':'top', - 'fill':'x'}}) - self.objframe = Frame(self.main, {Pack:{'side':'top', 'fill':'x', - 'expand':1}}) - - - self.check_button = Button(self.cmdframe, - {'text':'Check', 'command':self.cb_check, - Pack:{'side':'left', 'padx':'0.5m'}}) - self.save_button = Button(self.cmdframe, - {'text':'Save...', 'command':self.cb_save, - Pack:{'side':'left', 'padx':'0.5m'}}) - self.code_button = Button(self.cmdframe, - {'text':'Generate code...', - 'command':self.cb_gencode, - Pack:{'side':'left', 'padx':'0.5m'}}) - self.quit_button = Button(self.cmdframe, - {'text':'Quit', - 'command':self.cb_quit, - Pack:{'side':'right', 'padx':'0.5m'}}) - - self.module = UI_module(self) - self.objects = [] - self.modified = 0 - - def run(self): - self.main.mainloop() - - def cb_quit(self, *args): - if self.modified: - if not askyn('You have not saved\nAre you sure you want to quit?'): - return - sys.exit(0) - - def cb_check(self, *args): - try: - self.module.synchronize() - for o in self.objects: - o.synchronize() - except oops: - pass - - def cb_save(self, *args): - try: - pycode = self.module.gencode('m', self.objects) - except oops: - return - - fn = askfile('Python file name: ') - if not fn: - return - - fp = open(fn, 'w') - - fp.write(pycode) - fp.close() - - def cb_gencode(self, *args): - try: - pycode = self.module.gencode('m', self.objects) - except oops: - pass - - fn = askfile('C file name: ') - if not fn: - return - - fp = open(fn, 'w') - - try: - exec pycode - except: - message('An error occurred:-)') - return - genmodule.write(fp, m) - fp.close() - -class UI_module: - def __init__(self, parent): - self.parent = parent - self.frame = Frame(parent.objframe, {'relief':'raised', 'bd':'0.2m', - Pack:{'side':'top', - 'fill':'x'}}) - self.f1 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m', - 'fill':'x'}}) - self.f2 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m', - 'fill':'x'}}) - self.f3 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m', - 'fill':'x'}}) - self.f4 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m', - 'fill':'x'}}) - - self.l1 = Label(self.f1, {'text':'Module:', Pack:{'side':'left', - 'padx':'0.5m'}}) - self.name_entry = Entry(self.f1, {'relief':'sunken', - Pack:{'side':'left', 'padx':'0.5m', 'expand':1}}) - self.l2 = Label(self.f1, {'text':'Abbrev:', Pack:{'side':'left', - 'padx':'0.5m'}}) - self.abbrev_entry = Entry(self.f1, {'relief':'sunken', 'width':5, - Pack:{'side':'left', 'padx':'0.5m'}}) - - self.l3 = Label(self.f2, {'text':'Methods:', Pack:{'side':'left', - 'padx':'0.5m'}}) - self.method_list = ScrolledListbox(self.f2, {'relief':'sunken','bd':2, - Pack:{'side':'left', 'expand':1, - 'padx':'0.5m', 'fill':'both'}}) - - self.l4 = Label(self.f3, {'text':'Add method:', Pack:{'side':'left', - 'padx':'0.5m'}}) - self.method_entry = Entry(self.f3, {'relief':'sunken', - Pack:{'side':'left', 'padx':'0.5m', 'expand':1}}) - self.method_entry.bind('<Return>', self.cb_method) - self.delete_button = Button(self.f3, {'text':'Delete method', - 'command':self.cb_delmethod, - Pack:{'side':'left', - 'padx':'0.5m'}}) - - self.newobj_button = Button(self.f4, {'text':'new object', - 'command':self.cb_newobj, - Pack:{'side':'left', - 'padx':'0.5m'}}) - - def cb_delmethod(self, *args): - list = self.method_list.curselection() - for i in list: - self.method_list.delete(i) - - def cb_newobj(self, *arg): - self.parent.objects.append(UI_object(self.parent)) - - def cb_method(self, *arg): - name = self.method_entry.get() - if not name: - return - self.method_entry.delete('0', 'end') - self.method_list.insert('end', name) - - def synchronize(self): - n = self.name_entry.get() - if not n: - message('Module name not set') - raise oops - if not checkid(n): - message('Module name not an identifier:\n'+n) - raise oops - if not self.abbrev_entry.get(): - self.abbrev_entry.insert('end', n) - m = getlistlist(self.method_list) - for n in m: - if not checkid(n): - message('Method name not an identifier:\n'+n) - raise oops - - def gencode(self, name, objects): - rv = '' - self.synchronize() - for o in objects: - o.synchronize() - onames = [] - for i in range(len(objects)): - oname = 'o'+`i+1` - rv = rv + objects[i].gencode(oname) - onames.append(oname) - rv = rv + (name+' = genmodule.module()\n') - rv = rv + (name+'.name = '+`self.name_entry.get()`+'\n') - rv = rv + (name+'.abbrev = '+`self.abbrev_entry.get()`+'\n') - rv = rv + (name+'.methodlist = '+`getlistlist(self.method_list)`+'\n') - rv = rv + (name+'.objects = ['+string.joinfields(onames, ',')+']\n') - rv = rv + ('\n') - return rv - -object_number = 0 - -class UI_object: - def __init__(self, parent): - global object_number - - object_number = object_number + 1 - self.num = object_number - self.vpref = 'o'+`self.num`+'_' - self.frame = Toplevel(parent.objframe) -# self.frame.pack() - self.frame.title('Modulator: object view') -# self.frame = Frame(parent.objframe, {'relief':'raised', 'bd':'0.2m', -# Pack:{'side':'top', -# 'fill':'x'}}) - self.f1 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m', - 'fill':'x'}}) - self.f2 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m', - 'fill':'x'}}) - self.f3 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m', - 'fill':'x'}}) - self.f4 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m', - 'fill':'x'}}) - - - self.l1 = Label(self.f1, {'text':'Object:', Pack:{'side':'left', - 'padx':'0.5m'}}) - self.name_entry = Entry(self.f1, {'relief':'sunken', - Pack:{'side':'left', 'padx':'0.5m', 'expand':1}}) - self.l2 = Label(self.f1, {'text':'Abbrev:', Pack:{'side':'left', - 'padx':'0.5m'}}) - self.abbrev_entry = Entry(self.f1, {'relief':'sunken', 'width':5, - Pack:{'side':'left', 'padx':'0.5m'}}) - - self.l3 = Label(self.f2, {'text':'Methods:', Pack:{'side':'left', - 'padx':'0.5m'}}) - self.method_list = ScrolledListbox(self.f2, {'relief':'sunken','bd':2, - Pack:{'side':'left', 'expand':1, - 'padx':'0.5m', 'fill':'both'}}) - - self.l4 = Label(self.f3, {'text':'Add method:', Pack:{'side':'left', - 'padx':'0.5m'}}) - self.method_entry = Entry(self.f3, {'relief':'sunken', - Pack:{'side':'left', 'padx':'0.5m', 'expand':1}}) - self.method_entry.bind('<Return>', self.cb_method) - self.delete_button = Button(self.f3, {'text':'Delete method', - 'command':self.cb_delmethod, - Pack:{'side':'left', - 'padx':'0.5m'}}) - - - self.l5 = Label(self.f4, {'text':'functions:', - Pack:{'side':'left', - 'padx':'0.5m'}}) - self.f5 = Frame(self.f4, {Pack:{'side':'left', 'pady':'0.5m', - 'fill':'both'}}) - self.l6 = Label(self.f4, {'text':'Types:', - Pack:{'side':'left', 'padx':'0.5m'}}) - self.f6 = Frame(self.f4, {Pack:{'side':'left', 'pady':'0.5m', - 'fill':'x'}}) - self.funcs = {} - for i in genmodule.FUNCLIST: - vname = self.vpref+i - self.f5.setvar(vname, 0) - b = Checkbutton(self.f5, {'variable':vname, 'text':i, - Pack:{'side':'top', 'pady':'0.5m', - 'anchor':'w','expand':1}}) - self.funcs[i] = b - self.f5.setvar(self.vpref+'new', 1) - - self.types = {} - for i in genmodule.TYPELIST: - vname = self.vpref + i - self.f6.setvar(vname, 0) - b = Checkbutton(self.f6, {'variable':vname, 'text':i, - Pack:{'side':'top', 'pady':'0.5m', - 'anchor':'w'}}) - self.types[i] = b - - def cb_method(self, *arg): - name = self.method_entry.get() - if not name: - return - self.method_entry.delete('0', 'end') - self.method_list.insert('end', name) - - def cb_delmethod(self, *args): - list = self.method_list.curselection() - for i in list: - self.method_list.delete(i) - - def synchronize(self): - n = self.name_entry.get() - if not n: - message('Object name not set') - raise oops - if not self.abbrev_entry.get(): - self.abbrev_entry.insert('end', n) - n = self.abbrev_entry.get() - if not checkid(n): - message('Abbreviation not an identifier:\n'+n) - raise oops - m = getlistlist(self.method_list) - for n in m: - if not checkid(n): - message('Method name not an identifier:\n'+n) - raise oops - if m: - self.f5.setvar(self.vpref+'tp_getattr', 1) - pass - - def gencode(self, name): - rv = '' - rv = rv + (name+' = genmodule.object()\n') - rv = rv + (name+'.name = '+`self.name_entry.get()`+'\n') - rv = rv + (name+'.abbrev = '+`self.abbrev_entry.get()`+'\n') - rv = rv + (name+'.methodlist = '+`getlistlist(self.method_list)`+'\n') - fl = [] - for fn in genmodule.FUNCLIST: - vname = self.vpref + fn - if self.f5.getvar(vname) == '1': - fl.append(fn) - rv = rv + (name+'.funclist = '+`fl`+'\n') - - fl = [] - for fn in genmodule.TYPELIST: - vname = self.vpref + fn - if self.f5.getvar(vname) == '1': - fl.append(fn) - - rv = rv + (name+'.typelist = '+`fl`+'\n') - - rv = rv + ('\n') - return rv - - -def main(): - if len(sys.argv) < 2: - ui = UI() - ui.run() - elif len(sys.argv) == 2: - fp = open(sys.argv[1]) - pycode = fp.read() - try: - exec pycode - except: - sys.stderr.write('An error occurred:-)\n') - sys.exit(1) - genmodule.write(sys.stdout, m) - else: - sys.stderr.write('Usage: modulator [file]\n') - sys.exit(1) - -main() diff --git a/Tools/modulator/varsubst.py b/Tools/modulator/varsubst.py deleted file mode 100644 index ec89fe3517..0000000000 --- a/Tools/modulator/varsubst.py +++ /dev/null @@ -1,61 +0,0 @@ -# -# Variable substitution. Variables are $delimited$ -# -import string -import regex -import regsub - -error = 'varsubst.error' - -class Varsubst: - def __init__(self, dict): - self.dict = dict - self.prog = regex.compile('\$[a-zA-Z0-9_]*\$') - self.do_useindent = 0 - - def useindent(self, onoff): - self.do_useindent = onoff - - def subst(self, str): - rv = '' - while 1: - pos = self.prog.search(str) - if pos < 0: - return rv + str - if pos: - rv = rv + str[:pos] - str = str[pos:] - len = self.prog.match(str) - if len == 2: - # Escaped dollar - rv = rv + '$' - str = str[2:] - continue - name = str[1:len-1] - str = str[len:] - if not self.dict.has_key(name): - raise error, 'No such variable: '+name - value = self.dict[name] - if self.do_useindent and '\n' in value: - value = self._modindent(value, rv) - rv = rv + value - - def _modindent(self, value, old): - lastnl = string.rfind(old, '\n', 0) + 1 - lastnl = len(old) - lastnl - sub = '\n' + (' '*lastnl) - return regsub.gsub('\n', sub, value) - -def _test(): - import sys - import os - - sys.stderr.write('-- Copying stdin to stdout with environment map --\n') - c = Varsubst(os.environ) - c.useindent(1) - d = sys.stdin.read() - sys.stdout.write(c.subst(d)) - sys.exit(1) - -if __name__ == '__main__': - _test() diff --git a/Tools/scripts/README b/Tools/scripts/README deleted file mode 100644 index 005edf57fa..0000000000 --- a/Tools/scripts/README +++ /dev/null @@ -1,33 +0,0 @@ -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! - -byteyears.py Print product of a file's size and age -checkpyc.py Check presence and validity of ".pyc" files -classfix.py Convert old class syntax to new -copytime.py Copy one file's atime and mtime to another -dutree.py Format du(1) output as a tree sorted by size -eptags.py Create Emacs TAGS file for Python modules -findlinksto.py Recursively find symbolic links to a given path prefix -fixcid.py Massive identifier substitution on C source files -fixheader.py Add some cpp magic to a C include file -fixps.py Fix Python scripts' first line (if #!) -ftpmirror.py FTP mirror script -h2py.py Translate #define's into Python assignments -ifdef.py Remove #if(n)def groups from C sources -linktree.py Make a copy of a tree with links to original files -lll.py Find and list symbolic links in current directory -methfix.py Fix old method syntax def f(self, (a1, ..., aN)): -mkreal.py Turn a symbolic link into a real file or directory -objgraph.py Print object graph from nm output on a library -pathfix.py Change #!/usr/local/bin/python into something else -pdeps.py Print dependencies between Python modules -pindent.py Indent Python code, giving block-closing comments -ptags.py Create vi tags file for Python modules -pystone.py Benchmark, based on "Dhrystone" C benchmark -suff.py Sort a list of files by suffix -sum5.py Print md5 checksums of files -which.py Find a program in $PATH -xxci.py Wrapper for rcsdiff and ci diff --git a/Tools/scripts/byteyears.py b/Tools/scripts/byteyears.py deleted file mode 100755 index 4abdca641c..0000000000 --- a/Tools/scripts/byteyears.py +++ /dev/null @@ -1,57 +0,0 @@ -#! /usr/local/bin/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 -import string -from stat import * - -# 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 file in sys.argv[1:]: - if len(file) > maxlen: maxlen = len(file) - -# Process each argument in turn -for file in sys.argv[1:]: - try: - st = statfunc(file) - except os.error, msg: - sys.stderr.write('can\'t stat ' + `file` + ': ' + `msg` + '\n') - status = 1 - st = () - if st: - anytime = st[itime] - size = st[ST_SIZE] - age = now - anytime - byteyears = float(size) * float(age) / secs_per_year - print string.ljust(file, maxlen), - print string.rjust(`int(byteyears)`, 8) - -sys.exit(status) diff --git a/Tools/scripts/checkpyc.py b/Tools/scripts/checkpyc.py deleted file mode 100755 index 6ef6492a0b..0000000000 --- a/Tools/scripts/checkpyc.py +++ /dev/null @@ -1,69 +0,0 @@ -#! /usr/local/bin/python -# Check that all ".pyc" files exist and are up-to-date -# Uses module 'os' - -import sys -import os -from stat import ST_MTIME - -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 = '\0\0\0\0' - try: - if sys.version[:5] >= '0.9.4': - MAGIC = '\224\224\224\0' - except: - pass - if not silent: - print 'Using MAGIC word', `MAGIC` - for dirname in sys.path: - try: - names = os.listdir(dirname) - except os.error: - print 'Cannot list directory', `dirname` - continue - if not silent: - print 'Checking', `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', `name` - continue - if verbose: - print 'Check', `name`, '...' - name_c = name + 'c' - try: - f = open(name_c, 'r') - except IOError: - print 'Cannot open', `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 `name_c` - continue - mtime = get_long(mtime_str) - if mtime == 0 or mtime == -1: - print 'Bad ".pyc" file', `name_c` - elif mtime <> st[ST_MTIME]: - print 'Out-of-date ".pyc" file', - print `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) - -main() diff --git a/Tools/scripts/classfix.py b/Tools/scripts/classfix.py deleted file mode 100755 index 09a94006d4..0000000000 --- a/Tools/scripts/classfix.py +++ /dev/null @@ -1,188 +0,0 @@ -#! /usr/local/bin/python - -# Fix Python source files to use the new class definition syntax, i.e., -# class C() = base(), base(), ...: ... -# is changed to -# 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 regex -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 = regex.compile('^[a-zA-Z0-9_]+\.py$') -def ispython(name): - return ispythonprog.match(name) >= 0 - -def recursedown(dirname): - dbg('recursedown(' + `dirname` + ')\n') - bad = 0 - try: - names = os.listdir(dirname) - except os.error, msg: - err(dirname + ': cannot list directory: ' + `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 ispython(name): - if fix(fullname): bad = 1 - for fullname in subdirs: - if recursedown(fullname): bad = 1 - return bad - -def fix(filename): -## dbg('fix(' + `filename` + ')\n') - try: - f = open(filename, 'r') - except IOError, msg: - err(filename + ': cannot open: ' + `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 - 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: '+\ - `msg`+'\n') - return 1 - f.seek(0) - lineno = 0 - rep(filename + ':\n') - continue # restart from the beginning - rep(`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(tempname + ': warning: chmod failed (' + `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 (' + `msg` + ')\n') - # Now move the temp file to the original file - try: - os.rename(tempname, filename) - except os.error, msg: - err(filename + ': rename failed (' + `msg` + ')\n') - 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 = regex.compile(classexpr) - -# Expressions for finding base class expressions. -baseexpr = '^ *\(.*\) *( *) *$' -baseprog = regex.compile(baseexpr) - -import string - -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 = string.splitfields(basepart, ',') - - # 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 = string.joinfields(bases, ', ') - - return head + '(' + basepart + '):' + tail - -main() diff --git a/Tools/scripts/copytime.py b/Tools/scripts/copytime.py deleted file mode 100755 index 599e3370c1..0000000000 --- a/Tools/scripts/copytime.py +++ /dev/null @@ -1,25 +0,0 @@ -#! /usr/local/bin/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) - -main() diff --git a/Tools/scripts/dutree.doc b/Tools/scripts/dutree.doc deleted file mode 100644 index 2a094261b1..0000000000 --- a/Tools/scripts/dutree.doc +++ /dev/null @@ -1,54 +0,0 @@ -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/Tools/scripts/dutree.py b/Tools/scripts/dutree.py deleted file mode 100755 index 58d0b14542..0000000000 --- a/Tools/scripts/dutree.py +++ /dev/null @@ -1,55 +0,0 @@ -#! /usr/local/bin/python -# Format du output in a tree shape - -import os, string, sys - -def main(): - p = os.popen('du ' + string.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 - file = line[i:-1] - comps = string.splitfields(file, '/') - if comps[0] == '': comps[0] = '/' - if comps[len(comps)-1] == '': del comps[len(comps)-1] - total, d = store(size, comps, total, d) - display(total, d) - -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(`list[0][0]`) - for tsub, key in list: - if tsub is None: - psub = prefix - else: - print prefix + string.rjust(`tsub`, width) + ' ' + key - psub = prefix + ' '*(width-1) + '|' + ' '*(len(key)+1) - if d.has_key(key): - show(tsub, d[key][1], psub) - -main() diff --git a/Tools/scripts/eptags.py b/Tools/scripts/eptags.py deleted file mode 100755 index 63b5781347..0000000000 --- a/Tools/scripts/eptags.py +++ /dev/null @@ -1,50 +0,0 @@ -#! /usr/local/bin/python - -# eptags -# -# Create a TAGS file for Python programs, usable with GNU Emacs (version 18). -# Tagged are: -# - functions (even inside other defs or classes) -# - classes -# Warns about files it cannot open. -# No warnings about duplicate tags. - -import sys -import regex - -def main(): - outfp = open('TAGS', 'w') - args = sys.argv[1:] - for file in args: - treat_file(file, outfp) - -expr = '^[ \t]*\(def\|class\)[ \t]+\([a-zA-Z0-9_]+\)[ \t]*[:(]' -matcher = regex.compile(expr) - -def treat_file(file, outfp): - try: - fp = open(file, 'r') - except: - print 'Cannot open', file - return - charno = 0 - lineno = 0 - tags = [] - size = 0 - while 1: - line = fp.readline() - if not line: break - lineno = lineno + 1 - if matcher.search(line) >= 0: - (a, b), (a1, b1), (a2, b2) = matcher.regs[:3] - name = line[a2:b2] - pat = line[a:b] - tag = pat + '\177' + `lineno` + ',' + `charno` + '\n' - tags.append(name, tag) - size = size + len(tag) - charno = charno + len(line) - outfp.write('\f\n' + file + ',' + `size` + '\n') - for name, tag in tags: - outfp.write(tag) - -main() diff --git a/Tools/scripts/findlinksto.py b/Tools/scripts/findlinksto.py deleted file mode 100755 index d2fc430b28..0000000000 --- a/Tools/scripts/findlinksto.py +++ /dev/null @@ -1,42 +0,0 @@ -#! /usr/local/bin/python - -# findlinksto -# -# find symbolic links to a path matching a regular expression - -import os -import sys -import regex -import getopt - -def main(): - try: - opts, args = getopt.getopt(sys.argv[1:], '') - if len(args) < 2: - raise getopt.error, 'not enough arguments' - except getopt.error, msg: - sys.stdout = sys.stderr - print msg - print 'usage: findlinksto pattern directory ...' - sys.exit(2) - pat, dirs = args[0], args[1:] - prog = regex.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) >= 0: - print name, '->', linkto - except os.error: - pass - -main() diff --git a/Tools/scripts/fixcid.py b/Tools/scripts/fixcid.py deleted file mode 100755 index c1df5f3144..0000000000 --- a/Tools/scripts/fixcid.py +++ /dev/null @@ -1,318 +0,0 @@ -#! /usr/local/bin/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 (on 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 regex -import string -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 regex.match(Wanted, name) >= 0 - -def recursedown(dirname): - dbg('recursedown(' + `dirname` + ')\n') - 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(' + `filename` + ')\n') - 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(`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 succes - 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 = '\(' + string.joinfields(OutsideComment, '\|') + '\)' -OutsideCommentProgram = regex.compile(OutsideCommentPattern) - -InsideComment = (Identifier, Number, CommentEnd) -InsideCommentPattern = '\(' + string.joinfields(InsideComment, '\|') + '\)' -InsideCommentProgram = regex.compile(InsideCommentPattern) - -def initfixline(): - global Program - Program = OutsideCommentProgram - -def fixline(line): - global Program -## print '-->', `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 = string.index(line, '#') - except string.index_error: - i = -1 # Happens to delete trailing \n - words = string.split(line[:i]) - if not words: continue - if len(words) == 3 and words[0] == 'struct': - words[:2] = [words[0] + ' ' + words[1]] - elif len(words) <> 2: - err(substfile + ':' + `lineno` + - ': warning: bad line: ' + 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(substfile + ':' + `lineno` + - ': warning: overriding: ' + - key + ' ' + value + '\n') - err(substfile + ':' + `lineno` + - ': warning: previous: ' + Dict[key] + '\n') - Dict[key] = value - fp.close() - -main() diff --git a/Tools/scripts/fixheader.py b/Tools/scripts/fixheader.py deleted file mode 100755 index 8f121fa874..0000000000 --- a/Tools/scripts/fixheader.py +++ /dev/null @@ -1,49 +0,0 @@ -#! /usr/local/bin/python - -# Add some standard cpp magic to a header file - -import sys -import string - -def main(): - args = sys.argv[1:] - for file in args: - process(file) - -def process(file): - try: - f = open(file, 'r') - except IOError, msg: - sys.stderr.write('%s: can\'t open: %s\n' % (file, str(msg))) - return - data = f.read() - f.close() - if data[:2] <> '/*': - sys.stderr.write('%s does not begin with C comment\n' % file) - return - try: - f = open(file, 'w') - except IOError, msg: - sys.stderr.write('%s: can\'t write: %s\n' % (file, str(msg))) - return - sys.stderr.write('Processing %s ...\n' % file) - magic = 'Py_' - for c in file: - if c in string.letters + string.digits: - magic = magic + string.upper(c) - 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, '*/' - -main() diff --git a/Tools/scripts/fixps.py b/Tools/scripts/fixps.py deleted file mode 100755 index 3238c49377..0000000000 --- a/Tools/scripts/fixps.py +++ /dev/null @@ -1,32 +0,0 @@ -#! /usr/local/bin/python - -# Fix Python script(s) to reference the interpreter in /usr/local/bin. - -import sys -import regex -import regsub - - -def main(): - for file in sys.argv[1:]: - try: - f = open(file, 'r+') - except IOError: - print file, ': can\'t open for update' - continue - line = f.readline() - if regex.match('^#! */usr/local/python', line) < 0: - print file, ': not a /usr/local/python script' - f.close() - continue - rest = f.read() - line = regsub.sub('/usr/local/python', \ - '/usr/local/bin/python', line) - print file, ':', `line` - f.seek(0) - f.write(line) - f.write(rest) - f.close() - - -main() diff --git a/Tools/scripts/ftpmirror.py b/Tools/scripts/ftpmirror.py deleted file mode 100755 index ba9335d7b1..0000000000 --- a/Tools/scripts/ftpmirror.py +++ /dev/null @@ -1,318 +0,0 @@ -#! /usr/local/bin/python - -# Mirror a remote ftp subtree into a local directory tree. -# Basic usage: ftpmirror [options] host remotedir localdir -# -# XXX To do: -# - handle symbolic links -# - back up .mirrorinfo before overwriting -# - use pickles for .mirrorinfo? - -import os -import sys -import time -import getopt -import string -import ftplib -from fnmatch import fnmatch - -usage_msg = """ -usage: ftpmirror [-v] [-q] [-i] [-m] [-n] [-r] [-s pat] - [-l username [-p passwd [-a account]]] - hostname [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 files no longer pertinent --l username [-p passwd [-a account]]: login info (default anonymous ftp) --s pat: skip files matching pattern -hostname: remote host -remotedir: remote directory (default initial) -localdir: local directory (default current) -""" -def usage(*args): - sys.stdout = sys.stderr - for msg in args: print msg - print usage_msg - sys.exit(2) - -verbose = 1 # 0 for -q, 2 for -v -interactive = 0 -mac = 0 -rmok = 0 -nologin = 0 -skippats = ['.', '..', '.mirrorinfo'] - -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 = '' - 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) - if not args: usage('hostname missing') - host = args[0] - 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...' % host - f.connect(host) - if not nologin: - if verbose: - print 'Logging in as %s...' % (login or 'anonymous') - f.login(login, passwd, account) - if verbose: print 'OK.' - pwd = f.pwd() - if verbose > 1: print 'PWD =', `pwd` - if remotedir: - if verbose > 1: print 'cwd(%s)' % `remotedir` - f.cwd(remotedir) - if verbose > 1: print 'OK.' - pwd = f.pwd() - if verbose > 1: print 'PWD =', `pwd` - # - mirrorsubdir(f, localdir) - -def mirrorsubdir(f, localdir): - pwd = f.pwd() - if localdir and not os.path.isdir(localdir): - if verbose: print 'Creating local directory', localdir - try: - makedir(localdir) - except os.error, msg: - print "Failed to establish local directory", 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 %s' % infofilename - info = {} - subdirs = [] - listing = [] - if verbose: print 'Listing remote directory %s...' % pwd - f.retrlines('LIST', listing.append) - for line in listing: - if verbose > 1: print '-->', `line` - if mac: - # Mac listing has just filenames; - # trailing / means subdirectory - filename = string.strip(line) - mode = '-' - if filename[-1:] == '/': - filename = filename[:-1] - mode = 'd' - infostuff = '' - else: - # Parse, assuming a UNIX listing - words = string.split(line) - if len(words) < 6: - if verbose > 1: print 'Skipping short line' - continue - if words[-2] == '->': - if verbose > 1: - print 'Skipping symbolic link %s -> %s' % \ - (words[-3], words[-1]) - continue - filename = words[-1] - infostuff = words[-5:-1] - mode = words[0] - skip = 0 - for pat in skippats: - if fnmatch(filename, pat): - if verbose > 1: - print 'Skip pattern', pat, - print 'matches', filename - skip = 1 - break - if skip: - continue - if mode[0] == 'd': - if verbose > 1: - print 'Remembering subdirectory', filename - subdirs.append(filename) - continue - if info.has_key(filename) and info[filename] == infostuff: - if verbose > 1: - print 'Already have this version of', 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 - try: - fp = open(tempname, 'w') - except IOError, msg: - print "Can't create %s: %s" % (tempname, str(msg)) - continue - if verbose: - print 'Retrieving %s from %s as %s...' % \ - (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.rename(tempname, fullname) - except os.error, msg: - print "Can't rename %s to %s: %s" % (tempname, - fullname, - str(msg)) - continue - info[filename] = infostuff - writedict(info, infofilename) - if verbose: - 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 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 - fullname = os.path.join(localdir, name) - if not rmok: - if verbose: - print 'Local file', fullname, - print 'is no longer pertinent' - continue - if verbose: print 'Removing local file', fullname - try: - os.unlink(fullname) - except os.error, msg: - print "Can't remove local file %s: %s" % \ - (fullname, str(msg)) - # - # Recursively mirror subdirectories - for subdir in subdirs: - if interactive: - doit = askabout('subdirectory', subdir, pwd) - if not doit: continue - if verbose: print 'Processing subdirectory', subdir - localsubdir = os.path.join(localdir, subdir) - pwd = f.pwd() - if verbose > 1: - print 'Remote directory now:', pwd - print 'Remote cwd', subdir - try: - f.cwd(subdir) - except ftplib.error_perm, msg: - print "Can't chdir to", subdir, ":", msg - else: - if verbose: print 'Mirroring as', 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.' - -# 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 = string.lower(string.strip(raw_input(prompt))) - 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). -def writedict(dict, filename): - fp = open(filename, 'w') - fp.write('{\n') - for key, value in dict.items(): - fp.write('%s: %s,\n' % (`key`, `value`)) - fp.write('}\n') - fp.close() - -main() diff --git a/Tools/scripts/h2py.py b/Tools/scripts/h2py.py deleted file mode 100755 index 4cea2353cb..0000000000 --- a/Tools/scripts/h2py.py +++ /dev/null @@ -1,141 +0,0 @@ -#! /usr/local/bin/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, regex, regsub, string, getopt, os - -p_define = regex.compile('^#[\t ]*define[\t ]+\([a-zA-Z0-9_]+\)[\t ]+') - -p_macro = regex.compile( - '^#[\t ]*define[\t ]+\([a-zA-Z0-9_]+\)(\([_a-zA-Z][_a-zA-Z0-9]*\))[\t ]+') - -p_include = regex.compile('^#[\t ]*include[\t ]+<\([a-zA-Z0-9_/\.]+\)') - -p_comment = regex.compile('/\*\([^*]+\|\*+[^/]\)*\(\*+/\)?') - -ignores = [p_comment] - -p_char = regex.compile("'\(\\\\.[^\\\\]*\|[^\\\\]\)'") - -filedict = {} - -try: - searchdirs=string.splitfields(os.environ['include'],';') -except KeyError: - try: - searchdirs=string.splitfields(os.environ['INCLUDE'],';') - except KeyError: - searchdirs=['/usr/include'] - -def main(): - opts, args = getopt.getopt(sys.argv[1:], 'i:') - for o, a in opts: - if o == '-i': - ignores.append(regex.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 = string.rfind(outfile, '.') - if i > 0: outfile = outfile[:i] - outfile = string.upper(outfile) - outfile = outfile + '.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 - break - process(fp, outfp) - outfp.close() - fp.close() - -def process(fp, outfp, env = {}): - lineno = 0 - while 1: - line = fp.readline() - if not line: break - lineno = lineno + 1 - n = p_define.match(line) - if n >= 0: - # gobble up continuation lines - while line[-2:] == '\\\n': - nextline = fp.readline() - if not nextline: break - lineno = lineno + 1 - line = line + nextline - name = p_define.group(1) - body = line[n:] - # replace ignored patterns by spaces - for p in ignores: - body = regsub.gsub(p, ' ', body) - # replace char literals by ord(...) - body = regsub.gsub(p_char, 'ord(\\0)', body) - stmt = '%s = %s\n' % (name, string.strip(body)) - ok = 0 - try: - exec stmt in env - except: - sys.stderr.write('Skipping: %s' % stmt) - else: - outfp.write(stmt) - n =p_macro.match(line) - if n >= 0: - macro, arg = p_macro.group(1, 2) - body = line[n:] - for p in ignores: - body = regsub.gsub(p, ' ', body) - body = regsub.gsub(p_char, 'ord(\\0)', 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) - if p_include.match(line) >= 0: - regs = p_include.regs - a, b = regs[1] - filename = line[a:b] - if not filedict.has_key(filename): - filedict[filename] = None - inclfp = None - for dir in searchdirs: - try: - inclfp = open(dir + '/' + filename, 'r') - 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' % filename) - -main() diff --git a/Tools/scripts/ifdef.py b/Tools/scripts/ifdef.py deleted file mode 100755 index 9d74be2fec..0000000000 --- a/Tools/scripts/ifdef.py +++ /dev/null @@ -1,113 +0,0 @@ -#! /usr/local/bin/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 regex -import getopt -import string - -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 file in args: - if file == '-': - process(sys.stdin, sys.stdout) - else: - f = open(file, '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 = string.strip(line) - if tmp[:1] != '#': - if ok: fpo.write(line) - continue - tmp = string.strip(tmp[1:]) - words = string.split(tmp) - 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) - -main() diff --git a/Tools/scripts/linktree.py b/Tools/scripts/linktree.py deleted file mode 100755 index 3239434a0b..0000000000 --- a/Tools/scripts/linktree.py +++ /dev/null @@ -1,76 +0,0 @@ -#! /usr/local/bin/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) - -sys.exit(main()) diff --git a/Tools/scripts/lll.py b/Tools/scripts/lll.py deleted file mode 100755 index 0043645b4c..0000000000 --- a/Tools/scripts/lll.py +++ /dev/null @@ -1,25 +0,0 @@ -#! /usr/local/bin/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) - -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) diff --git a/Tools/scripts/mailerdaemon.py b/Tools/scripts/mailerdaemon.py deleted file mode 100755 index 245f670217..0000000000 --- a/Tools/scripts/mailerdaemon.py +++ /dev/null @@ -1,257 +0,0 @@ -"""mailerdaemon - classes to parse mailer-daemon messages""" - -import string -import rfc822 -import regex -import os -import sys - -Unparseable = 'mailerdaemon.Unparseable' - -class ErrorMessage(rfc822.Message): - def __init__(self, fp): - rfc822.Message.__init__(self, fp) - - def is_warning(self): - sub = self.getheader('Subject') - if not sub: - return 0 - sub = string.lower(sub) - if sub == 'waiting mail': return 1 - if string.find(sub, 'warning') >= 0: return 1 - return 0 - - def get_errors(self): - for p in EMPARSERS: - self.rewindbody() - try: - return p(self.fp) - except Unparseable: - pass - raise Unparseable - -sendmail_pattern = regex.compile('[0-9][0-9][0-9] ') -def emparse_sendmail(fp): - while 1: - line = fp.readline() - if not line: - raise Unparseable - line = line[:-1] - - # Check that we're not in the returned message yet - if string.lower(line)[:5] == 'from:': - raise Unparseable - line = string.split(line) - if len(line) > 3 and \ - ((line[0] == '-----' and line[1] == 'Transcript') or - (line[0] == '---' and line[1] == 'The' and - line[2] == 'transcript') or - (line[0] == 'While' and line[1] == 'talking' and line[2] == 'to')): - # Yes, found it! - break - - errors = [] - found_a_line = 0 - warnings = 0 - while 1: - line = fp.readline() - if not line: - break - line = line[:-1] - if not line: - continue - found_a_line = 1 - if sendmail_pattern.match(line) == 4: - # Yes, an error/warning line. Ignore 4, remember 5, stop on rest - if line[0] == '5': - errors.append(line) - elif line[0] == '4': - warnings = 1 - else: - raise Unparseable - line = string.split(line) - if line and line[0][:3] == '---': - break - # Empty transcripts are ok, others without an error are not. - if found_a_line and not (errors or warnings): - raise Unparseable - return errors - -def emparse_cts(fp): - while 1: - line = fp.readline() - if not line: - raise Unparseable - line = line[:-1] - - # Check that we're not in the returned message yet - if string.lower(line)[:5] == 'from:': - raise Unparseable - line = string.split(line) - if len(line) > 3 and line[0][:2] == '|-' and line[1] == 'Failed' \ - and line[2] == 'addresses': - # Yes, found it! - break - - errors = [] - while 1: - line = fp.readline() - if not line: - break - line = line[:-1] - if not line: - continue - if line[:2] == '|-': - break - errors.append(line) - return errors - -def emparse_aol(fp): - while 1: - line = fp.readline() - if not line: - raise Unparseable - line = line[:-1] - if line: - break - exp = 'The mail you sent could not be delivered to:' - if line[:len(exp)] != exp: - raise Unparseable - errors = [] - while 1: - line = fp.readline() - if sendmail_pattern.match(line) == 4: - # Yes, an error/warning line. Ignore 4, remember 5, stop on rest - if line[0] == '5': - errors.append(line) - elif line[0] != '4': - raise Unparseable - elif line == '\n': - break - else: - raise Unparseable - return errors - -def emparse_compuserve(fp): - while 1: - line = fp.readline() - if not line: - raise Unparseable - line = line[:-1] - if line: - break - exp = 'Your message could not be delivered for the following reason:' - if line[:len(exp)] != exp: - raise Unparseable - errors = [] - while 1: - line = fp.readline() - if not line: break - if line[:3] == '---': break - line = line[:-1] - if not line: continue - if line == 'Please resend your message at a later time.': - continue - line = 'Compuserve: ' + line - errors.append(line) - return errors - -prov_pattern = regex.compile('.* | \(.*\)') - -def emparse_providence(fp): - while 1: - line = fp.readline() - if not line: - raise Unparseable - line = line[:-1] - - # Check that we're not in the returned message yet - if string.lower(line)[:5] == 'from:': - raise Unparseable - exp = 'The following errors occurred' - if line[:len(exp)] == exp: - break - - errors = [] - while 1: - line = fp.readline() - if not line: - break - line = line[:-1] - if not line: - continue - if line[:4] == '----': - break - if prov_pattern.match(line) > 0: - errors.append(prov_pattern.group(1)) - - if not errors: - raise Unparseable - return errors - -EMPARSERS = [emparse_sendmail, emparse_aol, emparse_cts, emparse_compuserve, - emparse_providence] - -def parsedir(dir, modify): - os.chdir(dir) - files = os.listdir('.') - pat = regex.compile('^[0-9]*$') - errordict = {} - errorlast = {} - nok = nwarn = nbad = 0 - - for fn in files: - if pat.match(fn) > 0: - # Ok, so it's a numeric filename. Lets try to parse it. - fp = open(fn) - m = ErrorMessage(fp) - sender = m.getaddr('From') - print '%s\t%-40s\t'%(fn, sender[1]), - - if m.is_warning(): - print 'warning only' - nwarn = nwarn + 1 - if modify: - os.unlink(fn) - continue - - try: - errors = m.get_errors() - except Unparseable: - print '** Not parseable' - nbad = nbad + 1 - continue - print len(errors), 'errors' - - # Remember them - for e in errors: - if not errordict.has_key(e): - errordict[e] = 1 - else: - errordict[e] = errordict[e] + 1 - errorlast[e] = fn - - nok = nok + 1 - if modify: - os.unlink(fn) - - print '--------------' - print nok, 'files parsed,',nwarn,'files warning-only,', - print nbad,'files unparseable' - print '--------------' - for e in errordict.keys(): - print errordict[e], '\t', errorlast[e], '\t', 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/Tools/scripts/methfix.py b/Tools/scripts/methfix.py deleted file mode 100755 index 60f2a56cbc..0000000000 --- a/Tools/scripts/methfix.py +++ /dev/null @@ -1,173 +0,0 @@ -#! /usr/local/bin/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 regex -import os -from stat import * -import string - -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 = regex.compile('^[a-zA-Z0-9_]+\.py$') -def ispython(name): - return ispythonprog.match(name) >= 0 - -def recursedown(dirname): - dbg('recursedown(' + `dirname` + ')\n') - bad = 0 - try: - names = os.listdir(dirname) - except os.error, msg: - err(dirname + ': cannot list directory: ' + `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 ispython(name): - if fix(fullname): bad = 1 - for fullname in subdirs: - if recursedown(fullname): bad = 1 - return bad - -def fix(filename): -## dbg('fix(' + `filename` + ')\n') - try: - f = open(filename, 'r') - except IOError, msg: - err(filename + ': cannot open: ' + `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 - 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 = string.split(line[2:]) - if words and regex.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(tempname+': cannot create: '+\ - `msg`+'\n') - return 1 - f.seek(0) - lineno = 0 - rep(filename + ':\n') - continue # restart from the beginning - rep(`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(tempname + ': warning: chmod failed (' + `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 (' + `msg` + ')\n') - # Now move the temp file to the original file - try: - os.rename(tempname, filename) - except os.error, msg: - err(filename + ': rename failed (' + `msg` + ')\n') - return 1 - # Return succes - return 0 - - -fixpat = '^[ \t]+def +[a-zA-Z0-9_]+ *( *self *, *\(( *\(.*\) *)\) *) *:' -fixprog = regex.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 - - -main() diff --git a/Tools/scripts/mkreal.py b/Tools/scripts/mkreal.py deleted file mode 100755 index bc4dd1300a..0000000000 --- a/Tools/scripts/mkreal.py +++ /dev/null @@ -1,65 +0,0 @@ -#! /usr/local/bin/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 file in files: - if file not in (os.curdir, os.pardir): - os.symlink(join(linkto, file), join(name, file)) - -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) - -main() diff --git a/Tools/scripts/objgraph.py b/Tools/scripts/objgraph.py deleted file mode 100755 index c6bbe665a2..0000000000 --- a/Tools/scripts/objgraph.py +++ /dev/null @@ -1,215 +0,0 @@ -#!/usr/local/bin/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 string -import os -import getopt -import regex - -# Types of symbols. -# -definitions = 'TRGDSBAEC' -externals = 'UV' -ignore = 'Nntrgdsbavuc' - -# Regular expression to parse "nm -o" output. -# -matcher = regex.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(file): - while 1: - s = file.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 file in flist: - print file + ':' - elist = file2undef[file] - 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 file in files: - callers = [] - for label in file2def[file]: - if undef2file.has_key(label): - callers = callers + undef2file[label] - if callers: - callers.sort() - print file + ':' - lastfn = '' - for fn in callers: - if fn <> lastfn: - print '\t' + fn - lastfn = fn - else: - print file + ': unused' - -# Print undefine names and where they are used. -# -def printundef(): - undefs = {} - for file in file2undef.keys(): - for ext in file2undef[file]: - if not def2file.has_key(ext): - store(undefs, ext, file) - elist = undefs.keys() - elist.sort() - for ext in elist: - print ext + ':' - flist = undefs[ext] - flist.sort() - for file in flist: - print '\t' + file - -# 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 file in args: - if file == '-': - readinput(sys.stdin) - else: - readinput(open(file, '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. -# -try: - sys.exit(main()) -except KeyboardInterrupt: - sys.exit(1) diff --git a/Tools/scripts/pathfix.py b/Tools/scripts/pathfix.py deleted file mode 100755 index b80ce7ea72..0000000000 --- a/Tools/scripts/pathfix.py +++ /dev/null @@ -1,150 +0,0 @@ -#! /usr/local/bin/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 regex -import os -from stat import * -import string -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 = regex.compile('^[a-zA-Z0-9_]+\.py$') -def ispython(name): - return ispythonprog.match(name) >= 0 - -def recursedown(dirname): - dbg('recursedown(' + `dirname` + ')\n') - bad = 0 - try: - names = os.listdir(dirname) - except os.error, msg: - err(dirname + ': cannot list directory: ' + `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 ispython(name): - if fix(fullname): bad = 1 - for fullname in subdirs: - if recursedown(fullname): bad = 1 - return bad - -def fix(filename): -## dbg('fix(' + `filename` + ')\n') - try: - f = open(filename, 'r') - except IOError, msg: - err(filename + ': cannot open: ' + `msg` + '\n') - 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(tempname+': cannot create: '+`msg`+'\n') - 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(tempname + ': warning: chmod failed (' + `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 (' + `msg` + ')\n') - # Now move the temp file to the original file - try: - os.rename(tempname, filename) - except os.error, msg: - err(filename + ': rename failed (' + `msg` + ')\n') - return 1 - # Return succes - return 0 - -prog = regex.compile('\(#![ \t]*\)\(/[^ \t\n]*\)\(.*\n\)') - -def fixline(line): - if prog.match(line) < 0: - return line - head, tail = prog.group(1, 3) - return head + new_interpreter + tail - -main() diff --git a/Tools/scripts/pdeps.py b/Tools/scripts/pdeps.py deleted file mode 100755 index 8cf573fee3..0000000000 --- a/Tools/scripts/pdeps.py +++ /dev/null @@ -1,167 +0,0 @@ -#! /usr/local/bin/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 regex -import os -import string - - -# 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 = regex.compile('^[ \t]*from[ \t]+\([^ \t]+\)[ \t]+') -m_from = regex.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 = string.splitfields(line[a1:b1], ',') - # print '#', line, words - for word in words: - word = string.strip(word) - 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 string.ljust(mod, maxlen), ':', - if mod in list: - print '(*)', - for ref in list: - print ref, - print - - -# Call main and honor exit status -try: - sys.exit(main()) -except KeyboardInterrupt: - sys.exit(1) diff --git a/Tools/scripts/pindent.py b/Tools/scripts/pindent.py deleted file mode 100755 index 6432f4cc2d..0000000000 --- a/Tools/scripts/pindent.py +++ /dev/null @@ -1,440 +0,0 @@ -#! /usr/local/bin/python -#! /usr/local/bin/python - -# This file contains a class and a main program that perform two -# related (though complimentary) formatting operations on Python -# programs. When called as "pindend -c", it takes a valid Python -# program as input and outputs a version augmented with block-closing -# comments. 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). - -# Both 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). - -# 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) -# 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 - -import os -import regex -import string -import sys - -next = {} -next['if'] = next['elif'] = 'elif', 'else', 'end' -next['while'] = next['for'] = 'else', 'end' -next['try'] = 'except', 'finally' -next['except'] = 'except', 'else', 'end' -next['else'] = next['finally'] = next['def'] = next['class'] = 'end' -next['end'] = () -start = 'if', 'while', 'for', 'try', 'def', 'class' - -class PythonIndenter: - - def __init__(self, fpi = sys.stdin, fpo = sys.stdout, - indentsize = STEPSIZE, tabsize = TABSIZE): - self.fpi = fpi - self.fpo = fpo - self.indentsize = indentsize - self.tabsize = tabsize - self.lineno = 0 - self.write = fpo.write - self.kwprog = regex.symcomp( - '^[ \t]*\(<kw>[a-z]+\)' - '\([ \t]+\(<id>[a-zA-Z_][a-zA-Z0-9_]*\)\)?' - '[^a-zA-Z0-9_]') - self.endprog = regex.symcomp( - '^[ \t]*#?[ \t]*end[ \t]+\(<kw>[a-z]+\)' - '\([ \t]+\(<id>[a-zA-Z_][a-zA-Z0-9_]*\)\)?' - '[^a-zA-Z0-9_]') - self.wsprog = regex.compile('^[ \t]*') - # end def __init__ - - 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 = max(0, self.wsprog.match(line)) - 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 - if self.endprog.match(line) >= 0: - kw = 'end' - kw2 = self.endprog.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 - if self.kwprog.match(line) >= 0: - kw = self.kwprog.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 complete(self): - self.indentsize = 1 - stack = [] - todo = [] - current, firstkw, lastkw, topid = 0, '', '', '' - while 1: - line = self.getline() - i = max(0, self.wsprog.match(line)) - if self.endprog.match(line) >= 0: - thiskw = 'end' - endkw = self.endprog.group('kw') - thisid = self.endprog.group('id') - elif self.kwprog.match(line) >= 0: - thiskw = self.kwprog.group('kw') - if not next.has_key(thiskw): - thiskw = '' - # end if - if thiskw in ('def', 'class'): - thisid = self.kwprog.group('id') - else: - thisid = '' - # end if - elif line[i:i+1] in ('\n', '#'): - todo.append(line) - continue - else: - thiskw = '' - # end if - indent = len(string.expandtabs(line[:i], 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): - pi = PythonIndenter(input, output, stepsize, tabsize) - pi.complete() -# end def complete_filter - -def reformat_filter(input = sys.stdin, output = sys.stdout, - stepsize = STEPSIZE, tabsize = TABSIZE): - pi = PythonIndenter(input, output, stepsize, tabsize) - pi.reformat() -# end def reformat - -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 = string.find(self.buf, '\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): - input = StringReader(source) - output = StringWriter() - pi = PythonIndenter(input, output, stepsize, tabsize) - pi.complete() - return output.getvalue() -# end def complete_string - -def reformat_string(source, stepsize = STEPSIZE, tabsize = TABSIZE): - input = StringReader(source) - output = StringWriter() - pi = PythonIndenter(input, output, stepsize, tabsize) - pi.reformat() - return output.getvalue() -# end def reformat_string - -def complete_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE): - source = open(filename, 'r').read() - result = complete_string(source, stepsize, tabsize) - 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 reformat_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE): - source = open(filename, 'r').read() - result = reformat_string(source, stepsize, tabsize) - if source == result: return 0 - # end if - import os - os.rename(filename, filename + '~') - 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|-r) [-s stepsize] [-t tabsize] [file] ... --c : complete a correctly indented program (add #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) -[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 test(): - import getopt - try: - opts, args = getopt.getopt(sys.argv[1:], 'crs:t:') - 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 - for o, a in opts: - if o == '-c': - action = 'complete' - elif o == '-r': - action = 'reformat' - elif o == '-s': - stepsize = string.atoi(a) - elif o == '-t': - tabsize = string.atoi(a) - # end if - # end for - if not action: - sys.stderr.write( - 'You must specify -c(omplete) 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) - else: - action = eval(action + '_file') - for file in args: - action(file, stepsize, tabsize) - # end for - # end if -# end def test - -if __name__ == '__main__': - test() -# end if diff --git a/Tools/scripts/ptags.py b/Tools/scripts/ptags.py deleted file mode 100755 index b8fc232d78..0000000000 --- a/Tools/scripts/ptags.py +++ /dev/null @@ -1,50 +0,0 @@ -#! /usr/local/bin/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 -import regex -import os - -tags = [] # Modified global variable! - -def main(): - args = sys.argv[1:] - for file in args: treat_file(file) - 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 = regex.compile(expr) - -def treat_file(file): - try: - fp = open(file, 'r') - except: - print 'Cannot open', file - return - base = os.path.basename(file) - if base[-3:] == '.py': base = base[:-3] - s = base + '\t' + file + '\t' + '1\n' - tags.append(s) - while 1: - line = fp.readline() - if not line: break - if matcher.search(line) >= 0: - (a, b), (a1, b1), (a2, b2) = matcher.regs[:3] - name = line[a2:b2] - s = name + '\t' + file + '\t/^' + line[a:b] + '/\n' - tags.append(s) - -main() diff --git a/Tools/scripts/pystone.py b/Tools/scripts/pystone.py deleted file mode 100755 index 954e6c9ebf..0000000000 --- a/Tools/scripts/pystone.py +++ /dev/null @@ -1,229 +0,0 @@ -#! /usr/local/bin/python - -""" -"PYSTONE" Benchmark Program - -Version: Python/1.0 (corresponds to C/1.1) - -Author: Reinhold P. Weicker, CACM Vol 27, No 10, 10/84 pg. 1013. - - Translated from ADA to C by Rick Richardson. - Every method to preserve ADA-likeness has been used, - at the expense of C-ness. - - Translated from C to Python by Guido van Rossum. -""" - -LOOPS = 1000 - -from time import clock - -__version__ = "1.0" - -[Ident1, Ident2, Ident3, Ident4, Ident5] = range(1, 6) - -class Record: - - def __init__(self, PtrComp = None, Discr = 0, EnumComp = 0, - IntComp = 0, StringComp = 0): - self.PtrComp = PtrComp - self.Discr = Discr - self.EnumComp = EnumComp - self.IntComp = IntComp - self.StringComp = StringComp - - def copy(self): - return Record(self.PtrComp, self.Discr, self.EnumComp, - self.IntComp, self.StringComp) - -TRUE = 1 -FALSE = 0 - -def main(): - Proc0() - -IntGlob = 0 -BoolGlob = FALSE -Char1Glob = '\0' -Char2Glob = '\0' -Array1Glob = [0]*51 -Array2Glob = map(lambda x: x[:], [Array1Glob]*51) -PtrGlb = None -PtrGlbNext = None - -def Proc0(): - global IntGlob - global BoolGlob - global Char1Glob - global Char2Glob - global Array1Glob - global Array2Glob - global PtrGlb - global PtrGlbNext - - starttime = clock() - for i in range(LOOPS): - pass - nulltime = clock() - starttime - - PtrGlbNext = Record() - PtrGlb = Record() - PtrGlb.PtrComp = PtrGlbNext - PtrGlb.Discr = Ident1 - PtrGlb.EnumComp = Ident3 - PtrGlb.IntComp = 40 - PtrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING" - String1Loc = "DHRYSTONE PROGRAM, 1'ST STRING" - Array2Glob[8][7] = 10 - - starttime = clock() - - for i in range(LOOPS): - Proc5() - Proc4() - IntLoc1 = 2 - IntLoc2 = 3 - String2Loc = "DHRYSTONE PROGRAM, 2'ND STRING" - EnumLoc = Ident2 - BoolGlob = not Func2(String1Loc, String2Loc) - while IntLoc1 < IntLoc2: - IntLoc3 = 5 * IntLoc1 - IntLoc2 - IntLoc3 = Proc7(IntLoc1, IntLoc2) - IntLoc1 = IntLoc1 + 1 - Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3) - PtrGlb = Proc1(PtrGlb) - CharIndex = 'A' - while CharIndex <= Char2Glob: - if EnumLoc == Func1(CharIndex, 'C'): - EnumLoc = Proc6(Ident1) - CharIndex = chr(ord(CharIndex)+1) - IntLoc3 = IntLoc2 * IntLoc1 - IntLoc2 = IntLoc3 / IntLoc1 - IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1 - IntLoc1 = Proc2(IntLoc1) - - benchtime = clock() - starttime - nulltime - print "Pystone(%s) time for %d passes = %g" % \ - (__version__, LOOPS, benchtime) - print "This machine benchmarks at %g pystones/second" % \ - (LOOPS/benchtime) - -def Proc1(PtrParIn): - PtrParIn.PtrComp = NextRecord = PtrGlb.copy() - PtrParIn.IntComp = 5 - NextRecord.IntComp = PtrParIn.IntComp - NextRecord.PtrComp = PtrParIn.PtrComp - NextRecord.PtrComp = Proc3(NextRecord.PtrComp) - if NextRecord.Discr == Ident1: - NextRecord.IntComp = 6 - NextRecord.EnumComp = Proc6(PtrParIn.EnumComp) - NextRecord.PtrComp = PtrGlb.PtrComp - NextRecord.IntComp = Proc7(NextRecord.IntComp, 10) - else: - PtrParIn = NextRecord.copy() - return PtrParIn - -def Proc2(IntParIO): - IntLoc = IntParIO + 10 - while 1: - if Char1Glob == 'A': - IntLoc = IntLoc - 1 - IntParIO = IntLoc - IntGlob - EnumLoc = Ident1 - if EnumLoc == Ident1: - break - return IntParIO - -def Proc3(PtrParOut): - global IntGlob - - if PtrGlb != None: - PtrParOut = PtrGlb.PtrComp - else: - IntGlob = 100 - PtrGlb.IntComp = Proc7(10, IntGlob) - return PtrParOut - -def Proc4(): - global Char2Glob - - BoolLoc = Char1Glob == 'A' - BoolLoc = BoolLoc or BoolGlob - Char2Glob = 'B' - -def Proc5(): - global Char1Glob - global BoolGlob - - Char1Glob = 'A' - BoolGlob = FALSE - -def Proc6(EnumParIn): - EnumParOut = EnumParIn - if not Func3(EnumParIn): - EnumParOut = Ident4 - if EnumParIn == Ident1: - EnumParOut = Ident1 - elif EnumParIn == Ident2: - if IntGlob > 100: - EnumParOut = Ident1 - else: - EnumParOut = Ident4 - elif EnumParIn == Ident3: - EnumParOut = Ident2 - elif EnumParIn == Ident4: - pass - elif EnumParIn == Ident5: - EnumParOut = Ident3 - return EnumParOut - -def Proc7(IntParI1, IntParI2): - IntLoc = IntParI1 + 2 - IntParOut = IntParI2 + IntLoc - return IntParOut - -def Proc8(Array1Par, Array2Par, IntParI1, IntParI2): - global IntGlob - - IntLoc = IntParI1 + 5 - Array1Par[IntLoc] = IntParI2 - Array1Par[IntLoc+1] = Array1Par[IntLoc] - Array1Par[IntLoc+30] = IntLoc - for IntIndex in range(IntLoc, IntLoc+2): - Array2Par[IntLoc][IntIndex] = IntLoc - Array2Par[IntLoc][IntLoc-1] = Array2Par[IntLoc][IntLoc-1] + 1 - Array2Par[IntLoc+20][IntLoc] = Array1Par[IntLoc] - IntGlob = 5 - -def Func1(CharPar1, CharPar2): - CharLoc1 = CharPar1 - CharLoc2 = CharLoc1 - if CharLoc2 != CharPar2: - return Ident1 - else: - return Ident2 - -def Func2(StrParI1, StrParI2): - IntLoc = 1 - while IntLoc <= 1: - if Func1(StrParI1[IntLoc], StrParI2[IntLoc+1]) == Ident1: - CharLoc = 'A' - IntLoc = IntLoc + 1 - if CharLoc >= 'W' and CharLoc <= 'Z': - IntLoc = 7 - if CharLoc == 'X': - return TRUE - else: - if StrParI1 > StrParI2: - IntLoc = IntLoc + 7 - return TRUE - else: - return FALSE - -def Func3(EnumParIn): - EnumLoc = EnumParIn - if EnumLoc == Ident3: return TRUE - return FALSE - -if __name__ == '__main__': - main() diff --git a/Tools/scripts/suff.py b/Tools/scripts/suff.py deleted file mode 100755 index 491fd3b482..0000000000 --- a/Tools/scripts/suff.py +++ /dev/null @@ -1,29 +0,0 @@ -#! /usr/local/bin/python - -# suff -# -# show different suffixes amongst arguments - -import sys - -def main(): - files = sys.argv[1:] - suffixes = {} - for file in files: - suff = getsuffix(file) - if not suffixes.has_key(suff): - suffixes[suff] = [] - suffixes[suff].append(file) - keys = suffixes.keys() - keys.sort() - for suff in keys: - print `suff`, len(suffixes[suff]) - -def getsuffix(file): - suff = '' - for i in range(len(file)): - if file[i] == '.': - suff = file[i:] - return suff - -main() diff --git a/Tools/scripts/sum5.py b/Tools/scripts/sum5.py deleted file mode 100755 index fdb83faa13..0000000000 --- a/Tools/scripts/sum5.py +++ /dev/null @@ -1,97 +0,0 @@ -#! /usr/local/bin/python - -# print md5 checksum for files - -bufsize = 8096 -fnfilter = None -rmode = 'r' - -usage = """ -usage: sum5 [-b] [-t] [-l] [-s bufsize] [file ...] --b : read files in binary mode --t : read files in text mode (default) --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 string -import os -import md5 -import regsub - -StringType = type('') -FileType = type(sys.stdin) - -def sum(*files): - sts = 0 - if files and type(files[-1]) == FileType: - out, files = files[-1], files[:-1] - else: - out = sys.stdout - if len(files) == 1 and type(files[0]) != StringType: - files = files[0] - for f in files: - if type(f) == StringType: - 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(file, out = sys.stdout): - try: - fp = open(file, rmode) - except IOError, msg: - sys.stderr.write('%s: Can\'t open: %s\n' % (file, msg)) - return 1 - if fnfilter: - file = fnfilter(file) - sts = printsumfp(fp, file, out) - fp.close() - return sts - -def printsumfp(fp, file, out = sys.stdout): - m = md5.md5() - 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' % (file, msg)) - return 1 - out.write('%s %s\n' % (hexify(m.digest()), file)) - return 0 - -def hexify(s): - res = '' - for c in s: - res = res + '%02x' % ord(c) - return res - -def main(args = sys.argv[1:], out = sys.stdout): - global fnfilter, rmode, bufsize - import getopt - 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 - if o == '-b': - rmode = 'rb' - if o == '-t': - rmode = 'r' - if o == '-s': - bufsize = string.atoi(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/Tools/scripts/texi2html.py b/Tools/scripts/texi2html.py deleted file mode 100755 index a1c0ebd44a..0000000000 --- a/Tools/scripts/texi2html.py +++ /dev/null @@ -1,1500 +0,0 @@ -#! /usr/local/bin/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 fexible error handling -# How about icons ? - -import os -import regex -import regsub -import string - -MAGIC = '\\input texinfo' - -cmprog = regex.compile('^@\([a-z]+\)\([ \t]\|$\)') # Command (line-oriented) -blprog = regex.compile('^[ \t]*$') # Blank line -kwprog = regex.compile('@[a-z]+') # Keyword (embedded, usually with {} args) -spprog = regex.compile('[\n@{}&<>]') # Special characters in running text -miprog = regex.compile( \ - '^\* \([^:]*\):\(:\|[ \t]*\([^\t,\n.]+\)\([^ \t\n]*\)\)[ \t\n]*') - # menu item (Yuck!) - - -class Node: - __doc__ = """ - 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. """ - - 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 = [] - self.type = 0 - self.cont = '' - - def write (self, *lines): - for line in lines: - self.lines.append (line) - - 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): - if nodename: - if string.lower(nodename) == '(dir)': - addr = '../dir.html' - else: - addr = makefile(nodename) - self.write(label, ': <A HREF="', addr, '" TYPE="', \ - label, '">', nodename, '</A> \n') - - - def finalize(self): - length = len (self.lines) - self.text = string.joinfields (self.lines, '') - self.lines = [] - self.write ('<BR> <HR>\n') - if self.cont != self.next: - self.link('Cont', self.cont) - self.link('Next', self.next) - self.link('Prev', self.prev) - self.link('Up', self.up) - if self.name <> self.topname: - self.link('Top', self.topname) - self.write ('<BR> <HR> <P>\n') - links = string.joinfields (self.lines, '') - self.lines = [] - - self.prologue = \ - '<!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN">\n' + \ - '<!- Converted with texi2html and Python>\n' + \ - '<P>\n<HEAD>\n' + \ - '<TITLE>' + self.title + '</TITLE>\n' + \ - '</HEAD>\n<BODY>\n<P>\n' + \ - links - - if length > 20: - self.epilogue = links + '</BODY>\n' - else: - self.epilogue = '</BODY>\n' - - -class TexinfoParser: - - # 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.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.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 (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) >= 0): - line = fp.readline() - lineno = lineno + 1 - if line[:len(MAGIC)] <> MAGIC: - raise SyntaxError, 'file does not begin with '+`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 - if cmprog.match(line) >= 0: - a, b = cmprog.regs[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) - elif blprog.match(line) >= 0 and \ - 'format' not in self.stack and \ - 'example' not in self.stack: - if accu: - if not self.skip: - self.process(accu) - 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 = string.joinfields(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.skip, self.stack, - if accu: print accu[0][:30], - if accu[0][30:] or accu[1:]: print '...', - print - if self.stack and self.stack[-1] == 'menu': - # XXX should be done differently - for line in accu: - if miprog.match(line) < 0: - line = string.strip(line) + '\n' - self.expand(line) - continue - (bgn, end), (a, b), (c, d), (e, f), (g, h) = \ - miprog.regs[:5] - label = line[a:b] - nodename = line[c:d] - if nodename[0] == ':': nodename = label - else: nodename = line[e:f] - punct = line[g:h] - self.write('<DT><A HREF="', \ - makefile(nodename), \ - '" TYPE=Menu>', nodename, \ - '</A>', punct, '\n<DD>') - self.expand(line[end:]) - else: - text = string.joinfields(accu, '') - self.expand(text) - - # Write a string, expanding embedded @-commands - def expand(self, text): - stack = [] - i = 0 - n = len(text) - while i < n: - start = i - i = spprog.search(text, i) - if i < 0: - self.write(text[start:]) - break - self.write(text[start:i]) - c = text[i] - i = i+1 - if c == '\n': - if self.nofill > 0: - self.write('<P>\n') - else: - 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 '+`c` - start = i - while i < n and text[i] in string.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', `file` - return - if self.debugging: - print '--> file', `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 - if self.debugging: - print '<-- file', `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('(C)') - def open_copyright(self): self.write('(C)') - def close_copyright(self): pass - - def open_minus(self): self.write('-') - def close_minus(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 = string.splitfields(text, ',') - n = len(args) - for i in range(n): - args[i] = string.strip(args[i]) - while len(args) < 3: args.append('') - node = args[0] - file = args[2] - self.write('`', file, '\', node `', node, '\'') - - def makeref(self): - text = self.collectsavings() - args = string.splitfields(text, ',') - n = len(args) - for i in range(n): - args[i] = string.strip(args[i]) - 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>') - - # --- 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>') - - open_t = open_code - close_t = close_code - - def open_dfn(self): self.write('<DFN>') - def close_dfn(self): self.write('</DFN>') - - def open_emph(self): self.write('<I>') - def close_emph(self): self.write('</I>') - - open_i = open_emph - close_i = close_emph - - def open_footnote(self): - # if self.savetext <> None: - # print '*** Recursive footnote -- expect weirdness' - id = len(self.footnotes) + 1 - self.write('<A NAME="footnoteref', `id`, \ - '" HREF="#footnotetext', `id`, '">(', `id`, ')</A>') - # self.savetext = '' - self.startsaving () - - def close_footnote(self): - id = len(self.footnotes) + 1 - # self.footnotes.append(`id`, self.savetext) - self.footnotes.append(`id`, self.collectsavings()) - # self.savetext = None - - def writefootnotes(self): - self.write('<H2>---------- Footnotes ----------</H2>\n') - for id, text in self.footnotes: - self.write('<A NAME="footnotetext', id, \ - '" HREF="#footnoteref', id, '">(', \ - id, ')</A>\n', text, '<P>\n') - self.footnotes = [] - - def open_file(self): self.write('<FILE>') - def close_file(self): self.write('</FILE>') - - 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('<B>') - def close_strong(self): self.write('</B>') - - open_b = open_strong - close_b = close_strong - - 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>') - - open_titlefont = open_ - close_titlefont = close_ - - def open_small(self): pass - def close_small(self): pass - - def command(self, line): - a, b = cmprog.regs[1] - cmd = line[a:b] - args = string.strip(line[b:]) - if self.debugging > 1: - print 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 = string.split(args) - 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 = string.splitfields (args, ' ') - key = fields[0] - if len(fields) == 1: - value = 1 - else: - value = string.joinfields (fields[1:], ' ') - self.values[key]=value - print self.values - - 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): - print self.stack - print self.stackinfo - if self.stackinfo[len(self.stack) + 1]: - self.skip = self.skip - 1 - del self.stackinfo[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 - - end_ifclear = end_ifset - - 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): - print args - self.startsaving() - self.expand (args) - self.title = self.collectsavings () - print self.title - 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 = string.splitfields(args, ',') - while len(parts) < 4: parts.append('') - for i in range(4): parts[i] = string.strip(parts[i]) - 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 '--- 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 - # No idea what this means, but this is what latex2html writes - # self.write('<!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN">\n') - # self.write('<!- Converted with texi2html and Python>\n') - # self.write ('<P>\n<HEAD>\n') - # self.write('<TITLE>', title, '</TITLE>\n') - # self.write ('</HEAD>\n<BODY>\n<P>\n<BR> <HR>\n') - # self.link('Next', next) - # self.link('Prev', prev) - # self.link('Up', up) - # if self.nodename <> self.topname: - # self.link('Top', self.topname) - # self.write ('<BR> <HR> <P>\n') - self.node = Node (self.dirname, self.nodename, self.topname, \ - title, next, prev, up) - - def link(self, label, nodename): - if nodename: - if string.lower(nodename) == '(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 + `i` + '.' - args = x + ' ' + args - self.contents.append(level, args, self.nodename) - self.write('<', type, '>') - self.expand(args) - self.write('</', type, '>\n') - if self.debugging: - 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>\n') - for level, title, node in self.contents: - if level <= maxlevel: - self.write('<LI>', '. '*level, '<A HREF="', \ - makefile(node), '">') - self.expand(title) - self.write('</A> ', node, '\n') - self.write('</UL>\n') - - # --- 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): - # Insert <args> blank lines - if args: - try: - n = string.atoi(args) - except string.atoi_error: - n = 1 - else: - n = 1 - self.write('<P>\n'*max(n, 0)) - - 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{' + name + '}') - for word in rest: self.expand(' ' + makevar(word)) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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{' + name + '}') - # If there are too many arguments, show them - for word in rest: self.expand(' ' + word) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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{' + datatype + '} @b{' + name + '}') - for word in rest: self.expand(' ' + makevar(word)) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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{' + datatype + '} @b{' + name + '}') - # If there are too many arguments, show them - for word in rest: self.expand(' ' + word) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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{' + name + '}') - # If there are too many arguments, show them - for word in rest: self.expand(' ' + word) - self.expand(' -- ' + category + ' of ' + classname) - self.write('<DD>\n') - self.index('vr', name + ' @r{of ' + 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{' + name + '}') - for word in rest: self.expand(' ' + makevar(word)) - self.expand(' -- ' + category + ' on ' + classname) - self.write('<DD>\n') - self.index('fn', name + ' @r{on ' + 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{' + name + '}') - for word in rest: self.expand(' ' + word) - self.expand(' -- ' + category) - self.write('<DD>\n') - 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 do_item(self, args): - if self.itemindex: self.index(self.itemindex, args) - if self.itemarg: - if self.itemarg[0] == '@' and self.itemarg[1:2] and \ - self.itemarg[1] in string.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('<DD>') - else: - self.write('<LI>') - self.expand(args) - self.write(' ') - do_itemx = do_item # XXX Should suppress leading blank line - - # --- Enumerations, displays, quotations --- - # XXX Most of these should increase the indentation somehow - - def bgn_quotation(self, args): self.write('<P>') - def end_quotation(self): self.write('<P>\n') - - def bgn_example(self, args): - self.nofill = self.nofill + 1 - self.write('<PRE><CODE>') - def end_example(self): - self.write('</CODE></PRE>') - 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 - - def bgn_display(self, args): - self.nofill = self.nofill + 1 - self.write('<PRE>\n') - def end_display(self): - self.write('</PRE>\n') - self.nofill = self.nofill - 1 - - def bgn_format(self, args): - self.nofill = self.nofill + 1 - self.write('<PRE><CODE>\n') - def end_format(self): - self.write('</CODE></PRE>\n') - self.nofill = self.nofill - 1 - - 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('<H2>Menu</H2><DL COMPACT>\n') - def end_menu(self): self.write('</DL>\n') - - 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', `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) - - def do_synindex(self, args): - words = string.split(args) - 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 = string.split(args) - for name in words: - if self.whichindex.has_key(name): - self.prindex(name) - else: - print '*** No index named', `name` - - def prindex(self, name): - iscodeindex = (name not in self.noncodeindices) - index = self.whichindex[name] - if not index: return - if self.debugging: - print '--- Generating', self.indextitle[name], 'index' - # The node already provides a title - index1 = [] - junkprog = regex.compile('^\(@[a-z]+\)?{') - for key, node in index: - sortkey = string.lower(key) - # Remove leading `@cmd{' from sort key - # -- don't bother about the matching `}' - oldsortkey = sortkey - while 1: - i = junkprog.match(sortkey) - if i < 0: break - sortkey = sortkey[i:] - index1.append(sortkey, key, node) - del index[:] - index1.sort() - self.write('<DL COMPACT>\n') - for sortkey, key, node in index1: - if self.debugging > 1: print key, ':', node - self.write('<DT>') - if iscodeindex: key = '@code{' + key + '}' - self.expand(key) - self.write('<DD><A HREF="', makefile(node), \ - '">', node, '</A>\n') - 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 string.ljust(cmd, 20), self.unknown[cmd] - - -# 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 = regex.compile('[@{} ]') -def findwordend(str, i, n): - level = 0 - while i < n: - i = fwprog.search(str, i) - if i < 0: break - 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): - return fixfunnychars(nodename) + '.html' - - -# Characters that are perfectly safe in filenames and hyperlinks -goodchars = string.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 = string.index(sequence, 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 - parser = TexinfoParser() - while sys.argv[1:2] == ['-d']: - parser.debugging = parser.debugging + 1 - del sys.argv[1:2] - if sys.argv[1] == '-c': - parser.cont = 1 - del sys.argv[1] - if len(sys.argv) <> 3: - print 'usage: texi2html [-d] [-d] [-c] inputfile outputdirectory' - sys.exit(2) - file = sys.argv[1] - parser.setdirname(sys.argv[2]) - if file == '-': - fp = sys.stdin - else: - parser.setincludedir(os.path.dirname(file)) - try: - fp = open(file, 'r') - except IOError, msg: - print file, ':', msg - sys.exit(1) - parser.parse(fp) - fp.close() - parser.report() - - -test() - -# Emacs local variables -# -# Local Variables: -# py-indent-offset: 8 -# End: diff --git a/Tools/scripts/which.py b/Tools/scripts/which.py deleted file mode 100755 index 07c0d2e7d0..0000000000 --- a/Tools/scripts/which.py +++ /dev/null @@ -1,53 +0,0 @@ -#! /usr/local/bin/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, os, string -from stat import * - -def msg(str): - sys.stderr.write(str + '\n') - -pathlist = string.splitfields(os.environ['PATH'], ':') - -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: - file = os.path.join(dir, prog) - try: - st = os.stat(file) - except os.error: - continue - if not S_ISREG(st[ST_MODE]): - msg(file + ': not a disk file') - else: - mode = S_IMODE(st[ST_MODE]) - if mode & 0111: - if not ident: - print file - ident = st[:3] - else: - if st[:3] == ident: - s = 'same as: ' - else: - s = 'also: ' - msg(s + file) - else: - msg(file + ': not executable') - if longlist: - sts = os.system('ls ' + longlist + ' ' + file) - if sts: msg('"ls -l" exit status: ' + `sts`) - if not ident: - msg(prog + ': not found') - sts = 1 - -sys.exit(sts) diff --git a/Tools/scripts/xxci.py b/Tools/scripts/xxci.py deleted file mode 100755 index 9ab5669eb5..0000000000 --- a/Tools/scripts/xxci.py +++ /dev/null @@ -1,117 +0,0 @@ -#! /usr/local/bin/python - -# xxci -# -# check in files for which rcsdiff returns nonzero exit status - -import sys -import os -from stat import * -import commands -import fnmatch -import string - -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 + string.split(f.read()) - -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'] - -try: - setup() - go(getargs()) -except KeyboardInterrupt: - print '[Intr]' diff --git a/Tools/world/world b/Tools/world/world deleted file mode 100755 index 7491708773..0000000000 --- a/Tools/world/world +++ /dev/null @@ -1,143 +0,0 @@ -#! /depot/sundry/plat/bin/python -# -# Note: you may have to edit the top line in this file. -# -# Usage: world addr1 [addr2 ...] -# -# $Id$ - -# This little script will take an Internet address of the form -# foobar@some.place.domain and will print out where in the world that -# message originated from. Its pretty dumb in that it just matches -# the `domain' part against a hard-coded list, which can probably -# change fairly quickly given the world's political fluidity. - -import sys -prog = sys.argv[0] -del sys.argv[0] -if not sys.argv: - print "No addresses provided.\nUsage:", prog, "addr1 [addr2 ...]\n" - - -# The mappings -nameorg = { - "arpa": "Arpanet", - "com": "commercial", - "edu": "educational", - "gov": "government", - "mil": "military", - "net": "networking", - "org": "non-commercial", - "int": "international" - } - - -country = { - "ag": "Antigua and Barbuda", - "al": "Albania", - "aq": "Antarctica", - "ar": "Argentina", - "at": "Austria", - "au": "Australia", - "bb": "Barbados", - "be": "Belgium", - "bg": "Bulgaria", - "bo": "Bolivia", - "br": "Brazil", - "bs": "Bahamas", - "bz": "Belize", - "ca": "Canada", - "ch": "Switzerland", - "cl": "Chile", - "cm": "Cameroon", - "cn": "China", - "co": "Colombia", - "cr": "Costa Rica", - "cy": "Cyprus", - "cz": "Czech Republic", - "de": "Germany", - "dk": "Denmark", - "dm": "Dominica", - "do": "Dominican Republic", - "ec": "Ecuador", - "ee": "Estonia", - "eg": "Egypt", - "es": "Spain", - "fi": "Finland", - "fj": "Fiji", - "fr": "France", - "gb": "Great Britain", - "gh": "Ghana", - "gr": "Greece", - "hk": "Hong Kong", - "hr": "Croatia", - "hu": "Hungary", - "id": "Indonesia", - "ie": "Ireland", - "il": "Israel", - "in": "India", - "is": "Iceland", - "it": "Italy", - "jm": "Jamaica", - "jp": "Japan", - "km": "Comoros", - "kn": "Saint Kitts and Nevis", - "kr": "Republic of Korea", - "kw": "Kuwait", - "lc": "Saint Lucia", - "li": "Liechtenstein", - "lk": "Sri Lanka", - "lu": "Luxembourg", - "lv": "Latvia", - "my": "Malaysia", - "mx": "Mexico", - "na": "Namibia", - "ni": "Nicaragua", - "nl": "Netherlands", - "no": "Norway", - "nz": "New Zealand", - "pe": "Peru", - "pg": "Papua New Guinea", - "ph": "Philippines", - "pl": "Poland", - "pr": "Puerto Rico", - "pt": "Portugal", - "py": "Paraguay", - "ro": "Romania", - "se": "Sweden", - "sg": "Singapore", - "si": "Slovenia", - "sk": "Slovakia", - "sr": "Suriname", - "su": "USSR", - "tw": "Taiwan", - "th": "Thailand", - "tn": "Tunisia", - "tr": "Turkey", - "tt": "Trinidad and Tobago", - "uk": "United Kingdom", - "us": "United States", - "uy": "Uruguay", - "vc": "Saint Vincent and the Grenadines", - "ve": "Venezuela", - "vi": "Virgin Islands", - "yu": "Yugoslavia", - "za": "South Africa", - "zw": "Zimbabwe" - } - -import string - -while sys.argv: - rawaddr = sys.argv[0] - del sys.argv[0] - - components = string.splitfields(rawaddr, ".") - addr = components[-1] - - if nameorg.has_key(addr): - print addr, "is from a USA", nameorg[addr], "organization" - elif country.has_key(addr): - print addr, "originated from", country[addr] - else: - print "I have no idea where", addr, "came from!" diff --git a/acconfig.h b/acconfig.h deleted file mode 100644 index 60d5bfb674..0000000000 --- a/acconfig.h +++ /dev/null @@ -1,79 +0,0 @@ -/* Leave this blank line here -- autoheader needs it! */ - - -/* Define if your <unistd.h> contains bad prototypes for exec*() - (as it does on SGI IRIX 4.x) */ -#undef BAD_EXEC_PROTOTYPES - -/* Define if your compiler botches static forward declarations - (as it does on SCI ODT 3.0) */ -#undef BAD_STATIC_FORWARD - -/* Define to `long' if <time.h> doesn't define. */ -#undef clock_t - -/* Define if getpgrp() must be called as getpgrp(0). */ -#undef GETPGRP_HAVE_ARG - -/* Define if gettimeofday() does not have second (timezone) argument - This is the case on Motorola V4 (R40V4.2) */ -#undef GETTIMEOFDAY_NO_TZ - -/* Define this if your time.h defines altzone */ -#undef HAVE_ALTZONE - -/* Define if your compiler supports function prototypes */ -#undef HAVE_PROTOTYPES - -/* Define if your compiler supports variable length function prototypes - (e.g. void fprintf(FILE *, char *, ...);) *and* <stdarg.h> */ -#undef HAVE_STDARG_PROTOTYPES - -/* Define if you have POSIX threads */ -#undef _POSIX_THREADS - -/* Define if setpgrp() must be called as setpgrp(0, 0). */ -#undef SETPGRP_HAVE_ARG - -/* Define to empty if the keyword does not work. */ -#undef signed - -/* Define for SOLARIS 2.x */ -#undef SOLARIS - -/* Define if you can safely include both <sys/select.h> and <sys/time.h> - (which you can't on SCO ODT 3.0). */ -#undef SYS_SELECT_WITH_SYS_TIME - -/* Define if a va_list is an array of some kind */ -#undef VA_LIST_IS_ARRAY - -/* Define to empty if the keyword does not work. */ -#undef volatile - -/* Define if you want to use SGI (IRIX 4) dynamic linking. - This requires the "dl" library by Jack Jansen, - ftp://ftp.cwi.nl/pub/dynload/dl-1.6.tar.Z. - Don't bother on IRIX 5, it already has dynamic linking using SunOS - style shared libraries */ -#undef WITH_SGI_DL - -/* Define if you want to emulate SGI (IRIX 4) dynamic linking. - This is rumoured to work on VAX (Ultrix), Sun3 (SunOS 3.4), - Sequent Symmetry (Dynix), and Atari ST. - This requires the "dl-dld" library, - ftp://ftp.cwi.nl/pub/dynload/dl-dld-1.1.tar.Z, - as well as the "GNU dld" library, - ftp://ftp.cwi.nl/pub/dynload/dld-3.2.3.tar.Z. - Don't bother on SunOS 4 or 5, they already have dynamic linking using - shared libraries */ -#undef WITH_DL_DLD - -/* Define if you want to compile in rudimentary thread support */ -#undef WITH_THREAD - -/* Define if you want to use the GNU readline library */ -#undef WITH_READLINE - - -/* Leave that blank line there-- autoheader needs it! */ diff --git a/config.h.in b/config.h.in deleted file mode 100644 index 98ff9e6868..0000000000 --- a/config.h.in +++ /dev/null @@ -1,320 +0,0 @@ -/* config.h.in. Generated automatically from configure.in by autoheader. */ - -/* Define if on AIX 3. - System headers sometimes define this. - We just want to avoid a redefinition error message. */ -#ifndef _ALL_SOURCE -#undef _ALL_SOURCE -#endif - -/* Define if type char is unsigned and you are not using gcc. */ -#ifndef __CHAR_UNSIGNED__ -#undef __CHAR_UNSIGNED__ -#endif - -/* Define to empty if the keyword does not work. */ -#undef const - -/* Define to `int' if <sys/types.h> doesn't define. */ -#undef gid_t - -/* Define if your struct tm has tm_zone. */ -#undef HAVE_TM_ZONE - -/* Define if you don't have tm_zone but do have the external array - tzname. */ -#undef HAVE_TZNAME - -/* Define if on MINIX. */ -#undef _MINIX - -/* Define to `int' if <sys/types.h> doesn't define. */ -#undef mode_t - -/* Define to `long' if <sys/types.h> doesn't define. */ -#undef off_t - -/* Define to `int' if <sys/types.h> doesn't define. */ -#undef pid_t - -/* Define if the system does not provide POSIX.1 features except - with this defined. */ -#undef _POSIX_1_SOURCE - -/* Define if you need to in order for stat and other things to work. */ -#undef _POSIX_SOURCE - -/* Define as the return type of signal handlers (int or void). */ -#undef RETSIGTYPE - -/* Define to `unsigned' if <sys/types.h> doesn't define. */ -#undef size_t - -/* Define if you have the ANSI C header files. */ -#undef STDC_HEADERS - -/* Define if you can safely include both <sys/time.h> and <time.h>. */ -#undef TIME_WITH_SYS_TIME - -/* Define if your <sys/time.h> declares struct tm. */ -#undef TM_IN_SYS_TIME - -/* Define to `int' if <sys/types.h> doesn't define. */ -#undef uid_t - -/* Define if your <unistd.h> contains bad prototypes for exec*() - (as it does on SGI IRIX 4.x) */ -#undef BAD_EXEC_PROTOTYPES - -/* Define if your compiler botches static forward declarations - (as it does on SCI ODT 3.0) */ -#undef BAD_STATIC_FORWARD - -/* Define to `long' if <time.h> doesn't define. */ -#undef clock_t - -/* Define if getpgrp() must be called as getpgrp(0). */ -#undef GETPGRP_HAVE_ARG - -/* Define if gettimeofday() does not have second (timezone) argument - This is the case on Motorola V4 (R40V4.2) */ -#undef GETTIMEOFDAY_NO_TZ - -/* Define this if your time.h defines altzone */ -#undef HAVE_ALTZONE - -/* Define if your compiler supports function prototypes */ -#undef HAVE_PROTOTYPES - -/* Define if your compiler supports variable length function prototypes - (e.g. void fprintf(FILE *, char *, ...);) *and* <stdarg.h> */ -#undef HAVE_STDARG_PROTOTYPES - -/* Define if you have POSIX threads */ -#undef _POSIX_THREADS - -/* Define if setpgrp() must be called as setpgrp(0, 0). */ -#undef SETPGRP_HAVE_ARG - -/* Define to empty if the keyword does not work. */ -#undef signed - -/* Define if you can safely include both <sys/select.h> and <sys/time.h> - (which you can't on SCO ODT 3.0). */ -#undef SYS_SELECT_WITH_SYS_TIME - -/* Define if a va_list is an array of some kind */ -#undef VA_LIST_IS_ARRAY - -/* Define to empty if the keyword does not work. */ -#undef volatile - -/* Define if you want to use SGI (IRIX 4) dynamic linking. - This requires the "dl" library by Jack Jansen, - ftp://ftp.cwi.nl/pub/dynload/dl-1.6.tar.Z. - Don't bother on IRIX 5, it already has dynamic linking using SunOS - style shared libraries */ -#undef WITH_SGI_DL - -/* Define if you want to emulate SGI (IRIX 4) dynamic linking. - This is rumoured to work on VAX (Ultrix), Sun3 (SunOS 3.4), - Sequent Symmetry (Dynix), and Atari ST. - This requires the "dl-dld" library, - ftp://ftp.cwi.nl/pub/dynload/dl-dld-1.1.tar.Z, - as well as the "GNU dld" library, - ftp://ftp.cwi.nl/pub/dynload/dld-3.2.3.tar.Z. - Don't bother on SunOS 4 or 5, they already have dynamic linking using - shared libraries */ -#undef WITH_DL_DLD - -/* Define if you want to compile in rudimentary thread support */ -#undef WITH_THREAD - -/* Define if you want to use the GNU readline library */ -#undef WITH_READLINE - -/* Define if you have the chown function. */ -#undef HAVE_CHOWN - -/* Define if you have the clock function. */ -#undef HAVE_CLOCK - -/* Define if you have the dlopen function. */ -#undef HAVE_DLOPEN - -/* Define if you have the ftime function. */ -#undef HAVE_FTIME - -/* Define if you have the ftruncate function. */ -#undef HAVE_FTRUNCATE - -/* Define if you have the gethostname_r function. */ -#undef HAVE_GETHOSTNAME_R - -/* Define if you have the getpeername function. */ -#undef HAVE_GETPEERNAME - -/* Define if you have the getpgrp function. */ -#undef HAVE_GETPGRP - -/* Define if you have the getpid function. */ -#undef HAVE_GETPID - -/* Define if you have the gettimeofday function. */ -#undef HAVE_GETTIMEOFDAY - -/* Define if you have the getwd function. */ -#undef HAVE_GETWD - -/* Define if you have the hypot function. */ -#undef HAVE_HYPOT - -/* Define if you have the link function. */ -#undef HAVE_LINK - -/* Define if you have the lstat function. */ -#undef HAVE_LSTAT - -/* Define if you have the mkfifo function. */ -#undef HAVE_MKFIFO - -/* Define if you have the nice function. */ -#undef HAVE_NICE - -/* Define if you have the readlink function. */ -#undef HAVE_READLINK - -/* Define if you have the select function. */ -#undef HAVE_SELECT - -/* Define if you have the setgid function. */ -#undef HAVE_SETGID - -/* Define if you have the setpgid function. */ -#undef HAVE_SETPGID - -/* Define if you have the setpgrp function. */ -#undef HAVE_SETPGRP - -/* Define if you have the setsid function. */ -#undef HAVE_SETSID - -/* Define if you have the setuid function. */ -#undef HAVE_SETUID - -/* Define if you have the setvbuf function. */ -#undef HAVE_SETVBUF - -/* Define if you have the sigaction function. */ -#undef HAVE_SIGACTION - -/* Define if you have the siginterrupt function. */ -#undef HAVE_SIGINTERRUPT - -/* Define if you have the sigrelse function. */ -#undef HAVE_SIGRELSE - -/* Define if you have the strftime function. */ -#undef HAVE_STRFTIME - -/* Define if you have the symlink function. */ -#undef HAVE_SYMLINK - -/* Define if you have the tcgetpgrp function. */ -#undef HAVE_TCGETPGRP - -/* Define if you have the tcsetpgrp function. */ -#undef HAVE_TCSETPGRP - -/* Define if you have the times function. */ -#undef HAVE_TIMES - -/* Define if you have the truncate function. */ -#undef HAVE_TRUNCATE - -/* Define if you have the uname function. */ -#undef HAVE_UNAME - -/* Define if you have the waitpid function. */ -#undef HAVE_WAITPID - -/* Define if you have the <dirent.h> header file. */ -#undef HAVE_DIRENT_H - -/* Define if you have the <dlfcn.h> header file. */ -#undef HAVE_DLFCN_H - -/* Define if you have the <fcntl.h> header file. */ -#undef HAVE_FCNTL_H - -/* Define if you have the <limits.h> header file. */ -#undef HAVE_LIMITS_H - -/* Define if you have the <ncurses.h> header file. */ -#undef HAVE_NCURSES_H - -/* Define if you have the <ndir.h> header file. */ -#undef HAVE_NDIR_H - -/* Define if you have the <signal.h> header file. */ -#undef HAVE_SIGNAL_H - -/* Define if you have the <stdarg.h> header file. */ -#undef HAVE_STDARG_H - -/* Define if you have the <stddef.h> header file. */ -#undef HAVE_STDDEF_H - -/* Define if you have the <stdlib.h> header file. */ -#undef HAVE_STDLIB_H - -/* Define if you have the <sys/audioio.h> header file. */ -#undef HAVE_SYS_AUDIOIO_H - -/* Define if you have the <sys/dir.h> header file. */ -#undef HAVE_SYS_DIR_H - -/* Define if you have the <sys/ndir.h> header file. */ -#undef HAVE_SYS_NDIR_H - -/* Define if you have the <sys/param.h> header file. */ -#undef HAVE_SYS_PARAM_H - -/* Define if you have the <sys/select.h> header file. */ -#undef HAVE_SYS_SELECT_H - -/* Define if you have the <sys/time.h> header file. */ -#undef HAVE_SYS_TIME_H - -/* Define if you have the <sys/times.h> header file. */ -#undef HAVE_SYS_TIMES_H - -/* Define if you have the <sys/un.h> header file. */ -#undef HAVE_SYS_UN_H - -/* Define if you have the <sys/utsname.h> header file. */ -#undef HAVE_SYS_UTSNAME_H - -/* Define if you have the <sys/wait.h> header file. */ -#undef HAVE_SYS_WAIT_H - -/* Define if you have the <thread.h> header file. */ -#undef HAVE_THREAD_H - -/* Define if you have the <unistd.h> header file. */ -#undef HAVE_UNISTD_H - -/* Define if you have the <utime.h> header file. */ -#undef HAVE_UTIME_H - -/* Define if you have the dl library (-ldl). */ -#undef HAVE_LIBDL - -/* Define if you have the dld library (-ldld). */ -#undef HAVE_LIBDLD - -/* Define if you have the ieee library (-lieee). */ -#undef HAVE_LIBIEEE - -/* Define if you have the sun library (-lsun). */ -#undef HAVE_LIBSUN diff --git a/configure b/configure deleted file mode 100755 index 53452e2684..0000000000 --- a/configure +++ /dev/null @@ -1,3329 +0,0 @@ -#! /bin/sh - -# From configure.in Revision: 1.25 - -# Guess values for system-dependent variables and create Makefiles. -# Generated automatically using autoconf version 2.10 -# Copyright (C) 1992, 93, 94, 95, 96 Free Software Foundation, Inc. -# -# This configure script is free software; the Free Software Foundation -# gives unlimited permission to copy, distribute and modify it. - -# Defaults: -ac_help= -ac_default_prefix=/usr/local -# Any additions from configure.in: -ac_help="$ac_help ---without-gcc never use gcc" -ac_help="$ac_help ---with-readline=DIRECTORY GNU readline" -ac_help="$ac_help ---with-thread[=DIRECTORY] make interpreter thread-safe" -ac_help="$ac_help ---with-sgi-dl=DIRECTORY IRIX 4 dynamic linking" -ac_help="$ac_help ---with-dl-dld=DL_DIR,DLD_DIR GNU dynamic linking" -ac_help="$ac_help ---with-libm=STRING math library" -ac_help="$ac_help ---with-libc=STRING C library" - -# Initialize some variables set by options. -# The variables have the same names as the options, with -# dashes changed to underlines. -build=NONE -cache_file=./config.cache -exec_prefix=NONE -host=NONE -no_create= -nonopt=NONE -no_recursion= -prefix=NONE -program_prefix=NONE -program_suffix=NONE -program_transform_name=s,x,x, -silent= -site= -srcdir= -target=NONE -verbose= -x_includes=NONE -x_libraries=NONE -bindir='${exec_prefix}/bin' -sbindir='${exec_prefix}/sbin' -libexecdir='${exec_prefix}/libexec' -datadir='${prefix}/share' -sysconfdir='${prefix}/etc' -sharedstatedir='${prefix}/com' -localstatedir='${prefix}/var' -libdir='${exec_prefix}/lib' -includedir='${prefix}/include' -oldincludedir='/usr/include' -infodir='${prefix}/info' -mandir='${prefix}/man' - -# Initialize some other variables. -subdirs= -MFLAGS= MAKEFLAGS= - -ac_prev= -for ac_option -do - - # If the previous option needs an argument, assign it. - if test -n "$ac_prev"; then - eval "$ac_prev=\$ac_option" - ac_prev= - continue - fi - - case "$ac_option" in - -*=*) ac_optarg=`echo "$ac_option" | sed 's/[-_a-zA-Z0-9]*=//'` ;; - *) ac_optarg= ;; - esac - - # Accept the important Cygnus configure options, so we can diagnose typos. - - case "$ac_option" in - - -bindir | --bindir | --bindi | --bind | --bin | --bi) - ac_prev=bindir ;; - -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) - bindir="$ac_optarg" ;; - - -build | --build | --buil | --bui | --bu) - ac_prev=build ;; - -build=* | --build=* | --buil=* | --bui=* | --bu=*) - build="$ac_optarg" ;; - - -cache-file | --cache-file | --cache-fil | --cache-fi \ - | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) - ac_prev=cache_file ;; - -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ - | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) - cache_file="$ac_optarg" ;; - - -datadir | --datadir | --datadi | --datad | --data | --dat | --da) - ac_prev=datadir ;; - -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \ - | --da=*) - datadir="$ac_optarg" ;; - - -disable-* | --disable-*) - ac_feature=`echo $ac_option|sed -e 's/-*disable-//'` - # Reject names that are not valid shell variable names. - if test -n "`echo $ac_feature| sed 's/[-a-zA-Z0-9_]//g'`"; then - { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; } - fi - ac_feature=`echo $ac_feature| sed 's/-/_/g'` - eval "enable_${ac_feature}=no" ;; - - -enable-* | --enable-*) - ac_feature=`echo $ac_option|sed -e 's/-*enable-//' -e 's/=.*//'` - # Reject names that are not valid shell variable names. - if test -n "`echo $ac_feature| sed 's/[-_a-zA-Z0-9]//g'`"; then - { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; } - fi - ac_feature=`echo $ac_feature| sed 's/-/_/g'` - case "$ac_option" in - *=*) ;; - *) ac_optarg=yes ;; - esac - eval "enable_${ac_feature}='$ac_optarg'" ;; - - -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ - | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ - | --exec | --exe | --ex) - ac_prev=exec_prefix ;; - -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ - | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ - | --exec=* | --exe=* | --ex=*) - exec_prefix="$ac_optarg" ;; - - -gas | --gas | --ga | --g) - # Obsolete; use --with-gas. - with_gas=yes ;; - - -help | --help | --hel | --he) - # Omit some internal or obsolete options to make the list less imposing. - # This message is too long to be a string in the A/UX 3.1 sh. - cat << EOF -Usage: configure [options] [host] -Options: [defaults in brackets after descriptions] -Configuration: - --cache-file=FILE cache test results in FILE - --help print this message - --no-create do not create output files - --quiet, --silent do not print \`checking...' messages - --version print the version of autoconf that created configure -Directory and file names: - --prefix=PREFIX install architecture-independent files in PREFIX - [$ac_default_prefix] - --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX - [same as prefix] - --bindir=DIR user executables in DIR [EPREFIX/bin] - --sbindir=DIR system admin executables in DIR [EPREFIX/sbin] - --libexecdir=DIR program executables in DIR [EPREFIX/libexec] - --datadir=DIR read-only architecture-independent data in DIR - [PREFIX/share] - --sysconfdir=DIR read-only single-machine data in DIR [PREFIX/etc] - --sharedstatedir=DIR modifiable architecture-independent data in DIR - [PREFIX/com] - --localstatedir=DIR modifiable single-machine data in DIR [PREFIX/var] - --libdir=DIR object code libraries in DIR [EPREFIX/lib] - --includedir=DIR C header files in DIR [PREFIX/include] - --oldincludedir=DIR C header files for non-gcc in DIR [/usr/include] - --infodir=DIR info documentation in DIR [PREFIX/info] - --mandir=DIR man documentation in DIR [PREFIX/man] - --srcdir=DIR find the sources in DIR [configure dir or ..] - --program-prefix=PREFIX prepend PREFIX to installed program names - --program-suffix=SUFFIX append SUFFIX to installed program names - --program-transform-name=PROGRAM - run sed PROGRAM on installed program names -EOF - cat << EOF -Host type: - --build=BUILD configure for building on BUILD [BUILD=HOST] - --host=HOST configure for HOST [guessed] - --target=TARGET configure for TARGET [TARGET=HOST] -Features and packages: - --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) - --enable-FEATURE[=ARG] include FEATURE [ARG=yes] - --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] - --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) - --x-includes=DIR X include files are in DIR - --x-libraries=DIR X library files are in DIR -EOF - if test -n "$ac_help"; then - echo "--enable and --with options recognized:$ac_help" - fi - exit 0 ;; - - -host | --host | --hos | --ho) - ac_prev=host ;; - -host=* | --host=* | --hos=* | --ho=*) - host="$ac_optarg" ;; - - -includedir | --includedir | --includedi | --included | --include \ - | --includ | --inclu | --incl | --inc) - ac_prev=includedir ;; - -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ - | --includ=* | --inclu=* | --incl=* | --inc=*) - includedir="$ac_optarg" ;; - - -infodir | --infodir | --infodi | --infod | --info | --inf) - ac_prev=infodir ;; - -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) - infodir="$ac_optarg" ;; - - -libdir | --libdir | --libdi | --libd) - ac_prev=libdir ;; - -libdir=* | --libdir=* | --libdi=* | --libd=*) - libdir="$ac_optarg" ;; - - -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ - | --libexe | --libex | --libe) - ac_prev=libexecdir ;; - -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ - | --libexe=* | --libex=* | --libe=*) - libexecdir="$ac_optarg" ;; - - -localstatedir | --localstatedir | --localstatedi | --localstated \ - | --localstate | --localstat | --localsta | --localst \ - | --locals | --local | --loca | --loc | --lo) - ac_prev=localstatedir ;; - -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ - | --localstate=* | --localstat=* | --localsta=* | --localst=* \ - | --locals=* | --local=* | --loca=* | --loc=* | --lo=*) - localstatedir="$ac_optarg" ;; - - -mandir | --mandir | --mandi | --mand | --man | --ma | --m) - ac_prev=mandir ;; - -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) - mandir="$ac_optarg" ;; - - -nfp | --nfp | --nf) - # Obsolete; use --without-fp. - with_fp=no ;; - - -no-create | --no-create | --no-creat | --no-crea | --no-cre \ - | --no-cr | --no-c) - no_create=yes ;; - - -no-recursion | --no-recursion | --no-recursio | --no-recursi \ - | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) - no_recursion=yes ;; - - -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ - | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ - | --oldin | --oldi | --old | --ol | --o) - ac_prev=oldincludedir ;; - -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ - | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ - | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) - oldincludedir="$ac_optarg" ;; - - -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) - ac_prev=prefix ;; - -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) - prefix="$ac_optarg" ;; - - -program-prefix | --program-prefix | --program-prefi | --program-pref \ - | --program-pre | --program-pr | --program-p) - ac_prev=program_prefix ;; - -program-prefix=* | --program-prefix=* | --program-prefi=* \ - | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) - program_prefix="$ac_optarg" ;; - - -program-suffix | --program-suffix | --program-suffi | --program-suff \ - | --program-suf | --program-su | --program-s) - ac_prev=program_suffix ;; - -program-suffix=* | --program-suffix=* | --program-suffi=* \ - | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) - program_suffix="$ac_optarg" ;; - - -program-transform-name | --program-transform-name \ - | --program-transform-nam | --program-transform-na \ - | --program-transform-n | --program-transform- \ - | --program-transform | --program-transfor \ - | --program-transfo | --program-transf \ - | --program-trans | --program-tran \ - | --progr-tra | --program-tr | --program-t) - ac_prev=program_transform_name ;; - -program-transform-name=* | --program-transform-name=* \ - | --program-transform-nam=* | --program-transform-na=* \ - | --program-transform-n=* | --program-transform-=* \ - | --program-transform=* | --program-transfor=* \ - | --program-transfo=* | --program-transf=* \ - | --program-trans=* | --program-tran=* \ - | --progr-tra=* | --program-tr=* | --program-t=*) - program_transform_name="$ac_optarg" ;; - - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil) - silent=yes ;; - - -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) - ac_prev=sbindir ;; - -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ - | --sbi=* | --sb=*) - sbindir="$ac_optarg" ;; - - -sharedstatedir | --sharedstatedir | --sharedstatedi \ - | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ - | --sharedst | --shareds | --shared | --share | --shar \ - | --sha | --sh) - ac_prev=sharedstatedir ;; - -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ - | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ - | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ - | --sha=* | --sh=*) - sharedstatedir="$ac_optarg" ;; - - -site | --site | --sit) - ac_prev=site ;; - -site=* | --site=* | --sit=*) - site="$ac_optarg" ;; - - -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) - ac_prev=srcdir ;; - -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) - srcdir="$ac_optarg" ;; - - -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ - | --syscon | --sysco | --sysc | --sys | --sy) - ac_prev=sysconfdir ;; - -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ - | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) - sysconfdir="$ac_optarg" ;; - - -target | --target | --targe | --targ | --tar | --ta | --t) - ac_prev=target ;; - -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) - target="$ac_optarg" ;; - - -v | -verbose | --verbose | --verbos | --verbo | --verb) - verbose=yes ;; - - -version | --version | --versio | --versi | --vers) - echo "configure generated by autoconf version 2.10" - exit 0 ;; - - -with-* | --with-*) - ac_package=`echo $ac_option|sed -e 's/-*with-//' -e 's/=.*//'` - # Reject names that are not valid shell variable names. - if test -n "`echo $ac_package| sed 's/[-_a-zA-Z0-9]//g'`"; then - { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; } - fi - ac_package=`echo $ac_package| sed 's/-/_/g'` - case "$ac_option" in - *=*) ;; - *) ac_optarg=yes ;; - esac - eval "with_${ac_package}='$ac_optarg'" ;; - - -without-* | --without-*) - ac_package=`echo $ac_option|sed -e 's/-*without-//'` - # Reject names that are not valid shell variable names. - if test -n "`echo $ac_package| sed 's/[-a-zA-Z0-9_]//g'`"; then - { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; } - fi - ac_package=`echo $ac_package| sed 's/-/_/g'` - eval "with_${ac_package}=no" ;; - - --x) - # Obsolete; use --with-x. - with_x=yes ;; - - -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ - | --x-incl | --x-inc | --x-in | --x-i) - ac_prev=x_includes ;; - -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ - | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) - x_includes="$ac_optarg" ;; - - -x-libraries | --x-libraries | --x-librarie | --x-librari \ - | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) - ac_prev=x_libraries ;; - -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ - | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) - x_libraries="$ac_optarg" ;; - - -*) { echo "configure: error: $ac_option: invalid option; use --help to show usage" 1>&2; exit 1; } - ;; - - *) - if test -n "`echo $ac_option| sed 's/[-a-z0-9.]//g'`"; then - echo "configure: warning: $ac_option: invalid host type" 1>&2 - fi - if test "x$nonopt" != xNONE; then - { echo "configure: error: can only configure for one host and one target at a time" 1>&2; exit 1; } - fi - nonopt="$ac_option" - ;; - - esac -done - -if test -n "$ac_prev"; then - { echo "configure: error: missing argument to --`echo $ac_prev | sed 's/_/-/g'`" 1>&2; exit 1; } -fi - -trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15 - -# File descriptor usage: -# 0 standard input -# 1 file creation -# 2 errors and warnings -# 3 some systems may open it to /dev/tty -# 4 used on the Kubota Titan -# 6 checking for... messages and results -# 5 compiler messages saved in config.log -if test "$silent" = yes; then - exec 6>/dev/null -else - exec 6>&1 -fi -exec 5>./config.log - -echo "\ -This file contains any messages produced by compilers while -running configure, to aid debugging if configure makes a mistake. -" 1>&5 - -# Strip out --no-create and --no-recursion so they do not pile up. -# Also quote any args containing shell metacharacters. -ac_configure_args= -for ac_arg -do - case "$ac_arg" in - -no-create | --no-create | --no-creat | --no-crea | --no-cre \ - | --no-cr | --no-c) ;; - -no-recursion | --no-recursion | --no-recursio | --no-recursi \ - | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) ;; - *" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?]*) - ac_configure_args="$ac_configure_args '$ac_arg'" ;; - *) ac_configure_args="$ac_configure_args $ac_arg" ;; - esac -done - -# NLS nuisances. -# Only set LANG and LC_ALL to C if already set. -# These must not be set unconditionally because not all systems understand -# e.g. LANG=C (notably SCO). -if test "${LC_ALL+set}" = set; then LC_ALL=C; export LC_ALL; fi -if test "${LANG+set}" = set; then LANG=C; export LANG; fi - -# confdefs.h avoids OS command line length limits that DEFS can exceed. -rm -rf conftest* confdefs.h -# AIX cpp loses on an empty file, so make sure it contains at least a newline. -echo > confdefs.h - -# A filename unique to this package, relative to the directory that -# configure is in, which we can look for to find out if srcdir is correct. -ac_unique_file=Include/object.h - -# Find the source files, if location was not specified. -if test -z "$srcdir"; then - ac_srcdir_defaulted=yes - # Try the directory containing this script, then its parent. - ac_prog=$0 - ac_confdir=`echo $ac_prog|sed 's%/[^/][^/]*$%%'` - test "x$ac_confdir" = "x$ac_prog" && ac_confdir=. - srcdir=$ac_confdir - if test ! -r $srcdir/$ac_unique_file; then - srcdir=.. - fi -else - ac_srcdir_defaulted=no -fi -if test ! -r $srcdir/$ac_unique_file; then - if test "$ac_srcdir_defaulted" = yes; then - { echo "configure: error: can not find sources in $ac_confdir or .." 1>&2; exit 1; } - else - { echo "configure: error: can not find sources in $srcdir" 1>&2; exit 1; } - fi -fi -srcdir=`echo "${srcdir}" | sed 's%\([^/]\)/*$%\1%'` - -# Prefer explicitly selected file to automatically selected ones. -if test -z "$CONFIG_SITE"; then - if test "x$prefix" != xNONE; then - CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site" - else - CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site" - fi -fi -for ac_site_file in $CONFIG_SITE; do - if test -r "$ac_site_file"; then - echo "loading site script $ac_site_file" - . "$ac_site_file" - fi -done - -if test -r "$cache_file"; then - echo "loading cache $cache_file" - . $cache_file -else - echo "creating cache $cache_file" - > $cache_file -fi - -ac_ext=c -# CFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options. -ac_cpp='$CPP $CPPFLAGS' -ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.$ac_ext 1>&5' -ac_link='${CC-cc} -o conftest $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5' - -if (echo "testing\c"; echo 1,2,3) | grep c >/dev/null; then - # Stardent Vistra SVR4 grep lacks -e, says ghazi@caip.rutgers.edu. - if (echo -n testing; echo 1,2,3) | sed s/-n/xn/ | grep xn >/dev/null; then - ac_n= ac_c=' -' ac_t=' ' - else - ac_n=-n ac_c= ac_t= - fi -else - ac_n= ac_c='\c' ac_t= -fi - - - - -# checks for alternative programs -echo $ac_n "checking for --without-gcc""... $ac_c" 1>&6 -# Check whether --with-gcc or --without-gcc was given. -if test "${with_gcc+set}" = set; then - withval="$with_gcc" - - case $withval in - no) CC=cc - without_gcc=yes;; - yes) CC=gcc - without_gcc=no;; - *) CC=$withval - without_gcc=$withval;; - esac -else - - case `uname -s` in - OSF1) CC=cc - without_gcc=;; - *) without_gcc=no;; - esac -fi - -echo "$ac_t""$without_gcc" 1>&6 - -# If the user switches compilers, we can't believe the cache -if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC" -then - { echo "configure: error: cached CC is different -- throw away $cache_file -(it is also a good idea to do 'make clean' before compiling)" 1>&2; exit 1; } -fi - -# Extract the first word of "gcc", so it can be a program name with args. -set dummy gcc; ac_word=$2 -echo $ac_n "checking for $ac_word""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else - IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}:" - for ac_dir in $PATH; do - test -z "$ac_dir" && ac_dir=. - if test -f $ac_dir/$ac_word; then - ac_cv_prog_CC="gcc" - break - fi - done - IFS="$ac_save_ifs" -fi -fi -CC="$ac_cv_prog_CC" -if test -n "$CC"; then - echo "$ac_t""$CC" 1>&6 -else - echo "$ac_t""no" 1>&6 -fi - -if test -z "$CC"; then - # Extract the first word of "cc", so it can be a program name with args. -set dummy cc; ac_word=$2 -echo $ac_n "checking for $ac_word""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else - IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}:" - ac_prog_rejected=no - for ac_dir in $PATH; do - test -z "$ac_dir" && ac_dir=. - if test -f $ac_dir/$ac_word; then - if test "$ac_dir/$ac_word" = "/usr/ucb/cc"; then - ac_prog_rejected=yes - continue - fi - ac_cv_prog_CC="cc" - break - fi - done - IFS="$ac_save_ifs" -if test $ac_prog_rejected = yes; then - # We found a bogon in the path, so make sure we never use it. - set dummy $ac_cv_prog_CC - shift - if test $# -gt 0; then - # We chose a different compiler from the bogus one. - # However, it has the same basename, so the bogon will be chosen - # first if we set CC to just the basename; use the full file name. - shift - set dummy "$ac_dir/$ac_word" "$@" - shift - ac_cv_prog_CC="$@" - fi -fi -fi -fi -CC="$ac_cv_prog_CC" -if test -n "$CC"; then - echo "$ac_t""$CC" 1>&6 -else - echo "$ac_t""no" 1>&6 -fi - - test -z "$CC" && { echo "configure: error: no acceptable cc found in \$PATH" 1>&2; exit 1; } -fi - -echo $ac_n "checking whether we are using GNU C""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_prog_gcc'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.c <<EOF -#ifdef __GNUC__ - yes; -#endif -EOF -if { ac_try='${CC-cc} -E conftest.c'; { (eval echo configure:652: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }; } | egrep yes >/dev/null 2>&1; then - ac_cv_prog_gcc=yes -else - ac_cv_prog_gcc=no -fi -fi - -echo "$ac_t""$ac_cv_prog_gcc" 1>&6 -if test $ac_cv_prog_gcc = yes; then - GCC=yes - if test "${CFLAGS+set}" != set; then - echo $ac_n "checking whether ${CC-cc} accepts -g""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_prog_gcc_g'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - echo 'void f(){}' > conftest.c -if test -z "`${CC-cc} -g -c conftest.c 2>&1`"; then - ac_cv_prog_gcc_g=yes -else - ac_cv_prog_gcc_g=no -fi -rm -f conftest* - -fi - -echo "$ac_t""$ac_cv_prog_gcc_g" 1>&6 - if test $ac_cv_prog_gcc_g = yes; then - CFLAGS="-g -O" - else - CFLAGS="-O" - fi - fi -else - GCC= - test "${CFLAGS+set}" = set || CFLAGS="-g" -fi - -# Extract the first word of "ranlib", so it can be a program name with args. -set dummy ranlib; ac_word=$2 -echo $ac_n "checking for $ac_word""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_prog_RANLIB'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - if test -n "$RANLIB"; then - ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. -else - IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}:" - for ac_dir in $PATH; do - test -z "$ac_dir" && ac_dir=. - if test -f $ac_dir/$ac_word; then - ac_cv_prog_RANLIB="ranlib" - break - fi - done - IFS="$ac_save_ifs" - test -z "$ac_cv_prog_RANLIB" && ac_cv_prog_RANLIB=":" -fi -fi -RANLIB="$ac_cv_prog_RANLIB" -if test -n "$RANLIB"; then - echo "$ac_t""$RANLIB" 1>&6 -else - echo "$ac_t""no" 1>&6 -fi - - -for ac_prog in ar aal -do -# Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -echo $ac_n "checking for $ac_word""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_prog_AR'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - if test -n "$AR"; then - ac_cv_prog_AR="$AR" # Let the user override the test. -else - IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}:" - for ac_dir in $PATH; do - test -z "$ac_dir" && ac_dir=. - if test -f $ac_dir/$ac_word; then - ac_cv_prog_AR="$ac_prog" - break - fi - done - IFS="$ac_save_ifs" -fi -fi -AR="$ac_cv_prog_AR" -if test -n "$AR"; then - echo "$ac_t""$AR" 1>&6 -else - echo "$ac_t""no" 1>&6 -fi - -test -n "$AR" && break -done -test -n "$AR" || AR="ar" - - - - -# Install just never works :-( -if test -z "$INSTALL" -then - INSTALL=cp - INSTALL_PROGRAM=cp - INSTALL_DATA=cp -else - INSTALL_PROGRAM="$INSTALL" - INSTALL_DATA="$INSTALL -m 644" -fi - -# Optimizer/debugger flags passed between Makefiles -if test -z "$OPT" -then OPT=-O -fi - -# checks for UNIX variants that set C preprocessor variables -echo $ac_n "checking how to run the C preprocessor""... $ac_c" 1>&6 -# On Suns, sometimes $CPP names a directory. -if test -n "$CPP" && test -d "$CPP"; then - CPP= -fi -if test -z "$CPP"; then -if eval "test \"`echo '$''{'ac_cv_prog_CPP'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - # This must be in double quotes, not single quotes, because CPP may get - # substituted into the Makefile and "${CC-cc}" will confuse make. - CPP="${CC-cc} -E" - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. - cat > conftest.$ac_ext <<EOF -#line 786 "configure" -#include "confdefs.h" -#include <assert.h> -Syntax Error -EOF -ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:792: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } -ac_err=`grep -v '^ *+' conftest.out` -if test -z "$ac_err"; then - : -else - echo "$ac_err" >&5 - rm -rf conftest* - CPP="${CC-cc} -E -traditional-cpp" - cat > conftest.$ac_ext <<EOF -#line 801 "configure" -#include "confdefs.h" -#include <assert.h> -Syntax Error -EOF -ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:807: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } -ac_err=`grep -v '^ *+' conftest.out` -if test -z "$ac_err"; then - : -else - echo "$ac_err" >&5 - rm -rf conftest* - CPP=/lib/cpp -fi -rm -f conftest* -fi -rm -f conftest* - ac_cv_prog_CPP="$CPP" -fi - CPP="$ac_cv_prog_CPP" -else - ac_cv_prog_CPP="$CPP" -fi -echo "$ac_t""$CPP" 1>&6 - -echo $ac_n "checking for AIX""... $ac_c" 1>&6 -cat > conftest.$ac_ext <<EOF -#line 829 "configure" -#include "confdefs.h" -#ifdef _AIX - yes -#endif - -EOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - egrep "yes" >/dev/null 2>&1; then - rm -rf conftest* - echo "$ac_t""yes" 1>&6; cat >> confdefs.h <<\EOF -#define _ALL_SOURCE 1 -EOF - -else - rm -rf conftest* - echo "$ac_t""no" 1>&6 -fi -rm -f conftest* - - -ac_safe=`echo "minix/config.h" | tr './\055' '___'` -echo $ac_n "checking for minix/config.h""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 856 "configure" -#include "confdefs.h" -#include <minix/config.h> -EOF -ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:861: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } -ac_err=`grep -v '^ *+' conftest.out` -if test -z "$ac_err"; then - rm -rf conftest* - eval "ac_cv_header_$ac_safe=yes" -else - echo "$ac_err" >&5 - rm -rf conftest* - eval "ac_cv_header_$ac_safe=no" -fi -rm -f conftest* -fi -if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then - echo "$ac_t""yes" 1>&6 - MINIX=yes -else - echo "$ac_t""no" 1>&6 -MINIX= -fi - -if test "$MINIX" = yes; then - cat >> confdefs.h <<\EOF -#define _POSIX_SOURCE 1 -EOF - - cat >> confdefs.h <<\EOF -#define _POSIX_1_SOURCE 2 -EOF - - cat >> confdefs.h <<\EOF -#define _MINIX 1 -EOF - -fi - - -# checks for header files -# If we cannot run a trivial program, we must be cross compiling. -echo $ac_n "checking whether cross-compiling""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_c_cross'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - if test "$cross_compiling" = yes; then - ac_cv_c_cross=yes -else -cat > conftest.$ac_ext <<EOF -#line 907 "configure" -#include "confdefs.h" -main(){return(0);} -EOF -{ (eval echo configure:911: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } -if test -s conftest && (./conftest; exit) 2>/dev/null; then - ac_cv_c_cross=no -else - ac_cv_c_cross=yes -fi -fi -rm -fr conftest* -fi - -echo "$ac_t""$ac_cv_c_cross" 1>&6 -cross_compiling=$ac_cv_c_cross - -echo $ac_n "checking for ANSI C header files""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_header_stdc'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 929 "configure" -#include "confdefs.h" -#include <stdlib.h> -#include <stdarg.h> -#include <string.h> -#include <float.h> -EOF -ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:937: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } -ac_err=`grep -v '^ *+' conftest.out` -if test -z "$ac_err"; then - rm -rf conftest* - ac_cv_header_stdc=yes -else - echo "$ac_err" >&5 - rm -rf conftest* - ac_cv_header_stdc=no -fi -rm -f conftest* - -if test $ac_cv_header_stdc = yes; then - # SunOS 4.x string.h does not declare mem*, contrary to ANSI. -cat > conftest.$ac_ext <<EOF -#line 952 "configure" -#include "confdefs.h" -#include <string.h> -EOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - egrep "memchr" >/dev/null 2>&1; then - : -else - rm -rf conftest* - ac_cv_header_stdc=no -fi -rm -f conftest* - -fi - -if test $ac_cv_header_stdc = yes; then - # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. -cat > conftest.$ac_ext <<EOF -#line 970 "configure" -#include "confdefs.h" -#include <stdlib.h> -EOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - egrep "free" >/dev/null 2>&1; then - : -else - rm -rf conftest* - ac_cv_header_stdc=no -fi -rm -f conftest* - -fi - -if test $ac_cv_header_stdc = yes; then - # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. -if test "$cross_compiling" = yes; then - : -else -cat > conftest.$ac_ext <<EOF -#line 991 "configure" -#include "confdefs.h" -#include <ctype.h> -#define ISLOWER(c) ('a' <= (c) && (c) <= 'z') -#define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) -#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) -int main () { int i; for (i = 0; i < 256; i++) -if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) exit(2); -exit (0); } - -EOF -{ (eval echo configure:1002: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } -if test -s conftest && (./conftest; exit) 2>/dev/null; then - : -else - ac_cv_header_stdc=no -fi -fi -rm -fr conftest* -fi -fi - -echo "$ac_t""$ac_cv_header_stdc" 1>&6 -if test $ac_cv_header_stdc = yes; then - cat >> confdefs.h <<\EOF -#define STDC_HEADERS 1 -EOF - -fi - -for ac_hdr in dlfcn.h fcntl.h limits.h ncurses.h signal.h stdarg.h stddef.h stdlib.h thread.h unistd.h utime.h sys/audioio.h sys/param.h sys/select.h sys/time.h sys/times.h sys/un.h sys/utsname.h sys/wait.h -do -ac_safe=`echo "$ac_hdr" | tr './\055' '___'` -echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 1029 "configure" -#include "confdefs.h" -#include <$ac_hdr> -EOF -ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:1034: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } -ac_err=`grep -v '^ *+' conftest.out` -if test -z "$ac_err"; then - rm -rf conftest* - eval "ac_cv_header_$ac_safe=yes" -else - echo "$ac_err" >&5 - rm -rf conftest* - eval "ac_cv_header_$ac_safe=no" -fi -rm -f conftest* -fi -if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then - echo "$ac_t""yes" 1>&6 - ac_tr_hdr=HAVE_`echo $ac_hdr | tr 'abcdefghijklmnopqrstuvwxyz./\055' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ___'` - cat >> confdefs.h <<EOF -#define $ac_tr_hdr 1 -EOF - -else - echo "$ac_t""no" 1>&6 -fi -done - -ac_header_dirent=no -for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h -do -ac_safe=`echo "$ac_hdr" | tr './\055' '___'` -echo $ac_n "checking for $ac_hdr that defines DIR""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_header_dirent_$ac_safe'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 1067 "configure" -#include "confdefs.h" -#include <sys/types.h> -#include <$ac_hdr> -int main() { return 0; } -int t() { -DIR *dirp = 0; -; return 0; } -EOF -if { (eval echo configure:1076: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_header_dirent_$ac_safe=yes" -else - rm -rf conftest* - eval "ac_cv_header_dirent_$ac_safe=no" -fi -rm -f conftest* - -fi -if eval "test \"`echo '$ac_cv_header_dirent_'$ac_safe`\" = yes"; then - echo "$ac_t""yes" 1>&6 - ac_tr_hdr=HAVE_`echo $ac_hdr | tr 'abcdedfghijklmnopqrstuvwxyz./\055' 'ABCDEDFGHIJKLMNOPQRSTUVWXYZ___'` - cat >> confdefs.h <<EOF -#define $ac_tr_hdr 1 -EOF - ac_header_dirent=$ac_hdr; break -else - echo "$ac_t""no" 1>&6 -fi -done -# Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. -if test $ac_header_dirent = dirent.h; then -echo $ac_n "checking for -ldir""... $ac_c" 1>&6 -ac_lib_var=`echo dir'_'opendir | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-ldir $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1107 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char opendir(); - -int main() { return 0; } -int t() { -opendir() -; return 0; } -EOF -if { (eval echo configure:1119: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - LIBS="$LIBS -ldir" -else - echo "$ac_t""no" 1>&6 -fi - -else -echo $ac_n "checking for -lx""... $ac_c" 1>&6 -ac_lib_var=`echo x'_'opendir | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-lx $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1146 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char opendir(); - -int main() { return 0; } -int t() { -opendir() -; return 0; } -EOF -if { (eval echo configure:1158: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - LIBS="$LIBS -lx" -else - echo "$ac_t""no" 1>&6 -fi - -fi - - -# checks for typedefs -was_it_defined=no -echo $ac_n "checking for clock_t in time.h""... $ac_c" 1>&6 -cat > conftest.$ac_ext <<EOF -#line 1183 "configure" -#include "confdefs.h" -#include <time.h> -EOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - egrep "clock_t" >/dev/null 2>&1; then - rm -rf conftest* - was_it_defined=yes -else - rm -rf conftest* - cat >> confdefs.h <<\EOF -#define clock_t long -EOF - -fi -rm -f conftest* - -echo "$ac_t""$was_it_defined" 1>&6 - -echo $ac_n "checking for mode_t""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_type_mode_t'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 1207 "configure" -#include "confdefs.h" -#include <sys/types.h> -#if STDC_HEADERS -#include <stdlib.h> -#endif -EOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - egrep "mode_t" >/dev/null 2>&1; then - rm -rf conftest* - ac_cv_type_mode_t=yes -else - rm -rf conftest* - ac_cv_type_mode_t=no -fi -rm -f conftest* - -fi -echo "$ac_t""$ac_cv_type_mode_t" 1>&6 -if test $ac_cv_type_mode_t = no; then - cat >> confdefs.h <<\EOF -#define mode_t int -EOF - -fi - -echo $ac_n "checking for off_t""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_type_off_t'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 1238 "configure" -#include "confdefs.h" -#include <sys/types.h> -#if STDC_HEADERS -#include <stdlib.h> -#endif -EOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - egrep "off_t" >/dev/null 2>&1; then - rm -rf conftest* - ac_cv_type_off_t=yes -else - rm -rf conftest* - ac_cv_type_off_t=no -fi -rm -f conftest* - -fi -echo "$ac_t""$ac_cv_type_off_t" 1>&6 -if test $ac_cv_type_off_t = no; then - cat >> confdefs.h <<\EOF -#define off_t long -EOF - -fi - -echo $ac_n "checking for pid_t""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_type_pid_t'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 1269 "configure" -#include "confdefs.h" -#include <sys/types.h> -#if STDC_HEADERS -#include <stdlib.h> -#endif -EOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - egrep "pid_t" >/dev/null 2>&1; then - rm -rf conftest* - ac_cv_type_pid_t=yes -else - rm -rf conftest* - ac_cv_type_pid_t=no -fi -rm -f conftest* - -fi -echo "$ac_t""$ac_cv_type_pid_t" 1>&6 -if test $ac_cv_type_pid_t = no; then - cat >> confdefs.h <<\EOF -#define pid_t int -EOF - -fi - -echo $ac_n "checking return type of signal handlers""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_type_signal'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 1300 "configure" -#include "confdefs.h" -#include <sys/types.h> -#include <signal.h> -#ifdef signal -#undef signal -#endif -#ifdef __cplusplus -extern "C" void (*signal (int, void (*)(int)))(int); -#else -void (*signal ()) (); -#endif - -int main() { return 0; } -int t() { -int i; -; return 0; } -EOF -if { (eval echo configure:1318: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - ac_cv_type_signal=void -else - rm -rf conftest* - ac_cv_type_signal=int -fi -rm -f conftest* - -fi - -echo "$ac_t""$ac_cv_type_signal" 1>&6 -cat >> confdefs.h <<EOF -#define RETSIGTYPE $ac_cv_type_signal -EOF - - -echo $ac_n "checking for size_t""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_type_size_t'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 1340 "configure" -#include "confdefs.h" -#include <sys/types.h> -#if STDC_HEADERS -#include <stdlib.h> -#endif -EOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - egrep "size_t" >/dev/null 2>&1; then - rm -rf conftest* - ac_cv_type_size_t=yes -else - rm -rf conftest* - ac_cv_type_size_t=no -fi -rm -f conftest* - -fi -echo "$ac_t""$ac_cv_type_size_t" 1>&6 -if test $ac_cv_type_size_t = no; then - cat >> confdefs.h <<\EOF -#define size_t unsigned -EOF - -fi - -echo $ac_n "checking for uid_t in sys/types.h""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_type_uid_t'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 1371 "configure" -#include "confdefs.h" -#include <sys/types.h> -EOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - egrep "uid_t" >/dev/null 2>&1; then - rm -rf conftest* - ac_cv_type_uid_t=yes -else - rm -rf conftest* - ac_cv_type_uid_t=no -fi -rm -f conftest* - -fi - -echo "$ac_t""$ac_cv_type_uid_t" 1>&6 -if test $ac_cv_type_uid_t = no; then - cat >> confdefs.h <<\EOF -#define uid_t int -EOF - - cat >> confdefs.h <<\EOF -#define gid_t int -EOF - -fi - - -# Set name for machine-dependent library files - -echo $ac_n "checking MACHDEP""... $ac_c" 1>&6 -if test -z "$MACHDEP" -then - ac_sys_system=`uname -s | tr -d '/ ' | tr '[A-Z]' '[a-z]'` - ac_sys_release=`uname -r | tr -d '/ ' | sed 's/\..*//'` - ac_sys_cpu=`(uname -p 2>/dev/null || uname -m) | - tr '[A-Z]' '[a-z]'` -## MACHDEP="$ac_sys_system$ac_sys_release$ac_sys_cpu" - MACHDEP="$ac_sys_system$ac_sys_release" - case MACHDEP in - '') MACHDEP=unknown;; - esac -fi -echo "$ac_t""$MACHDEP" 1>&6 - -# Set info about shared libraries. -# XXX This should try things out instead of testing uname! - - - - -ac_sys_system=`uname -s` -ac_sys_release=`uname -r` -# SO is the extension of shared libraries `(including the dot!) -# -- usually .so, .sl on HP-UX -echo $ac_n "checking SO""... $ac_c" 1>&6 -if test -z "$SO" -then - case $ac_sys_system in - hp*|HP*) SO=.sl;; - *) SO=.so;; - esac -fi -echo "$ac_t""$SO" 1>&6 -# LDSHARED is the ld *command* used to create shared library -# -- "ld" on SunOS 4.x.x, "ld -G" on SunOS 5.x, "ld -shared" on IRIX 5 -echo $ac_n "checking LDSHARED""... $ac_c" 1>&6 -if test -z "$LDSHARED" -then - case $ac_sys_system/$ac_sys_release in - IRIX*) LDSHARED="ld -shared";; - SunOS/4*) LDSHARED="ld";; - SunOS/5*) LDSHARED="ld -G";; - hp*|HP*) LDSHARED="ld -b";; - OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";; - DYNIX/ptx*) LDSHARED="ld -G";; - Linux*) LDSHARED="gcc-elf -shared";; - FreeBSD*) LDSHARED="ld -Bshareable";; - *) LDSHARED="ld";; - esac -fi -echo "$ac_t""$LDSHARED" 1>&6 -# CCSHARED are the C *flags* used to create objects to go into a shared -# library -- this is only needed for a few systems -echo $ac_n "checking CCSHARED""... $ac_c" 1>&6 -if test -z "$CCSHARED" -then - case $ac_sys_system in - hp*|HP*) if test "$GCC" = yes; - then CCSHARED="-fpic"; - else CCSHARED="+z"; - fi;; - Linux*) CCSHARED="-fpic";; - FreeBSD*) CCSHARED="-fpic";; - esac -fi -echo "$ac_t""$CCSHARED" 1>&6 -# LINKFORSHARED are the flags passed to the $(CC) command that links -# the python executable -- this is only needed for a few systems -echo $ac_n "checking LINKFORSHARED""... $ac_c" 1>&6 -if test -z "$LINKFORSHARED" -then - case $ac_sys_system in - hp*|HP*) LINKFORSHARED="-Wl,-E";; - Linux*) LINKFORSHARED="-rdynamic";; - esac -fi -echo "$ac_t""$LINKFORSHARED" 1>&6 - -# checks for libraries -echo $ac_n "checking for -ldl""... $ac_c" 1>&6 -ac_lib_var=`echo dl'_'dlopen | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-ldl $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1490 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char dlopen(); - -int main() { return 0; } -int t() { -dlopen() -; return 0; } -EOF -if { (eval echo configure:1502: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - ac_tr_lib=HAVE_LIB`echo dl | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'` - cat >> confdefs.h <<EOF -#define $ac_tr_lib 1 -EOF - - LIBS="-ldl $LIBS" - -else - echo "$ac_t""no" 1>&6 -fi - # Dynamic linking for SunOS/Solaris and SYSV -echo $ac_n "checking for -ldld""... $ac_c" 1>&6 -ac_lib_var=`echo dld'_'shl_load | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-ldld $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1534 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char shl_load(); - -int main() { return 0; } -int t() { -shl_load() -; return 0; } -EOF -if { (eval echo configure:1546: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - ac_tr_lib=HAVE_LIB`echo dld | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'` - cat >> confdefs.h <<EOF -#define $ac_tr_lib 1 -EOF - - LIBS="-ldld $LIBS" - -else - echo "$ac_t""no" 1>&6 -fi - # Dynamic linking for HP-UX -echo $ac_n "checking for -lsun""... $ac_c" 1>&6 -ac_lib_var=`echo sun'_'getpwnam | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-lsun $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1578 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char getpwnam(); - -int main() { return 0; } -int t() { -getpwnam() -; return 0; } -EOF -if { (eval echo configure:1590: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - ac_tr_lib=HAVE_LIB`echo sun | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'` - cat >> confdefs.h <<EOF -#define $ac_tr_lib 1 -EOF - - LIBS="-lsun $LIBS" - -else - echo "$ac_t""no" 1>&6 -fi - # NIS (== YP) interface for IRIX 4 -# The following three (nsl,inet,socket) are needed on Sequent; -# the order of checking must be this. Most SVR4 platforms will -# need -lsocket and -lnsl. However on SGI IRIX 5, these exist but -# broken. I see no elegant solution (probably CHECK_LIB should be -# fixed to only add the library if the given entry point is not -# satisfied without it). -if test "`uname -s`" != IRIX -then -echo $ac_n "checking for -lnsl""... $ac_c" 1>&6 -ac_lib_var=`echo nsl'_'t_open | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-lnsl $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1630 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char t_open(); - -int main() { return 0; } -int t() { -t_open() -; return 0; } -EOF -if { (eval echo configure:1642: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - LIBS="-lnsl $LIBS" -else - echo "$ac_t""no" 1>&6 -fi - # SVR4 -echo $ac_n "checking for -linet""... $ac_c" 1>&6 -ac_lib_var=`echo inet'_'gethostbyname | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-linet -lnsl $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1668 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char gethostbyname(); - -int main() { return 0; } -int t() { -gethostbyname() -; return 0; } -EOF -if { (eval echo configure:1680: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - LIBS="-linet $LIBS" -else - echo "$ac_t""no" 1>&6 -fi - # Sequent -echo $ac_n "checking for -lsocket""... $ac_c" 1>&6 -ac_lib_var=`echo socket'_'socket | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-lsocket $LIBS $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1706 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char socket(); - -int main() { return 0; } -int t() { -socket() -; return 0; } -EOF -if { (eval echo configure:1718: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - LIBS="-lsocket $LIBS" -else - echo "$ac_t""no" 1>&6 -fi - # SVR4 sockets -fi - -# XXX need to check whether libreadline.a actually exists there! -# XXX Also, on some systems, it's libreadline.so... -echo $ac_n "checking for --with-readline""... $ac_c" 1>&6 -# Check whether --with-readline or --without-readline was given. -if test "${with_readline+set}" = set; then - withval="$with_readline" - -echo "$ac_t""$withval" 1>&6 -cat >> confdefs.h <<\EOF -#define WITH_READLINE 1 -EOF - -if test ! -d "$withval" -then { echo "configure: error: proper usage is --with-readline=DIRECTORY" 1>&2; exit 1; } -fi -termcap= -echo $ac_n "checking for -ltermcap""... $ac_c" 1>&6 -ac_lib_var=`echo termcap'_'tgetent | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-ltermcap $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1762 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char tgetent(); - -int main() { return 0; } -int t() { -tgetent() -; return 0; } -EOF -if { (eval echo configure:1774: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - termcap=termcap -else - echo "$ac_t""no" 1>&6 - -echo $ac_n "checking for -ltermlib""... $ac_c" 1>&6 -ac_lib_var=`echo termlib'_'tgetent | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-ltermlib $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1799 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char tgetent(); - -int main() { return 0; } -int t() { -tgetent() -; return 0; } -EOF -if { (eval echo configure:1811: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - termcap=termlib -else - echo "$ac_t""no" 1>&6 -fi - -fi - -if test ! -z "$termcap" -then LIBS="$LIBS $withval/libreadline.a" - # Avoid possible conflict between shared libraries termcap and gl - # on IRIX 5: both contain a routine called clear. - if test -f /usr/lib/lib$termcap.a - then LIBS="$LIBS /usr/lib/lib$termcap.a" - else LIBS="$LIBS -l$termcap" - fi -else { echo "configure: error: no working termcap/termlib" 1>&2; exit 1; } -fi -else - echo "$ac_t""no" 1>&6 -fi - - -echo $ac_n "checking for --with-thread""... $ac_c" 1>&6 -# Check whether --with-thread or --without-thread was given. -if test "${with_thread+set}" = set; then - withval="$with_thread" - -echo "$ac_t""$withval" 1>&6 -if test -d "$withval" -then LIBS="$LIBS -L$withval" -fi -echo $ac_n "checking for -lpthreads""... $ac_c" 1>&6 -ac_lib_var=`echo pthreads'_'pthread_create | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-lpthreads $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1863 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char pthread_create(); - -int main() { return 0; } -int t() { -pthread_create() -; return 0; } -EOF -if { (eval echo configure:1875: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - cat >> confdefs.h <<\EOF -#define WITH_THREAD 1 -EOF - -cat >> confdefs.h <<\EOF -#define _POSIX_THREADS 1 -EOF - -LIBS="$LIBS -lpthreads" -LIBOBJS="$LIBOBJS thread.o" -else - echo "$ac_t""no" 1>&6 -fi - -echo $ac_n "checking for -lmpc""... $ac_c" 1>&6 -ac_lib_var=`echo mpc'_'usconfig | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-lmpc $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1910 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char usconfig(); - -int main() { return 0; } -int t() { -usconfig() -; return 0; } -EOF -if { (eval echo configure:1922: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - cat >> confdefs.h <<\EOF -#define WITH_THREAD 1 -EOF - -LIBS="$LIBS -lmpc" -LIBOBJS="$LIBOBJS thread.o" -else - echo "$ac_t""no" 1>&6 -fi - -echo $ac_n "checking for -lthread""... $ac_c" 1>&6 -ac_lib_var=`echo thread'_'thr_create | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-lthread $LIBS" -cat > conftest.$ac_ext <<EOF -#line 1953 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char thr_create(); - -int main() { return 0; } -int t() { -thr_create() -; return 0; } -EOF -if { (eval echo configure:1965: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - cat >> confdefs.h <<\EOF -#define WITH_THREAD 1 -EOF - -LIBS="$LIBS -lthread" -LIBOBJS="$LIBOBJS thread.o" -else - echo "$ac_t""no" 1>&6 -fi - - -else - echo "$ac_t""no" 1>&6 -fi - - -# -I${DLINCLDIR} is added to the compile rule for importdl.o - -DLINCLDIR=/ - -echo $ac_n "checking for --with-sgi-dl""... $ac_c" 1>&6 -# Check whether --with-sgi-dl or --without-sgi-dl was given. -if test "${with_sgi_dl+set}" = set; then - withval="$with_sgi_dl" - -echo "$ac_t""$withval" 1>&6 -cat >> confdefs.h <<\EOF -#define WITH_SGI_DL 1 -EOF - -dldir=$withval -if test -d "$dldir" -then LIBS="$LIBS -L$dldir" -else { echo "configure: error: proper usage is --with-sgi-dl=DIRECTORY" 1>&2; exit 1; } -fi -DLINCLDIR=${dldir} -LIBS="$LIBS -ldl -lmld" -else - echo "$ac_t""no" 1>&6 -fi - - -echo $ac_n "checking for --with-dl-dld""... $ac_c" 1>&6 -# Check whether --with-dl-dld or --without-dl-dld was given. -if test "${with_dl_dld+set}" = set; then - withval="$with_dl_dld" - -echo "$ac_t""$withval" 1>&6 -cat >> confdefs.h <<\EOF -#define WITH_DL_DLD 1 -EOF - -dldir=`echo "$withval" | sed 's/,.*//'` -dlddir=`echo "$withval" | sed 's/.*,//'` -if test -d "$dldir" -a -d "$dlddir" -then LIBS="$LIBS -L$dldir -L$dlddir" -else { echo "configure: error: proper usage is --with-dl-dld=DL_DIRECTORY" 1>&2; exit 1; } -fi -DLINCLDIR=${dldir} -LIBS="$LIBS -ldl -ldld" -else - echo "$ac_t""no" 1>&6 -fi - - -# checks for library functions -for ac_func in chown clock dlopen ftime ftruncate \ - gethostname_r getpeername getpgrp getpid gettimeofday getwd \ - link lstat mkfifo nice readlink \ - select setgid setuid setsid setpgid setpgrp setvbuf \ - sigaction siginterrupt sigrelse strftime symlink \ - tcgetpgrp tcsetpgrp times truncate uname waitpid -do -echo $ac_n "checking for $ac_func""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 2056 "configure" -#include "confdefs.h" -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func(); below. */ -#include <assert.h> -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char $ac_func(); - -int main() { return 0; } -int t() { - -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined (__stub_$ac_func) || defined (__stub___$ac_func) -choke me -#else -$ac_func(); -#endif - -; return 0; } -EOF -if { (eval echo configure:2080: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_func_$ac_func=yes" -else - rm -rf conftest* - eval "ac_cv_func_$ac_func=no" -fi -rm -f conftest* - -fi -if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then - echo "$ac_t""yes" 1>&6 - ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'` - cat >> confdefs.h <<EOF -#define $ac_tr_func 1 -EOF - -else - echo "$ac_t""no" 1>&6 -fi -done - \ -for ac_func in dup2 getcwd strerror memmove -do -echo $ac_n "checking for $ac_func""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 2109 "configure" -#include "confdefs.h" -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func(); below. */ -#include <assert.h> -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char $ac_func(); - -int main() { return 0; } -int t() { - -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined (__stub_$ac_func) || defined (__stub___$ac_func) -choke me -#else -$ac_func(); -#endif - -; return 0; } -EOF -if { (eval echo configure:2133: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_func_$ac_func=yes" -else - rm -rf conftest* - eval "ac_cv_func_$ac_func=no" -fi -rm -f conftest* - -fi -if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then - echo "$ac_t""yes" 1>&6 - : -else - echo "$ac_t""no" 1>&6 -LIBOBJS="$LIBOBJS ${ac_func}.o" -fi - -done - -echo $ac_n "checking for getpgrp""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_func_getpgrp'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 2158 "configure" -#include "confdefs.h" -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char getpgrp(); below. */ -#include <assert.h> -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char getpgrp(); - -int main() { return 0; } -int t() { - -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined (__stub_getpgrp) || defined (__stub___getpgrp) -choke me -#else -getpgrp(); -#endif - -; return 0; } -EOF -if { (eval echo configure:2182: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_func_getpgrp=yes" -else - rm -rf conftest* - eval "ac_cv_func_getpgrp=no" -fi -rm -f conftest* - -fi -if eval "test \"`echo '$ac_cv_func_'getpgrp`\" = yes"; then - echo "$ac_t""yes" 1>&6 - cat > conftest.$ac_ext <<EOF -#line 2195 "configure" -#include "confdefs.h" -#include <unistd.h> -int main() { return 0; } -int t() { -getpgrp(0); -; return 0; } -EOF -if { (eval echo configure:2203: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - cat >> confdefs.h <<\EOF -#define GETPGRP_HAVE_ARG 1 -EOF - -fi -rm -f conftest* - -else - echo "$ac_t""no" 1>&6 -fi - -echo $ac_n "checking for setpgrp""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_func_setpgrp'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 2221 "configure" -#include "confdefs.h" -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char setpgrp(); below. */ -#include <assert.h> -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char setpgrp(); - -int main() { return 0; } -int t() { - -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined (__stub_setpgrp) || defined (__stub___setpgrp) -choke me -#else -setpgrp(); -#endif - -; return 0; } -EOF -if { (eval echo configure:2245: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_func_setpgrp=yes" -else - rm -rf conftest* - eval "ac_cv_func_setpgrp=no" -fi -rm -f conftest* - -fi -if eval "test \"`echo '$ac_cv_func_'setpgrp`\" = yes"; then - echo "$ac_t""yes" 1>&6 - cat > conftest.$ac_ext <<EOF -#line 2258 "configure" -#include "confdefs.h" -#include <unistd.h> -int main() { return 0; } -int t() { -setpgrp(0,0); -; return 0; } -EOF -if { (eval echo configure:2266: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - cat >> confdefs.h <<\EOF -#define SETPGRP_HAVE_ARG 1 -EOF - -fi -rm -f conftest* - -else - echo "$ac_t""no" 1>&6 -fi - -echo $ac_n "checking for gettimeofday""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_func_gettimeofday'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 2284 "configure" -#include "confdefs.h" -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char gettimeofday(); below. */ -#include <assert.h> -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char gettimeofday(); - -int main() { return 0; } -int t() { - -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined (__stub_gettimeofday) || defined (__stub___gettimeofday) -choke me -#else -gettimeofday(); -#endif - -; return 0; } -EOF -if { (eval echo configure:2308: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_func_gettimeofday=yes" -else - rm -rf conftest* - eval "ac_cv_func_gettimeofday=no" -fi -rm -f conftest* - -fi -if eval "test \"`echo '$ac_cv_func_'gettimeofday`\" = yes"; then - echo "$ac_t""yes" 1>&6 - cat > conftest.$ac_ext <<EOF -#line 2321 "configure" -#include "confdefs.h" -#include <sys/time.h> -int main() { return 0; } -int t() { -gettimeofday((struct timeval*)0,(struct timezone*)0); -; return 0; } -EOF -if { (eval echo configure:2329: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - : -else - rm -rf conftest* - cat >> confdefs.h <<\EOF -#define GETTIMEOFDAY_NO_TZ 1 -EOF - -fi -rm -f conftest* - -else - echo "$ac_t""no" 1>&6 -fi - - -# checks for structures -echo $ac_n "checking whether time.h and sys/time.h may both be included""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_header_time'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 2351 "configure" -#include "confdefs.h" -#include <sys/types.h> -#include <sys/time.h> -#include <time.h> -int main() { return 0; } -int t() { -struct tm *tp; -; return 0; } -EOF -if { (eval echo configure:2361: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - ac_cv_header_time=yes -else - rm -rf conftest* - ac_cv_header_time=no -fi -rm -f conftest* - -fi - -echo "$ac_t""$ac_cv_header_time" 1>&6 -if test $ac_cv_header_time = yes; then - cat >> confdefs.h <<\EOF -#define TIME_WITH_SYS_TIME 1 -EOF - -fi - -echo $ac_n "checking whether struct tm is in sys/time.h or time.h""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_struct_tm'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 2385 "configure" -#include "confdefs.h" -#include <sys/types.h> -#include <time.h> -int main() { return 0; } -int t() { -struct tm *tp; tp->tm_sec; -; return 0; } -EOF -if { (eval echo configure:2394: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - ac_cv_struct_tm=time.h -else - rm -rf conftest* - ac_cv_struct_tm=sys/time.h -fi -rm -f conftest* - -fi - -echo "$ac_t""$ac_cv_struct_tm" 1>&6 -if test $ac_cv_struct_tm = sys/time.h; then - cat >> confdefs.h <<\EOF -#define TM_IN_SYS_TIME 1 -EOF - -fi - -echo $ac_n "checking for tm_zone in struct tm""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_struct_tm_zone'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 2418 "configure" -#include "confdefs.h" -#include <sys/types.h> -#include <$ac_cv_struct_tm> -int main() { return 0; } -int t() { -struct tm tm; tm.tm_zone; -; return 0; } -EOF -if { (eval echo configure:2427: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - ac_cv_struct_tm_zone=yes -else - rm -rf conftest* - ac_cv_struct_tm_zone=no -fi -rm -f conftest* - -fi - -echo "$ac_t""$ac_cv_struct_tm_zone" 1>&6 -if test "$ac_cv_struct_tm_zone" = yes; then - cat >> confdefs.h <<\EOF -#define HAVE_TM_ZONE 1 -EOF - -else - echo $ac_n "checking for tzname""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_var_tzname'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 2450 "configure" -#include "confdefs.h" -#include <time.h> -#ifndef tzname /* For SGI. */ -extern char *tzname[]; /* RS6000 and others reject char **tzname. */ -#endif -int main() { return 0; } -int t() { -atoi(*tzname); -; return 0; } -EOF -if { (eval echo configure:2461: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - ac_cv_var_tzname=yes -else - rm -rf conftest* - ac_cv_var_tzname=no -fi -rm -f conftest* - -fi - -echo "$ac_t""$ac_cv_var_tzname" 1>&6 - if test $ac_cv_var_tzname = yes; then - cat >> confdefs.h <<\EOF -#define HAVE_TZNAME 1 -EOF - - fi -fi - - -echo $ac_n "checking for time.h that defines altzone""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_header_time_altzone'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 2487 "configure" -#include "confdefs.h" -#include <time.h> -int main() { return 0; } -int t() { -return altzone; -; return 0; } -EOF -if { (eval echo configure:2495: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - ac_cv_header_time_altzone=yes -else - rm -rf conftest* - ac_cv_header_time_altzone=no -fi -rm -f conftest* - -fi - -echo "$ac_t""$ac_cv_header_time_altzone" 1>&6 -if test $ac_cv_header_time_altzone = yes; then - cat >> confdefs.h <<\EOF -#define HAVE_ALTZONE 1 -EOF - -fi - -was_it_defined=no -echo $ac_n "checking whether sys/select.h and sys/time.h may both be included""... $ac_c" 1>&6 -cat > conftest.$ac_ext <<EOF -#line 2517 "configure" -#include "confdefs.h" - -#include <sys/types.h> -#include <sys/select.h> -#include <sys/time.h> - -int main() { return 0; } -int t() { -; -; return 0; } -EOF -if { (eval echo configure:2529: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - cat >> confdefs.h <<\EOF -#define SYS_SELECT_WITH_SYS_TIME 1 -EOF - was_it_defined=yes -fi -rm -f conftest* - -echo "$ac_t""$was_it_defined" 1>&6 - -# checks for compiler characteristics - -echo $ac_n "checking whether char is unsigned""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_c_char_unsigned'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - if test "$GCC" = yes; then - # GCC predefines this symbol on systems where it applies. -cat > conftest.$ac_ext <<EOF -#line 2549 "configure" -#include "confdefs.h" -#ifdef __CHAR_UNSIGNED__ - yes -#endif - -EOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - egrep "yes" >/dev/null 2>&1; then - rm -rf conftest* - ac_cv_c_char_unsigned=yes -else - rm -rf conftest* - ac_cv_c_char_unsigned=no -fi -rm -f conftest* - -else -if test "$cross_compiling" = yes; then - { echo "configure: error: can not run test program while cross compiling" 1>&2; exit 1; } -else -cat > conftest.$ac_ext <<EOF -#line 2571 "configure" -#include "confdefs.h" -/* volatile prevents gcc2 from optimizing the test away on sparcs. */ -#if !defined(__STDC__) || __STDC__ != 1 -#define volatile -#endif -main() { - volatile char c = 255; exit(c < 0); -} -EOF -{ (eval echo configure:2581: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } -if test -s conftest && (./conftest; exit) 2>/dev/null; then - ac_cv_c_char_unsigned=yes -else - ac_cv_c_char_unsigned=no -fi -fi -rm -fr conftest* -fi -fi - -echo "$ac_t""$ac_cv_c_char_unsigned" 1>&6 -if test $ac_cv_c_char_unsigned = yes && test "$GCC" != yes; then - cat >> confdefs.h <<\EOF -#define __CHAR_UNSIGNED__ 1 -EOF - -fi - - -echo $ac_n "checking for working const""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_c_const'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 2606 "configure" -#include "confdefs.h" - -int main() { return 0; } -int t() { - -/* Ultrix mips cc rejects this. */ -typedef int charset[2]; const charset x; -/* SunOS 4.1.1 cc rejects this. */ -char const *const *ccp; -char **p; -/* NEC SVR4.0.2 mips cc rejects this. */ -struct point {int x, y;}; -static struct point const zero = {0,0}; -/* AIX XL C 1.02.0.0 rejects this. - It does not let you subtract one const X* pointer from another in an arm - of an if-expression whose if-part is not a constant expression */ -const char *g = "string"; -ccp = &g + (g ? g-g : 0); -/* HPUX 7.0 cc rejects these. */ -++ccp; -p = (char**) ccp; -ccp = (char const *const *) p; -{ /* SCO 3.2v4 cc rejects this. */ - char *t; - char const *s = 0 ? (char *) 0 : (char const *) 0; - - *t++ = 0; -} -{ /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ - int x[] = {25, 17}; - const int *foo = &x[0]; - ++foo; -} -{ /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ - typedef const int *iptr; - iptr p = 0; - ++p; -} -{ /* AIX XL C 1.02.0.0 rejects this saying - "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ - struct s { int j; const int *ap[3]; }; - struct s *b; b->j = 5; -} -{ /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ - const int foo = 10; -} - -; return 0; } -EOF -if { (eval echo configure:2656: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - ac_cv_c_const=yes -else - rm -rf conftest* - ac_cv_c_const=no -fi -rm -f conftest* - -fi - -echo "$ac_t""$ac_cv_c_const" 1>&6 -if test $ac_cv_c_const = no; then - cat >> confdefs.h <<\EOF -#define const -EOF - -fi - - -works=no -echo $ac_n "checking for working volatile""... $ac_c" 1>&6 -cat > conftest.$ac_ext <<EOF -#line 2679 "configure" -#include "confdefs.h" - -int main() { return 0; } -int t() { -volatile int x; x = 0; -; return 0; } -EOF -if { (eval echo configure:2687: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - works=yes -else - rm -rf conftest* - cat >> confdefs.h <<\EOF -#define volatile -EOF - -fi -rm -f conftest* - -echo "$ac_t""$works" 1>&6 - -works=no -echo $ac_n "checking for working signed char""... $ac_c" 1>&6 -cat > conftest.$ac_ext <<EOF -#line 2704 "configure" -#include "confdefs.h" - -int main() { return 0; } -int t() { -signed char c; -; return 0; } -EOF -if { (eval echo configure:2712: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - works=yes -else - rm -rf conftest* - cat >> confdefs.h <<\EOF -#define signed -EOF - -fi -rm -f conftest* - -echo "$ac_t""$works" 1>&6 - -have_prototypes=no -echo $ac_n "checking for prototypes""... $ac_c" 1>&6 -cat > conftest.$ac_ext <<EOF -#line 2729 "configure" -#include "confdefs.h" -int foo(int x) { return 0; } -int main() { return 0; } -int t() { -return foo(10); -; return 0; } -EOF -if { (eval echo configure:2737: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - cat >> confdefs.h <<\EOF -#define HAVE_PROTOTYPES 1 -EOF - have_prototypes=yes -fi -rm -f conftest* - -echo "$ac_t""$have_prototypes" 1>&6 - -works=no -echo $ac_n "checking for variable length prototypes and stdarg.h""... $ac_c" 1>&6 -cat > conftest.$ac_ext <<EOF -#line 2751 "configure" -#include "confdefs.h" - -#include <stdarg.h> -int foo(int x, ...) { return 0; } - -int main() { return 0; } -int t() { -return foo(10, 11, 12); -; return 0; } -EOF -if { (eval echo configure:2762: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - rm -rf conftest* - cat >> confdefs.h <<\EOF -#define HAVE_STDARG_PROTOTYPES 1 -EOF - works=yes -fi -rm -f conftest* - -echo "$ac_t""$works" 1>&6 - -if test "$have_prototypes" = yes; then -bad_prototypes=no -echo $ac_n "checking for bad exec* prototypes""... $ac_c" 1>&6 -cat > conftest.$ac_ext <<EOF -#line 2777 "configure" -#include "confdefs.h" -#include <unistd.h> -int main() { return 0; } -int t() { -char **t;execve("@",t,t); -; return 0; } -EOF -if { (eval echo configure:2785: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - : -else - rm -rf conftest* - cat >> confdefs.h <<\EOF -#define BAD_EXEC_PROTOTYPES 1 -EOF - bad_prototypes=yes -fi -rm -f conftest* - -echo "$ac_t""$bad_prototypes" 1>&6 -fi - -bad_forward=no -echo $ac_n "checking for bad static forward""... $ac_c" 1>&6 -if test "$cross_compiling" = yes; then - { echo "configure: error: can not run test program while cross compiling" 1>&2; exit 1; } -else -cat > conftest.$ac_ext <<EOF -#line 2805 "configure" -#include "confdefs.h" - -struct s { int a; int b; }; -static struct s foo; -int foobar() { - static int random; - random = (int) &foo; - return random; -} -static struct s foo = { 1, 2 }; -main() { - exit(!((int)&foo == foobar())); -} - -EOF -{ (eval echo configure:2821: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } -if test -s conftest && (./conftest; exit) 2>/dev/null; then - : -else - cat >> confdefs.h <<\EOF -#define BAD_STATIC_FORWARD 1 -EOF - bad_forward=yes -fi -fi -rm -fr conftest* -echo "$ac_t""$bad_forward" 1>&6 - -va_list_is_array=no -echo $ac_n "checking whether va_list is an array""... $ac_c" 1>&6 -cat > conftest.$ac_ext <<EOF -#line 2837 "configure" -#include "confdefs.h" - -#ifdef HAVE_STDARG_PROTOTYPES -#include <stdarg.h> -#else -#include <varargs.h> -#endif - -int main() { return 0; } -int t() { -va_list list1, list2; list1 = list2; -; return 0; } -EOF -if { (eval echo configure:2851: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then - : -else - rm -rf conftest* - cat >> confdefs.h <<\EOF -#define VA_LIST_IS_ARRAY 1 -EOF - va_list_is_array=yes -fi -rm -f conftest* - -echo "$ac_t""$va_list_is_array" 1>&6 - -# checks for system services -# (none yet) - -# Linux requires this for correct f.p. operations -echo $ac_n "checking for -lieee""... $ac_c" 1>&6 -ac_lib_var=`echo ieee'_'__fpu_control | tr './+\055' '__p_'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-lieee $LIBS" -cat > conftest.$ac_ext <<EOF -#line 2876 "configure" -#include "confdefs.h" -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char __fpu_control(); - -int main() { return 0; } -int t() { -__fpu_control() -; return 0; } -EOF -if { (eval echo configure:2888: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - ac_tr_lib=HAVE_LIB`echo ieee | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'` - cat >> confdefs.h <<EOF -#define $ac_tr_lib 1 -EOF - - LIBS="-lieee $LIBS" - -else - echo "$ac_t""no" 1>&6 -fi - - -# check for --with-libm=... - -LIBM=-lm -# Check whether --with-libm or --without-libm was given. -if test "${with_libm+set}" = set; then - withval="$with_libm" - -if test "$withval" != yes -then LIBM=$withval -else { echo "configure: error: proper usage is --with-libm=STRING" 1>&2; exit 1; } -fi -fi - - -# check for --with-libc=... - -# Check whether --with-libc or --without-libc was given. -if test "${with_libc+set}" = set; then - withval="$with_libc" - -if test "$withval" != yes -then LIBC=$withval -else { echo "configure: error: proper usage is --with-libc=STRING" 1>&2; exit 1; } -fi -fi - - -# check for hypot() in math library -LIBS_SAVE=$LIBS -LIBS="$LIBS $LIBM" -for ac_func in hypot -do -echo $ac_n "checking for $ac_func""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <<EOF -#line 2950 "configure" -#include "confdefs.h" -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func(); below. */ -#include <assert.h> -/* Override any gcc2 internal prototype to avoid an error. */ -/* We use char because int might match the return type of a gcc2 - builtin and then its argument prototype would still apply. */ -char $ac_func(); - -int main() { return 0; } -int t() { - -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined (__stub_$ac_func) || defined (__stub___$ac_func) -choke me -#else -$ac_func(); -#endif - -; return 0; } -EOF -if { (eval echo configure:2974: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then - rm -rf conftest* - eval "ac_cv_func_$ac_func=yes" -else - rm -rf conftest* - eval "ac_cv_func_$ac_func=no" -fi -rm -f conftest* - -fi -if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then - echo "$ac_t""yes" 1>&6 - ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'` - cat >> confdefs.h <<EOF -#define $ac_tr_func 1 -EOF - -else - echo "$ac_t""no" 1>&6 -fi -done - -LIBS=$LIBS_SAVE - -# check for getopt -echo $ac_n "checking for genuine getopt""... $ac_c" 1>&6 -if eval "test \"`echo '$''{'ac_cv_func_getopt'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - if test "$cross_compiling" = yes; then - ac_cv_func_getopt=no -else -cat > conftest.$ac_ext <<EOF -#line 3007 "configure" -#include "confdefs.h" -#include <stdio.h> -extern int optind, opterr, getopt(); -extern char* optarg; -int main() { - char* av[] = { "testprog", "parameter", "-fFlag", NULL }; - opterr = 0; - if (getopt(3, av, "f:") == 'f') { exit(1); } - exit(0); -} -EOF -{ (eval echo configure:3019: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } -if test -s conftest && (./conftest; exit) 2>/dev/null; then - ac_cv_func_getopt=yes -else - ac_cv_func_getopt=no -fi -fi -rm -fr conftest* -fi -echo "$ac_t""$ac_cv_func_getopt" 1>&6 -test $ac_cv_func_getopt = no && LIBOBJS="$LIBOBJS getopt.o" - -# generate output files -trap '' 1 2 15 -cat > confcache <<\EOF -# This file is a shell script that caches the results of configure -# tests run on this system so they can be shared between configure -# scripts and configure runs. It is not useful on other systems. -# If it contains results you don't want to keep, you may remove or edit it. -# -# By default, configure uses ./config.cache as the cache file, -# creating it if it does not exist already. You can give configure -# the --cache-file=FILE option to use a different cache file; that is -# what configure does when it calls configure scripts in -# subdirectories, so they share the cache. -# Giving --cache-file=/dev/null disables caching, for debugging configure. -# config.status only pays attention to the cache file if you give it the -# --recheck option to rerun configure. -# -EOF -# Ultrix sh set writes to stderr and can't be redirected directly, -# and sets the high bit in the cache file unless we assign to the vars. -(set) 2>&1 | - sed -n "s/^\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\)=\(.*\)/\1=\${\1='\2'}/p" \ - >> confcache -if cmp -s $cache_file confcache; then - : -else - if test -w $cache_file; then - echo "updating cache $cache_file" - cat confcache > $cache_file - else - echo "not updating unwritable cache $cache_file" - fi -fi -rm -f confcache - -trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15 - -test "x$prefix" = xNONE && prefix=$ac_default_prefix -# Let make expand exec_prefix. -test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' - -# Any assignment to VPATH causes Sun make to only execute -# the first set of double-colon rules, so remove it if not needed. -# If there is a colon in the path, we need to keep it. -if test "x$srcdir" = x.; then - ac_vpsub='/^[ ]*VPATH[ ]*=[^:]*$/d' -fi - -trap 'rm -f $CONFIG_STATUS conftest*; exit 1' 1 2 15 - -DEFS=-DHAVE_CONFIG_H - -# Without the "./", some shells look in PATH for config.status. -: ${CONFIG_STATUS=./config.status} - -echo creating $CONFIG_STATUS -rm -f $CONFIG_STATUS -cat > $CONFIG_STATUS <<EOF -#! /bin/sh -# Generated automatically by configure. -# Run this file to recreate the current configuration. -# This directory was configured as follows, -# on host `(hostname || uname -n) 2>/dev/null | sed 1q`: -# -# $0 $ac_configure_args -# -# Compiler output produced by configure, useful for debugging -# configure, is in ./config.log if it exists. - -ac_cs_usage="Usage: $CONFIG_STATUS [--recheck] [--version] [--help]" -for ac_option -do - case "\$ac_option" in - -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) - echo "running \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion" - exec \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion ;; - -version | --version | --versio | --versi | --vers | --ver | --ve | --v) - echo "$CONFIG_STATUS generated by autoconf version 2.10" - exit 0 ;; - -help | --help | --hel | --he | --h) - echo "\$ac_cs_usage"; exit 0 ;; - *) echo "\$ac_cs_usage"; exit 1 ;; - esac -done - -ac_given_srcdir=$srcdir - -trap 'rm -fr `echo "Makefile Objects/Makefile Parser/Makefile Python/Makefile Modules/Makefile.pre config.h" | sed "s/:[^ ]*//g"` conftest*; exit 1' 1 2 15 -EOF -cat >> $CONFIG_STATUS <<EOF - -# Protect against being on the right side of a sed subst in config.status. -sed 's/%@/@@/; s/@%/@@/; s/%g\$/@g/; /@g\$/s/[\\\\&%]/\\\\&/g; - s/@@/%@/; s/@@/@%/; s/@g\$/%g/' > conftest.subs <<\\CEOF -$ac_vpsub -$extrasub -s%@CFLAGS@%$CFLAGS%g -s%@CPPFLAGS@%$CPPFLAGS%g -s%@CXXFLAGS@%$CXXFLAGS%g -s%@DEFS@%$DEFS%g -s%@LDFLAGS@%$LDFLAGS%g -s%@LIBS@%$LIBS%g -s%@exec_prefix@%$exec_prefix%g -s%@prefix@%$prefix%g -s%@program_transform_name@%$program_transform_name%g -s%@bindir@%$bindir%g -s%@sbindir@%$sbindir%g -s%@libexecdir@%$libexecdir%g -s%@datadir@%$datadir%g -s%@sysconfdir@%$sysconfdir%g -s%@sharedstatedir@%$sharedstatedir%g -s%@localstatedir@%$localstatedir%g -s%@libdir@%$libdir%g -s%@includedir@%$includedir%g -s%@oldincludedir@%$oldincludedir%g -s%@infodir@%$infodir%g -s%@mandir@%$mandir%g -s%@CC@%$CC%g -s%@RANLIB@%$RANLIB%g -s%@AR@%$AR%g -s%@INSTALL@%$INSTALL%g -s%@INSTALL_PROGRAM@%$INSTALL_PROGRAM%g -s%@INSTALL_DATA@%$INSTALL_DATA%g -s%@OPT@%$OPT%g -s%@CPP@%$CPP%g -s%@MACHDEP@%$MACHDEP%g -s%@SO@%$SO%g -s%@LDSHARED@%$LDSHARED%g -s%@CCSHARED@%$CCSHARED%g -s%@LINKFORSHARED@%$LINKFORSHARED%g -s%@DLINCLDIR@%$DLINCLDIR%g -s%@LIBOBJS@%$LIBOBJS%g -s%@LIBM@%$LIBM%g -s%@LIBC@%$LIBC%g - -CEOF -EOF -cat >> $CONFIG_STATUS <<EOF - -CONFIG_FILES=\${CONFIG_FILES-"Makefile Objects/Makefile Parser/Makefile Python/Makefile Modules/Makefile.pre"} -EOF -cat >> $CONFIG_STATUS <<\EOF -for ac_file in .. $CONFIG_FILES; do if test "x$ac_file" != x..; then - # Support "outfile[:infile]", defaulting infile="outfile.in". - case "$ac_file" in - *:*) ac_file_in=`echo "$ac_file"|sed 's%.*:%%'` - ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;; - *) ac_file_in="${ac_file}.in" ;; - esac - - # Adjust relative srcdir, etc. for subdirectories. - - # Remove last slash and all that follows it. Not all systems have dirname. - ac_dir=`echo $ac_file|sed 's%/[^/][^/]*$%%'` - if test "$ac_dir" != "$ac_file" && test "$ac_dir" != .; then - # The file is in a subdirectory. - test ! -d "$ac_dir" && mkdir "$ac_dir" - ac_dir_suffix="/`echo $ac_dir|sed 's%^\./%%'`" - # A "../" for each directory in $ac_dir_suffix. - ac_dots=`echo $ac_dir_suffix|sed 's%/[^/]*%../%g'` - else - ac_dir_suffix= ac_dots= - fi - - case "$ac_given_srcdir" in - .) srcdir=. - if test -z "$ac_dots"; then top_srcdir=. - else top_srcdir=`echo $ac_dots|sed 's%/$%%'`; fi ;; - /*) srcdir="$ac_given_srcdir$ac_dir_suffix"; top_srcdir="$ac_given_srcdir" ;; - *) # Relative path. - srcdir="$ac_dots$ac_given_srcdir$ac_dir_suffix" - top_srcdir="$ac_dots$ac_given_srcdir" ;; - esac - - echo creating "$ac_file" - rm -f "$ac_file" - configure_input="Generated automatically from `echo $ac_file_in|sed 's%.*/%%'` by configure." - case "$ac_file" in - *Makefile*) ac_comsub="1i\\ -# $configure_input" ;; - *) ac_comsub= ;; - esac - sed -e "$ac_comsub -s%@configure_input@%$configure_input%g -s%@srcdir@%$srcdir%g -s%@top_srcdir@%$top_srcdir%g -" -f conftest.subs $ac_given_srcdir/$ac_file_in > $ac_file -fi; done -rm -f conftest.subs - -# These sed commands are passed to sed as "A NAME B NAME C VALUE D", where -# NAME is the cpp macro being defined and VALUE is the value it is being given. -# -# ac_d sets the value in "#define NAME VALUE" lines. -ac_dA='s%^\([ ]*\)#\([ ]*define[ ][ ]*\)' -ac_dB='\([ ][ ]*\)[^ ]*%\1#\2' -ac_dC='\3' -ac_dD='%g' -# ac_u turns "#undef NAME" with trailing blanks into "#define NAME VALUE". -ac_uA='s%^\([ ]*\)#\([ ]*\)undef\([ ][ ]*\)' -ac_uB='\([ ]\)%\1#\2define\3' -ac_uC=' ' -ac_uD='\4%g' -# ac_e turns "#undef NAME" without trailing blanks into "#define NAME VALUE". -ac_eA='s%^\([ ]*\)#\([ ]*\)undef\([ ][ ]*\)' -ac_eB='$%\1#\2define\3' -ac_eC=' ' -ac_eD='%g' - -CONFIG_HEADERS=${CONFIG_HEADERS-"config.h"} -for ac_file in .. $CONFIG_HEADERS; do if test "x$ac_file" != x..; then - # Support "outfile[:infile]", defaulting infile="outfile.in". - case "$ac_file" in - *:*) ac_file_in=`echo "$ac_file"|sed 's%.*:%%'` - ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;; - *) ac_file_in="${ac_file}.in" ;; - esac - - echo creating $ac_file - - rm -f conftest.frag conftest.in conftest.out - cp $ac_given_srcdir/$ac_file_in conftest.in - -EOF - -# Transform confdefs.h into a sed script conftest.vals that substitutes -# the proper values into config.h.in to produce config.h. And first: -# Protect against being on the right side of a sed subst in config.status. -# Protect against being in an unquoted here document in config.status. -rm -f conftest.vals -cat > conftest.hdr <<\EOF -s/[\\&%]/\\&/g -s%[\\$`]%\\&%g -s%#define \([A-Za-z_][A-Za-z0-9_]*\) *\(.*\)%${ac_dA}\1${ac_dB}\1${ac_dC}\2${ac_dD}%gp -s%ac_d%ac_u%gp -s%ac_u%ac_e%gp -EOF -sed -n -f conftest.hdr confdefs.h > conftest.vals -rm -f conftest.hdr - -# This sed command replaces #undef with comments. This is necessary, for -# example, in the case of _POSIX_SOURCE, which is predefined and required -# on some systems where configure will not decide to define it. -cat >> conftest.vals <<\EOF -s%^[ ]*#[ ]*undef[ ][ ]*[a-zA-Z_][a-zA-Z_0-9]*%/* & */% -EOF - -# Break up conftest.vals because some shells have a limit on -# the size of here documents, and old seds have small limits too. -# Maximum number of lines to put in a single here document. -ac_max_here_lines=12 - -rm -f conftest.tail -while : -do - ac_lines=`grep -c . conftest.vals` - # grep -c gives empty output for an empty file on some AIX systems. - if test -z "$ac_lines" || test "$ac_lines" -eq 0; then break; fi - # Write a limited-size here document to conftest.frag. - echo ' cat > conftest.frag <<CEOF' >> $CONFIG_STATUS - sed ${ac_max_here_lines}q conftest.vals >> $CONFIG_STATUS - echo 'CEOF - sed -f conftest.frag conftest.in > conftest.out - rm -f conftest.in - mv conftest.out conftest.in -' >> $CONFIG_STATUS - sed 1,${ac_max_here_lines}d conftest.vals > conftest.tail - rm -f conftest.vals - mv conftest.tail conftest.vals -done -rm -f conftest.vals - -cat >> $CONFIG_STATUS <<\EOF - rm -f conftest.frag conftest.h - echo "/* $ac_file. Generated automatically by configure. */" > conftest.h - cat conftest.in >> conftest.h - rm -f conftest.in - if cmp -s $ac_file conftest.h 2>/dev/null; then - echo "$ac_file is unchanged" - rm -f conftest.h - else - # Remove last slash and all that follows it. Not all systems have dirname. - ac_dir=`echo $ac_file|sed 's%/[^/][^/]*$%%'` - if test "$ac_dir" != "$ac_file" && test "$ac_dir" != .; then - # The file is in a subdirectory. - test ! -d "$ac_dir" && mkdir "$ac_dir" - fi - rm -f $ac_file - mv conftest.h $ac_file - fi -fi; done - - - -exit 0 -EOF -chmod +x $CONFIG_STATUS -rm -fr confdefs* $ac_clean_files -test "$no_create" = yes || ${CONFIG_SHELL-/bin/sh} $CONFIG_STATUS || exit 1 - diff --git a/configure.in b/configure.in deleted file mode 100644 index e30c7e7692..0000000000 --- a/configure.in +++ /dev/null @@ -1,395 +0,0 @@ -dnl Process this file with autoconf 2.0 or later to make a configure script. -AC_REVISION($Revision$) -AC_PREREQ(2.0) -AC_INIT(Include/object.h) -AC_CONFIG_HEADER(config.h) - -# checks for alternative programs -AC_MSG_CHECKING(for --without-gcc) -AC_ARG_WITH(gcc, [--without-gcc never use gcc], [ - case $withval in - no) CC=cc - without_gcc=yes;; - yes) CC=gcc - without_gcc=no;; - *) CC=$withval - without_gcc=$withval;; - esac], [ - case `uname -s` in - OSF1) CC=cc - without_gcc=;; - *) without_gcc=no;; - esac]) -AC_MSG_RESULT($without_gcc) - -# If the user switches compilers, we can't believe the cache -if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC" -then - AC_ERROR(cached CC is different -- throw away $cache_file -(it is also a good idea to do 'make clean' before compiling)) -fi - -AC_PROG_CC -AC_PROG_RANLIB -AC_SUBST(AR) -AC_CHECK_PROGS(AR, ar aal, ar) -AC_SUBST(INSTALL) -AC_SUBST(INSTALL_PROGRAM) -AC_SUBST(INSTALL_DATA) -# Install just never works :-( -if test -z "$INSTALL" -then - INSTALL=cp - INSTALL_PROGRAM=cp - INSTALL_DATA=cp -else - INSTALL_PROGRAM="$INSTALL" - INSTALL_DATA="$INSTALL -m 644" -fi -AC_SUBST(OPT) -# Optimizer/debugger flags passed between Makefiles -if test -z "$OPT" -then OPT=-O -fi - -# checks for UNIX variants that set C preprocessor variables -AC_AIX -AC_MINIX - -# checks for header files -AC_HEADER_STDC -AC_CHECK_HEADERS(dlfcn.h fcntl.h limits.h ncurses.h signal.h stdarg.h stddef.h stdlib.h thread.h unistd.h utime.h sys/audioio.h sys/param.h sys/select.h sys/time.h sys/times.h sys/un.h sys/utsname.h sys/wait.h) -AC_HEADER_DIRENT - -# checks for typedefs -was_it_defined=no -AC_MSG_CHECKING(for clock_t in time.h) -AC_EGREP_HEADER(clock_t, time.h, was_it_defined=yes, AC_DEFINE(clock_t, long)) -AC_MSG_RESULT($was_it_defined) - -AC_TYPE_MODE_T -AC_TYPE_OFF_T -AC_TYPE_PID_T -AC_TYPE_SIGNAL -AC_TYPE_SIZE_T -AC_TYPE_UID_T - -# Set name for machine-dependent library files -AC_SUBST(MACHDEP) -AC_MSG_CHECKING(MACHDEP) -if test -z "$MACHDEP" -then - ac_sys_system=`uname -s | tr -d '[/ ]' | tr '[[A-Z]]' '[[a-z]]'` - ac_sys_release=`uname -r | tr -d '[/ ]' | sed 's/\..*//'` - ac_sys_cpu=`(uname -p 2>/dev/null || uname -m) | - tr '[[A-Z]]' '[[a-z]]'` -## MACHDEP="$ac_sys_system$ac_sys_release$ac_sys_cpu" - MACHDEP="$ac_sys_system$ac_sys_release" - case MACHDEP in - '') MACHDEP=unknown;; - esac -fi -AC_MSG_RESULT($MACHDEP) - -# Set info about shared libraries. -# XXX This should try things out instead of testing uname! -AC_SUBST(SO) -AC_SUBST(LDSHARED) -AC_SUBST(CCSHARED) -AC_SUBST(LINKFORSHARED) -ac_sys_system=`uname -s` -ac_sys_release=`uname -r` -# SO is the extension of shared libraries `(including the dot!) -# -- usually .so, .sl on HP-UX -AC_MSG_CHECKING(SO) -if test -z "$SO" -then - case $ac_sys_system in - hp*|HP*) SO=.sl;; - *) SO=.so;; - esac -fi -AC_MSG_RESULT($SO) -# LDSHARED is the ld *command* used to create shared library -# -- "ld" on SunOS 4.x.x, "ld -G" on SunOS 5.x, "ld -shared" on IRIX 5 -AC_MSG_CHECKING(LDSHARED) -if test -z "$LDSHARED" -then - case $ac_sys_system/$ac_sys_release in - IRIX*) LDSHARED="ld -shared";; - SunOS/4*) LDSHARED="ld";; - SunOS/5*) LDSHARED="ld -G";; - hp*|HP*) LDSHARED="ld -b";; - OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";; - DYNIX/ptx*) LDSHARED="ld -G";; - Linux*) LDSHARED="gcc-elf -shared";; - FreeBSD*) LDSHARED="ld -Bshareable";; - *) LDSHARED="ld";; - esac -fi -AC_MSG_RESULT($LDSHARED) -# CCSHARED are the C *flags* used to create objects to go into a shared -# library -- this is only needed for a few systems -AC_MSG_CHECKING(CCSHARED) -if test -z "$CCSHARED" -then - case $ac_sys_system in - hp*|HP*) if test "$GCC" = yes; - then CCSHARED="-fpic"; - else CCSHARED="+z"; - fi;; - Linux*) CCSHARED="-fpic";; - FreeBSD*) CCSHARED="-fpic";; - esac -fi -AC_MSG_RESULT($CCSHARED) -# LINKFORSHARED are the flags passed to the $(CC) command that links -# the python executable -- this is only needed for a few systems -AC_MSG_CHECKING(LINKFORSHARED) -if test -z "$LINKFORSHARED" -then - case $ac_sys_system in - hp*|HP*) LINKFORSHARED="-Wl,-E";; - Linux*) LINKFORSHARED="-rdynamic";; - esac -fi -AC_MSG_RESULT($LINKFORSHARED) - -# checks for libraries -AC_CHECK_LIB(dl, dlopen) # Dynamic linking for SunOS/Solaris and SYSV -AC_CHECK_LIB(dld, shl_load) # Dynamic linking for HP-UX -AC_CHECK_LIB(sun, getpwnam) # NIS (== YP) interface for IRIX 4 -# The following three (nsl,inet,socket) are needed on Sequent; -# the order of checking must be this. Most SVR4 platforms will -# need -lsocket and -lnsl. However on SGI IRIX 5, these exist but -# broken. I see no elegant solution (probably CHECK_LIB should be -# fixed to only add the library if the given entry point is not -# satisfied without it). -if test "`uname -s`" != IRIX -then -AC_CHECK_LIB(nsl, t_open, [LIBS="-lnsl $LIBS"]) # SVR4 -AC_CHECK_LIB(inet, gethostbyname, [LIBS="-linet $LIBS"], [], -lnsl) # Sequent -AC_CHECK_LIB(socket, socket, [LIBS="-lsocket $LIBS"], [], $LIBS) # SVR4 sockets -fi - -# XXX need to check whether libreadline.a actually exists there! -# XXX Also, on some systems, it's libreadline.so... -AC_MSG_CHECKING(for --with-readline) -AC_ARG_WITH(readline, [--with-readline=DIRECTORY GNU readline], [ -AC_MSG_RESULT($withval) -AC_DEFINE(WITH_READLINE) -if test ! -d "$withval" -then AC_ERROR(proper usage is --with-readline=DIRECTORY) -fi -termcap= -AC_CHECK_LIB(termcap, tgetent, [termcap=termcap], [ -AC_CHECK_LIB(termlib, tgetent, [termcap=termlib])]) -if test ! -z "$termcap" -then LIBS="$LIBS $withval/libreadline.a" - # Avoid possible conflict between shared libraries termcap and gl - # on IRIX 5: both contain a routine called clear. - if test -f /usr/lib/lib$termcap.a - then LIBS="$LIBS /usr/lib/lib$termcap.a" - else LIBS="$LIBS -l$termcap" - fi -else AC_ERROR(no working termcap/termlib, do not use --with-readline) -fi], AC_MSG_RESULT(no)) - -AC_MSG_CHECKING(for --with-thread) -AC_ARG_WITH(thread, [--with-thread[=DIRECTORY] make interpreter thread-safe], [ -AC_MSG_RESULT($withval) -if test -d "$withval" -then LIBS="$LIBS -L$withval" -fi -AC_CHECK_LIB(pthreads, pthread_create, [AC_DEFINE(WITH_THREAD) -AC_DEFINE(_POSIX_THREADS) -LIBS="$LIBS -lpthreads" -LIBOBJS="$LIBOBJS thread.o"]) -AC_CHECK_LIB(mpc, usconfig, [AC_DEFINE(WITH_THREAD) -LIBS="$LIBS -lmpc" -LIBOBJS="$LIBOBJS thread.o"]) -AC_CHECK_LIB(thread, thr_create, [AC_DEFINE(WITH_THREAD) -LIBS="$LIBS -lthread" -LIBOBJS="$LIBOBJS thread.o"]) -], AC_MSG_RESULT(no)) - -# -I${DLINCLDIR} is added to the compile rule for importdl.o -AC_SUBST(DLINCLDIR) -DLINCLDIR=/ - -AC_MSG_CHECKING(for --with-sgi-dl) -AC_ARG_WITH(sgi-dl, [--with-sgi-dl=DIRECTORY IRIX 4 dynamic linking], [ -AC_MSG_RESULT($withval) -AC_DEFINE(WITH_SGI_DL) -dldir=$withval -if test -d "$dldir" -then LIBS="$LIBS -L$dldir" -else AC_ERROR(proper usage is --with-sgi-dl=DIRECTORY) -fi -DLINCLDIR=${dldir} -LIBS="$LIBS -ldl -lmld"], AC_MSG_RESULT(no)) - -AC_MSG_CHECKING(for --with-dl-dld) -AC_ARG_WITH(dl-dld, [--with-dl-dld=DL_DIR,DLD_DIR GNU dynamic linking], [ -AC_MSG_RESULT($withval) -AC_DEFINE(WITH_DL_DLD) -dldir=`echo "$withval" | sed 's/,.*//'` -dlddir=`echo "$withval" | sed 's/.*,//'` -if test -d "$dldir" -a -d "$dlddir" -then LIBS="$LIBS -L$dldir -L$dlddir" -else AC_ERROR(proper usage is --with-dl-dld=DL_DIRECTORY,DLD_DIRECTORY) -fi -DLINCLDIR=${dldir} -LIBS="$LIBS -ldl -ldld"], AC_MSG_RESULT(no)) - -# checks for library functions -AC_CHECK_FUNCS(chown clock dlopen ftime ftruncate \ - gethostname_r getpeername getpgrp getpid gettimeofday getwd \ - link lstat mkfifo nice readlink \ - select setgid setuid setsid setpgid setpgrp setvbuf \ - sigaction siginterrupt sigrelse strftime symlink \ - tcgetpgrp tcsetpgrp times truncate uname waitpid) \ -AC_REPLACE_FUNCS(dup2 getcwd strerror memmove) -AC_CHECK_FUNC(getpgrp, AC_TRY_COMPILE([#include <unistd.h>], [getpgrp(0);], AC_DEFINE(GETPGRP_HAVE_ARG))) -AC_CHECK_FUNC(setpgrp, AC_TRY_COMPILE([#include <unistd.h>], [setpgrp(0,0);], AC_DEFINE(SETPGRP_HAVE_ARG))) -AC_CHECK_FUNC(gettimeofday, AC_TRY_COMPILE([#include <sys/time.h>], [gettimeofday((struct timeval*)0,(struct timezone*)0);], ,AC_DEFINE(GETTIMEOFDAY_NO_TZ))) - -# checks for structures -AC_HEADER_TIME -AC_STRUCT_TM -AC_STRUCT_TIMEZONE - -AC_MSG_CHECKING(for time.h that defines altzone) -AC_CACHE_VAL(ac_cv_header_time_altzone, -[AC_TRY_COMPILE([#include <time.h>], [return altzone;], - ac_cv_header_time_altzone=yes, - ac_cv_header_time_altzone=no)]) -AC_MSG_RESULT($ac_cv_header_time_altzone) -if test $ac_cv_header_time_altzone = yes; then - AC_DEFINE(HAVE_ALTZONE) -fi - -was_it_defined=no -AC_MSG_CHECKING(whether sys/select.h and sys/time.h may both be included) -AC_TRY_COMPILE([ -#include <sys/types.h> -#include <sys/select.h> -#include <sys/time.h> -], [;], [AC_DEFINE(SYS_SELECT_WITH_SYS_TIME) was_it_defined=yes]) -AC_MSG_RESULT($was_it_defined) - -# checks for compiler characteristics - -AC_C_CHAR_UNSIGNED - -AC_C_CONST - -works=no -AC_MSG_CHECKING(for working volatile) -AC_TRY_COMPILE([],[volatile int x; x = 0;], works=yes, AC_DEFINE(volatile, [])) -AC_MSG_RESULT($works) - -works=no -AC_MSG_CHECKING(for working signed char) -AC_TRY_COMPILE([], [signed char c;], works=yes, AC_DEFINE(signed, [])) -AC_MSG_RESULT($works) - -have_prototypes=no -AC_MSG_CHECKING(for prototypes) -AC_TRY_COMPILE([int foo(int x) { return 0; }], [return foo(10);], -AC_DEFINE(HAVE_PROTOTYPES) have_prototypes=yes) -AC_MSG_RESULT($have_prototypes) - -works=no -AC_MSG_CHECKING(for variable length prototypes and stdarg.h) -AC_TRY_COMPILE([ -#include <stdarg.h> -int foo(int x, ...) { return 0; } -], [return foo(10, 11, 12);], -AC_DEFINE(HAVE_STDARG_PROTOTYPES) works=yes) -AC_MSG_RESULT($works) - -if test "$have_prototypes" = yes; then -bad_prototypes=no -AC_MSG_CHECKING(for bad exec* prototypes) -AC_TRY_COMPILE([#include <unistd.h>], [char **t;execve("@",t,t);], , - AC_DEFINE(BAD_EXEC_PROTOTYPES) bad_prototypes=yes) -AC_MSG_RESULT($bad_prototypes) -fi - -bad_forward=no -AC_MSG_CHECKING(for bad static forward) -AC_TRY_RUN([ -struct s { int a; int b; }; -static struct s foo; -int foobar() { - static int random; - random = (int) &foo; - return random; -} -static struct s foo = { 1, 2 }; -main() { - exit(!((int)&foo == foobar())); -} -], , AC_DEFINE(BAD_STATIC_FORWARD) bad_forward=yes) -AC_MSG_RESULT($bad_forward) - -va_list_is_array=no -AC_MSG_CHECKING(whether va_list is an array) -AC_TRY_COMPILE([ -#ifdef HAVE_STDARG_PROTOTYPES -#include <stdarg.h> -#else -#include <varargs.h> -#endif -], [va_list list1, list2; list1 = list2;], , -AC_DEFINE(VA_LIST_IS_ARRAY) va_list_is_array=yes) -AC_MSG_RESULT($va_list_is_array) - -# checks for system services -# (none yet) - -# Linux requires this for correct f.p. operations -AC_CHECK_LIB(ieee, __fpu_control) - -# check for --with-libm=... -AC_SUBST(LIBM) -LIBM=-lm -AC_ARG_WITH(libm, [--with-libm=STRING math library], [ -if test "$withval" != yes -then LIBM=$withval -else AC_ERROR(proper usage is --with-libm=STRING) -fi]) - -# check for --with-libc=... -AC_SUBST(LIBC) -AC_ARG_WITH(libc, [--with-libc=STRING C library], [ -if test "$withval" != yes -then LIBC=$withval -else AC_ERROR(proper usage is --with-libc=STRING) -fi]) - -# check for hypot() in math library -LIBS_SAVE=$LIBS -LIBS="$LIBS $LIBM" -AC_CHECK_FUNCS(hypot) -LIBS=$LIBS_SAVE - -# check for getopt -AC_MSG_CHECKING(for genuine getopt) -AC_CACHE_VAL(ac_cv_func_getopt, -[AC_TRY_RUN([#include <stdio.h> -extern int optind, opterr, getopt(); -extern char* optarg; -int main() { - char* av[] = { "testprog", "parameter", "-fFlag", NULL }; - opterr = 0; - if (getopt(3, av, "f:") == 'f') { exit(1); } - exit(0); -}], ac_cv_func_getopt=yes, ac_cv_func_getopt=no, ac_cv_func_getopt=no)])dnl -AC_MSG_RESULT($ac_cv_func_getopt) -test $ac_cv_func_getopt = no && LIBOBJS="$LIBOBJS getopt.o" -AC_SUBST(LIBOBJS)dnl - -# generate output files -AC_OUTPUT(Makefile Objects/Makefile Parser/Makefile Python/Makefile Modules/Makefile.pre) diff --git a/install-sh b/install-sh deleted file mode 100755 index 0ff4b6a08e..0000000000 --- a/install-sh +++ /dev/null @@ -1,119 +0,0 @@ -#!/bin/sh - -# -# install - install a program, script, or datafile -# This comes from X11R5; it is not part of GNU. -# -# $XConsortium: install.sh,v 1.2 89/12/18 14:47:22 jim Exp $ -# -# This script is compatible with the BSD install script, but was written -# from scratch. -# - - -# set DOITPROG to echo to test this script - -# Don't use :- since 4.3BSD and earlier shells don't like it. -doit="${DOITPROG-}" - - -# put in absolute paths if you don't have them in your path; or use env. vars. - -mvprog="${MVPROG-mv}" -cpprog="${CPPROG-cp}" -chmodprog="${CHMODPROG-chmod}" -chownprog="${CHOWNPROG-chown}" -chgrpprog="${CHGRPPROG-chgrp}" -stripprog="${STRIPPROG-strip}" -rmprog="${RMPROG-rm}" - -instcmd="$mvprog" -chmodcmd="" -chowncmd="" -chgrpcmd="" -stripcmd="" -rmcmd="$rmprog -f" -mvcmd="$mvprog" -src="" -dst="" - -while [ x"$1" != x ]; do - case $1 in - -c) instcmd="$cpprog" - shift - continue;; - - -m) chmodcmd="$chmodprog $2" - shift - shift - continue;; - - -o) chowncmd="$chownprog $2" - shift - shift - continue;; - - -g) chgrpcmd="$chgrpprog $2" - shift - shift - continue;; - - -s) stripcmd="$stripprog" - shift - continue;; - - *) if [ x"$src" = x ] - then - src=$1 - else - dst=$1 - fi - shift - continue;; - esac -done - -if [ x"$src" = x ] -then - echo "install: no input file specified" - exit 1 -fi - -if [ x"$dst" = x ] -then - echo "install: no destination specified" - exit 1 -fi - - -# If destination is a directory, append the input filename; if your system -# does not like double slashes in filenames, you may need to add some logic - -if [ -d $dst ] -then - dst="$dst"/`basename $src` -fi - -# Make a temp file name in the proper directory. - -dstdir=`dirname $dst` -dsttmp=$dstdir/#inst.$$# - -# Move or copy the file name to the temp name - -$doit $instcmd $src $dsttmp - -# and set any options; do chmod last to preserve setuid bits - -if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; fi -if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; fi -if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; fi -if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; fi - -# Now rename the file to the real destination. - -$doit $rmcmd $dst -$doit $mvcmd $dsttmp $dst - - -exit 0 -- 2.11.4.GIT