PyAMF 0.1.1 released
We released PyAMF 0.1.1, a lightweight library that allows Flash and Python applications to communicate via Adobe's ActionScript Message Format. AMF3 and RemoteObject are supported in all the implemented Remoting gateways, currently supported for Django, Twisted, Web2Py and WSGI. This is bugfix release with the following important changes: - AMF3 encoder reported byte length header for non-ASCII string data (patch supplied by akaihola) - Decoder context not cleared between reading the remoting header and body. Check out the download page [1], installation instructions [2] and examples [3]. Questions? First stop is the mailing list [4], but we also hang out on [5]. Cheers, - the PyAMF team [1] http://pyamf.org/wiki/Download [2] http://pyamf.org/wiki/Install [3] http://pyamf.org/wiki/Examples [4] http://pyamf.org/wiki/MailingList [5] irc://freenode.net/pyamf -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Python-URL! - weekly Python news and links (Feb 18)
QOTW: Syntax can be, and has been, interoperable. The definitions of the telephone network, the Internet, email, and the Web are all bits-on-the-wire definitions of what you send back and forth, and they've all worked well enough to change the world. This belief that bits-on-the-wire is more important than data structures or APIs is at the center of my world view. - Tim Bray, author of, for example, What is RDF Given this indispensable process and architecture issue, isn't it obvious that it's totally irrelevant to the system's overall safety whether the compiler has performed the further smattering of semantically puny 'verifications' allowed by mandatory-declaration, stating-typing languages? - Alex Martelli A problem with itertools.groupby: groups apparently were being emptied before use: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f98e52fede997731/ Should __doubleunderscore__ names be defined by a programmer? http://groups.google.com/group/comp.lang.python/browse_thread/thread/999b15a600da5086/ Floating point numbers, Decimals, the upcoming Fraction type (rational) and their limitations: http://groups.google.com/group/comp.lang.python/browse_thread/thread/50e0e3f948eb94a6/ Also inf and nan support: http://groups.google.com/group/comp.lang.python/browse_thread/thread/3fd33cf86a563d6c/ Very simple RSS/Atom generators: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6ac9d6ecb4c09128/ Looking for replacements to C's __FILE__ and __LINE__ macros: http://groups.google.com/group/comp.lang.python/browse_thread/thread/34f3ef011e3484a Regular expression for prime numbers (?!) http://groups.google.com/group/comp.lang.python/browse_thread/thread/b30c697cbe5f6b82/ Notes on how Python manages memory: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4f906397187a88b9/ The longest thread this week is absolutely off topic, and started two weeks ago: the speed of light, archery as an esoteric knowledge, is pound a unit of mass?, wavicles...: http://groups.google.com/group/comp.lang.python/browse_frm/thread/8c7c359b600881e0/f84617b03f0ddfc1 Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish the efforts of Python enthusiats: http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the Planet sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djqas_ugroup=comp.lang.python.announce Python411 indexes podcasts ... to help people learn Python ... Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and
ANN: amplee 0.6.0 - AtomPub Python implementation
Hi all, I'm glad to announce the release of amplee in version 0.6.0 == Overview of this release == This release is an important move from previous releases as it doesn't include support for any HTTP layer out of the box anymore. The reason is that it made the previous API needlessly complex and stopped people to actually use amplee for what it aims at being: one simple representation of the AtomPub protocol server side. Basically I wish amplee was used as a library rather than as a host for AtomPub applications. The 0.6.x branch will focus therefore on polishing the AtomPub model API as well as the related sub-packages such as the index and graph extension. Moreover I would like to improve the performance of amplee although they have already improved since 0.5.x. The graph sub-package is a first stab at using graph theory via the igraph [1] package to perform foxy manipulations of Atom feeds. One major change since 0.5.x is the move from bridge [2] to Amara [3] to parse, query and generate XML documents within amplee. I think that change was for the best considering the capabilities of Amara. Another change is that I've dropped the INI file format for configuration and loading an amplee structure. Instead you can now directly use the XML service document itself and complete using a bit of extra code. That allows for some funny capabilities such as mirroring existing AtomPub service document (see the example directory for instance [4]). I would like to thank Eric Larson [5] and Mohanaraj Gopala Krishnan for their feedback and patience. They have provided the project with a tremendous help. == Download == * easy_install -U amplee * Tarballs http://www.defuze.org/oss/amplee/ * svn co https://svn.defuze.org/oss/amplee/ == Documentation == Home page: http://trac.defuze.org/wiki/amplee API: http://www.defuze.org/oss/amplee/api-0.6.0/ Tutorial (sort of): http://trac.defuze.org/wiki/amplee/Tutorial-0.6.x == TODO == * Add more tests * Improve documentation * Improve performance * Improve the graph and index sub-packages Have fun, -- Sylvain Hellegouarch http://www.defuze.org [1] http://cneurocvs.rmki.kfki.hu/igraph/ [2] http://trac.defuze.org/wiki/bridge [3] http://uche.ogbuji.net/tech/4suite/amara/ [4] http://trac.defuze.org/browser/oss/amplee/amplee/examples/miror [5] http://ionrock.org/ -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Public Python Training Classes
Holden Web is pleased to announce the availability of public classes in the Python language. The current schedule is available at http://holdenweb.com/py/training/ Our initial classes are mostly introductory, but we are also offering experimental half-day seminars, the first two of which are revised editions of Steve Holden's popular tutorials on wxPython and the DB API. If you know of anyone with Python training requirements we would appreciate your bringing this notice to their attention. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Tkinter = Rodney Dangerfield?
En Sun, 17 Feb 2008 17:35:35 -0200, [EMAIL PROTECTED] escribi�: Tkinter gets no respect. But IDLE's a Tkinter-based app and every example I've Googled up shows Tkinter as needing about half as much code as wx to do the same job. I'm beginning to Tkinter up my language application. Am I making a big mistake? I don't like Tk because the widgets are ugly, old-fashioned, and don't have the right look and feel. But Tkinter is a good library, and a lot easier to deploy than gtk by example. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Current Fastest Python Implementation?
Has anyone done any recent testing as to which current python implementation is the quickest? Perhaps for Django development - though the current one certainly is fast (and I doubt micro optimizations would make much difference in overall performance). Regardless - have those pypy folks made a faster implementation, or the jython folks? Or the .NET implementation? Sam -- http://mail.python.org/mailman/listinfo/python-list
Re: Developing a Package with Sub Packages
En Sun, 17 Feb 2008 22:34:27 -0200, Josh English [EMAIL PROTECTED] escribi�: Here's what I think is happening: IMS/__init__.py uses os.getcwd() to establish the path to the data folder and the files inside of it. When I run StoryCreator, os.getcwd() returns the story folder. If I'm right, how can I get the IMS/__init__.py module to use relative paths to its own module, and not the current working directory the os module provides? Use the module's own __file__ attribute: my_path = os.path.abspath(os.path.dirname(__file__)) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a Python Program/Tool That Will Add Line Numbers to a txt File
On Feb 15, 8:55 pm, Jeff Schwab [EMAIL PROTECTED] wrote: W. Watson wrote: See Subject. It's a simple txt file, each line is a Python stmt, but I need up to four digits added to each line with a space between the number field and the text. Perhaps someone has already done this or there's a source on the web for it. I'm not yet into files with Python. A sudden need has burst upon me. I'm using Win XP. i = 0 for line in sys.stdin: i += 1 print i, line, Or if you want consistent alignment: i = 0 for line in sys.stdin: i += 1 print %4s % i, line, I like your version best (it's very clean and easy to understand), but here's a few more versions... from itertools import count for i, line in zip(count(1), open('filename.txt')): print i, line, or with consistent alignment: for x in zip(count(1), open('filename.txt')): print %4d %s % x, the latter version gives rise to a one-liner open('output.txt','w').writelines('%4d %s' % x for x in zip(count(1), open('perms.py'))) but as I said, I like the simple for loop the best ;-) -- bjorn -- http://mail.python.org/mailman/listinfo/python-list
Re: Pmw Use and Grayson's Book
On Feb 18, 5:30 am, W. Watson [EMAIL PROTECTED] wrote: I wonder why he uses it? He uses it because Pmw does a lot of heavy lifting for you when designing Tkinter apps. Pmw adds things like widgets pre-populated with scrollbars and labels and automatic widget/label alignment. I use Pmw for all but the most trivial Tkinter applications. That said, there is nothing in Pmw that you couldn't implement yourself in plain Tkinter, it's just already been done for you. Check out the Pmw site for lots of examples and details. Also, if you do install the module, it comes with a demo directory. Run all.py to see Pmw in action. http://pmw.sourceforge.net If I want to run his examples, where do I put the lib he includes? Same folder as the example? Library modules (like Pmw) generally belong in site-packages (/usr/lib/ python2.x/site-packages in most unixes... not sure about windows). HTH, Pete -- http://mail.python.org/mailman/listinfo/python-list
Re: Current Fastest Python Implementation?
samuraisam wrote: Has anyone done any recent testing as to which current python implementation is the quickest? Search for a recent thread on CPython and IronPython. Perhaps for Django development - though the current one certainly is fast (and I doubt micro optimizations would make much difference in overall performance). Regardless - have those pypy folks made a faster implementation, or the jython folks? Or the .NET implementation? Depends on your use case. Take your application, do some benchmarking and use the implementation that turns out to be a) most reliable and b) the fastest. In that order. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Current Fastest Python Implementation?
On Feb 18, 9:37 am, Stefan Behnel [EMAIL PROTECTED] wrote: samuraisam wrote: Has anyone done any recent testing as to which current python implementation is the quickest? Search for a recent thread on CPython and IronPython. Perhaps for Django development - though the current one certainly is fast (and I doubt micro optimizations would make much difference in overall performance). Regardless - have those pypy folks made a faster implementation, or the jython folks? Or the .NET implementation? Depends on your use case. Take your application, do some benchmarking and use the implementation that turns out to be a) most reliable and b) the fastest. In that order. Stefan PyPy [http://codespeak.net/pypy/dist/pypy/doc/home.html] is getting progressively faster. In fact for certain things it can be faster than C [http:// morepypy.blogspot.com/2008/01/rpython-can-be-faster-than-c.html]! However it seems it still has a way to go to be fully operational! Still looks like the future to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Confusion
Most of the other questions have already been answered, so I'll tackle this one: On Feb 17, 8:36 pm, [EMAIL PROTECTED] wrote: Google's great, but it has no truth meter. Do I inherit from Frame? Or is that a big mistake. (Both positions repeated frequently.) Inherit from Frame if you want your class to be a packable widget. If you only intend to pack widgets in a supplied container, no need to subclass Frame... Pete -- http://mail.python.org/mailman/listinfo/python-list
Professional Grant Proposal Writing Workshop (June 2008: Seattle, Washington)
The Grant Institute's Grants 101: Professional Grant Proposal Writing Workshop will be held Seattle, Washington,June18 - 20, 2008. Interested development professionals, researchers, faculty, and graduate students should register as soon as possible, as demand means that seats will fill up quickly. Please forward, post, and distribute this e-mail to your colleagues and listservs. All participants will receive certification in professional grant writing from the Institute. For more information call (888) 824 - 4424 (213-817-5308 outside US) or visit The Grant Institute at www.thegrantinstitute.com. Please find the program description below: The Grant Institute Grants 101: Professional Grant Proposal Writing Workshop will be held in Seattle, Washington June18 -20, 2008 8:00 AM - 5:00 PM The Grant Institute's Grants 101 course is an intensive and detailed introduction to the process, structure, and skill of professional proposal writing. This course is characterized by its ability to act as a thorough overview, introduction, and refresher at the same time. In this course, participants will learn the entire proposal writing process and complete the course with a solid understanding of not only the ideal proposal structure, but a holistic understanding of the essential factors, which determine whether or not a program gets funded. Through the completion of interactive exercises and activities, participants will complement expert lectures by putting proven techniques into practice. This course is designed for both the beginner looking for a thorough introduction and the intermediate looking for a refresher course that will strengthen their grant acquisition skills. This class, simply put, is designed to get results by creating professional grant proposal writers. Participants will become competent program planning and proposal writing professionals after successful completion of the Grants 101 course. In three active and informative days, students will be exposed to the art of successful grant writing practices, and led on a journey that ends with a masterful grant proposal. Grants 101 consists of three (3) courses that will be completed during the three-day workshop. (1) Fundamentals of Program Planning This course is centered on the belief that "it's all about the program." This intensive course will teach professional program development essentials and program evaluation. While most grant writing "workshops" treat program development and evaluation as separate from the writing of a proposal, this class will teach students the relationship between overall program planning and grant writing. (2) Professional Grant Writing Designed for both the novice and experienced grant writer, this course will make each student an overall proposal writing specialist. In addition to teaching the basic components of a grant proposal, successful approaches, and the do's and don'ts of grant writing, this course is infused with expert principles that will lead to a mastery of the process. Strategy resides at the forefront of this course's intent to illustrate grant writing as an integrated, multidimensional, and dynamic endeavor. Each student will learn to stop writing the grant and to start writing the story. Ultimately, this class will illustrate how each component of the grant proposal represents an opportunity to use proven techniques for generating support. (3) Grant Research At its foundation, this course will address the basics of foundation, corporation, and government grant research. However, this course will teach a strategic funding research approach that encourages students to see research not as something they do before they write a proposal, but as an integrated part of the grant seeking process. Students will be exposed to online and database research tools, as well as publications and directories that contain information about foundation, corporation, and government grant opportunities. Focusing on funding sources and basic social science research, this course teaches students how to use research as part of a strategic grant acquisition effort. Registration $597.00 tuition includes all materials and certificates. Each student will receive: *The Grant Institute Certificate in Professional Grant Writing *The Grant Institute's Guide to Successful Grant Writing *The Grant Institute Grant Writer's Workbook with sample proposals, forms, and outlines Registration Methods 1) On-Line- Complete the online registration form at www.thegrantinstitute.com under Register Now. We'll send your confirmation by e-mail. 2) By Phone - Call (888) 824 - 4424 (213-817-5308 outside US)to register by phone. Our friendly Program Coordinators will be happy to assist you and answer your questions. 3) By E-mail - Send an e-mail with your name, organization, and basic contact information to [EMAIL PROTECTED] and we will reserve your slot and send your Confirmation Packet. You have received this invitation
Re: Is there a way to link a python program from several files?
On Feb 16, 7:53 pm, [EMAIL PROTECTED] (Edward A. Falk) wrote: IOW, is there a linker for python? I've written a program comprised of about five .py files. I'd like to find a way to combine them into a single executable. I wrote a small wiki page to sum-up my findings about such typical problem: http://www.freehackers.org/Packaging_a_python_program -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Confusion
On Feb 18, 1:41 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Most of the other questions have already been answered, so I'll tackle this one: On Feb 17, 8:36 pm, [EMAIL PROTECTED] wrote: Google's great, but it has no truth meter. Do I inherit from Frame? Or is that a big mistake. (Both positions repeated frequently.) Inherit from Frame if you want your class to be a packable widget. If you only intend to pack widgets in a supplied container, no need to subclass Frame... Pete Whether you should inherit from Frame or not depends on wether you want to write your code with a procedural style or with an object oriented style. You can write Tkinter programs with a procedural style(see previous examples), or you can write them with an object oriented style: import Tkinter as tk class MyLabelFrame(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.config(background='green') label1 = tk.Label(self, text='hello world', background='gray') label2 = tk.Label(self, text='goodbye', background='gray') label1.pack() #makes label visible label2.pack() #makes label visible class MyButtonFrame(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.config(background='black', padx=20, pady=20) button1 = tk.Button(self, text='suprise 1', command=self.sayhi) button2 = tk.Button(self, text='suprise 2', command=self.saybye) button1.pack() button2.pack() def sayhi(self): print 'hi' def saybye(self): print 'bye' class MyApp(object): def __init__(self, *frames): root = tk.Tk() root.geometry('600x400') root.config(background='red') frame1 = MyLabelFrame(root) frame2 = MyButtonFrame(root) frame1.pack(side=tk.TOP) frame2.pack(side=tk.BOTTOM) root.mainloop() app = MyApp() If you don't know what object oriented programming is, then stick to the simplicity of the procedural style in the previous examples. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a Python Program/Tool That Will Add Line Numbers to a txt File
On Thu, 14 Feb 2008, W. Watson wrote: See Subject. It's a simple txt file, each line is a Python stmt, but I need up to four digits added to each line with a space between the number field and the text. Perhaps someone has already done this or there's a source on the web for it. I'm not yet into files with Python. A sudden need has burst upon me. I'm using Win XP. -- Wayne Watson (Nevada City, CA) Web Page: speckledwithStars.net Hi Wayne, sorry for that: Change OS, and type cat -n program.py numbered.py Just joking, Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)
[RESEND of answer to all initial groups] On 16 Öåâ, 15:45, Steve Holden [EMAIL PROTECTED] wrote: Ilias Lazaridis wrote: [...] Of course I'll not stay with trac, I'll leave the sinking ship, I've prepare long time ago to do so, step by step. An will migrate step by step away from trac and python - toward an own implementation based on... perl and it's libraries. I'm sure you will find the Perl community much more welcoming and receptive to your ideas about how open source projects should be run. The perl projects can decide themselfs if they like to adopt the most essential things: http://case.lazaridis.com/wiki/Project I do not analyze languages and communities anymore, thus there is no need for them to 'worry', e.g. that I attemp to transform them to an high evolutive language system. Ruby and Python were excellent for this (Ruby = weak puppets, Python = egoism driven). I'll just use perl until I've implemented my own language, around 2010 to 2011, which will be most possibly close to perl (or a perl extension, if technically possibly and no legal barriers with libraries). Perl is available in nearly every webserver, and has very nice a logical OO functionality (although it's not very good marketed, this OO part). And perl keeps you highly independent, you can work with simple systems, close to the OS. Really, I don't understand the need for python. And after fighting with some indenting within html templates, I dislike the whitespace- syntax-thing of python again. Fortunately, as you have realized, you have choices and are under no compulsion to use any particular tool. As said above: python (essentially it's community in a wider scope) is an ideal domain to analyze how human egoism blocks evolution of technical systems. Thus, python is an important educational tool. Do it in perl, if you need something more 'pretty', do it in ruby, if you need something more 'serious' do it in java, if you have enough brain and time, do it in C++ from bottom up. And, apparently, do it in Python if you want to avoind running into Ilias Lazaridis. No, I'll be bound to python for some time, a year or so. And good news: as I cannot post to the trac-user group, I'll post the topics to comp.lang.python. (you can thank the project lead of trac, his lack of courage is the reason that the developers get out of control) I have to say your approach to IT systems seems somewhat pedestrian, The IT industry has failed to provide simple standards, systems. AI has failed to produce intelligent systems. So, maybe the IT industry is somewhat pedestrian, as its failure to control egoism has led to terrible software systems. Restarting from the beginning can give the impression of a learning child. but I wish you well in whatever it is you are trying to achieve. http://core.lazaridis.com/wiki/ActivityHistory I hope you have a good set of asbestos (i.e. flame-proof) trousers. As said, the analysis phase is over. But even if not: I've 'survived' within comp.lang.lisp for some months http://groups.google.gr/group/comp.lang.lisp/browse_frm/thread/879809... I think no language community can be worser. - Btw: If you would adopt the open-source-processes to digital electronic design, we would work today still with 8086. http://case.lazaridis.com/wiki/ProjectLead . -- http://mail.python.org/mailman/listinfo/python-list
Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)
[RESEND answer to all initial groups] On 16 Öåâ, 19:15, Jeff Schwab [EMAIL PROTECTED] wrote: Ilias Lazaridis wrote: Essence: snipSpam spam spam spam.../snip I just looked at your resume. http://lazaridis.com/resumes/lazaridis.html (need to update it, lot's of irrelevant stuff, should focus on my failures) What is Abstract Project Management? I've mentioned abstract _product_ management Don't know exactly, I've never tried to articulate the meaning which I've internally. You could extract the meaning from Abstract Base Class or Abstractness in general. Something like universal product management. Or managing a product without having many specific information about it. Something like this _possibly_: http://case.lazaridis.com/wiki/KomodoAudit -- http://mail.python.org/mailman/listinfo/python-list
Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)
Dear Ilias, Post in a single reply. Coko -- http://mail.python.org/mailman/listinfo/python-list
Re: different instances with different data descriptors with the same name
Fabrizio Pollastri wrote: Data descriptors are set as attributes of object types. So if one has many instances of the same class and wants each instance to have a different property (data descriptor) that can be accessed with a unique attribute name, it seems to me that there is no solution with data descriptors. There is any workaround to this? Thank in advance for any help. You can invent a naming convention and then invoke the getter/setter explicitly: class A(object): ... def __getattr__(self, name): ... if not name.startswith(_prop_): ... return getattr(self, _prop_ + name).__get__(self) ... raise AttributeError(name) ... a = A() a.p Traceback (most recent call last): File stdin, line 1, in module File stdin, line 4, in __getattr__ File stdin, line 5, in __getattr__ AttributeError: _prop_p a._prop_p = property(lambda self: self.x * self.x) a.x = 42 a.p 1764 But what are you really trying to do? Peter -- http://mail.python.org/mailman/listinfo/python-list
Need help to figure out urllib2.Request()
Hi folks, I tried to open some web pages with urllib2.Request(url, data, headers), but it always give me a 404 error. Eg. url = 'http://www.whatever.com/somephp.php' data = {} data['id'] = account for i in book2Open: data['book'] = i url_data = urllib.urlencode(data) request = urllib2.Request(url, url_data, headers) response = urllib2.urlopen(request) html = response.read() == HTTPError: HTTP Error 404: Not Found However, the page is retrievable when I manually put url and data together. Eg. url = 'http://www.whatever.com/somephp.php' data = {} data['id'] = account for i in book2Open: data['book'] = i url_data = urllib.urlencode(data) full_url = url + '?' + url_data request = urllib2.Request(full_url, , headers) response = urllib2.urlopen(request) html = response.read() == works fine Any idea ? -- This is a UTF-8 formatted mail --- James C.-C.Yu -- http://mail.python.org/mailman/listinfo/python-list
Re: decode Numeric Character References to unicode
On Feb 18, 3:20 am, William Heymann [EMAIL PROTECTED] wrote: How do I decode a string back to useful unicode that has xml numeric character references in it? Things like #21344; BeautifulSoup can handle two of the three formats for html entities. For instance, an 'o' with umlaut can be represented in three different ways: _ouml_; #246; #xf6; BeautifulSoup can convert the first two formats to unicode: from BeautifulSoup import BeautifulStoneSoup as BSS my_string = '#21344;' soup = BSS(my_string, convertEntities=BSS.XML_ENTITIES) print soup.contents[0].encode('utf-8') print soup.contents[0] --output:--- some asian looking character Traceback (most recent call last): File test1.py, line 6, in ? print soup.contents[0] UnicodeEncodeError: 'ascii' codec can't encode character u'\u5360' in position 0: ordinal not in range(128) The error message shows you the unicode string that BeautifulSoup produced: u'\u5360' If that won't work for you, it's not hard to write you own conversion function to handle all three formats: 1) Create a regex that will match any of the formats 2) Convert the first format using htmlentitydefs.name2codepoint 3) Convert the second format using unichar() 4) Convert the third format using int('0'+ match, 16) and then unichar() -- http://mail.python.org/mailman/listinfo/python-list
Re: decode Numeric Character References to unicode
On Feb 18, 4:53 am, 7stud [EMAIL PROTECTED] wrote: On Feb 18, 3:20 am, William Heymann [EMAIL PROTECTED] wrote: How do I decode a string back to useful unicode that has xml numeric character references in it? Things like #21344; #which is: _#21344_; (without the underscores) BeautifulSoup can handle two of the three formats for html entities. For instance, an 'o' with umlaut can be represented in three different ways: _ouml_; ö ö lol. It's hard to even make posts about this stuff because html entities get converted by the forum software. Here are the three different formats for an 'o with umlaut' with some underscores added to keep the forum software from rendering the characters: _ouml_; _#246_; _#xf6_; -- http://mail.python.org/mailman/listinfo/python-list
Re: decode Numeric Character References to unicode
7stud [EMAIL PROTECTED] wrote: On Feb 18, 4:53 am, 7stud [EMAIL PROTECTED] wrote: On Feb 18, 3:20 am, William Heymann [EMAIL PROTECTED] wrote: How do I decode a string back to useful unicode that has xml numeric cha racter references in it? Things like #21344; #which is: _#21344_; (without the underscores) BeautifulSoup can handle two of the three formats for html entities. For instance, an 'o' with umlaut can be represented in three different ways: _ouml_; ö ö lol. It's hard to even make posts about this stuff because html entities get converted by the forum software. Here are the three different formats for an 'o with umlaut' with some underscores added to keep the forum software from rendering the characters: _ouml_; _#246_; _#xf6_; FWIW, your original post was fine, it was just the quoted text in your followup that was wrong. I guess that is yet another reason to use a real newsreader or the mailing list rather than Google Groups. -- http://mail.python.org/mailman/listinfo/python-list
Re: linux disc space
DataSmash wrote: I simply want to capture the free disc space in a variable so that I can compare changes. I'm aware of a few commands like df -h or du - k, but I can't figure out how to capture those values as a variable. I also looked at os.statvfs(), but that output doesn't seem to make any sense at all to me, knowing the size of the disc. Thanks for your help! R.D. You could use the subprocess module to capture the output of your disk usage commands. -- Posted via a free Usenet account from http://www.teranews.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Seemingly odd 'is' comparison.
Tobiah [EMAIL PROTECTED] wrote: Subject: Seemingly odd 'is' comparison. Please put your question into the body of the message, not just the headers. print float(3.0) is float(3.0) True print float(3.0 * 1.0) is float(3.0) False Thanks, Tobiah Your values are already all floats so float() just returns its arguments. In other words you can omit it: 3.0 is 3.0 True 3.0 * 1.0 is 3.0 False 3.0 used twice in the same compilation unit is the same constant value used twice. 3.0 * 1.0 creates a new float value. Compare with: n = 3.0 n is 3.0 False Here two separate compilations result in two separate values. In general any immutable results of calculations which are the same may or may not share the same object and this can vary according to the version of Python or the phase of the moon. Only use 'is' when you actually care about object identity, don't use it for a shorthand for '=='. -- http://mail.python.org/mailman/listinfo/python-list
Re: decode Numeric Character References to unicode
7stud [EMAIL PROTECTED] writes: For instance, an 'o' with umlaut can be represented in three different ways: '' followed by 'ouml;' '' followed by '#246;' '' followed by '#xf6;' The fourth way, of course, is to simply have 'ö' appear directly as a character in the document, and set the correct character encoding. (Hint: UTF-8 is an excellent choice for the correct character encoding, if you get to choose.) -- \“With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars.” —Raymond Hettinger | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Fate of itertools.dropwhile() and itertools.takewhile()
On Dec 29, 2007 11:10 PM, Raymond Hettinger [EMAIL PROTECTED] wrote: I'm considering deprecating these two functions and would like some feedback from the community or from people who have a background in functional programming. Personally, I'd rather you kept them around. I have no FP background, and I found them easy enough to understand. These thoughts reflect my own experience with the itertools module. It may be that your experience with them has been different. Please let me know what you think. FWIW, I used them only today: http://tinyurl.com/22q6cb Not sure if something that ugly counts as a reason for keeping them around, though! -- Cheers, Simon B. [EMAIL PROTECTED] http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues -- http://mail.python.org/mailman/listinfo/python-list
How to overcome the incomplete download with urllib.urlretrieve ?
This is part of my code that invokes urllib.urlretrieve: for i in link2Visit: localName = i.split('/') i = i.replace(' ', '%20') tgtPath = ['d:\\', 'work', 'python', 'grab_n_view'] localPath = '' for j in tgtPath: localPath = os.path.join(localPath, j) localPath = os.path.join(localPath, localName[-1]) info = urllib.urlretrieve(i, localPath) link2Visit stores the url to some photos. After the script finishes running, I got a pile of incomplete JPG files, each takes only 413 bytes of my disk space. Did I miss something before using urllib.urlretrieve ? -- This is a UTF-8 formatted mail --- James C.-C.Yu -- http://mail.python.org/mailman/listinfo/python-list
Re: different instances with different data descriptors with the same name
On Feb 18, 11:21 am, Fabrizio Pollastri [EMAIL PROTECTED] wrote: Data descriptors are set as attributes of object types. So if one has many instances of the same class and wants each instance to have a different property (data descriptor) that can be accessed with a unique attribute name, it seems to me that there is no solution with data descriptors. There is any workaround to this? Thank in advance for any help. F. Pollastri If you explain your intent you might get some good advice. Here's one idea: [code] class Descriptor(object): val = 0 def __init__(self, initval=0): self.val = initval def __get__(self, obj, objtype): return '%05d' % self.val def __set__(self, obj, val): self.val = val def Factory(attrname, initval=0): class Obj(object): pass setattr(Obj, attrname, Descriptor(initval)) return Obj X = Factory('x') Y = Factory('y', 1) obj1 = X() print obj1.x obj2 = Y() print obj2.y obj2.y = 5 print obj2.y print obj2.x [/code] Outputs: 0 1 5 Traceback (most recent call last): ... AttributeError: 'Obj' object has no attribute 'x' Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: Seemingly odd 'is' comparison.
On Feb 13, 10:19 pm, Tobiah [EMAIL PROTECTED] wrote: print float(3.0) is float(3.0) True print float(3.0 * 1.0) is float(3.0) False [You don't need to wrap your floats in float()] def f(): ... return 3.0 is 3.0, 3.0*1.0 is 3.0 ... f() (True, False) import dis dis.dis(f) 2 0 LOAD_CONST 1 (3.0) 3 LOAD_CONST 1 (3.0) 6 COMPARE_OP 8 (is) 9 LOAD_CONST 3 (3.0) 12 LOAD_CONST 1 (3.0) 15 COMPARE_OP 8 (is) 18 BUILD_TUPLE 2 21 RETURN_VALUE As you can see when 3.0 is 3.0 is evaluated the same float object is put on the stack twice so the 'is' comparison is True (LOAD_CONST 1 / LOAD_CONST 1 / COMPARE_OP 8). Whereas when 3.0*1.0 is 3.0 is evaluated, *two* different float objects are put on the stack and compared (LOAD_CONST 3 / LOAD_CONST 1 / COMPARE_OP 8). Therefore the result is False. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Seemingly odd 'is' comparison.
Tobiah wrote: print float(3.0) is float(3.0) True print float(3.0 * 1.0) is float(3.0) False Thumb rule: Never compare strings, numbers or tuples with is. Only compare an object with a singleton like a type or None. is is not a comparison operator. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a Python Program/Tool That Will Add Line Numbers to a txt File
On Feb 14, 6:54 am, W. Watson [EMAIL PROTECTED] wrote: See Subject. It's a simple txt file, each line is a Python stmt, but I need up to four digits added to each line with a space between the number field and the text. Perhaps someone has already done this or there's a source on the web for it. I'm not yet into files with Python. A sudden need has burst upon me. I'm using Win XP. Not sure if Python program/tool means a tool or a program in Python, but if awk is okay, that's the tool I would use: awk '{printf( %4d %s\n, NR % 1, $0 )}' -- http://mail.python.org/mailman/listinfo/python-list
Re: Could WSGI handle Asynchronous response?
On Feb 18, 7:05 pm, est [EMAIL PROTECTED] wrote: I am writing a small 'comet'-like app using flup, something like this: def myapp(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Flup works!\n'] -Could this be part of response output? Could I time.sleep() for a while then write other outputs? if __name__ == '__main__': from flup.server.fcgi import WSGIServer WSGIServer(myapp, multiplexed=True, bindAddress=('0.0.0.0', )).run() So is WSGI really synchronous? How can I handle asynchronous outputs with flup/WSGI ? figured out myself :blush: :blush: def demo_app(environ,start_response): from StringIO import StringIO stdout = StringIO() print stdout, Hello world! print stdout h = environ.items(); h.sort() for k,v in h: print stdout, k,'=',`v` k=start_response(200 OK, [('Content-Type','text/plain')]) for x in range(1, 100): k(str(x)) time.sleep(1) return [stdout.getvalue()] This function-programming style is very odd :-) and PEP 333 document is so hard for a newbie -- http://mail.python.org/mailman/listinfo/python-list
Re: Pmw Use and Grayson's Book
On Feb 18, 2:29 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: On Feb 18, 5:30 am, W. Watson [EMAIL PROTECTED] wrote: I wonder why he uses it? He uses it because Pmw does a lot of heavy lifting for you when designing Tkinter apps. Pmw adds things like widgets pre-populated with scrollbars and labels and automatic widget/label alignment. I use Pmw for all but the most trivial Tkinter applications. That said, there is nothing in Pmw that you couldn't implement yourself in plain Tkinter, it's just already been done for you. Check out the Pmw site for lots of examples and details. Also, if you do install the module, it comes with a demo directory. Run all.py to see Pmw in action. http://pmw.sourceforge.net If I want to run his examples, where do I put the lib he includes? Same folder as the example? Library modules (like Pmw) generally belong in site-packages (/usr/lib/ python2.x/site-packages in most unixes... not sure about windows). HTH, Pete On Windows, most packages go here (adjust as needed for your setup): C:\Python24\Lib\site-packages Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: flattening a dict
Boris Borcic [EMAIL PROTECTED] wrote: It is more elementary in the mathematician's sense, and therefore preferable all other things being equal, imo. I've tried to split 'gen' but I can't say the result is so much better. def flattendict(d) : gen = lambda L : (x for M in exp(L) for x in rec(M)) exp = lambda L : (L+list(kv) for kv in L.pop().iteritems()) rec = lambda M : gen(M) if isinstance(M[-1],dict) else [M] return dict((tuple(L[:-1]),L[-1]) for L in gen([d])) Why, why, why, why are you using lambda here? It only makes the code harder to read (and it is bad enough without that). A lambda which is assigned directly to a variable is a bad code smell. -- http://mail.python.org/mailman/listinfo/python-list
Re: flattening a dict
Arnaud Delobelle wrote: On Feb 17, 4:03 pm, Boris Borcic [EMAIL PROTECTED] wrote: George Sakkis wrote: On Feb 17, 7:51 am, Arnaud Delobelle [EMAIL PROTECTED] wrote: BTW, I keep using the idiom itertools.chain(*iterable). I guess that during function calls *iterable gets expanded to a tuple. Wouldn't it be nice to have an equivalent one-argument function that takes an iterable of iterables and return the 'flattened' iterable? Indeed; I don't have any exact numbers but I roughly use this idiom as often or more as the case where chain() takes a known fixed number of arguments. The equivalent function you describe is trivial: def chain2(iter_of_iters): for iterable in iter_of_iters: for i in iterable: yield i or fwiw chainstar = lambda iters : (x for it in iters for x in it) - a form that better suggests how to inline it in the calling expression, if applicable. Indeed: def flattendict(d): def gen(d, pfx=()): return (x for k, v in d.iteritems() for x in (gen(v, pfx+(k,)) if isinstance(v, dict) else ((pfx+(k,), v),))) return dict(gen(d)) I don't know, I find the chain(*...) version more readable, In this case I could concede that it is, although I find both forms overly convoluted for easy reading. although this one is probably better. It is more elementary in the mathematician's sense, and therefore preferable all other things being equal, imo. I've tried to split 'gen' but I can't say the result is so much better. def flattendict(d) : gen = lambda L : (x for M in exp(L) for x in rec(M)) exp = lambda L : (L+list(kv) for kv in L.pop().iteritems()) rec = lambda M : gen(M) if isinstance(M[-1],dict) else [M] return dict((tuple(L[:-1]),L[-1]) for L in gen([d])) For fun I've also written a (vaguely prologish) non-recursive generator-based version that exploits undocumented (but logical) behavior of list.extend class iterstack(list) : __iter__ = lambda self : self def next(self) : while self : try : return self[-1].next() except StopIteration : self.pop() raise StopIteration def flattendict(d,stk=[]) : res={} its=iterstack() its.extend(stk[-1].iteritems() for stk[len(its)-1:] in chain([[d]],its) if isinstance(stk[-1],dict) or res.update([(stk.pop(),tuple(stk))[::-1]])) return res (testing was minimal) Challenge for who really has time to waste : replace the iterstack list subclass definition with a simple list + a generator expression inside flattendict. Cheers, BB -- http://mail.python.org/mailman/listinfo/python-list
Re: Could WSGI handle Asynchronous response?
On Mon, 18 Feb 2008 05:27:41 -0800 (PST), est [EMAIL PROTECTED] wrote: On Feb 18, 7:05 pm, est [EMAIL PROTECTED] wrote: I am writing a small 'comet'-like app using flup, something like this: def myapp(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Flup works!\n']-Could this be part of response output? Could I time.sleep() for a while then write other outputs? if __name__ == '__main__': from flup.server.fcgi import WSGIServer WSGIServer(myapp, multiplexed=True, bindAddress=('0.0.0.0', )).run() So is WSGI really synchronous? How can I handle asynchronous outputs with flup/WSGI ? figured out myself :blush: :blush: def demo_app(environ,start_response): from StringIO import StringIO stdout = StringIO() print stdout, Hello world! print stdout h = environ.items(); h.sort() for k,v in h: print stdout, k,'=',`v` k=start_response(200 OK, [('Content-Type','text/plain')]) for x in range(1, 100): k(str(x)) time.sleep(1) return [stdout.getvalue()] You can do this, but notice that you use up a thread (or a process) for each client by doing so. This means you'll be limited to a fairly small number of concurrent clients. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter = Rodney Dangerfield?
[EMAIL PROTECTED] wrote: Tkinter gets no respect. But IDLE's a Tkinter-based app and every example I've Googled up shows Tkinter as needing about half as much code as wx to do the same job. I'm beginning to Tkinter up my language application. Am I making a big mistake? No, you're not. Tkinter is a fine way to code up an application. I prefer it, even using Tkinter for commercial software. See http://www.codebykevin.com/phynchronicity.html for an example. -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter = Rodney Dangerfield?
Gabriel Genellina wrote: I don't like Tk because the widgets are ugly, old-fashioned, and don't have the right look and feel. Take another look. A year or so back Tkinter went to platform native widgets. -- http://mail.python.org/mailman/listinfo/python-list
pycon matplotlib tutorial deadline tomorrow
I will be presenting a tutorial on matplotlib a this year's pycon. If you are coming to the conference, are are already in the Chicago area, you may want to consider signing up for the tutorial http://us.pycon.org/2008/tutorials/ Tomorrow (Monday Feb 18th) is the deadline for registration. Here are some snippets from the proposal which covers the topic list and some additional info: = Intended audience = Tutorial attendees should be familiar with the basics of python and numpy. = Format description = The tutorial is a 20-30 minute overview of matplotlib capabilities, where the presenter will work interactively while explaining the main features and capabilities of matplotlib. After that, the rest of the tutorial will be interactive, hands on, exercises, that are will be a mix of type-along tutorial with students working through examples with help from the instructor. = Promotional summary = Matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. matplotlib can be used in python scripts, the python and ipython shell (ala matlab or mathematica), web application servers, and six graphical user interface toolkits. The tutorial will cover basic plotting from the python shell, and advanced topics like object oriented matplotlib, using matplotlib in a user interface or web application server and interactive event handling. = Tutorial outline = * 30 min: overview of capabilities and type along * 30 min: interactive graphics from the python shell * 30 min: object oriented matplotlib, web application servers and embedding matplotlib in GTK, Qt, Tk, FLTK or WX * 30 min: user interaction and event handling in matplotlib * 30 min: advanced topics * 30 min: question and answer = Presenter = The presenter is the original author and lea developer of matplotlib. After many years in academia, where he developed scientific python software for human intracortical epilepsy recording, he recently departed the confines of academia for the financial industry, where he continues to develop python based solutions for data analysis, modeling and visualization. = Previous presentations and tutorials = * SciPy 2004-6 : matplotlib presentations * PyCon 2005 : matplotlib presentation * SciPy 2006 : led tutorial on data analsysis and visualization with Fernando Perez * ChiPy: matplotlib presentation to the Chicago Python User's Group * UIC : scientific computing in python tutorial at Univ of Illinois Chicago * Py4Science : with Fernando Perez, teach 2 day seminar on scientific computing in python. Sessions at Los Alamos, UC Berkeley, Univ of Michigan, Claremont Colleges Hope to see you there! Let me know if you have any questions or topic requests JDH -- http://mail.python.org/mailman/listinfo/python-list
Re: Could WSGI handle Asynchronous response?
On Feb 18, 10:35 pm, Jean-Paul Calderone [EMAIL PROTECTED] wrote: On Mon, 18 Feb 2008 05:27:41 -0800 (PST), est [EMAIL PROTECTED] wrote: On Feb 18, 7:05 pm, est [EMAIL PROTECTED] wrote: I am writing a small 'comet'-like app using flup, something like this: def myapp(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Flup works!\n'] -Could this be part of response output? Could I time.sleep() for a while then write other outputs? if __name__ == '__main__': from flup.server.fcgi import WSGIServer WSGIServer(myapp, multiplexed=True, bindAddress=('0.0.0.0', )).run() So is WSGI really synchronous? How can I handle asynchronous outputs with flup/WSGI ? figured out myself :blush: :blush: def demo_app(environ,start_response): from StringIO import StringIO stdout = StringIO() print stdout, Hello world! print stdout h = environ.items(); h.sort() for k,v in h: print stdout, k,'=',`v` k=start_response(200 OK, [('Content-Type','text/plain')]) for x in range(1, 100): k(str(x)) time.sleep(1) return [stdout.getvalue()] You can do this, but notice that you use up a thread (or a process) for each client by doing so. This means you'll be limited to a fairly small number of concurrent clients. Jean-Paul- Hide quoted text - - Show quoted text - So, is there any solution that handles this nicely? Or, more specificly, is there any solution that is more 'comet'-like, let's say 'socket'-like than WSGI which could almost do full-dulex HTTP communications, and ready-to-use server client event-based code library? -- http://mail.python.org/mailman/listinfo/python-list
ANN: Phatch = PHoto bATCH processor and renamer based on PIL
I'm pleased to announce the release of Phatch which is a powerful batch processor and renamer. Phatch exposes a big part of the Python Imaging Library through an user friendly GUI. (It is using python-pyexiv2 to offer more extensive EXIF and IPTC support.) Phatch is not targeted at manipulating individual pictures (such as with Gimp), but repeating the same actions on hundreds or thousands of images. If you know PIL and have some nice recipes laying around, it is very easy to write plugins as Phatch generates the corresponding GUI automagically just like in Django. Any existings PIL scripts can be added very easily. Let me know if you want to contribute or have any questions. Homepage: http://photobatch.stani.be (free download link below) Tutorials: http://photobatch.wikidot.com/tutorials Translations: https://translations.launchpad.net/phatch/trunk/+pots/phatch License: GPLv3 Screenshot: http://photobatch.wikidot.com/local--files/start/Screenshot-Phatch3d.jpg (the perspective and reflection is produced by Phatch itself) Phatch has many features, like: - EXIF information inspector with thumbnail - limit jpeg file size when saving - tons of actions organized by tags (including perspective, round corners, shadow, reflection, ...) - console version (Phatch can now run without a gui on servers) - batch rename and copy files based on exif metadata - data stamping (http://photobatch.wikidot.com) - online documentation wiki (http://photobatch.wikidot.com) Linux only features: - desktop or panel droplets on which images or folders can be dropped (will be ported to Windows Mac) - Nautilus and desktop integration (with its own mime type and nautilus extension) - manpage with examples With python-pyexiv2 the following featues are added: - embedding the original EXIF and IPTC tags in the image All actions mostly have a separate pil function in their source code, so they could be read as a recipe book for PIL: * Auto Contrast - Maximize image contrast * Background - Put colour under transparent image * Border - Crop or add border to all sides * Brightness - Adjust brightness from black to white * Canvas - Crop the image or enlarge canvas without resizing the image * Colorize - Colorize grayscale image * Common - Copies the most common pixel value * Contrast - Adjust from grey to black white * Convert Mode - Convert the color mode of an image (grayscale, RGB, RGBA or CMYK) * Copy - Copy image file * Effect - Blur, Sharpen, Emboss, Smooth, ... * Equalize - Equalize the image histogram * Fit - Downsize and crop image with fixed ratio * Grayscale - Fade all colours to gray * Invert - Invert the colors of the image (negative) * Maximum - Copies the maximum pixel value * Mask - Apply a transparency mask * Median - Copies the median pixel value * Minimum - Copies the minimum pixel value * Offset - Offset by distance and wrap around * Posterize - Reduce the number of bits of colour channel * Perspective - Shear 2d or 3d * Rank - Copies the rank'th pixel value * Reflect - Drops a reflection * Rename - Rename image file * Rotate - Rotate with random angle * Round - Round or crossed corners with variable radius and corners * Saturation - Adjust saturation from grayscale to high * Save - Save an image with variable compression in different types * Scale - Scale an image with different resample filters. * Shadow - Drop a blurred shadow under a photo with variable position, blur and color * Solarize - Invert all pixel values above threshold * Text - Write text at a given position * Transpose - Flip or rotate an image by 90 degrees * Watermark - Apply a watermark image with variable placement (offset, scaling, tiling) and opacity I develop Phatch on Ubuntu/Linux, but I have tested and polished it regularly on Windows and Mac Os X. (Only the droplet functionality needs to be ported.) Phatch is submitted to Debian unstable and Ubuntu Hardy. Packagers for other platforms are welcome. Requirements: - PIL 1.1.5 or higher - wxPython 2.6 or higher - pyexiv2 (optional) - python nautilus bindings (optional) Best regards, Stani -- http://pythonide.stani.be -- http://mail.python.org/mailman/listinfo/python-list
RE: Looking for a Python Program/Tool That Will Add Line Numbers to atxt File
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of William Pursell Sent: Monday, February 18, 2008 8:37 AM To: python-list@python.org Subject: Re: Looking for a Python Program/Tool That Will Add Line Numbers to atxt File On Feb 14, 6:54 am, W. Watson [EMAIL PROTECTED] wrote: See Subject. It's a simple txt file, each line is a Python stmt, but I need up to four digits added to each line with a space between the number field and the text. Perhaps someone has already done this or there's a source on the web for it. I'm not yet into files with Python. A sudden need has burst upon me. I'm using Win XP. Not sure if Python program/tool means a tool or a program in Python, but if awk is okay, that's the tool I would use: awk '{printf( %4d %s\n, NR % 1, $0 )}' On a related note, since it's probably easier to install Perl instead of awk on a windows box: type foo.java | perl -ne $counter++; print sprintf(qq(%4d ), $counter), $_; -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux/Python Issues
[EMAIL PROTECTED] wrote: IOW: all this is assumed to be common *n*x knowledge. Both GNOME and KDE put Windows to shame. An old Windows guy, like me, can just start using either one without needing 'common *n*x knowledge.' Too bad the *n*x community isn't more welcoming to outsiders. Linspire's CNR puts Windows DLs to shame, but Python2.5 isn't there. Ugh. -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux/Python Issues
Paul Boddie wrote: Here's one page which probably tells you stuff you already know: http://wiki.python.org/moin/BeginnersGuide/Download Thank you! It says I need Python (which I've got) and the Python-devel package, which sounds like it might include Tkinter and IDLE. Now if only I knew where to get the Python-devel package ... -- http://mail.python.org/mailman/listinfo/python-list
Re: How to overcome the incomplete download with urllib.urlretrieve ?
This isn't super-helpful, but... James Yu wrote: This is part of my code that invokes urllib.urlretrieve: for i in link2Visit: localName = i.split('/') i = i.replace(' ', '%20') You should use urllib.quote or urllib.quote_plus (the latter replaces spaces with + instead of %20) rather than a half-solution that only escapes one character. tgtPath = ['d:\\', 'work', 'python', 'grab_n_view'] localPath = '' for j in tgtPath: localPath = os.path.join(localPath, j) You could do something like: tgtPath = os.path.join('d:\\', 'work', 'python', 'grab_n_view') (and don't repeat it on every loop). localPath = os.path.join(localPath, localName[-1]) What about using os.path.basename() instead of the localName business? info = urllib.urlretrieve(i, localPath) link2Visit stores the url to some photos. After the script finishes running, I got a pile of incomplete JPG files, each takes only 413 bytes of my disk space. Did I miss something before using urllib.urlretrieve ? Try opening one of the files in a text editor. It could be a 404 Not Found error document or something. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Confusion
Many thanks to all. -- http://mail.python.org/mailman/listinfo/python-list
Re: Could WSGI handle Asynchronous response?
On Mon, 18 Feb 2008 06:48:26 -0800 (PST), est [EMAIL PROTECTED] wrote: [snip] So, is there any solution that handles this nicely? Or, more specificly, is there any solution that is more 'comet'-like, let's say 'socket'-like than WSGI which could almost do full-dulex HTTP communications, and ready-to-use server client event-based code library? There are a number. Two based on Twisted: Athena - http://divmod.org/trac/wiki/DivmodNevow/Athena python-cometd - http://svn.xantus.org/shortbus/trunk/cometd-twisted/ (I'm one of the primary authors of the former.) Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux/Python Issues
On 18 Feb, 16:39, [EMAIL PROTECTED] wrote: Paul Boddie wrote: Here's one page which probably tells you stuff you already know: http://wiki.python.org/moin/BeginnersGuide/Download Thank you! It says I need Python (which I've got) and the Python-devel package, which sounds like it might include Tkinter and IDLE. Now if only I knew where to get the Python-devel package ... It would probably be the python-dev package if Linspire really is based on Debian. However, that only gives you the Python headers, as far as I remember. You would also need to get the packages for Tcl/Tk including those providing the headers. And IDLE and Tkinter are separate packages, too. But generally, just asking for the idle or idle-python2.5 packages will give you the stack of packages you need without any further thought required. That said, if the problem is that Linspire doesn't provide Python 2.5 as a package, then you're back to installing the Tcl/Tk packages and then building from source, configuring, building and installing Python as mentioned earlier. You could instead attempt to port the generic Debian package to Linspire, but this isn't for the timid. ;-) If finding Tcl/Tk packages is also a problem, you could build Tcl/Tk from scratch, too - something I've had to do in the distant past on operating systems like Solaris. Then, it's a matter of telling Python's configure program where you installed the Tcl/Tk headers and libraries. Paul P.S. I'm not sure if I can advise you on the specifics around Linspire. Ubuntu and Debian are quite transparent, and you can quite easily find packages for them on packages.ubuntu.com and packages.debian.org respectively. The whole CNR stuff and the proprietary software slant of Linspire obscures the solution, in my opinion. -- http://mail.python.org/mailman/listinfo/python-list
Python-URL! - weekly Python news and links (Feb 18)
QOTW: Syntax can be, and has been, interoperable. The definitions of the telephone network, the Internet, email, and the Web are all bits-on-the-wire definitions of what you send back and forth, and they've all worked well enough to change the world. This belief that bits-on-the-wire is more important than data structures or APIs is at the center of my world view. - Tim Bray, author of, for example, What is RDF Given this indispensable process and architecture issue, isn't it obvious that it's totally irrelevant to the system's overall safety whether the compiler has performed the further smattering of semantically puny 'verifications' allowed by mandatory-declaration, stating-typing languages? - Alex Martelli A problem with itertools.groupby: groups apparently were being emptied before use: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f98e52fede997731/ Should __doubleunderscore__ names be defined by a programmer? http://groups.google.com/group/comp.lang.python/browse_thread/thread/999b15a600da5086/ Floating point numbers, Decimals, the upcoming Fraction type (rational) and their limitations: http://groups.google.com/group/comp.lang.python/browse_thread/thread/50e0e3f948eb94a6/ Also inf and nan support: http://groups.google.com/group/comp.lang.python/browse_thread/thread/3fd33cf86a563d6c/ Very simple RSS/Atom generators: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6ac9d6ecb4c09128/ Looking for replacements to C's __FILE__ and __LINE__ macros: http://groups.google.com/group/comp.lang.python/browse_thread/thread/34f3ef011e3484a Regular expression for prime numbers (?!) http://groups.google.com/group/comp.lang.python/browse_thread/thread/b30c697cbe5f6b82/ Notes on how Python manages memory: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4f906397187a88b9/ The longest thread this week is absolutely off topic, and started two weeks ago: the speed of light, archery as an esoteric knowledge, is pound a unit of mass?, wavicles...: http://groups.google.com/group/comp.lang.python/browse_frm/thread/8c7c359b600881e0/f84617b03f0ddfc1 Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish the efforts of Python enthusiats: http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the Planet sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djqas_ugroup=comp.lang.python.announce Python411 indexes podcasts ... to help people learn Python ... Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and
Re: How to get current module object
Gabriel Genellina wrote: En Sun, 17 Feb 2008 16:25:44 -0200, Alex [EMAIL PROTECTED] escribi�: Can I get reference to module object of current module (from which the code is currently executed)? I know __import__('filename') should probably do that, but the call contains redundant information (filename, which needs to be updated), and it'll perform unnecessary search in loaded modules list. It shouldn't be a real problem (filename can probably be extracted from the traceback anyway), but I wonder if there is more direct and less verbose way. sys.modules[__name__] That's what I've been searching for, thanks. By the way, I know it might be trivial question... but function and class namespaces have __name__ attribute too. Why is global one always returned? Why do you want to get the module object? globals() returns the module namespace, its __dict__, perhaps its only useful attribute... To pass it as a parameter to a function (in another module), so it can work with several modules (plugins for main program) in a similar manner. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get current module object
Alex wrote: function and class namespaces have __name__ attribute too I was wrong - these were function and class _objects'_ namespaces -- http://mail.python.org/mailman/listinfo/python-list
Re: flattening a dict
Duncan Booth wrote: Boris Borcic [EMAIL PROTECTED] wrote: It is more elementary in the mathematician's sense, and therefore preferable all other things being equal, imo. I've tried to split 'gen' but I can't say the result is so much better. def flattendict(d) : gen = lambda L : (x for M in exp(L) for x in rec(M)) exp = lambda L : (L+list(kv) for kv in L.pop().iteritems()) rec = lambda M : gen(M) if isinstance(M[-1],dict) else [M] return dict((tuple(L[:-1]),L[-1]) for L in gen([d])) Why, why, why, why are you using lambda here? Because the 3 lambdas make manifest that they could be combined into a single expression and thus reveal that they replace a single expression. It only makes the code harder to read Matter of perceptions. I myself tend to find def g(...) : def f(x) : return (whatever) return y(f) a bit hard to follow. So frankly I don't feel it betters anything to write def flattendict(d) : def gen(L) : return (x for M in exp(L) for x in rec(M)) def exp(L) : return (L+list(kv) for kv in L.pop().iteritems()) def rec(M) : return gen(M) if isinstance(M[-1],dict) else [M] return dict((tuple(L[:-1]),L[-1]) for L in gen([d])) But whatever to please you Cheers, BB -- http://mail.python.org/mailman/listinfo/python-list
Python 3.0
Is there a logical reason why Python 3 is not backwards compatible? David Blubaugh -Original Message- From: Bill Hart [mailto:[EMAIL PROTECTED] Sent: Friday, February 15, 2008 7:44 PM To: Blubaugh, David A. Subject: Re: scary thought for consideration I don't know, it's in alpha now apparently and is not backwards compatible. Bill. On 16/02/2008, Blubaugh, David A. [EMAIL PROTECTED] wrote: When will Python 3 be available? Thanks, David -Original Message- From: Bill Hart [mailto:[EMAIL PROTECTED] Sent: Friday, February 15, 2008 7:03 PM To: Blubaugh, David A. Subject: Re: scary thought for consideration No it should be fine. Python 3 might cause problems. On 15/02/2008, Blubaugh, David A. [EMAIL PROTECTED] wrote: To All, I am wondering as far as the integration of MyHDL with Python 2.5, if there might be any potential version incompatibility issues? What I mean is will MyHDL not operate correctly, if it is executed with a Python 2.5 version not a Python 2.4? I will be testing to see if this possibility is indeed true over the weekend. Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
MyHDL
Dear Mr. Polo, Yes, I believe that there may indeed be a problem with MyHDL module running under python 2.5 under the windows environment. I have been having extensive problems with importing the MyHDL module. I will provide additional information if required. Thank you very much for all of your help. David Blubaugh -Original Message- From: Guilherme Polo [mailto:[EMAIL PROTECTED] Sent: Sunday, February 17, 2008 11:38 AM To: Blubaugh, David A. Subject: Re: scary thought for consideration 2008/2/15, Blubaugh, David A. [EMAIL PROTECTED]: Dear Polo, I was wondering if there is a possibility that you could provide help with this endeavor? We can need all the good help, that people such as yourself, can provide with this endeavor. Thank you for your direct response. David Blubaugh Hello David, Before anything you should check if it there is any problem with running your modules/project under python 2.5. If there is I can step in and help ;) By the way, previously I sent a copy to you and python-list as well. And sorry for the long delay to answer this. Cheers, -Original Message- From: Guilherme Polo [mailto:[EMAIL PROTECTED] Sent: Friday, February 15, 2008 5:33 PM To: Blubaugh, David A.; python-list@python.org Subject: Re: scary thought for consideration 2008/2/15, Blubaugh, David A. [EMAIL PROTECTED]: To All, I am wondering as far as the integration of MyHDL with Python 2.5, if there might be any potential version incompatibility issues? What I mean is will MyHDL not operate correctly, if it is executed with a Python 2.5 version not a Python 2.4? I will be testing to see if this possibility is indeed true over the weekend. That depends on how custom your project is. Take Zope for example, a lot of effort is being done to make it run under python 2.5. Having a good test suite ready would be a good way to determine if it runs correctly under python 2.5. Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -- http://mail.python.org/mailman/listinfo/python-list -- -- Guilherme H. Polo Goncalves -- -- Guilherme H. Polo Goncalves -- http://mail.python.org/mailman/listinfo/python-list
list mutability
hi im having this code l = [1, 3, 5, 'D', 1, 2, 3, 4, 5, 6, 7, 'A', 'S', 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 'A'] why i need to copy x list? can someone explain me. If i dont copy it i get this result: took_num_range(l) [[1, 2, 3, 4, 5, 6, 7], [6, 5, 4, 3, 2, 1, 0], [6, 5, 4, 3, 2, 1, 0], [6, 5, 4, 3, 2, 1, 0], [6, 5, 4, 3, 2, 1, 0]] but if i copy it i get result as im looking for took_num_range(l) [[1, 2, 3, 4, 5, 6, 7], [9, 8, 7, 6, 5, 4, 3], [8, 7, 6, 5, 4, 3, 2], [7, 6, 5, 4, 3, 2, 1], [6, 5, 4, 3, 2, 1, 0]] def took_num_range(l): j = [] x = [] for i in l: if type(i) is int and len(x) == 7: j.append(x) x = x[:] # im mean here x.pop(0) if type(i) is int and len(x) 7: x.append(i) if type(i) is not int and len(x) == 7: j.append(x) x = [] if type(i) is not int and len(x) != 7: x = [] return j thx -- http://mail.python.org/mailman/listinfo/python-list
average of PIL images
hi i have a set of RGB images of diff faces (of people )as a 2 dim numpyarray ..something like threefaces=array([[xa1,xa2,xa3], [xb1,xb2,xb3], [xc1,xc2,xc3]]) where xa1,xa2,xa3 are tuples each representing rgb values of a pixel of first image .. i need to create the average face image and display it.problem is i need to calculate (xa1+xb1+xc1)/3 etc to calculate avearge value of each pixel.how can i do this calculation.do i need to convert the r,g,b in to a single value for each pixel? the average value of a pixel will be a float isn't it? how can i create a PIL image from this? any help,directive greatly appreciated eric -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0
Blubaugh, David A. a écrit : Is there a logical reason why Python 3 is not backwards compatible? Yes : cleaning up some cruft and warts accumulated from the years. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0
Blubaugh, David A. wrote: Is there a logical reason why Python 3 is not backwards compatible? Yes. For a long time now the next *major* release of Python has been flagged as one which will take the opportunity to remove several design flaws from the original language and add features and syntax that couldn't be added as long as backwards compatibility was maintained. There are, however, significant features in the 2.6 CPython implementation that will assist in migration, including an (optional) warning mode for usages that would cause problems in 3.0 and a tool that will migrate code that doesn't get flagged with warnings through to Python 3.0. So, in summary: 2.6 is the bridge to Python 3.0, and if you use it you won't have too much trouble migrating when the time comes. Note that Python 3.0 is currently at alpha2, and that even when it is released the preferred version will be 2.6. The early adopters will beat the snot out of 3.0, and us ordinary folk will probably not be ready to move until 3.1 or thereabouts. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0
Blubaugh, David A. wrote: Is there a logical reason why Python 3 is not backwards compatible? Yes. It's a conscious decision by the developers and community to get rid of some of the crud and old design decisions that have crept into the language over the last 10+ years. The intent is to keep the incompatibilities to a minimum, but subject to the larger goal of producing a cleaner/better language unhindered by the need of absolute compatibility. Gary Herron David Blubaugh -Original Message- From: Bill Hart [mailto:[EMAIL PROTECTED] Sent: Friday, February 15, 2008 7:44 PM To: Blubaugh, David A. Subject: Re: scary thought for consideration I don't know, it's in alpha now apparently and is not backwards compatible. Bill. On 16/02/2008, Blubaugh, David A. [EMAIL PROTECTED] wrote: When will Python 3 be available? Thanks, David -Original Message- From: Bill Hart [mailto:[EMAIL PROTECTED] Sent: Friday, February 15, 2008 7:03 PM To: Blubaugh, David A. Subject: Re: scary thought for consideration No it should be fine. Python 3 might cause problems. On 15/02/2008, Blubaugh, David A. [EMAIL PROTECTED] wrote: To All, I am wondering as far as the integration of MyHDL with Python 2.5, if there might be any potential version incompatibility issues? What I mean is will MyHDL not operate correctly, if it is executed with a Python 2.5 version not a Python 2.4? I will be testing to see if this possibility is indeed true over the weekend. Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0
-On [20080218 18:33], Blubaugh, David A. ([EMAIL PROTECTED]) wrote: Is there a logical reason why Python 3 is not backwards compatible? The sheer amount of overhaul as documented in http://www.python.org/dev/peps/pep-3100/ makes it already not backwards compatible. Python has been progressing piece by piece, but the 2.x - 3.0 transition allows to clean up some thing in a good way, rather than bolting things on top of others. Anyway, please search around a bit, this kind of stuff has been extensively discussed in the past. -- Jeroen Ruigrok van der Werven asmodai(-at-)in-nomine.org / asmodai イェルーン ラウフロック ヴァン デル ウェルヴェン http://www.in-nomine.org/ | http://www.rangaku.org/ In the dark backward and abysm of time... -- http://mail.python.org/mailman/listinfo/python-list
Re: Developing a Package with Sub Packages
When testing the package in idle, this results in C:\Python25\Lib\idlelib instead of the file. The Data folder is created in this folder now. On 2/18/08, Gabriel Genellina [EMAIL PROTECTED] wrote: En Sun, 17 Feb 2008 22:34:27 -0200, Josh English [EMAIL PROTECTED] escribi�: Here's what I think is happening: IMS/__init__.py uses os.getcwd() to establish the path to the data folder and the files inside of it. When I run StoryCreator, os.getcwd() returns the story folder. If I'm right, how can I get the IMS/__init__.py module to use relative paths to its own module, and not the current working directory the os module provides? Use the module's own __file__ attribute: my_path = os.path.abspath(os.path.dirname(__file__)) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -- Josh English [EMAIL PROTECTED] http://joshenglish.livejournal.com -- http://mail.python.org/mailman/listinfo/python-list
Who is this person?? This is Mohammad
Who is this person?? This is Mohammad Who is this person?? This is Mohammad http://mohammad.islamway.com//?lang=eng -- http://mail.python.org/mailman/listinfo/python-list
Re: different instances with different data descriptors with the same name
En Mon, 18 Feb 2008 08:21:11 -0200, Fabrizio Pollastri [EMAIL PROTECTED] escribi�: Data descriptors are set as attributes of object types. So if one has many instances of the same class and wants each instance to have a different property (data descriptor) that can be accessed with a unique attribute name, it seems to me that there is no solution with data descriptors. There is any workaround to this? Thank in advance for any help. Use __getattr__ or change dynamically each instance's class. See this recent thread: http://groups.google.com/group/comp.lang.python/browse_frm/thread/bfc093464dd6ba9/ -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: list mutability
On Feb 19, 5:09 am, gigs [EMAIL PROTECTED] wrote: hi im having this code l = [1, 3, 5, 'D', 1, 2, 3, 4, 5, 6, 7, 'A', 'S', 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 'A'] why i need to copy x list? can someone explain me. If i dont copy it i get this result: took_num_range(l) [[1, 2, 3, 4, 5, 6, 7], [6, 5, 4, 3, 2, 1, 0], [6, 5, 4, 3, 2, 1, 0], [6, 5, 4, 3, 2, 1, 0], [6, 5, 4, 3, 2, 1, 0]] but if i copy it i get result as im looking for took_num_range(l) [[1, 2, 3, 4, 5, 6, 7], [9, 8, 7, 6, 5, 4, 3], [8, 7, 6, 5, 4, 3, 2], [7, 6, 5, 4, 3, 2, 1], [6, 5, 4, 3, 2, 1, 0]] def took_num_range(l): j = [] x = [] for i in l: if type(i) is int and len(x) == 7: j.append(x) x = x[:] # im mean here x.pop(0) j.append(x) saves a reference to the same list that x refers to. So when you later mutate that one list, all references in j refer to the mutated list. Instead of x = x[:] x.pop(0) which copies the contents twice, you can do x = x[1:] In a more complicated example, it would be better to take a copy at each point: j.append(x[:]) ... then you are sure you have a photo of x and it doesn't matter how/ when you mutate x later. if type(i) is int and len(x) 7: This is a big trap for the casual reader (len(x) may have changed since the previous if statement) ... see below. x.append(i) if type(i) is not int and len(x) == 7: j.append(x) x = [] if type(i) is not int and len(x) != 7: x = [] What do you want to do if your input ends with 7 integers and no letter, e.g. [1,2,3,'A',1,2,3,4,5,6,7] ? return j Some suggestions: 1. use meaningful names 2. don't have hard-wired numbers like 7 3. use else and elif as appropriate to avoid repeating conditions unnecessarily. Here's a suggested replacement for your code, tested to the extent shown: C:\junktype tooknumrange.py def took_num_range(seq, size, grab_end=False): result = [] queue = [] for item in seq: if isinstance(item, int): if len(queue) == size: result.append(queue) queue = queue[1:] queue.append(item) else: if len(queue) == size: result.append(queue) queue = [] if grab_end and len(queue) == size: result.append(queue) return result test1 = [ 1, 3, 5, 'D', 1, 2, 3, 4, 5, 6, 7, 'A', 'S', 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 'A', ] test1r = [ [1, 2, 3, 4, 5, 6, 7], [9, 8, 7, 6, 5, 4, 3], [8, 7, 6, 5, 4, 3, 2], [7, 6, 5, 4, 3, 2, 1], [6, 5, 4, 3, 2, 1, 0], ] test2 = [1, 2, 3, 4, 5] test2r = [[1, 2, 3, 4, 5]] ### or is it [] ??? tests = [ (test1, test1r, 7, False), (test2, [], 5, False), (test2, test2r, 5, True), ] failed = 0 for tno, (tseq, tresult, tsize, tgrab) in enumerate(tests): aresult = took_num_range(tseq, tsize, grab_end=tgrab) if aresult != tresult: failed += 1 print 'Test %d failed' % (tno+1) print 'Expected:', tresult print 'Actual :', aresult print 'Failed %d test(s) out of %d' % (failed, len(tests)) C:\junktooknumrange.py Failed 0 test(s) out of 3 HTH, John -- http://mail.python.org/mailman/listinfo/python-list
RE: Question
Dan, I have been working with examples within the Scipy and Numpy framework. Those are the examples that I have been working with at this time, including the FFT example. The following command: python setup.py install. Is what I did within the Python IDLE environment. However, python was not able to see this script file. Under directory should the MyHDL folder be located?? What I mean by this, should the MyHDL folder be installed in the same directory as where the Scipy folder is located?? If I am not making any sense, please inform me as soon as possible. Thank you for your help. Respectfully, David Blubaugh From: Dan Fabrizio [mailto:[EMAIL PROTECTED] Sent: Monday, February 18, 2008 1:17 PM To: Blubaugh, David A. Subject: Re: Question Hi David, I didn't have any problems with the install on Linux and Mac OS X. Both use python 2.5 python setup.py install. Can you tell me more about the problem you are having? Did you get the basic install to work? Did you try any of the examples? Dan On Feb 18, 2008 12:54 AM, Blubaugh, David A. [EMAIL PROTECTED] wrote: Dan, I am just a little bit curious as to how you installed MyHDL on your Linux machine?? Apparently, I am starting to believe that there are missing files in my installation for windows. Especially, my setup.py file may not be operational within windows. I have not received word from Mr. Decaluwe regarding any thoughts on a combined Scipy/MyHDL hybrid system. There is some internet mail list activity still occuring within the MyHDL site. I believe I will post a message on this forum and see if anyone will respond!! Also, there might be a new member in helping us, in addition to the moderate amount of help from Bill Hart. Thanks for all the help. David Blubaugh -Original Message- From: Blubaugh, David A. Sent: Fri 2/15/2008 5:56 PM To: 'Dan Fabrizio'; 'Dan Fabrizio' Subject: For your information -Original Message- From: Blubaugh, David A. Sent: Fri 2/15/2008 5:56 PM To: 'Dan Fabrizio'; 'Dan Fabrizio' Subject: For your information Dan, This is for your information. I am going to work more this weekend to see if there is a concern with python 2.5 with MyHDL. David -Original Message- From: Guilherme Polo [mailto:[EMAIL PROTECTED] Sent: Friday, February 15, 2008 5:33 PM To: Blubaugh, David A.; python-list@python.org Subject: Re: scary thought for consideration 2008/2/15, Blubaugh, David A. [EMAIL PROTECTED]: To All, I am wondering as far as the integration of MyHDL with Python 2.5, if there might be any potential version incompatibility issues? What I mean is will MyHDL not operate correctly, if it is executed with a Python 2.5 version not a Python 2.4? I will be testing to see if this possibility is indeed true over the weekend. That depends on how custom your project is. Take Zope for example, a lot of effort is being done to make it run under python 2.5. Having a good test suite ready would be a good way to determine if it runs correctly under python 2.5. Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -- http://mail.python.org/mailman/listinfo/python-list -- -- Guilherme H. Polo Goncalves This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After
Re: Developing a Package with Sub Packages
En Mon, 18 Feb 2008 16:23:28 -0200, Josh English [EMAIL PROTECTED] escribi�: When testing the package in idle, this results in C:\Python25\Lib\idlelib instead of the file. The Data folder is created in this folder now. Works for me: main.py: from testpkg import a testpkg directory (a subdirectory somewhere in sys.path): testpkg\__init__.py: (empty file) testpkg\a.py: import os print __name__, __file__, os.path.abspath(os.path.dirname(__file__)) In IDLE: File - Open, main.py. F5 (Run Module). Output: testpkg.a C:\APPS\PYTHON25\lib\site-packages\testpkg\a.pyc C:\APPS\PYTHON25\lib\site-packages\testpkg -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get current module object
En Mon, 18 Feb 2008 14:49:02 -0200, Alex [EMAIL PROTECTED] escribió: Gabriel Genellina wrote: That's what I've been searching for, thanks. By the way, I know it might be trivial question... but function and class namespaces have __name__ attribute too. Why is global one always returned? I don't understand the question (even with the later correction namespaces-objects) Why do you want to get the module object? globals() returns the module namespace, its __dict__, perhaps its only useful attribute... To pass it as a parameter to a function (in another module), so it can work with several modules (plugins for main program) in a similar manner. The function could receive a namespace to work with (a dictionary). Then you just call it with globals() == the namespace of the calling module. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Python for Safety-Critical Software Development for Aerospace Applications
To All, I was wondering if anyone has specific information as to the use of the Python language for the development of Safety-Critical software for aerospace applications?? For example, developing Python-based source code that has been verified to DO-178B Level A certification. Any information, will be more than appreciated. David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: average of PIL images
vaneric wrote: hi i have a set of RGB images of diff faces (of people )as a 2 dim numpyarray ..something like threefaces=array([[xa1,xa2,xa3], [xb1,xb2,xb3], [xc1,xc2,xc3]]) where xa1,xa2,xa3 are tuples each representing rgb values of a pixel of first image .. i need to create the average face image and display it.problem is i need to calculate (xa1+xb1+xc1)/3 etc to calculate avearge value of each pixel.how can i do this calculation. threefaces.mean(axis=0) do i need to convert the r,g,b in to a single value for each pixel? It depends on the problem that you are trying to solve. If monochrome images are acceptable for your problem, then it is probably best to convert all your images to monochrome to do the averaging. At least for a first cut. Averaging color images is tricky; you really shouldn't do it in the RGB colorspace. There are a couple of colorspaces which you could choose; different problems require different colorspaces. the average value of a pixel will be a float isn't it? Yes. how can i create a PIL image from this? # Cast the floating point data to bytes. avgface = avgface.astype(numpy.uint8) # Create the PIL image from the numpy data. img = Image.fromstring('L', (width, height), avgface.tostring()) -- 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: Need help to figure out urllib2.Request()
En Mon, 18 Feb 2008 09:21:10 -0200, James Yu [EMAIL PROTECTED] escribi�: Hi folks, I tried to open some web pages with urllib2.Request(url, data, headers), but it always give me a 404 error. Eg. url = 'http://www.whatever.com/somephp.php' data = {} data['id'] = account for i in book2Open: data['book'] = i url_data = urllib.urlencode(data) request = urllib2.Request(url, url_data, headers) response = urllib2.urlopen(request) html = response.read() == HTTPError: HTTP Error 404: Not Found However, the page is retrievable when I manually put url and data together. Eg. url = 'http://www.whatever.com/somephp.php' data = {} data['id'] = account for i in book2Open: data['book'] = i url_data = urllib.urlencode(data) full_url = url + '?' + url_data request = urllib2.Request(full_url, , headers) response = urllib2.urlopen(request) html = response.read() == works fine Any idea ? The first example uses HTTP POST method; the second HTTP GET. See http://docs.python.org/lib/module-urllib2.html -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Solve a Debate
On Feb 17, 11:23 pm, greg [EMAIL PROTECTED] wrote: Wolfgang Draxinger wrote: Somehow you seem to think, that a lookup table will require more resources (memory I guess you thought) than a sequence of comparisons. However you didn't take into account, that the program code itself requires memory, too (for the operation codes). In Python, there's the additional twist that for lookup tables based on a mutable type, such as a dictionary, you need to execute code to build the dictionary. So you end up using very roughly twice the memory -- for the code to build the dictionary, and the dictionary itself. If the dictionary isn't too huge, and it's looked up many times during each run of the program, the extra speed of the dict lookup is probably worth the overhead of creating it. If the dict is very large, and is consulted relatively few times in a given run, then it might well be faster and not use too much more memory to use a tree (NOT a linear sequence!) of if-else statements in the code. You could also consider loading the dict from some other form, such as a pickle, instead of creating it using code. This would use less memory, although probably would take roughly the same time to set up the table. For extremely large infrequently-used tables, it's probably better to look at not loading the whole table into memory at all, and keeping it in some kind of external indexed structure such as a b-tree, relational database, etc. In other languages, the tradeoffs will be completely different. E.g. in C, if you can describe the table entirely with static data, it'll be very fast to load and incur no overhead for code to create it at all. Also, with demand-paging out of the executable file, and infrequent lookups, only parts of the table will actually get loaded anyway. -- Greg Past a many-small certain point on numbers of hash-tables, if that's the right word, in a program, and intepreter process on a machine, is it be more time-efficient to allocate a 2**32-byte table? Are 'modulo' and 'doublesize' the only steps of the lookup process that it would eliminate, and are they expensive ones? If so, what point? If not, what's a tighter bottleneck? -- http://mail.python.org/mailman/listinfo/python-list
Re: average of PIL images
On Feb 18, 10:18 am, vaneric [EMAIL PROTECTED] wrote: hi i have a set of RGB images of diff faces (of people )as a 2 dim numpyarray ..something like threefaces=array([[xa1,xa2,xa3], [xb1,xb2,xb3], [xc1,xc2,xc3]]) where xa1,xa2,xa3 are tuples each representing rgb values of a pixel of first image .. i need to create the average face image and display it.problem is i need to calculate (xa1+xb1+xc1)/3 etc to calculate avearge value of each pixel.how can i do this calculation.do i need to convert the r,g,b in to a single value for each pixel? the average value of a pixel will be a float isn't it? how can i create a PIL image from this? any help,directive greatly appreciated eric import Numeric arr = Numeric.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]) col1 = arr[0:,0] print col1 sum = 0 count = 0 for num in col1: sum += num count += 1 avg = (sum * 1.0)/count #convert one term to a float to get float result print avg print round(avg) print int(round(avg)) print arr[0] size = len(arr[0]) for i in range(size): col = arr[0:, i] sum = 0 count = 0 for num in col: sum += num count += 1 result = (sum * 1.0) /count print result, result = int(round(result)) print result --output:-- [ 1 4 7 10] 5.5 6.0 6 [1 2 3] 5.5 6 6.5 7 7.5 8 -- http://mail.python.org/mailman/listinfo/python-list
Re: average of PIL images
On Feb 18, 1:58 pm, 7stud [EMAIL PROTECTED] wrote: On Feb 18, 10:18 am, vaneric [EMAIL PROTECTED] wrote: hi i have a set of RGB images of diff faces (of people )as a 2 dim numpyarray ..something like threefaces=array([[xa1,xa2,xa3], [xb1,xb2,xb3], [xc1,xc2,xc3]]) where xa1,xa2,xa3 are tuples each representing rgb values of a pixel of first image .. i need to create the average face image and display it.problem is i need to calculate (xa1+xb1+xc1)/3 etc to calculate avearge value of each pixel.how can i do this calculation.do i need to convert the r,g,b in to a single value for each pixel? the average value of a pixel will be a float isn't it? how can i create a PIL image from this? any help,directive greatly appreciated eric import Numeric arr = Numeric.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]) col1 = arr[0:,0] print col1 sum = 0 count = 0 for num in col1: sum += num count += 1 avg = (sum * 1.0)/count #convert one term to a float to get float result print avg print round(avg) print int(round(avg)) print arr[0] size = len(arr[0]) for i in range(size): col = arr[0:, i] sum = 0 count = 0 for num in col: sum += num count += 1 result = (sum * 1.0) /count print result, result = int(round(result)) print result --output:-- [ 1 4 7 10] 5.5 6.0 6 [1 2 3] 5.5 6 6.5 7 7.5 8 In this statement: col1 = arr[0:,0] the first term is the row or row range, and the second term is the column or column range. If you write this: num = arr[0,0] you get the element in row 0, column 0. But you can also specify ranges for each col or row: num = arr[1:, 2:] That says to get all elements from row 1 to the bottom that are in from column 2 to the end of the row. -- http://mail.python.org/mailman/listinfo/python-list
Re: average of PIL images
On Feb 18, 2:05 pm, 7stud [EMAIL PROTECTED] wrote: num = arr[1:, 2:] That says to get all elements from row 1 to the bottom that are in from column 2 to the end of the row. err.. That says to get all elements from row 1 to the last row which are in column 2, column 3, etc. to the end of the row. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Memory Manager
Paul Rubin wrote: The problem here is with a high allocation rate, you have to GC a lot more often, which typically involves copying live data. This is last century's issue. Copying data, RAM to RAM, is nearly free using the Intel architecture. This short article, http://www.martinrinehart.com/articles/repz.html explains why. I'd use one int per clock as a rule of thumb for the current copy rate in a single-core CPU. -- http://mail.python.org/mailman/listinfo/python-list
Re: average of PIL images
vaneric wrote: hi i have a set of RGB images of diff faces (of people )as a 2 dim numpyarray ..something like threefaces=array([[xa1,xa2,xa3], [xb1,xb2,xb3], [xc1,xc2,xc3]]) where xa1,xa2,xa3 are tuples each representing rgb values of a pixel of first image .. i need to create the average face image and display it.problem is i need to calculate (xa1+xb1+xc1)/3 etc to calculate avearge value of each pixel.how can i do this calculation.do i need to convert the r,g,b in to a single value for each pixel? the average value of a pixel will be a float isn't it? how can i create a PIL image from this? any help,directive greatly appreciated eric Take a look at ImageChops.difference. I've used it to calculate a difference value as follows: diff=ImageChops.difference(im1, im2) totaldiff=sum(ImageStat.Stat(diff)._getmedian()) Maybe at least this will point you in the right direction. -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Garbage collection
Hi, I'm building a server with python, but coming from a c++ background, garbage collection seems strange. For instance, I have a manager looking after many objects in a dict. When those objects are no longer needed, I use del manager[objectid], hoping to force the garbage collector to perform the delete. However, this doesn't trigger my overloaded __del__ destructor. Can I simply rely on the python garbage collector to take it from here? Is there a way to find how many references exist for an object? Thanks Simon -- Linux user #458601 - http://counter.li.org. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Memory Manager
[EMAIL PROTECTED] wrote: Paul Rubin wrote: The problem here is with a high allocation rate, you have to GC a lot more often, which typically involves copying live data. This is last century's issue. Copying data, RAM to RAM, is nearly free using the Intel architecture. This short article, http://www.martinrinehart.com/articles/repz.html explains why. I'd use one int per clock as a rule of thumb for the current copy rate in a single-core CPU. You have a strange idea of nearly free, and I find your analysis a little simplistic. You may take advantage of direct memory access, but cycles are still consumed. I presume also (though here my knowledge of present-day Intel and AMD architectures gets a little sketchy) that many data cache lines could still be invalidated by these moves, and that also has a significant effect on performance. Extending an integer array from 100 to 150 items is a pretty puny operation when you compare it with the amount of data that might need to be moved during a compactifying garbage collection of a 20MB Python program image. Not only that, but all pointers to an object have to be updated when it is relocated. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Question
En Mon, 18 Feb 2008 17:48:57 -0200, Blubaugh, David A. [EMAIL PROTECTED] escribi�: Dan, I have been working with examples within the Scipy and Numpy framework. Those are the examples that I have been working with at this time, including the FFT example. The following command: python setup.py install. Is what I did within the Python IDLE environment. However, python was not able to see this script file. Under directory should the MyHDL folder be located?? What I mean by this, should the MyHDL folder be installed in the same directory as where the Scipy folder is located?? If I am not making any sense, please inform me as soon as possible. Don't do that from inside IDLE. These are some step by step generic instructions to install a new package; they don't assume much about your previous knowledge. 1) Open a command prompt window (or system prompt, or console, or...). Go to the Start menu, click on Run, type cmd (without the quotes), press Enter. 2) See if you can invoke Python directly; type at the command prompt: C:\doesntmatter python -V (use a capital V, press Enter at the end. Don't type the text at the left of the sign). You should get a response like this: Python 2.5.1 If you get a similar response (maybe a different Python version), skip to step 5. If you get an error message telling that python isn't recognized as a command or something, continue on step 3. 3) Let's try to find where Python is located. As you appear to have IDLE installed and working, open it, and execute these two lines: import sys print sys.executable c:\python25\pythonw.exe Take note of the response, but omit the last w. We will call this the full path to python.exe. In the example above, the full path to python.exe would be c:\python25\python.exe 4) Repeat step 2 above, using the full path to python.exe instead of the bare word python: C:\doesntmatter c:\python25\python.exe -V [press Enter] Python 2.5.1 You should get the installed Python version number, not an error. 5) Decompress the package you want to install into any temporary folder -it doesn't matter where- using your favorite tool (WinRar, WinZip, 7zip, the Zip file handler built into WinXP...). Probably you've already done that. Take note of the temporary folder (should contain the setup.py script) 6) Come back to the command prompt and make that temporary folder your current directory, using the cd command. E.g. if it were c:\temp\mypackage-3.2, type: C:\doesntmatter cd c:\temp\mypackage-3.2 [press Enter] c:\temp\mypackage-3.2 7) Now execute: c:\temp\mypackage-3.2 python setup.py install [press Enter] (If you had to go thru steps 3 and 4 above, replace the word python with the full path to python.exe) This should start the package installation; read its documentation for further details. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux/Python Issues
Paul Boddie wrote: The whole CNR stuff and the proprietary software slant of Linspire obscures the solution, in my opinion. Thanks for all your help, Paul. CNR, which is now free, is absolutely marvelous when it's got what you need. If Python2.5 were in the warehouse, I'd have clicked, gone to make a cup of coffee and the appropriate icon would be on my desktop when I came back. If I were Python.org I'd not consider anything ready for release until it was in the warehouse. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Memory Manager
Quoting Steve Holden [EMAIL PROTECTED]: [...] Not only that, but all pointers to an object have to be updated when it is relocated. Any problem in computer science can be solved by another level of indirection -- David John Wheeler ;-) RB -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any Generic RSS/ATOM generator in Python?
On 11 Feb., 15:47, js [EMAIL PROTECTED] wrote: I'm looking for RSS/ATOM generator I can use in Python. I searched on pypi and the other places but I couldn't find any options on this. (I found many parsers, though) Is there any de-fact standard RSS/ATOM generator? (especially, I'd like to create Atom's) Do I have to do it myself from scratch? You didn't specify your use case very much. If you just want to add support for generating Atom/RSS feeds to your app and the format (i.e. which elements and attributes are used) isn't too dynamic, you could just an XML-templating language like Kid or Genshi. The feed generator included in TurboGears uses this approach. I recently packaged this as a separate module: http://chrisarndt.de/projects/turbofeeds/ The module still only makes sense in a TurboGears context but you may want to look at the Kid templates used, they could be used by any app that wants to generate Atom/RSS: http://trac.turbogears.org/browser/projects/TurboFeeds/trunk/turbofeeds/templates Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing a callable object to Thread
On Feb 16, 12:29 pm, Jeff Schwab [EMAIL PROTECTED] wrote: Paul Rubin wrote: Jeff Schwab [EMAIL PROTECTED] writes: Why not? They seem intuitive to me. I would find it weird if you couldn't have 0-tuple, and even weirder if you couldn't have a 1-tuple. Maybe my brain has been warped by too much C++ code. The idea is that a 2-tuple (of numbers, say) is a pair of numbers, a 3-tuple is three numbers, and a 1-tuple is one number. That would mean a number and a 1-tuple of numbers are the same thing, not separate types. No, that doesn't follow. A set with one element is not the same thing as that element, a sequence of one element is not the same thing as that element, and a tuple with one element is not the same thing as that element. Probably the analogue of tuples in human language would be like this: A: What ice-cream flavour do you have? B: Vanilla, Chocolate, and Strawberry If, for example, he only have Vanilla: A: What ice-cream flavour do you have? B: Vanilla This way of thinking makes 1-tuple the same as the element itself. -- http://mail.python.org/mailman/listinfo/python-list
Re: Garbage collection
Simon Pickles wrote: Hi, I'm building a server with python, but coming from a c++ background, garbage collection seems strange. For instance, I have a manager looking after many objects in a dict. When those objects are no longer needed, I use del manager[objectid], hoping to force the garbage collector to perform the delete. However, this doesn't trigger my overloaded __del__ destructor. Can I simply rely on the python garbage collector to take it from here? Objects are deleted at some undefined time after there are no references to the object. You will need to change your thinking about how destructors work. It is very different from C++. The good news is that you almost never have to do anything to clean up. My guess is that you might not even need to overload __del__ at all. People from a C++ background often mistakenly think that they have to write destructors when in fact they do not. What is your __del__ method doing? Is there a way to find how many references exist for an object? yes: from sys import getrefcount print getrefcount(x) Thanks Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Memory Manager
[EMAIL PROTECTED] wrote: Paul Rubin wrote: The problem here is with a high allocation rate, you have to GC a lot more often, which typically involves copying live data. This is last century's issue. Copying data, RAM to RAM, is nearly free using the Intel architecture. What's the Intel architecture? Do you mean the x86_64 architecture that was actually developed by AMD, or x86 for x some number, or do you actually mean IA64? This short article, http://www.martinrinehart.com/articles/repz.html explains why. I'd use one int per clock as a rule of thumb for the current copy rate in a single-core CPU. -- http://mail.python.org/mailman/listinfo/python-list
Double underscores -- ugly?
Hi guys, I've been using Python for some time now, and am very impressed with its lack of red tape and its clean syntax -- both probably due to the BDFL's ability to know when to say no. Most of the things that got me initially have been addressed in recent versions of Python, or are being addressed in Python 3000. But it looks like the double underscores are staying as is. This is probably a good thing unless there are better alternatives, but ... Is it just me that thinks __init__ is rather ugly? Not to mention if __name__ == '__main__': ...? I realise that double underscores make the language conceptually cleaner in many ways (because fancy syntax and operator overloading are just handled by methods), but they don't *look* nice. A solution could be as simple as syntactic sugar that converted to double underscores behind the scenes. A couple of ideas that come to my mind (though these have their problems too): def ~init(self): # shows it's special, but too like a C++ destructor def +init(self): # a bit too additive :-) defop add(self, other): # or this, equivalent to def __add__ def operator add(self, other): # new keyword, and a bit wordy Has anyone thought about alternatives? Is there a previous discussion on this I can look up? Cheers, Ben. -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux/Python Issues
[EMAIL PROTECTED] schrieb: [EMAIL PROTECTED] wrote: IOW: all this is assumed to be common *n*x knowledge. Both GNOME and KDE put Windows to shame. An old Windows guy, like me, can just start using either one without needing 'common *n*x knowledge.' Too bad the *n*x community isn't more welcoming to outsiders. Linspire's CNR puts Windows DLs to shame, but Python2.5 isn't there. Ugh. I might destroying pink dreams of windows cozyness, but to my knowledge *compiling* something under windows is at least as hard, if not harder, than under linux. As I said - I use ubuntu, and do issue an apt-get install python2.5 and afterwards I end up with a python2.5 including Tkinter and whatnot. You deliberately chose to do otherwise, goind the hard way - don't expect to be your hands being hold. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Seemingly odd 'is' comparison.
On Mon, 18 Feb 2008 14:11:53 +0100, Christian Heimes wrote: Tobiah wrote: print float(3.0) is float(3.0) True print float(3.0 * 1.0) is float(3.0) False Thumb rule: Never compare strings, numbers or tuples with is. Only compare an object with a singleton like a type or None. is is not a comparison operator. I know why you're saying it, I agree with your reasons, but I wouldn't say it that way. Never use is when you want to test for EQUALITY, regardless of whether the objects are strings, numbers, tuples, or anything else. To test for equality, use ==. Always use is when you wish to compare objects for IDENTITY, such as testing to see whether an object IS None (as opposed to some random object which just happens to compare equal to None). is is a comparison operator: it compares identity, not equality. It is more or less equivalent to the expression id(x) == id(y). Except for documented singletons such as modules and None, which objects have the same identity is platform dependent, version dependent, and even dependent on the execution history of your code. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing a callable object to Thread
On Feb 18, 4:26 pm, Jeff Schwab [EMAIL PROTECTED] wrote: Lie wrote: On Feb 16, 12:29 pm, Jeff Schwab [EMAIL PROTECTED] wrote: Paul Rubin wrote: Jeff Schwab [EMAIL PROTECTED] writes: Why not? They seem intuitive to me. I would find it weird if you couldn't have 0-tuple, and even weirder if you couldn't have a 1-tuple. Maybe my brain has been warped by too much C++ code. The idea is that a 2-tuple (of numbers, say) is a pair of numbers, a 3-tuple is three numbers, and a 1-tuple is one number. That would mean a number and a 1-tuple of numbers are the same thing, not separate types. No, that doesn't follow. A set with one element is not the same thing as that element, a sequence of one element is not the same thing as that element, and a tuple with one element is not the same thing as that element. Probably the analogue of tuples in human language would be like this: A: What ice-cream flavour do you have? B: Vanilla, Chocolate, and Strawberry If, for example, he only have Vanilla: A: What ice-cream flavour do you have? B: Vanilla This way of thinking makes 1-tuple the same as the element itself. Yes. I first heard the term tuple in a physics class, where it was used to mean that a mathematical function took an arbitrary number of objects. It was by analog with triple, quadruple, quintuple... n-tuple. That's a different context than computer science, though, which is a specific branch of mathematics with its own terminology. In CS, a tuple is a kind of data structure that is specifically not identical with any of its elements. That's the sort of tuple used in Python.- Hide quoted text - a= object() (a,) is a False (a,) is (a,) False a is a True (a,) == (a,) True a= [] a.append( a ) a [[...]] tuple(a) is tuple(a) False hasVanilla= True hasStrawberry= True hasChocolate= True if hasVanilla: print Vanilla if hasVanilla and not hasChocolate: print and if hasStrawberry: print Strawberry if hasVanilla or hasStrawberry and hasChocolate: print and if hasChocolate: print Chocolate. -- http://mail.python.org/mailman/listinfo/python-list
RE: Question
I have already solved that problem. Sorry for not alerting you as to me of solving this issue. Thank you very much for the help. I was wondering if you would be interested in helping in the development of a Scipy / MyHDL hybrid. The advantage of this would be to develop FPGA logic with the ease of Python programming. This would especially be helpful in the development of a rapid DSP development system for FPGAS. The rapid speed one could possibly obtain with this system might well be a great deal faster that FPGA development with MATLAB. Thank you for your help. David Blubaugh -Original Message- From: Gabriel Genellina [mailto:[EMAIL PROTECTED] Sent: Monday, February 18, 2008 4:24 PM To: python-list@python.org Subject: Re: Question En Mon, 18 Feb 2008 17:48:57 -0200, Blubaugh, David A. [EMAIL PROTECTED] escribi : Dan, I have been working with examples within the Scipy and Numpy framework. Those are the examples that I have been working with at this time, including the FFT example. The following command: python setup.py install. Is what I did within the Python IDLE environment. However, python was not able to see this script file. Under directory should the MyHDL folder be located?? What I mean by this, should the MyHDL folder be installed in the same directory as where the Scipy folder is located?? If I am not making any sense, please inform me as soon as possible. Don't do that from inside IDLE. These are some step by step generic instructions to install a new package; they don't assume much about your previous knowledge. 1) Open a command prompt window (or system prompt, or console, or...). Go to the Start menu, click on Run, type cmd (without the quotes), press Enter. 2) See if you can invoke Python directly; type at the command prompt: C:\doesntmatter python -V (use a capital V, press Enter at the end. Don't type the text at the left of the sign). You should get a response like this: Python 2.5.1 If you get a similar response (maybe a different Python version), skip to step 5. If you get an error message telling that python isn't recognized as a command or something, continue on step 3. 3) Let's try to find where Python is located. As you appear to have IDLE installed and working, open it, and execute these two lines: import sys print sys.executable c:\python25\pythonw.exe Take note of the response, but omit the last w. We will call this the full path to python.exe. In the example above, the full path to python.exe would be c:\python25\python.exe 4) Repeat step 2 above, using the full path to python.exe instead of the bare word python: C:\doesntmatter c:\python25\python.exe -V [press Enter] Python 2.5.1 You should get the installed Python version number, not an error. 5) Decompress the package you want to install into any temporary folder -it doesn't matter where- using your favorite tool (WinRar, WinZip, 7zip, the Zip file handler built into WinXP...). Probably you've already done that. Take note of the temporary folder (should contain the setup.py script) 6) Come back to the command prompt and make that temporary folder your current directory, using the cd command. E.g. if it were c:\temp\mypackage-3.2, type: C:\doesntmatter cd c:\temp\mypackage-3.2 [press Enter] c:\temp\mypackage-3.2 7) Now execute: c:\temp\mypackage-3.2 python setup.py install [press Enter] (If you had to go thru steps 3 and 4 above, replace the word python with the full path to python.exe) This should start the package installation; read its documentation for further details. -- Gabriel Genellina This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Understanding While Loop Execution
Hi folks, I'm still fairly new to programming in python and programming in general. A friend of mine is in a CompSci 101 course and was working on a slider game when he encountered a problem. We eventually figured out what the problem was and built a test case to help solve it, but I can't for the life of me figure out the why behind it. I tried googling it and searching the list but didn't find anything that really explained it. I'm sure it's probably just both of us misunderstanding what the while statement does. So I hoped to ask for some clarification here. So here is what we worked out was going on with his code. from random import shuffle mylist=[2,1,3] baselist=[1,2,3] newlist=[] count=0 while mylist!=baselist: count+=1 shuffle(mylist) newlist.append(mylist) print count, mylist, newlist Output: 1 [3, 1, 2] [[3, 1, 2]] 2 [1, 2, 3] [[1, 2, 3], [1, 2, 3]] What he wanted was a list of lists to use later as a replay. What we expected newlist.append(mylist) to do was to save a copy of mylist into the collection for each iteration of the while statement. However, what struck us as odd is that for each time the while loop executes it changes all the lists in the list. What I found even exasperating was if I created yet another list. from random import shuffle mylist=[2,1,3] baselist=[1,2,3] newlist=[] saved_shufs=[] count=0 while mylist!=baselist: count+=1 shuffle(mylist) newlist.append(mylist) saved_shufs.append(newlist[0]) print count, mylist, newlist[0], saved_shufs Output: 1 [1, 3, 2] [1, 3, 2] [[1, 3, 2]] 2 [3, 2, 1] [3, 2, 1] [[3, 2, 1], [3, 2, 1]] 3 [1, 2, 3] [1, 2, 3] [[1, 2, 3], [1, 2, 3], [1, 2, 3]] newlist[0] printed out correctly but when appending it into saved_shufs it still overwrote everything. Eventually, after plinking about I remembered that tuples were immutable and wound up creating a variable like tuple_of_mylist=tuple(mylist) then appending that into newlist. That kept the list of tuples fine. I'm still wondering though what I'm not grasping about while that made it do that to the lists? Or is it not even while, is it something else I'm not getting? Thanks in advance, B -- http://mail.python.org/mailman/listinfo/python-list
Re: flattening a dict
On Mon, 18 Feb 2008 14:03:20 +, Duncan Booth wrote: Why, why, why, why are you using lambda here? It only makes the code harder to read (and it is bad enough without that). A lambda which is assigned directly to a variable is a bad code smell. Oh come on. I don't get this allergy to lambda that so many people have. Look at the example given: def flattendict(d) : gen = lambda L : (x for M in exp(L) for x in rec(M)) exp = lambda L : (L+list(kv) for kv in L.pop().iteritems()) rec = lambda M : gen(M) if isinstance(M[-1],dict) else [M] return dict((tuple(L[:-1]),L[-1]) for L in gen([d])) The hard-to-read doesn't come from the lambda (which only adds a keyword and a name to each function), but the algorithm, which combines recursion, generator expressions, and tight coupling between three functions. Would the function be any easier to read written like this? # Untested def flattendict(d): def gen(L): return (x for M in exp(L) for x in rec(M)) def exp(L): return (L+list(kv) for kv in L.pop().iteritems()) def rec(M): return gen(M) if isinstance(M[-1],dict) else [M] return dict((tuple(L[:-1]),L[-1]) for L in gen([d])) No. The function is hard to read, not because it uses lambdas, but because it is obfuscated Python. The lambda syntax doesn't contribute to the obfuscation. And as for your point about bad code smells, no, I don't agree. If your function consists of a single expression, and you don't expect func.__name__ to have a meaningful value, then there's nothing wrong with using a named lambda. Anonymous functions are first-class objects in Python, just as classes and modules and named functions are, and people shouldn't make up superstitious rules about not assigning them to names. def foo(x): return x+1 foo = lambda x: x+1 The first case uses TWO keywords, a name, a declared argument and an expression; the lambda form uses ONE keyword, a name, a declared argument and an expression. The problem with lambdas comes from people trying to hammer multi- expression functions into a single-expression lambda, hence obfuscating the algorithm. That's no different from people who obfuscate multi- expression functions by writing them as a generator expression. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing a callable object to Thread
Lie wrote: On Feb 16, 12:29 pm, Jeff Schwab [EMAIL PROTECTED] wrote: Paul Rubin wrote: Jeff Schwab [EMAIL PROTECTED] writes: Why not? They seem intuitive to me. I would find it weird if you couldn't have 0-tuple, and even weirder if you couldn't have a 1-tuple. Maybe my brain has been warped by too much C++ code. The idea is that a 2-tuple (of numbers, say) is a pair of numbers, a 3-tuple is three numbers, and a 1-tuple is one number. That would mean a number and a 1-tuple of numbers are the same thing, not separate types. No, that doesn't follow. A set with one element is not the same thing as that element, a sequence of one element is not the same thing as that element, and a tuple with one element is not the same thing as that element. Probably the analogue of tuples in human language would be like this: A: What ice-cream flavour do you have? B: Vanilla, Chocolate, and Strawberry If, for example, he only have Vanilla: A: What ice-cream flavour do you have? B: Vanilla This way of thinking makes 1-tuple the same as the element itself. Yes. I first heard the term tuple in a physics class, where it was used to mean that a mathematical function took an arbitrary number of objects. It was by analog with triple, quadruple, quintuple... n-tuple. That's a different context than computer science, though, which is a specific branch of mathematics with its own terminology. In CS, a tuple is a kind of data structure that is specifically not identical with any of its elements. That's the sort of tuple used in Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: flattening a dict
On Feb 18, 10:22 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: [...] The problem with lambdas comes from people trying to hammer multi- expression functions into a single-expression lambda, hence obfuscating the algorithm. That's no different from people who obfuscate multi- expression functions by writing them as a generator expression. I'm sorry if my Python is difficult to understand. That's because I've got a bit of a Lisp... -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: flattening a dict
Arnaud Delobelle wrote: On Feb 18, 10:22 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: [...] The problem with lambdas comes from people trying to hammer multi- expression functions into a single-expression lambda, hence obfuscating the algorithm. That's no different from people who obfuscate multi- expression functions by writing them as a generator expression. I'm sorry if my Python is difficult to understand. That's because I've got a bit of a Lisp... That may be the first lambda-related humor I've ever heard. -- http://mail.python.org/mailman/listinfo/python-list
Re: Double underscores -- ugly?
benhoyt [EMAIL PROTECTED] writes: I realise that double underscores make the language conceptually cleaner in many ways (because fancy syntax and operator overloading are just handled by methods), but they don't *look* nice. That's a good thing, in that it draws attention to the names. The convention is by design: these names will be treated specially, so they should stand out visually to the reader. A solution could be as simple as syntactic sugar that converted to double underscores behind the scenes. A couple of ideas that come to my mind (though these have their problems too): def ~init(self): # shows it's special, but too like a C++ destructor def +init(self): # a bit too additive :-) defop add(self, other): # or this, equivalent to def __add__ def operator add(self, other): # new keyword, and a bit wordy None of these, IMO, meet the needs to stand out requirement met by double-underscore names. They also introduce special cases for the language parser (and thus for the reader to understand how the language will be parsed), whereas double-underscore names work without any special syntax handling. -- \ “Holy contributing to the delinquency of minors, Batman!” | `\—Robin | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing a callable object to Thread
[EMAIL PROTECTED] wrote: On Feb 18, 4:26 pm, Jeff Schwab [EMAIL PROTECTED] wrote: Lie wrote: On Feb 16, 12:29 pm, Jeff Schwab [EMAIL PROTECTED] wrote: Paul Rubin wrote: Jeff Schwab [EMAIL PROTECTED] writes: Why not? They seem intuitive to me. I would find it weird if you couldn't have 0-tuple, and even weirder if you couldn't have a 1-tuple. Maybe my brain has been warped by too much C++ code. The idea is that a 2-tuple (of numbers, say) is a pair of numbers, a 3-tuple is three numbers, and a 1-tuple is one number. That would mean a number and a 1-tuple of numbers are the same thing, not separate types. No, that doesn't follow. A set with one element is not the same thing as that element, a sequence of one element is not the same thing as that element, and a tuple with one element is not the same thing as that element. Probably the analogue of tuples in human language would be like this: A: What ice-cream flavour do you have? B: Vanilla, Chocolate, and Strawberry If, for example, he only have Vanilla: A: What ice-cream flavour do you have? B: Vanilla This way of thinking makes 1-tuple the same as the element itself. Yes. I first heard the term tuple in a physics class, where it was used to mean that a mathematical function took an arbitrary number of objects. It was by analog with triple, quadruple, quintuple... n-tuple. That's a different context than computer science, though, which is a specific branch of mathematics with its own terminology. In CS, a tuple is a kind of data structure that is specifically not identical with any of its elements. That's the sort of tuple used in Python.- Hide quoted text - a= object() (a,) is a False (a,) is not identical with a. (a,) is (a,) False The tuple on the left is not identical with the tuple on the right, even though they are equivalent. a is a True The variable on the left is identical with the one on the right. This is not the same comparison as (a,) is (a,), which actually contains the construction of two distinct objects. The moral equivalent of a is a would be: b = (a,) b is b True An interesting thing about Python is that numbers of built-in types are flyweights. Unlike literals of non-flyweight types, distinct instances of a given numeric literal actually refer to the same object: 5 is 5 True 99 is 99 True 3.5 is 3.5 True I wonder, will this be true of the upcoming Fraction class? (a,) == (a,) True The two tuples are equivalent (though not identical). a= [] a.append( a ) a [[...]] That's cool. I don't think would have known off the top of my head how the interactive interpreter would display something like that. Talk about a cyclic reference... tuple(a) is tuple(a) False The tuple on the left is not identical with the tuple on the right, even though they are equivalent. This is the sample as one of your earlier examples, just with slightly different syntax. hasVanilla= True hasStrawberry= True hasChocolate= True if hasVanilla: print Vanilla if hasVanilla and not hasChocolate: print and if hasStrawberry: print Strawberry if hasVanilla or hasStrawberry and hasChocolate: print and if hasChocolate: print Chocolate. You've tried to implement a set using a set of flags to indicate whether various items have membership in that set. See how an object representing a given flavor would have to be distinct from the object (boolean flag) indicating its set membership? Btw, your formatting could use some work. :) Some flavor combinations cause extra ands to be printed. Here's a little test harness, with PEP-friendly variable names, and showing how your booleans corresponding directly with traditional bit-bucket flag sets: def print_flavors(flags): print flags vanilla = flags 1 strawberry = flags 2 chocolate = flags 4 if vanilla: print Vanilla if vanilla and not chocolate: print and if strawberry: print Strawberry if vanilla or strawberry and chocolate: print and if chocolate: print Chocolate. if __name__ == '__main__': for flavor_flags in range(8): print_flavors(flavor_flags) -- http://mail.python.org/mailman/listinfo/python-list
Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)
[EMAIL PROTECTED] schrieb: Dear Ilias, Post in a single reply. He has to, in hopes to gain the traction he desires - as otherwise he's pretty much ignored these days. Which is a good thing of course... Diez -- http://mail.python.org/mailman/listinfo/python-list