Re: a simple question about the third index in slice
someone wrote: > I cannot quite understand when the third index is a negative > number,like this: > a = '0123456789' > a[1:10:2] I know the index step is 2, so it will collect items from > offset 1, 3, 5, 7, 9 > but when a negative number come,like: > a[1::-1] answer '10', and a[1:10:-1] only answer '', > what is the different between the two expression, where does the offset > begin and what is the end offset? the default values for start and stop depend on the sign of the step. you can use the slice type directly to see how this works: >>> slice(None,None,1).indices(10) (0, 10, 1) >>> slice(None,None,-1).indices(10) (9, -1, -1) >>> slice(1,None,-1).indices(10) (1, -1, -1) >>> slice(1,10,-1).indices(10) (1, 10, -1) also see footnote 5 on this page: http://docs.python.org/lib/typesseq.html -- http://mail.python.org/mailman/listinfo/python-list
Re: classmethods, class variables and subclassing
> Andrew Jaffe wrote: > >> Hi, >> >> I have a class with various class-level variables which are used to >> store global state information for all instances of a class. These are >> set by a classmethod as in the following >> >> class sup(object): >> cvar1 = None >> cvar2 = None >> >> @classmethod >> def setcvar1(cls, val): >> cls.cvar1 = val >> >> @classmethod >> def setcvar2(cls, val): >> cls.cvar2 = val >> >> @classmethod >> def printcvars(cls): >> print cls.cvar1, cls.cvar2 >> >> Now, the problem comes when I want to subclass this class. If I >> override the setcvar1 method to do some new things special to this >> class, and then call the sup.setcvar1() method, it all works fine: >> >> class sub(sup): >> cvar1a = None >> >> @classmethod >> def setcvar1(cls, val, vala): >> cls.cvar1a = vala >> sup.setcvar1(val) >> >> @classmethod >> def printcvars(cls): >> print cls.cvar1a >> sup.printcvars() >> >> This works fine, and sets cvar and cvar2 for both classes. >> >> However, if I *don't* override the setcvar2 method, but I call >> sub.setcvar2(val) directly, then only sub.cvar2 gets set; it is no >> longer identical to sup.cvar1! >> >> In particular, >> sub.setcvar1(1,10) >> sub.setcvar2(2) >> sub.printcvars() >> prints >>10 >>1 None >> >> i.e. sub.cvar1, sub.cvar1a, sub.cvar2= 1 10 2 >> but sup.cvar1, cvar2= 1 None >> >> This behavior is "expected", but is it desirable? >> > > You are experiencing this problem because you are using hard-wired class > names. Try using (for example) self.__class__. That way, even if your > method is inheroted by a subclass it will use the class of the object it > finds itself a method of. No need to use classmethods. The problem is that I actually do want to call these methods on the class itself, before I've made any instances. A -- http://mail.python.org/mailman/listinfo/python-list
Re: reload fails if module not in sys.path
Lonnie Princehouse wrote: > Maybe it could fall back to module.__file__ if the module isn't found > in sys.path?? > ... or reload could just take an optional path parameter... > > Or perhaps I'm the only one who thinks this is silly: > > >>> my_module = imp.load_module(module_name, > >>> *imp.find_module(module_name,path)) > >>> reload(my_module) > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named whatever load_module doesn't do everything that import does. > I guess I could just deal with this by fiddling with sys.path or using > imp.load_module again, but.. um.. I like to complain. ;-) > > The context here is that I'm loading user-defined modules as plugins, > and I don't want to keep the plugin directory in sys.path because of > potential module name conflicts. so add the plugin-directory to the front of sys.path temporarily, and remove it after you've imported the plugins. (this also allows the plugin writers to split their plugins over multiple modules, something that can often be quite nice) -- http://mail.python.org/mailman/listinfo/python-list
a simple question about the third index in slice
I cannot quite understand when the third index is a negative number,like this: a = '0123456789' a[1:10:2] I know the index step is 2, so it will collect items from offset 1, 3, 5, 7, 9 but when a negative number come,like: a[1::-1] answer '10', and a[1:10:-1] only answer '', what is the different between the two expression, where does the offset begin and what is the end offset? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on class member in python
It looks like there isn't a last word of the differrences -- http://mail.python.org/mailman/listinfo/python-list
Re: Cursor Location
"Samantha" <[EMAIL PROTECTED]> wrote: > >Is there any code that would allow a person to click a location on the >screen and have that location saved for a future use? For example to imbed a >watermark on an image or text, etc. Getting the point is easy. If you are using wxPython, your EVT_LEFT_UP handler gets a mouse event as a parameter: def OnClick( self, evt ): print evt.GetPositionTuple() Once you have the tuple, it's up to you to save it somewhere. -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
RE: sqlstring -- a library to build a SELECT statement
Title: RE: sqlstring -- a library to build a SELECT statement Tim Roberts wrote: "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > > > >An Example: > > > import sqlstring > model = sqlstring.TableFactory() > print model.person > >SELECT > >person.* > >FROM > >[person] person > > The [bracket] syntax is unique to Microsoft. > Everyone else, including Microsoft SQL Server, > uses "double quotes" to protect special characters > in identifiers. Except MySQL (at least 4.1), which uses backticks. http://dev.mysql.com/doc/refman/4.1/en/legal-names.html Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing a dll from Python
"dcrespo" <[EMAIL PROTECTED]> wrote: > >Can someone give me lights on how can I deal with dlls from python? > >My main purpose is to get access to a Unitech PT600 Bar Code system. I >have the dll that works fine through Visual Basic. But I'm migrating to >Python, so I need a way to use the same dll, or a C library. > >I tried to access a dll created by myself on Visual Basic. The dll just >have one function. It works perfect when using it on a VB project just >including it in the references configuration. But I can't access it >from python. I tried the ctypes module. Are you talking about VB6 or VB.NET? If you had to add a reference, then it is either a COM interface or a managed code class. DLLs don't get in through references -- they use the Declare statement. COM interfaces are pretty easy to call in Python. Calling managed code is almost impossible right now. -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlstring -- a library to build a SELECT statement
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > >An Example: > import sqlstring model = sqlstring.TableFactory() print model.person >SELECT >person.* >FROM >[person] person The [bracket] syntax is unique to Microsoft. Everyone else, including Microsoft SQL Server, uses "double quotes" to protect special characters in identifiers. -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sequence and/or pattern matching
Sorry for the confusion, I think my example was unclear. Thank you Mike for this piece of code who solves a part of my problem. In fact, the sequences are unknown at the beginning, so the first part of the code has to find possible sequences and if those sequences are repeated, counts how many time they appear (as your code does). I have found this morning that there's a software produced by i2 software who does this kind of job, but for telephone call analysis. Maybe the description could help to better understand my goal : http://www.i2.co.uk/products/Pattern_Tracer/default.asp Séb -- http://mail.python.org/mailman/listinfo/python-list
Re: connect to https unpossible. Please help.
"Mark Delon" <[EMAIL PROTECTED]> wrote: > >i want to log via python script to https page: > >'https://brokerjet.ecetra.com/at/' ># >But it does not work. > >I am using following code(see below) > >Has somebody any ideas? >How can I get to this https page? >Need I to know some infos from "provider"(certificates, etc)? >Thank u very much ! You are trying to set this up to use HTTP BasicAuth authorization, but this page is not using HTTP authorization. You can recognize HTTP authorization by the separate browser window that pops up to ask for your username and password. In this case, the username and password fields are just ordinary fields on a form. What you need to do is read the HTTP on that page, and figure out how to send a URL containing values for those fields. In this case, the form data goes to https://brokerjet.ecetra.com/at/welcome/loginaction.phtml, and you'll need to encode 'login' and 'pwd' fields in the POST data. However, that isn't the end of your trouble. That page will almost certainly send you a cookie, which you will need to send back with every request. -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Expat - how to UseForeignDTD
I needed to set Entity Parsing, such as parser.SetParamEntityParsing( expat.XML_PARAM_ENTITY_PARSING_ALWAYS ) -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt vs extension written in C
Quoth "Tamas Nepusz" <[EMAIL PROTECTED]>: | No, that's actually a bit more complicated. The library I'm working on | is designed for performing calculations on large-scale graphs (~1 | nodes and edges). I want to create a Python interface for that library, | so what I want to accomplish is that I could just type "from igraph | import *" in a Python command line and then access all of the | functionalities of the igraph library. Now it works, except the fact | that if, for example, I start computing the diameter of a random graph | of ~10 nodes and ~20 edges, I can't cancel it, because the | KeyboardInterrupt is not propagated to the Python toplevel (or it isn't | even generated until the igraph library routine returns). I would like | to allow the user to cancel the computation with the usual Ctrl-C and | return to the Python interactive interface. | This whole feature is not vital, but it would mean a big step towards | user-friendliness. | I have access to the source code of igraph as well (since one of my | colleagues is developing it), so another possible solution would be to | inject some calls into the igraph source code which temporarily cancels | the computation and checks whether there's something waiting in the | Python interpreter, but I haven't found any function in the API which | allows me to do this. Hm, tough question. Even in C, this would be a little awkward. If you only wanted the program to abort on ^C, then you could just replace the default sigint handler with SIG_DFL. But then you'd be back to the shell prompt, not the python prompt. If you want to catch the signal, but also abort a computation, then as you say, the computation needs to check periodically. Rather than peek into Python for this, I'm wondering if your module could set its own signal handler for SIGINT, which would set a library flag. Then call PyErr_SetInterrupt(), to emulate the normal signal handler. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: TK question
thank you very much, I have one more question that is tk related, I've use tkfileopendialog or whatever that name is to select files is there also a dialog for creating files, well not really creating them but allowing the same look and feel as many porgrams give for saving files? is there also a way/dialog whereby a user can specify a directory (if the application wanted to save multiple files into a 'project' folder) Thanks agian for the quick and accurate response to my first question, a small follow-up.. is it considered bad style to include main methods(and if __name__== "__main__") in all user defined classes, I realize it's usefulness when testing individual classes. thanks very much Matt Totally aside PyDEV is so much better then trustudio it runs smooth and isn't such a resource hog.. not to mention free -- http://mail.python.org/mailman/listinfo/python-list
Re: fun with lambdas
Robert Kern <[EMAIL PROTECTED]> writes: > Juan Pablo Romero wrote: >> Hello! >> >> given the definition >> >> def f(a,b): return a+b >> >> With this code: >> >> fs = [ lambda x: f(x,o) for o in [0,1,2]] >> >> or this >> >> fs = [] >> for o in [0,1,2]: >> fs.append( lambda x: f(x,o) ) >> >> I'd expect that fs contains partial evaluated functions, i.e. >> >> fs[0](0) == 0 >> fs[1](0) == 1 >> fs[2](0) == 2 >> >> But this is not the case :( >> >> What is happening here? > > Namespaces. The functions are looking up o at runtime. In both cases, o > is bound to the last object in [0,1,2] once the iteration is finished. > > Try this (although I'm sure there are better ways): > > In [4]: fs = [lambda x, o=o: f(x, o) for o in [0,1,2]] > > In [5]: fs[0](0) > Out[5]: 0 > > In [6]: fs[0](1) > Out[6]: 1 > > In [7]: fs[0](2) > Out[7]: 2 Right explanation. Right solution. Wrong examples. He wanted to see: >>> fs[0](0) 0 >>> fs[1](0) 1 >>> fs[2](0) 2 >>> List comprehensions were purposely designed to mimic for loops, which (unlike other languages) don't create a new variable for each pass through the loop. ((They also "leak" the variable to the surrounding namespace.) So you need to capture the current value of the loop index somewhere. An alternative (and maybe slightly cleaner) method is: >>> def makef(a): ... return lambda b: a + b ... >>> fs = [makef(o) for o in [0, 1, 2]] >>> fs[0](0) 0 >>> fs[1](0) 1 >>> fs[2](0) 2 >>> Generator comprehensions have the same issue: >>> fs = list(lambda x: f(o, x) for o in [0, 1, 2]) >>> fs[0](0) 2 >>> fs[1](0) 2 >>> fs[2](0) 2 >>> http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: fun with lambdas
You are asking it to return a list of lambda, not its evaluated value. map(lambda x: f(x,0), [0,1,2]) works. [ f(o) for o in [0,1,2] ] works too. Juan Pablo Romero wrote: > Hello! > > given the definition > > def f(a,b): return a+b > > With this code: > > fs = [ lambda x: f(x,o) for o in [0,1,2]] > > or this > > fs = [] > for o in [0,1,2]: > fs.append( lambda x: f(x,o) ) > > I'd expect that fs contains partial evaluated functions, i.e. > > fs[0](0) == 0 > fs[1](0) == 1 > fs[2](0) == 2 > > But this is not the case :( > > What is happening here? > > > Nevertheless, this code does work > > fs = [ eval("lambda x: f(x,%d)" % o) for o in [0,1,2,3]] > > Thanks. > >Juan Pablo -- http://mail.python.org/mailman/listinfo/python-list
Re: fun with lambdas
Juan Pablo Romero wrote: > Hello! > > given the definition > > def f(a,b): return a+b > > With this code: > > fs = [ lambda x: f(x,o) for o in [0,1,2]] > > or this > > fs = [] > for o in [0,1,2]: > fs.append( lambda x: f(x,o) ) > > I'd expect that fs contains partial evaluated functions, i.e. > > fs[0](0) == 0 > fs[1](0) == 1 > fs[2](0) == 2 > > But this is not the case :( > > What is happening here? Namespaces. The functions are looking up o at runtime. In both cases, o is bound to the last object in [0,1,2] once the iteration is finished. Try this (although I'm sure there are better ways): In [4]: fs = [lambda x, o=o: f(x, o) for o in [0,1,2]] In [5]: fs[0](0) Out[5]: 0 In [6]: fs[0](1) Out[6]: 1 In [7]: fs[0](2) Out[7]: 2 -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
fun with lambdas
Hello! given the definition def f(a,b): return a+b With this code: fs = [ lambda x: f(x,o) for o in [0,1,2]] or this fs = [] for o in [0,1,2]: fs.append( lambda x: f(x,o) ) I'd expect that fs contains partial evaluated functions, i.e. fs[0](0) == 0 fs[1](0) == 1 fs[2](0) == 2 But this is not the case :( What is happening here? Nevertheless, this code does work fs = [ eval("lambda x: f(x,%d)" % o) for o in [0,1,2,3]] Thanks. Juan Pablo -- http://mail.python.org/mailman/listinfo/python-list
Re: TK question
Forgot to answer the "better" part: class optFrame(Frame): def __init__(self, *args, **kwargs): Frame.__init__(self, *args, **kwargs) self.pack() self.make_widgets() def make_widgets(self): """ Put widgets here. """ pass def main(): tk = Tk() optWin = optFrame(tk) tk.mainloop() if __name__ == "__main__": main() James On Thursday 20 October 2005 19:16, MBW wrote: > I have a class that is a windows in a GUI > > the following is the code: > > class optWin: > > def __init__(self): > return None > > def __call__(self): > self.root = tk() > self.root.title("My title") > self.root.mainloop() > return None > > 1)Why doesn't this work when I go to call optWin > 2)What is a better way to do this > > Thanks in advance -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: TK question
optWin() will create a callable object which is an instance of the class optWin. Calling this callable object will call the __call__() method with the behavior you anticipate. You also need to import Tk from Tkinter and call Tk "Tk" and not "tk". Meditate on the following : from Tkinter import * class optWin: def __init__(self): return None def __call__(self): self.root = Tk() self.root.title("My title") self.root.mainloop() return None ow = optWin() ow() James On Thursday 20 October 2005 19:16, MBW wrote: > class optWin: > > def __init__(self): > return None > > def __call__(self): > self.root = tk() > self.root.title("My title") > self.root.mainloop() > return None -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Execute C code through Python
import subprocess subprocess.call("cmd") -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: > I am not sure your intention but I think there isn't a one language > fits all situation here. Very true. > C/C++ - for linux kernel hacking etc., many library out there still use > it > python - generic stuff > SQL - nothing beats it for many business apps > haskell - a language to train my brain > javascript - Web front end > > other than haskell and SQL, the others are more or less the same to me > so getting familiar with them is not too difficult. There are actually lots of good "train your brain" type languages. Members of the LISP family, for instance, to learn what you can do with lists, and also for how cool a real macro facility can be. I happen to like Scheme, but that's just me. APL, for learning you can do with arrays. SNOBOL for old-school string processing and pattern matching. Icon for what you can do with failure. Eiffel for what you can do with objects and DbC. CLU for duck typing with declerations. Prolog for what you can do without writing commands. Oz includes a nice combination of a lot of these things. The best ones have a book associated with them that teaches general programming practices using said language as an example - and hopefully does a good job of it. I've only got four of those: Scheme: Structure and Interpretation of Computer Programs, by Abelson, Sussman and Sussman. Commonly called SICP. Available online at http://mitpress.mit.edu/sicp/full-text/book/book.html >. Oz: Concepts, Techniques and Models of Computer Programming, by Van Roy and Haridi. Sometimes shortened to "The Oz book." Read more about it at http://www2.info.ucl.ac.be/people/PVR/book.html >. Eiffel: Object Oriented Software Construction, by Bertrand Meyer. Referred to as OOSC. Read more about it at http://archive.eiffel.com/doc/oosc/ >. LISP: On LISP, by Paul Graham. Download it at http://www.paulgraham.com/onlisp.html >. The first three are books about programming that happen to use a specific language that supports the techniques the authors want to discuss. On LISP on the other hand is more about what's unique about LISP programming, at least when compared to more conventional languages. A lot of what's good about LISP is also good about Python, so a lot of what he has to say carries over into Python. It's also the only place to get a thorough look at LISP macro programming, which knowledge does *not* carry over into Python - but you'll understand why people ask for macros in Python :-). If you know of some book/language pair that you think everyone would benefit from reading, I'd be interested in hearing about them. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
TK question
I have a class that is a windows in a GUI the following is the code: class optWin: def __init__(self): return None def __call__(self): self.root = tk() self.root.title("My title") self.root.mainloop() return None 1)Why doesn't this work when I go to call optWin 2)What is a better way to do this Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft Hatred FAQ
"Mike Schilling" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > An employee who refuses to act as directed, claiming that he's thinking of > the shareholders' interests, can be fired for cause. His only recourse > would be to become a shareholder (not hard), and then get the attention of > either the board or a large block of shareholders (much harder). If > management is actually breaking the law (say by Enron-like looting) rather > than simply making decisions he considers suboptimal, he can also go to > the authorities, but he does this in his capacity as private citizen; his > status as employee gives him no additional rights or responsibilities in > this respect. A shareholder (whether employee or not) who feels that management is not acting in the interests of all shareholders can file a derivative action (a form of lawsuit). This is supposed to prevent management for acting in the interests of the larger shareholders at the expense of the smaller ones. (Which is really easy if more than half the stock is owned by a single entity.) DS -- http://mail.python.org/mailman/listinfo/python-list
DBM scalability
I'm trying to create a dbm database with around 4.5 million entries but the existing dbm modules (dbhash, gdbm) don't seem to cut it. What happens is that the more entries are added, the more time per new entry is required, so the complexity seems to be much worse than linear. Is this to be expected and if so, should I expect better performance (i.e. linear or almost linear) from a real database, e.g. sqlite ? George -- http://mail.python.org/mailman/listinfo/python-list
os.makedirs should not succeed when the directory already exists (was Re: Python Doc Error: os.makedirs)
On Wed, Oct 19, 2005 at 09:26:16AM -0700, Dr. Who wrote: > The fact that the directory already exists is irrelevant to the function...it > still failed to create the directory. That's not true. Imagine that os.makedirs() is used inside tempfile.mkdtemp() (I looked, and it isn't) and the proposed behavior (do not raise an exception when the directory already exists) is adopted. In this case, there is a race condition between you and the attacker who guesses the next directory you will attempt to make. If he calls mkdir() before you do, then your os.makedirs() returns successfully (instead of raising an exception) and you place your files into a location that is under the control of someone else. If the attacker then makes the directory setuid himself, that files created in the directory are owned by him. Now, he can view and change the contents of these files. This can lead to a local priviledge escalation. Errors should never pass silently. Unless explicitly silenced. -- from the Zen of Python ('import this') ... and wanting them to do so may introduce a security bug in your software. If you know more about your users and their environments than I do (for instance, that none of them will ever use a multi-user computer system) maybe you should choose to wrap os.makedirs with something that silences EEXIST. But I'm glad Python does the secure thing and treats EEXIST as a failure by default. Jeff pgpWhf794NILT.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: nested escape chars in a shell command
I think you're mistaken about how 'sh -c' works. The next argument after "-c" is the script, and following arguments are the positional arguments. (what, you've never used -c in conjunction with positional arguments? me either!) Example: $ /bin/sh -c 'echo $#' a b c # i.e., a blank line $ /bin/sh -c 'echo $# 0=$0 1=$1 2=$2' a b c 2 0=a 1=b 2=c # i.e., a, b, c went to positional arguments Additionally, unless pexpect.spawn behaves differently than os.spawnv, "-c" is actually going to /bin/sh's argv[0], and you end up trying to execute /usr/bin/ssh as a shell script, which is probably not what you want! def shellquote(arg): # shell quoting technique I first read about on the 'git' development list # Everything is safely quoted inside a ''-quoted string, except a ' itself, # which can be written as '\'' (a backslash-escaped ' outside of the ''-quoted # string) return "'" + arg.replace("'", "'\\''") + "'" def shellquotelist(args): return " ".join([shellquote(arg) for arg in args]) # XXX: you may wish to assemle 'command' using shellquotelist too command1 = shellquotelist(['/bin/sh', '-c','/usr/bin/ssh','-t','-o', 'StrictHostKeyChecking no',host,command]) command2 = shellquotelist(['awk','{print %s:$0}'%host]) child = \ pexpect.spawn('/bin/sh', args=['/bin/sh', '-c', command1 + "|" + command2], timeout=30) Finally, in your case the use of awk would seem to be gratuitous. Instead, prepend the hostname to each line when you read the lines in. (this could easy or hard depending on the structure of the code where you read the output generated by child---if you do it with readline() or by iterating over the file, it is probably easy) Jeff pgp6UVusIacVl.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
I don't think you really need to give to much time in weighting between python or Ruby. Both are fine. But Python has the obvious advantage that it has much more modules than Ruby so many things you don't need to implement if you have real work to do. I recommend you give haskell a shot if you are "in" to programming because it makes you think differently, not necessary better(at least not all the time) but helps. I am not sure your intention but I think there isn't a one language fits all situation here. I frequently use the following: C/C++ - for linux kernel hacking etc., many library out there still use it python - generic stuff SQL - nothing beats it for many business apps haskell - a language to train my brain javascript - Web front end other than haskell and SQL, the others are more or less the same to me so getting familiar with them is not too difficult. Amol Vaidya wrote: > I've done a lot of studying on my own, and taken the classes that my > high-school offers. I feel that I have a fairly good understanding of Java, > and basic OO concepts due to that. I've created some semi-complex programs > in java, in my opinion, such as networked checkers, 8-player blackjack, a > space-shooter type game, a copy of mario (one level, anyway), and some other > stuff. I've also done a bit of studying on C. I've done a few projects in C, > including another space-shooter type of game using SDL, an IRC client and > some simple database-type programs. I also gave a shot at assembly using > NASM for x86 before, but didn't get too far. I wrote some trivial code -- > wrote to the video buffer, played with some bios interrupts, stuff like > that. The only thing I did in assembly was create a program that loads at > boot-up, and loads another program that just reiterates whatever you type > in. I only did that because I was curious. That's about as far as my > programming knowledge/experience goes. > > Well, I'm not sure what you mean by programming concepts. I'm familiar with > OO through Java, and procedural programming through C. I'd be more detailed, > but I'm not exactly sure what you are asking. Sorry. > > I have no idea what Scheme is, but I'll cettainly look it up as soon as I'm > done writing this. > > I've never given Perl a shot. It was another language I considered learning, > but my father's friend told me to go with Python or Ruby. > > Thanks for your help. Hopefully I wasn't too lengthy in this post. -- http://mail.python.org/mailman/listinfo/python-list
Re: reload fails if module not in sys.path
Lonnie Princehouse wrote: > So, it turns out that reload() fails if the module being reloaded isn't > in sys.path. > > Maybe it could fall back to module.__file__ if the module isn't found > in sys.path?? > ... or reload could just take an optional path parameter... > > Or perhaps I'm the only one who thinks this is silly: > > my_module = imp.load_module(module_name, *imp.find_module(module_name,path)) reload(my_module) > > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named whatever > You appear to have failed to load some module called "whatever", which I presume is the value of module_name? > > I guess I could just deal with this by fiddling with sys.path or using > imp.load_module again, but.. um.. I like to complain. ;-) > That's OK, but you may find fiddling with sys.path is more productive :-) > The context here is that I'm loading user-defined modules as plugins, > and I don't want to keep the plugin directory in sys.path because of > potential module name conflicts. > Hmm. I know that if your module isn't in sys.modules your reload will fail: >>> import trPyCard # picking a moduule at random >>> import sys >>> del sys.modules['trPyCard'] >>> reload(trPyCard) Traceback (most recent call last): File "", line 1, in ? ImportError: reload(): module trPyCard not in sys.modules >>> Apart from that, it would seem sensible not to try and use reload if you haven't used a kosher import mechanism - there are many caveats on the reload() documentation, and the mechanisms it uses aren't spelled out anywhere but in the interpreter source. It would seem easier just to ensure that the plugins directory(ies) appear first on sys.path and use __import__(). imp is high magic. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlstring -- a library to build a SELECT statement
> person ** ( > (person.type_id == 'customer') > & (person.id %= phone(phone.person_id))) > ) > Nevermind. This doesn't work because all of the X= operators in question are assignment operators, and therefore generate a Syntax Error if in a nested expression. I think I've settled on just doing a table.column.IN(blah) syntax. This should be obvious to anyone reading the code, and doesn't require mangling of the name (since it's capitalized). Then we'd have similar functions for other non intuitive things, such as LIKE, EXISTS (on the table) and even a WHERE: person.WHERE( (person.type_id == 'customer') & (person.id.IN(phone(phone.person_id))) ) -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlstring -- a library to build a SELECT statement
Tom Anderson wrote: > On Thu, 20 Oct 2005, [EMAIL PROTECTED] wrote: > > > On this line of thought, what about the += operator? That might be more > > intuative than //. I could even use -= for not in. > > You're going to have to explain to me how using an assignment operator for > something other than assignment is intuitive! > > -1 on this one from me, i'm afraid. Point. I do think it looks strange, because we're used to seeing += in code. But the concept is more along the lines of the == and != comparison operators. Python does expose other nice things, such as &= and %=, which (since people aren't used to seeing them used much), might be better candidates. Does %= seem more agreeable? (I'm already using % for a like statement). So, a statement could look like this: person ** ( (person.type_id == 'customer') & (person.id %= phone(phone.person_id))) ) becomes: select * from person where person.type_id = 'customer' and person.id in (select person_id from phone) > Using 'in' would be good. It does require some truly puke-inducing > contortions, though; since 'in' calls __contains__ on the right-hand > operand, and that's likely to be a list, or some other type that's not > under your control, you have to cross your fingers and hope that whatever > it is implements __contains__ with equality tests with the probe object on > the left-hand side and the candidates on the right (as lists do, at least > in 2.4.1). then, you just have to make your table names do the right thing > when compared to strings. > __contains__, while allowing side-effects on the object in question (even if though it's on the right), only returns true/false (not a custom object) afaik, so it breaks in a complex expression -- (a == b) & (c in d), won't work. You could modify D, but you can't pass that value to the whole Condition Expression. -- http://mail.python.org/mailman/listinfo/python-list
reload fails if module not in sys.path
So, it turns out that reload() fails if the module being reloaded isn't in sys.path. Maybe it could fall back to module.__file__ if the module isn't found in sys.path?? ... or reload could just take an optional path parameter... Or perhaps I'm the only one who thinks this is silly: >>> my_module = imp.load_module(module_name, *imp.find_module(module_name,path)) >>> reload(my_module) Traceback (most recent call last): File "", line 1, in ? ImportError: No module named whatever I guess I could just deal with this by fiddling with sys.path or using imp.load_module again, but.. um.. I like to complain. ;-) The context here is that I'm loading user-defined modules as plugins, and I don't want to keep the plugin directory in sys.path because of potential module name conflicts. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fund raising for SPE (Python IDE) on Mac Os X is great success!!
Dear Stani, It is good to hear that the donation was a success. And you deserve it, your contribution to the Python community is an example fot others and I am convinced that every donation, be it large or small, is well spent! A lot of us use SPE, don't we? greetz, DimitriOn 20 Oct 2005 12:38:04 -0700, SPE - Stani's Python Editor <[EMAIL PROTECTED]> wrote: Hi,I'd like to thank everyone who contributed, especially Richard Brownfrom Dartware and Rick Thomas. I'm highly impressed that the smallest user base of SPE collected the largest donation ever to SPE. Now it'smy turn to impress the SPE Mac users.As such the light is green for SPE on the Mac. First I will buy a Macand get used to it. Then I will optimize SPE for the Mac and try to release simultaneously. Be patient as this will take some time. Thenext releases (0.7) will be based on work I did before. But from 0.8releases SPE will also be tested & developed on Mac.Please subscribe to the mailing list as a developer, user and/or mac user. Of course donations are still welcome.Stanihttp://pythonide.stani.behttp://pythonide.stani.be/manual/html/manual.html --http://mail.python.org/mailman/listinfo/python-list-- "Some scientists claim that hydrogen, because it is so plentiful, is the basic building block of the universe. I dispute that. I say there is more stupidity than hydrogen, and that is the basic building block of the universe."-Frank Zappa-Please visit dimitri's website: www.serpia.com -- http://mail.python.org/mailman/listinfo/python-list
http/urlib pos/get question (newbie)
Hi, (I am _very_ new to web programming) I am writing a client module (browser plugin) and server module (Python CGI) that need to exchange information. I want the transaction to be intiated when the client accesses the link. I need data to go back and forth between the client and the server (cgi script) with no impact on what the browser shows. In the end (when I get the above to work), the server will say OK and the actual page will appear or NOK and an ERROR page will appear. I'm pretty clear (I think) as to what to do on the javascript (client) side (XMLHttp) but am not certain if my cgi script must "urlib.open" its own link in order to open the pipe on its side (there'll be some HTML GET/POST tag I assume but where is the pipe/socket ?) Thanks, Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt vs extension written in C
No, that's actually a bit more complicated. The library I'm working on is designed for performing calculations on large-scale graphs (~1 nodes and edges). I want to create a Python interface for that library, so what I want to accomplish is that I could just type "from igraph import *" in a Python command line and then access all of the functionalities of the igraph library. Now it works, except the fact that if, for example, I start computing the diameter of a random graph of ~10 nodes and ~20 edges, I can't cancel it, because the KeyboardInterrupt is not propagated to the Python toplevel (or it isn't even generated until the igraph library routine returns). I would like to allow the user to cancel the computation with the usual Ctrl-C and return to the Python interactive interface. This whole feature is not vital, but it would mean a big step towards user-friendliness. I have access to the source code of igraph as well (since one of my colleagues is developing it), so another possible solution would be to inject some calls into the igraph source code which temporarily cancels the computation and checks whether there's something waiting in the Python interpreter, but I haven't found any function in the API which allows me to do this. Tamas -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
On Thu, 20 Oct 2005, Amol Vaidya wrote: > "Casey Hawthorne" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > >> What languages do you know already? What computer science concepts do >> you know? What computer programming concepts do you know? Have you >> heard of Scheme? Good questions! >> Ruby is a bit Perl like -- so if you like Perl, chances are you might >> like Ruby. I don't think rubyists would appreciate that description. Ruby may be heavier on the funky symbols than python, but it's a very clean, elegant, usable, well-thought-out and deeply object-oriented language - in other words, nothing at all like perl. >> Python is more like Java. Python is *nothing* like java. >> I have heard, but have not been able to verify that if a program is >> about >> 10,000 lines in C++ >> it is about >> 5,000 lines in Java >> and it is about >> 3,000 lines in Python (Ruby to?) ITYM 300. Yes, ruby too. > I've done a lot of studying on my own, and taken the classes that my > high-school offers. I feel that I have a fairly good understanding of > Java, and basic OO concepts due to that. I've created some semi-complex > programs in java, in my opinion, such as networked checkers, 8-player > blackjack, a space-shooter type game, a copy of mario (one level, > anyway), and some other stuff. I've also done a bit of studying on C. > I've done a few projects in C, including another space-shooter type of > game using SDL, an IRC client and some simple database-type programs. I > also gave a shot at assembly using NASM for x86 before, but didn't get > too far. I wrote some trivial code -- wrote to the video buffer, played > with some bios interrupts, stuff like that. The only thing I did in > assembly was create a program that loads at boot-up, and loads another > program that just reiterates whatever you type in. I only did that > because I was curious. That's about as far as my programming > knowledge/experience goes. An excellent start! > Well, I'm not sure what you mean by programming concepts. I'm familiar > with OO through Java, and procedural programming through C. I'd be more > detailed, but I'm not exactly sure what you are asking. Sorry. I think i know what Casey means, but i don't know if i can explain it any better. Do you understand the concept orthogonality? The Once And Only Once principle? Have you ever heard of design patterns? > I have no idea what Scheme is, but I'll cettainly look it up as soon as > I'm done writing this. You won't like it. Give yourself another 5-10 years, and you might start to find it strangely intriguing. > I've never given Perl a shot. It was another language I considered > learning, but my father's friend told me to go with Python or Ruby. Your father has good friends. > Thanks for your help. Hopefully I wasn't too lengthy in this post. Lengthy is fine! Anyway, the upshot of all this is that, yes, you should learn python. Python is dope! tom -- NOW ALL ASS-KICKING UNTIL THE END -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt vs extension written in C
Tamas Nepusz wrote: > Hi everyone, > > I have tried to do some googling before asking my question here, but I > haven't found any suitable answer. I am developing a Python API for a > graph library written in pure C. The library is doing an awful lot of > math computations, and some of them can take a pretty long time > (depending on the size of the input). If I invoke such calculation from > Python using my own extension, the interpreter locks until the > calculation is complete (I mean, it is not responding to Ctrl-C or > SIGINT). > > My question is: is there any way to allow the user to use Ctrl-C to > generate a KeyboardInterrupt and cancel such large computations? I'm > assuming that although pressing Ctrl-C may generate a KeyboardInterrupt > in Python, it is not propagated to the user level until the call into > the graph library returns. I tried to add Py_BEGIN_ALLOW_THREADS before > the call to the underlying C library and Py_END_ALLOW_THREADS after > returning from it, but I had no luck. I'm not especially an expert with C-extensions. So I'm not sure if I can be of any help here. But if what you really are after is "only" terminating the whole program (instead of just the computation, and then continue), you might consider threads. Do the calls in a separate thread, and make that a daemon-thread. Then things _should_ work as expected, as the main thread will receive the signal. Hopefully... if your call releases the GIL. Which Py_*_ALLOW_THREADS seems to do. So - give it a try :) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Beginning Python (Practical Python 2.0)
I found this book at my local Border's this week. It appears to be a most excellent book. I own and have read Magnus' earlier book "Pactical Python" (which was excellent) but this one is even better. The first half of the book covers the language, and then the second half goes into depth developing several practical applications. And of course now the book is very up to date. While I obviously have not had time to really study this book, I believe that anyone looking for an introduction to Python would be very hard pressed to find a better choice than this book. Ron Stephens Python411 podcast sereis http://www.awaretek.com/python/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft Hatred FAQ
"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > On Thu, 20 Oct 2005 13:17:14 +, axel wrote: > >> Employees have *no* obligations towards the shareholders of a company. >> They are not employed or paid by the shareholders, they are employed >> by the company itself which is a separate legal entity. >> >> It is a different matter for the board of directors of a company. > > The board of directors are also employees of the company. That's why the > company can fire them. The relationships are a bit more complex than that: The shareholders elect a Board of Directors to represent their interests. The board then hires a management staff, which reports to them. The management staff hires other employees, who report (directly or indirectly) to management. An employee who refuses to act as directed, claiming that he's thinking of the shareholders' interests, can be fired for cause. His only recourse would be to become a shareholder (not hard), and then get the attention of either the board or a large block of shareholders (much harder). If management is actually breaking the law (say by Enron-like looting) rather than simply making decisions he considers suboptimal, he can also go to the authorities, but he does this in his capacity as private citizen; his status as employee gives him no additional rights or responsibilities in this respect. As Axel says, a regular employee has no direct obligations towards the shareholders. -- http://mail.python.org/mailman/listinfo/python-list
Re: Popularity of blogging tools used by python programmers
You might also consider Firedrop2, (see http://www.voidspace.org.uk/python/weblog/arch_d7_2005_10_15.shtml#e119 ) , a client side blog creation and content management system created by Hans Nowak and now being enhnaced and maintained by Michael Foord. Its very pythonic and extensable. Ron Stephens Python411 podcast sereis http://www.awaretek.com/python/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Execute C code through Python
Ernesto wrote: > What's the easiest and quickest way to execute a compiled C "command > line interface" program THROUGH Python? I don't know what you mean by THROUGH. But the subprocess, popen2 and os-modules deal with calling other programs. Try them in that order. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Set operations for lists: pythonic hints please!
[EMAIL PROTECTED] wrote: > Working with several thousand tagged items on a Tkinter Canvas, I want > to change different configurations of objects having a certain group of > tags. > > I've used the sets module, on the tuple returned by Tkinter.Canvas. > find_withtag() method. > > Since this method takes only one tag at time, I use it for each tag > that is part of the look-up group, create a set object for each tuple > and intersect the resulting sets, that I tuple out again to feed a loop > to change the configuration of the items. > > Anyone have a more pythonic way (or better performing ) way to suggest > ? It depends. If the search on tags is implemented linear, it might be better to loop over all items and filter suing a compound predicate, like this: rouge_artefacts = [item for m1.all_itmes() if item.has_tag("rouge") and item.has_tag("artefact")] Please note that I don't know TKinter's API, but I can't imagine that it lacks the possibility to fettch a list of all items and query an item for it tags. The synopsis may vary from above, thogh. But if tkinter stores the tagged items as mapping of tag -> set/list, then I think your approach is as fast as you can get. Time it out. And maybe another thing would be to manage that tagging relation yourself. Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Execute C code through Python
What's the easiest and quickest way to execute a compiled C "command line interface" program THROUGH Python? -- http://mail.python.org/mailman/listinfo/python-list
network installations
Hi All - I am working on a project that requires Python be installed on multiple Windows servers. I was wondering if anyone knew of a method/utility/script that can push the installation of Python to multiple networked servers from a centralized location. Thanks in advance! -shawn begin:vcard fn:Shawn Kelley n:Kelley;Shawn org:Oracle Corp.;Server Technologies adr:Suite 700;;111 Congress Ave;Austin;TX;78701;USA email;internet:[EMAIL PROTECTED] title:Senior Technologist tel;work:512.703.4708 tel;fax:512.703.4708 tel;cell:512.921.2970 x-mozilla-html:TRUE url:http://www.oracle.com version:2.1 end:vcard -- http://mail.python.org/mailman/listinfo/python-list
Re: A macro editor
On Thu, 20 Oct 2005, Diez B. Roggisch wrote: > So - _I_ think the better user-experience comes froma well-working easy > to use REPL to quickly give the scripts a try. I'd agree with that. Which is better, a difficult language with lots of fancy tools to help you write it, or an easy language? I don't know Groovy, but having looked at some examples, it looks like jave with a makeover, which, compared to python, sounds like a difficult language. As for python vs ruby, i can't really offer any insights on the languages themselves. Personally, i'd go for python, but that's because i know python and not ruby. tom -- NOW ALL ASS-KICKING UNTIL THE END -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlstring -- a library to build a SELECT statement
On Thu, 20 Oct 2005, Pierre Quentel wrote: [EMAIL PROTECTED] a écrit : My solution is sqlstring. A single-purpose library: to create SQL statement objects. With the same starting point - I don't like writing SQL strings inside Python code either - I have tested a different approach : use the Python list comprehension / generator expression syntax for the select requests For instance : s = query(r.name for r in planes if r.speed > 500) for item in s: print s query is a class whose instances are created with the generator expression as argument. The matching SQL request is built in the __init__ method, here : SELECT r.name FROM planes AS r WHERE r.speed > 500 That, sir, is absolute genius. Evil as fuck, but still absolute genius. tom -- NOW ALL ASS-KICKING UNTIL THE END-- http://mail.python.org/mailman/listinfo/python-list
Re: sqlstring -- a library to build a SELECT statement
On Thu, 20 Oct 2005, [EMAIL PROTECTED] wrote: > On this line of thought, what about the += operator? That might be more > intuative than //. I could even use -= for not in. You're going to have to explain to me how using an assignment operator for something other than assignment is intuitive! -1 on this one from me, i'm afraid. Using 'in' would be good. It does require some truly puke-inducing contortions, though; since 'in' calls __contains__ on the right-hand operand, and that's likely to be a list, or some other type that's not under your control, you have to cross your fingers and hope that whatever it is implements __contains__ with equality tests with the probe object on the left-hand side and the candidates on the right (as lists do, at least in 2.4.1). then, you just have to make your table names do the right thing when compared to strings. It's a shame (sort of) that you can't define entirely new operators in python. What we need is a __operate__(self, op, arg) special method, so you could do: >>> class Operable: ... def __operate__(self, op, arg): ... print "operating with", op, "on", arg ... >>> o = Operable() >>> o <~> "foo" operating with <~> on foo I'm sure that would do *wonders* for program readability :). tom -- NOW ALL ASS-KICKING UNTIL THE END -- http://mail.python.org/mailman/listinfo/python-list
Re: classmethods, class variables and subclassing
Andrew Jaffe wrote: > Hi, > > I have a class with various class-level variables which are used to > store global state information for all instances of a class. These are > set by a classmethod as in the following (in reality the setcvar method > is more complicated than this!): > > class sup(object): > cvar1 = None > cvar2 = None > > @classmethod > def setcvar1(cls, val): > cls.cvar1 = val > > @classmethod > def setcvar2(cls, val): > cls.cvar2 = val > > @classmethod > def printcvars(cls): > print cls.cvar1, cls.cvar2 > > > I can then call setcvar on either instances of the class or the class > itself. > > Now, the problem comes when I want to subclass this class. If I > override the setcvar1 method to do some new things special to this > class, and then call the sup.setcvar1() method, it all works fine: > > class sub(sup): > cvar1a = None > > @classmethod > def setcvar1(cls, val, vala): > cls.cvar1a = vala > sup.setcvar1(val) > > @classmethod > def printcvars(cls): > print cls.cvar1a > sup.printcvars() > > This works fine, and sets cvar and cvar2 for both classes. > > However, if I *don't* override the setcvar2 method, but I call > sub.setcvar2(val) directly, then only sub.cvar2 gets set; it is no > longer identical to sup.cvar1! > > In particular, > sub.setcvar1(1,10) > sub.setcvar2(2) > sub.printcvars() > prints >10 >1 None > > i.e. sub.cvar1, sub.cvar1a, sub.cvar2= 1 10 2 > but sup.cvar1, cvar2= 1 None > > since sup.cvar2 has never been set, and this is what sup.printcvars() > looks for. > > This behavior is "expected", but is it desirable? > > For my application, at least, I think the problem really comes in the > printcvars method: is there any way to call the overridden > sup.printcvars() but with, effectively, cls=sub? > > Thanks for reading this far! > > Andrew > > > Andrew > > > > > This seems like a bug > > Is this expected behavior, or a bug (or both -- it is expected but > probably not what is wanted!)? You are experiencing this problem because you are using hard-wired class names. Try using (for example) self.__class__. That way, even if your method is inheroted by a subclass it will use the class of the object it finds itself a method of. No need to use classmethods. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
newbie question about SocketServer
Is it just me or do the server_close() methods do squat? I'm primarily working with a ThreadingTCPServer object and trying to create a simple server that can shut itself down. But even simplest cases don't seem to work. Admittedly I am trying it from within my handler class, but for some odd reason, the server is allways willing to handle one more request before dying. Then it dies. -- http://mail.python.org/mailman/listinfo/python-list
Re: Set operations for lists: pythonic hints please!
Ouppsss! the title should have read:Set operation for tuples... (sigh!) -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft Hatred FAQ
On comp.os.linux.misc, in <[EMAIL PROTECTED]>, "Tim Slattery" wrote: Three OS's from corporate kings in their towers of glass, Seven from valley lords where orchards used to grow, Nine from dotcoms doomed to die, One from the Dark Lord Gates on his dark throne In the Land of Redmond where the Shadows lie. One OS to rule them all, one OS to find them, One OS to bring them all and in the darkness bind them, In the Land of Redmond where the Shadows lie. -- http://mail.python.org/mailman/listinfo/python-list
Set operations for lists: pythonic hints please!
Working with several thousand tagged items on a Tkinter Canvas, I want to change different configurations of objects having a certain group of tags. I've used the sets module, on the tuple returned by Tkinter.Canvas. find_withtag() method. Since this method takes only one tag at time, I use it for each tag that is part of the look-up group, create a set object for each tuple and intersect the resulting sets, that I tuple out again to feed a loop to change the configuration of the items. Anyone have a more pythonic way (or better performing ) way to suggest ? Thanks in advance, Jean-Marc # My test code # the code is not generic here # my question only pertains to the intersection algorithm perse from Tkinter import * import random, sets root=Tk() m1 = Canvas(root,width=410,height=410) m1.pack(fill=BOTH, expand=1) for i in range(10): x=random.randrange(1,400) y=random.randrange(1,400) m1.create_oval(x,y,x+10,y+10,fill="red",tags=("etoile","rouge")) for i in range(10): x=random.randrange(1,400) y=random.randrange(1,400) m1.create_rectangle(x,y,x+10,y+10,fill="red",tags=("artefact","rouge")) for i in range(10): x=random.randrange(1,400) y=random.randrange(1,400) m1.create_rectangle(x,y,x+10,y+10,fill="green",tags=("artefact","green")) # i=m1.find_withtag("artefact") j=m1.find_withtag("rouge") s1=sets.Set(i) s2=sets.Set(j) s3=s1.intersection(s2) myIntersection=tuple(s3._data.keys()) for i in myIntersection: m1.itemconfig(i,fill="black") root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: nested escape chars in a shell command
I can't seem to get that to work either. child = pexpect.spawn('/bin/sh',args=['-c','/usr/bin/ssh','-t','-o','StrictHostKeyChecking no',host,command,'|','awk','{print %s:$0}'%host], timeout=30) Complains its getting the wrong arguments to ssh. Eli -- http://mail.python.org/mailman/listinfo/python-list
Re: Popularity of blogging tools used by python programmers
Well, Python, Zope & Plone hosting are quite popular. However python based blog software isn't as sexy as let's say blogger. For SPE I first used a combination of PyDS&pycs.net. It is free for everyone, but unfortunately not stable enough to my standards. Luckily I got sponsored by zettai.net, who offer me excellent Zope hosting. There I use CoreBlog as I wanted consciously to use a python product. As a rule of thumb: when you are totally happy with the templates of prepacked blogs like blogger, then stick with that. But... even though they look slick, they all look the same. It's a bit the same problem of flash. So if you really want to modify your blog, you better take a product which is written in a language you understand. That's the reason why I like to work with Zope, Plone and CoreBlog. But I guess a python programmer using other blog systems is not as bad as a microsoft worker googling for the newest ipod. I'm sure a lot Perl or Ruby programmers also use mailman for their mailing lists. Stani http://pythonide.stani.be http://pythonide.stani.be/blog http://pythonide.stani.be/manual/html/manual.html -- http://mail.python.org/mailman/listinfo/python-list
Re: get a copy of a string leaving original intact
On Thursday 20 October 2005 22:43, Bell, Kevin wrote: > I need to copy a file, say "abc-1.tif" to another directory, but if it's > in there already, I need to transfer it named "abc-2.tif" but I'm going > about it all wrong. What a coincidence... I stepped about this today: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442460 Looks close to what you are trying. Kind Regards Christoph -- ~ ~ ".signature" [Modified] 1 line --100%--1,48 All -- http://mail.python.org/mailman/listinfo/python-list
get a copy of a string leaving original intact
I'm having trouble with something that seems like it should be simple. I need to copy a file, say "abc-1.tif" to another directory, but if it's in there already, I need to transfer it named "abc-2.tif" but I'm going about it all wrong. Here's what doesn't work: (I'll add the copy stuff from shutil after figuring out the basic string manipulation.) import os source = r"C:\Source" target = r"P:\Target" files = os.listdir(source) for f in files: if os.path.isfile(target + "\\" + f): # if it already exists print f + " exists" s = f # i'd like a copy to alter s = s.replace("-1", "-2") print "Altered it to be " + s print source + "\\" + s, target + "\\" + s else: print f + " IS NOT THERE YET" print source + "\\" + f, target + "\\" + f # use the original -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
"Casey Hawthorne" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > What languages do you know already? > > What computer science concepts do you know? > > What computer programming concepts do you know? > > > Have you heard of Scheme? > > > Ruby is a bit Perl like -- so if you like Perl, chances are you might > like Ruby. > > Python is more like Java. > > I have heard, but have not been able to verify that if a program is > about > 10,000 lines in C++ > it is about > 5,000 lines in Java > and it is about > 3,000 lines in Python (Ruby to?) I've done a lot of studying on my own, and taken the classes that my high-school offers. I feel that I have a fairly good understanding of Java, and basic OO concepts due to that. I've created some semi-complex programs in java, in my opinion, such as networked checkers, 8-player blackjack, a space-shooter type game, a copy of mario (one level, anyway), and some other stuff. I've also done a bit of studying on C. I've done a few projects in C, including another space-shooter type of game using SDL, an IRC client and some simple database-type programs. I also gave a shot at assembly using NASM for x86 before, but didn't get too far. I wrote some trivial code -- wrote to the video buffer, played with some bios interrupts, stuff like that. The only thing I did in assembly was create a program that loads at boot-up, and loads another program that just reiterates whatever you type in. I only did that because I was curious. That's about as far as my programming knowledge/experience goes. Well, I'm not sure what you mean by programming concepts. I'm familiar with OO through Java, and procedural programming through C. I'd be more detailed, but I'm not exactly sure what you are asking. Sorry. I have no idea what Scheme is, but I'll cettainly look it up as soon as I'm done writing this. I've never given Perl a shot. It was another language I considered learning, but my father's friend told me to go with Python or Ruby. Thanks for your help. Hopefully I wasn't too lengthy in this post. -- http://mail.python.org/mailman/listinfo/python-list
First Person View with Python
Hey, For a bit, I've been trying to create a first person view in Python, currently using the Soya engine. And while I can make the camera, and where I want it, how do I link it to controls? So that I can use WASD, etc. to move the camera? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Doc Error: os.makedirs
Thomas Bellman wrote: >try: > os.makedirs("/tmp/trh/spam/norwegian/blue/parrot/cheese") >except os.error, e: > if e.errno != errno.EEXIST: > raise This is what i want. Thanks. (the doc needs quite some improvement...) Xah [EMAIL PROTECTED] ∑ http://xahlee.org/ -- http://mail.python.org/mailman/listinfo/python-list
create user message for wxPython
Hi, There are 2 wxPython application, A and B and need to exchange msg. Sending WM_CLOSE, wxEVT_MOUSEWHEEL to B is OK, and sending user message like 1225 from A to B is also OK. But B didn't catch this message, note, B is running before A sends msg and can receive "WM_CLOSE". Do I have to make my own msg loop by using win32api, win32gui? I used win32gui to post Message to other windows. Using wx.Frame: wx.EVT_START_MSG= 1225 EVT_START_MSG_EVENT= wx.PyEventBinder(wx.EVT_START_MSG, 0) EVT_START_MSG_EVENT(self, self.OnStart) Or Self.Bind(EVT_START_MSG_EVENT,self.OnStart) def OnStart(self, event): print 'got start message' Thanks a lot in advance! James -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft Hatred FAQ
"Peter T. Breuer" <[EMAIL PROTECTED]> wrote: >No - they got the deal with IBM when they were a garage startup. Not quite a garage startup. They had initial success in Albuquerque, NM, writing a Basic interpreter for the MITS Altair machine. By the time IBM came to them, they had moved to Seattle and were having more success writing compilers for several languages for microcomputers. So no longer a garage startup, but still very small, and definitely not a monopoly. -- Tim Slattery [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Thank you for all the great information and links! I think I will do what a lot of you reccomended and try both for myself, the only problem is finding time with homework, college applications, and SATs coming up. I'll let you know how it turns out. Again, thank you all for the help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Popularity of blogging tools used by python programmers
Stewart Midwinter a écrit : > I've made a comparison of the relative popularity of blogging tools > used by python programmers. I was surprised by the number of python > developers not using python for their blogs; isn't that like GM > employees driving Toyota cars? > > See my post at: > > http://midtoad.homelinux.org/wp/?p=117 > Could it be say that Python programmers are wise enough to reinvent the wheel ?-) (just kidding...) -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to replace first word in string?
Realy Thanks, I will try this Hagai -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlstring -- a library to build a SELECT statement
[EMAIL PROTECTED] a écrit : > > > My solution is sqlstring. A single-purpose library: to create SQL > statement objects. These objects (such as sqlstring.Select), represent > complex SQL Statements, but as Python objects. The benefit is that you > can, at run-time, "build" the statement pythonically, without > getting bogged down in String Manipulation. The theory is that once in > use, things that were complex (string magic) become simpler, and allow > the program to worry about higher-level issues. > With the same starting point - I don't like writing SQL strings inside Python code either - I have tested a different approach : use the Python list comprehension / generator expression syntax for the select requests I have published a recipe on the Python Cookbook : http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442447 For instance : s = query(r.name for r in planes if r.speed > 500) for item in s: print s query is a class whose instances are created with the generator expression as argument. The matching SQL request is built in the __init__ method, here : SELECT r.name FROM planes AS r WHERE r.speed > 500 On two tables : s=query(r.name for r in planes for c in countries if r.country == c.country and c.continent == 'Europe') is translated into : SELECT r.name FROM countries AS c ,plane AS r WHERE (r.country = c.country AND c.continent = 'Europe') For the moment the implementation is not very elegant, especially for getting the source code of the generator expression (it would be nice if they had an attribute for that !), and I'm not sure if it could work for all the forms of the SELECT syntax. But it should cover at least the most usual kinds of requests, with a Pythonic syntax Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Fund raising for SPE (Python IDE) on Mac Os X is great success!!
Hi, I'd like to thank everyone who contributed, especially Richard Brown from Dartware and Rick Thomas. I'm highly impressed that the smallest user base of SPE collected the largest donation ever to SPE. Now it's my turn to impress the SPE Mac users. As such the light is green for SPE on the Mac. First I will buy a Mac and get used to it. Then I will optimize SPE for the Mac and try to release simultaneously. Be patient as this will take some time. The next releases (0.7) will be based on work I did before. But from 0.8 releases SPE will also be tested & developed on Mac. Please subscribe to the mailing list as a developer, user and/or mac user. Of course donations are still welcome. Stani http://pythonide.stani.be http://pythonide.stani.be/manual/html/manual.html -- http://mail.python.org/mailman/listinfo/python-list
classmethods, class variables and subclassing
Hi, I have a class with various class-level variables which are used to store global state information for all instances of a class. These are set by a classmethod as in the following (in reality the setcvar method is more complicated than this!): class sup(object): cvar1 = None cvar2 = None @classmethod def setcvar1(cls, val): cls.cvar1 = val @classmethod def setcvar2(cls, val): cls.cvar2 = val @classmethod def printcvars(cls): print cls.cvar1, cls.cvar2 I can then call setcvar on either instances of the class or the class itself. Now, the problem comes when I want to subclass this class. If I override the setcvar1 method to do some new things special to this class, and then call the sup.setcvar1() method, it all works fine: class sub(sup): cvar1a = None @classmethod def setcvar1(cls, val, vala): cls.cvar1a = vala sup.setcvar1(val) @classmethod def printcvars(cls): print cls.cvar1a sup.printcvars() This works fine, and sets cvar and cvar2 for both classes. However, if I *don't* override the setcvar2 method, but I call sub.setcvar2(val) directly, then only sub.cvar2 gets set; it is no longer identical to sup.cvar1! In particular, sub.setcvar1(1,10) sub.setcvar2(2) sub.printcvars() prints 10 1 None i.e. sub.cvar1, sub.cvar1a, sub.cvar2= 1 10 2 but sup.cvar1, cvar2= 1 None since sup.cvar2 has never been set, and this is what sup.printcvars() looks for. This behavior is "expected", but is it desirable? For my application, at least, I think the problem really comes in the printcvars method: is there any way to call the overridden sup.printcvars() but with, effectively, cls=sub? Thanks for reading this far! Andrew Andrew This seems like a bug Is this expected behavior, or a bug (or both -- it is expected but probably not what is wanted!)? -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on re.IGNORECASE
Thanks for your help. -myself -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on re.IGNORECASE
OK, I got it. - The re module search function syntax is: search( pattern, string[, flags]) where re.IGNORECASE is a valid flag. - The RE Object search method syntax is: search( string[, pos[, endpos]]) where "The optional second parameter pos gives an index in the string where the search is to start; it defaults to 0" It turns out that re.IGNORECASE has the value 2. Am I the only person bitten by this? http://docs.python.org/lib/node115.html http://docs.python.org/lib/re-objects.html -myself -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on re.IGNORECASE
[EMAIL PROTECTED] wrote: > Hi, > > I'm having some problems with basic RE in python. I was wondering > whether > somebody could provide a hint on what's going wrong with the following > script. Comments are included. > > TIA. > -myself > > >>python2.3 > > Python 2.3.4 (#1, Nov 18 2004, 13:39:30) > [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-39)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > import re pattern = re.compile('.*HTTP/(\d\.\d) *(\d*) *(.*)$') pattern.search("GGHTTP/1.1 200 OK\r\n", re.IGNORECASE) > > <_sre.SRE_Match object at 0xb75c6ed0> > pattern.search("GHTTP/1.1 200 OK\r\n", re.IGNORECASE) > > # this makes no sense to me. Why is the previous line matched Because the second argument to pattern.search() is the position where the search starts, not a flag. re.IGNORECASE == 2 so your search is skipping the first two chars. Try giving the flags as a second argument to re.compile(): >>> import re >>> re.IGNORECASE 2 >>> pattern = re.compile('.*HTTP/(\d\.\d) *(\d*) *(.*)$', re.IGNORECASE) >>> pattern.search("GGHTTP/1.1 200 OK\r\n") <_sre.SRE_Match object at 0x00965980> >>> pattern.search("GHTTP/1.1 200 OK\r\n") <_sre.SRE_Match object at 0x009659D0> >>> pattern.search("Ghttp/1.1 200 OK\r\n") <_sre.SRE_Match object at 0x009651B0> Kent > # and this not? > pattern.search("GHTTP/1.1 200 OK\r\n") > > <_sre.SRE_Match object at 0xb758d020> > -- http://mail.python.org/mailman/listinfo/python-list
Re: A macro editor
> My teammates and I were talking about to use one of Python, Ruby or > Groovy. But, we haven't decided which to use. > > What seems to be easier is to use Python, you know.. because of the > Jython thing. But, it is probably a mistake to take Jython without a > extensive analysis of the all possibilities. There seems to exist a Ruby java port, conveniently called jruby. Additionally, you might consider beanshell. > > From my point of view, the best choice will be those that allow the > average user getting results as fast as possible rather than the power > of the language itself. At the end, what we will write is a gateway to > access to our application's Java API through the scripts written by our > users. > > In this sense, I'd like to ask if someone knows if any of these > languages have a Java implementation that supports code auto-complete > and class navigation or any kind of functionality that would ease and > speed up the user's learning curve and productivity. > > In other words, is it possible to have a small and lightly intelligent > workbench window (a mini-Eclipse for example) for our future "macro > editor" within our application? I doubt that will be possible. A language that has no type-declarations - that is true for ruby & python (regardless of their respective VM implementations) - can't possibly deliver that feature. And it looks as if the same is true for groovy. The only thing I can imagine is that you try and recognize the "gateways" to your API-model and provide calltips for names that are bound to values from that model. E.g. if you have a module called "core" that contains an application-object that represents your application, you could try and identify code like this: app = core.applikation app. However, if the user does fancy tricks like this: setattr(self, "app", core.application) self.app. So - _I_ think the better user-experience comes froma well-working easy to use REPL to quickly give the scripts a try. Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
bypassing web forms hardcoding login and password
I need to hide the complexity from users to access an information webpage, which is normally accessible after filling in a web form with the correct data. The address of the information webpage is like https://external.address.com/info.asp? where is a number generated by the server. This number (always different) is generated by the server only when you open the first web page in your browser, fill in the right values in 2 fields (user, password) and click Login. Any advices? -- http://mail.python.org/mailman/listinfo/python-list
Question on re.IGNORECASE
Hi, I'm having some problems with basic RE in python. I was wondering whether somebody could provide a hint on what's going wrong with the following script. Comments are included. TIA. -myself > python2.3 Python 2.3.4 (#1, Nov 18 2004, 13:39:30) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-39)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> pattern = re.compile('.*HTTP/(\d\.\d) *(\d*) *(.*)$') >>> pattern.search("GGHTTP/1.1 200 OK\r\n", re.IGNORECASE) <_sre.SRE_Match object at 0xb75c6ed0> >>> pattern.search("GHTTP/1.1 200 OK\r\n", re.IGNORECASE) # this makes no sense to me. Why is the previous line matched # and this not? >>> pattern.search("GHTTP/1.1 200 OK\r\n") <_sre.SRE_Match object at 0xb758d020> -- http://mail.python.org/mailman/listinfo/python-list
A macro editor
Hello mates. I'm part of a big project's developer team. We are writting an application in Java and we are planning to add scripting functionality to it. What we exactly are planning is to give a kind of tool that would allow our users to write their own scripts to perform their special operations. Something like VBA does in several comercial applications. But, as we are GPL we have to use a close to GPL licensed-like language. My teammates and I were talking about to use one of Python, Ruby or Groovy. But, we haven't decided which to use. What seems to be easier is to use Python, you know.. because of the Jython thing. But, it is probably a mistake to take Jython without a extensive analysis of the all possibilities. From my point of view, the best choice will be those that allow the average user getting results as fast as possible rather than the power of the language itself. At the end, what we will write is a gateway to access to our application's Java API through the scripts written by our users. In this sense, I'd like to ask if someone knows if any of these languages have a Java implementation that supports code auto-complete and class navigation or any kind of functionality that would ease and speed up the user's learning curve and productivity. In other words, is it possible to have a small and lightly intelligent workbench window (a mini-Eclipse for example) for our future "macro editor" within our application? I promise that if get some info I'll publish it here as soon I have it. Thanks for your time! Jaume -- http://mail.python.org/mailman/listinfo/python-list
Re: sort problem
Michele Petrazzo wrote: > Lasse Vågsæther Karlsen wrote: > >> How about: >> >> list.sort(key=lambda x: x[3]) Better to use key=operator.itemgetter(3) > Yes, on my linux-test-box it work, but I my developer pc I don't have > the 2.4 yet. I think that this is a good reason for update :) or learn about decorate-sort-undecorate: lst = [ ...whatever ] lst = [ x[3], i, x for i, x in enumerate(lst) ] lst.sort() lst = [ x for _, _, x in lst ] Kent > > Thanks, > Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: need some advice on x y plot
ok, yeah, thats exactly what i am looking for. i will give it a go. thanks a whole lot. putt this off is a typo, pull this off is what i was meaning to type. this is cool. -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft Hatred FAQ
In comp.os.linux.misc T Beck <[EMAIL PROTECTED]> wrote: > Peter T. Breuer wrote: >> In comp.os.linux.misc David Schwartz <[EMAIL PROTECTED]> wrote: >> >> > "Peter T. Breuer" <[EMAIL PROTECTED]> wrote in message >> > news:[EMAIL PROTECTED] >> >> >> Not if they abuse a monopoly position in doing so, which is where we >> >> started. > [snip] >> O/ses on PC platforms, as determined by the courts. Thanks to their >> initial agreement with IBM, and subsequent nasty tactics. > So what I'm getting here is, that they abused their monopoly power to > secure their initial deal with IBM. No - they got the deal with IBM when they were a garage startup. Later they burned off competing dos's for the IBM PC via nasty tactics (like making their programs fail to run on drdos). When they got the monopoly position via those tactics, then they got PC makers to pay them for windows, whether windows went on the box or not, r else they charged them impossible prices for the o/s. Your argument is "anybody would have done that". Other companies have tried that sort of trick, and it's been illegal too. Google for it - don't take the word of us non-legal non-business people. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: need some advice on x y plot
[EMAIL PROTECTED] wrote: > how ? > i have tried to use unix timestamps, and i have also tried with > DateTime objects > do i need to use a scale that isn't linear (default in most) ? > how do i putt this off ? Here is some code that works for me. It plots multiple datasets against time. The input data looks like this: 2005-04-04 16:00:00 141.154.195.129 - W3SVC1 SP6018ASP2 208.254.37.191 443 GET /rkadqsr/newskills/newskills.cfm selectedTab=1 200 0 53440 599 1594 HTTP/1.1 adqsr.skillport.com Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1) CookiesEnabled=1;+ASPSESSIONIDACTSSRAT=MCNLNLGADPOFGFKAHJHLDDKG;+CFID=785030;+CFTOKEN=27203160 https://adqsr.skillport.com/rkadqsr/login/login.cfm 2005-04-04 16:00:00 208.254.38.216 - W3SVC1 SP6018ASP2 208.254.37.191 443 POST /_rkadqsrBackend_od_cgi/aiccisapi.dll - 200 0 372 274 4547 HTTP/1.0 adqsr.skillport.com aiccisapi - - 2005-04-04 16:00:00 208.254.38.240 - W3SVC1 SP6018ASP2 208.254.37.191 443 POST /_rkadqsrBackend_od_cgi/aiccisapi.dll - 200 0 372 3019 250 HTTP/1.0 adqsr.skillport.com aiccisapi - - import datetime, time import Gnuplot dataPath = 'ex05040416.log' datasets = {} startTime = None f = open(dataPath) for line in f: try: dat, tim, c_ip, cs_username, s_sitename, s_computername, s_ip, s_port, \ cs_method, cs_uri_stem, cs_uri_query, sc_status, sc_win32_status, sc_bytes, \ cs_bytes, time_taken, cs_version, cs_host, cs_User_Agent, cs_Cookie, cs_Referer = line.split() except ValueError: print "Can't parse", line continue tim = time.mktime(time.strptime(dat+' '+tim, "%Y-%m-%d %H:%M:%S")) delay = int(time_taken) if startTime is None: startTime = tim tim -= startTime #print tim, delay datasets.setdefault(sc_status, []).append([tim, delay]) g = Gnuplot.Gnuplot(debug=1) plotter = g.plot for key, values in datasets.items(): plotter(values) plotter = g.replot raw_input('Please press return to continue...\n') -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to replace first word in string?
Micah Elliott wrote: > And the regex is comparatively slow, though I'm not confident this one > is optimally written: > > $ python -mtimeit -s'import re' ' > re.sub(r"^(\w*)", r"/\1/", "a b c")' > 1 loops, best of 3: 44.1 usec per loop the above has to look the pattern up in the compilation cache for each loop, and it also has to parse the template string. precompiling the pattern and using a callback instead of a template string can speed things up somewhat: timeit -s"import re; sub = re.compile(r'^(\w*)').sub" "sub(lambda x: '/%s/' % x.groups(), 'a b c')" (but the replace solutions should be faster anyway; it's not free to prepare for a RE match, and sub uses the same split/join implementation as replace...) -- http://mail.python.org/mailman/listinfo/python-list
Re: need some advice on x y plot
On 2005-10-20, Grant Edwards <[EMAIL PROTECTED]> wrote: >> and insert None (or whatever value is used by charting >> package) for times where observations were not taken. This >> will mean that you have to preprocess your data by determining >> a time step step value that will fit your data. If you get 3 >> observations each 10 minutes apart then one an hour later, you >> will need to insert 5 empty observations in the list before >> the last observation. [...] > > That's completely unnecessary. Just pass a set of time,value > pairs and they'll get plotted as desired. For example, here's how gnuplot plots the data 2 12 3 10 4 9 101 8 102 6 103 9 20 ++--+---+---+--+---+--++ + + + + + "foo.dat" A+ | | | | | | 15 ++++ | | | | |A | | | 10 ++A ++ | A A | | A | | | | A | 5 ++++ | | | | | | + + + + + + + 0 ++--+---+---+--+---+--++ 0 20 40 60 80 100 120 Isn't that what you're asking for? -- Grant Edwards grante Yow! ... I have read the at INSTRUCTIONS... visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Would there be support for a more general cmp/__cmp__
[Toby Dickenson] > ... > ZODB's BTrees work in a similar way but use the regular python comparison > function, and the lack of a guarantee of a total ordering can be a liability. > Described here in 2002, but I think same is true today: > http://mail.zope.org/pipermail/zodb-dev/2002-February/002304.html There's a long discussion of this in the ZODB Programming Guide, subsection "5.3.1 Total Ordering and Persistence" on this page: http://www.zope.org/Wikis/ZODB/FrontPage/guide/node6.html That talks about more than the referenced ZODB thread covered. Persistence adds more twists, such as that the total ordering among keys must remain the same across time (including across Python releases; for example, how None compares to objects of other types has changed across releases). -- http://mail.python.org/mailman/listinfo/python-list
Re: need some advice on x y plot
On 2005-10-20, Larry Bates <[EMAIL PROTECTED]> wrote: > I would try to live with time scale being fixed I don't understand what you mean by "the time scale being fixed". It's not. If you just pass the time,value pairs to gnuplot, it does exactly what it should. > and insert > None (or whatever value is used by charting package) for > times where observations were not taken. This will mean that > you have to preprocess your data by determining a time step > step value that will fit your data. If you get 3 observations > each 10 minutes apart then one an hour later, you will need to > insert 5 empty observations in the list before the last > observation. > > Example: > > 1:00 > 1:10 > 1:20 > 2:20 > > 1:00 > 1:10 > 1:20 > 1:30 > 1:40 > 1:50 > 2:00 > 2:10 > 2:20 That's completely unnecessary. Just pass a set of time,value pairs and they'll get plotted as desired. -- Grant Edwards grante Yow! As a FAD follower, at my BEVERAGE choices are visi.comrich and fulfilling! -- http://mail.python.org/mailman/listinfo/python-list
Re: need some advice on x y plot
On 2005-10-20, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > i have tried to use unix timestamps, That has always worked for me. What happened? > and i have also tried with DateTime objects Never tried that. > do i need to use a scale that isn't linear (default in most) ? No. > how do i putt this off ? Huh? Gnuplot by default does exactly what you seem to want if you just pass it x,y values. -- Grant Edwards grante Yow! I always liked FLAG at DAY!! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to extract a part of html file
Thanks Mike that is just what I was looking for, I have looked at beautifulsoup but it doesn't really do what I want it to do, maybe I'm just new to python and don't exactly know what it is doing just yet. However string find woks. Thanks On Thu, 20 Oct 2005 09:47:37 -0400, Mike Meyer wrote: > Ben Finney <[EMAIL PROTECTED]> writes: > >> Joe <[EMAIL PROTECTED]> wrote: >>> I'm trying to extract part of html code from a tag to a tag >> For tag soup, use BeautifulSoup: >> http://www.crummy.com/software/BeautifulSoup/> > > Except he's trying to extract an apparently random part of the file. > BeautifulSoup is a wonderful thing for dealing with X/HTML documents as > structured documents, which is how you want to deal with them most of > the time. > > In this case, an re works nicely: > import re s = ' and ends with TD> >>> src="http://whatever/some.gif";> ' r = re.match('(.*)TD> >>> src="http://whatever/some.gif";> ', s) r.group(1) > ' and ends with ' > String.find also works really well: > start = s.find('') + len('>>> class="boldyellow">') stop = s.find('TD> >>> src="http://whatever/some.gif";> ', start) s[start:stop] > ' and ends with ' > Not a lot to choose between them. > > http://mail.python.org/mailman/listinfo/python-list
Cursor Location
Is there any code that would allow a person to click a location on the screen and have that location saved for a future use? For example to imbed a watermark on an image or text, etc. S -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching for txt file and importing to ms access
"Mark Line" <[EMAIL PROTECTED]> writes: > I'm managed to get some code to download a message from the email account > and save it to a text file, does any one have a link to some sample code to > search though a file until a string of characters is matched? Or could > point me to some functions that may help me with this? datafile = open("c:\\myfile.txt", "r") data = datafile.read() datafile.close() start = data.index(myindicator) will leave start as the index in data where the the string in myindicator first appears. If you want the end of myendicator, use start = data.find(myindicator) + len(myindicator). Have you considered not saving the message to disk? You can manipulate it all in memory. > I've also managed to connect to my access database, and just print out a > field in a table, but I cant find anywhere on the web that will help me to > import data? Any help would be great?! Can't help with that. The phrase "win32com" comes to mind, but I'm not a windows person. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: need some advice on x y plot
i have thought about doing this, just a little different. i was going to list the value pairs. take the start time and end time and plot 100 empty plots between them. add the value pairs, sort by time, and then draw it. The only thing is it get kinda complicated when the times change a lot. they could span an hour, a month, anything in between. i like your idea, i will check various packages for how to plot 'none' thanks sk. -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to replace first word in string?
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: > I am looking for the best and efficient way to replace the first word > in a str, like this: > "aa to become" -> "/aa/ to become" > I know I can use spilt and than join them > but I can also use regular expressions > and I sure there is a lot ways, but I need realy efficient one Assuming you know the whitespace will be spaces, I like find: new = "/aa/" + old[old.find(' '):] As for efficiency - I suggest you investigate the timeit module, and do some tests on data representative of what you're actaully going to be using. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: __getattr__, __setattr__
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: > for new style classes __getattribute__ is defined, see eg. > http://www.python.org/2.2.3/descrintro.html Steve Holden <[EMAIL PROTECTED]> writes: > >>> object.__getattribute__ > > > Ring any bells? Yes, of course. Thanks ;-) Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to replace first word in string?
On Oct 20, [EMAIL PROTECTED] wrote: > I am looking for the best and efficient way to replace the first word > in a str, like this: > "aa to become" -> "/aa/ to become" > I know I can use spilt and than join them > but I can also use regular expressions > and I sure there is a lot ways, but I need realy efficient one Of course there are many ways to skin this cat; here are some trials. The timeit module is useful for comparison (and I think I'm using it correctly :-). I thought that string concatenation was rather expensive, so its being faster than %-formatting surprised me a bit: $ python -mtimeit ' res = "/%s/ %s"% tuple("a b c".split(" ", 1))' 10 loops, best of 3: 3.87 usec per loop $ python -mtimeit ' b,e = "a b c".split(" ", 1); res = "/"+b+"/ "+e' 10 loops, best of 3: 2.78 usec per loop $ python -mtimeit ' "/"+"a b c".replace(" ", "/ ", 1)' 10 loops, best of 3: 2.32 usec per loop $ python -mtimeit ' "/%s" % ("a b c".replace(" ", "/ ", 1))' 10 loops, best of 3: 2.83 usec per loop $ python -mtimeit ' "a b c".replace("", "/", 1).replace(" ", "/ ", 1)' 10 loops, best of 3: 3.51 usec per loop There are possibly better ways to do this with strings. And the regex is comparatively slow, though I'm not confident this one is optimally written: $ python -mtimeit -s'import re' ' re.sub(r"^(\w*)", r"/\1/", "a b c")' 1 loops, best of 3: 44.1 usec per loop You'll probably want to experiment with longer strings if a test like "a b c" is not representative of your typical input. -- _ _ ___ |V|icah |- lliott http://micah.elliott.name [EMAIL PROTECTED] " " """ -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft Hatred FAQ
Peter T. Breuer wrote: > In comp.os.linux.misc David Schwartz <[EMAIL PROTECTED]> wrote: > > > "Peter T. Breuer" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > > >> Not if they abuse a monopoly position in doing so, which is where we > >> started. [snip] > O/ses on PC platforms, as determined by the courts. Thanks to their > initial agreement with IBM, and subsequent nasty tactics. So what I'm getting here is, that they abused their monopoly power to secure their initial deal with IBM. Which is what made them a monopoly. MS didn't have a monopoly before IBM, so what kind of draw did they have to make IBM sign the paper, except that they were offering something that IBM wanted, and IBM was willing to pay that much for it? Nobody made IBM sign that deal, IBM thought that it worked out OK for both parties. As for later deals with OEM manufacturers, if it's OK for MS to make that deal with IBM, then why does it suddenly become an "abuse of their power" if they're using the same business model? Don't get me wrong, I'm sure MS has done plenty of shady stuff, and I'm sure most every other sucessful company has. Just because we got a lawsuit to watch for MS doesn't mean other companies like Sony or IBM haven't done similar stuff we've never heard of. I'm just trying to figure out how offering their contract changed from OK to not OK, based purely on how well they were doing... --T Beck -- http://mail.python.org/mailman/listinfo/python-list
Re: sort problem
Lasse Vågsæther Karlsen wrote: > How about: > > list.sort(key=lambda x: x[3]) > > Does that work? > Yes, on my linux-test-box it work, but I my developer pc I don't have the 2.4 yet. I think that this is a good reason for update :) Thanks, Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Modules and Namespaces
Ooops, Larry, forgive me being to overhauled here: Actually self.RS = RS does not make the RS object available in the module, Steve's method does however. -Jelle -- http://mail.python.org/mailman/listinfo/python-list
Re: Set an environment variable
"Eric Brunel" <[EMAIL PROTECTED]> writes: > -myScript.py-- > print 'export MY_VARIABLE=value' > -- > > -myScript.sh-- > python myScript.py > /tmp/chgvars.sh > . /tmp/chgvars.sh It's simpler to use eval and command substitution: eval $(python myScript.py) http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Modules and Namespaces
Dear Steve & Larry, Both your methods worked flawless, thanks to both of you! I have to say Larry's way wins on style points, doens't it? What an awefull thing to get stuck on something that simple, what a gorgeous solution, thanks so much! -Jelle -- http://mail.python.org/mailman/listinfo/python-list
Re: How to retrieve the filename of a module
Il 2005-10-20, Lawrence Oluyede <[EMAIL PROTECTED]> ha scritto: > Il 2005-10-20, mku <[EMAIL PROTECTED]> ha scritto: >> Hi, >> >> thereŽs a function inside a module. How can these function retrieve >> the path+name of his module ? (The path is most important). >> That should also work if the module is part of a package. > > > [EMAIL PROTECTED]:~ $ cat > test.py > print __file__ > import os > print os.path.abspath(__file__) > > [EMAIL PROTECTED]:~ $ python test.py > test.py > /home/rhymes/test.py Also __name__ for the name of the module -- Lawrence http://www.oluyede.org/blog -- http://mail.python.org/mailman/listinfo/python-list
Re: How to retrieve the filename of a module
mku wrote: > Hi, > > there´s a function inside a module. How can these function retrieve > the path+name of his module ? (The path is most important). > That should also work if the module is part of a package. > > Thanks in advance > > Martin > Try the following in the function: import traceback f = traceback.extract_stack(limit=2) If you output f to the interpreter, you'll see the filename but I don't know what position in the output list it is guaranteed to be. Jim -- http://mail.python.org/mailman/listinfo/python-list
Re: need some advice on x y plot
I would try to live with time scale being fixed and insert None (or whatever value is used by charting package) for times where observations were not taken. This will mean that you have to preprocess your data by determining a time step step value that will fit your data. If you get 3 observations each 10 minutes apart then one an hour later, you will need to insert 5 empty observations in the list before the last observation. Example: 1:00 1:10 1:20 2:20 1:00 1:10 1:20 1:30 1:40 1:50 2:00 2:10 2:20 Maybe this will be of some help and I'm sure there are other ways. -Larry [EMAIL PROTECTED] wrote: > Hey there, > i have tried about every graphing package for python i can get to work > on my system. gnuplot, pychart, biggles, gdchart, etc.. (cant get > matplot to work) > so far, they all are working ok. I need to make an x y chart for some > data that comes in from sensors at different times durring the day. i > need it to show the value in the y and the time in the x . no problem > so far. But what i cannot get to happen is to scale x (time of the > plot) with respect to time. in other words, i get a chart with the > times evenly spaced out along the x axis, with their respective values. > i need the chart to show gaps when there are gaps in the data. i need > it to be able to scale by time. if i have 3 values that come in within > a few minutes, i need them to be displayed close together, as compared > to another value that may come in, say, an hour later. Does this make > sence ? > one of you guys know a charting app that will do this ? or is there > some other way i could do it? > > looking for suggestions, > sk > -- http://mail.python.org/mailman/listinfo/python-list
Re: How to retrieve the filename of a module
Il 2005-10-20, mku <[EMAIL PROTECTED]> ha scritto: > Hi, > > thereŽs a function inside a module. How can these function retrieve > the path+name of his module ? (The path is most important). > That should also work if the module is part of a package. [EMAIL PROTECTED]:~ $ cat > test.py print __file__ import os print os.path.abspath(__file__) [EMAIL PROTECTED]:~ $ python test.py test.py /home/rhymes/test.py Bye -- Lawrence http://www.oluyede.org/blog -- http://mail.python.org/mailman/listinfo/python-list
Re: sort problem
How about: list.sort(key=lambda x: x[3]) Does that work? -- http://mail.python.org/mailman/listinfo/python-list