Re: filtering keyword arguments
On Jul 12, 8:44 pm, Amir [EMAIL PROTECTED] wrote: How do you filter keyword arguments before passing them to a function? For example: def f(x=1): return x def g(a, **kwargs): print a, f(**kwargs) In [5]: g(1, x=3) 1 3 In [6]: g(1, x=3, y=4) TypeError: f() got an unexpected keyword argument 'y' Is there a way to do something like: def g(a, **kwargs): print a, f(filter_rules(f, **kwargs)) so only {'x': 3} is passed to f? I was hoping for a pythonic way of doing what in Mathematica is done by FilterRules: http://reference.wolfram.com/mathematica/ref/FilterRules.html Here it is as a decorator: def filter_arguments(func): def func2(*args, **kwargs): import inspect arglist, vararg, kwarg, defaults = inspect.getargspec(func) for k in kwargs.copy(): if k not in arglist: del kwargs[k] return func(*args, **kwargs) return func2 @filter_arguments def func(a=1, b=2): return a+b print func() print func(c=3) print func(a=3,b=4) -- http://mail.python.org/mailman/listinfo/python-list
Re: spam ...googlegroups.com ...googlegroups.com
WDC wrote: BTW I reported it, yo should too. Lew wrote: To whom did you report it, so that we may also report it there? Reports made to Google Groups are a complete waste of time. Google will only cancel *that* account (without blocking the IP address). It takes the spammer 30 seconds to enable *another* account. That is, ZERO real effect. It should also be noted that each time this is done plonk files could grow by one item. For Blogspot/Googlepages spam, report those to mailto:[EMAIL PROTECTED]adsense-abuse@ google.com That puts his site into Google Hell (screws up his GoogleRank). The most effective effort you can make is to do a reverse-DNS on the NNTP-Posting-Host http://private.dnsstuff.com/tools/whois.ch?ip=122.164.105.235email=on and report abusers to their providers. This assumes their ISPs aren't complete rogues. -- http://mail.python.org/mailman/listinfo/python-list
Re: Weird lambda rebinding/reassignment without me doing it
On Sat, 12 Jul 2008 16:32:25 -0400, Terry Reedy wrote: Steven D'Aprano wrote: On Thu, 10 Jul 2008 14:09:16 -0400, Terry Reedy wrote: g = lambda x:validate(x) This is doubly diseased. First, never write a 'name = lambda...' statement since it is equivalent to a def statement except that the resulting function object lacks a proper .funcname attribute. Using lambda in this way is no more diseased than aliasing any other object. In the context of giving advice to a confused beginner, I disagree. He must learn def statements. Lambda expressions are optional. Lots of things are optional. sets and frozen sets and decorators and classes and all sorts of things are optional, *and* capable of being misused and/or abused. Would you describe properties as diseased because some people might fill their classes with useless getters and setters? It's a matter of personal preference not to bind a lambda to a name. Functions, whether created by lambda or def, are first class objects, and as such there's nothing wrong with binding them to names. When I brought this up on pydev, in the context of a style guide addition, about 9 of 10 respondants agreed that this should be discouraged. Alex Martelli reported his experience that this construction more often leads people to the useless wrapping of function calls, such as the OP posted, than the def statement equivalent does. I have great respect for Alex, but anecdotes of that nature aren't proof. Such anecdotal evidence is subject to confirmation bias. I'm sure that Alex remembers the stupid pieces of code where people make such mistakes but I doubt very much he remembers the cases where they don't. But as a style guide... fine. Tell people it is discouraged. Tell them that other Python developers will laugh at them if they do it, apart from the ten percent who don't mind named lambdas. Point out that, like factory functions, there's a debugging cost to having functions with a unhelpful func_name attribute. But don't cross that line from discouragement to telling people that it is wrong to use named lambdas. That's what I object to. One of the major reasons people give for wanting lambda expressions kept in Python and for using them is that they do not want to have to think up a name for short expressions. If such a person then turns around and binds the resulting function object to a name, then that rationale disappears. That does not follow. The fact that I might choose to occasionally bind a lambda to a name doesn't mean I never use unbound functions. Your argument is like saying that the rationale for air conditioners (cooling in the hot weather) disappears because we can also use reverse-cycle air conditioners for heating in the cold weather. Lambdas are *necessary* if you want anonymous functions, just as we have anonymous strings, anonymous integers and so forth. It would be a poor language that forced people to write this: x = 1 s = 'two' def f(arg): return arg+3 mylist = [x, s, f] instead of the more sensible: mylist = [1, 'two', lambda arg: arg+3] That's why we need lambda. But once we have lambda, there is absolutely no reason why we must prohibit other uses of it. Given the above definition of mylist, would you then describe the following piece of code as diseased? def foo(mylist): g = mylist[2] for i in xrange(1): print g(i) That's a perfectly good micro-optimization technique, and I would hope you would not reject it merely because the function was anonymous. That would be irrational. I'm not defending the Original Poster's use of lambda in that specific piece of code. You are right to criticize it *specifically*. What I object to is that you generalize that criticism, and treat a personal preference as an absolute rule. By all means think my code is ugly for using named lambdas, and by all means tell me you think it is ugly, but don't tell me I'm corrupting the youth of today with my filthy disease- ridden code. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
iterator clone
Whats is the way to clone independent iterator? I can't use tee(), because I don't know how many independent iterators I need. copy and deepcopy doesn't work... --pavel -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this blowing the stack, thought it was tail-recursive...
On Sat, 12 Jul 2008 19:25:18 -0400, Terry Reedy wrote: ssecorp wrote: def fib(n): def fibt(a, b, n): if n = 1: return b else: return fibt(b, a + b, n - 1) if n == 0: return 0 else: return fibt(0, 1, n); and can memoization speed up this even more? tesintg with memoization doesnt really say anything because it is so fast it is instant anyway. Except for the fact that a+b gets slower as a and b get bigger, this would already be linear time in n. Memoization (here by means of a linear list) only helps if the list is preserved and one makes repeated requests for various fib values. I am just curious what input you tried that blew the stack? It had to be pretty large. No, not really. Try it for yourself: on my system, I get RuntimeError: maximum recursion depth exceeded with fib(999). fib(999) is a large number, with 208 digits, but not that large: 268638100244853593861467272021429239676166093189869523401 231759976179817002478816893383696544833565641918278561614 433563129766736422103503246348504103776803673341511728991 69723197082763985615764450078474174626L -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: iterator clone
Yosifov Pavel wrote: Whats is the way to clone independent iterator? I can't use tee(), because I don't know how many independent iterators I need. copy and deepcopy doesn't work... There is no general way. For short sequences you can store the items in a list which is also the worst-case behaviour of tee(). What are you trying to do? Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: spam [EMAIL PROTECTED] [EMAIL PROTECTED]
In article [EMAIL PROTECTED], Lew [EMAIL PROTECTED] wrote: WDC wrote: BTW I reported it, yo should too. To whom did you report it, so that we may also report it there? Google does not accept spam complaints. Go ahead, try it. That's why they've been the #1 Usenet spamming tool for years now. What you're seeing is the spam slowly expanding into the software development groups. uk.railway is probably a random group added to confuse spam filters. Some groups, like rec.photo.digital, have been getting hundreds of Google spams a day for about a year. Ask your news service for a Google UDP (Usenet Death Penalty) or configure your reader to drop everything with googlegroups.com in the Message-ID. http://improve-usenet.org/ -- I will not see your reply if you use Google. -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question : Iterators and zip
On 12 Jul, 21:50, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: On 12 juil, 20:55, [EMAIL PROTECTED] wrote: zip is (mostly) ok. What you're missing is how to use it for any arbitrary number of sequences. Try this instead: lists = [range(5), range(5,11), range(11, 16)] lists [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15]] for item in zip(*lists): ... print item ... (0, 5, 11) (1, 6, 12) (2, 7, 13) (3, 8, 14) (4, 9, 15) What is this *lis operation called? I am having trouble finding any reference to it in the python docs or the book learning python. Any other comments/suggestions appreciated. There's a difflib package in the standard lib. Did you give it a try ? I'll check it out, but I am a newbie, so I am writing this as a (useful) learning excercise. Thanks for the help Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.connect() hangs in SYN_SENT state.
On Sat, Jul 12, 2008 at 11:23 PM, bukzor [EMAIL PROTECTED] wrote: I'm connecting to an apache2 process on the same machine, for testing. When looking at netstat, the socket is in the SYN_SENT state, like this: $netstat -a -tcp tcp0 0 *:www *:* LISTEN 7635/apache2 tcp0 1 bukzor:38234adsl-75-61-84-249.d:www SYN_SENT 9139/python Anyone know a general reason this might happen? Even better, a way to fix it? That socket connection is to a remote machine, not the same one. Your test code works fine for me. The hang then crash (and I'm assuming crash here means an uncaught exception) just means that your packets are being silently ignored by whatever machine you're actually attempting to connect to. It's possible that your machine has odd DNS settings causing buzkor.hopto.org to resolve to the wrong address. -Miles -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with curses
On Sat, 12 Jul 2008 20:49:56 -0400, Clay Hobbs wrote: Unfortunately, the error message isn't very helpful. But it would be helpful to tell it. If you get exceptions, always copy'n'paste the traceback here. People might know what the exception means and share their wisdom. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
matplotlib: is there something like DISLIN's call newpag ?
Hi there, hope somebody here can help me out: is there a command in matplotlib which resembles DISLIN's CALL NEWPAG ? I am trying to make multiple plots on several pages, all stored in one ps (or pdf) document. Cheers -Ralf -- http://mail.python.org/mailman/listinfo/python-list
Re: heapq question
Giampaolo Rodola' [EMAIL PROTECTED] wrote: Having said that I'd like to understand if there are cases where deleting or moving an element of the heap, causes heappop() to return an element which is not the smallest one. Yes, of course there are: any time you delete element 0 of the heap you can do that. heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] heapify(heap) heap [0, 2, 1, 4, 5, 6, 7, 8, 9] del heap[0] heappop(heap) 2 By definition, element 0 is always the smallest but the next two elements could be in any order. If you delete an element other than 0 then the next pop won't be guaranteed to work. If you delete an element other than 0 the very next pop will work, but the heap conditions won't necessarily be restored so subsequent elements may come out in the wrong order. A simple example: heap = [0, 1, 3, 4, 2, 5] heapify(heap) heap [0, 1, 3, 4, 2, 5] del heap[1] heappop(heap), heappop(heap), heappop(heap) (0, 3, 2) -- http://mail.python.org/mailman/listinfo/python-list
Re: iterator clone
On 13 июл, 14:12, Peter Otten [EMAIL PROTECTED] wrote: Yosifov Pavel wrote: Whats is the way to clone independent iterator? I can't use tee(), because I don't know how many independent iterators I need. copy and deepcopy doesn't work... There is no general way. For short sequences you can store the items in a list which is also the worst-case behaviour of tee(). What are you trying to do? Peter I try to generate iterators (iterator of iterators). Peter, you are right! Thank you. For example, it's possible to use something like this: def cloneiter( it ): return (clonable,clone) return tee(it) and usage: clonable,seq1 = cloneiter(seq) ...iter over seq1... then clone again: clonable,seq2 = cloneiter(clonable) ...iter over seq2... Or in class: class ReIter: def __init__( self, it ): self._it = it def __iter__( self ): self._it,ret = tee(self._it) return ret and usage: ri = ReIter(seq) ...iter over ri... ...again iter over ri... ...and again... But I think (I'm sure!) it's deficiency of Python iterators! They are not very good... --Pavel -- http://mail.python.org/mailman/listinfo/python-list
Re: iterator clone
Yosifov Pavel wrote: On 13 июл, 14:12, Peter Otten [EMAIL PROTECTED] wrote: Yosifov Pavel wrote: Whats is the way to clone independent iterator? I can't use tee(), because I don't know how many independent iterators I need. copy and deepcopy doesn't work... There is no general way. For short sequences you can store the items in a list which is also the worst-case behaviour of tee(). What are you trying to do? Peter I try to generate iterators (iterator of iterators). Peter, you are right! Thank you. For example, it's possible to use something like this: def cloneiter( it ): return (clonable,clone) return tee(it) [snip] That is too abstract, sorry. What concrete problem are you trying to solve with your cloned iterators? There might be a way to rearrange your setup in a way that doesn't need them. But I think (I'm sure!) it's deficiency of Python iterators! They are not very good... Well, I think Python's iterators, especially the generators, are beautiful. More importantly, I think there is no general way to make iterators copyable, regardless of the programming language. The problem is that most of the useful ones depend on external state. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Correct use of try,except and raise?
Roy Smith [EMAIL PROTECTED] writes: ssecorp [EMAIL PROTECTED] wrote: i dont get what you mean, if i dont do anything python will raise an indexerror so it is an indexerror. You wrote: def pop(self): try: return self.queue.pop(0) except: raise IndexError, pop from empty queue You are assuming that the only possible exception that can be thrown by return self.queue.pop(0) is IndexError. Maybe, maybe not. I gave you one example of how something else could be thrown -- a typo in your code leading to a NameError. Maybe even something more exotic like MemoryError? The defensive thing to do is catch exactly the exception you expect to happen. In this case, that means IndexError. And you do that by except IndexError: raise TheErrorYouNowWantToRaise And except IndexError, e: if you want access to the exception as well. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SWIG to build C++ extension
Hello Bas, Thanks, man! Your recipe worked on Debian system, though not on RedHat, and I still have no idea why. :-) Anyway, I have it working. Thanks again. I took your example files and did the following: changed the #include edit_distance.h to #include edit_distance.c in the edit_distance.i file. Then I changed the first few lines of your function definition unsigned int edit_distance( const char* c1, const char* c2 ) { std::string s1( c1), s2( c2); and also adapted the signature in the edit_distance.i file. Then swig -shadow -c++ -python edit_distance.i g++ -c -fpic -I/usr/include/python edit_distance_wrap.cxx g++ -shared edit_distance_wrap.o -o _edit_distance.so -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing self: if self is a tree how to set to a different self
Paul McGuire [EMAIL PROTECTED] writes: On Jul 12, 6:18 am, Bart Kastermans [EMAIL PROTECTED] macbook.local wrote: This uses the function: def NoneOr (tree, mem_function, *arguments): if tree is not None then tree.mem_function (arguments). if tree == None: return None else: return getattr (tree, mem_function) (*arguments) Bart persnickety First I want to say these comments are absolutely great. I *very* much appreciated getting them. This kind of analysis and thinking about code is exactly what I want to learn for myself; so this helped me a lot. From the many interesting thoughts I got from this there is only one that is a bit dissonant with me; it is the next paragraph. This code reads wrongly to me on a couple of levels. First, I think the general computing consensus is that if-then-else is more readable/ logical if you assert the positive condition for the then-part, and put the alternative condition in the else-part. My impression is that the non-None-ness of tree is actually the positive assertion, as in: I had been experimenting with exactly this in some of my code. The choice seemed to be between (in the cases I had in front of me): 1) filter out the bad cases and deal with them, then have the code do the usual stuff, 2) set the conditions for being the usual case, then later deal with the bad stuff. I had been converging towards (1) as in def func (inputs): if inputs bad one way: deal with it if inputs bad another way: deal with it too take care of the generic remaining case case (2) would result in something like: def func (inputs): if inputs are not bad in any way: take care of the generic case elif in puts bad in one way: deal with it else: # bad in another way deal with it too Did I represent the case distinction as you had it in mind? I'll keep this more in mind when writing stuff and see how it works out. persnickety Better keep with more readable, logically these are clearly equivalent. /persnickety if tree != None: return getattr(tree, mem_function)(*arguments) else: return None Next, the more Pythonic test for None-ness is most clearly written as: if tree is not None: as there is only one None, and the identity is not check is simpler/ faster for Python to execute (and possibly - and more importantly - also simpler for readers to follow, as this reads more like a continuous sentence instead of a mixture of prose and mathematical notations). One might even suggest you could further abbreviate this test to: if tree: and get the same behavior. I would quibble with that, however, that this merely exploits a side-effect of Python, in which None values are always False, and *most* non-None values are True. But Python also interprets many non-None values as False, such as 0, or empty containers, such as lists, tuples, dicts, and strings. In fact, your tree class sounds like a structured container to me, and it would be reasonable to assume that you might implement __nonzero__ (pre-Python 2.6) or __bool__ (Python 2.6 and later) in your class to return False for an empty tree, which would still be a valid and not-None tree. You should be able to invoke methods on an empty tree just as one can call .upper(). So for this case, I would stick with the more explicit if tree is not None. Another Pythonicity is that methods will *always* return a value, even if you do not write a return statement - and that value is None. So if you assert the tree-not-None as the if condition, you don't even need the else part. You could just write: def NoneOr (tree, mem_function, *arguments): if tree is not None then tree.mem_function (arguments). if tree is not None: return getattr(tree, mem_function)(*arguments) Surprisingly, this actually reads almost verbatim from your doc string! So I would guess that this implementation is probably closest to your original intent for this method. Still, for explicitness'- sake, you might want to keep the else-part, just to make your intent clear and spelled-out. (Complaining about the presence or absence of this bit of code goes beyond persnickety...) /persnickety Note that the original code is perfectly valid Python, and will run just as efficiently as any of my alternative suggestions, which is why I enclosed my comments in 'persnickety' (http:// dictionary.reference.com/browse/persnickety) tags. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Correct use of try,except and raise?
Bart Kastermans [EMAIL PROTECTED] writes: Roy Smith [EMAIL PROTECTED] writes: The defensive thing to do is catch exactly the exception you expect to happen. In this case, that means IndexError. And you do that by except IndexError: raise TheErrorYouNowWantToRaise You only do that if you want to throw away important information, such as the traceback associated with the original exception. Not very friendly to debugging. And except IndexError, e: if you want access to the exception as well. Usually best if it can be achieved. Not least because the bare 'raise' statement will re-raise the original exception, complete with all its context. -- \ “If we don't believe in freedom of expression for people we | `\ despise, we don't believe in it at all.” —Noam Chomsky, | _o__) 1992-11-25 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is there no GUI-tools like this for Windows?
There is http://www.codeplex.com/IronPythonStudio -- http://mail.python.org/mailman/listinfo/python-list
Dynamic Invocation Interface
Is there any python CORBA ORB that support Dynamic Invocation Interface? Thanks -- http://mail.python.org/mailman/listinfo/python-list
About wmi
I want to prevent some process from running. The code is in the following. I encounter some unexpected troubles. Probelm1: This program cannot terminate scrcons.exe and FNPLicensingService.exe,which are system processes. Problem2:After a while, this program will abort by error File C:\Python25\lib\wmi.py, line 397, in __call__ handle_com_error (error_info) File C:\Python25\lib\wmi.py, line 190, in handle_com_error raise x_wmi, \n.join (exception_string) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 14: ordinal not in range(128) code-- # -*- coding:utf-8 -*- import pythoncom import wmi import threading import time from xml.dom.minidom import parse, parseString class Info (threading.Thread): def __init__ (self): threading.Thread.__init__ (self) def run (self): print 'In Another Thread...' pythoncom.CoInitialize () dom1 = parse('processTerminateList.xml') config_element = dom1.getElementsByTagName(processTerminateList) [0] servers = config_element.getElementsByTagName(processName) try: c = wmi.WMI () for process in c.Win32_Process (): for server in servers: if process.name == getText(server.childNodes): process.Terminate() print process.name process_watcher = c.Win32_Process.watch_for(creation) while True: new_process = process_watcher() name = new_process.Caption print name for server in servers: if name == getText(server.childNodes): new_process.Terminate() finally: pythoncom.CoUninitialize () def getText(nodelist): rc = for node in nodelist: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc if __name__ == '__main__': Info().start() -- processTerminateList.xml--- ?xml version=1.0 encoding=utf-8? processTerminateList processNamescrcons.exe/processName processNameTXPlatform.exe/processName processNamemdm.exe/processName processNameFNPLicensingService.exe/processName processNamenotepad.exe/processName processNameuedit32.exe/processName /processTerminateList -- http://mail.python.org/mailman/listinfo/python-list
Re: why is self used in OO-Python?
On Jul 13, 12:32 am, ssecorp [EMAIL PROTECTED] wrote: I first learned about OO from Java. I much prefer to program in Python though. However I am consufed about 2 things. 1. Why do I have to pass self into every method in a class? Since I am always doing why cant this be automated or abstracted away? Are the instances where I won't pass self? I imagine there is some tradeoff involved otherwise it would have been done away with. 2. self.item instead of getters and setters. I thought one of the main purposes of OO was encapsulation. Doesn't messing with internal object- representations break this? I see how the getters and setters could be just visual clutter and you have to add them to every class so it is annoying a bit in the same way as self described above. However I feel like I want getters and setters when I write classes, not sure of the advantages/disadvantages though. Only looking at the documentation of a Python-class, will internal representations be provided? If I have a class: class Stack(object): def __init__(self, *items): self.stack = list(items) def append(self, item): self.stack.append(item) def pop(self): return self.stack.pop() I can get to see the stack with var.stack but then why even implement append when I could do self.stack.append(x) etc. That way you could do away with OO completely. So why let people access the main attribute but not let them manipulate it? Makes more sense to draw the line to not access any attributes at all no? i think the following article may be helpful to you. Introduction to OOP with Python http://www.voidspace.org.uk/python/articles/OOP.shtml#id34 -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with curses
On Sat, 12 Jul 2008 20:49:56 -0400, Clay Hobbs wrote: Unfortunately, the error message isn't very helpful. But it would be helpful to tell it. If you get exceptions, always copy'n'paste the traceback here. People might know what the exception means and share their wisdom. Here is the error message: Traceback (most recent call last): File ./text_adventure.py, line 25, in module curses.wrapper(main) File /usr/lib/python2.5/curses/wrapper.py, line 44, in wrapper return func(stdscr, *args, **kwds) File ./text_adventure.py, line 19, in main stdscr.scroll(3) _curses.error: scroll() returned ERR -- Ratfink -- http://mail.python.org/mailman/listinfo/python-list
spam
On Jul 12, 9:21 am, Scott in SoCal [EMAIL PROTECTED] wrote: In message [EMAIL PROTECTED], rickman [EMAIL PROTECTED] wrote: spam *PLONK!* I love the way that people who plonk others feel the need to inform everyone of it. That ranks up there with, I know what you are, but what am I? -- http://mail.python.org/mailman/listinfo/python-list
Functional/Best?
I guess I can classify my application(s) as more procedural than anything else. But I have a question about the best way to handle something in Python. When given a mapping of keywords, I want to call a function based on a certain keyword found when parsing a text file. The mapping looks like this: definClassMap={'SECTION':'bldSection','COMPOSITION':'bldComposition','OBSERVATION':'bldObservation','ITEM_TREE':'bldItemTree'} So if the text file contains 'ITEM_TREE' I want to call bldItemTree which creates an instance of the class ItemTree. I currently use an if ..., elif ... construct. Is there a better, more efficient, more Pythonic way of doing this? Thanks, Tim -- ** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ** attachment: Displayemail.gif signature.asc Description: This is a digitally signed message part -- http://mail.python.org/mailman/listinfo/python-list
Re: Correct use of try,except and raise?
Ben Finney [EMAIL PROTECTED] wrote: If you are passing a sequence conceptually, then it's more Pythonic to pass it as a sequence explicitly:: def __init__(self, items): Call with e.g. Stack([foo, bar]) self.stack = list(items) I don't get this. You're forcing a copy to be made of the list. This changes the semantics of the original class, because the operations no longer change the original list. That may or may not be what you want. It's a design decision, not a doing it this way is more pythonic kind of thing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this blowing the stack, thought it was tail-recursive...
On Jul 13, 7:56 am, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Sat, 12 Jul 2008 19:25:18 -0400, Terry Reedy wrote: ssecorp wrote: def fib(n): def fibt(a, b, n): if n = 1: return b else: return fibt(b, a + b, n - 1) if n == 0: return 0 else: return fibt(0, 1, n); and can memoization speed up this even more? tesintg with memoization doesnt really say anything because it is so fast it is instant anyway. Except for the fact that a+b gets slower as a and b get bigger, this would already be linear time in n. Memoization (here by means of a linear list) only helps if the list is preserved and one makes repeated requests for various fib values. I am just curious what input you tried that blew the stack? It had to be pretty large. No, not really. Try it for yourself: on my system, I get RuntimeError: maximum recursion depth exceeded with fib(999). fib(999) is a large number, with 208 digits, but not that large: 268638100244853593861467272021429239676166093189869523401 231759976179817002478816893383696544833565641918278561614 433563129766736422103503246348504103776803673341511728991 69723197082763985615764450078474174626L -- Steven The default CPython recursion limit is 1000 - so hitting it with an input of 999 is not that surprising... You can set a higher limit with sys.setrecursionlimit(...) Michael Foord http://www.ironpythoninaction.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Correct use of try,except and raise?
Roy Smith [EMAIL PROTECTED] writes: Ben Finney [EMAIL PROTECTED] wrote: If you are passing a sequence conceptually, then it's more Pythonic to pass it as a sequence explicitly:: def __init__(self, items): Call with e.g. Stack([foo, bar]) self.stack = list(items) I don't get this. You're forcing a copy to be made of the list. The 'items' object might not be a list; it might be some other sequence. The rest of the class (as shown by the original poster) requires it to be a list. This changes the semantics of the original class, because the operations no longer change the original list. Which original class are you referring to? The one posted by the original poster of this thread had no original list; it gathered the positional arguments (using '*items') into an 'items' parameter, which *doesn't exist* until the function body executes. There *is* no original list in that implementation posed by the original poster; it's constructed at call time from the positional parameters to the function. If anything, my implementation above *preserves* that semantic, by making a new list from the passed-in sequence. -- \“Consider the daffodil. And while you're doing that, I'll be | `\ over here, looking through your stuff.” —Jack Handey | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: spam [EMAIL PROTECTED] [EMAIL PROTECTED]
Kevin McMurtrie wrote: In article [EMAIL PROTECTED], Lew [EMAIL PROTECTED] wrote: WDC wrote: BTW I reported it, yo should too. To whom did you report it, so that we may also report it there? Google does not accept spam complaints. Go ahead, try it. That's why they've been the #1 Usenet spamming tool for years now. What you're seeing is the spam slowly expanding into the software development groups. uk.railway is probably a random group added to confuse spam filters. Some groups, like rec.photo.digital, have been getting hundreds of Google spams a day for about a year. Ask your news service for a Google UDP (Usenet Death Penalty) or configure your reader to drop everything with googlegroups.com in the Message-ID. Some real users do use GG. Arne -- http://mail.python.org/mailman/listinfo/python-list
Re: Correct use of try,except and raise?
In article [EMAIL PROTECTED], Ben Finney [EMAIL PROTECTED] wrote: Which original class are you referring to? The one posted by the original poster of this thread had no original list; it gathered the positional arguments (using '*items') into an 'items' parameter, which *doesn't exist* until the function body executes. Ah, I didn't notice that. -- http://mail.python.org/mailman/listinfo/python-list
Re: spam [EMAIL PROTECTED] [EMAIL PROTECTED]
Arne Vajhøj wrote: Google does not accept spam complaints. Go ahead, try it. That's why they've been the #1 Usenet spamming tool for years now. What you're seeing is the spam slowly expanding into the software development groups. uk.railway is probably a random group added to confuse spam filters. Some groups, like rec.photo.digital, have been getting hundreds of Google spams a day for about a year. Ask your news service for a Google UDP (Usenet Death Penalty) or configure your reader to drop everything with googlegroups.com in the Message-ID. Some real users do use GG. This is true, however there are acceptable losses. donald Arne -- http://mail.python.org/mailman/listinfo/python-list
Re: About wmi
patrol wrote: I want to prevent some process from running. The code is in the following. I encounter some unexpected troubles. Probelm1: This program cannot terminate scrcons.exe and FNPLicensingService.exe,which are system processes. Problem2:After a while, this program will abort by error File C:\Python25\lib\wmi.py, line 397, in __call__ handle_com_error (error_info) File C:\Python25\lib\wmi.py, line 190, in handle_com_error raise x_wmi, \n.join (exception_string) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 14: ordinal not in range(128) code-- # -*- coding:utf-8 -*- import pythoncom import wmi import threading import time from xml.dom.minidom import parse, parseString class Info (threading.Thread): def __init__ (self): threading.Thread.__init__ (self) def run (self): print 'In Another Thread...' pythoncom.CoInitialize () dom1 = parse('processTerminateList.xml') config_element = dom1.getElementsByTagName(processTerminateList) [0] servers = config_element.getElementsByTagName(processName) try: c = wmi.WMI () for process in c.Win32_Process (): for server in servers: if process.name == getText(server.childNodes): process.Terminate() print process.name process_watcher = c.Win32_Process.watch_for(creation) while True: new_process = process_watcher() name = new_process.Caption print name for server in servers: if name == getText(server.childNodes): new_process.Terminate() finally: pythoncom.CoUninitialize () def getText(nodelist): rc = for node in nodelist: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc if __name__ == '__main__': Info().start() -- processTerminateList.xml--- ?xml version=1.0 encoding=utf-8? processTerminateList processNamescrcons.exe/processName processNameTXPlatform.exe/processName processNamemdm.exe/processName processNameFNPLicensingService.exe/processName processNamenotepad.exe/processName processNameuedit32.exe/processName /processTerminateList You should probably post this to comp.python.windows. Tim Golden (author of WMI interface) monitors that list religously (thanks Tim). -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: spam
rickman wrote: On Jul 12, 9:21 am, Scott in SoCal [EMAIL PROTECTED] wrote: In message [EMAIL PROTECTED], rickman [EMAIL PROTECTED] wrote: spam *PLONK!* I love the way that people who plonk others feel the need to inform everyone of it. That ranks up there with, I know what you are, but what am I? That's one interpretation, likely not the plonkers but supportable by reasoning. Another supportable interpretation is that it both does the offender the courtesy of notification so that they get one last chance to reconsider their behavior, and suggests to the community at large that they follow suit. So a public plonk is actually a service both to the troll/spammer/innocent victim of slander and to the larger newsgroup community. -- Lew -- http://mail.python.org/mailman/listinfo/python-list
Re: heapq question
On 13 Lug, 11:35, Duncan Booth [EMAIL PROTECTED] wrote: Giampaolo Rodola' [EMAIL PROTECTED] wrote: Having said that I'd like to understand if there are cases where deleting or moving an element of the heap, causes heappop() to return an element which is not the smallest one. Yes, of course there are: any time you delete element 0 of the heap you can do that. heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] heapify(heap) heap [0, 2, 1, 4, 5, 6, 7, 8, 9] del heap[0] heappop(heap) 2 By definition, element 0 is always the smallest but the next two elements could be in any order. If you delete an element other than 0 then the next pop won't be guaranteed to work. If you delete an element other than 0 the very next pop will work, but the heap conditions won't necessarily be restored so subsequent elements may come out in the wrong order. A simple example: heap = [0, 1, 3, 4, 2, 5] heapify(heap) heap [0, 1, 3, 4, 2, 5] del heap[1] heappop(heap), heappop(heap), heappop(heap) (0, 3, 2) Thanks, that's what I wanted to know. I understand that heapq is not that efficient to implement timeouts as I thought at first. It would have been perfect if there were functions to remove arbitrary elements withouth needing to re-heapify() the heap every time. Thanks for your help anyway. --- Giampaolo http://code.google.com/p/pyftpdlib/ -- http://mail.python.org/mailman/listinfo/python-list
wxPython code giving strange errors.
I'm busy trying to learn wxPython, and i'm trying to run the following piece of code (its from the wxPyWiki tutorial): import wx ID_ABOUT = 101 ID_EXIT = 110 class MainWindow(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) self.control = wx.TextCtrl(self,1,style=wx.TE_MULTILINE) self.CreateStatusBar() filemenu = wx.Menu() filemenu.Append(ID_ABOUT,About, Information about this program.) filemenu.AppendSeparator() filemenu.Append(ID_EXIT,Exit, Terminate the program.) menuBar = wx.MenuBar() menuBar.Append(filemenu,File) self.SetMenuBar(menuBar) self.Show(True) app = wx.PySimpleApp() frame = MainWindow(None, -1, Sample editor) app.MainLoop() Simple enough, but every single time I try to run it IDLE gives me this instead of the app I was hoping for: Traceback (most recent call last): File C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap \Python Stuff\Batch Picture Converter\main.py, line 24, in module frame = MainWindow(None, -1, Sample editor) File C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap \Python Stuff\Batch Picture Converter\main.py, line 9, in __init__ wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) File C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx \_windows.py, line 501, in __init__ _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) PyNoAppError: The wx.App object must be created first! As far as I can tell, the wx.App object IS being created first. I suspect a race condition of some sort here, but can anyone shed some light on this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Someone enlightened me
Marcus Low wrote: Opps here is the mail again, incase my formatting is lost, can someone explain to me why this code behaves differently when lister and self.lister is swap remarked. class abc : # remark this later and unremark self.lister lister = [] def __init__ (self, val): #self.lister = [] self.lister.append(val) globallist = [] def test () : global l for x in range(10) : o = abc(x) globallist.append(o) o = for i in globallist : print i.lister test() -- http://mail.python.org/mailman/listinfo/python-list It's a Python scoping rule: If a variable is assigned to anywhere within a function, it is assumed to be local *everywhere* within that function. See the faq for more: http://www.python.org/doc/faq/programming/#what-are-the-rules-for-local-and-global-variables-in-python Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython code giving strange errors.
teh_sAbEr wrote: I'm busy trying to learn wxPython, and i'm trying to run the following piece of code (its from the wxPyWiki tutorial): import wx ID_ABOUT = 101 ID_EXIT = 110 class MainWindow(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) self.control = wx.TextCtrl(self,1,style=wx.TE_MULTILINE) self.CreateStatusBar() filemenu = wx.Menu() filemenu.Append(ID_ABOUT,About, Information about this program.) filemenu.AppendSeparator() filemenu.Append(ID_EXIT,Exit, Terminate the program.) menuBar = wx.MenuBar() menuBar.Append(filemenu,File) self.SetMenuBar(menuBar) self.Show(True) app = wx.PySimpleApp() frame = MainWindow(None, -1, Sample editor) app.MainLoop() Simple enough, but every single time I try to run it IDLE gives me this instead of the app I was hoping for: Traceback (most recent call last): File C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap \Python Stuff\Batch Picture Converter\main.py, line 24, in module frame = MainWindow(None, -1, Sample editor) File C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap \Python Stuff\Batch Picture Converter\main.py, line 9, in __init__ wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) File C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx \_windows.py, line 501, in __init__ _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) PyNoAppError: The wx.App object must be created first! As far as I can tell, the wx.App object IS being created first. I suspect a race condition of some sort here, but can anyone shed some light on this? The main frame has to be created by the app itself, e.g. like so: class App(wx.App): def OnInit(self): self._frame = MainFrame( None, -1, _APP_CAPTION) self._frame.Show( True) self.SetTopWindow( self._frame) return True def Run(): app = App() app.MainLoop() if __name__ == '__main__': Run() HTH Thin -- http://mail.python.org/mailman/listinfo/python-list
SAX XML Parse Python error message
SAX XML Parse Python error message Hi, My first attempt at SAX, but have an error message I need help with. I cite the error message, code, and xml below. Be grateful if anyone can tell me what the fix is. Thanks. Traceback (most recent call last): File C:\Python24\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py, line 310, in RunScript exec codeObject in __main__.__dict__ File C:\pythonscripts\xml\parse3.py, line 43, in ? parser.parse(r'C:\perlscripts\xml\Document2.kml') File C:\Python24\lib\xml\sax\expatreader.py, line 107, in parse xmlreader.IncrementalParser.parse(self, source) File C:\Python24\lib\xml\sax\xmlreader.py, line 123, in parse self.feed(buffer) File C:\Python24\lib\xml\sax\expatreader.py, line 207, in feed self._parser.Parse(data, isFinal) File C:\Python24\lib\xml\sax\expatreader.py, line 303, in end_element self._cont_handler.endElement(name) File C:\pythonscripts\xml\parse3.py, line 39, in endElement print self.description, str(self.coordinates) AttributeError: G_Handler instance has no attribute 'coordinates' Code: from xml.sax import make_parser from xml.sax.handler import ContentHandler import string class G_Handler(ContentHandler): def __init__ (self): self.isFolderElement = 0 self.isdescriptionElement = 0 self.iscoordinatesElement = 0 def startElement(self, name , attrs): if name == 'Folder': self.isFolderElement= 1 self.Folder = if name == 'description': self.isdescriptionElement= 1 self.description = if name == 'coordinates': self.iscoordinatesElement = 1 self.coordinates = def characters (self, ch): if self.isFolderElement == 1: self.Folder = ch if self.isdescriptionElement == 1: self.description = ch if self.iscoordinatesElement == 1: self.coordinates = ch def endElement(self, name): if name == 'Folder': self.isFolderElement = 0 if name == 'description': self.isdescriptionElement= 0 if name == 'coordinates': self.iscoordinatesElement = 0 print self.description, str(self.coordinates) parser = make_parser() parser.setContentHandler(G_Handler()) parser.parse(r'C:\perlscripts\xml\Document2.kml') ?xml version=1.0 encoding=UTF-8? Folder description abc /description coordinates -84.4, 33.7 /coordinates description abc /description coordinates -86.7, 36.1 /coordinates /Folder -- http://mail.python.org/mailman/listinfo/python-list
Newbie Threading Question
It seems strange, but I can't find a list of operating systems which support / don't support threading in Python. Can anyone point me in the right direction? Thanks, Sam -- http://mail.python.org/mailman/listinfo/python-list
Re: SAX XML Parse Python error message
goldtech wrote: My first attempt at SAX, but have an error message I need help with. Just in case you prefer writing readable code over debugging SAX code into existence, try lxml. http://codespeak.net/lxml/ Here is a presentation you might find interesting. http://codespeak.net/lxml/s5/lxml-ep2008.html Stefan -- http://mail.python.org/mailman/listinfo/python-list
Unexpected default arguments behaviour (Maybe bug?)
Hi, I have just encountered a Python behaviour I wouldn't expect. Take the following code: class Parent: a = 1 def m (self, param = a): print param = %d % param class Child (Parent): a = 2 p = Parent () p.m () c = Child () c.m () I would expect to receive the following output: param = 1 param = 2 But actually I get: param = 1 param = 1 Is this the correct behaviour, and then why, or is it a bug? For reference, I am using Python 2.5.1 on UNIX. Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list
wxPython Tab
Is there a way to get wxPython to change the visible tab in a notebook (like I have tab 1 open but the computer will automatically change to tab 2)? Thanks, Sam -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython Tab
On Jul 13, 6:20 pm, Sparky [EMAIL PROTECTED] wrote: Is there a way to get wxPython to change the visible tab in a notebook (like I have tab 1 open but the computer will automatically change to tab 2)? Thanks, Sam look at http://docs.wxwidgets.org/stable/wx_wxnotebook.html#wxnotebooksetpagetext greetings, uwe -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a Python app with Mozilla
Is that why Komodo is so damned slow Brian Quinlan wrote: Kevin Walzer wrote: Komodo is not a Python application. It is a Mozilla application that supports Python development. Komodo is more akin to Thunderbird and Firefox than anything else; it uses the XUL framework for rendering widgets, if I'm not mistaken. If you want to build an application like Komodo, get a book on developing with the Mozilla framework (XUL, XPCOM, and all that) and look at that. Python has little to do with that. Most application logic in Komodo is implemented in Python, using the PyXPCOM bindings. The UI is implemented using XUL and JavaScript. The editor is Scintilla (C++). ../Komodo Edit.app/Contents/MacOS % find . -name *.py | xargs wc ... ... 126392 456858 4949602 total This doesn't include the python code in the Python libraries themselves. Cheers, Brian -- http://mail.python.org/mailman/listinfo/python-list
Magic?
So I was playing around with properties and wrote this: class lstr(str): def __init__(self, initval): self._s = initval self._len = len(self._s) def fget_s(self): return str(self._s) def fset_s(self, val): self._s = val self._len = len(self._s) s = property(fget_s, fset_s) def fget_len(self): return self._len def fset_len(self, val): raise AttributeError, Attribute is read-only. len = property(fget_len, fset_len) I obviously aimed at defining setters and getters for 's' and 'len' attributes via using properties to that. However, it appears that somehow this object prints the value of 's' attribute without me setting any specific methods to do that: astr = lstr('abcdef') astr 'abcdef' astr.swapcase() 'ABCDEF' How does it know to do that? I mean, I can understand how it knows to do that since I used property: astr.s 'abcdef' vars(astr) {'_len': 6, '_s': 'abcdef'} How does the instance know to use _s value to return when the instance is called? Is this due to some trick handling of overriden __init__ method (i.e. it knows to treat initval argument somehow specially)? Some other way? If so, how? -- http://mail.python.org/mailman/listinfo/python-list
Re: spam
rickman wrote: I love the way that people who plonk others feel the need to inform everyone of it. That ranks up there with, I know what you are, but what am I? It is a matter of basic politeness and common courtesy. Without the plonk, the killfiled poster is left hanging in the wind, wasting his time writing responses that will never be read. If you were talking with a blind man, would you silently creep out of the room leaving him talking to the walls, or would you be polite and excuse yourself before leaving? -- http://mail.python.org/mailman/listinfo/python-list
Re: Magic?
However, it appears that somehow this object prints the value of 's' attribute without me setting any specific methods to do that: astr = lstr('abcdef') astr 'abcdef' astr.swapcase() 'ABCDEF' Correction: it doesn't really get the value from _s attribute: astr = lstr('abcdef') astr.s 'abcdef' astr.s='xyzzy' astr 'abcdef' astr.s 'xyzzy' So my updated question is where does this lstr() instance keep the original value ('abcdef')? It obviously has smth to do with inheriting after str class, but I don't get the details of the mechanism. -- http://mail.python.org/mailman/listinfo/python-list
Re: spam
[EMAIL PROTECTED] wrote: rickman wrote: I love the way that people who plonk others feel the need to inform everyone of it. That ranks up there with, I know what you are, but what am I? It is a matter of basic politeness and common courtesy. Without the plonk, the killfiled poster is left hanging in the wind, wasting his time writing responses that will never be read. If you were talking with a blind man, would you silently creep out of the room leaving him talking to the walls, or would you be polite and excuse yourself before leaving? I think most people will want to be polite to a blind. I very much doubt that the same applies to usenet posters they want to plonk. Arne -- http://mail.python.org/mailman/listinfo/python-list
Re: like py2exe, but on a mac
On 13 jul 2008, at 00.39, Alexnb wrote: Hi All I am wondering what I can do to turn a python app (.py) into a mac OSX applicaiton (.app). Just like py2exe does. But I am also wondering since in your applications folder on macs it usually doesn't have an actual folder for each app. Rather an icon. so for firefox, you just see the icon. Unlike windows where you have a folder with everything, and the actual program is in it. where is all the application info stored? just in the .app? Finally whether or not there is an app like py2exe for mac, is there a way to skip the middle man and turn it straight into a .dmg with the app inside? -- View this message in context: http://www.nabble.com/like-py2exe%2C-but-on-a-mac-tp18424336p18424336.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list Platypus can bundle any script into an .app bundle. --- See the amazing new SF reel: Invasion of the man eating cucumbers from outer space. On congratulations for a fantastic parody, the producer replies : What parody? Tommy Nordgren [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: spam [EMAIL PROTECTED] [EMAIL PROTECTED]
donald wrote: Arne Vajhøj wrote: Google does not accept spam complaints. Go ahead, try it. That's why they've been the #1 Usenet spamming tool for years now. What you're seeing is the spam slowly expanding into the software development groups. uk.railway is probably a random group added to confuse spam filters. Some groups, like rec.photo.digital, have been getting hundreds of Google spams a day for about a year. Ask your news service for a Google UDP (Usenet Death Penalty) or configure your reader to drop everything with googlegroups.com in the Message-ID. Some real users do use GG. This is true, however there are acceptable losses. Everybody is free to look at it that way. Arne -- http://mail.python.org/mailman/listinfo/python-list
Socket problems
I am trying to write a simple python IRC client, roughly following this guide: http://www.devshed.com/c/a/Python/Python-and-IRC/ I have written some code, which uses the same commands as the guide, but I get this error: Traceback (most recent call last): File /Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/threading.py, line 486, in __bootstrap_inner self.run() File pythonirc.py, line 31, in run self.sock.send('NICK %s\r\n') % self.nick AttributeError: send Here is my code so far: [code] #!/usr/bin/env python from socket import * from threading import Thread import sys class IRCBot(Thread): def __init__(self, host, room, nick, port=6667, ssl=0): Thread.__init__(self) self.host = host self.port = port self.ssl = ssl self.room = room self.nick = nick self.sock = socket(AF_INET, SOCK_STREAM) def run(self): print Connecting... try: self.sock.connect((self.host, self.port)) except: print Could not connect to %s % self.host sys.exit(1) if self.ssl: try: self.sock = ssl(self.sock) except: print Server does not suport SSL sys.exit(1) self.sock.send('NICK %s\r\n') % self.nick self.sock.send('USER PyIRC PyIRC PyIRC :Python IRC\r\n') self.sock.send('JOIN #%s\r\n') % self.room while True: data = self.sock.recv(4096) if data.find('PING') != -1: self.sock.send('PONG' + data.split()[1]+'\r\n') print data def close(self): self.sock.send('PART #%s\r\n') % self.room self.sock.send('QUIT\r\n') self.sock.shutdown(SHIT_RDWR) self.sock.close() IRCBot('irc.psych0tik.net','hbh', 'pythonircclient',6697,1).start() [/code] Anyone know why it might be doing this? Config problem? Thanks in advance, Jon -- http://mail.python.org/mailman/listinfo/python-list
Re: heapq question
I understand that heapq is not that efficient to implement timeouts as I thought at first. It would have been perfect if there were functions to remove arbitrary elements withouth needing to re-heapify() the heap every time. It is efficient for that - you just need to use it correctly. To remove the nth element from a heap, replace it with the last element, and then _siftup that element: def remove_at_index_n(heap, n): if n == len(heap)-1: return heap.pop() result = heap[n] heap[n] = heap.pop() heapq._siftup(heap, n) return result The time complexity for that operation is O(log(len(heap))). HTH, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Unexpected default arguments behaviour (Maybe bug?)
[EMAIL PROTECTED] napisał(a): Hi, I have just encountered a Python behaviour I wouldn't expect. Take the following code: class Parent: a = 1 def m (self, param = a): print param = %d % param class Child (Parent): a = 2 p = Parent () p.m () c = Child () c.m () I would expect to receive the following output: param = 1 param = 2 But actually I get: param = 1 param = 1 Is this the correct behaviour, and then why, or is it a bug? For reference, I am using Python 2.5.1 on UNIX. Thanks in advance! I expect it's because default values for parameters are evaluated and bound at definition time. So once def m (self, param = a): line executes, the default value for parameter is forever bound to be 1. What you can do is for example: def m (self, param = None): if param is None: param = self.a print param = %d % param Regards, Marek -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question : Iterators and zip
[EMAIL PROTECTED] wrote: What is this *lis operation called? I am having trouble finding any reference to it in the python docs or the book learning python. One might call this argument unpacking, but Language Manual / Expressions / Primaries / Calls simply calls it *expression syntax. If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments; if there are positional arguments x1,...,*xN* , and expression evaluates to a sequence y1,...,*yM*, this is equivalent to a call with M+N positional arguments x1,...,*xN*,*y1*,...,*yM*. See Compound Statements / Function definitions for the mirror syntax in definitions. tjr -- http://mail.python.org/mailman/listinfo/python-list
Mutually referencing imports -- impossible?
I started off with a module that defined a class Vehicle, and then subclasses Car and Motorcycle. In the Car class, for some bizarre reason, I instantiated a Motorcycle. Please pretend that this can't be avoided for now. Meanwhile, my Motorcycle class instantiated a Car as well. Then I moved the Car and Motorcycle classes into separate files. Each imported the Vehicle module. Then I discovered that my Car module failed because the global Motorcycle wasn't defined. The same problem happened in my Motorcycle module. Car and Motorcycle can't both import each other. In the beginning, when all three (Vehicle, Car, and Motorcycle) were defined in the same file, everything worked fine. I don't know how to split them out in separate files now though and I really wish I could because the single file is enormous. Any ideas? Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Functional/Best?
Tim Cook wrote: I guess I can classify my application(s) as more procedural than anything else. But I have a question about the best way to handle something in Python. When given a mapping of keywords, I want to call a function based on a certain keyword found when parsing a text file. The mapping looks like this: definClassMap={'SECTION':'bldSection','COMPOSITION':'bldComposition','OBSERVATION':'bldObservation','ITEM_TREE':'bldItemTree'} So if the text file contains 'ITEM_TREE' I want to call bldItemTree which creates an instance of the class ItemTree. I currently use an if ..., elif ... construct. Is there a better, more efficient, more Pythonic way of doing this? Yes. Create a mapping of keywords to function objects rather than to function names! def bldSection(): whatever ... def bldItemTree(): whatever else class_map={ 'SECTION':bldSection, 'COMPOSITION':bldComposition, 'OBSERVATION':bldObservation, 'ITEM_TREE':bldItemTree, # trailing comma allows easy additions } for word in parselist: try; class_map[word]() except KeyError: whatever for non-keys tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Mutually referencing imports -- impossible?
Matthew Wilson wrote: I started off with a module that defined a class Vehicle, and then subclasses Car and Motorcycle. In the Car class, for some bizarre reason, I instantiated a Motorcycle. Please pretend that this can't be avoided for now. Meanwhile, my Motorcycle class instantiated a Car as well. Then I moved the Car and Motorcycle classes into separate files. Each imported the Vehicle module. Then I discovered that my Car module failed because the global Motorcycle wasn't defined. The same problem happened in my Motorcycle module. Car and Motorcycle can't both import each other. In the beginning, when all three (Vehicle, Car, and Motorcycle) were defined in the same file, everything worked fine. I don't know how to split them out in separate files now though and I really wish I could because the single file is enormous. Any ideas? Matt It is easy for imports to be mutually referencing. This presents no problem to Python if the importing of one module is interrupted by the import of another. However, if one of them imports specific names from a module, from ABC import abc or from ABC import * then it's possible that the (interrupted) import of module ABC has not progressed to the point that abc is defined. The solution: Just import ABC and later reference ABC.abc That being said, it is still a good design practice to structure your modules hierarchically rather than a circularly. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Mutually referencing imports -- impossible?
On Jul 13, 1:55 pm, Matthew Wilson [EMAIL PROTECTED] wrote: I started off with a module that defined a class Vehicle, and then subclasses Car and Motorcycle. In the Car class, for some bizarre reason, I instantiated a Motorcycle. Please pretend that this can't be avoided for now. Meanwhile, my Motorcycle class instantiated a Car as well. Then I moved the Car and Motorcycle classes into separate files. Each imported the Vehicle module. Then I discovered that my Car module failed because the global Motorcycle wasn't defined. The same problem happened in my Motorcycle module. Car and Motorcycle can't both import each other. In the beginning, when all three (Vehicle, Car, and Motorcycle) were defined in the same file, everything worked fine. I don't know how to split them out in separate files now though and I really wish I could because the single file is enormous. Any ideas? First thing to do is ask yourself: Are the Car and Motorcycle being created at import time, or are they being created after the imports by a function call? If it's the former, then yes, it's impossible. You can't do this, for instance: car.py: - import motorcycle a = motorcycle.Motorcycle() - motorcycle.py: - import car b = car.Car() - However, you can stick them in functions and call them afterwards and it will work: car.py: - import motorcycle def create_motorcycle(): global a a = motorcycle.Motorcycle() - motorcycle.py: - import car def create_car(): global b a = car.Car() - vehicle.py - import car import motorcycle car.create_motorcycle() motorcycle.create_car() - Second, if you're using from ... import statements, it won't work; you should change it to use plain imports as I did above. So the following wouldn't work : motorcycle.py: - from car import * a = Motorcycle() - car.py: - from motorcycle import * b = Car() - Third, if Motorcycle and Car are inside packages, you still need to avoid from ... import even just to import the module (unless you're willing to hook into the import machinery). For example, if car.py, motorcycle.py, and vehicle.py are all parts of the package carsim, then you'd have to do this: motorcycle.py: import carsim.car def create_car(): global a a = carsim.car.Car() and not motorcycle.py: from carsim import car def create_car(): global a a = car.Car() This last limitation is due to a wart in the import logic. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.connect() hangs in SYN_SENT state.
On Jul 13, 1:14 am, Miles [EMAIL PROTECTED] wrote: On Sat, Jul 12, 2008 at 11:23 PM, bukzor [EMAIL PROTECTED] wrote: I'm connecting to an apache2 process on the same machine, for testing. When looking at netstat, the socket is in the SYN_SENT state, like this: $netstat -a -tcp tcp 0 0 *:www *:* LISTEN 7635/apache2 tcp 0 1 bukzor:38234 adsl-75-61-84-249.d:www SYN_SENT 9139/python Anyone know a general reason this might happen? Even better, a way to fix it? That socket connection is to a remote machine, not the same one. Your test code works fine for me. The hang then crash (and I'm assuming crash here means an uncaught exception) just means that your packets are being silently ignored by whatever machine you're actually attempting to connect to. It's possible that your machine has odd DNS settings causing buzkor.hopto.org to resolve to the wrong address. -Miles I'm connecting to my machine through the internet, and the resolved URL of my router is what you're seeing above. If you run the code above you'll see what I mean. Thanks tho, --Buck -- http://mail.python.org/mailman/listinfo/python-list
Re: Socket problems
SSL objects use write, not send. You also need to change this: self.sock.write('NICK %s\r\n') % self.nick to this: self.sock.write('NICK %s\r\n' % self.nick) If you don't, the interpreter will bomb on trying to concatenate the return value for write (an integer) with the string self.nick. Hope this helps... Jonathon [EMAIL PROTECTED] wrote: I am trying to write a simple python IRC client, roughly following this guide: http://www.devshed.com/c/a/Python/Python-and-IRC/ I have written some code, which uses the same commands as the guide, but I get this error: Traceback (most recent call last): File /Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/threading.py, line 486, in __bootstrap_inner self.run() File pythonirc.py, line 31, in run self.sock.send('NICK %s\r\n') % self.nick AttributeError: send Here is my code so far: [code] #!/usr/bin/env python from socket import * from threading import Thread import sys class IRCBot(Thread): def __init__(self, host, room, nick, port=6667, ssl=0): Thread.__init__(self) self.host = host self.port = port self.ssl = ssl self.room = room self.nick = nick self.sock = socket(AF_INET, SOCK_STREAM) def run(self): print Connecting... try: self.sock.connect((self.host, self.port)) except: print Could not connect to %s % self.host sys.exit(1) if self.ssl: try: self.sock = ssl(self.sock) except: print Server does not suport SSL sys.exit(1) self.sock.send('NICK %s\r\n') % self.nick self.sock.send('USER PyIRC PyIRC PyIRC :Python IRC\r\n') self.sock.send('JOIN #%s\r\n') % self.room while True: data = self.sock.recv(4096) if data.find('PING') != -1: self.sock.send('PONG' + data.split()[1]+'\r\n') print data def close(self): self.sock.send('PART #%s\r\n') % self.room self.sock.send('QUIT\r\n') self.sock.shutdown(SHIT_RDWR) self.sock.close() IRCBot('irc.psych0tik.net','hbh', 'pythonircclient',6697,1).start() [/code] Anyone know why it might be doing this? Config problem? Thanks in advance, Jon -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
spam
spam -- http://mail.python.org/mailman/listinfo/python-list
RE: Terminate a python script from linux shell / bash script
Thank you guys for your help. My problem is that I project to use this command to terminate a script when uninstalling the software, so I can't store the PID. This command will be integrated in the spec file of the RPM package. Here's the script I'll use, it may help someone else: #!/bin/sh # PYTHON SCRIPT PROCESS KILLER by GBO v0.1 # This script will look for all the lines containing $SOFTWARENAME in the process list, and close them SOFTWARENAME='yoursoftware' #This is case insensitive JOBPRESENT=$(ps -ef | grep -i $SOFTWARENAME | grep -v grep) echo $JOBPRESENT ps -ef | grep -i $SOFTWARENAME | grep -v grep | awk '{print $2}' | xargs kill _ Pendant tout l'été, consultez vos emails Hotmail sur votre mobile ! http://www.messengersurvotremobile.com/?d=hotmail -- http://mail.python.org/mailman/listinfo/python-list
Re: heapq question
On 13 Lug, 19:31, Martin v. Löwis [EMAIL PROTECTED] wrote: I understand that heapq is not that efficient to implement timeouts as I thought at first. It would have been perfect if there were functions to remove arbitrary elements withouth needing to re-heapify() the heap every time. It is efficient for that - you just need to use it correctly. To remove the nth element from a heap, replace it with the last element, and then _siftup that element: def remove_at_index_n(heap, n): if n == len(heap)-1: return heap.pop() result = heap[n] heap[n] = heap.pop() heapq._siftup(heap, n) return result The time complexity for that operation is O(log(len(heap))). HTH, Martin Thanks, by doing some quick benchamrks it seems 20% faster than using heapify(). And if instead of removing an element I'd want to change its value? E.g.: heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] heapify(heap) heap [0, 2, 1, 4, 5, 6, 7, 8, 9] heap[4] = 12 --- Giampaolo http://code.google.com/p/pyftpdlib/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Threading Question
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 I'm not an expert on Python threading, so don't take my word as low, however, I believe that there's no need for a list of systems which support it because the Python virtual machine handles it. Thus, any system which supports Python (or at least Python versions with threading) will support Python threading. Again, I don't know a lot about this, but it would make sense. Sparky wrote: It seems strange, but I can't find a list of operating systems which support / don't support threading in Python. Can anyone point me in the right direction? Thanks, Sam -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkh6V8YACgkQLMI5fndAv9hVKgCePbrN4nwbsdZXNfIcnm3cXac5 5kUAnR0OeNB0gjsksRD2W5gcZ8c0pby0 =p3U+ -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: Mutually referencing imports -- impossible?
On Jul 13, 11:55 am, Matthew Wilson [EMAIL PROTECTED] wrote: I started off with a module that defined a class Vehicle, and then subclasses Car and Motorcycle. In the Car class, for some bizarre reason, I instantiated a Motorcycle. Please pretend that this can't be avoided for now. Meanwhile, my Motorcycle class instantiated a Car as well. Then I moved the Car and Motorcycle classes into separate files. Each imported the Vehicle module. Then I discovered that my Car module failed because the global Motorcycle wasn't defined. The same problem happened in my Motorcycle module. Car and Motorcycle can't both import each other. In the beginning, when all three (Vehicle, Car, and Motorcycle) were defined in the same file, everything worked fine. I don't know how to split them out in separate files now though and I really wish I could because the single file is enormous. Any ideas? Matt While it's possible for circular imports to work, it's very dangerous: it's not always possible to tell what went wrong without tracking down the process of the import step by step. There are more productive ways of banging your head against the wall and going insane. In your situation, it might be a whole lot easier to extract a common superclass that both of your classes could inherit from. John Roth -- http://mail.python.org/mailman/listinfo/python-list
Generating Lip-Synched animation?
Hello, I'm trying to write something like http://blabberize.com/, generating a video file with lip-sync. Currently the general idea is: * Generate animation images using GIMP * Sample voice and detect when there is sound and when there is silence - Still working on details for this one, will probably using audioop and wave modules * Generate a list of images according to the voice (using the bitrate for sync) * Generate video from images using mencoder Before I venture into this, does anybody has a better idea? Thanks, -- Miki [EMAIL PROTECTED] http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.connect() hangs in SYN_SENT state.
On Sun, Jul 13, 2008 at 2:32 PM, bukzor [EMAIL PROTECTED] wrote: On Jul 13, 1:14 am, Miles [EMAIL PROTECTED] wrote: On Sat, Jul 12, 2008 at 11:23 PM, bukzor [EMAIL PROTECTED] wrote: I'm connecting to an apache2 process on the same machine, for testing. When looking at netstat, the socket is in the SYN_SENT state, like this: $netstat -a -tcp tcp0 0 *:www *:* LISTEN 7635/apache2 tcp0 1 bukzor:38234adsl-75-61-84-249.d:www SYN_SENT9139/python Anyone know a general reason this might happen? Even better, a way to fix it? That socket connection is to a remote machine, not the same one. Your test code works fine for me. The hang then crash (and I'm assuming crash here means an uncaught exception) just means that your packets are being silently ignored by whatever machine you're actually attempting to connect to. It's possible that your machine has odd DNS settings causing buzkor.hopto.org to resolve to the wrong address. I'm connecting to my machine through the internet, and the resolved URL of my router is what you're seeing above. If you run the code above you'll see what I mean. I did run the code, and as I said, it works fine. Your description of the setup is not consistent. The netstat output unambiguously states that a Python script on buzkor is attempting to open a connection to the HTTP port on the adsl machine (and failing because adsl is not responding). The problem here is not Python; you seem to be confused about which machine is connecting to which. -Miles -- http://mail.python.org/mailman/listinfo/python-list
Re: heapq question
Giampaolo Rodola' [EMAIL PROTECTED] wrote: Thanks, that's what I wanted to know. I understand that heapq is not that efficient to implement timeouts as I thought at first. It would have been perfect if there were functions to remove arbitrary elements withouth needing to re-heapify() the heap every time. Thanks for your help anyway. There could be suitable functions, but there aren't any. I *think* this would work (untested): def popitem(heap, pos): if pos == 0: return heappop(heap) if pos == len(heap)-1: return heap.pop(pos) res = heap[pos] heap[pos] = heap.pop() heapq._siftup(heap, pos) return res the catch is that _siftup is written in Python whereas the publicly exposed heapq functions are written in C, so although in theory this is 'more efficient' than calling heapify() on the entire heap it may actually be slower. Bottom line though is that heaps aren't really suitable for timeouts. -- http://mail.python.org/mailman/listinfo/python-list
logging via SocketHandler and TCPserver
Every time I look at the logging module (up until now) I've given up and continue to use my home-grown logger that I've been using for years. I'm not giving up this time ;-) I find that I REALLY need to be able to monitor LOTS of running programs/processes and thought it would be nice to have them use SocketHandler logging and then I would write TCPServer to accept the log messages for real-time monitoring. I Googled (is that now a verb?) for several hours and came up with some code that I've turned in to something that works, but I can't figure out how to disconnect the server once it is connected The goal is to be able to start TCPServer, monitor the log messages sent via SocketHandler logger, disconnect, and move to the next application. Eventually I would like to wrap a GUI around all of this for monitoring a complex web application. Everything works, it just appears that I get into the while loop in LogRecordStreamHandler.handle and it never breaks out (until I kill the client). I can't seem to do anything with the LogRecordSocketReceiver.abort attribute to make it quit. I'm sure it is something simple (stupid?), but I've spent about 4 hours and I'm not getting anywhere. Thanks in advance for any assistance. Regards, Larry Below is my code: import sys import time import logging if sys.argv[1] == 'client': import logging.config logging.config.fileConfig(logging.conf) #create logger logger = logging.getLogger(VESconsole) while 1: logger.debug(debug message) logger.info(info message) logger.warn(warn message) logger.error(error message) logger.critical(critical message) time.sleep(2) elif sys.argv[1] == 'server': import cPickle import logging.handlers import SocketServer import struct import signal class LogRecordStreamHandler(SocketServer.StreamRequestHandler): Handler for a streaming logging request. This basically logs the record using whatever logging policy is configured locally. def handle(self): Handle multiple requests - each expected to be a 4-byte length, followed by the LogRecord in pickle format. Logs the record according to whatever policy is configured locally. while 1: chunk = self.connection.recv(4) if len(chunk) 4: break slen = struct.unpack(L, chunk)[0] chunk = self.connection.recv(slen) while len(chunk) slen: chunk = chunk + self.connection.recv(slen - len(chunk)) obj = self.unPickle(chunk) record = logging.makeLogRecord(obj) self.handleLogRecord(record) def unPickle(self, data): return cPickle.loads(data) def handleLogRecord(self, record): t = time.strftime('%a, %d %b %y %H:%M:%S', time.localtime(record.created)) print %s %s % (t, record.getMessage()) class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer): simple TCP socket-based logging receiver suitable for testing. allow_reuse_address = 1 def __init__(self, host='localhost', port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, handler=LogRecordStreamHandler): SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler) self.abort = 0 self.timeout = 1 self.logname = None def serve_until_stopped(self): import select abort = 0 while not abort: rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout) if rd: self.handle_request() abort = self.abort print serve_until_stopped exiting # # Start ThreadingTCPServer instance to accept SocketHandler log # messages from client. # tcpserver = LogRecordSocketReceiver() print Starting ThreadingTCPServer... tcpserver.serve_until_stopped() ''' #-logging.conf- [loggers] keys=root [handlers] keys=socketHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=socketHandler [handler_socketHandler] class=handlers.SocketHandler level=DEBUG args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT) host=localhost port=DEFAULT_TCP_LOGGING_PORT [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt= ''' -- http://mail.python.org/mailman/listinfo/python-list
Re: heapq question
On Sun, Jul 13, 2008 at 3:05 PM, Giampaolo Rodola' [EMAIL PROTECTED] wrote: On 13 Lug, 19:31, Martin v. Löwis [EMAIL PROTECTED] wrote: I understand that heapq is not that efficient to implement timeouts as I thought at first. It would have been perfect if there were functions to remove arbitrary elements withouth needing to re-heapify() the heap every time. It is efficient for that - you just need to use it correctly. To remove the nth element from a heap, replace it with the last element, and then _siftup that element: The time complexity for that operation is O(log(len(heap))). The problem is that in order to remove an arbitrary element from a heap, you usually have to do an O(n) linear search in order to find it first, since you can't know ahead of time which index an arbitrary element is at. (You can, actually, but only if your heap implementation somehow notifies the elements of their new index when it moves them in the heap, which the Python heapq module doesn't do, so you'd have to write your own heap implementation.) And if instead of removing an element I'd want to change its value? E.g.: heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] heapify(heap) heap [0, 2, 1, 4, 5, 6, 7, 8, 9] heap[4] = 12 Don't do that; you must first remove the element and then reinsert it. -Miles -- http://mail.python.org/mailman/listinfo/python-list
Re: SAX XML Parse Python error message
I would be grateful for support with the code I cited. It's not long and fairly standard. I'm sure my error(s) would be glaring to more experienced coders. I appreciated the heads-up about other options but I would be grateful for help getting this code to run. Thanks On Jul 13, 11:47 am, Stefan Behnel [EMAIL PROTECTED] wrote: goldtech wrote: My first attempt at SAX, but have an error message I need help with. Just in case you prefer writing readable code over debugging SAX code into existence, try lxml. http://codespeak.net/lxml/ Here is a presentation you might find interesting. http://codespeak.net/lxml/s5/lxml-ep2008.html Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: numeric emulation and the rich comparison operators
Gabriel Genellina wrote: En Thu, 10 Jul 2008 17:37:42 -0300, Ethan Furman [EMAIL PROTECTED] escribi�: Greetings, List! Still working on my Measure class, and my next question is... (drum roll please ;) What are the advantages of using __[eq|ne|lt|gt|le|ge]__ vs __cmp__? If your objects obey the trichotomy law (an object MUST BE less than, greater than, or equal to another one, and there is no other possibility) then __cmp__ is enough, and easier to define than all the rich comparison operations. In other cases, __cmp__ is not suitable: by example, complex numbers can't define greater than [in a way that preserves the meaning for real numbers]; you can only use equal or not equal. You can't use __cmp__ for this, because it *has* to return either 0 or 0 (implying greater than or less than). In this case it's best to use the rich comparison operators: define __eq__ and __ne__ and make all other comparisons between complex numbers raise an exception. That's exactly the information I needed. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Magic?
On Sun, Jul 13, 2008 at 12:55 PM, mk [EMAIL PROTECTED] wrote: So my updated question is where does this lstr() instance keep the original value ('abcdef')? It obviously has smth to do with inheriting after str class, but I don't get the details of the mechanism. Through the str.__new__ method: http://docs.python.org/ref/customization.html Calling a constructor: foo = Foo(1, 2, 3) Is roughly equivalent to: foo = Foo.__new__(Foo, 1, 2, 3) Foo.__init__(foo, 1, 2, 3) As a side note, you may already know this, but it's not necessary to create a property setter that raises an error to make a property read-only; you can simply not define a setter method. -Miles -- http://mail.python.org/mailman/listinfo/python-list
Re: SAX XML Parse Python error message
On Jul 13, 3:00 pm, goldtech [EMAIL PROTECTED] wrote: I would be grateful for support with the code I cited. It's not long and fairly standard. I'm sure my error(s) would be glaring to more experienced coders. I appreciated the heads-up about other options but I would be grateful for help getting this code to run. Thanks Initialize self.coodinates in the __init__ or indent the print self.description, str(self.coordinates) one more level. You have to remember that endElement is being called on the end of every element. In your case it is called by /description but the parser did not see coordinates yet. In def characters you should be collecting the ch in a buffer. It may be called multiple times for the same element. Something like self.description += ch would do for starters. Also you do not need to convert self.coordinates to string before printing, it is already a string and even if it was not print would convert it for you. That's it for now :-) Others may spot more issues with your code or my response. On the positive side I really liked how you asked the question. There was a short runnable example and traceback. Waldemar -- http://mail.python.org/mailman/listinfo/python-list
Re: SAX XML Parse Python error message
On Jul 13, 5:30 pm, Waldemar Osuch [EMAIL PROTECTED] wrote: On Jul 13, 3:00 pm, goldtech [EMAIL PROTECTED] wrote: I would be grateful for support with the code I cited. It's not long and fairly standard. I'm sure my error(s) would be glaring to more experienced coders. I appreciated the heads-up about other options but I would be grateful for help getting this code to run. Thanks Initialize self.coodinates in the __init__ or indent the print self.description, str(self.coordinates) one more level. You have to remember that endElement is being called on the end of every element. In your case it is called by /description but the parser did not see coordinates yet. In def characters you should be collecting the ch in a buffer. It may be called multiple times for the same element. Something like self.description += ch would do for starters. Also you do not need to convert self.coordinates to string before printing, it is already a string and even if it was not print would convert it for you. That's it for now :-) Others may spot more issues with your code or my response. On the positive side I really liked how you asked the question. There was a short runnable example and traceback. Waldemar Putting the print statements were they won't cause trouble and using ...+= ch (vs. only =) in the character section fixed it: ... def endElement(self, name): ... if name == 'description': self.isdescriptionElement= 0 print self.description if name == 'coordinates': self.iscoordinatesElement = 0 print self.coordinates ... I need to read your answer again carefully - I don't know if what I did is best - but it seemed to fix it. Thank you for the clear and cogent answer. Lee G. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unexpected default arguments behaviour (Maybe bug?)
On 13 Lug, 19:42, [EMAIL PROTECTED] wrote: I expect it's because default values for parameters are evaluated and bound at definition time. So once def m (self, param = a): line executes, the default value for parameter is forever bound to be 1. What you can do is for example: Yes, that's what I thought, too. Although, it does not seem to me the correct thing that has to be done, that is why I reported it. Also thanks for your suggestion, that might work, even though I already have implemented a workaround (two different methods). Regards! -- http://mail.python.org/mailman/listinfo/python-list
Re: Functional/Best?
On Jul 13, 7:00 pm, Terry Reedy [EMAIL PROTECTED] wrote: Tim Cook wrote: I guess I can classify my application(s) as more procedural than anything else. But I have a question about the best way to handle something in Python. When given a mapping of keywords, I want to call a function based on a certain keyword found when parsing a text file. The mapping looks like this: definClassMap={'SECTION':'bldSection','COMPOSITION':'bldComposition','OBSER VATION':'bldObservation','ITEM_TREE':'bldItemTree'} So if the text file contains 'ITEM_TREE' I want to call bldItemTree which creates an instance of the class ItemTree. I currently use an if ..., elif ... construct. Is there a better, more efficient, more Pythonic way of doing this? Yes. Create a mapping of keywords to function objects rather than to function names! def bldSection(): whatever ... def bldItemTree(): whatever else class_map={ 'SECTION':bldSection, 'COMPOSITION':bldComposition, 'OBSERVATION':bldObservation, 'ITEM_TREE':bldItemTree, # trailing comma allows easy additions } for word in parselist: try; class_map[word]() except KeyError: whatever for non-keys A nice variant of this, which minimizes repetition, is to group all the factory methods together into a class, naming them the same as the keyword... class Builder(object): def SECTION(self): ... def COMPOSITION(self): ... def OBSERVATION(self): ... def ITEM_TREE(self): ... builder = Builder() for word in parse_list: item = getattr(builder, word)() ... -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list
Using Groups inside Braces with Regular Expressions
I'm trying to delimit sentences in a block of text by defining the end-of-sentence marker as a period followed by a space followed by an uppercase letter or end-of-string. I'd imagine the regex for that would look something like: [^(?:[A-Z]|$)]\.\s+(?=[A-Z]|$) However, Python keeps giving me an unbalanced parenthesis error for the [^] part. If this isn't valid regex syntax, how else would I match a block of text that doesn't the delimiter pattern? Thanks, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Mutually referencing imports -- impossible?
On Jul 14, 3:55 am, Matthew Wilson [EMAIL PROTECTED] wrote: I started off with a module that defined a class Vehicle, and then subclasses Car and Motorcycle. In the Car class, for some bizarre reason, I instantiated a Motorcycle. Please pretend that this can't be avoided for now. Meanwhile, my Motorcycle class instantiated a Car as well. Then I moved the Car and Motorcycle classes into separate files. Each imported the Vehicle module. Then I discovered that my Car module failed because the global Motorcycle wasn't defined. The same problem happened in my Motorcycle module. Car and Motorcycle can't both import each other. And they should not import each other. In the beginning, when all three (Vehicle, Car, and Motorcycle) were defined in the same file, everything worked fine. You seem to have a strange notion of worked fine. I don't know how to split them out in separate files now though and I really wish I could because the single file is enormous. What is making a file with 3 classes enormous?? What is enormous? Any ideas? *WRONG WAY* *GO BACK* Your structure is not only bizarre, it is also (sticking with only 1 letter of the alphabet) a Byzantine, baroque, and broken concept. Asking us to pretend that this can't be avoided for now is asking us to aid and abet you in creating a meaningless and unmaintainable monster. Consider adding Truck and Bus subclasses. Will each subclass instantiate the other 3??? You should be able to add or remove a subclass without having to modify all other subclasses. The only rational solution is not to have the subclasses refer to each other. Tell us *why* you think you need to have Car refer to Motorcycle and vice versa, and we should be able to help you find a way out. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Mutually referencing imports -- impossible?
On Jul 14, 5:30 am, John Roth [EMAIL PROTECTED] wrote: On Jul 13, 11:55 am, Matthew Wilson [EMAIL PROTECTED] wrote: I started off with a module that defined a class Vehicle, and then subclasses Car and Motorcycle. In the Car class, for some bizarre reason, I instantiated a Motorcycle. Please pretend that this can't be avoided for now. Meanwhile, my Motorcycle class instantiated a Car as well. Then I moved the Car and Motorcycle classes into separate files. Each imported the Vehicle module. Then I discovered that my Car module failed because the global Motorcycle wasn't defined. The same problem happened in my Motorcycle module. Car and Motorcycle can't both import each other. In the beginning, when all three (Vehicle, Car, and Motorcycle) were defined in the same file, everything worked fine. I don't know how to split them out in separate files now though and I really wish I could because the single file is enormous. Any ideas? Matt While it's possible for circular imports to work, it's very dangerous: it's not always possible to tell what went wrong without tracking down the process of the import step by step. There are more productive ways of banging your head against the wall and going insane. In your situation, it might be a whole lot easier to extract a common superclass that both of your classes could inherit from. Like the Vehicle class the OP mentioned? -- http://mail.python.org/mailman/listinfo/python-list
Dictionary bidirectional
I need a dictionary where get the result from a 'key' (on left), but also from a 'value' (on right), how to get it? I know that dictionaries aren't bidirectional, but is there any way without use two dictionaries? Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython code giving strange errors.
On Jul 13, 10:18 am, teh_sAbEr [EMAIL PROTECTED] wrote: I'm busy trying to learn wxPython, and i'm trying to run the following piece of code (its from the wxPyWiki tutorial): import wx ID_ABOUT = 101 ID_EXIT = 110 class MainWindow(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) self.control = wx.TextCtrl(self,1,style=wx.TE_MULTILINE) self.CreateStatusBar() filemenu = wx.Menu() filemenu.Append(ID_ABOUT,About, Information about this program.) filemenu.AppendSeparator() filemenu.Append(ID_EXIT,Exit, Terminate the program.) menuBar = wx.MenuBar() menuBar.Append(filemenu,File) self.SetMenuBar(menuBar) self.Show(True) app = wx.PySimpleApp() frame = MainWindow(None, -1, Sample editor) app.MainLoop() Simple enough, but every single time I try to run it IDLE gives me this instead of the app I was hoping for: Traceback (most recent call last): File C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap \Python Stuff\Batch Picture Converter\main.py, line 24, in module frame = MainWindow(None, -1, Sample editor) File C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap \Python Stuff\Batch Picture Converter\main.py, line 9, in __init__ wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) File C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx \_windows.py, line 501, in __init__ _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) PyNoAppError: The wx.App object must be created first! As far as I can tell, the wx.App object IS being created first. I suspect a race condition of some sort here, but can anyone shed some light on this? This code works as is on Windows XP. However, I have gotten this error when trying to run it from IDLE and I've heard that that can happen in other Tkinter-based IDEs. Try running it from the command line and I'll bet you won't get that error. Also, there's a great wxPython user's group you can join from the official website: www.wxpython.org Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary bidirectional
On Jul 13, 4:21 pm, Kless [EMAIL PROTECTED] wrote: I need a dictionary where get the result from a 'key' (on left), but also from a 'value' (on right), how to get it? I know that dictionaries aren't bidirectional, but is there any way without use two dictionaries? Thanks in advance! You want to print the key as well as the value? -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Groups inside Braces with Regular Expressions
On Jul 14, 12:05 am, Chris [EMAIL PROTECTED] wrote: I'm trying to delimit sentences in a block of text by defining the end-of-sentence marker as a period followed by a space followed by an uppercase letter or end-of-string. I'd imagine the regex for that would look something like: [^(?:[A-Z]|$)]\.\s+(?=[A-Z]|$) However, Python keeps giving me an unbalanced parenthesis error for the [^] part. If this isn't valid regex syntax, how else would I match a block of text that doesn't the delimiter pattern? What is the [^(?:[A-Z]|$)] part meant to be doing? Is it meant to be matching everything up to the end of the sentence? [...] is a character class, so Python is parsing the character class as: [^(?:[A-Z]|$)] ^^ -- http://mail.python.org/mailman/listinfo/python-list
How to package a logging.config file?
I'm working on a package that uses the standard library logging module along with a .cfg file. In my code, I use logging.config.fileConfig('/home/matt/mypackage/matt.cfg') to load in the logging config file. However, it seems really obvious to me that this won't work when I share this package with others. I can't figure out what path to use when I load my .cfg file. Any ideas? Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.connect() hangs in SYN_SENT state.
On Jul 13, 1:08 pm, Miles [EMAIL PROTECTED] wrote: On Sun, Jul 13, 2008 at 2:32 PM, bukzor [EMAIL PROTECTED] wrote: On Jul 13, 1:14 am, Miles [EMAIL PROTECTED] wrote: On Sat, Jul 12, 2008 at 11:23 PM, bukzor [EMAIL PROTECTED] wrote: I'm connecting to an apache2 process on the same machine, for testing. When looking at netstat, the socket is in the SYN_SENT state, like this: $netstat -a -tcp tcp0 0 *:www *:* LISTEN 7635/apache2 tcp0 1 bukzor:38234adsl-75-61-84-249.d:www SYN_SENT9139/python Anyone know a general reason this might happen? Even better, a way to fix it? That socket connection is to a remote machine, not the same one. Your test code works fine for me. The hang then crash (and I'm assuming crash here means an uncaught exception) just means that your packets are being silently ignored by whatever machine you're actually attempting to connect to. It's possible that your machine has odd DNS settings causing buzkor.hopto.org to resolve to the wrong address. I'm connecting to my machine through the internet, and the resolved URL of my router is what you're seeing above. If you run the code above you'll see what I mean. I did run the code, and as I said, it works fine. Your description of the setup is not consistent. The netstat output unambiguously states that a Python script on buzkor is attempting to open a connection to the HTTP port on the adsl machine (and failing because adsl is not responding). The problem here is not Python; you seem to be confused about which machine is connecting to which. -Miles The problem only manifests about 1 in 20 runs. Below there's code for a client that shows the problem 100% of the time. The two URL's that I seem to be confused about point to the same IP. Maybe this will make it clear: PING bukzor.hopto.org (75.61.84.249) 56(84) bytes of data. 64 bytes from adsl-75-61-84-249.dsl.pltn13.sbcglobal.net (75.61.84.249): icmp_seq=1 ttl=255 time=1.68 ms 64 bytes from adsl-75-61-84-249.dsl.pltn13.sbcglobal.net (75.61.84.249): icmp_seq=2 ttl=255 time=0.493 ms 64 bytes from adsl-75-61-84-249.dsl.pltn13.sbcglobal.net (75.61.84.249): icmp_seq=3 ttl=255 time=0.602 ms Apparently netstat truncated the URL before. Here's the code I mentioned: [code] #!/usr/bin/env python from xmlrpclib import ServerProxy from time import time s = ServerProxy(http://bukzor.hopto.org/modpython/xmlrpc.py;, verbose=True) i = 0 start = time() while True: print s.helloworld() print s.add(1,2) print s.subtract(1,2) i += 3 print AVG: %.2fs % ((time() - start) / i) [/code] Thanks, --Buck -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary bidirectional
On Jul 13, 4:21 pm, Kless [EMAIL PROTECTED] wrote: I need a dictionary where get the result from a 'key' (on left), but also from a 'value' (on right), how to get it? I know that dictionaries aren't bidirectional, but is there any way without use two dictionaries? Thanks in advance! You need to use two dictionaries. Here's a class that someone's written that wraps it up into a single dict-like object for you: http://www.faqts.com/knowledge_base/view.phtml/aid/4376 -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Groups inside Braces with Regular Expressions
On Jul 13, 8:14 pm, MRAB [EMAIL PROTECTED] wrote: On Jul 14, 12:05 am, Chris [EMAIL PROTECTED] wrote: I'm trying to delimit sentences in a block of text by defining the end-of-sentence marker as a period followed by a space followed by an uppercase letter or end-of-string. I'd imagine the regex for that would look something like: [^(?:[A-Z]|$)]\.\s+(?=[A-Z]|$) However, Python keeps giving me an unbalanced parenthesis error for the [^] part. If this isn't valid regex syntax, how else would I match a block of text that doesn't the delimiter pattern? What is the [^(?:[A-Z]|$)] part meant to be doing? Is it meant to be matching everything up to the end of the sentence? [...] is a character class, so Python is parsing the character class as: [^(?:[A-Z]|$)] ^^ It was meant to include everything except the end-of-sentence pattern. However, I just realized that I can simply replace it with .*? -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Groups inside Braces with Regular Expressions
On Jul 14, 9:05 am, Chris [EMAIL PROTECTED] wrote: Misleading subject. [] brackets or square brackets {} braces or curly brackets () parentheses or round brackets I'm trying to delimit sentences in a block of text by defining the end-of-sentence marker as a period followed by a space followed by an uppercase letter or end-of-string. ... which has at least two problems: (1) You are insisting on at least one space between the period and the end-of-string (this can be overcome, see later). (2) Periods are often dropped in after abbreviations and contractions e.g. Mr. Geo. Smith. You will get three sentences out of that. I'd imagine the regex for that would look something like: [^(?:[A-Z]|$)]\.\s+(?=[A-Z]|$) However, Python keeps giving me an unbalanced parenthesis error for the [^] part. It's nice to know that Python is consistent with its error messages. If this isn't valid regex syntax, If? It definitely isn't valid syntax. The brackets should delimit a character class. You are trying to cram a somewhat complicated expression into a character class, or you should be using parentheses. However it's a bit hard to determine what you really meant that part of the pattern to achieve. how else would I match a block of text that doesn't the delimiter pattern? Start from the top down: A sentence is: anything (with some qualifications) followed by (but not including): a period followed by either 1 or more whitespaces then a capital letter or 0 or more whitespaces then end-of-string So something like this might do the trick: sep = re.compile(r'\.(?:\s+(?=[A-Z])|\s*(?=\Z))') sep.split('Hello. Mr. Chris X\nis here.\nIP addr 1.2.3.4. ') ['Hello', 'Mr', 'Chris X\nis here', 'IP addr 1.2.3.4', ''] -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary bidirectional
bukzor: You need to use two dictionaries. Here's a class that someone's written that wraps it up into a single dict-like object for you: http://www.faqts.com/knowledge_base/view.phtml/aid/4376 It contains code like: try: del self.data[item] except KeyError: pass Exceptions are useful in python, but with dictionaries this is probably faster (and shorter), even if it may perform two lookups: if item in self.data: del self.data[item] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: About wmi
On 7月13日, 下午10时26分, Larry Bates [EMAIL PROTECTED] wrote: patrol wrote: I want to prevent some process from running. The code is in the following. I encounter some unexpected troubles. Probelm1: This program cannot terminate scrcons.exe and FNPLicensingService.exe,which are system processes. Problem2:After a while, this program will abort by error File C:\Python25\lib\wmi.py, line 397, in __call__ handle_com_error (error_info) File C:\Python25\lib\wmi.py, line 190, in handle_com_error raise x_wmi, \n.join (exception_string) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 14: ordinal not in range(128) code--- # -*- coding:utf-8 -*- import pythoncom import wmi import threading import time from xml.dom.minidom import parse, parseString class Info (threading.Thread): def __init__ (self): threading.Thread.__init__ (self) def run (self): print 'In Another Thread...' pythoncom.CoInitialize () dom1 = parse('processTerminateList.xml') config_element = dom1.getElementsByTagName(processTerminateList) [0] servers = config_element.getElementsByTagName(processName) try: c = wmi.WMI () for process in c.Win32_Process (): for server in servers: if process.name == getText(server.childNodes): process.Terminate() print process.name process_watcher = c.Win32_Process.watch_for(creation) while True: new_process = process_watcher() name = new_process.Caption print name for server in servers: if name == getText(server.childNodes): new_process.Terminate() finally: pythoncom.CoUninitialize () def getText(nodelist): rc = for node in nodelist: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc if __name__ == '__main__': Info().start() -- processTerminateList.xml ?xml version=1.0 encoding=utf-8? processTerminateList processNamescrcons.exe/processName processNameTXPlatform.exe/processName processNamemdm.exe/processName processNameFNPLicensingService.exe/processName processNamenotepad.exe/processName processNameuedit32.exe/processName /processTerminateList You should probably post this to comp.python.windows. Tim Golden (author of WMI interface) monitors that list religously (thanks Tim). -Larry- 隐藏被引用文字 - - 显示引用的文字 - I cannot find comp.python.windows.What's the URL? -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.connect() hangs in SYN_SENT state.
On Sun, Jul 13, 2008 at 8:35 PM, bukzor [EMAIL PROTECTED] wrote: The problem only manifests about 1 in 20 runs. Below there's code for a client that shows the problem 100% of the time. The two URL's that I seem to be confused about point to the same IP. Maybe this will make it clear: PING bukzor.hopto.org (75.61.84.249) 56(84) bytes of data. 64 bytes from adsl-75-61-84-249.dsl.pltn13.sbcglobal.net (75.61.84.249): icmp_seq=1 ttl=255 time=1.68 ms For me, buzkor.hopto.org resolves to 69.65.19.125, which I hope explains why I thought you were confused, and increases my own suspicion that DNS settings are to blame. I let the script run for about five minutes without it failing. Does your luck change if you use localhost or a numeric IP address in the ServerProxy URL? -Miles -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.connect() hangs in SYN_SENT state.
On Sun, Jul 13, 2008 at 9:31 PM, Miles [EMAIL PROTECTED] wrote: On Sun, Jul 13, 2008 at 8:35 PM, bukzor [EMAIL PROTECTED] wrote: The problem only manifests about 1 in 20 runs. Below there's code for a client that shows the problem 100% of the time. The two URL's that I seem to be confused about point to the same IP. Maybe this will make it clear: PING bukzor.hopto.org (75.61.84.249) 56(84) bytes of data. 64 bytes from adsl-75-61-84-249.dsl.pltn13.sbcglobal.net (75.61.84.249): icmp_seq=1 ttl=255 time=1.68 ms For me, buzkor.hopto.org resolves to 69.65.19.125 Ahhh... bukzor. Well, that makes sense. Pardon my temporary dyslexia. -Miles -- http://mail.python.org/mailman/listinfo/python-list
Re: iterator clone
Well, I think Python's iterators, especially the generators, are beautiful. More importantly, I think there is no general way to make iterators copyable, regardless of the programming language. The problem is that most of the useful ones depend on external state. Peter Hmm, but tee() de facto do it (clone iterator) and ignore side-effects of iterator (external state). And tee() create independent **internal** state of iterator (current position). But **external** state - is headache of programmer. So, iterator/generator have to be method for copy itself (the tee() implementation) or be re- startable. Why not? Concrete problem was to generate iterators (iterator of slices). It was solved with ReIter. --Best regards, --pavel -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary bidirectional
[EMAIL PROTECTED] wrote: bukzor: You need to use two dictionaries. Here's a class that someone's written that wraps it up into a single dict-like object for you: http://www.faqts.com/knowledge_base/view.phtml/aid/4376 It contains code like: try: del self.data[item] except KeyError: pass Exceptions are useful in python, but with dictionaries this is probably faster (and shorter), even if it may perform two lookups: if item in self.data: del self.data[item] Bye, bearophile The only case where it would be faster would be if most of the keys were NOT in the dictionary (rather odd use case). Otherwise I believe you will find the first way quicker as the exceptions are infrequent. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: How to package a logging.config file?
Matthew Wilson wrote: I'm working on a package that uses the standard library logging module along with a .cfg file. In my code, I use logging.config.fileConfig('/home/matt/mypackage/matt.cfg') to load in the logging config file. However, it seems really obvious to me that this won't work when I share this package with others. I can't figure out what path to use when I load my .cfg file. Any ideas? Matt Normally you put the logging configuration file in the path where you put the program that you will be sharing (quite often with no path at all). -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: heapq question
On 13 Lug, 22:35, Miles [EMAIL PROTECTED] wrote: On Sun, Jul 13, 2008 at 3:05 PM, Giampaolo Rodola' [EMAIL PROTECTED] wrote: On 13 Lug, 19:31, Martin v. Löwis [EMAIL PROTECTED] wrote: I understand that heapq is not that efficient to implement timeouts as I thought at first. It would have been perfect if there were functions to remove arbitrary elements withouth needing to re-heapify() the heap every time. It is efficient for that - you just need to use it correctly. To remove the nth element from a heap, replace it with the last element, and then _siftup that element: The time complexity for that operation is O(log(len(heap))). The problem is that in order to remove an arbitrary element from a heap, you usually have to do an O(n) linear search in order to find it first, since you can't know ahead of time which index an arbitrary element is at. (You can, actually, but only if your heap implementation somehow notifies the elements of their new index when it moves them in the heap, which the Python heapq module doesn't do, so you'd have to write your own heap implementation.) And if instead of removing an element I'd want to change its value? E.g.: heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] heapify(heap) heap [0, 2, 1, 4, 5, 6, 7, 8, 9] heap[4] = 12 Don't do that; you must first remove the element and then reinsert it. -Miles That seems to be slower than re-heapifying() the heap. The code I used (which is probably wrong): def reset(self): Reschedule this call resetting the current countdown. assert not self.cancelled, Already cancelled self.timeout = time.time() + self.__delay n = heap.index(self) if n == len(heap) - 1: heap.pop() else: heap[n] = heap.pop() heapq._siftup(heap, n) heapq.heappush(heap, self) Moreover I have the feeling that doing such thing requires a different code whether the new value I use as replacement is lower or higher in comparison to the older one. Am I right? --- Giampaolo http://code.google.com/p/pyftpdlib/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary bidirectional
-- Forwarded message -- From: Akathorn Greyhat [EMAIL PROTECTED] Date: 2008/7/14 Subject: Re: Dictionary bidirectional To: Kless [EMAIL PROTECTED] 2008/7/14 Kless [EMAIL PROTECTED]: I need a dictionary where get the result from a 'key' (on left), but also from a 'value' (on right), how to get it? I know that dictionaries aren't bidirectional, but is there any way without use two dictionaries? Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list You could make your own class for that, maybe something like # class MyCoolDictionary(dict): def __init__(self, *args, **kargs): dict.__init__(self, *args, **kargs) def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: keys=[] for i in dictio.keys(): if dictio[i]==item: keys.append(i) return keys dictio=MyCoolDictionary({a : 1, b : 2, c : 2}) print dictio[a] print dictio[b] print dictio[1] print dictio[2] # The output of this code is: 1 2 ['a'] ['c', 'b'] Note that it isn't finish, maybe you'll need to make some kind of test before adding a new value because with this code one value can have multiple keys, and I have fixed it by returning a list of keys instead a single value. It's up to you =) I'm sorry of my poor english =( Regards, Akathorn Greyhat -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.connect() hangs in SYN_SENT state.
On Sat, Jul 12, 2008 at 11:23 PM, bukzor [EMAIL PROTECTED] wrote: Anyone know a general reason this might happen? Even better, a way to fix it? Another reason that a socket can hang in the SYN_SENT state (besides trying to connect to an unreachable host without getting an ICMP destination-unreachable message in response): if the server's listen queue is full, it will silently ignore SYN packets until there is room in the queue. Sorry again about the bukzor vs. buzkor thing. I don't know what's causing your problem (and it's probably not a DNS issue after all) but it's more likely to be a server issue than a client one. Maybe your client has an unusually low socket timeout for some reason, though; does increasing it (with socket.setdefaulttimeout) help? Mine seems to default to about 75 seconds. If you can't work out the root cause, but it only happens every once in a while, you could try changing your client code to catch the socket exception and retry a limited number of times. -Miles -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.connect() hangs in SYN_SENT state.
On Sun, Jul 13, 2008 at 10:29 PM, Miles [EMAIL PROTECTED] wrote: On Sat, Jul 12, 2008 at 11:23 PM, bukzor [EMAIL PROTECTED] wrote: Anyone know a general reason this might happen? Even better, a way to fix it? Maybe your client has an unusually low socket timeout for some reason, though; does increasing it (with socket.setdefaulttimeout) help? Never mind on that, as you already said that it hangs for about two minutes. Clearly my reading comprehension and retention rate are at an all-time low today. low-signal-to-noise-ratio-ly yours, Miles -- http://mail.python.org/mailman/listinfo/python-list