Call for Nominations of PSF Directors
The Board of Directors of the Python Software Foundation is issuing this call for nominations of new Directors. Self-nominations are the norm, so don't wait for somebody else to nominate you. If you are interested in serving as a Director, please write to [EMAIL PROTECTED] Directors need not be PSF members. Since the PSF is a small organization, the Directors and Officers are the PSF's executive in more than name: we not only discuss the work to be done, we also initiate and oversee the work (through committees), and we get a lot of the work done ourselves. It is therefore beneficial to have a large number of active Directors. As Tim Peters eloquently put it, This is pragmatic: volunteer time is hard to come by for PSF busy work, and, overall, directors seem to feel more compelling obligation in this regard than non-director PSF members. So, the bigger the board, the more gets done. At the annual Members' Meeting in 2004 nine people stood for election to the Board, but there were only seven positions, so two candidates were not elected. This was a mistake; we cannot afford to turn away volunteers. In 2005, when eight people stood for election, the Board was first increased to eight positions, allowing all the candidates to serve. The size of the Board can change again. (Section 5.4 of the PSF bylaws states: the number of directors shall be fixed by the members at each annual meeting of members.) The PSF's Directors and Officers conduct business via monthly meetings (one hour on IRC) and an active mailing list. We discuss the work being done and the work to be done, and Directors vote on resolutions. David Goodger, PSF Secretary On behalf of the PSF Board of Directors -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Paste 1.1
Paste 1.1 - This release includes a security fix, fixing a situation where you could escape the root when serving static files and running the Paste HTTP server publicly. If you used other WSGI servers or used the Paste HTTP server behind Apache this does not effect you. For an update of Paste 1.0 that includes *only* the security fix, use easy_install Paste==1.0.1 What Is Paste? -- URL: http://pythonpaste.org Install: easy_install Paste PasteScript PasteDeploy News: http://pythonpaste.org/news.html http://pythonpaste.org/script/news.html http://pythonpaste.org/deploy/news.html Paste is a set of WSGI components, each of which can be used in isolation. But used together they form an unstoppable force. Team WSGI, unite! These components let you do things like create applications that proxy to other websites, mount multiple applications under different prefixes, catch exceptions and interactively inspect the environment, and much more. Paste Deploy is a configuration system for these components. Paste Script is a jack of all trades that builds new project file layouts, runs WSGI server stacks, and does application deployment. Interesting News Paste ~ * Security fix for paste.urlparser.StaticURLParser. The problem allowed escaping the root (and reading files) when used with paste.httpserver (this does not effect other servers, and does not apply when proxying requests from Apache to paste.httpserver). * paste.httpserver and paste.fixture.TestApp url-unquote SCRIPT_NAME and PATH_INFO, as specified in the CGI spec. Thanks to Jon Nelson for pointing out both these issues. * paste.registry now works within the EvalException interactive debugger. * Added a __traceback_decorator__ magic local variable, to allow arbitrary manipulation of the output of paste.exceptions.collector before formatting. * Added unicorn power to paste.pony (from Chad Whitacre) * For paste.httpserver SSL support: add support loading an explicit certificate context, and using ssl_pem='*' create an unsigned SSL certificate (from Jason Kirtland). Paste Script * Allow variable assignments at the end of paster serve, like paster serve http_port=80; then you can use %(http_port)s in your config files (requires up-to-date Paste Deploy). Paste Deploy * Really nothing interesting. -- Ian Bicking | [EMAIL PROTECTED] | http://blog.ianbicking.org -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: module wide metaclass for new style classes
Daniel Nogradi wrote: I used to have the following code to collect all (old style) class names defined in the current module to a list called reg: def meta( reg ): def _meta( name, bases, dictionary ): reg.append( name ) return _meta reg = [ ] __metaclass__ = meta( reg ) class c1: pass class c2: pass print reg That code does not create classes. Here's a slightly simplified version: reg = [] def __metaclass__(name, bases, dict): ... reg.append(name) ... class A: pass ... reg ['A'] A is None True # oops! This would correctly print [ 'c1', 'c2' ]. Now I would like to switch to new style classes but replacing class c1: and class c2: by class c1(object): and class c2(object): doesn't work because the metaclass associated with object will be called and not mine. Of course if I would add __metaclass__ = meta(reg) to all class definitions that would work, but how do I do this on the module level? If present, __metaclass__ serves as a factory for classes without an explicit base class. For example, __metaclass__ = type would turn c1 and c2 into newstyle classes (that inherit from object). If you want side effects you can wrap the metaclass into a function: reg = [] def __metaclass__(name, bases, dict): ... reg.append(name) ... return type(name, bases, dict) ... class A: pass ... class B: pass ... reg ['A', 'B'] issubclass(A, object) True Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: textwrap.dedent replaces tabs?
Tom Plunket wrote: I guess I could manually replace all tabs with eight spaces (as opposed to 'correct' tab stops), and then replace them when done, but it's probably just as easy to write a non-destructive dedent. You mean, as easy as \talpha\tbeta\t.expandtabs() 'alpha beta' ? Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: OT : Bug/Issue tracking systems
[EMAIL PROTECTED] wrote: Hi, (Off-topic) I am looking to put an open-source bug/issue tracking system in place for our current project (eventually expanded for all projects), and would appreciate any experiences/comments/suggestions. Note the project is encompasses embedded hardware (ASIC plus firmware) plus application software. The easiest method is using a spreadsheet, but this is not very expandable. The requirements I have come up with - Free ;-) - Easy to setup and maintain (I want this to be an engieering tool, not an IT project) - A non linux expert should be able to download and install (rpms OK, deep understanding of makefiles and linux kernel not OK) - Ideally via text files, a bit of perl/tcl/python OK. I'd rather avoid SQL - Prove the system and then hand-off to IT for maintenance - Easy use - Browser UI - Mail ? - Linux - Flexible reporting/search - User/admin accounts - Initially internal network access only, eventually external (customer, partner) access - Cover HDL, H/W, F/W, Documentation, Change requests. Both ASIC and FPGA. - Eventually production issues (Yeild, Test programs?) - Maybe allow project deadlines included. - We use CVS, so any loose coupling useful - We have per project repositories, plus and repository containing common IP's (i.e a project will always use 2) - Medium size projects (upto 15-20 people) - Possible migration to other system in future (which I guess means a well supported database) Googling provided with lots of names - Bugzilla (seems to be in widest use for S/W projects) - GNATS (I recall using this in a previous job) - IssueTrackerSystem (ZOPE, Python) - Trac (Python) - Plus lots of others Any suggestions, comments, recommendations or pointers to papers/tutorals greatly appreciated. Steven Hi Steven, We mainly do ASIC design and the Verification team installed RT for local issue tracking at work. I would have suggested Trak, but I was on a different project at the time and they were doing the work. RT (http://www.bestpractical.com/rt) does the Job. They have got the IT team to install it on the compute farm somewhere and after an initial learning period, they got it to do what they want. I have used gnats in the past. It worked. Trac seems to me to have a lot going for it, but, alas, I have not had a chance to try it. i notice that you are using CVS. You might want to look into the facilities available with tools like mercurial http://blog.arabx.com.au/?p=254, http://www.selenic.com/mercurial/wiki/index.cgi, http://www.opensolaris.org/os/community/tools/scm/ http://video.google.co.uk/videoplay?docid=-7724296011317502612q=mercurial At work we pay for clearcase and it does the revision control job very well, but in another company that were using CVS or RCS I would re-evaluate the source control needs. - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Paul Rubin wrote: Raffael Cavallaro [EMAIL PROTECTED]'espam-s'il-vous-plait-mac.com writes: For example, a common lisp with optional static typing on demand would be strictly more expressive than common lisp. But, take say, haskell; haskell's static typing is not optional (you can work around it, but you have to go out of your way to do so); haskell's pure functional semantics are not optional (again, workarounds possible to a limited extent). This requires you to conceive your problem solution (i.e., program) within the framework of a particular paradigm. This lock-in to a particular paradigm, however powerful, is what makes any such language strictly less expressive than one with syntactic abstraction over a uniform syntax. Incorrect, I believe. The above is like saying Lisp's lack of optional manual storage allocation and machine pointers makes Lisp less powerful. That is true. By itself, that feature makes Lisp less poweful for real-world software dev, which is why we have implementation-defined escape hatches for that sort of thing. It's in fact the absence of those features that lets garbage collection work reliably. This is a bad analogy to the bondage-and-discipline of purely functional languages. The removal for the need for manual object lifetime computation does not cause a whole class of useful programs to be rejected. In fact, all previously correct programs continue to work as before, and in addition, some hitherto incorrect programs become correct. That's an increase in power: new programs are possible without losing the old ones. Wheas programs can't be made to conform to the pure functional paradigm by adjusting the semantics of some API function. Programs which don't conform have to be rejected, Reliable GC gets rid of a large and important class of program errors and makes possible programming in a style that relies on it. Right. GC gets rid of /program errors/. Pure functional programming gets rid of /programs/. You can make languages more powerful by removing features as well as by adding them. Note that changing the storage liberation request from an imperative to a hint isn't the removal of a feature. It's the /addition/ of a feature. The new feature is that objects can still be reliably used after the implementation was advised by the program that they are no longer needed. Programs which do this are no longer buggy. Another new feature is that programs can fail to advise the implementation that some objects are no longer needed, without causing a leak, so these programs are no longer buggy. The pool of non-buggy programs has increased without anything being rejected. Okay, that is not quite true, which brings me back to my very first point. GC does (effectively) reject programs which do nasty things with pointers. For instance, hiding pointers from being visible to GC. However, such things can be made to coexist with GC. GC and non-GC stuff /can/ and does, for pragmatic reasons, live in the same image. Likewise, functional programming and imperative programming can also coexist in the same image. /Pure/ functional programming isn't about adding the feature of functional programming. It's about eliminating other features which are not functional programming. -- http://mail.python.org/mailman/listinfo/python-list
Re: Metaclass uses?
Nathan Harmston wrote: Also is there anymore interesting OO stuff that Python has apart from Java. Duck Typing: http://www.thescripts.com/forum/thread22721.html; http://mindview.net/WebLog/log-0025, Python does not have checked exceptions: http://www.mindview.net/Etc/Discussions/CheckedExceptions - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Good Looking UI for a stand alone application
The Night Blogger [EMAIL PROTECTED] wrote: Can someone recommend me a good API for writing a sexy looking (Rich UI like WinForms) shrink wrap application No, because such a thing doesn't exist. My requirement is that the application needs to look as good on Windows as on the Apple Mac Crossplatform GUIs are a myth, you *always* end up with a lowest common denominator (aka Windows) which makes your application look like crap on other platforms. And when the toolkit/framework only makes it look like semi-crap, it makes it *feel* like crap. Because, you know, user interfaces aren't only about the look but also (and most importantly) the feel, and the lowest common denominator (aka Windows) won't bring a Mac feel to your app. Crossplatform toolkits/frameworks suck. All of them. No exception. If you want your app to look *AND* feel great on all platform, abstract the core of your application and embed it in platform native GUI code. -- Luc Heinrich -- http://mail.python.org/mailman/listinfo/python-list
Re: OT : Bug/Issue tracking systems
In [EMAIL PROTECTED], moogyd wrote: The requirements I have come up with […] - Ideally via text files, a bit of perl/tcl/python OK. I'd rather avoid SQL You should drop that requirement. The tracker will be used concurrently and this is handled very efficiently and reliable by a database backend. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Smarter way to do this? Unicode + stdin, stdout
BenjaMinster schrieb: I want to read and write unicode on stdin and stdout. I can't seem to find any way to force sys.stdin.encoding and sys.stdout.encoding to be utf-8, so I've got the following workaround: What operating system are you using? Why do you want to do this? Python attempts to determine the encoding of your terminal (if sys.stdout is a terminal), and set sys.stdout.encoding accordingly. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: module wide metaclass for new style classes
I used to have the following code to collect all (old style) class names defined in the current module to a list called reg: def meta( reg ): def _meta( name, bases, dictionary ): reg.append( name ) return _meta reg = [ ] __metaclass__ = meta( reg ) class c1: pass class c2: pass print reg That code does not create classes. Here's a slightly simplified version: reg = [] def __metaclass__(name, bases, dict): ... reg.append(name) ... class A: pass ... reg ['A'] A is None True # oops! This would correctly print [ 'c1', 'c2' ]. Now I would like to switch to new style classes but replacing class c1: and class c2: by class c1(object): and class c2(object): doesn't work because the metaclass associated with object will be called and not mine. Of course if I would add __metaclass__ = meta(reg) to all class definitions that would work, but how do I do this on the module level? If present, __metaclass__ serves as a factory for classes without an explicit base class. For example, __metaclass__ = type would turn c1 and c2 into newstyle classes (that inherit from object). If you want side effects you can wrap the metaclass into a function: reg = [] def __metaclass__(name, bases, dict): ... reg.append(name) ... return type(name, bases, dict) ... class A: pass ... class B: pass ... reg ['A', 'B'] issubclass(A, object) True Thanks a lot, and sorry for the copy-paste error, I had the 'return type(...)' line but didn't know that this already creates new-style classes. -- http://mail.python.org/mailman/listinfo/python-list
Control-C alternative in Windows
Hello, I've written a simple, standalone wiki server in Python. It runs a BaseHTTPServer's serve_forever() method until a KeyboardInterrupt is caught, at which point it writes changes to a file and exits. This works as expected in Linux. However, in Windows I cannot stop the script with Control-C. I've only been able to stop it with Ctrl-Break, which does not send KeyboardInterrupt. This means no saving to the file and effectively a useless script. Any ideas as to how I might make this work in Windows? Thanks in advance, Vlad -- http://mail.python.org/mailman/listinfo/python-list
Re: Good Looking UI for a stand alone application
Sandra-24 wrote: On 12/16/06, The Night Blogger [EMAIL PROTECTED] wrote: Can someone recommend me a good API for writing a sexy looking (Rich UI like WinForms) shrink wrap application My requirement is that the application needs to look as good on Windows as on the Apple Mac wxPython or something layered on it would be the way to go. I tried all the popular toolkits (except qt) and nothing else comes close for cross platform gui work. Don't let people persuade you otherwise, that caused me a lot of trouble. Well, you should try qt too ;) BTW, does wxWindow/wxPython have something that allows you to switch the OK and Cancel button position according to the current machine GUI guidelines? -- http://mail.python.org/mailman/listinfo/python-list
Core dump revisited
Hi, I have a python script that uses a C extention. I keep getting a recurring problem that causes a core dump a few lines after the C extention return data back tp python. I tried using pbd and gdb but I have not succeeded in understanding what went wrong and where. I post the python script here is the error message and gdb output after reading the core file: . printout from with C extention Completed freeing 2D arrays. Now freeing 1D arrays freed 1D arrays freeing 15km arrays Complete Returning data back to Python! In python: assigning tuple data to numeric arrays! Time to do the coastal effects Segmentation fault (core dumped) .. Now there next step after Time to do the coastal effects was never executed. And even if I put another print statement there the same thing happens. I am using python 2.3 and I have set my stacksize to unlimited. When reading the core dump file with gdb I get: gdb msgppscomp.py core.3203 GNU gdb 6.0-2mdk (Mandrake Linux) Copyright 2003 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type show copying to see the conditions. There is absolutely no warranty for GDB. Type show warranty for details. This GDB was configured as i586-mandrake-linux-gnu.../data/proj_ns1/safworks/sheldon/msgppscomp.py: not in executable format: File format not recognized Core was generated by `python msgppscomp.py'. Program terminated with signal 11, Segmentation fault. #0 0x40079dfa in ?? () (gdb) . I am not very familiar with using gdb with python and C extentions. I would like to get some ideas about where the problem might be. I have made sure that all the arrays in the C extention are freed before exiting so I doubt that this might be the problem. Here is the python script: #!/usr/bin/env python #!-*-coding: UTF-8 -*- class WriteHdfFile: def __init__(self,outfile): self.outfile = outfile self.COMPRESS_LVL = 6 def writeAreainfo(self): import _pyhl import sys sys.float_output_precision = 2 aList = _pyhl.nodelist() aNode = _pyhl.node(_pyhl.GROUP_ID,/PPS_MSG_COMP) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/LAT) aNode.setArrayValue(1,lat.shape,lat,float,-1) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/LON) aNode.setArrayValue(1,lon.shape,lon,float,-1) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/VALCONCEN) aNode.setArrayValue(1,valconcen.shape,valconcen,int,-1) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/LIGHTCON) aNode.setArrayValue(1,lightcon.shape,lightcon,float,-1) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/BIAS100) aNode.setArrayValue(1,bias100.shape,bias100,float,-1) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/BIAS75) aNode.setArrayValue(1,bias75.shape,bias75,float,-1) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/BIAS50) aNode.setArrayValue(1,bias50.shape,bias50,float,-1) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/BIAS25) aNode.setArrayValue(1,bias25.shape,bias25,float,-1) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/COAST) aNode.setArrayValue(1,coast.shape,coast,float,-1) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/STATISTICS) aNode.setArrayValue(1,stats.shape,stats,int,-1) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/PERCENTAGE) aNode.setArrayValue(1,percentage.shape,percentage,float,-1) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/VA_vs_BIAS) aNode.setArrayValue(1,va_area.shape,va_area,float,-1) aList.addNode(aNode) aNode=_pyhl.node(_pyhl.DATASET_ID,/VANUM) aNode.setArrayValue(1,vanum.shape,vanum,float,-1) aList.addNode(aNode) aNode = _pyhl.node(_pyhl.ATTRIBUTE_ID,/NSCENES) aNode.setScalarValue(-1,areascenes,int,-1) aList.addNode(aNode) aNode = _pyhl.node(_pyhl.ATTRIBUTE_ID,/SATELLITE) aNode.setScalarValue(-1,satid,string,-1) aList.addNode(aNode) self.status = aList.write(self.outfile,self.COMPRESS_LVL) return self.status #--- if __name__ == __main__: from Numeric import * import sys, os, string, math, glob import msgppsarea,msgppscoast import shelve date = str(200510) #date = sys.argv[1] #s= sys.argv[2] cp = 'cfc' global valconcen,bias100,bias75,lightcon,bias50,bias25,percentage,va_area,lat,lon global stats,areascenes,satid,vanum,coast valconcen =
Re: How to test if two strings point to the same file or directory?
Sandra-24 wrote: Comparing file system paths as strings is very brittle. Is there a better way to test if two paths point to the same file or directory (and that will work across platforms?) I suspect that the and that will work across platforms parenthesis is in effect a killer. However, if you're prepared to waive that particular requirement, I can suggest reading this page for a Win32 possibility: http://timgolden.me.uk/python/win32_how_do_i/see_if_two_files_are_the_same_file.html TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: OT : Bug/Issue tracking systems
Marc 'BlackJack' Rintsch wrote: In [EMAIL PROTECTED], moogyd wrote: The requirements I have come up with [...] - Ideally via text files, a bit of perl/tcl/python OK. I'd rather avoid SQL You should drop that requirement. The tracker will be used concurrently and this is handled very efficiently and reliable by a database backend. Ciao, Marc 'BlackJack' Rintsch Hi Marc, I am aware that I will probably need a database (probably supporting SQL), but I would like to avoid having to write SQL queries myself (i.e. It should all be transparent to me). Thanks, Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: skip last line in loops
lines = open('blah').readlines() for i in range(0, len(lines)-1) : print lines[i] [EMAIL PROTECTED] wrote: hi, how can i skip printing the last line using loops (for /while) eg for line in open(file): print line. I want to skip printing last line of the file.thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
Most values tend to work, but only because the SQL string representation happens to be the same as the Python representation. That may not apply to some float values, bool, perhaps others. I had hoped the tools would have solved those problems so I don't have to. In typed languages (Java, C#) those things tend to just work. Not true. There might be frameworks that aid this process - as there are for python (e.g. TurboGears validators), but especially when it comes to dates, even the larger ones like Struts for Java pretty much suck. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Shed Skin 0.0.15
Thanks to those that sent in bug reports. This is really, really useful. I already released 0.0.16, with the following improvements: -added frozenset -time.sleep now works on WIN32 -constant-string expressions and __doc__ attributes are made into nice C++ comments -added --nowrap optimization option to ss.py (disables checking for negative indices) -several minor bug-fixes reported by users of 0.0.15 Thanks, Mark. On 12/9/06, Mark Dufour [EMAIL PROTECTED] wrote: Hi all, After getting bogged down with work for a few months, I'm finally back to Shed Skin development. I have just released 0.0.15, with the following changes: -python2.5 support/compatibility -any, all, conditional expression support -moved libs to 'lib' dir; made it easier to add modules (see README) -os.stat, os.path.{split, splitext, isfile, isdir, islink, exists} compiled from PyPy source -os.{chdir, rename, stat, lstat} added -fnmatch module added -random.{sample, seed} added -several important bugfixes (e.g. except getopt.GetoptError) There's more information about this release and the current state of Shed Skin on my blog: http://shed-skin.blogspot.com/ I also started a page on Wikipedia. Maybe a text like this should replace the one on the Shed Skin website: http://en.wikipedia.org/wiki/Shed_Skin Projects for the near future are getting 'shuffle-db' working (a 600-line program to rebuild the database on an ipod shuffle; see my blog), and converting the 're' module from the PyPy implementation to C++ using Shed Skin. Please try out the new release, and let me know about any problems/wishes/successes. As always, I am very happy with minimized pieces of code that fail to compile or should produce a (better) error or warning message. http://mark.dufour.googlepages.com Mark. -- One of my most productive days was throwing away 1000 lines of code - Ken Thompson -- One of my most productive days was throwing away 1000 lines of code - Ken Thompson -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
dyork wrote: Most values tend to work, but only because the SQL string representation happens to be the same as the Python representation. That may not apply to some float values, bool, perhaps others. I had hoped the tools would have solved those problems so I don't have to. In typed languages (Java, C#) those things tend to just work. if you think that Python isn't typed, you've completely missed how things work. your problem is that you're removing every trace of the type information by casting everything to strings, not that Python itself (nor the database adapters) cannot handle typed data. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Paul Rubin http://[EMAIL PROTECTED] writes: Kaz Kylheku [EMAIL PROTECTED] writes: Lisp just seems hopelessly old-fashioned to me these days. A modernized version would be cool, but I think the more serious Lisp-like language designers have moved on to newer ideas. What are some of their names, and what ideas are they working on? http://caml.inria.fr http://www.haskell.org Aren't these old-fashioned and boring as well? /Jon -- 'j' - a n t h o n y at romeo/charley/november com -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
Am Sat, 16 Dec 2006 16:31:18 -0500 schrieb Carsten Haese: This may come as a shock to you, but MySQL is not the only database engine on the planet. Your recommendation may apply to MySQL, but it is not true for all databases in general. I can name at least two examples (Informix and Oracle) of database engines that are supported under Python 2.5, and if I were less lazy I could probably find more. Interbase / Firebird: http://sourceforge.net/project/showfiles.php?group_id=9913 All you need, Windows binaries, .src.tar.gz for Python 2.3 - 2.5, Firebird 1.0 - 2.0. -- http://mail.python.org/mailman/listinfo/python-list
Re: Control-C alternative in Windows
Vlad Dogaru wrote: I've written a simple, standalone wiki server in Python. It runs a BaseHTTPServer's serve_forever() method until a KeyboardInterrupt is caught, at which point it writes changes to a file and exits. This works as expected in Linux. However, in Windows I cannot stop the script with Control-C. I've only been able to stop it with Ctrl-Break, which does not send KeyboardInterrupt. This means no saving to the file and effectively a useless script. Any ideas as to how I might make this work in Windows? (http://www.python.org/download/releases/2.2.2/NEWS.txt): The signal module now supports SIGBREAK on Windows, thanks to Steven Scott. Note that SIGBREAK is unique to Windows. The default SIGBREAK action remains to call Win32 ExitProcess(). This can be changed via signal.signal(). For example: # Make Ctrl+Break raise KeyboardInterrupt, like Python's default Ctrl+C # (SIGINT) behavior. import signal signal.signal(signal.SIGBREAK, signal.default_int_handler) try: while 1: pass except KeyboardInterrupt: # We get here on Ctrl+C or Ctrl+Break now; if we had not changed # SIGBREAK, only on Ctrl+C (and Ctrl+Break would terminate the # program without the possibility for any Python-level cleanup). print Clean exit -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Raffael Cavallaro wrote: On 2006-12-16 13:58:37 -0500, Jon Harrop [EMAIL PROTECTED] said: Why do you think that uniform syntax is necessary to provide new paradigms when it is equivalent to infix syntax? Because it doesn't require one to write a parser for each new syntax for each new paradigm. Why not use a single, extensible parser, e.g. camlp4? In what way is Haskell's support for imperative programming limited? It requires one to frame everything in functional terms or to jump through the hoop of monads. Can you give some example code demonstrating these hoops? Can you give an example of a Lisp macro that does something useful that you can't do in these other languages? It isn't a question of can't do in these other languages, it's a matter of can't do as easily in these other languages. Yes, absolutely. Look at kenny tilton's cells. Its a dataflow paradigm built largely of macros. It goes completely against the semantics of haskell - cells is all about the eager evaluation of side effecting state mutation. Perhaps that is because Cells is written in a language (Lisp) that forces you to jump through hoops to get lazy evaluation? The Cells project appears to deal with a graph (in the graph-theoretic sense). There is nothing inherently side-effecting about that and the problem that Cells is trying to solve seems to be fundamentally lazy: update cells only when necessary. Could you do it in haskell? Yes, in the greenspun/turing-completeness sense, but not nearly as easily as in common lisp, because the very paradigm - eager evaluation combined with side effecting state mutation - goes against the basic semantics of haskell. Can you give some evidence to back that up, e.g. a program that solves a problem like this in Haskell but is more convoluted that the Lisp? You'd have to jump through extra hoops to build a system whose very nature contradicts two of the semantic foundations of haskell - laziness and absense of side effects. What if eager impurity isn't the very nature of the problem but, rather, is the very nature of Tilton's chosen solution? Then there's the issue of the new syntax. Easy to build in lisp without learning another language - lisp macros use lisp. You can use Lisp macros to add some of the features found in modern FPLs. Once you've done that, users of your modern Lisp variant must learn how to use your macros. How is that better than learning a modern FPL directly? What little I've seen of caml4p looks like perlesque line noise. Ultimately I think that the defaults of both haskell and ocaml - functional, static typing, non-uniform syntax - are things I don't want as defaults, but as options for later in the development of only certain pieces of code. I don't want to be required to jump through the pure-functional, must-use-monads-for-any-side-effects, static-type, non-uniform-syntax hoops to express my ideas. It makes me less flexible in dealing with individual parts of a program differently. You can use tools like camlp4 to generate uniform syntax from OCaml's syntax. You can also use the -dlambda to output OCaml's Lisp-like intermediate representation. Why do you think that uniform syntax like this Lisp: (defun intersect (orig dir scene) (labels ((aux (lam normal scene) (let* ((center (sphere-center scene)) (lamt (ray-sphere orig dir center (sphere-radius scene (if (= lamt lam) (values lam normal) (etypecase scene (group (dolist (kid (group-children scene)) (setf (values lam normal) (aux lam normal kid))) (values lam normal)) (sphere (values lamt (unitise (-v (+v orig (*v lamt dir)) center) (aux infinity zero scene))) is better than syntax with conventional mathematical grammar, like this equivalent OCaml: let rec intersect orig dir (lambda, _ as hit) (center, radius, scene) = let lambda' = ray_sphere orig dir center radius in if lambda' = lambda then hit else match scene with | Sphere - lambda', unitise (orig +| lambda' *| dir -| center) | Group scenes - List.fold_left (intersect orig dir) hit scenes From my point of view, people started with Lisp and used its macros to add new syntax to the language and they got Haskell and OCaml. After all, Haskell and OCaml are more popular that any given Lisp variant with similar features (e.g. pattern matching), AFAIK. -- Dr Jon D Harrop, Flying Frog Consultancy Objective CAML for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
fumanchu [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Here's the web adaptation layer I use: http://projects.amor.org/misc/browser/alamode.py Have a look at the coerce_in and coerce_out functions. Thanks! Plenty of useful ideas there. My web framework already does all the HTML stuff, so I don't need that. Also, I note that alamode has hard coded dates in MDY order, which is surprising given the Unicode support, and a real problem. DY -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
Carsten Haese [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Python is a typed language, too, and this thing works just fine, provided that you are using a reasonable DB-API implementation, and provided that you're actually binding objects as parameters instead of just sticking literal strings into your query. I'm currently using MySQLdb, but I'm looking for solutions that work universally. Binding objects is no different from literal strings. Since there is no portable underlying type for an SQL date, the interface will AFAIK always finish up using strings. At some point the SQL parser has to convert a literal string, either embedded in the query or bound as a parameter, into the equivalent date. I really hope the dbapi will know how to choose the right string format so I don't have to, but so far that's not at all certain. When reading stuff from the database, keep the results in whatever form they come. Convert to strings for display purposes if you must, but don't overwrite the object you got from the database if you intend to save it back into the database. That's not feasible. For Web stuff, the object from the database got thrown away after the page was rendered. We're dealing with a whole new request, with little or no previous state, and all the dates coming in with the request are strings, using formatting that depends on what the user wanted to see. I need to package that into a form ready for either an INSERT or UPDATE query. The user might have typed in dd-mmm-yy order, but the database interface might use mm/dd/. It needs two conversion layers, and I would rather use someone else's than write my own. Lazy, I guess. DY -- http://mail.python.org/mailman/listinfo/python-list
Re: How to test if two strings point to the same file or directory?
The current setup will not silently fail when run on win32. How could it? It doesn't exist; it can't be run. Ah...didn't know which it did (or didn't do) as I don't have a win32 box at hand on which to test it. In chasing the matter further, the OP mentioned that their particular problem was related to tilde-expansion/compression which python doesn't seem to distinguish. To take this into consideration, there's some advice at http://groups.google.com/group/comp.lang.python/browse_thread/thread/ee559c99d54d970b/b71cb7ac1b7be105 where Chris Tismer has an example function/module that uses Win32 API calls to normalize a path/filename to the short-name equiv. It looks like this could be integrated into the previous code I posted, so you'd have something like os.path.samefile = lambda f1, f2: ( LongToShort(abspath(f1)).lower() == LongToShort(abspath(f2)).lower() ) As stated, it's a bit fly-by-the-seat-of-the-pants as I don't have any boxes running Win32 here at home, but that would be the general gist of the idea. It would be handy to add it, as the semantic meaning is the same across platforms, even if the implementation details are vastly different. One of the reasons I use python is because it usually crosses platform boundaries with nary a blink. Just a few more ideas, -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
Carsten Haese [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] This may come as a shock to you, but MySQL is not the only database engine on the planet. Your recommendation may apply to MySQL, but it is not true for all databases in general. I can name at least two examples (Informix and Oracle) of database engines that are supported under Python 2.5, and if I were less lazy I could probably find more. Of course, no question about it. However, the database is currently in MySQL and it's convenient to keep working with it, given the other apps and other tools I'm using. This would be the first time I've been told: don't use that database, the language doesn't like it. DY -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
Dennis Lee Bieber [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] If you actually look at what the various DB-API adapters produce when sending to the database engine, floats, bools, etc. are all sent as string representations; about the only source for problems would be involved in the number of significant digits transferred for a float (you might feed 15 digits in, and only get 7 or 10 back) Having written adapters myself, I would not be confident that is true. It's convenient to use native formats for floats and ints, and strings for everything else. Regardless, you get trouble with (a) nulls (b) dates/times (c) decimal/currency (d) precision mismatches (e) collation mismatches (f) blobs (g) Unicode (h) special values like NaN. It takes great attention to detail to be sure it all works, and I really don't want to write it (again). I'd just like to choose some product X and It Just Works! DY -- http://mail.python.org/mailman/listinfo/python-list
Changing variable to integer
Hello I receive such error: File p4.py, line 24, in PrintWordCountFloat print %s %f % (word,words[word]) TypeError: list indices must be integers i call PrintWordCountFloat with hash table, keys are words(string) and values float. This part of the code: def PrintWordCountFloat(words): number = 0 for word in words: print %s %f % (word,words[word]) #line 24 number = number + 1 print Total words: %d %(number) My function displays whole table correctly, and after that i receive mentioned error. Why ? Where is the problem ? Thanx -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing variable to integer
vertigo wrote: Hello I receive such error: File p4.py, line 24, in PrintWordCountFloat print %s %f % (word,words[word]) TypeError: list indices must be integers i call PrintWordCountFloat with hash table, keys are words(string) and values float. This part of the code: def PrintWordCountFloat(words): number = 0 for word in words: print %s %f % (word,words[word]) #line 24 number = number + 1 print Total words: %d %(number) My function displays whole table correctly, and after that i receive mentioned error. Why ? Where is the problem ? Perhaps you meant something more along the lines of this: def PrintWordCountFloat(words): number = 0 for index, word in enumerate(words): print %s %f % (index, word) number = number + 1 print Total words: %d %(number) PrintWordCountFloat(range(10)) 0 0.00 1 1.00 2 2.00 3 3.00 4 4.00 5 5.00 6 6.00 7 7.00 8 8.00 9 9.00 Total words: 10 Or similar; I can't read your mind. Just know that enumerate(iterable) yields (index, value) for each item in iterable. Thanx -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing variable to integer
vertigo schrieb: Hello I receive such error: File p4.py, line 24, in PrintWordCountFloat print %s %f % (word,words[word]) TypeError: list indices must be integers i call PrintWordCountFloat with hash table, keys are words(string) and values float. This part of the code: def PrintWordCountFloat(words): number = 0 for word in words: print %s %f % (word,words[word]) #line 24 number = number + 1 print Total words: %d %(number) My function displays whole table correctly, and after that i receive mentioned error. Why ? Where is the problem ? words is a list. If your variable names mean anything, I presume that word is ... well, a word, thus a string. But you can't do [1,2,4]['some_word'] That only works on dictionaries, like this: {'some_word' : 100}['some_word'] Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to push data into Ical from Python ?
You could save your calendar_ to a .ics file which is in the VCal_ file format; but that requires the extra step of manually saving your calendar to a file or accessing the files that iCal creates behind the scenes in ~/Library/Application Support/iCal/Sources/ which is unclear and potentially hazardous to your data. I'm guessing you would prefer to access the calendar data directly from the script, like an Applescript would. One way would be to use Python's tie-ins to Applescript_ and apple events (AE). As you will read, this support isn't as strong as it used to be. Another idea that would require more effort, but earn you some hacker points, is to use PyObjC_ and access iCal's public programming interface. But by far the easiest is to google for what you want (my search was for: ical api), find the iCalModule_ and try to make that work for you. Although that module appears to only read the data and is targeted toward 3rd-party calendars that are stored in ~/Library/Calendars. share and enjoy, !!Dean .. _calendar: http://en.wikipedia.org/wiki/ICalendar .. _VCal: http://en.wikipedia.org/wiki/VCal .. _Applescript: http://pythonmac.org/wiki/AppleScript .. _PyObjC: http://pyobjc.sourceforge.net/ .. _iCalModule: http://www.devoesquared.com/Software/iCal_Module The Night Blogger wrote: Is there a way to pull push data into (Apple Mac OS X Calendar) Ical from Python ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing variable to integer
vertigo wrote: I receive such error: File p4.py, line 24, in PrintWordCountFloat print %s %f % (word,words[word]) TypeError: list indices must be integers i call PrintWordCountFloat with hash table, keys are words(string) and values float. This part of the code: def PrintWordCountFloat(words): number = 0 for word in words: print %s %f % (word,words[word]) #line 24 number = number + 1 print Total words: %d %(number) My function displays whole table correctly, and after that i receive mentioned error. Why ? Where is the problem ? You could be calling PrintWordCountFloat() twice, once with a dictionary and then with a list :-) If I'm wrong, you have to provide more code. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
John Nagle [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Actually, MySQLdb isn't released for Python 2.5 yet, so for anything with a database, you need an older version of Python. It's not really a problem so far. If you really want to change the conversions for TIMESTAMP, add the conv argument to connect. Make a copy of MySQLdb.converters.conversions, then replace the key MySQLdb.FIELD_TYPE.TIMESTAMP, which normally has the value 'mysql_timestamp_converter' with your own converter. You can then get the interface to emit a datetime object. Thanks! Very helpful. Actually, it's DATETIME I want and not TIMESTAMP, but you certainly pointed me in the right direction. Turns out the author of MySQLdb knows his onions, and virtually all of what I need is in there. Seems it's critical to send in the right Python type to trigger the right conversion routine to get the right result, and some of the choices are not completely obvious. Still, the concept is good. None of this will help performance; dates and times are sent over the connection to a MySQL database as strings. Whenever you touch SQL (a) you talk strings and (b) performance belongs on a different planet. I can live with that. DY -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing variable to integer
vertigo wrote: I receive such error: File p4.py, line 24, in PrintWordCountFloat print %s %f % (word,words[word]) TypeError: list indices must be integers please post the *entire* traceback message. see: http://effbot.org/pyfaq/tutor-i-need-help-im-getting-an-error-in-my-program-what-should-i-do /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
Fredrik Lundh [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] if you think that Python isn't typed, you've completely missed how things work. your problem is that you're removing every trace of the type information by casting everything to strings, not that Python itself (nor the database adapters) cannot handle typed data. Fortunately, I'm not offended. I know perfectly well that Python variables are NOT typed, that Python relies on a dynamically typed model and most other languages support static typing.I assume you know that too. The advantage of static typing in this context is that the variable still holds the type even if the value happens to be null. Any value that has been exposed to user input comes back as a string and has to be validated and converted to the correct data type. Static typing provides a convenient place to generically find out what that type is, to drive a validator/convertor. There are many ways to do the equivalent in Python, and I'm interested in any suggestions that save me some work. DY -- http://mail.python.org/mailman/listinfo/python-list
Re: Serial port failure
Rob [EMAIL PROTECTED] wrote: Craig, In the embedded firmware, the each box re-transmits after it finishes reading the packet. This is a very rudimentary system, and uses no flow control. The topology is that each embedded box has a master and a slave port. The master is used to receive data from the upstream box, and send acks or naks back to the upstream box. The slave is connected to the master of the next downstream box. Does that clear up the picture a little bit? Sure! I suggest you run with the rest of my post and see what happens... I've seen dozens of broken serial port drivers over the years! ... My advice is to try a different serial port hardware. I've found ones based on the PL2303 chip to be very reliable both under windows and linux. Eg this one :- http://www.scan.co.uk/Products/ProductInfo.asp?WebProductID=98192 Or one of these (which were based on PL2303 last time I bought one) http://www.comtrol.com/products/catalog.asp?group=usbserialhubs I don't think anything you can do from python/user-space should be able to lock up the kernel mode serial driver. If it does lock up it is a driver bug. Here you'll find a little program I wrote which, with the help of a loopback connector, you can check your serial port out http://www.craig-wood.com/nick/pub/cambert.exe Run the program from a cmd prompt and it will tell you how to use it. I've broken a lot of serial port drivers with that program ;-) -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing variable to integer
Perhaps you meant something more along the lines of this: def PrintWordCountFloat(words): number = 0 for index, word in enumerate(words): print %s %f % (index, word) number = number + 1 print Total words: %d %(number) PrintWordCountFloat(range(10)) 0 0.00 1 1.00 2 2.00 3 3.00 4 4.00 5 5.00 6 6.00 7 7.00 8 8.00 9 9.00 Total words: 10 Or similar; I can't read your mind. Just know that enumerate(iterable) yields (index, value) for each item in iterable. sorry, i was not precise. words is a dictionary. 1. How can i show it's all variable (with key and value) ? 2. How can i show sorted dictionary (by key) ? 3. Is there any function which could do fast iteration on elements of sorted dictionary ? Thanx -- http://mail.python.org/mailman/listinfo/python-list
Re: textwrap.dedent replaces tabs?
Tom Plunket wrote: CakeProphet wrote: Hmmm... a quick fix might be to temporarily replace all tab characters with another, relatively unused control character. MyString = MyString.replace(\t, chr(1)) MyString = textwrap.dedent(MyString) MyString = MyString.replace(chr(1), \t) Of course... this isn't exactly safe, but it's not going to be fatal, if it does mess something up. As long as you don't expect receiving any ASCII 1 characters. Well, there is that small problem that there are leading tabs that I want stripped. I guess I could manually replace all tabs with eight spaces (as opposed to 'correct' tab stops), and then replace them when done, but it's probably just as easy to write a non-destructive dedent. It's not that I don't understand /why/ it does it; indeed I'm sure it does this so you can mix tabs and spaces in Python source. Why anyone would intentionally do that, though, I'm not sure. ;) -tom! This should do the trick: Dedent = re.compile ('^\s+') for line in lines: print Dedent.sub ('', line) Frederic --- Testing: text = s = ''' # Dedent demo No indent Three space indent \tOne tab indent \t\tThree space, two tab indent \t \tOne tab, two space, one tab indent with two tabs here \t\t''' print text print s # Dedent demo No indent Three space indent One tab indent Three space - two tab indent One tab - two spaces - one tab indent with two tabs here for line in text.splitlines (): print Dedent.sub ('', line) # Dedent demo No indent Three space indent One tab indent Three space - two tab indent One tab - two spaces - one tab indent with two tabs here --- -- http://mail.python.org/mailman/listinfo/python-list
Re: tuple.index()
greg [EMAIL PROTECTED] wrote: A Python tuple is like a C struct, and a Python list is like a C array. A Python list is more like C++/STL vector than an array, but that's probably picking nits. The real problem is that while the *intent* of the Python tuple is to act like a C/C++ struct (again, the C++ flavor is a better analogy, since tuples have methods), that's a poor comparison. The struct does lookup by name, the tuple is inherently index based. Yes, I know that the struct element names are converted to offsets by the compiler, but from the programming interface point of view, they're named elements. In that respect, a Python dict is a better analogy for a C++ struct than a tuple is. Also, consider that tuples and lists are completely fungible. For any list l, list(tuple(l)) is an identity operation. The same is true of tuple(list(t)) for any tuple t. That implies that neither one contains any information that the other one doesn't. -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
The advantage of static typing in this context is that the variable still holds the type even if the value happens to be null. Any value that has been exposed to user input comes back as a string and has to be validated and converted to the correct data type. Static typing provides a convenient place to generically find out what that type is, to drive a validator/convertor. There are many ways to do the equivalent in Python, and I'm interested in any suggestions that save me some work. While this information in statically typed languages _can_ be used (but not always is, in a web context), it also is available in the database schema, which ultimately decides what it groks and what not. But this is - especially in web-development - only half the truth. Because even such a simple thing as reading a float value from the user gets complicated in the presence of different locales. It buys you nothing then to have static type declarations available. A decent framework for webdevelopment, as e.g. TurboGears, allows you to declare form field validation and coercion rules, thus on a higher application level (your code), you only deal with the correctly typed values. Diez -- http://mail.python.org/mailman/listinfo/python-list
Class and instance question
I'm confused (not for the first time). I create these classes: class T(object): def __new__(self): self.a = 1 class X(T): def __init__(self): self.a = 4 class Y: def __init__(self): self.a = 4 class Z(object): def __init__(self): self.a = 4 ... and these instances: t = T() x = X() y = Y() z = Z() and I want to examine the 'a' attributes. print T.a 1 print y.a 4 print z.a 4 So far, it's as I expect, but: print x.a Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'NoneType' object has no attribute 'a' print t.a Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'NoneType' object has no attribute 'a' So what the heck is 'T'? It seems that I can't instantiate it or derive from it, so I guess it isn't a proper class. But it's something; it has an attribute. What is it? How would it be used (or, I guess, how should the __new__() method be used)? Any hints? -- rzed -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
dyork wrote: Dennis Lee Bieber [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] If you actually look at what the various DB-API adapters produce when sending to the database engine, floats, bools, etc. are all sent as string representations; about the only source for problems would be involved in the number of significant digits transferred for a float (you might feed 15 digits in, and only get 7 or 10 back) Having written adapters myself, I would not be confident that is true. It's convenient to use native formats for floats and ints, and strings for everything else. Regardless, you get trouble with (a) nulls (b) dates/times (c) decimal/currency (d) precision mismatches (e) collation mismatches (f) blobs (g) Unicode (h) special values like NaN. It takes great attention to detail to be sure it all works, and I really don't want to write it (again). I'd just like to choose some product X and It Just Works! Ah. Then feel free to have a look at Dejavu, wherein I've worked all that out for you (okay, not NaN, but that wouldn't be hard). A quick look over http://projects.amor.org/dejavu/browser/trunk/storage/storemysql.py shows proper string escaping, correct handling of 1/0 for True and False, encoding, max precision, CURDATE, automatic scaling to BLOB columns for bytes 255, and BLOB index limitations. All of the Null, date/time, decimal, unicode, and other type adaptation support is in the generic http://projects.amor.org/dejavu/browser/trunk/storage/geniusql.py The same goes for Postgres, MS Access, SQLite, and SQL Server. Firebird and sqlite3 are in the works. Simple docs at http://projects.amor.org/docs/dejavu/ Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing variable to integer
vertigo wrote: Perhaps you meant something more along the lines of this: def PrintWordCountFloat(words): number = 0 for index, word in enumerate(words): print %s %f % (index, word) number = number + 1 print Total words: %d %(number) PrintWordCountFloat(range(10)) 0 0.00 1 1.00 2 2.00 3 3.00 4 4.00 5 5.00 6 6.00 7 7.00 8 8.00 9 9.00 Total words: 10 Or similar; I can't read your mind. Just know that enumerate(iterable) yields (index, value) for each item in iterable. sorry, i was not precise. words is a dictionary. 1. How can i show it's all variable (with key and value) ? 2. How can i show sorted dictionary (by key) ? 3. Is there any function which could do fast iteration on elements of sorted dictionary ? Thanx I hope this helps a bit: words = {help:20, copyright:25, credits:35} # show dictionary for w, s in words.iteritems(): print w, s ... credits 35 help 20 copyright 25 # show sorted dictionary # dicts are not ordered, so you have to sort them. for w, s in sorted(words.iteritems()): print w, s ... copyright 25 credits 35 help 20 -- Juho Schultz -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrapping classes with pure virtual functions
On Thu, Dec 14, 2006 at 01:57:10PM -0800, [EMAIL PROTECTED] wrote: Hi, I'm having problems wrapping a hierarchy of classes, actually having problems wrapping the base class. I don't need to use the WrapClass mechanism since I don't want to override classes in Python. My code boils down to: class Base { public: virtual ~Base() {} virtual void f() = 0; }; class Derived : public Base { public: virtual void f() {} void g() {} }; int main() { boost::python::class_Base class_base(Base); Why are you trying to make this type visible to python? It is pure virtual, you can never instantiate it. boost::python::class_Derived class_derived(Derived); return 0; } The first line inside main (the one exporting Base) is causing the compile time error: error C2259: 'Base' : cannot instantiate abstract class... The probem seems to be that struct value_holderBase holds a Base member instance by value, and this is not possible since Base can't be instantiated. I'm using Visual Studio 2005 and boost 1.33.1. Thanks -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Class and instance question
rzed [EMAIL PROTECTED] writes: To simplify take class T(object): def __new__(self): self.a = 1 and t = T() and then you get print t.a Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'NoneType' object has no attribute 'a' While T.a is 1. So what the heck is 'T'? It seems that I can't instantiate it or derive from it, so I guess it isn't a proper class. But it's something; it has an attribute. What is it? I don't know. How would it be used (or, I guess, how should the __new__() method be used)? Any hints? The __new__ method should return the class. In your case return is None. Further the parametername for the __new__ method should be better cls to have a distinction to the usual self for instances. See http://www.python.org/doc/2.4.4/ref/customization.html Best wishes -- http://mail.python.org/mailman/listinfo/python-list
Why there isn't a sort method for array ?
Hi, It seems that an array acts like an list very much, except it doesn't have a method sort. Regards, -- http://mail.python.org/mailman/listinfo/python-list
Re: OT : Bug/Issue tracking systems
Steven, I have worked with Trac a bit, only to demo it in my company. We ended up not going with it (for reasons not related to Trac), but I found it easy to set up and configure. I seems to be a very nice tool. I especially like the wiki integration, as it makes it really easy to link tickets with supporting information. Phil -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
On 2006-12-17 07:54:28 -0500, Jon Harrop [EMAIL PROTECTED] said: What if eager impurity isn't the very nature of the problem but, rather, is the very nature of Tilton's chosen solution? That's the whole point which you keep missing - that a programming language is expressive precisely to the extent that it allows you to express the solution in the *programmer's* chosen form, not the paradigm imposed by the language. You look down your nose at cells, but if that's the way kenny conceived of the problem - as a graph of changing state, why should he be forced to reconceptualize it according to someone else's notion of programming correctness (be that pure functional or any other paradigm)? By asking this question you've implicitly admitted that to solve it *as he thought of it* in a pure functional language would require reconceptualizing it (i.e., the aforementioned jumping through hoops). We don't want to reconceptualize everything according to a particular paradigm, we want the flexibility to write the solution to the problem in the terms we think and talk about it, not the procrustean bed of pure functional semantics. -- http://mail.python.org/mailman/listinfo/python-list
Re: converting mysql db into sqlite3.
gordy You could probably use the mysqldump command with the proper gordy options to export the contents of your mysql database to an ASCII gordy text file that contains the SQL insert statements. Not sure where the original post is. All I see is this reply. In case the OP is listening, I believe you can do this in a fairly straightforward manner with SQLAlchemy. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
On 2006-12-17 07:54:28 -0500, Jon Harrop [EMAIL PROTECTED] said: After all, Haskell and OCaml are more popular that any given Lisp variant with similar features (e.g. pattern matching), AFAIK. What doublespeak! haskell and ocaml are more popular than any lisp library that tries to imitate Haskell and ocaml. So what! This only speaks to the relative unpopularity of imitating these features of haskell and ocaml when you already have lisp. -- http://mail.python.org/mailman/listinfo/python-list
Re: Roundtrip SQL data especially datetime
dyork wrote: Carsten Haese [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] This may come as a shock to you, but MySQL is not the only database engine on the planet. Your recommendation may apply to MySQL, but it is not true for all databases in general. I can name at least two examples (Informix and Oracle) of database engines that are supported under Python 2.5, and if I were less lazy I could probably find more. Of course, no question about it. However, the database is currently in MySQL and it's convenient to keep working with it, given the other apps and other tools I'm using. This would be the first time I've been told: don't use that database, the language doesn't like it. Simple fact: mySQLdb is not yet available for Python 2.5. Nobody has said (or even hinted) that the language doesn't like it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrapping classes with pure virtual functions
Chris Lambacher wrote: On Thu, Dec 14, 2006 at 01:57:10PM -0800, [EMAIL PROTECTED] wrote: Hi, I'm having problems wrapping a hierarchy of classes, actually having problems wrapping the base class. I don't need to use the WrapClass mechanism since I don't want to override classes in Python. My code boils down to: class Base { public: virtual ~Base() {} virtual void f() = 0; }; class Derived : public Base { public: virtual void f() {} void g() {} }; int main() { boost::python::class_Base class_base(Base); Why are you trying to make this type visible to python? It is pure virtual, you can never instantiate it. Because I want to use subclasses of Base polymorphically from Python. Python will receive an instance of some Base subclass through a another exported function. boost::python::class_Derived class_derived(Derived); return 0; } The first line inside main (the one exporting Base) is causing the compile time error: error C2259: 'Base' : cannot instantiate abstract class... The probem seems to be that struct value_holderBase holds a Base member instance by value, and this is not possible since Base can't be instantiated. I'm using Visual Studio 2005 and boost 1.33.1. Thanks -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Class and instance question
rzed wrote: I'm confused (not for the first time). I create these classes: class T(object): def __new__(self): self.a = 1 class X(T): def __init__(self): self.a = 4 class Y: def __init__(self): self.a = 4 class Z(object): def __init__(self): self.a = 4 ... and these instances: t = T() x = X() y = Y() z = Z() and I want to examine the 'a' attributes. print T.a 1 print y.a 4 print z.a 4 So far, it's as I expect, but: print x.a Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'NoneType' object has no attribute 'a' print t.a Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'NoneType' object has no attribute 'a' So what the heck is 'T'? It seems that I can't instantiate it or derive from it, so I guess it isn't a proper class. But it's something; it has an attribute. What is it? How would it be used (or, I guess, how should the __new__() method be used)? Any hints? __new__ should return something. Since there is no return statement, None is returned. You might try something like: class T(object): def __new__(cls): cls= object.__new__(cls) cls.a= 1 return cls t= T() print t.a Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: No latin9 in Python?
Martin v. Löwis schrieb: Christoph Zwerschke schrieb: Shall I proceed writing such a patch? Shall I also add latin0 and l0 which are other inofficial aliases? Sure, go ahead. I see no need for the latin0/l0 aliases, though: they predate the formal adoption of iso-8859-15, and should be phased out by now (I'm sure that somebody will provide an example of a software that still uses it, but I likely won't find that single example convincing). Ok, I'll add the alias for latin9, the completely missing latin10, and will also have a look whether some other things are missing. But probably I'll only get round to doing so after the Christmas holidays. -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: How to test if two strings point to the same file or directory?
It looks like you can get a fairly good apporximation for samefile on win32. Currently I'm using the algorithm suggested by Tim Chase as it is good enough for my needs. But if one wanted to add samefile to the ntpath module, here's the algorithm I would suggest: If the passed files do not exist, apply abspath and normcase to both and return the result of comparing them for equality as strings. If both paths pass isfile(), try the mecahnism linked to in this thread which opens both files at the same time and compares volume and index information. Return this result. If that raises an error (maybe they will not allow us to open them) Try comparing them using the approach suggested by Tim Chase, but if that works there should be some indication given that the comparison may not be accurate (raise a warning?). If that also fails, raise an error. This should allow samfile to be used on win32 in well over 99.9% of cases with no surprises. For the rest it will either return a result that is likely correct with a warning of some kind, or it will fail entirely. It's not perfect, but you can't acheive perfection here. It would, however, have far less surprises than newbies using == to compare paths for equality. And it would also make os.path.samefile available on another platform. os.path.sameopenfile could be implemented perfectly using the comparison of volume and index information alone (assuming you can get a win32 handle out of the open file object, which I think you can) If someone would be willing to write a patch for the ntpath tests I would be willing to implement samefile as described above or as agreed upon in further discussion. Then we can submit it for inclusion in the stdlib. -- http://mail.python.org/mailman/listinfo/python-list
Re: tuple.index()
In article [EMAIL PROTECTED], greg [EMAIL PROTECTED] writes: | | A collection is inhomogeneous if, for some attribute that is needed | for at least one action on at least one element of the collection, | the attribute is not shared by all elements of the collection. | | If you mean attribute in the Python sense, then this | is wrong, because you're just defining it in terms of | concrete types again. No, I am not. I am using it in the normal English sense. | There is no rigorous definition in Python terms, because | Python doesn't formally embody the concept. But that | doesn't mean the concept isn't real. Of course the concept is real, but the point is that Python doesn't embody the concept of homogeneity in lists, formally or informally, as far as I know or anyone has pointed out. Regards, Nick Maclaren. -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing variable to integer
On Sun, 17 Dec 2006 17:00:46 +0100, Juho Schultz [EMAIL PROTECTED] wrote: vertigo wrote: Perhaps you meant something more along the lines of this: def PrintWordCountFloat(words): number = 0 for index, word in enumerate(words): print %s %f % (index, word) number = number + 1 print Total words: %d %(number) PrintWordCountFloat(range(10)) 0 0.00 1 1.00 2 2.00 3 3.00 4 4.00 5 5.00 6 6.00 7 7.00 8 8.00 9 9.00 Total words: 10 Or similar; I can't read your mind. Just know that enumerate(iterable) yields (index, value) for each item in iterable. sorry, i was not precise. words is a dictionary. 1. How can i show it's all variable (with key and value) ? 2. How can i show sorted dictionary (by key) ? 3. Is there any function which could do fast iteration on elements of sorted dictionary ? Thanx I hope this helps a bit: words = {help:20, copyright:25, credits:35} # show dictionary for w, s in words.iteritems(): print w, s ... credits 35 help 20 copyright 25 # show sorted dictionary # dicts are not ordered, so you have to sort them. for w, s in sorted(words.iteritems()): print w, s ... copyright 25 credits 35 help 20 Thanx, it's working :) -- http://mail.python.org/mailman/listinfo/python-list
length of multidimensional table
Hello i have: x = zeros([3,4],Float) how can i check how many rows and columns x have ? (what is the X and Y size of that table) ? Thanx -- http://mail.python.org/mailman/listinfo/python-list
Re: length of multidimensional table
In [EMAIL PROTECTED], vertigo wrote: i have: x = zeros([3,4],Float) how can i check how many rows and columns x have ? (what is the X and Y size of that table) ? Try `x.getshape()`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Raffael Cavallaro wrote: On 2006-12-17 07:54:28 -0500, Jon Harrop [EMAIL PROTECTED] said: What if eager impurity isn't the very nature of the problem but, rather, is the very nature of Tilton's chosen solution? That's the whole point which you keep missing - that a programming language is expressive precisely to the extent that it allows you to express the solution in the *programmer's* chosen form, not the paradigm imposed by the language. That is the ideal, yes. In practice, different languages encourage you to use different solutions. For example, when faced with a problem best solved using pattern matching in Lisp, most Lisp programmers would reinvent an ad-hoc, informally specified and bug-ridden pattern matcher of their own. Do you not think that Lispers typically compile their high-level algorithms into low-level Lisp constructs like COND or IF? You look down your nose at cells, but if that's the way kenny conceived of the problem - as a graph of changing state, why should he be forced to reconceptualize it according to someone else's notion of programming correctness (be that pure functional or any other paradigm)? Kenny isn't being forced to do anything. By asking this question you've implicitly admitted that to solve it *as he thought of it* in a pure functional language would require reconceptualizing it (i.e., the aforementioned jumping through hoops). You are saying that solving it as he solved it requires a different solution. How does that make Lisp any different to the next language? We don't want to reconceptualize everything according to a particular paradigm, we want the flexibility to write the solution to the problem in the terms we think and talk about it, not the procrustean bed of pure functional semantics. Of the programming paradigms that can be implemented in Lisp, Lisp doesn't exactly make them easy. Moreover, every time you pick a random Lisp library off the wall to implement some feature already found in most other languages, you fragment the already tiny user base into even fewer people. -- Dr Jon D Harrop, Flying Frog Consultancy Objective CAML for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet -- http://mail.python.org/mailman/listinfo/python-list
Re: length of multidimensional table
vertigo wrote: i have: x = zeros([3,4],Float) how can i check how many rows and columns x have ? (what is the X and Y size of that table) ? Data member x.shape (tuple) contains dimensions of array. -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Raffael Cavallaro wrote: haskell and ocaml are more popular than any lisp library that tries to imitate Haskell and ocaml. Implementing pattern matching does not mean imitating Haskell or OCaml. This only speaks to the relative unpopularity of imitating these features of haskell and ocaml when you already have lisp. On the contrary, Lisp predates the features and, since their inception, most Lisp programmers have moved on to newer languages. -- Dr Jon D Harrop, Flying Frog Consultancy Objective CAML for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrapping classes with pure virtual functions
[EMAIL PROTECTED] wrote: Chris Lambacher wrote: On Thu, Dec 14, 2006 at 01:57:10PM -0800, [EMAIL PROTECTED] wrote: Hi, I'm having problems wrapping a hierarchy of classes, actually having problems wrapping the base class. I don't need to use the WrapClass mechanism since I don't want to override classes in Python. My code boils down to: class Base { public: virtual ~Base() {} virtual void f() = 0; }; class Derived : public Base { public: virtual void f() {} void g() {} }; int main() { boost::python::class_Base class_base(Base); Why are you trying to make this type visible to python? It is pure virtual, you can never instantiate it. Because I want to use subclasses of Base polymorphically from Python. Python will receive an instance of some Base subclass through a another exported function. I don't know much about Boost. Does it have anything like boost::python::pointer_Base? You can't get polymorphism by direct access to a class. C++ compiler always knows the exact type of a direct, non-pointer-accessed object. So even if you could create a class_Base, it would only ever be a Base, and never a derived class. You have to use pointers to get polymorphism. As an alternative, consider wrapping the derived classes instead. It might not be much more work if Boost wraps everything nicely. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
first and last index as in matlab
In matlab I can do the following: ind = [3,5,7,2,4,7,8,24] ind = 3 5 7 2 4 7 824 ind(1) ans = 3 ind(end) ans =24 ind([1 end]) ans = 324 but I can't get the last line in python: In [690]: ind = [3,5,7,2,4,7,8,24] In [691]: ind[0]Out[691]: 3 In [692]: ind[-1:] Out[692]: [24] In [693]: ?? How do I pull out multiple indices as in matlab? Thanks, Evan -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
On 2006-12-17 12:49:46 -0500, Jon Harrop [EMAIL PROTECTED] said: For example, when faced with a problem best solved using pattern matching in Lisp, most Lisp programmers would reinvent an ad-hoc, informally specified and bug-ridden pattern matcher of their own. No, I think most of us would use an exising lisp pattern matcher, like cl-unification. By asking this question you've implicitly admitted that to solve it *as he thought of it* in a pure functional language would require reconceptualizing it (i.e., the aforementioned jumping through hoops). You are saying that solving it as he solved it requires a different solution. How does that make Lisp any different to the next language? Give kenny some credit for not being a complete idiot. Cells was originally designed to keep UI elements in sync with an internal application model. The UI domain is I/O, i.e., a side effect. To do this lazily invites situations where an inherently unpredictable user action forces a complex series of constraints to be computed before anything can be displayed to the user, so the user must wait while the lazy system catches up. To do this eagerly means that at any time, any unpredictable user action will cause already computed state to be displayed, because everything has been kept up to date automatically all along. I'm saying that he conceived of the problem in the most natural way - state with mutations - and implemented it that way. He was not forced by his language to reconceive it purely functionally, have haskell implement the default lazy semantics, only to require the programmer to find an escape hatch from this default laziness since what he really wants is eager evaluation of side effects (i.e., I/O - syncing of model state with GUI display). People habitually think of the world as state and mutations of state. We've been doing so for a minimum of tens of thousands of years, quite possibly a million or more. People are good at thinking about mutation. Maybe this should tell us something about the desirability of certain programming language semantics and that referential transparency is a bit overrated. We don't want to reconceptualize everything according to a particular paradigm, we want the flexibility to write the solution to the problem in the terms we think and talk about it, not the procrustean bed of pure functional semantics. Of the programming paradigms that can be implemented in Lisp, Lisp doesn't exactly make them easy. Moreover, every time you pick a random Lisp library off the wall to implement some feature already found in most other languages, you fragment the already tiny user base into even fewer people. Not all lisp programmers will be solving the same sorts of problems as each other, so naturally they'll be using different sets of libraries. This use of different sets of libraries for different tasks doesn't constitute laguage fragmentation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrapping classes with pure virtual functions
On 14 Dec 2006 13:57:10 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, I'm having problems wrapping a hierarchy of classes, actually having problems wrapping the base class. I don't need to use the WrapClass mechanism since I don't want to override classes in Python. My code boils down to: class Base { public: virtual ~Base() {} virtual void f() = 0; }; class Derived : public Base { public: virtual void f() {} void g() {} }; int main() { boost::python::class_Base class_base(Base); boost::python::class_Derived class_derived(Derived); return 0; } namespace bpl = boost::python; bpl::class_Base, boost::noncopyable(Base, bpl::no_init ) .def( f, bpl::pure_virtual( Base::f ) ); bpl::class_ Derived, bpl::bases Base ( Derived ) .def( f, Derived::f ) .def( g, Derived::g ); Few comments: 1. It is better to ask Boost.Python related questions on its mailing list: http://mail.python.org/mailman/listinfo/c++-sig/ 2. If you just start with Boost.Python, try Py++ ( http://language-binding.net/pyplusplus/pyplusplus.html ) Boost.Pythoncode generator It has nice GUI ( no need to learn any API ): http://language-binding.net/pyplusplus/documentation/tutorials/pyplusplus_gui.html -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: first and last index as in matlab
Evan wrote in news:[EMAIL PROTECTED] in comp.lang.python: In matlab I can do the following: ind = [3,5,7,2,4,7,8,24] ind = 3 5 7 2 4 7 824 ind(1) ans = 3 ind(end) ans =24 ind([1 end]) ans = 324 but I can't get the last line in python: In [690]: ind = [3,5,7,2,4,7,8,24] In [691]: ind[0]Out[691]: 3 In [692]: ind[-1:] Out[692]: [24] In [693]: ?? How do I pull out multiple indices as in matlab? [ind[0], ind[-1]] or if you need something that can be generalised: [ind[i] for i in [0, -1]] so if you have: indexes_of_ind = [0, 2, -1, -2] you can write: [ind[i] for i in indexes_of_ind] Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
On 2006-12-17 12:52:34 -0500, Jon Harrop [EMAIL PROTECTED] said: Implementing pattern matching does not mean imitating Haskell or OCaml. We were explicitly comparing lisp with haskell and ocaml. Adding features built into haskell and ocaml but not present in ANSI common lisp would therefore constitute imitating haskell and ocaml in the context of this discussion. Surely you don't think I'm unaware of the fact that haskell and ocaml weren't the first languages to use some form of pattern matching. I acutally used SNOBOL once upon a time. -- http://mail.python.org/mailman/listinfo/python-list
url filtering
Hello I want to do some text analysis based on html documents grabbed from internet. Is there any library which could allow me easily getting text from html documents (cutting javascript, html tags and other not nececary data) ? Thanx -- http://mail.python.org/mailman/listinfo/python-list
Re: url filtering
Am Sun, 17 Dec 2006 20:14:32 +0100 schrieb vertigo [EMAIL PROTECTED]: Hello I want to do some text analysis based on html documents grabbed from internet. Is there any library which could allow me easily getting text from html documents (cutting javascript, html tags and other not nececary data) ? Thanx Try Beautiful Soup: http://www.crummy.com/software/BeautifulSoup/ Dennis -- http://mail.python.org/mailman/listinfo/python-list
Re: first and last index as in matlab
Evan [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] In matlab I can do the following: ind = [3,5,7,2,4,7,8,24] ind = 3 5 7 2 4 7 824 ind(1) ans = 3 ind(end) ans =24 ind([1 end]) ans = 324 but I can't get the last line in python: In [690]: ind = [3,5,7,2,4,7,8,24] In [691]: ind[0]Out[691]: 3 In [692]: ind[-1:] Out[692]: [24] In [693]: ?? How do I pull out multiple indices as in matlab? Thanks, Evan Or use the third element of a slice, which defines a stepsize, and pick a step that will go from the first to the last element: lst = list(ABCDEFG) lst ['A', 'B', 'C', 'D', 'E', 'F', 'G'] lst[0::len(lst)-1] ['A', 'G'] -- Paul -- http://mail.python.org/mailman/listinfo/python-list
trees
Hello What library/functions/classes could i use to create trees ? Thanx -- http://mail.python.org/mailman/listinfo/python-list
Re: trees
vertigo wrote: What library/functions/classes could i use to create trees ? what kind of trees? using lists, tuples, or a class with child pointers is so extremely simple so it has to be something else you're after... /F -- http://mail.python.org/mailman/listinfo/python-list
RE: trees
vertigo wrote: Hello What library/functions/classes could i use to create trees ? I would suggest either a horticultural or religious class. I'm sure that any library will contain functional texts on both. Or you could just read the following: http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney -- http://mail.python.org/mailman/listinfo/python-list
Re: Need Simple Way To Determine If File Is Executable
Gabriel Genellina [EMAIL PROTECTED] wrote: On 16 dic, 04:47, Tim Roberts [EMAIL PROTECTED] wrote: os.stat(selected)[ST_MODE] (S_IXUSR|S_IXGRP|S_IXOTH This will tell you that x.exe is executable, even if x.exe contains nothing but zeros. Isn't the same with any other recipe, portable or not? Unless the OS actually tries to load and examine the file contents, which the OS's I'm aware of, don't do. Yes, of course, you're right. I was about to delve into a philosophical discussion about the difference in handling this between Linux and Windows, but they're both just conventions. One is based on an arbitrary flag, one is based on a file extension. Contents are irrelevant. -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: trees
Delaney, Timothy (Tim) wrote: vertigo wrote: Hello What library/functions/classes could i use to create trees ? SpeedTree, of course. http://www.speedtree.com They have great downloadable demos. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: first and last index as in matlab
Evan wrote: In matlab I can do the following: ind = [3,5,7,2,4,7,8,24] ind = 3 5 7 2 4 7 824 ind(1) ans = 3 ind(end) ans =24 ind([1 end]) ans = 324 but I can't get the last line in python: In [690]: ind = [3,5,7,2,4,7,8,24] In [691]: ind[0]Out[691]: 3 In [692]: ind[-1:] Out[692]: [24] In [693]: ?? How do I pull out multiple indices as in matlab? If you want functionality similar to Matlab in Python, you should use Numpy, which has the take function to do what you want. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need Simple Way To Determine If File Is Executable
Gabriel Genellina wrote: On 16 dic, 04:47, Tim Roberts [EMAIL PROTECTED] wrote: os.stat(selected)[ST_MODE] (S_IXUSR|S_IXGRP|S_IXOTH This will tell you that x.exe is executable, even if x.exe contains nothing but zeros. Isn't the same with any other recipe, portable or not? Unless the OS actually tries to load and examine the file contents, which the OS's I'm aware of, don't do. -- Gabriel Genellina On windows, you can use win32file.GetBinaryType to check if a file is actually a binary executable. Roger == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups = East and West-Coast Server Farms - Total Privacy via Encryption = -- http://mail.python.org/mailman/listinfo/python-list
Re: first and last index as in matlab
Beliavsky wrote: Evan wrote: In matlab I can do the following: ind = [3,5,7,2,4,7,8,24] ind = 3 5 7 2 4 7 824 ind(1) ans = 3 ind(end) ans =24 ind([1 end]) ans = 324 but I can't get the last line in python: In [690]: ind = [3,5,7,2,4,7,8,24] In [691]: ind[0]Out[691]: 3 In [692]: ind[-1:] Out[692]: [24] In [693]: ?? How do I pull out multiple indices as in matlab? If you want functionality similar to Matlab in Python, you should use Numpy, which has the take function to do what you want. Actually, in numpy, we also have fancy indexing similar to Matlab's: In [1]: from numpy import * In [2]: ind = array([3,5,7,2,4,7,8,24]) In [3]: ind[[0, -1]] Out[3]: array([ 3, 24]) -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Why there isn't a sort method for array ?
[EMAIL PROTECTED] [EMAIL PROTECTED] wrote: It seems that an array acts like an list very much, except it doesn't have a method sort. What do you mean by array? There is no such beast in the Python language. Do you mean the library module array? -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: first and last index as in matlab
It's quite straight forward, actually. What you need to know is that -1 is the index of the last element in a sequence, and that slicing excludes the 'end' value in 'start:end'. So if you type arr[0:N], you get the subsequence [arr[0], arr[1], arr[2], ..., arr[N-1]] When comparing with Matlab, Python slicing works like this: arr(1:end) - arr[:] or arr[0:] arr(1:end-1) - arr[:-1] or arr[0:-1] arr(1:end-N) - arr[:-N] or arr[0:-N] arr(end) - arr[-1] arr(1) - arr[0] arr(1:2:end) - arr[::2] or arr[0::2] arr(1:2:end-1) - arr[:-1:2] or arr[0:-1:2] Python slicing is not completely like Matlab, because it was adoped from Haskell. It can do the same as Matlab's indexing, but the syntax is different. If you think Matlab's indexing is more intuitive it is just because you are more used to it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need Simple Way To Determine If File Is Executable
Roger Upole wrote: Gabriel Genellina wrote: On 16 dic, 04:47, Tim Roberts [EMAIL PROTECTED] wrote: os.stat(selected)[ST_MODE] (S_IXUSR|S_IXGRP|S_IXOTH This will tell you that x.exe is executable, even if x.exe contains nothing but zeros. Isn't the same with any other recipe, portable or not? Unless the OS actually tries to load and examine the file contents, which the OS's I'm aware of, don't do. -- Gabriel Genellina On windows, you can use win32file.GetBinaryType to check if a file is actually a binary executable. Roger Yabut ... what about things like batch files? Does it return them as executable as well? -- Tim Daneliuk [EMAIL PROTECTED] PGP Key: http://www.tundraware.com/PGP/ -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
On Sat, 16 Dec 2006 14:05:06 -0500 Kirk Sluder [EMAIL PROTECTED] wrote: # And there is something that is missing here in arguing about computer # language notations in relationship to human language readability, or # correspondence to spoken language. I'm not writing code for another # human, I'm writing code for a machine. Often, the optimum expression # of an mathematical concept for a machine is relatively baroque # compared to the optimum expression for a human being. Well, the memorable quote from Structure and Interpretation of Computer Programs states that Programs should be written for people to read, and only incidentally for machines to execute. -- Best wishes, Slawomir Nowaczyk ( [EMAIL PROTECTED] ) If at first you do succeed, try not to look astonished. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why there isn't a sort method for array ?
Tim Roberts wrote: [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: It seems that an array acts like an list very much, except it doesn't have a method sort. What do you mean by array? There is no such beast in the Python language. Do you mean the library module array? Indubitably the OP means objects created by the array function in the array module. Does that help you answer his question? Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Good Looking UI for a stand alone application
On Sun, 17 Dec 2006 09:37:04 +0100, [EMAIL PROTECTED] (Luc Heinrich) wrote: Crossplatform toolkits/frameworks suck. All of them. No exception. If you want your app to look *AND* feel great on all platform, abstract the core of your application and embed it in platform native GUI code. +1. Applications beyond very basic GUI's are better off rewriting the GUI for each application, while keeping the business logic separate. Even something as basic as QuickTime sucks on Windows. I'd be curious to see the source code to Skype: I just installed the Linux version, and it looks very nice. Maybe it was recompiled with Kylix. -- http://mail.python.org/mailman/listinfo/python-list
import
I would like to lauch a server from outside the side package directory how do i specify a path with import #/home/gert/Desktop/www/db/py/start-server.py import cherrypy class HelloWorld: def index(self): return #external htm file Hello world! index.exposed = True if __name__ == '__main__': # ??? dont know what is this for import os.path conf = os.path.join(os.path.dirname(__file__), 'conf-server.py') cherrypy.config.update(conf) cherrypy.quickstart(HelloWorld()) else: cherrypy.tree.mount(HelloWorld()) # ??? dont know what is this for #/home/gert/Desktop/www/db/py/conf-server.py [global] server.socket_port = 8080 server.thread_pool = 10 -- http://mail.python.org/mailman/listinfo/python-list
Re: Good Looking UI for a stand alone application
Vincent Delporte wrote: On Sun, 17 Dec 2006 09:37:04 +0100, [EMAIL PROTECTED] (Luc Heinrich) wrote: Crossplatform toolkits/frameworks suck. All of them. No exception. If you want your app to look *AND* feel great on all platform, abstract the core of your application and embed it in platform native GUI code. +1. Applications beyond very basic GUI's are better off rewriting the GUI for each application, while keeping the business logic separate. Even something as basic as QuickTime sucks on Windows. Read my second reply before reading that part again ;) I'd be curious to see the source code to Skype: I just installed the Linux version, and it looks very nice. Maybe it was recompiled with Kylix. They use QT. Back to read the first part of your post. -- http://mail.python.org/mailman/listinfo/python-list
New os.path.exists() behavior - bug or feature?
Hi all, yesterday I installed Python-2.5 and python-2.4.4 on my windows2k box. When trying to use os.path.exists() to detect which drives are present on the system I noticed that these behave differently: Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type copyright, credits or license() for more information. import os for char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': if os.path.exists('%s:\\' % char): print '%s:\\' % char A:\ C:\ D:\ E:\ ### Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type copyright, credits or license() for more information. import os for char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': if os.path.exists('%s:\\' % char): print '%s:\\' % char C:\ When I insert a floppy into A: os.path.exists('A:\\') will return True on Python-2.5, too. Does anyone know, is this inconsistent behavior a bug or a new feature? I also noticed that the Tix binaries are no longer present in 2.5, does anyone know if it is planned to remove them pemanently? Thanks in advance Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: tuple.index()
Roy Smith wrote: The struct does lookup by name, the tuple is inherently index based. I was trying to help people understand the distinction we're talking about by showing an example of the same distinction in another language where it's much clearer. There are a great many ways in which C structs are different from Python tuples, and C arrays are different from Python lists. But they're not the aspects I'm drawing an analogy between. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Need Simple Way To Determine If File Is Executable
Tim Daneliuk wrote: Roger Upole wrote: Gabriel Genellina wrote: On 16 dic, 04:47, Tim Roberts [EMAIL PROTECTED] wrote: os.stat(selected)[ST_MODE] (S_IXUSR|S_IXGRP|S_IXOTH This will tell you that x.exe is executable, even if x.exe contains nothing but zeros. Isn't the same with any other recipe, portable or not? Unless the OS actually tries to load and examine the file contents, which the OS's I'm aware of, don't do. -- Gabriel Genellina On windows, you can use win32file.GetBinaryType to check if a file is actually a binary executable. Roger Yabut ... what about things like batch files? Does it return them as executable as well? No, it's strictly for binary executables. Roger == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups = East and West-Coast Server Farms - Total Privacy via Encryption = -- http://mail.python.org/mailman/listinfo/python-list
writing serial port data to the gzip file
I am trying to save data it is comming from the serial port continually for some period. (expect reading from serial port is 100% not a problem) Following is an example of the code I am trying to write. It works, but it produce an empty gz file (0kB size) even I am sure I am getting data from the serial port. It looks like g.close() does not close the gz file. I was reading in the doc: Calling a GzipFile object's close() method does not close fileobj, since you might wish to append more material after the compressed data... so I am completely lost now... thanks for your comments. Petr Jakes snippet of the code def dataOnSerialPort(): data=s.readLine() if data: return data else: return 0 while 1: g=gzip.GzipFile(/root/foofile.gz,w) while dataOnSerialPort(): g.write(data) else: g.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to push data into Ical from Python ?
You might find this useful: http://doughellmann.blogspot.com/2006/12/mailbox2ics.html The Night Blogger wrote: Is there a way to pull push data into (Apple Mac OS X Calendar) Ical from Python ? -- http://mail.python.org/mailman/listinfo/python-list
Re: tuple.index()
In article [EMAIL PROTECTED], greg [EMAIL PROTECTED] wrote: Roy Smith wrote: The struct does lookup by name, the tuple is inherently index based. I was trying to help people understand the distinction we're talking about by showing an example of the same distinction in another language where it's much clearer. There are a great many ways in which C structs are different from Python tuples, and C arrays are different from Python lists. But they're not the aspects I'm drawing an analogy between. -- Greg Well, yeah, but it's kind of like saying a tangerine and an orange are very different things because one of them is like an apple and the other one is like a pear :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Kaz Kylheku wrote: The removal for the need for manual object lifetime computation does not cause a whole class of useful programs to be rejected. Sometimes you must be able to guarantee that a resource has been disposed before you can continue. That is why we have finalisers in OCaml and dispose in .NET (to manage external resources). In fact, all previously correct programs continue to work as before, Removing (external) resource allocation will break some programs. and in addition, some hitherto incorrect programs become correct. That's an increase in power: new programs are possible without losing the old ones. It is a trade-off. Aside from managing external resources, GC has performance implications that affect the design decisions of real-time applications. Wheas programs can't be made to conform to the pure functional paradigm by adjusting the semantics of some API function. Programs which don't conform have to be rejected, You can rephrase any impure program as a pure program (Turing). Reliable GC gets rid of a large and important class of program errors and makes possible programming in a style that relies on it. Right. GC gets rid of /program errors/. Pure functional programming gets rid of /programs/. Pure functional programming does not get rid of any programs. Pure functional programming does get rid of program errors, e.g. concurrency issues. You can make languages more powerful by removing features as well as by adding them. Note that changing the storage liberation request from an imperative to a hint isn't the removal of a feature. It's the /addition/ of a feature. The new feature is that objects can still be reliably used after the implementation was advised by the program that they are no longer needed. Programs which do this are no longer buggy. Another new feature is that programs can fail to advise the implementation that some objects are no longer needed, without causing a leak, so these programs are no longer buggy. The pool of non-buggy programs has increased without anything being rejected. You have rejected all programs that rely upon a resource being disposed before a certain point. -- Dr Jon D Harrop, Flying Frog Consultancy Objective CAML for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet -- http://mail.python.org/mailman/listinfo/python-list
Re: writing serial port data to the gzip file
Petr Jakes wrote: I am trying to save data it is comming from the serial port continually for some period. (expect reading from serial port is 100% not a problem) Following is an example of the code I am trying to write. It works, but it produce an empty gz file (0kB size) even I am sure I am getting data from the serial port. It looks like g.close() does not close the gz file. I was reading in the doc: Calling a GzipFile object's close() method does not close fileobj, since you might wish to append more material after the compressed data... so I am completely lost now... thanks for your comments. Petr Jakes snippet of the code def dataOnSerialPort(): data=s.readLine() if data: return data else: return 0 while 1: g=gzip.GzipFile(/root/foofile.gz,w) while dataOnSerialPort(): g.write(data) else: g.close() Your while loop is discarding result of dataOnSerialPort, so you're probably writing empty string to the file many times. Typically this kind of loop are implemented using iterators. Check if your s object (is it from external library?) already implements iterator. If it does then for data in s: g.write(data) is all you need. If it doesn't, you can use iter to create iterator for you: for data in iter(s.readLine, ''): g.write(data) -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Kaz Kylheku [EMAIL PROTECTED] writes: Incorrect, I believe. The above is like saying Lisp's lack of optional manual storage allocation and machine pointers makes Lisp less powerful. That is true. By itself, that feature makes Lisp less poweful for real-world software dev, which is why we have implementation-defined escape hatches for that sort of thing. ... This is a bad analogy to the bondage-and-discipline of purely functional languages. [/] The removal for the need for manual object lifetime computation does not cause a whole class of useful programs to be rejected. Did you just say two conflicting things? It's that very rejection that necessitates the escape hatches. In fact, all previously correct programs continue to work as before, and in addition, some hitherto incorrect programs become correct. That's an increase in power: new programs are possible without losing the old ones. There's more to power than making more programs possible. We also want to be able to distinguish correct programs from incorrect ones. Lisp has the power to eliminate a large class of pointer-related errors that are common in C programs, so Lisp is more powerful than C in that regard. Increasing the number of programs one can write in the unfounded hope that they might be correct is just one way to increase power. You can sometimes do that by adding features to the language. Increasing the number of programs you can write that are demonstrably free of large classes of errors is another way to increase power. You can sometimes do that by REMOVING features. That's what the Lisp holdouts don't seem to understand. Right. GC gets rid of /program errors/. Pure functional programming gets rid of /programs/. GC also gets rid of programs. There are programs you can write in C but not in Lisp, like device drivers that poke specific machine addresses. /Pure/ functional programming isn't about adding the feature of functional programming. It's about eliminating other features which are not functional programming. It seems to me that Haskell does some mumbo-jumbo to be purely functional only in some theoretical sense. In practice, its purity is enforced only in functions with a certain class of type signatures (i.e. most functions). You can write impure code when needed, by adding certain monads to the type signature of your function. The point is Haskell's static type system can then tell exactly which parts of your code are pure and which are impure. If you do something impure in a funciton with the wrong signature, you get a compile time error. You can choose to write in a style that separates pure from impure functional code in a Lisp program, but the compiler can't check it for you. If you get it wrong and call an impure function from your pure code (say in a lock-free concurrent program), all kinds of obscure bugs can result, like pointer errors in a C program. -- http://mail.python.org/mailman/listinfo/python-list
Re: Class and instance question
Colin J. Williams wrote: rzed wrote: class T(object): def __new__(self): self.a = 1 ... t = T() and I want to examine the 'a' attributes. print T.a 1 print t.a Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'NoneType' object has no attribute 'a' So what the heck is 'T'? It seems that I can't instantiate it or derive from it, so I guess it isn't a proper class. But it's something; it has an attribute. What is it? How would it be used (or, I guess, how should the __new__() method be used)? Any hints? __new__ should return something. Since there is no return statement, None is returned. You might try something like: class T(object): def __new__(cls): cls= object.__new__(cls) cls.a= 1 return cls t= T() print t.a Or, to use a bit more revealing names: class NewT(object): def __new__(class_): instance = object.__new__(class_) instance.a = 1 return instance You might have figured more of this out with: t = T() print repr(t) newt = NewT() print repr(newt) T.a t.a --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
Paul Rubin wrote: [...] There are programs you can write in C but not in Lisp, like device drivers that poke specific machine addresses. I should assume you meant Common Lisp, but there isn't really any reason you couldn't (poke destination (peek source)) in some version of Lisp that was meant for writing device drivers (perhaps under a Lisp machine or something). SIOD actually has (%%% memref address) for peek. -- http://mail.python.org/mailman/listinfo/python-list