[OT] a little about regex
*** Your mail has been scanned by InterScan MSS. *** Hello, I'm trying to get working an assertion which filter address from some domain but if it's prefixed by '.com'. Even trying to put the result in a negate test I can't get the wanted result. The tought in program term : >>> def filter(adr): ... import re ... allow = re.compile('.*\.my(>|$)') ... deny = re.compile('.*\.com\.my(>|$)') ... cnt = 0 ... if deny.search(adr): cnt += 1 ... if allow.search(adr): cnt += 1 ... return cnt ... >>> filter('[EMAIL PROTECTED]') 2 >>> filter('[EMAIL PROTECTED]') 1 >>> Seem that I miss some better regex implementation to avoid that both of the filters taking action. I'm thinking of lookbehind (negative or positive) option, but I think I couldn't realize it yet. I think the compilation should either allow have no '.com' before '.my' or deny should have _only_ '.com' before '.my'. Sorry I don't get the correct sintax to do it. Suggestions are welcome. F -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexable Collating (feedback please)
Fixed... Changed the collate() function to return None the same as sort() since it is an in place collate. A comment in _test() doctests was reversed. CAPS_FIRST option puts words beginning with capitals before, not after, words beginning with lower case of the same letter. It seems I always find a few obvious glitches right after I post something. ;-) Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] a little about regex
Fulvio wrote: > ... if deny.search(adr): cnt += 1 > ... if allow.search(adr): cnt += 1 hint: under what circumstances are "cnt" decremented in the above snippet? -- http://mail.python.org/mailman/listinfo/python-list
RE: Where to find pydoc?
Hi, Can you be specific on which URLs can I find "python-tools". Cause I tried the one under easy_install, I still can't find it. Thanks and hope to hear from you again. -- Edward WIJAYA SINGAPORE From: [EMAIL PROTECTED] on behalf of Fredrik Lundh Sent: Mon 10/16/2006 5:08 PM To: python-list@python.org Subject: Re: Where to find pydoc? look for "python-tools" or a similar package in your favourite package repository. -- http://mail.python.org/mailman/listinfo/python-list Institute For Infocomm Research - Disclaimer - This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
How to convert this list to string?
Hi all I have a list like: >>> list [1, 2, 3] >>> list[1:] [2, 3] I want to get a string "2 3" >>> str(list[1:]) '[2, 3]' How can I do that ? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert this list to string?
On 18 Oct 2006 00:20:50 -0700, Jia Lu <[EMAIL PROTECTED]> wrote: > I want to get a string "2 3" > > >>> str(list[1:]) > '[2, 3]' > > How can I do that ? ' '.join(str(i) for i in list[1:]) -- Theerasak -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert this list to string?
Jia Lu wrote: > Hi all > > I have a list like: > list > [1, 2, 3] list[1:] > [2, 3] > > I want to get a string "2 3" > str(list[1:]) > '[2, 3]' > > How can I do that ? > " ".join(str(x) for x in list) -Travis -- http://mail.python.org/mailman/listinfo/python-list
Re: stdout not flushed before os.execvp()
On Wednesday 18 October 2006 00:25, Fredrik Lundh wrote: > |feature. the "exec" system call operates on a lower level than the > |stdio buffering system. I did in this manner: for exe in ('imap4', 'pop3'): if exe in cfgfil[optsrv + '.protocol']: exe = exe[:4]; exe = 'call_func = _call_' + exe.upper() \ + '(setting)' try: exec exe except ProtocolError: call_func = '#ERROR 02 = Protocol failed with %s' %optsrv break exists it a different way to do it? F -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Lee Harr wrote: > I understand how to create a property like this: > > class RC(object): > def _set_pwm(self, v): > self._pwm01 = v % 256 > def _get_pwm(self): > return self._pwm01 > pwm01 = property(_get_pwm, _set_pwm) > > > But what if I have a whole bunch of these pwm properties? > > I made this: > > class RC(object): > def _makeprop(name): > prop = '_%s' % name > def _set(self, v): > v_new = v % 256 > setattr(self, prop, v_new) > def _get(self): > return getattr(self, prop) > return property(_get, _set) > > pwm01 = _makeprop('pwm01') > pwm02 = _makeprop('pwm02') > > > Not too bad, except for having to repeat the name. > > I would like to just have a list of pwm names and > have them all set up like that. It would be nice if > each one was set to a default value of 127 also > > Any thoughts? The metaclass solution. I use this idiom occasionally, whenever I want to fiddle with the class dict before letting the type constructor at it. class mod256metatype(type): def __new__(metatype,name,bases,clsdict): for sym in clsdict.get('__mod256__',()): prop = '_%s' % sym def _set(self,v): setattr(self,prop,v%256) def _get(self): return getattr(self,prop) clsdict[sym] = property(_get,_set) return type.__new__(metatype,name,bases,clsdict) class RC(object): __metaclass__ = mod256metatype __mod256__ = ["pwm01","pwm02"] Carl -- http://mail.python.org/mailman/listinfo/python-list
Re: Where to find pydoc?
Wijaya Edward wrote: > Can you be specific on which URLs can I find "python-tools". > Cause I tried the one under easy_install, I still can't find it. it's an RPM. you should be able to get it from where you get other RedHat packages. -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] a little about regex
Fulvio wrote: > *** > Your mail has been scanned by InterScan MSS. > *** > > > Hello, > > I'm trying to get working an assertion which filter address from some domain > but if it's prefixed by '.com'. > Even trying to put the result in a negate test I can't get the wanted result. > > The tought in program term : > def filter(adr): > ... import re > ... allow = re.compile('.*\.my(>|$)') > ... deny = re.compile('.*\.com\.my(>|$)') > ... cnt = 0 > ... if deny.search(adr): cnt += 1 > ... if allow.search(adr): cnt += 1 > ... return cnt > ... filter('[EMAIL PROTECTED]') > 2 filter('[EMAIL PROTECTED]') > 1 > > Seem that I miss some better regex implementation to avoid that both of the > filters taking action. I'm thinking of lookbehind (negative or positive) > option, but I think I couldn't realize it yet. > I think the compilation should either allow have no '.com' before '.my' or > deny should have _only_ '.com' before '.my'. Sorry I don't get the correct > sintax to do it. > > Suggestions are welcome. > > F Instead of using two separate if's, Use an if - elif and be sure to test the narrower filter first. (You have them in the correct order) That way it will skip the more general filter and not increment cnt twice. It's not exactly clear on what output you are seeking. If you want 0 for not filtered and 1 for filtered, then look to Freds Hint. Or are you writing a test at the moment, a 1 means it only passed one filter so you know your filters are working as designed? Another approach would be to assign values for filtered, accepted, and undefined and set those accordingly instead of incrementing and decrementing a counter. Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert this list to string?
Jia Lu wrote: > Hi all > > I have a list like: > list > [1, 2, 3] list[1:] > [2, 3] > > I want to get a string "2 3" > str(list[1:]) > '[2, 3]' > > How can I do that ? http://effbot.org/zone/python-list.htm#printing -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for assignement operator
Could the "traits" package be of help? http://code.enthought.com/traits/ Alexander Eisenhuth wrote: > Hello, > > is there a assignement operator, that i can overwrite? > > class MyInt: > def __init__(self, val): > assert(isinstance(val, int)) > self._val = val > > a = MyInt(10) > > # Here i need to overwrite the assignement operator > a = 12 > > > Thanks > Alexander -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Michele Simionato wrote: > Lee Harr wrote: > > I understand how to create a property like this: > > > > class RC(object): > > def _set_pwm(self, v): > > self._pwm01 = v % 256 > > def _get_pwm(self): > > return self._pwm01 > > pwm01 = property(_get_pwm, _set_pwm) > > > > > > But what if I have a whole bunch of these pwm properties? > > > > I made this: > > > > class RC(object): > > def _makeprop(name): > > prop = '_%s' % name > > def _set(self, v): > > v_new = v % 256 > > setattr(self, prop, v_new) > > def _get(self): > > return getattr(self, prop) > > return property(_get, _set) > > > > pwm01 = _makeprop('pwm01') > > pwm02 = _makeprop('pwm02') > > > > > > Not too bad, except for having to repeat the name. > > > > I would like to just have a list of pwm names and > > have them all set up like that. It would be nice if > > each one was set to a default value of 127 also > > > > Any thoughts? > > > > Yes, what about this? > > import sys > > def defprop(name, default=127): > loc = sys._getframe(1).f_locals > prop = '_%s' % name > def _set(self, v): > v_new = v % 256 > setattr(self, prop, v_new) > def _get(self): > return getattr(self, prop, default) > loc[name] = property(_get, _set) > > class RC(object): > defprop('pwm01') > defprop('pwm02') > > rc = RC() > > print rc.pwm01 # 127 > print rc.pwm02 # 127 > rc.pwm02 = 1312 > print rc.pwm02 # 32 > > This is a bit hackish, but I would prefer this over a metaclass > solution. since it does not add > any hidden magic to your class. Why is this less hidden or magical than a metaclass ? I'd prefer the following instead: from itertools import chain, izip, repeat def ByteProperties(*names, **defaulted_names): def byte_property(name, default): return property(lambda self: getattr(self, name, default), lambda self,v: setattr(self, name, v%256)) def make_class(clsname, bases, dict): for name,default in chain(izip(names, repeat(127)), defaulted_names.iteritems()): assert name not in dict # sanity check dict[name] = byte_property('_'+name, default) return type(clsname,bases,dict) return make_class class RC(object): __metaclass__ = ByteProperties('pwm01', pwm02=64) rc = RC() print rc.pwm01, rc.pwm02 # 127 64 rc.pwm01 = 1312 print rc.pwm01, rc.pwm02 # 32 64 George -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Carl Banks wrote: > Lee Harr wrote: > > I understand how to create a property like this: > > > > class RC(object): > > def _set_pwm(self, v): > > self._pwm01 = v % 256 > > def _get_pwm(self): > > return self._pwm01 > > pwm01 = property(_get_pwm, _set_pwm) > > > > > > But what if I have a whole bunch of these pwm properties? > > > > I made this: > > > > class RC(object): > > def _makeprop(name): > > prop = '_%s' % name > > def _set(self, v): > > v_new = v % 256 > > setattr(self, prop, v_new) > > def _get(self): > > return getattr(self, prop) > > return property(_get, _set) > > > > pwm01 = _makeprop('pwm01') > > pwm02 = _makeprop('pwm02') > > > > > > Not too bad, except for having to repeat the name. > > > > I would like to just have a list of pwm names and > > have them all set up like that. It would be nice if > > each one was set to a default value of 127 also > > > > Any thoughts? > > > The metaclass solution. I use this idiom occasionally, whenever I want > to fiddle with the class dict before letting the type constructor at > it. > > class mod256metatype(type): > def __new__(metatype,name,bases,clsdict): > for sym in clsdict.get('__mod256__',()): > prop = '_%s' % sym > def _set(self,v): > setattr(self,prop,v%256) > def _get(self): > return getattr(self,prop) > clsdict[sym] = property(_get,_set) > return type.__new__(metatype,name,bases,clsdict) > > class RC(object): > __metaclass__ = mod256metatype > __mod256__ = ["pwm01","pwm02"] There's a subtle common bug here: all _get and _set closures will refer to the last property only. You have to remember to write "def _set(self,v,prop=prop)" and similarly for _get to do the right thing. By the way, I can't think of a case where the current behavior (i.e. binding the last value only) is the desired one. Is this just an implementation wart or am I missing something ? George -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert this list to string?
Jia Lu wrote: > Hi all > > I have a list like: > list > [1, 2, 3] list[1:] > [2, 3] > > I want to get a string "2 3" > str(list[1:]) > '[2, 3]' > > How can I do that ? > > thanks Just to be different from the other suggestions... >>> a = [1, 2, 3] >>> str(a[1:]).strip('[]').replace(',', '') '2 3' By the way. It's a good idea to try not to use 'list' or other built-in names for your own objects. Best to start with good habits so that you avoid odd hard to find bugs later. Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: python's OOP question
Bruno Desthuilliers wrote: > neoedmund wrote: > (snip) > > So I can reuse a method freely only if it's worth reusing. > > For the word "inheritance", in some aspect, meanings reuse the super > > class, with the condition: must reuse everything from super class. > > Not really. In fact, inheritance *is* a special case of > composition/delegation. A 'child' class is a class that has references > to other classes - it's 'parents' -, and then attributes that are not > found in the instance or child class are looked up in the parents > (according to mro rules in case of multiple inheritance). And that's all > there is. > > > It's lack of a option to select which methods are to be reused. > > Methods not redefined in the 'child' class or it's instance are > 'reusable'. Now they are only effectively 'reused' if and when called by > client code. So the 'option to select which methods are to be reused' is > mostly up to both the 'child' class and code using it. > > > this is something should be improved for general OOP i think. > > So to answer " What is your problem with having the other extra methods > > too ?", > > in real life, a class is not defined so well that any method is needed > > by sub-class. > > Then perhaps is it time to refactor. A class should be a highly cohesive > unit. If you find yourself needing only a specific subset of a class, it > may be time to extract this subset in it's own class. Given Python's > support for both multiple inheritance and composition/delegation, it's > usually a trivial task (unless you already mixed up too many orthogonal > concerns in your base class...). > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in '[EMAIL PROTECTED]'.split('@')])" ivestgating the web, i found something similiar with my approch: http://en.wikipedia.org/wiki/Duck_typing "Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs hasattr() tests" -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
George Sakkis wrote: > > Why is this less hidden or magical than a metaclass ? Because it does not use inheritance. It is not going to create properties on subclasses without you noticing it. Also, metaclasses are brittle: try to use them with __slots__, or with non-standard classes (i.e. extensions classes), or try to use multiple metaclasses. I wrote a paper about metaclasses abuses which should be published soon or later; you can see the draft here: http://www.phyast.pitt.edu/~micheles/python/classinitializer.html Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: python's OOP question
neoedmund wrote: > ivestgating the web, i found something similiar with my approch: > http://en.wikipedia.org/wiki/Duck_typing > "Duck-typing avoids tests using type() or isinstance(). Instead, it > typically employs hasattr() tests" that's not entirely correct, though: in Python, duck-typing typically uses "Easier to Ask Forgiveness than Permission" (EAFP), aka "Just Do It", rather than "Look Before You Leap" (LBYL). -- http://mail.python.org/mailman/listinfo/python-list
Re: python's OOP question
Bruno Desthuilliers wrote: > neoedmund wrote: > (snip) > > So I can reuse a method freely only if it's worth reusing. > > For the word "inheritance", in some aspect, meanings reuse the super > > class, with the condition: must reuse everything from super class. > > Not really. In fact, inheritance *is* a special case of > composition/delegation. A 'child' class is a class that has references > to other classes - it's 'parents' -, and then attributes that are not > found in the instance or child class are looked up in the parents > (according to mro rules in case of multiple inheritance). And that's all > there is. > > > It's lack of a option to select which methods are to be reused. > > Methods not redefined in the 'child' class or it's instance are > 'reusable'. Now they are only effectively 'reused' if and when called by > client code. So the 'option to select which methods are to be reused' is > mostly up to both the 'child' class and code using it. > > > this is something should be improved for general OOP i think. > > So to answer " What is your problem with having the other extra methods > > too ?", > > in real life, a class is not defined so well that any method is needed > > by sub-class. > > Then perhaps is it time to refactor. A class should be a highly cohesive > unit. If you find yourself needing only a specific subset of a class, it > may be time to extract this subset in it's own class. Given Python's > support for both multiple inheritance and composition/delegation, it's > usually a trivial task (unless you already mixed up too many orthogonal > concerns in your base class...). > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in '[EMAIL PROTECTED]'.split('@')])" I donnot agree with your "it's time to refactory" very much, man has probly never has time to do such things. suppose a system is working soundly, you maybe has no time or motivation to do refactory instead of having a vocation to a island. it's easy to say, at lease myself has not the experience to do such things, :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
George Sakkis wrote: > > from itertools import chain, izip, repeat > > def ByteProperties(*names, **defaulted_names): > def byte_property(name, default): > return property(lambda self: getattr(self, name, default), > lambda self,v: setattr(self, name, v%256)) > def make_class(clsname, bases, dict): > for name,default in chain(izip(names, repeat(127)), > defaulted_names.iteritems()): > assert name not in dict # sanity check > dict[name] = byte_property('_'+name, default) > return type(clsname,bases,dict) > return make_class > > > class RC(object): > __metaclass__ = ByteProperties('pwm01', pwm02=64) Notice that you are NOT using a custom metaclass here, you are just using the metaclass hook and you will avoid all issues of custom metaclasses. This is exactly the approach I advocate in the paper I referred before, so I think your solution is pretty safe in that respect. Still I think in this particular problem avoiding the __metaclass__ at all is possible and it should be preferred, just for sake of simplicity, not of safety). Michele Simionato M -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
George Sakkis wrote: > Michele Simionato wrote: > > import sys > > > > def defprop(name, default=127): > > loc = sys._getframe(1).f_locals > > prop = '_%s' % name > > def _set(self, v): > > v_new = v % 256 > > setattr(self, prop, v_new) > > def _get(self): > > return getattr(self, prop, default) > > loc[name] = property(_get, _set) > > > > class RC(object): > > defprop('pwm01') > > defprop('pwm02') > > > > rc = RC() > > > > print rc.pwm01 # 127 > > print rc.pwm02 # 127 > > rc.pwm02 = 1312 > > print rc.pwm02 # 32 > > > > This is a bit hackish, but I would prefer this over a metaclass > > solution. since it does not add > > any hidden magic to your class. > > Why is this less hidden or magical than a metaclass ? Devil's Advocate: he did say "hidden magic TO YOUR CLASS". If you use a (real) metaclass, then you have the icky feeling of a class permanently tainted by the unclean metaclass (even though the metaclass does nothing other than touch the class dict upon creation); whereas if you use Michele Simionato's hack, the icky feeling of using a stack frame object goes away after the property is created: you are left with a clean untainted class. Personally, the former doesn't make me feel icky at all. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Carl Banks wrote: > Devil's Advocate: he did say "hidden magic TO YOUR CLASS". > > If you use a (real) metaclass, then you have the icky feeling of a > class permanently tainted by the unclean metaclass (even though the > metaclass does nothing other than touch the class dict upon creation); > whereas if you use Michele Simionato's hack, the icky feeling of using > a stack frame object goes away after the property is created: you are > left with a clean untainted class. Yep, exactly. > Personally, the former doesn't make me feel icky at all. Please, do this experiment: take all classes defined in the Python standard library and add to them a custom do-nothing metaclass. See what happens. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
George Sakkis wrote: > There's a subtle common bug here: all _get and _set closures will refer > to the last property only. You have to remember to write "def > _set(self,v,prop=prop)" and similarly for _get to do the right thing. Sorry. My mistake. > By the way, I can't think of a case where the current behavior (i.e. > binding the last value only) is the desired one. Is this just an > implementation wart or am I missing something ? def some_function(a): def printvars(): print "DEBUG: %r,%r,%r" % (a,b,i) for i in some_range(): b = something(i) printvars() If you fix the value of the closure at function definition time, printvars() above doesn't work. One way or another, someone's going to get surprised. Better to let it be the experts. Carl -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for assignement operator
Tommi wrote: (please don't top-post - corrected) > > > Alexander Eisenhuth wrote: >> Hello, >> >> is there a assignement operator, that i can overwrite? >> >> class MyInt: >> def __init__(self, val): >> assert(isinstance(val, int)) >> self._val = val >> >> a = MyInt(10) >> >> # Here i need to overwrite the assignement operator >> a = 12 >> > Could the "traits" package be of help? > > http://code.enthought.com/traits/ > How could it help ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic module loading via __import__, nonetype?
Gabriel Genellina wrote: > At Monday 16/10/2006 13:33, John Allman wrote: > >> If i manually import a module, this method works a treat, however if i >> attempt to dynamically load a module at runtime the create method fails >> with the following error: >> >> TypeError: 'NoneType' object is not callable > > Can you cut down a reproducible test case, with *only* this behavior and > nothing more? > Hi Gabriel Thanks for the reply. I actually spotted my error (simple, stupid that i hadn't noticed). I had the create method creating an object if it could find a suitable class and importing a suitable class if it couldn't find one. I rather stupidly forgot to actually create an object after importing the class! I was completely stuck - it's amazing what a night's sleep will do for you! Thanks, John -- http://mail.python.org/mailman/listinfo/python-list
Re: a little about regex
Fulvio wrote: > I'm trying to get working an assertion which filter address from some domain > but if it's prefixed by '.com'. > Even trying to put the result in a negate test I can't get the wanted result. [...] > Seem that I miss some better regex implementation to avoid that both of the > filters taking action. I'm thinking of lookbehind (negative or positive) > option, but I think I couldn't realize it yet. > I think the compilation should either allow have no '.com' before '.my' or > deny should have _only_ '.com' before '.my'. Sorry I don't get the correct > sintax to do it. > > Suggestions are welcome. Try this: def filter(adr):# note that "filter" is a builtin function also import re allow = re.compile(r'.*(?|$)') # negative lookbehind deny = re.compile(r'.*\.com\.my(>|$)') cnt = 0 if deny.search(adr): cnt += 1 if allow.search(adr): cnt += 1 return cnt HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Michele Simionato wrote: > Carl Banks wrote: > > Devil's Advocate: he did say "hidden magic TO YOUR CLASS". > > > > If you use a (real) metaclass, then you have the icky feeling of a > > class permanently tainted by the unclean metaclass (even though the > > metaclass does nothing other than touch the class dict upon creation); > > whereas if you use Michele Simionato's hack, the icky feeling of using > > a stack frame object goes away after the property is created: you are > > left with a clean untainted class. > > Yep, exactly. > > > Personally, the former doesn't make me feel icky at all. > > Please, do this experiment: take all classes defined in the Python > standard library and add > to them a custom do-nothing metaclass. See what happens. Do you expect the result to be better or worse than if you applied stack frame hacks to the whole library? Come on, I don't think anyone's under the impression we're being indiscriminate here. Carl Banks (BTW, most of the standard library still uses old-style classes.) -- http://mail.python.org/mailman/listinfo/python-list
Wax: problem subclassing TextBox
Hey everyone, I've just started looking at Wax and have hit a problem I can't explain. I want an app to respond to every character input into a TextBox. Here's a simple, working example: +++ from wax import * class MainFrame(VerticalFrame): def Body(self): self.search = TextBox(self) self.search.OnChar = self.OnChar self.AddComponent(self.search, expand='h', border=5) def OnChar(self, event): print 'OnChar:', event.GetKeyCode() event.Skip() app = Application(MainFrame) app.Run() +++ This displays a TextBox and entering "abcd" results in: OnChar: 97 OnChar: 98 OnChar: 99 OnChar: 100 Rather than defining the OnChar hook on the main frame, though, it makes more sense (to me) to be defined on the TextBox itself, so I tried subclassing it as follows: +++ class NewTextBox(TextBox): def OnChar(self, event): print 'on char', event.GetKeyCode() event.Skip() class MainFrame(VerticalFrame): def Body(self): self.search = NewTextBox(self) self.AddComponent(self.search, expand='h', border=5) +++ With the same input of 'abcd', I get the following: on char 97 on char 97 on char 98 on char 98 on char 99 on char 99 on char 100 on char 100 As I understand it, event.Skip() should propagate the event up the inheritance chain, but I don't see how that would result in NewTextBox.OnChar being called _twice_ for each input. Stopping the event there by removing the event.Skip() does result in only one 'on char XX' line for each character, but also stops _all_ OnChar actions for the TextBox - such as updating the value and displaying it - and I really don't want to have to reimplement the full functionality just to prevent this. Is there something glaringly obvious that I'm doing wrong in the above code? Thanks for any help... - alex23 -- http://mail.python.org/mailman/listinfo/python-list
RE: making a valid file name...
> > Hi I'm writing a python script that creates directories from user > input. > Sometimes the user inputs characters that aren't valid > characters for a > file or directory name. > Here are the characters that I consider to be valid characters... > > valid = > ':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' > > if I have a string called fname I want to go through each character in > the filename and if it is not a valid character, then I want > to replace > it with a space. > > This is what I have: > > def fixfilename(fname): > valid = > ':.\,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' > for i in range(len(fname)): > if valid.find(fname[i]) < 0: > fname[i] = ' ' >return fname > > Anyone think of a simpler solution? > I got; >>> import re >>> badfilename='£"%^"£^"£$^ihgeroighroeig3645^£$^"knovin98u4#346#1461461' >>> valid=':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' >>> goodfilename=re.sub('[^'+valid+']',' ',badfilename) >>> goodfilename ' ^ ^ ^ihgeroighroeig3645^ ^ knovin98u4 346 1461461' This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
Re: creating many similar properties
Carl Banks wrote: > Come on, I don't think anyone's under the impression we're being > indiscriminate here. Ok, but I don't think that in the case at hand we should recommend a metaclass solution. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Book about database application development?
Dennis Lee Bieber wrote: > > Python has a half dozen GUI toolkits, and multiple adapters for > databases (some don't even follow DB-API2 specs). All independently > written. So no, you are not going to find, say, a grid widget that > automatically links to a database table/view/cursor, with bi-directional > updates. Aren't we going round in circles here? There presumably are grid widgets connected to database tables/views/cursors, if only exposed via user interface toolkits and other frameworks such as PyQt, Dabo and so on, but I thought the questioner wanted to know how to implement these things from the ground up. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Web Site?
*% a écrit : > Is there a problem with the Python and wxPython web sites? I cannot > seem to get them up, and I am trying to find some documentation... > > Thanks, > Mike All the sites hosted on sourceforge that rely on their vhost computer ( ie, site hosted on sourceforge that do not display the sourceforge.net address ) are broken. You get a blank page instead. http://wxpython.sourceforge.net/ works http://wxpython.org/ doesn't work It has been like that for a few hours already. -- http://mail.python.org/mailman/listinfo/python-list
Re: python's OOP question
"neoedmund" <[EMAIL PROTECTED]> writes: > Bruno Desthuilliers wrote: > > neoedmund wrote: > > > in real life, a class is not defined so well that any method is > > > needed by sub-class. > > > > Then perhaps is it time to refactor. A class should be a highly > > cohesive unit. If you find yourself needing only a specific subset > > of a class, it may be time to extract this subset in it's own > > class. > > I donnot agree with your "it's time to refactory" very much, man has > probly never has time to do such things. I respectfully suggest that the *reason* you find yourself with little time to refactor is probably related to the fact that you *need* to refactor. If your code is crufty and poorly-designed, it is costing you every time you need to maintain it. Would it help if we called it "preventative maintenance"? -- \"I bought a dog the other day. I named him Stay. It's fun to | `\ call him. 'Come here, Stay! Come here, Stay!' He went insane. | _o__) Now he just ignores me and keeps typing." -- Steven Wright | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: python's OOP question
On 2006-10-18, neoedmund <[EMAIL PROTECTED]> wrote: > ivestgating the web, i found something similiar with my approch: > http://en.wikipedia.org/wiki/Duck_typing > "Duck-typing avoids tests using type() or isinstance(). Instead, it > typically employs hasattr() tests" It's pity it didn't get called quack typing. One ckecks if some unknown noun can quack, not if a duck can do something unknown. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
portable extensions options for external libraries
Hi. I want to create a portable setup.py file for windows / linux for an extension package that i need to link with external libraries (gsl and boost). on windows i do something like this: imaging = Extension( 'pyag.imaging._imaging', sources = ( glob.glob( 'Source/pyag/imaging/Src/*.cpp' ) + glob.glob( 'Source/pyag/imaging/Src/*.h' ) ), include_dirs = ( get_numpy_include_dirs() + [ 'Source/pyag/imaging/Src/', 'C:/Program Files/boost/include/boost-1_35', 'C:/Program Files/GnuWin32/include'] ), library_dirs = [ 'C:/Program Files/GnuWin32/lib' ], libraries = [ 'libgsl', 'libgslcblas' ] ) obviously, the paths could vary. on unix, i need something like: imaging = Extension( 'pyag.imaging._imaging', sources = ( glob.glob( 'Source/pyag/imaging/Src/*.cpp' ) + glob.glob( 'Source/pyag/imaging/Src/*.h' ) ), include_dirs = ( get_numpy_include_dirs() + [ 'Source/pyag/imaging/Src/' ] ) ) so my question is: what is the right way of specifying extensions options (include_dirs, libraries, library_dirs) so that they are portable between windows and linux? i'm thinking environment variables. Though fairly easy to do, i was wondering if python/distutils provided something more convenient, like searching through "common" directories, though those aren't very standard on windows? Optimally, i would like to have something like: imaging = Extension( 'pyag.imaging._imaging', sources = ( glob.glob( 'Source/pyag/imaging/Src/*.cpp' ) + glob.glob( 'Source/pyag/imaging/Src/*.h' ) ), include_dirs = ( get_numpy_include_dirs() + [ 'Source/pyag/imaging/Src/' ] + boost_include_dirs + gsl_include_dirs ), library_dirs = boost_library_dirs + gsl_library_dirs, libraries = boost_libraries + gsl_libraries ) thx for any help. alex. -- http://mail.python.org/mailman/listinfo/python-list
matrix Multiplication
hi evrybody! I wan't to multiply two square matrixes, and i don't understand why it doesn't work. Could you explain me? def multmat(A,B): "A*B" if len(A)!=len(B): return "error" D=[] C=[] for i in range(len(A)): D.append(0) for i in range(len(A)): C.append(D) for i in range(len(A)): for j in range(len(A)): for k in range(len(A)): C[i][j]+=A[i][k]*B[k][j] print C[i][j] print C[i] return C when i use it on : >>> A=[[2,3,4],[5,8,6],[4,5,7]] >>> B=[[1,0,0],[0,1,0],[0,0,1]] I get : 2 2 2 0 3 3 0 0 4 [2, 3, 4] 7 7 7 3 11 11 4 4 10 [7, 11, 10] 11 11 11 11 16 16 10 10 17 [11, 16, 17] [[11, 16, 17], [11, 16, 17], [11, 16, 17]] thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: making a valid file name...
Matthew Warren wrote: >>> import re >>> badfilename='£"%^"£^"£$^ihgeroighroeig3645^£$^"knovin98u4#346#1461461' >>> valid=':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' >>> goodfilename=re.sub('[^'+valid+']',' ',badfilename) to create arbitrary character sets, it's usually best to run the character string through re.escape() before passing it to the RE engine. -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix Multiplication
"Sssasss" wrote: > I wan't to multiply two square matrixes, and i don't understand why it > doesn't work. > > def multmat(A,B): >"A*B" >if len(A)!=len(B): return "error" >D=[] >C=[] >for i in range(len(A)): D.append(0) >for i in range(len(A)): C.append(D) append doesn't copy data, so you're basically adding len(A) references to the same D list to C. for more on this, see: http://pyfaq.infogami.com/how-do-i-create-a-multidimensional-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Plotting histograms
[EMAIL PROTECTED] wrote: > hi, I have some values(say from -a to a) stored in a vector and I want > to plot a histogram for those values. How can I get it done in python. > I have installed and imported the Matplotlib package but on executing > the code > [N,x]=hist(eig, 10) # make a histogram > I am getting an error saying "NameError: name 'hist' is not > defined". > > Is there any other way to plot histograms over a given range? >>> # create random vector ... from random import randrange >>> a = 5 >>> v = [randrange(-a, a+1) for i in xrange(100)] >>> >>> # print histogram ... for i in range(-a, a+1): ... print "%+d %s" % (i, '*' * v.count(i)) ... -5 * -4 * -3 * -2 ** -1 ** +0 * +1 +2 *** +3 * +4 +5 :) -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexable Collating (feedback please)
On Oct 18, 2:42 am, Ron Adam <[EMAIL PROTECTED]> wrote: > I put together the following module today and would like some feedback on any > obvious problems. Or even opinions of weather or not it is a good approach. ,,, def __call__(self, a, b): """ This allows the Collate class work as a sort key. USE: list.sort(key=Collate(flags)) """ return cmp(self.transform(a), self.transform(b)) You document _call__ as useful for the "key" keyword to sort, but you implement it for the "cmp" keyword. The "key" allows much better performance, since it's called only once per value. Maybe just : return self.transform(a) -- George -- http://mail.python.org/mailman/listinfo/python-list
Re: making a valid file name...
You should use the s.translate() It's 100x faster: #Creates the translation table ValidChars = ":./,^0123456789abcdefghijklmnopqrstuvwxyz" InvalidChars = "".join([chr(i) for i in range(256) if not chr(i).lower() in ValidChars]) TranslationTable = "".join([chr(i) for i in range(256)]) def valid_filename(fname): return fname.translate(TranslationTable, InvalidChars) >> valid = >> ':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' >> >> if I have a string called fname I want to go through each character in >> the filename and if it is not a valid character, then I want >> to replace >> it with a space. -- Ceci est une signature automatique de MesNews. Site : http://www.mesnews.net -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix Multiplication
Fredrik Lundh wrote: > "Sssasss" wrote: > > > I wan't to multiply two square matrixes, and i don't understand why it > > doesn't work. > > > > def multmat(A,B): > >"A*B" > >if len(A)!=len(B): return "error" > >D=[] > >C=[] > >for i in range(len(A)): D.append(0) > >for i in range(len(A)): C.append(D) > > append doesn't copy data, so you're basically adding len(A) references to > the same D list to C. for more on this, see: > > http://pyfaq.infogami.com/how-do-i-create-a-multidimensional-list > > Ok!! Tank you very much, i understand now. ciao -- http://mail.python.org/mailman/listinfo/python-list
codecs.EncodedFile
Perhaps I'm just bad at searching for bugs, but anyhow, I wanted to know what you all thought about the following behavior. A quick search of pydev archives yielded a nice wrapper to apply to streams to perform decoding and encoding behind the scenes. Assuming I get the correct encodings from somewhere (that's a whole 'nother thread): Here's the docs: EncodedFile( file, input[, output[, errors]]) Return a wrapped version of file which provides transparent encoding translation. Strings written to the wrapped file are interpreted according to the given input encoding and then written to the original file as strings using the output encoding. The intermediate encoding will usually be Unicode but depends on the specified codecs. If output is not given, it defaults to input. errors may be given to define the error handling. It defaults to 'strict', which causes ValueError to be raised in case an encoding error occurs. Base on that, I wrote the following code at startup: sys.stdout = codecs.EncodedFile(sys.stdout, 'latin-1', 'cp437') sys.stdin = codecs.EncodedFile(sys.stdin, 'cp437', 'latin-1') Now my application never returns from its first call to sys.stdin.readline. It turns out to be troublesome for my case because the EncodedFile object translates calls to readline into calls to read. I believe it ought to raise a NotImplemented exception when readline is called. As it is it silently causes interactive applications to apparently hang forever, and breaks the line-buffering expectation of non-interactive applications. If raising the exception is too much to ask, then at least it should be documented better. -- Neil Cerutti The choir invites any member of the congregation who enjoys sinning to join the choir. --Church Bulletin Blooper -- http://mail.python.org/mailman/listinfo/python-list
Re: python's OOP question
Neil Cerutti wrote: > On 2006-10-18, neoedmund <[EMAIL PROTECTED]> wrote: >> ivestgating the web, i found something similiar with my approch: >> http://en.wikipedia.org/wiki/Duck_typing >> "Duck-typing avoids tests using type() or isinstance(). Instead, it >> typically employs hasattr() tests" > > It's pity it didn't get called quack typing. That's because the quacks prescribe static typing. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix Multiplication
On 2006-10-18 14:15:17 +0200, Sssasss wrote: > Fredrik Lundh wrote: > > "Sssasss" wrote: > > > > > I wan't to multiply two square matrixes, and i don't understand why it > > > doesn't work. > > > > > > def multmat(A,B): > > >"A*B" > > >if len(A)!=len(B): return "error" > > >D=[] > > >C=[] > > >for i in range(len(A)): D.append(0) > > >for i in range(len(A)): C.append(D) > > > > append doesn't copy data, so you're basically adding len(A) references to > > the same D list to C. for more on this, see: > > > > http://pyfaq.infogami.com/how-do-i-create-a-multidimensional-list > > > > > > Ok!! Tank you very much, i understand now. You might also want to look at numpy/numarray. Gerrit. -- http://mail.python.org/mailman/listinfo/python-list
MemoryError - IMAP retrieve self._sock.recv(recv_size)
Hi there. I have been receiving MemoryErrors using the Windows version of Python 2.5. The script I have written times the sending and the reception of emails with various attachments. I get many exceptions when using the IMAP downloads. This happens randomly; sometimes the file downloads OK, and other times no. Using an exception and traceback function, I can see the following... MemoryError File "C:\Documents and Settings\root\Desktop\TMO\Python scripts\imap-v2.3a.py", line 263, in main typ, data = M.fetch(num, '(RFC822)') File "C:\Python25\lib\imaplib.py", line 437, in fetch typ, dat = self._simple_command(name, message_set, message_parts) File "C:\Python25\lib\imaplib.py", line 1055, in _simple_command return self._command_complete(name, self._command(name, *args)) File "C:\Python25\lib\imaplib.py", line 885, in _command_complete typ, data = self._get_tagged_response(tag) File "C:\Python25\lib\imaplib.py", line 986, in _get_tagged_response self._get_response() File "C:\Python25\lib\imaplib.py", line 948, in _get_response data = self.read(size) File "C:\Python25\lib\imaplib.py", line 236, in read return self.file.read(size) File "C:\Python25\lib\socket.py", line 308, in read data = self._sock.recv(recv_size) Is this a know bug or is there something I can do to work around this? Thanks, Stephen -- http://mail.python.org/mailman/listinfo/python-list
Re: MemoryError - IMAP retrieve self._sock.recv(recv_size)
"Stephen G" <[EMAIL PROTECTED]> wrote: > I get many exceptions when using the IMAP downloads. This happens > randomly; sometimes the file downloads OK, and other times no. > File "C:\Python25\lib\socket.py", line 308, in read >data = self._sock.recv(recv_size) > > Is this a know bug or is there something I can do to work around this? looks like this http://mail.python.org/pipermail/python-list/2005-December/317239.html or some variation thereof. -- http://mail.python.org/mailman/listinfo/python-list
Re: Numpy-f2py troubles
Hi Andrea, you should post this to the numpy list: numpy-discussion@lists.sourceforge.net Cheers! Bernhard Andrea Gavana schrieb: > Hello NG, > > I am using the latest Numpy release 1.0rc2 which includes F2PY. I > have switched to Python 2.5 so this is the only alternative I have > (IIUC). With Python 2.4, I was able to build a very simple fortran > extension without problems. > > My extension contains 4 subroutines that scan a file and do simple operations. > Now, attempting to run the second subroutine as: > > dprops, dwgnames, dunits = readsmspec.readsmspec(smspec, dimens) > > Prompt a ValueError from Python: > > File "D:\MyProjects\Carolina\MainPanel.py", line 894, in ReadSMSPECFile > dprops, dwgnames, dunits = readsmspec.readsmspec(smspec, dimens) > ValueError: data type must provide an itemsize > > ?!? I have never seen anything like that and googling around didn't > give me any answer. The function accepts two inputs: > > - smspec: a filename, maximum 1000 characters long > - dimens: an integer > > and returns 3 array of chars, each of them with size (8, dimens). Does > anyone know what I may be doing wrong? > > Thank you very much for every pointer. > > > -- > Andrea. > > "Imagination Is The Only Weapon In The War Against Reality." > http://xoomer.virgilio.it/infinity77/ -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix Multiplication
Il 18 Oct 2006 04:17:29 -0700, Sssasss ha scritto: > hi evrybody! > > I wan't to multiply two square matrixes, and i don't understand why it > doesn't work. Can I suggest a little bit less cumbersome algorithm? def multmat2(A,B): "A*B" if len(A)!=len(B): return "error" # this check is not enough! n = range(len(A)) C = [] for i in n: C.append([0]*len(A)) # add a row to C for j in n: a = A[i]# get row i from A b = [row[j] for row in B] # get col j from B C[i][j] = sum([x*y for x,y in zip(a,b)]) return C regards D. -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix Multiplication
Sssasss wrote: > hi evrybody! > > I wan't to multiply two square matrixes, and i don't understand why it > doesn't work. > Could you explain me? > > def multmat(A,B): >"A*B" >if len(A)!=len(B): return "error" Wrong validation here: you _can_ multiply two matrices with a different number of rows! And instead of returning "error" you should raise an exception. [...] I suggest using a linear algebra package, but if you insist in using lists of lists: >>> b = [[1, 2, 3, 4], ... [4, 5, 6, 7], ... [7, 8, 9, 10]] >>> >>> a = [[1, 2, 3], ... [4, 5, 6]] >>> >>> ab = [[sum(i*j for i, j in zip(row, col)) for col in zip(*b)] for row in a] >>> ab [[30, 36, 42, 48], [66, 81, 96, 111]] Straightforward from the definition of matrix multiplication. -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert this list to string?
Thank you very much. I memoed all you views. :) -- http://mail.python.org/mailman/listinfo/python-list
PIL: Image.draft -- what are the modes that I can use?
I have PIL 1.1.5 on python 2.4.1 and I am attempting to get a smaller (file size) of an image. for example: im = ImageGrab.grab() im.save("tmp.gif") about 1.7mb im.save("tmp.jpeg") about 290kb anyways I want to save the image as a GIF, but not have it be so largeso I thought that the Image.draft method would be what I wanted im.draft(mode, size) Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a colour JPEG to greyscale while loading it, or to extract a 128x192 version from a PCD file. .what 'modes' can I use? or is there another way to shrink the size of the image (other than resizing it)? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
"abcd" wrote: >I have PIL 1.1.5 on python 2.4.1 and I am attempting to get a smaller > (file size) of an image. > > for example: > im = ImageGrab.grab() > > im.save("tmp.gif") about 1.7mb > im.save("tmp.jpeg") about 290kb > > anyways I want to save the image as a GIF, but not have it be so > largeso I thought that the Image.draft method would be what I > wanted GIF is horribly unsuitable for screenshots on modern machines. have you considered using PNG ? or even better, Flash? here's a tool that lets you use VNC to capture the screen, and then convert the result to a flash animation: http://www.unixuser.org/~euske/vnc2swf/ > im.draft(mode, size) > > Configures the image file loader so it returns a version of the image > that as closely as possible matches the given mode and size. For > example, you can use this method to convert a colour JPEG to greyscale > while loading it, or to extract a 128x192 version from a PCD file. note the use of the words "loader" and "loading". draft is used to speed things up when loading images, not compress things when storing them. -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
Fredrik Lundh wrote: > GIF is horribly unsuitable for screenshots on modern machines. have you > considered using PNG ? > > or even better, Flash? well I am trying to take screenshots and make them into an animated GIF, however, putting them into a Flash movie would be coolany idea how to go about doing either with python? (windows, possibly linux later) -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
"abcd" wrote: >> or even better, Flash? > > well I am trying to take screenshots and make them into an animated > GIF, however, putting them into a Flash movie would be coolany idea > how to go about doing either with python? (windows, possibly linux > later) to repeat myself: here's a tool that lets you use VNC to capture the screen, and then convert the result to a flash animation: http://www.unixuser.org/~euske/vnc2swf/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
oh and vnc2swf would not be an option, i cant be setting up a vnc server, etc. just need to use python (and necessary packages). animated gif would probably be best i am assuming. -- http://mail.python.org/mailman/listinfo/python-list
Re: Restart a Python COM Server
OK, well thank you for your help (merci pour ton aide!) M.E. MC wrote: > Hi! > > It is the normal behavior of COM. > > Note that, Python being dynamic, you can modify Python script, OF THE > INTERIOR, during execution. > > -- > @-salutations > > Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Win32 python and excel macros
Hi Experts, Looking for a very quick bit on of advice on how to make some python code run. I'm a newbie to both VBA and Python, so i apologise if this is very easy but i'm about to tear my hair out after googling for the last 3 days. I have written a large python script which inside of it creates an Excel table, the name of this file and how many objects can change for each project i run. I have then written a VBA script which takes the info from Excel and drops it into a PowerPoint Pres. Both of these procedures work fine, but i am coming unstuck when i try to apply the macro, (or .xla) file to the new tables autmatically. Can anyone give me any guidance on this? The macro is called sub is CTP and the add-in file is CTP.XLA Below is the code i've managed to 'Stick' together Mike import win32com.client xl = win32com.client.Dispatch("Excel.Application") ppt = win32com.client.Dispatch("PowerPoint.Application") xl.Visible = 1 #open MS Excel ppt.Visible = 1 #open MS Powerpoint xl.Workbooks.Open('Z:\\projects\\surveys\\SPSS - Generic files\\big output.xls') #A table for a project xl.Workbooks.Open('Z:\\projects\\surveys\\SPSS - Generic files\\CTP.xla') # Stored macro add-in ppt.Presentations.Open('Z:\\projects\\surveys\\SPSS - Generic files\\Basic Template.ppt') xl.Application.ExecuteExcel4macro('CTP!CTP.xla()"[big output.XLS]') -- http://mail.python.org/mailman/listinfo/python-list
Python RPM package arch compatability
Hello all, A quick question if I may. I'm running RHEL 4 on a x86_64 and I'm curious if any of the packages at http://www.python.org/download/releases/2.4/rpms/ would suite my setup. If they don't can I simply build from source and not overwrite /usr/bin/Python (for the same reasons as listed at the above mentioned webpage)? Respectfully, Christopher Taylor -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
Fredrik Lundh wrote: > to repeat myself: > > here's a tool that lets you use VNC to capture the screen, and then > convert > the result to a flash animation: > >http://www.unixuser.org/~euske/vnc2swf/ > > is there a way to make animated GIFs with python? vnc2swf is to much for what i was hoping. i have no problem with installing python packages, but having to use VNC is a bit much. thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Save/Store whole class (or another object) in a file
Hi, thanks for the reply,but unfortunately this does not work with the type of classes I am dealing with. When trying to pickle the class I get the following error: File "/usr/lib/python2.4/copy_reg.py", line 76, in _reduce_ex raise TypeError("a class that defines __slots__ without " TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled So there is something missing in this class? Or any other idea how to do this? Alex Sybren Stuvel wrote: > [EMAIL PROTECTED] enlightened us with: > > is it possible in python (with/without matplotlib, numpy etc) to > > store a whole class with its data into a file > > Check out the pickle module. > > Sybren > -- > Sybren Stüvel > Stüvel IT - http://www.stuvel.eu/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python RPM package arch compatability
Christopher Taylor wrote: > A quick question if I may. I'm running RHEL 4 on a x86_64 and I'm > curious if any of the packages at > http://www.python.org/download/releases/2.4/rpms/ would suite my > setup. > > If they don't can I simply build from source and not overwrite > /usr/bin/Python (for the same reasons as listed at the above mentioned > webpage)? if you use "make altinstall" instead of "make install", the installation process will only install a pythonX.Y binary (e.g. python2.5). -- http://mail.python.org/mailman/listinfo/python-list
How to execute a linux command by python?
How to execute a linux command by python? for example: execute "ls" or "useradd oracle" Who can help me? thank you! -- http://mail.python.org/mailman/listinfo/python-list
Re: Flexable Collating (feedback please)
[EMAIL PROTECTED] wrote: > > On Oct 18, 2:42 am, Ron Adam <[EMAIL PROTECTED]> wrote: >> I put together the following module today and would like some feedback on any >> obvious problems. Or even opinions of weather or not it is a good approach. > ,,, > def __call__(self, a, b): > """ This allows the Collate class work as a sort key. > > USE: list.sort(key=Collate(flags)) > """ > return cmp(self.transform(a), self.transform(b)) > > You document _call__ as useful for the "key" keyword to sort, but you > implement it for the "cmp" keyword. The "key" allows much better > performance, since it's called only once per value. Maybe just : > return self.transform(a) > > -- George > Thanks, I changed it to the following... def __call__(self, a): """ This allows the Collate class work as a sort key. USE: list.sort(key=Collate(flags)) """ return self.transform(a) And also changed the sort call here ... def collate(slist, flags=0): """ Collate list of strings in place. """ slist.sort(key=Collate(flags)) <<< Today I'll do some performance tests to see how much faster it is for moderate sized lists. Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: Python RPM package arch compatability
So just build it from source and use make altinstall instead? That simple huh? Will I need to do anything else to make sure things are put in their correct place? Respectfully, Christopher Taylor On 10/18/06, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Christopher Taylor wrote: > > > A quick question if I may. I'm running RHEL 4 on a x86_64 and I'm > > curious if any of the packages at > > http://www.python.org/download/releases/2.4/rpms/ would suite my > > setup. > > > > If they don't can I simply build from source and not overwrite > > /usr/bin/Python (for the same reasons as listed at the above mentioned > > webpage)? > > if you use "make altinstall" instead of "make install", the installation > process will > only install a pythonX.Y binary (e.g. python2.5). > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
fredrik, in other posts you have mentioned the use of gifmaker. i have tried that with the following: I am using gifmaker.py from PIL v1.1.5 on python 2.4.1. CODE import ImageGrab, gifmaker seq = [] while keepOnGoing: im = ImageGrab.grab() seq.append(im) fp = open("out.gif", "wb") gifmaker.makedelta(fp, seq) fp.close() --- however I am getting this error: Exception in thread Thread-3: Traceback (most recent call last): File "c:\Python24\lib\threading.py", line 442, in __bootstrap self.run() File "c:\foo.py", line 10, in run gifmaker.makedelta(fp, seq) File "c:\gifmaker.py", line 79, in makedelta for s in getheader(im) + getdata(im): File "c:\Python24\Lib\site-packages\PIL\GifImagePlugin.py", line 383, in getdata ImageFile._save(im, fp, [("gif", (0,0)+im.size, 0, RAWMODE[im.mode])]) KeyError: 'RGB' Any ideas? Basically I want to make an animated GIF out of a bunch of images taken using the ImageGrab module. -- http://mail.python.org/mailman/listinfo/python-list
Re: Save/Store whole class (or another object) in a file
[EMAIL PROTECTED] wrote: > thanks for the reply,but unfortunately this does not work with the type > of classes I am dealing with. When trying to pickle the class I get the > following error: > > File "/usr/lib/python2.4/copy_reg.py", line 76, in _reduce_ex > raise TypeError("a class that defines __slots__ without " > TypeError: a class that defines __slots__ without defining __getstate__ > cannot be pickled > > So there is something missing in this class? did you remember to read the error message before posting ? -- http://mail.python.org/mailman/listinfo/python-list
Re: MemoryError - IMAP retrieve self._sock.recv(recv_size)
Fredrik, Thanks for the response. I did see that, but having been dated 2005 I thought that it might have been patched. I am also sometimes getting the same problem with the urllib.py module. T his may have to do with the interaction between Python and the mobile optimization client that I am testing. I do not see this problem when using Internet Explorer and the optimization client, nor is there a problem when using Python and no optimization client. I am working with the optimization client vendor to have them test my Python script with their product. This problem is intermittent with the optimization client which is annoying since most of the time it works. Iteration Number 12 18/10/2006 14:01:23 Downloading http://tmotest.de/ftp/3MB.doc Error: problem downloading 3MB.doc error File "C:\Documents and Settings\root\Desktop\TMO\Python scripts\http-v2.3a.py", line 130, in main urllib.urlretrieve(total_URL, downloaded_file) File "C:\Python25\lib\urllib.py", line 89, in urlretrieve return _urlopener.retrieve(url, filename, reporthook, data) File "C:\Python25\lib\urllib.py", line 248, in retrieve block = fp.read(bs) File "C:\Python25\lib\socket.py", line 308, in read data = self._sock.recv(recv_size) I am hesitant to make any changes to the python libraries as I need to distribute these scripts with a standard Python install. I guess an other option is to try and learn something like Perl and recode all the test scripts... -- http://mail.python.org/mailman/listinfo/python-list
Re: Restart a Python COM Server
[EMAIL PROTECTED] wrote: > Hello all. > I am desperately in need for you help guys. Here is the story: > 1- I have created a small simple COM serve with python (along the lines > read in Win32 Programming with python). > 2- If I start the server and call a function from VBE everything works > fine > 3- I then want to modify the function in the python COM server > 4- I unregister the server and register it again hoping the changes > will take effect > 5- I make call to the function from VBE but the it seems that VBE > doesn't reload/refresh the reference to the server. > So I do I get VBE to point to the last version of the server? If I > close VBE and reload it then it works. But I think there is probably a > smarter way. Please, tell me there is! > Few posts deal with the issue, but so far I couldn't find anything > about it... > > Thanx all > M.E I don't know how well this works for python-based COM components, but the general fix is to setup a Component Services package. This creates a proxy component which can be independently killed from the Component Services management console. -- http://mail.python.org/mailman/listinfo/python-list
Re: a little about regex
Rob Wolfe wrote: ... > def filter(adr):# note that "filter" is a builtin function also > import re > > allow = re.compile(r'.*(?|$)') # negative lookbehind > deny = re.compile(r'.*\.com\.my(>|$)') > cnt = 0 > if deny.search(adr): cnt += 1 > if allow.search(adr): cnt += 1 > return cnt Which makes the 'deny' code here redundant so in this case the function could be reduced to: import re def allow(adr):# note that "filter" is a builtin function also allow = re.compile(r'.*(?|$)') # negative lookbehind if allow.search(adr): return True return False Though having the explicit allow and deny expressions may make what's going on clearer than the fairly esoteric negative lookbehind. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to execute a linux command by python?
haishan chang wrote: > How to execute a linux command by python? > for example: execute "ls" or "useradd oracle" > Who can help me? start here: http://www.python.org/doc/lib/ -- http://mail.python.org/mailman/listinfo/python-list
Re: MemoryError - IMAP retrieve self._sock.recv(recv_size)
Stephen G wrote: > I am hesitant to make any changes to the python libraries as > I need to distribute these scripts with a standard Python install. well, you could at least check if the suggestions in that thread makes the problem go away... (if so, shipping a patched version with your program is trivial). -- http://mail.python.org/mailman/listinfo/python-list
Re: Save/Store whole class (or another object) in a file
[EMAIL PROTECTED] wrote: > Hi, > > thanks for the reply,but unfortunately this does not work with the type > of classes I am dealing with. When trying to pickle the class I get the > following error: > > File "/usr/lib/python2.4/copy_reg.py", line 76, in _reduce_ex > raise TypeError("a class that defines __slots__ without " > TypeError: a class that defines __slots__ without defining __getstate__ > cannot be pickled > > So there is something missing in this class? Or any other idea how to > do this? > > Alex yes, read the documentation: http://docs.python.org/dev/lib/pickle-inst.html Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Dictionaries
How can I add two dictionaries into one? E.g. a={'a:1} b={'b':2} I need the result {'a':1,'b':2}. Is it possible? Thank you L. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to execute a linux command by python?
Fredrik Lundh wrote: > start here: > > http://www.python.org/doc/lib/ make sure you skim though the *entire* list. when you've done that, see the "process management" section in the "os" module documentation (make sure to read the entire page before you decide which API to use), and also the "subprocess" module documentation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
On 18 Oct 2006 08:24:27 -0700, Lad <[EMAIL PROTECTED]> wrote: > How can I add two dictionaries into one? > E.g. > a={'a:1} > b={'b':2} > > I need > > the result {'a':1,'b':2}. >>> a={'a':1} >>> b={'b':2} >>> a.update(b) >>> a {'a': 1, 'b': 2} -- Cheers, Simon B [EMAIL PROTECTED] http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: doctest quiet again before exit how
> ... every run of doctest after the first is verbose ... > *** DocTestRunner.merge: '__main__' in both testers; summing outcomes. Another path to the same bug: import doctest print doctest.testfile(__file__, verbose=False) print doctest.testfile(__file__, verbose=False) Mystifiedly yours, rank Python newbie, Pat LaVarre -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
Lad wrote: > How can I add two dictionaries into one? > E.g. > a={'a:1} > b={'b':2} > > I need > > the result {'a':1,'b':2}. > > Is it possible? > > Thank you > L. > > Yes, use update. Beware that this modifies a dictionary in place rather than returning a new dictionary. >>> a={'a':1} >>> b={'b':2} >>> a.update(b) >>> a {'a': 1, 'b': 2} Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
> How can I add two dictionaries into one? > E.g. > a={'a:1} > b={'b':2} > > I need > > the result {'a':1,'b':2}. >>> a.update(b) >>> a {'a':1,'b':2} -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Win32 python and excel macros
[EMAIL PROTECTED] wrote: > Hi Experts, > > Looking for a very quick bit on of advice on how to make some python > code run. I'm a newbie to both VBA and Python, so i apologise if this > is very easy but i'm about to tear my hair out after googling for the > last 3 days. > > I have written a large python script which inside of it creates an > Excel table, the name of this file and how many objects can change for > each project i run. > > I have then written a VBA script which takes the info from Excel and > drops it into a PowerPoint Pres. > > Both of these procedures work fine, but i am coming unstuck when i try > to apply the macro, (or .xla) file to the new tables autmatically. Can > anyone give me any guidance on this? > > The macro is called sub is CTP and the add-in file is CTP.XLA > > Below is the code i've managed to 'Stick' together > > Mike > > import win32com.client > xl = win32com.client.Dispatch("Excel.Application") > ppt = win32com.client.Dispatch("PowerPoint.Application") > xl.Visible = 1 #open MS Excel > ppt.Visible = 1 #open MS Powerpoint > xl.Workbooks.Open('Z:\\projects\\surveys\\SPSS - Generic files\\big > output.xls') #A table for a project > xl.Workbooks.Open('Z:\\projects\\surveys\\SPSS - Generic > files\\CTP.xla') # Stored macro add-in > ppt.Presentations.Open('Z:\\projects\\surveys\\SPSS - Generic > files\\Basic Template.ppt') > xl.Application.ExecuteExcel4macro('CTP!CTP.xla()"[big output.XLS]') It doesn't really make sense to apply a *file* to a *file* - you apply a sub or function in that file to a range in the other file (I'm assuming that your table is stored as a range of cells). What ExcecuteExcel4Macro is expecting as input is a string along the lines of 'CTP!MacroName(Workbooks("big output").Range("A1:C100"))' (experiment with using "" instead of " since VBA requires embedded " to be escaped by "" - but since you are writing this in Python it might not be necessary). Maybe experiment with writing a VBA macro in Excel which can successfuly launch the macro you need and then translate the appropriate snippet to your python script. Also - are you sure that the add-in macro is an old-style Excel4 macro? That would make it about 10 years old or deliberately retro. If not - the run method might be more appropriate. You should probably open the workbooks in such a way that big output.xls is the active workbook (and not ctp.xla) since most add-ins assume that the calling workbook is the active workbook (although - I don't know how an old-style pre-VBA Excel4 macro handled things). Thus you would probably want to open big output.xls last (or use xl.Application.Workbooks("big output").Activate ) to make sure that it is the active workbook. Also - do you even have to open ctp.xla explicitly? If it is an installed add-in then that line might be redundant. A final potential problem is that big output.xls might require a reference to ctp.xla. This sometimes happens when you try to invoke add-in code from another VBA project - but I would think that the ExecuteExcel4macro would bypass that. I can't comment on the python part of the equation - I am a complete newbie there. You might consider reposting this in microsoft.public.excel.programming since many of the regular posters there know a lot about automating Excel from scripting languages. They could at least help you with the VBA side of the equation. I hope that my random thoughts don't misguide you too much. -John Coleman -- http://mail.python.org/mailman/listinfo/python-list
Re: Win32 python and excel macros
Thanks for your advice on this matter, I'm actually using Excel 2003!! so it shows how much i know! i did manage to get the prog to run with the line xl.Application.Run("CTP.xla!sheet1.CTP") but it didn't do anything... i'm guessing it is along the lines of wht you were saying earlier about big output being the active worksheet. I'll give that a go now Thanks for the advice Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
dict(a.items() + b.items()) Lad wrote: > How can I add two dictionaries into one? > E.g. > a={'a:1} > b={'b':2} > > I need > > the result {'a':1,'b':2}. > > Is it possible? -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
On Wed, 18 Oct 2006 08:24:27 -0700, Lad wrote: > How can I add two dictionaries into one? > E.g. > a={'a:1} > b={'b':2} > > I need > > the result {'a':1,'b':2}. > > Is it possible? What should the result be if both dictionaries have the same key? a={'a':1, 'b'=2} b={'b':3} should the result be: {'a':1, 'b'=2} # keep the existing value {'a':1, 'b'=3} # replace the existing value {'a':1, 'b'=[2, 3]} # keep both values or something else? Other people have already suggested using the update() method. If you want more control, you can do something like this: def add_dict(A, B): """Add dictionaries A and B and return a new dictionary.""" C = A.copy() # start with a copy of A for key, value in B.items(): if C.has_key(key): raise ValueError("duplicate key '%s' detected!" % key) C[key] = value return C -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Win32 python and excel macros
After just running trying that update it hits the macro perfectly but hten i get an error message after i type in a couple of values.. as per below Traceback (most recent call last): File "", line 148, in ? File ">", line 14, in Run File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 258, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None) I know you said you didn't know much about python, so if any other experts outthere can give me a clue.. i'll be very appreciative Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
abcd wrote: > ... Are you sure you can't use VNC? An animated GIF based on full-screen grabs will be amazingly huge and have very low color quality at the same time. Installing VNC on Windows should take you about 30 seconds, honest. Or is this for some sort of project where you can't use anything but CPython software...? Brett Hoerner -- http://mail.python.org/mailman/listinfo/python-list
Install from source on a x86_64 machine
Hello all, Being relatively new to linux I'm a little confused about what options I need to use to build python from source. Currently, I have python installed as part of the inital RHEL4 load located at /usr/bin/Python and /usr/bin/Python2.3 . Some of the files are located in /usr/lib64/Python2.3 and in /usr/lib/Python2.3 . Please let me know if you need dir lsitings. I'm trying to compile from source and plan on using the --enable-unicode=ucs4 option for the configure script due to some RHEL messing around with Tcl/Tk. *** How do I get make altinstall to put the appropriate files in /usr/lib64/Python2.4 and /usr/lib/Python2.4 respectively ? *** Respectfully, Christopher Taylor -- http://mail.python.org/mailman/listinfo/python-list
Re: Image.draft -- what are the modes that I can use?
Brett Hoerner wrote: > Are you sure you can't use VNC? An animated GIF based on full-screen > grabs will be amazingly huge and have very low color quality at the > same time. > > Installing VNC on Windows should take you about 30 seconds, honest. > > Or is this for some sort of project where you can't use anything but > CPython software...? > > Brett Hoerner the latter. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
Tim Chase wrote: > > How can I add two dictionaries into one? > > E.g. > > a={'a:1} > > b={'b':2} > > > > I need > > > > the result {'a':1,'b':2}. > > >>> a.update(b) > >>> a > {'a':1,'b':2} > > -tkc Thank you ALL for help. However It does not work as I would need. Let's suppose I have a={'c':1,'d':2} b={'c':2} but a.update(b) will make {'c': 2, 'd': 2} and I would need {'c': 3, 'd': 2} (because `c` is 1 in `a` dictionary and `c` is 2 in `b` dictionary, so 1+2=3) How can be done that? Thank you for the reply L -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
> However It does not work as I would need. > Let's suppose I have > > a={'c':1,'d':2} > b={'c':2} > but > a.update(b) > will make > {'c': 2, 'd': 2} > > and I would need > {'c': 3, 'd': 2} Ah...a previously omitted detail. There are likely a multitude of ways to do it. However, the one that occurs to me off the top of my head would be something like dict((k, a.get(k, 0) + b.get(k, 0)) for k in a.keys()+b.keys()) If the sets are huge, you can use itertools >>> from itertools import chain >>> dict((k, a.get(k, 0) + b.get(k, 0)) for k in chain(a.keys(),b.keys())) {'c': 3, 'd': 2} which would reduce the need for creating the combined dictionary, only to throw it away. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
Steven, Thank you for your reply and question. > > What should the result be if both dictionaries have the same key? The answer: the values should be added together and assigned to the key That is {'a':1, 'b':5} ( from your example below) Is there a solution? Thanks for the reply L. > > a={'a':1, 'b'=2} > b={'b':3} > > should the result be: > {'a':1, 'b'=2} # keep the existing value > {'a':1, 'b'=3} # replace the existing value > {'a':1, 'b'=[2, 3]} # keep both values > or something else? > > Other people have already suggested using the update() method. If you want > more control, you can do something like this: > > def add_dict(A, B): > """Add dictionaries A and B and return a new dictionary.""" > C = A.copy() # start with a copy of A > for key, value in B.items(): > if C.has_key(key): > raise ValueError("duplicate key '%s' detected!" % key) > C[key] = value > return C > > > -- > Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
Lad wrote: > Let's suppose I have > > a={'c':1,'d':2} > b={'c':2} > but > a.update(b) > will make > {'c': 2, 'd': 2} > > and I would need > {'c': 3, 'd': 2} > > (because `c` is 1 in `a` dictionary and `c` is 2 in `b` dictionary, so > 1+2=3) > > How can be done that? dict([(k, a.get(k, 0) + b.get(k,0)) for k in set(a.keys() + b.keys())]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for assignement operator
Bruno Desthuilliers wrote: > Tommi wrote: > (please don't top-post - corrected) >> >> Alexander Eisenhuth wrote: >>> Hello, >>> >>> is there a assignement operator, that i can overwrite? >>> >>> class MyInt: >>> def __init__(self, val): >>> assert(isinstance(val, int)) >>> self._val = val >>> >>> a = MyInt(10) >>> >>> # Here i need to overwrite the assignement operator >>> a = 12 >>> > >> Could the "traits" package be of help? >> >> http://code.enthought.com/traits/ > > How could it help ? It doesn't. (I am an Enthought developer.) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
Lad wrote: > The answer: the values should be added together and assigned to the key > That is > {'a':1, 'b':5} > ( from your example below) > > Is there a solution? have you tried coding a solution and failed, or are you just expecting people to code for free? -- http://mail.python.org/mailman/listinfo/python-list
Re: portable extensions options for external libraries
Alexandre Guimond wrote: > so my question is: what is the right way of specifying extensions > options (include_dirs, libraries, library_dirs) so that they are > portable between windows and linux? i'm thinking environment variables. The user can already use command-line options and CFLAGS if he so desires, so I wouldn't add any new environment variables. $ CFLAGS=-I/opt/local/include python setup.py build_ext -L/opt/local/lib > Though fairly easy to do, i was wondering if python/distutils provided > something more convenient, like searching through "common" directories, > though those aren't very standard on windows? distutils wouldn't do any searching at all. Your compiler will, though. > Optimally, i would like > to have something like: > > imaging = Extension( 'pyag.imaging._imaging', > sources = ( glob.glob( > 'Source/pyag/imaging/Src/*.cpp' ) + > glob.glob( > 'Source/pyag/imaging/Src/*.h' ) ), > include_dirs = ( get_numpy_include_dirs() + > [ 'Source/pyag/imaging/Src/' ] + > boost_include_dirs + > gsl_include_dirs ), > library_dirs = boost_library_dirs + > gsl_library_dirs, > libraries = boost_libraries + gsl_libraries ) That's pretty much how everyone else does it. Just make sure that boost_{include,library}_dirs and gsl_{include,library}_dirs are defined near the top of the file with suitable comments to draw attention to them. However, I might suggest making a setup.cfg with something like the following section (unindented): # Uncomment and modify the following section to configure the locations of the # Boost and GSL headers and libraries. #[build_ext] #include-dirs=/opt/local/include,/usr/local/include #library-dirs=/opt/local/lib,/usr/local/lib Changing data in a data file feels better to me than changing data in a program for some reason. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix Multiplication
David wrote: > Il 18 Oct 2006 04:17:29 -0700, Sssasss ha scritto: > > > hi evrybody! > > > > I wan't to multiply two square matrixes, and i don't understand why it > > doesn't work. > Can I suggest a little bit less cumbersome algorithm? > > def multmat2(A,B): > "A*B" > if len(A)!=len(B): return "error" # this check is not enough! > n = range(len(A)) > C = [] > for i in n: > C.append([0]*len(A)) # add a row to C > for j in n: > a = A[i]# get row i from A > b = [row[j] for row in B] # get col j from B > C[i][j] = sum([x*y for x,y in zip(a,b)]) > return C > > regards > D. This one is really nice, i didn't knew the zip function, thank you ciao -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix Multiplication
Roberto Bonvallet wrote: > Sssasss wrote: > > hi evrybody! > > > > I wan't to multiply two square matrixes, and i don't understand why it > > doesn't work. > > Could you explain me? > > > > def multmat(A,B): > >"A*B" > >if len(A)!=len(B): return "error" > > Wrong validation here: you _can_ multiply two matrices with a different > number of rows! And instead of returning "error" you should raise an > exception. > > [...] > > I suggest using a linear algebra package, but if you insist in using lists > of lists: > > >>> b = [[1, 2, 3, 4], > ... [4, 5, 6, 7], > ... [7, 8, 9, 10]] > >>> > >>> a = [[1, 2, 3], > ... [4, 5, 6]] > >>> > >>> ab = [[sum(i*j for i, j in zip(row, col)) for col in zip(*b)] for row in > >>> a] > >>> ab > [[30, 36, 42, 48], [66, 81, 96, 111]] > > Straightforward from the definition of matrix multiplication. > -- > Roberto Bonvallet Thank you, this one is very short! yes of course we can multiply different kinds of matrices, bu since I'm starting with python i started with something quick. ciao -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionaries
On Wed, 18 Oct 2006 09:31:50 -0700, Lad wrote: > > Steven, > Thank you for your reply and question. > >> >> What should the result be if both dictionaries have the same key? > The answer: the values should be added together and assigned to the key > That is > {'a':1, 'b':5} > ( from your example below) > > Is there a solution? Of course there is a solution. You just have to program it. Look again at my example code before: def add_dict(A, B): """Add dictionaries A and B and return a new dictionary.""" C = A.copy() # start with a copy of A for key, value in B.items(): if C.has_key(key): raise ValueError("duplicate key '%s' detected!" % key) C[key] = value return C Can you see how to modify this function to do what you want? (Hint: instead of raising a ValueError exception, you want to do something else.) -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to execute a linux command by python?
> > How to execute a linux command by python? > > for example: execute "ls" or "useradd oracle" > > Who can help me? > > start here: > > http://www.python.org/doc/lib/ > And continue here: http://www.python.org/doc/lib/os-process.html -- http://mail.python.org/mailman/listinfo/python-list
Help: Python2.3 & Python2.4 on RHEL4 x86_64
RHEL comes with Python2.3 installed. A program I need to install requires Python2.4 So I got Python2.4 from source and compiled it up. I configured it with --prefix=/usr --exec-prefix=/usr and --enable-unicode=ucs4 . I then make'd it and then make altinstall so that it didn't overwrite the /usr/bin/Python link to /usr/bin/Python2.3 . Well, for some reason, the arch dependent files did NOT get placed properly in /usr/lib64/Python2.4, they instead went to /usr/lib/Python2.4. Also, when I tried to load pysqlite: $ Python2.4 >>> from pysqlite2 import test I get the following traceback: Traceback (most recent call last): File "setup.py", line 24, in ? import glob, os, re, sys File "/usr/lib64/python2.3/glob.py", line 4, in ? import fnmatch File "/usr/lib64/python2.3/fnmatch.py", line 13, in ? import re File "/usr/lib64/python2.3/re.py", line 5, in ? from sre import * File "/usr/lib64/python2.3/sre.py", line 97, in ? import sre_compile File "/usr/lib64/python2.3/sre_compile.py", line 17, in ? assert _sre.MAGIC == MAGIC, "SRE module mismatch" AssertionError: SRE module mismatch This basically means to me that Python2.4 is loading gloab.py from /usr/lib64/Python2.3 insead of /usr/lib/Python2.4 (even thought I wanted to install the related files in /usr/lib64/Python2.4) Can someome please help! Respectfully, Christopher Taylor -- http://mail.python.org/mailman/listinfo/python-list