Re: Evil, evil wxPython (and a glimmer of hope)
[EMAIL PROTECTED] wrote: I rarely do GUIs, and reminded myself today why that is the case (simply, it's not fun). I implemented a simple TreeCtrl, and had to implement my own 'children' method, of all things! Here it is: def children(self,node): c = [] nc,cookie = self.GetFirstChild(node) while 1: info = self.GetItemText(nc) c.append((info,nc)) nc, cookie= self.GetNextChild(node,cookie) if not nc.IsOk(): break return c And it even fails with zero children. This is as unpythonic as it gets. However, it should be pretty easy to write small wrapper over the wxPython api. I'm thinking of wrapping or injecting additional methods to TreeCtrl that start with lowercase letters and return something sensible, with reasonable methods. Something like: root = self.AddRoot(root dir) # root is normal wx TreeCtrl root tree = EasyWx(root) # now tree is our wrapped, more fun root for c in tree.children(): print c.name # etc. etc. This is a bit like Brian Orendorff's path module that turns something low level to something you can use easily, without throwing you into a world of frameworks, toolkits and whatnot. I can see there are things like Wax or PythonCard, but they are still too frameworky, and you don't use them to extend wxPython, you use *them* and they use wxPython. I'd basically like to rely on something that is there for the long haul (plain wxPython API) but only use convenience wrappers *on my own initiative*, as it seems convenient. Just like I'd use the path module. wxPython is great as it is (a simple wrapper for a C++ toolkit) and the basic design is ok proven, I'm just too lazy to use it in its current form. Take a look at dabo, II think they're doing exactly what you're describing. http://blog.dabodev.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a better way?
[EMAIL PROTECTED] wrote: Problem: You have a list of unknown length, such as this: list = [X,X,X,O,O,O,O]. You want to extract all and only the X's. You know the X's are all up front and you know that the item after the last X is an O, or that the list ends with an X. There are never O's between X's. I have been using something like this: _ while list[0] != O: storage.append(list[0]) list.pop(0) if len(list) == 0: break _ But this seems ugly to me, and using while give me the heebies. Is there a better approach? hope this is clear. thanks There's a few ways to do this, really depends on : mylist = [1,2,3,4,5,6,0,0,0] list comprehension (will get ALL non zeros, and strip out all zeros, but is different from your function): [x for x in mylist if x != 0] list slice(same as your function): mylist[:mylist.index(0)] Depends what you want to happen if your list is something like: [1,2,3,0,4,5,6,0,0] [0,1,2,3,4,5,6] [0,1,2,3,4,5,6,0] [1,2,3,4,5,6] -- http://mail.python.org/mailman/listinfo/python-list
Re: Too Many if Statements?
slogging_away wrote: Hi - I'm running Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32, and have a script that makes numerous checks on text files, (configuration files), so discrepancies can be reported. The script works fine but it appears that I may have hit a wall with 'if' statements. Due to the number of checks perfromed by the script on the text files, (over 500), there are quite a few 'if' statements in the script, (over 1150). It seems that it is at the point that when I add any additional 'if' statements the script will not run. No error is produced - it just returns to the python prompt much the same as when a successful 'Check Module' command is selected. If I delete some other 'if' statements the new ones work so it appears that it has hit a limit on the number of 'if' statements. This has stunted any further checks for the script to make on the text files. Hs anyone ever run into this sort of thing? I can't say I've run into it before but your description makes me think there are other approaches you could take. Does splitting the large number of if statements into separate functions help at all? If you're checking some text to see if a number of static strings are contained therein, you could put the test strings into a list and loop through...something like this (untested): tests = [ 'looking for this string', 'and this one', 'am i in the text' ] # etc... for test in tests: if test not in text: raise LookupError -- http://mail.python.org/mailman/listinfo/python-list
Re: Code Feedback
I believe the while 1: pass is there to keep the main thread alive until all the readers are done. If you want the program to end after the readers are done you can append them all to a list then iterate through and wait for the threads to join() if __name__==__main__: library = Library() readers = input(Number of Readers?) readerlist = [] for i in range(1,readers): newReader = Reader(library, Reader + str (i), random.randint(1,7), random.randint(1,7)) newReader.start() readerlist.append(newReader) for reader in readerlist: reader.join() -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing numbers into characters using dictionaries
Ok there's a couple things going on here. t = text.split('@') // splits the digits/blocks apart from each other this will give you a list: ['', '7706', '7002', '7075', '7704'] You may want to change the line to skip the first empty value: t = text.split('@')[1:] Next your loop. something = 1 while True: var = str(a[t[something]]) print var, // I want it to change @[EMAIL PROTECTED]@[EMAIL PROTECTED] into lawl I think what you want to do here is loop through your list t, take the values out of the encrypted text and lookup that value in a. In python, you can loop through a list like this: for encrypted_char in t: var = a[encrypted_char] print var, now instead of printing each char as you decrypt it you should collect them first and do the print at the end. So you get: temp_list = [] for encrypted_char in t: var = a[encrypted_char] temp_list.append(var) print ''.join(temp_list) This still won't help with the key error you're getting though, but you can catch that error by surrounding your offending line with a try/except block: temp_list = [] for encrypted_char in t: try: var = a[encrypted_char] temp_list.append(var) except KeyError: print encrypted_char, not in, a temp_list.append('?') print ''.join(temp_list) So your final script looks like this: text = '@[EMAIL PROTECTED]@[EMAIL PROTECTED]' # some text num = '213654' # Number s1 = '700' s2 = '770' s4 = '707' # it adds these later on. # splits the digits/blocks apart from each other t = text.split('@')[1:] a = {s2+num[3]:l, s1+num[0]:a, s4+num[5]:w} temp_list = [] for encrypted_char in t: try: var = a[encrypted_char] temp_list.append(var) except KeyError: print encrypted_char, not in, a temp_list.append('?') print ''.join(temp_list) Fixing either your initial text or your a dict depends on your requirements. -- http://mail.python.org/mailman/listinfo/python-list
Re: forced spaces when inserting a variable between strings
You can use: print img src=%s.jpg % (number) or print img src=+str(number)+.jpg or a number of others, but for short strings one of these two generally work fine. -- http://mail.python.org/mailman/listinfo/python-list
Re: MVC in wxPython HELP!
See this recent explanation by has: http://groups.google.ca/group/comp.lang.python/msg/f8990a2c666a793c?hl=en; (The rest of the thread may lead you to more concrete examples as well.) -- http://mail.python.org/mailman/listinfo/python-list
Re: strange behaviour when writing a large amount of data on stdout
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 No problems on Windows 2000 Pro with 512MB of RAM -- http://mail.python.org/mailman/listinfo/python-list
Re: asyncore question
Not 100% sure why print d gives None but if you need to print something that represents the instance, use repr d.__str__ method-wrapper object at 0x0098C450 str(d) 'None' repr(d) 'asyncore.dispatcher at 0x8d5be8' print repr(d) asyncore.dispatcher at 0x8d5be8 Why isn't __str__ in dir? dir(d) ['__doc__', '__getattr__', '__init__', '__module__', '__repr__', '_map', 'accept ', 'accepting', 'add_channel', 'addr', 'bind', 'close', 'closing', 'connect', 'c onnected', 'create_socket', 'debug', 'del_channel', 'handle_accept', 'handle_clo se', 'handle_connect', 'handle_error', 'handle_expt', 'handle_expt_event', 'hand le_read', 'handle_read_event', 'handle_write', 'handle_write_event', 'listen', ' log', 'log_info', 'readable', 'recv', 'send', 'set_reuse_addr', 'set_socket', 's ocket', 'writable'] -- http://mail.python.org/mailman/listinfo/python-list
Re: Cursor Position.
This script should be a good start: from ctypes import * import time PUL = POINTER(c_ulong) class KeyBdInput(Structure): _fields_ = [(wVk, c_ushort), (wScan, c_ushort), (dwFlags, c_ulong), (time, c_ulong), (dwExtraInfo, PUL)] class HardwareInput(Structure): _fields_ = [(uMsg, c_ulong), (wParamL, c_short), (wParamH, c_ushort)] class MouseInput(Structure): _fields_ = [(dx, c_long), (dy, c_long), (mouseData, c_ulong), (dwFlags, c_ulong), (time,c_ulong), (dwExtraInfo, PUL)] class Input_I(Union): _fields_ = [(ki, KeyBdInput), (mi, MouseInput), (hi, HardwareInput)] class Input(Structure): _fields_ = [(type, c_ulong), (ii, Input_I)] class POINT(Structure): _fields_ = [(x, c_ulong), (y, c_ulong)] def Click(x,y): orig = POINT() windll.user32.GetCursorPos(byref(orig)) windll.user32.SetCursorPos(x,y) FInputs = Input * 2 extra = c_ulong(0) ii_ = Input_I() ii_.mi = MouseInput( 0, 0, 0, 2, 0, pointer(extra) ) ii2_ = Input_I() ii2_.mi = MouseInput( 0, 0, 0, 4, 0, pointer(extra) ) x = FInputs( ( 0, ii_ ), ( 0, ii2_ ) ) windll.user32.SendInput(2, pointer(x), sizeof(x[0])) return orig.x, orig.y -- http://mail.python.org/mailman/listinfo/python-list
Re: Hash map with multiple keys per value ?
Are you looking for this type of thing? class Test: value = 900 t = Test() d['1'] = t d['2'] = t d['3'] = t d['3'].value = 800 d['1'].value -- http://mail.python.org/mailman/listinfo/python-list
Re: Function to execute only once
I've been seeing alot about decorators and closures lately and my initial thought was that this would be a good place to use them instead of wrapping it around a class. That was my initial thought :) What I came up with was this: def execute_once(fn): result = None def executor(*args, **kwargs): if not result: result = fn(*args, **kwargs) return result return executor @execute_once def execute(tmp): tmp = tmp+1 return tmp def func1(tmp): execute(tmp) def func2(tmp): execute(tmp) tmp=0 print 'init tmp:', tmp func1(tmp) print 'ran func1 tmp:', tmp func2(tmp) print 'ran func2 tmp:', tmp It gives the following error: init tmp: 0 Traceback (most recent call last): File C:\Download\test.py, line 26, in ? func1(tmp) File C:\Download\test.py, line 19, in func1 execute(tmp) File C:\Download\test.py, line 5, in executor if not result: UnboundLocalError: local variable 'result' referenced before assignment Makes sense to me, except I expected some closure 'magic'. I thought that when I wrapped executor() inside execute_once() the name result would be available to executor(). What am I missing here (I expect the answer to be 'alot') but is this type of solution valid for this problem? -- http://mail.python.org/mailman/listinfo/python-list
Re: Function to execute only once
The problem seemed to be because I was rebinding result inside executor. Can someone explain why it works below but not in the first one? Also why is it if I set tmp as a global and don't pass it as a paremeter to the various functions as per the OP that I get an UnboundLocalError: local variable 'tmp' referenced before assignment? def execute_once(fn): print in execute_once result = {} def executor(*args, **kwargs): if fn not in result: result[fn] = fn(*args, **kwargs) return result[fn] return executor @execute_once def execute(tmp): print in execute tmp = tmp+1 return tmp def func1(tmp): return execute(tmp) def func2(tmp): return execute(tmp) tmp = 0 print 'init tmp:', tmp tmp = func1(tmp) print 'ran func1 tmp:', tmp tmp = func2(tmp) print 'ran func2 tmp:', tmp tmp = func1(tmp) print 'ran func1 tmp:', tmp OUTPUT: in execute_once init tmp: 0 in execute ran func1 tmp: 1 ran func2 tmp: 1 ran func1 tmp: 1 -- http://mail.python.org/mailman/listinfo/python-list
Wrapping a class set method
Hi there, I have the following simplified classes: class Project: def __init__(self,pname): self.devices = {} # Dictionary of Device objects self.pname = pname def setpname(self,pname): self.pname = pname def adddevice(self,dname): self.devices[dname] = Device(self,dname) class Device: def __init__(self,parent,dname): self.parent = parent self.dname = dname def setdname(self,dname): self.dname = dname Now, what I would like to do is wrap all of the set/add methods in a function that pickles the Project object. I would then save the pickled objects and use them to undo any changes to the above data structures. I have a suspicion that there's an easier way to do this than explicitly adding a Project.pickleme() call to the beginning of all of my set/add methods. So is there a way to wrap methods for this type of functionality or is there another way of doing this, maybe without using setter methods? -- http://mail.python.org/mailman/listinfo/python-list
Re: Mouseclick
I did this a little while ago, there's some setup stuff in here for sending keyboard commands as well. Coercing the structs into python was the hardest part. Basically Click(x,y) moves the mouse to the specified spot on the screen (not window) sends a mouse down followed by mouse up event then returns to your original position. Sorry for lack of comments. from ctypes import * import time PUL = POINTER(c_ulong) class KeyBdInput(Structure): _fields_ = [(wVk, c_ushort), (wScan, c_ushort), (dwFlags, c_ulong), (time, c_ulong), (dwExtraInfo, PUL)] class HardwareInput(Structure): _fields_ = [(uMsg, c_ulong), (wParamL, c_short), (wParamH, c_ushort)] class MouseInput(Structure): _fields_ = [(dx, c_long), (dy, c_long), (mouseData, c_ulong), (dwFlags, c_ulong), (time,c_ulong), (dwExtraInfo, PUL)] class Input_I(Union): _fields_ = [(ki, KeyBdInput), (mi, MouseInput), (hi, HardwareInput)] class Input(Structure): _fields_ = [(type, c_ulong), (ii, Input_I)] class POINT(Structure): _fields_ = [(x, c_ulong), (y, c_ulong)] def Click(x,y): orig = POINT() windll.user32.GetCursorPos(byref(orig)) windll.user32.SetCursorPos(x,y) FInputs = Input * 2 extra = c_ulong(0) ii_ = Input_I() ii_.mi = MouseInput( 0, 0, 0, 2, 0, pointer(extra) ) ii2_ = Input_I() ii2_.mi = MouseInput( 0, 0, 0, 4, 0, pointer(extra) ) x = FInputs( ( 0, ii_ ), ( 0, ii2_ ) ) windll.user32.SendInput(2, pointer(x), sizeof(x[0])) return orig.x, orig.y -- http://mail.python.org/mailman/listinfo/python-list
Re: Help Optimizing Word Search
With a list of letters: 'ABAE?S?' your implementation ran 3.5 times faster than the one from http://blog.vrplumber.com/427 (in 0.437 seconds vs 1.515) Without wildcards yours runs slightly quicker as well. I guess with the wildcards, using an re as a quick filter against each word, versus the translate method is much faster. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help Optimizing Word Search
First of all thank you very much for the reply. I hope I'm not too verbose here, just hope that if someone else runs into a similar problem they can find an answer here. This appears to be a Computer Science 101 Data Structures and Algorithms question, not a Python question, but here's an answer anyway Heh, it's been awhile since I took data structures 101 but I asked here after reading about python generators, and although I can't quite get my head around them, I have a sense that they could help me check all mutations (is this the right word?) of the candidate strings. Thanks for the ideas on finding matches, I will have to try the bit filter out to see if its faster. The trie works similar to this in that it will return a 3 if the substring is not in the dictionary so that you don't have to check any superset of the mutation. Although to clarify, the reason I posted was mostly for help on my weak wildcard algorithm. If aa is in your dictionary, what queries would retrieve it? Any query that contains either a and a or a and ? or ? and ?. So some examples would be: aa, a?, aba, baa, bbbaba, b?b?, bab?, ?ab etc... Searching with wild cards: your example of query == ?? seems to yield all two-letter words. I'd like to see what you expect for a?, ?a, ab?, and aa? before suggesting how to tackle wild cards. Reverse-engineering requirements out of other folks' code is not something I do for fun :-) My apologies, in my haste my example of what query == ?? yields was unclear. Every list of candidate letters should yield every unique (if possible) mutation, of length 1 to len(candidate). Heh, exactly what each of those strings would yield is pretty much the root of my problem: ?? yields (the order of the results dont matter): a, b, c, d, e, f, ..., x, y, z, aa, ab, ac, ..., ax, ay, az, ba, bb, bc, ..., ya, yb, yc, ..., yx, yy, yz, za, zb, zc, ..., zx, zy, zz a? yields a, b, c, d, ..., x, y, z, aa, ab, ac, ..., ax, ay, az, ba, ca, da, ..., xa, ya, za ?a yields same as a? ab? yields a, b, c, d, ..., x, y, z, aa, ab, ac, ..., ax, ay, az, ba, bb, bc, ..., bx, by, bz, ca, cb, da, db, ea, eb, ..., xa, xb, ya, yb, za, zb, aba, abb, abc, abd, ..., abx, aby, abz, baa, bab, bac, ..., bax, bay, baz, aab, acb, adb, ..., axb, ayb, azb, bba, bca, bda, ... bxa, bya, bza, cba, dba, eba, xba, yba, zba HTH, basically every possible string out of the given pool of up to 10 letters. Ok writing these out just gave me an idea on how I could try and write this another way. Ok done. Wow, this program actually ran much much slower than my original 135 seconds vs 9 seconds!! I'm not sure if I made a huge mistake or if it's because in the original I can stop searching superset-candidates if the candidate is not a substring of a dictionary word (in the same way the mask would reject impossible mutations). This produces the correct mutations however (although not unique as I wrote out above): -- begin code -- !def getmutations(pool): ! !for i, letter in enumerate(pool): !pool2 = pool[:] !pool2.pop(i) ! !for mutation in getmutations(pool2): !if letter != '?': !yield letter + mutation !else: !for c in alpha: !yield c + mutation ! !yield !letters = list('abae?s?') !s = time.time() !output = open('words.log','w') !for candidate in getmutations(letters): !# Check if word is valid !result = mytrie.query(candidate) ! !# Found a word, add it to the database !if result == 1: !words[candidate] = 1 ! !print time.time() - s --- end code --- -- http://mail.python.org/mailman/listinfo/python-list
Re: Help Optimizing Word Search
Mike, Thanks, this worked great, and was 4x faster than my method! Thanks everyone for replying! The changes I made were: !rest = ''.join([chr(i) for i in range(256) if chr(i).upper() not in WORD]) !# a wildcard in the word means that we check all letters !if '?' in WORD: !rest = '' !translator = string.maketrans('','') and !try: !pool.remove( char ) !except ValueError: !# nested try to remove possible wildcard !try: !pool.remove( '?' ) !except ValueError: !return False -- http://mail.python.org/mailman/listinfo/python-list