Leo 4.4.4 beta 3 released
Leo 4.4.4 beta 3 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106 Leo 4.4.4 contains many important features originally planned for later releases. It's been a good month :-) Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.4: - The Great Graph Aha (tm): simple scripts allow Leo outlines to represent arbitrary directed graphs. There is no need for a separate 'graph world'. The graphed.py plugin is a direct result of this Aha. The graphed.py plugin allows you to create general graphs from Leo outlines. - @menus trees in settings files create all of Leo's menus. It is now dead easy to make Leo's menus look the way you want. - @buttons trees in settings files create common @button nodes created in all Leo outlines. - @auto nodes eliminate sentinels in derived files, thereby allowing people to collaborate using Leo more easily. - New commands for resolving cvs conflicts. - A threading_colorizer plugin replaces the __jEdit_colorizer__ plugin. This plugin features much better performance and a new, elegant algorithm. - Leo is now compatible with jython. - The usual assortment of bug fixes and other minor improvements. Links: -- Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html Edward K. Ream email: [EMAIL PROTECTED] Leo: http://webpages.charter.net/edreamleo/front.html -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Monitoring external processes
On Oct 23, 3:09 pm, [EMAIL PROTECTED] wrote: Hi, Is there a way to track external processes launched by python on the Mac? I am using subprocess module to launch the process. Thanks Sunil If using Python 2.3/2.4, you can use os.wait(). If using Python 2.5, there is also have os.wait3() and os.wait4(). See the operating system manual pages for the difference. Ie., man wait4 Graham -- http://mail.python.org/mailman/listinfo/python-list
Re: ignoring chinese characters parsing xml file
Fabian López wrote: Thanks Mark, the code is like this. The attrib name is the problem: from lxml import etree context = etree.iterparse(file.xml) for action, elem in context: if elem.tag == weblog: print action, elem.tag , elem.attrib[name],elem.attrib[url], The problem is the print statement. Looks like your terminal encoding (that Python needs to encode the unicode string to) can't handle these unicode characters. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: ignoring chinese characters parsing xml file
On 10/23/07, Fabian López [EMAIL PROTECTED] wrote: Hi, I am parsing an XML file that includes chineses characters, like ^�u�u啖啖才是�w.���扉L锍才是�� or ヘアアイロン... The problem is that I get an error like: UnicodeEncodeerror:'charmap' codec can't encode characters in position The thing is that I would like to ignore it and parse all the characters less these ones. So, could anyone help me? I suppose that I can catch an exception that ignores it or maybe use any function that detects this chinese characters and after that ignore them. Sorry, that's not Chinese but Japanese. And I don't know which encoding is in the source xml, because most of xml files should be encoded in utf-8, and it'll be ok for CJK characters, and how did you get this error? -- I like python! UliPad The Python Editor: http://code.google.com/p/ulipad/ meide wxPython UI module: http://code.google.com/p/meide/ My Blog: http://www.donews.net/limodou -- http://mail.python.org/mailman/listinfo/python-list
Microsoft drops appeal of European antitrust case
On Oct 22, 9:25 pm, [EMAIL PROTECTED] wrote: Microsoft drops appeal of European antitrust case template_bas template_bas The software giant, which faces a $1 billion fine, will make some of its Windows operating system code available so developers can better design products for it. By Jim Puzzanghera, Los Angeles Times Staff Writer 11:43 AM PDT, October 22, 2007 WASHINGTON -- Microsoft Corp. will drop its appeal of a long-running and costly European antitrust case and make some of its highly guarded software code available at low prices so developers can better design products that work with the Windows operating system, European officials said today. The decision came after Europe's second-highest court last month rejected Microsoft's appeal of a 2004 antitrust decision that had led to a record $703-million fine for abuse of its dominance in computer operating systems. On top of that fine, the European Commission in 2005 started levying a daily noncompliance fine against Microsoft that has brought the total to more than $1 billion. Running out of legal options, Microsoft agreed to abide by the 2004 decision, ending a case that began in 1998, said Neelie Kroes, European Commissioner for Competition Policy. Now that Microsoft has agreed to comply with the 2004 decision, the company can no longer use the market power it derived from its 95% share of the PC operating system market and 80% profit margin to harm consumers by killing competition on any market it wishes, she said in a written statement. Kroes said she had been in almost daily contact with Microsoft Chief Executive Steve Ballmer over the last two or three weeks in an attempt to resolve the case. Microsoft agreed to drop its appeal and provide information to software developers to allow their products to work with Windows. Microsoft had agreed to provide the information before but at costs that European officials said were wholly unreasonable, Kroes said. Microsoft said in a statement that it would continue to work closely with the commission and the industry to ensure a flourishing and competitive environment for information technology in Europe and around the world. The Redmond, Wash., company will lower its fee for a worldwide license to use its software code, from 5.95% of the requesting company's revenue to just 0.4%. Microsoft also dropped its demand for a royalty of 2.98% of the money made from software developed using Microsoft's protocols. Now, companies will have to pay only a one-time fee of 10,000 euros, or about $14,161. Microsoft also will make its code available to open-source developers, such as those that design applications for the Linux operating system, under terms that allow other users of the software to copy and modify it. Microsoft's obligation to document its protocols is an ongoing one -- the documentation needs to be maintained as products evolve and new issues may arise once it is being used by developers, Kroes said. But as of today, the major issues concerning compliance have been resolved. Microsoft officials declined to comment. [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
It's The Oil
On Oct 22, 9:34 pm, [EMAIL PROTECTED] wrote: Hiroshima,Nagasaki,Genocide in Australia and North America http://countercurrents.org/holt221007.htm It's The Oil By Jim Holt 22 October, 2007 London Review Of Books Iraq is 'unwinnable', a 'quagmire', a 'fiasco': so goes the received opinion. But there is good reason to think that, from the Bush-Cheney perspective, it is none of these things. Indeed, the US may be 'stuck' precisely where Bush et al want it to be, which is why there is no 'exit strategy'. Iraq has 115 billion barrels of known oil reserves. That is more than five times the total in the United States. And, because of its long isolation, it is the least explored of the world's oil-rich nations. A mere two thousand wells have been drilled across the entire country; in Texas alone there are a million. It has been estimated, by the Council on Foreign Relations, that Iraq may have a further 220 billion barrels of undiscovered oil; another study puts the figure at 300 billion. If these estimates are anywhere close to the mark, US forces are now sitting on one quarter of the world's oil resources. The value of Iraqi oil, largely light crude with low production costs, would be of the order of $30 trillion at today's prices. For purposes of comparison, the projected total cost of the US invasion/occupation is around $1 trillion. Who will get Iraq's oil? One of the Bush administration's 'benchmarks' for the Iraqi government is the passage of a law to distribute oil revenues. The draft law that the US has written for the Iraqi congress would cede nearly all the oil to Western companies. The Iraq National Oil Company would retain control of 17 of Iraq's 80 existing oilfields, leaving the rest - including all yet to be discovered oil - under foreign corporate control for 30 years. 'The foreign companies would not have to invest their earnings in the Iraqi economy,' the analyst Antonia Juhasz wrote in the New York Times in March, after the draft law was leaked. 'They could even ride out Iraq's current instability by signing contracts now, while the Iraqi government is at its weakest, and then wait at least two years before even setting foot in the country.' As negotiations over the oil law stalled in September, the provincial government in Kurdistan simply signed a separate deal with the Dallas-based Hunt Oil Company, headed by a close political ally of President Bush. How will the US maintain hegemony over Iraqi oil? By establishing permanent military bases in Iraq. Five self-sufficient 'super-bases' are in various stages of completion. All are well away from the urban areas where most casualties have occurred. There has been precious little reporting on these bases in the American press, whose dwindling corps of correspondents in Iraq cannot move around freely because of the dangerous conditions. (It takes a brave reporter to leave the Green Zone without a military escort.) In February last year, the Washington Post reporter Thomas Ricks described one such facility, the Balad Air Base, forty miles north of Baghdad. A piece of (well- fortified) American suburbia in the middle of the Iraqi desert, Balad has fast-food joints, a miniature golf course, a football field, a cinema and distinct neighbourhoods - among them, 'KBR-land', named after the Halliburton subsidiary that has done most of the construction work at the base. Although few of the 20,000 American troops stationed there have ever had any contact with an Iraqi, the runway at the base is one of the world's busiest. 'We are behind only Heathrow right now,' an air force commander told Ricks. The Defense Department was initially coy about these bases. In 2003, Donald Rumsfeld said: 'I have never, that I can recall, heard the subject of a permanent base in Iraq discussed in any meeting.' But this summer the Bush administration began to talk openly about stationing American troops in Iraq for years, even decades, to come. Several visitors to the White House have told the New York Times that the president himself has become fond of referring to the 'Korea model'. When the House of Representatives voted to bar funding for 'permanent bases' in Iraq, the new term of choice became 'enduring bases', as if three or four decades wasn't effectively an eternity. But will the US be able to maintain an indefinite military presence in Iraq? It will plausibly claim a rationale to stay there for as long as civil conflict simmers, or until every groupuscule that conveniently brands itself as 'al-Qaida' is exterminated. The civil war may gradually lose intensity as Shias, Sunnis and Kurds withdraw into separate enclaves, reducing the surface area for sectarian friction, and as warlords consolidate local authority. De facto partition will be the result. But this partition can never become de jure. (An independent Kurdistan in the north might upset Turkey, an independent Shia region in
The finger of suspicion
On Oct 22, 9:51 pm, [EMAIL PROTECTED] wrote: The time of fall The fake anthrax letters The absence of pentagon video, the most highly defended building The thermate residue The molten metal pools The pyroclastic flow of dust The shattering of the whole building into dust and small pieces The spherical particles of molten iron with sulfur, potassium and permanganate elements The finger of suspicion, nay certainty points to only the yank and the anglo-saxon bastards And all that to steal the oil. Bin Laden and Adam Gadahn productions are make in the Langley HQ of CIA. Al-Qaida does not exist. The goal is to prevent democratic order in the oil rich arab countries. -- http://mail.python.org/mailman/listinfo/python-list
Re: ignoring chinese characters parsing xml file
On 10/23/07, Stefan Behnel [EMAIL PROTECTED] wrote: Fabian López wrote: Thanks Mark, the code is like this. The attrib name is the problem: from lxml import etree context = etree.iterparse(file.xml) for action, elem in context: if elem.tag == weblog: print action, elem.tag , elem.attrib[name],elem.attrib[url], The problem is the print statement. Looks like your terminal encoding (that Python needs to encode the unicode string to) can't handle these unicode characters. I agree. For Japanese, you should know the exactly encoding name, and convert them, just like: print text.encoding('encoding') -- I like python! UliPad The Python Editor: http://code.google.com/p/ulipad/ meide wxPython UI module: http://code.google.com/p/meide/ My Blog: http://www.donews.net/limodou -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatic Generation of Python Class Files
On Mon, 22 Oct 2007 17:31:51 -0600, Steven Bethard wrote: Bruno Desthuilliers wrote: Computed attributes are IMHO not only a life-saver when it comes to refactoring. There are cases where you *really* have - by 'design' I'd say - the semantic of a property, but know from the start you'll need computation (for whatever reason). Then what would be the rationale for using explicit getters/setters ? I'd be interested to hear what these use cases are. Stupid little example: A circle object with `radius` and `diameter` attributes. It doesn't make sense to store both a as normal attributes because they will eventually get out of sync. One can be implemented as a property. Another one is delegation of attribute access. I'm thinking of a wrapper class around an object with an attribute, say `is_active`, and a wrapper that has a property with the same name that returns the value of the wrapped objects attribute. Or lazy computation of an attribute. Breaks expectations for the first access -- long calculation for simple attribute access -- but meets it for every subsequent access. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatic Generation of Python Class Files
Steven Bethard a écrit : Bruno Desthuilliers wrote: Steven Bethard a écrit : (snip) In Python, you can use property() to make method calls look like attribute access. This could be necessary if you have an existing API that used public attributes, but changes to your code require those attributes to do additional calculations now. But if you're creating a class for the first time, it should *never* use property(). There's no need to retrofit anything. May I kindly disagree here ?-) Of course. ;-) Computed attributes are IMHO not only a life-saver when it comes to refactoring. There are cases where you *really* have - by 'design' I'd say - the semantic of a property, but know from the start you'll need computation (for whatever reason). Then what would be the rationale for using explicit getters/setters ? I'd be interested to hear what these use cases are. I once wrote a small ORM-like wrapper for LDAP access, and, for reasons that might be obvious for anyone having worked with LDAP, I choosed to keep the record values in the format used by the lower level LDAP lib and let user code access them thru computed attributes (actually custom-made descriptors). Talking about ORMs, most of them surely use a similar scheme. I could also list the CS101 examples, like Shape.area, Rect.bottom_right, Person.age, etc... And yes, some of these attributes are obviously read-only. That doesn't prevent them from being semantically *properties*, not *behaviour*. Generally, people expect that attributes are used for simple state, and methods are used when some sort of computation is required. If you use attributes when some computation is required, you violate your users' expectations. Depends on which kind of people and on their background. I obviously don't advocate the use of computed attributes for heavy, non-cachable computations (please don't call me stupid !-), but not suffering from a too long exposures to some low-level mainstream languages, I never assume that attribute syntax implies direct attribute access. Of course, you can always document that your attributes require computation. But you're definitely adding some cognitive load by violating the normal expected behavior of attributes and methods. normal expected behaviour ? normal according to which norm, and expected by who ? In a language with a very strong builtin support for computed attributes, the only thing to expect is that you don't have to call an attribute to get to the value. -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
Marco Mariani marcarta.com wrote: I don't see how my answer is in any way worse than those based on lambda. Maybe I'm just envious because when I was his age I couldn't google for answers. He should at least be able to do that, shouldn't he? But wait. That would mean understanding what a factorial is. That would require a second search, or a textbook, or an understanding of arithmetics before programming with or without recursion. Should we blame the teachers? Yes. And burn their cars to get their attention! Asking someone to write a factorial algorithm before he knows WTF a factorial is, is either insane, or the ultimate demonstration of deliberate lack of cooperation and coordination between departments. I feel kind of strongly about this ever since, as a student, the physics people expected me to use mathematics that I had not been taught yet... ;-) I shall try to refrain from commenting on the concept of introducing recursion into a first course in CS - I am too much tainted by my ability to mentally see the stack growth in a small processor to be qualified to comment. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help parsing with pyparsing...
Paul McGuire ptstin.rr.com wrote: By the way, are these possible data lines?: A Line With No Upper Case Words A LINE WITH NO TITLE CASE WORDS SOME UPPER CASE WORDS A Title That Begins With A One Letter Word That last one is a killer, and comes under the heading of cruel and unusual. try this: THIS IS NONSENSE, SAY I A Fellow Needs A Break I can't think of a way to handle these without explicitly programming for them. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help parsing with pyparsing...
Just Another Victim of the Ambient Morality ihatemail.com wrote: FAHRENHEIT 451 2000 Copies Sold 1984 Book Of The Year The last example is actually okay but the first one is honestly ambiguous. hey - Fahrenheit 451 - if my memory serves me correctly, by Ray Bradbury, is a classic of SF. - firemen burn stuff instead of putting fires out, and they have a marvellous mechanical dog equipped with a syringe, for hunting down survivors... And the title purports to be the temp at which paper spontaneously combusts. Worth a read, if you haven't yet. So 'I' have no problem parsing the title, but I have to agree with the statement above. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Write by logging.FileHandler to one file by many processess
On Oct 18, 4:08 am, Gabriel Genellina [EMAIL PROTECTED] wrote: Yes, output from several processes comes horribly mixed... I've avoided it using separate log files for each process; but if that's not possible, one could try using syslog or a SocketHandler and a separate listening process. The Python logging docs even contain a working example of such a listening process (receiver): http://www.python.org/doc/current/lib/network-logging.html Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
On Oct 23, 8:53 am, Hendrik van Rooyen [EMAIL PROTECTED] wrote: Marco Mariani marcarta.com wrote: I don't see how my answer is in any way worse than those based on lambda. Maybe I'm just envious because when I was his age I couldn't google for answers. He should at least be able to do that, shouldn't he? But wait. That would mean understanding what a factorial is. That would require a second search, or a textbook, or an understanding of arithmetics before programming with or without recursion. Should we blame the teachers? Yes. And burn their cars to get their attention! Asking someone to write a factorial algorithm before he knows WTF a factorial is, is either insane, or the ultimate demonstration of deliberate lack of cooperation and coordination between departments. I feel kind of strongly about this ever since, as a student, the physics people expected me to use mathematics that I had not been taught yet... ;-) I shall try to refrain from commenting on the concept of introducing recursion into a first course in CS - I am too much tainted by my ability to mentally see the stack growth in a small processor to be qualified to comment. - Hendrik Completely agree with this point of view. After being on the receiving end of such problems when first introduced to Haskell and told to look at a database written in it and work my way through it (without having started the course on databases, locks, or any of that jargon) you find yourself almost helpless at times. Hard to google for something you don't know about. Recursive calling is a fun, and yet painful, thing... -- http://mail.python.org/mailman/listinfo/python-list
Re: Python - why don't this script work?
On Oct 23, 6:50 am, Ohmster [EMAIL PROTECTED] wrote: Adam Atlas [EMAIL PROTECTED] wrote in news:1193108392.089611.91170 @v29g2000prd.googlegroups.com: I think you're executing it as a shell script. Run python image- harvester.py, or add #!/usr/bin/env python to the top of the file. Hey that is a cool idea, I think I will try it. I found out what is wrong and did not get the results I want, I think the images are protected with script. See my other post in this thread for details. Shoot, the followup might have gone to alt.os.linux. I will repost for you here. I figured it out, I have to run python I think first then the script and the URL like this: $ python image-harvester.pyhttp://public.fotki.com/DaGennelman/ Now that actually seems to be doing something and it sure is busy now. It is making a lot of little subdirectories in my test directory. I had to copy image-harvester.py to the test directory first, then run python and image-harvester.py w/URL and it is going to town. Tons of subfolders, so far not images yet but it is not done. At least it is doing something now and not bitching and hanging. I guess I had to call up python and pass it to the script as the script does not seem to pull up python on it's own. So far I have 60 directories and about 45 robots.txt but no jpg files yet. I will let you know what happens. I think that these images are protected by script, you never get a valid URL to the imgage file, just referrers, and numbers and what not. When the image is finally displayed in your browser, then you can save it but not until then. Pretty good way to stop a harvester. Is this assumption pretty much correct or is there a way to make this work? Now that I use python as the first command, I can run it in an ssh window now and do not require an x-server. Feel free to jump right in with your input on how this should or won't work and what can be done to make it better. I have all of my scripts in a $HOME/scripts/ directory and it is in my path but running this from another directory does not work if image-harvester.py is not in the harvest directory where I run the script from. I can right click on the image and save it but the amazing script trips all over itself with these wacky file name. I am all ears if someone figures it. -- ~Ohmster | ohmster /a/t/ ohmster dot com Put messageforohmster in message body (That is Message Body, not Subject!) to pass my spam filter. Do note that the reason you may not see images is that the website has, '''correctly''', identified your program as an automated bot and blocked it access to things... -- http://mail.python.org/mailman/listinfo/python-list
Anagrams
This was from a random website I found on practising good programming techniques and I thought I'd see what ways people could find to write out this example. Below are my two examples (which should work...). I am merely interested in other techniques people have (without resorting to overusage of C modules and such like), just python and good computer science techniques. For the wordlist go to this link a href=http://codekata.pragprog.com/ 2007/01/kata_six_anagra.htmlKata Anagrams/a Anyway here are my two examples. This one uses a dictionary to store prime values of each letter in the alphabet and for each line multiple the results of the characters (which is unique for each anagram) and add them to a dictionary for printing latter. pre def anagram_finder(): primeAlpha = {'a':2, 'b':3, 'c':5, 'd':7,'e' : 11, 'f':13, 'g':17, 'h':19,\ 'i':23, 'j':29, 'k':31, 'l':37, 'm':41, 'n':43, 'o': 47, 'p':53,\ 'q':59, 'r':61, 's':67, 't':71, 'u':73, 'v':79, 'w': 83, 'x':89,\ 'y':97, 'z':101} dictAna = {} file = open (wordlist.txt, r) for line in file: value = 1 for s in line: if s.lower() in primeAlpha: value *= primeAlpha[s.lower()] dictAna.setdefault(value, []).append(line.strip()) file.close() print \n.join(['Anagrams are: %s' % (v) for k, v in dictAna.items() if len(dictAna[k]) 1]) /pre My second is a little bit simpler. Each dictionary key is an alphabetical ordering of the line in question, so that anagrams will appear the same. It will add to the dictionary the new word either in an existing key, or create a new one for it. pre def anagram_finder(): dict = {} file = ('wordlist.txt', 'r') for line in file: strip_line = line.strip().lower() sort_line = str(sorted(strip_line)) dict.setdefault(sort_line, []).append(strip_line) file.close() print '\n'.join(['Anagrams are: %s' % (v) for k, v in dict.items() if len(dict[k]) 1]) /pre Comparing them with timeit, they both took around 1 second or so, with the first being slightly faster. What other ways do people think will work (and do mine actually work for other people!) -- http://mail.python.org/mailman/listinfo/python-list
Re: C++ version of the C Python API?
2007/10/21, Robert Dailey [EMAIL PROTECTED]: On 10/21/07, Martin v. Löwis [EMAIL PROTECTED] wrote: No, I literally meant that the Python C API is object-oriented. You don't need an object-oriented language to write object-oriented code. I disagree with this statement. C is not an object oriented language, and I've seen attempts to make it somewhat object oriented, however it failed miserably in readability and manageability overhead. just FYI. What about the linux kernel? It's (in large parts) perfectly designed by OO principles (the vfs for example). And I can't remember that it was written in C++. Make a struct with some funtion pointers in it and you are at a basic OO level. the pointers could then manipulate the variables in the struct (remember a C++ struct ist just a class with all things being public). How does that differ from python? - I can't remember having visibility modifiers in python (so that would lead to that python isn't object oriented as any programmer could at any time directly manipulate any method/variable/whatsoever of your classes) -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours -- http://mail.python.org/mailman/listinfo/python-list
How to implement function like this?
Hello gurus, I have a question, a function like below, it is implemented by me, :) def funcA(tarray): a = [2,3,4] if len(tarray) =3: return a[0],a[1], a[2] elif len(tarray) == 2: return a[0],a[1], funcB(1)[0] elif len(tarray) == 1: return a[0], funcB(2)[0], funcB(2)[1] else: return funcB(3)[0], funcB(3)[1], funcB(3)[2] The return of funcA is always 3 values, but depending on the length of tarray, I need to return different values accordingly. if tarray lenght is 2, I need to get another one value from funcB, if tarray length is 0, I need to get all three values from funcB. Is there a brief way to achieve it? Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: Monitoring external processes
On 10/23/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Is there a way to track external processes launched by python on the Mac? I am using subprocess module to launch the process. Depending on how much detail you are looking for, PSI might be worth a look. http://www.psychofx.com/psi/ -- 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
Re: How to implement function like this?
On Tue, 23 Oct 2007 16:28:37 +0800, Yinghe Chen wrote: Hello gurus, I have a question, a function like below, it is implemented by me, :) def funcA(tarray): a = [2,3,4] if len(tarray) =3: return a[0],a[1], a[2] elif len(tarray) == 2: return a[0],a[1], funcB(1)[0] elif len(tarray) == 1: return a[0], funcB(2)[0], funcB(2)[1] else: return funcB(3)[0], funcB(3)[1], funcB(3)[2] The return of funcA is always 3 values, but depending on the length of tarray, I need to return different values accordingly. if tarray lenght is 2, I need to get another one value from funcB, if tarray length is 0, I need to get all three values from funcB. Untested: def func_a(t_array): result = [2, 3, 4] t_array_length = len(t_array) remaining_length = len(result) - t_array_length if t_array_length len(result): result = (result[:t_array_length] + func_b(remaining_length)[:remaining_length]) return tuple(result) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: How to implement function like this?
Yinghe Chen [EMAIL PROTECTED] writes: def funcA(tarray): a = [2,3,4] if len(tarray) =3: return a[0],a[1], a[2] elif len(tarray) == 2: return a[0],a[1], funcB(1)[0] elif len(tarray) == 1: return a[0], funcB(2)[0], funcB(2)[1] else: return funcB(3)[0], funcB(3)[1], funcB(3)[2] untested: from itertools import chain, islice def funcA(tarray): xB = max(3 - len(tarray), 0) return chain(a, islice(funcB(xB), xB)) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to implement function like this?
even shorter: def funcA(tarray): s = min(len(tarray), 3) return [2, 3, 4][0:s] + [e for e in funcB(3-s)[0:3-s]] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to implement function like this?
On Tue, 23 Oct 2007 11:48:08 +0200, Loic Mahe wrote: even shorter: def funcA(tarray): s = min(len(tarray), 3) return [2, 3, 4][0:s] + [e for e in funcB(3-s)[0:3-s]] Why the list comprehension!? Ciao, Marc 'Blackjack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
japanese encoding iso-2022-jp in python vs. perl
Hi, I am rather new to python, and am currently struggling with some encoding issues. I have some utf-8-encoded text which I need to encode as iso-2022-jp before sending it out to the world. I am using python's encode functions: -- var = var.encode(iso-2022-jp, replace) print var -- I am using the 'replace' argument because there seem to be a couple of utf-8 japanese characters which python can't correctly convert to iso-2022-jp. The output looks like this: ↓東京???日比谷線?北千住行 However if use perl's encode module to re-encode the exact same bit of text: -- $var = encode(iso-2022-jp, decode(utf8, $var)) print $var -- I get proper output (no unsightly question-marks): ↓東京メトロ日比谷線・北千住行 So, what's the deal? Why can't python properly encode some of these characters? I know there are a host of different iso-2022-jp variants, could it be using a different one than I think (the default)? I'm quite liking python at the moment for a variety of different reasons (I suspect perl will forever win when it comes to regular expressions but everything else is pretty darn nice), but this is a bit worrying. -Joe -- http://mail.python.org/mailman/listinfo/python-list
Re: How to implement function like this?
Marc 'BlackJack' Rintsch a écrit : On Tue, 23 Oct 2007 11:48:08 +0200, Loic Mahe wrote: even shorter: def funcA(tarray): s = min(len(tarray), 3) return [2, 3, 4][0:s] + [e for e in funcB(3-s)[0:3-s]] Why the list comprehension!? Ciao, Marc 'Blackjack' Rintsch sorry I just read too fast and thought he worked with lists ... anyway 'e for e in' and so list comprehension was useless here def funcA(tarray): s = min(len(tarray), 3) return (2, 3, 4,)[0:s] + funcB(3-s)[0:3-s] this is ok if funcB(...) returns a tuple ... if it returns a list just add: tuple(funcB(...)) note: list comprehension transforms a tuple into a list -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
Tim Chase wrote: fact = lambda i: i 1 and reduce(mul, xrange(1, i+1)) or not i and 1 or None Stunts like this would get a person fired around here if they were found in production code :) eheh, indeed. def fact(n): try: return eval('*'.join(str(x) for x in range(1,n+1))) except: return 1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
On 22 oct, 23:39, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Nope, still doesn't work: def fact(x): return reduce(operator.mul,xrange(1,x+1),1) fact() should raise an exception if x is negative. So, where is the problem? if not allowing negative numbers is so important for you, add a if statement and raise a ValueError exception. -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
On Oct 23, 1:58 pm, [EMAIL PROTECTED] wrote: On 22 oct, 23:39, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Nope, still doesn't work: def fact(x): return reduce(operator.mul,xrange(1,x+1),1) fact() should raise an exception if x is negative. So, where is the problem? if not allowing negative numbers is so important for you, add a if statement and raise a ValueError exception. indeed, especially considering that fact(x) is essentially just a lambda statement as Marco Mariani said. -- http://mail.python.org/mailman/listinfo/python-list
numpy confusion
Hi all, I'm trying to do some calculations with NumPy but apparently didn't quite got the basics. For example I need Exponential Moving Average function. That is, I have an array of values and want to apply a function F(current, previous) to each element of the array. How can I pass the 'previous' element to the function? In plain python it would be a simple loop: for index in arange(len(in_data[1:])): result[index] = F(in_data[index], result[index-1]) I assume it's somehow possible with numpy.frompyfunc() and actually found one example in SciPy TimeSeries library. Unfortunately I don't fully understand how that one works :-/ Is anyone able to shed some light on this thing? Thanks PaPa -- http://mail.python.org/mailman/listinfo/python-list
Problem with PEXPECT in Python
import sys,os import pexpect source_file= 'sourcefile.txt' user='username' ip='00.00.00.00' desti_path='/home/jai/………' password='bond007' cmd ='scp'+' '+source_file+' '+user+'@'+ip+':'+desti_path try: foo = pexpect.spawn(cmd) foo.expect('.ssword:*') foo.sendline(passwd) foo.sendline('Passwd_to_server') foo.interact() except Exception,e: pass Its simple, this should work, it works for me -- http://mail.python.org/mailman/listinfo/python-list
pure python data compression (zip)
Hallo I wonder if there are any pure python implementations available/known for the zip (or any other) data compression... As far as I know python's zlib uses http://www.zlib.net/, which is written in C. Unfortunately this is not solution for me, because my target only has a python interpreter I have googled for a while, but I don't have found anything useful. Regards, René -- http://mail.python.org/mailman/listinfo/python-list
RE: japanese encoding iso-2022-jp in python vs. perl
On Behalf Of kettle I am rather new to python, and am currently struggling with some encoding issues. I have some utf-8-encoded text which I need to encode as iso-2022-jp before sending it out to the world. I am using python's encode functions: -- var = var.encode(iso-2022-jp, replace) print var -- Possibly silly question: Is that a utf-8 string, or Unicode? print unicode(var, utf8).encode(iso-2022-jp) On my computer (Japanese XP), your string round-trips between utf-8 and iso-2022-jp without problems. Another possible thing to look at is whether your Python output terminal can print Japanese OK. Does it choke when printing the string as Unicode? Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
Re: pure python data compression (zip)
2007/10/23, Rene Maurer [EMAIL PROTECTED]: Hallo I wonder if there are any pure python implementations available/known for the zip (or any other) data compression... As far as I know python's zlib uses http://www.zlib.net/, which is written in C. Unfortunately this is not solution for me, because my target only has a python interpreter I have googled for a while, but I don't have found anything useful. Regards, René -- http://mail.python.org/mailman/listinfo/python-list I have implemented Huffman in Python, it is not very fast yet. Further improvements would requires writing some parts in C and use as a module in Python, or maybe I just didn't think enough on how to improve the python code. If you don't know how huffman works, you may read this: http://gpolo.ath.cx:81/implements/huffman I have described the improvements I have done to this teaching version here: http://gpolo.ath.cx:81/texts/opc If you don't want to read at all, you can search at pypi for huffman It doesn't have all the functionalities of any normal compressor, like compressing directories, but it could be implemented of course. Feedback is welcome -- -- Guilherme H. Polo Goncalves -- http://mail.python.org/mailman/listinfo/python-list
Re: pure python data compression (zip)
On Tue, 23 Oct 2007 14:47:40 +0200, Rene Maurer [EMAIL PROTECTED] wrote: Hallo I wonder if there are any pure python implementations available/known for the zip (or any other) data compression... As far as I know python's zlib uses http://www.zlib.net/, which is written in C. Unfortunately this is not solution for me, because my target only has a python interpreter I have googled for a while, but I don't have found anything useful. What is your target, that it can only run programs written in Python, not C? And what Python interpreter are you using? Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with PEXPECT in Python
cmd ='scp'+' '+source_file+' '+user+'@'+ip+':'+desti_path You might wanna try to login with a public/private key pair, then scp won't ask for a password. -- http://mail.python.org/mailman/listinfo/python-list
Re: Monitoring external processes
On Oct 22, 11:33 pm, Graham Dumpleton [EMAIL PROTECTED] wrote: On Oct 23, 3:09 pm, [EMAIL PROTECTED] wrote: Hi, Is there a way to track external processes launched by python on the Mac? I am using subprocess module to launch the process. Thanks Sunil If using Python 2.3/2.4, you can use os.wait(). If using Python 2.5, there is also have os.wait3() and os.wait4(). See the operating system manual pages for the difference. Ie., man wait4 Graham Ah! Exactly what I needed. Thanks Sunil. -- http://mail.python.org/mailman/listinfo/python-list
How can i protect text format ?
Hi.. I want to do a forum with python but i have a problem.. I have a textarea and i write: line 1 hi line 2 how r u And then i save to this database ( colomn data type is text) And than it looks line 1 hi line 2 how r u.. How can i protect \n characters ? -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i protect text format ?
On Tue, Oct 23, 2007 at 06:30:18AM -0700, Abandoned wrote regarding How can i protect text format ?: Hi.. I want to do a forum with python but i have a problem.. I have a textarea and i write: line 1 hi line 2 how r u And then i save to this database ( colomn data type is text) And than it looks line 1 hi line 2 how r u.. How can i protect \n characters ? -- http://mail.python.org/mailman/listinfo/python-list Are you sure they're getting lost on the way into the DB? Could they be getting lost on the way out? Say... into an HTML page? You need to pinpoint your problem more clearly to get a helpful response. Cheers, Cliff -- http://mail.python.org/mailman/listinfo/python-list
Set operations on object attributes question
Hi, I have run into something I would like to do, but am not sure how to code it up. I would like to perform 'set-like' operations (union, intersection, etc) on a set of objects, but have the set operations based on an attribute of the object, rather than the whole object. For instance, say I have (pseudo-code): LoTuples1 = [(1,1,0),(1,2,1),(1,3,3)] Set1=set(LoTuples1) LoTuples2 = [(2,1,3),(2,2,4),(2,3,2)] Set2=set(LoTuples2) What I would like to be able to do is: Set3 = Set1union(Set2) Set3.intersection(Set2, use object[2]) to return: set([(2,1,3), (1,3,3)]) How can one do this operation? Thanks, Duane -- http://mail.python.org/mailman/listinfo/python-list
Cross-compiling porting of io.h, distutils compilator argument
Hi all, I want to create a robot with a router board based on processor atheros 2.6, called fonera. I have installed a version of linux, Openwrt and python and i want to use it for some reasons, but i have problems to have access to GPIO pins on the board to read and write on harware(pic, memories...) so i want to include into python a porting of io.h I founded an already python wrapped version of io.h called ioport.c that i found here: http://www.hare.demon.co.uk/ioport/ioport.html ( i can't use pyparallel because i need to specify port address ,different from parallel ) but i have a problem: the compiler for that platform can be used only in cross compiling mode, and i have it on my pc, so it is compiled for my pc, and i can't use it on my router. I know that to compile that module to been used i need to use distutils, but distutils, when i run it, say me that can't find the compiler gcc, so the only way that i have to compile this module is to compile it on my pc, but i need to use the cross-compilator.So i need to specify to distutils the path of the compilator, and also where to pick io.h, because the io.h version for openwrt is different, and i have it with the cross-compilator, so i need also to specify the path of include libraries. If someone know how i can also directly use the gcc cross-compilator to build the module, without using distutils, but i need also to know when i compile it, then howto use on python as library. thanks Otacon22 -- http://mail.python.org/mailman/listinfo/python-list
Re: Cross-compiling porting of io.h, distutils compilator argument
On 23 Okt, 15:20, Otacon22 [EMAIL PROTECTED] wrote: If someone know how i can also directly use the gcc cross-compilator to build the module, without using distutils, but i need also to know when i compile it, then howto use on python as library. I think that this bug/patch is the most promising for cross-compiling Python, although I'm not sure if it meets your requirements exactly: http://bugs.python.org/issue1597850 Perhaps Python 2.6 will get improved cross-compilation support with this patch applied. Meanwhile, the following patch says this about distutils: Although scons doesn't support cross-builds either, it at least doesn't prevent them. http://bugs.python.org/issue841454 I know of patches which support cross-compilation using cmake as well, although I don't see the core developers embracing things like SCons or cmake in preference to distutils, regardless of any lack of support distutils might have in this area. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i protect text format ?
On Oct 23, 4:41 pm, J. Clifford Dyer [EMAIL PROTECTED] wrote: On Tue, Oct 23, 2007 at 06:30:18AM -0700, Abandoned wrote regarding How can i protect text format ?: Hi.. I want to do a forum with python but i have a problem.. I have a textarea and i write: line 1 hi line 2 how r u And then i save to this database ( colomn data type is text) And than it looks line 1 hi line 2 how r u.. How can i protect \n characters ? -- http://mail.python.org/mailman/listinfo/python-list Are you sure they're getting lost on the way into the DB? Could they be getting lost on the way out? Say... into an HTML page? You need to pinpoint your problem more clearly to get a helpful response. Cheers, Cliff Yes when i selected the data it have one row (there isn't \n) -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i protect text format ?
On 10/23/07, Abandoned [EMAIL PROTECTED] wrote: Hi.. I want to do a forum with python but i have a problem.. I have a textarea and i write: line 1 hi line 2 how r u And then i save to this database ( colomn data type is text) And than it looks line 1 hi line 2 how r u.. How can i protect \n characters ? I don't think the issue has anything to do with python. I guess while you are displaying the text into an HTML page the \n characters should be replaced by br / to appear as newlines. Cheers, -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i protect text format ?
On 23 Okt, 15:30, Abandoned [EMAIL PROTECTED] wrote: Hi.. I want to do a forum with python but i have a problem.. I have a textarea and i write: line 1 hi line 2 how r u And then i save to this database ( colomn data type is text) And than it looks line 1 hi line 2 how r u.. How can i protect \n characters ? Some questions: 1. How do you extract the data from the textarea? Which Web framework/ library are you using? 2. Are you sure that the \n characters are missing when you extract the data? (Printing/writing the data to a log, perhaps using the repr function, can be very useful.) 3. How do you save the data to the database? 4. How do you view the contents in the database? If you aren't yet viewing the contents in your application, but instead in your database client, does your database client show \n characters? If your application is showing the contents, what does the data look like before you try and display it? (Again, writing to a log can be useful.) Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Set operations on object attributes question
On 2007-10-23, TheSeeker [EMAIL PROTECTED] wrote: Hi, I have run into something I would like to do, but am not sure how to code it up. I would like to perform 'set-like' operations (union, intersection, etc) on a set of objects, but have the set operations based on an attribute of the object, rather than the whole object. For instance, say I have (pseudo-code): LoTuples1 = [(1,1,0),(1,2,1),(1,3,3)] Set1=set(LoTuples1) LoTuples2 = [(2,1,3),(2,2,4),(2,3,2)] Set2=set(LoTuples2) What I would like to be able to do is: Set3 = Set1union(Set2) Set3.intersection(Set2, use object[2]) to return: set([(2,1,3), (1,3,3)]) How can one do this operation? Put your data in a class, and implement __hash__ and __eq__ Finally, put your objects in sets. Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: parsing the output from matlab
On 10/22/07, wang frank [EMAIL PROTECTED] wrote I have a big log file generated from matlabe, for each variable, it print the name of the variable and an empty line and then the value. such as: x1 = 0.1 y = 7 z = 6.7 x1 = 0.5 I want to use python to parse the file and selectively print out the vairable and its value. For example, I want to print out all the value related with x1, so the output will be x1 = 0.1 x1 = 0.5. Here is a fairly naive version with re named groups that should handle the example you pasted. In [62]: import re In [63]: px = re.compile('(?Pvariable\w+)\s=\s+(?Pvalue\d.*\d*)') In [64]: for var in px.finditer(s): print %s = %s %(var.group('variable'), var.group('value')) : : a = 0.1 y = 7 z = 6.7 x1 = 0.5 To filter for only the x1's just test for the group named 'variable': In [66]: for var in px.finditer(s): : if var.group('variable')=='x1': : print %s = %s %(var.group('variable'), var.group ('value')) : : x1 = 0.5 But I'm betting these files get more complex than just the snippet you included, in which case it's probably worth looking at pyparsing http://pyparsing.wikispaces.com/ and regular expressions. -- Travis Brady http://travisbrady.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: web.py postgresql error
On Oct 22, 9:06 pm, [EMAIL PROTECTED] wrote: hi everyone, i'm very new to python and to this forum. i'm actually just trying to work through the tutorial on webpy.org. so far, so good, but as i tried to incorporate a postgresql database into the demo web app i'm receiving this error print out: [...] ImportError: No module named pgdb any thoughts would be greatly appreciated. thanks, doug It looks like you just haven't installed PyGreSQL yet. http:// www.pygresql.org/ Future web.py questions should probably be directed to the web.py group http://groups.google.com/group/webpy/, though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
On Oct 22, 11:45 am, Ant [EMAIL PROTECTED] wrote: Er, no. And neither is mine. You may want to google for the definition of factorial! Don't google for the definition... google for the answer! import urllib import re urllib.URLopener.version = Mozilla/4.0 def fact(x): r = re.compile(r%d ! = (\d+) % x) for line in urllib.urlopen(http://www.google.cl/search?q=%d%%21; % x): m = r.search(line) if m: return int(m.group(1)) -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: Bidirectional communication over unix socket (named pipe)
Hi list, I've been looking around and I found a very interesting solution to this problem, but instead of using a file for communication the author (Eduardo Fleury) uses a reference to the abstract namespace, chek it out... http://blog.eduardofleury.com/archives/2007/09/13/ Raul -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression
On 10/22/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, I'm trying to learn regular expressions, but I am having trouble with this. I want to search a document that has mixed data; however, the last line of every entry has something like C5H4N4O3 or CH5N3.ClH. All of the letters are upper case and there will always be numbers and possibly one . However below only gave me none. import os, codecs, re text = 'C:\\text_samples\\sample.txt' text = codecs.open(text,'r','utf-8') test = re.compile('\u+\d+\.') for line in text: print test.search(line) -- http://mail.python.org/mailman/listinfo/python-list I need a little more info. How can you know whether you're matching the text you're going for, and not other data which looks similar? Do you have a specific field length? Is it guaranteed to contain a digit? Is it required to start with a letter? Does it always start with 'C'? You need to have those kinds of rules in mind to write your regex. Shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression
On Oct 22, 5:29 pm, [EMAIL PROTECTED] wrote: Hi, I'm trying to learn regular expressions, but I am having trouble with this. I want to search a document that has mixed data; however, the last line of every entry has something like C5H4N4O3 or CH5N3.ClH. All of the letters are upper case and there will always be numbers and possibly one . However below only gave me none. import os, codecs, re text = 'C:\\text_samples\\sample.txt' text = codecs.open(text,'r','utf-8') test = re.compile('\u+\d+\.') for line in text: print test.search(line) If those are chemical symbols, then I guarantee that there will be lower case letters in the expression (like the l in ClH). -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
On 2007-10-23, Hendrik van Rooyen [EMAIL PROTECTED] wrote: Yuk. Reminds me of one of the Hitachi processors that has a single depth hardware link register that tells a subroutine where it was called from. That's how ARM processors work, and they're everywhere these days. -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
Dennis Lee Bieber [EMAIL PROTECTED] wrote: Heh... the one saving grace of taking a CS major in a period where the primary languages taught were FORTRAN (IV), COBOL (74), and something close to KK BASIC. Heck, even the assembler class followed the FORTRAN parameter handling scheme (argument addresses copied to static locals and used via one level of indirection) -- It would take me some time, today, to figure out how to even create a stack (even the return address was passed via a reserved register and saved locally): call,2 sub-address data arg1-address data arg2-address do-something . . . sub-address: store,2 my-return load,9 *my-return,1 ;indexed access store,9 param1 load,9 *my-return,2 store,9 param2 do-stuff load,2 my-return addimmediate,2 2 ;number of args to adjust return return,2 (format: label command,register argument *argument ;indirection argument,x ;indexed ) -- Yuk. Reminds me of one of the Hitachi processors that has a single depth hardware link register that tells a subroutine where it was called from. I was thinking of a stack that grows when you call or push, and shrinks when you return or pop. When there are only 128 or so bytes, and an address is two bytes, recursive calling soon runs into trouble. Especially so if you also use the stack to pass params... - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
Roberto Bonvallet wrote: import urllib import re urllib.URLopener.version = Mozilla/4.0 def fact(x): r = re.compile(r%d ! = (\d+) % x) for line in urllib.urlopen(http://www.google.cl/search?q=%d%%21; % x): m = r.search(line) if m: return int(m.group(1)) You solution reminds me the web-based WTF calculator. http://worsethanfailure.com/Articles/OMGWTF-Finalist-05-WTF-Web-Calc.aspx -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding idle timeout capabilities to asyncore
On 22 Ott, 12:28, Giampaolo Rodola' [EMAIL PROTECTED] wrote: Hi there. We're talking about an asyncore-based server. Just for the heck of it I'd like to set a timeout which will disconnects the clients if they're inactive (i.e., no command or data transfer in progress) for a long period of time. I was thinking about putting the timeout value into an attribute: def settimeout(self, secs): self.timeout = time.time() + secs And then have the readable method call time.time() at every loop to check if time has passed or not: def readable(self): if time.time() = self.timeout: self.send(Timeout) self.close() return 1 My only concern is if it's a good idea calling time.time() so often. Since A LOT of clients could be connected simultaneously, couldn't it be a too much resource-intensive operation? I'd also be curious to know how Twisted implemented this kind of stuff. By calling time.time() at every loop? Thanks in advance. Calling time.time() is relatively inexpensive in comparison to pure Python function calls, but indeed, it could be a bottleneck. I don't know what Twisted does, but what I would do is to add two variables to each instance of the class you want to add timeouts to; self.timeout and self.lastdata . self.lastdata would hold the time for the last time you sent or received data on the socket, and self.timeout would hold the delay between when you last sent/received data and when it should be closed due to idle timeout. Now, since you are smart, you don't need to alter your handle_send() or handle_receive() methods in your asyncore subclass. Instead, you rewrite asyncore.poll() to update .lastdata for every socket that is in either the reader or writer list, which will result in one time.time() call. Further, to check for timeouts, you only ever need to check those sockets that are *not* in the readable or writable lists... To be precise, add the following block to your own copy of asyncore.poll just after the 'for fd in e:' block... #handle timeouts rw = set(r) + set(w) now = time.time() for f in (i for i in rw if i in map): map[f].lastdata = now for j in (map[i] for i in map if i not in rw): if j.timeout+j.lastdata now: #timeout! j.handle_close() You ARE going to need to initialize .timeout and .lastdata members for every instance, but that shouldn't be so bad (for a socket that doesn't time out, I would actually suggest a 1 hour or 1 day timeout). - Josiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Set operations on object attributes question
[Duane] LoTuples1 = [(1,1,0),(1,2,1),(1,3,3)] Set1=set(LoTuples1) LoTuples2 = [(2,1,3),(2,2,4),(2,3,2)] Set2=set(LoTuples2) What I would like to be able to do is: Set3 = Set1union(Set2) Set3.intersection(Set2, use object[2]) to return: set([(2,1,3), (1,3,3)]) How can one do this operation? Conceptually, there is more than one operation going on. First, finding the attributes shared in both sets: ca = set(t[2] for t in LoTuples1) set(t[2] for t in LoTuples2) which gives: set([3]) Second, find any tuple which has that attribute (including multiple results for the same attribute): set(t for t in (LoTuples1 + LoTuples2) if t[2] in ca) which returns: set([(2, 1, 3), (1, 3, 3)]) Wanting multiple results for the same attribute value (i.e. both (2,1,3) and (1,3,3) have 3 in the second position) is why multiple steps are needed; otherwise, the behavior of intersection() is to return a single representative of the equivalence class. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Speed of Nested Functions Lambda Expressions
Hi All, It is really convenient to use nested functions and lambda expressions. What I'd like to know is if Python compiles fn_inner() only once and change the binding of v every time fn_outer() is called or if Python compile and generate a new function object every time. If it is the latter, will there be a huge performance hit? Would someone give some hint about how exactly Python does this internally? def fn_outer(v): a=v*2 def fn_inner(): print V:%d,%d % (v,a) fn_inner() Thanks, Geoffrey -- http://mail.python.org/mailman/listinfo/python-list
greatest and least of these...
I just wrote a program to let the user input a series of whole numbers and tell them which is least and which is greatest based off of a menu. However, the menu isn't kicking in after they pick a number. I included a while statement for a loop just for the menu and compared it to my other programs that have a similar setup and are working, but I'm stumped. Here's the program... def main(): #define and initialize variables #choice as int choice = 0 #number as int number = 0 #intro print WELCOME TO THE GREATEST AND LEAST NUMBER PROGRAM! print #Menu loop while choice != 2: #display menu print Please choose from the following menu: print 1. Enter a number print 2. Exit print #prompt user for their menu choice choice = input(Enter your choice here: ) #if statements to determine which choice if choice == 1: nums = [] while number =0: nums.append(number) number = input(Please enter a number.) elif choice == 2: print Have a great day! if len(nums) 0: print The smallest number that you entered was:,min(nums) print The largest number that you entered was:,max(nums) else: #invalid print Invalid selection. Enter either one or two. print Also, if they quit the program with choice #2 and entered numbers, it should display the greatest and least of them. If they just started and didn't enter anything and want to quit, I get an error message saying UnboundLocalError: local variable 'nums' referenced before assignment. Isn't the if statement supposed to keep python from going there since if they didn't enter any input, the length of the list should just be zero. -- http://mail.python.org/mailman/listinfo/python-list
Re: Speed of Nested Functions Lambda Expressions
beginner wrote: Hi All, It is really convenient to use nested functions and lambda expressions. What I'd like to know is if Python compiles fn_inner() only once and change the binding of v every time fn_outer() is called or if Python compile and generate a new function object every time. If it is the latter, will there be a huge performance hit? Would someone give some hint about how exactly Python does this internally? def fn_outer(v): a=v*2 def fn_inner(): print V:%d,%d % (v,a) fn_inner() Thanks, Geoffrey The code is compiled only once when the file is initially read in. During execution of fn_outer, v will be bound to a value, then a, then fn_inner will be bound (to an already compiled code object) and so on. Really, from the point of view of Python while executing fn_outer, the def of fn_inner looks just like an assignment with fn_inner as the variable name and a code object as the value. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Hiding tracebacks from end-users
I'm writing a command-line application that is meant to be relatively user friendly to non-technical users. (Some wags might like to say that user friendly and command-line application are, by definition, contradictory. I disagree.) Consequently, I'd like to suppress Python's tracebacks if an error does occur, replacing it with a more friendly error message. I'm doing something like this: try: setup() do_something_useful() except KeyboardInterrupt: print sys.stderr, User cancelled sys.exit(2) except Exception, e: if expert_mode: # experts get the full traceback with no hand-holding. raise else: # print a more friendly error message if isinstance(e, AssertionError): msg = An unexpected program state occurred elif isinstance(e, urllib2.HTTPError): msg = An Internet error occurred else: # catch-all for any other exception msg = An error occurred printsys.stderr, msg printsys.stderr, e sys.exit(1) else: sys.exit(0) Is this a good approach? Is there another way to suppress the traceback and just print the error message? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: pure python data compression (zip)
Guilherme Polo writes (23.10.2007): 2007/10/23, Rene Maurer [EMAIL PROTECTED]: I wonder if there are any pure python implementations available/known for the zip (or any other) data compression... As far as I know python's zlib uses http://www.zlib.net/, which is written in C. Unfortunately this is not solution for me, because my target only has a python interpreter I have implemented Huffman in Python, it is not very fast yet. Further improvements would requires writing some parts in C and use as a module in Python, or maybe I just didn't think enough on how to improve the python code. If you don't know how huffman works, you may read this: http://gpolo.ath.cx:81/implements/huffman I have described the improvements I have done to this teaching version here: http://gpolo.ath.cx:81/texts/opc Thank you very much. I will have a look this and try it out. Regards, René -- http://mail.python.org/mailman/listinfo/python-list
Leo 4.4.4 beta 3 released
Leo 4.4.4 beta 3 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106 Leo 4.4.4 contains many important features originally planned for later releases. It's been a good month :-) Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.4: - The Great Graph Aha (tm): simple scripts allow Leo outlines to represent arbitrary directed graphs. There is no need for a separate 'graph world'. The graphed.py plugin is a direct result of this Aha. The graphed.py plugin allows you to create general graphs from Leo outlines. - @menus trees in settings files create all of Leo's menus. It is now dead easy to make Leo's menus look the way you want. - @buttons trees in settings files create common @button nodes created in all Leo outlines. - @auto nodes eliminate sentinels in derived files, thereby allowing people to collaborate using Leo more easily. - New commands for resolving cvs conflicts. - A threading_colorizer plugin replaces the __jEdit_colorizer__ plugin. This plugin features much better performance and a new, elegant algorithm. - Leo is now compatible with jython. - The usual assortment of bug fixes and other minor improvements. Links: -- Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html Edward K. Ream email: [EMAIL PROTECTED] Leo: http://webpages.charter.net/edreamleo/front.html -- http://mail.python.org/mailman/listinfo/python-list
Re: pure python data compression (zip)
Jean-Paul Calderone wrote (23.10.2007): On Tue, 23 Oct 2007 14:47:40 +0200, Rene Maurer [EMAIL PROTECTED] wrote: Hallo I wonder if there are any pure python implementations available/known for the zip (or any other) data compression... As far as I know python's zlib uses http://www.zlib.net/, which is written in C. Unfortunately this is not solution for me, because my target only has a python interpreter I have googled for a while, but I don't have found anything useful. What is your target, that it can only run programs written in Python, not C? And what Python interpreter are you using? Target is a GPRS modem (telit 863-PY) http://www.telit.co.it/product.asp?productId=97 It comes with Python 1.5.2 including the follwoing modules: marshal, imp, _main_, _builtin_, sys, md5 (all others are not supported, as well as floats are not supported). Regards, René -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding idle timeout capabilities to asyncore
On Tue, 23 Oct 2007 15:34:19 -, Josiah Carlson [EMAIL PROTECTED] wrote: [snip] Calling time.time() is relatively inexpensive in comparison to pure Python function calls, but indeed, it could be a bottleneck. Did you benchmark this on some system? There isn't really any pure Python function calls that can replace time.time() in a sensible way, so I made up one that does some random things (including calling another Python function) and compared it to time.time: [EMAIL PROTECTED]:~$ python -m timeit -s ' def g(): return 1. + 2 + 3 * 4 - 5 / 6 + 7 ** 8 def f(): return g() ' 'f()' 100 loops, best of 3: 1.39 usec per loop [EMAIL PROTECTED]:~$ python -m timeit -s 'from time import time as f' 'f()' 10 loops, best of 3: 4.68 usec per loop [EMAIL PROTECTED]:~$ Not really useful in any real-world sense, but I still wouldn't characterize time.time as relatively inexpensive. Of course, for any real-world work, one would want to profile the application to determine if removing calls to time.time() could make a worthwhile difference. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: ignoring chinese characters parsing xml file
Thanks, I have tried all you told me. It was an error on print statement. So I decided to catch the exception if I had an UnicodeEncodeError, that is, if I had chinese/japanese characters because they don't interest to me and it worked. The strip_asian function of Ryan didn't work well here, but it's a good idea for next goals. Thanks a lot! Fabian 2007/10/23, limodou [EMAIL PROTECTED]: On 10/23/07, Stefan Behnel [EMAIL PROTECTED] wrote: Fabian López wrote: Thanks Mark, the code is like this. The attrib name is the problem: from lxml import etree context = etree.iterparse(file.xml) for action, elem in context: if elem.tag == weblog: print action, elem.tag , elem.attrib[name],elem.attrib [url], The problem is the print statement. Looks like your terminal encoding (that Python needs to encode the unicode string to) can't handle these unicode characters. I agree. For Japanese, you should know the exactly encoding name, and convert them, just like: print text.encoding('encoding') -- I like python! UliPad The Python Editor: http://code.google.com/p/ulipad/ meide wxPython UI module: http://code.google.com/p/meide/ My Blog: http://www.donews.net/limodou -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: greatest and least of these...
On Tue, 23 Oct 2007 11:56:33 -0400, Shawn Minisall wrote: I just wrote a program to let the user input a series of whole numbers and tell them which is least and which is greatest based off of a menu. However, the menu isn't kicking in after they pick a number. I included a while statement for a loop just for the menu and compared it to my other programs that have a similar setup and are working, but I'm stumped. Here's the program... def main(): #define and initialize variables #choice as int choice = 0 #number as int number = 0 #intro print WELCOME TO THE GREATEST AND LEAST NUMBER PROGRAM! print #Menu loop while choice != 2: #display menu print Please choose from the following menu: print 1. Enter a number print 2. Exit print #prompt user for their menu choice choice = input(Enter your choice here: ) #if statements to determine which choice if choice == 1: nums = [] while number =0: nums.append(number) number = input(Please enter a number.) Maybe you want to exchange those two last lines!? elif choice == 2: print Have a great day! if len(nums) 0: print The smallest number that you entered was:,min(nums) print The largest number that you entered was:,max(nums) Also, if they quit the program with choice #2 and entered numbers, it should display the greatest and least of them. If they just started and didn't enter anything and want to quit, I get an error message saying UnboundLocalError: local variable 'nums' referenced before assignment. Isn't the if statement supposed to keep python from going there since if they didn't enter any input, the length of the list should just be zero. Which list? If the branch for ``choice == 1`` isn't executed then the list will never be created an the name `nums` doesn't exist. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: greatest and least of these...
What do you mean when you say the menu doesn't kick in? Do you get an exception, or does simply nothing happen? Before the if statements, you should put print choice so you can see what value is being returned by the input function. Also maybe print type(choice) for a bit more inspection. Speaking of which, you should probably be using something like int(raw_input()) instead of just input() - if you read the help on the two functions you should see why. Hope this helps. Jason On Oct 23, 11:56 am, Shawn Minisall [EMAIL PROTECTED] wrote: I just wrote a program to let the user input a series of whole numbers and tell them which is least and which is greatest based off of a menu. However, the menu isn't kicking in after they pick a number. I included a while statement for a loop just for the menu and compared it to my other programs that have a similar setup and are working, but I'm stumped. Here's the program... def main(): #define and initialize variables #choice as int choice = 0 #number as int number = 0 #intro print WELCOME TO THE GREATEST AND LEAST NUMBER PROGRAM! print #Menu loop while choice != 2: #display menu print Please choose from the following menu: print 1. Enter a number print 2. Exit print #prompt user for their menu choice choice = input(Enter your choice here: ) #if statements to determine which choice if choice == 1: nums = [] while number =0: nums.append(number) number = input(Please enter a number.) elif choice == 2: print Have a great day! if len(nums) 0: print The smallest number that you entered was:,min(nums) print The largest number that you entered was:,max(nums) else: #invalid print Invalid selection. Enter either one or two. print Also, if they quit the program with choice #2 and entered numbers, it should display the greatest and least of them. If they just started and didn't enter anything and want to quit, I get an error message saying UnboundLocalError: local variable 'nums' referenced before assignment. Isn't the if statement supposed to keep python from going there since if they didn't enter any input, the length of the list should just be zero. -- http://mail.python.org/mailman/listinfo/python-list
Life-time of temporary variables in list comprehensions
Hi All, If I have a list comprehension: ab=[A,B] c = ABC [1.0 if c=='A' else c='B' for c in ab] print c B My test shows that if c is not defined before the list comprehension, it will be created in the list comprehension; if it is defined before the list comprehension, the value will be overwritten. In other words, temp variables are not local to list comprehensions. My question is why is this and is there any way to make c local to list comp? Thanks, Geoffrey -- http://mail.python.org/mailman/listinfo/python-list
Re: Normalize a polish L
On Oct 22, 7:50 pm, Mike Orr [EMAIL PROTECTED] wrote: Well, that gets into official vs unofficial conversions. Does the Spanish Academy really say 'ü' should be converted to 'u'? No, but it's the only conversion that makes sense. The only Spanish letter that doesn't have a standard common conversion by convention is 'ñ', which is usually ASCIIfied as n, nn, gn, nh, ni, ny, ~n, n~, or N, with all of them being frequently seen on the Internet. But whether that should be hardcoded into a blog URL library is different matter, and if it is there should probably be plugin tables for different preferred standards. Actually there is a hardcoded conversion, that is dropping all accented letters altogether, which is IMHO the worst possible convention. I have a gallery of pictures of Valparaíso and Viña del Mar whose URL is .../ValparaSoViADelMar. And if I wrote a blog entry about pingüinos and ñandúes, it would appear probably as .../ping-inos- and-and-es. Ugly and off-topic :) -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
New module for method level access modifiers
I have started work on a new module that would allow the decoration of class methods to restrict access based on calling context. Specifically, I have created 3 decorators named public, private and protected. These modifiers work as follows: Private: A private method can only be called from a method defined in the same class as the called method. Protected: A protected method can only be called from a method defined in the same or class derived from the called method's class. Public: No access restrictions (essentially a no-op). Programmers with a C++ or Java background will be familiar with these concepts in those languages; these decorators attempt to emulate their behavior Bugs: 1) These decorators will not tolerate other decorators because they examine the call stack in order to determine the caller's frame. A second decorator, either before or after the access decorator will insert a stack frame, which the current version of these decorators cannot handle. Making sure decorators set their wrapper functions __name__, __doc__ and append to its dictionary would be required at least for interoperability. 2) As noted, staticmethod and classmethod cannot be handled by the access decorators, not only because they are decorators themselves, but because the current access decorators require access to an instance of the class (self) in order to do method resolution. classmethod support could probably be added without too much difficulty but staticmethods, because they have no self or cls, would be difficult. 3) Friend classes, as defined in C++. These would probably be defined as a class-level list of classes that may have private/protected access to the given class's internals. This should not be too hard to add. 4) Decorators for member variables -- these decorators can already be applied to get_* and set_* methods for properties. Overriding __getattr__ may be a better solution for attribute access, however. Source available at: http://starship.python.net/crew/timehorse/access.py Jeffrey -- http://mail.python.org/mailman/listinfo/python-list
Re: greatest and least of these...
On Oct 23, 2007, at 10:56 AM, Shawn Minisall wrote: I just wrote a program to let the user input a series of whole numbers and tell them which is least and which is greatest based off of a menu. However, the menu isn't kicking in after they pick a number. I included a while statement for a loop just for the menu and compared it to my other programs that have a similar setup and are working, but I'm stumped. Here's the program... def main(): #define and initialize variables #choice as int choice = 0 #number as int number = 0 #intro print WELCOME TO THE GREATEST AND LEAST NUMBER PROGRAM! print #Menu loop while choice != 2: #display menu print Please choose from the following menu: print 1. Enter a number print 2. Exit print #prompt user for their menu choice choice = input(Enter your choice here: ) #if statements to determine which choice if choice == 1: nums = [] while number =0: nums.append(number) number = input(Please enter a number.) You're telling the script to continue asking for numbers until a non- positive number is entered. Enter a negative number and you'll see your menu again. What you probably want is to change this. elif choice == 2: print Have a great day! if len(nums) 0: print The smallest number that you entered was:,min(nums) print The largest number that you entered was:,max (nums) else: #invalid print Invalid selection. Enter either one or two. print Also, if they quit the program with choice #2 and entered numbers, it should display the greatest and least of them. If they just started and didn't enter anything and want to quit, I get an error message saying UnboundLocalError: local variable 'nums' referenced before assignment. Isn't the if statement supposed to keep python from going there since if they didn't enter any input, the length of the list should just be zero. The exception is because you're not ensure that nums is ever initialized. Erik Jones Software Developer | Emma® [EMAIL PROTECTED] 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate market in style. Visit us online at http://www.myemma.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Hiding tracebacks from end-users
On Oct 23, 7:07 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: I'm writing a command-line application that is meant to be relatively user friendly to non-technical users. (Some wags might like to say that user friendly and command-line application are, by definition, contradictory. I disagree.) Consequently, I'd like to suppress Python's tracebacks if an error does occur, replacing it with a more friendly error message. I'm doing something like this: try: setup() do_something_useful() except KeyboardInterrupt: print sys.stderr, User cancelled sys.exit(2) except Exception, e: if expert_mode: # experts get the full traceback with no hand-holding. raise else: # print a more friendly error message if isinstance(e, AssertionError): msg = An unexpected program state occurred elif isinstance(e, urllib2.HTTPError): msg = An Internet error occurred else: # catch-all for any other exception msg = An error occurred printsys.stderr, msg printsys.stderr, e sys.exit(1) else: sys.exit(0) Is this a good approach? Is there another way to suppress the traceback and just print the error message? -- Steven. No, I think with try-catch statements only. But this is a good approach and you have nothing to worry about. -- http://mail.python.org/mailman/listinfo/python-list
Re: Life-time of temporary variables in list comprehensions
On Tue, 2007-10-23 at 17:02 +, beginner wrote: Hi All, If I have a list comprehension: ab=[A,B] c = ABC [1.0 if c=='A' else c='B' for c in ab] c='B' is invalid syntax. Maybe you mean c=='B'. That doesn't make much sense, but at least it's correct syntax. print c B My test shows that if c is not defined before the list comprehension, it will be created in the list comprehension; if it is defined before the list comprehension, the value will be overwritten. In other words, temp variables are not local to list comprehensions. My question is why is this and is there any way to make c local to list comp? The only way to keep c from being overwritten currently is to avoid using a list comprehension. Generator expressions don't leak their iteration variable to the outside, so you can write this instead: list(1.0 if c=='A' else c=='B' for c in ab) HTH, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Life-time of temporary variables in list comprehensions
beginner schrieb: Hi All, If I have a list comprehension: ab=[A,B] c = ABC [1.0 if c=='A' else c='B' for c in ab] print c B My test shows that if c is not defined before the list comprehension, it will be created in the list comprehension; if it is defined before the list comprehension, the value will be overwritten. In other words, temp variables are not local to list comprehensions. My question is why is this and is there any way to make c local to list comp? Unfortunately, not as such. They do leak their variable names. But what you can do ist to create generator expressions (which don't leak) and put a list around them: list(1.0 if c == 'A' else c=B for c in ab) See also http://www.python.org/dev/peps/pep-0289/ Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Life-time of temporary variables in list comprehensions
On Tue, 23 Oct 2007 17:02:48 +, beginner wrote: My test shows that if c is not defined before the list comprehension, it will be created in the list comprehension; if it is defined before the list comprehension, the value will be overwritten. In other words, temp variables are not local to list comprehensions. That's right. My question is why is this and is there any way to make c local to list comp? It was a design decision that is now regretted. There is no way for you to make it local to the list comp except to wait for a new version of Python that behaves in the way you want. Or you can look at generator expressions, which are written just like list comprehensions except with round brackets (). They are not quite the same thing, but you can often use one in place of the other. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
On Oct 23, 6:58 am, [EMAIL PROTECTED] wrote: On 22 oct, 23:39, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Nope, still doesn't work: def fact(x): return reduce(operator.mul,xrange(1,x+1),1) fact() should raise an exception if x is negative. So, where is the problem? The fact that it returns 1 for negative x? And didn't you see my followup message? About how the example, as posted, doesn't even produce correct answers for legal values of x? if not allowing negative numbers is so important for you, Mathematical consistency is only important to _me_? add a if statement and raise a ValueError exception. Not necessary when done correctly. Didn't you see my example? -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatic Generation of Python Class Files
Marc 'BlackJack' Rintsch wrote: On Mon, 22 Oct 2007 17:31:51 -0600, Steven Bethard wrote: Bruno Desthuilliers wrote: Computed attributes are IMHO not only a life-saver when it comes to refactoring. There are cases where you *really* have - by 'design' I'd say - the semantic of a property, but know from the start you'll need computation (for whatever reason). Then what would be the rationale for using explicit getters/setters ? I'd be interested to hear what these use cases are. Stupid little example: A circle object with `radius` and `diameter` attributes. It doesn't make sense to store both a as normal attributes because they will eventually get out of sync. One can be implemented as a property. Could be. But I'd tend to define a get_diameter() method here. As a user of your class, I'd like to know which one is doing the computation. What if I'm using ridiculously large ints, and I care about the multiplication? Another one is delegation of attribute access. I'm thinking of a wrapper class around an object with an attribute, say `is_active`, and a wrapper that has a property with the same name that returns the value of the wrapped objects attribute. This is retrofitting to an API, so it already falls under the only time I think you *should* be using property(). Although in this case, it might be that __getattr__ is more appropriate. Or lazy computation of an attribute. Breaks expectations for the first access -- long calculation for simple attribute access -- but meets it for every subsequent access. There are descriptors better than property() at achieving this behavior. See for example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363602 My personal experience is that every time I write stuff this way (and I have many times), I end up re-writing it later as a method because it's less confusing for a method to take a long time than it is for an attribute access. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
On Oct 23, 5:55 am, Marco Mariani [EMAIL PROTECTED] wrote: Tim Chase wrote: fact = lambda i: i 1 and reduce(mul, xrange(1, i+1)) or not i and 1 or None Stunts like this would get a person fired around here if they were found in production code :) eheh, indeed. def fact(n): try: return eval('*'.join(str(x) for x in range(1,n+1))) except: return 1 Needs work. IDLE 1.2 def fact(n): try: return eval('*'.join(str(x) for x in range(1,n+1))) except: return 1 fact(3) 6 fact(2) 2 fact(1) 1 fact(0) 1 fact(-1) 1 fact(-2) 1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatic Generation of Python Class Files
Bruno Desthuilliers wrote: Steven Bethard a écrit : Bruno Desthuilliers wrote: Steven Bethard a écrit : (snip) In Python, you can use property() to make method calls look like attribute access. This could be necessary if you have an existing API that used public attributes, but changes to your code require those attributes to do additional calculations now. But if you're creating a class for the first time, it should *never* use property(). There's no need to retrofit anything. May I kindly disagree here ?-) Of course. ;-) Computed attributes are IMHO not only a life-saver when it comes to refactoring. There are cases where you *really* have - by 'design' I'd say - the semantic of a property, but know from the start you'll need computation (for whatever reason). Then what would be the rationale for using explicit getters/setters ? I'd be interested to hear what these use cases are. I once wrote a small ORM-like wrapper for LDAP access, and, for reasons that might be obvious for anyone having worked with LDAP, I choosed to keep the record values in the format used by the lower level LDAP lib and let user code access them thru computed attributes (actually custom-made descriptors). But this is trying to match an existing API, the only case that I think you *should* be using property(). I could also list the CS101 examples, like Shape.area, Rect.bottom_right, Person.age, etc... And yes, some of these attributes are obviously read-only. That doesn't prevent them from being semantically *properties*, not *behaviour*. But as I mentioned in another email here, I'd rather know which ones require computation, on the off chance that even the small amount of additional calculation matters (say, for large integers or in a very tight loop). I guess as long as your documentation is clear about which attributes require computation and which don't... STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't Write to PostGIS PostGreSQL database via psycopg2
On Oct 22, 8:43 pm, Erik Jones [EMAIL PROTECTED] wrote: On Oct 22, 2007, at 8:19 PM, David Michael Schruth, wrote: Hi, I am sort of in a jam here. I am using the PsycoPG2 library to read data out of a windows XP based PostGIS / PostGreSQL database but I am apparently unable to write (update or insert) even though I am able to read (select) I am using PsycoPG2 2.0.6 (psycopg2-2.0.6.win32-py2.5-pg8.2.4- release.exe ) with Python 2.5 (python-2.5.msi) and PostGres 8.2.5.-1 (postgresql-8.2.5-1.zip) and PostGIS 8.2 (postgis-pg82-setup-1.3.1-1.exe) I can use PGadminIII to paste the same SQL queries and execute just fine, but when I try to execute them via python code like import psycopg2 conn = psycopg2.connect(dbname='postgis' user='postgres' host='localhost' password='12345') c=conn.cursor() c.execute(INSERT INTO thetable (name) VALUES ('asdf');) c.execute(UPDATE thetable SET name = 'somename' WHERE id = 321;) print(c.statusmessage) #returns INSERT 0 1 and UPDATE 0 respectively It gives me very specialized table specific error messages if the query is wrong, but when it's correct, it does nothing and doesn't update. The only way I can update is pasting the query into the PgAdminIII query window. This is a problem on two separate machines (XP and Windows 2003 server) with all of the above components installed by two different people.'' The return value of the insert of 'INSERT 0 1' indicates that one row was inserted so the insert certainly worked. If you're not seeing the results when you look at the database after the script has run it's probably because you need to call conn.commit() after your execute statements in order to commit your transaction as psycopg does not, by default, run in autocommit mode. The update's return value of 'UPDATE 0' indicates that the where condition of your update query did not, in fact, match any existing rows in your table. Erik Jones Software Developer | Emma® [EMAIL PROTECTED] 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate market in style. Visit us online athttp://www.myemma.com Thank you so much that fixed the problem! -- http://mail.python.org/mailman/listinfo/python-list
Re: open remote terminal
Hi Rafael, Rafael Sachetto wrote: Take a look at this documentation: http://pexpect.sourceforge.net/pxssh.html thanks for the link, but it actually looks to me almost like my little example... I somehow don't get it!? Any more hints? Fabian pexpect would be the usual solution, I believe, if you could get it to interact correctly with your virtual terminal. http://pexpect.sourceforge.net/ I actually gave it a first very simple try: import pexpect child=pexpect.spawn('xterm') child.sendline('ls') Unfortunately nothing happens expect the start of xterm!? Does anyone have an idea, what I am doing wrong? Fabian -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Set operations on object attributes question
Hi, Thanks for the response! (See below for more discussion) On Oct 23, 10:39 am, Raymond Hettinger [EMAIL PROTECTED] wrote: [Duane] LoTuples1 = [(1,1,0),(1,2,1),(1,3,3)] Set1=set(LoTuples1) LoTuples2 = [(2,1,3),(2,2,4),(2,3,2)] Set2=set(LoTuples2) What I would like to be able to do is: Set3 = Set1union(Set2) Set3.intersection(Set2, use object[2]) to return: set([(2,1,3), (1,3,3)]) How can one do this operation? Conceptually, there is more than one operation going on. First, finding the attributes shared in both sets: ca = set(t[2] for t in LoTuples1) set(t[2] for t in LoTuples2) which gives: set([3]) In my use case, I already know object[2] is the key I wish to use, so I could do this without the first step. I am thinking of object[n] as the 'key' I wish to operate on, and the other items in the tuple are useful attributes I'll need in the end. Second, find any tuple which has that attribute (including multiple results for the same attribute): set(t for t in (LoTuples1 + LoTuples2) if t[2] in ca) which returns: set([(2, 1, 3), (1, 3, 3)]) Wanting multiple results for the same attribute value (i.e. both (2,1,3) and (1,3,3) have 3 in the second position) is why multiple steps are needed; otherwise, the behavior of intersection() is to return a single representative of the equivalence class. This second operation is really much like what I cam up with before I started looking into exploiting the power of sets (this same operation can be done strictly with lists, right?) Since what I _really_ wanted from this was the intersection of the objects (based on attribute 2), I was looking for a set-based solution, kinda like a decorate - set operation - undecorate pattern. Perhaps the problem does not fall into that category. Thanks for your help, Duane -- http://mail.python.org/mailman/listinfo/python-list
Re: Hiding tracebacks from end-users
On Oct 23, 11:07 am, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: I'm writing a command-line application that is meant to be relatively user friendly to non-technical users. (Some wags might like to say that user friendly and command-line application are, by definition, contradictory. I disagree.) Consequently, I'd like to suppress Python's tracebacks if an error does occur, replacing it with a more friendly error message. I'm doing something like this: try: setup() do_something_useful() except KeyboardInterrupt: print sys.stderr, User cancelled sys.exit(2) except Exception, e: if expert_mode: # experts get the full traceback with no hand-holding. raise else: # print a more friendly error message if isinstance(e, AssertionError): msg = An unexpected program state occurred elif isinstance(e, urllib2.HTTPError): msg = An Internet error occurred else: # catch-all for any other exception msg = An error occurred printsys.stderr, msg printsys.stderr, e sys.exit(1) else: sys.exit(0) Is this a good approach? Is there another way to suppress the traceback and just print the error message? -- Steven. I think this is a good approach too. But why are you using If statements for some errors? You should be able to do something like this: try: do something except AssertionError: do something except ZeroDivisionError: do something except urllib2.HTTPError: do something except... etc, etc... If you know what errors to expect, make them into a specific except block. And leave the catchall on there for the exceptions you've forgotten. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
[EMAIL PROTECTED] wrote: Needs work. Uh... ok.. this one gives an exception ;-) def fact(n): try: return eval('*'.join(str(x) for x in range(1,n+1))) except: return n=0 or ValueError print fact(-1) type 'exceptions.ValueError' -- http://mail.python.org/mailman/listinfo/python-list
Re: Hiding tracebacks from end-users
On Oct 23, 12:07 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: ... if expert_mode: # experts get the full traceback with no hand-holding. raise else: # print a more friendly error message ... Another approach is to always print a friendly error message, but append the traceback to a log file (see the traceback module for how to do that.) The friendly error message can include a note that full information is available in the log file. The advantage of that is that you capture critical information that is otherwise lost when a non-expert user hits the exception. For intermittent bugs that are hard to reproduce, this can be a lifesaver - especially when your favorite non-expert user seems to have a knack for generating errors that you can't figure out how to create ;-) Alan -- http://mail.python.org/mailman/listinfo/python-list
Root element name not declared
Hi guys, i'm using pyrxp to parse some xml like this one: ?xml version=1.0? !DOCTYPE MyMessage SYSTEM mymessage.dtd MyMessage release=2.0 Fromabc/From Todef/To . where the dtd is defined like this: !ENTITY % UsingLocalNames IGNORE ![%UsingLocalNames;[ !ENTITY % MyMessage !ENTITY % FieldA !ENTITY % FieldB , While parsing, I receive an error like this one: Root element name MyMessage not declared Being both the file and the dtd provided by the supplier, I believe they're correct so I don't understand what's wrong. MyMessage IS declared... isn't it sufficient? Thanx korovev -- http://mail.python.org/mailman/listinfo/python-list
Re: Cross-platform GUI development
On Oct 13, 12:34 am, Michael L Torrie [EMAIL PROTECTED] wrote: Alexandre Badez wrote: Personnaly, I use PyQt simply because I prefere Qt to Gtk, witch is much more integrated with all desktop than Gtk. In fact, your application in Qt on Mac, Win or Linux look like a native app. Qt doesn't look very native on my desktop. In fact, Qt apps have always looked out of place on a Gnome desktop. On Windows and Mac, no question, they look pretty native. You do have to take pains to make the app feel native, though. Like follow the UI guidelines of the platform, etc. Just a question of feeling I think; because most of those GUI framework, offer quiet the same functionality. GTK (like Pidgin or the GIMP) looks pretty native on Windows to me. Years of using Windows is probably why I think GTK/GNOME looks better than Qt/KDE. -- http://mail.python.org/mailman/listinfo/python-list
tracking/ordering log files
Hi, I heard that there was a utility for keeping files and specifically log files organized, but haven't been able to find anything but the logging class. The logging class seems to help create the content of a log file, but unless I am missing something, it doesn't keep track of multiple log files. What I am looking for is some utility that allows me to create a log file, say test.log, when the program runs. Then the next time it runs it will see that test.log already exists and will create test.log.1 or something similiar. Ideally it would also be able to throw out log files that are older than a certain date or sequence, so if we got to creating the 10th file it would delete the first one and so on. I am sorry for the ambiguois question, but I was told this existed, can't find it and would like to know if I'm on a wild goose chase and should just put something together myself. Thank you, Nik -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatic Generation of Python Class Files
Steven Bethard a écrit : Bruno Desthuilliers wrote: Steven Bethard a écrit : Bruno Desthuilliers wrote: Steven Bethard a écrit : (snip) In Python, you can use property() to make method calls look like attribute access. This could be necessary if you have an existing API that used public attributes, but changes to your code require those attributes to do additional calculations now. But if you're creating a class for the first time, it should *never* use property(). There's no need to retrofit anything. May I kindly disagree here ?-) Of course. ;-) Computed attributes are IMHO not only a life-saver when it comes to refactoring. There are cases where you *really* have - by 'design' I'd say - the semantic of a property, but know from the start you'll need computation (for whatever reason). Then what would be the rationale for using explicit getters/setters ? I'd be interested to hear what these use cases are. I once wrote a small ORM-like wrapper for LDAP access, and, for reasons that might be obvious for anyone having worked with LDAP, I choosed to keep the record values in the format used by the lower level LDAP lib and let user code access them thru computed attributes (actually custom-made descriptors). But this is trying to match an existing API, Certainly not. There's *no* existing API here. It's just exposing as attributes some values that are *not* attributes, and that requires some computation to get at. the only case that I think you *should* be using property(). I could also list the CS101 examples, like Shape.area, Rect.bottom_right, Person.age, etc... And yes, some of these attributes are obviously read-only. That doesn't prevent them from being semantically *properties*, not *behaviour*. But as I mentioned in another email here, I'd rather know which ones require computation, on the off chance that even the small amount of additional calculation matters (say, for large integers or in a very tight loop). And then ? If you need to get this value, and getting it requires computation, then you'll have to do that computation - whatever the context. Looks like premature optimization to me. And then, what then if the implementation changes and what was plain attributes get turned into properties and vice-versa ? I guess as long as your documentation is clear about which attributes require computation and which don't... Why should it ? FWIW, I mentionned that I would obviously not use properties for values requiring heavy, non cachable computation. This set aside, the fact that the attribute is computed (or not) is none of the concerns of client code. I think you know that concept, it's called 'encapsulation' !-) -- http://mail.python.org/mailman/listinfo/python-list
Can't refer to base class attribute?
I've got a Base class with an attribute foo (of type Foo), and a Derived class (derived from Base). In Derived's constructor, I try to refer to Base.foo, but python complains: AttributeError: class Base has no attribute 'foo' Any ideas? (code below) === CODE === #!/usr/bin/python class Foo: def __init__ (self): self.x = 3 class Base: def __init__ (self): self.foo = Foo() class Derived(Base): def __init__(self): Base.__init__(self) Base.foo.x = 5 Derived() === EOF === -- http://mail.python.org/mailman/listinfo/python-list
Re: Cross-platform GUI development
On 10/23/07, maco [EMAIL PROTECTED] wrote: On Oct 13, 12:34 am, Michael L Torrie [EMAIL PROTECTED] wrote: Alexandre Badez wrote: Personnaly, I use PyQt simply because I prefere Qt to Gtk, witch is much more integrated with all desktop than Gtk. In fact, your application in Qt on Mac, Win or Linux look like a native app. Qt doesn't look very native on my desktop. In fact, Qt apps have always looked out of place on a Gnome desktop. On Windows and Mac, no question, they look pretty native. You do have to take pains to make the app feel native, though. Like follow the UI guidelines of the platform, etc. Just a question of feeling I think; because most of those GUI framework, offer quiet the same functionality. GTK (like Pidgin or the GIMP) looks pretty native on Windows to me. This can only be because you don't use these programs often, or you've never actually looked at them. The GIMP in particular has almost nothing in common with the native controls - it's got a different background color, a different drawing model (note nasty delayed repaints when resizing), clearly non-native dialogs like file pickers, non-standard menu icons, just a huge list. Pidgin has a fairly minimal interface so it's flaws are less obvious, but they're still there. If this doesn't bother you, more power to you, but don't make the mistake of thinking that GIMP is any way native on windows. Years of using Windows is probably why I think GTK/GNOME looks better than Qt/KDE. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: New module for method level access modifiers
TimeHorse a écrit : I have started work on a new module that would allow the decoration of class methods to restrict access based on calling context. Specifically, I have created 3 decorators named public, private and protected. Lord have mercy. -- http://mail.python.org/mailman/listinfo/python-list
Re: japanese encoding iso-2022-jp in python vs. perl
var = var.encode(iso-2022-jp, replace) print var [...] ↓東京メトロ日比谷線・北千住行 So, what's the deal? Why can't python properly encode some of these characters? It's not clear. As Ryan says, it works just fine (and so it does for me with Python 2.4.4 on Debian). What Python version are you using, and what is the precise string that you want to encode? (use print repr(var) to report that exact value) HTH, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: New module for method level access modifiers
On 10/23/07, Bruno Desthuilliers [EMAIL PROTECTED] wrote: Specifically, I have created 3 decorators named public, private and protected. Lord have mercy. +1 QOTW. -- 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
Re: Monitoring external processes
On Oct 22, 11:33 pm, Graham Dumpleton [EMAIL PROTECTED] wrote: On Oct 23, 3:09 pm, [EMAIL PROTECTED] wrote: Hi, Is there a way to track external processes launched by python on the Mac? I am using subprocess module to launch the process. Thanks Sunil If using Python 2.3/2.4, you can use os.wait(). If using Python 2.5, there is also have os.wait3() and os.wait4(). See the operating system manual pages for the difference. Ie., man wait4 Graham I'm having a slight problem using wait3 or wait4. I want monitor a launched process and get its resource usage information. When I call os.wait4 with the pid the first time the call returns successfully but the second time around I get a OSError with No child processes error. I have tried using WCONTINUED, WNOHANG and WUNTRACED options. Sunil. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't refer to base class attribute?
On Tue, 23 Oct 2007 18:54:06 +, mrstephengross wrote: I've got a Base class with an attribute foo (of type Foo), and a Derived class (derived from Base). In Derived's constructor, I try to refer to Base.foo, but python complains: AttributeError: class Base has no attribute 'foo' Because the class `Base` doesn't have an attribute `foo`. Just believe the error message. :-) Any ideas? (code below) === CODE === #!/usr/bin/python class Foo: def __init__ (self): self.x = 3 class Base: def __init__ (self): self.foo = Foo() `Base` has no `foo` attribute but *instances* of `Base` have. class Derived(Base): def __init__(self): Base.__init__(self) Base.foo.x = 5 Instances of `Derived` have a `foo` attribute inherited from `Base`. So the last line should be ``self.foo.x = 5``. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: New module for method level access modifiers
On Tue, Oct 23, 2007 at 08:54:52PM +0200, Bruno Desthuilliers wrote regarding Re: New module for method level access modifiers: TimeHorse a ?crit : I have started work on a new module that would allow the decoration of class methods to restrict access based on calling context. Specifically, I have created 3 decorators named public, private and protected. Lord have mercy. I invented a new decorator too. It gets rid of many of the limitations of python, including duck typing and hideously flat namespaces. It's used kind of like this: @java def public_com.sun.lord.have.mercy(): pass Implementation forthcoming... -- http://mail.python.org/mailman/listinfo/python-list
Re: Write by logging.FileHandler to one file by many processess
En Tue, 23 Oct 2007 05:08:11 -0300, Vinay Sajip [EMAIL PROTECTED] escribi�: On Oct 18, 4:08 am, Gabriel Genellina [EMAIL PROTECTED] wrote: Yes, output from several processes comes horribly mixed... I've avoided it using separate log files for each process; but if that's not possible, one could try using syslog or a SocketHandler and a separate listening process. The Python logging docs even contain a working example of such a listening process (receiver): http://www.python.org/doc/current/lib/network-logging.html Great! -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Python on Intel A110?
Will the stock Windows version of Python install on a Samsung Q1U-EL UMPC running Vista and with an Intel A110 processor? I want to do some development and just happened to think about this. I don't know what these processors are compatible with at the binary level. Thanks! Bob -- http://mail.python.org/mailman/listinfo/python-list